Manualul PHP

by:
Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Hannes Magnusson
Georg Richter
Damien Seguy
Jakub Vrana
?i al?ii
2017-02-22
Edited By: Peter Cowburn
by:
Traducerea în limba româna:
Paul Dorneanu
Adrian Jurjica
Cristi Radulescu
Valentin Tutu
Iulian Nastasache
Daniel Toma
Dorel Nastasa
Dan Matornei
Rare? Benea
Valentin Agachi
Cristi Armeana
Adrian Spinei
Cristian Câmpean
?erban Gheorghe Ghi?a
Gabriel Preda
Simion Onea
Alexandru Szasz
© 1997-2017 Grupul de Documentare PHP
  • Copyright
  • Manualul PHP
    • Prefa?a
  • Pentru început
    • Introducere
    • A simple tutorial
  • Installarea ?i configurarea
    • Aspecte generale privind instalarea
    • Installation on Unix systems
    • Instalarea pe Mac OS X
    • Installation on Windows systems
    • Instalarea pe platforme de Cloud Computing
    • FastCGI Process Manager (FPM)
    • Installation of PECL extensions
    • Probleme?
    • Runtime Configuration
  • Informa?ii de referin?a despre limbaj
    • Sintaxa de baza
    • Types
    • Variables
    • Constants
    • Expressions
    • Operators
    • Control Structures
    • Functions
    • Clase ?i Obiecte
    • Namespaces
    • Errors
    • Exceptions
    • Generators
    • References Explained
    • Predefined Variables
    • Excep?ii predefinite
    • Interfe?e ?i clase predefinite
    • Context options and parameters
    • Supported Protocols and Wrappers
  • Securitatea
    • Introducere
    • General considerations
    • Instalat ca un binar CGI
    • Instalat ca modul Apache
    • Session Security
    • Filesystem Security
    • Securitatea Bazelor de Date
    • Error Reporting
    • Using Register Globals
    • User Submitted Data
    • Magic Quotes
    • Ascunderea PHP
    • Cea mai noua versiune
  • Facilita?i
    • HTTP authentication with PHP
    • Cookies
    • Sesiuni
    • Dealing with XForms
    • Handling file uploads
    • Using remote files
    • Connection handling
    • Persistent Database Connections
    • Safe Mode
    • Command line usage — Using PHP from the command line
    • Garbage Collection
    • DTrace Dynamic Tracing
  • Informa?ii de referin?a despre func?ii
    • Afectarea comportamentului PHP
    • Manipularea cu formate audio
    • Servicii de autentificare
    • Extensii specifice liniei de comanda
    • Extensii de compresie ?i arhivare
    • Procesarea cardurilor de credit
    • Extensii criptografice
    • Extensii de lucru cu baze de date
    • Extensii referitoare la data ?i ora
    • Extensii referitoare la sistemul de fi?iere
    • Sus?inerea limbajului uman ?i a codificarii caracterelor
    • Generarea ?i procesarea imaginilor
    • Extensii referitoare la po?ta electronica
    • Extensii matematice
    • Ie?iri MIME non-textuale
    • Extensii de control al proceselor
    • Alte extensii de baza
    • Alte servicii
    • Extensii ale motorului de cautare
    • Extensii specifice serverului
    • Extensii de lucru cu sesiuni
    • Procesarea textului
    • Extensii referitoare la variabile ?i tipuri
    • Servicii Web
    • Extensii doar pentru Windows
    • Manipularea XML
    • Extensii GUI
  • Nucleul PHP: Ghidul unui hacker
    • Preface
    • Memory management
    • Working with Variables
    • Writing Functions
    • Writing Classes
    • Working with Resources
    • Working with INI settings
    • Working with streams
    • The "counter" Extension - A Continuing Example
    • The PHP 5 build system
    • Extension structure
    • PDO Driver How-To
    • Extension FAQs
    • Zend Engine 2 API reference
    • Zend Engine 2 Opcodes
    • Zend Engine 1
  • FAQ — FAQ: Întrebari frecvente
    • Informa?ii generale
    • Mailing lists
    • Obtaining PHP
    • Database issues
    • Installation
    • Build Problems
    • Using PHP
    • Password Hashing — Safe Password Hashing
    • PHP and HTML
    • PHP and COM
    • Miscellaneous Questions
  • Anexe
    • Istoria PHP ?i a proiectelor asociate
    • Migrating from PHP 7.0.x to PHP 7.1.x
    • Migrating from PHP 5.6.x to PHP 7.0.x
    • Migrating from PHP 5.5.x to PHP 5.6.x
    • Migrating from PHP 5.4.x to PHP 5.5.x
    • Migrating from PHP 5.3.x to PHP 5.4.x
    • Migrating from PHP 5.2.x to PHP 5.3.x
    • Migrarea de la PHP 5.1.x la PHP 5.2.x
    • Migrarea de la PHP 5.0.x la PHP 5.1.x
    • Migrarea de la PHP 4 la PHP 5.0.x
    • Depistarea erorilor (debugging) în PHP
    • Op?iunile de configurare
    • Directive php.ini
    • Lista/Categoriile extensiilor
    • Lista pseudonimelor func?iilor
    • Lista cuvintelor rezervate
    • Lisa tipurilor de resurse
    • Lista filtrelor disponibile
    • Lista transporturilor prin socket-e sus?inute
    • Tabelele de compara?ii ale tipurilor PHP
    • Lista semnelor interpretorului
    • Ghidul de stabilire a denumirilor de catre utilizatori
    • Despre manual
    • Creative Commons Attribution 3.0
    • Listingul-indice
    • Jurnalul modificarilor
  • Edi?ia în formatul HTML Help
    • About This Edition
    • Using PHP Manual CHM Edition
    • The Full Text Search
    • Integrating the PHP Manual
Copyright
PHP Manual


Copyright

Copyright © 1997 - 2017 de catre Grupul de Documentare PHP. Acest material poate fi distribuit numai în baza termenelor ?i condi?iilor stabilite în documentul "Creative Commons Attribution 3.0 License" sau ulterioara. O copie a licen?ei Creative Commons Attribution 3.0 este distribuita cu acest manual. Cea mai recenta versiune disponibila la moment la adresa » http://creativecommons.org/licenses/by/3.0/.

În caz ca sunte?i cointeresat în redistribuirea sau republicarea acestui document integral sau par?ial, modificat sau nemodificat, ?i daca aveti întrebari, va rugam sa contacta?i de?inatorii dreptului de reproducere la adresa » doc-license@lists.php.net. Va rugam sa ?ine?i cont ca aceasta adresa este mapata (redirec?ionata) catre arhiva listei publice de distribu?ie po?tala.

Manualul PHP
Manualul PHP
Manualul PHP


Manualul PHP
PHP Manual

Manualul PHP

  • Prefa?a
Copyright
Prefa?a
Manualul PHP
PHP Manual


Prefa?a

PHP, ce înseamna "PHP: Hypertext Preprocessor" este un limbaj de scripting de uz general, cu cod-sursa deschis (Open Source), utilizat pe scara larga, ?i care este potrivit în special pentru dezvoltarea aplica?iilor web ?i poate fi integrat în HTML. Sintaxa sa provine din C, Java ?i Perl ?i este u?or de înva?at. Scopul principal al limbajului este acela de a permite programatorilor web sa creeze rapid pagini web generate dinamic, însa cu PHP pute?i realiza mult mai multe.

Acest manual consta în primul rând dintr-o referin?a a func?iilor, dar de asemenea con?ine ?i o prezentare a limbajului, explica?ia celor mai importante facilita?i oferite de PHP, ?i alte informa?ii suplimentare.

Pute?i descarca acest manual în câteva formate la adresa » http://www.php.net/download-docs.php. Informa?ii suplimentare despre modul în care acest manual este dezvoltat pot fi gasite în anexa 'Despre manual'. Daca va intereseaza istoria PHP, vizita?i anexa corespunzatoare.

Autori ?i colaboratori

În prezent noi eviden?iem cele mai active persoane pe prima pagina a manualului, dar sunt mult mai mul?i colaboratori care în prezent ne ajuta în lucrul nostru, sau care au acordat un sprijin substan?ial proiectului în trecut. Exista si multe persoane necunoscute, care ajuta cu adnotari pe paginile manualului, care în mod continuu sunt incluse în referin?e; pentru lucrul lor le suntem de asemenea foarte recunoscatori. Toate listele afi?ate mai jos sunt în ordine alfabetica.

Autori ?i redactori

Urmatorii colaboratori trebiue sa fie recunoscu?i pentru impactul pe care l-au avut, ?i/sau continua sa-l aiba asupra con?inutului manualului: Bill Abt, Jouni Ahto, Alexander Aulbach, Christoph Michael Becker, 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, Philip Olson, 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.

Urmatorii colaboratori au depus un efort semnificativ în redactarea manualului: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe, Philip Olson ?i Egon Schmid.

Raspunzatorii pentru între?inerea adnotarilor utilizatorilor

Cei mai activi raspunzatori pentru între?inere în prezent sunt: Daniel Brown, Nuno Lopes, Felipe Pena, Thiago Pojda ?i Maciek Sokolewicz.

Aceste persoane de asemenea au depus un mare efort la între?inerea adnotarilor utilizatorilor: 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.

Traducerea în limba Româna

Versiunea în limba româna a manualului PHP este realizata, în mod voluntar, de o echipa interna?ionala de traducatori formata din Paul Dorneanu (ini?iatorul acestui proiect), Adrian Jurjica, Cristi Radulescu, Valentin ?u?u, Iulian Nastasache, Daniel Toma, 1ns0mn1a, Dorel Nastasa, Dan Matornei, Rare? Benea, Valentin Agachi, Cristi Armeana, Adrian Spinei, ?erban Gheorghe Ghi?a, Gabriel Preda, Simion Onea, Alexandru Szasz.

Daca dori?i sa contribui?i la traducerea manualului PHP, este de ajuns sa va înscrie?i la lista de discu?ii doc-ro@lists.php.net ?i sa ne contacta?i. De asemenea va recomandam sa vizita?i urmatoarele resurse PHP române?ti: » http://www.rophp.net/ ?i » http://www.phpromania.net.

Manualul PHP
Pentru început
Manualul PHP


Pentru început

  • Introducere
    • Ce este PHP?
    • Ce poate face PHP?
  • 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?
Prefa?a
Introducere
Manualul PHP


Introducere

Cuprins

  • Ce este PHP?
  • Ce poate face PHP?
Pentru început
Ce este PHP?
Pentru început


Ce este PHP?

PHP (acronim recursiv pentru PHP: Hypertext Preprocessor) este un limbaj de scripting de uz general, cu cod-sursa deschis (open source), utilizat pe scara larga, ?i care este potrivit în special pentru dezvoltarea aplica?iilor web ?i poate fi integrat în HTML.

Frumos, dar totu?i ce înseamna aceasta? Un exemplu:

Example #1 Un exemplu introductiv

<!DOCTYPE HTML>
<html>
    <head>
        <title>Exemplu</title>
    </head>
    <body>

        <?php
        echo "Salut, sunt un script PHP!";
        ?>

    </body>
</html>

În locul unei mul?imi de comenzi pentru a afi?a HTML (cum este cazul în C sau Perl), paginile PHP con?in HTML cu cod-sursa încorporat, care realizeaza "ceva" (în acest caz, afi?eaza "Salut, sunt un script PHP!"). Codul-sursa PHP este încorporat între ni?te instruc?iuni de procesare de început ?i de sfâr?it speciale <?php ?i ?>, care va permit sa intra?i ?i sa ie?i?i din "modul PHP".

Ceea ce face PHP sa difere de un JavaScript de partea clientului este ca codul sau este executat pe server, generând HTML care este apoi trimis catre client. Clientul va primi rezultatele rularii acelui script, fara a putea cunoa?te codul-sursa ce sta la baza. Dumneavoastra chiar pute?i sa configura?i web server-ul sa proceseze toate fi?ierele HTML cu PHP, ?i atunci într-adevar nu va fi nici o modalitate ca utilizatorii sa afle ce ave?i ascuns în mâneca.

Cel mai bun lucru la PHP este simplitatea extrema pentru un începator, dar totodata existen?a multor facilita?i avansate pentru un programator profesionist. Sa nu va fie teama sa citi?i lista lunga a facilita?ilor PHP. Pute?i sa va implica?i în scurt timp ?i sa începe?i a scrie scripturi simple peste câteva ore.

Cu toate ca dezvoltarea PHP e axata pe scripting de partea server-ului, pute?i sa realiza?i mult mai multe cu el. Citi?i în continuare ?i afla?i mai multe detalii în sec?iunea întitulata Ce poate face PHP?, sau trece?i direct la ghidul de utilizare introductiv daca sunte?i interesat doar de programarea web.

Introducere
Ce poate face PHP?
Introducere


Ce poate face PHP?

Orice. PHP este axat în principal pe scripting de partea server-ului, deci pute?i realiza cu el orice poate realiza un alt program CGI, cum ar fi colectarea datelor din forme, generarea con?inutului dinamic al paginilor sau trimiterea ?i primirea cookies. Dar PHP poate face mult mai multe.

Sunt trei domenii principale, unde scripturile PHP sunt utilizate.

  • Scripting de partea serverului. Acesta este cel mai tradi?ional ?i de baza domeniu al PHP. Ave?i nevoie de trei lucruri pentru ca aceasta sa func?ioneze. Analizatorul PHP (în calitate de CGI, sau modul pentru server), un server web ?i un navigator web. Trebuie sa rula?i serverul web cu o instalare PHP conectata la el. Pute?i accesa ie?irile programului PHP cu navigatorul web, vizualizând pagina PHP prin server. Toate acestea pot rula pe computerul dumneavoastra de acasa, daca doar experimenta?i cu programarea în PHP. Citi?i sec?iunea cu instruc?iuni de instalare pentru informa?ii suplimentare.
  • Scripting în linia de comanda. Pute?i sa face?i un script PHP sa ruleze fara un server ?i navigator web. Ave?i nevoie doar de analizatorul PHP pentru a-l utiliza în acest mod. Acest mod de utilizare este ideal pentru script-uri executate în mod regulat cu cron (pe *nix sau Linux) sau cu Task Scheduler (pe Windows). Aceste script-uri pot fi utilizate de asemenea pentru lucrari simple de procesare a textelor. Citi?i sec?iunea despre Utilizarea PHP în linia de comanda pentru informa?ii suplimentare.
  • Scrierea aplica?iilor de birou. PHP probabil ca nu este cel mai potrivit limbaj pentru a crea o aplica?ie de birou cu o interfa?a grafica a utilizatorului, dar daca cunoa?te?i PHP foarte bine ?i dori?i sa utiliza?i unele facilita?i avansate ale PHP în aplica?ii de partea clientului, pute?i sa utiliza?i PHP-GTK pentru a scrie asemenea aplica?ii. De asemenea ave?i posibilitatea sa scrie?i în acest mod aplica?ii ce vor rula pe mai multe platforme. PHP-GTK este o extensie a PHP, care nu este disponibila în distributivul de baza. Daca v-a interesat PHP-GTK, vizita?i » propriul sau website.

PHP poate fi utilizat pe toate sistemele de operare majore, inclusiv Linux, multe variante Unix (inclusiv HP-UX, Solaris ?i OpenBSD), Microsoft Windows, Mac OS X, RISC OS ?i probabil altele. PHP de asemenea sus?ine majoritatea server-elor web existente în prezent. Acestea includ Apache, IIS, ?i multe altele. De asemenea se includ ?i serverele ce pot utiliza binarul PHP FastCGI, cum ar fi lighttpd ?i nginx. PHP func?ioneaza ca modul sau ca procesor CGI.

Deci cu PHP ave?i libertatea alegerii sistemului de operare ?i a serverului web. Ba chiar mai mult, ave?i posibilitatea sa utiliza?i programarea procedurala sau programarea orientata pe obiecte (POO), sau o combina?ie a acestora.

Cu PHP nu sunte?i limitat doar la afi?area HTML. Posibilita?ile PHP permit de a afi?a imagini, fi?iere PDF ?i chiar filme Flash (utilizând libswf ?i Ming) generate "din zbor". Pute?i de asemenea cu u?urin?a sa afi?a?i orice text, cum ar fi XHTML sau alt fi?ier XML. PHP poate genera automat aceste fi?iere ?i le poate salva în sistemul de fi?iere, în loc sa le afi?eze, formând astfel un sistem de cache al con?inutului dinamic de partea server-ului.

Una dintre cele mai puternice ?i semnificative facilita?i ale PHP este sus?inerea unui larg domeniu de baze de date. Scrierea unei pagini web ce acceseaza o baza de date este incredibl de simpla utilizând una din extensiile de lucru cu baze de date (de ex. pentru mysql), sau utilizând un nivel de abstractizare precum PDO, sau conectarea la orice baza de date ce sus?ine standardul "Open Database Connection" cu ajutorul extensiei ODBC. Alte baze de date pot utiliza cURL sau socket-uri, cum ar fi CouchDB.

PHP de asemenea poate sa "converseze" cu alte servicii utilizând protocoale cum ar fi LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (pe Windows) ?i multe altele. Pute?i de asemenea sa deschide?i socket-uri de re?ea "crude" ?i sa interac?iona?i utilizând orice alt protocol. PHP sus?ine WDDX - schimbul de date complexe între aproape toate limbajele de programare web. Vorbind despre interconectare, PHP sus?ine instan?ierea obiectelor Java ?i utilizarea lor transparenta ca obiecte PHP.

PHP poseda facilita?i de procesare a textului foarte utile, care includ expresii regulare compatibile cu Perl (PCRE) ?i multe extensii ?i instrumente pentru accesarea ?i interpretarea documentelor XML. PHP standardizeaza toate extensiile XML pe baza solida a bibliotecii libxml2 ?i extinde setul de facilita?i adaugând sus?inerea SimpleXML, XMLReader ?i XMLWriter.

Exista multe alte extensii interesante aranjate atât în ordine alfabetica cât ?i dupa categorii. De asemenea exista extensii PECL suplimentare care pot fi, sau pot sa nu fie documentate în cadrul manualului PHP, cum ar fi » XDebug.

Dupa cum pute?i vedea, aceasta pagina nu este suficienta pentru a eviden?ia toate facilita?ile ?i beneficiile oferite de PHP. Citi?i în continuare sec?iunile despre instalarea PHP ?i accesa?i referin?ele func?iilor pentru a gasi explica?iile extensiilor men?ionate anterior.

Ce este PHP?
A simple tutorial
Introducere


A simple tutorial

Cuprins

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

Ce poate face PHP?
What do I need?
Pentru început


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.

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:

Example #1 Our first PHP script: hello.php

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

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

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

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

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

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

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

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

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

Nota: A Note on Windows Notepad

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

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

Example #2 Get system information from PHP

<?php phpinfo(); ?>

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

Nota:

$_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. As of PHP 5.4.0 these older variables have been removed. (See also the note on old code.)

To display this variable, you can simply do:

Example #1 Printing a variable (Array element)

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

A sample output of this script may be:

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:

Example #2 Example using control structures and functions

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

A sample output of this script may be:

You are using Internet Explorer.<br />

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

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

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

Example #3 Mixing both HTML and PHP modes

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

A sample output of this script may be:

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

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

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:

Example #1 A simple HTML form

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

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

Example #2 Printing data from our form

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

A sample output of this script may be:

Hi Joe. You are 22 years old.

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

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 old $HTTP_*_VARS arrays are not available as of PHP 5.4.0. The following superglobal arrays were introduced in PHP » 4.1.0. They are: $_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST, and $_SESSION.
  • 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.

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
Installarea ?i configurarea
A simple tutorial


Installarea ?i configurarea

  • Aspecte generale privind instalarea
  • Installation on Unix systems
    • Apache 1.3.x on Unix systems
    • Apache 2.x on Unix systems
    • Nginx 1.4.x on Unix systems
    • Lighttpd 1.4 on Unix systems
    • Sun, iPlanet and Netscape servers on Sun Solaris
    • LiteSpeed Web Server/OpenLiteSpeed Web Server on Unix systems
    • CGI and command line setups
    • HP-UX specific installation notes
    • OpenBSD installation notes
    • Solaris specific installation tips
    • Debian GNU/Linux installation notes
  • Instalarea pe Mac OS X
    • Using Packages
    • Using the bundled PHP
    • Compilarea PHP pe Mac OS X
  • Installation on Windows systems
    • Install Requirements
    • PECL
    • Instrumente de instalare a PHP pe Windows
    • Recommended Configuration on Windows systems
    • Manual PHP Installation on Windows
    • Troubleshooting PHP on Windows
    • Installation on old Windows systems
  • Instalarea pe platforme de Cloud Computing
    • Azure App Services
    • 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
  • Probleme?
    • Citi?i FAQ
    • Alte probleme
    • Rapoarte de probleme
  • Runtime Configuration
    • The configuration file
    • .user.ini files
    • Where a configuration setting may be set
    • How to change configuration settings
What's next?
Aspecte generale privind instalarea
Manualul PHP


Aspecte generale privind instalarea

Înainte de a începe instalarea, trebuie sa ?ti?i pentru ce dori?i sa utiliza?i PHP. Exista trei domenii principale de utilizare a PHP. Ele sunt descrise în sec?iunea Ce poate face PHP?

  • Site-uri web ?i aplica?ii web (scripting de partea server-ului)
  • Scripting pentru linia de comanda
  • Aplica?ii de birou cu interfa?a grafica (GUI)

Pentru prima, ?i cea mai des întâlnita forma, ve?i avea nevoie de trei lucruri: însu?i PHP, un server web ?i un navigator web. Probabil deja ave?i un navigator web ?i, în dependen?a de sistemul dumneavoastra de operare, pute?i sa ave?i ?i un server web (de ex. Apache pe Linux ?i MacOS X; IIS pe Windows). Pute?i de asemenea sa închiria?i spa?iu web de la o companie. În acest caz nu trebuie personal sa configura?i ceva, numai sa scrie?i script-urile PHP, sa le încarca?i pe server-ul care îl închiria?i ?i sa vede?i rezultatele în navigator.

În caz ca configura?i personal server-ul ?i PHP, ave?i doua posibilita?i în alegerea metodei de conectare dintre PHP ?i server. Pentru multe servere PHP are o interfa?a-modul directa (denumita de asemenea SAPI). Aceste servere includ Apache, Microsoft Internet Information Server, serverele Netscape ?i iPlanet. Multe alte servere sus?in ISAPI - interfa?a-modul Microsoft (OmniHTTPd spre exemplu). Daca PHP nu este sus?inut ca modul pentru server-ul dumneavoastra web, atunci oricând îl pute?i utiliza ca procesor CGI sau FastCGI. Aceasta înseamna sa configura?i serverul dumneavoastra sa utilizeze executabilul CGI al PHP pentru a procesa toate cererile de fi?iere PHP de pe server.

Daca de asemenea sunte?i interesat sa utiliza?i PHP pentru scripting în linia de comanda (de ex. sa scrie?i scripturi care sa genereze automat careva imagini offline, sau sa procesa?i fi?iere textuale în dependen?a de careva argumente pe care le transmite?i), întotdeauna ve?i avea nevoie de executabilul pentru linia de comanda. Pentru a afla mai multe informa?ii, citi?i sec?iunea despre scrierea aplica?iilor PHP pentru linia de comanda. În acest caz nu ve?i avea nevoie de server sau navigator.

Cu PHP de asemenea pute?i scrie aplica?ii de birou cu interfa?a GUI utilizând extensia PHP-GTK. Aceasta este o abordare total diferita decât scrierea paginilor web, deoarece nu afi?a?i careva HTML, dar gestiona?i ferestre ?i obiecte din cadrul lor. Pentru mai multe informa?ii despre PHP-GTK, va rugam sa » vizita?i site-ul dedicat acestei extensii. PHP-GTK nu este inclusa în distributivul oficial al PHP.

De acum înainte, aceasta sec?iune va lamuri configurarea PHP pentru servere web pe Unix ?i Windows cu interfe?e-modul ?i executabile CGI. De asemenea ve?i gasi în urmatoarele sec?iuni informa?ii despre executabilul pentru linia de comanda.

Codul-sursa PHP ?i distributivele binare pentru Windows pot fi gasite la » http://www.php.net/downloads.php. Va recomandam sa alege?i o » oglinda mai apropiata pentru a descarca distributivele.

Installarea ?i configurarea
Installation on Unix systems
Installarea ?i configurarea


Installation on Unix systems

Cuprins

  • Apache 1.3.x on Unix systems
  • Apache 2.x on Unix systems
  • Nginx 1.4.x on Unix systems
  • Lighttpd 1.4 on Unix systems
  • Sun, iPlanet and Netscape servers on Sun Solaris
  • LiteSpeed Web Server/OpenLiteSpeed Web Server on Unix systems
  • 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 Git 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:
    • PHP 5.4: 1.28, 1.35, 1.75, 1.875, 2.0, 2.1, 2.2, 2.3, 2.4, 2.4.1, 2.4.2, 2.4.3, 2.5, 2.5.1, 2.6, 2.6.1, 2.6.2, 2.6.4
    • PHP 5.5: 2.4, 2.4.1, 2.4.2, 2.4.3, 2.5, 2.5.1, 2.6, 2.6.1, 2.6.2, 2.6.3, 2.6.4, 2.6.5, 2.7
    • PHP 5.6: 2.4 or later, excluding 3.0 only (3.0.1 and later are OK)
    • PHP 7.0: 2.4 or later

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.

Nota:

Some Unix systems (such as OpenBSD and SELinux) may disallow mapping pages both writable and executable for security reasons, what is called PaX MPROTECT or W^X violation protection. This kind of memory mapping is, however, necessary for PCRE's JIT support, so either PHP has to be built without PCRE's JIT support, or the binary has to be whitelisted by any means provided by the system.

Nota: Cross-compiling for ARM with the Android toolchain is currently not supported.

Aspecte generale privind instalarea
Apache 1.3.x on Unix systems
Installarea ?i configurarea


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.

Example #1 Installation Instructions (Apache Shared Module Version) for PHP

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

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

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

11. make
12. make install

    If you decide to change your configure options after installation,
    you only need to repeat the last three steps. You only need to
    restart apache for the new module to take effect. A recompile of
    Apache is not needed.

    Note that unless told otherwise, 'make install' will also install PEAR,
    various PHP tools such as phpize, install the PHP CLI, and more.

13. Setup your php.ini file:

      cp php.ini-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:

Example #2 Installation Instructions (Static Module Installation for Apache) for PHP

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

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

10. cd ../apache_1.3.x

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

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

13. cd ../php-5.x.y
14. cp php.ini-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.

Example #3 Example commands for restarting Apache

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

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

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

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

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

Different examples of compiling PHP for apache are as follows:

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

This will create a libphp5.so 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.

Nota:

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.

Nota:

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.

Avertizare

Nu va recomandam sa utiliza?i în modul de producere un MPM bazat pe fire de execu?ie cu Apache2. În loc, utiliza?i prefork MPM, care este cel implicit pentru Apache 2.0 ?i 2.2. Pentru informa?ii suplimentare despre cauze, citi?i înregistrarea corespunzatoare din FAQ despre utilizarea Apache2 cu un MPM bazat pe fire de execu?ie .

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.

    For PHP 7:

    LoadModule php7_module modules/libphp7.so

    For PHP 5:

    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.

Nota:

The Apache MultiViews FAQ discusses using multiviews with PHP.

Nota:

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
Nginx 1.4.x on Unix systems
Installation on Unix systems


Nginx 1.4.x on Unix systems

This documentation will cover installing and configuring PHP with PHP-FPM for a Nginx 1.4.x HTTP server.

This guide will assume that you have built Nginx from source and therefore all binaries and configuration files are located at /usr/local/nginx. If this is not the case and you have obtained Nginx through other means then please refer to the » Nginx Wiki in order to translate this manual to your setup.

This guide will cover the basics of configuring an Nginx server to process PHP applications and serve them on port 80, it is recommended that you study the Nginx and PHP-FPM documentation if you wish to optimise your setup past the scope of this documentation.

Please note that throughout this documentation version numbers have been replaced with an 'x' to ensure this documentation stays correct in the future, please replace these as necessary with the corresponding version numbers.

  1. It is recomended that you visit the Nginx Wiki » install page in order to obtain and install Nginx on your system.

  2. Obtain and unpack the PHP source:

    tar zxf php-x.x.x

  3. 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 PHP-FPM and MySQL support.

    cd ../php-x.x.x
./configure --enable-fpm --with-mysql
make
sudo make install

  4. Obtain and move configuration files to their correct locations

    cp php.ini-development /usr/local/php/php.ini
cp /usr/local/etc/php-fpm.conf.default /usr/local/etc/php-fpm.conf
cp sapi/fpm/php-fpm /usr/local/bin

  5. It is important that we prevent Nginx from passing requests to the PHP-FPM backend if the file does not exists, allowing us to prevent arbitrarily script injection.

    We can fix this by setting the cgi.fix_pathinfo directive to 0 within our php.ini file.

    Load up php.ini:

    vim /usr/local/php/php.ini

    Locate cgi.fix_pathinfo= and modify it as follows:

    cgi.fix_pathinfo=0

  6. php-fpm.conf must be modified to specify that php-fpm must run as the user www-data and the group www-data before we can start the service:

    vim /usr/local/etc/php-fpm.conf

    Find and modify the following:

    ; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
user = www-data
group = www-data

    The php-fpm service can now be started:

    /usr/local/bin/php-fpm

    This guide will not configure php-fpm any further, if you are interested in further configuring php-fpm then please consult the documentation.

  7. Nginx must now be configured to support the processing of PHP applications:

    vim /usr/local/nginx/conf/nginx.conf

    Modify the default location block to be aware it must attempt to serve .php files:

    location / {
    root   html;
    index  index.php index.html index.htm;
}

    The next step is to ensure that .php files are passed to the PHP-FPM backend. Below the commented default PHP location block, enter the following:

    location ~* \.php$ {
    fastcgi_index   index.php;
    fastcgi_pass    127.0.0.1:9000;
    include         fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
}

    Restart Nginx.

    sudo /usr/local/nginx/sbin/nginx -s stop
sudo /usr/local/nginx/sbin/nginx

  8. Create a test file

    rm /usr/local/nginx/html/index.html
echo "<?php phpinfo(); ?>" >> /usr/local/nginx/html/index.php

    Now navigate to http://localhost. The phpinfo() should now be shown.

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

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

Example #1 Partial lighttpd.conf

server.modules += ( "mod_fastcgi" )

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

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

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.

Example #2 Spawning FastCGI Responders

#!/bin/sh

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

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

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

PHP_FCGI_CHILDREN=16
PHP_FCGI_MAX_REQUESTS=10000

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

echo $! > "$PHP_PID"

Connecting to remote FCGI instances

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

Example #3 Connecting to remote php-fastcgi instances

fastcgi.server = ( ".php" =>
   (( "host" => "10.0.0.2", "port" => 1030 ),
    ( "host" => "10.0.0.3", "port" => 1030 ))
)
Nginx 1.4.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>

Nota:

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!

Nota:

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.

Nota:

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

Lighttpd 1.4 on Unix systems
LiteSpeed Web Server/OpenLiteSpeed Web Server on Unix systems
Installation on Unix systems


LiteSpeed Web Server/OpenLiteSpeed Web Server on Unix systems

LiteSpeed PHP is an optimized compilation of PHP built to work with LiteSpeed products through the LiteSpeed SAPI. LSPHP runs as its own process and has its own standalone binary, which can be used as a simple command line binary to execute PHP scripts from the command line.

The LSAPI is a highly optimized API that allows communication between LiteSpeed and third party web engines. Its protocol is similar to FCGI, but is more efficient.

This documentation will cover installing and configuring PHP with LSAPI for a LiteSpeed Web Server and OpenLiteSpeed Web Server.

This guide will assume that either LSWS or OLS is installed with their default paths and flags. The default installation directory for both web servers is /usr/local/lsws and both can be run from the bin subdirectory.

Please note that throughout this documentation, version numbers have been replaced with an x to ensure this documentation stays correct in the future, please replace these, as necessary, with the corresponding version numbers.

  1. To obtain and install either LiteSpeed Web Server or OpenLiteSpeed Web Server, visit the LiteSpeed Web Server wiki » install page or OpenLiteSpeed wiki » install page.

  2. Obtain and unpack the php source:

    mkdir /home/php
cd /home/php
wget http://us1.php.net/get/php-x.x.x.tar.gz/from/this/mirror
tar -zxvf php-x.x.x.tar.gz
cd php-x.x.x

  3. Configure and build PHP. This is where PHP can be customized with various options, such as which extensions will be enabled. Run ./configure --help for a list of available options. In the example, we'll use the default recommended configuration options for LiteSpeed Web Server:

    ./configure ... '--with-litespeed'
make
sudo make install

  4. Checking The LSPHP Installation

    One of the simplest ways to check whether the installation of PHP was successful is to run the following code:

    cd /usr/local/lsws/fcgi-bin/
./lsphp5 -v

    This should return information about the new PHP build:

    PHP 5.6.17 (litespeed) (built: Mar 22 2016 11:34:19)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies

    Notice the litespeed in parenthesis. This means that the PHP binary has been built with LSAPI support.

Following the steps above, LiteSpeed / OpenLiteSpeed Web Server should now be running with support for PHP as an SAPI extension. There are many more configuration options available for LSWS / OLS and PHP. For more information, check out the LiteSpeed wiki about » PHP.

Using LSPHP from the command line:

LSPHP(LSAPI + PHP) command line mode is used to process PHP scripts running on a remote server that does not necessarily have a web server running. It is used to process PHP scripts residing on a local web server (separate). This setup is suitable for service scalability as PHP processing is offloaded to a remote server.

Start lsphp from the command line on a remote server: LSPHP is an executable and can be started manually and bound to IPv4, IPv6, or Unix domain socket addresses with the command line option -b socket_address

Examples:

Have LSPHP bind to port 3000 on all IPv4 and IPv6 addresses:

/path/to/lsphp -b [::]:3000

Have LSPHP bind to port 3000 on all IPv4 addresses:

/path/to/lsphp -b *:3000

Have LSPHP bind to address 192.168.0.2:3000:

/path/to/lsphp -b 192.168.0.2:3000

Have LSPHP accept requests on Unix domain socket /tmp/lsphp_manual.sock:

/path/to/lsphp -b /tmp/lsphp_manual.sock

Environment variables can be added before the LSPHP executable:

PHP_LSAPI_MAX_REQUESTS=500 PHP_LSAPI_CHILDREN=35 /path/to/lsphp -b IP_address:port

Currently LiteSpeed PHP can be used with LiteSpeed Web Server, OpenLiteSpeed Web Server, and Apache mod_lsapi. For steps on server-side configuration, visit the wiki pages for » LiteSpeed Web Server and » OpenLiteSpeed.

LSPHP can be installed in several other ways as well.

CentOS: On CentOS, LSPHP can be installed from the LiteSpeed Repository or the Remi Repository using » RPM.

Debian: On Debian, LSPHP can be installed from the LiteSpeed Repository using » apt.

cPanel: Visit the respective » wiki page about how to install LSPHP with cPanel and LSWS/OLS using EasyApache 4.

Plesk: Plesk can be used with LSPHP on CentOS, CloudLinux, Debian, and Ubuntu, for more details on this, visit the respective » wiki page

Sun, iPlanet and Netscape servers on Sun Solaris
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.

Avertizare

Un server configurat în regim CGI este susceptibil câtorva atacuri posibile. Va rugam sa citi?i sec?iunea despre securitatea CGI pentru a afla cum sa va apara?i de astfel de atacuri.

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

LiteSpeed Web Server/OpenLiteSpeed Web Server on Unix systems
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 5.8.

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 php, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php-mysql or php-imap. You need to use the phpxs command to activate and deactivate these modules in your php.ini.

Example #1 OpenBSD Package Install Example

# pkg_add php
# pkg_add php-fpm
# pkg_add php-mysql
  (install the PEAR libraries)
# pkg_add pear

Follow the instructions shown with each package!

  (to remove packages)
# pkg_delete php
# pkg_delete php-fpm
# pkg_delete php-mysql
# pkg_delete pear

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

  • Apache and Nginx are no longer the default server on OpenBSD, but they can both be easily found in ports and packages. The new default server is also called 'httpd'.
  • The default install of httpd 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.
  • The OpenBSD 5.7+ package for the » gd extension requires XFree86 to be installed. This can be added post-installation (See OpenBSD FAQ#4) by adding the xbase.tgz file set.

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.

Avertizare

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.

Example #1 Debian Install Example with Apache 2

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

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

Example #2 Stopping and starting Apache once PHP is installed

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

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.

Example #3 Methods for listing additional PHP 5 packages

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

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

Example #4 Install PHP with MySQL, cURL

# apt-get install php5-mysql php5-curl

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

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
Instalarea pe Mac OS X
Installation on Unix systems


Instalarea pe Mac OS X

Cuprins

  • Using Packages
  • Using the bundled PHP
  • Compilarea PHP pe Mac OS X

Aceasta sec?iune con?ine note ?i sfaturi specifice pentru instalarea PHP pe Mac OS X. PHP se furnizeaza cu Mac-uri, ?i compilarea este similara cu Ghidul de instalare pe Unix.

Debian GNU/Linux installation notes
Using Packages
Installarea ?i configurarea


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/
  • Liip: » http://php-osx.liip.ch/
  • Fink: » http://www.finkproject.org/
  • Homebrew: » https://github.com/Homebrew/homebrew-php

Instalarea pe Mac OS X
Using the bundled PHP
Instalarea pe 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.

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

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

    Nota:

    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
Compilarea PHP pe Mac OS X
Instalarea pe Mac OS X


Compilarea PHP pe Mac OS X

Utiliza?i Ghidul de instalare pe Unix pentru a compila PHP pe Mac OS X.

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


Installation on Windows systems

Cuprins

  • Install Requirements
  • PECL
  • Instrumente de instalare a PHP pe Windows
  • Recommended Configuration on Windows systems
  • Manual PHP Installation on Windows
  • Troubleshooting PHP on Windows
  • Installation on old Windows systems

Installing PHP on modern Microsoft Windows systems and recommended configuration with common web servers.

Nota:

If you are looking for information about older systems, such as Windows XP, 2003, 98 or Apache 1.x, see the Legacy Info section.

The Official releases of PHP on Windows are recommended for production use. However, you are welcome to build PHP from Source. You will need a Visual Studio environment. See » Step by Step Build Instructions.

  • Using PHP on Windows Command line

  • Installing PHP on Azure App Services (aka Microsoft Azure, Windows Azure, or (Windows) Azure Web Apps).

Compilarea PHP pe Mac OS X
Install Requirements
Installarea ?i configurarea


Install Requirements

PHP 5.5+ require at least Windows 2008/Vista, or 2008r2, 2012, 2012r2, 2016 or 7, 8, 8.1, 10. Either 32-Bit or 64-bit (aka X86 or X64. PHP does not run on Windows RT/WOA/ARM).

PHP requires the Visual C runtime(CRT). Many applications require that so it may already be installed.

PHP 5.5 and 5.6 require VC CRT 11 (Visual Studio 2012). See: » https://www.microsoft.com/en-us/download/details.aspx?id=30679

PHP 7.0+ requires VC CRT 14 (Visual Studio 2015). See: » https://www.microsoft.com/en-us/download/details.aspx?id=48145

You MUST download the x86 CRT for PHP x86 builds and the x64 CRT for PHP x64 builds.

If CRT is already installed, the installer will tell you that and not change anything.

The CRT installer supports the /quiet and /norestart command-line switches, so you can script running it.

VC11 CRT DLLs can be copied from your local machine to a remote machine(a `Copy Deployment` installation) instead of running the installer on the remote machine (such as a web server you have restricted access to). See: http://www.sitepoint.com/install-php53-windows/

VC14 CRT does not support a `Copy Deployment` installation. VC14 CRT has many more DLLs(most in files with names starting with api-*). If you can find them all and copy them, it will also work (try a tool like Resource Hacker to get a list of all the DLLs to copy).

Installation on Windows systems
PECL
Installation on Windows systems


PECL

PECL extensions are pre-built for Windows and available from: » http://windows.php.net/downloads/pecl/releases/

Some extensions use features specific to some Unix systems and so are not available on Windows. Otherwise, all extensions are available for Windows.

Install Requirements
Instrumente de instalare a PHP pe Windows
Installation on Windows systems


Instrumente de instalare a PHP pe Windows

Instrumente de instalare a PHP

Daca dori?i sa configura?i PHP, unele aplica?ii PHP generale ?i utiliza?i IIS, cea mai u?oara modalitate este de a utiliza Web Platform Installer (WebPI) de la Microsoft.

XAMPP, WampServer ?i BitNami vor configura aplica?iile PHP pentru a fi utilizate cu Apache pe Windows.

PECL
Recommended Configuration on Windows systems
Installation on Windows systems


Recommended Configuration on Windows systems

OpCache

Highly Recommended that you enable OpCache. This extension is included with PHP for Windows. It compiles and optimizes PHP scripts and caches them in memory so that they aren't compiled every time the page is loaded.

In your php.ini, set

Example #1 Recommended OpCache configuration

zend_extension=php_opcache.dll
opcache.enable=On
opcache.cli_enable=On
And restart your web server. For more info, see: OpCache Configuration

WinCache

Recommended that you use WinCache if using IIS, especially if in a shared web hosting environment or using networked file storage (NAS). All PHP Applications automatically benefit from WinCache's file cache feature. File system operations are cached in memory. WinCache also can cache user objects in memory and share them between php.exe or php-cgi.exe processes (share objects between requests). Many major web applications have a plugin or extension or configuration option to make use of the WinCache user object cache. If you need high performance, you should use the object cache in your applications. See: » http://pecl.php.net/package/WinCache to download a WinCache DLL (or tgz) to your PHP extensions directory (extensions_dir in your php.ini). In your php.ini, set

Example #2 Recommended WinCache configuration

extension=php_wincache.dll
wincache.fcenabled=1
wincache.ocenabled=1
For more info, see: » http://php.net/manual/en/wincache.configuration.php

IIS Configuration

In IIS Manager, Install FastCGI module and add a handler mapping for `.php` to the path to PHP-CGI.exe (not PHP.exe)

You may use the APPCMD command line tool to script IIS configuration.

Database

You'll probably need a Database Server. Popular databases provide PHP extensions to use them. If your web site doesn't get a lot of traffic, you can run your database server on the same server as your web server. Many popular database servers run on Windows.

PHP includes mysqli and pdo_mysql extensions. PHP 5.5 and 5.6 include mysql extension (deprecated in 7.0).

See » https://dev.mysql.com/downloads/windows/

Instrumente de instalare a PHP pe Windows
Manual PHP Installation on Windows
Installation on Windows systems


Manual PHP Installation on Windows

Choose Web Server

  • IIS is builtin to Windows. On Windows Server, use Server Manager to add the IIS role. Be sure to include the CGI Role Feature. On Windows Desktop, use Control Panel's Add/Remove Programs to add IIS. See: » https://msdn.microsoft.com/en-us/library/ms181052%28v=vs.80%29.aspx?f=255&MSPPError=-2147217396 For desktop web apps and web-development, you can also use IIS/Express or PHP Desktop

    Example #1 Command line to configure IIS and PHP

    @echo off

    REM download .ZIP file of PHP build from http://windows.php.net/downloads/
    REM
    REM path to directory you decompressed PHP .ZIP file into
set phpdir=c:\php
set phppath=php-5.6.19-nts-Win32-VC11-x86

REM Clear current PHP handlers
%windir%\system32\inetsrv\appcmd clear config /section:system.webServer/fastCGI
%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers /-[name='PHP_via_FastCGI']

REM Set up the PHP handler
%windir%\system32\inetsrv\appcmd set config /section:system.webServer/fastCGI /+[fullPath='%phpdir%\%phppath%\php-cgi.exe']
%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers /+[name='PHP_via_FastCGI',path='*.php',verb='*',modules='FastCgiModule',scriptProcessor='%phpdir%\%phppath%\php-cgi.exe',resourceType='Unspecified']
%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers /accessPolicy:Read,Script

REM Configure FastCGI Variables
%windir%\system32\inetsrv\appcmd set config -section:system.webServer/fastCgi /[fullPath='%phpdir%\%phppath%\php-cgi.exe'].instanceMaxRequests:10000
%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi /+"[fullPath='%phpdir%\%phppath%\php-cgi.exe'].environmentVariables.[name='PHP_FCGI_MAX_REQUESTS',value='10000']"
%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi /+"[fullPath='%phpdir%\%phppath%\php-cgi.exe'].environmentVariables.[name='PHPRC',value='%phpdir%\%phppath%\php.ini']"
    How to manually configure IIS

  • There are several builds of Apache2 for Windows. We support ApacheLounge, but other options include XAMPP, WampServer and BitNami, which provide automatic installer tools. You may use mod_php or mod_fastcgi to load PHP on Apache. If you use mod_php, you MUST use a TS build of Apache built with same version of Visual C and same CPU (x86 or x64). How to manually configure Apache2

Choose Build

Download PHP production releases from » http://windows.php.net/download/. A lot of testing and optimization is already done on the snapshot and qa releases, but you are welcome to help us do more. There are 4 types of PHP builds:

  • Thread-Safe(TS) - use for single process web serves, like Apache with mod_php

  • Non-Thread-Safe(NTS) - use for IIS and other FastCGI web servers (Apache with mod_fastcgi) and recommended for command-line scripts

  • x86 - production use of PHP 5.5 or 5.6 or 7.0.

  • x64 - production use of PHP 7.0+ unless its a 32-bit only version of Windows. 5.5 and 5.6 x64 are expiremental.

Recommended Configuration on Windows systems
Troubleshooting PHP on Windows
Installation on Windows systems


Troubleshooting PHP on Windows

Check Temp Directory Permissions

  1. Right-click temp directory in File Explorer to get the permissions.

  2. For IIS, check that user IIS_User has MODIFY permission. You can get the temporary directory from the configuration or php info.

Manual PHP Installation on Windows
Installation on old Windows systems
Installation on Windows systems


Installation on old Windows systems

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.

Nota:

Windows XP/2003 are no longer supported as of PHP 5.5.0.

Nota:

Windows 98/Me/NT4/2000 are no longer supported as of PHP 5.3.0.

Nota:

Windows 95 is no longer supported as of PHP 4.3.0.

If you have a development environment such as Microsoft Visual Studio, you can also 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.

Manual Installation Steps

This section contains instructions for manually installing and configuring PHP on Microsoft Windows.

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 - to choose the right version for you, follow the detailed guide on the » download page.

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:

Example #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

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

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

Nota:

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:

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

Example #3 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.

Nota:

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.

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

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

Example #6 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.

Example #7 Changing the location of php.ini file

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

Microsoft IIS 7.0 and later

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

Enabling FastCGI support in IIS

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

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

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

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

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

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

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

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

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

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

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

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

Configuring IIS to process PHP requests

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

Nota:

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:

Example #8 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.

Example #9 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.

Example #10 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.

Nota:

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.

Example #11 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>

Nota:

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.

Example #12 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:

Example #13 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.

Example #14 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.

Example #15 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.

Example #16 Changing the location of php.ini file

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

Apache 1.3.x on Microsoft Windows

This section contains notes and hints specific to Apache 1.3.x installs of PHP on Microsoft Windows systems. There are also

Nota:

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.

Nota: ?ine?i minte ca la adaugarea cailor în fi?ierele de configurare Apache pentru Windows, toate backslash-urile cum ar fi în c:\directory\file.ext ar trebui convertite în slash-uri normale: c:/directory/file.ext. De asemenea poate fi necesar un slash la sfâr?it pentru directoare.

Installing as an Apache module

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

Example #17 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:

Example #18 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.

Avertizare

Un server configurat în regim CGI este susceptibil câtorva atacuri posibile. Va rugam sa citi?i sec?iunea despre securitatea CGI pentru a afla cum sa va apara?i de astfel de atacuri.

If you would like to present PHP source files syntax highlighted, there is no such convenient option as with the module version of PHP. If you chose to configure Apache to use PHP as a CGI binary, you will need to use the highlight_file() function. To do this simply create a PHP script file and add this code: <?php highlight_file('some_php_script.php'); ?>.

Apache 2.x on Microsoft Windows

This section contains notes and hints specific to Apache 2.x installs of PHP on Microsoft Windows systems. We also

Nota:

You should read the manual installation steps first!

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

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.

Nota: ?ine?i minte ca la adaugarea cailor în fi?ierele de configurare Apache pentru Windows, toate backslash-urile cum ar fi în c:\directory\file.ext ar trebui convertite în slash-uri normale: c:/directory/file.ext. De asemenea poate fi necesar un slash la sfâr?it pentru directoare.

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:

Example #19 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"

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

Example #20 PHP and Apache 2.x as CGI

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

Avertizare

Un server configurat în regim CGI este susceptibil câtorva atacuri posibile. Va rugam sa citi?i sec?iunea despre securitatea CGI pentru a afla cum sa va apara?i de astfel de atacuri.

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:

Example #21 Configure Apache to run PHP as FastCGI

LoadModule fcgid_module modules/mod_fcgid.so

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

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

Sun, iPlanet and Netscape servers on Microsoft Windows

This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Windows.

From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to Apache compatibility are also available. For support in current web servers

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

Nota:

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

Nota:

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!

Nota:

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.

Nota:

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

Sambar Server on Microsoft Windows

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

Nota:

You should read the manual installation steps first!

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

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

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

    Example #22 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.

Nota:

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

Xitami on Microsoft Windows

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

Nota:

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.

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

Avertizare

Un server configurat în regim CGI este susceptibil câtorva atacuri posibile. Va rugam sa citi?i sec?iunea despre securitatea CGI pentru a afla cum sa va apara?i de astfel de atacuri.

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

Compilarea din cod-sursa

Acest capitol lamure?te compilarea PHP din codul-sursa pe platforma windows utilizând instrumente Microsoft. Pentru a compila PHP cu cygwin, referi?i-va la Installation on Unix systems.

A se vedea documenta?ia Wiki la: » http://wiki.php.net/internals/windows/stepbystepbuild

Installation of extensions on Windows

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

The DLLs for PHP extensions are prefixed with php_.

Many extensions are built into the Windows version of PHP. This means additional DLL files, and the extension directive, are not used to load these extensions. The Windows PHP Extensions table lists extensions that require, or used to require, additional PHP DLL files. Here's a list of built in extensions (updated PHP 5.0.4): BCMath, Caledar, COM, Ctype, DOM, FTP, LibXML, Iconv, ODBC, PCRE, Session, SimpleXML, SPL, SQLite, WDDX, XML ?i Zlib.

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

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

    extension_dir = C:\php\extensions

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

    Example #23 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 main folder, but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package. 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.

Nota: 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 | None
php_crack.dll | Crack functions | None
php_ctype.dll | ctype family functions | None
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_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 | None
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 | None
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), 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_ldap.dll | LDAP functions | 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 | 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 | Requires libmysql.dll (bundled)
php_mysqli.dll | MySQLi functions | 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_pdf.dll | PDF functions | None
php_pgsql.dll | PostgreSQL functions | None
php_shmop.dll | Shared Memory functions | None
php_snmp.dll | SNMP get and walk functions | NT only!
php_soap.dll | SOAP functions | None
php_sockets.dll | Socket functions | None
php_sybase_ct.dll | Sybase functions | Requires: Sybase client libraries
php_tidy.dll | Tidy functions | None
php_tokenizer.dll | Tokenizer functions | None
php_w32api.dll | W32api functions | None
php_xmlrpc.dll | XML-RPC functions | Requires: iconv.dll (bundled)
php_xslt.dll | XSLT functions | 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 | None

Command Line PHP on Microsoft Windows

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

Nota:

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.

    Nota:

    Both PATH and PATHEXT are important pre-existing system variables in Windows, and care should be taken to not overwrite either variable, only to add to them.

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

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

    Nota:

    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.

Example #24 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

Nota:

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. As of Windows 10, this setting seems to be reversed, making the default install of Windows 10 support inherited console handles automatically. This » Microsoft forum post provides the explanation.

Troubleshooting PHP on Windows
Instalarea pe platforme de Cloud Computing
Installation on Windows systems


Instalarea pe platforme de Cloud Computing

Cuprins

  • Azure App Services
  • Amazon EC2

PHP se instaleza în cloud. În cloud-ul PHP!

Installation on old Windows systems
Azure App Services
Installarea ?i configurarea


Azure App Services

PHP is frequently used on Azure App Services (aka Microsoft Azure, Windows Azure, Azure Web Apps).

Azure App Services manages pools of Windows Web Servers to host your web application, as an alternative to managing your own web server on your own Azure Compute VMs or other servers.

PHP is already enabled for your Azure App Services web site automatically. In the Azure Portal, select your web site, and you can choose which version of PHP to use. You may want to choose a newer version than the default.

As such, PHP and extensions will run on Azure App Services just as it will on other Windows servers. Much of the knowledgebase is also portable, so see the Windows Troubleshooting Page too. However, the management interface for Azure App Services is different:

  • Azure portal: create, edit settings and delete web sites. » Azure Portal

  • Kudu Dashboard: [your web site name].azurewebsites.net Then, the Kudu dashboard is » https://[your web site name].scm.azurewebsites.net/. The Dashboard gives you access to some debugging capabilities, file management and site extensions. Site extensions are an Azure mechanism to add extra programs, like PHP preview builds, to your web site.

  • You can not use IIS Manager, Server Manager, or RDP.

There is also a PHP SDK for programmatically using many Azure Services from your PHP code. See » Azure SDK for PHP.

For more information, see » Azure PHP Developer Center

WinCache

WinCache is enabled by default on Azure App Services and it is recommended that you leave it enabled. If you install your own build of PHP, you should enable WinCache on that too.

Custom PHP Build

You may upload your own PHP build to your D:\Home (C:\ is NOT writable). Then in the Azure Portal, set SCRIPT_PROCESSOR for .php to the absolute path to php-cgi.exe file in your build.

Instalarea pe platforme de Cloud Computing
Amazon EC2
Instalarea pe platforme de Cloud Computing


Amazon EC2

PHP se instaleaza pe » platforma cloud EC2.

A se vedea ?i » SDK AWS pentru PHP.

Azure App Services
FastCGI Process Manager (FPM)
Instalarea pe platforme de Cloud Computing


FastCGI Process Manager (FPM)

Cuprins

  • 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
Installarea ?i configurarea


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

  • --with-fpm-systemd - Activate systemd integration (default - no).

  • --with-fpm-acl - Use POSIX Access Control Lists (default - no). Since PHP 5.6.5.

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


Configuration

FPM uses php.ini syntax for its configuration file - php-fpm.conf, and pool configuration files.

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. If it's set to "syslog", log is sent to syslogd instead of being written in a local file.

log_level string

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

syslog.facility string

used to specify what type of program is logging the message. Default value: daemon.

syslog.ident string

Prepended to every message. If you have multiple FPM instances running on the same server, you can change the default value which must suit common needs. Default value: php-fpm.

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.

process.max int

The maximum number of processes FPM will fork. This has been design to control the global number of processes when using dynamic PM within a lot of pools. Use it with caution. Default value: 0.

process.priority int

Specify the nice(2) priority to apply to the master process (only if set). The value can vary from -19 (highest priority) to 20 (lower priority). Default value: not set.

daemonize boolean

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

rlimit_files int

Set open file descriptor rlimit for the master process. Default value: Set open file descriptor rlimit for the master process.

rlimit_core int

Set max core size rlimit for the master process. Default value: 0.

events.mechanism string

Specify the event mechanism FPM will use. The following is available: select, pool, epoll, kqueue (*BSD), port (Solaris). Default value: not set (auto detection).

systemd_interval int

When FPM is build with systemd integration, specify the interval, in second, between health report notification to systemd. Set to 0 to disable. Default value: 10.

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. IPv6 addresses are allowed since PHP 5.5.20 and 5.6.4.

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

listen.group string

See listen.owner.

listen.mode string

See listen.owner.

listen.acl_users string

When POSIX Access Control Lists are supported you can set them using this option. When set, listen.owner and listen.group are ignored. Value is a comma separated list of user names. Since PHP 5.6.5.

listen.acl_groups string

See listen.acl_users. Value is a comma separated list of group names. Since PHP 5.6.5.

user string

Unix user of FPM processes. This option is mandatory.

group string

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

pm string

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

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

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

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

pm.max_children int

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

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

pm.start_servers int

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

The number of seconds after which an idle process will be killed. Used only when pm is set to ondemand. Available units: s(econds)(default), m(inutes), h(ours), or d(ays). Default value: 10s.

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.

process.priority int

Specify the nice(2) priority to apply to the worker process (only if set). The value can vary from -19 (highest priority) to 20 (lower priority). Default value: not set.

prefix string

Specify prefix for path evaluation

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 for child processes in this pool. Default value: system defined value.

rlimit_core int

Set max core size rlimit for child processes in this pool. 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.

clear_env boolean

Clear environment in FPM workers. Prevents arbitrary environment variables from reaching FPM worker processes by clearing the environment in workers before env vars specified in this pool configuration are added. Since PHP 5.4.27, 5.5.11, and 5.6.0. Default value: Yes.

security.limit_extensions string

Limits the extensions of the main script FPM will allow to parse. This can prevent configuration mistakes on the web server side. You should only limit FPM to .php extensions to prevent malicious users to use other extensions to execute php code. Default value: .php .phar

access.log string

The access log file. Default value: not set

access.format string

The access log format. Default value: "%R - %u %t \"%m %r\" %s"

It's possible to pass additional environment variables and update PHP settings of a certain pool. To do this, you need to add the following options to the pool configuration file.

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

As of 5.3.3, PHP settings are also possible to be set in webserver.

Example #2 set PHP settings in nginx.conf

set $php_value "pcre.backtrack_limit=424242";
set $php_value "$php_value \n pcre.recursion_limit=99999";
fastcgi_param  PHP_VALUE $php_value;

fastcgi_param  PHP_ADMIN_VALUE "open_basedir=/var/www/htdocs";
Precautie

Because these settings are passed to php-fpm as fastcgi headers, php-fpm should not be bound to a worldwide accessible address. Otherwise, anyone could alter the PHP configuration options. See also listen.allowed_clients.

Installation
Installation of PECL extensions
FastCGI Process Manager (FPM)


Installation of PECL extensions

Cuprins

  • 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
Installarea ?i configurarea


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 the 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 Git 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 The PHP project compiles and offers Windows DLLs for most PECL extensions on the respective package page.
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" 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 » PECL submit.

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:

Example #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

Nota:

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 /your/phpsrcdir/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

Nota: 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
Probleme?
Installation of PECL extensions


Probleme?

Cuprins

  • Citi?i FAQ
  • Alte probleme
  • Rapoarte de probleme
Compiling PECL extensions statically into PHP
Citi?i FAQ
Installarea ?i configurarea


Citi?i FAQ

Unele probleme se întâlnesc mai des decât altele. Cele mai des întâlnite sunt descrise în FAQ al PHP, ce face parte din acest manual.

Probleme?
Alte probleme
Probleme?


Alte probleme

Daca tot a?i ramas blocat, cineva din lista de distribu?ie po?tala a instalarii PHP ar putea sa va ajute. Întâi ar trebui sa verifica?i arhivele, probabil cineva de acum a dat un raspuns altcuiva în legatura cu aceea?i problema pe care o ave?i ?i dumneavoastra. Arhivele sunt disponibile de pe pagina de suport » http://www.php.net/support.php. Pentru a va înscrie la lista de distribu?ie po?tala a instalarii PHP trimite?i un mesaj vid la adresa » php-install-subscribe@lists.php.net. Adresa listei de distribu?ie po?tala este » php-install@lists.php.net.

Daca dori?i sa ob?ine?i ajutor din lista de distribu?ie po?tala va rugam sa fi?i cât mai precis ?i sa oferi?i detaliile necesare despre mediul de lucru (care este sistemul de operare, versiunea PHP, care este serverul web, daca rula?i PHP în regim CGI sau ca modul al serverului, modul securizat, etc.), ?i preferabil cod-sursa suficient pentru ca al?ii sa poata reproduce ?i testa problema dumneavoastra.

Citi?i FAQ
Rapoarte de probleme
Probleme?


Rapoarte de probleme

Daca consdera?i ca a?i depistat o problema în PHP, va rugam sa o raporta?i. Programatorii PHP probabil ca nu ?tiu despre ea, ?i daca nu o raporta?i, sunt ?anse sa nu fie corectata degraba. Pute?i sa raporta?i probleme utilizând sistemul de urmarire a problemelor la » http://bugs.php.net/. Va rugam sa nu raporta?i despre probleme în listele de distibu?ie po?tala sau în scrisori personale. Sistemul de urmarire a problemelor este potrivit ?i pentru cererile de noi facilita?i.

Va rugam sa studia?i documentul » Cum sa raporta?i o problema înainte de a transmite rapoarte de probleme!

Alte probleme
Runtime Configuration
Probleme?


Runtime Configuration

Cuprins

  • The configuration file
  • .user.ini files
  • Where a configuration setting may be set
  • How to change configuration settings
Rapoarte de probleme
The configuration file
Installarea ?i configurarea


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

Nota:

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.

Using environment variables can be used in php.ini as shown below.

Example #1 php.ini Environment Variables

; PHP_MEMORY_LIMIT is taken from environment
memory_limit = ${PHP_MEMORY_LIMIT}

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 Git helpful too.

Example #2 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".

Scan directories

It is possible to configure PHP to scan for .ini files in a directory after reading php.ini. This can be done at compile time by setting the --with-config-file-scan-dir option. In PHP 5.2.0 and later, the scan directory can then be overridden at run time by setting the PHP_INI_SCAN_DIR environment variable.

It is possible to scan multiple directories by separating them with the platform-specific path separator (; on Windows, NetWare and RISC OS; : on all other platforms; the value PHP is using is available as the PATH_SEPARATOR constant). If a blank directory is given in PHP_INI_SCAN_DIR, PHP will also scan the directory given at compile time via --with-config-file-scan-dir .

Within each directory, PHP will scan all files ending in .ini in alphabetical order. A list of the files that were loaded, and in what order, is available by calling php_ini_scanned_files(), or by running PHP with the --ini option.

Assuming PHP is configured with --with-config-file-scan-dir=/etc/php.d,
and that the path separator is :...

$ php
  PHP will load all files in /etc/php.d/*.ini as configuration files.

$ PHP_INI_SCAN_DIR=/usr/local/etc/php.d php
  PHP will load all files in /usr/local/etc/php.d/*.ini as
  configuration files.

$ PHP_INI_SCAN_DIR=:/usr/local/etc/php.d php
  PHP will load all files in /etc/php.d/*.ini, then
  /usr/local/etc/php.d/*.ini as configuration files.

$ PHP_INI_SCAN_DIR=/usr/local/etc/php.d: php
  PHP will load all files in /usr/local/etc/php.d/*.ini, then
  /etc/php.d/*.ini as configuration files.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | Hash marks (#) are no longer recognized as comments.
5.3.0 | Hash marks (#) should no longer be used as comments and will throw a deprecation warning if used.
5.2.0 | The PHP_INI_SCAN_DIR environment variable can be set to override the scan directory set via the configure script.
5.1.0 | It is possible to refer to existing .ini variables from within .ini files.

Runtime Configuration
.user.ini files
Runtime Configuration


.user.ini files

Since PHP 5.3.0, PHP includes support for configuration 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 running PHP as Apache module, 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. Since PHP 5.3, entry can be set in .user.ini
PHP_INI_PERDIR | Entry can be set in php.ini, .htaccess, httpd.conf or .user.ini (since PHP 5.3)
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.

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

Example #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>

Precautie

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
Informa?ii de referin?a despre limbaj
Runtime Configuration


Informa?ii de referin?a despre limbaj

  • Sintaxa de baza
    • Tag-uri PHP
    • Evadarea din HTML
    • Separarea instruc?iunilor
    • Comentarii
  • Types
    • Introduction
    • Booleans
    • Integers
    • Floating point numbers
    • Strings
    • Arrays
    • Objects
    • Resources
    • NULL
    • Callbacks / Callables
    • Pseudo-types and variables used in this documentation
    • Type Juggling
  • Variables
    • Basics
    • Predefined Variables
    • Variable scope
    • Variable variables
    • Variables From External Sources
  • Constants
    • Syntax
    • Magic constants
  • Expressions
  • 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
  • Functions
    • User-defined functions
    • Function arguments
    • Returning values
    • Variable functions
    • Internal (built-in) functions
    • Anonymous functions
  • Clase ?i Obiecte
    • Introducere
    • The Basics
    • Properties
    • Class Constants
    • Autoîncarcarea claselor
    • Constructori ?i Destructori
    • Vizibilitatea
    • Object Inheritance
    • Scope Resolution Operator (::)
    • Static Keyword
    • Clase Abstracte
    • Object Interfaces
    • Traits
    • Anonymous classes
    • Overloading
    • Object Iteration
    • Magic Methods
    • Final Keyword
    • Object Cloning
    • Comparing Objects
    • Indicarea Tipului
    • 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
  • Errors
    • Basics
    • Errors in PHP 7
  • Exceptions
    • Extending Exceptions
  • Generators
    • Generators overview
    • Generator syntax
    • Comparing generators with Iterator objects
  • References Explained
    • What References Are
    • What References Do
    • What References Are Not
    • Passing by Reference
    • Returning References
    • Unsetting References
    • Spotting References
  • 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
  • Excep?ii predefinite
    • Exception
    • ErrorException
    • Error
    • ArithmeticError
    • AssertionError
    • DivisionByZeroError
    • ParseError
    • TypeError
  • Interfe?e ?i clase predefinite
    • Traversable — The Traversable interface
    • Iterator — The Iterator interface
    • IteratorAggregate — The IteratorAggregate interface
    • Throwable
    • ArrayAccess — The ArrayAccess interface
    • Serializable — The Serializable interface
    • Closure — The Closure class
    • Generator — The Generator 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
    • MongoDB context options — MongoDB 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
Sintaxa de baza
Manualul PHP


Sintaxa de baza

Cuprins

  • Tag-uri PHP
  • Evadarea din HTML
  • Separarea instruc?iunilor
  • Comentarii
Informa?ii de referin?a despre limbaj
Tag-uri PHP
Informa?ii de referin?a despre limbaj


Tag-uri PHP

Când PHP parseaza un fi?ier, se uita dupa tag-urile de deschidere ?i închidere, acestea sunt <?php ?i ?>, care indica când PHP începe ?i termina interpretarea codului dintre ele. Parsarea în aceasta maniera permite PHP sa fie încorporat în tot felul de documente, pentru ca orice este în afara perechii de tag-uri de deschidere ?i închidere este ignorat de catre parsatorul PHP.

De asemenea, PHP permite tag scurt de deschidere <? (nu se încurajeaza folosirea lui deoarece este valabil numai activând directiva short_open_tag din fi?ierul de configurare php.ini, sau daca PHP a fost configurat cu op?iunea --enable-short-tags ).

Daca un fi?ier con?ine numai cod PHP, este de preferat omiterea tag-ului de închidere PHP de la sfâr?itul paginii. Aceasta previne spa?iu gol accidental sau noi rânduri adaugate dupa tag-ul de închidere PHP, ceea ce ar cauza efecte nedorite deaorece PHP va începe buferizarea ie?irii când nu este nici o inten?ie din partea programatorului sa trimita vre-o ie?ire la acel punct din script.

<?php
echo "Hello world";

// ... more code

echo "Ultima declara?ie";

// script-ul se termina aici fara tag de închidere

Istoricul schimbarilor
Versiune | Descriere
7.0.0 | Tag-urile ASP <%, %>, <%= ?i tag-ul de stil script <script language="php"> sunt excluse din PHP.
5.4.0 | Tag-ul <?= este mereu disponibil indiferent de setarea ini short_open_tag.

Sintaxa de baza
Evadarea din HTML
Sintaxa de baza


Evadarea din HTML

Totul ce se afla în afara perechilor de tag-uri de deschidere ?i închidere este ignorat de catre parsatorul PHP, ceea ce permite fi?ierelor PHP sa aiba con?inut mixt. Aceasta permite PHP sa fie încorporat în documente HTML, de exemplu pentru a crea ?abloane.

<p>Acesta va fi ignorat de PHP ?i afi?at în browser.</p>
<?php echo 'În timp ce acesta va fi parsat.'; ?>
<p>Acesta va fi de asemenea ignorat de PHP ?i afi?at în browser.</p>
Aceasta func?ioneaza conform a?teptarilor, deoarece când PHP întâlne?te tag-ul de închidere, pur ?i simplu începe sa afi?eze tot ce gase?te (cu excep?ia trecerii la linie noua ce urmeaza imediat dupa acesta - vezi separarea instruc?iunilor) pâna când da de un alt tag de deschidere, doar daca nu este în mijlocul unei declara?ii condi?ionale, caz în care interpretatorul va determina rezultatul condi?ionalului înainte de a lua o decizie peste ce sa sara. Vezi urmatorul exemplu.

Utilizarea structurilor cu condi?ii

Example #1 Evadare avansata folosind condi?ii

<?php if ($expression == true): ?>
  Aceasta se va afi?a daca expresia este adevarata.
<?php else: ?>
  Altfel aceasta va fi afi?at.
<?php endif; ?>
În acest exemplu PHP va sari peste blocurile unde con?ionalul nu este îndeplinit, chiar daca sunt în afara tag-urilor PHP de deschidere/închidere, PHP sare peste ele conform condi?iilor, deoarece interpretatorul PHP va sari peste blocurile condi?iei neîndeplinite.

Pentru afi?area blocurilor mari de text, în general ie?irea din parsatorul PHP este mai eficienta decât trimiterea întregului text prin echo sau print.

În PHP 5 sunt disponibile cel mult cinci perechi diferite de tag-uri de deschidere ?i de închidere, în dependen?a de modul cum este configurat PHP. Doua dintre ele, <?php ?> ?i <script language="php"> </script> sunt mereu disponibile. De asemenea exista tag-ul scurt de afi?are <?= ?>, care este întotdeauna disponibil în PHP 5.4.0 ?i ulterior.

Celelalte doua sunt tag-urile scurte ?i tag-uri în stil ASP. Ca atare, în timp ce unii oameni gasesc tag-urile scurte ?i tag-urile stil ASP comode, ele sunt mai pu?in portabile, ?i în general nerecomandate.

Nota:

De asemenea re?ine?i ca daca încorpora?i PHP în XML sau XHTML va trebui sa folosi?i tag-urile <?php ?> pentru a va conforma standardelor.

PHP 7 înceteaza sus?inerea tag-urilor ASP ?i <script language="php">. Ca atare, va recomandam sa utiliza?i doar <?php ?> ?i <?= ?> la scrierea codului PHP pentru maximizarea compatibilita?ii.

Example #2 Tag-uri PHP de deschidere ?i închidere

1.  <?php echo 'daca vrei sa folose?ti cod PHP în documente XHTML sau XML
                folose?te aceste tag-uri'; ?>

2.  Pute?i utiliza tag-ul scurt de afi?are pentru a <?= 'afi?a aceasta' ?>.
    El este întotdeauna activat în PHP 5.4.0 ?i ulterior, ?i este echivalent cu
    <?php echo 'afi?a aceasta' ?>.

3.  <? echo 'acest cod este între tag-uri scurte ?i va func?iona doar daca '.
            'op?iunea short_open_tag este activata'; ?>

4.  <script language="php">
        echo 'anumitori editori (precum FrontPage) nu le place
              sa proceseze instruc?iuni între aceste tag-uri';
    </script>
    Aceasta sintaxa este eliminata în PHP 7.0.0.

5.  <% echo 'Op?ional pute?i folosi tag-uri stil ASP'; %>
    Codul între aceste tag-uri <%= $variable; %> este o scurtatura pentru acest cod <% echo $variable; %>
    Aceste doua sintaxe au fost eliminate în PHP 7.0.0.

Tag-uri scurte (exemplul trei) sunt disponibile numai când sunt activate cu ajutorul directivei short_open_tag din fi?ierul de configurare php.ini, sau daca PHP a fost configurat cu op?iunea --enable-short-tags .

Tag-uri stil ASP (exemplul cinci) sunt valabile numai când sunt activate cu ajutorul directivei asp_tags din fi?ierul de configurare php.ini ?i au fost eliminate în PHP 7.0.0.

Nota:

Folosirea tag-urilor scurte ar trebui evitata în timpul dezvoltarii aplica?iilor sau bibliotecilor destinate redistribuirii, sau implemetarii pe servere PHP asupra carora nu ave?i control, deoarece tag-urile scurte s-ar putea sa nu fie sus?inute de acel server. Pentru cod portabil, redistribuibil, asigura?i-va ca nu folosi?i tag-uri scurte.

Nota:

În PHP 5.2 ?i versiunile anterioare, parsatorul nu permite ca tag-ul de deschidere <?php sa fie singurul element din fi?ier. Aceasta este permis începând cu PHP 5.3 cu condi?ia sa existe unul sau mai multe caractere spa?iu gol dupa tag-ul de deschidere.

Nota:

Începând cu PHP 5.4, tag-ul scurt de afi?are <?= este mereu recunoscut ?i valid, indiferent de setarea short_open_tag.

Tag-uri PHP
Separarea instruc?iunilor
Sintaxa de baza


Separarea instruc?iunilor

Precum în C sau Perl, PHP necesita ca instruc?iunile sa fie terminate cu punct ?i virgula. Tag-ul de închidere al unui bloc de cod PHP implica automat punct ?i virgula; nu trebuie sa ave?i punct ?i virgula la finalul ultimului rând al unui bloc PHP. Tag-ul de închidere pentru bloc va include ?i trecerea la linia noua imediat urmatoare, daca aceasta este prezenta.

<?php
    echo 'Acesta este un test';
?>

<?php echo 'Acesta este un test' ?>

<?php echo 'Am omis ultimul tag de închidere';

Nota:

Tag-ul de închidere al unui bloc PHP la sfâr?itul unui fi?ier este op?ional ?i, în anumite cazuri, omiterea lui este folositoare când se folosesc include sau require, astfel încât nu apar spa?ii goale nedorite la sfâr?itul fi?ierelor, ?i ve?i putea sa adauga?i antete la raspuns mai târziu. Este de asemenea comod daca folosi?i buferizarea ie?irii, ?i nu este de dorit vizualizarea spa?iului gol la sfâr?itul par?ii generate de fi?ierele incluse.

Evadarea din HTML
Comentarii
Sintaxa de baza


Comentarii

PHP suporta comentarii 'C', 'C++' sau stil Unix shell (stil Perl). De exemplu:

<?php
    echo 'Acesta este un test'; // Acesta este un comentariu de un rând tip C++
    /* Acesta este un comentariu multi-rând
       înca un rând de comentariu */
    echo 'Acesta este înca un test';
    echo 'Un Test Final'; # Acesta este un comentariu de un rând stil shell
?>

Comentariul stil "un rând" comenteaza pâna la sfâr?itul liniei sau blocului curent de cod PHP, oricare dintre acestea survine mai întâi. Aceasta înseamna ca codul HTML dupa // ... ?> sau # ... ?> VA FI afi?at: ?> iese din modul PHP ?i intra în modul HTML, iar // sau # nu pot influen?a acest lucru. Daca directiva de configura?ie asp_tags este activata, se comporta la fel cu // %> ?i # %>. Totu?i, tag-ul </script> nu iese din modul PHP in comentariile de un rând.

<h1>Acesta este un <?php # echo 'simplu';?> exemplu</h1>
<p>Antetul de deasupra va arata 'Acesta este un  exemplu'.</p>

Comentariile în stil "C" se termina la primul */ întâlnit. Asigura?i-va ca nu încorpora?i comentarii în stil "C" unul în altul. Este u?or de facut aceasta gre?eala daca încerca?i sa comenta?i un bloc mare de cod.

<?php
 /*
    echo 'Acesta este un test'; /* Acest comentariu va cauza o problema */
 */
?>

Separarea instruc?iunilor
Types
Sintaxa de baza


Types

Cuprins

  • Introduction
  • Booleans
  • Integers
  • Floating point numbers
  • Strings
  • Arrays
  • Objects
  • Resources
  • NULL
  • Callbacks / Callables
  • Pseudo-types and variables used in this documentation
  • Type Juggling
Comentarii
Introduction
Informa?ii de referin?a despre limbaj


Introduction

PHP supports eight primitive types.

Four scalar types:

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

Three compound types:

  • array
  • object
  • callable

And finally two special types:

  • resource
  • NULL

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

  • mixed
  • number
  • callback (aka callable)
  • array|object
  • void

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.

Nota: 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 constants 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
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

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

Avertizare

-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 Z = {..., -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.

Example #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)
$a = 0b11111111; // binary number (equivalent to 255 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, except on Windows prior to PHP 7, where it was always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, maximum value using the constant PHP_INT_MAX since PHP 5.0.5, and minimum value using the constant PHP_INT_MIN since PHP 7.0.0.

Avertizare

Prior to PHP 7, if an invalid digit was given in an octal integer (i.e. 8 or 9), the rest of the number was ignored. Since PHP 7, a parse error is emitted.

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.

Example #2 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)
?>

Example #3 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 towards zero, 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.

If a resource is converted to an integer, then the result will be the unique resource number assigned to the resource by PHP at runtime.

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 other than Windows), 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!

Nota:

As of PHP 7.0.0, instead of being undefined and platform-dependent, NaN and Infinity will always be zero when cast to integer.

Avertizare

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

Precautie

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

Avertizare

Floating point precision

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

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

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

For a "simple" explanation, see the » floating point guide that's also titled "Why don’t my numbers add up?"

Converting to float

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

Comparing floats

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

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

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

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

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

NaN

Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unrepresentable value in floating-point calculations. Any loose or strict comparisons of this value against any other value, including itself, but except TRUE, 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.

Nota: As of PHP 7.0.0, there are no particular restrictions regarding the length of a string on 64-bit builds. On 32-bit builds and in earlier versions, a string can be as large as up to 2GB (2147483647 bytes maximum)

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.

Nota: 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 the following 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.4)
\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, which silently overflows to fit in a byte (e.g. "\400" === "\000")
\x[0-9A-Fa-f]{1,2} | the sequence of characters matching the regular expression is a character in hexadecimal notation
\u{[0-9A-Fa-f]+} | the sequence of characters matching the regular expression is a Unicode codepoint, which will be output to the string as that codepoint's UTF-8 representation (added in PHP 7.0.0)

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.

Avertizare

It is very important to note that the line with the closing identifier must contain no other characters, except 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 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.

Example #1 Invalid example

<?php
class foo {
    public $bar = <<<EOT
bar
    EOT;
}
// Identifier must not be indented
?>

Example #2 Valid example

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

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

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.

Example #3 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;
?>

Exemplul de mai sus va afi?a:

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:

Example #4 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:

Example #5 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:

Example #6 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.

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

Exemplul de mai sus va afi?a:

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

Example #8 Static data example

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

Nota:

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.";
// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of ${juice}s."
?>

Exemplul de mai sus va afi?a:

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

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.

Example #9 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 $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
?>

Exemplul de mai sus va afi?a:

He drank some apple juice.
He drank some orange juice.
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 .

As of PHP 7.1.0 also negative numeric indices are supported.

Example #10 Negative numeric indices

<?php
$array = [-3 => 'foo'];
echo "The element at index -3 is $array[-3].", PHP_EOL;
?>

Exemplul de mai sus va afi?a:

The element at index -3 is foo.

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

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

Exemplul de mai sus va afi?a:

I am bar.
I am bar.

Nota:

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.

Nota: As of PHP 7.1.0, negative string offsets are also supported. These specify the offset from the end of the string. Formerly, negative offsets emitted E_NOTICE for reading (yielding an empty string) and E_WARNING for writing (leaving the string untouched).

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

Avertizare

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. Only the first character of an assigned string is used. As of PHP 7.1.0, assigning an empty string throws a fatal error. Formerly, it assigned a NULL byte.

Avertizare

Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1.

Nota: As of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was silently converted to an array.

Example #11 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';

?>

As of PHP 5.4 string offsets have to either be integers or integer-like strings, otherwise a warning will be thrown. Previously an offset like "foo" was silently cast to 0.

Example #12 Differences between PHP 5.3 and PHP 5.4

<?php
$str = 'abc';

var_dump($str['1']);
var_dump(isset($str['1']));

var_dump($str['1.0']);
var_dump(isset($str['1.0']));

var_dump($str['x']);
var_dump(isset($str['x']));

var_dump($str['1x']);
var_dump(isset($str['1x']));
?>

Exemplul de mai sus va afi?a în PHP 5.3:

string(1) "b"
bool(true)
string(1) "b"
bool(true)
string(1) "a"
bool(true)
string(1) "b"
bool(true)

Exemplul de mai sus va afi?a în PHP 5.4:

string(1) "b"
bool(true)

Warning: Illegal string offset '1.0' in /tmp/t.php on line 7
string(1) "b"
bool(false)

Warning: Illegal string offset 'x' in /tmp/t.php on line 9
string(1) "a"
bool(false)
string(1) "b"
bool(false)

Nota:

Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.

Nota:

PHP 5.5 added support for accessing characters within string literals using [] or {}.

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

Nota:

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.

In order to convert objects to string magic method __toString must be used.

Resources are always converted to strings with the structure "Resource id #1", where 1 is the resource number assigned to the resource by PHP at runtime. While the exact structure of this string should not be relied on and is subject to change, it will always be unique for a given resource within the lifetime of a script being executed (ie a Web request or CLI process) and won't be reused. 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 be 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 using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.

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

The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. array(1, 2) is preferred over array(1, 2, ). For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new elements at the end.

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

Example #1 A simple array

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

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

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

Additionally the following key casts will occur:

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

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

Example #2 Type Casting and Overwriting example

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

Exemplul de mai sus va afi?a:

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

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

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

Example #3 Mixed integer and string keys

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

Exemplul de mai sus va afi?a:

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

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

Example #4 Indexed arrays without key

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

Exemplul de mai sus va afi?a:

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

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

Example #5 Keys not on all elements

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

Exemplul de mai sus va afi?a:

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

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

Accessing array elements with square bracket syntax

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

Example #6 Accessing array elements

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

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

Exemplul de mai sus va afi?a:

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

Nota:

Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).

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

As of PHP 5.5 it is possible to array dereference an array literal.

Example #7 Array dereferencing

<?php
function getArray() {
    return array(1, 2, 3);
}

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

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

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

Nota:

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.

Nota:

Array dereferencing a scalar value which is not a string silently yields NULL, i.e. without issuing an error message.

Creating/modifying with square bracket syntax

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

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

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

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize a variable by a direct assignment.

Nota: As of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was silently converted to 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
?>

Nota:

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

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

<?php
// Create a simple array.
$array = array(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);
?>

Exemplul de mai sus va afi?a:

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.

Nota:

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

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

Exemplul de mai sus va afi?a:

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 occurred";
$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 occurred";
$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.

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

Example #8 Using array()

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

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

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

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

Example #9 Collection

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

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

?>

Exemplul de mai sus va afi?a:

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 by passing them by reference.

Example #10 Changing element in the loop

<?php
foreach ($colors as &$color) {
    $color = strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */

print_r($colors);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

This example creates a one-based array.

Example #11 One-based index

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

Exemplul de mai sus va afi?a:

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

Example #12 Filling an array

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

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

Example #13 Sorting an array

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

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

Example #14 Recursive and multi-dimensional arrays

<?php
$fruits = array ( "fruits"  => array ( "a" => "orange",
                                       "b" => "banana",
                                       "c" => "apple"
                                     ),
                  "numbers" => array ( 1,
                                       2,
                                       3,
                                       4,
                                       5,
                                       6
                                     ),
                  "holes"   => array (      "first",
                                       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. An array converts to an object with properties named by keys and corresponding values, with the exception of numeric keys which will be inaccessible unless iterated.

<?php
$obj = (object) array('1' => 'foo');
var_dump(isset($obj->{'1'})); // outputs 'bool(false)'
var_dump(key($obj)); // outputs 'int(1)'
?>

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 handles 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 being part of 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.

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

<?php
$var = NULL;
?>

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

Casting to NULL

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

Resources
Callbacks / Callables
Types


Callbacks / Callables

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

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

Passing

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

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1. Accessing protected and private methods from within a class is allowed.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0. As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName'.

Apart from common user-defined function, anonymous functions can also be passed to a callback parameter.

Example #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

// Type 6: Objects implementing __invoke can be used as callables (since PHP 5.3)
class C {
    public function __invoke($name) {
        echo 'Hello ', $name, "\n";
    }
}

$c = new C();
call_user_func($c, 'PHP!');
?>

Example #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);
?>

Exemplul de mai sus va afi?a:

2 4 6 8 10

Nota:

Func?iile de apel invers înregistrate cu astfel de func?ii ca call_user_func() ?i call_user_func_array() nu vor fi apelate daca exista o excep?ie neinterceptata emisa într-un apel precedent.

NULL
Pseudo-types and variables used in this documentation
Types


Pseudo-types and variables used in this documentation

Pseudo-types are keywords used in the PHP documentation to specify the types or values an argument can have. Please note that that they are not primitives of the PHP language. So you cannot use pseudo-types as typehints in your own custom functions.

mixed

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

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

number

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

callback

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

array|object

array|object indicates that a parameter can be either array or object.

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.

Callbacks / Callables
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 multiplication 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 = "1";  // $foo is string (ASCII 49)
$foo *= 2;   // $foo is now an integer (2)
$foo = $foo * 1.3;  // $foo is now a float (2.6)
$foo = 5 * "10 Little Piggies"; // $foo is integer (50)
$foo = 5 * "10 Small Pigs";     // $foo is integer (50)
?>

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.

Nota:

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

Nota:

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
Variables
Types


Variables

Cuprins

  • Basics
  • Predefined Variables
  • Variable scope
  • Variable variables
  • Variables From External Sources
Type Juggling
Basics
Informa?ii de referin?a despre limbaj


Basics

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable 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]*'

Nota: For our purposes here, a letter is a-z, A-Z, and the bytes from 127 through 255 (0x7f-0xff).

Nota: $this is a special variable that can't be assigned.

Sfat

Accesa?i de asemenea Ghidul de stabilire a denumirilor de catre utilizatori.

For information on variable related functions, see the Variable Functions Reference.

<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var";      // outputs "Bob, Joe"

$4site = 'not yet';     // invalid; starts with a number
$_4site = 'not yet';    // valid; starts with an underscore
$täyte = 'mansikka';    // valid; 'ä' is (Extended) ASCII 228.
?>

By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.

PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:

<?php
$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
echo $foo;                 // $foo is altered too.
?>

One important thing to note is that only named variables may be assigned by reference.

<?php
$foo = 25;
$bar = &$foo;      // This is a valid assignment.
$bar = &(24 * 7);  // Invalid; references an unnamed expression.

function test()
{
   return 25;
}

$bar = &test();    // Invalid.
?>

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

Example #1 Default values of uninitialized variables

<?php
// Unset AND unreferenced (no use context) variable; outputs NULL
var_dump($unset_var);

// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
echo($unset_bool ? "true\n" : "false\n");

// String usage; outputs 'string(3) "abc"'
$unset_str .= 'abc';
var_dump($unset_str);

// Integer usage; outputs 'int(25)'
$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int);

// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);

// Array usage; outputs array(1) {  [3]=>  string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);

// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

Variables
Predefined Variables
Variables


Predefined Variables

PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line. For a listing of these variables, please see the section on Reserved Predefined Variables.

Avertizare

In PHP 4.2.0 and later, the default value for the PHP directive register_globals is off. This is a major change in PHP. Having register_globals off affects the set of predefined variables available in the global scope. For example, to get DOCUMENT_ROOT you'll use $_SERVER['DOCUMENT_ROOT'] instead of $DOCUMENT_ROOT, or $_GET['id'] from the URL http://www.example.com/test.php?id=3 instead of $id, or $_ENV['HOME'] instead of $HOME.

For related information on this change, read the configuration entry for register_globals, the security chapter on Using Register Globals , as well as the PHP » 4.1.0 and » 4.2.0 Release Announcements.

Using the available PHP Reserved Predefined Variables, like the superglobal arrays, is preferred.

From version 4.1.0 onward, PHP provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These new arrays are rather special in that they are automatically global--i.e., automatically available in every scope. For this reason, they are often known as "superglobals". (There is no mechanism in PHP for user-defined superglobals.) The superglobals are listed below; however, for a listing of their contents and further discussion on PHP predefined variables and their natures, please see the section Reserved Predefined Variables. Also, you'll notice how the older predefined variables ($HTTP_*_VARS) still exist. Începând cu PHP 5.0.0 variabilele predefinite cu tablourile lungi pot fi dezactivate cu ajutorul directivei register_long_arrays.

Nota: Variable variables

Superglobals cannot be used as variable variables inside functions or class methods.

Nota:

Even though both the superglobal and HTTP_*_VARS can exist at the same time; they are not identical, so modifying one will not change the other.

If certain variables in variables_order are not set, their appropriate PHP predefined arrays are also left empty.

Basics
Variable scope
Variables


Variable scope

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:

<?php
$a = 1;
include 'b.inc';
?>

Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:

<?php
$a = 1; /* global scope */

function test()
{
    echo $a; /* reference to local scope variable */
}

test();
?>

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

The global keyword

First, an example use of global:

Example #1 Using global

<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;
}

Sum();
echo $b;
?>

The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:

Example #2 Using $GLOBALS instead of global

<?php
$a = 1;
$b = 2;

function Sum()
{
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

Sum();
echo $b;
?>

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals:

Example #3 Example demonstrating superglobals and scope

<?php
function test_global()
{
    // Most predefined variables aren't "super" and require
    // 'global' to be available to the functions local scope.
    global $HTTP_POST_VARS;

    echo $HTTP_POST_VARS['name'];

    // Superglobals are available in any scope and do
    // not require 'global'. Superglobals are available
    // as of PHP 4.1.0, and HTTP_POST_VARS is now
    // deemed deprecated.
    echo $_POST['name'];
}
?>

Nota:

Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

Using static variables

Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:

Example #4 Example demonstrating need for static variables

<?php
function test()
{
    $a = 0;
    echo $a;
    $a++;
}
?>

This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

Example #5 Example use of static variables

<?php
function test()
{
    static $a = 0;
    echo $a;
    $a++;
}
?>

Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.

Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:

Example #6 Static variables with recursive functions

<?php
function test()
{
    static $count = 0;

    $count++;
    echo $count;
    if ($count < 10) {
        test();
    }
    $count--;
}
?>

Nota:

Static variables may be declared as seen in the examples above. From PHP 5.6 you can assign values to these variables which are the result of expressions, but you can't use any function here, what will cause a parse error.

Example #7 Declaring static variables

<?php
function foo(){
    static $int = 0;          // correct
    static $int = 1+2;        // correct (as of PHP 5.6)
    static $int = sqrt(121);  // wrong  (as it is a function)

    $int++;
    echo $int;
}
?>

Nota:

Static declarations are resolved in compile-time.

References with global and static variables

The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:

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

Exemplul de mai sus va afi?a:

NULL
object(stdClass)(0) {
}

A similar behaviour applies to the static statement. References are not stored statically:

<?php
function &get_instance_ref() {
    static $obj;

    echo 'Static object: ';
    var_dump($obj);
    if (!isset($obj)) {
        // Assign a reference to the static variable
        $obj = &new stdclass;
    }
    $obj->property++;
    return $obj;
}

function &get_instance_noref() {
    static $obj;

    echo 'Static object: ';
    var_dump($obj);
    if (!isset($obj)) {
        // Assign the object to the static variable
        $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();
?>

Exemplul de mai sus va afi?a:

Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
}

This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.

Predefined Variables
Variable variables
Variables


Variable variables

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

<?php
$a = 'hello';
?>

A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.

<?php
$$a = 'world';
?>

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:

<?php
echo "$a ${$a}";
?>

produces the exact same output as:

<?php
echo "$a $hello";
?>

i.e. they both produce: hello world.

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.

Precautie

Further dereferencing a variable property that is an array has different semantics between PHP 5 and PHP 7. The PHP 7.0 migration guide includes further details on the types of expressions that have changed, and how to place curly braces to avoid ambiguity.

Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of mulitple parts, or when the property name contains characters that are not otherwise valid (e.g. from json_decode() or SimpleXML).

Example #1 Variable property example

<?php
class foo {
    var $bar = 'I am bar.';
    var $arr = array('I am A.', 'I am B.', 'I am C.');
    var $r   = 'I am r.';
}

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

$start = 'b';
$end   = 'ar';
echo $foo->{$start . $end} . "\n";

$arr = 'arr';
echo $foo->{$arr[1]} . "\n";

?>

Exemplul de mai sus va afi?a:

I am bar.
I am bar.
I am bar.
I am r.

Avertizare

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.

Variable scope
Variables From External Sources
Variables


Variables From External Sources

HTML Forms (GET and POST)

When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are few ways to access this information, for example:

Example #1 A simple HTML form

<form action="foo.php" method="post">
    Name:  <input type="text" name="username" /><br />
    Email: <input type="text" name="email" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

As of PHP 5.4.0, there are only two ways to access data from your HTML forms. Currently available methods are listed below:

Example #2 Accessing data from a simple POST HTML form

<?php
echo $_POST['username'];
echo $_REQUEST['username'];
?>

There were some other ways of accessing user input in old PHP versions. These are listed below. See changelog at the bottom of the page for more details.

Example #3 Old methods of accessing user input

<?php
// WATCH OUT: these methods ARE NOT supported anymore.
// Valid ones were described above.

// Using import_request_variables() - this function has been removed in PHP 5.4.0
   import_request_variables('p', 'p_');
   echo $p_username;

// These long predefined variables were removed in PHP 5.4.0
   echo $HTTP_POST_VARS['username'];

// Using register_globals. This feature was removed in PHP 5.4.0
   echo $username;
?>

Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING (the information after the '?' in a URL). So, for example, http://www.example.com/test.php?id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST.

Nota:

Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"].

PHP also understands arrays in the context of form variables (see the related faq). You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data:

Example #4 More complex form variables

<?php
if ($_POST) {
    echo '<pre>';
    echo htmlspecialchars(print_r($_POST, true));
    echo '</pre>';
}
?>
<form action="" method="post">
    Name:  <input type="text" name="personal[name]" /><br />
    Email: <input type="text" name="personal[email]" /><br />
    Beer: <br />
    <select multiple name="beer[]">
        <option value="warthog">Warthog</option>
        <option value="guinness">Guinness</option>
        <option value="stuttgarter">Stuttgarter Schwabenbräu</option>
    </select><br />
    <input type="submit" value="submit me!" />
</form>

IMAGE SUBMIT variable names

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="sub" />

When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.

HTTP Cookies

PHP transparently supports HTTP cookies as defined by » RFC 6265. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the header() function. Cookie data is then available in the appropriate cookie data arrays, such as $_COOKIE as well as in $_REQUEST. See the setcookie() manual page for more details and examples.

If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:

<?php
  setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
  setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?>

That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first.

Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.

Example #5 A setcookie() example

<?php
if (isset($_COOKIE['count'])) {
    $count = $_COOKIE['count'] + 1;
} else {
    $count = 1;
}
setcookie('count', $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?>

Dots in incoming variable names

Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:

<?php
$varname.ext;  /* invalid variable name */
?>
Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended result.

For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.

Determining variable types

Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Register Globals, Magic Quotes and register_long_arrays has been removed
5.3.0 | Register Globals, Magic Quotes and register_long_arrays became deprecated
4.2.0 | register_globals directive defaults to off.
4.1.0 | Superglobal arrays, like $_POST and $_GET became available

Variable variables
Constants
Variables


Constants

Cuprins

  • Syntax
  • Magic constants

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Sfat

Accesa?i de asemenea Ghidul de stabilire a denumirilor de catre utilizatori.

Example #1 Valid and invalid constant names

<?php

// Valid constant names
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR", "something more");

// Invalid constant names
define("2FOO",    "something");

// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something");

?>

Nota: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).

Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope. For more information on scope, read the manual section on variable scope.

Variables From External Sources
Syntax
Informa?ii de referin?a despre limbaj


Syntax

You can define a constant by using the define()-function or by using the const keyword outside a class definition as of PHP 5.3.0. While define() allows a constant to be defined to an arbitrary expression, the const keyword has restrictions as outlined in the next paragraph. Once a constant is defined, it can never be changed or undefined.

When using the const keyword, only scalar data (boolean, integer, float and string) can be contained in constants prior to PHP 5.6. From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.

You can get the value of a constant by simply specifying its name. Unlike with variables, you should not prepend a constant with a $. You can also use the function constant() to read a constant's value if you wish to obtain the constant's name dynamically. Use get_defined_constants() to get a list of all defined constants.

Nota: Constants and (global) variables are in a different namespace. This implies that for example TRUE and $TRUE are generally different.

If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string (CONSTANT vs "CONSTANT"). An error of level E_NOTICE will be issued when this happens. See also the manual entry on why $foo[bar] is wrong (unless you first define() bar as a constant). This does not apply to (fully) qualified constants, which will raise a fatal error if undefined. If you simply want to check if a constant is set, use the defined() function.

These are the differences between constants and variables:

  • Constants do not have a dollar sign ($) before them;
  • Prior to PHP 5.3, Constants may only be defined using the define() function, not by simple assignment;
  • Constants may be defined and accessed anywhere without regard to variable scoping rules;
  • Constants may not be redefined or undefined once they have been set; and
  • Constants may only evaluate to scalar values. As of PHP 5.6 it is possible to define array constant using const keywords and as of PHP 7 array constants can also be defined using define() You may use arrays in constant scalar expressions (for example, const FOO = array(1,2,3)[0];), but the end result must be a value of allowed type.

Example #1 Defining Constants

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
?>

Example #2 Defining Constants using the const keyword

<?php
// Works as of PHP 5.3.0
const CONSTANT = 'Hello World';

echo CONSTANT;

// Works as of PHP 5.6.0
const ANOTHER_CONST = CONSTANT.'; Goodbye World';
echo ANOTHER_CONST;

const ANIMALS = array('dog', 'cat', 'bird');
echo ANIMALS[1]; // outputs "cat"

// Works as of PHP 7
define('ANIMALS', array(
    'dog',
    'cat',
    'bird'
));
echo ANIMALS[1]; // outputs "cat"
?>

Nota:

As opposed to defining constants using define(), constants defined using the const keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops, if statements or try/ catch blocks.

See also Class Constants.

Constants
Magic constants
Constants


Magic constants

PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.

There are nine magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script. All these "magical" constants are resolved at compile time, unlike regular constants thats resolved at runtime. These special constants are case-insensitive and are as follows:

A few "magical" PHP constants
Name | Description
__LINE__ | The current line number of the file.
__FILE__ | The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
__DIR__ | The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FUNCTION__ | The function name.
__CLASS__ | The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__ | The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__ | The class method name.
__NAMESPACE__ | The name of the current namespace.
ClassName::class | The fully qualified class name. See also ::class.

See also
get_class(),
get_object_vars(),
file_exists() ?i
function_exists().

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | Added ::class magic constant
5.4.0 | Added __TRAIT__ constant
5.3.0 | Added __DIR__ and __NAMESPACE__ constants
5.0.0 | Added __METHOD__ constant
5.0.0 | Before this version values of some magic constants were always lowercased. All of them are case-sensitive now (contain names as they were declared).
4.3.0 | Added __FUNCTION__ and __CLASS__ constants
4.0.2 | __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances

Syntax
Expressions
Constants


Expressions

Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".

The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).

After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.

Slightly more complex examples for expressions are functions. For instance, consider the following function:

<?php
function foo ()
{
    return 5;
}
?>

Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something.

Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports four scalar value types: integer values, floating point values (float), string values and boolean values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.

PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5. Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'.

Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is identical. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').

A very common type of expressions are comparison expressions. These expressions evaluate to either FALSE or TRUE. PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as if statements.

The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.

There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:

<?php
$first ? $second : $third
?>

If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.

The following example should help you understand pre- and post-increment and expressions in general a bit better:

<?php
function double($i)
{
    return $i*2;
}
$b = $a = 5;        /* assign the value five into the variable $a and $b */
$c = $a++;          /* post-increment, assign original value of $a
                       (5) to $c */
$e = $d = ++$b;     /* pre-increment, assign the incremented value of
                       $b (6) to $d and $e */

/* at this point, both $d and $e are equal to 6 */

$f = double($d++);  /* assign twice the value of $d before
                       the increment, 2*6 = 12 to $f */
$g = double(++$e);  /* assign twice the value of $e after
                       the increment, 2*7 = 14 to $g */
$h = $g += 10;      /* first, $g is incremented by 10 and ends with the
                       value of 24. the value of the assignment (24) is
                       then assigned into $h, and $h ends with the value
                       of 24 as well. */
?>

Some expressions can be considered as statements. In this case, a statement has the form of 'expr ;' that is, an expression followed by a semicolon. In '$b = $a = 5;', '$a = 5' is a valid expression, but it's not a statement by itself. '$b = $a = 5;' however is a valid statement.

One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE. The constants TRUE and FALSE (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the section about type-casting for details about how.

PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.

Magic constants
Operators
Informa?ii de referin?a despre limbaj


Operators

Cuprins

  • 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. The section also explains operator precedence and associativity, which govern exactly how expressions containing several different operators are evaluated.

Expressions
Operator Precedence
Informa?ii de referin?a despre limbaj


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 how the operators are grouped. For example "-" is left-associative, so 1 - 2 - 3 is grouped as (1 - 2) - 3 and evaluates to -4. "=" on the other hand is right-associative, so $a = $b = $c is grouped as $a = ($b = $c).

Operators of equal precedence that are non-associative cannot be used next to each other, for example 1 < 2 > 1 is illegal in PHP. The expression 1 <= 1 == 1 on the other hand is legal, because the == operator has lesser precedence than the <= operator.

Use of parentheses, even when not strictly necessary, can often increase readability of the code by making grouping explicit rather than relying on the implicit operator precedence and associativity.

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

Operator Precedence
Associativity | Operators | Additional Information
non-associative | clone new | clone and new
left | [ | array()
right | ** | arithmetic
right | ++ -- ~ (int) (float) (string) (array) (object) (bool) @ | types and increment/decrement
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
right | ?? | comparison
left | ? : | ternary
right | = += -= *= **= /= .= %= &= |= ^= <<= >>= | assignment
left | and | logical
left | xor | logical
left | or | logical

Example #1 Associativity

<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
// ternary operator associativity differs from C/C++
$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
?>

Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.

Example #2 Undefined order of evaluation

<?php
$a = 1;
echo $a + $a++; // may print either 2 or 3

$i = 1;
$array[$i] = $i++; // may set either index 1 or 2
?>

Example #3 +, - and . have the same precedence

<?php
$x = 4;
// this line might result in unexpected output:
echo "x minus one equals " . $x-1 . ", or so I hope\n";
// because it is evaluated like this line:
echo (("x minus one equals " . $x) - 1) . ", or so I hope\n";
// the desired precendence can be enforced by using parentheses:
echo "x minus one equals " . ($x-1) . ", or so I hope\n";
?>

Exemplul de mai sus va afi?a:

-1, or so I hope
-1, or so I hope
x minus one equals 3, or so I hope

Nota:

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 | Identity | Conversion of $a to int or float as appropriate.
-$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 | Modulo | Remainder of $a divided by $b.
$a ** $b | Exponentiation | Result of raising $a to the $b'th power. Introduced in PHP 5.6.

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. For integer division, see intdiv().

Operands of modulo are converted to integers (by stripping the decimal part) before processing. For floating-point modulo, see fmod().

The result of the modulo 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.

?>

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.

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

If both operands for the &, | and ^ operators are strings, then the operation will be performed on the ASCII values of the characters that make up the strings and the result will be a string. In all other cases, both operands will be converted to integers and the result will be an integer.

If the operand for the ~ operator is a string, the operation will be performed on the ASCII values of the characters that make up the string and the result will be a string, otherwise the operand and the result will be treated as integers.

Both operands and the result for the << and >> operators are always treated as integers.

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

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

Exemplul de mai sus va afi?a:

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

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

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

Exemplul de mai sus va afi?a pe ma?ini pe 32 de bi?i:

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

Exemplul de mai sus va afi?a pe ma?ini pe 64 de bi?i:

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

Avertizare

Shifting integers by values greater than or equal to the system long integer width results in undefined behavior. In other words, don't shift more than 31 bits on a 32-bit system, and don't shift more than 63 bits on a 64-bit system.

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.
$a <=> $b | Spaceship | An integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b. Available as of PHP 7.

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;
}
?>
<?php
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1

// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1

// Objects
$a = (object) ["a" => "b"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 0

$a = (object) ["a" => "b"];
$b = (object) ["a" => "c"];
echo $a <=> $b; // -1

$a = (object) ["a" => "c"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 1

// only values are compared
$a = (object) ["a" => "b"];
$b = (object) ["b" => "b"];
echo $a <=> $b; // 1

?>

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 both sides 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)
object | anything | object is always greater
array | anything | array is always greater

Example #1 Boolean/null comparison

<?php
// Bool and null are compared as bool always
var_dump(1 == TRUE);  // TRUE - same as (bool)1 == TRUE
var_dump(0 == FALSE); // TRUE - same as (bool)0 == FALSE
var_dump(100 < TRUE); // FALSE - same as (bool)100 < TRUE
var_dump(-10 < FALSE);// FALSE - same as (bool)-10 < FALSE
var_dump(min(-100, -10, NULL, 10, 100)); // NULL - (bool)NULL < (bool)-100 is FALSE < TRUE
?>

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

Avertizare

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.

Example #3 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.

Nota: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. 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.

Nota:

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:

Example #4 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.
?>

Null Coalescing Operator

Further exists the "??" (or null coalescing) operator, available as of PHP 7.

Example #5 Assigning a default value

<?php
// Example usage for: Null Coalesce Operator
$action = $_POST['action'] ?? 'default';

// The above is identical to this if/else statement
if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else {
    $action = 'default';
}

?>
The expression (expr1) ?? (expr2) evaluates to expr2 if expr1 is NULL, and expr1 otherwise.

In particular, this operator does not emit a notice if the left-hand side value does not exist, just like isset(). This is especially useful on array keys.

Nota: Please note that the null coalescing operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $foo ?? $bar; in a return-by-reference function will therefore not work and a warning is issued.

Nota:

Please note that the null coalescing operator allows for simple nesting:

Example #6 Nesting null coalescing operator

<?php

$foo = null;
$bar = null;
$baz = 1;
$qux = 2;

echo $foo ?? $bar ?? $baz ?? $qux; // outputs 1

?>

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

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

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

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

?>

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

Avertizare

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

Nota:

The backtick operator is disabled when modul securizat is enabled or shell_exec() is disabled.

Nota:

Unlike some other languages, backticks have no special meaning 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.

Nota: The increment/decrement operators only affect numbers and strings. Arrays, objects and resources are not affected. 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 alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

Example #1 Arithmetic Operations on Character Variables

<?php
echo '== Alphabets ==' . PHP_EOL;
$s = 'W';
for ($n=0; $n<6; $n++) {
    echo ++$s . PHP_EOL;
}
// Digit characters behave differently
echo '== Digits ==' . PHP_EOL;
$d = 'A8';
for ($n=0; $n<6; $n++) {
    echo ++$d . PHP_EOL;
}
$d = 'A08';
for ($n=0; $n<6; $n++) {
    echo ++$d . PHP_EOL;
}
?>

Exemplul de mai sus va afi?a:

== Characters ==
X
Y
Z
AA
AB
AC
== Digits ==
A9
B0
B1
B2
B3
B4
A09
A10
A11
A12
A13
A14

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

Example #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 before the "or" operation occurs
// 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 before the "and" operation occurs
// Acts like: (($h = true) and false)
$h = true and false;

var_dump($g, $h);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

$a += $b; // Union of $a += $b is $a and $b
echo "Union of \$a += \$b: \n";
var_dump($a);
?>
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"
}
Union of $a += $b:
array(3) {
  'a' =>
  string(5) "apple"
  'b' =>
  string(6) "banana"
  'c' =>
  string(6) "cherry"
}

Elements of arrays are equal for the comparison if they have the same key and value.

Example #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:

Example #1 Using instanceof with classes

<?php
class MyClass
{
}

class NotMyClass
{
}
$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
?>

Exemplul de mai sus va afi?a:

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:

Example #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);
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)

To check if an object is not an instanceof a class, the logical not operator can be used.

Example #3 Using instanceof to check if object is not an instanceof a class

<?php
class MyClass
{
}

$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>

Exemplul de mai sus va afi?a:

bool(true)

Lastly, instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface:

Example #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);
?>

Exemplul de mai sus va afi?a:

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:

Example #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'
?>

Exemplul de mai sus va afi?a:

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

instanceof does not throw any error if the variable being tested is not an object, it simply returns FALSE. Constants, however, are not allowed.

Example #6 Using instanceof to test other variables

<?php
$a = 1;
$b = NULL;
$c = imagecreate(5, 5);
var_dump($a instanceof stdClass); // $a is an integer
var_dump($b instanceof stdClass); // $b is NULL
var_dump($c instanceof stdClass); // $c is a resource
var_dump(FALSE instanceof stdClass);
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(false)
bool(false)
PHP Fatal error:  instanceof expects an object instance, constant given

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:

Example #7 Avoiding classname lookups and fatal errors with instanceof in PHP 5.0

<?php
$d = 'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
?>

Exemplul de mai sus va afi?a:

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

Cuprins

  • 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
Informa?ii de referin?a despre limbaj


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

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

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

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.

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

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

Nota:

Mixing syntaxes in the same control block is not supported.

Avertizare

Any output (including whitespace) between a switch statement and the first case will result in a syntax error. For example, this is invalid:

<?php switch ($foo): ?>
    <?php case 1: ?>
    ...
<?php endswitch ?>

Whereas this is valid, as the trailing newline after the switch statement is considered part of the closing ?> and hence nothing is output between the switch and case:

<?php switch ($foo): ?>
<?php case 1: ?>
    ...
<?php endswitch ?>

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

elseif/else if
while
Control Structures


while

(PHP 4, PHP 5, PHP 7)

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

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

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;

It's a common thing to many users to iterate through 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 < count($people); ++$i) {
    $people[$i]['salt'] = mt_rand(000000, 999999);
}
?>

The above code can be slow, because the array size is fetched on every iteration. Since the size never changes, the loop be easily optimized by using an intermediate variable to store the size instead of repeatedly calling count():

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

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

do-while
foreach
Control Structures


foreach

(PHP 4, PHP 5, PHP 7)

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.

Nota:

In PHP 5, 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 in PHP 5, changing it within the loop may lead to unexpected behavior.

In PHP 7, foreach does not use the internal array pointer.

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

Avertizare

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset(). Otherwise you will experience the following behavior:

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)

// without an unset($value), $value is still a reference to the last item: $arr[3]

foreach ($arr as $key => $value) {
    // $arr[3] will be updated with each value from $arr...
    echo "{$key} => {$value} ";
    print_r($arr);
}
// ...until ultimately the second-to-last value is copied onto the last value

// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
?>

Before PHP 5.5.0, referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code works only as of PHP 5.5.0:

<?php
foreach (array(1, 2, 3, 4) as &$value) {
    $value = $value * 2;
}
?>

Nota:

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

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

Unpacking nested arrays with list()

(PHP 5 >= 5.5.0, PHP 7)

PHP 5.5 added the ability to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value.

For example:

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b)) {
    // $a contains the first element of the nested array,
    // and $b contains the second element.
    echo "A: $a; B: $b\n";
}
?>

Exemplul de mai sus va afi?a:

A: 1; B: 2
A: 3; B: 4

You can provide fewer elements in the list() than there are in the nested array, in which case the leftover array values will be ignored:

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a)) {
    // Note that there is no $b here.
    echo "$a\n";
}
?>

Exemplul de mai sus va afi?a:

1
3

A notice will be generated if there aren't enough array elements to fill the list():

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b, $c)) {
    echo "A: $a; B: $b; C: $c\n";
}
?>

Exemplul de mai sus va afi?a:

Notice: Undefined offset: 2 in example.php on line 7
A: 1; B: 2; C:

Notice: Undefined offset: 2 in example.php on line 7
A: 3; B: 4; C:

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | foreach does not use the internal array pointer anymore.
5.5.0 | Referencing of $value is supported for expressions. Formerly, only variables have been supported.
5.5.0 | Unpacking nested arrays with list() is supported.

for
break
Control Structures


break

(PHP 4, PHP 5, PHP 7)

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. The default value is 1, only the immediate enclosing structure is broken out of.

<?php
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

/* Using the optional argument. */

$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "At 5<br />\n";
        break 1;  /* Exit only the switch. */
    case 10:
        echo "At 10; quitting<br />\n";
        break 2;  /* Exit the switch and the while. */
    default:
        break;
    }
}
?>

Changelog for break
Versiune | Descriere
5.4.0 | break 0; is no longer valid. In previous versions it was interpreted the same as break 1;.
5.4.0 | Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument.

foreach
continue
Control Structures


continue

(PHP 4, PHP 5, PHP 7)

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.

Nota: In PHP the switch statement is considered a looping structure for the purposes of continue. continue behaves like break (when no arguments are passed). If a switch is inside a loop, continue 2 will continue with the next iteration of the outer loop.

continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. The default value is 1, thus skipping to the end of the current loop.

<?php
while (list($key, $value) = each($arr)) {
    if (!($key % 2)) { // skip even members
        continue;
    }
    do_something_odd($value);
}

$i = 0;
while ($i++ < 5) {
    echo "Outer<br />\n";
    while (1) {
        echo "Middle<br />\n";
        while (1) {
            echo "Inner<br />\n";
            continue 3;
        }
        echo "This never gets output.<br />\n";
    }
    echo "Neither does this.<br />\n";
}
?>

Omitting the semicolon after continue can lead to confusion. Here's an example of what you shouldn't do.

<?php
for ($i = 0; $i < 5; ++$i) {
    if ($i == 2)
        continue
    print "$i\n";
}
?>

One can expect the result to be:

0
1
3
4

but, in PHP versions below 5.4.0, 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.)

Nota:

As of PHP 5.4.0, the above example will raise an E_COMPILE_ERROR error.

Changelog for continue
Versiune | Descriere
5.4.0 | continue 0; is no longer valid. In previous versions it was interpreted the same as continue 1;.
5.4.0 | Removed the ability to pass in variables (e.g., $num = 2; continue $num;) as the numerical argument.

break
switch
Control Structures


switch

(PHP 4, PHP 5, PHP 7)

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.

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

Nota:

Note that switch/case does loose comparison.

Istoricul schimbarilor
Versiune | Descriere
7.0.0 | Multiple default cases will raise a E_COMPILE_ERROR error.

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:

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

Example #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 whose expression evaluates to 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 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, PHP 5, PHP 7)

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 three directives are recognized: the ticks directive (See below for more information on the ticks directive), the encoding directive (See below for more information on the encoding directive) and the strict_types directive (See for more information the strict section on the Function arguments page)

Versiune | Descriere
5.3.0 | Added encoding directive
7.0.0 | Added strict_types directive

As directives are handled as the file is being compiled, only literals may be given as directive values. Variables and constants cannot be used. To illustrate:

<?php
// This is valid:
declare(ticks=1);

// This is invalid:
const TICK_VALUE = 1;
declare(ticks=TICK_VALUE);
?>

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

Example #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);
}

?>

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

Example #3 Declaring an encoding for the script.

<?php
declare(encoding='ISO-8859-1');
// code here
?>

Precautie

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

See also zend.script_encoding.

switch
return
Control Structures


return

(PHP 4, PHP 5, PHP 7)

return returns program control to the calling module. Execution resumes at the expression following the called module's invocation.

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 also ends 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 included or required, then control is passed back to the calling file. Furthermore, if the current script file was included, 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.

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

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

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

(PHP 4, PHP 5, PHP 7)

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

(PHP 4, PHP 5, PHP 7)

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.

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

Example #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 include wrappers" are enabled in PHP, 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.

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

?>

Avertizare

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: include returns FALSE on failure and raises a warning. Successful includes, unless overridden by the included file, return 1. 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.

Example #4 Comparing return value of include

<?php
// won't work, evaluated as include(('vars.php') == TRUE), i.e. include('')
if (include('vars.php') == TRUE) {
    echo 'OK';
}

// works
if ((include 'vars.php') == TRUE) {
    echo 'OK';
}
?>

Example #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:

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

Nota: Deoarece aceasta este o construc?ie a limbajului ?i nu o func?ie, ea nu poate fi apelata utilizând func?ii de operare cu variabile .

See also require, require_once, include_once, get_included_files(), readfile(), virtual(), and include_path.

require
require_once
Control Structures


require_once

(PHP 4, PHP 5, PHP 7)

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

(PHP 4, PHP 5, PHP 7)

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, and include_once returns TRUE. As the name suggests, the file 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.

Nota:

With PHP 4, _once functionality differs with case-insensitive operating systems (like Windows) so for example:

Example #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, PHP 7)

What's the worse thing that could happen if you use goto?
Image courtesy of » xkcd

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.

Example #1 goto example

<?php
goto a;
echo 'Foo';

a:
echo 'Bar';
?>

Exemplul de mai sus va afi?a:

Bar

Example #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';
?>

Exemplul de mai sus va afi?a:

j hit 17

Example #3 This will not work

<?php
goto loop;
for($i=0,$j=50; $i<100; $i++) {
  while($j--) {
    loop:
  }
}
echo "$i = $i";
?>

Exemplul de mai sus va afi?a:

Fatal error: 'goto' into loop or switch statement is disallowed in
script on line 2

Nota:

The goto operator is available as of PHP 5.3.

include_once
Functions
Control Structures


Functions

Cuprins

  • User-defined functions
  • Function arguments
  • Returning values
  • Variable functions
  • Internal (built-in) functions
  • Anonymous functions
goto
User-defined functions
Informa?ii de referin?a despre limbaj


User-defined functions

A function may be defined using syntax such as the following:

Example #1 Pseudo code to demonstrate function uses

<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
    echo "Example function.\n";
    return $retval;
}
?>

Any valid PHP code may appear inside a function, even other functions and class definitions.

Function names follow the same rules as other labels in PHP. A valid function 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]*.

Sfat

Accesa?i de asemenea Ghidul de stabilire a denumirilor de catre utilizatori.

Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.

When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.

Example #2 Conditional functions

<?php

$makefoo = true;

/* We can't call foo() from here
   since it doesn't exist yet,
   but we can call bar() */

bar();

if ($makefoo) {
  function foo()
  {
    echo "I don't exist until program execution reaches me.\n";
  }
}

/* Now we can safely call foo()
   since $makefoo evaluated to true */

if ($makefoo) foo();

function bar()
{
  echo "I exist immediately upon program start.\n";
}

?>

Example #3 Functions within functions

<?php
function foo()
{
  function bar()
  {
    echo "I don't exist until foo() is called.\n";
  }
}

/* We can't call bar() yet
   since it doesn't exist. */

foo();

/* Now we can call bar(),
   foo()'s processing has
   made it accessible. */

bar();

?>

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.

Nota: Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.

Both variable number of arguments and default arguments are supported in functions. See also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.

It is possible to call recursive functions in PHP.

Example #4 Recursive functions

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

Nota: Recursive function/method calls with over 100-200 recursion levels can smash the stack and cause a termination of the current script. Especially, infinite recursion is considered a programming error.

Functions
Function arguments
Functions


Function arguments

Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right.

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are also supported.

Example #1 Passing arrays to functions

<?php
function takes_array($input)
{
    echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>

Passing arguments by reference

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition:

Example #2 Passing function parameters by reference

<?php
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>

Default argument values

A function may define C++-style default values for scalar arguments as follows:

Example #3 Use of default parameters in functions

<?php
function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>

Exemplul de mai sus va afi?a:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

PHP also allows the use of arrays and the special type NULL as default values, for example:

Example #4 Using non-scalar types as default values

<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
    $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
    return "Making a cup of ".join(", ", $types)." with $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
?>

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet:

Example #5 Incorrect usage of default function arguments

<?php
function makeyogurt($type = "acidophilus", $flavour)
{
    return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry");   // won't work as expected
?>

Exemplul de mai sus va afi?a:

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 .

Now, compare the above with this:

Example #6 Correct usage of default function arguments

<?php
function makeyogurt($flavour, $type = "acidophilus")
{
    return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry");   // works as expected
?>

Exemplul de mai sus va afi?a:

Making a bowl of acidophilus raspberry.

Nota: As of PHP 5, arguments that are passed by reference may have a default value.

Type declarations

Nota:

Type declarations were also known as type hints in PHP 5.

Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.

To specify a type declaration, the type name should be added before the parameter name. The declaration can be made to accept NULL values if the default value of the parameter is set to NULL.

Valid types

Type | Description | Minimum PHP version
Class/interface name | The parameter must be an instanceof the given class or interface name. | PHP 5.0.0
self | The parameter must be an instanceof the same class as the one the method is defined on. This can only be used on class and instance methods. | PHP 5.0.0
array | The parameter must be an array. | PHP 5.1.0
callable | The parameter must be a valid callable. | PHP 5.4.0
bool | The parameter must be a boolean value. | PHP 7.0.0
float | The parameter must be a floating point number. | PHP 7.0.0
int | The parameter must be an integer. | PHP 7.0.0
string | The parameter must be a string. | PHP 7.0.0
Avertizare

Aliases for the above scalar types are not supported. Instead, they are treated as class or interface names. For example, using boolean as a parameter or return type will require an argument or return value that is an instanceof the class or interface boolean, rather than of type bool:

<?php
 function test(boolean $param) {}
 test(true);
 ?>

Exemplul de mai sus va afi?a:

 Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given, called in - on line 1 and defined in -:1

Exemple

Example #7 Basic class type declaration

<?php
class C {}
class D extends C {}

// This doesn't extend C.
class E {}

function f(C $c) {
    echo get_class($c)."\n";
}

f(new C);
f(new D);
f(new E);
?>

Exemplul de mai sus va afi?a:

C
D

Fatal error: Uncaught TypeError: Argument 1 passed to f() must be an instance of C, instance of E given, called in - on line 14 and defined in -:8
Stack trace:
#0 -(14): f(Object(E))
#1 {main}
  thrown in - on line 8

Example #8 Basic interface type declaration

<?php
interface I { public function f(); }
class C implements I { public function f() {} }

// This doesn't implement I.
class E {}

function f(I $i) {
    echo get_class($i)."\n";
}

f(new C);
f(new E);
?>

Exemplul de mai sus va afi?a:

C

Fatal error: Uncaught TypeError: Argument 1 passed to f() must implement interface I, instance of E given, called in - on line 13 and defined in -:8
Stack trace:
#0 -(13): f(Object(E))
#1 {main}
  thrown in - on line 8

Example #9 Nullable type declaration

<?php
class C {}

function f(C $c = null) {
    var_dump($c);
}

f(new C);
f(null);
?>

Exemplul de mai sus va afi?a:

object(C)#1 (0) {
}
NULL

Strict typing

By default, PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string.

It is possible to enable strict mode on a per-file basis. In strict mode, only a variable of exact type of the type declaration will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float. Function calls from within internal functions will not be affected by the strict_types declaration.

To enable strict mode, the declare statement is used with the strict_types declaration:

Precautie

Enabling strict mode will also affect return type declarations.

Nota:

Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller's preference (weak typing) will be respected, and the value will be coerced.

Nota:

Strict typing is only defined for scalar type declarations, and as such, requires PHP 7.0.0 or later, as scalar type declarations were added in that version.

Example #10 Strict typing

<?php
declare(strict_types=1);

function sum(int $a, int $b) {
    return $a + $b;
}

var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
?>

Exemplul de mai sus va afi?a:

int(3)

Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 9 and defined in -:4
Stack trace:
#0 -(9): sum(1.5, 2.5)
#1 {main}
  thrown in - on line 4

Example #11 Weak typing

<?php
function sum(int $a, int $b) {
    return $a + $b;
}

var_dump(sum(1, 2));

// These will be coerced to integers: note the output below!
var_dump(sum(1.5, 2.5));
?>

Exemplul de mai sus va afi?a:

int(3)
int(3)

Example #12 Catching TypeError

<?php
declare(strict_types=1);

function sum(int $a, int $b) {
    return $a + $b;
}

try {
    var_dump(sum(1, 2));
    var_dump(sum(1.5, 2.5));
} catch (TypeError $e) {
    echo 'Error: '.$e->getMessage();
}
?>

Exemplul de mai sus va afi?a:

int(3)
Error: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 10

Variable-length argument lists

PHP has support for variable-length argument lists in user-defined functions. This is implemented using the ... token in PHP 5.6 and later, and using the func_num_args(), func_get_arg(), and func_get_args() functions in PHP 5.5 and earlier.

... in PHP 5.6+

In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:

Example #13 Using ... to access variable arguments

<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
?>

Exemplul de mai sus va afi?a:

10

You can also use ... when calling functions to unpack an array or Traversable variable or literal into the argument list:

Example #14 Using ... to provide arguments

<?php
function add($a, $b) {
    return $a + $b;
}

echo add(...[1, 2])."\n";

$a = [1, 2];
echo add(...$a);
?>

Exemplul de mai sus va afi?a:

3
3

You may specify normal positional arguments before the ... token. In this case, only the trailing arguments that don't match a positional argument will be added to the array generated by ....

It is also possible to add a type hint before the ... token. If this is present, then all arguments captured by ... must be objects of the hinted class.

Example #15 Type hinted variable arguments

<?php
function total_intervals($unit, DateInterval ...$intervals) {
    $time = 0;
    foreach ($intervals as $interval) {
        $time += $interval->$unit;
    }
    return $time;
}

$a = new DateInterval('P1D');
$b = new DateInterval('P2D');
echo total_intervals('d', $a, $b).' days';

// This will fail, since null isn't a DateInterval object.
echo total_intervals('d', null);
?>

Exemplul de mai sus va afi?a:

3 days
Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2

Finally, you may also pass variable arguments by reference by prefixing the ... with an ampersand (&).

Older versions of PHP

No special syntax is required to note that a function is variadic; however access to the function's arguments must use func_num_args(), func_get_arg() and func_get_args().

The first example above would be implemented as follows in PHP 5.5 and earlier:

Example #16 Accessing variable arguments in PHP 5.5 and earlier

<?php
function sum() {
    $acc = 0;
    foreach (func_get_args() as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
?>

Exemplul de mai sus va afi?a:

10

User-defined functions
Returning values
Functions


Returning values

Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called. See return for more information.

Nota:

If the return is omitted the value NULL will be returned.

Use of return

Example #1 Use of return

<?php
function square($num)
{
    return $num * $num;
}
echo square(4);   // outputs '16'.
?>

A function can not return multiple values, but similar results can be obtained by returning an array.

Example #2 Returning an array to get multiple values

<?php
function small_numbers()
{
    return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?>

To return a reference from a function, use the reference operator & in both the function declaration and when assigning the returned value to a variable:

Example #3 Returning a reference from a function

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

$newref =& returns_reference();
?>

For more information on references, please check out References Explained.

Return type declarations

PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of the value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.

Strict typing also has an effect on return type declarations. In the default weak mode, returned values will be coerced to the correct type if they are not already of that type. In strong mode, the returned value must be of the correct type, otherwise a TypeError will be thrown.

Nota:

When overriding a parent method, the child's method must match any return type declaration on the parent. If the parent doesn't define a return type, then the child method may do so.

Exemple

Example #4 Basic return type declaration

<?php
function sum($a, $b): float {
    return $a + $b;
}

// Note that a float will be returned.
var_dump(sum(1, 2));
?>

Exemplul de mai sus va afi?a:

float(3)

Example #5 Strict mode in action

<?php
declare(strict_types=1);

function sum($a, $b): int {
    return $a + $b;
}

var_dump(sum(1, 2));
var_dump(sum(1, 2.5));
?>

Exemplul de mai sus va afi?a:

int(3)

Fatal error: Uncaught TypeError: Return value of sum() must be of the type integer, float returned in - on line 5 in -:5
Stack trace:
#0 -(9): sum(1, 2.5)
#1 {main}
  thrown in - on line 5

Example #6 Returning an object

<?php
class C {}

function getC(): C {
    return new C;
}

var_dump(getC());
?>

Exemplul de mai sus va afi?a:

object(C)#1 (0) {
}
Function arguments
Variable functions
Functions


Variable functions

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

Variable functions won't work with language constructs such as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

Example #1 Variable function example

<?php
function foo() {
    echo "In foo()<br />\n";
}

function bar($arg = '')
{
    echo "In bar(); argument was '$arg'.<br />\n";
}

// This is a wrapper function around echo
function echoit($string)
{
    echo $string;
}

$func = 'foo';
$func();        // This calls foo()

$func = 'bar';
$func('test');  // This calls bar()

$func = 'echoit';
$func('test');  // This calls echoit()
?>

Object methods can also be called with the variable functions syntax.

Example #2 Variable method example

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }

    function Bar()
    {
        echo "This is Bar";
    }
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

?>

When calling static methods, the function call is stronger than the static property operator:

Example #3 Variable method example with static properties

<?php
class Foo
{
    static $variable = 'static property';
    static function Variable()
    {
        echo 'Method Variable called';
    }
}

echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope.
$variable = "Variable";
Foo::$variable();  // This calls $foo->Variable() reading $variable in this scope.

?>

As of PHP 5.4.0, you can call any callable stored in a variable.

Example #4 Complex callables

<?php
class Foo
{
    static function bar()
    {
        echo "bar\n";
    }
    function baz()
    {
        echo "baz\n";
    }
}

$func = array("Foo", "bar");
$func(); // prints "bar"
$func = array(new Foo, "baz");
$func(); // prints "baz"
$func = "Foo::bar";
$func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error
?>

See also is_callable(), call_user_func(), variable variables and function_exists().

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | 'ClassName::methodName' is allowed as variable function.
5.4.0 | Arrays, which are valid callables, are allowed as variable functions.

Returning values
Internal (built-in) functions
Functions


Internal (built-in) functions

PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in, otherwise fatal "undefined function" errors will appear. For example, to use image functions such as imagecreatetruecolor(), PHP must be compiled with GD support. Or, to use mysql_connect(), PHP must be compiled with MySQL support. There are many core functions that are included in every version of PHP, such as the string and variable functions. A call to phpinfo() or get_loaded_extensions() will show which extensions are loaded into PHP. Also note that many extensions are enabled by default and that the PHP manual is split up by extension. See the configuration, installation, and individual extension chapters, for information on how to set up PHP.

Reading and understanding a function's prototype is explained within the manual section titled how to read a function definition. It's important to realize what a function returns or if a function works directly on a passed in value. For example, str_replace() will return the modified string while usort() works on the actual passed in variable itself. Each manual page also has specific information for each function like information on function parameters, behavior changes, return values for both success and failure, and availability information. Knowing these important (yet often subtle) differences is crucial for writing correct PHP code.

Nota: If the parameters given to a function are not what it expects, such as passing an array where a string is expected, the return value of the function is undefined. In this case it will likely return NULL but this is just a convention, and cannot be relied upon.

See also function_exists(), the function reference, get_extension_funcs(), and dl().

Variable functions
Anonymous functions
Functions


Anonymous functions

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

Anonymous functions are implemented using the Closure class.

Example #1 Anonymous function example

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
?>

Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon:

Example #2 Anonymous function variable assignment example

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. From PHP 7.1, these variables may not include superglobals, $this, or variables with the same name as a parameter.

Example #3 Inheriting variables from the parent scope

<?php
$message = 'hello';

// No "use"
$example = function () {
    var_dump($message);
};
$example();

// Inherit $message
$example = function () use ($message) {
    var_dump($message);
};
$example();

// Inherited variable's value is from when the function
// is defined, not when called
$message = 'world';
$example();

// Reset message
$message = 'hello';

// Inherit by-reference
$example = function () use (&$message) {
    var_dump($message);
};
$example();

// The changed value in the parent scope
// is reflected inside the function call
$message = 'world';
$example();

// Closures can also accept regular arguments
$example = function ($arg) use ($message) {
    var_dump($arg . ' ' . $message);
};
$example("hello");
?>

Exemplul de mai sus va afi?a ceva similar cu:

Notice: Undefined variable: message in /example.php on line 6
NULL
string(5) "hello"
string(5) "hello"
string(5) "hello"
string(5) "world"
string(11) "hello world"

Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example:

Example #4 Closures and scoping

<?php
// A basic shopping cart which contains a list of added products
// and the quantity of each product. Includes a method which
// calculates the total price of the items in the cart using a
// closure as a callback.
class Cart
{
    const PRICE_BUTTER  = 1.00;
    const PRICE_MILK    = 3.00;
    const PRICE_EGGS    = 6.95;

    protected $products = array();

    public function add($product, $quantity)
    {
        $this->products[$product] = $quantity;
    }

    public function getQuantity($product)
    {
        return isset($this->products[$product]) ? $this->products[$product] :
               FALSE;
    }

    public function getTotal($tax)
    {
        $total = 0.00;

        $callback =
            function ($quantity, $product) use ($tax, &$total)
            {
                $pricePerItem = constant(__CLASS__ . "::PRICE_" .
                    strtoupper($product));
                $total += ($pricePerItem * $quantity) * ($tax + 1.0);
            };

        array_walk($this->products, $callback);
        return round($total, 2);
    }
}

$my_cart = new Cart;

// Add some items to the cart
$my_cart->add('butter', 1);
$my_cart->add('milk', 3);
$my_cart->add('eggs', 6);

// Print the total with a 5% sales tax.
print $my_cart->getTotal(0.05) . "\n";
// The result is 54.29
?>

Example #5 Automatic binding of $this

<?php

class Test
{
    public function testing()
    {
        return function() {
            var_dump($this);
        };
    }
}

$object = new Test;
$function = $object->testing();
$function();

?>

Exemplul de mai sus va afi?a:

object(Test)#1 (0) {
}

Exemplul de mai sus va afi?a în PHP 5.3:

Notice: Undefined variable: this in script.php on line 8
NULL

As of PHP 5.4.0, when declared in the context of a class, the current class is automatically bound to it, making $this available inside of the function's scope. If this automatic binding of the current class is not wanted, then static anonymous functions may be used instead.

Static anonymous functions

As of PHP 5.4, anonymous functions may be declared statically. This prevents them from having the current class automatically bound to them. Objects may also not be bound to them at runtime.

Example #6 Attempting to use $this inside a static anonymous function

<?php

class Foo
{
    function __construct()
    {
        $func = static function() {
            var_dump($this);
        };
        $func();
    }
};
new Foo();

?>

Exemplul de mai sus va afi?a:

Notice: Undefined variable: this in %s on line %d
NULL

Example #7 Attempting to bind an object to a static anonymous function

<?php

$func = static function() {
    // function body
};
$func = $func->bindTo(new StdClass);
$func();

?>

Exemplul de mai sus va afi?a:

Warning: Cannot bind an instance to a static closure in %s on line %d

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Anonymous functions may not close over superglobals, $this, or any variable with the same name as a parameter.
5.4.0 | Anonymous functions may use $this, as well as be declared statically.
5.3.0 | Anonymous functions become available.

Note

Nota: It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within a closure.

Internal (built-in) functions
Clase ?i Obiecte
Functions


Clase ?i Obiecte

Cuprins

  • Introducere
  • The Basics
  • Properties
  • Class Constants
  • Autoîncarcarea claselor
  • Constructori ?i Destructori
  • Vizibilitatea
  • Object Inheritance
  • Scope Resolution Operator (::)
  • Static Keyword
  • Clase Abstracte
  • Object Interfaces
  • Traits
  • Anonymous classes
  • Overloading
  • Object Iteration
  • Magic Methods
  • Final Keyword
  • Object Cloning
  • Comparing Objects
  • Indicarea Tipului
  • Late Static Bindings
  • Objects and references
  • Object Serialization
  • OOP Changelog
Anonymous functions
Introducere
Informa?ii de referin?a despre limbaj


Introducere

Începând cu PHP 5, modelul de obiecte a fost rescris pentru a mari performan?a ?i a introduce facilita?i noi. Aceasta a fost o schimbare majora dupa PHP 4. PHP 5 acum are un model de obiecte deplin.

Printre facilita?ile noi în PHP 5 sunt clase ?i metode de tip visibility, abstract ?i final, metode magice ?i interfe?e adi?ionale, clonarea ?i typehinting.

PHP trateaza obiectele la fel ca pe ni?te referin?e sau handle-uri, ceea ce înseamna ca fiecare variabila con?ine o referin?a la obiect ?i nu o copie a întregului obiect. Vede?i Obiecte ?i referin?e

Sfat

Accesa?i de asemenea Ghidul de stabilire a denumirilor de catre utilizatori.

Clase ?i Obiecte
The Basics
Clase ?i Obiecte


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, provided it is 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").

Example #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). As of PHP 7.0.0 calling a non-static method statically from an incompatible context results in $this being undefined inside the method. Calling a non-static method statically from an incompatible context has been deprecated as of PHP 5.6.0. As of PHP 7.0.0 calling a non-static method statically has been generally deprecated (even if called from a compatible context). Before PHP 5.6.0 such calls already triggered a strict notice.

Example #2 Some examples of the $this pseudo-variable

We're assuming that error_reporting is disabled for this example; otherwise the following code would trigger deprecated and strict notices, respectively, depending on the PHP version.

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

Exemplul de mai sus va afi?a în PHP 5:

$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.

Exemplul de mai sus va afi?a în PHP 7:

$this is defined (A)
$this is not defined.
$this is not defined.
$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.

Example #3 Creating an instance

<?php
$instance = new SimpleClass();

// This can also be done with a variable:
$className = 'SimpleClass';
$instance = new $className(); // new SimpleClass()
?>

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.

Example #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);
?>

Exemplul de mai sus va afi?a:

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:

Example #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);
?>

Exemplul de mai sus va afi?a:

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

PHP 5.4.0 introduced the possibility to access a member of a newly created object in a single expression:

Example #6 Access member of newly created object

<?php
echo (new DateTime())->format('Y');
?>

Exemplul de mai sus va afi?a ceva similar cu:

2016

Properties and methods

Class properties and methods live in separate "namespaces", so it is possible to have a property and a method with the same name. Referring to both a property and a method has the same notation, and whether a property will be accessed or a method will be called, solely depends on the context, i.e. whether the usage is a variable access or a function call.

Example #7 Property access vs. method call

class Foo
{
    public $bar = 'property';

    public function bar() {
        return 'method';
    }
}

$obj = new Foo();
echo $obj->bar, PHP_EOL, $obj->bar(), PHP_EOL;

Exemplul de mai sus va afi?a:

property
method

That means that calling an anonymous function which has been assigned to a property is not directly possible. Instead the property has to be assigned to a variable first, for instance. As of PHP 7.0.0 it is possible to call such a property directly by enclosing it in parentheses.

Example #8 Calling an anonymous function stored in a property

class Foo
{
    public $bar;

    public function __construct() {
        $this->bar = function() {
            return 42;
        };
    }
}

$obj = new Foo();

// as of PHP 5.3.0:
$func = $obj->bar;
echo $func(), PHP_EOL;

// alternatively, as of PHP 7.0.0:
echo ($obj->bar)(), PHP_EOL;

Exemplul de mai sus va afi?a:

42

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.

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

Exemplul de mai sus va afi?a:

Extending class
a default value

::class

Since PHP 5.5, the class keyword is also used for class name resolution. You can get a string containing the fully qualified name of the ClassName class by using ClassName::class. This is particularly useful with namespaced classes.

Example #10 Class name resolution

<?php
namespace NS {
    class ClassName {
    }

    echo ClassName::class;
}
?>

Exemplul de mai sus va afi?a:

NS\ClassName

Nota:

The class name resolution using ::class is a compile time transformation. That means at the time the class name string is created no autoloading has happened yet. As a consequence, class names are expanded even if the class does not exist. No error is issued in that case.

Introducere
Properties
Clase ?i Obiecte


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 Vizibilitatea for more information on the meanings of public, protected, and private.

Nota:

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 non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property. See Static Keyword for more information on the difference between static and non-static properties.

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

Example #1 property declarations

<?php
class SimpleClass
{
   // valid as of PHP 5.6.0:
   public $var1 = 'hello ' . 'world';
   // valid as of PHP 5.3.0:
   public $var2 = <<<EOD
hello world
EOD;
   // valid as of PHP 5.6.0:
   public $var3 = 1+2;
   // invalid property declarations:
   public $var4 = self::myStaticMethod();
   public $var5 = $myVar;

   // valid property declarations:
   public $var6 = myConstant;
   public $var7 = array(true, false);

   // valid as of PHP 5.3.0:
   public $var8 = <<<'EOD'
hello world
EOD;
}
?>

Nota:

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

As of PHP 5.3.0 heredocs and nowdocs can be used in any static data context, including property declarations.

Example #2 Example of using a nowdoc to initialize a property

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

Nota:

Nowdoc and Heredoc support was added in PHP 5.3.0.

The Basics
Class Constants
Clase ?i Obiecte


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 default visibility of class constants is public.

The value must be a constant expression, not (for example) a variable, a property, 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).

Note that class constants are allocated once per class, and not for each class instance.

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

Example #2 Static data example

<?php
class foo {
    // As of PHP 5.3.0
    const BAR = <<<'EOT'
bar
EOT;
    // As of PHP 5.3.0
    const BAZ = <<<EOT
baz
EOT;
}
?>

Nota:

Support for initializing constants with Heredoc and Nowdoc syntax was added in PHP 5.3.0.

The special ::class constant are available as of PHP 5.5.0, and allows for fully qualified class name resolution at compile, this is useful for namespaced classes:

Example #3 Namespaced ::class example

<?php
namespace foo {
    class bar {
    }

    echo bar::class; // foo\bar
}
?>

Example #4 Constant expression example

<?php
const ONE = 1;

class foo {
    // As of PHP 5.6.0
    const TWO = ONE * 2;
    const THREE = ONE + self::TWO;
    const SENTENCE = 'The value of THREE is '.self::THREE;
}
?>

It is possible to provide a scalar expression involving numeric and string literals and/or constants in context of a class constant.

Nota:

Constant expression support was added in PHP 5.6.0.

Example #5 Class constant visibility modifiers

<?php
class Foo {
    // As of PHP 7.1.0
    public const BAR = 'bar';
    private const BAZ = 'baz';
}
echo Foo::BAR, PHP_EOL;
echo Foo::BAZ, PHP_EOL;
?>

Output of the above example in PHP 7.1:

bar

Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …

Nota:

As of PHP 7.1.0 visibility modifiers are allowed for class constants.

Properties
Autoîncarcarea claselor
Clase ?i Obiecte


Autoîncarcarea claselor

Mul?i programatori care scriu aplica?ii orientate pe obiecte creaza câte un fi?ier PHP pentru fiecare clasa pe care o definesc. O problema delicata era lista mare de fi?iere ce trebuiau incluse la începutul fiecarui script.

În PHP 5, acest lucru nu mai este necesar. Func?ia spl_autoload_register() înregistreaza orice numar de autoîncarcatoare, permi?ând claselor ?i interfe?elor sa fie încarcate automat în caz ca nu sunt înca definite. Înregistrând autoîncarcatoarele, PHP i se ofera o ultima ?ansa de a încarca clasa sau interfa?a înainte de a e?ua cu eroare.

Sfat

Cu toate ca ?i func?ia __autoload() poate fi utilizata pentru autoîncarcarea claselor ?i interfe?elor, este preferabila utilizarea func?iei spl_autoload_register(). Aceasta reprezinta o alternativa mai flexibila (permi?ând specificarea în aplica?ie a oricarui numar de autoîncarcatoare, ca de exemplu în biblioteci ale ter?ilor). Din acest motiv utilizarea __autoload() nu este recomandata ?i poate fi considerata învechita sau chiar eliminata în viitor.

Nota:

Înainte de PHP 5.3, excep?iile aruncate în fun?ia __autoload() nu puteau fi captate într-un bloc catch rezultând astfel o eroare fatala. Începând cu PHP 5.3 aceasta este posibil daca clasa unei excep?ii personalizate este definita la momentul generarii excep?iei personalizate. Func?ia __autoload() poate fi folosita pentru a încarca recursiv clasa excep?iei personalizate.

Nota:

Aceasta func?ie speciala nu este disponibila daca folosi?i PHP în mod CLI interactiv.

Nota:

Daca denumirea clasei este utilizata de ex. în call_user_func(), atunci ea poate con?ine caractere periculoase, cum ar fi ../. Nu este recomandat sa utiliza?i datele introduse de utilizator în asemenea func?ii, sau, cel pu?in, sa verifica?i ce s-a introdus în __autoload().

Example #1 Exemplu cu autoîncarcare

Acest exemplu încearca sa încarce clasele MyClass1 ?i MyClass2 din fi?ierele MyClass1.php ?i MyClass2.php.

<?php
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$obj  = new MyClass1();
$obj2 = new MyClass2();
?>

Example #2 Un alt exemplu Autoload

Acest exemplu încearca sa încarce interfa?a ITest.

<?php

spl_autoload_register(function ($name) {
    var_dump($name);
});

class Foo implements ITest {
}

/*
string(5) "ITest"

Fatal error: Interface 'ITest' not found in ...
*/
?>

Example #3 Autoîncarcarea cu tratarea excep?iilor pentru 5.3.0+

Acest exemplu arunca o excep?ie ?i demonstreaza cum se capteaza cu try/catch.

<?php
spl_autoload_register(function ($name) {
    echo "Vreau sa încarc $name.\n";
    throw new Exception("Nu pot încarca $name.");
});

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

Exemplul de mai sus va afi?a:

Vreau sa încarc NonLoadableClass.
Nu pot încarca NonLoadableClass.

Example #4 Autoîncarcarea cu tratarea excep?iilor pentru 5.3.0+ - Fara excep?ie personalizata

Acest exemplu atunca o excep?ie personalizata care nu a fost încarcata înca.

<?php
spl_autoload_register(function ($name) {
    echo "Vreau sa încarc $name.\n";
    throw new MissingException("Nu pot încarca $name.");
});

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

Exemplul de mai sus va afi?a:

Vreau sa încarc NonLoadableClass.
Nu pot încarca  MissingException.

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

A se vedea ?i

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

Class Constants
Constructori ?i Destructori
Clase ?i Obiecte


Constructori ?i Destructori

Constructor

void __construct ([ mixed $args = "" [, $... ]] )

PHP 5 permite programatorilor sa defineasca constructori pentru clase. Clasele care au definit un constructor vor apela aceasta metoda la fiecare obiect nou creat, pentru ca acesta (obiectul) sa fie utilizabil pentru ini?ializare înante de a fi folosit.

Nota: Constructorul-parinte nu este apelat implicit daca clasa-fiica define?te un constructor. Pentru a apela un constructor-parinte, este necesar de a apela parent::__construct() din cadrul constructorului-fiu. Daca clasa-fiica nu define?te un constructor, atunci acesta poate fi mo?tenit de la clasa-parinte la fel ca o metoda normala a clasei (daca aceasta nu a fost declarata ca privata).

Example #1 utilizarea noilor constructori unifica?i

<?php
class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}

class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}

class OtherSubClass extends BaseClass {
    // inherits BaseClass's constructor
}

// In BaseClass constructor
$obj = new BaseClass();

// In BaseClass constructor
// In SubClass constructor
$obj = new SubClass();

// In BaseClass constructor
$obj = new OtherSubClass();
?>

Pentru compatibilitate cu PHP 3 ?i 4, daca PHP nu poate gasi func?ia __construct() pentru o clasa data, ?i aceasta func?ie nu a fost mo?tenita de la clasa parinte, va fi cautata func?ia constructor de stil vechi, cu numele clasei. Drept urmare, singurul caz care va duce la probleme de compatibilitate este daca clasa a avut o metoda __construct() folosita cu alt scop semantic.

Avertizare

Constructorii de stil vechi sunt ÎNVECHI?I în PHP 7.0 ?i vor fi elimina?i într-o versiune ulterioara. Trebuie întotdeauna sa utiliza?i __construct() în coduri-sursa noi.

Spre deosebire de alte metode, PHP nu va genera un mesaj de eroare de nivel E_STRICT atunci când __construct() este suprascrisa cu al?i parametri decât cei ai metodei __construct() din clasa-parinte.

Începând cu PHP 5.3.3, metodele cu acela?i nume ca ?i ultimul element al unei clase din spa?iul de nume nu vor mai fi tratate ca constructor. Aceasta schimbare nu afecteaza clasele fara spa?ii de nume.

Example #2 Constructori în clasele cu spa?ii de nume

<?php
namespace Foo;
class Bar {
    public function Bar() {
        // tratata ca constructor în PHP 5.3.0-5.3.2
        // tratata ca o metoda obi?nuita începând cu PHP 5.3.3
    }
}
?>

Destructori

void __destruct ( void )

PHP 5 introduce un concept de distrugere a unui obiect similar cu cel regasit în alte limbaje de programare orientate pe obiecte (C++). Metoda de distrugere va fi apelata imediat ce nu mai sunt careva referin?e catre un anumit obiect sau în orice ordine în timpul secven?ei de deconectare.

Example #3 Exemplu destructor

<?php
class ClassaCuDestructor {
   function __construct() {
       print "Sunt în constructor.\n";
       $this->name = "ClassaCuDestructor";
   }

   function __destruct() {
       print "Distrug " . $this->name . "\n";
   }
}

$obj = new ClassaCuDestructor();
?>

La fel ca la constructori, destructorii-parinti nu vor fi apela?i implicit. Pentru a apela destructorul-parinte trebuie sa apela?i explicit parent::__destruct() în destructorul descendent. De asemenea, ca ?i în cazul constructorilor, o clasa-fiica poate sa mo?teneasca destructorul parintelui daca ea nu-?i implementeaza destructorul propriu.

Destructorul este apelat chiar daca scriptul este terminat cu apelul la func?ia exit(). Apelând exit() într-un destructor va preveni apelarea tuturor rutinelor de terminare din scriptul respectiv.

Nota:

Destructorii apela?i la momentul terminarii execu?iei scriptului au antetele HTTP trimise deja. Directorul de lucru în timpul fazei de deconectare a scriptului poate sa difere în cazul anumitor SAPI-uri (de ex. Apache).

Nota:

Încercarea de a arunca o excep?ie dintr-un destructor (apelat la momentul terminarii execu?iei scriptului) va cauza o eroare fatala.

Autoîncarcarea claselor
Vizibilitatea
Clase ?i Obiecte


Vizibilitatea

Vizibilitatea unei propieta?i sau a unei metode poate fi definita prefixând declara?ia cu unul din cuvintele cheie: public, protected sau private. Membrele claselor (proprieta?i sau metode) declarate public pot fi accesate oriunde. Membrele declarate protected pot fi accesate doar în interiorul clasei, precum ?i de clasele mo?tenite. Membrele declarate private pot fi accesate doar de clasa care le define?te.

Vizibilitatea proprieta?ilor

Proprieta?ile unei clase trebuie definite ca public, private, sau protected. Daca sunt declarate utilizând var, proprietatea va fi definita ca publica.

Example #1 Declarare proprieta?ilor

<?php
/**
 * Definire ClassaMea
 */
class ClassaMea
{
    public $membru_public = 'Eu sunt: Public';
    protected $membru_protected = 'Eu sunt: Protected';
    private $membru_private = 'Eu sunt: Private';

    function afiseazaBunaZiua()
    {
        echo $this->membru_public . ", ";
        echo $this->membru_protected . ", ";
        echo $this->membru_private;
    }
}

$obj = new ClassaMea();
echo $obj->membru_public;    // Func?ioneaza
echo $obj->membru_protected; // Eroare fatala
echo $obj->membru_private;   // Eroare fatala
$obj->afiseazaBunaZiua();    // Afi?eaza Eu sunt: Public, Eu sunt: Protected, Eu sunt: Private

/**
 * Define ClassaMea2
 */
class ClassaMea2 extends ClassaMea
{
    // Putem redeclara metodele publice ?i protected, dar nu ?i pe cele private
    protected $membru_protected = 'Eu sunt: Protected2';

    function afiseazaBunaZiua()
    {
        echo $this->membru_public . ",";
        echo $this->membru_protected;
        echo $this->membru_private;
    }
}

$obj2 = new ClassaMea2();
echo $obj->membru_public;     // Func?ioneaza
echo $obj2->membru_protected; // Eroare fatala
echo $obj2->membru_private;   // Nedefinit
$obj2->afiseazaBunaZiua();    // Afi?eaza Eu sunt: Public, Eu sunt: Protected2

?>

Nota: Metoda PHP 4 de a declara variabile folosind cuvântul cheie var este înca sus?inuta din motive de compatibilitate (fiind sinonim cuvântului cheie public). În PHP 5 înainte de 5.1.3, utilizarea sa va emite o avertizare de tip E_STRICT.

Vizibilitatea metodelor

Metodele claselor pot fi definite ca public, private, sau protected. Metodele declarate fara un cuvânt-cheie de vizibilitate sunt definite ca publice.

Example #2 Declara?ie metode

<?php
/**
 * Define?te MyClass
 */
class MyClass
{
    // Declara un constructor public
    public function __construct() { }

    // Declara o metoda publica
    public function MyPublic() { }

    // Declara o metoda protected
    protected function MyProtected() { }

    // Declara o metoda private
    private function MyPrivate() { }

    // Aceasta este public
    function Foo()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate();
    }
}

$myclass = new MyClass;
$myclass->MyPublic(); // Func?ioneaza
$myclass->MyProtected(); // Eroare fatala
$myclass->MyPrivate(); // Eroare fatala
$myclass->Foo(); // Cele Public, Protected ?i Private func?ioneaza

/**
 * Define?te MyClass2
 */
class MyClass2 extends MyClass
{
    // Aceasta este public
    function Foo2()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate(); // Eroare fatala
    }
}

$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Func?ioneaza
$myclass2->Foo2(); // Public ?i Protected func?ioneaza, dar nu ?i 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
?>

Vizibilitatea din cadrul altor obiecte

Obiectele de acela?i tip vor avea acces reciproc la membrele private ?i protejate, cu toate ca nu reprezinta aceea?i instan?a. Aceasta se întâmpla din cauza ca detaliile specifice de implementare se cunosc deja în interiorul acestor obiecte.

Example #3 Accesarea membrelor private ale unui obiect de acela?i tip

<?php
class Test
{
    private $foo;

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

    private function bar()
    {
        echo 'S-a accesat metoda privata.';
    }

    public function baz(Test $other)
    {
        // Putem modifica proprietatea privata:
        $other->foo = 'salut';
        var_dump($other->foo);

        // Putem de asemenea apela metoda privata:
        $other->bar();
    }
}

$test = new Test('test');

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

Exemplul de mai sus va afi?a:

string(5) "salut"
S-a accesat metoda privata.
Constructori ?i Destructori
Object Inheritance
Clase ?i Obiecte


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.

Nota:

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

Example #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'

?>
Vizibilitatea
Scope Resolution Operator (::)
Clase ?i Obiecte


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!

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

Example #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';
$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.

Example #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
Clase ?i Obiecte


Static Keyword

Sfat

This page describes the use of the static keyword to define static methods and properties. static can also be used to define static variables and for late static bindings. Please refer to those pages for information on those meanings of static.

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot 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.

Static methods

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.

Precautie

In PHP 5, calling non-static methods statically generates an E_STRICT level warning.

Avertizare

In PHP 7, calling non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. Support for calling non-static methods statically may be removed in the future.

Example #1 Static method example

<?php
class Foo {
    public static function aStaticMethod() {
        // ...
    }
}

Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>

Static properties

Static properties cannot be accessed through the object using the arrow operator ->.

Like any other PHP static variable, static properties may only be initialized using a literal or constant before PHP 5.6; expressions are not allowed. In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self, parent and static).

Example #2 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";
?>
Scope Resolution Operator (::)
Clase Abstracte
Clase ?i Obiecte


Clase Abstracte

PHP 5 introduce clase ?i metode abstracte. Clasele definite ca abstracte nu pot fi instan?iate ?i orice clasa care con?ine cel pu?in o metoda abstracta trebuie sa fie ?i ea abstracta. Metodele abstracte declara doar semnatura unei metode ?i nu pot defini o implementare concreta.

La mo?tenirea dintr-o clasa abstracta, toate metodele abstracte din parinte trebuie implementate; în plus, aceste metode trebuie definite cu o vizibilitate identica (sau mai pu?in restrictiva). De exemplu, daca metoda este definita 'protected', implementarea concreta trebuie sa defineasca func?ia 'protected' sau 'public', dar nu 'private'. În plus, semnaturile metodelor trebuie sa corespunda una alteia, adica sugestia tipului ?i numarul argumentelor necesare trebuie sa fie acelea?i. De exemplu, daca clasa-fiica define?te un argument op?ional, în timp ce semnatura metodei abstracte nu define?te, atunci nu este nici un conflict în semnatura. Aceasta la fel se aplica ?i la constructori începând cu PHP 5.4. Înainte de 5.4 semnaturile constructorilor puteau sa difere.

Example #1 Exemplu de clasa abstracta

<?php
abstract class AbstractClass
{
    // For?eaza implementarea în copii a urmatoarelor metode
    abstract protected function getValue();
    abstract protected function prefixValue($prefix);

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

Exemplul de mai sus va afi?a:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

Example #2 Exemplu cu clasa abstracta

<?php
abstract class AbstractClass
{
    // Metoda noastra abstracta trebuie doar sa defineasca argumentele necesare
    abstract protected function prefixName($name);

}

class ConcreteClass extends AbstractClass
{

    // Clasa noastra fiica poate defini argumente op?ionale care nu sunt prezente în semnatura parintelui
    public function prefixName($name, $separator = ".") {
        if ($name == "Pacman") {
            $prefix = "Mr";
        } elseif ($name == "Pacwoman") {
            $prefix = "Mrs";
        } else {
            $prefix = "";
        }
        return "{$prefix}{$separator} {$name}";
    }
}

$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "\n";
echo $class->prefixName("Pacwoman"), "\n";
?>

Exemplul de mai sus va afi?a:

Mr. Pacman
Mrs. Pacwoman

Codul vechi care nu are nici o clasa sau func?ie definita de utilizator cu numele 'abstract' ar trebui sa func?ioneze fara modificari.

Static Keyword
Object Interfaces
Clase ?i Obiecte


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 in the same way as a class, but with the interface keyword replacing the class keyword and 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.

Nota:

Prior to PHP 5.3.9, a class could not implement two interfaces that specified a method with the same name, since it would cause ambiguity. More recent versions of PHP allow this as long as the duplicate methods have the same signature.

Nota:

Interfaces can be extended like classes using the extends operator.

Nota:

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

Constants

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

Exemple

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

Example #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)
    {
    }
}
?>

Example #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()
    {
    }
}
?>

Example #4 Interfaces with constants

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

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

// This will however not work because it's 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.

Clase Abstracte
Traits
Clase ?i Obiecte


Traits

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

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

Example #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 turn override inherited methods.

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

Exemplul de mai sus va afi?a:

Hello World!

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

Exemplul de mai sus va afi?a:

Hello Universe!

Multiple Traits

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

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

Exemplul de mai sus va afi?a:

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 choose exactly one of the conflicting methods.

Since this only allows one to exclude methods, the as operator can be used to add an alias to one of the methods. Note the as operator does not rename the method and it does not affect any other method either.

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

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

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

Exemplul de mai sus va afi?a:

Hello World!

Abstract Trait Members

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

Example #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

Traits can define both static members and static methods.

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

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

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

Example #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
Anonymous classes
Clase ?i Obiecte


Anonymous classes

Support for anonymous classes was added in PHP 7. Anonymous classes are useful when simple, one-off objects need to be created.

<?php

// Pre PHP 7 code
class Logger
{
    public function log($msg)
    {
        echo $msg;
    }
}

$util->setLogger(new Logger());

// PHP 7+ code
$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});

They can pass arguments through to their constructors, extend other classes, implement interfaces, and use traits just like a normal class can:

<?php

class SomeClass {}
interface SomeInterface {}
trait SomeTrait {}

var_dump(new class(10) extends SomeClass implements SomeInterface {
    private $num;

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

    use SomeTrait;
});

Exemplul de mai sus va afi?a:

object(class@anonymous)#1 (1) {
  ["Command line code0x104c5b612":"class@anonymous":private]=>
  int(10)
}

Nesting an anonymous class within another class does not give it access to any private or protected methods or properties of that outer class. In order to use the outer class' protected properties or methods, the anonymous class can extend the outer class. To use the private properties of the outer class in the anonymous class, they must be passed through its constructor:

<?php

class Outer
{
    private $prop = 1;
    protected $prop2 = 2;

    protected function func1()
    {
        return 3;
    }

    public function func2()
    {
        return new class($this->prop) extends Outer {
            private $prop3;

            public function __construct($prop)
            {
                $this->prop3 = $prop;
            }

            public function func3()
            {
                return $this->prop2 + $this->prop3 + $this->func1();
            }
        };
    }
}

echo (new Outer)->func2()->func3();

Exemplul de mai sus va afi?a:

6

All objects created by the same anonymous class declaration are instances of that very class.

<?php
function anonymous_class()
{
    return new class {};
}

if (get_class(anonymous_class()) === get_class(anonymous_class())) {
    echo 'same class';
} else {
    echo 'different class';
}

Exemplul de mai sus va afi?a:

same class

Nota:

Note that anonymous classes are assigned a name by the engine, as demonstrated in the following example. This name has to be regarded an implementation detail, which should not be relied upon.

<?php
echo get_class(new class {});

Exemplul de mai sus va afi?a ceva similar cu:

class@anonymous/in/oNi1A0x7f8636ad2021

Traits
Overloading
Clase ?i Obiecte


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.

Nota:

None of the arguments of these magic methods can be passed by reference.

Nota:

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.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Added __callStatic(). Added warning to enforce public visibility and non-static declaration.
5.1.0 | Added __isset() and __unset(). Added support for __get() for overloading of private properties.
5.0.0 | Added __get().

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.

Nota:

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;

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

Exemplul de mai sus va afi?a:

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.

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

Exemplul de mai sus va afi?a:

Calling object method 'runTest' in object context
Calling static method 'runTest' in static context
Anonymous classes
Object Iteration
Clase ?i Obiecte


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.

Example #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();

?>

Exemplul de mai sus va afi?a:

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 of the visible properties that could be accessed.

To take it a step further, the Iterator interface may be implemented. This allows the object to dictate how it will be iterated and what values will be available on each iteration.

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

Exemplul de mai sus va afi?a:

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:

The IteratorAggregate interface can be used as an alternative to implementing all of the Iterator methods. IteratorAggregate only requires the implementation of a single method, IteratorAggregate::getIterator(), which should return an instance of a class implementing Iterator.

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

Exemplul de mai sus va afi?a:

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:

Nota:

For more examples of iterators, see the SPL Extension.

Nota:

Users of PHP 5.5 and later may also want to investigate generators, which provide an alternative way of defining iterators.

Overloading
Magic Methods
Clase ?i Obiecte


Magic Methods

The function names
__construct(),
__destruct(),
__call(),
__callStatic(),
__get(),
__set(),
__isset(),
__unset(),
__sleep(),
__wakeup(),
__toString(),
__invoke(),
__set_state(),
__clone() and
__debugInfo()
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.

Precautie

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.

Nota:

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.

Example #1 Sleep and wakeup

<?php
class Connection
{
    protected $link;
    private $dsn, $username, $password;

    public function __construct($dsn, $username, $password)
    {
        $this->dsn = $dsn;
        $this->username = $username;
        $this->password = $password;
        $this->connect();
    }

    private function connect()
    {
        $this->link = new PDO($this->dsn, $this->username, $this->password);
    }

    public function __sleep()
    {
        return array('dsn', 'username', 'password');
    }

    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.

Avertizare

You cannot throw an exception from within a __toString() method. Doing so will result in a fatal error.

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

Exemplul de mai sus va afi?a:

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.

Nota:

This feature is available since PHP 5.3.0.

Example #3 Using __invoke()

<?php
class CallableClass
{
    public function __invoke($x)
    {
        var_dump($x);
    }
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>

Exemplul de mai sus va afi?a:

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

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

?>

Exemplul de mai sus va afi?a:

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

Nota: When exporting an object, var_export() does not check whether __set_state() is implemented by the object's class, so re-importing such objects will fail, if __set_state() is not implemented. Particularly, this affects some internal classes. It is the responsibility of the programmer to verify that only objects will be re-imported, whose class implements __set_state().

__debugInfo()

array __debugInfo ( void )

This method is called by var_dump() when dumping an object to get the properties that should be shown. If the method isn't defined on an object, then all public, protected and private properties will be shown.

This feature was added in PHP 5.6.0.

Example #5 Using __debugInfo()

<?php
class C {
    private $prop;

    public function __construct($val) {
        $this->prop = $val;
    }

    public function __debugInfo() {
        return [
            'propSquared' => $this->prop ** 2,
        ];
    }
}

var_dump(new C(42));
?>

Exemplul de mai sus va afi?a:

object(C)#1 (1) {
  ["propSquared"]=>
  int(1764)
}
Object Iteration
Final Keyword
Clase ?i Obiecte


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.

Example #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()
?>

Example #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)
?>

Nota: Properties cannot be declared final, only classes and methods may be declared as final.

Magic Methods
Object Cloning
Clase ?i Obiecte


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.

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

?>

Exemplul de mai sus va afi?a:

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
        )

)

PHP 7.0.0 introduced the possibility to access a member of a freshly cloned object in a single expression:

Example #2 Access member of freshly cloned object

<?php
$dateTime = new DateTime();
echo (clone $dateTime)->format('Y');
?>

Exemplul de mai sus va afi?a ceva similar cu:

2016
Final Keyword
Comparing Objects
Clase ?i Obiecte


Comparing Objects

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 (values are compared with ==), and are instances of the same class.

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.

Example #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);
?>

Exemplul de mai sus va afi?a:

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

Nota:

Extensions can define own rules for their objects comparison (==).

Object Cloning
Indicarea Tipului
Clase ?i Obiecte


Indicarea Tipului

Aceasta documenta?ie a fost transferata în referin?a func?iilor.

Comparing Objects
Late Static Bindings
Clase ?i Obiecte


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:

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

Exemplul de mai sus va afi?a:

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.

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

Exemplul de mai sus va afi?a:

B

Nota:

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.

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

Exemplul de mai sus va afi?a:

success!
success!
success!

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

Nota:

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.

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

Exemplul de mai sus va afi?a:

A
C
C

Indicarea Tipului
Objects and references
Clase ?i Obiecte


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.

Example #1 References and Objects

<?php
class A {
    public $foo = 1;
}

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

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

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

$e = new A;

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

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

?>

Exemplul de mai sus va afi?a:

2
2
2
Late Static Bindings
Object Serialization
Clase ?i Obiecte


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

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

Beyond the above advice, note that you can also hook into the serialization and unserialization events on an object using the __sleep() and __wakeup() methods. Using __sleep() also allows you to only serialize a subset of the object's properties.

Objects and references
OOP Changelog
Clase ?i Obiecte


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.

Versiune | Descriere
5.6.0 | Added: The __debugInfo() method.
5.5.0 | Added: The ::class magic constant.
5.5.0 | Added: finally to handle exceptions.
5.4.0 | Added: traits.
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 provison. 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
Clase ?i Obiecte


Namespaces

Cuprins

  • 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
Informa?ii de referin?a despre limbaj


Namespaces overview

(PHP 5 >= 5.3.0, PHP 7)

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.

Versiune | Descriere
7.0.0 | Added Group use Declarations.

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:

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

Nota:

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

Although any valid PHP code can be contained within a namespace, only the following types of code are affected by namespaces: classes (including abstracts and traits), 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.

Example #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:

Example #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, PHP 7)

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:

Example #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, PHP 7)

Multiple namespaces may also be declared in the same file. There are two allowed syntaxes.

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

Example #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:

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

Example #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, PHP 7)

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.

Example #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 7)

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:

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

Example #2 Dynamically accessing namespaced elements

<?php
namespace namespacename;
class classname
{
    function __construct()
    {
        echo __METHOD__,"\n";
    }
}
function funcname()
{
    echo __FUNCTION__,"\n";
}
const constname = "namespaced";

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

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.

Example #1 __NAMESPACE__ example, namespaced code

<?php
namespace MyProject;

echo '"', __NAMESPACE__, '"'; // outputs "MyProject"
?>

Example #2 __NAMESPACE__ example, global code

<?php

echo '"', __NAMESPACE__, '"'; // outputs ""
?>
The __NAMESPACE__ constant is useful for dynamically constructing names, for instance:

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

Example #4 the namespace operator, inside a namespace

<?php
namespace MyProject;

use blah\blah as mine; // see "Using namespaces: Aliasing/Importing"

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

Example #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, PHP 7)

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.

All versions of PHP that support namespaces support three kinds of aliasing or importing: aliasing a class name, aliasing an interface name, and aliasing a namespace name. PHP 5.6+ also allows aliasing or importing function and constant names.

In PHP, aliasing is accomplished with the use operator. Here is an example showing all 5 kinds of importing:

Example #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;

// importing a function (PHP 5.6+)
use function My\Full\functionName;

// aliasing a function (PHP 5.6+)
use function My\Full\functionName as func;

// importing a constant (PHP 5.6+)
use const My\Full\CONSTANT;

$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
func(); // calls function My\Full\functionName
echo CONSTANT; // echoes the value of My\Full\CONSTANT
?>
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

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

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

Example #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:

Example #5 Illegal importing rule

<?php
namespace Languages;

function toGreenlandic()
{
    use Languages\Danish;

    // ...
}
?>

Nota:

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

Group use declarations

From PHP 7.0 onwards, classes, functions and constants being imported from the same namespace can be grouped together in a single use statement.

<?php

// Pre PHP 7 code
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;

use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;

// PHP 7+ code
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};
namespace keyword and __NAMESPACE__ constant
Global space
Namespaces


Global space

(PHP 5 >= 5.3.0, PHP 7)

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.

Example #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, PHP 7)

Inside a namespace, when PHP encounters an 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:

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

Example #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, PHP 7)

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. The namespace \Foo is also a fully qualified name.

Relative name

This is an identifier starting with namespace, such as namespace\Foo\Bar.

Names are resolved following these resolution rules:

  1. Fully qualified names always resolve to the name without leading namespace separator. For instance \A\B resolves to A\B.
  2. Relative names always resolve to the name with namespace replaced by the current namespace. If the name occurs in the global namespace, the namespace\ prefix is stripped. For example namespace\A inside namespace X\Y resolves to X\Y\A. The same name inside the global namespace resolves to A.
  3. For qualified names the first segment of the name is translated according to the current class/namespace import table. For example, if the namespace A\B\C is imported as C, the name C\D\E is translated to A\B\C\D\E.
  4. For qualified names, if no import rule applies, the current namespace is prepended to the name. For example, the name C\D\E inside namespace A\B, resolves to A\B\C\D\E.
  5. For unqualified names, the name is translated according to the current import table for the respective symbol type. This means that class-like names are translated according to the class/namespace import table, function names according to the function import table and constants according to the constant import table. For example, after use A\B\C; a usage such as new C() resolves to the name A\B\C(). Similarly, after use function A\B\fn; a usage such as fn() resolves to the name A\B\fn.
  6. For unqualified names, if no import rule applies and the name refers to a class-like symbol, the current namespace is prepended. For example new C() inside namespace A\B resolves to name A\B\C.
  7. For unqualified names, if no import rule applies and the name refers to a function or constant and the code is outside the global namespace, the name is resolved at runtime. Assuming the code is in namespace A\B, 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().

Example #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, PHP 7)

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. Before PHP 5.6 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:

Example #1 Accessing global classes outside a namespace

<?php
$a = new \stdClass;
?>

This is functionally equivalent to:

Example #2 Accessing global classes outside a namespace

<?php
$a = new stdClass;
?>

How do I use internal or global classes in a namespace?

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

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

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

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

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

Example #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); // calls the global function "sort"
    $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 {}
}
?>

Before PHP 5.6 neither functions nor constants can be imported via the use statement.

Before PHP 5.6 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();
?>
As of PHP 5.6 aliasing or importing function and constant names is allowed.

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:

Example #9 Dangers of using namespaced names inside a double-quoted string

<?php
$a = "dangerous\name"; // \n is a newline inside double quoted strings!
$obj = new $a;

$a = '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.

Example #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

Example #11 Undefined constants

<?php
namespace bar;
const NULL = 0; // fatal error;
const true = 'stupid'; // also fatal error;
// etc.
?>

Name resolution rules
Errors
Namespaces


Errors

Cuprins

  • Basics
  • Errors in PHP 7

Introduction

Sadly, no matter how careful we are when writing our code, errors are a fact of life. PHP will report errors, warnings and notices for many common coding and runtime problems, and knowing how to detect and handle these errors will make debugging much easier.

FAQ: things you need to know about namespaces
Basics
Informa?ii de referin?a despre limbaj


Basics

PHP reports errors in response to a number of internal error conditions. These may be used to signal a number of different conditions, and can be displayed and/or logged as required.

Every error that PHP generates includes a type. A list of these types is available, along with a short description of their behaviour and how they can be caused.

Handling errors with PHP

If no error handler is set, then PHP will handle any errors that occur according to its configuration. Which errors are reported and which are ignored is controlled by the error_reporting php.ini directive, or at runtime by calling error_reporting(). It is strongly recommended that the configuration directive be set, however, as some errors can occur before execution of your script begins.

In a development environment, you should always set error_reporting to E_ALL, as you need to be aware of and fix the issues raised by PHP. In production, you may wish to set this to a less verbose level such as E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED, but in many cases E_ALL is also appropriate, as it may provide early warning of potential issues.

What PHP does with these errors depends on two further php.ini directives. display_errors controls whether the error is shown as part of the script's output. This should always be disabled in a production environment, as it can include confidential information such as database passwords, but is often useful to enable in development, as it ensures immediate reporting of issues.

In addition to displaying errors, PHP can log errors when the log_errors directive is enabled. This will log any errors to the file or syslog defined by error_log. This can be extremely useful in a production environment, as you can log errors that occur and then generate reports based on those errors.

User error handlers

If PHP's default error handling is inadequate, you can also handle many types of error with your own custom error handler by installing it with set_error_handler(). While some error types cannot be handled this way, those that can be handled can then be handled in the way that your script sees fit: for example, this can be used to show a custom error page to the user and then report more directly than via a log, such as by sending an e-mail.

Errors
Errors in PHP 7
Errors


Errors in PHP 7

PHP 7 changes how most errors are reported by PHP. Instead of reporting errors through the traditional error reporting mechanism used by PHP 5, most errors are now reported by throwing Error exceptions.

As with normal exceptions, these Error exceptions will bubble up until they reach the first matching catch block. If there are no matching blocks, then any default exception handler installed with set_exception_handler() will be called, and if there is no default exception handler, then the exception will be converted to a fatal error and will be handled like a traditional error.

As the Error hierarchy does not inherit from Exception, code that uses catch (Exception $e) { ... } blocks to handle uncaught exceptions in PHP 5 will find that these Errors are not caught by these blocks. Either a catch (Error $e) { ... } block or a set_exception_handler() handler is required.

Error hierarchy

  • Throwable
    • Error
      • ArithmeticError
        • DivisionByZeroError
      • AssertionError
      • ParseError
      • TypeError
    • Exception
      • ...
Basics
Exceptions
Errors


Exceptions

Cuprins

  • 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 or finally block.

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.

catch

Multiple catch blocks can be used to catch different classes of exceptions. Normal execution (when no exception is thrown within the try block) 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().

finally

In PHP 5.5 and later, a finally block may also be specified after or instead of catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.

Note

Nota:

Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException.

Sfat

The Standard PHP Library (SPL) provides a good number of built-in exceptions.

Exemple

Example #3 Throwing an Exception

<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    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\n";
?>

Exemplul de mai sus va afi?a:

0.2
Caught exception: Division by zero.
Hello World

Example #4 Exception handling with a finally block

<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    return 1/$x;
}

try {
    echo inverse(5) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    echo "First finally.\n";
}

try {
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    echo "Second finally.\n";
}

// Continue execution
echo "Hello World\n";
?>

Exemplul de mai sus va afi?a:

0.2
First finally.
Caught exception: Division by zero.
Second finally.
Hello World

Example #5 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();

?>

Exemplul de mai sus va afi?a:

string(4) "foo!"
Errors in PHP 7
Extending Exceptions
Informa?ii de referin?a despre limbaj


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.

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

Nota:

Exceptions cannot be cloned. Attempting to clone an Exception will result in a fatal E_ERROR error.

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

Nota:

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
Generators
Exceptions


Generators

Cuprins

  • Generators overview
  • Generator syntax
  • Comparing generators with Iterator objects
Extending Exceptions
Generators overview
Informa?ii de referin?a despre limbaj


Generators overview

(PHP 5 >= 5.5.0, PHP 7)

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.

A simple example of this is to reimplement the range() function as a generator. The standard range() function has to generate an array with every value in it and return it, which can result in large arrays: for example, calling range(0, 1000000) will result in well over 100 MB of memory being used.

As an alternative, we can implement an xrange() generator, which will only ever need enough memory to create an Iterator object and track the current state of the generator internally, which turns out to be less than 1 kilobyte.

Example #1 Implementing range() as a generator

<?php
function xrange($start, $limit, $step = 1) {
    if ($start < $limit) {
        if ($step <= 0) {
            throw new LogicException('Step must be +ve');
        }

        for ($i = $start; $i <= $limit; $i += $step) {
            yield $i;
        }
    } else {
        if ($step >= 0) {
            throw new LogicException('Step must be -ve');
        }

        for ($i = $start; $i >= $limit; $i += $step) {
            yield $i;
        }
    }
}

/*
 * Note that both range() and xrange() result in the same
 * output below.
 */

echo 'Single digit odd numbers from range():  ';
foreach (range(1, 9, 2) as $number) {
    echo "$number ";
}
echo "\n";

echo 'Single digit odd numbers from xrange(): ';
foreach (xrange(1, 9, 2) as $number) {
    echo "$number ";
}
?>

Exemplul de mai sus va afi?a:

Single digit odd numbers from range():  1 3 5 7 9
Single digit odd numbers from xrange(): 1 3 5 7 9

Generator objects

When a generator function is called for the first time, an object of the internal Generator class is returned. This object implements the Iterator interface in much the same way as a forward-only iterator object would, and provides methods that can be called to manipulate the state of the generator, including sending values to and returning values from it.

Generators
Generator syntax
Generators


Generator syntax

A generator function looks just like a normal function, except that instead of returning a value, a generator yields as many values as it needs to.

When a generator function is called, it returns an object that can be iterated over. When you iterate over that object (for instance, via a foreach loop), PHP will call the generator function each time it needs a value, then saves the state of the generator when the generator yields a value so that it can be resumed when the next value is required.

Once there are no more values to be yielded, then the generator function can simply exit, and the calling code continues just as if an array has run out of values.

Nota:

A generator cannot return a value: doing so will result in a compile error. An empty return statement is valid syntax within a generator and it will terminate the generator.

yield keyword

The heart of a generator function is the yield keyword. In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function.

Example #1 A simple example of yielding values

<?php
function gen_one_to_three() {
    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
        yield $i;
    }
}

$generator = gen_one_to_three();
foreach ($generator as $value) {
    echo "$value\n";
}
?>

Exemplul de mai sus va afi?a:

1
2
3

Nota:

Internally, sequential integer keys will be paired with the yielded values, just as with a non-associative array.

Precautie

If you use yield in an expression context (for example, on the right hand side of an assignment), you must surround the yield statement with parentheses in PHP 5. For example, this is valid:

$data = (yield $value);

But this is not, and will result in a parse error in PHP 5:

$data = yield $value;

The parenthetical restrictions do not apply in PHP 7.

This syntax may be used in conjunction with the Generator::send() method.

Yielding values with keys

PHP also supports associative arrays, and generators are no different. In addition to yielding simple values, as shown above, you can also yield a key at the same time.

The syntax for yielding a key/value pair is very similar to that used to define an associative array, as shown below.

Example #2 Yielding a key/value pair

<?php
/*
 * The input is semi-colon separated fields, with the first
 * field being an ID to use as a key.
 */

$input = <<<'EOF'
1;PHP;Likes dollar signs
2;Python;Likes whitespace
3;Ruby;Likes blocks
EOF;

function input_parser($input) {
    foreach (explode("\n", $input) as $line) {
        $fields = explode(';', $line);
        $id = array_shift($fields);

        yield $id => $fields;
    }
}

foreach (input_parser($input) as $id => $fields) {
    echo "$id:\n";
    echo "    $fields[0]\n";
    echo "    $fields[1]\n";
}
?>

Exemplul de mai sus va afi?a:

1:
    PHP
    Likes dollar signs
2:
    Python
    Likes whitespace
3:
    Ruby
    Likes blocks
Precautie

As with the simple value yields shown earlier, yielding a key/value pair in an expression context requires the yield statement to be parenthesised:

$data = (yield $key => $value);

Yielding null values

Yield can be called without an argument to yield a NULL value with an automatic key.

Example #3 Yielding NULLs

<?php
function gen_three_nulls() {
    foreach (range(1, 3) as $i) {
        yield;
    }
}

var_dump(iterator_to_array(gen_three_nulls()));
?>

Exemplul de mai sus va afi?a:

array(3) {
  [0]=>
  NULL
  [1]=>
  NULL
  [2]=>
  NULL
}

Yielding by reference

Generator functions are able to yield values by reference as well as by value. This is done in the same way as returning references from functions: by prepending an ampersand to the function name.

Example #4 Yielding values by reference

<?php
function &gen_reference() {
    $value = 3;

    while ($value > 0) {
        yield $value;
    }
}

/*
 * Note that we can change $number within the loop, and
 * because the generator is yielding references, $value
 * within gen_reference() changes.
 */
foreach (gen_reference() as &$number) {
    echo (--$number).'... ';
}
?>

Exemplul de mai sus va afi?a:

2... 1... 0...

Generator delegation via yield from

In PHP 7, generator delegation allows you to yield values from another generator, Traversable object, or array by using the yield from keyword. The outer generator will then yield all values from the inner generator, object, or array until that is no longer valid, after which execution will continue in the outer generator.

If a generator is used with yield from, the yield from expression will also return any value returned by the inner generator.

Precautie

Storing into an array (e.g. with iterator_to_array())

yield from does not reset the keys. It preserves the keys returned by the Traversable object, or array. Thus some values may share a common key with another yield or yield from, which, upon insertion into an array, will overwrite former values with that key.

A common case where this matters is iterator_to_array() returning a keyed array by default, leading to possibly unexpected results. iterator_to_array() has a second parameter use_keys which can be set to FALSE to collect all the values while ignoring the keys returned by the Generator.

Example #5 yield from with iterator_to_array()

<?php
function from() {
    yield 1; // key 0
    yield 2; // key 1
    yield 3; // key 2
}
function gen() {
    yield 0; // key 0
    yield from from(); // keys 0-2
    yield 4; // key 1
}
// pass false as second parameter to get an array [0, 1, 2, 3, 4]
var_dump(iterator_to_array(gen()));
?>

Exemplul de mai sus va afi?a:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(4)
  [2]=>
  int(3)
}

Example #6 Basic use of yield from

<?php
function count_to_ten() {
    yield 1;
    yield 2;
    yield from [3, 4];
    yield from new ArrayIterator([5, 6]);
    yield from seven_eight();
    yield 9;
    yield 10;
}

function seven_eight() {
    yield 7;
    yield from eight();
}

function eight() {
    yield 8;
}

foreach (count_to_ten() as $num) {
    echo "$num ";
}
?>

Exemplul de mai sus va afi?a:

1 2 3 4 5 6 7 8 9 10

Example #7 yield from and return values

<?php
function count_to_ten() {
    yield 1;
    yield 2;
    yield from [3, 4];
    yield from new ArrayIterator([5, 6]);
    yield from seven_eight();
    return yield from nine_ten();
}

function seven_eight() {
    yield 7;
    yield from eight();
}

function eight() {
    yield 8;
}

function nine_ten() {
    yield 9;
    return 10;
}

$gen = count_to_ten();
foreach ($gen as $num) {
    echo "$num ";
}
echo $gen->getReturn();
?>

Exemplul de mai sus va afi?a:

1 2 3 4 5 6 7 8 9 10
Generators overview
Comparing generators with Iterator objects
Generators


Comparing generators with Iterator objects

The primary advantage of generators is their simplicity. Much less boilerplate code has to be written compared to implementing an Iterator class, and the code is generally much more readable. For example, the following function and class are equivalent:

<?php
function getLinesFromFile($fileName) {
    if (!$fileHandle = fopen($fileName, 'r')) {
        return;
    }

    while (false !== $line = fgets($fileHandle)) {
        yield $line;
    }

    fclose($fileHandle);
}

// versus...

class LineIterator implements Iterator {
    protected $fileHandle;

    protected $line;
    protected $i;

    public function __construct($fileName) {
        if (!$this->fileHandle = fopen($fileName, 'r')) {
            throw new RuntimeException('Couldn\'t open file "' . $fileName . '"');
        }
    }

    public function rewind() {
        fseek($this->fileHandle, 0);
        $this->line = fgets($this->fileHandle);
        $this->i = 0;
    }

    public function valid() {
        return false !== $this->line;
    }

    public function current() {
        return $this->line;
    }

    public function key() {
        return $this->i;
    }

    public function next() {
        if (false !== $this->line) {
            $this->line = fgets($this->fileHandle);
            $this->i++;
        }
    }

    public function __destruct() {
        fclose($this->fileHandle);
    }
}
?>

This flexibility does come at a cost, however: generators are forward-only iterators, and cannot be rewound once iteration has started. This also means that the same generator can't be iterated over multiple times: the generator will need to be rebuilt by calling the generator function again.

Generator syntax
References Explained
Generators


References Explained

Cuprins

  • What References Are
  • What References Do
  • What References Are Not
  • Passing by Reference
  • Returning References
  • Unsetting References
  • Spotting References
Comparing generators with Iterator objects
What References Are
Informa?ii de referin?a despre limbaj


What References Are

References in PHP are a means to access the same variable content by different names. They are not like C pointers; for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses, and so on. See What References Are Not for more information. Instead, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The closest analogy is with Unix filenames and files - variable names are directory entries, while variable content is the file itself. References can be likened to hardlinking in Unix filesystem.

References Explained
What References Do
References Explained


What References Do

There are three basic operations performed using references: assigning by reference, passing by reference, and returning by reference. This section will give an introduction to these operations, with links for further reading.

Assign By Reference

In the first of these, PHP references allow you to make two variables refer to the same content. Meaning, when you do:

<?php
$a =& $b;
?>
it means that $a and $b point to the same content.

Nota:

$a and $b are completely equal here. $a is not pointing to $b or vice versa. $a and $b are pointing to the same place.

Nota:

If you assign, pass, or return an undefined variable by reference, it will get created.

Example #1 Using references with undefined variables

<?php
function foo(&$var) { }

foo($a); // $a is "created" and assigned to null

$b = array();
foo($b['b']);
var_dump(array_key_exists('b', $b)); // bool(true)

$c = new StdClass;
foo($c->d);
var_dump(property_exists($c, 'd')); // bool(true)
?>

The same syntax can be used with functions that return references, and with the new operator (since PHP 4.0.4 and before PHP 5.0.0):

<?php
$foo =& find_var($bar);
?>
Since PHP 5, new returns a reference automatically, so using =& in this context is deprecated and produces an E_DEPRECATED message in PHP 5.3 and later, and an E_STRICT message in earlier versions. As of PHP 7.0 it is syntactically invalid. (Technically, the difference is that, in PHP 5, object variables, much like resources, are a mere pointer to the actual object data, so these object references are not "references" in the same sense used before (aliases). For more information, see Objects and references.)

Avertizare

If you assign a reference to a variable declared global inside a function, the reference will be visible only inside the function. You can avoid this by using the $GLOBALS array.

Example #2 Referencing global variables inside functions

<?php
$var1 = "Example variable";
$var2 = "";

function global_references($use_globals)
{
    global $var1, $var2;
    if (!$use_globals) {
        $var2 =& $var1; // visible only inside the function
    } else {
        $GLOBALS["var2"] =& $var1; // visible also in global context
    }
}

global_references(false);
echo "var2 is set to '$var2'\n"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2'\n"; // var2 is set to 'Example variable'
?>
Think about global $var; as a shortcut to $var =& $GLOBALS['var'];. Thus assigning another reference to $var only changes the local variable's reference.

Nota:

If you assign a value to a variable with references in a foreach statement, the references are modified too.

Example #3 References and foreach statement

<?php
$ref = 0;
$row =& $ref;
foreach (array(1, 2, 3) as $row) {
    // do something
}
echo $ref; // 3 - last element of the iterated array
?>

While not being strictly an assignment by reference, expressions created with the language construct array() can also behave as such by prefixing & to the array element to add. Example:

<?php
$a = 1;
$b = array(2, 3);
$arr = array(&$a, &$b[0], &$b[1]);
$arr[0]++; $arr[1]++; $arr[2]++;
/* $a == 2, $b == array(3, 4); */
?>

Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value. Example:

<?php
/* Assignment of scalar variables */
$a = 1;
$b =& $a;
$c = $b;
$c = 7; //$c is not a reference; no change to $a or $b

/* Assignment of array variables */
$arr = array(1);
$a =& $arr[0]; //$a and $arr[0] are in the same reference set
$arr2 = $arr; //not an assignment-by-reference!
$arr2[0]++;
/* $a == 2, $arr == array(2) */
/* The contents of $arr are changed even though it's not a reference! */
?>
In other words, the reference behavior of arrays is defined in an element-by-element basis; the reference behavior of individual elements is dissociated from the reference status of the array container.

Pass By Reference

The second thing references do is to pass variables by reference. This is done by making a local variable in a function and a variable in the calling scope referencing the same content. Example:

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
?>
will make $a to be 6. This happens because in the function foo the variable $var refers to the same content as $a. For more information on this, read the passing by reference section.

Return By Reference

The third thing references can do is return by reference.

What References Are
What References Are Not
References Explained


What References Are Not

As said before, references are not pointers. That means, the following construct won't do what you expect:

<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);
?>

What happens is that $var in foo will be bound with $bar in the caller, but then re-bound with $GLOBALS["baz"]. There's no way to bind $bar in the calling scope to something else using the reference mechanism, since $bar is not available in the function foo (it is represented by $var, but $var has only variable contents and not name-to-value binding in the calling symbol table). You can use returning references to reference variables selected by the function.

What References Do
Passing by Reference
References Explained


Passing by Reference

You can pass a variable by reference to a function so the function can modify the variable. The syntax is as follows:

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
// $a is 6 here
?>

Nota: There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

The following things can be passed by reference:

  • Variables, i.e. foo($a)
  • New statements, i.e. foo(new foobar())

  • References returned from functions, i.e.:

    <?php
    function foo(&$var)
    {
            $var++;
    }
    function &    bar()
    {
            $a = 5;
        return     $a;
    }
    foo(bar());
    ?>
    See more about returning by reference.

No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:

<?php
function foo(&$var)
{
    $var++;
}
function bar() // Note the missing &
{
    $a = 5;
    return $a;
}
foo(bar()); // Produces fatal error as of PHP 5.0.5, strict standards notice
            // as of PHP 5.1.1, and notice as of PHP 7.0.0

foo($a = 5); // Expression, not variable
foo(5); // Produces fatal error
?>

What References Are Not
Returning References
References Explained


Returning References

Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so. To return references, use this syntax:

<?php
class foo {
    public $value = 42;

    public function &getValue() {
        return $this->value;
    }
}

$obj = new foo;
$myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42.
$obj->value = 2;
echo $myValue;                // prints the new value of $obj->value, i.e. 2.
?>
In this example, the property of the object returned by the getValue function would be set, not the copy, as it would be without using reference syntax.

Nota: Unlike parameter passing, here you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for $myValue.

Nota: If you try to return a reference from a function with the syntax: return ($this->value); this will not work as you are attempting to return the result of an expression, and not a variable, by reference. You can only return variables by reference from a function - nothing else. Since PHP 5.1.0, an E_NOTICE error is issued if the code tries to return a dynamic expression or a result of the new operator.

To use the returned reference, you must use reference assigment:

<?php
function &collector() {
  static $collection = array();
  return $collection;
}
$collection = &collector();
$collection[] = 'foo';
?>
To pass the returned reference to another function expecting a reference you can use this syntax:
<?php
function &collector() {
  static $collection = array();
  return $collection;
}
array_push(collector(), 'foo');
?>

Nota: Note that array_push(&collector(), 'foo'); will not work, it results in a fatal error.

Passing by Reference
Unsetting References
References Explained


Unsetting References

When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example:

<?php
$a = 1;
$b =& $a;
unset($a);
?>
won't unset $b, just $a.

Again, it might be useful to think about this as analogous to the Unix unlink call.

Returning References
Spotting References
References Explained


Spotting References

Many syntax constructs in PHP are implemented via referencing mechanisms, so everything mentioned herein about reference binding also applies to these constructs. Some constructs, like passing and returning by reference, are mentioned above. Other constructs that use references are:

global References

When you declare a variable as global $var you are in fact creating reference to a global variable. That means, this is the same as:

<?php
$var =& $GLOBALS["var"];
?>

This also means that unsetting $var won't unset the global variable.

$this

In an object method, $this is always a reference to the caller object.

Unsetting References
Predefined Variables
References Explained


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

Cuprins

  • 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
Spotting References
Superglobals
Informa?ii de referin?a despre limbaj


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

Descrierea

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

Istoricul schimbarilor

Versiune | Descriere
4.1.0 | Superglobals were introduced to PHP.

Note

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

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

Nota: Variable variables

Superglobals cannot be used as variable variables inside functions or class methods.

A se vedea ?i

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

$GLOBALS — References all variables available in global scope

Descrierea

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.

Exemple

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

Exemplul de mai sus va afi?a ceva similar cu:

$foo in global scope: Example content
$foo in current scope: local variable

Note

Nota:

Aceasta este o variabila 'superglobala', sau globala automata. Aceasta pur ?i simplu înseamna ca ea este disponibila în toate circumstan?ele pe parcursul script-ului. Nu este nevoie de a scrie global $variable; pentru a o accesa din func?ii sau metode.

Nota: 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 [removed]

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

$_SERVER -- $HTTP_SERVER_VARS [removed] — Server and execution environment information

Descrierea

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

Nota: Prior to PHP 5.4.0, $HTTP_SERVER_VARS contained the same initial information, but was not a superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER were different variables and that PHP handled them as such.)

Indici

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/foo/bar.php would be /foo/bar.php. 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.

Nota: Under Apache 2, you must set UseCanonicalName = On and ServerName. Otherwise, this value reflects the hostname supplied by the client, which can be spoofed. It is not safe to rely on this value in security-dependent contexts.

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

Nota:

PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD.

'REQUEST_TIME'
The timestamp of the start of the request. Available since PHP 5.1.0.
'REQUEST_TIME_FLOAT'
The timestamp of the start of the request, with microsecond precision. Available since PHP 5.4.0.
'QUERY_STRING'
The query string, if any, via which the page was accessed.
'DOCUMENT_ROOT'
The document root directory under which the current script is executing, as defined in the server's configuration file.
'HTTP_ACCEPT'
Contents of the Accept: header from the current request, if there is one.
'HTTP_ACCEPT_CHARSET'
Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
'HTTP_ACCEPT_ENCODING'
Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
'HTTP_ACCEPT_LANGUAGE'
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
'HTTP_CONNECTION'
Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
'HTTP_HOST'
Contents of the Host: header from the current request, if there is one.
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
'HTTP_USER_AGENT'
Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.
'HTTPS'
Set to a non-empty value if the script was queried through the HTTPS protocol.

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

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

Nota:

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.

Nota: Under the Apache 2, you must set UseCanonicalName = On, as well as UseCanonicalPhysicalPort = On in order to get the physical (real) port, otherwise, this value can be spoofed and it may or may not return the physical port value. It is not safe to rely on this value in security-dependent contexts.

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

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

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | $HTTP_SERVER_VARS isn't available anymore due to the removal of long arrays registering.
5.3.0 | Directive register_long_arrays which caused $HTTP_SERVER_VARS to be available has been deprecated.
4.1.0 | Introduced $_SERVER that deprecated $HTTP_SERVER_VARS.

Exemple

Example #1 $_SERVER example

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

Exemplul de mai sus va afi?a ceva similar cu:

www.example.com

Note

Nota:

Aceasta este o variabila 'superglobala', sau globala automata. Aceasta pur ?i simplu înseamna ca ea este disponibila în toate circumstan?ele pe parcursul script-ului. Nu este nevoie de a scrie global $variable; pentru a o accesa din func?ii sau metode.

A se vedea ?i

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

$_GET -- $HTTP_GET_VARS [deprecated] — HTTP GET variables

Descrierea

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)

Istoricul schimbarilor

Versiune | Descriere
4.1.0 | Introduced $_GET that deprecated $HTTP_GET_VARS.

Exemple

Example #1 $_GET example

<?php
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>

Assuming the user entered http://example.com/?name=Hannes

Exemplul de mai sus va afi?a ceva similar cu:

Hello Hannes!

Note

Nota:

Aceasta este o variabila 'superglobala', sau globala automata. Aceasta pur ?i simplu înseamna ca ea este disponibila în toate circumstan?ele pe parcursul script-ului. Nu este nevoie de a scrie global $variable; pentru a o accesa din func?ii sau metode.

Nota:

The GET variables are passed through urldecode().

A se vedea ?i

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

$_POST -- $HTTP_POST_VARS [deprecated] — HTTP POST variables

Descrierea

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

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

Istoricul schimbarilor

Versiune | Descriere
4.1.0 | Introduced $_POST that deprecated $HTTP_POST_VARS.

Exemple

Example #1 $_POST example

<?php
echo 'Hello ' . htmlspecialchars($_POST["name"]) . '!';
?>

Assuming the user POSTed name=Hannes

Exemplul de mai sus va afi?a ceva similar cu:

Hello Hannes!

Note

Nota:

Aceasta este o variabila 'superglobala', sau globala automata. Aceasta pur ?i simplu înseamna ca ea este disponibila în toate circumstan?ele pe parcursul script-ului. Nu este nevoie de a scrie global $variable; pentru a o accesa din func?ii sau metode.

A se vedea ?i

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

$_FILES -- $HTTP_POST_FILES [deprecated] — HTTP File Upload variables

Descrierea

An associative array of items uploaded to the current script via the HTTP POST method. The structure of this array is outlined in the POST method uploads section.

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

Istoricul schimbarilor

Versiune | Descriere
4.1.0 | Introduced $_FILES that deprecated $HTTP_POST_FILES.

Note

Nota:

Aceasta este o variabila 'superglobala', sau globala automata. Aceasta pur ?i simplu înseamna ca ea este disponibila în toate circumstan?ele pe parcursul script-ului. Nu este nevoie de a scrie global $variable; pentru a o accesa din func?ii sau metode.

A se vedea ?i

  • move_uploaded_file() - Moves an uploaded file to a new location
  • Handling File Uploads

$_POST
$_REQUEST
Predefined Variables


HTTP Request variables

$_FILES
$_SESSION
Predefined Variables
PHP Manual

$_REQUEST

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

$_REQUEST — HTTP Request variables

Descrierea

An associative array that by default contains the contents of $_GET, $_POST ?i $_COOKIE.

Istoricul schimbarilor

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

Note

Nota:

Aceasta este o variabila 'superglobala', sau globala automata. Aceasta pur ?i simplu înseamna ca ea este disponibila în toate circumstan?ele pe parcursul script-ului. Nu este nevoie de a scrie global $variable; pentru a o accesa din func?ii sau metode.

Nota:

When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array.

Nota:

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.

A se vedea ?i

  • import_request_variables() - Importa variabilele GET/POST/Cookie în circumstan?a globala
  • 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, PHP 7)

$_SESSION -- $HTTP_SESSION_VARS [deprecated] — Session variables

Descrierea

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)

Istoricul schimbarilor

Versiune | Descriere
4.1.0 | Introduced $_SESSION that deprecated $HTTP_SESSION_VARS.

Note

Nota:

Aceasta este o variabila 'superglobala', sau globala automata. Aceasta pur ?i simplu înseamna ca ea este disponibila în toate circumstan?ele pe parcursul script-ului. Nu este nevoie de a scrie global $variable; pentru a o accesa din func?ii sau metode.

A se vedea ?i

  • session_start() - Start new or resume existing session

$_REQUEST
$_ENV
Predefined Variables


Environment variables

$_SESSION
$_COOKIE
Predefined Variables
PHP Manual

$_ENV

$HTTP_ENV_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

$_ENV -- $HTTP_ENV_VARS [deprecated] — Environment variables

Descrierea

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)

Istoricul schimbarilor

Versiune | Descriere
4.1.0 | Introduced $_ENV that deprecated $HTTP_ENV_VARS.

Exemple

Example #1 $_ENV example

<?php
echo 'My username is ' .$_ENV["USER"] . '!';
?>

Assuming "bjori" executes this script

Exemplul de mai sus va afi?a ceva similar cu:

My username is bjori!

Note

Nota:

Aceasta este o variabila 'superglobala', sau globala automata. Aceasta pur ?i simplu înseamna ca ea este disponibila în toate circumstan?ele pe parcursul script-ului. Nu este nevoie de a scrie global $variable; pentru a o accesa din func?ii sau metode.

A se vedea ?i

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

$_COOKIE -- $HTTP_COOKIE_VARS [deprecated] — HTTP Cookies

Descrierea

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)

Istoricul schimbarilor

Versiune | Descriere
4.1.0 | Introduced $_COOKIE that deprecated $HTTP_COOKIE_VARS.

Exemple

Example #1 $_COOKIE example

<?php
echo 'Hello ' . htmlspecialchars($_COOKIE["name"]) . '!';
?>

Assuming the "name" cookie has been set earlier

Exemplul de mai sus va afi?a ceva similar cu:

Hello Hannes!

Note

Nota:

Aceasta este o variabila 'superglobala', sau globala automata. Aceasta pur ?i simplu înseamna ca ea este disponibila în toate circumstan?ele pe parcursul script-ului. Nu este nevoie de a scrie global $variable; pentru a o accesa din func?ii sau metode.

A se vedea ?i

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

$php_errormsg — The previous error message

Descrierea

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

Avertizare

If a user defined error handler (set_error_handler()) is set $php_errormsg is only set if the error handler returns FALSE.

Exemple

Example #1 $php_errormsg example

<?php
@strpos();
echo $php_errormsg;
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

Avertizare

Aceasta facilitate este ÎNVECHITA începând cu PHP 5.6.0 ?i ELIMINATA începând cu PHP 7.0.0.

$HTTP_RAW_POST_DATA contains the raw POST data. See always_populate_raw_post_data.

In general, php://input should be used instead of $HTTP_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, PHP 7)

$http_response_header — HTTP response headers

Descrierea

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.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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=Windows-1252"
}
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, PHP 7)

$argc — The number of arguments passed to script

Descrierea

Contains the number of arguments passed to the current script when running from the command line.

Nota: The script's filename is always passed as an argument to the script, therefore the minimum value of $argc is 1.

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

Exemple

Example #1 $argc example

<?php
var_dump($argc);
?>

When executing the example with: php script.php arg1 arg2 arg3

Exemplul de mai sus va afi?a ceva similar cu:

int(4)

$http_response_header
$argv
Predefined Variables


Array of arguments passed to script

$argc
Excep?ii predefinite
Predefined Variables
PHP Manual

$argv

(PHP 4, PHP 5, PHP 7)

$argv — Array of arguments passed to script

Descrierea

Contains an array of all the arguments passed to the script when running from the command line.

Nota: The first argument $argv[0] is always the name that was used to run the script.

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

Exemple

Example #1 $argv example

<?php
var_dump($argv);
?>

When executing the example with: php script.php arg1 arg2 arg3

Exemplul de mai sus va afi?a ceva similar cu:

array(4) {
  [0]=>
  string(10) "script.php"
  [1]=>
  string(4) "arg1"
  [2]=>
  string(4) "arg2"
  [3]=>
  string(4) "arg3"
}

A se vedea ?i

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

$argc
Excep?ii predefinite
Predefined Variables


Excep?ii predefinite

Cuprins

  • Exception
  • ErrorException
  • Error
  • ArithmeticError
  • AssertionError
  • DivisionByZeroError
  • ParseError
  • TypeError

A se vedea Excep?ii SPL

$argv
Exception
Informa?ii de referin?a despre limbaj


Exception

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Exception is the base class for all Exceptions in PHP 5, and the base class for all user exceptions in PHP 7.

In PHP 7, Exception implements the Throwable interface.

Sinopsisul clasei

Exception {
/* Proprieta?i */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode */
public __construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )
final public string getMessage ( void )
final public Throwable 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 )
}

Proprieta?i

message

The exception message

code

The exception code

file

The filename where the exception was created

line

The line where the exception was created

Cuprins

  • 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 was created
  • Exception::getLine — Gets the line in which the exception was created
  • 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
Excep?ii predefinite
Exception::__construct
Excep?ii predefinite


Construct the exception

Exception
Exception::getMessage
Exception
PHP Manual

Exception::__construct

(PHP 5 >= 5.1.0, PHP 7)

Exception::__construct — Construct the exception

Descrierea

public Exception::__construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )

Constructs the Exception.

Parametri

message

The Exception message to throw.

code

The Exception code.

previous

The previous exception used for the exception chaining.

Nota: Calling the constructor of class Exception from a subclass ignores the default arguments, if the properties $code and $message are already set.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | The previous parameter is now of type Throwable.
5.3.0 | The previous parameter was added.

Note

Nota:

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

Exception::getMessage — Gets the Exception message

Descrierea

final public string Exception::getMessage ( void )

Returns the Exception message.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the Exception message as a string.

Exemple

Example #1 Exception::getMessage() example

<?php
try {
    throw new Exception("Some error message");
} catch(Exception $e) {
    echo $e->getMessage();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Some error message

A se vedea ?i

  • Throwable::getMessage() - Gets the message

Exception::__construct
Exception::getPrevious
Exception


Returns previous Exception

Exception::getMessage
Exception::getCode
Exception
PHP Manual

Exception::getPrevious

(PHP 5 >= 5.3.0, PHP 7)

Exception::getPrevious — Returns previous Exception

Descrierea

final public Throwable Exception::getPrevious ( void )

Returns previous exception (the third parameter of Exception::__construct()).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the previous Throwable if available or NULL otherwise.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | The return type declaration changed to Throwable.

Exemple

Example #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 happened", 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());
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

/home/bjori/ex.php:8 Something happened (911) [MyCustomException]
/home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException]

A se vedea ?i

  • Throwable::getPrevious() - Returns the previous Throwable

Exception::getMessage
Exception::getCode
Exception


Gets the Exception code

Exception::getPrevious
Exception::getFile
Exception
PHP Manual

Exception::getCode

(PHP 5 >= 5.1.0, PHP 7)

Exception::getCode — Gets the Exception code

Descrierea

final public mixed Exception::getCode ( void )

Returns the Exception code.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Exemple

Example #1 Exception::getCode() example

<?php
try {
    throw new Exception("Some error message", 30);
} catch(Exception $e) {
    echo "The exception code is: " . $e->getCode();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

The exception code is: 30

A se vedea ?i

  • Throwable::getCode() - Gets the exception code

Exception::getPrevious
Exception::getFile
Exception


Gets the file in which the exception was created

Exception::getCode
Exception::getLine
Exception
PHP Manual

Exception::getFile

(PHP 5 >= 5.1.0, PHP 7)

Exception::getFile — Gets the file in which the exception was created

Descrierea

final public string Exception::getFile ( void )

Get the name of the file in which the exception was created.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the filename in which the exception was created.

Exemple

Example #1 Exception::getFile() example

<?php
try {
    throw new Exception;
} catch(Exception $e) {
    echo $e->getFile();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

/home/bjori/tmp/ex.php

A se vedea ?i

  • Throwable::getFile() - Gets the file in which the exception was created

Exception::getCode
Exception::getLine
Exception


Gets the line in which the exception was created

Exception::getFile
Exception::getTrace
Exception
PHP Manual

Exception::getLine

(PHP 5 >= 5.1.0, PHP 7)

Exception::getLine — Gets the line in which the exception was created

Descrierea

final public int Exception::getLine ( void )

Get line number where the exception was created.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the line number where the exception was created.

Exemple

Example #1 Exception::getLine() example

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

Exemplul de mai sus va afi?a ceva similar cu:

The exception was created on line: 3

A se vedea ?i

  • Throwable::getLine() - Gets the line on which the object was instantiated

Exception::getFile
Exception::getTrace
Exception


Gets the stack trace

Exception::getLine
Exception::getTraceAsString
Exception
PHP Manual

Exception::getTrace

(PHP 5 >= 5.1.0, PHP 7)

Exception::getTrace — Gets the stack trace

Descrierea

final public array Exception::getTrace ( void )

Returns the Exception stack trace.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the Exception stack trace as an array.

Exemple

Example #1 Exception::getTrace() example

<?php
function test() {
 throw new Exception;
}

try {
 test();
} catch(Exception $e) {
 var_dump($e->getTrace());
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [0]=>
  array(4) {
    ["file"]=>
    string(22) "/home/bjori/tmp/ex.php"
    ["line"]=>
    int(7)
    ["function"]=>
    string(4) "test"
    ["args"]=>
    array(0) {
    }
  }
}

A se vedea ?i

  • Throwable::getTrace() - Gets the stack trace

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

Exception::getTraceAsString — Gets the stack trace as a string

Descrierea

final public string Exception::getTraceAsString ( void )

Returns the Exception stack trace as a string.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the Exception stack trace as a string.

Exemple

Example #1 Exception::getTraceAsString() example

<?php
function test() {
    throw new Exception;
}

try {
    test();
} catch(Exception $e) {
    echo $e->getTraceAsString();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}

A se vedea ?i

  • Throwable::getTraceAsString() - Gets the stack trace as a string

Exception::getTrace
Exception::__toString
Exception


String representation of the exception

Exception::getTraceAsString
Exception::__clone
Exception
PHP Manual

Exception::__toString

(PHP 5 >= 5.1.0, PHP 7)

Exception::__toString — String representation of the exception

Descrierea

public string Exception::__toString ( void )

Returns the string representation of the exception.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the string representation of the exception.

Exemple

Example #1 Exception::__toString() example

<?php
try {
    throw new Exception("Some error message");
} catch(Exception $e) {
    echo $e;
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

exception 'Exception' with message 'Some error message' in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}

A se vedea ?i

  • Throwable::__toString() - Gets a string representation of the thrown object

Exception::getTraceAsString
Exception::__clone
Exception


Clone the exception

Exception::__toString
ErrorException
Exception
PHP Manual

Exception::__clone

(PHP 5 >= 5.1.0, PHP 7)

Exception::__clone — Clone the exception

Descrierea

final private void Exception::__clone ( void )

Tries to clone the Exception, which results in Fatal error.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Exceptions are not clonable.

Exception::__toString
ErrorException
Exception


ErrorException

(PHP 5 >= 5.1.0, PHP 7)

Introducere

An Error Exception.

Sinopsisul clasei

ErrorException extends Exception {
/* Proprieta?i */
protected int $severity ;
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode */
public __construct ([ string $message = "" [, int $code = 0 [, int $severity = E_ERROR [, string $filename = __FILE__ [, int $lineno = __LINE__ [, Exception $previous = NULL ]]]]]] )
final public int getSeverity ( void )
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Proprieta?i

severity

The severity of the exception

Exemple

Example #1 Use set_error_handler() to change error messages into ErrorException.

<?php
function exception_error_handler($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting
        return;
    }
    throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Fatal error: Uncaught exception 'ErrorException' with message 'strpos() expects at least 2 parameters, 0 given' in /home/bjori/tmp/ex.php:12
Stack trace:
#0 [internal function]: exception_error_handler(2, 'strpos() expect...', '/home/bjori/php...', 12, Array)
#1 /home/bjori/php/cleandocs/test.php(12): strpos()
#2 {main}
  thrown in /home/bjori/tmp/ex.php on line 12

Cuprins

  • ErrorException::__construct — Constructs the exception
  • ErrorException::getSeverity — Gets the exception severity
Exception::__clone
ErrorException::__construct
Excep?ii predefinite


Constructs the exception

ErrorException
ErrorException::getSeverity
ErrorException
PHP Manual

ErrorException::__construct

(PHP 5 >= 5.1.0, PHP 7)

ErrorException::__construct — Constructs the exception

Descrierea

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

Constructs the Exception.

Parametri

message

The Exception message to throw.

code

The Exception code.

severity

The severity level of the exception.

Nota:

While the severity can be any integer value, it is intended that the error constants be used.

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.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | The previous parameter was added.

ErrorException
ErrorException::getSeverity
ErrorException


Gets the exception severity

ErrorException::__construct
Error
ErrorException
PHP Manual

ErrorException::getSeverity

(PHP 5 >= 5.1.0, PHP 7)

ErrorException::getSeverity — Gets the exception severity

Descrierea

final public int ErrorException::getSeverity ( void )

Returns the severity of the exception.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the severity level of the exception.

Exemple

Example #1 ErrorException::getSeverity() example

<?php
try {
    throw new ErrorException("Exception message", 0, E_USER_ERROR);
} catch(ErrorException $e) {
    echo "This exception severity is: " . $e->getSeverity();
    var_dump($e->getSeverity() === E_USER_ERROR);
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

This exception severity is: 256
bool(true)

ErrorException::__construct
Error
ErrorException


Error

(PHP 7)

Introducere

Error is the base class for all internal PHP errors.

Sinopsisul clasei

Error implements Throwable {
/* Proprieta?i */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode */
public __construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )
final public string getMessage ( void )
final public Throwable 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 )
}

Proprieta?i

message

The error message

code

The error code

file

The filename where the error happened

line

The line where the error happened

Cuprins

  • Error::__construct — Construct the error object
  • Error::getMessage — Gets the error message
  • Error::getPrevious — Returns previous Throwable
  • Error::getCode — Gets the error code
  • Error::getFile — Gets the file in which the error occurred
  • Error::getLine — Gets the line in which the error occurred
  • Error::getTrace — Gets the stack trace
  • Error::getTraceAsString — Gets the stack trace as a string
  • Error::__toString — String representation of the error
  • Error::__clone — Clone the error
ErrorException::getSeverity
Error::__construct
Excep?ii predefinite


Construct the error object

Error
Error::getMessage
Error
PHP Manual

Error::__construct

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

Error::__construct — Construct the error object

Descrierea

public Error::__construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )

Constructs the Error.

Parametri

message

The error message.

code

The error code.

previous

The previous throwable used for the exception chaining.

Note

Nota:

The message is NOT binary safe.

Error
Error::getMessage
Error


Gets the error message

Error::__construct
Error::getPrevious
Error
PHP Manual

Error::getMessage

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

Error::getMessage — Gets the error message

Descrierea

final public string Error::getMessage ( void )

Returns the error message.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the error message as a string.

Exemple

Example #1 Error::getMessage() example

<?php
try {
    throw new Error("Some error message");
} catch(Error $e) {
    echo $e->getMessage();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Some error message

A se vedea ?i

  • Throwable::getMessage() - Gets the message

Error::__construct
Error::getPrevious
Error


Returns previous Throwable

Error::getMessage
Error::getCode
Error
PHP Manual

Error::getPrevious

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

Error::getPrevious — Returns previous Throwable

Descrierea

final public Throwable Error::getPrevious ( void )

Returns previous Throwable (the third parameter of Error::__construct()).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the previous Throwable if available or NULL otherwise.

Exemple

Example #1 Error::getPrevious() example

Looping over, and printing out, error trace.

<?php
class MyCustomError extends Error {}

function doStuff() {
    try {
        throw new InvalidArgumentError("You are doing it wrong!", 112);
    } catch(Error $e) {
        throw new MyCustomError("Something happened", 911, $e);
    }
}

try {
    doStuff();
} catch(Error $e) {
    do {
        printf("%s:%d %s (%d) [%s]\n", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
    } while($e = $e->getPrevious());
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

/home/bjori/ex.php:8 Something happened (911) [MyCustomError]
/home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentError]

A se vedea ?i

  • Throwable::getPrevious() - Returns the previous Throwable

Error::getMessage
Error::getCode
Error


Gets the error code

Error::getPrevious
Error::getFile
Error
PHP Manual

Error::getCode

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

Error::getCode — Gets the error code

Descrierea

final public mixed Error::getCode ( void )

Returns the error code.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the error code as integer

Exemple

Example #1 Error::getCode() example

<?php
try {
    throw new Error("Some error message", 30);
} catch(Error $e) {
    echo "The Error code is: " . $e->getCode();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

The Error code is: 30

A se vedea ?i

  • Throwable::getCode() - Gets the exception code

Error::getPrevious
Error::getFile
Error


Gets the file in which the error occurred

Error::getCode
Error::getLine
Error
PHP Manual

Error::getFile

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

Error::getFile — Gets the file in which the error occurred

Descrierea

final public string Error::getFile ( void )

Get the name of the file the error occurred.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the filename in which the error occurred.

Exemple

Example #1 Error::getFile() example

<?php
try {
    throw new Error;
} catch(Error $e) {
    echo $e->getFile();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

/home/bjori/tmp/ex.php

A se vedea ?i

  • Throwable::getFile() - Gets the file in which the exception was created

Error::getCode
Error::getLine
Error


Gets the line in which the error occurred

Error::getFile
Error::getTrace
Error
PHP Manual

Error::getLine

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

Error::getLine — Gets the line in which the error occurred

Descrierea

final public int Error::getLine ( void )

Get line number where the error occurred.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the line number where the error occurred.

Exemple

Example #1 Error::getLine() example

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

Exemplul de mai sus va afi?a ceva similar cu:

The error was created on line: 3

A se vedea ?i

  • Throwable::getLine() - Gets the line on which the object was instantiated

Error::getFile
Error::getTrace
Error


Gets the stack trace

Error::getLine
Error::getTraceAsString
Error
PHP Manual

Error::getTrace

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

Error::getTrace — Gets the stack trace

Descrierea

final public array Error::getTrace ( void )

Returns the stack trace.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the stack trace as an array.

Exemple

Example #1 Error::getTrace() example

<?php
function test() {
 throw new Error;
}

try {
 test();
} catch(Error $e) {
 var_dump($e->getTrace());
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [0]=>
  array(4) {
    ["file"]=>
    string(22) "/home/bjori/tmp/ex.php"
    ["line"]=>
    int(7)
    ["function"]=>
    string(4) "test"
    ["args"]=>
    array(0) {
    }
  }
}

A se vedea ?i

  • Throwable::getTrace() - Gets the stack trace

Error::getLine
Error::getTraceAsString
Error


Gets the stack trace as a string

Error::getTrace
Error::__toString
Error
PHP Manual

Error::getTraceAsString

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

Error::getTraceAsString — Gets the stack trace as a string

Descrierea

final public string Error::getTraceAsString ( void )

Returns the stack trace as a string.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the stack trace as a string.

Exemple

Example #1 Error::getTraceAsString() example

<?php
function test() {
    throw new Error;
}

try {
    test();
} catch(Error $e) {
    echo $e->getTraceAsString();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}

A se vedea ?i

  • Throwable::getTraceAsString() - Gets the stack trace as a string

Error::getTrace
Error::__toString
Error


String representation of the error

Error::getTraceAsString
Error::__clone
Error
PHP Manual

Error::__toString

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

Error::__toString — String representation of the error

Descrierea

public string Error::__toString ( void )

Returns the string representation of the error.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the string representation of the error.

Exemple

Example #1 Error::__toString() example

<?php
try {
    throw new Error("Some error message");
} catch(Error $e) {
    echo $e;
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Error: Some error message in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}

A se vedea ?i

  • Throwable::__toString() - Gets a string representation of the thrown object

Error::getTraceAsString
Error::__clone
Error


Clone the error

Error::__toString
ArithmeticError
Error
PHP Manual

Error::__clone

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

Error::__clone — Clone the error

Descrierea

final private void Error::__clone ( void )

Error can not be clone, so this method results in fatal error.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Errors are not clonable.

Error::__toString
ArithmeticError
Error


ArithmeticError

(PHP 7)

Introducere

ArithmeticError is thrown when an error occurs while performing mathematical operations. In PHP 7.0, these errors include attempting to perform a bitshift by a negative amount, and any call to intdiv() that would result in a value outside the possible bounds of an integer.

Sinopsisul clasei

ArithmeticError extends Error {
/* Metode mo?tenite */
final public string Error::getMessage ( void )
final public Throwable Error::getPrevious ( void )
final public mixed Error::getCode ( void )
final public string Error::getFile ( void )
final public int Error::getLine ( void )
final public array Error::getTrace ( void )
final public string Error::getTraceAsString ( void )
public string Error::__toString ( void )
final private void Error::__clone ( void )
}
Error::__clone
AssertionError
Excep?ii predefinite


AssertionError

(PHP 7)

Introducere

AssertionError is thrown when an assertion made via assert() fails.

Sinopsisul clasei

AssertionError extends Error {
/* Metode mo?tenite */
final public string Error::getMessage ( void )
final public Throwable Error::getPrevious ( void )
final public mixed Error::getCode ( void )
final public string Error::getFile ( void )
final public int Error::getLine ( void )
final public array Error::getTrace ( void )
final public string Error::getTraceAsString ( void )
public string Error::__toString ( void )
final private void Error::__clone ( void )
}
ArithmeticError
DivisionByZeroError
Excep?ii predefinite


DivisionByZeroError

(PHP 7)

Introducere

DivisionByZeroError is thrown when an attempt is made to divide a number by zero.

Sinopsisul clasei

DivisionByZeroError extends ArithmeticError {
/* Metode mo?tenite */
final public string Error::getMessage ( void )
final public Throwable Error::getPrevious ( void )
final public mixed Error::getCode ( void )
final public string Error::getFile ( void )
final public int Error::getLine ( void )
final public array Error::getTrace ( void )
final public string Error::getTraceAsString ( void )
public string Error::__toString ( void )
final private void Error::__clone ( void )
}
AssertionError
ParseError
Excep?ii predefinite


ParseError

(PHP 7)

Introducere

ParseError is thrown when an error occurs while parsing PHP code, such as when eval() is called.

Sinopsisul clasei

ParseError extends Error {
/* Metode mo?tenite */
final public string Error::getMessage ( void )
final public Throwable Error::getPrevious ( void )
final public mixed Error::getCode ( void )
final public string Error::getFile ( void )
final public int Error::getLine ( void )
final public array Error::getTrace ( void )
final public string Error::getTraceAsString ( void )
public string Error::__toString ( void )
final private void Error::__clone ( void )
}
DivisionByZeroError
TypeError
Excep?ii predefinite


TypeError

(PHP 7)

Introducere

There are three scenarios where a TypeError may be thrown. The first is where the argument type being passed to a function does not match its corresponding declared parameter type. The second is where a value being returned from a function does not match the declared function return type. The third is where an invalid number of arguments are passed to a built-in PHP function (strict mode only).

Sinopsisul clasei

TypeError extends Error {
/* Metode mo?tenite */
final public string Error::getMessage ( void )
final public Throwable Error::getPrevious ( void )
final public mixed Error::getCode ( void )
final public string Error::getFile ( void )
final public int Error::getLine ( void )
final public array Error::getTrace ( void )
final public string Error::getTraceAsString ( void )
public string Error::__toString ( void )
final private void Error::__clone ( void )
}
ParseError
Interfe?e ?i clase predefinite
Excep?ii predefinite


Interfe?e ?i clase predefinite

Cuprins

  • Traversable
  • Iterator
  • IteratorAggregate
  • Throwable
  • ArrayAccess
  • Serializable
  • Closure
  • Generator

A se vedea de asemenea ?i interfe?e SPL ?i clase rezervate.

TypeError
Traversable
Informa?ii de referin?a despre limbaj


The Traversable interface

(PHP 5 >= 5.0.0, PHP 7)

Introducere

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.

Nota:

Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.

Nota:

This is an internal engine interface which cannot be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead. When implementing an interface which extends Traversable, make sure to list IteratorAggregate or Iterator before its name in the implements clause.

Descrierea succinta a interfe?ei

Traversable {
}

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

Interfe?e ?i clase predefinite
Iterator
Interfe?e ?i clase predefinite


The Iterator interface

(PHP 5 >= 5.0.0, PHP 7)

Introducere

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

Descrierea succinta a interfe?ei

Iterator extends Traversable {
/* Metode */
abstract public mixed current ( void )
abstract public scalar key ( void )
abstract public void next ( void )
abstract public void rewind ( void )
abstract public boolean valid ( void )
}

Predefined iterators

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

Exemple

Example #1 Basic usage

This example demonstrates in which order methods are called when using foreach with an iterator.

<?php
class myIterator implements Iterator {
    private $position = 0;
    private $array = array(
        "firstelement",
        "secondelement",
        "lastelement",
    );

    public function __construct() {
        $this->position = 0;
    }

    function rewind() {
        var_dump(__METHOD__);
        $this->position = 0;
    }

    function current() {
        var_dump(__METHOD__);
        return $this->array[$this->position];
    }

    function key() {
        var_dump(__METHOD__);
        return $this->position;
    }

    function next() {
        var_dump(__METHOD__);
        ++$this->position;
    }

    function valid() {
        var_dump(__METHOD__);
        return isset($this->array[$this->position]);
    }
}

$it = new myIterator;

foreach($it as $key => $value) {
    var_dump($key, $value);
    echo "\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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"

Cuprins

  • 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
Interfe?e ?i clase predefinite


Return the current element

Iterator
Iterator::key
Iterator
PHP Manual

Iterator::current

(PHP 5 >= 5.0.0, PHP 7)

Iterator::current — Return the current element

Descrierea

abstract public mixed Iterator::current ( void )

Returns the current element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Iterator::key — Return the key of the current element

Descrierea

abstract public scalar Iterator::key ( void )

Returns the key of the current element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns scalar on success, or NULL on failure.

Erori/Excep?ii

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

Iterator::next — Move forward to next element

Descrierea

abstract public void Iterator::next ( void )

Moves the current position to the next element.

Nota:

This method is called after each foreach loop.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Iterator::rewind — Rewind the Iterator to the first element

Descrierea

abstract public void Iterator::rewind ( void )

Rewinds back to the first element of the Iterator.

Nota:

This is the first method called when starting a foreach loop. It will not be executed after foreach loops.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Iterator::valid — Checks if current position is valid

Descrierea

abstract public boolean Iterator::valid ( void )

This method is called after Iterator::rewind() and Iterator::next() to check if the current position is valid.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The return value will be casted to boolean and then evaluated. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Iterator::rewind
IteratorAggregate
Iterator


The IteratorAggregate interface

(PHP 5 >= 5.0.0, PHP 7)

Introducere

Interface to create an external Iterator.

Descrierea succinta a interfe?ei

IteratorAggregate extends Traversable {
/* Metode */
abstract public Traversable getIterator ( void )
}

Example #1 Basic usage

<?php
class myData implements IteratorAggregate {
    public $property1 = "Public property one";
    public $property2 = "Public property two";
    public $property3 = "Public property three";

    public function __construct() {
        $this->property4 = "last property";
    }

    public function getIterator() {
        return new ArrayIterator($this);
    }
}

$obj = new myData;

foreach($obj as $key => $value) {
    var_dump($key, $value);
    echo "\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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"

Cuprins

  • IteratorAggregate::getIterator — Retrieve an external iterator
Iterator::valid
IteratorAggregate::getIterator
Interfe?e ?i clase predefinite


Retrieve an external iterator

IteratorAggregate
Throwable
IteratorAggregate
PHP Manual

IteratorAggregate::getIterator

(PHP 5 >= 5.0.0, PHP 7)

IteratorAggregate::getIterator — Retrieve an external iterator

Descrierea

abstract public Traversable IteratorAggregate::getIterator ( void )

Returns an external iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An instance of an object implementing Iterator or Traversable

Erori/Excep?ii

Throws an Exception on failure.

IteratorAggregate
Throwable
IteratorAggregate


Throwable

(PHP 7)

Introducere

Throwable is the base interface for any object that can be thrown via a throw statement in PHP 7, including Error and Exception.

Nota:

PHP classes cannot implement the Throwable interface directly, and must instead extend Exception.

Descrierea succinta a interfe?ei

Throwable {
/* Metode */
abstract public string getMessage ( void )
abstract public int getCode ( void )
abstract public string getFile ( void )
abstract public int getLine ( void )
abstract public array getTrace ( void )
abstract public string getTraceAsString ( void )
abstract public Throwable getPrevious ( void )
abstract public string __toString ( void )
}

Cuprins

  • Throwable::getMessage — Gets the message
  • Throwable::getCode — Gets the exception code
  • Throwable::getFile — Gets the file in which the exception was created
  • Throwable::getLine — Gets the line on which the object was instantiated
  • Throwable::getTrace — Gets the stack trace
  • Throwable::getTraceAsString — Gets the stack trace as a string
  • Throwable::getPrevious — Returns the previous Throwable
  • Throwable::__toString — Gets a string representation of the thrown object
IteratorAggregate::getIterator
Throwable::getMessage
Interfe?e ?i clase predefinite


Gets the message

Throwable
Throwable::getCode
Throwable
PHP Manual

Throwable::getMessage

(PHP 7)

Throwable::getMessage — Gets the message

Descrierea

abstract public string Throwable::getMessage ( void )

Returns the message associated with the thrown object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the message associated with the thrown object.

A se vedea ?i

  • Exception::getMessage() - Gets the Exception message

Throwable
Throwable::getCode
Throwable


Gets the exception code

Throwable::getMessage
Throwable::getFile
Throwable
PHP Manual

Throwable::getCode

(PHP 7)

Throwable::getCode — Gets the exception code

Descrierea

abstract public int Throwable::getCode ( void )

Returns the error code associated with the thrown object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

A se vedea ?i

  • Exception::getCode() - Gets the Exception code

Throwable::getMessage
Throwable::getFile
Throwable


Gets the file in which the exception was created

Throwable::getCode
Throwable::getLine
Throwable
PHP Manual

Throwable::getFile

(PHP 7)

Throwable::getFile — Gets the file in which the exception was created

Descrierea

abstract public string Throwable::getFile ( void )

Get the name of the file in which the exception was created.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the filename in which the exception was created.

A se vedea ?i

  • Exception::getFile() - Gets the file in which the exception was created

Throwable::getCode
Throwable::getLine
Throwable


Gets the line on which the object was instantiated

Throwable::getFile
Throwable::getTrace
Throwable
PHP Manual

Throwable::getLine

(PHP 7)

Throwable::getLine — Gets the line on which the object was instantiated

Descrierea

abstract public int Throwable::getLine ( void )

Returns the line number where the thrown object was instantiated.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the line number where the thrown object was instantiated.

A se vedea ?i

  • Exception::getLine() - Gets the line in which the exception was created

Throwable::getFile
Throwable::getTrace
Throwable


Gets the stack trace

Throwable::getLine
Throwable::getTraceAsString
Throwable
PHP Manual

Throwable::getTrace

(PHP 7)

Throwable::getTrace — Gets the stack trace

Descrierea

abstract public array Throwable::getTrace ( void )

Returns the stack trace as an array.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the stack trace as an array in the same format as debug_backtrace().

A se vedea ?i

  • Exception::getTrace() - Gets the stack trace

Throwable::getLine
Throwable::getTraceAsString
Throwable


Gets the stack trace as a string

Throwable::getTrace
Throwable::getPrevious
Throwable
PHP Manual

Throwable::getTraceAsString

(PHP 7)

Throwable::getTraceAsString — Gets the stack trace as a string

Descrierea

abstract public string Throwable::getTraceAsString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the stack trace as a string.

A se vedea ?i

  • Exception::getTraceAsString() - Gets the stack trace as a string

Throwable::getTrace
Throwable::getPrevious
Throwable


Returns the previous Throwable

Throwable::getTraceAsString
Throwable::__toString
Throwable
PHP Manual

Throwable::getPrevious

(PHP 7)

Throwable::getPrevious — Returns the previous Throwable

Descrierea

abstract public Throwable Throwable::getPrevious ( void )

Returns any previous Throwable (for example, one provided as the third parameter to Exception::__construct()).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the previous Throwable if available, or NULL otherwise.

A se vedea ?i

  • Exception::getPrevious() - Returns previous Exception

Throwable::getTraceAsString
Throwable::__toString
Throwable


Gets a string representation of the thrown object

Throwable::getPrevious
ArrayAccess
Throwable
PHP Manual

Throwable::__toString

(PHP 7)

Throwable::__toString — Gets a string representation of the thrown object

Descrierea

abstract public string Throwable::__toString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the string representation of the thrown object.

A se vedea ?i

  • Exception::__toString() - String representation of the exception

Throwable::getPrevious
ArrayAccess
Throwable


The ArrayAccess interface

(PHP 5 >= 5.0.0, PHP 7)

Introducere

Interface to provide accessing objects as arrays.

Descrierea succinta a interfe?ei

ArrayAccess {
/* Metode */
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 )
}

Example #1 Basic usage

<?php
class obj implements ArrayAccess {
    private $container = array();

    public function __construct() {
        $this->container = array(
            "one"   => 1,
            "two"   => 2,
            "three" => 3,
        );
    }

    public function offsetSet($offset, $value) {
        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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

)

Cuprins

  • ArrayAccess::offsetExists — Whether an offset exists
  • ArrayAccess::offsetGet — Offset to retrieve
  • ArrayAccess::offsetSet — Assign a value to the specified offset
  • ArrayAccess::offsetUnset — Unset an offset
Throwable::__toString
ArrayAccess::offsetExists
Interfe?e ?i clase predefinite


Whether an offset exists

ArrayAccess
ArrayAccess::offsetGet
ArrayAccess
PHP Manual

ArrayAccess::offsetExists

(PHP 5 >= 5.0.0, PHP 7)

ArrayAccess::offsetExists — Whether an offset exists

Descrierea

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.

Nota:

When using empty() ArrayAccess::offsetGet() will be called and checked if empty only if ArrayAccess::offsetExists() returns TRUE.

Parametri

offset

An offset to check for.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Nota:

The return value will be casted to boolean if non-boolean was returned.

Exemple

Example #1 ArrayAccess::offsetExists() example

<?php
class obj implements arrayaccess {
    public function offsetSet($offset, $value) {
        var_dump(__METHOD__);
    }
    public function offsetExists($var) {
        var_dump(__METHOD__);
        if ($var == "foobar") {
            return true;
        }
        return false;
    }
    public function offsetUnset($var) {
        var_dump(__METHOD__);
    }
    public function offsetGet($var) {
        var_dump(__METHOD__);
        return "value";
    }
}

$obj = new obj;

echo "Runs obj::offsetExists()\n";
var_dump(isset($obj["foobar"]));

echo "\nRuns obj::offsetExists() and obj::offsetGet()\n";
var_dump(empty($obj["foobar"]));

echo "\nRuns obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get\n";
var_dump(empty($obj["foobaz"]));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

ArrayAccess::offsetGet — Offset to retrieve

Descrierea

abstract public mixed ArrayAccess::offsetGet ( mixed $offset )

Returns the value at specified offset.

This method is executed when checking if offset is empty().

Parametri

offset

The offset to retrieve.

Note

Nota:

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.

Valorile întoarse

Can return all value types.

A se vedea ?i

  • ArrayAccess::offsetExists() - Whether an offset exists

ArrayAccess::offsetExists
ArrayAccess::offsetSet
ArrayAccess


Assign a value to the specified offset

ArrayAccess::offsetGet
ArrayAccess::offsetUnset
ArrayAccess
PHP Manual

ArrayAccess::offsetSet

(PHP 5 >= 5.0.0, PHP 7)

ArrayAccess::offsetSet — Assign a value to the specified offset

Descrierea

abstract public void ArrayAccess::offsetSet ( mixed $offset , mixed $value )

Assigns a value to the specified offset.

Parametri

offset

The offset to assign the value to.

value

The value to set.

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Nota:

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

Exemplul de mai sus va afi?a:

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

Nota:

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


Unset an offset

ArrayAccess::offsetSet
Serializable
ArrayAccess
PHP Manual

ArrayAccess::offsetUnset

(PHP 5 >= 5.0.0, PHP 7)

ArrayAccess::offsetUnset — Unset an offset

Descrierea

abstract public void ArrayAccess::offsetUnset ( mixed $offset )

Unsets an offset.

Nota:

This method will not be called when type-casting to (unset)

Parametri

offset

The offset to unset.

Valorile întoarse

Nu este întoarsa nici o valoare.

ArrayAccess::offsetSet
Serializable
ArrayAccess


The Serializable interface

(PHP 5 >= 5.1.0, PHP 7)

Introducere

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

Note, that when an old instance of a class that implements this interface now, which had been serialized before the class implemeted the interface, is unserialized, __wakeup() is called instead of the serialize method, which might be useful for migration purposes.

Descrierea succinta a interfe?ei

Serializable {
/* Metode */
abstract public string serialize ( void )
abstract public void unserialize ( string $serialized )
}

Example #1 Basic usage

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

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

var_dump($ser);

$newobj = unserialize($ser);

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

Exemplul de mai sus va afi?a ceva similar cu:

string(38) "C:3:"obj":23:{s:15:"My private data";}"
string(15) "My private data"

Cuprins

  • Serializable::serialize — String representation of object
  • Serializable::unserialize — Constructs the object
ArrayAccess::offsetUnset
Serializable::serialize
Interfe?e ?i clase predefinite


String representation of object

Serializable
Serializable::unserialize
Serializable
PHP Manual

Serializable::serialize

(PHP 5 >= 5.1.0, PHP 7)

Serializable::serialize — String representation of object

Descrierea

abstract public string Serializable::serialize ( void )

Should return the string representation of the object.

Nota:

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

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the string representation of the object or NULL

Erori/Excep?ii

Throws Exception when returning other types than strings and NULL.

A se vedea ?i

  • __sleep()

Serializable
Serializable::unserialize
Serializable


Constructs the object

Serializable::serialize
Closure
Serializable
PHP Manual

Serializable::unserialize

(PHP 5 >= 5.1.0, PHP 7)

Serializable::unserialize — Constructs the object

Descrierea

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

Called during unserialization of the object.

Nota:

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

Parametri

serialized

The string representation of the object.

Valorile întoarse

The return value from this method is ignored.

A se vedea ?i

  • __wakeup()

Serializable::serialize
Closure
Serializable


The Closure class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

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.

Sinopsisul clasei

Closure {
/* Metode */
private __construct ( void )
public static Closure bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] )
public Closure bindTo ( object $newthis [, mixed $newscope = "static" ] )
public mixed call ( object $newthis [, mixed $... ] )
}

Cuprins

  • 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
  • Closure::call — Binds and calls the closure
Serializable::unserialize
Closure::__construct
Interfe?e ?i clase predefinite


Constructor that disallows instantiation

Closure
Closure::bind
Closure
PHP Manual

Closure::__construct

(PHP 5 >= 5.3.0, PHP 7)

Closure::__construct — Constructor that disallows instantiation

Descrierea

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

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

A se vedea ?i

  • 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

(PHP 5 >= 5.4.0, PHP 7)

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

Descrierea

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.

Parametri

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. It is not allowed to pass (an object of) an internal class as this parameter.

Valorile întoarse

Returns a new Closure object sau FALSE în cazul e?ecului

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | newscope can not be (an object of) an internal class anymore, what was possible prior to this version.

Exemple

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

Exemplul de mai sus va afi?a ceva similar cu:

1
2

A se vedea ?i

  • 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
Closure::call
Closure
PHP Manual

Closure::bindTo

(PHP 5 >= 5.4.0, PHP 7)

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

Descrierea

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.

Nota:

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

Parametri

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.

Valorile întoarse

Returns the newly created Closure object sau FALSE în cazul e?ecului

Exemple

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

Exemplul de mai sus va afi?a ceva similar cu:

1
2

A se vedea ?i

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


Binds and calls the closure

Closure::bindTo
Generator
Closure
PHP Manual

Closure::call

(PHP 7)

Closure::call — Binds and calls the closure

Descrierea

public mixed Closure::call ( object $newthis [, mixed $... ] )

Temporarily binds the closure to newthis, and calls it with any given parameters.

Parametri

newthis

The object to bind the closure to for the duration of the call.

...

Zero or more parameters, which will be given as parameters to the closure.

Valorile întoarse

Returns the return value of the closure.

Exemple

Example #1 Closure::call() example

<?php
class Value {
    protected $value;

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

    public function getValue() {
        return $this->value;
    }
}

$three = new Value(3);
$four = new Value(4);

$closure = function ($delta) { var_dump($this->getValue() + $delta); };
$closure->call($three, 4);
$closure->call($four, 4);
?>

Exemplul de mai sus va afi?a:

int(7)
int(8)
Closure::bindTo
Generator
Closure


The Generator class

(PHP 5 >= 5.5.0, PHP 7)

Introducere

Generator objects are returned from generators.

Precautie

Generator objects cannot be instantiated via new.

Sinopsisul clasei

Generator implements Iterator {
/* Metode */
public mixed current ( void )
public mixed getReturn ( void )
public mixed key ( void )
public void next ( void )
public void rewind ( void )
public mixed send ( mixed $value )
public mixed throw ( Throwable $exception )
public bool valid ( void )
public void __wakeup ( void )
}

Cuprins

  • Generator::current — Get the yielded value
  • Generator::getReturn — Get the return value of a generator
  • Generator::key — Get the yielded key
  • Generator::next — Resume execution of the generator
  • Generator::rewind — Rewind the iterator
  • Generator::send — Send a value to the generator
  • Generator::throw — Throw an exception into the generator
  • Generator::valid — Check if the iterator has been closed
  • Generator::__wakeup — Serialize callback
Closure::call
Generator::current
Interfe?e ?i clase predefinite


Get the yielded value

Generator
Generator::getReturn
Generator
PHP Manual

Generator::current

(PHP 5 >= 5.5.0, PHP 7)

Generator::current — Get the yielded value

Descrierea

public mixed Generator::current ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the yielded value.

Generator
Generator::getReturn
Generator


Get the return value of a generator

Generator::current
Generator::key
Generator
PHP Manual

Generator::getReturn

(PHP 7)

Generator::getReturn — Get the return value of a generator

Descrierea

public mixed Generator::getReturn ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the generator's return value once it has finished executing.

Exemple

Example #1 Generator::getReturn() example

<?php

$gen = (function() {
    yield 1;
    yield 2;

    return 3;
})();

foreach ($gen as $val) {
    echo $val, PHP_EOL;
}

echo $gen->getReturn(), PHP_EOL;

Exemplul de mai sus va afi?a:

1
2
3

Generator::current
Generator::key
Generator


Get the yielded key

Generator::getReturn
Generator::next
Generator
PHP Manual

Generator::key

(PHP 5 >= 5.5.0, PHP 7)

Generator::key — Get the yielded key

Descrierea

public mixed Generator::key ( void )

Gets the key of the yielded value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the yielded key.

Exemple

Example #1 Generator::key() example

<?php

function Gen()
{
    yield 'key' => 'value';
}

$gen = Gen();

echo "{$gen->key()} => {$gen->current()}";

Exemplul de mai sus va afi?a:

key => value

Generator::getReturn
Generator::next
Generator


Resume execution of the generator

Generator::key
Generator::rewind
Generator
PHP Manual

Generator::next

(PHP 5 >= 5.5.0, PHP 7)

Generator::next — Resume execution of the generator

Descrierea

public void Generator::next ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Generator::key
Generator::rewind
Generator


Rewind the iterator

Generator::next
Generator::send
Generator
PHP Manual

Generator::rewind

(PHP 5 >= 5.5.0, PHP 7)

Generator::rewind — Rewind the iterator

Descrierea

public void Generator::rewind ( void )

If iteration has already begun, this will throw an exception.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Generator::next
Generator::send
Generator


Send a value to the generator

Generator::rewind
Generator::throw
Generator
PHP Manual

Generator::send

(PHP 5 >= 5.5.0, PHP 7)

Generator::send — Send a value to the generator

Descrierea

public mixed Generator::send ( mixed $value )

Sends the given value to the generator as the result of the current yield expression and resumes execution of the generator.

If the generator is not at a yield expression when this method is called, it will first be let to advance to the first yield expression before sending the value. As such it is not necessary to "prime" PHP generators with a Generator::next() call (like it is done in Python).

Parametri

value

Value to send into the generator. This value will be the return value of the yield expression the generator is currently at.

Valorile întoarse

Returns the yielded value.

Exemple

Example #1 Using Generator::send() to inject values

<?php
function printer() {
    echo "I'm printer!".PHP_EOL;
    while (true) {
        $string = yield;
        echo $string.PHP_EOL;
    }
}

$printer = printer();
$printer->send('Hello world!');
$printer->send('Bye world!');
?>

Exemplul de mai sus va afi?a:

I'm printer!
Hello world!
Bye world!

Generator::rewind
Generator::throw
Generator


Throw an exception into the generator

Generator::send
Generator::valid
Generator
PHP Manual

Generator::throw

(PHP 5 >= 5.5.0, PHP 7)

Generator::throw — Throw an exception into the generator

Descrierea

public mixed Generator::throw ( Throwable $exception )

Throws an exception into the generator and resumes execution of the generator. The behavior will be the same as if the current yield expression was replaced with a throw $exception statement.

If the generator is already closed when this method is invoked, the exception will be thrown in the caller's context instead.

Parametri

exception

Exception to throw into the generator.

Valorile întoarse

Returns the yielded value.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | The exception parameter also accepts Throwable now.

Exemple

Example #1 Throwing an exception into a generator

<?php
function gen() {
    echo "Foo\n";
    try {
        yield;
    } catch (Exception $e) {
        echo "Exception: {$e->getMessage()}\n";
    }
    echo "Bar\n";
}

$gen = gen();
$gen->rewind();
$gen->throw(new Exception('Test'));
?>

Exemplul de mai sus va afi?a:

Foo
Exception: Test
Bar

Generator::send
Generator::valid
Generator


Check if the iterator has been closed

Generator::throw
Generator::__wakeup
Generator
PHP Manual

Generator::valid

(PHP 5 >= 5.5.0, PHP 7)

Generator::valid — Check if the iterator has been closed

Descrierea

public bool Generator::valid ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns FALSE if the iterator has been closed. Otherwise returns TRUE.

Generator::throw
Generator::__wakeup
Generator


Serialize callback

Generator::valid
Context options and parameters
Generator
PHP Manual

Generator::__wakeup

(PHP 5 >= 5.5.0, PHP 7)

Generator::__wakeup — Serialize callback

Descrierea

public void Generator::__wakeup ( void )

Throws an exception as generators can't be serialized.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Generator::valid
Context options and parameters
Generator


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

Cuprins

  • 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
  • MongoDB context options — MongoDB context option listing
  • Context parameters — Context parameter listing
Generator::__wakeup
Socket context options
Informa?ii de referin?a despre limbaj


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

Descrierea

Socket context options are available for all wrappers that work over sockets, like tcp, http and ftp.

Op?iuni

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 for IPv4 addresses, and [ip]:port for IPv6 addresses. Setting the IP or the port to 0 will let the system choose the IP and/or port.

Nota:

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.

Nota:

This is only applicable to stream_socket_server().

ipv6_v6only

Overrides the OS default regarding mapping IPv4 into IPv6.

Nota:

This is important in particular when trying to listen on IPv4 addresses separately while there exists a binding on [::].

This is only applicable to stream_socket_server().

so_reuseport

Allows multiple bindings to a same ip:port pair, even from separate processes.

Nota:

This is only applicable to stream_socket_server().

so_broadcast

Enables sending and receiving data to/from broadcast addresses.

Nota:

This is only applicable to stream_socket_server().

Istoricul schimbarilor

Versiune | Descriere
7.0.1 | Added ipv6_v6only.
7.0.0 | Added so_broadcast.
7.0.0 | Added so_reuseport.
5.3.3 | Added backlog.
5.1.0 | Added bindto.

Exemple

Example #1 Basic bindto usage example

<?php
// connect to the internet using the '192.168.0.100' IP
$opts = array(
    'socket' => array(
        'bindto' => '192.168.0.100:0',
    ),
);

// connect to the internet using the '192.168.0.100' IP and port '7000'
$opts = array(
    'socket' => array(
        'bindto' => '192.168.0.100:7000',
    ),
);

// connect to the internet using the '2001:db8::1' IPv6 address
// and port '7000'
$opts = array(
    'socket' => array(
        'bindto' => '[2001:db8::1]: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

Descrierea

Context options for http:// and https:// transports.

Op?iuni

method string

GET, POST, or any other HTTP method supported by the remote server.

Defaults to GET.

header array or 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 header redirects. Set to 0 to disable.

Defaults to 1.

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.

Nota:

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.

Istoricul schimbarilor

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

Exemple

Example #1 Fetch a page and send POST data

<?php

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

Example #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);
?>

Note

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

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

A se vedea ?i

  • 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

Descrierea

Context options for ftp:// and ftps:// transports.

Op?iuni

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.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Added proxy.

Note

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

A se vedea ?i

  • 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

Descrierea

Context options for ssl:// and tls:// transports.

Op?iuni

peer_name string

Peer name to be used. If this value is not set, then the name is guessed based on the hostname used when opening the stream.

verify_peer boolean

Require verification of SSL certificate used.

Defaults to TRUE.

verify_peer_name boolean

Require verification of peer name.

Defaults to TRUE.

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. The private key also may be contained in a separate file specified by local_pk.

local_pk string

Path to local private key file on filesystem in case of separate files for certificate (local_cert) and private key.

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.

Nota: This option is deprecated, in favour of peer_name, as of PHP 5.6.0.

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.

Nota: This option is deprecated, in favour of peer_name, as of PHP 5.6.0.

disable_compression boolean

If set, disable TLS compression. This can help mitigate the CRIME attack vector.

peer_fingerprint string | array

Aborts when the remote certificate digest doesn't match the specified hash.

When a string is used, the length will determine which hashing algorithm is applied, either "md5" (32) or "sha1" (40).

When an array is used, the keys indicate the hashing algorithm name and each corresponding value is the expected digest.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Added peer_fingerprint and verify_peer_name. verify_peer default changed to TRUE.
5.4.13 | Added disable_compression. Requires OpenSSL >= 1.0.0.
5.3.2 | Added SNI_enabled and SNI_server_name.

Note

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

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

A se vedea ?i

  • 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

Descrierea

CURL context options are available when the CURL extension was compiled using the --with-curlwrappers configure option.

Op?iuni

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

Nota:

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

Nota:

This option is available for both the http and ftp protocol wrappers.

Exemple

Example #1 Fetch a page and send POST data

<?php

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

A se vedea ?i

  • Socket context options

SSL context options
Phar context options
Context options and parameters


Phar context option listing

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

Phar context options

Phar context options — Phar context option listing

Descrierea

Context options for phar:// wrapper.

Op?iuni

compress int

One of Phar compression constants.

metadata mixed

Phar metadata. See Phar::setMetadata().

A se vedea ?i

  • phar://
  • Phar stream wrapper

CURL context options
MongoDB context options
Context options and parameters


MongoDB context option listing

Phar context options
Context parameters
Context options and parameters
PHP Manual

MongoDB context options

MongoDB context options — MongoDB context option listing

Descrierea

Context options for mongodb:// transports.

Op?iuni

log_cmd_insert callable

A callback function called when inserting a document, see log_cmd_insert().

log_cmd_delete callable

A callback function called when deleting a document, see log_cmd_delete().

log_cmd_update callable

A callback function called when updating a document, see log_cmd_update().

log_write_batch callable

A callback function called when executing a Write Batch, see log_write_batch().

log_reply callable

A callback function called when reading a reply from MongoDB, see log_reply().

log_getmore callable

A callback function called when retrieving more results from a MongoDB cursor, see log_getmore().

log_killcursor callable

A callback function called executing a killcursor opcode, see log_killcursor().

Istoricul schimbarilor

Versiune | Descriere
pecl/mongo 1.5.0 | Added Write API Context options

A se vedea ?i

  • Socket context options
  • SSL context options

Phar context options
Context parameters
Context options and parameters


Context parameter listing

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

Context parameters

Context parameters — Context parameter listing

Descrierea

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

Parametri

notification callable

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

See stream_notification_callback for more details.

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

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

Cuprins

  • 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://
Informa?ii de referin?a despre limbaj


Accessing local filesystem

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

file://

file:// — Accessing local filesystem

Descrierea

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.

Utilizare

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

Op?iuni

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

Istoricul schimbarilor

Versiune | Descriere
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

Descrierea

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.

Utilizare

  • 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

Op?iuni

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

Istoricul schimbarilor

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

Exemple

Example #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);
    }

}

?>

Note

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

A se vedea ?i

  • 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

Descrierea

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.

Utilizare

  • 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

Op?iuni

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

Istoricul schimbarilor

Versiune | Descriere
4.3.0 | Added ftps://.

Note

Nota:

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.

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

A se vedea ?i

  • 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

Descrierea

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

Nota: Prior to PHP 5.6, a stream opened with php://input could only be read once; the stream did 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. Multiple filter chains can be specified on one 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.

Op?iuni

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.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | php://input was made reusable.
5.3.6 | php://fd was added.
5.1.0 | php://memory and php://temp were added.
5.0.0 | php://filter was added.

Exemple

Example #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);
?>

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

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

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

Example #5 php://memory and php://temp are not reusable

php://memory and php://temp and not reusable, i.e. after the streams have been closed there is no way to refer to them again.

file_put_contents('php://memory', 'PHP');
echo file_get_contents('php://memory'); // prints nothing
ftp://
zlib://
Supported Protocols and Wrappers


Compression Streams

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

zlib://

bzip2://

zip://

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

Descrierea

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.

Utilizare

  • compress.zlib://file.gz
  • compress.bzip2://file.bz2
  • zip://archive.zip#dir/file.txt

Op?iuni

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)

Descrierea

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

Utilizare

  • data://text/plain;base64,

Op?iuni

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

Exemple

Example #1 Print data:// contents

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

Example #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

Descrierea

The glob: stream wrapper is available since PHP 5.3.0.

Utilizare

  • glob://

Op?iuni

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

Exemple

Example #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

Descrierea

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

Utilizare

  • phar://

Op?iuni

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

A se vedea ?i

  • 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

Descrierea

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

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

Utilizare

  • 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

Op?iuni

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

Exemple

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

Example #2 This $session variable must be kept available!

In order to use the ssh2.*://$session wrappers you must keep the $session resouce variable. The code below will not have the desired effect:

<?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');
$connection_string = "ssh2.sftp://$session/";
unset($session);
$stream = fopen($connection_string . "path/to/file", 'r');
?>

unset() closes the session, because $connection_string does not hold a reference to the $session variable, just a string cast derived from it. This also happens when the unset() is implicit because of leaving scope (like in a function).

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


RAR

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

rar://

rar:// — RAR

Descrierea

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

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

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

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

Utilizare

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

Op?iuni

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

Exemple

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

Exemplul de mai sus va afi?a ceva similar cu:

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

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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)

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

Utilizare

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

Op?iuni

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

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

Exemple

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


Process Interaction Streams

ogg://
Securitatea
Supported Protocols and Wrappers
PHP Manual

expect://

expect:// — Process Interaction Streams

Descrierea

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

Nota: 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)

Utilizare

  • expect://command

Op?iuni

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

Exemple

ogg://
Securitatea
Supported Protocols and Wrappers


Securitatea

  • Introducere
  • General considerations
  • Instalat ca un binar CGI
    • Atacuri posibile
    • Cazul 1: numai fi?ierele publice sunt servite clientului
    • Cazul 2: utilizarea cgi.force_redirect
    • Cazul 3: stabilirea doc_root sau user_dir
    • Cazul 4: interpretorul PHP se afla în afara directorului radacina web
  • Instalat ca modul Apache
  • Session Security
  • Filesystem Security
    • Null bytes related issues
  • Securitatea Bazelor de Date
    • Designul bazelor de date
    • Conectarea la baza de date
    • Model de stocare criptata
    • Injectarea SQL
  • 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
  • Ascunderea PHP
  • Cea mai noua versiune
expect://
Introducere
Manualul PHP


Introducere

PHP este un limbaj de programare web puternic, iar interpretorul sau, fie ca este inclus în serverul web ca un modul, sau executat separat ca binar CGI, este capabil sa acceseze fi?iere, sa execute comenzi sau sa deschida conexiuni în re?ea pe server. Aceste proprieta?i fac ca totul ce este rulat pe server sa fie implicit nesecurizat. PHP a fost proiectat în mod specific pentru ca sa fie un limbaj mai securizat pentru scrierea programelor CGI decât Perl sau C, ?i cu o selectare corecta a op?iunilor de configurare la compilare ?i la rulare, dublate de o tehnica de programare corespunzatoare, PHP va poate oferi combina?ia perfecta de libertate ?i securitate de care ave?i nevoie.

Deoarece exista multe modalita?i diferite de a utiliza PHP, exista ?i multe op?iuni de configurare care îi controleaza comportamentul. O gama larga de op?iuni de configurare garanteaza posibilitatea utilizarii PHP pentru o întreaga suita de întrebuin?ari, dar aceasta totodata înseamna ca pot exista combina?ii ale acestor op?iuni ?i ale configura?iilor de servere, care vor duce la crearea unui mediu de execu?ie nesecurizat.

Flexibilitatea configura?iilor în PHP este egala ?i rivalizeaza cu flexibilitatea codului-sursa. PHP poate fi utilizat pentru a construi aplica?ii complete pentru servere, cu toate avantajele unui utilizator shell, sau poate fi utilizat ca o simpla incluziune de partea serverului cu grad de risc redus, într-un mediu bine controlat. Modul de construire a acestui mediu ?i cât de securizat este el depinde în mare masura de programatorul PHP.

Acest capitol începe cu câteva sfaturi generale în privin?a securita?ii, explica diferite combina?ii ale op?iunilor de configurare, precum ?i situa?iile în care pot fi folosite cu siguran?a; descrie de asemenea, diferite considera?ii legate de programare la diferite nivele de securitate.

Securitatea
General considerations
Securitatea


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.

Introducere
Instalat ca un binar CGI
Securitatea


Instalat ca un binar CGI

Cuprins

  • Atacuri posibile
  • Cazul 1: numai fi?ierele publice sunt servite clientului
  • Cazul 2: utilizarea cgi.force_redirect
  • Cazul 3: stabilirea doc_root sau user_dir
  • Cazul 4: interpretorul PHP se afla în afara directorului radacina web
General considerations
Atacuri posibile
Securitatea


Atacuri posibile

Utilizarea PHP în calitate de binar CGI este o op?iune pentru cazurile când dintr-un anume motiv nu se dore?te integrarea PHP în calitate de modul în serverul software (precum Apache), sau PHP se va utiliza cu diferite tipuri de înveli?uri CGI pentru a crea medii securizate cu ajutorul chroot ?i setuid pentru scripturi. Aceasta varianta implica de obicei instalarea binarului PHP executabil în directorul cgi-bin al serverului web. Îndrumarul CERT » CA-96.11 nu recomanda plasarea oricarui tip de interpretor de acest gen în directorul cgi-bin. Chiar daca binarul PHP poate fi folosit ca un interpretor de sine statator, PHP a fost conceput în a?a fel, încât sa previna atacuri, pe care o asemenea varianta de utilizare le face posibila:

  • Accesarea fi?ierelor din sistem: http://my.host/cgi-bin/php?/etc/passwd Informa?ia din URL de dupa semnul de întrebare (?) este transmisa interpretorului în calitate de argumente în linia de comanda de catre interfa?a CGI. De obicei interpretoarele deschid ?i executa fi?ierul specificat ca prim argument în linia de comanda. Când este apelat ca un binar CGI, PHP refuza sa interpreteze argumentele din linia de comanda.
  • Accesarea oricarui document web de pe server: http://my.host/cgi-bin/php/secret/doc.html Informa?iile introduse în URL dupa denumirea binarului PHP, /secret/doc.html sunt de obicei utilizate pentru a specifica denumirea ?i calea catre fi?ierul care trebuie deschis de catre interpretorul CGI. De obicei directivele din configura?ia unui server web (Apache: Action) sunt folosite pentru a redirec?iona interpelarile catre documente ca http://my.host/secret/script.php catre interpretorul PHP. În acest caz, serverul web verifica mai întâi permisiunile de acces catre directorul /secret, ?i dupa aceea creeaza interpelarea de redirec?ionare catre http://my.host/cgi-bin/php/secret/script.php. Cu regret, daca interpelarea este ini?ial scrisa în aceasta forma, serverul web nu efectueaza nici o verificare de acces catre fi?ierul /secret/script.php, ci numai catre fi?ierul /cgi-bin/php. În acest fel, orice utilizator care poate accesa fi?ierul /cgi-bin/php, poate accesa ?i orice document protejat de pe serverul web. În PHP, directivele de configurare în timpul rularii cgi.force_redirect, doc_root ?i user_dir pot fi utilizate pentru a preveni acest atac, daca arborele de documente de pe server con?ine directoare cu acces restric?ionat. Observa?i mai jos explica?ii detaliate despre diferite combina?ii.
Instalat ca un binar CGI
Cazul 1: numai fi?ierele publice sunt servite clientului
Instalat ca un binar CGI


Cazul 1: numai fi?ierele publice sunt servite clientului

Daca serverul dumneavoastra nu are nici un fel de con?inut (directoare / fi?iere) care este restric?ionat prin parola sau pe baza de IP, atunci nu este nevoie de aceste op?iuni de configurare. Daca serverul web nu va permite sa efectua?i redirec?ionari, sau nu poseda mijloace de a comunica binarului PHP ca interpelarea este redirec?ionata securizat, pute?i specifica op?iunea --enable-force-cgi-redirect scriptului de configurare. Totu?i trebuie sa va asigura?i ca scripturile dumneavoastra PHP nu se bazeaza pe una din metodele de apelare a scriptului - direct http://my.host/cgi-bin/php/dir/script.php sau prin redirec?ionare http://my.host/dir/script.php.

Redirec?ionarea poate fi configurata în Apache utilizând directivele AddHandler ?i Action (vezi mai jos).

Atacuri posibile
Cazul 2: utilizarea cgi.force_redirect
Instalat ca un binar CGI


Cazul 2: utilizarea cgi.force_redirect

Op?iunea de configurare cgi.force_redirect previne rularea unui script PHP direct printr-un URL gen http://my.host/cgi-bin/php/secretdir/script.php. PHP va ac?iona în acest mod numai daca a trecut printr-o regula de redirec?ionare a serverului web. PHP de versiune anterioara 4.2.0 utiliza pentru aceasta op?iunea la compilare --enable-force-cgi-redirect.

De obicei redirec?ionarea în configura?ia Apache se efectueaza cu ajutorul urmatoarelor directive:

Action php-script /cgi-bin/php
AddHandler php-script .php

Aceasta op?iune a fost testata numai cu serverul Apache, ?i se bazeaza pe setarea variabilei non-standard CGI REDIRECT_STATUS, pentru interpelarile redirec?ionate. Daca serverul dumneavoastra nu sus?ine nici o metoda de a determina daca interpelarea este directa sau redirec?ionata, nu pute?i folosi aceasta op?iune, ?i trebuie sa folosi?i alte cai de a rula versiunea CGI descrise aici.

Cazul 1: numai fi?ierele publice sunt servite clientului
Cazul 3: stabilirea doc_root sau user_dir
Instalat ca un binar CGI


Cazul 3: stabilirea doc_root sau user_dir

Includerea de con?inut activ, de pilda scripturi ?i executabile, în directoarele serverului web destinate documentelor este de multe ori considerata o metoda nesigura. Daca, din cauza unei gre?eli în configura?ie, scripturile nu sunt executate ci afi?ate ca documente HTML, aceasta va duce la dezvaluirea proprieta?ii intelectuale sau a informa?iei securizate, cum ar fi parolele. De aceea mul?i administratori de sistem configureaza o alta structura de directoare pentru scripturile care sunt accesibile numai prin PHP CGI, deci care vor fi întotdeauna interpretate ?i nu afi?ate direct.

De asemenea daca metoda de determinare a redirec?ionarii interpelarii, descrisa mai sus, nu este disponibila, atunci este necesara configurarea unui director doc_root pentru scripturi, care este diferit de cel pentru documente web.

Pute?i stabili directorul-radacina al scripturilor PHP prin directiva doc_root din fi?ierul de configura?ie, sau pute?i configura variabila de mediu PHP_DOCUMENT_ROOT. Daca este setata, versiunea CGI a PHP întotdeauna va construi denumirea fi?ierului astfel ca sa fie deschis cu acest doc_root ?i informa?iile despre cale din interpelare, de aceea pute?i fi sigur ca nici un script nu va fi executat în afara acestui director (excep?ie fiind user_dir de mai jos).

O alta op?iune folosita este user_dir. Când user_dir nu este configurat, singurul lucru care controleaza fi?ierul deschis este doc_root. Deschiderea unui URL ca http://my.host/~user/doc.php nu va rezulta în deschiderea unui fi?ier din directorul home al utilizatorului, ci a unui fi?ier numit ~user/doc.php din doc_root (da, un director a carui denumire începe cu tilda [~]).

Daca user_dir este configurat spre exemplu ca public_php, o interpelare de genul http://my.host/~user/doc.php va deschide un fi?ier numit doc.php din directorul numit public_php aflat în directorul home al utilizatorului "user". Daca directorul radacina al utilizatorului "user" este /home/user, fi?ierul executat este /home/user/public_php/doc.php.

Expansiunea user_dir se petrece independent de setarea doc_root, deci pute?i controla accesul la directorul radacina ?i la directoarele utilizatorilor în mod separat.

Cazul 2: utilizarea cgi.force_redirect
Cazul 4: interpretorul PHP se afla în afara directorului radacina web
Instalat ca un binar CGI


Cazul 4: interpretorul PHP se afla în afara directorului radacina web

O metoda foarte sigura este de a plasa binarul interpretorului PHP undeva în afara arborelui fi?ierelor pentru web. În /usr/local/bin, spre exemplu. Singurul dezavantaj al acestei op?iuni este ca trebuie sa introduce?i urmatoarea linie:

#!/usr/local/bin/php
la începutul fiecarui fi?ier care con?ine tag-uri PHP. De asemenea va trebui sa face?i fi?ierul executabil. Adica trata?i-l exact ca pe un script CGI scris în Perl, sau sh, sau orice alt limbaj de scripting care utilizeaza mecanismul #! de evadare din înveli?ul sistemului pentru a se lansa.

Pentru ca PHP sa utilizeze informa?iile din PATH_INFO ?i PATH_TRANSLATED în mod corect, interpretorul PHP trebuie compilat cu op?iunea de configurare --enable-discard-path.

Cazul 3: stabilirea doc_root sau user_dir
Instalat ca modul Apache
Instalat ca un binar CGI


Instalat ca modul Apache

Când PHP este utilizat ca modul în Apache, el mo?tene?te permisiunile implicite ale Apache (de obicei acelea ale utilizatorului "nobody"). Acest fapt are mai multe impacte asupra securita?ii ?i autorizarii. De exemplu, daca utiliza?i PHP pentru a accesa o baza de date, ?i daca aceasta nu are control de acces inclus, va trebui sa faceti aceasta baza de date sa fie accesibila utilizatorului "nobody". Aceasta înseamna ca un script malefic va putea accesa ?i modifica baza de date chiar fara a introduce numele utilizatorului ?i parola. Este posibil ca un robot de indexare web sa acceseze accidental panoul de administrare al bazei de date ?i sa modifice sau sa ?tearga toate datele. Va pute?i proteja cu ajutorul sistemului de autorizare al Apache, sau printr-un model de acces personalizat folosind LDAP, fi?iere tip .htaccess, etc. pe care sa le introduce?i în scripturile PHP create.

Adesea, dupa ce politica de securitate a fost stabilita, iar utilizatorul PHP (în acest caz, utilizatorul Apache) prezinta risc redus fa?a de sistem, iese la iveala faptul ca PHP este restric?ionat în a scrie în fi?ierele ?i directoarele utilizatorilor, sau nu poate accesa ?i schimba anumite baze de date. El a fost securizat atât în a scrie fi?iere bune, cât ?i rele, sau inserarea de tranzac?ii atât benefice, cât ?i daunatoare bazelor de date.

O gre?eala de securitate frecventa este ca atunci când se ajunge în acest moment, sa se dea permisiuni de root serverului Apache, sau sa se extinda permisiunile într-un careva alt mod.

Extinderea privilegiilor utilizatorului Apache catre root este deosebit de periculoasa ?i poate duce la compromiterea întregului sistem, a?a ca opera?iunile 'sudo', 'chroot', sau alte modalita?i de a rula root nu ar trebui luate în considerare în caz ca nu sunte?i expert în securitare.

Exista ?i solu?ii mai simple. Utilizând open_basedir pute?i controla ?i restric?iona ce directorii dori?i, în care poate avea acces PHP. În plus pute?i stabili zone numai pentru Apache, pentru a preveni toate ac?iunile din web asupra fi?ierelor utilizatorilor ?i de sistem.

Cazul 4: interpretorul PHP se afla în afara directorului radacina web
Session Security
Securitatea


Session Security

It is important keeping HTTP session mangement secure. Session releated security is described in Session Security section of Session module reference.

Instalat ca modul Apache
Filesystem Security
Securitatea


Filesystem Security

Cuprins

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

Example #1 Poor variable checking leads to....

<?php
// remove a file from the user's home directory
$username = $_POST['user_submitted_name'];
$userfile = $_POST['user_submitted_filename'];
$homedir  = "/home/$username";

unlink("$homedir/$userfile");

echo "The file has been deleted!";
?>
Since the username and the filename are postable from a user form, they can submit a username and a filename belonging to someone else, and delete it even if they're not supposed to be allowed to do so. In this case, you'd want to use some other form of authentication. Consider what could happen if the variables submitted were "../etc/" and "passwd". The code would then effectively read:

Example #2 ... A filesystem attack

<?php
// removes a file from anywhere on the hard drive that
// the PHP user has access to. If PHP has root access:
$username = $_POST['user_submitted_name']; // "../etc"
$userfile = $_POST['user_submitted_filename']; // "passwd"
$homedir  = "/home/$username"; // "/home/../etc"

unlink("$homedir/$userfile"); // "/home/../etc/passwd"

echo "The file has been deleted!";
?>
There are two important measures you should take to prevent these issues.
  • Only allow limited permissions to the PHP web user binary.
  • Check all variables which are submitted.
Here is an improved script:

Example #3 More secure file name checking

<?php
// removes a file from the hard drive that
// the PHP user has access to.
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanism
$userfile = basename($_POST['user_submitted_filename']);
$homedir  = "/home/$username";

$filepath = "$homedir/$userfile";

if (file_exists($filepath) && unlink($filepath)) {
    $logstring = "Deleted $filepath\n";
} else {
    $logstring = "Failed to delete $filepath\n";
}
$fp = fopen("/home/logging/filedelete.log", "a");
fwrite($fp, $logstring);
fclose($fp);

echo htmlentities($logstring, ENT_QUOTES);

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

Example #4 More secure file name checking

<?php
$username     = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$userfile     = $_POST['user_submitted_filename'];
$homedir      = "/home/$username";

$filepath     = "$homedir/$userfile";

if (!ctype_alnum($username) || !preg_match('/^(?:[a-z0-9_-]|\.(?!\.))+$/iD', $userfile)) {
    die("Bad username/filename");
}

//etc...
?>

Depending on your operating system, there are a wide variety of files which you should be concerned about, including device entries (/dev/ or COM1), configuration files (/etc/ files and the .ini files), well known file storage areas (/home/, My Documents), etc. For this reason, it's usually easier to create a policy where you forbid everything except for what you explicitly allow.

Session Security
Null bytes related issues
Securitatea


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:

Example #1 Script vulnerable to null bytes

<?php
$file = $_GET['file']; // "../../etc/passwd\0"
if (file_exists('/home/wwwrun/'.$file.'.php')) {
    // file_exists will return true as the file /home/wwwrun/../../etc/passwd exists
    include '/home/wwwrun/'.$file.'.php';
    // the file /etc/passwd will be included
}
?>

Therefore, any tainted string that is used in a filesystem operation should always be validated properly. Here is a better version of the previous example:

Example #2 Correctly validating the input

<?php
$file = $_GET['file'];

// Whitelisting possible values
switch ($file) {
    case 'main':
    case 'foo':
    case 'bar':
        include '/home/wwwrun/include/'.$file.'.php';
        break;
    default:
        include '/home/wwwrun/include/main.php';
}
?>
Filesystem Security
Securitatea Bazelor de Date
Filesystem Security


Securitatea Bazelor de Date

Cuprins

  • Designul bazelor de date
  • Conectarea la baza de date
  • Model de stocare criptata
  • Injectarea SQL

În zilele noastre, bazele de date sunt componente esen?iale ale aplica?iilor web, dând posibilitate acestora de a servi con?inut dinamic. Datorita faptului ca informa?ii secrete sau cu caracter confiden?ial se stocheaza adesea într-o baza de date, va trebui sa lua?i în considerare protejarea bazelor de date.

Pentru a primi sau trimite orice informa?ie, trebuie sa va conecta?i la baza de date, sa trimite?i o interpelare valida, sa prelua?i rezultatele ?i sa închide?i conexiunea. Recent, cel mai folosit limbaj query pentru asemenea tip de interac?iune este Structured Query Language (SQL). Vede?i cum un atacator poate sa manipuleze o interpelare SQL.

Dupa cum probabil a?i presupus, PHP nu va poate proteja bazele de date în sine. Urmatoarele sec?iuni tind sa fie o introducere în no?iunile de baza ale accesarii ?i manipularii bazelor de date cu scripturi PHP.

Pastra?i în minte urmatoarea regula: securitate maxima. Cu cât cre?te?i masurile de protec?ie asupra bazelor de date, cu atât mai mica este probabilitatea ca un atacator sa reu?easca sa sustraga date importante sau sa abuzeze de ele. Încerca?i ca structura ?i designul bazei de date sa fie cât mai eficiente, dupa care va pute?i pune problemele legate de securitate.

Null bytes related issues
Designul bazelor de date
Securitatea


Designul bazelor de date

Primul pas este întotdeauna crearea bazei de date, doar daca nu dori?i sa utiliza?i o baza de date creata de altcineva. Când o baza de date este creata, ea este desemnata unui anume utilizator, care a executat comanda de creare. În general, numai proprietarul (sau superuserul) pot face orice cu obiectele din acea baza de date, iar pentru a lasa ?i al?i utilizatori sa o foloseasca, ei trebuie sa aiba privilegii.

Aplica?iile pe care le construi?i nu ar trebui sa se conecteze niciodata la o baza de date cu privilegii de administrator sau superuser, pentru ca ace?ti utilizatori pot executa orice fel de query, de exemplu, modificarea schemei (?tergerea tabelelor) sau ?tergerea întregului con?inut.

Pute?i crea diferi?i utilizatori de baze de date pentru fiecare aspect al aplica?iei, cu drepturi la obiectele bazei strict delimitate. Se pot da numai privilegiile strict necesare, ?i evita?i ca acela?i user sa interac?ioneze cu mai multe baze de date. Aceasta înseamna ca daca un intrus va capata acces la baza de date din numele aplica?iei dumneavoastra, acesta va putea face doar opera?iunile, pe care le poate face aplica?ia dumneavoastra.

Se recomanda sa nu implementa?i toata business-logica în aplica?ia web (de ex. în script-ul dumneavoastra). În loc, realiza?i aceasta în schema bazei de date utilizând viziuni, trigger-e sau reguli. Daca sistemul va evolua, va aparea necesitatea de a deschide noi porturi la baza de date ?i va trebui sa reimplementa?i logica separat în fiecare client al bazei de date. Or, trigger-e pot fi utilizate pentru a manipula câmpuri în mod transparent ?i automat, ceea ce deseori va ajuta la depistarea problemelor în aplica?ie, sau la regasirea tranzac?iilor.

Securitatea Bazelor de Date
Conectarea la baza de date
Securitatea Bazelor de Date


Conectarea la baza de date

Pute?i sa va conecta?i la baza de date folosind encrip?ia SSL pentru a spori siguran?a datelor, sau pute?i folosi ssh pentru a cripta datele dintre clien?ii din re?ea ?i serverul de baze de date. Daca este folosita una dintre aceste metode, atunci interceptarea traficului ?i accesul la informa?iile sensibile despre bazele de date ar fi foarte dificila pentru un atacator.

Designul bazelor de date
Model de stocare criptata
Securitatea Bazelor de Date


Model de stocare criptata

SSL/SSH protejeaza traversarea datelor de la client la server, însa SSL/SSH nu protejeaza datele stocate în baza de date. SSL este un protocol de tranzit.

Odata ce atacatorul capata acces la baza de date direct (evitând serverul web), informa?ia stocata poate fi expusa sau abuzata, daca ea nu este protejata de însa?i baza de date. Criptarea datelor este o buna masura pentru a diminua acest risc, însa prea pu?ine baze de date ofera acest tip de criptare.

Cea mai u?oara cale de a rezolva problema este de a crea propriul pachet de criptare, ?i apoi folosirea lui cu scripturile PHP. PHP va poate ajuta în aceasta prin intermediul câtorva extensii, cum ar fi Mcrypt ?i Mhash, care acopera o varietate larga de algoritmi de criptare. Scriptul cripteaza datele înainte de a fi inserate în baza de date, ?i le decripteaza la extragerea acestora. Verifica?i documenta?ia de rigoare pentru a studia mai multe despre modalita?ile de operare ale criptarii.

Hashing

În cazul datelor cu adevarat ascunse, daca reprezentarea lor deschisa nu este necesara (de ex. nu vor fi afi?ate), ar trebui luata în considerare procedura de hashing. Cel mai cunoscut exemplu este stocarea hash-ului criptografic al unei parole în baza de date, în loc de stocarea parolei înse?i.

În PHP 5.5 sau ulterior func?iile de lucru cu parole ofera o metoda comoda de a transforma în hash date confiden?iale ?i de a lucra mai departe cu aceste hash-uri. În PHP 5.3.7+ poate fi utilizata ?i biblioteca » password_compat.

password_hash() este utilizata pentru a transforma în hash un ?ir de caractere dat utilizând cel mai puternic algoritm disponibil la moment, ?i password_verify() verifica daca o parola data se potrive?te hash-ului stocat în baza de date.

Example #1 Transformarea parolei în hash

<?php

// storing password hash
$query  = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            pg_escape_string($username),
            password_hash($password, PASSWORD_DEFAULT));
$result = pg_query($connection, $query);

// querying if user submitted the right password
$query = sprintf("SELECT pwd FROM users WHERE name='%s';",
            pg_escape_string($username));
$row = pg_fetch_assoc(pg_query($connection, $query));

if ($row && password_verify($password, $row['pwd'])) {
    echo 'Welcome, ' . htmlspecialchars($username) . '!';
} else {
    echo 'Authentication failed for ' . htmlspecialchars($username) . '.';
}

?>

În versiuni mai vechi ale PHP aceasta poate fi ob?inut cu ajutorul func?iei crypt().

Example #2 Transformarea parolei în hash utilizând crypt()

<?php

// storing password hash
// $random_chars retrieved e.g. using /dev/random
$query  = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            pg_escape_string($username),
            pg_escape_string(crypt($password, '$2a$07$' . $random_chars . '$')));
$result = pg_query($connection, $query);

// querying if user submitted the right password
$query = sprintf("SELECT pwd FROM users WHERE name='%s';",
            pg_escape_string($username));
$row = pg_fetch_assoc(pg_query($connection, $query));

if ($row && crypt($password, $row['pwd']) == $row['pwd']) {
    echo 'Welcome, ' . htmlspecialchars($username) . '!';
} else {
    echo 'Authentication failed for ' . htmlspecialchars($username) . '.';
}

?>
Conectarea la baza de date
Injectarea SQL
Securitatea Bazelor de Date


Injectarea SQL

Mul?i developeri web nu ?tiu cum pot fi manipulate interpelarile SQL, ?i acorda toata încrederea unei asemenea comenzi. Interpelarile SQL pot ocoli controalele de acces, în consecin?a sa treaca peste metodele de autentificare ?i verificarile de autoriza?ie, iar câteodata pot chiar sa faciliteze accesul la comenzile de sistem.

Injectarea directa a comenzilor SQL este o tehnica în care atacatorul creeaza sau modifica comenzile SQL pentru a scoate la iveala datele sensibile, sau pentru a suprascrie o anumita valoare, sau chiar pentru a executa comenzi periculoase la nivel de sistem. Acest lucru este înfaptuit de catre aplica?ia care preia inputul utilizatorului, îl combina cu parametrii statici pentru a forma o interpelare SQL. Urmatoarele exemple sunt bazate pe cazuri reale, cu regret.

Datorita lipsei validarii inputului ?i conectarii la baza de date cu drepturi de superuser, sau a unui user care poate crea la rândul lui al?i useri, atacatorul poate crea un superuser în baza de date.

Example #1 Împar?irea rezultatelor în mai multe pagini ... ?i crearea de superuseri (PostgreSQL)

<?php

$offset = argv[0]; // atentie, nu se face validarea inputului!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);

?>
Utilizatorii obi?nui?i fac click pe linkurile 'next', 'prev' unde variabila $offset este encodata în URL. Scriptul se a?teapta ca variabila $offset sa fie un numar zecimal. Cu toate acestea, ce se întâmpla daca cineva încearca sa intervina, adaugând la URL urmatoarele date prelucrate cu func?ia urlencode():
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--
Daca se executa, atunci scriptul va permite modificarea parolei superuser-ului. Observa?i ca 0; este pentru a oferi un offset corect interpelarii originale ?i pentru a o termina.

Nota:

Este o tehnica obi?nuita de a for?a parserul SQL sa ignore restul interpelarii scrise de developer, cu ajutorul --, care este simbolul pentru comentariu în SQL.

O reala posibilitate de a afla parole este de a manipula rezultatele din paginile de cautare. Singurul lucru de care are nevoie atacatorul este sa vada daca exista variabile în declara?iile SQL care nu sunt protejate corespunzator. Se pot manipula variabilele din formularele care utilizeaza WHERE, ORDER BY, LIMIT sau condi?iile OFFSET din declara?iile SELECT. Daca baza de date suporta construc?ii UNION, atacatorul poate încerca sa lipeasca o interpelare întreaga la cea originala pentru a lista parolele dintr-un tabel arbitrar. Folosirea parolelor criptate este pe deplin încurajata.

Example #2 Listarea unor articole ... ?i a unor parole (orice server de baze de date)

<?php

$query  = "SELECT id, name, inserted, size FROM products
                  WHERE size = '$size'";
$result = odbc_exec($conn, $query);

?>
Partea statica a interpelarii poate fi combinata cu înca un SELECT care sa arate parolele:
'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--
Daca aceasta interpelare (ne-am jucat cu ' ?i --) ar fi fost atribuita unei variabile utilizate la formarea $query, am fi dat de belea.

Comanda SQL UPDATE nu este nici ea ocolita de probleme. Aceste interpelari sunt amenin?ate de atacurile prin taierea ?i alipirea unei noi interpelari. În plus, atacatorul se mai poate juca ?i cu declara?ia SET. În acest caz, atacatorul trebuie sa cunoasca careva informa?ii despre schema, de ex. structura tabelului din care dore?te sa extraga sau sa manipuleze informa?ia. Acest lucru poate fi facut prin examinarea denumirilor variabilelor din formulare, sau prin procedeul brute-force. Nu exista multe conven?ii prin care se delimiteaza câmpurile pentru user sau parola.

Example #3 De la resetarea unei parole ... pâna la ob?inerea mai multor privilegii (orice server de baze de date)

<?php
$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?>
Însa un utilizator rau voit poate introduce ' or uid like'%admin% în $uid pentru a schimba parola utilizatorului admin, sau pur ?i simplu seteaza valoarea $pwd în hehehe', trusted=100, admin='yes pentru a ob?ine mai multe privilegii. În acest caz interpelarea ar arata în felul urmator:
<?php

// $uid: ' or uid like '%admin%
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%';";

// $pwd: hehehe', trusted=100, admin='yes
$query = "UPDATE usertable SET pwd='hehehe', trusted=100, admin='yes' WHERE
...;";

?>

Un exemplu înspaimântator despre cum pot fi rulate comenzi la nivel de sistem de operare pe unele servere de baze de date.

Example #4 Atacarea sistemului de operare pe care lucreaza baza de date (MSSQL Server)

<?php

$query  = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);

?>
Daca un atacator introduce valoarea a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- în loc de $prod, atunci $query va deveni:
<?php

$query  = "SELECT * FROM products
           WHERE id LIKE '%a%'
           exec master..xp_cmdshell 'net user test testpass /ADD'--";
$result = mssql_query($query);

?>
Serverul MSSQL executa interpelarea SQL incluzând ?i comanda de adaugare a unui user nou în baza de date cu conturi locale. Daca aceasta aplica?ie rula ca sa ?i serviciul MSSQLSERVER rula cu destule privilegii, atacatorul avea acum un cont pe serverul respectiv unde sa execute comenzi.

Nota:

Unele dintre exemplele de mai sus sunt legate de anumite servere de baze de date. Acest lucru nu înseamna ca atacuri similare nu pot avea loc asupra altor produse similare lor. Serverul dumneavoastra de baze de date poate fi vulnerabil într-o maniera asemanatoare.

Un exemplu amuzant legat de probleme cu injectari SQL
Imagine oferita de » xkcd

Tehnici de evitare

Cu toate ca este evident ca un atacator trebuie sa posede cel pu?in careva cuno?tin?e în privin?a arhitecturii bazei de date pentru a desfa?ura un atac cu succes, ob?inerea acestei informa?ii este deseori foarte simpla. Spre exemplu, daca o baza de date face parte dintr-un pachet software cu sursa deschisa, sau disponibila publicului larg, cu o instalare implicita, aceasta informa?ie este absolut deschisa ?i disponibila tuturor. Aceasta informa?ie poate de asemenea sa fie divulgata de un cod-sursa închis - chiar daca este codificat, camuflat sau compilat - ?i chiar de propriul dumneavoastra cod prin afi?area mesajelor de eroare. Alte metode includ utilizarea numelor raspândite pentru tabele ?i coloane. Spre exemplu, un formular de login care utilizeaza un tabel 'users' cu denumirile coloanelor 'id', 'username' ?i 'password'.

Aceste atacuri sunt de obicei bazate pe exploatarea codului scris de developeri fara a lua în calcul securitatea lui. Niciodata nu ave?i încredere în nici un fel de input, mai ales când acesta provine din partea clientului, chiar daca acesta vine dintr-un câmp select, câmp ascuns sau cookie. Primul exemplu arata ca o interpelare aparent nevinovata poate cauza un dezastru.

  • Niciodata nu va conecta?i la baza de date ca superuser sau ca orice alt utilizator care poate manipula mai multe baze de date decât cea folosita. Folosi?i întotdeauna useri cu privilegii limitate.
  • Utiliza?i interpelari preparate cu variabile ata?ate. Ele sunt oferite de PDO, de MySQLi ?i de alte biblioteci.
  • Verifica?i daca un input con?ine tipul de date corect. PHP are o varietate de func?ii de validare, de la cele mai simple, care pot fi gasite în Func?ii asupra variabilelor ?i în Func?ii ale tipurilor de caractere (de ex. is_numeric(), ctype_digit() respectiv) ?i pâna la Expresii regulate compatibile Perl.

  • Daca aplica?ia a?teapta un input numeric, încerca?i sa verifica?i datele cu func?ia ctype_digit(), sau schimba?i tipul variabilei utilizând func?ia settype(), sau folosi?i reprezenta?ia numerica prin sprintf().

    Example #5 O metoda mai sigura de formare a interpelarii pentru paginare

    <?php

    settype    ($offset, 'integer');
    $query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";

    // observa?i %d (care înseamna formatul integer) din string-ul de formatare,
    // folosirea %s (string) ar fi fara sens
    $query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
                         $offset);

    ?>

  • Daca nivelul bazei de date nu sus?ine ata?area variabilelor, atunci filtra?i fiecare valoare non-numerica furnizata de utilizator transmisa bazei de date cu ajutorul func?iei 'string escape' specifica fiecarei baze de date (de ex. mysql_real_escape_string(), sqlite_escape_string(), etc.). Func?ii generice precum addslashes() sunt utile doar în medii foarte specifice (de. ex. MySQL cu un set de caractere single-byte cu op?iunea NO_BACKSLASH_ESCAPES deconectata), de aceea este mai bine sa fie evitate.
  • Nu afi?a?i informa?ii specifice bazei de date, în special despre schema acesteia. Vede?i de asemenea Raportarea erorilor ?i Prelucrarea erorilor ?i func?ii de logare.
  • Pute?i utiliza proceduri stocate ?i cursoare de date predefinite pentru a abstractiza accesul la date, pentru ca utilizatorii sa nu interac?ioneze direct cu tabelele sau viziunile, dar aceasta solu?ie poate avea alte consecin?e.

În afara de acestea, pute?i loga interpelarile în interiorul scriptului ?i în baza de date, daca aceasta sus?ine acest lucru. Bineîn?eles, logarea nu poate preveni atacurile sau încercarile de a vatama baza de date, dar poate fi utila în depistarea aplica?iei în care a avut loc incidentul. Log-ul nu este util prin sine, ci prin informa?ia pe care o con?ine. Mai multa detaliere este de obicei mai buna decât lipsa detaliilor.

Model de stocare criptata
Error Reporting
Securitatea Bazelor de Date


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:

Example #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:

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

Example #3 Finding dangerous variables with E_ALL

<?php
if ($username) {  // Not initialized or checked before usage
    $good_login = 1;
}
if ($good_login == 1) { // If above test fails, not initialized or checked before usage
    readfile ("/highly/sensitive/data/index.html");
}
?>

Injectarea SQL
Using Register Globals
Securitatea


Using Register Globals

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

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

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

Example #1 Example misuse with register_globals = on

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

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

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

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

Example #2 Example use of sessions with register_globals on or off

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

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

} else {

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

}
?>

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

Example #3 Detecting simple variable poisoning

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

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

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

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

} else {

   // MAGIC_COOKIE isn't set through this REQUEST

}
?>

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

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

Error Reporting
User Submitted Data
Securitatea


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.

Example #1 Dangerous Variable Usage

<?php
// remove a file from the user's home directory... or maybe
// somebody else's?
unlink ($evil_var);

// Write logging of their access... or maybe an /etc/passwd entry?
fwrite ($fp, $evil_var);

// Execute something trivial.. or rm -rf *?
system ($evil_var);
exec ($evil_var);

?>

You should always carefully examine your code to make sure that any variables being submitted from a web browser are being properly checked, and ask yourself the following questions:

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


Magic Quotes

Cuprins

  • What are Magic Quotes
  • Why did we use Magic Quotes
  • Why not to use Magic Quotes
  • Disabling Magic Quotes
Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

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

User Submitted Data
What are Magic Quotes
Securitatea


What are Magic Quotes

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

When on, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically. This is identical to what addslashes() does.

There are three magic quote directives:

  • magic_quotes_gpc Affects HTTP Request data (GET, POST, and COOKIE). Cannot be set at runtime, and defaults to on in PHP. See also get_magic_quotes_gpc().
  • magic_quotes_runtime If enabled, most functions that return data from an external source, including databases and text files, will have quotes escaped with a backslash. Can be set at runtime, and defaults to off in PHP. See also set_magic_quotes_runtime() and get_magic_quotes_runtime().
  • magic_quotes_sybase If enabled, a single-quote is escaped with a single-quote instead of a backslash. If on, it completely overrides magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NULL's will remain untouched and unescaped. See also ini_get() for retrieving its value.
Magic Quotes
Why did we use Magic Quotes
Magic Quotes


Why did we use Magic Quotes

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

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


Why not to use Magic Quotes

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

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

Example #1 Disabling magic quotes server side

An example that sets the value of these directives to Off in php.ini. For additional details, read the manual section titled How to change configuration settings.

; Magic quotes
;

; Magic quotes for incoming GET/POST/Cookie data.
magic_quotes_gpc = Off

; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.
magic_quotes_runtime = Off

; Use Sybase-style magic quotes (escape ' with '' instead of \').
magic_quotes_sybase = Off

If access to the server configuration is unavailable, use of .htaccess is also an option. For example:

php_flag magic_quotes_gpc Off

In the interest of writing portable code (code that works in any environment), like if setting at the server level is not possible, here's an example to disable magic_quotes_gpc at runtime. This method is inefficient so it's preferred to instead set the appropriate directives elsewhere.

Example #2 Disabling magic quotes at runtime

<?php
if (get_magic_quotes_gpc()) {
    $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
Ascunderea PHP
Magic Quotes


Ascunderea PHP

În general, securitatea prin obscuritate este una dintre cele mai slabe forme de securitate. Dar în unele cazuri se dore?te orice sporire, cât de mica a securita?ii.

Câteva tehnici simple pot ajuta la ascunderea PHP, posibil încetinind un atacator care încearca sa descopere puncte slabe în sistemul dumneavoastra. Stabilind expose_php = off în fi?ierul php.ini, pute?i reduce cantitatea de informa?ii trimisa de server.

O alta tactica este configurarea serverelor web, cum ar fi Apache sa prelucreze ?i sa interpreteze diferite tipuri de fi?iere cu PHP, fie printr-o directiva .htaccess, fie direct în configura?ia Apache. Apoi pute?i utiliza extensii de fi?iere, care sa induca în eroare:

Example #1 Ascunderea PHP ca alt limbaj de scripting

# Face codul PHP sa arate ca alte limbaje de programare web
AddType application/x-httpd-php .asp .py .pl
Sau ascunderea lui completa:

Example #2 Utilizarea tipurilor necunoscute în calitate de extensii PHP

# Face codul PHP sa aiba extensii ciudate
AddType application/x-httpd-php .bop .foo .133t
Sau deghizarea drept cod HTML, dar acest lucru are un impact minor asupra performan?ei, deoarece tot codul HTML va fi procesat de motorul PHP:

Example #3 Folosirea tipurilor HTML pentru extensiile PHP

# Face codul PHP sa arate ca HTML
AddType application/x-httpd-php .htm .html
Pentru ca aceasta modificare sa func?ioneze eficient, trebuie sa redenumi?i toate fi?ierele PHP cu extensiile de mai sus. În timp ce aceasta reprezinta o forma a securita?ii prin obscuritate, este o masura de prevenire minora, cu mici neajunsuri.

Disabling Magic Quotes
Cea mai noua versiune
Securitatea


Cea mai noua versiune

PHP, ca ?i orice alt sistem major, este într-un proces constant de examinare minu?ioasa ?i îmbunata?ire. Fiecare versiune noua deseori va include atât schimbari minore cât ?i majore pentru a îmbunata?i securitatea ?i pentru a repara orice neajunsuri, problemele de configurare, precum ?i alte schimbari care au impact asupra securita?ii ?i stabilita?ii sistemului dumneavoastra.

Ca ?i cu alte limbaje de script ?i programe care ruleaza la nivel de sistem, cea mai buna solu?ie este reînnoirea regulata ?i eviden?a ultimelor versiuni ?i a schimbarilor survenite în acestea.

Ascunderea PHP
Facilita?i
Securitatea


Facilita?i

  • HTTP authentication with PHP
  • Cookies
  • Sesiuni
  • Dealing with XForms
  • Handling file uploads
    • POST method uploads
    • Error Messages Explained
    • Common Pitfalls
    • Uploading multiple files
    • PUT method support
    • A se vedea ?i
  • Using remote files
  • Connection handling
  • Persistent Database Connections
  • Safe Mode
    • Security and Safe Mode
    • Functions restricted/disabled by safe mode
  • 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
    • INI settings
  • Garbage Collection
    • Reference Counting Basics
    • Collecting Cycles
    • Performance Considerations
  • DTrace Dynamic Tracing
    • Introduction to PHP and DTrace
    • Using PHP and DTrace
    • Using SystemTap with PHP DTrace Static Probes
Cea mai noua versiune
HTTP authentication with PHP
Manualul PHP


HTTP authentication with PHP

It is possible to use the header() function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER array. Both "Basic" and "Digest" (since PHP 5.1.0) authentication methods are supported. See the header() function for more information.

An example script fragment which would force client authentication on a page is as follows:

Example #1 Basic HTTP Authentication example

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>

Example #2 Digest HTTP Authentication example

This example shows you how to implement a simple Digest HTTP authentication script. For more information read the » RFC 2617.

<?php
$realm = 'Restricted area';

//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');

if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: Digest realm="'.$realm.
           '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');

    die('Text to send if user hits Cancel button');
}

// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
    !isset($users[$data['username']]))
    die('Wrong Credentials!');

// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);

if ($data['response'] != $valid_response)
    die('Wrong Credentials!');

// ok, valid username & password
echo 'You are logged in as: ' . $data['username'];

// function to parse the http auth header
function http_digest_parse($txt)
{
    // protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();
    $keys = implode('|', array_keys($needed_parts));

    preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

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

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

Nota: Compatibility Note

Please be careful when coding the HTTP header lines. In order to guarantee maximum compatibility with all clients, the keyword "Basic" should be written with an uppercase "B", the realm string must be enclosed in double (not single) quotes, and exactly one space should precede the 401 code in the HTTP/1.0 401 header line. Authentication parameters have to be comma-separated as seen in the digest example above.

Instead of simply printing out PHP_AUTH_USER and PHP_AUTH_PW, as done in the above example, you may want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file.

Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now.

In order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page and modul securizat is enabled. Regardless, REMOTE_USER can be used to identify the externally-authenticated user. So, you can use $_SERVER['REMOTE_USER'].

Nota: Configuration Note

PHP uses the presence of an AuthType directive to determine whether external authentication is in effect.

Note, however, that the above does not prevent someone who controls a non-authenticated URL from stealing passwords from authenticated URLs on the same server.

Both Netscape Navigator and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button.

Example #3 HTTP Authentication example forcing a new name/password

<?php
function authenticate() {
    header('WWW-Authenticate: Basic realm="Test Authentication System"');
    header('HTTP/1.0 401 Unauthorized');
    echo "You must enter a valid login ID and password to access this resource\n";
    exit;
}

if (!isset($_SERVER['PHP_AUTH_USER']) ||
    ($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
    authenticate();
} else {
    echo "<p>Welcome: " . htmlspecialchars($_SERVER['PHP_AUTH_USER']) . "<br />";
    echo "Old: " . 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";
}
?>

This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource as long as the credential requirements haven't changed. The user can press the '_' key to clear their authentication information, however.

In order to get HTTP Authentication to work using IIS server with the CGI version of PHP you must edit your IIS configuration "Directory Security". Click on "Edit" and only check "Anonymous Access", all other fields should be left unchecked.

Nota: IIS Note:
For HTTP Authentication to work with IIS, the PHP directive cgi.rfc2616_headers must be set to 0 (the default value).

Nota:

If safe mode is enabled, the uid of the script is added to the realm part of the WWW-Authenticate header.

Facilita?i
Cookies
Facilita?i


Cookies

PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies or send any headers.

Any cookies sent to you from the client will automatically be included into a $_COOKIE auto-global array if variables_order contains "C". If you wish to assign multiple values to a single cookie, just add [] to the cookie name.

Depending on register_globals, regular PHP variables can be created from cookies. However it's not recommended to rely on them as this feature is often turned off for the sake of security.

For more details, including notes on browser bugs, see the setcookie() and setrawcookie() function.

HTTP authentication with PHP
Sesiuni
Facilita?i


Sesiuni

Sus?inerea sesiunilor în PHP consta în oferirea unei modalita?i de a pastra anumite date la accesari ulterioare ale script-ului. Aceasta va permite sa construi?i aplica?ii mai personalizate ?i sa îmbunata?i?i atractivitatea web site-ului dumneavoastra. Toate informa?iile necesare le pute?i gasi în sec?iunea Referin?e despre sesiuni.

Cookies
Dealing with XForms
Facilita?i


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.

Example #1 A simple XForms search form

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

The above form displays a text input box (named q), and a submit button. When the submit button is clicked, the form will be sent to the page referred to by action.

Here's where it starts to look different from your web application's point of view. In a normal HTML form, the data would be sent as application/x-www-form-urlencoded, in the XForms world however, this information is sent as XML formatted data.

If you're choosing to work with XForms then you probably want that data as XML, in that case, look in $HTTP_RAW_POST_DATA where you'll find the XML document generated by the browser which you can pass into your favorite XSLT engine or document parser.

If you're not interested in formatting and just want your data to be loaded into the traditional $_POST variable, you can instruct the client browser to send it as application/x-www-form-urlencoded by changing the method attribute to urlencoded-post.

Example #2 Using an XForm to populate $_POST

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="urlencoded-post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

Nota: As of this writing, many browsers do not support XForms. Check your browser version if the above examples fails.

Sesiuni
Handling file uploads
Facilita?i


Handling file uploads

Cuprins

  • POST method uploads
  • Error Messages Explained
  • Common Pitfalls
  • Uploading multiple files
  • PUT method support
  • A se vedea ?i
Dealing with XForms
POST method uploads
Facilita?i


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.

Nota: Related Configurations Note

See also the file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size and max_input_time directives in php.ini

PHP also supports PUT-method file uploads as used by Netscape Composer and W3C's Amaya clients. See the PUT Method Support for more details.

Example #1 File Upload Form

A file upload screen can be built by creating a special form which looks something like this:

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

The __URL__ in the above example should be replaced, and point to a PHP file.

The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too large and the transfer failed. Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled.

Nota:

Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.

The global $_FILES will contain all the uploaded file information. Its contents 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.

Files will, by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in php.ini. The server's default directory can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using putenv() from within a PHP script will not work. This environment variable can also be used to make sure that other operations are working on uploaded files, as well.

Example #2 Validating file uploads

See also the function entries for is_uploaded_file() and move_uploaded_file() for further information. The following example will process the file upload that came from a form.

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>

The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can, for example, use the $_FILES['userfile']['size'] variable to throw away any files that are either too small or too big. You could use the $_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria, but use this only as first of a series of checks, because this value is completely under the control of the client and not checked on the PHP side. Also, you could use $_FILES['userfile']['error'] and plan your logic according to the error codes. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere.

If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.

The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.

Example #3 Uploading array of files

PHP supports HTML array feature even with files.

<form action="" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        // basename() may prevent filesystem traversal attacks;
        // further validation/sanitation of the filename may be appropriate
        $name = basename($_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

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

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.

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

Avertizare

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:

Example #1 Uploading multiple files

<form action="file-upload.php" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="userfile[]" type="file" /><br />
  <input name="userfile[]" type="file" /><br />
  <input type="submit" value="Send files" />
</form>

When the above form is submitted, the arrays $_FILES['userfile'], $_FILES['userfile']['name'], and $_FILES['userfile']['size'] will be initialized (as well as in $HTTP_POST_FILES for PHP versions prior to 4.1.0). When register_globals is on, globals for uploaded files are also initialized. Each of these will be a numerically indexed array of the appropriate values for the submitted files.

For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. In this case, $_FILES['userfile']['name'][0] would contain the value review.html, and $_FILES['userfile']['name'][1] would contain the value xwp.out. Similarly, $_FILES['userfile']['size'][0] would contain review.html's file size, and so forth.

$_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are also set.

Avertizare

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.

Example #1 Saving HTTP PUT files

<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");

/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");

/* Read the data 1 KB at a time
   and write to the file */
while ($data = fread($putdata, 1024))
  fwrite($fp, $data);

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

Uploading multiple files
A se vedea ?i
Handling file uploads


A se vedea ?i

  • Filesystem Security

PUT method support
Using remote files
Handling file uploads


Using remote files

As long as allow_url_fopen is enabled in php.ini, you can use HTTP and FTP URLs with most of the functions that take a filename as a parameter. In addition, URLs can be used with the include, include_once, require and require_once statements (since PHP 5.2.0, allow_url_include must be enabled for these). See Supported Protocols and Wrappers for more information about the protocols supported by PHP.

For example, you can use this to open a file on a remote web server, parse the output for the data you want, and then use that data in a database query, or simply to output it in a style matching the rest of your website.

Example #1 Getting the title of a remote page

<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
    echo "<p>Unable to open remote file.\n";
    exit;
}
while (!feof ($file)) {
    $line = fgets ($file, 1024);
    /* This only works if the title and its tags are on one line */
    if (preg_match ("@\<title\>(.*)\</title\>@i", $line, $out)) {
        $title = $out[1];
        break;
    }
}
fclose($file);
?>

You can also write to files on an FTP server (provided that you have connected as a user with the correct access rights). You can only create new files using this method; if you try to overwrite a file that already exists, the fopen() call will fail.

To connect as a user other than 'anonymous', you need to specify the username (and possibly password) within the URL, such as 'ftp://user:password@ftp.example.com/path/to/file'. (You can use the same sort of syntax to access files via HTTP when they require Basic authentication.)

Example #2 Storing data on a remote server

<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
    echo "<p>Unable to open remote file for writing.\n";
    exit;
}
/* Write the data here. */
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>

Nota:

You might get the idea from the example above that you can use this technique to write to a remote log file. Unfortunately that would not work because the fopen() call will fail if the remote file already exists. To do distributed logging like that, you should take a look at syslog().

A se vedea ?i
Connection handling
Facilita?i


Connection handling

Internally in PHP a connection status is maintained. There are 4 possible states:

  • 0 - NORMAL
  • 1 - ABORTED
  • 2 - TIMEOUT
  • 3 - ABORTED and TIMEOUT

When a PHP script is running normally, the NORMAL state is active. If the remote client disconnects, the ABORTED state flag is turned on. A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on.

You can decide whether or not you want a client disconnect to cause your script to be aborted. Sometimes it is handy to always have your scripts run to completion even if there is no remote browser receiving the output. The default behaviour is however for your script to be aborted when the remote client disconnects. This behaviour can be set via the ignore_user_abort php.ini directive as well as through the corresponding php_value ignore_user_abort Apache httpd.conf directive or with the ignore_user_abort() function. If you do not tell PHP to ignore a user abort and the user aborts, your script will terminate. The one exception is if you have registered a shutdown function using register_shutdown_function(). With a shutdown function, when the remote user hits his STOP button, the next time your script tries to output something PHP will detect that the connection has been aborted and the shutdown function is called. This shutdown function will also get called at the end of your script terminating normally, so to do something different in case of a client disconnect you can use the connection_aborted() function. This function will return TRUE if the connection was aborted.

Your script can also be terminated by the built-in script timer. The default timeout is 30 seconds. It can be changed using the max_execution_time php.ini directive or the corresponding php_value max_execution_time Apache httpd.conf directive as well as with the set_time_limit() function. When the timer expires the script will be aborted and as with the above client disconnect case, if a shutdown function has been registered it will be called. Within this shutdown function you can check to see if a timeout caused the shutdown function to be called by calling the connection_status() function. This function will return 2 if a timeout caused the shutdown function to be called.

One thing to note is that both the ABORTED and the TIMEOUT states can be active at the same time. This is possible if you tell PHP to ignore user aborts. PHP will still note the fact that a user may have broken the connection, but the script will keep running. If it then hits the time limit it will be aborted and your shutdown function, if any, will be called. At this point you will find that connection_status() returns 3.

Using remote files
Persistent Database Connections
Facilita?i


Persistent Database Connections

Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).

People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same link, they do not give you an ability to build up a transaction efficiently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.

Why?

This has to do with the way web servers work. There are three ways in which your web server can utilize PHP to generate web pages.

The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist.

The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When a request comes in from a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be served by a different child process than the first time. When opening a persistent connection, every following page requesting SQL services can reuse the same established connection to the SQL server.

The last method is to use PHP as a plug-in for a multithreaded web server. Currently PHP 4 has support for ISAPI, WSAPI, and NSAPI (on Windows), which all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack (iPlanet), Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. The behavior is essentially the same as for the multiprocess model described before.

If persistent connections don't have any added functionality, what are they good for?

The answer here is extremely simple -- efficiency. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.

Note, however, that this can have some drawbacks if you are using a database with connection limits that are exceeded by persistent child connections. If your database has a limit of 16 simultaneous connections, and in the course of a busy server session, 17 child threads attempt to connect, one will not be able to. If there are bugs in your scripts which do not allow the connections to shut down (such as infinite loops), the database with only 16 connections may be rapidly swamped. Check your database documentation for information on handling abandoned or idle connections.

Avertizare

There are a couple of additional caveats to keep in mind when using persistent connections. One is that when using table locking on a persistent connection, if the script for whatever reason cannot release the lock, then subsequent scripts using the same connection will block indefinitely and may require that you either restart the httpd server or the database server. Another is that when using transactions, a transaction block will also carry over to the next script which uses that connection if script execution ends before the transaction block does. In either case, you can use register_shutdown_function() to register a simple cleanup function to unlock your tables or roll back your transactions. Better yet, avoid the problem entirely by not using persistent connections in scripts which use table locks or transactions (you can still use them elsewhere).

An important summary. Persistent connections were designed to have one-to-one mapping to regular connections. That means that you should always be able to replace persistent connections with non-persistent connections, and it won't change the way your script behaves. It may (and probably will) change the efficiency of the script, but not its behavior!

See also fbsql_pconnect(),
ibase_pconnect(), ifx_pconnect(),
ingres_pconnect(),
msql_pconnect(), mssql_pconnect(),
mysql_pconnect(), ociplogon(),
odbc_pconnect(), oci_pconnect(),
pfsockopen(), pg_pconnect(), and
sybase_pconnect().

Connection handling
Safe Mode
Facilita?i


Safe Mode

Cuprins

  • Security and Safe Mode
  • Functions restricted/disabled by safe mode

The PHP safe mode is an attempt to solve the shared-server security problem. It is architecturally incorrect to try to solve this problem at the PHP level, but since the alternatives at the web server and OS levels aren't very realistic, many people, especially ISP's, use safe mode for now.

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

Changelog for safe mode
Versiune | Descriere
5.4.0 | Removed from PHP, and generates a fatal E_CORE_ERROR level error when enabled.
5.3.0 | Deprecated, and E_DEPRECATED errors were added.

Persistent Database Connections
Security and Safe Mode
Facilita?i


Security and Safe Mode

Security and Safe Mode Configuration Directives
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
safe_mode | "0" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_gid | "0" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_exec_dir | "" | 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_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

safe_mode boolean

Whether to enable PHP's safe mode. If PHP is compiled with --enable-safe-mode then defaults to On, otherwise Off.

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

safe_mode_gid boolean

By default, Safe Mode does a UID compare check when opening files. If you want to relax this to a GID compare, then turn on safe_mode_gid. Whether to use UID (FALSE) or GID (TRUE) checking upon file access.

safe_mode_include_dir string

UID/GID checks are bypassed when including files from this directory and its subdirectories (directory must also be in include_path or full path must including).

This directive can take a colon (semi-colon on Windows) separated path in a fashion similar to the include_path directive, rather than just a single directory. The restriction specified is actually a prefix, not a directory name. This means that "safe_mode_include_dir = /dir/incl" also allows 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: "safe_mode_include_dir = /dir/incl/" If the value of this directive is empty, no files with different UID/GID can be included.
safe_mode_exec_dir string

If PHP is used in safe mode, system() and the other functions executing system programs refuse to start programs that are not in this directory. You have to use / as directory separator on all environments including Windows.

safe_mode_allowed_env_vars string

Setting certain environment variables may be a potential security breach. This 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 here. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR).

Nota:

If this directive is empty, PHP will let the user modify ANY environment variable!

safe_mode_protected_env_vars string

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

See also: open_basedir, disable_functions, disable_classes, register_globals, display_errors, and log_errors.

When safe_mode is on, PHP checks to see if the owner of the current script matches the owner of the file to be operated on by a file function or its directory. For example:

-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
Running script.php:
<?php
 readfile('/etc/passwd');
?>
results in this error when safe mode is enabled:
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

However, there may be environments where a strict UID check is not appropriate and a relaxed GID check is sufficient. This is supported by means of the safe_mode_gid switch. Setting it to On performs the relaxed GID checking, setting it to Off (the default) performs UID checking.

If instead of safe_mode, you set an open_basedir directory then all file operations will be limited to files under the specified directory. For example (Apache httpd.conf example):

<Directory /docroot>
  php_admin_value open_basedir /docroot
</Directory>
If you run the same script.php with this open_basedir setting then this is the result:
Warning: open_basedir restriction in effect. File is in wrong directory in
/docroot/script.php on line 2

You can also disable individual functions. Note that the disable_functions directive can not be used outside of the php.ini file which means that you cannot disable functions on a per-virtualhost or per-directory basis in your httpd.conf file. If we add this to our php.ini file:

disable_functions = readfile,system
Then we get this output:
Warning: readfile() has been disabled for security reasons in
/docroot/script.php on line 2

Avertizare

These PHP restrictions are not valid in executed binaries, of course.

Safe Mode
Functions restricted/disabled by safe mode
Safe Mode


Functions restricted/disabled by safe mode

This is a still probably incomplete and possibly incorrect listing of the functions limited by safe mode.

Safe mode limited functions
Function | Limitations
dbmopen() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa.
dbase_open() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa.
filepro() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa.
filepro_rowcount() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa.
filepro_retrieve() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa.
ifx_* | sql_safe_mode restrictions, (!= safe mode)
ingres_* | sql_safe_mode restrictions, (!= safe mode)
mysql_* | sql_safe_mode restrictions, (!= safe mode)
pg_lo_import() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa.
posix_mkfifo() | Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa.
putenv() | Obeys the safe_mode_protected_env_vars and safe_mode_allowed_env_vars ini-directives. See also the documentation on putenv()
move_uploaded_file() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa.
chdir() | Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa.
dl() | Aceasta func?ie este dezactivata atunci când PHP ruleaza în modul securizat.
backtick operator | Aceasta func?ie este dezactivata atunci când PHP ruleaza în modul securizat.
shell_exec() (functional equivalent of backticks) | Aceasta func?ie este dezactivata atunci când PHP ruleaza în modul securizat.
exec() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
system() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
passthru() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
popen() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
fopen() | Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa.
mkdir() | Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa.
rmdir() | Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa.
rename() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa. Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa.
unlink() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa. Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa.
copy() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa. Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa. (on source and target)
chgrp() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa.
chown() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa.
chmod() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa. In addition, you cannot set the SUID, SGID and sticky bits
touch() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa. Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa.
symlink() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa. Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa. (note: only the target is checked)
link() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa. Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa. (note: only the target is checked)
apache_request_headers() | In safe mode, headers beginning with authorization (case-insensitive) will not be returned.
header() | In safe mode, 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).
PHP_AUTH variables | In safe mode, the variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE are not available in $_SERVER. Regardless, you can still use REMOTE_USER for the USER. (note: only affected since PHP 4.3.0)
highlight_file(), show_source() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa. Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa.
parse_ini_file() | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa. Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa.
set_time_limit() | Has no effect when PHP is running in modul securizat.
max_execution_time | Has no effect when PHP is running in modul securizat.
mail() | In safe mode, the fifth parameter is disabled.
session_start() | The owner of a script must be the same as owner of a session.save_path directory if the default files session.save_handler is used.
All filesystem and stream functions. | Verifica daca fi?ierele ?i directoarele cu care se opereaza au acela?i UID (proprietar) ca ?i script-ul care se executa. Verifica daca directorul în care se opereaza are acela?i UID (proprietar) ca ?i script-ul ce se executa. (see the safe_mode_include_dir php.ini option.

Security and Safe Mode
Command line usage
Safe Mode


Using PHP from the command line

Cuprins

  • Introduction
  • Differences to other SAPIs
  • Options
  • Usage
  • I/O streams
  • Interactive shell
  • Built-in web server
  • INI settings
Functions restricted/disabled by safe mode
Introduction
Facilita?i


Introduction

The main focus of CLI 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.

Nota:

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.

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

Nota:

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 does not support GET, POST or file uploads.

    Nota:

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

    Nota:

    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.

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

    Nota:

    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 <addr>:<port> Run with built-in web server.
  -t <docroot>     Specify document root <docroot> for built-in web server.
  -s               Output HTML syntax highlighted source.
  -v               Version number
  -w               Output source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.

  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin

  --ini            Show configuration file names

  --rf <name>      Show information about function <name>.
  --rc <name>      Show information about class <name>.
  --re <name>      Show information about extension <name>.
  --rz <name>      Show information about Zend extension <name>.
  --ri <name>      Show configuration for extension <name>.

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

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

-b --bindpath

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

-C --no-chdir

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

-q --no-header

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

-T --timing

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

-c --php-ini

Specifies either a directory in which to look for php.ini, or a custom INI file (which does not need to be named php.ini), e.g.:

$ php -c /custom/directory/ my_script.php

$ php -c /custom/directory/custom-file.ini my_script.php

If this option is not specified, php.ini is searched for in the default locations.

-n --no-php-ini

Ignore php.ini completely.

-d --define

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

 -d configuration_directive[=value]

# Omitting the value part will set the given configuration directive to "1"
$ php -d max_execution_time
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"

# Passing an empty value part will set the configuration directive to ""
php -d max_execution_time=
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""

# The configuration directive will be set to anything passed after the '=' character
$  php -d max_execution_time=20
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php
        -d max_execution_time=doesntmakesense
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"

-e --profile-info

Activate the extended information mode, to be used by a debugger/profiler.

-f --file

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

Nota:

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.

Nota:

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

-m --modules

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

Nota:

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

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

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

Nota:

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

Nota:

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.

Example #4 Using the -B , -R and -E options to count the number of lines of a project.

$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";'
Total Lines: 37328

-S --server

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

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

Display colour syntax highlighted source.

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

Nota:

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

-v --version

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

Nota:

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.

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

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

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

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

Example #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

Nota:

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.

    Nota:

    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.

    Nota:

    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:

Example #1 Execute PHP script as shell script

#!/usr/bin/php
<?php
var_dump($argv);
?>

Assuming this file is named test in the current directory, 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.

Example #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:

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

Nota:

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.

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

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

Example #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: ' " { ( >

Nota:

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.

Nota:

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

Avertizare

This web server was designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network.

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

The web server runs a only one single-threaded process, so PHP applications will stall if a request is blocked.

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, the lookup for index.php and index.html will be continued in the parent directory and so on until one is found or the document root has been reached. If an index.php or index.html is found, it is returned and $_SERVER['PATH_INFO'] is set to the trailing part of the URI. Otherwise 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. 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.

Standard MIME types are returned for files with extensions: .3gp, .apk, .avi, .bmp, .css, .csv, .doc, .docx, .flac, .gif, .gz, .gzip, .htm, .html, .ics, .jpe, .jpeg, .jpg, .js, .kml, .kmz, .m4a, .mov, .mp3, .mp4, .mpeg, .mpg, .odp, .ods, .odt, .oga, .ogg, .ogv, .pdf, .pdf, .png, .pps, .pptx, .qt, .svg, .swf, .tar, .text, .tif, .txt, .wav, .webm, .wmv, .xls, .xlsx, .xml, .xsl, .xsd, and .zip.

Changelog: Supported MIME Types (file extensions)
Versiune | Descriere
5.5.12 | .xml, .xsl, and .xsd
5.5.7 | .3gp, .apk, .avi, .bmp, .csv, .doc, .docx, .flac, .gz, .gzip, .ics, .kml, .kmz, .m4a, .mp3, .mp4, .mpg, .mpeg, .mov, .odp, .ods, .odt, .oga, .pdf, .pptx, .pps, .qt, .swf, .tar, .text, .tif, .wav, .wmv, .xls, .xlsx, and .zip
5.5.5 | .pdf
5.4.11 | .ogg, .ogv, and .webm
5.4.4 | .htm and .svg

Example #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

Example #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

Example #3 Using a Router Script

In this example, 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

Example #4 Checking for CLI Web Server Use

To reuse a framework router script during development with the CLI web server and later also with a production web server:

<?php
// router.php
if (php_sapi_name() == 'cli-server') {
    /* route static assets and return false */
}
/* go on with normal index.php operations */
?>
$ php -S localhost:8000 router.php

Example #5 Handling Unsupported File Types

If you need to serve a static resource whose MIME type is not handled by the CLI web server, use:

<?php
// router.php
$path = pathinfo($_SERVER["SCRIPT_FILENAME"]);
if ($path["extension"] == "el") {
    header("Content-Type: text/x-script.elisp");
    readfile($_SERVER["SCRIPT_FILENAME"]);
}
else {
    return FALSE;
}
?>
$ php -S localhost:8000 router.php

Example #6 Accessing the CLI Web Server From Remote Machines

You can make the web server accessible on port 8000 to any interface with:

$ php -S 0.0.0.0:8000
Interactive shell
INI settings
Command line usage


INI settings

CLI SAPI Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
cli_server.color | "0" | PHP_INI_ALL | Available since PHP 5.4.0.

Iata o explica?ie pe scurt a directivelor de configurare.

cli_server.color boolean

Enable the built-in development web server to use ANSI color coding in terminal output.

Built-in web server
Garbage Collection
Command line usage


Garbage Collection

Cuprins

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

INI settings
Reference Counting Basics
Facilita?i


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:

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

Example #2 Displaying zval information

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

Exemplul de mai sus va afi?a:

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

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

Example #3 Increasing refcount of a zval

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

Exemplul de mai sus va afi?a:

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 a symbol is unassigned (e.g. by calling unset()). The following example shows this:

Example #4 Decreasing zval refcount

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

Exemplul de mai sus va afi?a:

a: (refcount=3, is_ref=0)='new string'
a: (refcount=2, 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. As opposed to scalar values, arrays and objects store their properties in a symbol table of their own. This means that the following example creates three zval containers:

Example #5 Creating a array zval

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

Exemplul de mai sus va afi?a ceva similar cu:

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:

Example #6 Adding already existing element to an array

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

Exemplul de mai sus va afi?a ceva similar cu:

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:

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

Exemplul de mai sus va afi?a ceva similar cu:

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:

Example #8 Adding the array itself as an element of it self

<?php
$a = array( 'one' );
$a[] =& $a;
xdebug_debug_zval( 'a' );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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:

Example #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; however, as of 5.3.0, PHP 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.

Example #1 Memory usage example

<?php
class Foo
{
    public $var = '3.14159265359';
}

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

Example #2 GC performance influences

<?php
class Foo
{
    public $var = '3.14159265359';
}

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:

Example #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:

Example #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:

Example #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
DTrace Dynamic Tracing
Garbage Collection


DTrace Dynamic Tracing

Cuprins

  • Introduction to PHP and DTrace
  • Using PHP and DTrace
  • Using SystemTap with PHP DTrace Static Probes
Performance Considerations
Introduction to PHP and DTrace
Facilita?i


Introduction to PHP and DTrace

DTrace is an always-available, low overhead, tracing framework available on a number of platforms including Solaris, Mac OS X, Oracle Linux and BSD. DTrace can trace operating system behavior and user program execution. It can display argument values and be used to infer performance statistics. Probes are monitored by user created scripts written in the DTrace D scripting language. This allows efficient analysis of data points.

PHP probes that are not being actively monitored by a user's DTrace D script do not contain instrumented code so there is no performance degradation during normal application execution. Probes that are being monitored incur an overhead low enough to generally allow DTrace monitoring on live production systems.

PHP incorporates "User-level Statically Defined Tracing" (USDT) probes that are triggered at runtime. For example, when a D script is monitoring PHP's function-entry probe, then, every time a PHP script function is called, this probe is fired and the associated D script action code is executed. This action code could, for example, print probe arguments such as the source file location of the PHP function. Or the action could aggregate data such as the number of times each function is called.

Only the PHP USDT probes are described here. Refer to external general and operating system-specific DTrace literature to see how DTrace can be used to trace arbitrary functions, and how it can be used to trace operating system behavior. Note not all DTrace features are available in all DTrace implementations.

DTrace static probes are included in PHP 5.4. Prior to this they were available via a » PECL extension, which is now obsolete.

The static DTrace probes in PHP can alternatively be used with the SystemTap facility on some Linux distributions.

DTrace Dynamic Tracing
Using PHP and DTrace
DTrace Dynamic Tracing


Using PHP and DTrace

PHP can be configured with DTrace static probes on platforms that support DTrace Dynamic Tracing.

Configuring PHP for DTrace Static Probes

Refer to external platform specific documentation for enabling operating system DTrace support. For example, on Oracle Linux boot a UEK3 kernel and do:

# modprobe fasttrap
# chmod 666 /dev/dtrace/helper

Instead of using chmod, you could instead use an ACL package rule to limit device access to a specific user.

Build PHP with the --enable-dtrace configuration parameter:

# ./configure --enable-dtrace ...
# make
# make install

This enables the static probes in core PHP. Any PHP extensions that provide their own probes should be built separately as shared extensions.

DTrace Static Probes in Core PHP

The following static probes are available in PHP
Probe Name | Probe Description | Probe Arguments
request-startup | Fires when a request starts. | char *file, char *request_uri, char *request_method
request-shutdown | Fires when a request shutdown. | char *file, char *request_uri, char *request_method
compile-file-entry | Fires when the compilation of a script starts. | char *compile_file, char *compile_file_translated
compile-file-return | Fires when the compilation of a script finishes. | char *compile_file, char *compile_file_translated
execute-entry | Fires when an opcode array is to be executed. For example, it fires on function calls, includes, and generator resumes. | char *request_file, int lineno
execute-return | Fires after execution of an opcode array. | char *request_file, int lineno
function-entry | Fires when the PHP engine enters a PHP function or method call. | char *function_name, char *request_file, int lineno, char *classname, char *scope
function-return | Fires when the PHP engine returns from a PHP function or method call. | char *function_name, char *request_file, int lineno, char *classname, char *scope
exception-thrown | Fires when an exception is thrown. | char *classname
exception-caught | Fires when an exception is caught. | char *classname
error | Fires when an error occurs, regardless of the error_reporting level. | char *errormsg, char *request_file, int lineno

PHP extensions may also have additional static probes.

Listing DTrace Static Probes in PHP

To list available probes, start a PHP process and then run:

# dtrace -l

The output will be similar to:

   ID   PROVIDER            MODULE                          FUNCTION NAME
   [ . . . ]
    4   php15271               php               dtrace_compile_file compile-file-entry
    5   php15271               php               dtrace_compile_file compile-file-return
    6   php15271               php                        zend_error error
    7   php15271               php  ZEND_CATCH_SPEC_CONST_CV_HANDLER exception-caught
    8   php15271               php     zend_throw_exception_internal exception-thrown
    9   php15271               php                 dtrace_execute_ex execute-entry
   10   php15271               php           dtrace_execute_internal execute-entry
   11   php15271               php                 dtrace_execute_ex execute-return
   12   php15271               php           dtrace_execute_internal execute-return
   13   php15271               php                 dtrace_execute_ex function-entry
   14   php15271               php                 dtrace_execute_ex function-return
   15   php15271               php              php_request_shutdown request-shutdown
   16   php15271               php               php_request_startup request-startup

The Provider column values consist of php and the process id of the currently running PHP process.

If the Apache web server is running, the module name might be, for example, libphp5.so, and there would be multiple blocks of listings, one per running Apache process.

The Function column refers to PHP's internal C implementation function names where each provider is located.

If a PHP process is not running, then no PHP probes will be shown.

DTrace with PHP Example

This example shows the basics of the DTrace D scripting language.

Example #1 all_probes.d for tracing all PHP Static Probes with DTrace

#!/usr/sbin/dtrace -Zs

#pragma D option quiet

php*:::compile-file-entry
{
    printf("PHP compile-file-entry\n");
    printf("  compile_file              %s\n", copyinstr(arg0));
    printf("  compile_file_translated   %s\n", copyinstr(arg1));
}

php*:::compile-file-return
{
    printf("PHP compile-file-return\n");
    printf("  compile_file              %s\n", copyinstr(arg0));
    printf("  compile_file_translated   %s\n", copyinstr(arg1));
}

php*:::error
{
    printf("PHP error\n");
    printf("  errormsg                  %s\n", copyinstr(arg0));
    printf("  request_file              %s\n", copyinstr(arg1));
    printf("  lineno                    %d\n", (int)arg2);
}

php*:::exception-caught
{
    printf("PHP exception-caught\n");
    printf("  classname                 %s\n", copyinstr(arg0));
}

php*:::exception-thrown
{
    printf("PHP exception-thrown\n");
    printf("  classname                 %s\n", copyinstr(arg0));
}

php*:::execute-entry
{
    printf("PHP execute-entry\n");
    printf("  request_file              %s\n", copyinstr(arg0));
    printf("  lineno                    %d\n", (int)arg1);
}

php*:::execute-return
{
    printf("PHP execute-return\n");
    printf("  request_file              %s\n", copyinstr(arg0));
    printf("  lineno                    %d\n", (int)arg1);
}

php*:::function-entry
{
    printf("PHP function-entry\n");
    printf("  function_name             %s\n", copyinstr(arg0));
    printf("  request_file              %s\n", copyinstr(arg1));
    printf("  lineno                    %d\n", (int)arg2);
    printf("  classname                 %s\n", copyinstr(arg3));
    printf("  scope                     %s\n", copyinstr(arg4));
}

php*:::function-return
{
    printf("PHP function-return\n");
    printf("  function_name             %s\n", copyinstr(arg0));
    printf("  request_file              %s\n", copyinstr(arg1));
    printf("  lineno                    %d\n", (int)arg2);
    printf("  classname                 %s\n", copyinstr(arg3));
    printf("  scope                     %s\n", copyinstr(arg4));
}

php*:::request-shutdown
{
    printf("PHP request-shutdown\n");
    printf("  file                      %s\n", copyinstr(arg0));
    printf("  request_uri               %s\n", copyinstr(arg1));
    printf("  request_method            %s\n", copyinstr(arg2));
}

php*:::request-startup
{
    printf("PHP request-startup\n");
    printf("  file                      %s\n", copyinstr(arg0));
    printf("  request_uri               %s\n", copyinstr(arg1));
    printf("  request_method            %s\n", copyinstr(arg2));
}

This script uses the -Z option to dtrace, allowing it to be run when there is no PHP process executing. If this option were omitted the script would immediately terminate because it knows none of the probes to be monitored are in existence.

The script traces all core PHP static probe points throughout the duration of a running PHP script. Run the D script:

# ./all_probes.d

Run a PHP script or application. The monitoring D script will output each probe's arguments as it fires.

When monitoring is complete, the D script can be terminated with a ^C.

On multi-CPU machines the probe ordering might not appear to be sequential. This depends on which CPU was processing the probes, and how threads migrate across CPUs. Displaying probe time stamps will help reduce confusion, for example:

php*:::function-entry
{
      printf("%lld: PHP function-entry ", walltimestamp);
      [ . . .]
}

See Also

  • OCI8 and DTrace Dynamic Tracing
Introduction to PHP and DTrace
Using SystemTap with PHP DTrace Static Probes
DTrace Dynamic Tracing


Using SystemTap with PHP DTrace Static Probes

On some Linux distributions, the SystemTap tracing utility can be used to trace PHP's static DTrace probes. This is available with PHP 5.4.20 and PHP 5.5.

Installing PHP with SystemTap

Install the SystemTap SDT development package:

# yum install systemtap-sdt-devel

Install PHP with the DTrace probes enabled:

# ./configure --enable-dtrace ...
# make

Listing Static Probes with SystemTap

The static probes in PHP can be listed using stap:

# stap -l 'process.provider("php").mark("*")' -c 'sapi/cli/php -i'

This outputs:

process("sapi/cli/php").provider("php").mark("compile__file__entry")
process("sapi/cli/php").provider("php").mark("compile__file__return")
process("sapi/cli/php").provider("php").mark("error")
process("sapi/cli/php").provider("php").mark("exception__caught")
process("sapi/cli/php").provider("php").mark("exception__thrown")
process("sapi/cli/php").provider("php").mark("execute__entry")
process("sapi/cli/php").provider("php").mark("execute__return")
process("sapi/cli/php").provider("php").mark("function__entry")
process("sapi/cli/php").provider("php").mark("function__return")
process("sapi/cli/php").provider("php").mark("request__shutdown")
process("sapi/cli/php").provider("php").mark("request__startup")

SystemTap with PHP Example

Example #1 all_probes.stp for tracing all PHP Static Probes with SystemTap

probe process("sapi/cli/php").provider("php").mark("compile__file__entry") {
    printf("Probe compile__file__entry\n");
    printf("  compile_file %s\n", user_string($arg1));
    printf("  compile_file_translated %s\n", user_string($arg2));
}
probe process("sapi/cli/php").provider("php").mark("compile__file__return") {
    printf("Probe compile__file__return\n");
    printf("  compile_file %s\n", user_string($arg1));
    printf("  compile_file_translated %s\n", user_string($arg2));
}
probe process("sapi/cli/php").provider("php").mark("error") {
    printf("Probe error\n");
    printf("  errormsg %s\n", user_string($arg1));
    printf("  request_file %s\n", user_string($arg2));
    printf("  lineno %d\n", $arg3);
}
probe process("sapi/cli/php").provider("php").mark("exception__caught") {
    printf("Probe exception__caught\n");
    printf("  classname %s\n", user_string($arg1));
}
probe process("sapi/cli/php").provider("php").mark("exception__thrown") {
    printf("Probe exception__thrown\n");
    printf("  classname %s\n", user_string($arg1));
}
probe process("sapi/cli/php").provider("php").mark("execute__entry") {
    printf("Probe execute__entry\n");
    printf("  request_file %s\n", user_string($arg1));
    printf("  lineno %d\n", $arg2);
}
probe process("sapi/cli/php").provider("php").mark("execute__return") {
    printf("Probe execute__return\n");
    printf("  request_file %s\n", user_string($arg1));
    printf("  lineno %d\n", $arg2);
}
probe process("sapi/cli/php").provider("php").mark("function__entry") {
    printf("Probe function__entry\n");
    printf("  function_name %s\n", user_string($arg1));
    printf("  request_file %s\n", user_string($arg2));
    printf("  lineno %d\n", $arg3);
    printf("  classname %s\n", user_string($arg4));
    printf("  scope %s\n", user_string($arg5));
}
probe process("sapi/cli/php").provider("php").mark("function__return") {
    printf("Probe function__return: %s\n", user_string($arg1));
    printf(" function_name %s\n", user_string($arg1));
    printf("  request_file %s\n", user_string($arg2));
    printf("  lineno %d\n", $arg3);
    printf("  classname %s\n", user_string($arg4));
    printf("  scope %s\n", user_string($arg5));
}
probe process("sapi/cli/php").provider("php").mark("request__shutdown") {
    printf("Probe request__shutdown\n");
    printf("  file %s\n", user_string($arg1));
    printf("  request_uri %s\n", user_string($arg2));
    printf("  request_method %s\n", user_string($arg3));
}
probe process("sapi/cli/php").provider("php").mark("request__startup") {
    printf("Probe request__startup\n");
    printf("  file %s\n", user_string($arg1));
    printf("  request_uri %s\n", user_string($arg2));
    printf("  request_method %s\n", user_string($arg3));
}

The above script will trace all core PHP static probe points throughout the duration of a running PHP script:

# stap -c 'sapi/cli/php test.php' all_probes.stp

Using PHP and DTrace
Informa?ii de referin?a despre func?ii
DTrace Dynamic Tracing


Informa?ii de referin?a despre func?ii

Sfat

A se vedea ?i Lista/Categoriile extensiilor.

  • Afectarea comportamentului PHP
    • APC — Alternative PHP Cache
    • APCu — APC User Cache
    • APD — Advanced PHP debugger
    • bcompiler — PHP bytecode Compiler
    • BLENC — Blenc - BLowfish ENCoder for PHP source scripts
    • Error Handling — Error Handling and Logging
    • htscanner — htaccess-like support for all SAPIs
    • inclued — Inclusion hierarchy viewer
    • Memtrack
    • OPcache
    • Output Control — Output Buffering Control
    • PHP Options/Info — PHP Options and Information
    • runkit
    • scream — Break the silence operator
    • uopz
    • Weakref — Weak References
    • WinCache — Windows Cache for PHP
    • Xhprof — Hierarchical Profiler
  • Manipularea cu formate audio
    • ID3 — ID3 Tags
    • KTaglib
    • oggvorbis — OGG/Vorbis
    • OpenAL — Legaturile Audio OpenAL
  • Servicii de autentificare
    • KADM5 — Kerberos V
    • Radius
  • Extensii specifice liniei de comanda
    • Ncurses — Controlul ecranului terminalului cu Ncurses
    • Newt
    • Readline — GNU Readline
  • Extensii de compresie ?i arhivare
    • Bzip2
    • LZF
    • Phar
    • Rar — Rar Archiving
    • Zip
    • Zlib — Zlib Compression
  • Procesarea cardurilor de credit
    • MCVE — MCVE (Monetra) Payment
  • Extensii criptografice
    • Crack — Cracklib
    • CSPRNG
    • Hash — HASH Message Digest Framework
    • Mcrypt
    • Mhash
    • OpenSSL
    • Password Hashing
  • Extensii de lucru cu baze de date
    • Nivele de abstractizare
    • Extensii de lucru cu baze de date specifice anumitor producatori
  • Extensii referitoare la data ?i ora
    • Calendar
    • Date/Time — Date and Time
    • HRTime — High resolution timing
  • Extensii referitoare la sistemul de fi?iere
    • Direct IO
    • Directorii
    • Fileinfo — File Information
    • Filesystem
    • Inotify
    • Mimetype
    • Proctitle
    • xattr
    • xdiff
  • Sus?inerea limbajului uman ?i a codificarii caracterelor
    • Enchant — Enchant spelling library
    • FriBiDi
    • Gender — Determine gender of firstnames
    • Gettext
    • iconv
    • intl — Internationalization Functions
    • Stringuri multioctet
    • Pspell
    • Recode — GNU Recode
  • Generarea ?i procesarea imaginilor
    • Cairo
    • Exif — Exchangeable image information
    • GD — Image Processing and GD
    • Gmagick
    • ImageMagick — Image Processing (ImageMagick)
  • Extensii referitoare la po?ta electronica
    • Cyrus — Administrarea Cyrus IMAP
    • IMAP — IMAP, POP3 ?i NNTP
    • Po?ta
    • Mailparse
    • vpopmail
  • Extensii matematice
    • BC Math — BCMath Arbitrary Precision Mathematics
    • GMP — GNU Multiple Precision
    • Lapack
    • Math — Mathematical Functions
    • Statistics
    • Trader — Technical Analysis for Traders
  • Ie?iri MIME non-textuale
    • FDF — Forms Data Format
    • GnuPG — GNU Privacy Guard
    • haru — Haru PDF
    • Ming — Ming (flash)
    • PDF
    • PS — PostScript document creation
    • RPM Reader — RPM Header Reading
  • Extensii de control al proceselor
    • Eio
    • Ev
    • Expect
    • Libevent
    • PCNTL — Process Control
    • POSIX
    • Program execution — System program execution
    • pthreads
    • Semaphore — Semaphore, Shared Memory and IPC
    • Shared Memory
    • Sync
  • Alte extensii de baza
    • GeoIP — Geo IP Location
    • FANN — FANN (Fast Artificial Neural Network)
    • JSON — Notarea Obiect JavaScript
    • Judy — Judy Arrays
    • Lua
    • Diverse — Func?ii diverse
    • Parsekit
    • SPL — Standard PHP Library (SPL)
    • SPL Types — SPL Type Handling
    • Streams
    • Tidy
    • Tokenizer
    • URL-uri
    • V8js — Integrarea cu motorul Javascript V8
    • Yaml — YAML Data Serialization
    • Yaf — Yet Another Framework
    • Taint
  • Alte servicii
    • chdb — Constant hash database
    • cURL — Client URL Library
    • Event
    • FAM — File Alteration Monitor
    • FTP
    • Gearman
    • Gopher — Net Gopher
    • Gupnp
    • Hyperwave API
    • LDAP — Lightweight Directory Access Protocol
    • 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
    • 0MQ messaging — ZMQ
    • ZooKeeper
  • Extensii ale motorului de cautare
    • mnoGoSearch
    • Solr — Apache Solr
    • Sphinx — Sphinx Client
    • Swish — Swish Indexing
  • Extensii specifice serverului
    • Apache
    • Managerul de procese FastCGI
    • IIS — IIS Administration
    • NSAPI
  • Extensii de lucru cu sesiuni
    • Msession — Mohawk Software Session Handler Functions
    • Sessions — Session Handling
    • Session PgSQL — PostgreSQL Session Save Handler
  • Procesarea textului
    • BBCode — Bulletin Board Code
    • PCRE — Regular Expressions (Perl-Compatible)
    • POSIX Regex — Regular Expression (POSIX Extended)
    • ssdeep — ssdeep Fuzzy Hashing
    • Strings
  • Extensii referitoare la variabile ?i tipuri
    • Arrays
    • Classes/Objects — Class/Object Information
    • Classkit
    • Ctype — Character type checking
    • Data Structures
    • Filter — Data Filtering
    • Manipularea func?iilor
    • Quickhash
    • Reflection
    • Manipularea variabilelor
  • Servicii Web
    • OAuth
    • SCA
    • SOAP
    • Yar — Yet Another RPC Framework
    • XML-RPC
  • Extensii doar pentru Windows
    • COM — COM and .Net (Windows)
    • win32ps
    • win32service
  • Manipularea XML
    • DOM — Document Object Model
    • libxml
    • SDO — Service Data Objects
    • SDO-DAS-Relational — SDO Relational Data Access Service
    • SDO DAS XML — SDO XML Data Access Service
    • SimpleXML
    • WDDX
    • XMLDiff — XML diff and merge
    • XML Parser
    • XMLReader
    • XMLWriter
    • XSL
  • Extensii GUI
    • UI
Using SystemTap with PHP DTrace Static Probes
Afectarea comportamentului PHP
Manualul PHP


Afectarea comportamentului PHP

  • APC — Alternative PHP Cache
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii APC
    • APCIterator — The APCIterator class
  • APCu — APC User Cache
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii APCu
    • APCUIterator — The APCUIterator class
  • APD — Advanced PHP debugger
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii APD
  • bcompiler — PHP bytecode Compiler
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • bcompiler Func?ii
  • BLENC — Blenc - BLowfish ENCoder for PHP source scripts
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii blenc
  • Error Handling — Error Handling and Logging
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii de gestiune a erorilor
  • htscanner — htaccess-like support for all SAPIs
    • Introducere
    • Instalarea / configurarea
  • inclued — Inclusion hierarchy viewer
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii inclued
  • Memtrack
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
  • OPcache
    • Introducere
    • Instalarea / configurarea
    • Func?ii OPcache
  • Output Control — Output Buffering Control
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii de control a ie?irilor
  • PHP Options/Info — PHP Options and Information
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii pentru op?iuni/informa?ii PHP
  • runkit
    • Introducere
    • Constante predefinite
    • Instalarea / configurarea
    • Func?ii runkit
  • scream — Break the silence operator
    • Introducere
    • Instalarea / configurarea
    • Exemple
  • uopz
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii uopz
  • Weakref — Weak References
    • Introducere
    • Instalarea / configurarea
    • WeakRef — The WeakRef class
    • WeakMap — The WeakMap class
  • WinCache — Windows Cache for PHP
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii WinCache
    • Building for Windows
  • Xhprof — Hierarchical Profiler
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii xhprof
Informa?ii de referin?a despre func?ii
APC
Informa?ii de referin?a despre func?ii


Alternative PHP Cache

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii APC
    • apc_add — Cache a new 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
Afectarea comportamentului PHP
Introducere
Afectarea comportamentului PHP


Introducere

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.

Avertizare

This extension is considered unmaintained and dead. However, the source code for this extension is still available within PECL GIT here: http://git.php.net/?p=pecl/caching/apc.git.

Nota:

Alternatives to this extension are OPcache, APCu, Windows Cache for PHP and the Session Upload Progress API.

APC
Instalarea / configurarea
APC


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
APC


Necesita?i

Nu sunt necesare biblioteci externe pentru a asambla aceasta extensie.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/apc.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

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

Nota: For more in-depth, highly technical implementation details, see the » developer-supplied TECHNOTES file .

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în 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
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.shm_strings_buffer | "4M" | PHP_INI_SYSTEM | Available since APC 3.1.4.
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.serializer | "default" | PHP_INI_SYSTEM | Available since APC 3.1.0.
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 in APC 3.0.14 - 3.1.11.
apc.localcache.size | "512" | PHP_INI_SYSTEM | vailable in APC 3.0.14 - 3.1.11.
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.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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 string

The size of each shared memory segment given by a shorthand notation as described in this FAQ. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.

apc.shm_strings_buffer string

The size of memory to use as a shared buffer for strings used internally by APC. Size Should be suffixed by M for megabytes, G for gigabytes. Enabling this option will reduce the amount of memory used per PHP-FPM worker as strings will be stored once rather than for each worker.

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

Used to configure APC to use a third party serializer.

apc.include_once_override boolean

Optimize include_once and require_once calls and avoid the expensive system calls used.

Avertizare

This feature is EXPERIMENTAL. The behaviour of this directive, its name, and surrounding documentation may change without notice in a future release of APC. This feature should be used at your own risk.

apc.rfc1867 boolean

RFC1867 File Upload Progress hook handler is only available if APC was compiled against PHP 5.2.0 or later. When enabled, any file uploads which includes a field called APC_UPLOAD_PROGRESS before the file field in an upload form will cause APC to automatically create an upload_key user cache entry where key is the value of the APC_UPLOAD_PROGRESS form entry.

Note that the hidden field specified by APC_UPLOAD_PROGRESS must come before the file field, otherwise the upload progress will not work correctly.

Note that the file upload tracking is not threadsafe at this point, so new uploads that happen while a previous one is still going will disable the tracking for the previous.

Note that the rate is only available once all file transfers are completed.

Example #1 An apc.rfc1867 example

<?php
print_r(apc_fetch("upload_$_POST[APC_UPLOAD_PROGRESS]"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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 integer

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.

Avertizare

This feature is potentially dangerous. Unmapping the shared memory segment in a fatal signal handler may cause undefined behaviour if a fatal error occurs.

Nota:

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

Optionally, set a path to the directory that APC will load cache data at startup.

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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)

Tipurile resurselor
Func?ii APC
APC


Func?ii APC

Cuprins

  • apc_add — Cache a new 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
Constante predefinite
apc_add
APC


Cache a new variable in the data store

Func?ii APC
apc_bin_dump
Func?ii APC
PHP Manual

apc_add

(PECL apc >= 3.0.13)

apc_add — Cache a new variable in the data store

Descrierea

bool apc_add ( string $key , mixed $var [, int $ttl = 0 ] )
array apc_add ( array $values [, mixed $unused = NULL [, int $ttl = 0 ]] )

Caches a variable in the data store, only if it's not already stored.

Nota: Unlike many other mechanisms in PHP, variables stored using apc_add() will persist between requests (until the value is removed from the cache).

Parametri

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.

Valorile întoarse

Returns TRUE if something has effectively been added into the cache, FALSE otherwise. Second syntax returns array with error keys.

Exemple

Example #1 A apc_add() example

<?php
$bar = 'BAR';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
$bar = 'NEVER GETS SET';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
?>

Exemplul de mai sus va afi?a:

string(3) "BAR"
string(3) "BAR"

A se vedea ?i

  • 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

Func?ii APC
apc_bin_dump
Func?ii APC


Get a binary dump of the given files and user variables

apc_add
apc_bin_dumpfile
Func?ii APC
PHP Manual

apc_bin_dump

(PECL apc >= 3.1.4)

apc_bin_dump — Get a binary dump of the given files and user variables

Descrierea

string apc_bin_dump ([ array $files = NULL [, array $user_vars = NULL ]] )

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii APC


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

apc_bin_dump
apc_bin_load
Func?ii APC
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

Descrierea

int apc_bin_dumpfile ( array $files , array $user_vars , string $filename [, int $flags = 0 [, resource $context = NULL ]] )

Outputs a binary dump of the given files and user variables from the APC cache to the named file.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii APC


Load a binary dump into the APC file/user cache

apc_bin_dumpfile
apc_bin_loadfile
Func?ii APC
PHP Manual

apc_bin_load

(PECL apc >= 3.1.4)

apc_bin_load — Load a binary dump into the APC file/user cache

Descrierea

bool apc_bin_load ( string $data [, int $flags = 0 ] )

Loads the given binary dump into the APC file/user cache.

Parametri

data

The binary dump being loaded, likely from apc_bin_dump().

flags

Either APC_BIN_VERIFY_CRC32, APC_BIN_VERIFY_MD5, or both.

Valorile întoarse

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

Exemple

Example #1 apc_bin_load() example

<?php
$data = apc_bin_dump(NULL, NULL);
apc_bin_load($data, APC_BIN_VERIFY_MD5 | APC_BIN_VERIFY_CRC32);
?>

A se vedea ?i

  • 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
Func?ii APC


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

apc_bin_load
apc_cache_info
Func?ii APC
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

Descrierea

bool apc_bin_loadfile ( string $filename [, resource $context = NULL [, int $flags = 0 ]] )

Loads a binary dump from a file into the APC file/user cache.

Parametri

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.

Valorile întoarse

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

A se vedea ?i

  • 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
Func?ii APC


Retrieves cached information from APC's data store

apc_bin_loadfile
apc_cas
Func?ii APC
PHP Manual

apc_cache_info

(PECL apc >= 2.0.0)

apc_cache_info — Retrieves cached information from APC's data store

Descrierea

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

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

Parametri

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.

Valorile întoarse

Array of cached data (and meta-data) sau FALSE în cazul e?ecului

Nota: apc_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.

Istoricul schimbarilor

Versiune | Descriere
3.0.11 | The limited parameter was introduced.
3.0.16 | The "filehits" option for the cache_type parameter was introduced.

Exemple

Example #1 A apc_cache_info() example

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

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • 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
Func?ii APC


Updates an old value with a new value

apc_cache_info
apc_clear_cache
Func?ii APC
PHP Manual

apc_cas

(PECL apc >= 3.1.1)

apc_cas — Updates an old value with a new value

Descrierea

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.

Parametri

key

The key of the value being updated.

old

The old value (the value currently stored).

new

The new value to update to.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

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

Exemplul de mai sus va afi?a ceva similar cu:

$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

A se vedea ?i

  • apc_dec() - Decrease a stored number
  • apc_store() - Cache a variable in the data store
apc_cache_info
apc_clear_cache
Func?ii APC


Clears the APC cache

apc_cas
apc_compile_file
Func?ii APC
PHP Manual

apc_clear_cache

(PECL apc >= 2.0.0)

apc_clear_cache — Clears the APC cache

Descrierea

bool apc_clear_cache ([ string $cache_type = "" ] )

Clears the user/system cache.

Parametri

cache_type

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

Valorile întoarse

Returns TRUE always

A se vedea ?i

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

apc_cas
apc_compile_file
Func?ii APC


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

apc_clear_cache
apc_dec
Func?ii APC
PHP Manual

apc_compile_file

(PECL apc >= 3.0.13)

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

Descrierea

mixed apc_compile_file ( string $filename [, bool $atomic = true ] )

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

Parametri

filename

Full or relative path to a PHP file that will be compiled and stored in the bytecode cache.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii APC


Decrease a stored number

apc_compile_file
apc_define_constants
Func?ii APC
PHP Manual

apc_dec

(PECL apc >= 3.1.1)

apc_dec — Decrease a stored number

Descrierea

int apc_dec ( string $key [, int $step = 1 [, bool &$success ]] )

Decreases a stored integer value.

Parametri

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.

Valorile întoarse

Returns the current value of key's value on success, sau FALSE în cazul e?ecului

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Let's do something with success
42
41
31
21
bool(true)

Now, let's fail
bool(false)
bool(false)

A se vedea ?i

  • apc_inc() - Increase a stored number
apc_compile_file
apc_define_constants
Func?ii APC


Defines a set of constants for retrieval and mass-definition

apc_dec
apc_delete_file
Func?ii APC
PHP Manual

apc_define_constants

(PECL apc >= 3.0.0)

apc_define_constants — Defines a set of constants for retrieval and mass-definition

Descrierea

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.

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

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 apc_define_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
echo ONE, TWO, THREE;
?>

Exemplul de mai sus va afi?a:

123

A se vedea ?i

  • 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
Func?ii APC


Deletes files from the opcode cache

apc_define_constants
apc_delete
Func?ii APC
PHP Manual

apc_delete_file

(PECL apc >= 3.1.1)

apc_delete_file — Deletes files from the opcode cache

Descrierea

mixed apc_delete_file ( mixed $keys )

Deletes the given files from the opcode cache.

Parametri

keys

The files to be deleted. Accepts a string, array of strings, or an APCIterator object.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Or if keys is an array, then an empty array is returned on success, or an array of failed files is returned.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)

A se vedea ?i

  • 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
Func?ii APC


Removes a stored variable from the cache

apc_delete_file
apc_exists
Func?ii APC
PHP Manual

apc_delete

(PECL apc >= 3.0.0)

apc_delete — Removes a stored variable from the cache

Descrierea

mixed apc_delete ( string $key )

Removes a stored variable from the cache.

Parametri

key

The key used to store the value (with apc_store()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 A apc_delete() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
apc_delete('foo');
// this is obviously useless in this form
?>

A se vedea ?i

  • apc_store() - Cache a variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache

apc_delete_file
apc_exists
Func?ii APC


Checks if APC key exists

apc_delete
apc_fetch
Func?ii APC
PHP Manual

apc_exists

(PECL apc >= 3.1.4)

apc_exists — Checks if APC key exists

Descrierea

mixed apc_exists ( mixed $keys )

Checks if one or more APC keys exist.

Parametri

keys

A string, or an array of strings, that contain keys.

Valorile întoarse

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.

Exemple

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

?>

Exemplul de mai sus va afi?a ceva similar cu:

Foo exists: apple
Baz does not exist
array(2) {
  ["foo"]=>
  bool(true)
  ["bar"]=>
  bool(true)
}

A se vedea ?i

  • apc_cache_info() - Retrieves cached information from APC's data store
  • apc_fetch() - Fetch a stored variable from the cache
apc_delete
apc_fetch
Func?ii APC


Fetch a stored variable from the cache

apc_exists
apc_inc
Func?ii APC
PHP Manual

apc_fetch

(PECL apc >= 3.0.0)

apc_fetch — Fetch a stored variable from the cache

Descrierea

mixed apc_fetch ( mixed $key [, bool &$success ] )

Fetchs a stored variable from the cache.

Parametri

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.

Valorile întoarse

The stored variable or array of variables on success; FALSE on failure

Exemple

Example #1 A apc_fetch() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

Exemplul de mai sus va afi?a:

string(3) "BAR"

Istoricul schimbarilor

Versiune | Descriere
3.0.17 | The success parameter was added.

A se vedea ?i

  • apc_store() - Cache a variable in the data store
  • apc_delete() - Removes a stored variable from the cache
  • APCIterator

apc_exists
apc_inc
Func?ii APC


Increase a stored number

apc_fetch
apc_load_constants
Func?ii APC
PHP Manual

apc_inc

(PECL apc >= 3.1.1)

apc_inc — Increase a stored number

Descrierea

int apc_inc ( string $key [, int $step = 1 [, bool &$success ]] )

Increases a stored number.

Parametri

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.

Valorile întoarse

Returns the current value of key's value on success, sau FALSE în cazul e?ecului

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

42
43
53
63
bool(true)
Now, let's fail

bool(false)
bool(false)

A se vedea ?i

  • apc_dec() - Decrease a stored number
apc_fetch
apc_load_constants
Func?ii APC


Loads a set of constants from the cache

apc_inc
apc_sma_info
Func?ii APC
PHP Manual

apc_load_constants

(PECL apc >= 3.0.0)

apc_load_constants — Loads a set of constants from the cache

Descrierea

bool apc_load_constants ( string $key [, bool $case_sensitive = true ] )

Loads a set of constants from the cache.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 apc_load_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?>

Exemplul de mai sus va afi?a:

123

A se vedea ?i

  • 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
Func?ii APC


Retrieves APC's Shared Memory Allocation information

apc_load_constants
apc_store
Func?ii APC
PHP Manual

apc_sma_info

(PECL apc >= 2.0.0)

apc_sma_info — Retrieves APC's Shared Memory Allocation information

Descrierea

array apc_sma_info ([ bool $limited = false ] )

Retrieves APC's Shared Memory Allocation information.

Parametri

limited

When set to FALSE (default) apc_sma_info() will return a detailed information about each segment.

Valorile întoarse

Array of Shared Memory Allocation data; FALSE on failure.

Exemple

Example #1 A apc_sma_info() example

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

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [num_seg] => 1
    [seg_size] => 31457280
    [avail_mem] => 31448408
    [block_lists] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [size] => 31448408
                            [offset] => 8864
                        )

                )

        )

)

A se vedea ?i

  • APC configuration directives

apc_load_constants
apc_store
Func?ii APC


Cache a variable in the data store

apc_sma_info
APCIterator
Func?ii APC
PHP Manual

apc_store

(PECL apc >= 3.0.0)

apc_store — Cache a variable in the data store

Descrierea

bool apc_store ( string $key , mixed $var [, int $ttl = 0 ] )
array apc_store ( array $values [, mixed $unused = NULL [, int $ttl = 0 ]] )

Cache a variable in the data store.

Nota: Unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests (until the value is removed from the cache).

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Second syntax returns array with error keys.

Exemple

Example #1 A apc_store() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

Exemplul de mai sus va afi?a:

string(3) "BAR"

A se vedea ?i

  • apc_add() - Cache a new variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache
  • apc_delete() - Removes a stored variable from the cache

apc_sma_info
APCIterator
Func?ii APC


The APCIterator class

(PECL apc >= 3.1.1)

Introducere

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.

Sinopsisul clasei

APCIterator implements Iterator {
/* Methods */
public __construct ( string $cache [, mixed $search = null [, int $format = APC_ITER_ALL [, int $chunk_size = 100 [, int $list = APC_LIST_ACTIVE ]]]] )
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 )
}

Cuprins

  • 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

Descrierea

public APCIterator::__construct ( string $cache [, mixed $search = null [, int $format = APC_ITER_ALL [, int $chunk_size = 100 [, int $list = APC_LIST_ACTIVE ]]]] )

Constructs an APCIterator object.

Parametri

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

Valorile întoarse

An APCIterator object on success, or NULL on failure.

Exemple

Example #1 A APCIterator::__construct() example

<?php
foreach (new APCIterator('user', '/^counter\./') as $counter) {
    echo "$counter[key]: $counter[value]\n";
    apc_dec($counter['key'], $counter['value']);
}
?>

A se vedea ?i

  • 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

Descrierea

public mixed APCIterator::current ( void )

Gets the current item from the APCIterator stack.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current item on success, or FALSE if no more items or exist, or on failure.

A se vedea ?i

  • 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

Descrierea

public int APCIterator::getTotalCount ( void )

Get the total count.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The total count.

A se vedea ?i

  • 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

Descrierea

public int APCIterator::getTotalHits ( void )

Gets the total number of cache hits.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The number of hits on success, or FALSE on failure.

A se vedea ?i

  • 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

Descrierea

public int APCIterator::getTotalSize ( void )

Gets the total cache size.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The total cache size.

A se vedea ?i

  • 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

Descrierea

public string APCIterator::key ( void )

Gets the current iterator key.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the key on success, or FALSE upon failure.

A se vedea ?i

  • 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

Descrierea

public void APCIterator::next ( void )

Moves the iterator pointer to the next element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public void APCIterator::rewind ( void )

Rewinds back the iterator to the first element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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
APCu
APCIterator
PHP Manual

APCIterator::valid

(PECL apc >= 3.1.1)

APCIterator::valid — Checks if current position is valid

Descrierea

public void APCIterator::valid ( void )

Checks if the current iterator position is valid.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the current iterator position is valid, otherwise FALSE.

A se vedea ?i

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


APC User Cache

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii APCu
    • apcu_add — Cache a new variable in the data store
    • apcu_cache_info — Retrieves cached information from APCu's data store
    • apcu_cas — Updates an old value with a new value
    • apcu_clear_cache — Clears the APCu cache
    • apcu_dec — Decrease a stored number
    • apcu_delete — Removes a stored variable from the cache
    • apcu_entry — Atomically fetch or generate a cache entry
    • apcu_exists — Checks if entry exists
    • apcu_fetch — Fetch a stored variable from the cache
    • apcu_inc — Increase a stored number
    • apcu_sma_info — Retrieves APCu Shared Memory Allocation information
    • apcu_store — Cache a variable in the data store
  • APCUIterator — The APCUIterator class
    • APCUIterator::__construct — Constructs an APCUIterator iterator object
    • APCUIterator::current — Get current item
    • APCUIterator::getTotalCount — Get total count
    • APCUIterator::getTotalHits — Get total cache hits
    • APCUIterator::getTotalSize — Get total cache size
    • APCUIterator::key — Get iterator key
    • APCUIterator::next — Move pointer to next item
    • APCUIterator::rewind — Rewinds iterator
    • APCUIterator::valid — Checks if current position is valid
APCIterator::valid
Introducere
Afectarea comportamentului PHP


Introducere

APCu is APC stripped of opcode caching.

The first APCu codebase was versioned 4.0.0, it was forked from the head of the APC master branch at the time.

PHP 7 support is available as of APCu 5.0.0.

APCu can provide a compatibility mode, such that it can provide a drop in replacement for the applicable parts of APC.

APCu
Instalarea / configurarea
APCu


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
APCu


Instalarea

If backward compatibility with the applicable parts of APC is required, APCu must be configured with the option --enable-apcu-bc.

Avertizare

PHP 7 has a separate module (» apc.so) for backwards compatibility with APC.

In backward compatibility mode, APCu registers the applicable APC functions with backward compatible prototypes.

Where an APC function accepted cache_type, it is simply ignored by the backward compatible version, and omitted from the prototype for the APCu version.

Nota: On Windows, APCu 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.

Nota: For more in-depth, highly technical implementation details, see the » developer-supplied TECHNOTES file .

APCu sources can be found » here.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Although the default APCu settings are fine for many installations, serious users should consider tuning the following parameters.

There is one decision to be made configuring APCu. How much memory is going to be allocated to APCu. The ini directive that controls this is apc.shm_size Read the sections on this 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 APCu. If GD is enabled in PHP, it will even display some interesting graphs. If APCu 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 APCu.

When APCu is compiled with mmap support (Memory Mapping), it will use only one memory segment, unlike when APCu 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.

APCu configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
apc.enabled | "1" | PHP_INI_SYSTEM |
apc.shm_segments | "1" | PHP_INI_SYSTEM |
apc.shm_size | "32M" | PHP_INI_SYSTEM |
apc.entries_hint | "4096" | PHP_INI_SYSTEM |
apc.ttl | "0" | PHP_INI_SYSTEM |
apc.gc_ttl | "3600" | PHP_INI_SYSTEM |
apc.mmap_file_mask | NULL | PHP_INI_SYSTEM |
apc.slam_defense | "1" | PHP_INI_SYSTEM |
apc.enable_cli | "0" | PHP_INI_SYSTEM |
apc.use_request_time | "1" | PHP_INI_ALL |
apc.serializer | "default" | PHP_INI_SYSTEM |
apc.rfc1867 | "0" | PHP_INI_SYSTEM |
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 |
apc.coredump_unmap | "0" | PHP_INI_SYSTEM |
apc.preload_path | NULL | PHP_INI_SYSTEM |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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 string

The size of each shared memory segment given by a shorthand notation as described in this FAQ. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.

apc.entries_hint integer

A "hint" about the number of distinct variables that might be stored. 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.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.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.

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

Used to configure APC to use a third party serializer.

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.

Example #1 An apc.rfc1867 example

<?php
print_r(apcu_fetch("upload_$_POST[APC_UPLOAD_PROGRESS]"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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 integer

TTL for rfc1867 entries.

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.

Avertizare

This feature is potentially dangerous. Unmapping the shared memory segment in a fatal signal handler may cause undefined behaviour if a fatal error occurs.

Nota:

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

Optionally, set a path to the directory that APC will load cache data at startup.

apc.use_request_time bool

Use the SAPI request start time for TTL.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)

Tipurile resurselor
Func?ii APCu
APCu


Func?ii APCu

Cuprins

  • apcu_add — Cache a new variable in the data store
  • apcu_cache_info — Retrieves cached information from APCu's data store
  • apcu_cas — Updates an old value with a new value
  • apcu_clear_cache — Clears the APCu cache
  • apcu_dec — Decrease a stored number
  • apcu_delete — Removes a stored variable from the cache
  • apcu_entry — Atomically fetch or generate a cache entry
  • apcu_exists — Checks if entry exists
  • apcu_fetch — Fetch a stored variable from the cache
  • apcu_inc — Increase a stored number
  • apcu_sma_info — Retrieves APCu Shared Memory Allocation information
  • apcu_store — Cache a variable in the data store
Constante predefinite
apcu_add
APCu


Cache a new variable in the data store

Func?ii APCu
apcu_cache_info
Func?ii APCu
PHP Manual

apcu_add

(PECL apcu >= 4.0.0)

apcu_add — Cache a new variable in the data store

Descrierea

bool apcu_add ( string $key , mixed $var [, int $ttl = 0 ] )
array apcu_add ( array $values [, mixed $unused = NULL [, int $ttl = 0 ]] )

Caches a variable in the data store, only if it's not already stored.

Nota: Unlike many other mechanisms in PHP, variables stored using apcu_add() will persist between requests (until the value is removed from the cache).

Parametri

key

Store the variable using this name. keys are cache-unique, so attempting to use apcu_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 apcu_add() and apcu_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.

Valorile întoarse

Returns TRUE if something has effectively been added into the cache, FALSE otherwise. Second syntax returns array with error keys.

Exemple

Example #1 A apcu_add() example

<?php
$bar = 'BAR';
apcu_add('foo', $bar);
var_dump(apcu_fetch('foo'));
echo "\n";
$bar = 'NEVER GETS SET';
apcu_add('foo', $bar);
var_dump(apcu_fetch('foo'));
echo "\n";
?>

Exemplul de mai sus va afi?a:

string(3) "BAR"
string(3) "BAR"

A se vedea ?i

  • apcu_store() - Cache a variable in the data store
  • apcu_fetch() - Fetch a stored variable from the cache
  • apcu_delete() - Removes a stored variable from the cache

Func?ii APCu
apcu_cache_info
Func?ii APCu


Retrieves cached information from APCu's data store

apcu_add
apcu_cas
Func?ii APCu
PHP Manual

apcu_cache_info

(PECL apcu >= 4.0.0)

apcu_cache_info — Retrieves cached information from APCu's data store

Descrierea

array apcu_cache_info ([ bool $limited = false ] )

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

Parametri

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.

Valorile întoarse

Array of cached data (and meta-data) sau FALSE în cazul e?ecului

Nota: apcu_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.

Istoricul schimbarilor

Versiune | Descriere
3.0.11 | The limited parameter was introduced.
3.0.16 | The "filehits" option for the cache_type parameter was introduced.

Exemple

Example #1 A apcu_cache_info() example

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

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [num_slots] => 2000
    [ttl] => 0
    [num_hits] => 9
    [num_misses] => 3
    [start_time] => 1123958803
    [cache_list] => Array
        (
            [0] => Array
                (
                    [filename] => /path/to/apcu_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)
)

A se vedea ?i

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

apcu_add
apcu_cas
Func?ii APCu


Updates an old value with a new value

apcu_cache_info
apcu_clear_cache
Func?ii APCu
PHP Manual

apcu_cas

(PECL apcu >= 4.0.0)

apcu_cas — Updates an old value with a new value

Descrierea

bool apcu_cas ( string $key , int $old , int $new )

apcu_cas() updates an already existing integer value if the old parameter matches the currently stored value with the value of the new parameter.

Parametri

key

The key of the value being updated.

old

The old value (the value currently stored).

new

The new value to update to.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 apcu_cas() example

<?php
apcu_store('foobar', 2);
echo '$foobar = 2', PHP_EOL;
echo '$foobar == 1 ? 2 : 1 = ', (apcu_cas('foobar', 1, 2) ? 'ok' : 'fail'), PHP_EOL;
echo '$foobar == 2 ? 1 : 2 = ', (apcu_cas('foobar', 2, 1) ? 'ok' : 'fail'), PHP_EOL;

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

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

apcu_store('perfection', 'xyz');
echo '$perfection == 2 ? 1 : 2 = ', (apcu_cas('perfection', 2, 1) ? 'ok' : 'epic fail'), PHP_EOL;

echo '$foobar = ', apcu_fetch('foobar'), PHP_EOL;
?>

Exemplul de mai sus va afi?a ceva similar cu:

$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

A se vedea ?i

  • apcu_dec() - Decrease a stored number
  • apcu_store() - Cache a variable in the data store
apcu_cache_info
apcu_clear_cache
Func?ii APCu


Clears the APCu cache

apcu_cas
apcu_dec
Func?ii APCu
PHP Manual

apcu_clear_cache

(PECL apcu >= 4.0.0)

apcu_clear_cache — Clears the APCu cache

Descrierea

bool apcu_clear_cache ( void )

Clears the cache.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE always

A se vedea ?i

  • apcu_cache_info() - Retrieves cached information from APCu's data store

apcu_cas
apcu_dec
Func?ii APCu


Decrease a stored number

apcu_clear_cache
apcu_delete
Func?ii APCu
PHP Manual

apcu_dec

(PECL apcu >= 4.0.0)

apcu_dec — Decrease a stored number

Descrierea

int apcu_dec ( string $key [, int $step = 1 [, bool &$success ]] )

Decreases a stored integer value.

Parametri

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.

Valorile întoarse

Returns the current value of key's value on success, sau FALSE în cazul e?ecului

Exemple

Example #1 apcu_dec() example

<?php
echo "Let's do something with success", PHP_EOL;

apcu_store('anumber', 42);

echo apcu_fetch('anumber'), PHP_EOL;

echo apcu_dec('anumber'), PHP_EOL;
echo apcu_dec('anumber', 10), PHP_EOL;
echo apcu_dec('anumber', 10, $success), PHP_EOL;

var_dump($success);

echo "Now, let's fail", PHP_EOL, PHP_EOL;

apcu_store('astring', 'foo');

$ret = apcu_dec('astring', 1, $fail);

var_dump($ret);
var_dump($fail);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Let's do something with success
42
41
31
21
bool(true)
Now, let's fail

bool(false)
bool(false)

A se vedea ?i

  • apcu_inc() - Increase a stored number
apcu_clear_cache
apcu_delete
Func?ii APCu


Removes a stored variable from the cache

apcu_dec
apcu_entry
Func?ii APCu
PHP Manual

apcu_delete

(PECL apcu >= 4.0.0)

apcu_delete — Removes a stored variable from the cache

Descrierea

bool apcu_delete ( mixed $key )

Removes a stored variable from the cache.

Parametri

key

A key used to store the value as a string for a single key, or as an array of strings for several keys, or as an APCUIterator object.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 A apcu_delete() example

<?php
$bar = 'BAR';
apcu_store('foo', $bar);
apcu_delete('foo');
// this is obviously useless in this form

// Alternatively delete multiple keys.
apcu_delete(['foo', 'bar', 'baz']);

// Or use an Iterator with a regular expression.
apcu_delete(new APCUIterator('#^myprefix_#'));
?>

A se vedea ?i

  • apcu_store() - Cache a variable in the data store
  • apcu_fetch() - Fetch a stored variable from the cache
  • apcu_clear_cache() - Clears the APCu cache
  • APCUIterator

apcu_dec
apcu_entry
Func?ii APCu


Atomically fetch or generate a cache entry

apcu_delete
apcu_exists
Func?ii APCu
PHP Manual

apcu_entry

(PECL apcu >= 5.1.0)

apcu_entry — Atomically fetch or generate a cache entry

Descrierea

mixed apcu_entry ( string $key , callable $generator [, int $ttl = 0 ] )

Atomically attempts to find key in the cache, if it cannot be found generator is called, passing key as the only argument. The return value of the call is then cached with the optionally specified ttl, and returned.

Nota: When control enters apcu_entry() the lock for the cache is acquired exclusively, it is released when control leaves apcu_entry(): In effect, this turns the body of generator into a critical section, disallowing two processes from executing the same code paths concurrently. In addition, it prohibits the concurrent execution of any other APCu functions, since they will acquire the same lock.

Avertizare

The only APCu function that can be called safely by generator is apcu_entry().

Parametri

key

Identity of cache entry

generator

A callable that accepts key as the only argument and returns the value to cache.

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

Valorile întoarse

Returns the cached value

Exemple

Example #1 An apcu_entry() example

<?php
$config = apcu_entry("config", function($key) {
 return [
   "fruit" => apcu_entry("config.fruit", function($key){
     return [
       "apples",
       "pears"
     ];
   }),
   "people" => apcu_entry("config.people", function($key){
     return [
      "bob",
      "joe",
      "niki"
     ];
   })
 ];
});

var_dump($config);
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["fruit"]=>
  array(2) {
    [0]=>
    string(6) "apples"
    [1]=>
    string(5) "pears"
  }
  ["people"]=>
  array(3) {
    [0]=>
    string(3) "bob"
    [1]=>
    string(3) "joe"
    [2]=>
    string(4) "niki"
  }
}

A se vedea ?i

  • apcu_store() - Cache a variable in the data store
  • apcu_fetch() - Fetch a stored variable from the cache
  • apcu_delete() - Removes a stored variable from the cache

apcu_delete
apcu_exists
Func?ii APCu


Checks if entry exists

apcu_entry
apcu_fetch
Func?ii APCu
PHP Manual

apcu_exists

(PECL apcu >= 4.0.0)

apcu_exists — Checks if entry exists

Descrierea

mixed apcu_exists ( mixed $keys )

Checks if one or more APCu entries exist.

Parametri

keys

A string, or an array of strings, that contain keys.

Valorile întoarse

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.

Exemple

Example #1 apcu_exists() example

<?php
$fruit  = 'apple';
$veggie = 'carrot';

apcu_store('foo', $fruit);
apcu_store('bar', $veggie);

if (apcu_exists('foo')) {
    echo "Foo exists: ";
    echo apcu_fetch('foo');
} else {
    echo "Foo does not exist";
}

echo PHP_EOL;
if (apcu_exists('baz')) {
    echo "Baz exists.";
} else {
    echo "Baz does not exist";
}

echo PHP_EOL;

$ret = apcu_exists(array('foo', 'donotexist', 'bar'));
var_dump($ret);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Foo exists: apple
Baz does not exist
array(2) {
  ["foo"]=>
  bool(true)
  ["bar"]=>
  bool(true)
}

A se vedea ?i

  • apcu_cache_info() - Retrieves cached information from APCu's data store
  • apcu_fetch() - Fetch a stored variable from the cache
apcu_entry
apcu_fetch
Func?ii APCu


Fetch a stored variable from the cache

apcu_exists
apcu_inc
Func?ii APCu
PHP Manual

apcu_fetch

(PECL apcu >= 4.0.0)

apcu_fetch — Fetch a stored variable from the cache

Descrierea

mixed apcu_fetch ( mixed $key [, bool &$success ] )

Fetchs an entry from the cache.

Parametri

key

The key used to store the value (with apcu_store()). If an array is passed then each element is fetched and returned.

success

Set to TRUE in success and FALSE in failure.

Valorile întoarse

The stored variable or array of variables on success; FALSE on failure

Exemple

Example #1 A apcu_fetch() example

<?php
$bar = 'BAR';
apcu_store('foo', $bar);
var_dump(apcu_fetch('foo'));
?>

Exemplul de mai sus va afi?a:

string(3) "BAR"

Istoricul schimbarilor

Versiune | Descriere
3.0.17 | The success parameter was added.

A se vedea ?i

  • apcu_store() - Cache a variable in the data store
  • apcu_delete() - Removes a stored variable from the cache
  • APCUIterator

apcu_exists
apcu_inc
Func?ii APCu


Increase a stored number

apcu_fetch
apcu_sma_info
Func?ii APCu
PHP Manual

apcu_inc

(PECL apcu >= 4.0.0)

apcu_inc — Increase a stored number

Descrierea

int apcu_inc ( string $key [, int $step = 1 [, bool &$success ]] )

Increases a stored number.

Parametri

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.

Valorile întoarse

Returns the current value of key's value on success, sau FALSE în cazul e?ecului

Exemple

Example #1 apcu_inc() example

<?php
echo "Let's do something with success", PHP_EOL;

apcu_store('anumber', 42);

echo apcu_fetch('anumber'), PHP_EOL;

echo apcu_inc('anumber'), PHP_EOL;
echo apcu_inc('anumber', 10), PHP_EOL;
echo apcu_inc('anumber', 10, $success), PHP_EOL;

var_dump($success);

echo "Now, let's fail", PHP_EOL, PHP_EOL;

apcu_store('astring', 'foo');

$ret = apcu_inc('astring', 1, $fail);

var_dump($ret);
var_dump($fail);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Let's do something with success
42
43
53
63
bool(true)
Now, let's fail

bool(false)
bool(false)

A se vedea ?i

  • apcu_dec() - Decrease a stored number
apcu_fetch
apcu_sma_info
Func?ii APCu


Retrieves APCu Shared Memory Allocation information

apcu_inc
apcu_store
Func?ii APCu
PHP Manual

apcu_sma_info

(PECL apcu >= 4.0.0)

apcu_sma_info — Retrieves APCu Shared Memory Allocation information

Descrierea

array apcu_sma_info ([ bool $limited = false ] )

Retrieves APCu Shared Memory Allocation information.

Parametri

limited

When set to FALSE (default) apcu_sma_info() will return a detailed information about each segment.

Valorile întoarse

Array of Shared Memory Allocation data; FALSE on failure.

Exemple

Example #1 A apcu_sma_info() example

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

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [num_seg] => 1
    [seg_size] => 31457280
    [avail_mem] => 31448408
    [block_lists] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [size] => 31448408
                            [offset] => 8864
                        )

                )

        )

)

A se vedea ?i

  • APCu configuration directives

apcu_inc
apcu_store
Func?ii APCu


Cache a variable in the data store

apcu_sma_info
APCUIterator
Func?ii APCu
PHP Manual

apcu_store

(PECL apcu >= 4.0.0)

apcu_store — Cache a variable in the data store

Descrierea

bool apcu_store ( string $key , mixed $var [, int $ttl = 0 ] )
array apcu_store ( array $values [, mixed $unused = NULL [, int $ttl = 0 ]] )

Cache a variable in the data store.

Nota: Unlike many other mechanisms in PHP, variables stored using apcu_store() will persist between requests (until the value is removed from the cache).

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Second syntax returns array with error keys.

Exemple

Example #1 A apcu_store() example

<?php
$bar = 'BAR';
apcu_store('foo', $bar);
var_dump(apcu_fetch('foo'));
?>

Exemplul de mai sus va afi?a:

string(3) "BAR"

A se vedea ?i

  • apcu_add() - Cache a new variable in the data store
  • apcu_fetch() - Fetch a stored variable from the cache
  • apcu_delete() - Removes a stored variable from the cache

apcu_sma_info
APCUIterator
Func?ii APCu


The APCUIterator class

(PECL apcu >= 5.0.0)

Introducere

The APCUIterator class makes it easier to iterate over large APCu 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.

Sinopsisul clasei

APCUIterator implements Iterator {
/* Methods */
public __construct ([ mixed $search = null [, int $format = APCU_ITER_ALL [, int $chunk_size = 100 [, int $list = APCU_LIST_ACTIVE ]]]] )
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 )
}

Cuprins

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


Constructs an APCUIterator iterator object

APCUIterator
APCUIterator::current
APCUIterator
PHP Manual

APCUIterator::__construct

(PECL apcu >= 5.0.0)

APCUIterator::__construct — Constructs an APCUIterator iterator object

Descrierea

public APCUIterator::__construct ([ mixed $search = null [, int $format = APCU_ITER_ALL [, int $chunk_size = 100 [, int $list = APCU_LIST_ACTIVE ]]]] )

Constructs an APCUIterator object.

Parametri

search

A PCRE regular expression that matches against APCu 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 or more of the APCU_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 APCU_LIST_ACTIVE or APCU_LIST_DELETED.

Valorile întoarse

An APCUIterator object on success, or NULL on failure.

Exemple

Example #1 A APCUIterator::__construct() example

<?php
foreach (new APCUIterator('/^counter\./') as $counter) {
    echo "$counter[key]: $counter[value]\n";
    apc_dec($counter['key'], $counter['value']);
}
?>

A se vedea ?i

  • apcu_exists() - Checks if entry exists
  • apcu_cache_info() - Retrieves cached information from APCu's data store
APCUIterator
APCUIterator::current
APCUIterator


Get current item

APCUIterator::__construct
APCUIterator::getTotalCount
APCUIterator
PHP Manual

APCUIterator::current

(PECL apcu >= 5.0.0)

APCUIterator::current — Get current item

Descrierea

public mixed APCUIterator::current ( void )

Gets the current item from the APCUIterator stack.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current item on success, or FALSE if no more items or exist, or on failure.

A se vedea ?i

  • APCUIterator::next() - Move pointer to next item
  • Iterator::current() - Return the current element
APCUIterator::__construct
APCUIterator::getTotalCount
APCUIterator


Get total count

APCUIterator::current
APCUIterator::getTotalHits
APCUIterator
PHP Manual

APCUIterator::getTotalCount

(PECL apcu >= 5.0.0)

APCUIterator::getTotalCount — Get total count

Descrierea

public int APCUIterator::getTotalCount ( void )

Get the total count.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The total count.

A se vedea ?i

  • APCUIterator::getTotalHits() - Get total cache hits
  • APCUIterator::getTotalSize() - Get total cache size
  • apcu_cache_info() - Retrieves cached information from APCu's data store
APCUIterator::current
APCUIterator::getTotalHits
APCUIterator


Get total cache hits

APCUIterator::getTotalCount
APCUIterator::getTotalSize
APCUIterator
PHP Manual

APCUIterator::getTotalHits

(PECL apcu >= 5.0.0)

APCUIterator::getTotalHits — Get total cache hits

Descrierea

public int APCUIterator::getTotalHits ( void )

Gets the total number of cache hits.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The number of hits on success, or FALSE on failure.

A se vedea ?i

  • APCUIterator::getTotalCount() - Get total count
  • APCUIterator::getTotalSize() - Get total cache size
  • apcu_cache_info() - Retrieves cached information from APCu's data store
APCUIterator::getTotalCount
APCUIterator::getTotalSize
APCUIterator


Get total cache size

APCUIterator::getTotalHits
APCUIterator::key
APCUIterator
PHP Manual

APCUIterator::getTotalSize

(PECL apcu >= 5.0.0)

APCUIterator::getTotalSize — Get total cache size

Descrierea

public int APCUIterator::getTotalSize ( void )

Gets the total cache size.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The total cache size.

A se vedea ?i

  • APCUIterator::getTotalCount() - Get total count
  • APCUIterator::getTotalHits() - Get total cache hits
  • apc_cache_info() - Retrieves cached information from APC's data store
APCUIterator::getTotalHits
APCUIterator::key
APCUIterator


Get iterator key

APCUIterator::getTotalSize
APCUIterator::next
APCUIterator
PHP Manual

APCUIterator::key

(PECL apcu >= 5.0.0)

APCUIterator::key — Get iterator key

Descrierea

public string APCUIterator::key ( void )

Gets the current iterator key.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the key on success, or FALSE upon failure.

A se vedea ?i

  • APCUIterator::current() - Get current item
  • Iterator::key() - Return the key of the current element
APCUIterator::getTotalSize
APCUIterator::next
APCUIterator


Move pointer to next item

APCUIterator::key
APCUIterator::rewind
APCUIterator
PHP Manual

APCUIterator::next

(PECL apcu >= 5.0.0)

APCUIterator::next — Move pointer to next item

Descrierea

public void APCUIterator::next ( void )

Moves the iterator pointer to the next element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • APCUIterator::current() - Get current item
  • APCUIterator::rewind() - Rewinds iterator
  • Iterator::next() - Move forward to next element
APCUIterator::key
APCUIterator::rewind
APCUIterator


Rewinds iterator

APCUIterator::next
APCUIterator::valid
APCUIterator
PHP Manual

APCUIterator::rewind

(PECL apcu >= 5.0.0)

APCUIterator::rewind — Rewinds iterator

Descrierea

public void APCUIterator::rewind ( void )

Rewinds back the iterator to the first element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • APCUIterator::next() - Move pointer to next item
  • Iterator::next() - Move forward to next element
APCUIterator::next
APCUIterator::valid
APCUIterator


Checks if current position is valid

APCUIterator::rewind
APD
APCUIterator
PHP Manual

APCUIterator::valid

(PECL apcu >= 5.0.0)

APCUIterator::valid — Checks if current position is valid

Descrierea

public void APCUIterator::valid ( void )

Checks if the current iterator position is valid.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the current iterator position is valid, otherwise FALSE.

A se vedea ?i

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


Advanced PHP debugger

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Building on Win32
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • How to use PHP-APD in your scripts
  • Func?ii APD
    • 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
APCUIterator::valid
Introducere
Afectarea comportamentului PHP


Introducere

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.

Precautie

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
Instalarea / configurarea
APD


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Building on Win32
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
APD


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/apd.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

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)

Necesita?i
Building on Win32
Instalarea / configurarea


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.

Instalarea
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

APD Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
apd.dumpdir | NULL | PHP_INI_ALL |
apd.statement_tracing | "0" | PHP_INI_ALL | Available since apd 0.9.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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 |
Tipurile resurselor
Exemple
APD


Exemple

Cuprins

  • How to use PHP-APD in your scripts
Constante predefinite
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.

    Sfat

    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.

Exemple
Func?ii APD
Exemple


Func?ii APD

Informa?ii de contact

Daca ave?i careva comentarii, corectari de bug-uri, îmbunata?iri, sau dori?i sa contribui?i la dezvoltarea acestei fiare, trimite?i un mesaj la » apd@mail.communityconnect.com. Orice ajutor e binevenit.

Cuprins

  • 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

Func?ii APD
apd_callstack
Func?ii APD
PHP Manual

apd_breakpoint

(PECL apd >= 0.2)

apd_breakpoint — Stops the interpreter and waits on a CR from the socket

Descrierea

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.

Parametri

debug_level

Un integer care se formeaza sumând împreuna constante XXX_TRACE.

Nu este recomandabil sa utiliza?i MEMORY_TRACE. Este foarte înceata ?i se pare ca este imprecisa. ASSIGNMENT_TRACE nu este implementata deocamdata.

Pentru a activa toate trasarile func?ionale (TIMING, FUNCTIONS, ARGS SUMMARY (ca în cazul strace -c)) utiliza?i valoarea 99

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Typical session using tcplisten

bash#tcplisten localhost 7777

APD - Advanced PHP Debugger Trace File
---------------------------------------------------------------------------
Process Pid (6118)
Trace Begun at Sun Mar 10 23:13:12 2002
---------------------------------------------------------------------------
(  0.000000): apd_set_session_trace called at /home/alan/Projects/project2/test.
php:5
(  0.074824): apd_set_session_trace_socket() at /home/alan/Projects/project2/tes
t.php:5 returned.  Elapsed (0.074824)
(  0.074918): apd_breakpoint() /home/alan/Projects/project2/test.php:7
              ++ argv[0] $(??) = 9
apd_breakpoint() at /home/alan/Projects/project2/test.php:7 returned.  Elapsed (
-2089521468.1073275368)
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:10
>apd_echo($i);
EXEC: apd_echo($i);
0
>apd_echo(serialize(apd_get_active_symbols()));
EXEC:  apd_echo(serialize(apd_get_active_symbols()));
a:47:{i:0;s:4:"PWD";i:1;s:10:"COLORFGBG";i:2;s:11:"XAUTHORITY";i:3;s:14:"
COLORTERM_BCE";i:4;s:9:"WINDOWID";i:5;s:14:"ETERM_VERSION";i:6;s:16:"SE
SSION_MANAGER";i:7;s:4:"PS1";i:8;s:11:"GDMSESSION";i:9;s:5:"USER";i:10;s:5:"
MAIL";i:11;s:7:"OLDPWD";i:12;s:5:"LANG";i:13;s:10:"COLORTERM";i:14;s:8:"DISP
LAY";i:15;s:8:"LOGNAME";i:16;s:6:"
>apd_echo(system('ls /home/mydir'));
........
>apd_continue(0);

Func?ii APD
apd_callstack
Func?ii APD


Returns the current call stack as an array

apd_breakpoint
apd_clunk
Func?ii APD
PHP Manual

apd_callstack

(PECL apd 0.2-0.4)

apd_callstack — Returns the current call stack as an array

Descrierea

array apd_callstack ( void )

Returns the current call stack as an array

Valorile întoarse

An array containing the current call stack.

Exemple

Example #1 apd_callstack() example

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

apd_breakpoint
apd_clunk
Func?ii APD


Throw a warning and a callstack

apd_callstack
apd_continue
Func?ii APD
PHP Manual

apd_clunk

(PECL apd 0.2-0.4)

apd_clunk — Throw a warning and a callstack

Descrierea

void apd_clunk ( string $warning [, string $delimiter = "<BR />" ] )

Behaves like perl's Carp::cluck. Throw a warning and a callstack.

Parametri

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 apd_clunk() example

<?php
apd_clunk("Some Warning", "<br/>");
?>

A se vedea ?i

  • apd_croak() - Throw an error, a callstack and then exit

apd_callstack
apd_continue
Func?ii APD


Restarts the interpreter

apd_clunk
apd_croak
Func?ii APD
PHP Manual

apd_continue

(PECL apd >= 0.2)

apd_continue — Restarts the interpreter

Descrierea

bool apd_continue ( int $debug_level )

Usually sent via the socket to restart the interpreter.

Parametri

debug_level

Un integer care se formeaza sumând împreuna constante XXX_TRACE.

Nu este recomandabil sa utiliza?i MEMORY_TRACE. Este foarte înceata ?i se pare ca este imprecisa. ASSIGNMENT_TRACE nu este implementata deocamdata.

Pentru a activa toate trasarile func?ionale (TIMING, FUNCTIONS, ARGS SUMMARY (ca în cazul strace -c)) utiliza?i valoarea 99

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 apd_continue() example

<?php
apd_continue(0);
?>

apd_clunk
apd_croak
Func?ii APD


Throw an error, a callstack and then exit

apd_continue
apd_dump_function_table
Func?ii APD
PHP Manual

apd_croak

(PECL apd 0.2-0.4)

apd_croak — Throw an error, a callstack and then exit

Descrierea

void apd_croak ( string $warning [, string $delimiter = "<BR />" ] )

Behaves like perl's Carp::croak. Throw an error, a callstack and then exit.

Parametri

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 apd_croak() example

<?php
apd_croak("Some Warning","<P>");
?>

A se vedea ?i

  • apd_clunk() - Throw a warning and a callstack

apd_continue
apd_dump_function_table
Func?ii APD


Outputs the current function table

apd_croak
apd_dump_persistent_resources
Func?ii APD
PHP Manual

apd_dump_function_table

(Unknown)

apd_dump_function_table — Outputs the current function table

Descrierea

void apd_dump_function_table ( void )

Outputs the current function table.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 apd_dump_function_table() example

<?php
apd_dump_function_table();
?>

apd_croak
apd_dump_persistent_resources
Func?ii APD


Return all persistent resources as an array

apd_dump_function_table
apd_dump_regular_resources
Func?ii APD
PHP Manual

apd_dump_persistent_resources

(PECL apd 0.2-0.4)

apd_dump_persistent_resources — Return all persistent resources as an array

Descrierea

array apd_dump_persistent_resources ( void )

Return all persistent resources as an array.

Valorile întoarse

An array containing the current persistent resources.

Exemple

Example #1 apd_dump_persistent_resources() example

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

A se vedea ?i

  • apd_dump_regular_resources() - Return all current regular resources as an array

apd_dump_function_table
apd_dump_regular_resources
Func?ii APD


Return all current regular resources as an array

apd_dump_persistent_resources
apd_echo
Func?ii APD
PHP Manual

apd_dump_regular_resources

(PECL apd 0.2-0.4)

apd_dump_regular_resources — Return all current regular resources as an array

Descrierea

array apd_dump_regular_resources ( void )

Return all current regular resources as an array.

Valorile întoarse

An array containing the current regular resources.

Exemple

Example #1 apd_dump_regular_resources() example

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

A se vedea ?i

  • apd_dump_persistent_resources() - Return all persistent resources as an array

apd_dump_persistent_resources
apd_echo
Func?ii APD


Echo to the debugging socket

apd_dump_regular_resources
apd_get_active_symbols
Func?ii APD
PHP Manual

apd_echo

(PECL apd >= 0.2)

apd_echo — Echo to the debugging socket

Descrierea

bool apd_echo ( string $output )

Usually sent via the socket to request information about the running script.

Parametri

output

The debugged variable.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 apd_echo() example

<?php
apd_echo($i);
?>

apd_dump_regular_resources
apd_get_active_symbols
Func?ii APD


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

apd_echo
apd_set_pprof_trace
Func?ii APD
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

Descrierea

array apd_get_active_symbols ( void )

Returns the names of all the variables defined in the active scope, (not their values).

Valorile întoarse

A multidimensional array with all the variables.

Exemple

Example #1 apd_get_active_symbols() example

<?php
apd_echo(apd_get_active_symbols());
?>

apd_echo
apd_set_pprof_trace
Func?ii APD


Starts the session debugging

apd_get_active_symbols
apd_set_session_trace_socket
Func?ii APD
PHP Manual

apd_set_pprof_trace

(PECL apd >= 0.2)

apd_set_pprof_trace — Starts the session debugging

Descrierea

string apd_set_pprof_trace ([ string $dump_directory = ini_get("apd.dumpdir") [, string $fragment = "pprof" ]] )

Starts debugging to pprof_{process_id} in the dump directory.

Parametri

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

Valorile întoarse

Returns path of the destination file.

Exemple

Example #1 apd_set_pprof_trace() example

<?php
apd_set_pprof_trace();
?>

A se vedea ?i

  • apd_set_session_trace() - Starts the session debugging

apd_get_active_symbols
apd_set_session_trace_socket
Func?ii APD


Starts the remote session debugging

apd_set_pprof_trace
apd_set_session_trace
Func?ii APD
PHP Manual

apd_set_session_trace_socket

(PECL apd >= 0.2)

apd_set_session_trace_socket — Starts the remote session debugging

Descrierea

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.

Parametri

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.

debug_level

Un integer care se formeaza sumând împreuna constante XXX_TRACE.

Nu este recomandabil sa utiliza?i MEMORY_TRACE. Este foarte înceata ?i se pare ca este imprecisa. ASSIGNMENT_TRACE nu este implementata deocamdata.

Pentru a activa toate trasarile func?ionale (TIMING, FUNCTIONS, ARGS SUMMARY (ca în cazul strace -c)) utiliza?i valoarea 99

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii APD


Starts the session debugging

apd_set_session_trace_socket
apd_set_session
Func?ii APD
PHP Manual

apd_set_session_trace

(PECL apd 0.2-0.4)

apd_set_session_trace — Starts the session debugging

Descrierea

void apd_set_session_trace ( int $debug_level [, string $dump_directory = ini_get("apd.dumpdir") ] )

Starts debugging to apd_dump_{process_id} in the dump directory.

Parametri

debug_level

Un integer care se formeaza sumând împreuna constante XXX_TRACE.

Nu este recomandabil sa utiliza?i MEMORY_TRACE. Este foarte înceata ?i se pare ca este imprecisa. ASSIGNMENT_TRACE nu este implementata deocamdata.

Pentru a activa toate trasarile func?ionale (TIMING, FUNCTIONS, ARGS SUMMARY (ca în cazul strace -c)) utiliza?i valoarea 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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 apd_set_session_trace() example

<?php
apd_set_session_trace(99);
?>

apd_set_session_trace_socket
apd_set_session
Func?ii APD


Changes or sets the current debugging level

apd_set_session_trace
override_function
Func?ii APD
PHP Manual

apd_set_session

(PECL apd 0.2-0.4)

apd_set_session — Changes or sets the current debugging level

Descrierea

void apd_set_session ( int $debug_level )

This can be used to increase or decrease debugging in a different area of your application.

Parametri

debug_level

Un integer care se formeaza sumând împreuna constante XXX_TRACE.

Nu este recomandabil sa utiliza?i MEMORY_TRACE. Este foarte înceata ?i se pare ca este imprecisa. ASSIGNMENT_TRACE nu este implementata deocamdata.

Pentru a activa toate trasarile func?ionale (TIMING, FUNCTIONS, ARGS SUMMARY (ca în cazul strace -c)) utiliza?i valoarea 99

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 apd_set_session() example

<?php
apd_set_session(9);
?>

apd_set_session_trace
override_function
Func?ii APD


Overrides built-in functions

apd_set_session
rename_function
Func?ii APD
PHP Manual

override_function

(PECL apd >= 0.2)

override_function — Overrides built-in functions

Descrierea

bool override_function ( string $function_name , string $function_args , string $function_code )

Overrides built-in functions by replacing them in the symbol table.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 override_function() example

<?php
override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');
?>

apd_set_session
rename_function
Func?ii APD


Renames orig_name to new_name in the global function table

override_function
bcompiler
Func?ii APD
PHP Manual

rename_function

(PECL apd >= 0.2)

rename_function — Renames orig_name to new_name in the global function table

Descrierea

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.

Parametri

original_name

The original function name.

new_name

The new name for the original_name function.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 rename_function() example

<?php
rename_function('mysql_connect', 'debug_mysql_connect' );
?>

override_function
bcompiler
Func?ii APD


PHP bytecode Compiler

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • bcompiler Func?ii
    • 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 a 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 a 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
Introducere
Afectarea comportamentului PHP


Introducere

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

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
Instalarea / configurarea
bcompiler


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
bcompiler


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/bcompiler.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Aceasta extensie nu are directive de configurare definite în php.ini.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
bcompiler Func?ii
bcompiler


bcompiler Func?ii

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.

Cuprins

  • 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 a 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 a 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
Constante predefinite
bcompiler_load_exe
bcompiler


Reads and creates classes from a bcompiler exe file

bcompiler Func?ii
bcompiler_load
bcompiler Func?ii
PHP Manual

bcompiler_load_exe

(PECL bcompiler >= 0.4)

bcompiler_load_exe — Reads and creates classes from a bcompiler exe file

Descrierea

bool bcompiler_load_exe ( string $filename )

Reads data from a bcompiler exe file and creates classes from the bytecodes.

Parametri

filename

The exe file path, as a string.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 bcompiler_load_exe() example

<?php

bcompiler_load_exe("/tmp/example.exe");
print_r(get_defined_classes());

?>

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • bcompiler_load() - Reads and creates classes from a bz compressed file

bcompiler Func?ii
bcompiler_load
bcompiler Func?ii


Reads and creates classes from a bz compressed file

bcompiler_load_exe
bcompiler_parse_class
bcompiler Func?ii
PHP Manual

bcompiler_load

(PECL bcompiler >= 0.4)

bcompiler_load — Reads and creates classes from a bz compressed file

Descrierea

bool bcompiler_load ( string $filename )

Reads data from a bzcompressed file and creates classes from the bytecodes.

Parametri

filename

The bzcompressed file path, as a string.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 bcompiler_load() example

<?php

bcompiler_load("/tmp/example");

print_r(get_defined_classes());

?>

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Nota:

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.

A se vedea ?i

  • bcompiler_load_exe() - Reads and creates classes from a bcompiler exe file

bcompiler_load_exe
bcompiler_parse_class
bcompiler Func?ii


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

bcompiler_load
bcompiler_read
bcompiler Func?ii
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

Descrierea

bool bcompiler_parse_class ( string $class , string $callback )

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

Parametri

class

The class name, as a string.

callback

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 bcompiler_parse_class() example

<?php

function readByteCodes($data) {
    print_r($data);
}

bcompiler_parse_class("DB","readByteCodes");

?>

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Nota:

This function has been removed from bcompiler and is no longer available as of bcompiler 0.5.

bcompiler_load
bcompiler_read
bcompiler Func?ii


Reads and creates classes from a filehandle

bcompiler_parse_class
bcompiler_write_class
bcompiler Func?ii
PHP Manual

bcompiler_read

(PECL bcompiler >= 0.4)

bcompiler_read — Reads and creates classes from a filehandle

Descrierea

bool bcompiler_read ( resource $filehandle )

Reads data from a open file handle and creates classes from the bytecodes.

Parametri

filehandle

A file handle as returned by fopen().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 bcompiler_read() example

<?php
$fh = fopen("/tmp/example","r");
bcompiler_read($fh);
fclose($fh);
print_r(get_defined_classes());

?>

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Nota:

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


Writes a defined class as bytecodes

bcompiler_read
bcompiler_write_constant
bcompiler Func?ii
PHP Manual

bcompiler_write_class

(PECL bcompiler >= 0.4)

bcompiler_write_class — Writes a defined class as bytecodes

Descrierea

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.

Parametri

filehandle

A file handle as returned by fopen().

className

The class name, as a string.

extends

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 bcompiler_write_class() example

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

?>

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Nota:

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.

A se vedea ?i

  • 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 Func?ii


Writes a defined constant as bytecodes

bcompiler_write_class
bcompiler_write_exe_footer
bcompiler Func?ii
PHP Manual

bcompiler_write_constant

(PECL bcompiler >= 0.5)

bcompiler_write_constant — Writes a defined constant as bytecodes

Descrierea

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.

Parametri

filehandle

A file handle as returned by fopen().

constantName

The name of the defined constant, as a string.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 bcompiler_write_constant() example

<?php
define("MODULE_MAX", 30);

$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_constant($fh,"MODULE_MAX");
bcompiler_write_footer($fh);
fclose($fh);

?>

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • 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 Func?ii


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

bcompiler_write_constant
bcompiler_write_file
bcompiler Func?ii
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

Descrierea

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.

Parametri

filehandle

A file handle as returned by fopen().

startpos

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_class() - Writes a 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 Func?ii


Writes a php source file as bytecodes

bcompiler_write_exe_footer
bcompiler_write_footer
bcompiler Func?ii
PHP Manual

bcompiler_write_file

(PECL bcompiler >= 0.6)

bcompiler_write_file — Writes a php source file as bytecodes

Descrierea

bool bcompiler_write_file ( resource $filehandle , string $filename )

This function compiles specified source file into bytecodes, and writes them to the open file handle.

Parametri

filehandle

A file handle as returned by fopen().

filename

The source file path, as a string.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 bcompiler_write_file() example

<?php
$fh = fopen("example.phb", "w");
bcompiler_write_header($fh);
bcompiler_write_file($fh, "example.php");
bcompiler_write_footer($fh);
fclose($fh);
/* the following should be equivalent:
include "example.php";
   and
include "example.phb";
*/
?>

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • 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 Func?ii


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

bcompiler_write_file
bcompiler_write_function
bcompiler Func?ii
PHP Manual

bcompiler_write_footer

(PECL bcompiler >= 0.4)

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

Descrierea

bool bcompiler_write_footer ( resource $filehandle )

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

Parametri

filehandle

A file handle as returned by fopen().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

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

?>

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • bcompiler_write_header() - Writes the bcompiler header

bcompiler_write_file
bcompiler_write_function
bcompiler Func?ii


Writes a defined function as bytecodes

bcompiler_write_footer
bcompiler_write_functions_from_file
bcompiler Func?ii
PHP Manual

bcompiler_write_function

(PECL bcompiler >= 0.5)

bcompiler_write_function — Writes a defined function as bytecodes

Descrierea

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

Parametri

filehandle

A file handle as returned by fopen().

functionName

The function name, as a string.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 bcompiler_write_function() example

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

?>

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • 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 Func?ii


Writes all functions defined in a file as bytecodes

bcompiler_write_function
bcompiler_write_header
bcompiler Func?ii
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 bcompiler_write_functions_from_file() example

<?php
require('module.php');

$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_functions_from_file($fh,'module.php');
bcompiler_write_footer($fh);
fclose($fh);

?>

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • 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 Func?ii


Writes the bcompiler header

bcompiler_write_functions_from_file
bcompiler_write_included_filename
bcompiler Func?ii
PHP Manual

bcompiler_write_header

(PECL bcompiler >= 0.3)

bcompiler_write_header — Writes the bcompiler header

Descrierea

bool bcompiler_write_header ( resource $filehandle [, string $write_ver ] )

Writes the header part of a bcompiler file.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 bcompiler_write_header() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_footer($fh);
fclose($fh);

?>

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

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

bcompiler_write_functions_from_file
bcompiler_write_included_filename
bcompiler Func?ii


Writes an included file as bytecodes

bcompiler_write_header
BLENC
bcompiler Func?ii
PHP Manual

bcompiler_write_included_filename

(PECL bcompiler >= 0.5)

bcompiler_write_included_filename — Writes an included file as bytecodes

Descrierea

bool bcompiler_write_included_filename ( resource $filehandle , string $filename )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

bcompiler_write_header
BLENC
bcompiler Func?ii


Blenc - BLowfish ENCoder for PHP source scripts

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii blenc
    • blenc_encrypt — Encrypt a PHP script with BLENC.
bcompiler_write_included_filename
Introducere
Afectarea comportamentului PHP


Introducere

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

BLENC is a PHP source script protector that:

  • Encodes your source code with the blowfish algorithm.
  • Allows transparent decryption and execution of PHP scripts previously encoded with BLENC.

BLENC is an extension which hooks into the Zend Engine, allowing for transparent encryption and execution of PHP scripts using the blowfish algorithm. It is not designed for complete security (it is still possible to disassemble the script into op codes using a package such as XDebug), however it does keep people out of your code and make reverse engineering difficult.

In order to protect your PHP script you must encrypt each script with blenc_encrypt() function. After you can include the encoded script like the example below:

<?php

/* PHP script encoded with BLENC */
$my_source_encoded = 'my_source_encoded.phpe';

include($my_source_encoded);
?>

BLENC supports also expiration time for the module. So, if you want deploy your source code with a expiration time, you have to compile the extension modifying the header file related to encryption and expiration time. Please see configuration section for further informations.

BLENC
Instalarea / configurarea
BLENC


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
BLENC


Necesita?i

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/blenc

It's strongly recommended to install BLENC from sources without 'pecl' command. In this way you can:

  • Specify your personal encryption key used to create redistributable keys. Your sourcecode will be more difficult to decrypt also for users that can read your key_file on webserver.
  • Specify a expiration date for the BLENC module. With expiration date you can decide that BLENC module on target system will work until a date. After that BLENC will not decrypt any files.
All these configuration options are stored into header file: blenc_protect.h

Please read the content of blenc_protect.h in sources of BLENC to know how set these hardcoded options.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Blenc Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
blenc.key_file | /usr/local/etc/blenckeys | PHP_INI_ALL |

Iata o explica?ie pe scurt a directivelor de configurare.

blenc.key_file string

It's the location where BLENC can find the file containing a list of available decryption keys. This file must be readable by webserver.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

BLENC_EXT_VERSION (string)

Tipurile resurselor
Func?ii blenc
BLENC


Func?ii blenc

Cuprins

  • blenc_encrypt — Encrypt a PHP script with BLENC.
Constante predefinite
blenc_encrypt
BLENC


Encrypt a PHP script with BLENC.

Func?ii blenc
Error Handling
Func?ii blenc
PHP Manual

blenc_encrypt

(PECL blenc >= 5)

blenc_encrypt — Encrypt a PHP script with BLENC.

Descrierea

string blenc_encrypt ( string $plaintext , string $encodedfile [, string $encryption_key ] )

Encrypt the plaintext content and write it into encodedfile

Parametri

plaintext

A source code to encrypt. Does not need to contain opening/closing PHP tags

encodedfile

The filename where BLENC will save the encoded source.

encryption_key

The key that BLENC will use to encrypt plaintext content. If not given BLENC will create a valid key.

Valorile întoarse

BLENC will return the redistributable key that must be saved into key_file: the path of key_file is specified at runtime with the option blenc.key_file

Exemple

Example #1 blenc_encrypt() example

<?php

/* read the PHP source code */
$source_code = file_get_contents("my_source_to_protect.php");

/* create the encrypted version */
$redistributable_key = blenc_encrypt($source_code, "my_source_encoded.php");

/* read which is the key_file */
$key_file = ini_get('blenc.key_file');

/* save the redistributable key */
file_put_contents($key_file, $redistributable_key, FILE_APPEND);
?>

Func?ii blenc
Error Handling
Func?ii blenc


Error Handling and Logging

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii de gestiune a erorilor
    • debug_backtrace — Generates a backtrace
    • debug_print_backtrace — Prints a backtrace
    • error_clear_last — Clear the most recent error
    • error_get_last — Get the last occurred error
    • error_log — Trimite un mesaj de eroare catre rutinele definite de prelucrare a erorilor
    • error_reporting — Stabile?te ce erori PHP vor fi raportate
    • restore_error_handler — Restabile?te func?ia precedenta de gestionare a erorilor
    • restore_exception_handler — Restores the previously defined exception handler function
    • set_error_handler — Stabile?te o func?ie definita de utilizator pentru prelucrarea erorilor
    • set_exception_handler — Sets a user-defined exception handler function
    • trigger_error — Genereaza un mesaj de eroare/avertizare/notificare la nivelul utilizatorului
    • user_error — Pseudonim al trigger_error
blenc_encrypt
Introducere
Afectarea comportamentului PHP


Introducere

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
Instalarea / configurarea
Error Handling


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Error Handling


Instalarea

Nu este necesar de a instala ceva suplimentar pentru a utiliza aceste func?ii; ele fac parte din nucleul PHP.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Errors and Logging Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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 |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

PHP 5.3 or later, the default value is E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED. This setting does not show E_NOTICE, E_STRICT and E_DEPRECATED level errors. You may want to show them during development. Prior to PHP 5.3.0, the default value is E_ALL & ~E_NOTICE & ~E_STRICT. In PHP 4 the default value is E_ALL & ~E_NOTICE.

Nota:

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.

Nota:

In PHP 5 a new error level E_STRICT is available. Prior to PHP 5.4.0 E_STRICT was not included within E_ALL, so you would have to explicitly enable this kind of error level in PHP < 5.4.0. Enabling E_STRICT during development has some benefits. STRICT messages provide suggestions that can help ensure the best interoperability and forward compatibility of your code. These messages may include things such as calling non-static methods statically, defining properties in a compatible class definition while defined in a used trait, and prior to PHP 5.3 some deprecated features would issue E_STRICT errors such as assigning objects by reference upon instantiation.

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

Nota:

This is a feature to support your development and should never be used on production systems (e.g. systems connected to the internet).

Nota:

Although display_errors may be set at runtime (with ini_set()), it won't have any effect 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.

Nota:

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, but not to explicitly called functions such as error_log().

În cazul utilizarii unui integer, valoarea este masurata în octe?i. De asemenea poate fi utilizata nota?ia prescurtata, dupa cum este descris în acest 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

If enabled, error messages will include HTML tags. The 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.

If disabled, error message will be solely plain text.

xmlrpc_errors boolean

If enabled, 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.

Nota:

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.

Nota:

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. See also error_log().

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt întotdeauna disponibile ca parte componenta a nucleului PHP.

Nota: 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 occurred, 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.

Tipurile resurselor
Exemple
Error Handling


Exemple

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.

Example #1 Using error handling in a script

<?php
// we will do our own error handling
error_reporting(0);

// user defined error handling function
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
    // timestamp for the error entry
    $dt = date("Y-m-d H:i:s (T)");

    // define an assoc array of error string
    // in reality the only entries we should
    // consider are E_WARNING, E_NOTICE, E_USER_ERROR,
    // E_USER_WARNING and E_USER_NOTICE
    $errortype = array (
                E_ERROR              => 'Error',
                E_WARNING            => 'Warning',
                E_PARSE              => 'Parsing Error',
                E_NOTICE             => 'Notice',
                E_CORE_ERROR         => 'Core Error',
                E_CORE_WARNING       => 'Core Warning',
                E_COMPILE_ERROR      => 'Compile Error',
                E_COMPILE_WARNING    => 'Compile Warning',
                E_USER_ERROR         => 'User Error',
                E_USER_WARNING       => 'User Warning',
                E_USER_NOTICE        => 'User Notice',
                E_STRICT             => 'Runtime Notice',
                E_RECOVERABLE_ERROR  => 'Catchable Fatal Error'
                );
    // set of errors for which a var trace will be saved
    $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);

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

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

    // for testing
    // echo $err;

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

function distance($vect1, $vect2)
{
    if (!is_array($vect1) || !is_array($vect2)) {
        trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);
        return NULL;
    }

    if (count($vect1) != count($vect2)) {
        trigger_error("Vectors need to be of the same size", E_USER_ERROR);
        return NULL;
    }

    for ($i=0; $i<count($vect1); $i++) {
        $c1 = $vect1[$i]; $c2 = $vect2[$i];
        $d = 0.0;
        if (!is_numeric($c1)) {
            trigger_error("Coordinate $i in vector 1 is not a number, using zero",
                            E_USER_WARNING);
            $c1 = 0.0;
        }
        if (!is_numeric($c2)) {
            trigger_error("Coordinate $i in vector 2 is not a number, using zero",
                            E_USER_WARNING);
            $c2 = 0.0;
        }
        $d += $c2*$c2 - $c1*$c1;
    }
    return sqrt($d);
}

$old_error_handler = set_error_handler("userErrorHandler");

// undefined constant, generates a warning
$t = I_AM_NOT_DEFINED;

// define some "vectors"
$a = array(2, 3, "foo");
$b = array(5.5, 4.3, -1.6);
$c = array(1, -3);

// generate a user error
$t1 = distance($c, $b) . "\n";

// generate another user error
$t2 = distance($b, "i am not an array") . "\n";

// generate a warning
$t3 = distance($a, $b) . "\n";

?>

Constante predefinite
Func?ii de gestiune a erorilor
Error Handling


Func?ii de gestiune a erorilor

A se vedea ?i

Accesa?i de asemenea syslog().

Cuprins

  • debug_backtrace — Generates a backtrace
  • debug_print_backtrace — Prints a backtrace
  • error_clear_last — Clear the most recent error
  • error_get_last — Get the last occurred error
  • error_log — Trimite un mesaj de eroare catre rutinele definite de prelucrare a erorilor
  • error_reporting — Stabile?te ce erori PHP vor fi raportate
  • restore_error_handler — Restabile?te func?ia precedenta de gestionare a erorilor
  • restore_exception_handler — Restores the previously defined exception handler function
  • set_error_handler — Stabile?te o func?ie definita de utilizator pentru prelucrarea erorilor
  • set_exception_handler — Sets a user-defined exception handler function
  • trigger_error — Genereaza un mesaj de eroare/avertizare/notificare la nivelul utilizatorului
  • user_error — Pseudonim al trigger_error
Exemple
debug_backtrace
Error Handling


Generates a backtrace

Func?ii de gestiune a erorilor
debug_print_backtrace
Func?ii de gestiune a erorilor
PHP Manual

debug_backtrace

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

debug_backtrace — Generates a backtrace

Descrierea

array debug_backtrace ([ int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT [, int $limit = 0 ]] )

debug_backtrace() generates a PHP backtrace.

Parametri

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.

Valorile întoarse

Returns an array of associative arrays. The possible returned elements are as follows:

Possible returned elements from debug_backtrace()
Denumire | Tip | Descriere
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).

Istoricul schimbarilor

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

Exemple

Example #1 debug_backtrace() example

<?php
// filename: /tmp/a.php

function a_test($str)
{
    echo "\nHi: $str";
    var_dump(debug_backtrace());
}

a_test('friend');
?>

<?php
// filename: /tmp/b.php
include_once '/tmp/a.php';
?>

Results similar to the following when executing /tmp/b.php:

Hi: friend
array(2) {
[0]=>
array(4) {
    ["file"] => string(10) "/tmp/a.php"
    ["line"] => int(10)
    ["function"] => string(6) "a_test"
    ["args"]=>
    array(1) {
      [0] => &string(6) "friend"
    }
}
[1]=>
array(4) {
    ["file"] => string(10) "/tmp/b.php"
    ["line"] => int(2)
    ["args"] =>
    array(1) {
      [0] => string(10) "/tmp/a.php"
    }
    ["function"] => string(12) "include_once"
  }
}

A se vedea ?i

  • trigger_error() - Genereaza un mesaj de eroare/avertizare/notificare la nivelul utilizatorului
  • debug_print_backtrace() - Prints a backtrace

Func?ii de gestiune a erorilor
debug_print_backtrace
Func?ii de gestiune a erorilor


Prints a backtrace

debug_backtrace
error_clear_last
Func?ii de gestiune a erorilor
PHP Manual

debug_print_backtrace

(PHP 5, PHP 7)

debug_print_backtrace — Prints a backtrace

Descrierea

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.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added the optional parameter limit.
5.3.6 | Added the optional parameter options.

Exemple

Example #1 debug_print_backtrace() example

<?php
// include.php file

function a() {
    b();
}

function b() {
    c();
}

function c(){
    debug_print_backtrace();
}

a();

?>
<?php
// test.php file
// this is the file you should run

include 'include.php';
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • debug_backtrace() - Generates a backtrace

debug_backtrace
error_clear_last
Func?ii de gestiune a erorilor


Clear the most recent error

debug_print_backtrace
error_get_last
Func?ii de gestiune a erorilor
PHP Manual

error_clear_last

(PHP 7)

error_clear_last — Clear the most recent error

Descrierea

void error_clear_last ( void )

Valorile întoarse

Clears the most recent errors, making it unable to be retrieved with error_get_last().

Exemple

Example #1 An error_clear_last() example

<?php
var_dump(error_get_last());
error_clear_last();
var_dump(error_get_last());

@$a = $b;

var_dump(error_get_last());
error_clear_last();
var_dump(error_get_last());
?>

Exemplul de mai sus va afi?a ceva similar cu:

NULL
NULL
array(4) {
  ["type"]=>
  int(8)
  ["message"]=>
  string(21) "Undefined variable: b"
  ["file"]=>
  string(9) "%s"
  ["line"]=>
  int(6)
}
NULL

A se vedea ?i

  • Error constants

debug_print_backtrace
error_get_last
Func?ii de gestiune a erorilor


Get the last occurred error

error_clear_last
error_log
Func?ii de gestiune a erorilor
PHP Manual

error_get_last

(PHP 5 >= 5.2.0, PHP 7)

error_get_last — Get the last occurred error

Descrierea

array error_get_last ( void )

Gets information about the last error that occurred.

Valorile întoarse

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.

Exemple

Example #1 An error_get_last() example

<?php
echo $a;
print_r(error_get_last());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [type] => 8
    [message] => Undefined variable: a
    [file] => C:\WWW\index.php
    [line] => 2
)

A se vedea ?i

  • Error constants
  • Variable $php_errormsg
  • error_clear_last() - Clear the most recent error
  • Directive display_errors
  • Directive html_errors
  • Directive xmlrpc_errors

error_clear_last
error_log
Func?ii de gestiune a erorilor


Trimite un mesaj de eroare catre rutinele definite de prelucrare a erorilor

error_get_last
error_reporting
Func?ii de gestiune a erorilor
PHP Manual

error_log

(PHP 4, PHP 5, PHP 7)

error_log — Trimite un mesaj de eroare catre rutinele definite de prelucrare a erorilor

Descrierea

bool error_log ( string $message [, int $message_type = 0 [, string $destination [, string $extra_headers ]]] )

Trimite un mesaj de eroare în log-ul de erori al server-ului web, sau într-un fi?ier.

Parametri

message

Mesajul de eroare ce trebuie logat.

message_type

Indica unde ar trebui sa fie trimisa eroarea. Tipurile posibile ale mesajului sunt urmatoarele:

Tipurile de logari error_log()
0 | message este transmis log-ului de sistem al PHP utilizând mecanismul de logare al Sistemului de Operare, sau un fi?ier, în dependen?a de setarile directivei de configurare error_log. Aceasta este op?iunea implicita.
1 | message este transmis prin email spre adresa indicata în parametrul destination. Acesta este unicul tip de mesaj, unde se utilizeaza al patrulea parametru extra_headers.
2 | Aceasta op?iune nu mai exista deja.
3 | message este adaugat la sfâr?itul fi?ierului destination. Sfâr?itul de linie nu este adaugat automat la string-ul message.
4 | message este transmis direct spre func?ia de logare SAPI.

destination

Destina?ia. Semnifica?ia acesteia depinde de valoarea parametrului message_type descris mai sus.

extra_headers

Antete suplimentare. Acestea sunt utilizate în caz ca parametrul message_type are valoarea 1. Acest tip de mesaj utilizeaza aceea?i func?ie interna ca ?i mail().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Avertizare

error_log() nu este sigura binar. message va fi trunchiat de caracterul null.

Sfat

message nu trebuie sa con?ina caracterul null. Observa?i ca message poate fi transmis într-un fi?ier, mail, syslog, etc. Utiliza?i func?iile de convertire/evadare necesare, base64_encode(), rawurlencode() sau addslashes() înainte de a apela error_log().

Exemple

Example #1 Exemple error_log()

<?php
// Trimite o în?tiin?are prin intermediul log-ului server-ului în caz ca nu este
// posibila conectarea la baza de date.
if (!Ora_Logon($username, $password)) {
    error_log("Baza de date Oracle nu este disponibila!", 0);
}

// În?tiin?eaza administratorul prin email daca ramânem fara FOO
if (!($foo = allocate_new_foo())) {
    error_log("Nevoie mare, nu mai avem FOO!", 1,
               "operator@example.com");
}

// Un alt mod de a apela error_log():
error_log("Ai dat-o în bara!", 3, "/var/tmp/my-errors.log");
?>

Istoricul schimbarilor

Versiune | Descriere
5.2.7 | A fost adaugata valoarea posibila 4 la message_type.

error_get_last
error_reporting
Func?ii de gestiune a erorilor


Stabile?te ce erori PHP vor fi raportate

error_log
restore_error_handler
Func?ii de gestiune a erorilor
PHP Manual

error_reporting

(PHP 4, PHP 5, PHP 7)

error_reporting — Stabile?te ce erori PHP vor fi raportate

Descrierea

int error_reporting ([ int $level ] )

Func?ia error_reporting() stabile?te directiva error_reporting în timpul rularii. PHP poseda multe nivele de erori, iar utilizarea acestei func?ii va permite sa stabili?i nivelul ce va fi activ pe durata execu?iei script-ului dumneavoastra. Daca parametrul op?ional level nu este stabilit, error_reporting() va întoarce doar nivelul curent de raportare a erorilor.

Parametri

level

Noul nivel error_reporting. Poate fi indicat fie printr-o masca de bi?i, sau prin constante denumite. Utilizarea constantelor denumite este încurajata pentru a se asigura compatibilitatea cu versiunile viitoare. Odata cu adaugarea noilor nivele de erori, domeniul constantelor întregi cre?te, de aceea nivelele de erori vechi bazate pe constante întregi nu se vor comporta întotdeauna conform a?teptarilor.

Constantele disponibile ale nivelelor de erori sunt enumarate mai jos. Semnifica?iile acestor nivele de erori sunt descrise în constante predefinite.

Valorile întoarse

Întoarce vechiul nivel error_reporting sau nivelul curent daca parametrul level nu este furnizat.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | E_STRICT a devenit parte componenta a E_ALL.
5.3.0 | Au fost introduse E_DEPRECATED ?i E_USER_DEPRECATED.
5.2.0 | A fost introdusa E_RECOVERABLE_ERROR.
5.0.0 | A fost introdusa E_STRICT (nu face parte din E_ALL).

Exemple

Example #1 Exemple error_reporting()

<?php

// Suprima toate raportarile erorilor
error_reporting(0);

// Raporteaza erorile simple la rulare
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Raportarea E_NOTICE de asemenea poate fi utila (pentru a afla variabile
// neini?ializate sau pentru a intercepta gre?eli de tipar în denumirile
// variablelor ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Raporteaza toate erorile cu excep?ia E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Raporteaza toate erorile PHP (vezi jurnalul schimbarilor)
error_reporting(E_ALL);

// Raporteaza toate erorile PHP
error_reporting(-1);

// La fel ca ?i error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

?>

Note

Avertizare

Majoritatea erorilor E_STRICT sunt evaluate la momentul compilarii, de aceea astfel de erori nu sunt raportate în fi?ier când în error_reporting sunt incluse ?i erorile E_STRICT (?i vice versa).

Sfat

Transmiterea valorii -1 va afi?a toate erorile posibile, chiar ?i atunci când vor fi adaugate nivele ?i constante noi în versiunile viitoare ale PHP. Constanta E_ALL se comporta în acela?i mod începând cu PHP 5.4.

A se vedea ?i

  • Directiva display_errors
  • Directiva html_errors
  • Directiva xmlrpc_errors
  • ini_set() - Sets the value of a configuration option

error_log
restore_error_handler
Func?ii de gestiune a erorilor


Restabile?te func?ia precedenta de gestionare a erorilor

error_reporting
restore_exception_handler
Func?ii de gestiune a erorilor
PHP Manual

restore_error_handler

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

restore_error_handler — Restabile?te func?ia precedenta de gestionare a erorilor

Descrierea

bool restore_error_handler ( void )

Se utilizeaza dupa modificarea func?iei de gestionare a erorilor cu ajutorul set_error_handler(), pentru a reveni la gestionarul erorilor precedent (care poate fi cel încorporat, sau o func?ie definita de utilizator).

Valorile întoarse

Aceasta func?ie întotdeuna întoarce TRUE.

Exemple

Example #1 Exemplu restore_error_handler()

Decide daca unserialize() a cauzat o eroare, apoi restabile?te gestionarul de erori original.

<?php
function unserialize_handler($errno, $errstr)
{
    echo "Invalid serialized value.\n";
}

$serialized = 'foo';
set_error_handler('unserialize_handler');
$original = unserialize($serialized);
restore_error_handler();
?>

Exemplul de mai sus va afi?a:

Invalid serialized value.

A se vedea ?i

  • error_reporting() - Stabile?te ce erori PHP vor fi raportate
  • set_error_handler() - Stabile?te o func?ie definita de utilizator pentru prelucrarea erorilor
  • restore_exception_handler() - Restores the previously defined exception handler function
  • trigger_error() - Genereaza un mesaj de eroare/avertizare/notificare la nivelul utilizatorului

error_reporting
restore_exception_handler
Func?ii de gestiune a erorilor


Restores the previously defined exception handler function

restore_error_handler
set_error_handler
Func?ii de gestiune a erorilor
PHP Manual

restore_exception_handler

(PHP 5, PHP 7)

restore_exception_handler — Restores the previously defined exception handler function

Descrierea

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

Valorile întoarse

This function always returns TRUE.

Exemple

Example #1 restore_exception_handler() example

<?php
    function exception_handler_1(Exception $e)
    {
        echo '[' . __FUNCTION__ . '] ' . $e->getMessage();
    }

    function exception_handler_2(Exception $e)
    {
        echo '[' . __FUNCTION__ . '] ' . $e->getMessage();
    }

    set_exception_handler('exception_handler_1');
    set_exception_handler('exception_handler_2');

    restore_exception_handler();

    throw new Exception('This triggers the first exception handler...');
?>

Exemplul de mai sus va afi?a:

[exception_handler_1] This triggers the first exception handler...

A se vedea ?i

  • set_exception_handler() - Sets a user-defined exception handler function
  • set_error_handler() - Stabile?te o func?ie definita de utilizator pentru prelucrarea erorilor
  • restore_error_handler() - Restabile?te func?ia precedenta de gestionare a erorilor
  • error_reporting() - Stabile?te ce erori PHP vor fi raportate

restore_error_handler
set_error_handler
Func?ii de gestiune a erorilor


Stabile?te o func?ie definita de utilizator pentru prelucrarea erorilor

restore_exception_handler
set_exception_handler
Func?ii de gestiune a erorilor
PHP Manual

set_error_handler

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

set_error_handler — Stabile?te o func?ie definita de utilizator pentru prelucrarea erorilor

Descrierea

mixed set_error_handler ( callable $error_handler [, int $error_types = E_ALL | E_STRICT ] )

Stabile?te o func?ie a utilizatorului (error_handler) pentru a prelucra erorile într-un script.

Aceasta func?ie poate fi utilizata pentru definirea propriului dumneavoastra mod de a prelucra erorile în timpul rularii, spre exemplu în aplica?ii în care este nevoie de a efectua cura?irea datelor / fi?ierelor atunci când survine o eroare critica, sau când ave?i nevoie sa declan?a?i o eroare în anumite circumstan?e (utilizând trigger_error()).

Este important de a ?ine minte ca func?ia standarda de prelucrare a erorii a PHP este ocolita complet pentru tipurile de erori specificate în error_types daca func?ia de apel invers nu întoarce FALSE. Setarile error_reporting() nu vor avea nici un efect ?i func?ia dumneavoastra de prelucrare a erorii va fi apelata în orice caz - însa pute?i totu?i citi valoarea curenta a error_reporting ?i sa ac?iona?i corespunzator. Merita de men?ionat ca aceasta valoare va fi 0 daca instruc?iunea care a cauzat eroarea a fost prefixata cu operatorul de control al erorii @.

De asemenea observa?i ca este responsabilitatea dumneavoastra sa efectua?i die() daca este necesar. Daca func?ia de prelucrare a erorii întoarce controlul execu?iei, execu?ia scriptului continua cu urmatoarea instruc?iune dupa acea care a cauzat eroarea.

Urmatoarele tipuri de erori nu pot fi prelucrate de o func?ie definita de utilizator: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING ?i majoritatea E_STRICT ce survin în fi?ier, unde set_error_handler() este apelat.

Daca erorile survin înainte de execu?ia script-ului (de ex. la încarcarea fi?ierelor), func?iile proprii de prelucrare a erorilor nu pot fi apelate, deoarece înca nu sunt înregistrate la acel moment.

Parametri

error_handler

O func?ie de apel invers cu urmatoarea semnatura NULL poate fi transmisa pentru a restabili acest handler la starea sa implicita. În loc de denumirea func?iei, un tablou ce con?ine o referin?a la obiect ?i denumirea metodei pot fi furnizate.

bool handler ( int $errno , string $errstr [, string $errfile [, int $errline [, array $errcontext ]]] )
errno
Primul parametru, errno, con?ine nivelul erorii (tip integer).
errstr
Al doilea parametru, errstr, con?ine mesajul de eroare (tip string).
errfile
Al treilea parametru op?ional, errfile, con?ine denumirea fi?ierului în care a avut loc eroarea (tip string).
errline
Al patrulea parametru op?ional, errline, con?ine numarul liniei unde a avut loc eroarea (tip integer).
errcontext
Al cincilea parametru op?ional, errcontext, este un tablou ce indica spre tabelul de simboluri activ la momentul când a avut loc eroarea. Cu alte cuvinte, errcontext va con?ine un tablou cu toate variabilele ce au existat în contextul în care s-a produs eroarea. Func?ia de prelucrare a erorii definita de utilizator nu trebuie sa modifice contextul erorii.

Daca func?ia întoarce FALSE, atunci func?ia normala de gestiune a erorii continua.

error_types

Poate fi utilizat pentru a masca declan?area func?iei error_handler în mod asemanator cum setarea ini error_reporting controleaza care erori sunt afi?ate. Fara aceasta masca stabilita error_handler va fi apelata la orice eroare, indiferent de setarile error_reporting.

Valorile întoarse

Întoarce un string con?inând func?ia de prelucrare a erorii definita anterior (daca exista). Daca se utilizeaza func?ia implicita de prelucrare a erorii, va fi întors NULL. NULL este întors de asemenea ?i în cazul unei erori, cum ar fi o func?ie de prelucrare a erorii invalida. Daca func?ia precedenta de prelucrare a erorii era o metoda a unei clase, aceasta func?ie va întoarce un tablou indexat, incluzând clasa ?i denumirea metodei.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | error_handler acum accepta NULL.
5.2.0 | Func?ia de prelucrare a erorii trebuie sa întoarca FALSE pentru a popula $php_errormsg.

Exemple

Example #1 Controlul erorilor cu set_error_handler() ?i trigger_error()

Exemplul ce urmeaza demonstreaza prelucrarea excep?iilor interne prin generarea erorilor ?i prelucrarea lor cu ajutorul unei func?ii definite de utilizator:

<?php
// Func?ia de prelucrare a erorilor
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if (!(error_reporting() & $errno)) {
        // Acest cod de eroare nu este inclus în 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;
    }

    /* Nu executa func?ia interna a PHP de prelucrare a erorii */
    return true;
}

// Func?ie pentru a verifica prelucrarea erorilor
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;
}

// Se stabile?te func?ia de prelucrare a erorilor definita de utilizator
$old_error_handler = set_error_handler("myErrorHandler");

// declan?am unele erori, în primul rând definim un tablou mixt cu un element non-numeric
echo "vector a\n";
$a = array(2, 3, "foo", 5.5, 43.3, 21.11);
print_r($a);

// acum generam urmatorul tablou
echo "----\nvector b - a notice (b = log(PI) * a)\n";
/* Valoarea din pozi?ia $pos nu este un numar, se va utiliza 0 (zero) */
$b = scale_by_log($a, M_PI);
print_r($b);

// aici este o problema: se transmite un string în loc de un array
echo "----\nvector c - a warning\n";
/* Vector de intrare incorect, se a?teapta un tablou de valori */
$c = scale_by_log("not array", 2.3);
var_dump($c); // NULL

// aceasta este o eroare critica, logaritmul lui zero, sau a unui numar negativ este nedefinit
echo "----\nvector d - fatal error\n";
/* log(x) pentru x <= 0 nu este definit, a?i utilizat: scale = $scale" */
$d = scale_by_log($a, -2.5);
var_dump($d); // Niciodata nu se ajunge aici
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • ErrorException
  • error_reporting() - Stabile?te ce erori PHP vor fi raportate
  • restore_error_handler() - Restabile?te func?ia precedenta de gestionare a erorilor
  • trigger_error() - Genereaza un mesaj de eroare/avertizare/notificare la nivelul utilizatorului
  • constantele nivelelor de erori
  • informa?ie despre tipul callback

restore_exception_handler
set_exception_handler
Func?ii de gestiune a erorilor


Sets a user-defined exception handler function

set_error_handler
trigger_error
Func?ii de gestiune a erorilor
PHP Manual

set_exception_handler

(PHP 5, PHP 7)

set_exception_handler — Sets a user-defined exception handler function

Descrierea

callable set_exception_handler ( callable $exception_handler )

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.

Parametri

exception_handler

Name of the function to be called when an uncaught exception occurs. This handler function needs to accept one parameter, which will be the exception object that was thrown. This is the handler signature before PHP 7:

void handler ( Exception $ex )

Since PHP 7, most errors are reported by throwing Error exceptions, which will be caught by the handler as well. Both Error and Exception implements the Throwable interface. This is the handler signature since PHP 7:

void handler ( Throwable $ex )

NULL may be passed instead, to reset this handler to its default state.

Precautie

Note that providing an explicit Exception type hint for the ex parameter in your callback will cause issues with the changed exception hierarchy in PHP 7.

Valorile întoarse

Returns the name of the previously defined exception handler, or NULL on error. If no previous handler was defined, NULL is also returned.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | The type of parameter passed into exception_handler changed from Exception to Throwable
5.5.0 | Previously, if NULL was passed then this function returned TRUE. It returns the previous handler since PHP 5.5.0.

Exemple

Example #1 set_exception_handler() example

<?php
function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>

A se vedea ?i

  • restore_exception_handler() - Restores the previously defined exception handler function
  • restore_error_handler() - Restabile?te func?ia precedenta de gestionare a erorilor
  • error_reporting() - Stabile?te ce erori PHP vor fi raportate
  • informa?ie despre tipul callback
  • PHP 5 Exceptions

set_error_handler
trigger_error
Func?ii de gestiune a erorilor


Genereaza un mesaj de eroare/avertizare/notificare la nivelul utilizatorului

set_exception_handler
user_error
Func?ii de gestiune a erorilor
PHP Manual

trigger_error

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

trigger_error — Genereaza un mesaj de eroare/avertizare/notificare la nivelul utilizatorului

Descrierea

bool trigger_error ( string $error_msg [, int $error_type = E_USER_NOTICE ] )

Utilizata pentru a declan?a o condi?ie de eroare la nivel de utilizator, ea poate fi utilizata în combina?ie cu handler-ul de erori încorporat, sau cu o func?ie definita de utilizator care a fost stabilita ca un nou handler al erorii (set_error_handler()).

Aceasta func?ie este utila atunci când ave?i nevoie sa genera?i un raspuns anumit la apari?ia unei excep?ii în timpul rularii.

Parametri

error_msg

Mesajul desemnat pentru aceata eroare. Lungimea este limitata la 1024 octe?i. Toate caracterele peste lungimea de 1024 octe?i vor fi trunchiate.

error_type

Tipul erorii desemnat pentru aceasta eroare. Aceasta func?ioneaza numai cu familia de constante E_USER, ?i va avea valoarea implicita E_USER_NOTICE.

Valorile întoarse

Aceasta func?ie întoarce FALSE daca error_type este specificat, TRUE în caz contrar.

Exemple

Example #1 Exemplu trigger_error()

Accesa?i set_error_handler() pentru un exemplu mai detaliat.

<?php
if ($divisor == 0) {
    trigger_error("Diviziune la zero", E_USER_ERROR);
}
?>

Note

Avertizare

Entita?ile HTML din error_msg nu sunt "evadate". Utiliza?i htmlentities() asupra mesajului daca eroarea trebuie afi?ata într-un navigator.

A se vedea ?i

  • error_reporting() - Stabile?te ce erori PHP vor fi raportate
  • set_error_handler() - Stabile?te o func?ie definita de utilizator pentru prelucrarea erorilor
  • restore_error_handler() - Restabile?te func?ia precedenta de gestionare a erorilor
  • Constantele nivelelor de eroare

set_exception_handler
user_error
Func?ii de gestiune a erorilor


Pseudonim al trigger_error

trigger_error
htscanner
Func?ii de gestiune a erorilor
PHP Manual

user_error

(PHP 4, PHP 5, PHP 7)

user_error — Pseudonim al trigger_error()

Descrierea

Aceasta func?ie este pseudonim pentru: trigger_error().

trigger_error
htscanner
Func?ii de gestiune a erorilor


htaccess-like support for all SAPIs

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
user_error
Introducere
Afectarea comportamentului PHP


Introducere

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 (IIS5/6/7, lighttpd, etc.).

htscanner
Instalarea / configurarea
htscanner


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
htscanner


Necesita?i

PHP de versiunea 5.2.0 sau ulterioara.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/htscanner

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

htscanner Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | 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 |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
inclued
Instalarea / configurarea


Inclusion hierarchy viewer

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Example that implements inclued into an application
  • Func?ii inclued
    • inclued_get_data — Get the inclued data
Tipurile resurselor
Introducere
Afectarea comportamentului PHP


Introducere

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
Instalarea / configurarea
inclued


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
inclued


Necesita?i

PHP version 5.1.0 or greater.

The included gengraph.php file utilizes the » graphviz library, however, this is not required.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/inclued

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

inclued Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
inclued.enabled | Off | PHP_INI_SYSTEM |
inclued.dumpdir | NULL | PHP_INI_SYSTEM |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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

Precautie

Because every request creates a file, this directory may fill up fast!

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
inclued


Exemple

Cuprins

  • Example that implements inclued into an application
Constante predefinite
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.

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

Example #2 Example use of gengraph.php

This example creates an image named inclued.png that shows the inclued data.

# First, create the dot file
$ php gengraph.php -i /tmp/wp.ser -o wp.dot

# Next, create the image
$ dot -Tpng -o inclued.png wp.dot

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

Exemplul de mai sus va afi?a ceva similar cu:

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

Exemple
Func?ii inclued
Exemple


Func?ii inclued

Cuprins

  • inclued_get_data — Get the inclued data
Example that implements inclued into an application
inclued_get_data
inclued


Get the inclued data

Func?ii inclued
Memtrack
Func?ii inclued
PHP Manual

inclued_get_data

(PECL inclued >= 0.1.0)

inclued_get_data — Get the inclued data

Descrierea

array inclued_get_data ( void )

Get the inclued data.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The inclued data.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
  [includes] => Array
    (
      [0] => Array
        (
          [operation] => include
          [op_type] => 2
          [filename] => x.php
          [opened_path] => /tmp/x.php
          [fromfile] => /tmp/z.php
          [fromline] => 2
        )
    )
)

A se vedea ?i

  • inclued examples
  • debug_backtrace() - Generates a backtrace
  • include - include

Func?ii inclued
Memtrack
Func?ii inclued


Memtrack

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic usage
inclued_get_data
Introducere
Afectarea comportamentului PHP


Introducere

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.

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

Memtrack
Instalarea / configurarea
Memtrack


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Memtrack


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/memtrack

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Memtrack Configuration Options
Denumire | Valoare implicita | Poate fi modificata
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
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
Memtrack


Exemple

Cuprins

  • Basic usage
Constante predefinite
Basic usage
Memtrack


Basic usage

Basic example on using memtrack extension:

Example #1 Creating large array in a function

<?php

/* /tmp/example1.php */

function foo() {
    $a = array();
    for ($i = 0; $i < 10000; $i++) $a[] = "test";
    return $a;
}
$arr = foo();

?>

Run the example with the following command:

php -d memtrack.enabled=1 -d memtrack.soft_limit=1M -d memtrack.vm_limit=3M /tmp/example1.php

Exemplul de mai sus va afi?a ceva similar cu:

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
Exemple
OPcache
Exemple


OPcache

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Func?ii OPcache
    • opcache_compile_file — Compiles and caches a PHP script without executing it
    • opcache_get_configuration — Get configuration information about the cache
    • opcache_get_status — Get status information about the cache
    • opcache_invalidate — Invalidates a cached script
    • opcache_is_script_cached — Tells whether a script is cached in OPCache
    • opcache_reset — Resets the contents of the opcode cache
Basic usage
Introducere
Afectarea comportamentului PHP


Introducere

OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request.

This extension is bundled with PHP 5.5.0 and later, and is » available in PECL for PHP versions 5.2, 5.3 and 5.4.

OPcache
Instalarea / configurarea
OPcache


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
OPcache


Instalarea

The process of installing OPcache varies depending on which version of PHP you're running. Please refer to the appropriate section below.

Nota:

If you want to use OPcache with » Xdebug, you must load OPcache before Xdebug.

PHP 5.5.0 and later

OPcache can only be compiled as a shared extension. If you have disabled the building of default extensions with --disable-all , you must compile PHP with the --enable-opcache option for OPcache to be available.

Once compiled, you can use the zend_extension configuration directive to load the OPcache extension into PHP. This can be done with zend_extension=/full/path/to/opcache.so on non-Windows platforms, and zend_extension=C:\path\to\php_opcache.dll on Windows.

PHP 5.2, 5.3 and 5.4

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/ZendOpcache.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Recommended php.ini settings

The following settings are generally recommended as providing good performance:

opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=1

You may also want to consider disabling opcache.save_comments and enabling opcache.enable_file_override, however note that you will have to test your code before using these in production as they are known to break some frameworks and applications, particularly in cases where documentation comment annotations are used.

A full list of configuration directives supported by OPcache is also available.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

OPcache configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
opcache.enable | "1" | PHP_INI_ALL |
opcache.enable_cli | "0" | PHP_INI_SYSTEM |
opcache.memory_consumption | "64" | PHP_INI_SYSTEM |
opcache.interned_strings_buffer | "4" | PHP_INI_SYSTEM |
opcache.max_accelerated_files | "2000" | PHP_INI_SYSTEM |
opcache.max_wasted_percentage | "5" | PHP_INI_SYSTEM |
opcache.use_cwd | "1" | PHP_INI_SYSTEM |
opcache.validate_timestamps | "1" | PHP_INI_ALL |
opcache.revalidate_freq | "2" | PHP_INI_ALL |
opcache.revalidate_path | "0" | PHP_INI_ALL |
opcache.save_comments | "1" | PHP_INI_SYSTEM |
opcache.load_comments | "1" | PHP_INI_ALL |
opcache.fast_shutdown | "0" | PHP_INI_SYSTEM |
opcache.enable_file_override | "0" | PHP_INI_SYSTEM |
opcache.optimization_level | "0xffffffff" | PHP_INI_SYSTEM |
opcache.inherited_hack | "1" | PHP_INI_SYSTEM |
opcache.dups_fix | "0" | PHP_INI_ALL |
opcache.blacklist_filename | "" | PHP_INI_SYSTEM |
opcache.max_file_size | "0" | PHP_INI_SYSTEM |
opcache.consistency_checks | "0" | PHP_INI_ALL |
opcache.force_restart_timeout | "180" | PHP_INI_SYSTEM |
opcache.error_log | "" | PHP_INI_SYSTEM |
opcache.log_verbosity_level | "1" | PHP_INI_SYSTEM |
opcache.preferred_memory_model | "" | PHP_INI_SYSTEM |
opcache.protect_memory | "0" | PHP_INI_SYSTEM |
opcache.mmap_base | NULL | PHP_INI_SYSTEM |
opcache.restrict_api | "" | PHP_INI_SYSTEM |
opcache.file_cache | NULL | PHP_INI_SYSTEM | Available as of PHP 7.0.0
opcache.file_cache_only | "0" | PHP_INI_SYSTEM | Available as of PHP 7.0.0
opcache.file_cache_consistency_checks | "1" | PHP_INI_SYSTEM | Available as of PHP 7.0.0
opcache.file_cache_fallback | "1" | PHP_INI_SYSTEM | Available as of PHP 7.0.0
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

opcache.enable boolean

Enables the opcode cache. When disabled, code is not optimised or cached. The setting opcache.enable can not be enabled at runtime through ini_set(), it can only be disabled. Trying to enable it at in a script will generate a warning.

opcache.enable_cli boolean

Enables the opcode cache for the CLI version of PHP. This is mostly useful for testing and debugging.

opcache.memory_consumption integer

The size of the shared memory storage used by OPcache, in megabytes.

opcache.interned_strings_buffer integer

The amount of memory used to store interned strings, in megabytes. This configuration directive is ignored in PHP < 5.3.0.

opcache.max_accelerated_files integer

The maximum number of keys (and therefore scripts) in the OPcache hash table. The actual value used will be the first number in the set of prime numbers { 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987 } that is greater than or equal to the configured value. The minimum value is 200. The maximum value is 100000 in PHP < 5.5.6, and 1000000 in later versions.

opcache.max_wasted_percentage integer

The maximum percentage of wasted memory that is allowed before a restart is scheduled.

opcache.use_cwd boolean

If enabled, OPcache appends the current working directory to the script key, thereby eliminating possible collisions between files with the same base name. Disabling this directive improves performance, but may break existing applications.

opcache.validate_timestamps boolean

If enabled, OPcache will check for updated scripts every opcache.revalidate_freq seconds. When this directive is disabled, you must reset OPcache manually via opcache_reset(), opcache_invalidate() or by restarting the Web server for changes to the filesystem to take effect.

opcache.revalidate_freq integer

How often to check script timestamps for updates, in seconds. 0 will result in OPcache checking for updates on every request.

This configuration directive is ignored if opcache.validate_timestamps is disabled.

opcache.revalidate_path boolean

If disabled, existing cached files using the same include_path will be reused. Thus, if a file with the same name is elsewhere in the include_path, it won't be found.

opcache.save_comments boolean

If disabled, all documentation comments will be discarded from the opcode cache to reduce the size of the optimised code. Disabling this configuration directive may break applications and frameworks that rely on comment parsing for annotations, including Doctrine, Zend Framework 2 and PHPUnit.

opcache.load_comments boolean

If disabled, documentation comments won't be loaded from the opcode cache even if they exist. This can be used with opcache.save_comments to only load comments for applications that require them.

opcache.fast_shutdown boolean

If enabled, a fast shutdown sequence is used that doesn't free each allocated block, but relies on the Zend Engine memory manager to deallocate the entire set of request variables en masse.

opcache.enable_file_override boolean

When enabled, the opcode cache will be checked for whether a file has already been cached when file_exists(), is_file() and is_readable() are called. This may increase performance in applications that check the existence and readability of PHP scripts, but risks returning stale data if opcache.validate_timestamps is disabled.

opcache.optimization_level integer

A bitmask that controls which optimisation passes are executed.

opcache.inherited_hack boolean

In PHP < 5.3, OPcache stores the places where DECLARE_CLASS opcodes used inheritance; when the file is loaded, OPcache then tries to bind the inherited classes using the current environment. The problem is that while the DECLARE_CLASS opcode may not be needed for the current script, if the script requires that the opcode be defined, it may not run.

This configuration directive is ignored in PHP 5.3 and later.

opcache.dups_fix boolean

This hack should only be enabled to work around "Cannot redeclare class" errors.

opcache.blacklist_filename string

The location of the OPcache blacklist file. A blacklist file is a text file containing the names of files that should not be accelerated, one per line. Wildcards are allowed, and prefixes can also be provided. Lines starting with a semi-colon are ignored as comments.

A simple blacklist file might look as follows:

; Matches a specific file.
/var/www/broken.php
; A prefix that matches all files starting with x.
/var/www/x
; A wildcard match.
/var/www/*-broken.php
opcache.max_file_size integer

The maximum file size that will be cached, in bytes. If this is 0, all files will be cached.

opcache.consistency_checks integer

If non-zero, OPcache will verify the cache checksum every N requests, where N is the value of this configuration directive. This should only be enabled when debugging, as it will impair performance.

opcache.force_restart_timeout integer

The length of time to wait for a scheduled restart to begin if the cache isn't active, in seconds. If the timeout is hit, then OPcache assumes that something is wrong and will kill the processes holding locks on the cache to permit a restart.

If opcache.log_verbosity_level is set to 2 or above, a warning will be recorded in the error log when this occurs.

opcache.error_log string

The error log for OPcache errors. An empty string is treated the same as stderr, and will result in logs being sent to standard error (which will be the Web server error log in most cases).

opcache.log_verbosity_level integer

The log verbosity level. By default, only fatal errors (level 0) and errors (level 1) are logged. Other levels available are warnings (level 2), information messages (level 3) and debug messages (level 4).

opcache.preferred_memory_model string

The preferred memory model for OPcache to use. If left empty, OPcache will choose the most appropriate model, which is the correct behaviour in virtually all cases.

Possible values include mmap, shm, posix and win32.

opcache.protect_memory boolean

Protects shared memory from unexpected writes while executing scripts. This is useful for internal debugging only.

opcache.mmap_base string

The base used for shared memory segments on Windows. All PHP processes have to map shared memory into the same address space. Using this directive allows "Unable to reattach to base address" errors to be fixed.

opcache.restrict_api string

Allows calling OPcache API functions only from PHP scripts which path is started from specified string. The default "" means no restriction.

opcache.file_cache string

Enables and sets the second level cache directory. It should improve performance when SHM memory is full, at server restart or SHM reset. The default "" disables file based caching.

opcache.file_cache_only boolean

Enables or disables opcode caching in shared memory.

opcache.file_cache_consistency_checks boolean

Enables or disables checksum validation when script loaded from file cache.

opcache.file_cache_fallback boolean

Implies opcache.file_cache_only=1 for a certain process that failed to reattach to the shared memory (for Windows only). Explicitly enabled file cache is required.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
Func?ii OPcache
Instalarea / configurarea


Func?ii OPcache

Cuprins

  • opcache_compile_file — Compiles and caches a PHP script without executing it
  • opcache_get_configuration — Get configuration information about the cache
  • opcache_get_status — Get status information about the cache
  • opcache_invalidate — Invalidates a cached script
  • opcache_is_script_cached — Tells whether a script is cached in OPCache
  • opcache_reset — Resets the contents of the opcode cache
Tipurile resurselor
opcache_compile_file
OPcache


Compiles and caches a PHP script without executing it

Func?ii OPcache
opcache_get_configuration
Func?ii OPcache
PHP Manual

opcache_compile_file

(PHP 5 >= 5.5.5, PHP 7, PECL ZendOpcache > 7.0.2)

opcache_compile_file — Compiles and caches a PHP script without executing it

Descrierea

boolean opcache_compile_file ( string $file )

This function compiles a PHP script and adds it to the opcode cache without executing it. This can be used to prime the cache after a Web server restart by pre-caching files that will be included in later requests.

Parametri

file

The path to the PHP script to be compiled.

Valorile întoarse

Returns TRUE if file was compiled successfully sau FALSE în cazul e?ecului.

Erori/Excep?ii

If file cannot be loaded or compiled, an error of level E_WARNING is generated. You may use @ to suppress this warning.

A se vedea ?i

  • opcache_invalidate() - Invalidates a cached script

Func?ii OPcache
opcache_get_configuration
Func?ii OPcache


Get configuration information about the cache

opcache_compile_file
opcache_get_status
Func?ii OPcache
PHP Manual

opcache_get_configuration

(PHP 5 >= 5.5.5, PHP 7, PECL ZendOpcache > 7.0.2)

opcache_get_configuration — Get configuration information about the cache

Descrierea

array opcache_get_configuration ( void )

This function returns configuration information about the cache instance

Valorile întoarse

Returns an array of information, including ini, blacklist and version

Erori/Excep?ii

If opcache.restrict_api is in use and the current path is in violation of the rule, an E_WARNING will be raised; no status information will be returned.

A se vedea ?i

  • opcache_get_status() - Get status information about the cache

opcache_compile_file
opcache_get_status
Func?ii OPcache


Get status information about the cache

opcache_get_configuration
opcache_invalidate
Func?ii OPcache
PHP Manual

opcache_get_status

(PHP 5 >= 5.5.5, PHP 7, PECL ZendOpcache > 7.0.2)

opcache_get_status — Get status information about the cache

Descrierea

array opcache_get_status ([ boolean $get_scripts = TRUE ] )

This function returns state information about the cache instance

Parametri

get_scripts

Include script specific state information

Valorile întoarse

Returns an array of information, optionally containing script specific state information

Erori/Excep?ii

If opcache.restrict_api is in use and the current path is in violation of the rule, an E_WARNING will be raised; no status information will be returned.

A se vedea ?i

  • opcache_get_configuration() - Get configuration information about the cache

opcache_get_configuration
opcache_invalidate
Func?ii OPcache


Invalidates a cached script

opcache_get_status
opcache_is_script_cached
Func?ii OPcache
PHP Manual

opcache_invalidate

(PHP 5 >= 5.5.0, PHP 7, PECL ZendOpcache >= 7.0.0)

opcache_invalidate — Invalidates a cached script

Descrierea

boolean opcache_invalidate ( string $script [, boolean $force = FALSE ] )

This function invalidates a particular script from the opcode cache. If force is unset or FALSE, the script will only be invalidated if the modification time of the script is newer than the cached opcodes.

Parametri

script

The path to the script being invalidated.

force

If set to TRUE, the script will be invalidated regardless of whether invalidation is necessary.

Valorile întoarse

Returns TRUE if the opcode cache for script was invalidated or if there was nothing to invalidate, or FALSE if the opcode cache is disabled.

A se vedea ?i

  • opcache_compile_file() - Compiles and caches a PHP script without executing it
  • opcache_reset() - Resets the contents of the opcode cache

opcache_get_status
opcache_is_script_cached
Func?ii OPcache


Tells whether a script is cached in OPCache

opcache_invalidate
opcache_reset
Func?ii OPcache
PHP Manual

opcache_is_script_cached

(PHP 5 >= 5.6.0, PHP 7, PECL ZendOpcache >= 7.0.4)

opcache_is_script_cached — Tells whether a script is cached in OPCache

Descrierea

boolean opcache_is_script_cached ( string $file )

This function checks if a PHP script has been cached in OPCache. This can be used to more easily detect the "warming" of the cache for a particular script.

Parametri

file

The path to the PHP script to be checked.

Valorile întoarse

Returns TRUE if file is cached in OPCache, FALSE otherwise.

A se vedea ?i

  • opcache_compile_file() - Compiles and caches a PHP script without executing it

opcache_invalidate
opcache_reset
Func?ii OPcache


Resets the contents of the opcode cache

opcache_is_script_cached
Output Control
Func?ii OPcache
PHP Manual

opcache_reset

(PHP 5 >= 5.5.0, PHP 7, PECL ZendOpcache >= 7.0.0)

opcache_reset — Resets the contents of the opcode cache

Descrierea

boolean opcache_reset ( void )

This function resets the entire opcode cache. After calling opcache_reset(), all scripts will be reloaded and reparsed the next time they are hit.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the opcode cache was reset, or FALSE if the opcode cache is disabled.

A se vedea ?i

  • opcache_invalidate() - Invalidates a cached script

opcache_is_script_cached
Output Control
Func?ii OPcache


Output Buffering Control

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic usage
    • Ouput rewrite usage
  • Func?ii de control a ie?irilor
    • flush — Flush system 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
opcache_reset
Introducere
Afectarea comportamentului PHP


Introducere

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

Output Control
Instalarea / configurarea
Output Control


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Output Control


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Output Control configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL | Available since PHP 4.0.4. Before PHP 7.1.0, this was used to set session's trans sid rewrite. From PHP 7.1.0, it is only used by output_add_rewrite_var().
url_rewriter.hosts | $_SERVER['HTTP_HOST'] is used as default. | PHP_INI_ALL | Available since PHP 7.1.0
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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

Nota:

You cannot use both mb_output_handler() with
ob_iconv_handler() and you cannot use both
ob_gzhandler() and
zlib.output_compression.

Nota:

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

url_rewriter.tags string
url_rewriter.tags specifies which HTML tags are rewritten by output_add_rewrite_var() values. Defaults to a=href,area=href,frame=src,input=src,form= form is special tag. <input hidden="session_id" name="session_name"> is added as form variable.

Nota: Before PHP 7.1.0, url_rewriter.tags was used to specify session.trans_sid_tags. Since PHP 7.1.0, fieldset is no longer considered as special tag.

url_rewriter.hosts string
url_rewriter.hosts specifies which hosts are rewritten to include output_add_rewrite_var() values. Defaults to $_SERVER['HTTP_HOST']. Multiple hosts can be specified by ",", no space is allowed between hosts. e.g. php.net,wiki.php.net,bugs.php.net

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt întotdeauna disponibile ca parte componenta a nucleului PHP.

PHP_OUTPUT_HANDLER_START (integer)

Indica ca buferizarea ie?irii a început.

PHP_OUTPUT_HANDLER_WRITE (integer)

Indica ca zona-tampon a ie?irilor a fost descarcata ?i au fost afi?ate date.

Disponibila începând cu PHP 5.4.

PHP_OUTPUT_HANDLER_FLUSH (integer)

Indica ca zona-tampon a fost descarcata.

Disponibila începând cu PHP 5.4.

PHP_OUTPUT_HANDLER_CLEAN (integer)

Indica ca zona-tampon de ie?ire a fost cura?ita.

Disponibila începând cu PHP 5.4.

PHP_OUTPUT_HANDLER_FINAL (integer)

Indica ca aceasta este ultima opera?iune de buferizarea a ie?irilor.

Disponibila începând cu PHP 5.4.

PHP_OUTPUT_HANDLER_CONT (integer)

Indica ca zona-tampon a fost descarcata, dar buferizarea ie?irilor va continua.

Începând cu PHP 5.4 aceasta este un pseudonim pentru PHP_OUTPUT_HANDLER_WRITE.

PHP_OUTPUT_HANDLER_END (integer)

Indica ca buferizarea ie?irilor s-a încheiat.

Începând cu PHP 5.4 aceasta este un pseudonim pentru PHP_OUTPUT_HANDLER_FINAL.

PHP_OUTPUT_HANDLER_CLEANABLE (integer)

Controleaza daca o zona-tampon de ie?ire creata cu ob_start() poate fi cura?ata.

Disponibila începând cu PHP 5.4.

PHP_OUTPUT_HANDLER_FLUSHABLE (integer)

Controleaza daca o zona-tampon de ie?ire creata cu ob_start() poate fi descarcata.

Disponibila începând cu PHP 5.4.

PHP_OUTPUT_HANDLER_REMOVABLE (integer)

Controleaza daca o zona-tampon de ie?ire creata cu ob_start() poate fi eliminata înainte de sfâr?itul scriptului.

Disponibila începând cu PHP 5.4.

PHP_OUTPUT_HANDLER_STDFLAGS (integer)

Setul implicit de fanioane a zonei-tampon de ie?ire; în prezent echivalenta cu PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE.

Disponibila începând cu PHP 5.4.

Tipurile resurselor
Exemple
Output Control


Exemple

Cuprins

  • Basic usage
  • Ouput rewrite usage
Constante predefinite
Basic usage
Output Control


Basic usage

Example #1 Output Control example

<?php

ob_start();
echo "Hello\n";

setcookie("cookiename", "cookiedata");

ob_end_flush();

?>

In the above example, the output from echo would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (Headers cannot normally be sent to the browser after data has already been sent.)

Exemple
Ouput rewrite usage
Exemple


Ouput rewrite usage

Since PHP 7.1.0, output_add_rewrite_var(), output_reset_rewrite_vars() use dedicated output buffer. i.e. It does not use trans sid output buffer.

Example #1 Output rewrite example

<?php
// This code works with PHP 7.1.0, 7.0.10, 5.6.25 and up.

// HTTP_HOST is default target host. Set manually to make sample code works.
$_SERVER['HTTP_HOST'] = 'php.net';

// Output rewriter only rewrite form. Add a=href.
// Tags can be specified tag_name=url_attr, e.g. img=src,iframe=src
// No space allowed between settings.
// Form tag is special tag that add hidden input.
ini_set('url_rewriter.tags','a=href,form=');
var_dump(ini_get('url_rewriter.tags'));

// This is added to URL and form
output_add_rewrite_var('test', 'value');
?>
<a href="//php.net/index.php?bug=1234">bug1234</a>
<form action="https://php.net/?bug=1234&edit=1" action="post">
 <input type="text" name="title" />
</form>

Exemplul de mai sus va afi?a:

<a href="//php.net/?bug=1234&test=value">bug1234</a>
<form action="https://php.net/?bug=1234&edit=1" method="post"><input type="hidden" name="test" value="value" />
 <input type="text" name="title" />
</form>

Since PHP 7.1.0, output rewrite functions have it's own INI settings, url_rewriter.tags and url_rewriter.hosts.

Basic usage
Func?ii de control a ie?irilor
Exemple


Func?ii de control a ie?irilor

A se vedea ?i

Vede?i de asemenea header() ?i setcookie().

Cuprins

  • flush — Flush system 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
Ouput rewrite usage
flush
Output Control


Flush system output buffer

Func?ii de control a ie?irilor
ob_clean
Func?ii de control a ie?irilor
PHP Manual

flush

(PHP 4, PHP 5, PHP 7)

flush — Flush system output buffer

Descrierea

void flush ( void )

Flushes the system 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.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • ob_flush() - Flush (send) 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

Func?ii de control a ie?irilor
ob_clean
Func?ii de control a ie?irilor


Clean (erase) the output buffer

flush
ob_end_clean
Func?ii de control a ie?irilor
PHP Manual

ob_clean

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ob_clean — Clean (erase) the output buffer

Descrierea

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.

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE flag. Otherwise ob_clean() will not work.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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
Func?ii de control a ie?irilor


Clean (erase) the output buffer and turn off output buffering

ob_clean
ob_end_flush
Func?ii de control a ie?irilor
PHP Manual

ob_end_clean

(PHP 4, PHP 5, PHP 7)

ob_end_clean — Clean (erase) the output buffer and turn off output buffering

Descrierea

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.

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise ob_end_clean() will not work.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. 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).

Erori/Excep?ii

If the function fails it generates an E_NOTICE.

Exemple

The following example shows an easy way to get rid of all output buffers:

Example #1 ob_end_clean() example

<?php
ob_start();
echo 'Text that won\'t get displayed.';
ob_end_clean();
?>

A se vedea ?i

  • 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
Func?ii de control a ie?irilor


Flush (send) the output buffer and turn off output buffering

ob_end_clean
ob_flush
Func?ii de control a ie?irilor
PHP Manual

ob_end_flush

(PHP 4, PHP 5, PHP 7)

ob_end_flush — Flush (send) the output buffer and turn off output buffering

Descrierea

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.

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_FLUSHABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise ob_end_flush() will not work.

Nota: This function is similar to ob_get_flush(), except that ob_get_flush() returns the buffer as a string.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. 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).

Erori/Excep?ii

If the function fails it generates an E_NOTICE.

Exemple

Example #1 ob_end_flush() example

The following example shows an easy way to flush and end all output buffers:

<?php
  while (@ob_end_flush());
?>

A se vedea ?i

  • 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
Func?ii de control a ie?irilor


Flush (send) the output buffer

ob_end_flush
ob_get_clean
Func?ii de control a ie?irilor
PHP Manual

ob_flush

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ob_flush — Flush (send) the output buffer

Descrierea

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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
Func?ii de control a ie?irilor


Get current buffer contents and delete current output buffer

ob_flush
ob_get_contents
Func?ii de control a ie?irilor
PHP Manual

ob_get_clean

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ob_get_clean — Get current buffer contents and delete current output buffer

Descrierea

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

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE flag. Otherwise ob_get_clean() will not work.

Valorile întoarse

Returns the contents of the output buffer and end output buffering. If output buffering isn't active then FALSE is returned.

Exemple

Example #1 A simple ob_get_clean() example

<?php

ob_start();

echo "Hello World";

$out = ob_get_clean();
$out = strtolower($out);

var_dump($out);
?>

Exemplul de mai sus va afi?a:

string(11) "hello world"

A se vedea ?i

  • ob_get_contents() - Return the contents of the output buffer
  • ob_start() - Turn on output buffering

ob_flush
ob_get_contents
Func?ii de control a ie?irilor


Return the contents of the output buffer

ob_get_clean
ob_get_flush
Func?ii de control a ie?irilor
PHP Manual

ob_get_contents

(PHP 4, PHP 5, PHP 7)

ob_get_contents — Return the contents of the output buffer

Descrierea

string ob_get_contents ( void )

Gets the contents of the output buffer without clearing it.

Valorile întoarse

This will return the contents of the output buffer or FALSE, if output buffering isn't active.

Exemple

Example #1 A simple ob_get_contents() example

<?php

ob_start();

echo "Hello ";

$out1 = ob_get_contents();

echo "World";

$out2 = ob_get_contents();

ob_end_clean();

var_dump($out1, $out2);
?>

Exemplul de mai sus va afi?a:

string(6) "Hello "
string(11) "Hello World"

A se vedea ?i

  • ob_start() - Turn on output buffering
  • ob_get_length() - Return the length of the output buffer

ob_get_clean
ob_get_flush
Func?ii de control a ie?irilor


Flush the output buffer, return it as a string and turn off output buffering

ob_get_contents
ob_get_length
Func?ii de control a ie?irilor
PHP Manual

ob_get_flush

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering

Descrierea

string ob_get_flush ( void )

ob_get_flush() flushes the output buffer, return it as a string and turns off output buffering.

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_FLUSHABLE flag. Otherwise ob_get_flush() will not work.

Nota: This function is similar to ob_end_flush(), except that this function returns the buffer as a string.

Valorile întoarse

Returns the output buffer or FALSE if no buffering is active.

Exemple

Example #1 ob_get_flush() example

<?php
//using output_buffering=On
print_r(ob_list_handlers());

//save buffer in a file
$buffer = ob_get_flush();
file_put_contents('buffer.txt', $buffer);

print_r(ob_list_handlers());
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => default output handler
)
Array
(
)

A se vedea ?i

  • 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
Func?ii de control a ie?irilor


Return the length of the output buffer

ob_get_flush
ob_get_level
Func?ii de control a ie?irilor
PHP Manual

ob_get_length

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

ob_get_length — Return the length of the output buffer

Descrierea

int ob_get_length ( void )

This will return the length of the contents in the output buffer, in bytes.

Valorile întoarse

Returns the length of the output buffer contents, in bytes, or FALSE if no buffering is active.

Exemple

Example #1 A simple ob_get_length() example

<?php

ob_start();

echo "Hello ";

$len1 = ob_get_length();

echo "World";

$len2 = ob_get_length();

ob_end_clean();

echo $len1 . ", ." . $len2;
?>

Exemplul de mai sus va afi?a:

6, 11

A se vedea ?i

  • ob_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer

ob_get_flush
ob_get_level
Func?ii de control a ie?irilor


Return the nesting level of the output buffering mechanism

ob_get_length
ob_get_status
Func?ii de control a ie?irilor
PHP Manual

ob_get_level

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ob_get_level — Return the nesting level of the output buffering mechanism

Descrierea

int ob_get_level ( void )

Returns the nesting level of the output buffering mechanism.

Valorile întoarse

Returns the level of nested output buffering handlers or zero if output buffering is not active.

A se vedea ?i

  • ob_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer

ob_get_length
ob_get_status
Func?ii de control a ie?irilor


Get status of output buffers

ob_get_level
ob_gzhandler
Func?ii de control a ie?irilor
PHP Manual

ob_get_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ob_get_status — Get status of output buffers

Descrierea

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.

Parametri

full_status

TRUE to return all active output buffer levels. If FALSE or not set, only the top level output buffer is returned.

Valorile întoarse

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 | Value
level | Output nesting level
type | PHP_OUTPUT_HANDLER_INTERNAL (0) or PHP_OUTPUT_HANDLER_USER (1)
status | One of PHP_OUTPUT_HANDLER_START (0), PHP_OUTPUT_HANDLER_CONT (1) or PHP_OUTPUT_HANDLER_END (2)
name | Name of active output handler or ' default output handler' if none is set
del | 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 | Value
chunk_size | Chunk size as set by ob_start()
size | ...
blocksize | ...

A se vedea ?i

  • 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
Func?ii de control a ie?irilor


ob_start callback function to gzip output buffer

ob_get_status
ob_implicit_flush
Func?ii de control a ie?irilor
PHP Manual

ob_gzhandler

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ob_gzhandler — ob_start callback function to gzip output buffer

Descrierea

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.

Parametri

buffer

mode

Valorile întoarse

Exemple

Example #1 ob_gzhandler() example

<?php

ob_start("ob_gzhandler");

?>
<html>
<body>
<p>This should be a compressed page.</p>
</body>
</html>

Note

Nota:

ob_gzhandler() requires the zlib extension.

Nota:

You cannot use both ob_gzhandler() and zlib.output_compression. Also note that using zlib.output_compression is preferred over ob_gzhandler().

A se vedea ?i

  • 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
Func?ii de control a ie?irilor


Turn implicit flush on/off

ob_gzhandler
ob_list_handlers
Func?ii de control a ie?irilor
PHP Manual

ob_implicit_flush

(PHP 4, PHP 5, PHP 7)

ob_implicit_flush — Turn implicit flush on/off

Descrierea

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.

Parametri

flag

TRUE to turn implicit flushing on, FALSE otherwise.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • flush() - Flush system 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
Func?ii de control a ie?irilor


List all output handlers in use

ob_implicit_flush
ob_start
Func?ii de control a ie?irilor
PHP Manual

ob_list_handlers

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ob_list_handlers — List all output handlers in use

Descrierea

array ob_list_handlers ( void )

Lists all output handlers in use.

Valorile întoarse

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

Exemple

Example #1 ob_list_handlers() example

<?php
//using output_buffering=On
print_r(ob_list_handlers());
ob_end_flush();

ob_start("ob_gzhandler");
print_r(ob_list_handlers());
ob_end_flush();

// anonymous functions
ob_start(function($string) { return $string; });
print_r(ob_list_handlers());
ob_end_flush();
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => default output handler
)

Array
(
    [0] => ob_gzhandler
)

Array
(
    [0] => Closure::__invoke
)

A se vedea ?i

  • 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
Func?ii de control a ie?irilor


Turn on output buffering

ob_list_handlers
output_add_rewrite_var
Func?ii de control a ie?irilor
PHP Manual

ob_start

(PHP 4, PHP 5, PHP 7)

ob_start — Turn on output buffering

Descrierea

bool ob_start ([ callable $output_callback = NULL [, int $chunk_size = 0 [, int $flags = PHP_OUTPUT_HANDLER_STDFLAGS ]]] )

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.

Avertizare

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.

Parametri

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. This is the callback signature:

string handler ( string $buffer [, int $phase ] )
buffer
Contents of the output buffer.
phase
Bitmask of PHP_OUTPUT_HANDLER_* constants.

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.

Nota:

ob_gzhandler() function exists 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.

flags

The flags parameter is a bitmask that controls the operations that can be performed on the output buffer. The default is to allow output buffers to be cleaned, flushed and removed, which can be set explicitly via PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE, or PHP_OUTPUT_HANDLER_STDFLAGS as shorthand.

Each flag controls access to a set of functions, as described below:

Constant | Functions
PHP_OUTPUT_HANDLER_CLEANABLE | ob_clean(), ob_end_clean(), and ob_get_clean().
PHP_OUTPUT_HANDLER_FLUSHABLE | ob_end_flush(), ob_flush(), and ob_get_flush().
PHP_OUTPUT_HANDLER_REMOVABLE | ob_end_clean(), ob_end_flush(), and ob_get_flush().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | In case ob_start() is used inside an output buffer callback, this function will no longer issue an E_ERROR but instead an E_RECOVERABLE_ERROR, allowing custom error handlers to catch such errors.
5.4.0 | The third parameter of ob_start() changed from a boolean parameter called erase (which, if set to FALSE, would prevent the output buffer from being deleted until the script finished executing) to an integer parameter called flags. Unfortunately, this results in an API compatibility break for code written prior to PHP 5.4.0 that uses the third parameter. See the flags example for an example of how to handle this with code that needs to be compatible with both.
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.

Exemple

Example #1 User defined callback function example

<?php

function callback($buffer)
{
  // replace all the apples with oranges
  return (str_replace("apples", "oranges", $buffer));
}

ob_start("callback");

?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php

ob_end_flush();

?>

Exemplul de mai sus va afi?a:

<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>

Example #2 Creating an uneraseable output buffer in a way compatible with both PHP 5.3 and 5.4

<?php

if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  ob_start(null, 0, PHP_OUTPUT_HANDLER_STDFLAGS ^
    PHP_OUTPUT_HANDLER_REMOVABLE);
} else {
  ob_start(null, 0, false);
}

?>

A se vedea ?i

  • 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() - Convert character encoding as output buffer handler
  • mb_output_handler() - Callback function converts character encoding in output buffer
  • ob_tidyhandler() - ob_start callback function to repair the buffer

ob_list_handlers
output_add_rewrite_var
Func?ii de control a ie?irilor


Add URL rewriter values

ob_start
output_reset_rewrite_vars
Func?ii de control a ie?irilor
PHP Manual

output_add_rewrite_var

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

output_add_rewrite_var — Add URL rewriter values

Descrierea

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.

This function's behaviour is controlled by the url_rewriter.tags and url_rewriter.hosts php.ini parameters.

Nota: Calling this function will implicitly start output buffering if it is not active already.

Parametri

name

The variable name.

value

The variable value.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Before PHP 7.1.0, rewrite vars set by output_add_rewrite_var() use the same Session module trans sid output buffer. Since PHP 7.1.0, dedicated output buffer is used, url_rewriter.tags is used solely for output functions, url_rewriter.hosts is addedd.

Exemple

Example #1 output_add_rewrite_var() example

<?php
output_add_rewrite_var('var', 'value');

// some links
echo '<a href="file.php">link</a>
<a href="http://example.com">link2</a>';

// a form
echo '<form action="script.php" method="post">
<input type="text" name="var2" />
</form>';

print_r(ob_list_handlers());
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • output_reset_rewrite_vars() - Reset URL rewriter values
  • ob_flush() - Flush (send) the output buffer
  • ob_list_handlers() - List all output handlers in use
  • url_rewriter.tags
  • url_rewriter.hosts
  • session.trans_sid_tags
  • session.trans_sid_hosts

ob_start
output_reset_rewrite_vars
Func?ii de control a ie?irilor


Reset URL rewriter values

output_add_rewrite_var
PHP Options/Info
Func?ii de control a ie?irilor
PHP Manual

output_reset_rewrite_vars

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

output_reset_rewrite_vars — Reset URL rewriter values

Descrierea

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Before PHP 7.1.0, rewrite vars set by output_add_rewrite_var() use the same Session module trans sid output buffer. Since PHP 7.1.0, dedicated output buffer is used and output_reset_rewrite_vars() only removes rewrite vars defined by output_add_rewrite_var().

Exemple

Example #1 output_reset_rewrite_vars() example

<?php
session_start();
output_add_rewrite_var('var', 'value');

echo '<a href="file.php">link</a>';
ob_flush();

output_reset_rewrite_vars();
echo '<a href="file.php">link</a>';
?>

Exemplul de mai sus va afi?a:

<a href="file.php?PHPSESSID=xxx&var=value">link</a>
<a href="file.php">link</a>

A se vedea ?i

  • output_add_rewrite_var() - Add URL rewriter values
  • ob_flush() - Flush (send) the output buffer
  • ob_list_handlers() - List all output handlers in use
  • url_rewriter.tags
  • url_rewriter.hosts
  • session.trans_sid_tags
  • session.trans_sid_hosts

output_add_rewrite_var
PHP Options/Info
Func?ii de control a ie?irilor


PHP Options and Information

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii pentru op?iuni/informa?ii PHP
    • assert_options — Set/get the various assert flags
    • assert — Checks if assertion is FALSE
    • cli_get_process_title — Returns the current process title
    • cli_set_process_title — Sets the process title
    • 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
    • gc_mem_caches — Reclaims memory used by the Zend Engine memory manager
    • 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 — Pseudonim pentru get_included_files
    • get_resources — Returns active resources
    • 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 — Pseudonim pentru 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 — Pseudonim pentru 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
output_reset_rewrite_vars
Introducere
Afectarea comportamentului PHP


Introducere

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
Instalarea / configurarea
PHP Options/Info


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
PHP Options/Info


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

PHP Options/Inf Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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 |
assert.exception | "0" | PHP_INI_ALL | Available since PHP 7.0.0.
enable_dl | "1" | PHP_INI_SYSTEM | Aceasta facilitate învechita cu siguran?a va fi eliminata în viitor.
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 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. Removed in PHP 5.4.0.
magic_quotes_runtime | "0" | PHP_INI_ALL | Removed in PHP 5.4.0.
zend.enable_gc | "1" | PHP_INI_ALL | Available since PHP 5.3.0.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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

assert.exception boolean

Issue an AssertionError exception for the failed assertion.

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 modul securizat. In modul securizat, 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 modul securizat. 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. Timing begins at the moment PHP is invoked at the server and ends when execution begins.

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 (limit is applied to $_GET, $_POST and $_COOKIE superglobal separately). 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.

magic_quotes_gpc boolean
Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically.

Nota:

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
Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

If magic_quotes_runtime is enabled, most functions that return data from any sort of external source including databases and text files will have quotes escaped with a backslash. If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash.

Functions affected by magic_quotes_runtime (does not include functions from PECL):

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

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt întotdeauna disponibile ca parte componenta a nucleului PHP.

Pre-defined phpcredits() constants
Constant | Value | Description
CREDITS_GROUP | 1 | A list of the core developers
CREDITS_GENERAL | 2 | General credits: Language design and concept, PHP authors and SAPI module.
CREDITS_SAPI | 4 | A list of the server API modules for PHP, and their authors.
CREDITS_MODULES | 8 | A list of the extension modules for PHP, and their authors.
CREDITS_DOCS | 16 | The credits for the documentation team.
CREDITS_FULLPAGE | 32 | Usually used in combination with the other flags. Indicates that a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_QA | 64 | The credits for the quality assurance team.
CREDITS_ALL | -1 | All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_QA CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags. This is the default value.
phpinfo() constants
Constant | Value | Description
INFO_GENERAL | 1 | The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS | 2 | PHP Credits. See also phpcredits().
INFO_CONFIGURATION | 4 | Current Local and Master values for PHP directives. See also ini_get().
INFO_MODULES | 8 | Loaded modules and their respective settings.
INFO_ENVIRONMENT | 16 | Environment Variable information that's also available in $_ENV.
INFO_VARIABLES | 32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE | 64 | PHP License information. See also the » license faq.
INFO_ALL | -1 | Shows all of the above. This is the default value.
INI constants
Constant | Value | Description
INI_USER | 1 | Unused
INI_PERDIR | 2 | Unused
INI_SYSTEM | 4 | Unused
INI_ALL | 7 | Unused

Assert constants, these values are used to set the assertion options in assert_options().

assert() constants
Constant | INI Setting | Description
ASSERT_ACTIVE | assert.active | Enable assert() evaluation.
ASSERT_CALLBACK | assert.callback | Callback to call on failed assertions.
ASSERT_BAIL | assert.bail | Terminate execution on failed assertions.
ASSERT_WARNING | assert.warning | Issues a PHP warning for each failed assertion
ASSERT_QUIET_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/7/8/8.1).
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.
Tipurile resurselor
Func?ii pentru op?iuni/informa?ii PHP
PHP Options/Info


Func?ii pentru op?iuni/informa?ii PHP

Cuprins

  • assert_options — Set/get the various assert flags
  • assert — Checks if assertion is FALSE
  • cli_get_process_title — Returns the current process title
  • cli_set_process_title — Sets the process title
  • 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
  • gc_mem_caches — Reclaims memory used by the Zend Engine memory manager
  • 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 — Pseudonim pentru get_included_files
  • get_resources — Returns active resources
  • 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 — Pseudonim pentru 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 — Pseudonim pentru 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
Constante predefinite
assert_options
PHP Options/Info


Set/get the various assert flags

Func?ii pentru op?iuni/informa?ii PHP
assert
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

assert_options

(PHP 4, PHP 5, PHP 7)

assert_options — Set/get the various assert flags

Descrierea

mixed assert_options ( int $what [, mixed $value ] )

Set the various assert() control options or just query their current settings.

Parametri

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.

Valorile întoarse

Returns the original setting of any option or FALSE on errors.

Exemple

Example #1 assert_options() example

<?php
// This is our function to handle
// assert failures
function assert_failure()
{
    echo 'Assert failed';
}

// This is our test function
function test_assert($parameter)
{
    assert(is_bool($parameter));
}

// Set our assert options
assert_options(ASSERT_ACTIVE,   true);
assert_options(ASSERT_BAIL,     true);
assert_options(ASSERT_WARNING,  false);
assert_options(ASSERT_CALLBACK, 'assert_failure');

// Make an assert that would fail
test_assert(1);

// This is never reached due to ASSERT_BAIL
// being true
echo 'Never reached';
?>

A se vedea ?i

  • assert() - Checks if assertion is FALSE

Func?ii pentru op?iuni/informa?ii PHP
assert
Func?ii pentru op?iuni/informa?ii PHP


Checks if assertion is FALSE

assert_options
cli_get_process_title
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

assert

(PHP 4, PHP 5, PHP 7)

assert — Checks if assertion is FALSE

Descrierea

PHP 5 and 7

bool assert ( mixed $assertion [, string $description ] )

PHP 7

bool assert ( mixed $assertion [, Throwable $exception ] )

assert() will check the given assertion and take appropriate action if its result is FALSE.

Traditional assertions (PHP 5 and 7)

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). Users of PHP 5.4.8 and later may also provide a fourth optional argument, which will contain the description given to assert(), if it was set.

Expectations (PHP 7 only)

assert() is a language construct in PHP 7, allowing for the definition of expectations: assertions that take effect in development and testing environments, but are optimised away to have zero cost in production.

While assert_options() can still be used to control behaviour as described above for backward compatibility reasons, PHP 7 only code should use the two new configuration directives to control the behaviour of assert() and not call assert_options().

PHP 7 configuration directives for assert()
Directive Default value Possible values
zend.assertions 1
  • 1: generate and execute code (development mode)
  • 0: generate code but jump around it at runtime
  • -1: do not generate code (production mode)
assert.exception 0
  • 1: throw when the assertion fails, either by throwing the object provided as the exception or by throwing a new AssertionError object if exception wasn't provided
  • 0: use or generate a Throwable as described above, but only generate a warning based on that object rather than throwing it (compatible with PHP 5 behaviour)

Parametri

assertion

The assertion. In PHP 5, this must be either a string to be evaluated or a boolean to be tested. In PHP 7, this may also be any expression that returns a value, which will be executed and the result used to indicate whether the assertion succeeded or failed.

description

An optional description that will be included in the failure message if the assertion fails.

exception

In PHP 7, the second parameter can be a Throwable object instead of a descriptive string, in which case this is the object that will be thrown if the assertion fails and the assert.exception configuration directive is enabled.

Valorile întoarse

FALSE if the assertion is false, TRUE otherwise.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | assert() is now a language construct and not a function. assertion() can now be an expression. The second parameter is now interpreted either as an exception (if a Throwable object is given), or as the description supported from PHP 5.4.8 onwards.
5.4.8 | The description parameter was added. The description is also now provided to a callback function in ASSERT_CALLBACK mode as the fourth argument.

Exemple

Traditional assertions (PHP 5 and 7)

Example #1 Handle a failed assertion with a custom handler

<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler($file, $line, $code)
{
    echo "<hr>Assertion Failed:
        File '$file'<br />
        Line '$line'<br />
        Code '$code'<br /><hr />";
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert('mysql_query("")');
?>

Example #2 Using a custom handler to print a description

<?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, $desc = null)
{
    echo "Assertion failed at $file:$line: $code";
    if ($desc) {
        echo ": $desc";
    }
    echo "\n";
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert('2 < 1');
assert('2 < 1', 'Two is less than one');
?>

Exemplul de mai sus va afi?a:

 Assertion failed at test.php:21: 2 < 1
 Assertion failed at test.php:22: 2 < 1: Two is less than one

Expectations (PHP 7 only)

Example #3 Expectations without a custom exception

<?php
assert(true == false);
echo 'Hi!';
?>

With zend.assertions set to 0, the above example will output:

Hi!

With zend.assertions set to 1 and assert.exception set to 0, the above example will output:

Warning: assert(): assert(true == false) failed in - on line 2
Hi!

With zend.assertions set to 1 and assert.exception set to 1, the above example will output:

Fatal error: Uncaught AssertionError: assert(true == false) in -:2
Stack trace:
#0 -(2): assert(false, 'assert(true == ...')
#1 {main}
  thrown in - on line 2

Example #4 Expectations with a custom exception

<?php
class CustomError extends AssertionError {}

assert(true == false, new CustomError('True is not false!'));
echo 'Hi!';
?>

With zend.assertions set to 0, the above example will output:

Hi!

With zend.assertions set to 1 and assert.exception set to 0, the above example will output:

Warning: assert(): CustomError: True is not false! in -:4
Stack trace:
#0 {main} failed in - on line 4
Hi!

With zend.assertions set to 1 and assert.exception set to 1, the above example will output:

Fatal error: Uncaught CustomError: True is not false! in -:4
Stack trace:
#0 {main}
  thrown in - on line 4

A se vedea ?i

  • assert_options() - Set/get the various assert flags

assert_options
cli_get_process_title
Func?ii pentru op?iuni/informa?ii PHP


Returns the current process title

assert
cli_set_process_title
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

cli_get_process_title

(PHP 5 >= 5.5.0, PHP 7)

cli_get_process_title — Returns the current process title

Descrierea

string cli_get_process_title ( void )

Returns the current process title, as set by cli_set_process_title(). Note that this may not exactly match what is shown in ps or top, depending on your operating system.

This function is available only in CLI mode.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Return a string with the current process title or NULL on error.

Erori/Excep?ii

An E_WARNING will be generated if the operating system is unsupported.

Exemple

Example #1 cli_get_process_title() example

<?php
echo "Process title: " . cli_get_process_title() . "\n";
?>

A se vedea ?i

  • cli_set_process_title() - Sets the process title

assert
cli_set_process_title
Func?ii pentru op?iuni/informa?ii PHP


Sets the process title

cli_get_process_title
dl
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

cli_set_process_title

(PHP 5 >= 5.5.0, PHP 7)

cli_set_process_title — Sets the process title

Descrierea

bool cli_set_process_title ( string $title )

Sets the process title visible in tools such as top and ps. This function is available only in CLI mode.

Parametri

title

The new title.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

An E_WARNING will be generated if the operating system is unsupported.

Exemple

Example #1 cli_set_process_title() example

<?php
$title = "My Amazing PHP Script";
$pid = getmypid(); // you can use this to see your process title in ps

if (!cli_set_process_title($title)) {
    echo "Unable to set process title for PID $pid...\n";
    exit(1);
} else {
    echo "The process title '$title' for PID $pid has been set for your process!\n";
    sleep(5);
}
?>

A se vedea ?i

  • cli_get_process_title() - Returns the current process title
  • setproctitle() - Set the process title

cli_get_process_title
dl
Func?ii pentru op?iuni/informa?ii PHP


Loads a PHP extension at runtime

cli_set_process_title
extension_loaded
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

dl

(PHP 4, PHP 5, PHP 7)

dl — Loads a PHP extension at runtime

Descrierea

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

Avertizare

This function was removed from most SAPIs in PHP 5.3.0, and was removed from PHP-FPM in PHP 7.0.0.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. If the functionality of loading modules is not available or has been disabled (either by setting enable_dl off or by enabling modul securizat 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.

Exemple

Example #1 dl() examples

<?php
// Example loading an extension based on OS
if (!extension_loaded('sqlite')) {
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        dl('php_sqlite.dll');
    } else {
        dl('sqlite.so');
    }
}

// Or using PHP_SHLIB_SUFFIX constant
if (!extension_loaded('sqlite')) {
    $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
    dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
}
?>

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | dl() is disabled in PHP-FPM.
5.3.9 | dl() is enabled in PHP-FPM, albeit discouraged.
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.

Note

Nota:

dl() is not supported when PHP is built with ZTS support. Use the Extension Loading Directives instead.

Nota:

dl() is case sensitive on Unix platforms.

Nota: Aceasta func?ie este dezactivata atunci când PHP ruleaza în modul securizat.

A se vedea ?i

  • Extension Loading Directives
  • extension_loaded() - Find out whether an extension is loaded

cli_set_process_title
extension_loaded
Func?ii pentru op?iuni/informa?ii PHP


Find out whether an extension is loaded

dl
gc_collect_cycles
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

extension_loaded

(PHP 4, PHP 5, PHP 7)

extension_loaded — Find out whether an extension is loaded

Descrierea

bool extension_loaded ( string $name )

Finds out whether the extension is loaded.

Parametri

name

The extension name. This parameter is case-insensitive.

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]

Valorile întoarse

Returns TRUE if the extension identified by name is loaded, FALSE otherwise.

Exemple

Example #1 extension_loaded() example

<?php
if (!extension_loaded('gd')) {
    if (!dl('gd.so')) {
        exit;
    }
}
?>

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Forces collection of any existing garbage cycles

extension_loaded
gc_disable
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

gc_collect_cycles

(PHP 5 >= 5.3.0, PHP 7)

gc_collect_cycles — Forces collection of any existing garbage cycles

Descrierea

int gc_collect_cycles ( void )

Forces collection of any existing garbage cycles.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns number of collected cycles.

A se vedea ?i

  • Garbage Collection

extension_loaded
gc_disable
Func?ii pentru op?iuni/informa?ii PHP


Deactivates the circular reference collector

gc_collect_cycles
gc_enable
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

gc_disable

(PHP 5 >= 5.3.0, PHP 7)

gc_disable — Deactivates the circular reference collector

Descrierea

void gc_disable ( void )

Deactivates the circular reference collector, setting zend.enable_gc to 0.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Garbage Collection

gc_collect_cycles
gc_enable
Func?ii pentru op?iuni/informa?ii PHP


Activates the circular reference collector

gc_disable
gc_enabled
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

gc_enable

(PHP 5 >= 5.3.0, PHP 7)

gc_enable — Activates the circular reference collector

Descrierea

void gc_enable ( void )

Activates the circular reference collector, setting zend.enable_gc to 1.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Garbage Collection

gc_disable
gc_enabled
Func?ii pentru op?iuni/informa?ii PHP


Returns status of the circular reference collector

gc_enable
gc_mem_caches
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

gc_enabled

(PHP 5 >= 5.3.0, PHP 7)

gc_enabled — Returns status of the circular reference collector

Descrierea

bool gc_enabled ( void )

Returns status of the circular reference collector.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the garbage collector is enabled, FALSE otherwise.

Exemple

Example #1 A gc_enabled() example

<?php
if(gc_enabled()) gc_collect_cycles();
?>

A se vedea ?i

  • Garbage Collection

gc_enable
gc_mem_caches
Func?ii pentru op?iuni/informa?ii PHP


Reclaims memory used by the Zend Engine memory manager

gc_enabled
get_cfg_var
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

gc_mem_caches

(PHP 7)

gc_mem_caches — Reclaims memory used by the Zend Engine memory manager

Descrierea

int gc_mem_caches ( void )

Reclaims memory used by the Zend Engine memory manager.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the number of bytes freed.

A se vedea ?i

  • Garbage Collection

gc_enabled
get_cfg_var
Func?ii pentru op?iuni/informa?ii PHP


Gets the value of a PHP configuration option

gc_mem_caches
get_current_user
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

get_cfg_var

(PHP 4, PHP 5, PHP 7)

get_cfg_var — Gets the value of a PHP configuration option

Descrierea

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.

Parametri

option

The configuration option name.

Valorile întoarse

Returns the current value of the PHP configuration variable specified by option, or FALSE if an error occurs.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | get_cfg_var() was fixed to be able to return "array" ini options.

A se vedea ?i

  • ini_get() - Gets the value of a configuration option
  • ini_get_all() - Gets all configuration options

gc_mem_caches
get_current_user
Func?ii pentru op?iuni/informa?ii PHP


Gets the name of the owner of the current PHP script

get_cfg_var
get_defined_constants
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

get_current_user

(PHP 4, PHP 5, PHP 7)

get_current_user — Gets the name of the owner of the current PHP script

Descrierea

string get_current_user ( void )

Returns the name of the owner of the current PHP script.

Valorile întoarse

Returns the username as a string.

Exemple

Example #1 get_current_user() example

<?php
echo 'Current script owner: ' . get_current_user();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Current script owner: SYSTEM

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Returns an associative array with the names of all the constants and their values

get_current_user
get_extension_funcs
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

get_defined_constants

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

get_defined_constants — Returns an associative array with the names of all the constants and their values

Descrierea

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.

Parametri

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

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

)

Valorile întoarse

Returns an array of constant name => constant value array, optionally groupped by extension name registering the constant.

Istoricul schimbarilor

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

Exemple

Example #1 get_defined_constants() Example

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

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • 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() - Întoarce un msiv cu toate variabilele definite

get_current_user
get_extension_funcs
Func?ii pentru op?iuni/informa?ii PHP


Returns an array with the names of the functions of a module

get_defined_constants
get_include_path
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

get_extension_funcs

(PHP 4, PHP 5, PHP 7)

get_extension_funcs — Returns an array with the names of the functions of a module

Descrierea

array get_extension_funcs ( string $module_name )

This function returns the names of all the functions defined in the module indicated by module_name.

Parametri

module_name

The module name.

Nota:

This parameter must be in lowercase.

Valorile întoarse

Returns an array with all the functions, or FALSE if module_name is not a valid extension.

Exemple

Example #1 Prints the XML functions

<?php
print_r(get_extension_funcs("xml"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • ReflectionExtension::getFunctions() - Gets extension functions

get_defined_constants
get_include_path
Func?ii pentru op?iuni/informa?ii PHP


Gets the current include_path configuration option

get_extension_funcs
get_included_files
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

get_include_path

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

get_include_path — Gets the current include_path configuration option

Descrierea

string get_include_path ( void )

Gets the current include_path configuration option value.

Valorile întoarse

Returns the path, as a string.

Exemple

Example #1 get_include_path() example

<?php
echo get_include_path();

// Or using ini_get()
echo ini_get('include_path');
?>

A se vedea ?i

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

get_extension_funcs
get_included_files
Func?ii pentru op?iuni/informa?ii PHP


Returns an array with the names of included or required files

get_include_path
get_loaded_extensions
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

get_included_files

(PHP 4, PHP 5, PHP 7)

get_included_files — Returns an array with the names of included or required files

Descrierea

array get_included_files ( void )

Gets the names of all files that have been included using include, include_once, require or require_once.

Valorile întoarse

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.

Exemple

Example #1 get_included_files() example

<?php
// This file is abc.php

include 'test1.php';
include_once 'test2.php';
require 'test3.php';
require_once 'test4.php';

$included_files = get_included_files();

foreach ($included_files as $filename) {
    echo "$filename\n";
}

?>

Exemplul de mai sus va afi?a:

/path/to/abc.php
/path/to/test1.php
/path/to/test2.php
/path/to/test3.php
/path/to/test4.php

Note

Nota:

Files included using the auto_prepend_file configuration directive are not included in the returned array.

A se vedea ?i

  • include - include
  • include_once - include_once
  • require - require
  • require_once - require_once
  • get_required_files() - Pseudonim pentru get_included_files

get_include_path
get_loaded_extensions
Func?ii pentru op?iuni/informa?ii PHP


Returns an array with the names of all modules compiled and loaded

get_included_files
get_magic_quotes_gpc
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

get_loaded_extensions

(PHP 4, PHP 5, PHP 7)

get_loaded_extensions — Returns an array with the names of all modules compiled and loaded

Descrierea

array get_loaded_extensions ([ bool $zend_extensions = false ] )

This function returns the names of all the modules compiled and loaded in the PHP interpreter.

Parametri

zend_extensions

Only return Zend extensions, if not then regular extensions, like mysqli are listed. Defaults to FALSE (return regular extensions).

Valorile întoarse

Returns an indexed array of all the modules names.

Istoricul schimbarilor

Versiune | Descriere
5.2.4 | The optional zend_extensions parameter was added

Exemple

Example #1 get_loaded_extensions() Example

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

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Gets the current configuration setting of magic_quotes_gpc

get_loaded_extensions
get_magic_quotes_runtime
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

get_magic_quotes_gpc

(PHP 4, PHP 5, PHP 7)

get_magic_quotes_gpc — Gets the current configuration setting of magic_quotes_gpc

Descrierea

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

Valorile întoarse

Returns 0 if magic_quotes_gpc is off, 1 otherwise. Or always returns FALSE as of PHP 5.4.0.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Always returns FALSE because the magic quotes feature was removed from PHP.

Exemple

Example #1 get_magic_quotes_gpc() example

<?php
// If magic quotes are enabled
echo $_POST['lastname'];             // O\'reilly
echo addslashes($_POST['lastname']); // O\\\'reilly

// Usage across all PHP versions
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')";
?>

Note

Nota:

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

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Gets the current active configuration setting of magic_quotes_runtime

get_magic_quotes_gpc
get_required_files
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

get_magic_quotes_runtime

(PHP 4, PHP 5, PHP 7)

get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime

Descrierea

bool get_magic_quotes_runtime ( void )

Returns the current active configuration setting of magic_quotes_runtime.

Valorile întoarse

Returns 0 if magic_quotes_runtime is off, 1 otherwise. Or always returns FALSE as of PHP 5.4.0.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Always returns FALSE because the magic quotes feature was removed from PHP.

Exemple

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

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Pseudonim pentru get_included_files

get_magic_quotes_runtime
get_resources
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

get_required_files

(PHP 4, PHP 5, PHP 7)

get_required_files — Pseudonim pentru get_included_files()

Descrierea

Aceasta func?ie este pseudonim pentru: get_included_files().

get_magic_quotes_runtime
get_resources
Func?ii pentru op?iuni/informa?ii PHP


Returns active resources

get_required_files
getenv
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

get_resources

(PHP 7)

get_resources — Returns active resources

Descrierea

array get_resources ([ string $type ] )

Returns an array of all currently active resources, optionally filtered by resource type.

Parametri

type

If defined, this will cause get_resources() to only return resources of the given type. A list of resource types is available.

If the string Unknown is provided as the type, then only resources that are of an unknown type will be returned.

If omitted, all resources will be returned.

Valorile întoarse

Returns an array of currently active resources, indexed by resource number.

Exemple

Example #1 Unfiltered get_resources()

<?php
$fp = tmpfile();
var_dump(get_resources());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [1]=>
  resource(1) of type (stream)
}

Example #2 Filtered get_resources()

<?php
$fp = tmpfile();
var_dump(get_resources('stream'));
var_dump(get_resources('curl'));
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [1]=>
  resource(1) of type (stream)
}
array(0) {
}

A se vedea ?i

  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • 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() - Întoarce un msiv cu toate variabilele definite

get_required_files
getenv
Func?ii pentru op?iuni/informa?ii PHP


Gets the value of an environment variable

get_resources
getlastmod
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

getenv

(PHP 4, PHP 5, PHP 7)

getenv — Gets the value of an environment variable

Descrierea

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

Parametri

varname

The variable name.

Valorile întoarse

Returns the value of the environment variable varname, or FALSE if the environment variable varname does not exist.

Exemple

Example #1 getenv() Example

<?php
// Example use of getenv()
$ip = getenv('REMOTE_ADDR');

// Or simply use a Superglobal ($_SERVER or $_ENV)
$ip = $_SERVER['REMOTE_ADDR'];
?>

A se vedea ?i

  • putenv() - Sets the value of an environment variable
  • apache_getenv() - Get an Apache subprocess_env variable
  • Superglobals

get_resources
getlastmod
Func?ii pentru op?iuni/informa?ii PHP


Gets time of last page modification

getenv
getmygid
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

getlastmod

(PHP 4, PHP 5, PHP 7)

getlastmod — Gets time of last page modification

Descrierea

int getlastmod ( void )

Gets the time of the last modification of the main script of execution.

If you're interested in getting the last modification time of a different file, consider using filemtime().

Valorile întoarse

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.

Exemple

Example #1 getlastmod() example

<?php
// outputs e.g. 'Last modified: March 04 1998 20:43:59.'
echo "Last modified: " . date ("F d Y H:i:s.", getlastmod());
?>

A se vedea ?i

  • date() - Formateaza o ora/data
  • 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() - Gets file modification time

getenv
getmygid
Func?ii pentru op?iuni/informa?ii PHP


Get PHP script owner's GID

getlastmod
getmyinode
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

getmygid

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

getmygid — Get PHP script owner's GID

Descrierea

int getmygid ( void )

Gets the group ID of the current script.

Valorile întoarse

Returns the group ID of the current script, or FALSE on error.

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Gets the inode of the current script

getmygid
getmypid
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

getmyinode

(PHP 4, PHP 5, PHP 7)

getmyinode — Gets the inode of the current script

Descrierea

int getmyinode ( void )

Gets the inode of the current script.

Valorile întoarse

Returns the current script's inode as an integer, or FALSE on error.

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Gets PHP's process ID

getmyinode
getmyuid
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

getmypid

(PHP 4, PHP 5, PHP 7)

getmypid — Gets PHP's process ID

Descrierea

int getmypid ( void )

Gets the current PHP process ID.

Valorile întoarse

Returns the current PHP process ID, or FALSE on error.

Note

Avertizare

Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on pids in security-dependent contexts.

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Gets PHP script owner's UID

getmypid
getopt
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

getmyuid

(PHP 4, PHP 5, PHP 7)

getmyuid — Gets PHP script owner's UID

Descrierea

int getmyuid ( void )

Gets the user ID of the current script.

Valorile întoarse

Returns the user ID of the current script, or FALSE on error.

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Gets options from the command line argument list

getmyuid
getrusage
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

getopt

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

getopt — Gets options from the command line argument list

Descrierea

array getopt ( string $options [, array $longopts [, int &$optind ]] )

Parses options passed to the script.

Parametri

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.
optind
If the optind parameter is present, then the index where argument parsing stopped will be written to this variable.

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. If a value is required, it does not matter whether the value has leading white space or not. See note.

Nota: Optional values do not accept " " (space) as a separator.

Nota:

The format for the options and longopts is almost the same, the only difference is that longopts takes an array of options (where each element is the option) whereas options takes a string (where each character is the option).

Valorile întoarse

This function will return an array of option / argument pairs, sau FALSE în cazul e?ecului.

Nota:

The parsing of options will end at the first non-option found, anything that follows is discarded.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Added the optind parameter.
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.

Exemple

Example #1 getopt() example: The basics

<?php
// Script example.php
$options = getopt("f:hp:");
var_dump($options);
?>
shell> php example.php -fvalue -h

Exemplul de mai sus va afi?a:

array(2) {
  ["f"]=>
  string(5) "value"
  ["h"]=>
  bool(false)
}

Example #2 getopt() example: Introducing long options

<?php
// Script example.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);
?>
shell> php example.php -f "value for f" -v -a --required value --optional="optional value" --option

Exemplul de mai sus va afi?a:

array(6) {
  ["f"]=>
  string(11) "value for f"
  ["v"]=>
  bool(false)
  ["a"]=>
  bool(false)
  ["required"]=>
  string(5) "value"
  ["optional"]=>
  string(14) "optional value"
  ["option"]=>
  bool(false)
}

Example #3 getopt() example: Passing multiple options as one

<?php
// Script example.php
$options = getopt("abc");
var_dump($options);
?>
shell> php example.php -aaac

Exemplul de mai sus va afi?a:

array(2) {
  ["a"]=>
  array(3) {
    [0]=>
    bool(false)
    [1]=>
    bool(false)
    [2]=>
    bool(false)
  }
  ["c"]=>
  bool(false)
}

Example #4 getopt() example: Using optind

<?php
// Script example.php
$optind = null;
$opts = getopt('a:b:', [], $optind);
$pos_args = array_slice($argv, $optind);
var_dump($pos_args);
shell> php example.php -a 1 -b 2 -- test

Exemplul de mai sus va afi?a:

array(1) {
  [0]=>
  string(4) "test"
}

A se vedea ?i

  • $argv

getmyuid
getrusage
Func?ii pentru op?iuni/informa?ii PHP


Gets the current resource usages

getopt
ini_alter
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

getrusage

(PHP 4, PHP 5, PHP 7)

getrusage — Gets the current resource usages

Descrierea

array getrusage ([ int $who = 0 ] )

This is an interface to getrusage(2). It gets data returned from the system call.

Parametri

who

If who is 1, getrusage will be called with RUSAGE_CHILDREN.

Valorile întoarse

Returns an associative array containing the data returned from the system call. All entries are accessible by using their documented field names.

Exemple

Example #1 getrusage() example

<?php
$dat = getrusage();
echo $dat["ru_nswap"];         // number of swaps
echo $dat["ru_majflt"];        // number of page faults
echo $dat["ru_utime.tv_sec"];  // user time used (seconds)
echo $dat["ru_utime.tv_usec"]; // user time used (microseconds)
?>

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | This function is now supported on Windows.

Note

Nota:

On Windows getrusage() will only return the following members:

  • "ru_stime.tv_sec"
  • "ru_stime.tv_usec"
  • "ru_utime.tv_sec"
  • "ru_utime.tv_usec"
  • "ru_majflt" (only if who is RUSAGE_SELF)
  • "ru_maxrss" (only if who is RUSAGE_SELF)

If getrusage() is called with who set to 1 (RUSAGE_CHILDREN), then resource usage for threads are collected (meaning that internally the function is called with RUSAGE_THREAD).

Nota:

on BeOS 2000, only the following members are returned:

  • "ru_stime.tv_sec"
  • "ru_stime.tv_usec"
  • "ru_utime.tv_sec"
  • "ru_utime.tv_usec"

A se vedea ?i

  • Your system's man page on getrusage(2)

getopt
ini_alter
Func?ii pentru op?iuni/informa?ii PHP


Pseudonim pentru ini_set

getrusage
ini_get_all
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

ini_alter

(PHP 4, PHP 5, PHP 7)

ini_alter — Pseudonim pentru ini_set()

Descrierea

Aceasta func?ie este pseudonim pentru: ini_set().

getrusage
ini_get_all
Func?ii pentru op?iuni/informa?ii PHP


Gets all configuration options

ini_alter
ini_get
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

ini_get_all

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ini_get_all — Gets all configuration options

Descrierea

array ini_get_all ([ string $extension [, bool $details = true ]] )

Returns all the registered configuration options.

Parametri

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

Valorile întoarse

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.

Nota:

It's possible for a directive to have multiple access levels, which is why access shows the appropriate bitmask values.

Note

Nota:

ini_get_all() ignores "array" ini options such as pdo.dsn.*.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Added details.

Exemple

Example #1 ini_get_all() examples

<?php
print_r(ini_get_all("pcre"));
print_r(ini_get_all());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [pcre.backtrack_limit] => Array
        (
            [global_value] => 100000
            [local_value] => 100000
            [access] => 7
        )

    [pcre.recursion_limit] => Array
        (
            [global_value] => 100000
            [local_value] => 100000
            [access] => 7
        )

)
Array
(
    [allow_call_time_pass_reference] => Array
        (
            [global_value] => 0
            [local_value] => 0
            [access] => 6
        )

    [allow_url_fopen] => Array
        (
            [global_value] => 1
            [local_value] => 1
            [access] => 4
        )

    ...

)

Example #2 Disabling details

<?php
print_r(ini_get_all("pcre", false)); // Added in PHP 5.3.0
print_r(ini_get_all(null, false)); // Added in PHP 5.3.0
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [pcre.backtrack_limit] => 100000
    [pcre.recursion_limit] => 100000
)
Array
(
    [allow_call_time_pass_reference] => 0
    [allow_url_fopen] => 1
    ...
)

A se vedea ?i

  • 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
  • ReflectionExtension::getINIEntries() - Gets extension ini entries

ini_alter
ini_get
Func?ii pentru op?iuni/informa?ii PHP


Gets the value of a configuration option

ini_get_all
ini_restore
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

ini_get

(PHP 4, PHP 5, PHP 7)

ini_get — Gets the value of a configuration option

Descrierea

string ini_get ( string $varname )

Returns the value of the configuration option on success.

Parametri

varname

The configuration option name.

Valorile întoarse

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.

Exemple

Example #1 A few ini_get() examples

<?php
/*
Our php.ini contains the following settings:

display_errors = On
register_globals = Off
post_max_size = 8M
*/

echo 'display_errors = ' . ini_get('display_errors') . "\n";
echo 'register_globals = ' . ini_get('register_globals') . "\n";
echo 'post_max_size = ' . ini_get('post_max_size') . "\n";
echo 'post_max_size+1 = ' . (ini_get('post_max_size')+1) . "\n";
echo 'post_max_size in bytes = ' . return_bytes(ini_get('post_max_size'));

function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return $val;
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

display_errors = 1
register_globals = 0
post_max_size = 8M
post_max_size+1 = 9
post_max_size in bytes = 8388608

Note

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

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

Nota:

ini_get() can't read "array" ini options such as pdo.dsn.*, and returns FALSE in this case.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Previously, the empty string was returned if the configuration option didn't exist. now, FALSE is returned instead.

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Restores the value of a configuration option

ini_get
ini_set
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

ini_restore

(PHP 4, PHP 5, PHP 7)

ini_restore — Restores the value of a configuration option

Descrierea

void ini_restore ( string $varname )

Restores a given configuration option to its original value.

Parametri

varname

The configuration option name.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ini_restore() example

<?php
$setting = 'y2k_compliance';

echo 'Current value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;

ini_set($setting, ini_get($setting) ? 0 : 1);
echo 'New value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;

ini_restore($setting);
echo 'Original value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;
?>

Exemplul de mai sus va afi?a:

Current value for 'y2k_compliance': 1
New value for 'y2k_compliance': 0
Original value for 'y2k_compliance': 1

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Sets the value of a configuration option

ini_restore
magic_quotes_runtime
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

ini_set

(PHP 4, PHP 5, PHP 7)

ini_set — Sets the value of a configuration option

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the old value on success, FALSE on failure.

Exemple

Example #1 Setting an ini option

<?php
echo ini_get('display_errors');

if (!ini_get('display_errors')) {
    ini_set('display_errors', '1');
}

echo ini_get('display_errors');
?>

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Pseudonim pentru set_magic_quotes_runtime

ini_set
main
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

magic_quotes_runtime

(PHP 4, PHP 5)

magic_quotes_runtime — Pseudonim pentru set_magic_quotes_runtime()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.3.0 ?i ELIMINAT începând cu PHP 7.0.0.

Descrierea

Aceasta func?ie este pseudonim pentru: set_magic_quotes_runtime()

ini_set
main
Func?ii pentru op?iuni/informa?ii PHP


Dummy for main

magic_quotes_runtime
memory_get_peak_usage
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

main

main — Dummy for main()

Descrierea

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

A se vedea ?i

  • html_errors
  • display_errors

magic_quotes_runtime
memory_get_peak_usage
Func?ii pentru op?iuni/informa?ii PHP


Returns the peak of memory allocated by PHP

main
memory_get_usage
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

memory_get_peak_usage

(PHP 5 >= 5.2.0, PHP 7)

memory_get_peak_usage — Returns the peak of memory allocated by PHP

Descrierea

int memory_get_peak_usage ([ bool $real_usage = false ] )

Returns the peak of memory, in bytes, that's been allocated to your PHP script.

Parametri

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.

Valorile întoarse

Returns the memory peak in bytes.

Istoricul schimbarilor

Versiune | Descriere
5.2.1 | Compiling with --enable-memory-limit is no longer required for this function to exist.
5.2.0 | real_usage was added.

A se vedea ?i

  • memory_get_usage() - Returns the amount of memory allocated to PHP
  • memory_limit

main
memory_get_usage
Func?ii pentru op?iuni/informa?ii PHP


Returns the amount of memory allocated to PHP

memory_get_peak_usage
php_ini_loaded_file
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

memory_get_usage

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

memory_get_usage — Returns the amount of memory allocated to PHP

Descrierea

int memory_get_usage ([ bool $real_usage = false ] )

Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.

Parametri

real_usage

Set this to TRUE to get total memory allocated from system, including unused pages. If not set or FALSE only the used memory is reported.

Nota:

PHP does not track memory that is not allocated by emalloc()

Valorile întoarse

Returns the memory amount in bytes.

Istoricul schimbarilor

Versiune | Descriere
5.2.1 | Compiling with --enable-memory-limit is no longer required for this function to exist.
5.2.0 | real_usage was added.

Exemple

Example #1 A memory_get_usage() example

<?php
// This is only an example, the numbers below will
// differ depending on your system

echo memory_get_usage() . "\n"; // 36640

$a = str_repeat("Hello", 4242);

echo memory_get_usage() . "\n"; // 57960

unset($a);

echo memory_get_usage() . "\n"; // 36744

?>

A se vedea ?i

  • memory_get_peak_usage() - Returns the peak of memory allocated by PHP
  • memory_limit

memory_get_peak_usage
php_ini_loaded_file
Func?ii pentru op?iuni/informa?ii PHP


Retrieve a path to the loaded php.ini file

memory_get_usage
php_ini_scanned_files
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

php_ini_loaded_file

(PHP 5 >= 5.2.4, PHP 7)

php_ini_loaded_file — Retrieve a path to the loaded php.ini file

Descrierea

string php_ini_loaded_file ( void )

Check if a php.ini file is loaded, and retrieve its path.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The loaded php.ini path, or FALSE if one is not loaded.

Exemple

Example #1 php_ini_loaded_file() example

<?php
$inipath = php_ini_loaded_file();

if ($inipath) {
    echo 'Loaded php.ini: ' . $inipath;
} else {
    echo 'A php.ini file is not loaded';
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Loaded php.ini: /usr/local/php/php.ini

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Return a list of .ini files parsed from the additional ini dir

php_ini_loaded_file
php_logo_guid
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

php_ini_scanned_files

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

php_ini_scanned_files — Return a list of .ini files parsed from the additional ini dir

Descrierea

string php_ini_scanned_files ( void )

php_ini_scanned_files() returns a comma-separated list of configuration files parsed after php.ini. The directories searched are set by a compile time option and, optionally, by an environment variable at run time: more information can be found in the installation guide.

The returned configuration files include the full path.

Valorile întoarse

Returns a comma-separated string of .ini files on success. Each comma is followed by a newline. If the configure directive --with-config-file-scan-dir wasn't set and the PHP_INI_SCAN_DIR environment variable isn'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().

Exemple

Example #1 A simple example to list the returned ini files

<?php
if ($filelist = php_ini_scanned_files()) {
    if (strlen($filelist) > 0) {
        $files = explode(',', $filelist);

        foreach ($files as $file) {
            echo "<li>" . trim($file) . "</li>\n";
        }
    }
}
?>

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Gets the logo guid

php_ini_scanned_files
php_sapi_name
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

php_logo_guid

(PHP 4, PHP 5 < 5.5)

php_logo_guid — Gets the logo guid

Descrierea

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.

Avertizare

Aceasta func?ie este ÎNVECHITA ?i ELIMINATA începând cu PHP 5.5.0.

Valorile întoarse

Returns PHPE9568F34-D428-11d2-A769-00AA001ACF42.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | php_logo_guid() has been removed from PHP.

Exemple

Example #1 php_logo_guid() example

<?php

echo '<img src="' . $_SERVER['PHP_SELF'] .
     '?=' . php_logo_guid() . '" alt="PHP Logo !" />';

?>

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Returns the type of interface between web server and PHP

php_logo_guid
php_uname
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

php_sapi_name

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

php_sapi_name — Returns the type of interface between web server and PHP

Descrierea

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.

Valorile întoarse

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, cli-server, continuity, embed, fpm-fcgi, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.

Exemple

Example #1 php_sapi_name() example

This example checks for the substring cgi because it may also be cgi-fcgi.

<?php
$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi') {
    echo "You are using CGI PHP\n";
} else {
    echo "You are not using CGI PHP\n";
}
?>

Note

Nota: An alternative approach

The PHP constant PHP_SAPI has the same value as php_sapi_name().

Sfat

A potential gotcha

The defined SAPI may not be obvious, because for example instead of apache it may be defined as apache2handler or apache2filter.

A se vedea ?i

  • PHP_SAPI

php_logo_guid
php_uname
Func?ii pentru op?iuni/informa?ii PHP


Returns information about the operating system PHP is running on

php_sapi_name
phpcredits
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

php_uname

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

php_uname — Returns information about the operating system PHP is running on

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the description, as a string.

Exemple

Example #1 Some php_uname() examples

<?php
echo php_uname();
echo PHP_OS;

/* Some possible outputs:
Linux localhost 2.4.21-0.13mdk #1 Fri Mar 14 15:08:06 EST 2003 i686
Linux

FreeBSD localhost 3.2-RELEASE #15: Mon Dec 17 08:46:02 GMT 2001
FreeBSD

Windows NT XN1 5.1 build 2600
WINNT
*/

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    echo 'This is a server using Windows!';
} else {
    echo 'This is a server not using Windows!';
}

?>

There are also some related Predefined PHP constants that may come in handy, for example:

Example #2 A few OS related constant examples

<?php
// *nix
echo DIRECTORY_SEPARATOR; // /
echo PHP_SHLIB_SUFFIX;    // so
echo PATH_SEPARATOR;      // :

// Win*
echo DIRECTORY_SEPARATOR; // \
echo PHP_SHLIB_SUFFIX;    // dll
echo PATH_SEPARATOR;      // ;
?>

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Prints out the credits for PHP

php_uname
phpinfo
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

phpcredits

(PHP 4, PHP 5, PHP 7)

phpcredits — Prints out the credits for PHP

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Prints the general credits

<?php
phpcredits(CREDITS_GENERAL);
?>

Example #2 Prints the core developers and the documentation group

<?php
phpcredits(CREDITS_GROUP | CREDITS_DOCS | CREDITS_FULLPAGE);
?>

Example #3 Printing all the credits

<html>
 <head>
  <title>My credits page</title>
 </head>
 <body>
<?php
// some code of your own
phpcredits(CREDITS_ALL - CREDITS_FULLPAGE);
// some more code
?>
 </body>
</html>

Note

Nota:

phpcredits() outputs plain text instead of HTML when using the CLI mode.

A se vedea ?i

  • phpversion() - Gets the current PHP version
  • php_logo_guid() - Gets the logo guid
  • phpinfo() - Outputs information about PHP's configuration

php_uname
phpinfo
Func?ii pentru op?iuni/informa?ii PHP


Outputs information about PHP's configuration

phpcredits
phpversion
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

phpinfo

(PHP 4, PHP 5, PHP 7)

phpinfo — Outputs information about PHP's configuration

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | Logo GUIDs were replaced with data URIs, and so turning off expose_php now has no effect on the result of phpinfo(). Credits are also now embedded within the output itself instead of linked.
5.2.2 | The "Loaded Configuration File" information was added, when before only "Configuration File (php.ini) Path" existed.

Exemple

Example #1 phpinfo() Example

<?php

// Show all information, defaults to INFO_ALL
phpinfo();

// Show just the module information.
// phpinfo(8) yields identical results.
phpinfo(INFO_MODULES);

?>

Note

Nota:

In versions of PHP before 5.5, 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.

Nota:

phpinfo() outputs plain text instead of HTML when using the CLI mode.

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Gets the current PHP version

phpinfo
putenv
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

phpversion

(PHP 4, PHP 5, PHP 7)

phpversion — Gets the current PHP version

Descrierea

string phpversion ([ string $extension ] )

Returns a string containing the version of the currently running PHP parser or extension.

Parametri

extension

An optional extension name.

Valorile întoarse

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.

Exemple

Example #1 phpversion() example

<?php
// prints e.g. 'Current PHP version: 4.1.1'
echo 'Current PHP version: ' . phpversion();

// prints e.g. '2.0' or nothing if the extension isn't enabled
echo phpversion('tidy');
?>

Example #2 PHP_VERSION_ID example and usage

<?php
// PHP_VERSION_ID is available as of PHP 5.2.7, if our
// version is lower than that, then emulate it
if (!defined('PHP_VERSION_ID')) {
    $version = 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, ...
}
?>

Note

Nota:

This information is also available in the predefined constant PHP_VERSION. More versioning information is available using the PHP_VERSION_* constants.

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Sets the value of an environment variable

phpversion
restore_include_path
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

putenv

(PHP 4, PHP 5, PHP 7)

putenv — Sets the value of an environment variable

Descrierea

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.

Parametri

setting

The setting, like "FOO=BAR"

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Setting an environment variable

<?php
putenv("UNIQID=$uniqid");
?>

Note

Avertizare

The safe_mode_allowed_env_vars and safe_mode_protected_env_vars directives only take effect when safe_mode is enabled.

A se vedea ?i

  • getenv() - Gets the value of an environment variable
  • apache_setenv() - Stabile?te o variabila de mediu a unui subprocess Apache

phpversion
restore_include_path
Func?ii pentru op?iuni/informa?ii PHP


Restores the value of the include_path configuration option

putenv
set_include_path
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

restore_include_path

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

restore_include_path — Restores the value of the include_path configuration option

Descrierea

void restore_include_path ( void )

Restores the include_path configuration option back to its original master value as set in php.ini

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 restore_include_path() example

<?php

echo get_include_path();  // .:/usr/local/lib/php

set_include_path('/inc');

echo get_include_path();  // /inc

restore_include_path();

// Or using ini_restore()
ini_restore('include_path');

echo get_include_path();  // .:/usr/local/lib/php

?>

A se vedea ?i

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

putenv
set_include_path
Func?ii pentru op?iuni/informa?ii PHP


Sets the include_path configuration option

restore_include_path
set_magic_quotes_runtime
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

set_include_path

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

set_include_path — Sets the include_path configuration option

Descrierea

string set_include_path ( string $new_include_path )

Sets the include_path configuration option for the duration of the script.

Parametri

new_include_path

The new value for the include_path

Valorile întoarse

Returns the old include_path on success sau FALSE în cazul e?ecului.

Exemple

Example #1 set_include_path() example

<?php
set_include_path('/usr/lib/pear');

// Or using ini_set()
ini_set('include_path', '/usr/lib/pear');
?>

Example #2 Adding to the include path

Making use of the PATH_SEPARATOR constant, it is possible to extend the include path regardless of the operating system.

In this example we add /usr/lib/pear to the end of the existing include_path.

<?php
$path = '/usr/lib/pear';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
?>

A se vedea ?i

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

restore_include_path
set_magic_quotes_runtime
Func?ii pentru op?iuni/informa?ii PHP


Sets the current active configuration setting of magic_quotes_runtime

set_include_path
set_time_limit
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

set_magic_quotes_runtime

(PHP 4, PHP 5)

set_magic_quotes_runtime — Sets the current active configuration setting of magic_quotes_runtime

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 7.0.0.

Descrierea

bool set_magic_quotes_runtime ( bool $new_setting )

Set the current active configuration setting of magic_quotes_runtime.

Erori/Excep?ii

Since PHP 5.3 this function has been deprecated and will raise an E_DEPRECATED warning upon execution. Since PHP 5.4 this function will also raise an E_CORE_ERROR on trying to enable magic quotes.

Parametri

new_setting

FALSE for off, TRUE for on.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 set_magic_quotes_runtime() example

<?php
// Create a temporary file pointer
$fp = tmpfile();

// Write some data to the pointer
fwrite($fp, '\'PHP\' is a Recursive acronym');

// Without magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(false);

echo 'Without magic_quotes_runtime: ' . fread($fp, 64), PHP_EOL;

// With magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(true);

echo 'With magic_quotes_runtime: ' . fread($fp, 64), PHP_EOL;

// Clean up
fclose($fp);
?>

Exemplul de mai sus va afi?a:

Without magic_quotes_runtime: 'PHP' is a Recursive acronym
With magic_quotes_runtime: \'PHP\' is a Recursive acronym

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Limits the maximum execution time

set_magic_quotes_runtime
sys_get_temp_dir
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

set_time_limit

(PHP 4, PHP 5, PHP 7)

set_time_limit — Limits the maximum execution time

Descrierea

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

Parametri

seconds

The maximum execution time, in seconds. If set to zero, no time limit is imposed.

Valorile întoarse

Returns TRUE on success, or FALSE on failure.

Note

Avertizare

This function has no effect when PHP is running in modul securizat. There is no workaround other than turning off safe mode or changing the time limit in the php.ini.

Nota:

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.

A se vedea ?i

  • max_execution_time
  • max_input_time

set_magic_quotes_runtime
sys_get_temp_dir
Func?ii pentru op?iuni/informa?ii PHP


Returns directory path used for temporary files

set_time_limit
version_compare
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

sys_get_temp_dir

(PHP 5 >= 5.2.1, PHP 7)

sys_get_temp_dir — Returns directory path used for temporary files

Descrierea

string sys_get_temp_dir ( void )

Returns the path of the directory PHP stores temporary files in by default.

Valorile întoarse

Returns the path of the temporary directory.

Exemple

Example #1 sys_get_temp_dir() example

<?php
// Create a temporary file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam(sys_get_temp_dir(), 'Tux');

echo $temp_file;
?>

Exemplul de mai sus va afi?a ceva similar cu:

C:\Windows\Temp\TuxA318.tmp

A se vedea ?i

  • tmpfile() - Creates a temporary file
  • tempnam() - Create file with unique file name

set_time_limit
version_compare
Func?ii pentru op?iuni/informa?ii PHP


Compares two "PHP-standardized" version number strings

sys_get_temp_dir
zend_logo_guid
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

version_compare

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

version_compare — Compares two "PHP-standardized" version number strings

Descrierea

mixed version_compare ( string $version1 , string $version2 [, string $operator ] )

version_compare() compares two "PHP-standardized" version number strings.

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

Parametri

version1

First version number.

version2

Second version number.

operator

If the third optional operator argument is specified, test for a particular relationship. The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.

This parameter is case-sensitive, values should be lowercase.

Valorile întoarse

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.

Exemple

The examples below use the PHP_VERSION constant, because it contains the value of the PHP version that is executing the code.

Example #1 version_compare() examples

<?php
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
    echo 'I am at least PHP version 7.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 at least PHP version 5.0.0, my version: ' . PHP_VERSION . "\n";
}

if (version_compare(PHP_VERSION, '5.0.0', '<')) {
    echo 'I am still PHP 4, my version: ' . PHP_VERSION . "\n";
}
?>

Note

Nota:

The PHP_VERSION constant holds current PHP version.

Nota:

Note that pre-release versions, such as 5.3.0-dev, are considered lower than their final release counterparts (like 5.3.0).

Nota:

Special version strings such as alpha and beta are case sensitive. Version strings from arbitrary sources that do not adhere to the PHP standard may need to be lowercased via strtolower() before calling version_compare().

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


Gets the Zend guid

version_compare
zend_thread_id
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

zend_logo_guid

(PHP 4, PHP < 5.5)

zend_logo_guid — Gets the Zend guid

Descrierea

string zend_logo_guid ( void )

This function returns the ID which can be used to display the Zend logo using the built-in image.

Avertizare

Aceasta func?ie este ÎNVECHITA ?i ELIMINATA începând cu PHP 5.5.0.

Valorile întoarse

Returns PHPE9568F35-D428-11d2-A769-00AA001ACF42.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | zend_logo_guid() has been removed from PHP.

Exemple

Example #1 zend_logo_guid() example

<?php

echo '<img src="' . $_SERVER['PHP_SELF'] .
     '?=' . zend_logo_guid() . '" alt="Zend Logo !" />';

?>

A se vedea ?i

  • php_logo_guid() - Gets the logo guid

version_compare
zend_thread_id
Func?ii pentru op?iuni/informa?ii PHP


Returns a unique identifier for the current thread

zend_logo_guid
zend_version
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

zend_thread_id

(PHP 5, PHP 7)

zend_thread_id — Returns a unique identifier for the current thread

Descrierea

int zend_thread_id ( void )

This function returns a unique identifier for the current thread.

Valorile întoarse

Returns the thread id as an integer.

Exemple

Example #1 zend_thread_id() example

<?php
$thread_id = zend_thread_id();

echo 'Current thread id is: ' . $thread_id;
?>

Exemplul de mai sus va afi?a ceva similar cu:

Current thread id is: 7864

Note

Nota:

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
Func?ii pentru op?iuni/informa?ii PHP


Gets the version of the current Zend engine

zend_thread_id
runkit
Func?ii pentru op?iuni/informa?ii PHP
PHP Manual

zend_version

(PHP 4, PHP 5, PHP 7)

zend_version — Gets the version of the current Zend engine

Descrierea

string zend_version ( void )

Returns a string containing the version of the currently running Zend Engine.

Valorile întoarse

Returns the Zend Engine version number, as a string.

Exemple

Example #1 zend_version() example

<?php
echo "Zend engine version: " . zend_version();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Zend engine version: 2.2.0

A se vedea ?i

  • 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
Func?ii pentru op?iuni/informa?ii PHP


runkit

  • Introducere
  • Constante predefinite
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Func?ii runkit
    • 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
Introducere
Afectarea comportamentului PHP


Introducere

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
Constante predefinite
runkit


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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_CLASS_STATIC_PROPS (integer)
runkit_import() flag indicating that class static properties should be imported from the specified file. Available since Runkit 1.0.1.
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() and runkit_method_redefine()
RUNKIT_ACC_PROTECTED (integer)
PHP 5 specific flag to runkit_method_add() and runkit_method_redefine()
RUNKIT_ACC_PRIVATE (integer)
PHP 5 specific flag to runkit_method_add() and runkit_method_redefine()
RUNKIT_ACC_STATIC (integer)
PHP 5 specific flag to runkit_method_add() and runkit_method_redefine(). Available since Runkit 1.0.1.
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.
Introducere
Instalarea / configurarea
runkit


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Constante predefinite
Necesita?i
runkit


Necesita?i

Modifying Constants, Functions, Classes, and Methods as well as Custom Superglobals works with all releases of PHP 5. No special requirements are necessary.

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/runkit.

Windows binaries (DLL files) for this PECL extension are available from the PECL website.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Runkit Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
runkit.superglobal | "" | PHP_INI_PERDIR |
runkit.internal_override | "0" | PHP_INI_SYSTEM |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Example #1 Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini

<?php
function show_values() {
  echo "Foo is $_FOO\n";
  echo "Bar is $_BAR\n";
  echo "Baz is $_BAZ\n";
}

$_FOO = 'foo';
$_BAR = 'bar';
$_BAZ = 'baz';

/* Displays foo and bar, but not baz */
show_values();
?>
runkit.internal_override boolean
Enables ability to modify/rename/remove internal functions.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
Func?ii runkit
Instalarea / configurarea


Func?ii runkit

Cuprins

  • 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
Tipurile resurselor
Runkit_Sandbox
runkit


Runkit Sandbox Class -- PHP Virtual Machine

Func?ii runkit
Runkit_Sandbox_Parent
Func?ii runkit
PHP Manual

Runkit_Sandbox

(PECL runkit >= 0.7.0)

Runkit_Sandbox — Runkit Sandbox Class -- PHP Virtual Machine

Descrierea

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.

Nota: Sus?inerea cutiei cu nisip (sandbox) (necesara pentru runkit_lint(), runkit_lint_file(), ?i clasa Runkit_Sandbox) este disponibila numai în PHP 5.1 sau cu versiuni special modificate ale PHP 5.0 ?i necesita ca siguran?a firelor de execu?ie sa fie activata. Vede?i fi?ierul README inclus în pachetul runkit pentru a afla mai multe informa?ii.

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.

Example #1 Instantiating a restricted sandbox

<?php
$options = array(
  'safe_mode'=>true,
  'open_basedir'=>'/var/www/users/jdoe/',
  'allow_url_fopen'=>'false',
  'disable_functions'=>'exec,shell_exec,passthru,system',
  'disable_classes'=>'myAppClass');
$sandbox = new Runkit_Sandbox($options);
/* Non-protected ini settings may set normally */
$sandbox->ini_set('html_errors',true);
?>

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.

Example #2 Working with variables in a sandbox

<?php
$sandbox = new Runkit_Sandbox();

$sandbox->foo = 'bar';
$sandbox->eval('echo "$foo\n"; $bar = $foo . "baz";');
echo "{$sandbox->bar}\n";
if (isset($sandbox->foo)) unset($sandbox->foo);
$sandbox->eval('var_dump(isset($foo));');
?>

Exemplul de mai sus va afi?a:

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

Example #3 Calling sandbox functions

<?php
$sandbox = new Runkit_Sandbox();

echo $sandbox->str_replace('a','f','abc');
?>

Exemplul de mai sus va afi?a:

fbc

When passing arguments to a sandbox function, the arguments are taken from the outer instance of PHP. If you wish to pass arguments from the sandbox's scope, be sure to access them as properties of the sandbox object as illustrated above.

Example #4 Passing arguments to sandbox functions

<?php
$sandbox = new Runkit_Sandbox();

$foo = 'bar';
$sandbox->foo = 'baz';
echo $sandbox->str_replace('a',$foo,'a');
echo $sandbox->str_replace('a',$sandbox->foo,'a');
?>

Exemplul de mai sus va afi?a:

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

Func?ii runkit
Runkit_Sandbox_Parent
Func?ii runkit


Runkit Anti-Sandbox Class

Runkit_Sandbox
runkit_class_adopt
Func?ii runkit
PHP Manual

Runkit_Sandbox_Parent

(PECL runkit >= 0.7.0)

Runkit_Sandbox_Parent — Runkit Anti-Sandbox Class

Descrierea

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.

Nota: Sus?inerea cutiei cu nisip (sandbox) (necesara pentru runkit_lint(), runkit_lint_file(), ?i clasa Runkit_Sandbox) este disponibila numai în PHP 5.1 sau cu versiuni special modificate ale PHP 5.0 ?i necesita ca siguran?a firelor de execu?ie sa fie activata. Vede?i fi?ierul README inclus în pachetul runkit pentru a afla mai multe informa?ii.

In order for any of the Runkit_Sandbox_Parent features to function. Support must be enabled on a per-sandbox basis by enabling the parent_access flag from the parent's context.

Example #1 Working with variables in a sandbox

<?php
$sandbox = new Runkit_Sandbox();
$sandbox['parent_access'] = true;
?>

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.

Example #2 Accessing parental variables

<?php
$php = new Runkit_Sandbox();
$php['parent_access'] = true;
$php['parent_read'] = true;

$test = "Global";

$php->eval('$PARENT = new Runkit_Sandbox_Parent;');

$php['parent_scope'] = 0;
one();

$php['parent_scope'] = 1;
one();

$php['parent_scope'] = 2;
one();

$php['parent_scope'] = 3;
one();

$php['parent_scope'] = 4;
one();

$php['parent_scope'] = 5;
one();

function one() {
    $test = "one()";
    two();
}

function two() {
    $test = "two()";
    three();
}

function three() {
    $test = "three()";
    $GLOBALS['php']->eval('var_dump($PARENT->test);');
}
?>

Exemplul de mai sus va afi?a:

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
Func?ii runkit


Convert a base class to an inherited class, add ancestral methods when appropriate

Runkit_Sandbox_Parent
runkit_class_emancipate
Func?ii runkit
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

Descrierea

bool runkit_class_adopt ( string $classname , string $parentname )

Parametri

classname

Name of class to be adopted

parentname

Parent class which child class is extending

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 A runkit_class_adopt() example

<?php
class myParent {
  function parentFunc() {
    echo "Parent Function Output\n";
  }
}

class myChild {
}

runkit_class_adopt('myChild','myParent');
myChild::parentFunc();
?>

Exemplul de mai sus va afi?a:

Parent Function Output

A se vedea ?i

  • runkit_class_emancipate() - Convert an inherited class to a base class, removes any method whose scope is ancestral

Runkit_Sandbox_Parent
runkit_class_emancipate
Func?ii runkit


Convert an inherited class to a base class, removes any method whose scope is ancestral

runkit_class_adopt
runkit_constant_add
Func?ii runkit
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

Descrierea

bool runkit_class_emancipate ( string $classname )

Parametri

classname

Name of class to emancipate

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 A runkit_class_emancipate() example

<?php
class myParent {
  function parentFunc () {
    echo "Parent Function Output\n";
  }
}
class myChild extends myParent {
}

myChild::parentFunc();
runkit_class_emancipate('myChild');
myChild::parentFunc();
?>

Exemplul de mai sus va afi?a:

Parent Function Output
Fatal error: Call to undefined function:  parentFunc() in example.php on line 12

A se vedea ?i

  • runkit_class_adopt() - Convert a base class to an inherited class, add ancestral methods when appropriate

runkit_class_adopt
runkit_constant_add
Func?ii runkit


Similar to define(), but allows defining in class definitions as well

runkit_class_emancipate
runkit_constant_redefine
Func?ii runkit
PHP Manual

runkit_constant_add

(PECL runkit >= 0.7.0)

runkit_constant_add — Similar to define(), but allows defining in class definitions as well

Descrierea

bool runkit_constant_add ( string $constname , mixed $value )

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii runkit


Redefine an already defined constant

runkit_constant_add
runkit_constant_remove
Func?ii runkit
PHP Manual

runkit_constant_redefine

(PECL runkit >= 0.7.0)

runkit_constant_redefine — Redefine an already defined constant

Descrierea

bool runkit_constant_redefine ( string $constname , mixed $newvalue )

Parametri

constname

Constant to redefine. Either string indicating global constant, or classname::constname indicating class constant.

newvalue

New value to assign to constant.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii runkit


Remove/Delete an already defined constant

runkit_constant_redefine
runkit_function_add
Func?ii runkit
PHP Manual

runkit_constant_remove

(PECL runkit >= 0.7.0)

runkit_constant_remove — Remove/Delete an already defined constant

Descrierea

bool runkit_constant_remove ( string $constname )

Parametri

constname

Name of constant to remove. Either a string indicating a global constant, or classname::constname indicating a class constant.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii runkit


Add a new function, similar to create_function

runkit_constant_remove
runkit_function_copy
Func?ii runkit
PHP Manual

runkit_function_add

(PECL runkit >= 0.7.0)

runkit_function_add — Add a new function, similar to create_function()

Descrierea

bool runkit_function_add ( string $funcname , string $arglist , string $code [, bool $return_by_reference = NULL [, string $doc_comment = NULL ]] )
bool runkit_function_add ( string $funcname , Closure $closure [, string $doc_comment = NULL ] )

Parametri

funcname

Name of function to be created

arglist

Comma separated argument list

code

Code making up the function

closure

A closure that defines the function.

return_by_reference

Whether the function should return by reference.

doc_comment

The doc comment of the function.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
runkit 1.0.4 | An alternative syntax expecting a closure has been added.
runkit 1.0.4 | The optional parameters return_by_reference and doc_comment have been added.

Exemple

Example #1 A runkit_function_add() example

<?php
runkit_function_add('testme','$a,$b','echo "The value of a is $a\n"; echo "The value of b is $b\n";');
testme(1,2);
?>

Exemplul de mai sus va afi?a:

The value of a is 1
The value of b is 2

A se vedea ?i

  • 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
Func?ii runkit


Copy a function to a new function name

runkit_function_add
runkit_function_redefine
Func?ii runkit
PHP Manual

runkit_function_copy

(PECL runkit >= 0.7.0)

runkit_function_copy — Copy a function to a new function name

Descrierea

bool runkit_function_copy ( string $funcname , string $targetname )

Parametri

funcname

Name of existing function

targetname

Name of new function to copy definition to

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 A runkit_function_copy() example

<?php
function original() {
  echo "In a function\n";
}
runkit_function_copy('original','duplicate');
original();
duplicate();
?>

Exemplul de mai sus va afi?a:

In a function
In a function

A se vedea ?i

  • 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
Func?ii runkit


Replace a function definition with a new implementation

runkit_function_copy
runkit_function_remove
Func?ii runkit
PHP Manual

runkit_function_redefine

(PECL runkit >= 0.7.0)

runkit_function_redefine — Replace a function definition with a new implementation

Descrierea

bool runkit_function_redefine ( string $funcname , string $arglist , string $code [, bool $return_by_reference = NULL [, string $doc_comment = NULL ]] )
bool runkit_function_redefine ( string $funcname , Closure $closure [, string $doc_comment = NULL ] )

Nota: Implicit numai func?ii din spa?iul utilizatorilor pot fi eliminate, redenumite sau modificate. Pentru a depa?i (modifica) func?iile interne, trebuie sa activa?i parametrul runkit.internal_override din php.ini.

Parametri

funcname

Name of function to redefine

arglist

New list of arguments to be accepted by function

code

New code implementation

closure

A closure that defines the function.

return_by_reference

Whether the function should return by reference.

doc_comment

The doc comment of the function.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
runkit 1.0.4 | An alternative syntax expecting a closure has been added.
runkit 1.0.4 | The optional parameters return_by_reference and doc_comment have been added.

Exemple

Example #1 A runkit_function_redefine() example

<?php
function testme() {
  echo "Original Testme Implementation\n";
}
testme();
runkit_function_redefine('testme','','echo "New Testme Implementation\n";');
testme();
?>

Exemplul de mai sus va afi?a:

Original Testme Implementation
New Testme Implementation

A se vedea ?i

  • 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_method_redefine() - Dynamically changes the code of the given method

runkit_function_copy
runkit_function_remove
Func?ii runkit


Remove a function definition

runkit_function_redefine
runkit_function_rename
Func?ii runkit
PHP Manual

runkit_function_remove

(PECL runkit >= 0.7.0)

runkit_function_remove — Remove a function definition

Descrierea

bool runkit_function_remove ( string $funcname )

Nota: Implicit numai func?ii din spa?iul utilizatorilor pot fi eliminate, redenumite sau modificate. Pentru a depa?i (modifica) func?iile interne, trebuie sa activa?i parametrul runkit.internal_override din php.ini.

Parametri

funcname

Name of function to be deleted

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii runkit


Change a function's name

runkit_function_remove
runkit_import
Func?ii runkit
PHP Manual

runkit_function_rename

(PECL runkit >= 0.7.0)

runkit_function_rename — Change a function's name

Descrierea

bool runkit_function_rename ( string $funcname , string $newname )

Nota: Implicit numai func?ii din spa?iul utilizatorilor pot fi eliminate, redenumite sau modificate. Pentru a depa?i (modifica) func?iile interne, trebuie sa activa?i parametrul runkit.internal_override din php.ini.

Parametri

funcname

Current function name

newname

New function name

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii runkit


Process a PHP file importing function and class definitions, overwriting where appropriate

runkit_function_rename
runkit_lint_file
Func?ii runkit
PHP Manual

runkit_import

(PECL runkit >= 0.7.0)

runkit_import — Process a PHP file importing function and class definitions, overwriting where appropriate

Descrierea

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 may be automatically overwritten by their new definitions.

Parametri

filename

Filename to import function and class definitions from

flags

Bitwise OR of the RUNKIT_IMPORT_* family of constants.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 runkit_import() example

<?php
// import classes entirely
runkit_import('myfile.inc', RUNKIT_IMPORT_CLASSES);

/* import classes, but not imports their static properties
   (RUNKIT_IMPORT_CLASS_STATIC_PROPS is available since 1.0.1) */
runkit_import('myfile.inc', RUNKIT_IMPORT_CLASSES & ~RUNKIT_IMPORT_CLASS_STATIC_PROPS);

/* import only static properties of classes
   (RUNKIT_IMPORT_CLASS_STATIC_PROPS is available since 1.0.1) */
runkit_import('myfile.inc', RUNKIT_IMPORT_CLASS_STATIC_PROPS);
?>

runkit_function_rename
runkit_lint_file
Func?ii runkit


Check the PHP syntax of the specified file

runkit_import
runkit_lint
Func?ii runkit
PHP Manual

runkit_lint_file

(PECL runkit >= 0.7.0)

runkit_lint_file — Check the PHP syntax of the specified file

Descrierea

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.

Nota: Sus?inerea cutiei cu nisip (sandbox) (necesara pentru runkit_lint(), runkit_lint_file(), ?i clasa Runkit_Sandbox) este disponibila numai în PHP 5.1 sau cu versiuni special modificate ale PHP 5.0 ?i necesita ca siguran?a firelor de execu?ie sa fie activata. Vede?i fi?ierul README inclus în pachetul runkit pentru a afla mai multe informa?ii.

Parametri

filename

File containing PHP Code to be lint checked

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • runkit_lint() - Check the PHP syntax of the specified php code

runkit_import
runkit_lint
Func?ii runkit


Check the PHP syntax of the specified php code

runkit_lint_file
runkit_method_add
Func?ii runkit
PHP Manual

runkit_lint

(PECL runkit >= 0.7.0)

runkit_lint — Check the PHP syntax of the specified php code

Descrierea

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.

Nota: Sus?inerea cutiei cu nisip (sandbox) (necesara pentru runkit_lint(), runkit_lint_file(), ?i clasa Runkit_Sandbox) este disponibila numai în PHP 5.1 sau cu versiuni special modificate ale PHP 5.0 ?i necesita ca siguran?a firelor de execu?ie sa fie activata. Vede?i fi?ierul README inclus în pachetul runkit pentru a afla mai multe informa?ii.

Parametri

code

PHP Code to be lint checked

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • runkit_lint_file() - Check the PHP syntax of the specified file

runkit_lint_file
runkit_method_add
Func?ii runkit


Dynamically adds a new method to a given class

runkit_lint
runkit_method_copy
Func?ii runkit
PHP Manual

runkit_method_add

(PECL runkit >= 0.7.0)

runkit_method_add — Dynamically adds a new method to a given class

Descrierea

bool runkit_method_add ( string $classname , string $methodname , string $args , string $code [, int $flags = RUNKIT_ACC_PUBLIC [, string $doc_comment = NULL ]] )
bool runkit_method_add ( string $classname , string $methodname , Closure $closure [, int $flags = RUNKIT_ACC_PUBLIC [, string $doc_comment = NULL ]] )

Parametri

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

closure

A closure that defines the method.

flags

The type of method to create, can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE optionally combined via bitwise OR with RUNKIT_ACC_STATIC (since 1.0.1)

Nota:

This parameter is only used as of PHP 5, because, prior to this, all methods were public.

doc_comment

The doc comment of the function.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
runkit 1.0.4 | An alternative syntax expecting a closure has been added.
runkit 1.0.4 | The optional parameter doc_comment has been added.

Exemple

Example #1 runkit_method_add() example

<?php
class Example {
    function foo() {
        echo "foo!\n";
    }
}

// create an Example object
$e = new Example();

// Add a new public method
runkit_method_add(
    'Example',
    'add',
    '$num1, $num2',
    'return $num1 + $num2;',
    RUNKIT_ACC_PUBLIC
);

// add 12 + 4
echo $e->add(12, 4);
?>

Exemplul de mai sus va afi?a:

16

A se vedea ?i

  • 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
Func?ii runkit


Copies a method from class to another

runkit_method_add
runkit_method_redefine
Func?ii runkit
PHP Manual

runkit_method_copy

(PECL runkit >= 0.7.0)

runkit_method_copy — Copies a method from class to another

Descrierea

bool runkit_method_copy ( string $dClass , string $dMethod , string $sClass [, string $sMethod ] )

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 runkit_method_copy() example

<?php
class Foo {
    function example() {
        return "foo!\n";
    }
}

class Bar {
    // initially, no methods
}

// copy the example() method from the Foo class to the Bar class, as baz()
runkit_method_copy('Bar', 'baz', 'Foo', 'example');

// output copied function
echo Bar::baz();
?>

Exemplul de mai sus va afi?a:

foo!

A se vedea ?i

  • 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
Func?ii runkit


Dynamically changes the code of the given method

runkit_method_copy
runkit_method_remove
Func?ii runkit
PHP Manual

runkit_method_redefine

(PECL runkit >= 0.7.0)

runkit_method_redefine — Dynamically changes the code of the given method

Descrierea

bool runkit_method_redefine ( string $classname , string $methodname , string $args , string $code [, int $flags = RUNKIT_ACC_PUBLIC [, string $doc_comment = NULL ]] )
bool runkit_method_redefine ( string $classname , string $methodname , Closure $closure [, int $flags = RUNKIT_ACC_PUBLIC [, string $doc_comment = NULL ]] )

Nota: Aceasta func?ie nu poate fi utilizata pentru a manipula metoda care la moment ruleaza, sau este înlan?uita.

Parametri

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

closure

A closure that defines the method.

flags

The redefined method can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE optionally combined via bitwise OR with RUNKIT_ACC_STATIC (since 1.0.1)

doc_comment

The doc comment of the function.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
runkit 1.0.4 | An alternative syntax expecting a closure has been added.
runkit 1.0.4 | The optional parameter doc_comment has been added.

Exemple

Example #1 runkit_method_redefine() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " . $e->foo();

// Redefine the 'foo' method
runkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    RUNKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>

Exemplul de mai sus va afi?a:

Before: foo!
After: bar!

A se vedea ?i

  • 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
Func?ii runkit


Dynamically removes the given method

runkit_method_redefine
runkit_method_rename
Func?ii runkit
PHP Manual

runkit_method_remove

(PECL runkit >= 0.7.0)

runkit_method_remove — Dynamically removes the given method

Descrierea

bool runkit_method_remove ( string $classname , string $methodname )

Nota: Aceasta func?ie nu poate fi utilizata pentru a manipula metoda care la moment ruleaza, sau este înlan?uita.

Parametri

classname

The class in which to remove the method

methodname

The name of the method to remove

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 runkit_method_remove() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }

    function bar() {
        return "bar!\n";
    }
}

// Remove the 'foo' method
runkit_method_remove(
    'Example',
    'foo'
);

echo implode(' ', get_class_methods('Example'));

?>

Exemplul de mai sus va afi?a:

bar

A se vedea ?i

  • 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
Func?ii runkit


Dynamically changes the name of the given method

runkit_method_remove
runkit_return_value_used
Func?ii runkit
PHP Manual

runkit_method_rename

(PECL runkit >= 0.7.0)

runkit_method_rename — Dynamically changes the name of the given method

Descrierea

bool runkit_method_rename ( string $classname , string $methodname , string $newname )

Nota: Aceasta func?ie nu poate fi utilizata pentru a manipula metoda care la moment ruleaza, sau este înlan?uita.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 runkit_method_rename() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// Rename the 'foo' method to 'bar'
runkit_method_rename(
    'Example',
    'foo',
    'bar'
);

// output renamed function
echo Example::bar();
?>

Exemplul de mai sus va afi?a:

foo!

A se vedea ?i

  • 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
Func?ii runkit


Determines if the current functions return value will be used

runkit_method_rename
runkit_sandbox_output_handler
Func?ii runkit
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

Descrierea

bool runkit_return_value_used ( void )

Valorile întoarse

Returns TRUE if the function's return value is used by the calling scope, otherwise FALSE

Exemple

Example #1 runkit_return_value_used() example

<?php
function foo() {
  var_dump(runkit_return_value_used());
}

foo();
$f = foo();
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

runkit_method_rename
runkit_sandbox_output_handler
Func?ii runkit


Specify a function to capture and/or process output from a runkit sandbox

runkit_return_value_used
runkit_superglobals
Func?ii runkit
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

Descrierea

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.

Nota: Sus?inerea cutiei cu nisip (sandbox) (necesara pentru runkit_lint(), runkit_lint_file(), ?i clasa Runkit_Sandbox) este disponibila numai în PHP 5.1 sau cu versiuni special modificate ale PHP 5.0 ?i necesita ca siguran?a firelor de execu?ie sa fie activata. Vede?i fi?ierul README inclus în pachetul runkit pentru a afla mai multe informa?ii.

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

Parametri

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.

Valorile întoarse

Returns the name of the previously defined output handler callback, or FALSE if no handler was previously defined.

Exemple

Example #1 Feeding output to a variable

<?php
function capture_output($str) {
  $GLOBALS['sandbox_output'] .= $str;

  return '';
}

$sandbox_output = '';

$php = new Runkit_Sandbox();
runkit_sandbox_output_handler($php, 'capture_output');
$php->echo("Hello\n");
$php->eval('var_dump("Excuse me");');
$php->die("I lost myself.");
unset($php);

echo "Sandbox Complete\n\n";
echo $sandbox_output;
?>

Exemplul de mai sus va afi?a:

Sandbox Complete

Hello
string(9) "Excuse me"
I lost myself.

runkit_return_value_used
runkit_superglobals
Func?ii runkit


Return numerically indexed array of registered superglobals

runkit_sandbox_output_handler
scream
Func?ii runkit
PHP Manual

runkit_superglobals

(PECL runkit >= 0.7.0)

runkit_superglobals — Return numerically indexed array of registered superglobals

Descrierea

array runkit_superglobals ( void )

Valorile întoarse

Returns a numerically indexed array of the currently registered superglobals. i.e. _GET, _POST, _REQUEST, _COOKIE, _SESSION, _SERVER, _ENV, _FILES

A se vedea ?i

  • Variable Scope

runkit_sandbox_output_handler
scream
Func?ii runkit


Break the silence operator

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Exemple
    • Example that shows the effect of scream
runkit_superglobals
Introducere
Afectarea comportamentului PHP


Introducere

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
Instalarea / configurarea
scream


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
scream


Necesita?i

PHP de versiune 5.2.0 sau ulterioara.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/scream

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

scream Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Changelog
scream.enabled | Off | PHP_INI_ALL |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

scream.enabled int

Whether or not to enable scream.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
Exemple
Instalarea / configurarea


Exemple

Cuprins

  • Example that shows the effect of scream
Tipurile resurselor
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.

Example #1 Enabling and disabling scream at runtime

<?php
// Make sure errors will be shown
ini_set('display_errors', true);
error_reporting(E_ALL);

// Disable scream - this is the default and produce an error
ini_set('scream.enabled', false);
echo "Opening http://example.com/not-existing-file\n";
@fopen('http://example.com/not-existing-file', 'r');

// Now enable scream and try again
ini_set('scream.enabled', true);
echo "Opening http://example.com/not-existing-file\n";
@fopen('http://example.com/not-existing-file', 'r');
?>

Exemplul de mai sus va afi?a ceva similar cu:

Opening http://example.com/not-existing-file
Opening http://example.com/not-existing-file

Warning: fopen(http://example.com/not-existing-file): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in example.php on line 14

Nota: Usually one would set this in the php.ini configuration file instead of changing the code.

Exemple
uopz
Exemple


uopz

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii uopz
    • uopz_backup — Backup a function
    • uopz_compose — Compose a class
    • uopz_copy — Copy a function
    • uopz_delete — Delete a function
    • uopz_extend — Extend a class at runtime
    • uopz_flags — Get or set flags on function or class
    • uopz_function — Creates a function at runtime
    • uopz_implement — Implements an interface at runtime
    • uopz_overload — Overload a VM opcode
    • uopz_redefine — Redefine a constant
    • uopz_rename — Rename a function at runtime
    • uopz_restore — Restore a previously backed up function
    • uopz_undefine — Undefine a constant
Example that shows the effect of scream
Introducere
Afectarea comportamentului PHP


Introducere

The uopz - User Operations for Zend - extension exposes Zend Engine functionality normally used at compilation and execution time in order to allow modification of the internal structures that represent PHP code, and for user code to interact with the VM.

uopz supports the following activities:

  • Overloading some opcodes including ZEND_EXIT and ZEND_NEW
  • Backup and restore functions and methods
  • Renaming functions and methods
  • Copying of functions and methods
  • Deletion of functions and methods
  • Redefinition of global and class constants
  • Deletion of global and class constants
  • Runtime composition and modification of classes

Nota:

All of the activities supported are compatible with opcache

uopz
Instalarea / configurarea
uopz


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
uopz


Necesita?i

uopz requires 5.4+

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

uopz releases are hosted by PECL and the source code by » github, the easiest route to installation is the normal PECL route: » http://pecl.php.net/package/uopz.

Windows users can download prebuilt release binaries from the » PECL website.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

uopz must be loaded as a zend_extension

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

The following opcodes are defined as constants by uopz:

ZEND_EXIT (integer)
Invoked by exit() and die(), recieves no arguments. Return boolean TRUE to exit, FALSE to continue
ZEND_NEW (integer)
Invoked by object construction, receives the class of object being created as the only argument
ZEND_THROW (integer)
Invoked by the throw construct, receives the class of exception being thrown as the only argument
ZEND_FETCH_CLASS (integer)
Invoked upon composure, recieves the class the name of the class being fetched as the only argument
ZEND_ADD_TRAIT (integer)
Invoked upon composure, recieves the class the trait is being added to as the first argument, and the name of the trait as the second argument
ZEND_ADD_INTERFACE (integer)
Invoked upon composure, recieves the class the interface is being added to as the first argument, and the name of the interface as the second argument
ZEND_INSTANCEOF (integer)
Invoked by instanceof operator, recieves the object being verified as the first argument, and the name of the class which that object should be as the second argument

The following constants control the VM's behaviour after a user handler is invoked, be extremely careful!

ZEND_USER_OPCODE_CONTINUE (integer)
Advance 1 opcode and continuue
ZEND_USER_OPCODE_ENTER (integer)
Enter into new op_array without recursion
ZEND_USER_OPCODE_LEAVE (integer)
Return to calling op_array within the same executor
ZEND_USER_OPCODE_DISPATCH (integer)
Dispatch to original opcode handler
ZEND_USER_OPCODE_DISPATCH_TO (integer)
Dispatch to a specific handler (OR'd with ZEND opcode constant)
ZEND_USER_OPCODE_RETURN (integer)
Exit from executor (return from function)

The following modifiers are registered as constants by uopz

ZEND_ACC_PUBLIC (integer)
Mark function as public, the default
ZEND_ACC_PROTECTED (integer)
Mark function as protected
ZEND_ACC_PRIVATE (integer)
Mark function as private
ZEND_ACC_STATIC (integer)
Mark function as static
ZEND_ACC_FINAL (integer)
Mark function as final
ZEND_ACC_ABSTRACT (integer)
Mark function as abstract
ZEND_ACC_CLASS (integer)
Dummy registered for consistency, the default kind of class entry
ZEND_ACC_INTERFACE (integer)
Mark class as interface
ZEND_ACC_TRAIT (integer)
Mark class as trait
ZEND_ACC_FETCH (integer)
Used for getting flags only

Tipurile resurselor
Func?ii uopz
uopz


Func?ii uopz

Cuprins

  • uopz_backup — Backup a function
  • uopz_compose — Compose a class
  • uopz_copy — Copy a function
  • uopz_delete — Delete a function
  • uopz_extend — Extend a class at runtime
  • uopz_flags — Get or set flags on function or class
  • uopz_function — Creates a function at runtime
  • uopz_implement — Implements an interface at runtime
  • uopz_overload — Overload a VM opcode
  • uopz_redefine — Redefine a constant
  • uopz_rename — Rename a function at runtime
  • uopz_restore — Restore a previously backed up function
  • uopz_undefine — Undefine a constant
Constante predefinite
uopz_backup
uopz


Backup a function

Func?ii uopz
uopz_compose
Func?ii uopz
PHP Manual

uopz_backup

(PECL uopz >= 1.0.3)

uopz_backup — Backup a function

Descrierea

void uopz_backup ( string $class , string $function )
void uopz_backup ( string $function )

Backup a function at runtime, to be restored on shutdown

Parametri

class

The name of the class containing the function to backup

function

The name of the function

Valorile întoarse

Exemple

Example #1 uopz_backup() example

<?php
uopz_backup("fgets");
uopz_function("fgets", function(){
    return true;
});
var_dump(fgets());
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
Func?ii uopz
uopz_compose
Func?ii uopz


Compose a class

uopz_backup
uopz_copy
Func?ii uopz
PHP Manual

uopz_compose

(PECL uopz >= 1.0.0)

uopz_compose — Compose a class

Descrierea

void uopz_compose ( string $name , array $classes [, array $methods [, array $properties [, int $flags ]]] )

Creates a new class of the given name that implements, extends, or uses all of the provided classes

Parametri

name

A legal class name

classes

An array of class, interface and trait names

methods

An associative array of methods, values are either closures or [modifiers => closure]

properties

An associative array of properties, keys are names, values are modifiers

flags

Entry type, by default ZEND_ACC_CLASS

Valorile întoarse

Exemple

Example #1 uopz_compose() example

<?php
class myClass {}
trait myTrait {}
interface myInterface {}

uopz_compose(
    Composed::class, [
        myClass::class,
        myTrait::class,
        myInterface::class
    ], [
    "__construct" => function() {
        /* ... */
    }
]);

var_dump(
 class_uses(Composed::class),
 class_parents(Composed::class),
 class_implements(Composed::class));
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  ["myTrait"]=>
  string(7) "myTrait"
}
array(1) {
  ["myClass"]=>
  string(7) "myClass"
}
array(1) {
  ["myInterface"]=>
  string(11) "myInterface"
}
uopz_backup
uopz_copy
Func?ii uopz


Copy a function

uopz_compose
uopz_delete
Func?ii uopz
PHP Manual

uopz_copy

(PECL uopz >= 1.0.4)

uopz_copy — Copy a function

Descrierea

Closure uopz_copy ( string $class , string $function )
Closure uopz_copy ( string $function )

Copy a function by name

Parametri

class

The name of the class containing the function to copy

function

The name of the function

Valorile întoarse

A Closure for the specified function

Exemple

Example #1 uopz_copy() example

<?php
$strtotime = uopz_copy('strtotime');

uopz_function("strtotime", function($arg1, $arg2) use($strtotime) {
    /* can call original strtotime from here */
    var_dump($arg1);
});

var_dump(strtotime('dummy'));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(5) "dummy"
uopz_compose
uopz_delete
Func?ii uopz


Delete a function

uopz_copy
uopz_extend
Func?ii uopz
PHP Manual

uopz_delete

(PECL uopz >= 1.0.0)

uopz_delete — Delete a function

Descrierea

void uopz_delete ( string $class , string $function )
void uopz_delete ( string $function )

Deletes a function or method

Parametri

class

function

Valorile întoarse

Exemple

Example #1 uopz_delete() example

<?php
uopz_delete("strlen");

echo strlen("Hello World");
?>

Exemplul de mai sus va afi?a ceva similar cu:

PHP Fatal error: Call to undefined function strlen() in /path/to/script.php on line 4

Example #2 uopz_delete() class example

<?php
class My {
    public static function strlen($arg) {
        return strlen($arg);
    }
}

uopz_delete(My::class, "strlen");

echo My::strlen("Hello World");
?>

Exemplul de mai sus va afi?a ceva similar cu:

PHP Fatal error: Call to undefined method My::strlen() in /path/to/script.php on line 10
uopz_copy
uopz_extend
Func?ii uopz


Extend a class at runtime

uopz_delete
uopz_flags
Func?ii uopz
PHP Manual

uopz_extend

(PECL uopz >= 1.0.0)

uopz_extend — Extend a class at runtime

Descrierea

void uopz_extend ( string $class , string $parent )

Makes class extend parent

Parametri

class

The name of the class to extend

parent

The name of the class to inherit

Valorile întoarse

Exemple

Example #1 uopz_extend() example

<?php
class A {}
class B {}

uopz_extend(A::class, B::class);

var_dump(class_parents(A::class));
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  ["B"]=>
  string(1) "B"
}
uopz_delete
uopz_flags
Func?ii uopz


Get or set flags on function or class

uopz_extend
uopz_function
Func?ii uopz
PHP Manual

uopz_flags

(PECL uopz >= 2.0.2)

uopz_flags — Get or set flags on function or class

Descrierea

int uopz_flags ( string $class , string $function , int $flags )
int uopz_flags ( string $function , int $flags )

Get or set the flags on a class or function entry at runtime

Parametri

class

The name of a class

function

The name of the function

flags

A valid set of ZEND_ACC_ flags, ZEND_ACC_FETCH to read flags

Valorile întoarse

If setting, returns old flags, else returns flags

Exemple

Example #1 uopz_flags() example

<?php
class Test {
    public function method() {
        return __CLASS__;
    }
}

$flags = uopz_flags("Test", "method", ZEND_ACC_FETCH);

var_dump((bool) (uopz_flags("Test", "method", ZEND_ACC_FETCH) & ZEND_ACC_PRIVATE));
var_dump((bool) (uopz_flags("Test", "method", ZEND_ACC_FETCH) & ZEND_ACC_STATIC));

var_dump(uopz_flags("Test", "method", $flags|ZEND_ACC_STATIC|ZEND_ACC_PRIVATE));

var_dump((bool) (uopz_flags("Test", "method", ZEND_ACC_FETCH) & ZEND_ACC_PRIVATE));
var_dump((bool) (uopz_flags("Test", "method", ZEND_ACC_FETCH) & ZEND_ACC_STATIC));
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
bool(false)
int(1234567890)
bool(true)
bool(true)
uopz_extend
uopz_function
Func?ii uopz


Creates a function at runtime

uopz_flags
uopz_implement
Func?ii uopz
PHP Manual

uopz_function

(PECL uopz >= 1.0.0)

uopz_function — Creates a function at runtime

Descrierea

void uopz_function ( string $class , string $function , Closure $handler [, int $modifiers ] )
void uopz_function ( string $function , Closure $handler [, int $modifiers ] )

Creates a function at runtime

Parametri

class

The name of the class to receive the new function

function

The name of the function

handler

The Closure for the function

modifiers

The modifiers for the function, by default copied or ZEND_ACC_PUBLIC

Valorile întoarse

Exemple

Example #1 uopz_function() example

<?php
uopz_function("my_strlen", function($arg) {
    return strlen($arg);
});
echo my_strlen("Hello World");
?>

Exemplul de mai sus va afi?a ceva similar cu:

11

Example #2 uopz_function() class example

<?php
class My {}

uopz_function(My::class, "strlen", function($arg) {
    return strlen($arg);
}, ZEND_ACC_STATIC);

echo My::strlen("Hello World");
?>

Exemplul de mai sus va afi?a ceva similar cu:

11
uopz_flags
uopz_implement
Func?ii uopz


Implements an interface at runtime

uopz_function
uopz_overload
Func?ii uopz
PHP Manual

uopz_implement

(PECL uopz >= 1.0.0)

uopz_implement — Implements an interface at runtime

Descrierea

void uopz_implement ( string $class , string $interface )

Makes class implement interface

Parametri

class

interface

Valorile întoarse

Exemple

Example #1 uopz_implement() example

<?php
interface myInterface {}

class myClass {}

uopz_implement(myClass::class, myInterface::class);

var_dump(class_implements(myClass::class));
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  ["myInterface"]=>
  string(11) "myInterface"
}
uopz_function
uopz_overload
Func?ii uopz


Overload a VM opcode

uopz_implement
uopz_redefine
Func?ii uopz
PHP Manual

uopz_overload

(PECL uopz >= 1.0.0)

uopz_overload — Overload a VM opcode

Descrierea

void uopz_overload ( int $opcode , Callable $callable )

Overloads the specified opcode with the user defined function

Parametri

opcode

A valid opcode, see constants for details of supported codes

callable

Valorile întoarse

Exemple

Example #1 uopz_overload() example

<?php
uopz_overload(ZEND_EXIT, function(){});

exit();
echo "Hello World";
?>

Exemplul de mai sus va afi?a ceva similar cu:

Hello World
uopz_implement
uopz_redefine
Func?ii uopz


Redefine a constant

uopz_overload
uopz_rename
Func?ii uopz
PHP Manual

uopz_redefine

(PECL uopz >= 1.0.0)

uopz_redefine — Redefine a constant

Descrierea

void uopz_redefine ( string $class , string $constant , mixed $value )
void uopz_redefine ( string $constant , mixed $value )

Redefines the given constant as value

Parametri

class

The name of the class containing the constant

constant

The name of the constant

value

The new value for the constant, must be a valid type for a constant variable

Valorile întoarse

Exemple

Example #1 uopz_redefine() example

<?php
define("MY", 100);

uopz_redefine("MY", 1000);

echo MY;
?>

Exemplul de mai sus va afi?a ceva similar cu:

1000
uopz_overload
uopz_rename
Func?ii uopz


Rename a function at runtime

uopz_redefine
uopz_restore
Func?ii uopz
PHP Manual

uopz_rename

(PECL uopz >= 1.0.0)

uopz_rename — Rename a function at runtime

Descrierea

void uopz_rename ( string $class , string $function , string $rename )
void uopz_rename ( string $function , string $rename )

Renames function to rename

Nota:

If both functions exist, this effectively swaps their names

Parametri

class

The name of the class containing the function

function

The name of an existing function

rename

The new name for the function

Valorile întoarse

Exemple

Example #1 uopz_rename() example

<?php
uopz_rename("strlen", "original_strlen");

echo original_strlen("Hello World");
?>

Exemplul de mai sus va afi?a ceva similar cu:

11

Example #2 uopz_rename() class example

<?php
class My {
    public function strlen($arg) {
        return strlen($arg);
    }
}

uopz_rename(My::class, "strlen", "original_strlen");

echo My::original_strlen("Hello World");
?>

Exemplul de mai sus va afi?a ceva similar cu:

11
uopz_redefine
uopz_restore
Func?ii uopz


Restore a previously backed up function

uopz_rename
uopz_undefine
Func?ii uopz
PHP Manual

uopz_restore

(PECL uopz >= 1.0.3)

uopz_restore — Restore a previously backed up function

Descrierea

void uopz_restore ( string $class , string $function )
void uopz_restore ( string $function )

Restore a previously backed up function

Parametri

class

The name of the class containing the function to restore

function

The name of the function

Valorile întoarse

Exemple

Example #1 uopz_restore() example

<?php
uopz_backup("fgets");
uopz_function("fgets", function(){
    return true;
});
var_dump(fgets());
uopz_restore('fgets');
fgets();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Warning: fgets() expects at least 1 parameter, 0 given in /path/to/script.php on line 8
uopz_rename
uopz_undefine
Func?ii uopz


Undefine a constant

uopz_restore
Weakref
Func?ii uopz
PHP Manual

uopz_undefine

(PECL uopz >= 1.0.0)

uopz_undefine — Undefine a constant

Descrierea

void uopz_undefine ( string $class , string $constant )
void uopz_undefine ( string $constant )

Removes the constant at runtime

Parametri

class

The name of the class containing constant

constant

The name of an existing constant

Valorile întoarse

Exemple

Example #1 uopz_undefine() example

<?php
define("MY", true);

uopz_undefine("MY");

var_dump(defined("MY"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
uopz_restore
Weakref
Func?ii uopz


Weak References

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Tipurile resurselor
  • 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
  • WeakMap — The WeakMap class
    • WeakMap::__construct — Constructs a new map
    • WeakMap::count — Counts the number of live entries in the map
    • WeakMap::current — Returns the current value under iteration
    • WeakMap::key — Returns the current key under iteration.
    • WeakMap::next — Advances to the next map element
    • WeakMap::offsetExists — Checks whether a certain object is in the map
    • WeakMap::offsetGet — Returns the value pointed to by a certain object
    • WeakMap::offsetSet — Updates the map with a new key-value pair
    • WeakMap::offsetUnset — Removes an entry from the map
    • WeakMap::rewind — Rewinds the iterator to the beginning of the map
    • WeakMap::valid — Returns whether the iterator is still on a valid map element
uopz_undefine
Introducere
Afectarea comportamentului PHP


Introducere

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.

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

Exemplul de mai sus va afi?a:

Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!

Weakref
Instalarea / configurarea
Weakref


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Tipurile resurselor
Introducere
Necesita?i
Weakref


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/weakref.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Instalarea
WeakRef
Instalarea / configurarea


The WeakRef class

(PECL weakref >= 0.1.0)

Introducere

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.

Sinopsisul clasei

WeakRef {
/* Metode */
public Weakref::__construct ( object $object )
public bool Weakref::acquire ( void )
public object Weakref::get ( void )
public bool Weakref::release ( void )
public bool Weakref::valid ( void )
}

Exemple

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

Exemplul de mai sus va afi?a:

Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!

Cuprins

  • 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
Tipurile resurselor
Weakref::acquire
Weakref


Acquires a strong reference on that object

WeakRef
Weakref::__construct
WeakRef
PHP Manual

Weakref::acquire

(PECL weakref >= 0.1.0)

Weakref::acquire — Acquires a strong reference on that object

Descrierea

public bool Weakref::acquire ( void )

Acquires a strong reference on that object, virtually turning the weak reference into a strong one.

The Weakref instance maintains an internal acquired counter to track outstanding strong references. If the call to Weakref::acquire() is successful, this counter will be incremented by one.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the reference was valid and could be turned into a strong reference, FALSE otherwise.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

Unsetting o1...
Unsetting o2...
Destroying object!

Example #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();

?>

Exemplul de mai sus va afi?a:

Acquiring...
  Unsetting...
  Acquiring...
    Acquiring...
    Releasing...
  Releasing...
Releasing...
Destroying object!

A se vedea ?i

  • 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

(PECL weakref >= 0.1.0)

Weakref::__construct — Constructs a new weak reference

Descrierea

public Weakref::__construct ( object $object )

Constructs a new weak reference.

Parametri

object

The object to reference.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

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

Exemplul de mai sus va afi?a:

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

(PECL weakref >= 0.1.0)

Weakref::get — Returns the object pointed to by the weak reference

Descrierea

public object Weakref::get ( void )

Returns the object pointed to by the weak reference.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the object if the reference is still valid, NULL otherwise.

A se vedea ?i

  • 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

(PECL weakref >= 0.1.0)

Weakref::release — Releases a previously acquired reference

Descrierea

public bool Weakref::release ( void )

Releases a previously acquired reference, potentially turning a strong reference back into a weak reference.

The Weakref instance maintains an internal acquired counter to track outstanding strong references. If the call to Weakref::release() is successful, this counter will be decremented by one. Once this counter reaches zero, the strong reference is turned back into a weak reference.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the reference was previously acquired and thus could be released, FALSE otherwise.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

Unsetting o1...
Unsetting o2...
Destroying object!

A se vedea ?i

  • Weakref::acquire() - Acquires a strong reference on that object

Weakref::get
Weakref::valid
WeakRef


Checks whether the object referenced still exists

Weakref::release
WeakMap
WeakRef
PHP Manual

Weakref::valid

(PECL weakref >= 0.1.0)

Weakref::valid — Checks whether the object referenced still exists

Descrierea

public bool Weakref::valid ( void )

Checks whether the object referenced still exists.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the object still exists and is thus still accessible via Weakref::get(), FALSE otherwise.

A se vedea ?i

  • Weakref::get() - Returns the object pointed to by the weak reference

Weakref::release
WeakMap
WeakRef


The WeakMap class

(PECL weakref >= 0.2.0)

Introducere

Sinopsisul clasei

WeakMap implements Countable , ArrayAccess , Iterator {
/* Metode */
public __construct ( void )
public int count ( void )
public mixed current ( void )
public object key ( void )
public void next ( void )
public bool offsetExists ( object $object )
public mixed offsetGet ( object $object )
public void offsetSet ( object $object , mixed $value )
public void offsetUnset ( object $object )
public void rewind ( void )
public bool valid ( void )
}

Exemple

Example #1 Weakmap usage example

<?php
$wm = new WeakMap();

$o = new StdClass;

class A {
    public function __destruct() {
        echo "Dead!\n";
    }
}

$wm[$o] = new A;

var_dump(count($wm));
echo "Unsetting..\n";
unset($o);
echo "Done\n";
var_dump(count($wm));

Exemplul de mai sus va afi?a:

int(1)
Unsetting..
Dead!
Done
int(0)

Cuprins

  • WeakMap::__construct — Constructs a new map
  • WeakMap::count — Counts the number of live entries in the map
  • WeakMap::current — Returns the current value under iteration
  • WeakMap::key — Returns the current key under iteration.
  • WeakMap::next — Advances to the next map element
  • WeakMap::offsetExists — Checks whether a certain object is in the map
  • WeakMap::offsetGet — Returns the value pointed to by a certain object
  • WeakMap::offsetSet — Updates the map with a new key-value pair
  • WeakMap::offsetUnset — Removes an entry from the map
  • WeakMap::rewind — Rewinds the iterator to the beginning of the map
  • WeakMap::valid — Returns whether the iterator is still on a valid map element
Weakref::valid
WeakMap::__construct
Weakref


Constructs a new map

WeakMap
WeakMap::count
WeakMap
PHP Manual

WeakMap::__construct

(PECL weakref >= 0.2.0)

WeakMap::__construct — Constructs a new map

Descrierea

public WeakMap::__construct ( void )

Constructs a new map.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

WeakMap
WeakMap::count
WeakMap


Counts the number of live entries in the map

WeakMap::__construct
WeakMap::current
WeakMap
PHP Manual

WeakMap::count

(PECL weakref >= 0.2.0)

WeakMap::count — Counts the number of live entries in the map

Descrierea

public int WeakMap::count ( void )

Counts the number of live entries in the map.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the number of live entries in the map.

WeakMap::__construct
WeakMap::current
WeakMap


Returns the current value under iteration

WeakMap::count
WeakMap::key
WeakMap
PHP Manual

WeakMap::current

(PECL weakref >= 0.2.0)

WeakMap::current — Returns the current value under iteration

Descrierea

public mixed WeakMap::current ( void )

Returns the current value being iterated on in the map.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The value currently being iterated on.

WeakMap::count
WeakMap::key
WeakMap


Returns the current key under iteration.

WeakMap::current
WeakMap::next
WeakMap
PHP Manual

WeakMap::key

(PECL weakref >= 0.2.0)

WeakMap::key — Returns the current key under iteration.

Descrierea

public object WeakMap::key ( void )

Returns the object serving as key in the map, at the current iterating position.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The object key currently being iterated.

WeakMap::current
WeakMap::next
WeakMap


Advances to the next map element

WeakMap::key
WeakMap::offsetExists
WeakMap
PHP Manual

WeakMap::next

(PECL weakref >= 0.2.0)

WeakMap::next — Advances to the next map element

Descrierea

public void WeakMap::next ( void )

Advances to the next map element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

WeakMap::key
WeakMap::offsetExists
WeakMap


Checks whether a certain object is in the map

WeakMap::next
WeakMap::offsetGet
WeakMap
PHP Manual

WeakMap::offsetExists

(PECL weakref >= 0.2.0)

WeakMap::offsetExists — Checks whether a certain object is in the map

Descrierea

public bool WeakMap::offsetExists ( object $object )

Checks whether the passed object is referenced in the map.

Parametri

object

Object to check for.

Valorile întoarse

Returns TRUE if the object is contained in the map, FALSE otherwise.

WeakMap::next
WeakMap::offsetGet
WeakMap


Returns the value pointed to by a certain object

WeakMap::offsetExists
WeakMap::offsetSet
WeakMap
PHP Manual

WeakMap::offsetGet

(PECL weakref >= 0.2.0)

WeakMap::offsetGet — Returns the value pointed to by a certain object

Descrierea

public mixed WeakMap::offsetGet ( object $object )

Returns the value pointed to by a certain object.

Parametri

object

Some object contained as key in the map.

Valorile întoarse

Returns the value associated to the object passed as argument, NULL otherwise.

WeakMap::offsetExists
WeakMap::offsetSet
WeakMap


Updates the map with a new key-value pair

WeakMap::offsetGet
WeakMap::offsetUnset
WeakMap
PHP Manual

WeakMap::offsetSet

(PECL weakref >= 0.2.0)

WeakMap::offsetSet — Updates the map with a new key-value pair

Descrierea

public void WeakMap::offsetSet ( object $object , mixed $value )

Updates the map with a new key-value pair. If the key already existed in the map, the old value is replaced with the new.

Parametri

object

The object serving as key of the key-value pair.

value

The arbitrary data serving as value of the key-value pair.

Valorile întoarse

Nu este întoarsa nici o valoare.

WeakMap::offsetGet
WeakMap::offsetUnset
WeakMap


Removes an entry from the map

WeakMap::offsetSet
WeakMap::rewind
WeakMap
PHP Manual

WeakMap::offsetUnset

(PECL weakref >= 0.2.0)

WeakMap::offsetUnset — Removes an entry from the map

Descrierea

public void WeakMap::offsetUnset ( object $object )

Removes an entry from the map.

Parametri

object

The key object to remove from the map.

Valorile întoarse

Nu este întoarsa nici o valoare.

WeakMap::offsetSet
WeakMap::rewind
WeakMap


Rewinds the iterator to the beginning of the map

WeakMap::offsetUnset
WeakMap::valid
WeakMap
PHP Manual

WeakMap::rewind

(PECL weakref >= 0.2.0)

WeakMap::rewind — Rewinds the iterator to the beginning of the map

Descrierea

public void WeakMap::rewind ( void )

Rewinds the iterator to the beginning of the map.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

WeakMap::offsetUnset
WeakMap::valid
WeakMap


Returns whether the iterator is still on a valid map element

WeakMap::rewind
WinCache
WeakMap
PHP Manual

WeakMap::valid

(PECL weakref >= 0.2.0)

WeakMap::valid — Returns whether the iterator is still on a valid map element

Descrierea

public bool WeakMap::valid ( void )

Returns whether the iterator is still on a valid map element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the iterator is on a valid element that can be accessed, FALSE otherwise.

WeakMap::rewind
WinCache
WeakMap


Windows Cache for PHP

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • WinCache Statistics Script
    • WinCache Session Handler
    • WinCache Functions Reroutes
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii WinCache
    • 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
WeakMap::valid
Introducere
Afectarea comportamentului PHP


Introducere

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
Instalarea / configurarea
WinCache


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • WinCache Statistics Script
  • WinCache Session Handler
  • WinCache Functions Reroutes
  • Tipurile resurselor
Introducere
Necesita?i
WinCache


Necesita?i

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

Nota: The WinCache Extension can only be used when IIS is configured to run PHP via FastCGI.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » 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.

Nota: Do not forget to remove phpinfo.php file from the web site's root folder after verifying that extension has been enabled.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

The following table lists and explains the configuration settings provided by the WinCache extension:

WinCache configuration options
Denumire | Valoare implicita | Minimum | Maximum | Poate fi modificata | Jurnal al modificarilor
wincache.fcenabled | "1" | "0" | "1" | PHP_INI_ALL | Available as of WinCache 1.0.0
wincache.fcenabledfilter | "NULL" | "NULL" | "NULL" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.fcachesize | "24" | "5" | "255" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.fcndetect | "1" | "0" | "1" | PHP_INI_SYSTEM | Available as of WinCache 1.1.0
wincache.maxfilesize | "256" | "10" | "2048" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.ocenabled | "1" | "0" | "1" | PHP_INI_ALL | Available as of WinCache 1.0.0. Removed as of 2.0.0.0
wincache.ocenabledfilter | "NULL" | "NULL" | "NULL" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0. Removed as of 2.0.0.0
wincache.ocachesize | "96" | "15" | "255" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0. Removed as of 2.0.0.0
wincache.filecount | "4096" | "1024" | "16384" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.chkinterval | "30" | "0" | "300" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.ttlmax | "1200" | "0" | "7200" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.enablecli | 0 | 0 | 1 | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.ignorelist | NULL | NULL | NULL | PHP_INI_ALL | Available as of WinCache 1.0.0
wincache.namesalt | NULL | NULL | NULL | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.ucenabled | 1 | 0 | 1 | PHP_INI_SYSTEM | Available as of WinCache 1.1.0
wincache.ucachesize | 8 | 5 | 85 | PHP_INI_SYSTEM | Available as of WinCache 1.1.0
wincache.scachesize | 8 | 5 | 85 | PHP_INI_SYSTEM | Available as of WinCache 1.1.0
wincache.rerouteini | NULL | NULL | NULL | PHP_INI_SYSTEM | Available as of WinCache 1.2.0. Removed as of 1.3.7
wincache.reroute_enabled | 1 | 0 | 1 | PHP_INI_SYSTEM | PHP_INI_PERDIR | Available as of WinCache 1.3.7
wincache.srwlocks | 1 | 0 | 1 | PHP_INI_SYSTEM | Available as of WinCache 1.3.6.3. Removed as of 2.0.0.0
wincache.filemapdir | NULL | NULL | NULL | PHP_INI_SYSTEM | Available as of WinCache 1.3.7.4
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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
Avertizare

This option has been REMOVED as of 2.0.0.0

Enables or disables the opcode cache functionality
wincache.ocenabledfilter string
Avertizare

This option has been REMOVED as of 2.0.0.0

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
Avertizare

This option has been REMOVED as of 2.0.0.0

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

Example #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
Avertizare

This option has been REMOVED as of 1.3.7. See wincache.reroute_enabled for similar functionality as of 1.3.7.

Specifies an absolute or a relateve path to the reroute.ini file that contains the list of PHP functions whose implementation should be replaced with the WinCache function equivalents. If a relative path is specified then it is assumed to be relative to the location of php-cgi.exe file.
wincache.reroute_enabled boolean
Enables or disables the rerouting of certain file I/O functions through the file cache.
wincache.srwlocks boolean
Avertizare

This option has been REMOVED as of 2.0.0.0

Enables or disables the use of shared reader/writer locks. Disabling is useful when troubleshooting deadlock conditions in WinCache.
wincache.filemapdir string
Specifies an absolute path to a directory where WinCache will store the temporary files used for shared memory segments. This directory must be on the local machine and not on a networked file system. If the directory is not specified, WinCache will use the Windows System Page File for all shared memory segments.

Instalarea
WinCache Statistics Script
Instalarea / configurarea


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:

Example #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 ========================== */
?>

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

Configura?ia la rulare
WinCache Session Handler
Instalarea / configurarea


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.

Example #1 Enabling WinCache session handler

session.save_handler = wincache
session.save_path = C:\inetpub\temp\session\

WinCache Statistics Script
WinCache Functions Reroutes
Instalarea / configurarea


WinCache Functions Reroutes

NOTE: wincache.rerouteini was removed as of WinCache 1.3.7.0. It has been replaced with automatic function reroutes. See: wincache.reroute_enabled.

The WinCache functions reroutes (available since WinCache 1.2.0, removed since WinCache 1.3.7.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.

Example #1 Enabling WinCache functions reroutes

wincache.rerouteini = C:\PHP\reroute.ini

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

Example #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
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

WinCache Functions Reroutes
Constante predefinite
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii WinCache
WinCache


Func?ii WinCache

Cuprins

  • 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
Constante predefinite
wincache_fcache_fileinfo
WinCache


Retrieves information about files cached in the file cache

Func?ii WinCache
wincache_fcache_meminfo
Func?ii WinCache
PHP Manual

wincache_fcache_fileinfo

(PECL wincache >= 1.0.0)

wincache_fcache_fileinfo — Retrieves information about files cached in the file cache

Descrierea

array wincache_fcache_fileinfo ([ bool $summaryonly = false ] )

Retrieves information about file cache content and its usage.

Parametri

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the file cache summary.

Valorile întoarse

Array of meta data about file cache sau FALSE în cazul e?ecului

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

Exemple

Example #1 A wincache_fcache_fileinfo() example

<pre>
<?php
print_r(wincache_fcache_fileinfo());
?>
</pre>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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

Func?ii WinCache
wincache_fcache_meminfo
Func?ii WinCache


Retrieves information about file cache memory usage

wincache_fcache_fileinfo
wincache_lock
Func?ii WinCache
PHP Manual

wincache_fcache_meminfo

(PECL wincache >= 1.0.0)

wincache_fcache_meminfo — Retrieves information about file cache memory usage

Descrierea

array wincache_fcache_meminfo ( void )

Retrieves information about memory usage by file cache.

Valorile întoarse

Array of meta data about file cache memory usage sau FALSE în cazul e?ecului

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

Exemple

Example #1 A wincache_fcache_meminfo() example

<pre>
<?php
print_r(wincache_fcache_meminfo());
?>
</pre>

Exemplul de mai sus va afi?a:

Array
(
    [memory_total] => 134217728
    [memory_free] => 131339120
    [num_used_blks] => 361
    [num_free_blks] => 3
    [memory_overhead] => 5856
)

A se vedea ?i

  • 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
Func?ii WinCache


Acquires an exclusive lock on a given key

wincache_fcache_meminfo
wincache_ocache_fileinfo
Func?ii WinCache
PHP Manual

wincache_lock

(PECL wincache >= 1.1.0)

wincache_lock — Acquires an exclusive lock on a given key

Descrierea

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

Avertizare

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii WinCache


Retrieves information about files cached in the opcode cache

wincache_lock
wincache_ocache_meminfo
Func?ii WinCache
PHP Manual

wincache_ocache_fileinfo

(PECL wincache >= 1.0.0)

wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache

Descrierea

array wincache_ocache_fileinfo ([ bool $summaryonly = false ] )

Retrieves information about opcode cache content and its usage.

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Parametri

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the opcode cache summary.

Valorile întoarse

Array of meta data about opcode cache sau FALSE în cazul e?ecului

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

Exemple

Example #1 A wincache_ocache_fileinfo() example

<pre>
<?php
print_r(wincache_ocache_fileinfo());
?>
</pre>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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
Func?ii WinCache


Retrieves information about opcode cache memory usage

wincache_ocache_fileinfo
wincache_refresh_if_changed
Func?ii WinCache
PHP Manual

wincache_ocache_meminfo

(PECL wincache >= 1.0.0)

wincache_ocache_meminfo — Retrieves information about opcode cache memory usage

Descrierea

array wincache_ocache_meminfo ( void )

Retrieves information about memory usage by opcode cache.

Valorile întoarse

Array of meta data about opcode cache memory usage sau FALSE în cazul e?ecului

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

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Exemple

Example #1 A wincache_ocache_meminfo() example

<pre>
<?php
print_r(wincache_ocache_meminfo());
?>
</pre>

Exemplul de mai sus va afi?a:

Array
(
    [memory_total] => 134217728
    [memory_free] => 112106972
    [num_used_blks] => 15469
    [num_free_blks] => 4
    [memory_overhead] => 247600
)

A se vedea ?i

  • 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
Func?ii WinCache


Refreshes the cache entries for the cached files

wincache_ocache_meminfo
wincache_rplist_fileinfo
Func?ii WinCache
PHP Manual

wincache_refresh_if_changed

(PECL wincache >= 1.0.0)

wincache_refresh_if_changed — Refreshes the cache entries for the cached files

Descrierea

bool wincache_refresh_if_changed ([ array $files = NULL ] )

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.

Parametri

files

An array of file names for files that need to be refreshed. An absolute or relative file paths can be used.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

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.

Example #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));
?>

A se vedea ?i

  • 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
Func?ii WinCache


Retrieves information about resolve file path cache

wincache_refresh_if_changed
wincache_rplist_meminfo
Func?ii WinCache
PHP Manual

wincache_rplist_fileinfo

(PECL wincache >= 1.0.0)

wincache_rplist_fileinfo — Retrieves information about resolve file path cache

Descrierea

array wincache_rplist_fileinfo ([ bool $summaryonly = false ] )

Retrieves information about cached mappings between relative file paths and corresponding absolute file paths.

Valorile întoarse

Array of meta data about the resolve file path cache sau FALSE în cazul e?ecului

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

Exemple

Example #1 A wincache_rplist_fileinfo() example

<pre>
<?php
print_r(wincache_rplist_fileinfo());
?>
</pre>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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
Func?ii WinCache


Retrieves information about memory usage by the resolve file path cache

wincache_rplist_fileinfo
wincache_scache_info
Func?ii WinCache
PHP Manual

wincache_rplist_meminfo

(PECL wincache >= 1.0.0)

wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache

Descrierea

array wincache_rplist_meminfo ( void )

Retrieves information about memory usage by resolve file path cache.

Valorile întoarse

Array of meta data that describes memory usage by resolve file path cache. sau FALSE în cazul e?ecului

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

Exemple

Example #1 A wincache_rplist_meminfo() example

<pre>
<?php
print_r(wincache_rplist_meminfo());
?>
</pre>

Exemplul de mai sus va afi?a:

Array
(
    [memory_total] => 9437184
    [memory_free] => 9416744
    [num_used_blks] => 23
    [num_free_blks] => 1
    [memory_overhead] => 416
)

A se vedea ?i

  • 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
Func?ii WinCache


Retrieves information about files cached in the session cache

wincache_rplist_meminfo
wincache_scache_meminfo
Func?ii WinCache
PHP Manual

wincache_scache_info

(PECL wincache >= 1.1.0)

wincache_scache_info — Retrieves information about files cached in the session cache

Descrierea

array wincache_scache_info ([ bool $summaryonly = false ] )

Retrieves information about session cache content and its usage.

Parametri

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the session cache summary.

Valorile întoarse

Array of meta data about session cache sau FALSE în cazul e?ecului

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

Exemple

Example #1 A wincache_scache_info() example

<pre>
<?php
print_r(wincache_scache_info());
?>
</pre>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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
Func?ii WinCache


Retrieves information about session cache memory usage

wincache_scache_info
wincache_ucache_add
Func?ii WinCache
PHP Manual

wincache_scache_meminfo

(PECL wincache >= 1.1.0)

wincache_scache_meminfo — Retrieves information about session cache memory usage

Descrierea

array wincache_scache_meminfo ( void )

Retrieves information about memory usage by session cache.

Valorile întoarse

Array of meta data about session cache memory usage sau FALSE în cazul e?ecului

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

Exemple

Example #1 A wincache_scache_meminfo() example

<pre>
<?php
print_r(wincache_scache_meminfo());
?>
</pre>

Exemplul de mai sus va afi?a:

Array
(
    [memory_total] => 5242880
    [memory_free] => 5215056
    [num_used_blks] => 6
    [num_free_blks] => 3
    [memory_overhead] => 176
)

A se vedea ?i

  • 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
Func?ii WinCache


Adds a variable in user cache only if variable does not already exist in the cache

wincache_scache_meminfo
wincache_ucache_cas
Func?ii WinCache
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

Descrierea

bool wincache_ucache_add ( string $key , mixed $value [, int $ttl = 0 ] )
bool wincache_ucache_add ( array $values [, mixed $unused = NULL [, 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.

Parametri

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.

Valorile întoarse

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.

Exemple

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

Exemplul de mai sus va afi?a:

bool(true)
bool(false)
string(3) "BAR"

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

Exemplul de mai sus va afi?a:

array(0) { }
array(4) {
  ["green"]=> int(-1)
  ["Blue"]=> int(-1)
  ["yellow"]=> int(-1)
  ["cyan"]=> int(-1)
}
string(1) "6"

A se vedea ?i

  • 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
Func?ii WinCache


Compares the variable with old value and assigns new value to it

wincache_ucache_add
wincache_ucache_clear
Func?ii WinCache
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

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

Exemplul de mai sus va afi?a:

bool(true)
int(1)

A se vedea ?i

  • 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
Func?ii WinCache


Deletes entire content of the user cache

wincache_ucache_cas
wincache_ucache_dec
Func?ii WinCache
PHP Manual

wincache_ucache_clear

(PECL wincache >= 1.1.0)

wincache_ucache_clear — Deletes entire content of the user cache

Descrierea

bool wincache_ucache_clear ( void )

Clears/deletes all the values stored in the user cache.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

array(5) { ["green"]=> int(1)
           ["red"]=> int(2)
           ["orange"]=> int(4)
           ["blue"]=> int(8)
           ["cyan"]=> int(16) }
bool(true)
bool(false)

A se vedea ?i

  • 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
Func?ii WinCache


Decrements the value associated with the key

wincache_ucache_clear
wincache_ucache_delete
Func?ii WinCache
PHP Manual

wincache_ucache_dec

(PECL wincache >= 1.1.0)

wincache_ucache_dec — Decrements the value associated with the key

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the decremented value on success and FALSE on failure.

Exemple

Example #1 Using wincache_ucache_dec()

<?php
wincache_ucache_set('counter', 1);
var_dump(wincache_ucache_dec('counter', 2923, $success));
var_dump($success);
?>

Exemplul de mai sus va afi?a:

int(2922)
bool(true)

A se vedea ?i

  • 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
Func?ii WinCache


Deletes variables from the user cache

wincache_ucache_dec
wincache_ucache_exists
Func?ii WinCache
PHP Manual

wincache_ucache_delete

(PECL wincache >= 1.1.0)

wincache_ucache_delete — Deletes variables from the user cache

Descrierea

bool wincache_ucache_delete ( mixed $key )

Deletes the elements in the user cache pointed by key.

Parametri

key

The key that was used to store the variable in the cache. key is case sensitive. key can be an array of keys.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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.

Exemple

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

Exemplul de mai sus va afi?a:

bool(true)
bool(false)

Example #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));
?>

Exemplul de mai sus va afi?a:

array(4) { [0]=> string(5) "green"
           [1]=> string(4) "Blue"
           [2]=> string(6) "yellow"
           [3]=> string(4) "cyan" }

Example #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));
?>

Exemplul de mai sus va afi?a:

array(2) { [0]=> string(6) "yellow"
           [1]=> string(4) "cyan" }

A se vedea ?i

  • 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
Func?ii WinCache


Checks if a variable exists in the user cache

wincache_ucache_delete
wincache_ucache_get
Func?ii WinCache
PHP Manual

wincache_ucache_exists

(PECL wincache >= 1.1.0)

wincache_ucache_exists — Checks if a variable exists in the user cache

Descrierea

bool wincache_ucache_exists ( string $key )

Checks if a variable with the key exists in the user cache or not.

Parametri

key

The key that was used to store the variable in the cache. key is case sensitive.

Valorile întoarse

Returns TRUE if variable with the key exitsts, otherwise returns FALSE.

Exemple

Example #1 Using wincache_ucache_exists()

<?php
if (!wincache_ucache_exists('green'))
    wincache_ucache_set('green', 1);
var_dump(wincache_ucache_exists('green'));
?>

Exemplul de mai sus va afi?a:

bool(true)

A se vedea ?i

  • 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
Func?ii WinCache


Gets a variable stored in the user cache

wincache_ucache_exists
wincache_ucache_inc
Func?ii WinCache
PHP Manual

wincache_ucache_get

(PECL wincache >= 1.1.0)

wincache_ucache_get — Gets a variable stored in the user cache

Descrierea

mixed wincache_ucache_get ( mixed $key [, bool &$success ] )

Gets a variable stored in the user cache.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

string(4) "blue"
bool(true)

Example #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);
?>

Exemplul de mai sus va afi?a:

array(4) { ["green"]=> string(1) "5"
           ["Blue"]=> string(1) "6"
           ["yellow"]=> string(1) "7"
           ["cyan"]=> string(1) "8" }
bool(true)

A se vedea ?i

  • 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
Func?ii WinCache


Increments the value associated with the key

wincache_ucache_get
wincache_ucache_info
Func?ii WinCache
PHP Manual

wincache_ucache_inc

(PECL wincache >= 1.1.0)

wincache_ucache_inc — Increments the value associated with the key

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the incremented value on success and FALSE on failure.

Exemple

Example #1 Using wincache_ucache_inc()

<?php
wincache_ucache_set('counter', 1);
var_dump(wincache_ucache_inc('counter', 2921, $success));
var_dump($success);
?>

Exemplul de mai sus va afi?a:

int(2922)
bool(true)

A se vedea ?i

  • 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
Func?ii WinCache


Retrieves information about data stored in the user cache

wincache_ucache_inc
wincache_ucache_meminfo
Func?ii WinCache
PHP Manual

wincache_ucache_info

(PECL wincache >= 1.1.0)

wincache_ucache_info — Retrieves information about data stored in the user cache

Descrierea

array wincache_ucache_info ([ bool $summaryonly = false [, string $key = NULL ]] )

Retrieves information about data stored in the user cache.

Parametri

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.

Valorile întoarse

Array of meta data about user cache sau FALSE în cazul e?ecului

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

Exemple

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

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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
Func?ii WinCache


Retrieves information about user cache memory usage

wincache_ucache_info
wincache_ucache_set
Func?ii WinCache
PHP Manual

wincache_ucache_meminfo

(PECL wincache >= 1.1.0)

wincache_ucache_meminfo — Retrieves information about user cache memory usage

Descrierea

array wincache_ucache_meminfo ( void )

Retrieves information about memory usage by user cache.

Valorile întoarse

Array of meta data about user cache memory usage sau FALSE în cazul e?ecului

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

Exemple

Example #1 A wincache_ucache_meminfo() example

<pre>
<?php
print_r(wincache_ucache_meminfo());
?>
</pre>

Exemplul de mai sus va afi?a:

Array
(
    [memory_total] => 5242880
    [memory_free] => 5215056
    [num_used_blks] => 6
    [num_free_blks] => 3
    [memory_overhead] => 176
)

A se vedea ?i

  • 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
Func?ii WinCache


Adds a variable in user cache and overwrites a variable if it already exists in the cache

wincache_ucache_meminfo
wincache_unlock
Func?ii WinCache
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

Descrierea

bool wincache_ucache_set ( mixed $key , mixed $value [, int $ttl = 0 ] )
bool wincache_ucache_set ( array $values [, mixed $unused = NULL [, 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.

Parametri

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.

Valorile întoarse

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.

Exemple

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

Exemplul de mai sus va afi?a:

bool(true)
string(3) "BAR"
bool(true)
string(3) "BAR1"

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

Exemplul de mai sus va afi?a:

array(0) {}
array(0) {}
string(1) "6"

A se vedea ?i

  • 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
Func?ii WinCache


Releases an exclusive lock on a given key

wincache_ucache_set
Building for Windows
Func?ii WinCache
PHP Manual

wincache_unlock

(PECL wincache >= 1.1.0)

wincache_unlock — Releases an exclusive lock on a given key

Descrierea

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.

Avertizare

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.

Parametri

key

Name of the key in the cache to release the lock on.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii WinCache


Building for Windows

Cuprins

  • 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

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii xhprof
    • xhprof_disable — Stops xhprof profiler
    • xhprof_enable — Start xhprof profiler
    • xhprof_sample_disable — Stops xhprof sample profiler
    • xhprof_sample_enable — Start XHProf profiling in sampling mode
Verifying the build
Introducere
Afectarea comportamentului PHP


Introducere

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
Instalarea / configurarea
Xhprof


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Xhprof


Necesita?i

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

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/xhprof

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Xhprof Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
xhprof.output_dir | "" | PHP_INI_ALL |

Iata o explica?ie pe scurt a directivelor de configurare.

xhprof.output_dir string

Directory used by the default implementation of the iXHProfRuns interface (namely, the XHProfRuns_Default class) for storing XHProf runs.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
Exemple
Xhprof


Exemple

Example #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";

?>

Exemplul de mai sus va afi?a ceva similar cu:

http://localhost/xhprof/xhprof_html/index.php?run=t11_4bdf44d21121f&source=xhprof_testing
Constante predefinite
Func?ii xhprof
Xhprof


Func?ii xhprof

Cuprins

  • xhprof_disable — Stops xhprof profiler
  • xhprof_enable — Start xhprof profiler
  • xhprof_sample_disable — Stops xhprof sample profiler
  • xhprof_sample_enable — Start XHProf profiling in sampling mode
Exemple
xhprof_disable
Xhprof


Stops xhprof profiler

Func?ii xhprof
xhprof_enable
Func?ii xhprof
PHP Manual

xhprof_disable

(PECL xhprof >= 0.9.0)

xhprof_disable — Stops xhprof profiler

Descrierea

array xhprof_disable ( void )

Stops the profiler, and returns xhprof data from the run.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array of xhprof data, from the run.

Exemple

Example #1 xhprof_disable() example

<?php
xhprof_enable();

$foo = strlen("foo bar");

$xhprof_data = xhprof_disable();

print_r($xhprof_data);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [main()==>strlen] => Array
        (
            [ct] => 1
            [wt] => 279
        )

    [main()==>xhprof_disable] => Array
        (
            [ct] => 1
            [wt] => 9
        )

    [main()] => Array
        (
            [ct] => 1
            [wt] => 610
        )

)
Func?ii xhprof
xhprof_enable
Func?ii xhprof


Start xhprof profiler

xhprof_disable
xhprof_sample_disable
Func?ii xhprof
PHP Manual

xhprof_enable

(PECL xhprof >= 0.9.0)

xhprof_enable — Start xhprof profiler

Descrierea

void xhprof_enable ([ int $flags = 0 [, array $options ]] )

Start xhprof profiling.

Parametri

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.

Valorile întoarse

NULL

Istoricul schimbarilor

Versiune | Descriere
0.9.2 | The optional options parameter was added.

Exemple

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

A se vedea ?i

  • xhprof_disable() - Stops xhprof profiler
  • xhprof_sample_enable() - Start XHProf profiling in sampling mode
  • memory_get_usage() - Returns the amount of memory allocated to PHP
  • getrusage() - Gets the current resource usages
xhprof_disable
xhprof_sample_disable
Func?ii xhprof


Stops xhprof sample profiler

xhprof_enable
xhprof_sample_enable
Func?ii xhprof
PHP Manual

xhprof_sample_disable

(PECL xhprof >= 0.9.0)

xhprof_sample_disable — Stops xhprof sample profiler

Descrierea

array xhprof_sample_disable ( void )

Stops the sample mode xhprof profiler, and

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array of xhprof sample data, from the run.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [1272935300.800000] => main()
    [1272935300.900000] => main()
)
xhprof_enable
xhprof_sample_enable
Func?ii xhprof


Start XHProf profiling in sampling mode

xhprof_sample_disable
Manipularea cu formate audio
Func?ii xhprof
PHP Manual

xhprof_sample_enable

(PECL xhprof >= 0.9.0)

xhprof_sample_enable — Start XHProf profiling in sampling mode

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

NULL

A se vedea ?i

  • 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
Manipularea cu formate audio
Func?ii xhprof


Manipularea cu formate audio

  • ID3 — ID3 Tags
    • Introducere
    • Instalarea / configurarea
    • Predefined Constants
    • Func?ii ID3
  • KTaglib
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • 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
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Context options
    • Exemple
  • OpenAL — Legaturile Audio OpenAL
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii OpenAL
xhprof_sample_enable
ID3
Informa?ii de referin?a despre func?ii


ID3 Tags

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Predefined Constants
  • Func?ii 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
Manipularea cu formate audio
Introducere
Manipularea cu formate audio


Introducere

These functions let you read and manipulate ID3 tags. ID3 tags are used in MP3 files to store title of the song, as well as information about the artist, album, genre, year and track number.

Since version 0.2 it is also possible to extract text frames from ID3 v2.2+ tags.

ID3
Instalarea / configurarea
ID3


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
ID3


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/id3.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
Predefined Constants
Instalarea / configurarea


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.

Tipurile resurselor
Func?ii ID3
ID3


Func?ii ID3

Cuprins

  • 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

Func?ii ID3
id3_get_frame_short_name
Func?ii 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

Descrierea

string id3_get_frame_long_name ( string $frameId )

id3_get_frame_long_name() returns the long name for an ID3v2 frame.

Parametri

frameId

An ID3v2 frame

Valorile întoarse

Returns the frame long name or FALSE on errors.

Exemple

Example #1 id3_get_frame_long_name() example

<?php
$longName = id3_get_frame_long_name("TOLY");
echo $longName;
?>

Exemplul de mai sus va afi?a:

Original lyricist(s)/text writer(s)

A se vedea ?i

  • id3_get_frame_short_name() - Get the short name of an ID3v2 frame

Func?ii ID3
id3_get_frame_short_name
Func?ii ID3


Get the short name of an ID3v2 frame

id3_get_frame_long_name
id3_get_genre_id
Func?ii 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

Descrierea

string id3_get_frame_short_name ( string $frameId )

id3_get_frame_short_name() returns the short name for an ID3v2 frame.

Parametri

frameId

An ID3v2 frame

Valorile întoarse

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

Exemple

Example #1 id3_get_frame_short_name() example

<?php
$shortName = id3_get_frame_short_name("TOLY");
echo $shortName;
?>

Exemplul de mai sus va afi?a:

originalLyricist

A se vedea ?i

  • id3_get_frame_long_name() - Get the long name of an ID3v2 frame

id3_get_frame_long_name
id3_get_genre_id
Func?ii ID3


Get the id for a genre

id3_get_frame_short_name
id3_get_genre_list
Func?ii ID3
PHP Manual

id3_get_genre_id

(PECL id3 >= 0.1)

id3_get_genre_id — Get the id for a genre

Descrierea

int id3_get_genre_id ( string $genre )

id3_get_genre_id() returns the id for a genre.

Parametri

genre

Genre name as string.

Valorile întoarse

The genre id or FALSE on errors.

Exemple

Example #1 id3_get_genre_id() example

<?php
$id = id3_get_genre_id("Alternative");
echo $id;
?>

Exemplul de mai sus va afi?a:

20

A se vedea ?i

  • 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
Func?ii ID3


Get all possible genre values

id3_get_genre_id
id3_get_genre_name
Func?ii ID3
PHP Manual

id3_get_genre_list

(PECL id3 >= 0.1)

id3_get_genre_list — Get all possible genre values

Descrierea

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.

Valorile întoarse

Returns an array containing all possible genres that may be stored in an ID3 tag.

Exemple

Example #1 id3_get_genre_list() example

<?php
$genres = id3_get_genre_list();
print_r($genres);
?>

Exemplul de mai sus va afi?a:

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
)

A se vedea ?i

  • 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
Func?ii ID3


Get the name for a genre id

id3_get_genre_list
id3_get_tag
Func?ii ID3
PHP Manual

id3_get_genre_name

(PECL id3 >= 0.1)

id3_get_genre_name — Get the name for a genre id

Descrierea

string id3_get_genre_name ( int $genre_id )

id3_get_genre_name() returns the name for a genre id.

Parametri

genre_id

An integer ranging from 0 to 147

Valorile întoarse

Returns the name as a string.

Exemple

Example #1 id3_get_genre_name() example

<?php
$genre = id3_get_genre_name(20);
echo $genre;
?>

Exemplul de mai sus va afi?a:

Alternative

A se vedea ?i

  • 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
Func?ii ID3


Get all information stored in an ID3 tag

id3_get_genre_name
id3_get_version
Func?ii ID3
PHP Manual

id3_get_tag

(PECL id3 >= 0.1)

id3_get_tag — Get all information stored in an ID3 tag

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #1 id3_get_tag() example

<?php
$tag = id3_get_tag( "path/to/example.mp3" );
print_r($tag);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [title] => DN-38416
    [artist] => Re:\Legion
    [album] => Reflections
    [year] => 2004
    [genre] => 19
)

Example #2 id3_get_tag() example

<?php
$tag = id3_get_tag( "path/to/example2.mp3", ID3_V2_3 );
print_r($tag);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • 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
Func?ii ID3


Get version of an ID3 tag

id3_get_tag
id3_remove_tag
Func?ii ID3
PHP Manual

id3_get_version

(PECL id3 >= 0.1)

id3_get_version — Get version of an ID3 tag

Descrierea

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.

Parametri

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

Valorile întoarse

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.

Exemple

Example #1 id3_get_version() example

<?php
$version = id3_get_version( "path/to/example.mp3" );
if ($version & ID3_V1_0) {
    echo "Contains a 1.x tag\n";
}
if ($version & ID3_V1_1) {
    echo "Contains a 1.1 tag\n";
}
if ($version & ID3_V2) {
    echo "Contains a 2.x tag\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Contains a 1.x tag
Contains a 1.1 tag

A se vedea ?i

  • 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
Func?ii ID3


Remove an existing ID3 tag

id3_get_version
id3_set_tag
Func?ii ID3
PHP Manual

id3_remove_tag

(PECL id3 >= 0.1)

id3_remove_tag — Remove an existing ID3 tag

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 id3_remove_tag() example

<?php
$result = id3_remove_tag( "path/to/example.mp3", ID3_V1_0 );
if ($result === true) {
    echo "Tag successfully removed\n";
}
?>

If the file is writable and contained a 1.0 tag, this will output:

Tag successfully removed

Note

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

A se vedea ?i

  • 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
Func?ii ID3


Update information stored in an ID3 tag

id3_remove_tag
KTaglib
Func?ii ID3
PHP Manual

id3_set_tag

(PECL id3 >= 0.1)

id3_set_tag — Update information stored in an ID3 tag

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 id3_set_tag() example

<?php
$data = array(
              "title" => "Re:Start",
              "artist" => "Re:\Legion",
              "comment" => "A nice track"
             );
$result = id3_set_tag( "path/to/example.mp3", $data, ID3_V1_0 );
if ($result === true) {
    echo "Tag successfully updated\n";
}
?>

If the file is writable, this will output:

Tag successfully updated

Note

Nota: Currently id3_set_tag() only supports version 1.0 and 1.1.

A se vedea ?i

  • 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
Func?ii ID3


KTaglib

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
  • Constante predefinite
  • 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 copyright status of an MPEG file
    • KTaglib_MPEG_AudioProperties::isOriginal — Returns if the file is marked as the original file
    • KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns if protection mechanisms of an MPEG file are enabled
  • 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
Introducere
Manipularea cu formate audio


Introducere

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.

Nota:

At the moment ktaglib is able to read and write ID3v1 and ID3v2 tags.

KTaglib
Instalarea / configurarea
KTaglib


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
Introducere
Necesita?i
KTaglib


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/ktaglib.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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
Instalarea
KTaglib_MPEG_File
KTaglib


The KTaglib_MPEG_File class

(0.0.1)

Introducere

Represents an MPEG file. MPEG files can have ID3v1, ID3v2 tags and audio properties.

Class synopsis

KTaglib_MPEG_File {
/* Metode */
public KTaglib_MPEG_File getAudioProperties ( void )
public KTaglib_ID3v1_Tag getID3v1Tag ([ bool $create = false ] )
public KTaglib_ID3v2_Tag getID3v2Tag ([ bool $create = false ] )
}

Cuprins

  • 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
Constante predefinite
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

Descrierea

public KTaglib_MPEG_File::__construct ( string $filename )

Opens a new MPEG file.

Parametri

filename

The file to read

Exemple

Example #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

Descrierea

public KTaglib_MPEG_File KTaglib_MPEG_File::getAudioProperties ( void )

Returns an object that provides access to the audio properties of the mpeg file.

Valorile întoarse

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

Descrierea

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.

Valorile întoarse

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

Descrierea

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.

Valorile întoarse

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

(0.0.1)

Introducere

Represents the audio properties of a MPEG file, like length, bitrate or samplerate.

Class synopsis

KTaglib_MPEG_AudioProperties {
/* Metode */
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 )
}

Cuprins

  • 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 copyright status of an MPEG file
  • KTaglib_MPEG_AudioProperties::isOriginal — Returns if the file is marked as the original file
  • KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns if protection mechanisms of an MPEG file are enabled
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

Descrierea

public int KTaglib_MPEG_AudioProperties::getBitrate ( void )

Returns the bitrate of the MPEG file

Valorile întoarse

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

Descrierea

public int KTaglib_MPEG_AudioProperties::getChannels ( void )

Returns the amount of channels of the MPEG file

Valorile întoarse

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

Descrierea

public int KTaglib_MPEG_AudioProperties::getLayer ( void )

Returns the layer of the MPEG file (usually 3 for MP3).

Valorile întoarse

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

Descrierea

public int KTaglib_MPEG_AudioProperties::getLength ( void )

Returns the length of the MPEG file

Valorile întoarse

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

Descrierea

public int KTaglib_MPEG_AudioProperties::getSampleBitrate ( void )

Returns the sample bitrate of the MPEG file

Valorile întoarse

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

Descrierea

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

Valorile întoarse

Returns the version

KTaglib_MPEG_AudioProperties::getSampleBitrate
KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties


Returns the copyright status of an 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 copyright status of an MPEG file

Descrierea

public bool KTaglib_MPEG_AudioProperties::isCopyrighted ( void )

Returns true if the MPEG file is copyrighted

Valorile întoarse

Returns true if the MPEG file is copyrighted

KTaglib_MPEG_AudioProperties::getVersion
KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_MPEG_AudioProperties


Returns if the file is marked as the original 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 if the file is marked as the original file

Descrierea

public bool KTaglib_MPEG_AudioProperties::isOriginal ( void )

Returns true if the file is marked as the original file

Valorile întoarse

Returns true if the file is marked as the original file

KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties::isProtectionEnabled
KTaglib_MPEG_AudioProperties


Returns if protection mechanisms of an MPEG file are enabled

KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_Tag
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::isProtectionEnabled

(0.0.1)

KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns if protection mechanisms of an MPEG file are enabled

Descrierea

public bool KTaglib_MPEG_AudioProperties::isProtectionEnabled ( void )

Returns true if protection mechanisms (like DRM) are enabled for this file

Valorile întoarse

Returns true if protection mechanisms (like DRM) are enabled for this file

KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_Tag
KTaglib_MPEG_AudioProperties


The KTaglib_Tag class

(0.0.1)

Introducere

Base class for ID3v1 or ID3v2 tags

Class synopsis

KTaglib_Tag {
/* Metode */
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 )
}

Cuprins

  • 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

Descrierea

public string KTaglib_Tag::getAlbum ( void )

Returns the album string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Valorile întoarse

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

Descrierea

public string KTaglib_Tag::getArtist ( void )

Returns the artist string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Valorile întoarse

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

Descrierea

public string KTaglib_Tag::getComment ( void )

Returns the comment of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Valorile întoarse

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

Descrierea

public string KTaglib_Tag::getGenre ( void )

Returns the genre of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Valorile întoarse

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

Descrierea

public string KTaglib_Tag::getTitle ( void )

Returns the title string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Valorile întoarse

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

Descrierea

public int KTaglib_Tag::getTrack ( void )

Returns the track number of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Valorile întoarse

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

Descrierea

public int KTaglib_Tag::getYear ( void )

Returns the year of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Valorile întoarse

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

Descrierea

public bool KTaglib_Tag::isEmpty ( void )

Returns true if the tag exists, but is empty. This method is implemented in ID3v1 and ID3v2 tags.

Valorile întoarse

Returns true if the tag is empty, otherwise false.

KTaglib_Tag::getYear
KTaglib_ID3v2_Tag
KTaglib_Tag


The KTaglib_ID3v2_Tag class

(0.0.1)

Introducere

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 {
/* Metode */
public bool addFrame ( KTaglib_ID3v2_Frame $frame )
public array getFrameList ( void )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

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.

Valorile întoarse

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

Descrierea

public array KTaglib_ID3v2_Tag::getFrameList ( void )

Returns an array of ID3v2 frames, associated with the ID3v2 tag.

Valorile întoarse

Return an array of KTaglib_ID3v2_Frame objects

KTaglib_ID3v2_Tag::addFrame
KTaglib_ID3v2_Frame
KTaglib_ID3v2_Tag


The KTaglib_ID3v2_Frame class

(0.0.1)

Introducere

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 {
/* Metode */
public int getSize ( void )
public string __toString ( void )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

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.

Valorile întoarse

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

Descrierea

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

Valorile întoarse

Returns a string representation of the frame.

KTaglib_ID3v2_Frame::getSize
KTaglib_ID3v2_AttachedPictureFrame
KTaglib_ID3v2_Frame


The KTaglib_ID3v2_AttachedPictureFrame class

(0.0.1)

Introducere

Represents an ID3v2 frame that can hold a picture.

Class synopsis

extends KTaglib_ID3v2_Frame {
/* Metode */
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 )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

public string KTaglib_ID3v2_AttachedPictureFrame::getDescription ( void )

Returns the attached description for a picture frame in an ID3v2.x frame.

Valorile întoarse

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

Descrierea

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.

Valorile întoarse

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

Descrierea

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.

Valorile întoarse

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

Descrierea

public bool KTaglib_ID3v2_AttachedPictureFrame::savePicture ( string $filename )

Saves the attached picture to the given filename.

Valorile întoarse

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

Descrierea

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

Descrierea

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.

Valorile întoarse

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

Descrierea

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

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Context options
  • Exemple
    • Examples on using the ogg:// wrapper.
KTaglib_ID3v2_AttachedPictureFrame::setType
Introducere
Manipularea cu formate audio


Introducere

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 in the predefined constants section.

oggvorbis
Instalarea / configurarea
oggvorbis


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
oggvorbis


Necesita?i

This extension requires PHP >= 4.3.0, » libogg >= 1.0, and » libvorbis >= 1.0.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/oggvorbis

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
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')
Constante predefinite
Exemple
oggvorbis


Exemple

Cuprins

  • Examples on using the ogg:// wrapper.
Context options
Examples on using the ogg:// wrapper.
oggvorbis


Examples on using the ogg:// wrapper.

Example #1 Reading an OGG/Vorbis file

<?php
dl("oggvorbis.so");

/* By default, ogg:// will decode to Signed 16-bit Little Endian */
$fp = fopen('ogg://myaudio.ogg', 'r');

/* Collect some information about the file. */
$metadata = stream_get_meta_data($fp);

/* Inspect the first song (usually the only song,
   but OGG/Vorbis files may be chained) */
$songdata = $metadata['wrapper_data'][0];

echo "OGG/Vorbis file encoded by: {$songdata['vendor']}\n.";
echo "  {$songdata['channels']} channels of {$songdata['rate']}Hz sampling encoded at {$songdata['bitrate_nominal']}bps.\n";
foreach($songdata['comments'] as $comment) {
    echo "  $comment\n";
}

while ($audio_data = fread($fp, 8192)) {
  /* Do something with the PCM audio we're extracting from the OGG.
     Copying to /dev/dsp is a good target on linux systems,
     just remember to setup the device for your sampling mode first. */
}

fclose($fp);

?>

Example #2 Encode an audio file to OGG/Vorbis

<?php
dl('oggvorbis.so');

$context = stream_context_create(array('ogg'=>array(
             'pcm_mode' => OGGVORBIS_PCM_S8,  /* Signed 8bit audio */
             'rate' => 44100,                 /* 44kHz CD quality */
             'bitrate' => 0.5,                /* Midquality VBR */
             'channels' => 1,                 /* Mono */
             'serialno' => 12345)));          /* Unique within our stream */

/* Open file for appending.  This will "chain" a second OGG stream at the end of the first. */
$ogg = fopen('ogg://mysong.ogg', 'a', false, $context);

$pcm = fopen('mysample.pcm', 'r');

/* Compress the raw PCM audio from mysample.pcm into mysong.ogg */
stream_copy_to_stream($pcm, $ogg);

fclose($pcm);
fclose($ogg);
?>

Exemple
OpenAL
Exemple


Legaturile Audio OpenAL

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii OpenAL
    • 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.
Introducere
Manipularea cu formate audio


Introducere

Legaturi audio independente de platforma. Necesita » biblioteca OpenAL.

OpenAL
Instalarea / configurarea
OpenAL


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
OpenAL


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/openal.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

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

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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
Tipurile resurselor
Func?ii OpenAL
OpenAL


Func?ii OpenAL

Cuprins

  • 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
Constante predefinite
openal_buffer_create
OpenAL


Generate OpenAL buffer

Func?ii OpenAL
openal_buffer_data
Func?ii OpenAL
PHP Manual

openal_buffer_create

(PECL openal >= 0.1.0)

openal_buffer_create — Generate OpenAL buffer

Descrierea

resource openal_buffer_create ( void )

Valorile întoarse

Returns an Open AL(Buffer) resource on success or FALSE on failure.

A se vedea ?i

  • openal_buffer_loadwav() - Load a .wav file into a buffer
  • openal_buffer_data() - Load a buffer with data

Func?ii OpenAL
openal_buffer_data
Func?ii OpenAL


Load a buffer with data

openal_buffer_create
openal_buffer_destroy
Func?ii OpenAL
PHP Manual

openal_buffer_data

(PECL openal >= 0.1.0)

openal_buffer_data — Load a buffer with data

Descrierea

bool openal_buffer_data ( resource $buffer , int $format , string $data , int $freq )

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • openal_buffer_loadwav() - Load a .wav file into a buffer
  • openal_stream() - Begin streaming on a source

openal_buffer_create
openal_buffer_destroy
Func?ii OpenAL


Destroys an OpenAL buffer

openal_buffer_data
openal_buffer_get
Func?ii OpenAL
PHP Manual

openal_buffer_destroy

(PECL openal >= 0.1.0)

openal_buffer_destroy — Destroys an OpenAL buffer

Descrierea

bool openal_buffer_destroy ( resource $buffer )

Parametri

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • openal_buffer_create() - Generate OpenAL buffer

openal_buffer_data
openal_buffer_get
Func?ii OpenAL


Retrieve an OpenAL buffer property

openal_buffer_destroy
openal_buffer_loadwav
Func?ii OpenAL
PHP Manual

openal_buffer_get

(PECL openal >= 0.1.0)

openal_buffer_get — Retrieve an OpenAL buffer property

Descrierea

int openal_buffer_get ( resource $buffer , int $property )

Parametri

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.

Valorile întoarse

Returns an integer value appropriate to the property requested sau FALSE în cazul e?ecului.

A se vedea ?i

  • openal_buffer_create() - Generate OpenAL buffer

openal_buffer_destroy
openal_buffer_loadwav
Func?ii OpenAL


Load a .wav file into a buffer

openal_buffer_get
openal_context_create
Func?ii OpenAL
PHP Manual

openal_buffer_loadwav

(PECL openal >= 0.1.0)

openal_buffer_loadwav — Load a .wav file into a buffer

Descrierea

bool openal_buffer_loadwav ( resource $buffer , string $wavfile )

Parametri

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

wavfile

Path to .wav file on local file system.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • openal_buffer_data() - Load a buffer with data
  • openal_stream() - Begin streaming on a source

openal_buffer_get
openal_context_create
Func?ii OpenAL


Create an audio processing context

openal_buffer_loadwav
openal_context_current
Func?ii OpenAL
PHP Manual

openal_context_create

(PECL openal >= 0.1.0)

openal_context_create — Create an audio processing context

Descrierea

resource openal_context_create ( resource $device )

Parametri

device

An Open AL(Device) resource (previously created by openal_device_open()).

Valorile întoarse

Returns an Open AL(Context) resource on success or FALSE on failure.

A se vedea ?i

  • openal_device_open() - Initialize the OpenAL audio layer
  • openal_context_destroy() - Destroys a context

openal_buffer_loadwav
openal_context_current
Func?ii OpenAL


Make the specified context current

openal_context_create
openal_context_destroy
Func?ii OpenAL
PHP Manual

openal_context_current

(PECL openal >= 0.1.0)

openal_context_current — Make the specified context current

Descrierea

bool openal_context_current ( resource $context )

Parametri

context

An Open AL(Context) resource (previously created by openal_context_create()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • openal_context_create() - Create an audio processing context

openal_context_create
openal_context_destroy
Func?ii OpenAL


Destroys a context

openal_context_current
openal_context_process
Func?ii OpenAL
PHP Manual

openal_context_destroy

(PECL openal >= 0.1.0)

openal_context_destroy — Destroys a context

Descrierea

bool openal_context_destroy ( resource $context )

Parametri

context

An Open AL(Context) resource (previously created by openal_context_create()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • openal_context_create() - Create an audio processing context

openal_context_current
openal_context_process
Func?ii OpenAL


Process the specified context

openal_context_destroy
openal_context_suspend
Func?ii OpenAL
PHP Manual

openal_context_process

(PECL openal >= 0.1.0)

openal_context_process — Process the specified context

Descrierea

bool openal_context_process ( resource $context )

Parametri

context

An Open AL(Context) resource (previously created by openal_context_create()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii OpenAL


Suspend the specified context

openal_context_process
openal_device_close
Func?ii OpenAL
PHP Manual

openal_context_suspend

(PECL openal >= 0.1.0)

openal_context_suspend — Suspend the specified context

Descrierea

bool openal_context_suspend ( resource $context )

Parametri

context

An Open AL(Context) resource (previously created by openal_context_create()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii OpenAL


Close an OpenAL device

openal_context_suspend
openal_device_open
Func?ii OpenAL
PHP Manual

openal_device_close

(PECL openal >= 0.1.0)

openal_device_close — Close an OpenAL device

Descrierea

bool openal_device_close ( resource $device )

Parametri

device

An Open AL(Device) resource (previously created by openal_device_open()) to be closed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • openal_device_open() - Initialize the OpenAL audio layer

openal_context_suspend
openal_device_open
Func?ii OpenAL


Initialize the OpenAL audio layer

openal_device_close
openal_listener_get
Func?ii OpenAL
PHP Manual

openal_device_open

(PECL openal >= 0.1.0)

openal_device_open — Initialize the OpenAL audio layer

Descrierea

resource openal_device_open ([ string $device_desc ] )

Parametri

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.

Valorile întoarse

Returns an Open AL(Device) resource on success or FALSE on failure.

A se vedea ?i

  • openal_device_close() - Close an OpenAL device
  • openal_context_create() - Create an audio processing context

openal_device_close
openal_listener_get
Func?ii OpenAL


Retrieve a listener property

openal_device_open
openal_listener_set
Func?ii OpenAL
PHP Manual

openal_listener_get

(PECL openal >= 0.1.0)

openal_listener_get — Retrieve a listener property

Descrierea

mixed openal_listener_get ( int $property )

Parametri

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

Valorile întoarse

Returns a float or array of floats (as appropriate) sau FALSE în cazul e?ecului.

A se vedea ?i

  • openal_listener_set() - Set a listener property

openal_device_open
openal_listener_set
Func?ii OpenAL


Set a listener property

openal_listener_get
openal_source_create
Func?ii OpenAL
PHP Manual

openal_listener_set

(PECL openal >= 0.1.0)

openal_listener_set — Set a listener property

Descrierea

bool openal_listener_set ( int $property , mixed $setting )

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • openal_listener_get() - Retrieve a listener property

openal_listener_get
openal_source_create
Func?ii OpenAL


Generate a source resource

openal_listener_set
openal_source_destroy
Func?ii OpenAL
PHP Manual

openal_source_create

(PECL openal >= 0.1.0)

openal_source_create — Generate a source resource

Descrierea

resource openal_source_create ( void )

Valorile întoarse

Returns an Open AL(Source) resource on success or FALSE on failure.

A se vedea ?i

  • 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
Func?ii OpenAL


Destroy a source resource

openal_source_create
openal_source_get
Func?ii OpenAL
PHP Manual

openal_source_destroy

(PECL openal >= 0.1.0)

openal_source_destroy — Destroy a source resource

Descrierea

bool openal_source_destroy ( resource $source )

Parametri

source

An Open AL(Source) resource (previously created by openal_source_create()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • openal_source_create() - Generate a source resource

openal_source_create
openal_source_get
Func?ii OpenAL


Retrieve an OpenAL source property

openal_source_destroy
openal_source_pause
Func?ii OpenAL
PHP Manual

openal_source_get

(PECL openal >= 0.1.0)

openal_source_get — Retrieve an OpenAL source property

Descrierea

mixed openal_source_get ( resource $source , int $property )

Parametri

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

Valorile întoarse

Returns the type associated with the property being retrieved sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii OpenAL


Pause the source

openal_source_get
openal_source_play
Func?ii OpenAL
PHP Manual

openal_source_pause

(PECL openal >= 0.1.0)

openal_source_pause — Pause the source

Descrierea

bool openal_source_pause ( resource $source )

Parametri

source

An Open AL(Source) resource (previously created by openal_source_create()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii OpenAL


Start playing the source

openal_source_pause
openal_source_rewind
Func?ii OpenAL
PHP Manual

openal_source_play

(PECL openal >= 0.1.0)

openal_source_play — Start playing the source

Descrierea

bool openal_source_play ( resource $source )

Parametri

source

An Open AL(Source) resource (previously created by openal_source_create()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii OpenAL


Rewind the source

openal_source_play
openal_source_set
Func?ii OpenAL
PHP Manual

openal_source_rewind

(PECL openal >= 0.1.0)

openal_source_rewind — Rewind the source

Descrierea

bool openal_source_rewind ( resource $source )

Parametri

source

An Open AL(Source) resource (previously created by openal_source_create()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii OpenAL


Set source property

openal_source_rewind
openal_source_stop
Func?ii OpenAL
PHP Manual

openal_source_set

(PECL openal >= 0.1.0)

openal_source_set — Set source property

Descrierea

bool openal_source_set ( resource $source , int $property , mixed $setting )

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii OpenAL


Stop playing the source

openal_source_set
openal_stream
Func?ii OpenAL
PHP Manual

openal_source_stop

(PECL openal >= 0.1.0)

openal_source_stop — Stop playing the source

Descrierea

bool openal_source_stop ( resource $source )

Parametri

source

An Open AL(Source) resource (previously created by openal_source_create()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • openal_source_play() - Start playing the source
  • openal_source_pause() - Pause the source
  • openal_source_rewind() - Rewind the source

openal_source_set
openal_stream
Func?ii OpenAL


Begin streaming on a source

openal_source_stop
Servicii de autentificare
Func?ii OpenAL
PHP Manual

openal_stream

(PECL openal >= 0.1.0)

openal_stream — Begin streaming on a source

Descrierea

resource openal_stream ( resource $source , int $format , int $rate )

Parametri

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.

Valorile întoarse

Returns a stream resource on success sau FALSE în cazul e?ecului.

A se vedea ?i

  • openal_source_create() - Generate a source resource
  • fwrite() - Binary-safe file write

openal_source_stop
Servicii de autentificare
Func?ii OpenAL


Servicii de autentificare

  • KADM5 — Kerberos V
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • KADM5 Func?ii
  • Radius
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Radius
openal_stream
KADM5
Informa?ii de referin?a despre func?ii


Kerberos V

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
    • Constants for Attribute Flags
    • Constants for Options
  • Exemple
    • Basic usage
  • KADM5 Func?ii
    • 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
Servicii de autentificare
Introducere
Servicii de autentificare


Introducere

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
Instalarea / configurarea
KADM5


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
KADM5


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/kadm5.

Nota:

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.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

This extension defines a KADM5 handle returned by kadm5_init_with_password().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Cuprins

  • Constants for Attribute Flags
  • Constants for Options

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Tipurile resurselor
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

Constante predefinite
Constants for Options
Constante predefinite


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
Exemple
Constante predefinite


Exemple

Cuprins

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

Example #1 KADM5 extension overview example

<?php

  $handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

  print "<h1>get_principals</h1>\n";
  $principals = kadm5_get_principals($handle);
  for( $i=0; $i<count($principals); $i++)
      print "$principals[$i]<br>\n";

  print "<h1>get_policies</h1>\n";
  $policies = kadm5_get_policies($handle);
  for( $i=0; $i<count($policies); $i++)
      print "$policies[$i]<br>\n";

  print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";

  $options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );
  $keys = array_keys($options);
  for( $i=0; $i<count($keys); $i++) {
    $value = $options[$keys[$i]];
    print "$keys[$i]: $value<br>\n";
  }

  $options = array(KADM5_PRINC_EXPIRE_TIME => 0);
  kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);

  kadm5_destroy($handle);
?>

Exemple
KADM5 Func?ii
Exemple


KADM5 Func?ii

Cuprins

  • 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 Func?ii
kadm5_create_principal
KADM5 Func?ii
PHP Manual

kadm5_chpass_principal

(PECL kadm5 >= 0.2.3)

kadm5_chpass_principal — Changes the principal's password

Descrierea

bool kadm5_chpass_principal ( resource $handle , string $principal , string $password )

kadm5_chpass_principal() sets the new password password for the principal.

Parametri

handle

A KADM5 handle.

principal

The principal.

password

The new password.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Example of changing principal's password

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

kadm5_chpass_principal($handle, "burbach@GONICUS.LOCAL", "newpassword");

kadm5_destroy($handle);
?>

KADM5 Func?ii
kadm5_create_principal
KADM5 Func?ii


Creates a kerberos principal with the given parameters

kadm5_chpass_principal
kadm5_delete_principal
KADM5 Func?ii
PHP Manual

kadm5_create_principal

(PECL kadm5 >= 0.2.3)

kadm5_create_principal — Creates a kerberos principal with the given parameters

Descrierea

bool kadm5_create_principal ( resource $handle , string $principal [, string $password [, array $options ]] )

Creates a principal with the given password.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Example of principal's creation

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
                 KADM5_POLICY => "default",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);

kadm5_destroy($handle);
?>

A se vedea ?i

  • 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 Func?ii


Deletes a kerberos principal

kadm5_create_principal
kadm5_destroy
KADM5 Func?ii
PHP Manual

kadm5_delete_principal

(PECL kadm5 >= 0.2.3)

kadm5_delete_principal — Deletes a kerberos principal

Descrierea

bool kadm5_delete_principal ( resource $handle , string $principal )

Removes the principal from the Kerberos database.

Parametri

handle

A KADM5 handle.

principal

The removed principal.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 kadm5_delete_principal() example

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

kadm5_delete_principal($handle, "burbach@GONICUS.LOCAL");

kadm5_destroy($handle);
?>

A se vedea ?i

  • 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 Func?ii


Closes the connection to the admin server and releases all related resources

kadm5_delete_principal
kadm5_flush
KADM5 Func?ii
PHP Manual

kadm5_destroy

(PECL kadm5 >= 0.2.3)

kadm5_destroy — Closes the connection to the admin server and releases all related resources

Descrierea

bool kadm5_destroy ( resource $handle )

Closes the connection to the admin server and releases all related resources.

Parametri

handle

A KADM5 handle.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • kadm5_init_with_password() - Opens a connection to the KADM5 library

kadm5_delete_principal
kadm5_flush
KADM5 Func?ii


Flush all changes to the Kerberos database

kadm5_destroy
kadm5_get_policies
KADM5 Func?ii
PHP Manual

kadm5_flush

(PECL kadm5 >= 0.2.3)

kadm5_flush — Flush all changes to the Kerberos database

Descrierea

bool kadm5_flush ( resource $handle )

Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server open.

Parametri

handle

A KADM5 handle.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

kadm5_destroy
kadm5_get_policies
KADM5 Func?ii


Gets all policies from the Kerberos database

kadm5_flush
kadm5_get_principal
KADM5 Func?ii
PHP Manual

kadm5_get_policies

(PECL kadm5 >= 0.2.3)

kadm5_get_policies — Gets all policies from the Kerberos database

Descrierea

array kadm5_get_policies ( resource $handle )

Gets an array containing the policies's names.

Parametri

handle

A KADM5 handle.

Valorile întoarse

Returns array of policies on success sau FALSE în cazul e?ecului.

Exemple

Example #1 kadm5_get_policies() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_policies</h1>\n";
foreach (kadm5_get_policies($handle) as $policy) {
    echo "$policy<br />\n";
}

kadm5_destroy($handle);
?>

kadm5_flush
kadm5_get_principal
KADM5 Func?ii


Gets the principal's entries from the Kerberos database

kadm5_get_policies
kadm5_get_principals
KADM5 Func?ii
PHP Manual

kadm5_get_principal

(PECL kadm5 >= 0.2.3)

kadm5_get_principal — Gets the principal's entries from the Kerberos database

Descrierea

array kadm5_get_principal ( resource $handle , string $principal )

Gets the principal's entries from the Kerberos database.

Parametri

handle

A KADM5 handle.

principal

The principal.

Valorile întoarse

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 sau FALSE în cazul e?ecului.

Exemple

Example #1 kadm5_get_principal() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";

$options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );

foreach ($options as $key => $value) {
    echo "$key: $value<br />\n";
}

kadm5_destroy($handle);
?>

A se vedea ?i

  • kadm5_get_principals() - Gets all principals from the Kerberos database

kadm5_get_policies
kadm5_get_principals
KADM5 Func?ii


Gets all principals from the Kerberos database

kadm5_get_principal
kadm5_init_with_password
KADM5 Func?ii
PHP Manual

kadm5_get_principals

(PECL kadm5 >= 0.2.3)

kadm5_get_principals — Gets all principals from the Kerberos database

Descrierea

array kadm5_get_principals ( resource $handle )

kadm5_get_principals() returns an array containing the principals's names.

Parametri

handle

A KADM5 handle.

Valorile întoarse

Returns array of principals on success sau FALSE în cazul e?ecului.

Exemple

Example #1 kadm5_get_principals() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_principals</h1>\n";
foreach (kadm5_get_principals($handle) as $principal) {
    echo "$principal<br />\n";
}

kadm5_destroy($handle);
?>

A se vedea ?i

  • kadm5_get_principal() - Gets the principal's entries from the Kerberos database

kadm5_get_principal
kadm5_init_with_password
KADM5 Func?ii


Opens a connection to the KADM5 library

kadm5_get_principals
kadm5_modify_principal
KADM5 Func?ii
PHP Manual

kadm5_init_with_password

(PECL kadm5 >= 0.2.3)

kadm5_init_with_password — Opens a connection to the KADM5 library

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a KADM5 handle on success sau FALSE în cazul e?ecului.

Exemple

Example #1 KADM5 initialization example

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
                 KADM5_POLICY => "default",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);

kadm5_destroy($handle);
?>

Note

Nota:

Connection should be closed after use with kadm5_destroy().

A se vedea ?i

  • kadm5_destroy() - Closes the connection to the admin server and releases all related resources

kadm5_get_principals
kadm5_modify_principal
KADM5 Func?ii


Modifies a kerberos principal with the given parameters

kadm5_init_with_password
Radius
KADM5 Func?ii
PHP Manual

kadm5_modify_principal

(PECL kadm5 >= 0.2.3)

kadm5_modify_principal — Modifies a kerberos principal with the given parameters

Descrierea

bool kadm5_modify_principal ( resource $handle , string $principal , array $options )

Modifies a principal according to the given options.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Example of modifying principal

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH;
$options = array(KADM5_PRINC_EXPIRE_TIME => 3451234,
                 KADM5_POLICY => "gonicus",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);

kadm5_destroy($handle);
?>

A se vedea ?i

  • kadm5_create_principal() - Creates a kerberos principal with the given parameters
  • kadm5_delete_principal() - Deletes a kerberos principal

kadm5_init_with_password
Radius
KADM5 Func?ii


Radius

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
    • RADIUS Options
    • RADIUS Packet Types
    • RADIUS Attribute Types
    • RADIUS Vendor Specific Attribute Types
  • Exemple
  • Func?ii Radius
    • 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_tagged_attr_data — Extracts the data from a tagged attribute
    • radius_get_tagged_attr_tag — Extracts the tag from a tagged 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_salt_encrypt_attr — Salt-encrypts a value
    • 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
Introducere
Servicii de autentificare


Introducere

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.

Nota:

An exact description for libradius can be found » here. A detailed description of the configuration file can be found » here.

Radius
Instalarea / configurarea
Radius


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Radius


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/radius.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Cuprins

  • RADIUS Options
  • RADIUS Packet Types
  • RADIUS Attribute Types
  • RADIUS Vendor Specific Attribute Types

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

RADIUS_MPPE_KEY_LEN (integer)
The maximum length of MPPE keys.
Tipurile resurselor
RADIUS Options
Radius


RADIUS Options

Several RADIUS functions accept option flags as bitmasks. The constants representing those flags are listed below.

RADIUS_OPTION_SALT (integer)

When set, this option will result in the attribute value being salt-encrypted.

RADIUS_OPTION_TAGGED (integer)

When set, this option will result in the attribute value being tagged with the value of the tag parameter.

Constante predefinite
RADIUS Packet Types
Constante predefinite


RADIUS Packet Types

RADIUS packets, whether requests or responses, always include a type. These constants are provided to make it easier to specify types when using radius_create_request() and when comparing the result of radius_send_request().

RADIUS_ACCESS_REQUEST (integer)

An Access-Request, used to authenticate a user against a RADIUS server. Access request packets must include a RADIUS_NAS_IP_ADDRESS or a RADIUS_NAS_IDENTIFIER attribute, must also include a RADIUS_USER_PASSWORD, RADIUS_CHAP_PASSWORD or a RADIUS_STATE attribute, and should include a RADIUS_USER_NAME attribute.

RADIUS_ACCESS_ACCEPT (integer)

An Access-Accept response to an Access-Request indicating that the RADIUS server authenticated the user successfully.

RADIUS_ACCESS_REJECT (integer)

An Access-Reject response to an Access-Request indicating that the RADIUS server could not authenticate the user.

RADIUS_ACCESS_CHALLENGE (integer)

An Access-Challenge response to an Access-Request indicating that the RADIUS server requires further information in another Access-Request before authenticating the user.

RADIUS_ACCOUNTING_REQUEST (integer)

An Accounting-Request, used to convey accounting information for a service to the RADIUS server.

RADIUS_ACCOUNTING_RESPONSE (integer)

An Accounting-Response response to an Accounting-Request.

RADIUS_COA_REQUEST (integer)

A CoA-Request, sent from the RADIUS server to indicate that the authorisations within the user session have changed. A response must be sent in the form of a CoA-ACK or a CoA-NAK.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_COA_ACK (integer)

A CoA-ACK, sent to the RADIUS server to indicate that the user authorisations have been updated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_COA_NAK (integer)

A CoA-NAK, sent to the RADIUS server to indicate that the user authorisations could not be updated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_DISCONNECT_REQUEST (integer)

A Disconnect-Request, sent from the RADIUS server to indicate that the user session must be terminated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_DISCONNECT_ACK (integer)

A Disconnect-ACK, sent to the RADIUS server to indicate that the user session has been terminated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_DISCONNECT_NAK (integer)

A Disconnect-NAK, sent to the RADIUS server to indicate that the user session could not be terminated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS Options
RADIUS Attribute Types
Constante predefinite


RADIUS Attribute Types

These constants define RADIUS attribute types that can be used with
radius_put_addr(), radius_put_attr(),
radius_put_int() and
radius_put_string().

RADIUS_USER_NAME (integer)

The User-Name attribute. The attribute value is expected to be a string containing the name of the user being authenticated, and can be set using radius_put_attr().

RADIUS_USER_PASSWORD (integer)

The User-Password attribute. The attribute value is expected to be a string containing the user's password, and can be set using radius_put_attr(). This value will be obfuscated on transmission as described in » section 5.2 of RFC 2865.

RADIUS_CHAP_PASSWORD (integer)

The Chap-Password attribute. The attribute value is expected to be a string with the first byte containing the CHAP identifier, and the subsequent 16 bytes containing the MD5 hash of the CHAP identifier, the plaintext password and the CHAP challenge value concatenated together. Note that the CHAP challenge value should also be sent separately in a RADIUS_CHAP_CHALLENGE attribute.

Example #1 Using CHAP passwords

<?php
// Firstly, we'll create an authentication handle and request.
$radh = radius_auth_open();
radius_add_server($radh, $server, $port, $secret, 3, 3);
radius_create_request($radh, RADIUS_ACCESS_REQUEST);

// Assuming $password contains the plaintext password, we now:

// Generate a challenge.
$challenge = mt_rand();

// Specify a CHAP identifier.
$ident = 1;

// Add the Chap-Password attribute.
$cp = md5(pack('Ca*', $ident, $password.$challenge), true);
radius_put_attr($radh, RADIUS_CHAP_PASSWORD, pack('C', $ident).$cp);

// Add the Chap-Challenge attribute.
radius_put_attr($radh, RADIUS_CHAP_CHALLENGE, $challenge);

/* From here, you would add the remaining attributes and
 * call radius_send_request(). */
?>

RADIUS_NAS_IP_ADDRESS (integer)

The NAS-IP-Address attribute. The attribute value is expected to the IP address of the RADIUS client encoded as an integer, which can be set using radius_put_addr().

RADIUS_NAS_PORT (integer)

The NAS-Port attribute. The attribute value is expected to be the physical port of the user on the RADIUS client encoded as an integer, which can be set using radius_put_int().

RADIUS_SERVICE_TYPE (integer)

The Service-Type attribute. The attribute value indicates the service type the user is requesting, and is expected to be an integer, which can be set using radius_put_int().

A number of constants are provided to represent the possible values of this attribute. They include:

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

The Framed-Protocol attribute. The attribute value is expected to be an integer indicating the framing to be used for framed access, and can be set using radius_put_int(). The possible attribute values include these constants:

  • RADIUS_PPP
  • RADIUS_SLIP
  • RADIUS_ARAP
  • RADIUS_GANDALF
  • RADIUS_XYLOGICS

RADIUS_FRAMED_IP_ADDRESS (integer)

The Framed-IP-Address attribute. The attribute value is expected to be the address of the user's network encoded as an integer, which can be set using radius_put_addr() and retrieved using radius_cvt_addr().

RADIUS_FRAMED_IP_NETMASK (integer)

The Framed-IP-Netmask attribute. The attribute value is expected to be the netmask of the user's network encoded as an integer, which can be set using radius_put_addr() and retrieved using radius_cvt_addr().

RADIUS_FRAMED_ROUTING (integer)

The Framed-Routing attribute. The attribute value is expected to be an integer indicating the routing method for the user, which can be set using radius_put_int().

Possible values include:

  • 0: No routing
  • 1: Send routing packets
  • 2: Listen for routing packets
  • 3: Send and listen

RADIUS_FILTER_ID (integer)

The Filter-ID attribute. The attribute value is expected to be an implementation-specific, human-readable string of filters, which can be set using radius_put_attr().

RADIUS_FRAMED_MTU (integer)

The Framed-MTU attribute. The attribute value is expected to be an integer indicating the MTU to be configured for the user, and can be set using radius_put_int().

RADIUS_FRAMED_COMPRESSION (integer)

The Framed-Compression attribute. The attribute value is expected to be an integer indicating the compression protocol to be used, and can be set using radius_put_int(). Possible values include these constants:

  • RADIUS_COMP_NONE: No compression
  • RADIUS_COMP_VJ: VJ TCP/IP header compression
  • RADIUS_COMP_IPXHDR: IPX header compression
  • RADIUS_COMP_STAC_LZS: Stac-LZS compression (added in PECL radius 1.3.0b2)

RADIUS_LOGIN_IP_HOST (integer)

The Login-IP-Host attribute. The attribute value is expected to the IP address to connect the user to, encoded as an integer, which can be set using radius_put_addr().

RADIUS_LOGIN_SERVICE (integer)

The Login-Service attribute. The attribute value is an integer indicating the service to connect the user to on the login host. The value can be converted to a PHP integer via radius_cvt_int().

RADIUS_LOGIN_TCP_PORT (integer)

The Login-TCP-Port attribute. The attribute value is an integer indicating the port to connect the user to on the login host. The value can be converted to a PHP integer via radius_cvt_int().

RADIUS_REPLY_MESSAGE (integer)

The Reply-Message attribute. The attribute value is a string containing text that may be displayed to the user in response to an access request.

RADIUS_CALLBACK_NUMBER (integer)

The Callback-Number attribute. The attribute value is a string containing the dialing string to use for callback.

RADIUS_CALLBACK_ID (integer)

The Callback-Id attribute. The attribute value is a string containing an implementation-specific name of the place to be called.

RADIUS_FRAMED_ROUTE (integer)

The Framed-Route attribute. The attribute value is a string containing an implementation-specific set of routes to be configured for the user.

RADIUS_FRAMED_IPX_NETWORK (integer)

The Framed-IPX-Network attribute. The attribute value is an integer containing the IPX network to be configured for the user, or 0xFFFFFFFE to indicate that the RADIUS client should select the network, and can be accessed via radius_cvt_int().

RADIUS_STATE (integer)

The State attribute. The attribute value is an implementation-defined string included in an Access-Challenge from a server that must be included in the subsequent Access-Request, and can be set using radius_put_attr().

RADIUS_CLASS (integer)

The Class attribute. The attribute value is an arbitrary string included in an Access-Accept message that should then be sent to the accounting server in Accounting-Request messages, and can be set using radius_put_attr().

RADIUS_VENDOR_SPECIFIC (integer)

The Vendor-Specific attribute. In general, vendor attribute values
should be set using radius_put_vendor_addr(),
radius_put_vendor_attr(),
radius_put_vendor_int() and
radius_put_vendor_string(), rather than directly.

This constant is mostly useful when interpreting vendor specific attributes in responses from a RADIUS server; when a vendor specific attribute is received, the radius_get_vendor_attr() function should be used to access the vendor ID, attribute type and attribute value.

RADIUS_SESSION_TIMEOUT (integer)

Session timeout

RADIUS_IDLE_TIMEOUT (integer)

Idle timeout

RADIUS_TERMINATION_ACTION (integer)

Termination action

RADIUS_CALLED_STATION_ID (integer)

Called Station Id

RADIUS_CALLING_STATION_ID (integer)

Calling Station Id

RADIUS_NAS_IDENTIFIER (integer)

NAS ID

RADIUS_PROXY_STATE (integer)

Proxy State

RADIUS_LOGIN_LAT_SERVICE (integer)

Login LAT Service

RADIUS_LOGIN_LAT_NODE (integer)

Login LAT Node

RADIUS_LOGIN_LAT_GROUP (integer)

Login LAT Group

RADIUS_FRAMED_APPLETALK_LINK (integer)

Framed Appletalk Link

RADIUS_FRAMED_APPLETALK_NETWORK (integer)

Framed Appletalk Network

RADIUS_FRAMED_APPLETALK_ZONE (integer)

Framed Appletalk Zone

RADIUS_CHAP_CHALLENGE (integer)

Challenge

RADIUS_NAS_PORT_TYPE (integer)

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

Port Limit

RADIUS_LOGIN_LAT_PORT (integer)

Login LAT Port

RADIUS_CONNECT_INFO (integer)

Connect info

RADIUS_ACCT_STATUS_TYPE (integer)

Accounting status type, one of:

  • RADIUS_START
  • RADIUS_STOP
  • RADIUS_ACCOUNTING_ON
  • RADIUS_ACCOUNTING_OFF

RADIUS_ACCT_DELAY_TIME (integer)

Accounting delay time

RADIUS_ACCT_INPUT_OCTETS (integer)

Accounting input bytes

RADIUS_ACCT_OUTPUT_OCTETS (integer)

Accounting output bytes

RADIUS_ACCT_SESSION_ID (integer)

Accounting session ID

RADIUS_ACCT_AUTHENTIC (integer)

Accounting authentic, one of:

  • RADIUS_AUTH_RADIUS
  • RADIUS_AUTH_LOCAL
  • RADIUS_AUTH_REMOTE

RADIUS_ACCT_SESSION_TIME (integer)

Accounting session time

RADIUS_ACCT_INPUT_PACKETS (integer)

Accounting input packets

RADIUS_ACCT_OUTPUT_PACKETS (integer)

Accounting output packets

RADIUS_ACCT_TERMINATE_CAUSE (integer)

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

Accounting multi session ID

RADIUS_ACCT_LINK_COUNT (integer)

Accounting link count

RADIUS Packet Types
RADIUS Vendor Specific Attribute Types
Constante predefinite


RADIUS Vendor Specific Attribute Types

RADIUS_VENDOR_MICROSOFT (integer)

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

RADIUS Attribute Types
Exemple
Constante predefinite


Exemple

Howto start?

  • get a radius resource
  • configure the library
  • create the request
  • put attributes
  • send the request
  • receive attributes
  • close the radius resource (optional)
Take also a look at the examples in this package.

The package contains an example php script. This script demonstrates howto authenticate with radius using PAP or CHAP (md5). If you authenticate with Microsoft Radius servers then its not possible to use CHAP (md5). If you would like to authenticate with Microsoft Servers you have to use MS-CHAPv1 or MS-CHAPv2, but its more complicated, because you need md4, sha1 and des to generate the right data. The enclosed examples demonstrate all authentication-methods, including MS-CHAPv1 and MS-CHAPv2. To get the MS-CHAP to work you need the mcrypt and the mhash extension, starting with version 1.2 of the package, the mcrypt extension is no longer needed.

RADIUS Vendor Specific Attribute Types
Func?ii Radius
Radius


Func?ii Radius

Cuprins

  • 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_tagged_attr_data — Extracts the data from a tagged attribute
  • radius_get_tagged_attr_tag — Extracts the tag from a tagged 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_salt_encrypt_attr — Salt-encrypts a value
  • radius_send_request — Sends the request and waites for a reply
  • radius_server_secret — Returns the shared secret
  • radius_strerror — Returns an error message
Exemple
radius_acct_open
Radius


Creates a Radius handle for accounting

Func?ii Radius
radius_add_server
Func?ii Radius
PHP Manual

radius_acct_open

(PECL radius >= 1.1.0)

radius_acct_open — Creates a Radius handle for accounting

Descrierea

resource radius_acct_open ( void )

Valorile întoarse

Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.

Exemple

Example #1 radius_acct_open() example

<?php
$res = radius_acct_open ()
    or die ("Could not create handle");
print("Handle successfully created");
?>

Func?ii Radius
radius_add_server
Func?ii Radius


Adds a server

radius_acct_open
radius_auth_open
Func?ii Radius
PHP Manual

radius_add_server

(PECL radius >= 1.1.0)

radius_add_server — Adds a server

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

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

A se vedea ?i

  • radius_config() - Causes the library to read the given configuration file

radius_acct_open
radius_auth_open
Func?ii Radius


Creates a Radius handle for authentication

radius_add_server
radius_close
Func?ii Radius
PHP Manual

radius_auth_open

(PECL radius >= 1.1.0)

radius_auth_open — Creates a Radius handle for authentication

Descrierea

resource radius_auth_open ( void )

Valorile întoarse

Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.

Exemple

Example #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
Func?ii Radius


Frees all ressources

radius_auth_open
radius_config
Func?ii Radius
PHP Manual

radius_close

(PECL radius >= 1.1.0)

radius_close — Frees all ressources

Descrierea

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

radius_auth_open
radius_config
Func?ii Radius


Causes the library to read the given configuration file

radius_close
radius_create_request
Func?ii Radius
PHP Manual

radius_config

(PECL radius >= 1.1.0)

radius_config — Causes the library to read the given configuration file

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • radius_add_server() - Adds a server

radius_close
radius_create_request
Func?ii Radius


Create accounting or authentication request

radius_config
radius_cvt_addr
Func?ii Radius
PHP Manual

radius_create_request

(PECL radius >= 1.1.0)

radius_create_request — Create accounting or authentication request

Descrierea

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

Nota: Attention: You must call this function, before you can put any attribute!

Parametri

radius_handle

type

Type is RADIUS_ACCESS_REQUEST or RADIUS_ACCOUNTING_REQUEST.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 radius_create_request() example

<?php
if (!radius_create_request($res, RADIUS_ACCESS_REQUEST)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

A se vedea ?i

  • radius_send_request() - Sends the request and waites for a reply

radius_config
radius_cvt_addr
Func?ii Radius


Converts raw data to IP-Address

radius_create_request
radius_cvt_int
Func?ii Radius
PHP Manual

radius_cvt_addr

(PECL radius >= 1.1.0)

radius_cvt_addr — Converts raw data to IP-Address

Descrierea

string radius_cvt_addr ( string $data )

Exemple

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

A se vedea ?i

  • radius_cvt_int() - Converts raw data to integer
  • radius_cvt_string() - Converts raw data to string

radius_create_request
radius_cvt_int
Func?ii Radius


Converts raw data to integer

radius_cvt_addr
radius_cvt_string
Func?ii Radius
PHP Manual

radius_cvt_int

(PECL radius >= 1.1.0)

radius_cvt_int — Converts raw data to integer

Descrierea

int radius_cvt_int ( string $data )

Exemple

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

A se vedea ?i

  • radius_cvt_addr() - Converts raw data to IP-Address
  • radius_cvt_string() - Converts raw data to string

radius_cvt_addr
radius_cvt_string
Func?ii Radius


Converts raw data to string

radius_cvt_int
radius_demangle_mppe_key
Func?ii Radius
PHP Manual

radius_cvt_string

(PECL radius >= 1.1.0)

radius_cvt_string — Converts raw data to string

Descrierea

string radius_cvt_string ( string $data )

Exemple

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

A se vedea ?i

  • radius_cvt_addr() - Converts raw data to IP-Address
  • radius_cvt_int() - Converts raw data to integer

radius_cvt_int
radius_demangle_mppe_key
Func?ii Radius


Derives mppe-keys from mangled data

radius_cvt_string
radius_demangle
Func?ii Radius
PHP Manual

radius_demangle_mppe_key

(PECL radius >= 1.2.0)

radius_demangle_mppe_key — Derives mppe-keys from mangled data

Descrierea

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.

Valorile întoarse

Returns the demangled string, or FALSE on error.

radius_cvt_string
radius_demangle
Func?ii Radius


Demangles data

radius_demangle_mppe_key
radius_get_attr
Func?ii Radius
PHP Manual

radius_demangle

(PECL radius >= 1.2.0)

radius_demangle — Demangles data

Descrierea

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.

Valorile întoarse

Returns the demangled string, or FALSE on error.

radius_demangle_mppe_key
radius_get_attr
Func?ii Radius


Extracts an attribute

radius_demangle
radius_get_tagged_attr_data
Func?ii Radius
PHP Manual

radius_get_attr

(PECL radius >= 1.1.0)

radius_get_attr — Extracts an attribute

Descrierea

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.

Valorile întoarse

Returns an associative array containing the attribute-type and the data, or error number <= 0.

Exemple

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

A se vedea ?i

  • 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_tagged_attr_data
Func?ii Radius


Extracts the data from a tagged attribute

radius_get_attr
radius_get_tagged_attr_tag
Func?ii Radius
PHP Manual

radius_get_tagged_attr_data

(PECL radius >= 1.3.0)

radius_get_tagged_attr_data — Extracts the data from a tagged attribute

Descrierea

string radius_get_tagged_attr_data ( string $data )

If a tagged attribute has been returned from radius_get_attr(), radius_get_tagged_attr_data() will return the data from the attribute.

Parametri

data

The tagged attribute to be decoded.

Valorile întoarse

Returns the data from the tagged attribute sau FALSE în cazul e?ecului.

Exemple

Example #1 radius_get_tagged_attr_data() 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'];

    $tag = radius_get_tagged_attr_tag($data);
    $value = radius_get_tagged_attr_data($data);

    printf("Got tagged attribute with tag %d and value %s\n", $tag, $value);
}
?>

A se vedea ?i

  • radius_get_attr() - Extracts an attribute
  • radius_get_tagged_attr_tag() - Extracts the tag from a tagged attribute

radius_get_attr
radius_get_tagged_attr_tag
Func?ii Radius


Extracts the tag from a tagged attribute

radius_get_tagged_attr_data
radius_get_vendor_attr
Func?ii Radius
PHP Manual

radius_get_tagged_attr_tag

(PECL radius >= 1.3.0)

radius_get_tagged_attr_tag — Extracts the tag from a tagged attribute

Descrierea

integer radius_get_tagged_attr_tag ( string $data )

If a tagged attribute has been returned from radius_get_attr(), radius_get_tagged_attr_data() will return the tag from the attribute.

Parametri

data

The tagged attribute to be decoded.

Valorile întoarse

Returns the tag from the tagged attribute sau FALSE în cazul e?ecului.

Exemple

Example #1 radius_get_tagged_attr_tag() 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'];

    $tag = radius_get_tagged_attr_tag($data);
    $value = radius_get_tagged_attr_data($data);

    printf("Got tagged attribute with tag %d and value %s\n", $tag, $value);
}
?>

A se vedea ?i

  • radius_get_attr() - Extracts an attribute
  • radius_get_tagged_attr_data() - Extracts the data from a tagged attribute

radius_get_tagged_attr_data
radius_get_vendor_attr
Func?ii Radius


Extracts a vendor specific attribute

radius_get_tagged_attr_tag
radius_put_addr
Func?ii Radius
PHP Manual

radius_get_vendor_attr

(PECL radius >= 1.1.0)

radius_get_vendor_attr — Extracts a vendor specific attribute

Descrierea

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.

Valorile întoarse

Returns an associative array containing the attribute-type, vendor and the data, or FALSE on error.

Exemple

Example #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));
        }

    }
}
?>

A se vedea ?i

  • radius_get_attr() - Extracts an attribute
  • radius_put_vendor_attr() - Attaches a vendor specific binary attribute

radius_get_tagged_attr_tag
radius_put_addr
Func?ii Radius


Attaches an IP address attribute

radius_get_vendor_attr
radius_put_attr
Func?ii Radius
PHP Manual

radius_put_addr

(PECL radius >= 1.1.0)

radius_put_addr — Attaches an IP address attribute

Descrierea

bool radius_put_addr ( resource $radius_handle , int $type , string $addr [, int $options = 0 [, int $tag ]] )

Attaches an IP address attribute to the current RADIUS request.

Nota:

O interpelare trebuie sa fie creata cu ajutorul radius_create_request()înainte ca aceasta func?ie sa poata fi apelata.

Parametri

radius_handle

Resursa RADIUS.

type

Tipul atributului.

addr

An IPv4 address in string form, such as 10.0.0.1.

options

O masca de bi?i a op?iunilor atributului. Op?iunile disponibile includ RADIUS_OPTION_TAGGED ?i RADIUS_OPTION_SALT.

tag

Eticheta atributului. Acest parametru e ignorat daca nu a fost stabilita op?iunea RADIUS_OPTION_TAGGED.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
PECL radius 1.3.0 | The options and tag parameters were added.

radius_get_vendor_attr
radius_put_attr
Func?ii Radius


Attaches a binary attribute

radius_put_addr
radius_put_int
Func?ii Radius
PHP Manual

radius_put_attr

(PECL radius >= 1.1.0)

radius_put_attr — Attaches a binary attribute

Descrierea

bool radius_put_attr ( resource $radius_handle , int $type , string $value [, int $options = 0 [, int $tag ]] )

Attaches a binary attribute to the current RADIUS request.

Nota:

O interpelare trebuie sa fie creata cu ajutorul radius_create_request()înainte ca aceasta func?ie sa poata fi apelata.

Parametri

radius_handle

Resursa RADIUS.

type

Tipul atributului.

value

The attribute value, which will be treated as a raw binary string.

options

O masca de bi?i a op?iunilor atributului. Op?iunile disponibile includ RADIUS_OPTION_TAGGED ?i RADIUS_OPTION_SALT.

tag

Eticheta atributului. Acest parametru e ignorat daca nu a fost stabilita op?iunea RADIUS_OPTION_TAGGED.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

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

Istoricul schimbarilor

Versiune | Descriere
PECL radius 1.3.0 | The options and tag parameters were added.

A se vedea ?i

  • 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
Func?ii Radius


Attaches an integer attribute

radius_put_attr
radius_put_string
Func?ii Radius
PHP Manual

radius_put_int

(PECL radius >= 1.1.0)

radius_put_int — Attaches an integer attribute

Descrierea

bool radius_put_int ( resource $radius_handle , int $type , int $value [, int $options = 0 [, int $tag ]] )

Attaches an integer attribute to the current RADIUS request.

Nota:

O interpelare trebuie sa fie creata cu ajutorul radius_create_request()înainte ca aceasta func?ie sa poata fi apelata.

Parametri

radius_handle

Resursa RADIUS.

type

Tipul atributului.

value

The attribute value.

options

O masca de bi?i a op?iunilor atributului. Op?iunile disponibile includ RADIUS_OPTION_TAGGED ?i RADIUS_OPTION_SALT.

tag

Eticheta atributului. Acest parametru e ignorat daca nu a fost stabilita op?iunea RADIUS_OPTION_TAGGED.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
PECL radius 1.3.0 | The options and tag parameters were added.

Exemple

Example #1 radius_put_int() example

<?php
if (!radius_put_int($res, RAD_FRAMED_PROTOCOL, RAD_PPP)) {
   echo 'RadiusError:' . radius_strerror($res). "\n<br />";
   exit;
}
?>

A se vedea ?i

  • 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
Func?ii Radius


Attaches a string attribute

radius_put_int
radius_put_vendor_addr
Func?ii Radius
PHP Manual

radius_put_string

(PECL radius >= 1.1.0)

radius_put_string — Attaches a string attribute

Descrierea

bool radius_put_string ( resource $radius_handle , int $type , string $value [, int $options = 0 [, int $tag ]] )

Attaches a string attribute to the current RADIUS request. In general, radius_put_attr() is a more useful function for attaching string attributes, as it is binary safe.

Nota:

O interpelare trebuie sa fie creata cu ajutorul radius_create_request()înainte ca aceasta func?ie sa poata fi apelata.

Parametri

radius_handle

Resursa RADIUS.

type

Tipul atributului.

value

The attribute value. This value is expected by the underlying library to be null terminated, therefore this parameter is not binary safe.

options

O masca de bi?i a op?iunilor atributului. Op?iunile disponibile includ RADIUS_OPTION_TAGGED ?i RADIUS_OPTION_SALT.

tag

Eticheta atributului. Acest parametru e ignorat daca nu a fost stabilita op?iunea RADIUS_OPTION_TAGGED.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
PECL radius 1.3.0 | The options and tag parameters were added.

Exemple

Example #1 radius_put_string() example

<?php
if (!radius_put_string($res, RADIUS_USER_NAME, 'billy')) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

A se vedea ?i

  • 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
Func?ii Radius


Attaches a vendor specific IP address attribute

radius_put_string
radius_put_vendor_attr
Func?ii Radius
PHP Manual

radius_put_vendor_addr

(PECL radius >= 1.1.0)

radius_put_vendor_addr — Attaches a vendor specific IP address attribute

Descrierea

bool radius_put_vendor_addr ( resource $radius_handle , int $vendor , int $type , string $addr )

Attaches an IP address vendor specific attribute to the current RADIUS request.

Nota:

O interpelare trebuie sa fie creata cu ajutorul radius_create_request()înainte ca aceasta func?ie sa poata fi apelata.

Parametri

radius_handle

Resursa RADIUS.

vendor

ID-ul vânzatorului (producatorului).

type

Tipul atributului.

addr

An IPv4 address in string form, such as 10.0.0.1.

options

O masca de bi?i a op?iunilor atributului. Op?iunile disponibile includ RADIUS_OPTION_TAGGED ?i RADIUS_OPTION_SALT.

tag

Eticheta atributului. Acest parametru e ignorat daca nu a fost stabilita op?iunea RADIUS_OPTION_TAGGED.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
PECL radius 1.3.0 | The options and tag parameters were added.

radius_put_string
radius_put_vendor_attr
Func?ii Radius


Attaches a vendor specific binary attribute

radius_put_vendor_addr
radius_put_vendor_int
Func?ii Radius
PHP Manual

radius_put_vendor_attr

(PECL radius >= 1.1.0)

radius_put_vendor_attr — Attaches a vendor specific binary attribute

Descrierea

bool radius_put_vendor_attr ( resource $radius_handle , int $vendor , int $type , string $value [, int $options = 0 [, int $tag ]] )

Attaches a vendor specific binary attribute to the current RADIUS request.

Nota:

O interpelare trebuie sa fie creata cu ajutorul radius_create_request()înainte ca aceasta func?ie sa poata fi apelata.

Parametri

radius_handle

Resursa RADIUS.

vendor

ID-ul vânzatorului (producatorului).

type

Tipul atributului.

value

The attribute value, which will be treated as a raw binary string.

options

O masca de bi?i a op?iunilor atributului. Op?iunile disponibile includ RADIUS_OPTION_TAGGED ?i RADIUS_OPTION_SALT.

tag

Eticheta atributului. Acest parametru e ignorat daca nu a fost stabilita op?iunea RADIUS_OPTION_TAGGED.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
PECL radius 1.3.0 | The options and tag parameters were added.

Exemple

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

A se vedea ?i

  • radius_get_vendor_attr() - Extracts a vendor specific attribute

radius_put_vendor_addr
radius_put_vendor_int
Func?ii Radius


Attaches a vendor specific integer attribute

radius_put_vendor_attr
radius_put_vendor_string
Func?ii Radius
PHP Manual

radius_put_vendor_int

(PECL radius >= 1.1.0)

radius_put_vendor_int — Attaches a vendor specific integer attribute

Descrierea

bool radius_put_vendor_int ( resource $radius_handle , int $vendor , int $type , int $value [, int $options = 0 [, int $tag ]] )

Attaches a vendor specific integer attribute to the current RADIUS request.

Nota:

O interpelare trebuie sa fie creata cu ajutorul radius_create_request()înainte ca aceasta func?ie sa poata fi apelata.

Parametri

radius_handle

Resursa RADIUS.

vendor

ID-ul vânzatorului (producatorului).

type

Tipul atributului.

value

The attribute value.

options

O masca de bi?i a op?iunilor atributului. Op?iunile disponibile includ RADIUS_OPTION_TAGGED ?i RADIUS_OPTION_SALT.

tag

Eticheta atributului. Acest parametru e ignorat daca nu a fost stabilita op?iunea RADIUS_OPTION_TAGGED.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
PECL radius 1.3.0 | The options and tag parameters were added.

A se vedea ?i

  • radius_put_vendor_string() - Attaches a vendor specific string attribute

radius_put_vendor_attr
radius_put_vendor_string
Func?ii Radius


Attaches a vendor specific string attribute

radius_put_vendor_int
radius_request_authenticator
Func?ii Radius
PHP Manual

radius_put_vendor_string

(PECL radius >= 1.1.0)

radius_put_vendor_string — Attaches a vendor specific string attribute

Descrierea

bool radius_put_vendor_string ( resource $radius_handle , int $vendor , int $type , string $value [, int $options = 0 [, int $tag ]] )

Attaches a vendor specific string attribute to the current RADIUS request. In general, radius_put_vendor_attr() is a more useful function for attaching string attributes, as it is binary safe.

Nota:

O interpelare trebuie sa fie creata cu ajutorul radius_create_request()înainte ca aceasta func?ie sa poata fi apelata.

Parametri

radius_handle

Resursa RADIUS.

vendor

ID-ul vânzatorului (producatorului).

type

Tipul atributului.

value

The attribute value. This value is expected by the underlying library to be null terminated, therefore this parameter is not binary safe.

options

O masca de bi?i a op?iunilor atributului. Op?iunile disponibile includ RADIUS_OPTION_TAGGED ?i RADIUS_OPTION_SALT.

tag

Eticheta atributului. Acest parametru e ignorat daca nu a fost stabilita op?iunea RADIUS_OPTION_TAGGED.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
PECL radius 1.3.0 | The options and tag parameters were added.

A se vedea ?i

  • radius_put_vendor_int() - Attaches a vendor specific integer attribute

radius_put_vendor_int
radius_request_authenticator
Func?ii Radius


Returns the request authenticator

radius_put_vendor_string
radius_salt_encrypt_attr
Func?ii Radius
PHP Manual

radius_request_authenticator

(PECL radius >= 1.1.0)

radius_request_authenticator — Returns the request authenticator

Descrierea

string radius_request_authenticator ( resource $radius_handle )

The request authenticator is needed for demangling mangled data like passwords and encryption-keys.

Valorile întoarse

Returns the request authenticator as string, or FALSE on error.

A se vedea ?i

  • radius_demangle() - Demangles data

radius_put_vendor_string
radius_salt_encrypt_attr
Func?ii Radius


Salt-encrypts a value

radius_request_authenticator
radius_send_request
Func?ii Radius
PHP Manual

radius_salt_encrypt_attr

(PECL radius >= 1.3.0)

radius_salt_encrypt_attr — Salt-encrypts a value

Descrierea

string radius_salt_encrypt_attr ( resource $radius_handle , string $data )

Applies the RADIUS salt-encryption algorithm to the given value.

In general, this is achieved automatically by providing the RADIUS_OPTION_SALT option to an attribute setter function, but this function can be used if low-level request construction is required.

Parametri

data

The data to be salt-encrypted.

Valorile întoarse

Returns the salt-encrypted data sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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_request_authenticator
radius_send_request
Func?ii Radius


Sends the request and waites for a reply

radius_salt_encrypt_attr
radius_server_secret
Func?ii Radius
PHP Manual

radius_send_request

(PECL radius >= 1.1.0)

radius_send_request — Sends the request and waites for a reply

Descrierea

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.

Valorile întoarse

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.

A se vedea ?i

  • radius_create_request() - Create accounting or authentication request

radius_salt_encrypt_attr
radius_server_secret
Func?ii Radius


Returns the shared secret

radius_send_request
radius_strerror
Func?ii Radius
PHP Manual

radius_server_secret

(PECL radius >= 1.1.0)

radius_server_secret — Returns the shared secret

Descrierea

string radius_server_secret ( resource $radius_handle )

The shared secret is needed as salt for demangling mangled data like passwords and encryption-keys.

Valorile întoarse

Returns the server's shared secret as string, or FALSE on error.

radius_send_request
radius_strerror
Func?ii Radius


Returns an error message

radius_server_secret
Extensii specifice liniei de comanda
Func?ii Radius
PHP Manual

radius_strerror

(PECL radius >= 1.1.0)

radius_strerror — Returns an error message

Descrierea

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.

Valorile întoarse

Returns error messages as string from failed radius functions.

radius_server_secret
Extensii specifice liniei de comanda
Func?ii Radius


Extensii specifice liniei de comanda

  • Ncurses — Controlul ecranului terminalului cu Ncurses
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Ncurses
  • Newt
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Newt
  • Readline — GNU Readline
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Readline
radius_strerror
Ncurses
Informa?ii de referin?a despre func?ii


Controlul ecranului terminalului cu Ncurses

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
    • Codurile de eroare
    • Culori
    • Taste
    • ?oricel
  • Func?ii Ncurses
    • ncurses_addch — Adauga caracterul în pozi?ia curenta ?i avanseaza cursorul
    • ncurses_addchnstr — Adauga ?irul de caractere cu atribute, cu lungimea specificata, în pozi?ia curenta
    • ncurses_addchstr — Adauga ?irul de caractere cu atribute în pozi?ia curenta
    • ncurses_addnstr — Adauga ?irul de caractere cu lungimea specificata în pozi?ia curenta
    • ncurses_addstr — Afi?eaza textul în pozi?ia curenta
    • ncurses_assume_default_colors — Define?te culorile implicite pentru culoarea 0
    • ncurses_attroff — Deconecteaza atributele date
    • ncurses_attron — Conecteaza atributele date
    • ncurses_attrset — Stabile?te atributele date
    • ncurses_baudrate — Întoarce rata baud a terminalului
    • ncurses_beep — Face ca terminalul sa emita un semnal sonor
    • ncurses_bkgd — Stabile?te proprietatea fundalului pentru ecranul terminalului
    • ncurses_bkgdset — Controleaza fundalul ecranului
    • ncurses_border — Deseneaza o bordura în jurul ecranului utilizând caractere cu atribute
    • ncurses_bottom_panel — Muta panelul vizibil la fundul stivei
    • ncurses_can_change_color — Verifica daca defini?iile culorilor terminalului pot fi schimbate
    • ncurses_cbreak — Deconecteaza buferizarea intrarilor
    • ncurses_clear — Cura?a ecranul
    • ncurses_clrtobot — Cura?a ecranul din pozi?ia curenta pâna jos
    • ncurses_clrtoeol — Cura?a ecranul din pozi?ia curenta pâna la sfâr?itul liniei
    • ncurses_color_content — Ob?ine componentele RGB ale culorii
    • ncurses_color_set — Stabile?te culorile de prim plan ?i de fundal active
    • ncurses_curs_set — Stabile?te starea cursorului
    • ncurses_def_prog_mode — Salveaza modul terminalului (pentru program)
    • ncurses_def_shell_mode — Salveaza modul terminalului (pentru înveli?)
    • ncurses_define_key — Define?te un cod de cheie
    • ncurses_del_panel — Extrage panelul din stiva ?i îl elimina (dar nu ?i fereastra asociata)
    • ncurses_delay_output — Încetine?te afi?area la terminal utilizând caractere de umplutura
    • ncurses_delch — Elimina caracterul de la pozi?ia curenta, deplaseaza restul liniei în stânga
    • ncurses_deleteln — Elimina linia de la pozi?ia curenta, deplaseaza restul ecranului în sus
    • ncurses_delwin — Elimina o fereastra ncurses
    • ncurses_doupdate — Înscrie în terminal toate actualizarile pregatite
    • ncurses_echo — Activeaza afi?area la ecran a intrarilor de la tastatura
    • ncurses_echochar — Afi?area unui singur caracter, inclusiv actualizarea
    • ncurses_end — Opre?te utilizarea ncurses, cura?a ecranul
    • ncurses_erase — Cura?a ecranul terminalului
    • ncurses_erasechar — Întoarce caracterul de eliminare curent
    • ncurses_filter — Stabile?te LINES pentru iniscr() ?i newterm() în 1
    • ncurses_flash — Sclipe?te ecranul terminalului (clopo?el vizual)
    • ncurses_flushinp — Gole?te zona-tampon a intrarilor de la tastatura
    • ncurses_getch — Cite?te un caracter de la tastaura
    • ncurses_getmaxyx — Întoarce marimea unei ferestre
    • ncurses_getmouse — Cite?te evenimentul ?oricelului
    • ncurses_getyx — Întoarce pozi?ia curenta a cursorului într-o fereastra
    • ncurses_halfdelay — Stabile?te terminalul în mod semipauza
    • ncurses_has_colors — Verifica daca terminalul are capacita?i de redare a culorilor
    • ncurses_has_ic — Verifica capacita?ile de inserare ?i eliminare
    • ncurses_has_il — Verifica capacita?ile de inserare ?i eliminare a liniilor
    • ncurses_has_key — Verifica prezen?a unei taste func?ionale pe tastatura terminalului
    • ncurses_hide_panel — Elimina panelul din stiva, facându-l invizibil
    • ncurses_hline — Deseneaza o linie orizontala în pozi?ia curenta folosind un caracter atribuit ?i o lungime de maximum n caractere
    • ncurses_inch — Ob?ine caracterul ?i atributul de la pozi?ia curenta
    • ncurses_init_color — Define?te o culoare a terminalului
    • ncurses_init_pair — Define?te o pereche de culori
    • ncurses_init — Ini?ializeaza ncurses
    • ncurses_insch — Insereaza un caracter deplasând restul liniei, inclusiv caracterul din pozi?ia curenta
    • ncurses_insdelln — Insereaza linii înainte de linia curenta ?i deplaseaza afi?ajul în jos (numerele negative elimina ?i deplaseaza afi?ajul în sus)
    • ncurses_insertln — Insereaza o linie, deplaseaza restul ecranului în jos
    • ncurses_insstr — Insereaza un ?ir de caractere în pozi?ia curenta, deplasând restul liniei în dreapta
    • ncurses_instr — Cite?te un ?ir de caractere de la ecranul terminalului
    • ncurses_isendwin — Ncurses este în mod endwin, pot fi efectuate afi?ari normale la ecran
    • ncurses_keyok — Activeaza sau dezactiveaza un cod al tastei
    • ncurses_keypad — Conecteaza sau deconecteaza tastatura numerica
    • ncurses_killchar — Întoarce caracterul curent de eliminare a liniei
    • ncurses_longname — Întoarce descrierea terminalului
    • ncurses_meta — Activeaza / Dezactiveaza informa?iile de 8 bi?i despre meta chei
    • ncurses_mouse_trafo — Transforma coordonate
    • ncurses_mouseinterval — Stabile?te timpul de expirare pentru apasarile butoanelor ?oricelului
    • ncurses_mousemask — Stabile?te op?iunile ?oricelului
    • ncurses_move_panel — Deplaseaza un panel astfel încât col?ul stânga-sus sa fie în pozi?ia [startx, starty]
    • ncurses_move — Deplaseaza pozi?ia de afi?are
    • ncurses_mvaddch — Deplaseaza pozi?ia curenta ?i adauga un caracter
    • ncurses_mvaddchnstr — Deplaseaza pozi?ia ?i adauga ?irul de caractere cu atribute de lungime specificata
    • ncurses_mvaddchstr — Deplaseaza pozi?ia ?i adauga un ?ir de caractere cu atribute
    • ncurses_mvaddnstr — Deplaseaza pozi?ia ?i adauga un ?ir de caractere de lungime specificata
    • ncurses_mvaddstr — Deplaseaza pozi?ia ?i adauga un ?ir de caractere
    • ncurses_mvcur — Deplaseaza imediat cursorul
    • ncurses_mvdelch — Deplaseaza pozi?ia ?i elimina caracterul, deplaseaza restul liniei în stânga
    • ncurses_mvgetch — Deplaseaza pozi?ia ?i ob?ine caracterul din noua pozi?ie
    • ncurses_mvhline — Stabile?te pozi?ia noua ?i deseneaza o linie orizontala folosind un caracter cu atribute ?i o lungime maxima de n caractere
    • ncurses_mvinch — Deplaseaza pozi?ia ?i ob?ine caracterul cu atribute din pozi?ia noua
    • ncurses_mvvline — Stabile?te pozi?ia noua ?i deseneaza o linie verticala folosint un caracter cu atribute ?i o înal?ime maxima de n caractere
    • ncurses_mvwaddstr — Adauga un ?ir de caractere într-o pozi?ie noua din fereastra
    • ncurses_napms — Adoarme
    • ncurses_new_panel — Creeaza un nou panel ?i îl asociaza cu o fereastra
    • ncurses_newpad — Creeaza un nou pad (fereastra)
    • ncurses_newwin — Creeaza o fereastra noua
    • ncurses_nl — Transleaza caracterul de trecere în linie noua ?i caracterele "carriage return" / "line feed"
    • ncurses_nocbreak — Schimba terminalul în mod cooked
    • ncurses_noecho — Deconecteaza afi?area la ecran a tastelor apasate
    • ncurses_nonl — Nu transleaza caracterul de trecere în linie noua ?i caracterele "carriage return" / "line feed"
    • ncurses_noqiflush — Nu gole?te zona-tampon la caracterele de semnal
    • ncurses_noraw — Schimba terminalul din modul raw
    • ncurses_pair_content — Ob?ine culorile de prim plan ?i de fundal ale unei perechi de culori
    • ncurses_panel_above — Întoarce panelul care este de asupra altui panel
    • ncurses_panel_below — Întoarce panelul care este de sub alt panel
    • ncurses_panel_window — Întoarce fereastra asociata cu un panel
    • ncurses_pnoutrefresh — Copie o regiune dintr-un pad în ecranul virtual
    • ncurses_prefresh — Copie o regiune dintr-un pad în ecranul virtual
    • ncurses_putp — Aplica informa?ia de completare la ?irul de caractere ?i îl afi?eaza
    • ncurses_qiflush — Gole?te zona-tampon la caracterele de semnal
    • ncurses_raw — Schimba terminalul în mod raw
    • ncurses_refresh — Actualizeaza ecranul
    • ncurses_replace_panel — Înlocuie?te fereastra asociata cu un panel
    • ncurses_reset_prog_mode — Reseteaza modul programului salvat cu def_prog_mode
    • ncurses_reset_shell_mode — Reseteaza modul înveli?ului salvat cu def_shell_mode
    • ncurses_resetty — Restabile?te starea terminalului salvata
    • ncurses_savetty — Salveaza starea terminalului
    • ncurses_scr_dump — Salveaza con?inutul ecranului într-un fi?ier
    • ncurses_scr_init — Ini?ializeaza ecranul dintr-un fi?ier salvat
    • ncurses_scr_restore — Restabile?te ecranul dintr-un fi?ier salvat
    • ncurses_scr_set — Stabile?te con?inutul ecranului dintr-un fi?ier salvat
    • ncurses_scrl — Deplaseaza con?inutul ferestrei în sus sau în jos fara a modifica pozi?ia curenta
    • ncurses_show_panel — Plaseaza un panel invizibil în vârful stivei, facându-l vizibil
    • ncurses_slk_attr — Întoarce atributul curent al etichetelor soft ale tastelor
    • ncurses_slk_attroff — Deconecteaza atribute specificate pentru taste func?ionale cu etichete soft
    • ncurses_slk_attron — Conecteaza atribute specificate pentru taste func?ionale cu etichete soft
    • ncurses_slk_attrset — Stabile?te atribute specificate pentru taste func?ionale cu etichete soft
    • ncurses_slk_clear — Elimina etichetele soft de la ecran
    • ncurses_slk_color — Stabile?te culoarea pentru tastele cu eticheta soft
    • ncurses_slk_init — Ini?ializeaza taste func?ionale cu eticheta soft
    • ncurses_slk_noutrefresh — Copie cheile soft label pe ecranul virtual
    • ncurses_slk_refresh — Copie tastele etichetelor soft la ecran
    • ncurses_slk_restore — Restabile?te tastele cu etichete soft
    • ncurses_slk_set — Stabile?te etichetele tastelor func?ionale
    • ncurses_slk_touch — For?eaza afi?area când este efectuat ncurses_slk_noutrefresh
    • ncurses_standend — Stopeaza utilizarea atributului 'standout'
    • ncurses_standout — Începe utilizarea atributului 'standout'
    • ncurses_start_color — Ini?ializeaza func?ionalitatea culorilor
    • ncurses_termattrs — Întoarce un SAU logic al tuturor fanioanelor de atribute sus?inute de terminal
    • ncurses_termname — Întoarce denumirea scurta a terminalului
    • ncurses_timeout — Stabile?te timpul de expirare pentru secven?e speciale de taste
    • ncurses_top_panel — Deplaseaza un panel vizibil în vârful stivei
    • ncurses_typeahead — Specifica un descriptor de fi?ier diferit pentru verificarea typeahead
    • ncurses_ungetch — Plaseaza un caracter înapoi în fluxul de intrari
    • ncurses_ungetmouse — Plaseaza evenimentele ?oricelului în rând
    • ncurses_update_panels — Actualizeaza ecranul virtual pentru a reflecta rela?iile dintre panelurile din stiva
    • ncurses_use_default_colors — Atribuie culorile implicite ale terminalului culorii cu indicele -1
    • ncurses_use_env — Controleaza utilizarea informa?iilor de mediu despre dimensiunea terminalului
    • ncurses_use_extended_names — Controlezaa utilizarea denumirilor extinse în descrieri terminfo
    • ncurses_vidattr — Afi?eaza ?irul de caractere la terminal în modul video atribut
    • ncurses_vline — Deseneaza o linie verticala în pozi?ia curenta utilizând un caracter cu atribute, de o înal?ime maxima de n caractere
    • ncurses_waddch — Adauga un caracter în pozi?ia curenta din fereastra ?i avanseaza cursorul
    • ncurses_waddstr — Afi?eaza un text în pozi?ia curenta din fereastra
    • ncurses_wattroff — Deconecteaza atribute pentru o fereastra
    • ncurses_wattron — Conecteaza atribute pentru o fereastra
    • ncurses_wattrset — Stabile?te atribute pentru o fereastra
    • ncurses_wborder — Deseneaza o bordura în jurul ferestrei utilizând caractere cu atribute
    • ncurses_wclear — Cura?a fereastra
    • ncurses_wcolor_set — Stabile?te perechile de culori ale ferestrei
    • ncurses_werase — ?terge con?inutul ferestrei
    • ncurses_wgetch — Cite?te un caracter de la tastatura (fereastra)
    • ncurses_whline — Deseneaza o linie orizontala într-o fereastra în pozi?ia curenta utilizând un caracter cu atribute ?i o lungime maxima de n caractere
    • ncurses_wmouse_trafo — Transforma coordonate window/stdscr
    • ncurses_wmove — Deplaseaza pozi?ia de afi?are în fereastra
    • ncurses_wnoutrefresh — Copie fereastra în ecranul virtual
    • ncurses_wrefresh — Actualizeaza fereastra la ecranul terminalului
    • ncurses_wstandend — Încheie modul standout pentru o fereastra
    • ncurses_wstandout — Transfera o fererastra în mod standout
    • ncurses_wvline — Deseneaza o linie verticala într-o fereastra în pozi?ia curenta utilizând un caracter cu atribute, de o lungime maxima de n caractere
Extensii specifice liniei de comanda
Introducere
Extensii specifice liniei de comanda


Introducere

ncurses (new curses) este o emulare software gratuita a bibliotecii curses în System V Rel 4.0 (?i ulterioara). Ea utilizeaza formatul terminfo, sus?ine pads, culori, eviden?ieri multiple, caractere pentru formulare ?i mapari ale tastelor func?ionale. Din cauza naturii interactive a acestei biblioteci, ea va fi de pu?in folos pentru scrierea aplica?iilor Web, dar poate fi utila la scrierea scripturilor -- utilizarea PHP din linia de comanda.

Facilita?ile disponibile, cum ar fi culorile, depind de terminalul ce se utilizeaza. Utiliza?i func?ii precum ncurses_has_colors(), ncurses_can_change_color() ?i ncurses_has_ic() pentru a verifica anumite capacita?i ale terminalului.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.3.0.

ncurses este disponibila pentru urmatoarele platforme:

  • AIX
  • BeOS
  • Variante BSD (FreeBSD, NetBSD, OpenBSD)
  • Cygwin
  • Digital Unix (aka OSF1)
  • GNU/Linux
  • HPUX
  • IRIX64
  • Mac OS X
  • OS/2
  • QNX
  • SCO OpenServer
  • Solaris
  • Tru64

Ncurses
Instalarea / configurarea
Ncurses


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Ncurses


Necesita?i

Ave?i nevoie de bibliotecile ncurses ?i fi?ierele cu antete. Descarca?i ultima versiune de la adresa » ftp://ftp.gnu.org/pub/gnu/ncurses/ sau de la alta oglinda GNU.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/ncurses.

Sus?inerea manipularii cu ecrane CRT cu caractere extinse (ncursesw) a fost adaugata în versiunea 1.0.1 a acestei extensii PECL.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie define?te resurse pentru fereastra, panel ?i pad.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Cuprins

  • Codurile de eroare
  • Culori
  • Taste
  • ?oricel

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Tipurile resurselor
Codurile de eroare
Ncurses


Codurile de eroare

În caz de erori, func?iile ncurses întorc -1. Unele func?ii întorc 0 în caz de succes. Accesa?i paginile respective ale documenta?iei pentru a afla valorile întoarse.

Constante predefinite
Culori
Constante predefinite


Culori

Constantele culorilor în ncurses
constanta | semnifica?ia
NCURSES_COLOR_BLACK | nici o culoare (negru)
NCURSES_COLOR_WHITE | alb
NCURSES_COLOR_RED | ro?u - sus?inut când terminalul se afla în mod color
NCURSES_COLOR_GREEN | verde - sus?inut când terminalul se afla în mod color
NCURSES_COLOR_YELLOW | galben - sus?inut când terminalul se afla în mod color
NCURSES_COLOR_BLUE | albastru - sus?inut când terminalul se afla în mod color
NCURSES_COLOR_CYAN | cyan - sus?inut când terminalul se afla în mod color
NCURSES_COLOR_MAGENTA | purpuriu - sus?inut când terminalul se afla în mod color
Codurile de eroare
Taste
Constante predefinite


Taste

Constante ale tastelor în ncurses
constanta | semnifica?ia
NCURSES_KEY_F0 - NCURSES_KEY_F64 | tastele func?ionale F1 - F64
NCURSES_KEY_DOWN | sageata în jos
NCURSES_KEY_UP | sageata în sus
NCURSES_KEY_LEFT | sageata în stânga
NCURSES_KEY_RIGHT | sageata în dreapta
NCURSES_KEY_HOME | tasta home (sageata în stânga-sus)
NCURSES_KEY_BACKSPACE | backspace
NCURSES_KEY_DL | elimina o linie
NCURSES_KEY_IL | insereaza o linie
NCURSES_KEY_DC | elimina un caracter
NCURSES_KEY_IC | inserare a unui caracter sau intrare în mod de inserare
NCURSES_KEY_EIC | ie?ire din modul de inserare a caracterului
NCURSES_KEY_CLEAR | cura?a ecranul
NCURSES_KEY_EOS | cura?a pâna la sfâr?itul ecranului
NCURSES_KEY_EOL | cura?a pâna la sfâr?itul liniei
NCURSES_KEY_SF | deruleaza o linie înainte
NCURSES_KEY_SR | deruleaza o linie în urma
NCURSES_KEY_NPAGE | urmatoarea pagina
NCURSES_KEY_PPAGE | pagina precedenta
NCURSES_KEY_STAB | stabile?te tabula?ia
NCURSES_KEY_CTAB | elimina tabula?ia
NCURSES_KEY_CATAB | elimina toate tab-urile
NCURSES_KEY_SRESET | reset soft (par?ial)
NCURSES_KEY_RESET | reset hard
NCURSES_KEY_PRINT | imprima
NCURSES_KEY_LL | stânga-jos
NCURSES_KEY_A1 | stânga-sus pe tastatura numerica
NCURSES_KEY_A3 | dreapta-sus pe tastatura numerica
NCURSES_KEY_B2 | centrul tastaturii numerice
NCURSES_KEY_C1 | stânga-jos pe tastatura numerica
NCURSES_KEY_C3 | dreapta-jos pe tastatura numerica
NCURSES_KEY_BTAB | tabularea înapoi
NCURSES_KEY_BEG | început
NCURSES_KEY_CANCEL | anulare
NCURSES_KEY_CLOSE | închide
NCURSES_KEY_COMMAND | cmd (comanda)
NCURSES_KEY_COPY | copie
NCURSES_KEY_CREATE | creeaza
NCURSES_KEY_END | sfâr?it
NCURSES_KEY_EXIT | ie?ire
NCURSES_KEY_FIND | gase?te
NCURSES_KEY_HELP | ajutor
NCURSES_KEY_MARK | marcheaza
NCURSES_KEY_MESSAGE | mesaj
NCURSES_KEY_MOVE | deplaseaza
NCURSES_KEY_NEXT | urmatorul
NCURSES_KEY_OPEN | deschide
NCURSES_KEY_OPTIONS | op?iuni
NCURSES_KEY_PREVIOUS | precedent
NCURSES_KEY_REDO | reface
NCURSES_KEY_REFERENCE | ref (referin?a)
NCURSES_KEY_REFRESH | actualizeaza
NCURSES_KEY_REPLACE | înlocuie?te
NCURSES_KEY_RESTART | restart
NCURSES_KEY_RESUME | reia
NCURSES_KEY_SAVE | salveaza
NCURSES_KEY_SBEG | shift + început
NCURSES_KEY_SCANCEL | shift + anulare
NCURSES_KEY_SCOMMAND | shift + comanda
NCURSES_KEY_SCOPY | shift + copie
NCURSES_KEY_SCREATE | shift + creeaza
NCURSES_KEY_SDC | shift + elimina caracter
NCURSES_KEY_SDL | shift + elimina linia
NCURSES_KEY_SELECT | selecteaza
NCURSES_KEY_SEND | shift + sfâr?it
NCURSES_KEY_SEOL | shift + sfâr?it de linie
NCURSES_KEY_SEXIT | shift + ie?ire
NCURSES_KEY_SFIND | shift + cautare
NCURSES_KEY_SHELP | shift + ajutor
NCURSES_KEY_SHOME | shift + home
NCURSES_KEY_SIC | shift + intrare
NCURSES_KEY_SLEFT | shift + sageata în stânga
NCURSES_KEY_SMESSAGE | shift + mesaj
NCURSES_KEY_SMOVE | shift + deplaseaza
NCURSES_KEY_SNEXT | shift + urmatorul
NCURSES_KEY_SOPTIONS | shift + op?iuni
NCURSES_KEY_SPREVIOUS | shift + precedentul
NCURSES_KEY_SPRINT | shift + imprima
NCURSES_KEY_SREDO | shift + reface
NCURSES_KEY_SREPLACE | shift + înlocuie?te
NCURSES_KEY_SRIGHT | shift + sageata în dreapta
NCURSES_KEY_SRSUME | shift + reia
NCURSES_KEY_SSAVE | shift + salveaza
NCURSES_KEY_SSUSPEND | shift + suspenda
NCURSES_KEY_UNDO | anuleaza
NCURSES_KEY_MOUSE | a avut loc un eveniment al ?oricelului
NCURSES_KEY_MAX | valoarea maxima a tastei
Culori
?oricel
Constante predefinite


?oricel

constante ale ?oricelului
constanta | semnifica?ia
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASED | butonul (1-4) a fost eliberat
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSED | butonul (1-4) a fost apasat
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKED | butonul (1-4) a fost apasat
NCURSES_BUTTON1_DOUBLE_CLICKED - NCURSES_BUTTON4_DOUBLE_CLICKED | butonul (1-4) a fost apasat dublu
NCURSES_BUTTON1_TRIPLE_CLICKED - NCURSES_BUTTON4_TRIPLE_CLICKED | butonul (1-4) a fost apasat triplu
NCURSES_BUTTON_CTRL | ctrl a fost apasat în timpul apasarii butonului ?oricelului
NCURSES_BUTTON_SHIFT | shift a fost apasat în timpul apasarii butonului ?oricelului
NCURSES_BUTTON_ALT | alt a fost apasat în timpul apasarii butonului ?oricelului
NCURSES_ALL_MOUSE_EVENTS | raporteaza toate evenimentele ?oricelului
NCURSES_REPORT_MOUSE_POSITION | raporteaza pozi?ia ?oricelului
Taste
Func?ii Ncurses
Constante predefinite


Func?ii Ncurses

Cuprins

  • ncurses_addch — Adauga caracterul în pozi?ia curenta ?i avanseaza cursorul
  • ncurses_addchnstr — Adauga ?irul de caractere cu atribute, cu lungimea specificata, în pozi?ia curenta
  • ncurses_addchstr — Adauga ?irul de caractere cu atribute în pozi?ia curenta
  • ncurses_addnstr — Adauga ?irul de caractere cu lungimea specificata în pozi?ia curenta
  • ncurses_addstr — Afi?eaza textul în pozi?ia curenta
  • ncurses_assume_default_colors — Define?te culorile implicite pentru culoarea 0
  • ncurses_attroff — Deconecteaza atributele date
  • ncurses_attron — Conecteaza atributele date
  • ncurses_attrset — Stabile?te atributele date
  • ncurses_baudrate — Întoarce rata baud a terminalului
  • ncurses_beep — Face ca terminalul sa emita un semnal sonor
  • ncurses_bkgd — Stabile?te proprietatea fundalului pentru ecranul terminalului
  • ncurses_bkgdset — Controleaza fundalul ecranului
  • ncurses_border — Deseneaza o bordura în jurul ecranului utilizând caractere cu atribute
  • ncurses_bottom_panel — Muta panelul vizibil la fundul stivei
  • ncurses_can_change_color — Verifica daca defini?iile culorilor terminalului pot fi schimbate
  • ncurses_cbreak — Deconecteaza buferizarea intrarilor
  • ncurses_clear — Cura?a ecranul
  • ncurses_clrtobot — Cura?a ecranul din pozi?ia curenta pâna jos
  • ncurses_clrtoeol — Cura?a ecranul din pozi?ia curenta pâna la sfâr?itul liniei
  • ncurses_color_content — Ob?ine componentele RGB ale culorii
  • ncurses_color_set — Stabile?te culorile de prim plan ?i de fundal active
  • ncurses_curs_set — Stabile?te starea cursorului
  • ncurses_def_prog_mode — Salveaza modul terminalului (pentru program)
  • ncurses_def_shell_mode — Salveaza modul terminalului (pentru înveli?)
  • ncurses_define_key — Define?te un cod de cheie
  • ncurses_del_panel — Extrage panelul din stiva ?i îl elimina (dar nu ?i fereastra asociata)
  • ncurses_delay_output — Încetine?te afi?area la terminal utilizând caractere de umplutura
  • ncurses_delch — Elimina caracterul de la pozi?ia curenta, deplaseaza restul liniei în stânga
  • ncurses_deleteln — Elimina linia de la pozi?ia curenta, deplaseaza restul ecranului în sus
  • ncurses_delwin — Elimina o fereastra ncurses
  • ncurses_doupdate — Înscrie în terminal toate actualizarile pregatite
  • ncurses_echo — Activeaza afi?area la ecran a intrarilor de la tastatura
  • ncurses_echochar — Afi?area unui singur caracter, inclusiv actualizarea
  • ncurses_end — Opre?te utilizarea ncurses, cura?a ecranul
  • ncurses_erase — Cura?a ecranul terminalului
  • ncurses_erasechar — Întoarce caracterul de eliminare curent
  • ncurses_filter — Stabile?te LINES pentru iniscr() ?i newterm() în 1
  • ncurses_flash — Sclipe?te ecranul terminalului (clopo?el vizual)
  • ncurses_flushinp — Gole?te zona-tampon a intrarilor de la tastatura
  • ncurses_getch — Cite?te un caracter de la tastaura
  • ncurses_getmaxyx — Întoarce marimea unei ferestre
  • ncurses_getmouse — Cite?te evenimentul ?oricelului
  • ncurses_getyx — Întoarce pozi?ia curenta a cursorului într-o fereastra
  • ncurses_halfdelay — Stabile?te terminalul în mod semipauza
  • ncurses_has_colors — Verifica daca terminalul are capacita?i de redare a culorilor
  • ncurses_has_ic — Verifica capacita?ile de inserare ?i eliminare
  • ncurses_has_il — Verifica capacita?ile de inserare ?i eliminare a liniilor
  • ncurses_has_key — Verifica prezen?a unei taste func?ionale pe tastatura terminalului
  • ncurses_hide_panel — Elimina panelul din stiva, facându-l invizibil
  • ncurses_hline — Deseneaza o linie orizontala în pozi?ia curenta folosind un caracter atribuit ?i o lungime de maximum n caractere
  • ncurses_inch — Ob?ine caracterul ?i atributul de la pozi?ia curenta
  • ncurses_init_color — Define?te o culoare a terminalului
  • ncurses_init_pair — Define?te o pereche de culori
  • ncurses_init — Ini?ializeaza ncurses
  • ncurses_insch — Insereaza un caracter deplasând restul liniei, inclusiv caracterul din pozi?ia curenta
  • ncurses_insdelln — Insereaza linii înainte de linia curenta ?i deplaseaza afi?ajul în jos (numerele negative elimina ?i deplaseaza afi?ajul în sus)
  • ncurses_insertln — Insereaza o linie, deplaseaza restul ecranului în jos
  • ncurses_insstr — Insereaza un ?ir de caractere în pozi?ia curenta, deplasând restul liniei în dreapta
  • ncurses_instr — Cite?te un ?ir de caractere de la ecranul terminalului
  • ncurses_isendwin — Ncurses este în mod endwin, pot fi efectuate afi?ari normale la ecran
  • ncurses_keyok — Activeaza sau dezactiveaza un cod al tastei
  • ncurses_keypad — Conecteaza sau deconecteaza tastatura numerica
  • ncurses_killchar — Întoarce caracterul curent de eliminare a liniei
  • ncurses_longname — Întoarce descrierea terminalului
  • ncurses_meta — Activeaza / Dezactiveaza informa?iile de 8 bi?i despre meta chei
  • ncurses_mouse_trafo — Transforma coordonate
  • ncurses_mouseinterval — Stabile?te timpul de expirare pentru apasarile butoanelor ?oricelului
  • ncurses_mousemask — Stabile?te op?iunile ?oricelului
  • ncurses_move_panel — Deplaseaza un panel astfel încât col?ul stânga-sus sa fie în pozi?ia [startx, starty]
  • ncurses_move — Deplaseaza pozi?ia de afi?are
  • ncurses_mvaddch — Deplaseaza pozi?ia curenta ?i adauga un caracter
  • ncurses_mvaddchnstr — Deplaseaza pozi?ia ?i adauga ?irul de caractere cu atribute de lungime specificata
  • ncurses_mvaddchstr — Deplaseaza pozi?ia ?i adauga un ?ir de caractere cu atribute
  • ncurses_mvaddnstr — Deplaseaza pozi?ia ?i adauga un ?ir de caractere de lungime specificata
  • ncurses_mvaddstr — Deplaseaza pozi?ia ?i adauga un ?ir de caractere
  • ncurses_mvcur — Deplaseaza imediat cursorul
  • ncurses_mvdelch — Deplaseaza pozi?ia ?i elimina caracterul, deplaseaza restul liniei în stânga
  • ncurses_mvgetch — Deplaseaza pozi?ia ?i ob?ine caracterul din noua pozi?ie
  • ncurses_mvhline — Stabile?te pozi?ia noua ?i deseneaza o linie orizontala folosind un caracter cu atribute ?i o lungime maxima de n caractere
  • ncurses_mvinch — Deplaseaza pozi?ia ?i ob?ine caracterul cu atribute din pozi?ia noua
  • ncurses_mvvline — Stabile?te pozi?ia noua ?i deseneaza o linie verticala folosint un caracter cu atribute ?i o înal?ime maxima de n caractere
  • ncurses_mvwaddstr — Adauga un ?ir de caractere într-o pozi?ie noua din fereastra
  • ncurses_napms — Adoarme
  • ncurses_new_panel — Creeaza un nou panel ?i îl asociaza cu o fereastra
  • ncurses_newpad — Creeaza un nou pad (fereastra)
  • ncurses_newwin — Creeaza o fereastra noua
  • ncurses_nl — Transleaza caracterul de trecere în linie noua ?i caracterele "carriage return" / "line feed"
  • ncurses_nocbreak — Schimba terminalul în mod cooked
  • ncurses_noecho — Deconecteaza afi?area la ecran a tastelor apasate
  • ncurses_nonl — Nu transleaza caracterul de trecere în linie noua ?i caracterele "carriage return" / "line feed"
  • ncurses_noqiflush — Nu gole?te zona-tampon la caracterele de semnal
  • ncurses_noraw — Schimba terminalul din modul raw
  • ncurses_pair_content — Ob?ine culorile de prim plan ?i de fundal ale unei perechi de culori
  • ncurses_panel_above — Întoarce panelul care este de asupra altui panel
  • ncurses_panel_below — Întoarce panelul care este de sub alt panel
  • ncurses_panel_window — Întoarce fereastra asociata cu un panel
  • ncurses_pnoutrefresh — Copie o regiune dintr-un pad în ecranul virtual
  • ncurses_prefresh — Copie o regiune dintr-un pad în ecranul virtual
  • ncurses_putp — Aplica informa?ia de completare la ?irul de caractere ?i îl afi?eaza
  • ncurses_qiflush — Gole?te zona-tampon la caracterele de semnal
  • ncurses_raw — Schimba terminalul în mod raw
  • ncurses_refresh — Actualizeaza ecranul
  • ncurses_replace_panel — Înlocuie?te fereastra asociata cu un panel
  • ncurses_reset_prog_mode — Reseteaza modul programului salvat cu def_prog_mode
  • ncurses_reset_shell_mode — Reseteaza modul înveli?ului salvat cu def_shell_mode
  • ncurses_resetty — Restabile?te starea terminalului salvata
  • ncurses_savetty — Salveaza starea terminalului
  • ncurses_scr_dump — Salveaza con?inutul ecranului într-un fi?ier
  • ncurses_scr_init — Ini?ializeaza ecranul dintr-un fi?ier salvat
  • ncurses_scr_restore — Restabile?te ecranul dintr-un fi?ier salvat
  • ncurses_scr_set — Stabile?te con?inutul ecranului dintr-un fi?ier salvat
  • ncurses_scrl — Deplaseaza con?inutul ferestrei în sus sau în jos fara a modifica pozi?ia curenta
  • ncurses_show_panel — Plaseaza un panel invizibil în vârful stivei, facându-l vizibil
  • ncurses_slk_attr — Întoarce atributul curent al etichetelor soft ale tastelor
  • ncurses_slk_attroff — Deconecteaza atribute specificate pentru taste func?ionale cu etichete soft
  • ncurses_slk_attron — Conecteaza atribute specificate pentru taste func?ionale cu etichete soft
  • ncurses_slk_attrset — Stabile?te atribute specificate pentru taste func?ionale cu etichete soft
  • ncurses_slk_clear — Elimina etichetele soft de la ecran
  • ncurses_slk_color — Stabile?te culoarea pentru tastele cu eticheta soft
  • ncurses_slk_init — Ini?ializeaza taste func?ionale cu eticheta soft
  • ncurses_slk_noutrefresh — Copie cheile soft label pe ecranul virtual
  • ncurses_slk_refresh — Copie tastele etichetelor soft la ecran
  • ncurses_slk_restore — Restabile?te tastele cu etichete soft
  • ncurses_slk_set — Stabile?te etichetele tastelor func?ionale
  • ncurses_slk_touch — For?eaza afi?area când este efectuat ncurses_slk_noutrefresh
  • ncurses_standend — Stopeaza utilizarea atributului 'standout'
  • ncurses_standout — Începe utilizarea atributului 'standout'
  • ncurses_start_color — Ini?ializeaza func?ionalitatea culorilor
  • ncurses_termattrs — Întoarce un SAU logic al tuturor fanioanelor de atribute sus?inute de terminal
  • ncurses_termname — Întoarce denumirea scurta a terminalului
  • ncurses_timeout — Stabile?te timpul de expirare pentru secven?e speciale de taste
  • ncurses_top_panel — Deplaseaza un panel vizibil în vârful stivei
  • ncurses_typeahead — Specifica un descriptor de fi?ier diferit pentru verificarea typeahead
  • ncurses_ungetch — Plaseaza un caracter înapoi în fluxul de intrari
  • ncurses_ungetmouse — Plaseaza evenimentele ?oricelului în rând
  • ncurses_update_panels — Actualizeaza ecranul virtual pentru a reflecta rela?iile dintre panelurile din stiva
  • ncurses_use_default_colors — Atribuie culorile implicite ale terminalului culorii cu indicele -1
  • ncurses_use_env — Controleaza utilizarea informa?iilor de mediu despre dimensiunea terminalului
  • ncurses_use_extended_names — Controlezaa utilizarea denumirilor extinse în descrieri terminfo
  • ncurses_vidattr — Afi?eaza ?irul de caractere la terminal în modul video atribut
  • ncurses_vline — Deseneaza o linie verticala în pozi?ia curenta utilizând un caracter cu atribute, de o înal?ime maxima de n caractere
  • ncurses_waddch — Adauga un caracter în pozi?ia curenta din fereastra ?i avanseaza cursorul
  • ncurses_waddstr — Afi?eaza un text în pozi?ia curenta din fereastra
  • ncurses_wattroff — Deconecteaza atribute pentru o fereastra
  • ncurses_wattron — Conecteaza atribute pentru o fereastra
  • ncurses_wattrset — Stabile?te atribute pentru o fereastra
  • ncurses_wborder — Deseneaza o bordura în jurul ferestrei utilizând caractere cu atribute
  • ncurses_wclear — Cura?a fereastra
  • ncurses_wcolor_set — Stabile?te perechile de culori ale ferestrei
  • ncurses_werase — ?terge con?inutul ferestrei
  • ncurses_wgetch — Cite?te un caracter de la tastatura (fereastra)
  • ncurses_whline — Deseneaza o linie orizontala într-o fereastra în pozi?ia curenta utilizând un caracter cu atribute ?i o lungime maxima de n caractere
  • ncurses_wmouse_trafo — Transforma coordonate window/stdscr
  • ncurses_wmove — Deplaseaza pozi?ia de afi?are în fereastra
  • ncurses_wnoutrefresh — Copie fereastra în ecranul virtual
  • ncurses_wrefresh — Actualizeaza fereastra la ecranul terminalului
  • ncurses_wstandend — Încheie modul standout pentru o fereastra
  • ncurses_wstandout — Transfera o fererastra în mod standout
  • ncurses_wvline — Deseneaza o linie verticala într-o fereastra în pozi?ia curenta utilizând un caracter cu atribute, de o lungime maxima de n caractere
?oricel
ncurses_addch
Ncurses


Adauga caracterul în pozi?ia curenta ?i avanseaza cursorul

Func?ii Ncurses
ncurses_addchnstr
Func?ii Ncurses
PHP Manual

ncurses_addch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addch — Adauga caracterul în pozi?ia curenta ?i avanseaza cursorul

Descrierea

int ncurses_addch ( int $ch )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

ch

Func?ii Ncurses
ncurses_addchnstr
Func?ii Ncurses


Adauga ?irul de caractere cu atribute, cu lungimea specificata, în pozi?ia curenta

ncurses_addch
ncurses_addchstr
Func?ii Ncurses
PHP Manual

ncurses_addchnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchnstr — Adauga ?irul de caractere cu atribute, cu lungimea specificata, în pozi?ia curenta

Descrierea

int ncurses_addchnstr ( string $s , int $n )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

s

n

ncurses_addch
ncurses_addchstr
Func?ii Ncurses


Adauga ?irul de caractere cu atribute în pozi?ia curenta

ncurses_addchnstr
ncurses_addnstr
Func?ii Ncurses
PHP Manual

ncurses_addchstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchstr — Adauga ?irul de caractere cu atribute în pozi?ia curenta

Descrierea

int ncurses_addchstr ( string $s )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

s

ncurses_addchnstr
ncurses_addnstr
Func?ii Ncurses


Adauga ?irul de caractere cu lungimea specificata în pozi?ia curenta

ncurses_addchstr
ncurses_addstr
Func?ii Ncurses
PHP Manual

ncurses_addnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addnstr — Adauga ?irul de caractere cu lungimea specificata în pozi?ia curenta

Descrierea

int ncurses_addnstr ( string $s , int $n )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

s

n

ncurses_addchstr
ncurses_addstr
Func?ii Ncurses


Afi?eaza textul în pozi?ia curenta

ncurses_addnstr
ncurses_assume_default_colors
Func?ii Ncurses
PHP Manual

ncurses_addstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addstr — Afi?eaza textul în pozi?ia curenta

Descrierea

int ncurses_addstr ( string $text )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

text

ncurses_addnstr
ncurses_assume_default_colors
Func?ii Ncurses


Define?te culorile implicite pentru culoarea 0

ncurses_addstr
ncurses_attroff
Func?ii Ncurses
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?te culorile implicite pentru culoarea 0

Descrierea

int ncurses_assume_default_colors ( int $fg , int $bg )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

fg

bg

ncurses_addstr
ncurses_attroff
Func?ii Ncurses


Deconecteaza atributele date

ncurses_assume_default_colors
ncurses_attron
Func?ii Ncurses
PHP Manual

ncurses_attroff

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attroff — Deconecteaza atributele date

Descrierea

int ncurses_attroff ( int $attributes )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

attributes

ncurses_assume_default_colors
ncurses_attron
Func?ii Ncurses


Conecteaza atributele date

ncurses_attroff
ncurses_attrset
Func?ii Ncurses
PHP Manual

ncurses_attron

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attron — Conecteaza atributele date

Descrierea

int ncurses_attron ( int $attributes )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

attributes

ncurses_attroff
ncurses_attrset
Func?ii Ncurses


Stabile?te atributele date

ncurses_attron
ncurses_baudrate
Func?ii Ncurses
PHP Manual

ncurses_attrset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attrset — Stabile?te atributele date

Descrierea

int ncurses_attrset ( int $attributes )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

attributes

ncurses_attron
ncurses_baudrate
Func?ii Ncurses


Întoarce rata baud a terminalului

ncurses_attrset
ncurses_beep
Func?ii Ncurses
PHP Manual

ncurses_baudrate

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_baudrate — Întoarce rata baud a terminalului

Descrierea

int ncurses_baudrate ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_attrset
ncurses_beep
Func?ii Ncurses


Face ca terminalul sa emita un semnal sonor

ncurses_baudrate
ncurses_bkgd
Func?ii Ncurses
PHP Manual

ncurses_beep

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_beep — Face ca terminalul sa emita un semnal sonor

Descrierea

int ncurses_beep ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

ncurses_beep() transmite o alerta audibila (bell) ?i daca aceasta nu este posibil, sclipe?te ecranul.

A se vedea ?i

  • ncurses_flash() - Sclipe?te ecranul terminalului (clopo?el vizual)

ncurses_baudrate
ncurses_bkgd
Func?ii Ncurses


Stabile?te proprietatea fundalului pentru ecranul terminalului

ncurses_beep
ncurses_bkgdset
Func?ii Ncurses
PHP Manual

ncurses_bkgd

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgd — Stabile?te proprietatea fundalului pentru ecranul terminalului

Descrierea

int ncurses_bkgd ( int $attrchar )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

attrchar

ncurses_beep
ncurses_bkgdset
Func?ii Ncurses


Controleaza fundalul ecranului

ncurses_bkgd
ncurses_border
Func?ii Ncurses
PHP Manual

ncurses_bkgdset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgdset — Controleaza fundalul ecranului

Descrierea

void ncurses_bkgdset ( int $attrchar )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

attrchar

ncurses_bkgd
ncurses_border
Func?ii Ncurses


Deseneaza o bordura în jurul ecranului utilizând caractere cu atribute

ncurses_bkgdset
ncurses_bottom_panel
Func?ii Ncurses
PHP Manual

ncurses_border

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_border — Deseneaza o bordura în jurul ecranului utilizând caractere cu atribute

Descrierea

int ncurses_border ( int $left , int $right , int $top , int $bottom , int $tl_corner , int $tr_corner , int $bl_corner , int $br_corner )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Deseneaza liniile ?i col?urile specificate în jurul ferestrei principale.

Utiliza?i ncurses_wborder() pentru a desena borduri în jurul subferestrelor!

Parametri

Fiecare parametru a?teapta 0 pentru a desena linia, sau 1 pentru a sari peste ea.

left

right

top

bottom

tl_corner

Col?ul stânga-sus

tr_corner

Col?ul dreapta-sus

bl_corner

Col?ul stânga-jos

br_corner

Col?ul dreapta-jos

A se vedea ?i

  • ncurses_wborder() - Deseneaza o bordura în jurul ferestrei utilizând caractere cu atribute

ncurses_bkgdset
ncurses_bottom_panel
Func?ii Ncurses


Muta panelul vizibil la fundul stivei

ncurses_border
ncurses_can_change_color
Func?ii Ncurses
PHP Manual

ncurses_bottom_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bottom_panel — Muta panelul vizibil la fundul stivei

Descrierea

int ncurses_bottom_panel ( resource $panel )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

panel

ncurses_border
ncurses_can_change_color
Func?ii Ncurses


Verifica daca defini?iile culorilor terminalului pot fi schimbate

ncurses_bottom_panel
ncurses_cbreak
Func?ii Ncurses
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 — Verifica daca defini?iile culorilor terminalului pot fi schimbate

Descrierea

bool ncurses_can_change_color ( void )

Verifica daca terminalul are posibilita?i de afi?are a culorilor ?i daca programatorul poate modifica defini?iile culorilor utilizând ncurses_init_color(). ncurses trebuie sa fie ini?ializat utilizând ncurses_init() înainte de a apela aceasta func?ie.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce TRUE daca programatorul poate schimba defini?iile culorilor, sau FALSE în caz contrar.

A se vedea ?i

  • ncurses_has_colors() - Verifica daca terminalul are capacita?i de redare a culorilor
  • ncurses_init_color() - Define?te o culoare a terminalului
  • ncurses_start_color() - Ini?ializeaza func?ionalitatea culorilor

ncurses_bottom_panel
ncurses_cbreak
Func?ii Ncurses


Deconecteaza buferizarea intrarilor

ncurses_can_change_color
ncurses_clear
Func?ii Ncurses
PHP Manual

ncurses_cbreak

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_cbreak — Deconecteaza buferizarea intrarilor

Descrierea

bool ncurses_cbreak ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Deconecteaza buferizarea liniilor ?i procesarea caracterelor (caracterele de întrerupere ?i de control al fluxului nu sunt afectate), facând caracterele tapate de utilizator imediat disponibile programului.

Valorile întoarse

Întoarce TRUE sau NCURSES_ERR daca are loc o eroare.

A se vedea ?i

  • ncurses_nocbreak() - Schimba terminalul în mod cooked

ncurses_can_change_color
ncurses_clear
Func?ii Ncurses


Cura?a ecranul

ncurses_cbreak
ncurses_clrtobot
Func?ii Ncurses
PHP Manual

ncurses_clear

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clear — Cura?a ecranul

Descrierea

bool ncurses_clear ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Cura?a ecranul complet fara a stabili spa?iile libere.

Nota: ncurses_clear() cura?a ecranul fara a stabili spa?iile libere, care au afi?ajul fundalului curent. Pentru a cura?i ecranul cu spa?ii libere, utiliza?i ncurses_erase().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ncurses_erase() - Cura?a ecranul terminalului

ncurses_cbreak
ncurses_clrtobot
Func?ii Ncurses


Cura?a ecranul din pozi?ia curenta pâna jos

ncurses_clear
ncurses_clrtoeol
Func?ii Ncurses
PHP Manual

ncurses_clrtobot

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clrtobot — Cura?a ecranul din pozi?ia curenta pâna jos

Descrierea

bool ncurses_clrtobot ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

?terge toate liniile începând cu pozi?ia cursorului pâna la pozi?ia de jos a ecranului ?i creaza spa?ii libere. Spa?iile libere create cu ncurses_clrtobot() au afi?ajul fundalului curent.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ncurses_clear() - Cura?a ecranul
  • ncurses_clrtoeol() - Cura?a ecranul din pozi?ia curenta pâna la sfâr?itul liniei

ncurses_clear
ncurses_clrtoeol
Func?ii Ncurses


Cura?a ecranul din pozi?ia curenta pâna la sfâr?itul liniei

ncurses_clrtobot
ncurses_color_content
Func?ii Ncurses
PHP Manual

ncurses_clrtoeol

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clrtoeol — Cura?a ecranul din pozi?ia curenta pâna la sfâr?itul liniei

Descrierea

bool ncurses_clrtoeol ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Elimina linia curenta de la pozi?ia cursorului, pâna la sfâr?it. Spa?iile libere create de ncurses_clrtoeol() au afi?ajul fundalului curent.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ncurses_clear() - Cura?a ecranul
  • ncurses_clrtobot() - Cura?a ecranul din pozi?ia curenta pâna jos

ncurses_clrtobot
ncurses_color_content
Func?ii Ncurses


Ob?ine componentele RGB ale culorii

ncurses_clrtoeol
ncurses_color_set
Func?ii Ncurses
PHP Manual

ncurses_color_content

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_color_content — Ob?ine componentele RGB ale culorii

Descrierea

int ncurses_color_content ( int $color , int &$r , int &$g , int &$b )

Ob?ine componentele ro?u, verde, albastru ale defini?iei curente a culorii. Capacita?ile de culoare ale terminalului trebuie sa fie ini?ializate cu ncurses_start_color() înainte de a apela aceasta func?ie.

Parametri

color

Numarul culorii pentru care se va ob?ine informa?ia. Poate fi una din constantele de culoare predefinite.

r

O referin?a în care va fi întoarsa componenta ro?ie a culorii. Valoarea întoarsa referin?ei va fi între 0 ?i 1000.

g

O referin?a în care va fi întoarsa componenta verde a culorii. Valoarea întoarsa referin?ei va fi între 0 ?i 1000.

b

O referin?a în care va fi întoarsa componenta albastra a culorii. Valoarea întoarsa referin?ei va fi între 0 ?i 1000.

Valorile întoarse

Întoarce -1 daca func?ia s-a executat cu succes, ?i 0 daca ncurses sau capacita?ile de culori ale terminalului nu au fost ini?ializate.

A se vedea ?i

  • ncurses_init_color() - Define?te o culoare a terminalului
  • ncurses_start_color() - Ini?ializeaza func?ionalitatea culorilor

ncurses_clrtoeol
ncurses_color_set
Func?ii Ncurses


Stabile?te culorile de prim plan ?i de fundal active

ncurses_color_content
ncurses_curs_set
Func?ii Ncurses
PHP Manual

ncurses_color_set

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_color_set — Stabile?te culorile de prim plan ?i de fundal active

Descrierea

int ncurses_color_set ( int $pair )

Stabile?te culorile de prim plan ?i de fundal active. Orice caracter afi?at dupa invocarea acestei func?ii va avea aceste culori. Aceasta func?ie necesita ca culorile sa fie sus?inute de terminal ?i sa fie ini?ializate anterior cu ncurses_start_color().

ncurses utilizeaza perechi de culori pentru a specifica culorile de prim plan ?i fundal. Utiliza?i ncurses_init_pair() pentru a defini o pereche de culori.

Parametri

pair

Perechea de culori din care se ob?in culorile de prim plan ?i de fundal pentru a fi stabilite ca culori active.

Valorile întoarse

Întoarce -1 în caz de succes, ?i 0 în caz de e?ec.

Exemple

Example #1 Afi?area la ecran a unui ?ir de caractere cu o culoare specificata

<?php
ncurses_init();

// Daca terminalul sus?ine culori, ini?ializeaza ?i stabile?te culoarea activa
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Afi?eaza un ?ir de caractere în loca?ia specificata
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Transmite ie?irea la ecran
ncurses_refresh();

ncurses_end();
?>

A se vedea ?i

  • ncurses_init_pair() - Define?te o pereche de culori
  • ncurses_start_color() - Ini?ializeaza func?ionalitatea culorilor

ncurses_color_content
ncurses_curs_set
Func?ii Ncurses


Stabile?te starea cursorului

ncurses_color_set
ncurses_def_prog_mode
Func?ii Ncurses
PHP Manual

ncurses_curs_set

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_curs_set — Stabile?te starea cursorului

Descrierea

int ncurses_curs_set ( int $visibility )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

visibility

ncurses_color_set
ncurses_def_prog_mode
Func?ii Ncurses


Salveaza modul terminalului (pentru program)

ncurses_curs_set
ncurses_def_shell_mode
Func?ii Ncurses
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 — Salveaza modul terminalului (pentru program)

Descrierea

bool ncurses_def_prog_mode ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Salveaza modurile curente ale terminalului pentru program (în curses) pentru a fi utilizate de ncurses_reset_prog_mode().

Valorile întoarse

Întoarce FALSE în caz de succes, TRUE în caz contrar.

A se vedea ?i

  • ncurses_reset_prog_mode() - Reseteaza modul programului salvat cu def_prog_mode

ncurses_curs_set
ncurses_def_shell_mode
Func?ii Ncurses


Salveaza modul terminalului (pentru înveli?)

ncurses_def_prog_mode
ncurses_define_key
Func?ii Ncurses
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 — Salveaza modul terminalului (pentru înveli?)

Descrierea

bool ncurses_def_shell_mode ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Salveaza modurile curente ale terminalului pentru înveli? (nu în curses) pentru a fi utilizate de ncurses_reset_shell_mode().

Valorile întoarse

Întoarce FALSE în caz de succes, TRUE în caz contrar.

A se vedea ?i

  • ncurses_reset_shell_mode() - Reseteaza modul înveli?ului salvat cu def_shell_mode

ncurses_def_prog_mode
ncurses_define_key
Func?ii Ncurses


Define?te un cod de cheie

ncurses_def_shell_mode
ncurses_del_panel
Func?ii Ncurses
PHP Manual

ncurses_define_key

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_define_key — Define?te un cod de cheie

Descrierea

int ncurses_define_key ( string $definition , int $keycode )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

definition

keycode

ncurses_def_shell_mode
ncurses_del_panel
Func?ii Ncurses


Extrage panelul din stiva ?i îl elimina (dar nu ?i fereastra asociata)

ncurses_define_key
ncurses_delay_output
Func?ii Ncurses
PHP Manual

ncurses_del_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_del_panel — Extrage panelul din stiva ?i îl elimina (dar nu ?i fereastra asociata)

Descrierea

bool ncurses_del_panel ( resource $panel )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

panel

ncurses_define_key
ncurses_delay_output
Func?ii Ncurses


Încetine?te afi?area la terminal utilizând caractere de umplutura

ncurses_del_panel
ncurses_delch
Func?ii Ncurses
PHP Manual

ncurses_delay_output

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delay_output — Încetine?te afi?area la terminal utilizând caractere de umplutura

Descrierea

int ncurses_delay_output ( int $milliseconds )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

milliseconds

ncurses_del_panel
ncurses_delch
Func?ii Ncurses


Elimina caracterul de la pozi?ia curenta, deplaseaza restul liniei în stânga

ncurses_delay_output
ncurses_deleteln
Func?ii Ncurses
PHP Manual

ncurses_delch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delch — Elimina caracterul de la pozi?ia curenta, deplaseaza restul liniei în stânga

Descrierea

bool ncurses_delch ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Elimina caracterul de la pozi?ia cursorului. Toate caracterele din dreapta cursorului, de pe aceea?i linie, vor fi deplasate în stânga cu o pozi?ie, iar ultimul caracter de pe linie este înlocuit cu un caracter vid. Pozi?ia cursorului nu se schimba.

Valorile întoarse

Întoarce FALSE în caz de succes, TRUE în caz contrar.

A se vedea ?i

  • ncurses_deleteln() - Elimina linia de la pozi?ia curenta, deplaseaza restul ecranului în sus

ncurses_delay_output
ncurses_deleteln
Func?ii Ncurses


Elimina linia de la pozi?ia curenta, deplaseaza restul ecranului în sus

ncurses_delch
ncurses_delwin
Func?ii Ncurses
PHP Manual

ncurses_deleteln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_deleteln — Elimina linia de la pozi?ia curenta, deplaseaza restul ecranului în sus

Descrierea

bool ncurses_deleteln ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Elimina linia curenta de la pozi?ia cursorului. Toate liniile ce se afla mai jos de linia curenta sunt deplasate cu o linie în sus. Linia cea mai de jos este cura?ata. Pozi?ia cursorului nu se schimba.

Valorile întoarse

Întoarce FALSE în caz de succes, TRUE în caz contrar.

A se vedea ?i

  • ncurses_delch() - Elimina caracterul de la pozi?ia curenta, deplaseaza restul liniei în stânga

ncurses_delch
ncurses_delwin
Func?ii Ncurses


Elimina o fereastra ncurses

ncurses_deleteln
ncurses_doupdate
Func?ii Ncurses
PHP Manual

ncurses_delwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delwin — Elimina o fereastra ncurses

Descrierea

bool ncurses_delwin ( resource $window )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

ncurses_deleteln
ncurses_doupdate
Func?ii Ncurses


Înscrie în terminal toate actualizarile pregatite

ncurses_delwin
ncurses_echo
Func?ii Ncurses
PHP Manual

ncurses_doupdate

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_doupdate — Înscrie în terminal toate actualizarile pregatite

Descrierea

bool ncurses_doupdate ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Compara ecranul virtual cu cel fizic ?i actualizeaza ecranul fizic. Acest mod e mai eficient decât utilizarea mai multor apeluri de actualizare.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ncurses_delwin
ncurses_echo
Func?ii Ncurses


Activeaza afi?area la ecran a intrarilor de la tastatura

ncurses_doupdate
ncurses_echochar
Func?ii Ncurses
PHP Manual

ncurses_echo

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_echo — Activeaza afi?area la ecran a intrarilor de la tastatura

Descrierea

bool ncurses_echo ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Activeaza modul ecou. Toate caracterele tastate de utilizator sunt afi?ate la ecran la utilizarea ncurses_getch().

Valorile întoarse

Întoarce FALSE în caz de succes, TRUE daca are loc o eroare.

A se vedea ?i

  • ncurses_noecho() - Deconecteaza afi?area la ecran a tastelor apasate pentru a dezactiva modul ecou

ncurses_doupdate
ncurses_echochar
Func?ii Ncurses


Afi?area unui singur caracter, inclusiv actualizarea

ncurses_echo
ncurses_end
Func?ii Ncurses
PHP Manual

ncurses_echochar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_echochar — Afi?area unui singur caracter, inclusiv actualizarea

Descrierea

int ncurses_echochar ( int $character )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

character

ncurses_echo
ncurses_end
Func?ii Ncurses


Opre?te utilizarea ncurses, cura?a ecranul

ncurses_echochar
ncurses_erase
Func?ii Ncurses
PHP Manual

ncurses_end

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_end — Opre?te utilizarea ncurses, cura?a ecranul

Descrierea

int ncurses_end ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_echochar
ncurses_erase
Func?ii Ncurses


Cura?a ecranul terminalului

ncurses_end
ncurses_erasechar
Func?ii Ncurses
PHP Manual

ncurses_erase

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_erase — Cura?a ecranul terminalului

Descrierea

bool ncurses_erase ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Umple ecranul terminalului cu spa?ii vide.

Spa?iile vide create sunt afi?ate cu culoarea de fundal curenta, stabilita cu ncurses_bkgd().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ncurses_bkgd() - Stabile?te proprietatea fundalului pentru ecranul terminalului
  • ncurses_clear() - Cura?a ecranul

ncurses_end
ncurses_erasechar
Func?ii Ncurses


Întoarce caracterul de eliminare curent

ncurses_erase
ncurses_filter
Func?ii Ncurses
PHP Manual

ncurses_erasechar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_erasechar — Întoarce caracterul de eliminare curent

Descrierea

string ncurses_erasechar ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Întoarce caracterul de eliminare curent.

Valorile întoarse

Caracterul de eliminare curent (?irul de caractere).

A se vedea ?i

  • ncurses_killchar() - Întoarce caracterul curent de eliminare a liniei

ncurses_erase
ncurses_filter
Func?ii Ncurses


Stabile?te LINES pentru iniscr() ?i newterm() în 1

ncurses_erasechar
ncurses_flash
Func?ii Ncurses
PHP Manual

ncurses_filter

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_filter — Stabile?te LINES pentru iniscr() ?i newterm() în 1

Descrierea

void ncurses_filter ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_erasechar
ncurses_flash
Func?ii Ncurses


Sclipe?te ecranul terminalului (clopo?el vizual)

ncurses_filter
ncurses_flushinp
Func?ii Ncurses
PHP Manual

ncurses_flash

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_flash — Sclipe?te ecranul terminalului (clopo?el vizual)

Descrierea

bool ncurses_flash ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Sclipe?te ecranul, iar daca aceasta nu este posibil, transmite un semnal audibil (clopo?el).

Valorile întoarse

Întoarce FALSE în caz de success, TRUE în caz contrar.

A se vedea ?i

  • ncurses_beep() - Face ca terminalul sa emita un semnal sonor

ncurses_filter
ncurses_flushinp
Func?ii Ncurses


Gole?te zona-tampon a intrarilor de la tastatura

ncurses_flash
ncurses_getch
Func?ii Ncurses
PHP Manual

ncurses_flushinp

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_flushinp — Gole?te zona-tampon a intrarilor de la tastatura

Descrierea

bool ncurses_flushinp ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Arunca orice a fost tapat ?i înca nu a fost citit de programul dumneavoastra.

Valorile întoarse

Întoarce FALSE în caz de succes, TRUE în caz contrar.

ncurses_flash
ncurses_getch
Func?ii Ncurses


Cite?te un caracter de la tastaura

ncurses_flushinp
ncurses_getmaxyx
Func?ii Ncurses
PHP Manual

ncurses_getch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getch — Cite?te un caracter de la tastaura

Descrierea

int ncurses_getch ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_flushinp
ncurses_getmaxyx
Func?ii Ncurses


Întoarce marimea unei ferestre

ncurses_getch
ncurses_getmouse
Func?ii Ncurses
PHP Manual

ncurses_getmaxyx

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getmaxyx — Întoarce marimea unei ferestre

Descrierea

void ncurses_getmaxyx ( resource $window , int &$y , int &$x )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Ob?ine marimile orizontala ?i verticala ale ferestrei specificate în window ?i le înscrie în variabilele date.

Variabilele trebuie sa fie transmise prin referin?a, astfel ca ele sa fie actualizate când utilizatorul modifica marimea terminalului.

Parametri

window

Fereastra masurata

y

În aceasta variabila se va înscrie înal?imea ferestrei

x

În aceasta variabila se va înscrie la?imea ferestrei

Valorile întoarse

Nu este întoarsa nici o valoare.

ncurses_getch
ncurses_getmouse
Func?ii Ncurses


Cite?te evenimentul ?oricelului

ncurses_getmaxyx
ncurses_getyx
Func?ii Ncurses
PHP Manual

ncurses_getmouse

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getmouse — Cite?te evenimentul ?oricelului

Descrierea

bool ncurses_getmouse ( array &$mevent )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

ncurses_getmouse() cite?te evenimentul ?oricelului din rândul de evenimente.

Parametri

mevent

Op?iunile evenimentului vor fi înscrise în acest parametru, care trebuie sa fie un tablou transmis prin referin?a (a se vedea exemplul de mai jos).

În caz de succes, va fi transmis un tablou asociativ cu urmatoarele chei:

  • "id" : un identificator pentru a deosebi dispozitive multiple

  • "x" : pozi?ia relativa a ecranului pe axa x în celule de caractere

  • "y" : pozi?ia relativa a ecranului pe axa y în celule de caractere

  • "z" : în prezent nu este sus?inut

  • "mmask" : ac?iunea ?oricelului

Valorile întoarse

Întoarce FALSE daca un eveniment de la ?oricel este într-adevar vizibil în fereastra data, TRUE în caz contrar.

Exemple

Example #1 Exemplu ncurses_getmouse()

<?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:
    /* .... */
}
?>

A se vedea ?i

  • ncurses_ungetmouse() - Plaseaza evenimentele ?oricelului în rând

ncurses_getmaxyx
ncurses_getyx
Func?ii Ncurses


Întoarce pozi?ia curenta a cursorului într-o fereastra

ncurses_getmouse
ncurses_halfdelay
Func?ii Ncurses
PHP Manual

ncurses_getyx

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getyx — Întoarce pozi?ia curenta a cursorului într-o fereastra

Descrierea

void ncurses_getyx ( resource $window , int &$y , int &$x )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

y

x

ncurses_getmouse
ncurses_halfdelay
Func?ii Ncurses


Stabile?te terminalul în mod semipauza

ncurses_getyx
ncurses_has_colors
Func?ii Ncurses
PHP Manual

ncurses_halfdelay

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_halfdelay — Stabile?te terminalul în mod semipauza

Descrierea

int ncurses_halfdelay ( int $tenth )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

tenth

ncurses_getyx
ncurses_has_colors
Func?ii Ncurses


Verifica daca terminalul are capacita?i de redare a culorilor

ncurses_halfdelay
ncurses_has_ic
Func?ii Ncurses
PHP Manual

ncurses_has_colors

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_colors — Verifica daca terminalul are capacita?i de redare a culorilor

Descrierea

bool ncurses_has_colors ( void )

Verifica daca terminalul are capacita?i de redare a culorilor. Aceasta func?ie poate fi utilizata pentru a scrie programe independente de terminal. ncurses trebuie sa fie ini?ializat cu ncurses_init() înainte de a apela aceasta func?ie.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce TRUE daca terminalul are capacita?i de redare a culorilor, FALSE în caz contrar.

Exemple

Example #1 Afi?area la ecran a unui ?ir de caractere cu o culoare specificata

<?php
ncurses_init();

// Daca terminalul sus?ine culori, ini?ializeaza ?i stabile?te culoarea activa
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Afi?eaza un ?ir de caractere în pozi?ia specificata
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Transmite afi?ajul la ecran
ncurses_refresh();

ncurses_end();
?>

A se vedea ?i

  • ncurses_can_change_color() - Verifica daca defini?iile culorilor terminalului pot fi schimbate
  • ncurses_start_color() - Ini?ializeaza func?ionalitatea culorilor

ncurses_halfdelay
ncurses_has_ic
Func?ii Ncurses


Verifica capacita?ile de inserare ?i eliminare

ncurses_has_colors
ncurses_has_il
Func?ii Ncurses
PHP Manual

ncurses_has_ic

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_ic — Verifica capacita?ile de inserare ?i eliminare

Descrierea

bool ncurses_has_ic ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Verifica daca terminalul are capacita?i de inserare ?i eliminare.

Valorile întoarse

Întoarce TRUE daca terminalul poseda capacita?i de inserare / eliminare, FALSE în caz contrar.

A se vedea ?i

  • ncurses_has_il() - Verifica capacita?ile de inserare ?i eliminare a liniilor

ncurses_has_colors
ncurses_has_il
Func?ii Ncurses


Verifica capacita?ile de inserare ?i eliminare a liniilor

ncurses_has_ic
ncurses_has_key
Func?ii Ncurses
PHP Manual

ncurses_has_il

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_il — Verifica capacita?ile de inserare ?i eliminare a liniilor

Descrierea

bool ncurses_has_il ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Verifica daca terminalul poseda capacita?i de inserare ?i eliminare a liniilor.

Valorile întoarse

Întoarce TRUE daca terminalul poseda capacita?i de inserare / eliminare a liniilor, FALSE în caz contrar.

A se vedea ?i

  • ncurses_has_ic() - Verifica capacita?ile de inserare ?i eliminare

ncurses_has_ic
ncurses_has_key
Func?ii Ncurses


Verifica prezen?a unei taste func?ionale pe tastatura terminalului

ncurses_has_il
ncurses_hide_panel
Func?ii Ncurses
PHP Manual

ncurses_has_key

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_key — Verifica prezen?a unei taste func?ionale pe tastatura terminalului

Descrierea

int ncurses_has_key ( int $keycode )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

keycode

ncurses_has_il
ncurses_hide_panel
Func?ii Ncurses


Elimina panelul din stiva, facându-l invizibil

ncurses_has_key
ncurses_hline
Func?ii Ncurses
PHP Manual

ncurses_hide_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_hide_panel — Elimina panelul din stiva, facându-l invizibil

Descrierea

int ncurses_hide_panel ( resource $panel )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

panel

ncurses_has_key
ncurses_hline
Func?ii Ncurses


Deseneaza o linie orizontala în pozi?ia curenta folosind un caracter atribuit ?i o lungime de maximum n caractere

ncurses_hide_panel
ncurses_inch
Func?ii Ncurses
PHP Manual

ncurses_hline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_hline — Deseneaza o linie orizontala în pozi?ia curenta folosind un caracter atribuit ?i o lungime de maximum n caractere

Descrierea

int ncurses_hline ( int $charattr , int $n )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

charattr

n

ncurses_hide_panel
ncurses_inch
Func?ii Ncurses


Ob?ine caracterul ?i atributul de la pozi?ia curenta

ncurses_hline
ncurses_init_color
Func?ii Ncurses
PHP Manual

ncurses_inch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_inch — Ob?ine caracterul ?i atributul de la pozi?ia curenta

Descrierea

string ncurses_inch ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Întoarce caracterul de la pozi?ia curenta.

Valorile întoarse

Întoarce caracterul (ca string).

ncurses_hline
ncurses_init_color
Func?ii Ncurses


Define?te o culoare a terminalului

ncurses_inch
ncurses_init_pair
Func?ii Ncurses
PHP Manual

ncurses_init_color

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init_color — Define?te o culoare a terminalului

Descrierea

int ncurses_init_color ( int $color , int $r , int $g , int $b )

Define?te sau redefine?te o anumita culoare. Când aceasta func?ie este apelata, toate apari?iile de pe ecran ale culorii date, daca sunt, se schimba imediat conform noii defini?ii.

Capacita?ile de redare ale culorilor trebuie sa fie sus?inute de terminal ?i trebuie sa fie ini?ializate cu ncurses_start_color() înainte de apelarea acestei func?ii. În plus, terminalul trebuie sa posede capacita?i de schimbare a culorilor; utiliza?i ncurses_can_change_color() pentru a verifica aceasta.

Parametri

color

Numarul de identificare a culorii spre a fi redefinita. Poate fi ?i una din constantele implicite ale culorilor.

r

Valoarea componentei ro?ii a culorii, între 0 ?i 1000.

g

Valoarea componentei verzi a culorii, între 0 ?i 1000.

b

Valoarea componentei albastre a culorii, între 0 ?i 1000.

Valorile întoarse

Întoarce -1 daca func?ia s-a executat cu succes ?i 0 daca ncurses sau capacita?ile de redare ale culorilor nu au fost ini?ializate, sau daca terminalul nu poseda capacita?i de schimbare a culorilor.

A se vedea ?i

  • ncurses_color_content() - Ob?ine componentele RGB ale culorii
  • ncurses_start_color() - Ini?ializeaza func?ionalitatea culorilor

ncurses_inch
ncurses_init_pair
Func?ii Ncurses


Define?te o pereche de culori

ncurses_init_color
ncurses_init
Func?ii Ncurses
PHP Manual

ncurses_init_pair

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init_pair — Define?te o pereche de culori

Descrierea

int ncurses_init_pair ( int $pair , int $fg , int $bg )

Define?te sau redefine?te perechea data de culori cu valori noi pentru culoarea de prim plan ?i de fundal. Daca perechea de culori a fost ini?ializata anterior, ecranul este actualizat ?i toate apari?iile ei sunt modificate pentru a reflecta defini?ia noua.

Capacita?ile de redare a culorilor trebuie sa fie ini?ializate cu ncurses_start_color() înainte de a apela aceasta func?ie. Prima pereche de culori (perechea de culori 0) se presupune a fi implicit alb pe fundal negru, dar poate fi schimbata utilizând ncurses_assume_default_colors().

Parametri

pair

Numarul perechii de culori spre a fi definita.

fg

Culoarea de prim plan pentru perechea de culori. Poate fi una din culorile predefinite sau una definita de ncurses_init_color() daca terminalul poseda capacita?i de schimbare a culorilor.

bg

Culoarea de fundal pentru perechea de culori. Poate fi una din culorile predefinite sau una definita de ncurses_init_color() daca terminalul poseda capacita?i de schimbare a culorilor.

Valorile întoarse

Întoarce -1 daca func?ia s-a executat cu succes, ?i 0 daca ncurses sau sus?inerea culorilor nu a fost ini?ializata.

Note

Observa?i ca capacita?ile de schimbare a culorilor nu sunt necesare pentru definirea perechilor atunci când se folosesc culori pre-existente, dar numai pentru modificarea defini?iilor (componentele ro?u, verde, albastru) ale culorilor înse?i cu ncurses_init_color().

Exemple

Example #1 Afi?area la ecran a unui ?ir de caractere cu o culoare specificata

<?php
ncurses_init();

// Daca terminalul sus?ine culor, ini?ializeaza ?i stabile?te culoarea activa
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Afi?eaza un ?ir de caractere în pozi?ia specificata
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Transmite afi?ajul la ecran
ncurses_refresh();

ncurses_end();
?>

A se vedea ?i

  • ncurses_pair_content() - Ob?ine culorile de prim plan ?i de fundal ale unei perechi de culori
  • ncurses_start_color() - Ini?ializeaza func?ionalitatea culorilor

ncurses_init_color
ncurses_init
Func?ii Ncurses


Ini?ializeaza ncurses

ncurses_init_pair
ncurses_insch
Func?ii Ncurses
PHP Manual

ncurses_init

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init — Ini?ializeaza ncurses

Descrierea

void ncurses_init ( void )

Ini?ializeaza interfa?a ncurses. Aceasta func?ie trebuie sa fie utilizata înainte de apelarea oricarei alte func?ii ncurses.

Atrage?i aten?ia ca ncurses_end() trebuie apelata înainte de a ie?i din program, în caz contrar terminalul nu va fi restabilit în modul sau corect non-vizual.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • ncurses_end() - Opre?te utilizarea ncurses, cura?a ecranul

ncurses_init_pair
ncurses_insch
Func?ii Ncurses


Insereaza un caracter deplasând restul liniei, inclusiv caracterul din pozi?ia curenta

ncurses_init
ncurses_insdelln
Func?ii Ncurses
PHP Manual

ncurses_insch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insch — Insereaza un caracter deplasând restul liniei, inclusiv caracterul din pozi?ia curenta

Descrierea

int ncurses_insch ( int $character )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

character

ncurses_init
ncurses_insdelln
Func?ii Ncurses


Insereaza linii înainte de linia curenta ?i deplaseaza afi?ajul în jos (numerele negative elimina ?i deplaseaza afi?ajul în sus)

ncurses_insch
ncurses_insertln
Func?ii Ncurses
PHP Manual

ncurses_insdelln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insdelln — Insereaza linii înainte de linia curenta ?i deplaseaza afi?ajul în jos (numerele negative elimina ?i deplaseaza afi?ajul în sus)

Descrierea

int ncurses_insdelln ( int $count )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

count

ncurses_insch
ncurses_insertln
Func?ii Ncurses


Insereaza o linie, deplaseaza restul ecranului în jos

ncurses_insdelln
ncurses_insstr
Func?ii Ncurses
PHP Manual

ncurses_insertln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insertln — Insereaza o linie, deplaseaza restul ecranului în jos

Descrierea

int ncurses_insertln ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Insereaza o linie noua de asupra liniei curente. Linia cea mai de jos va fi pierduta.

ncurses_insdelln
ncurses_insstr
Func?ii Ncurses


Insereaza un ?ir de caractere în pozi?ia curenta, deplasând restul liniei în dreapta

ncurses_insertln
ncurses_instr
Func?ii Ncurses
PHP Manual

ncurses_insstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insstr — Insereaza un ?ir de caractere în pozi?ia curenta, deplasând restul liniei în dreapta

Descrierea

int ncurses_insstr ( string $text )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

text

ncurses_insertln
ncurses_instr
Func?ii Ncurses


Cite?te un ?ir de caractere de la ecranul terminalului

ncurses_insstr
ncurses_isendwin
Func?ii Ncurses
PHP Manual

ncurses_instr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_instr — Cite?te un ?ir de caractere de la ecranul terminalului

Descrierea

int ncurses_instr ( string &$buffer )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Cite?te un ?ir de caractere de la ecranul terminalului ?i întoarce numarul caracterelor citite de la caracterul curent pâna la sfâr?itul liniei.

Parametri

buffer

Caracterele. Atributele vor fi eliminate.

Valorile întoarse

Întoarce numarul de caractere.

ncurses_insstr
ncurses_isendwin
Func?ii Ncurses


Ncurses este în mod endwin, pot fi efectuate afi?ari normale la ecran

ncurses_instr
ncurses_keyok
Func?ii Ncurses
PHP Manual

ncurses_isendwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_isendwin — Ncurses este în mod endwin, pot fi efectuate afi?ari normale la ecran

Descrierea

bool ncurses_isendwin ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Verifica daca ncurses este în mod endwin.

Valorile întoarse

Întoarce TRUE, daca ncurses_end() a fost apelat fara alte apeluri ulterioare la ncurses_wrefresh(), FALSE în caz contrar.

A se vedea ?i

  • ncurses_end() - Opre?te utilizarea ncurses, cura?a ecranul
  • ncurses_wrefresh() - Actualizeaza fereastra la ecranul terminalului

ncurses_instr
ncurses_keyok
Func?ii Ncurses


Activeaza sau dezactiveaza un cod al tastei

ncurses_isendwin
ncurses_keypad
Func?ii Ncurses
PHP Manual

ncurses_keyok

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_keyok — Activeaza sau dezactiveaza un cod al tastei

Descrierea

int ncurses_keyok ( int $keycode , bool $enable )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

keycode

enable

ncurses_isendwin
ncurses_keypad
Func?ii Ncurses


Conecteaza sau deconecteaza tastatura numerica

ncurses_keyok
ncurses_killchar
Func?ii Ncurses
PHP Manual

ncurses_keypad

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_keypad — Conecteaza sau deconecteaza tastatura numerica

Descrierea

int ncurses_keypad ( resource $window , bool $bf )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

bf

ncurses_keyok
ncurses_killchar
Func?ii Ncurses


Întoarce caracterul curent de eliminare a liniei

ncurses_keypad
ncurses_longname
Func?ii Ncurses
PHP Manual

ncurses_killchar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_killchar — Întoarce caracterul curent de eliminare a liniei

Descrierea

string ncurses_killchar ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Întoarce caracterul curent de eliminare a liniei.

Valorile întoarse

Întoarce caracterul de eliminare (?ir de caractere).

A se vedea ?i

  • ncurses_erasechar() - Întoarce caracterul de eliminare curent

ncurses_keypad
ncurses_longname
Func?ii Ncurses


Întoarce descrierea terminalului

ncurses_killchar
ncurses_meta
Func?ii Ncurses
PHP Manual

ncurses_longname

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_longname — Întoarce descrierea terminalului

Descrierea

string ncurses_longname ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Întoarce o descriere pe lung a terminalului.

Valorile întoarse

Întoarce descrierea, ca ?ir de caractere, trunchiata la 128 caractere. În caz de erori întoarce NULL.

A se vedea ?i

  • ncurses_termname() - Întoarce denumirea scurta a terminalului

ncurses_killchar
ncurses_meta
Func?ii Ncurses


Activeaza / Dezactiveaza informa?iile de 8 bi?i despre meta chei

ncurses_longname
ncurses_mouse_trafo
Func?ii Ncurses
PHP Manual

ncurses_meta

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_meta — Activeaza / Dezactiveaza informa?iile de 8 bi?i despre meta chei

Descrierea

int ncurses_meta ( resource $window , bool $8bit )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

8bit

ncurses_longname
ncurses_mouse_trafo
Func?ii Ncurses


Transforma coordonate

ncurses_meta
ncurses_mouseinterval
Func?ii Ncurses
PHP Manual

ncurses_mouse_trafo

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mouse_trafo — Transforma coordonate

Descrierea

bool ncurses_mouse_trafo ( int &$y , int &$x , bool $toscreen )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

y

x

toscreen

ncurses_meta
ncurses_mouseinterval
Func?ii Ncurses


Stabile?te timpul de expirare pentru apasarile butoanelor ?oricelului

ncurses_mouse_trafo
ncurses_mousemask
Func?ii Ncurses
PHP Manual

ncurses_mouseinterval

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mouseinterval — Stabile?te timpul de expirare pentru apasarile butoanelor ?oricelului

Descrierea

int ncurses_mouseinterval ( int $milliseconds )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

milliseconds

ncurses_mouse_trafo
ncurses_mousemask
Func?ii Ncurses


Stabile?te op?iunile ?oricelului

ncurses_mouseinterval
ncurses_move_panel
Func?ii Ncurses
PHP Manual

ncurses_mousemask

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mousemask — Stabile?te op?iunile ?oricelului

Descrierea

int ncurses_mousemask ( int $newmask , int &$oldmask )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Stabile?te evenimentele ?oricelului ce vor fi raportate. Implicit nici un eveniment al ?oricelului nu va fi raportat.

Evenimentele ?oricelului sunt reprezentate de NCURSES_KEY_MOUSE în fluxul de intrare al ncurses_wgetch(). Pentru a citi datele evenimentului ?i a extrage evenimentul din rând, apela?i ncurses_getmouse().

Parametri

newmask

Op?iunile de mascare ale evenimentului ?oricelului pot fi stabilite cu urmatoarele constante predefinite:

  • 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

Ca un efect secundar, stabilirea valorii zero în newmask deconecteaza indicatorul ?oricelului. Stabilirea unai valori diferite de zero activeaza indicatorul ?oricelului.

oldmask

Aceasta va fi stabilita la valoarea precedenta a ma?tii evenimentului ?oricelului.

Valorile întoarse

Întoarce masca evenimentelor ce pot fi raportate. În caz de e?ec total întoarce 0.

Exemple

Example #1 Exemplu ncurses_mousemask()

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

A se vedea ?i

  • ncurses_getch() - Cite?te un caracter de la tastaura
  • ncurses_getmouse() - Cite?te evenimentul ?oricelului
  • ncurses_ungetmouse() - Plaseaza evenimentele ?oricelului în rând

ncurses_mouseinterval
ncurses_move_panel
Func?ii Ncurses


Deplaseaza un panel astfel încât col?ul stânga-sus sa fie în pozi?ia [startx, starty]

ncurses_mousemask
ncurses_move
Func?ii Ncurses
PHP Manual

ncurses_move_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_move_panel — Deplaseaza un panel astfel încât col?ul stânga-sus sa fie în pozi?ia [startx, starty]

Descrierea

int ncurses_move_panel ( resource $panel , int $startx , int $starty )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

panel

startx

starty

ncurses_mousemask
ncurses_move
Func?ii Ncurses


Deplaseaza pozi?ia de afi?are

ncurses_move_panel
ncurses_mvaddch
Func?ii Ncurses
PHP Manual

ncurses_move

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_move — Deplaseaza pozi?ia de afi?are

Descrierea

int ncurses_move ( int $y , int $x )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

y

x

ncurses_move_panel
ncurses_mvaddch
Func?ii Ncurses


Deplaseaza pozi?ia curenta ?i adauga un caracter

ncurses_move
ncurses_mvaddchnstr
Func?ii Ncurses
PHP Manual

ncurses_mvaddch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddch — Deplaseaza pozi?ia curenta ?i adauga un caracter

Descrierea

int ncurses_mvaddch ( int $y , int $x , int $c )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

y

x

c

ncurses_move
ncurses_mvaddchnstr
Func?ii Ncurses


Deplaseaza pozi?ia ?i adauga ?irul de caractere cu atribute de lungime specificata

ncurses_mvaddch
ncurses_mvaddchstr
Func?ii Ncurses
PHP Manual

ncurses_mvaddchnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddchnstr — Deplaseaza pozi?ia ?i adauga ?irul de caractere cu atribute de lungime specificata

Descrierea

int ncurses_mvaddchnstr ( int $y , int $x , string $s , int $n )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

y

x

s

n

ncurses_mvaddch
ncurses_mvaddchstr
Func?ii Ncurses


Deplaseaza pozi?ia ?i adauga un ?ir de caractere cu atribute

ncurses_mvaddchnstr
ncurses_mvaddnstr
Func?ii Ncurses
PHP Manual

ncurses_mvaddchstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddchstr — Deplaseaza pozi?ia ?i adauga un ?ir de caractere cu atribute

Descrierea

int ncurses_mvaddchstr ( int $y , int $x , string $s )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

y

x

s

ncurses_mvaddchnstr
ncurses_mvaddnstr
Func?ii Ncurses


Deplaseaza pozi?ia ?i adauga un ?ir de caractere de lungime specificata

ncurses_mvaddchstr
ncurses_mvaddstr
Func?ii Ncurses
PHP Manual

ncurses_mvaddnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddnstr — Deplaseaza pozi?ia ?i adauga un ?ir de caractere de lungime specificata

Descrierea

int ncurses_mvaddnstr ( int $y , int $x , string $s , int $n )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

y

x

s

n

ncurses_mvaddchstr
ncurses_mvaddstr
Func?ii Ncurses


Deplaseaza pozi?ia ?i adauga un ?ir de caractere

ncurses_mvaddnstr
ncurses_mvcur
Func?ii Ncurses
PHP Manual

ncurses_mvaddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddstr — Deplaseaza pozi?ia ?i adauga un ?ir de caractere

Descrierea

int ncurses_mvaddstr ( int $y , int $x , string $s )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

y

x

s

ncurses_mvaddnstr
ncurses_mvcur
Func?ii Ncurses


Deplaseaza imediat cursorul

ncurses_mvaddstr
ncurses_mvdelch
Func?ii Ncurses
PHP Manual

ncurses_mvcur

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvcur — Deplaseaza imediat cursorul

Descrierea

int ncurses_mvcur ( int $old_y , int $old_x , int $new_y , int $new_x )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

old_y

old_x

new_y

new_x

ncurses_mvaddstr
ncurses_mvdelch
Func?ii Ncurses


Deplaseaza pozi?ia ?i elimina caracterul, deplaseaza restul liniei în stânga

ncurses_mvcur
ncurses_mvgetch
Func?ii Ncurses
PHP Manual

ncurses_mvdelch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvdelch — Deplaseaza pozi?ia ?i elimina caracterul, deplaseaza restul liniei în stânga

Descrierea

int ncurses_mvdelch ( int $y , int $x )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

y

x

ncurses_mvcur
ncurses_mvgetch
Func?ii Ncurses


Deplaseaza pozi?ia ?i ob?ine caracterul din noua pozi?ie

ncurses_mvdelch
ncurses_mvhline
Func?ii Ncurses
PHP Manual

ncurses_mvgetch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvgetch — Deplaseaza pozi?ia ?i ob?ine caracterul din noua pozi?ie

Descrierea

int ncurses_mvgetch ( int $y , int $x )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

y

x

ncurses_mvdelch
ncurses_mvhline
Func?ii Ncurses


Stabile?te pozi?ia noua ?i deseneaza o linie orizontala folosind un caracter cu atribute ?i o lungime maxima de n caractere

ncurses_mvgetch
ncurses_mvinch
Func?ii Ncurses
PHP Manual

ncurses_mvhline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvhline — Stabile?te pozi?ia noua ?i deseneaza o linie orizontala folosind un caracter cu atribute ?i o lungime maxima de n caractere

Descrierea

int ncurses_mvhline ( int $y , int $x , int $attrchar , int $n )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

y

x

attrchar

n

ncurses_mvgetch
ncurses_mvinch
Func?ii Ncurses


Deplaseaza pozi?ia ?i ob?ine caracterul cu atribute din pozi?ia noua

ncurses_mvhline
ncurses_mvvline
Func?ii Ncurses
PHP Manual

ncurses_mvinch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvinch — Deplaseaza pozi?ia ?i ob?ine caracterul cu atribute din pozi?ia noua

Descrierea

int ncurses_mvinch ( int $y , int $x )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

y

x

ncurses_mvhline
ncurses_mvvline
Func?ii Ncurses


Stabile?te pozi?ia noua ?i deseneaza o linie verticala folosint un caracter cu atribute ?i o înal?ime maxima de n caractere

ncurses_mvinch
ncurses_mvwaddstr
Func?ii Ncurses
PHP Manual

ncurses_mvvline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvvline — Stabile?te pozi?ia noua ?i deseneaza o linie verticala folosint un caracter cu atribute ?i o înal?ime maxima de n caractere

Descrierea

int ncurses_mvvline ( int $y , int $x , int $attrchar , int $n )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

y

x

attrchar

n

ncurses_mvinch
ncurses_mvwaddstr
Func?ii Ncurses


Adauga un ?ir de caractere într-o pozi?ie noua din fereastra

ncurses_mvvline
ncurses_napms
Func?ii Ncurses
PHP Manual

ncurses_mvwaddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvwaddstr — Adauga un ?ir de caractere într-o pozi?ie noua din fereastra

Descrierea

int ncurses_mvwaddstr ( resource $window , int $y , int $x , string $text )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

y

x

text

ncurses_mvvline
ncurses_napms
Func?ii Ncurses


Adoarme

ncurses_mvwaddstr
ncurses_new_panel
Func?ii Ncurses
PHP Manual

ncurses_napms

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_napms — Adoarme

Descrierea

int ncurses_napms ( int $milliseconds )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

milliseconds

ncurses_mvwaddstr
ncurses_new_panel
Func?ii Ncurses


Creeaza un nou panel ?i îl asociaza cu o fereastra

ncurses_napms
ncurses_newpad
Func?ii Ncurses
PHP Manual

ncurses_new_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_new_panel — Creeaza un nou panel ?i îl asociaza cu o fereastra

Descrierea

resource ncurses_new_panel ( resource $window )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

ncurses_napms
ncurses_newpad
Func?ii Ncurses


Creeaza un nou pad (fereastra)

ncurses_new_panel
ncurses_newwin
Func?ii Ncurses
PHP Manual

ncurses_newpad

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_newpad — Creeaza un nou pad (fereastra)

Descrierea

resource ncurses_newpad ( int $rows , int $cols )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

rows

cols

ncurses_new_panel
ncurses_newwin
Func?ii Ncurses


Creeaza o fereastra noua

ncurses_newpad
ncurses_nl
Func?ii Ncurses
PHP Manual

ncurses_newwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_newwin — Creeaza o fereastra noua

Descrierea

resource ncurses_newwin ( int $rows , int $cols , int $y , int $x )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Creeaza o fereastra noua pentru a desena elemente în ea.

La crearea ferestrelor suplimentare, nu uita?i sa folosi?i ncurses_getmaxyx() pentru a verifica spa?iul disponibil, deoarece terminalele difera dupa dimensiuni ?i acestea pot varia.

Parametri

rows

Numarul de rânduri

cols

Numarul de coloane

y

Coordonata y a originii

x

Coordonata x a originii

Valorile întoarse

Întoarce identificatorul resursei pentru noua fereastra.

ncurses_newpad
ncurses_nl
Func?ii Ncurses


Transleaza caracterul de trecere în linie noua ?i caracterele "carriage return" / "line feed"

ncurses_newwin
ncurses_nocbreak
Func?ii Ncurses
PHP Manual

ncurses_nl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nl — Transleaza caracterul de trecere în linie noua ?i caracterele "carriage return" / "line feed"

Descrierea

bool ncurses_nl ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_newwin
ncurses_nocbreak
Func?ii Ncurses


Schimba terminalul în mod cooked

ncurses_nl
ncurses_noecho
Func?ii Ncurses
PHP Manual

ncurses_nocbreak

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nocbreak — Schimba terminalul în mod cooked

Descrierea

bool ncurses_nocbreak ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Întoarce terminalul în modul normal (cooked). Ini?ial terminalul poate sa fie, sau sa nu fie în modul cbreak, deoarece acest mod e mo?tenit. De aceea programul trebuie sa apeleze ncurses_cbreak() ?i ncurses_nocbreak() în mod explicit.

Valorile întoarse

Întoarce TRUE daca a avut loc vre-o eroare, FALSE în caz contrar.

A se vedea ?i

  • ncurses_cbreak() - Deconecteaza buferizarea intrarilor

ncurses_nl
ncurses_noecho
Func?ii Ncurses


Deconecteaza afi?area la ecran a tastelor apasate

ncurses_nocbreak
ncurses_nonl
Func?ii Ncurses
PHP Manual

ncurses_noecho

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noecho — Deconecteaza afi?area la ecran a tastelor apasate

Descrierea

bool ncurses_noecho ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Previne afi?area caracterelor tapate de utilizator.

Valorile întoarse

Întoarce TRUE daca a avut loc o eroare, FALSE în caz contrar.

A se vedea ?i

  • ncurses_echo() - Activeaza afi?area la ecran a intrarilor de la tastatura
  • ncurses_getch() - Cite?te un caracter de la tastaura

ncurses_nocbreak
ncurses_nonl
Func?ii Ncurses


Nu transleaza caracterul de trecere în linie noua ?i caracterele "carriage return" / "line feed"

ncurses_noecho
ncurses_noqiflush
Func?ii Ncurses
PHP Manual

ncurses_nonl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nonl — Nu transleaza caracterul de trecere în linie noua ?i caracterele "carriage return" / "line feed"

Descrierea

bool ncurses_nonl ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_noecho
ncurses_noqiflush
Func?ii Ncurses


Nu gole?te zona-tampon la caracterele de semnal

ncurses_nonl
ncurses_noraw
Func?ii Ncurses
PHP Manual

ncurses_noqiflush

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noqiflush — Nu gole?te zona-tampon la caracterele de semnal

Descrierea

void ncurses_noqiflush ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_nonl
ncurses_noraw
Func?ii Ncurses


Schimba terminalul din modul raw

ncurses_noqiflush
ncurses_pair_content
Func?ii Ncurses
PHP Manual

ncurses_noraw

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noraw — Schimba terminalul din modul raw

Descrierea

bool ncurses_noraw ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Schimba terminalul din modul raw. Modul raw este similar cu modul cbreak, unde caracterele tastate sunt imediat transmise programului utilizatorului. Diferen?a este ca în modul raw caracterele interrupt, quit, suspend ?i caracterele de control al fluxului sunt toate transmise neinterpretate, în loc sa se genereze un semnal.

Valorile întoarse

Întoarce TRUE daca a avut loc o eroare, FALSE în caz contrar.

A se vedea ?i

  • ncurses_raw() - Schimba terminalul în mod raw
  • ncurses_cbreak() - Deconecteaza buferizarea intrarilor
  • ncurses_nocbreak() - Schimba terminalul în mod cooked

ncurses_noqiflush
ncurses_pair_content
Func?ii Ncurses


Ob?ine culorile de prim plan ?i de fundal ale unei perechi de culori

ncurses_noraw
ncurses_panel_above
Func?ii Ncurses
PHP Manual

ncurses_pair_content

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_pair_content — Ob?ine culorile de prim plan ?i de fundal ale unei perechi de culori

Descrierea

int ncurses_pair_content ( int $pair , int &$f , int &$b )

Ob?ine culorile de prim plan ?i de fundal, ce constituie perechea data de culori. Capacita?ile terminalului de redare a culorilor trebuie sa fie ini?ializate cu ncurses_start_color() înainte de a apela aceasta func?ie.

Parametri

pair

Numarul perechii de culori pentru care se va ob?ine informa?ia.

f

O referin?a în care va fi întoarsa culoarea de prim plan a perechii de culori. Informa?ia întoarsa va fi un numar al culorii ce reprezinta una din culorile predefinite sau o culoare definita anterior cu ncurses_init_color(), daca terminalul sus?ine schimbarea culorilor.

b

O referin?a în care va fi întoarsa culoarea de fundal a perechii de culori. Informa?ia întoarsa va fi un numar al culorii ce reprezinta una din culorile predefinite sau o culoare definita anterior cu ncurses_init_color(), daca terminalul sus?ine schimbarea culorilor.

Valorile întoarse

Întoarce -1 daca func?ia s-a executat cu succes, sau 0 daca ncurses sau capacita?ile terminalului de redare a culorilor nu au fost ini?ializate.

A se vedea ?i

  • ncurses_init_pair() - Define?te o pereche de culori
  • ncurses_start_color() - Ini?ializeaza func?ionalitatea culorilor

ncurses_noraw
ncurses_panel_above
Func?ii Ncurses


Întoarce panelul care este de asupra altui panel

ncurses_pair_content
ncurses_panel_below
Func?ii Ncurses
PHP Manual

ncurses_panel_above

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_above — Întoarce panelul care este de asupra altui panel

Descrierea

resource ncurses_panel_above ( resource $panel )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

panel

Valorile întoarse

Daca panel este null, întoarce cel mai de jos panel din stiva.

ncurses_pair_content
ncurses_panel_below
Func?ii Ncurses


Întoarce panelul care este de sub alt panel

ncurses_panel_above
ncurses_panel_window
Func?ii Ncurses
PHP Manual

ncurses_panel_below

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_below — Întoarce panelul care este de sub alt panel

Descrierea

resource ncurses_panel_below ( resource $panel )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

panel

Parametri

Daca panel este null, întoarce cel mai de sus panel din stiva.

ncurses_panel_above
ncurses_panel_window
Func?ii Ncurses


Întoarce fereastra asociata cu un panel

ncurses_panel_below
ncurses_pnoutrefresh
Func?ii Ncurses
PHP Manual

ncurses_panel_window

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_window — Întoarce fereastra asociata cu un panel

Descrierea

resource ncurses_panel_window ( resource $panel )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

panel

ncurses_panel_below
ncurses_pnoutrefresh
Func?ii Ncurses


Copie o regiune dintr-un pad în ecranul virtual

ncurses_panel_window
ncurses_prefresh
Func?ii Ncurses
PHP Manual

ncurses_pnoutrefresh

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_pnoutrefresh — Copie o regiune dintr-un pad în ecranul virtual

Descrierea

int ncurses_pnoutrefresh ( resource $pad , int $pminrow , int $pmincol , int $sminrow , int $smincol , int $smaxrow , int $smaxcol )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pad

pminrow

pmincol

sminrow

smincol

smaxrow

smaxcol

ncurses_panel_window
ncurses_prefresh
Func?ii Ncurses


Copie o regiune dintr-un pad în ecranul virtual

ncurses_pnoutrefresh
ncurses_putp
Func?ii Ncurses
PHP Manual

ncurses_prefresh

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_prefresh — Copie o regiune dintr-un pad în ecranul virtual

Descrierea

int ncurses_prefresh ( resource $pad , int $pminrow , int $pmincol , int $sminrow , int $smincol , int $smaxrow , int $smaxcol )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pad

pminrow

pmincol

sminrow

smincol

smaxrow

smaxcol

ncurses_pnoutrefresh
ncurses_putp
Func?ii Ncurses


Aplica informa?ia de completare la ?irul de caractere ?i îl afi?eaza

ncurses_prefresh
ncurses_qiflush
Func?ii Ncurses
PHP Manual

ncurses_putp

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_putp — Aplica informa?ia de completare la ?irul de caractere ?i îl afi?eaza

Descrierea

int ncurses_putp ( string $text )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

text

ncurses_prefresh
ncurses_qiflush
Func?ii Ncurses


Gole?te zona-tampon la caracterele de semnal

ncurses_putp
ncurses_raw
Func?ii Ncurses
PHP Manual

ncurses_qiflush

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_qiflush — Gole?te zona-tampon la caracterele de semnal

Descrierea

void ncurses_qiflush ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_putp
ncurses_raw
Func?ii Ncurses


Schimba terminalul în mod raw

ncurses_qiflush
ncurses_refresh
Func?ii Ncurses
PHP Manual

ncurses_raw

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_raw — Schimba terminalul în mod raw

Descrierea

bool ncurses_raw ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Plaseaza terminalul în modul raw. Modul raw este similar cu modul cbreak, unde caracterele tastate sunt imediat transmise programului utilizatorului. Diferen?a este ca în modul raw caracterele interrupt, quit, suspend ?i caracterele de control al fluxului sunt toate transmise neinterpretate, în loc sa se genereze un semnal.

Valorile întoarse

Returns TRUE if any error occurred, otherwise FALSE.

A se vedea ?i

  • ncurses_noraw() - Schimba terminalul din modul raw
  • ncurses_cbreak() - Deconecteaza buferizarea intrarilor
  • ncurses_nocbreak() - Schimba terminalul în mod cooked

ncurses_qiflush
ncurses_refresh
Func?ii Ncurses


Actualizeaza ecranul

ncurses_raw
ncurses_replace_panel
Func?ii Ncurses
PHP Manual

ncurses_refresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_refresh — Actualizeaza ecranul

Descrierea

int ncurses_refresh ( int $ch )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

ch

ncurses_raw
ncurses_replace_panel
Func?ii Ncurses


Înlocuie?te fereastra asociata cu un panel

ncurses_refresh
ncurses_reset_prog_mode
Func?ii Ncurses
PHP Manual

ncurses_replace_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_replace_panel — Înlocuie?te fereastra asociata cu un panel

Descrierea

int ncurses_replace_panel ( resource $panel , resource $window )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

panel

window

ncurses_refresh
ncurses_reset_prog_mode
Func?ii Ncurses


Reseteaza modul programului salvat cu def_prog_mode

ncurses_replace_panel
ncurses_reset_shell_mode
Func?ii Ncurses
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 — Reseteaza modul programului salvat cu def_prog_mode

Descrierea

int ncurses_reset_prog_mode ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_replace_panel
ncurses_reset_shell_mode
Func?ii Ncurses


Reseteaza modul înveli?ului salvat cu def_shell_mode

ncurses_reset_prog_mode
ncurses_resetty
Func?ii Ncurses
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 — Reseteaza modul înveli?ului salvat cu def_shell_mode

Descrierea

int ncurses_reset_shell_mode ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_reset_prog_mode
ncurses_resetty
Func?ii Ncurses


Restabile?te starea terminalului salvata

ncurses_reset_shell_mode
ncurses_savetty
Func?ii Ncurses
PHP Manual

ncurses_resetty

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_resetty — Restabile?te starea terminalului salvata

Descrierea

bool ncurses_resetty ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Restabile?te starea terminalului, care a fost salvata anterior cu ncurses_savetty().

Valorile întoarse

Întotdeauna întoarce FALSE.

A se vedea ?i

  • ncurses_savetty() - Salveaza starea terminalului

ncurses_reset_shell_mode
ncurses_savetty
Func?ii Ncurses


Salveaza starea terminalului

ncurses_resetty
ncurses_scr_dump
Func?ii Ncurses
PHP Manual

ncurses_savetty

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_savetty — Salveaza starea terminalului

Descrierea

bool ncurses_savetty ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Salveaza starea curenta a terminalului. Starea terminalului salvata poate fi restabilita cu ncurses_resetty().

Valorile întoarse

Întotdeauna întoarce FALSE.

A se vedea ?i

  • ncurses_resetty() - Restabile?te starea terminalului salvata

ncurses_resetty
ncurses_scr_dump
Func?ii Ncurses


Salveaza con?inutul ecranului într-un fi?ier

ncurses_savetty
ncurses_scr_init
Func?ii Ncurses
PHP Manual

ncurses_scr_dump

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_dump — Salveaza con?inutul ecranului într-un fi?ier

Descrierea

int ncurses_scr_dump ( string $filename )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

filename

ncurses_savetty
ncurses_scr_init
Func?ii Ncurses


Ini?ializeaza ecranul dintr-un fi?ier salvat

ncurses_scr_dump
ncurses_scr_restore
Func?ii Ncurses
PHP Manual

ncurses_scr_init

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_init — Ini?ializeaza ecranul dintr-un fi?ier salvat

Descrierea

int ncurses_scr_init ( string $filename )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

filename

ncurses_scr_dump
ncurses_scr_restore
Func?ii Ncurses


Restabile?te ecranul dintr-un fi?ier salvat

ncurses_scr_init
ncurses_scr_set
Func?ii Ncurses
PHP Manual

ncurses_scr_restore

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_restore — Restabile?te ecranul dintr-un fi?ier salvat

Descrierea

int ncurses_scr_restore ( string $filename )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

filename

ncurses_scr_init
ncurses_scr_set
Func?ii Ncurses


Stabile?te con?inutul ecranului dintr-un fi?ier salvat

ncurses_scr_restore
ncurses_scrl
Func?ii Ncurses
PHP Manual

ncurses_scr_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_set — Stabile?te con?inutul ecranului dintr-un fi?ier salvat

Descrierea

int ncurses_scr_set ( string $filename )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

filename

ncurses_scr_restore
ncurses_scrl
Func?ii Ncurses


Deplaseaza con?inutul ferestrei în sus sau în jos fara a modifica pozi?ia curenta

ncurses_scr_set
ncurses_show_panel
Func?ii Ncurses
PHP Manual

ncurses_scrl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scrl — Deplaseaza con?inutul ferestrei în sus sau în jos fara a modifica pozi?ia curenta

Descrierea

int ncurses_scrl ( int $count )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

count

ncurses_scr_set
ncurses_show_panel
Func?ii Ncurses


Plaseaza un panel invizibil în vârful stivei, facându-l vizibil

ncurses_scrl
ncurses_slk_attr
Func?ii Ncurses
PHP Manual

ncurses_show_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_show_panel — Plaseaza un panel invizibil în vârful stivei, facându-l vizibil

Descrierea

int ncurses_show_panel ( resource $panel )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

panel

ncurses_scrl
ncurses_slk_attr
Func?ii Ncurses


Întoarce atributul curent al etichetelor soft ale tastelor

ncurses_show_panel
ncurses_slk_attroff
Func?ii Ncurses
PHP Manual

ncurses_slk_attr

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attr — Întoarce atributul curent al etichetelor soft ale tastelor

Descrierea

int ncurses_slk_attr ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Întoarce atributul etichetei soft a tastei curente.

Valorile întoarse

Atributul, ca un numar întreg.

ncurses_show_panel
ncurses_slk_attroff
Func?ii Ncurses


Deconecteaza atribute specificate pentru taste func?ionale cu etichete soft

ncurses_slk_attr
ncurses_slk_attron
Func?ii Ncurses
PHP Manual

ncurses_slk_attroff

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attroff — Deconecteaza atribute specificate pentru taste func?ionale cu etichete soft

Descrierea

int ncurses_slk_attroff ( int $intarg )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

intarg

ncurses_slk_attr
ncurses_slk_attron
Func?ii Ncurses


Conecteaza atribute specificate pentru taste func?ionale cu etichete soft

ncurses_slk_attroff
ncurses_slk_attrset
Func?ii Ncurses
PHP Manual

ncurses_slk_attron

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attron — Conecteaza atribute specificate pentru taste func?ionale cu etichete soft

Descrierea

int ncurses_slk_attron ( int $intarg )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

intarg

ncurses_slk_attroff
ncurses_slk_attrset
Func?ii Ncurses


Stabile?te atribute specificate pentru taste func?ionale cu etichete soft

ncurses_slk_attron
ncurses_slk_clear
Func?ii Ncurses
PHP Manual

ncurses_slk_attrset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attrset — Stabile?te atribute specificate pentru taste func?ionale cu etichete soft

Descrierea

int ncurses_slk_attrset ( int $intarg )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

intarg

ncurses_slk_attron
ncurses_slk_clear
Func?ii Ncurses


Elimina etichetele soft de la ecran

ncurses_slk_attrset
ncurses_slk_color
Func?ii Ncurses
PHP Manual

ncurses_slk_clear

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_clear — Elimina etichetele soft de la ecran

Descrierea

bool ncurses_slk_clear ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Func?ia ncurses_slk_clear() elimina etichetele soft ale tastelor de la ecran.

Valorile întoarse

Întoarce TRUE în caz de erori, FALSE în caz contrar.

ncurses_slk_attrset
ncurses_slk_color
Func?ii Ncurses


Stabile?te culoarea pentru tastele cu eticheta soft

ncurses_slk_clear
ncurses_slk_init
Func?ii Ncurses
PHP Manual

ncurses_slk_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_color — Stabile?te culoarea pentru tastele cu eticheta soft

Descrierea

int ncurses_slk_color ( int $intarg )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

intarg

ncurses_slk_clear
ncurses_slk_init
Func?ii Ncurses


Ini?ializeaza taste func?ionale cu eticheta soft

ncurses_slk_color
ncurses_slk_noutrefresh
Func?ii Ncurses
PHP Manual

ncurses_slk_init

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_init — Ini?ializeaza taste func?ionale cu eticheta soft

Descrierea

bool ncurses_slk_init ( int $format )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Ini?ializeaza func?iile tastelor cu eticheta soft

Aceasta func?ie trebuie sa fie apelata înainte de apelul ncurses_init() sau ncurses_newwin().

Parametri

format

Daca ncurses_init() utilizeaza eventual o linie din stdscr pentru a emula etichetele soft, atunci acest parametru determina modul cum etichetele sunt aranjate pe ecran.

0 indica o aranjare a etichetelor în mod 3-2-3, 1 indica un aranjament 4-4 ?i 2 indica modul asemanator cu PC 4-4-4, dar în plus o linie de indici va fi creata.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ncurses_slk_color
ncurses_slk_noutrefresh
Func?ii Ncurses


Copie cheile soft label pe ecranul virtual

ncurses_slk_init
ncurses_slk_refresh
Func?ii Ncurses
PHP Manual

ncurses_slk_noutrefresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_noutrefresh — Copie cheile soft label pe ecranul virtual

Descrierea

bool ncurses_slk_noutrefresh ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_slk_init
ncurses_slk_refresh
Func?ii Ncurses


Copie tastele etichetelor soft la ecran

ncurses_slk_noutrefresh
ncurses_slk_restore
Func?ii Ncurses
PHP Manual

ncurses_slk_refresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_refresh — Copie tastele etichetelor soft la ecran

Descrierea

int ncurses_slk_refresh ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Copie tastele etichetelor soft din ecranul virtual în cel fizic.

ncurses_slk_noutrefresh
ncurses_slk_restore
Func?ii Ncurses


Restabile?te tastele cu etichete soft

ncurses_slk_refresh
ncurses_slk_set
Func?ii Ncurses
PHP Manual

ncurses_slk_restore

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_restore — Restabile?te tastele cu etichete soft

Descrierea

int ncurses_slk_restore ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Restabile?te tastele cu etichete soft dupa ce a fost efectuat ncurses_slk_clear().

ncurses_slk_refresh
ncurses_slk_set
Func?ii Ncurses


Stabile?te etichetele tastelor func?ionale

ncurses_slk_restore
ncurses_slk_touch
Func?ii Ncurses
PHP Manual

ncurses_slk_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_set — Stabile?te etichetele tastelor func?ionale

Descrierea

bool ncurses_slk_set ( int $labelnr , string $label , int $format )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

labelnr

label

format

ncurses_slk_restore
ncurses_slk_touch
Func?ii Ncurses


For?eaza afi?area când este efectuat ncurses_slk_noutrefresh

ncurses_slk_set
ncurses_standend
Func?ii Ncurses
PHP Manual

ncurses_slk_touch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_touch — For?eaza afi?area când este efectuat ncurses_slk_noutrefresh

Descrierea

int ncurses_slk_touch ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

For?eaza ca toate etichetele tastelor soft sa fie afi?ate urmatoarea data când este efectuata ncurses_slk_noutrefresh().

ncurses_slk_set
ncurses_standend
Func?ii Ncurses


Stopeaza utilizarea atributului 'standout'

ncurses_slk_touch
ncurses_standout
Func?ii Ncurses
PHP Manual

ncurses_standend

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_standend — Stopeaza utilizarea atributului 'standout'

Descrierea

int ncurses_standend ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_slk_touch
ncurses_standout
Func?ii Ncurses


Începe utilizarea atributului 'standout'

ncurses_standend
ncurses_start_color
Func?ii Ncurses
PHP Manual

ncurses_standout

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_standout — Începe utilizarea atributului 'standout'

Descrierea

int ncurses_standout ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_standend
ncurses_start_color
Func?ii Ncurses


Ini?ializeaza func?ionalitatea culorilor

ncurses_standout
ncurses_termattrs
Func?ii Ncurses
PHP Manual

ncurses_start_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_start_color — Ini?ializeaza func?ionalitatea culorilor

Descrierea

int ncurses_start_color ( void )

Ini?ializeaza func?ionalitatea culorilor în ncurses. Aceasta func?ie trebuie apelata înaintea apelarii oricarei func?ii de manipulare a culorilor, dar dupa apelarea ncurses_init(). Este o practica buna de a apela aceasta func?ie imediat dupa apelarea ncurses_init().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce 0 în caz de succes, sau -1 daca tabelul de culori nu a putut fi alocat, sau ncurses nu a fost ini?ializat.

Exemple

Example #1 Afi?area la ecran a unui ?ir de caractere cu o culoare specificata

<?php
ncurses_init();

// Daca terminalul sus?ine culori, ini?ializeaza ?i stabile?te culoarea activa
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Afi?eaza ?irul de caractere în loca?ia specificata
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Transmite afi?area la ecran
ncurses_refresh();

ncurses_end();
?>

A se vedea ?i

  • ncurses_can_change_color() - Verifica daca defini?iile culorilor terminalului pot fi schimbate
  • ncurses_has_colors() - Verifica daca terminalul are capacita?i de redare a culorilor

ncurses_standout
ncurses_termattrs
Func?ii Ncurses


Întoarce un SAU logic al tuturor fanioanelor de atribute sus?inute de terminal

ncurses_start_color
ncurses_termname
Func?ii Ncurses
PHP Manual

ncurses_termattrs

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_termattrs — Întoarce un SAU logic al tuturor fanioanelor de atribute sus?inute de terminal

Descrierea

bool ncurses_termattrs ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_start_color
ncurses_termname
Func?ii Ncurses


Întoarce denumirea scurta a terminalului

ncurses_termattrs
ncurses_timeout
Func?ii Ncurses
PHP Manual

ncurses_termname

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_termname — Întoarce denumirea scurta a terminalului

Descrierea

string ncurses_termname ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Întoarce denumirea scurta a terminalului.

Valorile întoarse

Întoarce denumirea scurta a terminalului trunchiata la 14 caractere. În caz de erori întoarce NULL.

A se vedea ?i

  • ncurses_longname() - Întoarce descrierea terminalului

ncurses_termattrs
ncurses_timeout
Func?ii Ncurses


Stabile?te timpul de expirare pentru secven?e speciale de taste

ncurses_termname
ncurses_top_panel
Func?ii Ncurses
PHP Manual

ncurses_timeout

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_timeout — Stabile?te timpul de expirare pentru secven?e speciale de taste

Descrierea

void ncurses_timeout ( int $millisec )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

millisec

ncurses_termname
ncurses_top_panel
Func?ii Ncurses


Deplaseaza un panel vizibil în vârful stivei

ncurses_timeout
ncurses_typeahead
Func?ii Ncurses
PHP Manual

ncurses_top_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_top_panel — Deplaseaza un panel vizibil în vârful stivei

Descrierea

int ncurses_top_panel ( resource $panel )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

panel

ncurses_timeout
ncurses_typeahead
Func?ii Ncurses


Specifica un descriptor de fi?ier diferit pentru verificarea typeahead

ncurses_top_panel
ncurses_ungetch
Func?ii Ncurses
PHP Manual

ncurses_typeahead

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_typeahead — Specifica un descriptor de fi?ier diferit pentru verificarea typeahead

Descrierea

int ncurses_typeahead ( int $fd )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

fd

ncurses_top_panel
ncurses_ungetch
Func?ii Ncurses


Plaseaza un caracter înapoi în fluxul de intrari

ncurses_typeahead
ncurses_ungetmouse
Func?ii Ncurses
PHP Manual

ncurses_ungetch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_ungetch — Plaseaza un caracter înapoi în fluxul de intrari

Descrierea

int ncurses_ungetch ( int $keycode )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

keycode

ncurses_typeahead
ncurses_ungetmouse
Func?ii Ncurses


Plaseaza evenimentele ?oricelului în rând

ncurses_ungetch
ncurses_update_panels
Func?ii Ncurses
PHP Manual

ncurses_ungetmouse

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_ungetmouse — Plaseaza evenimentele ?oricelului în rând

Descrierea

bool ncurses_ungetmouse ( array $mevent )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Plaseaza un eveniment KEY_MOUSE în rândul evenimentelor de intrare ?i asociaza cu acest eveniment datele despre stare ?i despre coordonatele relative pe ecran ale celulei-caracter, specificate în mevent.

Parametri

mevent

Un tablou asociativ specificând op?iunile evenimentului:

  • "id" : un identificator pentru a diferen?ia dispozitive multiple

  • "x" : pozi?ia relativa pe axa x a celulei de caracter

  • "y" : pozi?ia relativa pe axa y a celulei de caracter

  • "z" : în prezent nu este sus?inut

  • "mmask" : ac?iunea ?oricelului

Valorile întoarse

Întoarce FALSE în caz de succes, TRUE în caz contrar.

A se vedea ?i

  • ncurses_getmouse() - Cite?te evenimentul ?oricelului

ncurses_ungetch
ncurses_update_panels
Func?ii Ncurses


Actualizeaza ecranul virtual pentru a reflecta rela?iile dintre panelurile din stiva

ncurses_ungetmouse
ncurses_use_default_colors
Func?ii Ncurses
PHP Manual

ncurses_update_panels

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_update_panels — Actualizeaza ecranul virtual pentru a reflecta rela?iile dintre panelurile din stiva

Descrierea

void ncurses_update_panels ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_ungetmouse
ncurses_use_default_colors
Func?ii Ncurses


Atribuie culorile implicite ale terminalului culorii cu indicele -1

ncurses_update_panels
ncurses_use_env
Func?ii Ncurses
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 — Atribuie culorile implicite ale terminalului culorii cu indicele -1

Descrierea

bool ncurses_use_default_colors ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ncurses_update_panels
ncurses_use_env
Func?ii Ncurses


Controleaza utilizarea informa?iilor de mediu despre dimensiunea terminalului

ncurses_use_default_colors
ncurses_use_extended_names
Func?ii Ncurses
PHP Manual

ncurses_use_env

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_use_env — Controleaza utilizarea informa?iilor de mediu despre dimensiunea terminalului

Descrierea

void ncurses_use_env ( bool $flag )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

flag

ncurses_use_default_colors
ncurses_use_extended_names
Func?ii Ncurses


Controlezaa utilizarea denumirilor extinse în descrieri terminfo

ncurses_use_env
ncurses_vidattr
Func?ii Ncurses
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 — Controlezaa utilizarea denumirilor extinse în descrieri terminfo

Descrierea

int ncurses_use_extended_names ( bool $flag )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

flag

ncurses_use_env
ncurses_vidattr
Func?ii Ncurses


Afi?eaza ?irul de caractere la terminal în modul video atribut

ncurses_use_extended_names
ncurses_vline
Func?ii Ncurses
PHP Manual

ncurses_vidattr

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_vidattr — Afi?eaza ?irul de caractere la terminal în modul video atribut

Descrierea

int ncurses_vidattr ( int $intarg )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

intarg

ncurses_use_extended_names
ncurses_vline
Func?ii Ncurses


Deseneaza o linie verticala în pozi?ia curenta utilizând un caracter cu atribute, de o înal?ime maxima de n caractere

ncurses_vidattr
ncurses_waddch
Func?ii Ncurses
PHP Manual

ncurses_vline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_vline — Deseneaza o linie verticala în pozi?ia curenta utilizând un caracter cu atribute, de o înal?ime maxima de n caractere

Descrierea

int ncurses_vline ( int $charattr , int $n )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

charattr

n

ncurses_vidattr
ncurses_waddch
Func?ii Ncurses


Adauga un caracter în pozi?ia curenta din fereastra ?i avanseaza cursorul

ncurses_vline
ncurses_waddstr
Func?ii Ncurses
PHP Manual

ncurses_waddch

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_waddch — Adauga un caracter în pozi?ia curenta din fereastra ?i avanseaza cursorul

Descrierea

int ncurses_waddch ( resource $window , int $ch )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

ch

ncurses_vline
ncurses_waddstr
Func?ii Ncurses


Afi?eaza un text în pozi?ia curenta din fereastra

ncurses_waddch
ncurses_wattroff
Func?ii Ncurses
PHP Manual

ncurses_waddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_waddstr — Afi?eaza un text în pozi?ia curenta din fereastra

Descrierea

int ncurses_waddstr ( resource $window , string $str [, int $n ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

str

n

ncurses_waddch
ncurses_wattroff
Func?ii Ncurses


Deconecteaza atribute pentru o fereastra

ncurses_waddstr
ncurses_wattron
Func?ii Ncurses
PHP Manual

ncurses_wattroff

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattroff — Deconecteaza atribute pentru o fereastra

Descrierea

int ncurses_wattroff ( resource $window , int $attrs )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

attrs

ncurses_waddstr
ncurses_wattron
Func?ii Ncurses


Conecteaza atribute pentru o fereastra

ncurses_wattroff
ncurses_wattrset
Func?ii Ncurses
PHP Manual

ncurses_wattron

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattron — Conecteaza atribute pentru o fereastra

Descrierea

int ncurses_wattron ( resource $window , int $attrs )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

attrs

ncurses_wattroff
ncurses_wattrset
Func?ii Ncurses


Stabile?te atribute pentru o fereastra

ncurses_wattron
ncurses_wborder
Func?ii Ncurses
PHP Manual

ncurses_wattrset

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattrset — Stabile?te atribute pentru o fereastra

Descrierea

int ncurses_wattrset ( resource $window , int $attrs )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

attrs

ncurses_wattron
ncurses_wborder
Func?ii Ncurses


Deseneaza o bordura în jurul ferestrei utilizând caractere cu atribute

ncurses_wattrset
ncurses_wclear
Func?ii Ncurses
PHP Manual

ncurses_wborder

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wborder — Deseneaza o bordura în jurul ferestrei utilizând caractere cu atribute

Descrierea

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

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Deseneaza liniile ?i col?urile specificate în jurul ferestrei specificate în window.

Utiliza?i ncurses_border() pentru bordura în jurul ferestrei principale.

Parametri

Fiecare parametru poate avea valoarea 0 pentru a desena linia ?i 1 pentru a o omite.

window

Fereastra asupra careia se opereaza

left

right

top

bottom

tl_corner

Col?ul stânga-sus

tr_corner

Col?ul dreapta-sus

bl_corner

Col?ul stânga-jos

br_corner

Col?ul dreapta-jos

A se vedea ?i

  • ncurses_border() - Deseneaza o bordura în jurul ecranului utilizând caractere cu atribute

ncurses_wattrset
ncurses_wclear
Func?ii Ncurses


Cura?a fereastra

ncurses_wborder
ncurses_wcolor_set
Func?ii Ncurses
PHP Manual

ncurses_wclear

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wclear — Cura?a fereastra

Descrierea

int ncurses_wclear ( resource $window )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

ncurses_wborder
ncurses_wcolor_set
Func?ii Ncurses


Stabile?te perechile de culori ale ferestrei

ncurses_wclear
ncurses_werase
Func?ii Ncurses
PHP Manual

ncurses_wcolor_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wcolor_set — Stabile?te perechile de culori ale ferestrei

Descrierea

int ncurses_wcolor_set ( resource $window , int $color_pair )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

color_pair

ncurses_wclear
ncurses_werase
Func?ii Ncurses


?terge con?inutul ferestrei

ncurses_wcolor_set
ncurses_wgetch
Func?ii Ncurses
PHP Manual

ncurses_werase

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_werase — ?terge con?inutul ferestrei

Descrierea

int ncurses_werase ( resource $window )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

ncurses_wcolor_set
ncurses_wgetch
Func?ii Ncurses


Cite?te un caracter de la tastatura (fereastra)

ncurses_werase
ncurses_whline
Func?ii Ncurses
PHP Manual

ncurses_wgetch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wgetch — Cite?te un caracter de la tastatura (fereastra)

Descrierea

int ncurses_wgetch ( resource $window )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

ncurses_werase
ncurses_whline
Func?ii Ncurses


Deseneaza o linie orizontala într-o fereastra în pozi?ia curenta utilizând un caracter cu atribute ?i o lungime maxima de n caractere

ncurses_wgetch
ncurses_wmouse_trafo
Func?ii Ncurses
PHP Manual

ncurses_whline

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_whline — Deseneaza o linie orizontala într-o fereastra în pozi?ia curenta utilizând un caracter cu atribute ?i o lungime maxima de n caractere

Descrierea

int ncurses_whline ( resource $window , int $charattr , int $n )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

charattr

n

ncurses_wgetch
ncurses_wmouse_trafo
Func?ii Ncurses


Transforma coordonate window/stdscr

ncurses_whline
ncurses_wmove
Func?ii Ncurses
PHP Manual

ncurses_wmouse_trafo

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wmouse_trafo — Transforma coordonate window/stdscr

Descrierea

bool ncurses_wmouse_trafo ( resource $window , int &$y , int &$x , bool $toscreen )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

x

y

toscreen

ncurses_whline
ncurses_wmove
Func?ii Ncurses


Deplaseaza pozi?ia de afi?are în fereastra

ncurses_wmouse_trafo
ncurses_wnoutrefresh
Func?ii Ncurses
PHP Manual

ncurses_wmove

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wmove — Deplaseaza pozi?ia de afi?are în fereastra

Descrierea

int ncurses_wmove ( resource $window , int $y , int $x )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

y

x

ncurses_wmouse_trafo
ncurses_wnoutrefresh
Func?ii Ncurses


Copie fereastra în ecranul virtual

ncurses_wmove
ncurses_wrefresh
Func?ii Ncurses
PHP Manual

ncurses_wnoutrefresh

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wnoutrefresh — Copie fereastra în ecranul virtual

Descrierea

int ncurses_wnoutrefresh ( resource $window )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

ncurses_wmove
ncurses_wrefresh
Func?ii Ncurses


Actualizeaza fereastra la ecranul terminalului

ncurses_wnoutrefresh
ncurses_wstandend
Func?ii Ncurses
PHP Manual

ncurses_wrefresh

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wrefresh — Actualizeaza fereastra la ecranul terminalului

Descrierea

int ncurses_wrefresh ( resource $window )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

ncurses_wnoutrefresh
ncurses_wstandend
Func?ii Ncurses


Încheie modul standout pentru o fereastra

ncurses_wrefresh
ncurses_wstandout
Func?ii Ncurses
PHP Manual

ncurses_wstandend

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wstandend — Încheie modul standout pentru o fereastra

Descrierea

int ncurses_wstandend ( resource $window )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

ncurses_wrefresh
ncurses_wstandout
Func?ii Ncurses


Transfera o fererastra în mod standout

ncurses_wstandend
ncurses_wvline
Func?ii Ncurses
PHP Manual

ncurses_wstandout

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wstandout — Transfera o fererastra în mod standout

Descrierea

int ncurses_wstandout ( resource $window )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

ncurses_wstandend
ncurses_wvline
Func?ii Ncurses


Deseneaza o linie verticala într-o fereastra în pozi?ia curenta utilizând un caracter cu atribute, de o lungime maxima de n caractere

ncurses_wstandout
Newt
Func?ii Ncurses
PHP Manual

ncurses_wvline

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wvline — Deseneaza o linie verticala într-o fereastra în pozi?ia curenta utilizând un caracter cu atribute, de o lungime maxima de n caractere

Descrierea

int ncurses_wvline ( resource $window , int $charattr , int $n )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

window

charattr

n

ncurses_wstandout
Newt
Func?ii Ncurses


Newt

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
    • 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
  • Exemple
    • Basic usage
  • Func?ii Newt
    • 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 — Descrierea
    • newt_checkbox_tree_get_multi_selection — Descrierea
    • newt_checkbox_tree_get_selection — Descrierea
    • newt_checkbox_tree_multi — Descrierea
    • newt_checkbox_tree_set_current — Descrierea
    • newt_checkbox_tree_set_entry_value — Descrierea
    • newt_checkbox_tree_set_entry — Descrierea
    • newt_checkbox_tree_set_width — Descrierea
    • newt_checkbox_tree — Descrierea
    • newt_checkbox — Descrierea
    • newt_clear_key_buffer — Discards the contents of the terminal's input buffer without waiting for additional input
    • newt_cls — Descrierea
    • newt_compact_button — Descrierea
    • newt_component_add_callback — Descrierea
    • newt_component_takes_focus — Descrierea
    • newt_create_grid — Descrierea
    • newt_cursor_off — Descrierea
    • newt_cursor_on — Descrierea
    • newt_delay — Descrierea
    • newt_draw_form — Descrierea
    • newt_draw_root_text — Displays the string text at the position indicated
    • newt_entry_get_value — Descrierea
    • newt_entry_set_filter — Descrierea
    • newt_entry_set_flags — Descrierea
    • newt_entry_set — Descrierea
    • newt_entry — Descrierea
    • 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 — Descrierea
    • newt_form_destroy — Destroys a form
    • newt_form_get_current — Descrierea
    • newt_form_run — Runs a form
    • newt_form_set_background — Descrierea
    • newt_form_set_height — Descrierea
    • newt_form_set_size — Descrierea
    • newt_form_set_timer — Descrierea
    • newt_form_set_width — Descrierea
    • newt_form_watch_fd — Descrierea
    • 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 — Descrierea
    • newt_grid_basic_window — Descrierea
    • newt_grid_free — Descrierea
    • newt_grid_get_size — Descrierea
    • newt_grid_h_close_stacked — Descrierea
    • newt_grid_h_stacked — Descrierea
    • newt_grid_place — Descrierea
    • newt_grid_set_field — Descrierea
    • newt_grid_simple_window — Descrierea
    • newt_grid_v_close_stacked — Descrierea
    • newt_grid_v_stacked — Descrierea
    • newt_grid_wrapped_window_at — Descrierea
    • newt_grid_wrapped_window — Descrierea
    • newt_init — Initialize newt
    • newt_label_set_text — Descrierea
    • newt_label — Descrierea
    • newt_listbox_append_entry — Descrierea
    • newt_listbox_clear_selection — Descrierea
    • newt_listbox_clear — Descrierea
    • newt_listbox_delete_entry — Descrierea
    • newt_listbox_get_current — Descrierea
    • newt_listbox_get_selection — Descrierea
    • newt_listbox_insert_entry — Descrierea
    • newt_listbox_item_count — Descrierea
    • newt_listbox_select_item — Descrierea
    • newt_listbox_set_current_by_key — Descrierea
    • newt_listbox_set_current — Descrierea
    • newt_listbox_set_data — Descrierea
    • newt_listbox_set_entry — Descrierea
    • newt_listbox_set_width — Descrierea
    • newt_listbox — Descrierea
    • newt_listitem_get_data — Descrierea
    • newt_listitem_set — Descrierea
    • newt_listitem — Descrierea
    • 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 — Descrierea
    • newt_radiobutton — Descrierea
    • newt_redraw_help_line — Descrierea
    • newt_reflow_text — Descrierea
    • newt_refresh — Updates modified portions of the screen
    • newt_resize_screen — Descrierea
    • newt_resume — Resume using the newt interface after calling newt_suspend
    • newt_run_form — Runs a form
    • newt_scale_set — Descrierea
    • newt_scale — Descrierea
    • newt_scrollbar_set — Descrierea
    • newt_set_help_callback — Descrierea
    • 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 — Descrierea
    • newt_textbox_reflowed — Descrierea
    • newt_textbox_set_height — Descrierea
    • newt_textbox_set_text — Descrierea
    • newt_textbox — Descrierea
    • newt_vertical_scrollbar — Descrierea
    • newt_wait_for_key — Doesn't return until a key has been pressed
    • newt_win_choice — Descrierea
    • newt_win_entries — Descrierea
    • newt_win_menu — Descrierea
    • newt_win_message — Descrierea
    • newt_win_messagev — Descrierea
    • newt_win_ternary — Descrierea
ncurses_wvline
Introducere
Extensii specifice liniei de comanda


Introducere

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 is very similar to the original Newt API of C programming language.

Newt
Instalarea / configurarea
Newt


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Newt


Necesita?i

This module uses the functions of the RedHat Newt library. You need libnewt version >= 0.51.0.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP. Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/newt.

In order to use these functions you must compile CGI or CLI PHP with newt support by using the --with-newt[=DIR] configure option.

Nota:

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

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

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

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Cuprins

  • 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

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Tipurile resurselor
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
Constante predefinite
Newt colorsets
Constante predefinite


Newt colorsets

Newt colorsets
constant | meaning
NEWT_COLORSET_ROOT |
NEWT_COLORSET_BORDER |
NEWT_COLORSET_WINDOW |
NEWT_COLORSET_SHADOW |
NEWT_COLORSET_TITLE |
NEWT_COLORSET_BUTTON |
NEWT_COLORSET_ACTBUTTON |
NEWT_COLORSET_CHECKBOX |
NEWT_COLORSET_ACTCHECKBOX |
NEWT_COLORSET_ENTRY |
NEWT_COLORSET_LABEL |
NEWT_COLORSET_LISTBOX |
NEWT_COLORSET_ACTLISTBOX |
NEWT_COLORSET_TEXTBOX |
NEWT_COLORSET_ACTTEXTBOX |
NEWT_COLORSET_HELPLINE |
NEWT_COLORSET_ROOTTEXT |
NEWT_COLORSET_EMPTYSCALE |
NEWT_COLORSET_FULLSCALE |
NEWT_COLORSET_DISENTRY |
NEWT_COLORSET_COMPACTBUTTON |
NEWT_COLORSET_ACTSELLISTBOX |
NEWT_COLORSET_SELLISTBOX |
Newt form exit reasons
Newt argument flags
Constante predefinite


Newt argument flags

Newt argument flags
constant | meaning
NEWT_ARG_LAST |
NEWT_ARG_APPEND |
Newt colorsets
Newt Flags Sense
Constante predefinite


Newt Flags Sense

Newt Flags Sense
constant | meaning
NEWT_FLAGS_SET |
NEWT_FLAGS_RESET |
NEWT_FLAGS_TOGGLE |
Newt argument flags
Newt Components Flags
Constante predefinite


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
Constante predefinite


File Descriptor Flags

File Descriptor Flags
constant | meaning
NEWT_FD_READ |
NEWT_FD_WRITE |
NEWT_FD_EXCEPT |
Newt Components Flags
Checkbox Tree Flags
Constante predefinite


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
Constante predefinite


Entry Flags

Entry Flags
constant | meaning
NEWT_ENTRY_SCROLL |
NEWT_ENTRY_HIDDEN |
NEWT_ENTRY_RETURNEXIT |
NEWT_ENTRY_DISABLED |
Checkbox Tree Flags
Listbox Flags
Constante predefinite


Listbox Flags

Listbox Flags
constant | meaning
NEWT_LISTBOX_RETURNEXIT |
Entry Flags
Textbox Flags
Constante predefinite


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
Constante predefinite


Form Flags

Form Flags
constant | meaning
NEWT_FORM_NOF12 | Don't exit form on F12 press
Textbox Flags
Newt Keys
Constante predefinite


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
Constante predefinite


Newt Anchors

Newt Anchors
constant | meaning
NEWT_ANCHOR_LEFT |
NEWT_ANCHOR_RIGHT |
NEWT_ANCHOR_TOP |
NEWT_ANCHOR_BOTTOM |
Newt Keys
Grid Flags
Constante predefinite


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
Exemple
Constante predefinite


Exemple

Cuprins

  • Basic usage
Grid Flags
Basic usage
Newt


Basic usage

This example is a PHP port of RedHat 'setup' utility dialog, executed in text mode.

Example #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);
?>
Exemple
Func?ii Newt
Exemple


Func?ii Newt

Cuprins

  • 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 — Descrierea
  • newt_checkbox_tree_get_multi_selection — Descrierea
  • newt_checkbox_tree_get_selection — Descrierea
  • newt_checkbox_tree_multi — Descrierea
  • newt_checkbox_tree_set_current — Descrierea
  • newt_checkbox_tree_set_entry_value — Descrierea
  • newt_checkbox_tree_set_entry — Descrierea
  • newt_checkbox_tree_set_width — Descrierea
  • newt_checkbox_tree — Descrierea
  • newt_checkbox — Descrierea
  • newt_clear_key_buffer — Discards the contents of the terminal's input buffer without waiting for additional input
  • newt_cls — Descrierea
  • newt_compact_button — Descrierea
  • newt_component_add_callback — Descrierea
  • newt_component_takes_focus — Descrierea
  • newt_create_grid — Descrierea
  • newt_cursor_off — Descrierea
  • newt_cursor_on — Descrierea
  • newt_delay — Descrierea
  • newt_draw_form — Descrierea
  • newt_draw_root_text — Displays the string text at the position indicated
  • newt_entry_get_value — Descrierea
  • newt_entry_set_filter — Descrierea
  • newt_entry_set_flags — Descrierea
  • newt_entry_set — Descrierea
  • newt_entry — Descrierea
  • 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 — Descrierea
  • newt_form_destroy — Destroys a form
  • newt_form_get_current — Descrierea
  • newt_form_run — Runs a form
  • newt_form_set_background — Descrierea
  • newt_form_set_height — Descrierea
  • newt_form_set_size — Descrierea
  • newt_form_set_timer — Descrierea
  • newt_form_set_width — Descrierea
  • newt_form_watch_fd — Descrierea
  • 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 — Descrierea
  • newt_grid_basic_window — Descrierea
  • newt_grid_free — Descrierea
  • newt_grid_get_size — Descrierea
  • newt_grid_h_close_stacked — Descrierea
  • newt_grid_h_stacked — Descrierea
  • newt_grid_place — Descrierea
  • newt_grid_set_field — Descrierea
  • newt_grid_simple_window — Descrierea
  • newt_grid_v_close_stacked — Descrierea
  • newt_grid_v_stacked — Descrierea
  • newt_grid_wrapped_window_at — Descrierea
  • newt_grid_wrapped_window — Descrierea
  • newt_init — Initialize newt
  • newt_label_set_text — Descrierea
  • newt_label — Descrierea
  • newt_listbox_append_entry — Descrierea
  • newt_listbox_clear_selection — Descrierea
  • newt_listbox_clear — Descrierea
  • newt_listbox_delete_entry — Descrierea
  • newt_listbox_get_current — Descrierea
  • newt_listbox_get_selection — Descrierea
  • newt_listbox_insert_entry — Descrierea
  • newt_listbox_item_count — Descrierea
  • newt_listbox_select_item — Descrierea
  • newt_listbox_set_current_by_key — Descrierea
  • newt_listbox_set_current — Descrierea
  • newt_listbox_set_data — Descrierea
  • newt_listbox_set_entry — Descrierea
  • newt_listbox_set_width — Descrierea
  • newt_listbox — Descrierea
  • newt_listitem_get_data — Descrierea
  • newt_listitem_set — Descrierea
  • newt_listitem — Descrierea
  • 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 — Descrierea
  • newt_radiobutton — Descrierea
  • newt_redraw_help_line — Descrierea
  • newt_reflow_text — Descrierea
  • newt_refresh — Updates modified portions of the screen
  • newt_resize_screen — Descrierea
  • newt_resume — Resume using the newt interface after calling newt_suspend
  • newt_run_form — Runs a form
  • newt_scale_set — Descrierea
  • newt_scale — Descrierea
  • newt_scrollbar_set — Descrierea
  • newt_set_help_callback — Descrierea
  • 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 — Descrierea
  • newt_textbox_reflowed — Descrierea
  • newt_textbox_set_height — Descrierea
  • newt_textbox_set_text — Descrierea
  • newt_textbox — Descrierea
  • newt_vertical_scrollbar — Descrierea
  • newt_wait_for_key — Doesn't return until a key has been pressed
  • newt_win_choice — Descrierea
  • newt_win_entries — Descrierea
  • newt_win_menu — Descrierea
  • newt_win_message — Descrierea
  • newt_win_messagev — Descrierea
  • newt_win_ternary — Descrierea
Basic usage
newt_bell
Newt


Send a beep to the terminal

Func?ii Newt
newt_button_bar
Func?ii Newt
PHP Manual

newt_bell

(PECL newt >= 0.1)

newt_bell — Send a beep to the terminal

Descrierea

void newt_bell ( void )

This function sends a beep to the terminal.

Nota:

Depending on the terminal's settings, this beep may or may not be audible.

Valorile întoarse

Nu este întoarsa nici o valoare.

Func?ii Newt
newt_button_bar
Func?ii Newt


This function returns a grid containing the buttons created.

newt_bell
newt_button
Func?ii Newt
PHP Manual

newt_button_bar

(PECL newt >= 0.1)

newt_button_bar — This function returns a grid containing the buttons created.

Descrierea

resource newt_button_bar ( array &$buttons )

This function returns a grid containing the buttons created.

Parametri

buttons

Valorile întoarse

Returns grid containing the buttons created.

newt_bell
newt_button
Func?ii Newt


Create a new button

newt_button_bar
newt_centered_window
Func?ii Newt
PHP Manual

newt_button

(PECL newt >= 0.1)

newt_button — Create a new button

Descrierea

resource newt_button ( int $left , int $top , string $text )

Creates a new button.

Parametri

left

X-coordinate of the button.

top

Y-coordinate of the button.

text

The text which should be displayed in the button.

Valorile întoarse

Returns a resource link to the created button component, or FALSE on error.

Exemple

Example #1 A newt_button() example

<?php

$form = newt_form();

$ok_button = newt_button(5, 12, "Run Tool");

newt_form_add_component($form, $ok_button);

?>

A se vedea ?i

  • newt_button_bar() - This function returns a grid containing the buttons created.

newt_button_bar
newt_centered_window
Func?ii Newt


Open a centered window of the specified size

newt_button
newt_checkbox_get_value
Func?ii Newt
PHP Manual

newt_centered_window

(PECL newt >= 0.1)

newt_centered_window — Open a centered window of the specified size

Descrierea

int newt_centered_window ( int $width , int $height [, string $title ] )

Open a centered window of the specified size.

Parametri

width

Window width

height

Window height

title

Window title

Valorile întoarse

Undefined value.

A se vedea ?i

  • 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
Func?ii Newt


Retreives value of checkox resource

newt_centered_window
newt_checkbox_set_flags
Func?ii Newt
PHP Manual

newt_checkbox_get_value

(PECL newt >= 0.1)

newt_checkbox_get_value — Retreives value of checkox resource

Descrierea

string newt_checkbox_get_value ( resource $checkbox )

This function returns the character in the sequence which indicates the current value of the checkbox.

Parametri

checkbox

Valorile întoarse

Returns character indicating the value of the checkbox.

newt_centered_window
newt_checkbox_set_flags
Func?ii Newt


Configures checkbox resource

newt_checkbox_get_value
newt_checkbox_set_value
Func?ii Newt
PHP Manual

newt_checkbox_set_flags

(PECL newt >= 0.1)

newt_checkbox_set_flags — Configures checkbox resource

Descrierea

void newt_checkbox_set_flags ( resource $checkbox , int $flags , int $sense )

This function allows to set various flags on checkbox resource.

Parametri

checkbox

flags

sense

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_checkbox_get_value
newt_checkbox_set_value
Func?ii Newt


Sets the value of the checkbox

newt_checkbox_set_flags
newt_checkbox_tree_add_item
Func?ii Newt
PHP Manual

newt_checkbox_set_value

(PECL newt >= 0.1)

newt_checkbox_set_value — Sets the value of the checkbox

Descrierea

void newt_checkbox_set_value ( resource $checkbox , string $value )

This function allows to set the current value of the checkbox resource.

Parametri

checkbox

value

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_checkbox_set_flags
newt_checkbox_tree_add_item
Func?ii Newt


Adds new item to the checkbox tree

newt_checkbox_set_value
newt_checkbox_tree_find_item
Func?ii Newt
PHP Manual

newt_checkbox_tree_add_item

(PECL newt >= 0.1)

newt_checkbox_tree_add_item — Adds new item to the checkbox tree

Descrierea

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.

Parametri

checkboxtree

text

data

flags

index

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_checkbox_set_value
newt_checkbox_tree_find_item
Func?ii Newt


Finds an item in the checkbox tree

newt_checkbox_tree_add_item
newt_checkbox_tree_get_current
Func?ii Newt
PHP Manual

newt_checkbox_tree_find_item

(PECL newt >= 0.1)

newt_checkbox_tree_find_item — Finds an item in the checkbox tree

Descrierea

array newt_checkbox_tree_find_item ( resource $checkboxtree , mixed $data )

Finds an item in the checkbox tree by item's data.

Parametri

checkboxtree

data

Valorile întoarse

Returns checkbox tree item resource, or NULL if it wasn't found.

newt_checkbox_tree_add_item
newt_checkbox_tree_get_current
Func?ii Newt


Returns checkbox tree selected item

newt_checkbox_tree_find_item
newt_checkbox_tree_get_entry_value
Func?ii Newt
PHP Manual

newt_checkbox_tree_get_current

(PECL newt >= 0.1)

newt_checkbox_tree_get_current — Returns checkbox tree selected item

Descrierea

mixed newt_checkbox_tree_get_current ( resource $checkboxtree )

This method returns checkbox tree selected tem.

Parametri

checkboxtree

Valorile întoarse

Returns current (selected) checkbox tree item.

newt_checkbox_tree_find_item
newt_checkbox_tree_get_entry_value
Func?ii Newt


newt_checkbox_tree_get_current
newt_checkbox_tree_get_multi_selection
Func?ii Newt
PHP Manual

newt_checkbox_tree_get_entry_value

(PECL newt >= 0.1)

newt_checkbox_tree_get_entry_value —

Descrierea

string newt_checkbox_tree_get_entry_value ( resource $checkboxtree , mixed $data )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

checkboxtree

data

Valorile întoarse

newt_checkbox_tree_get_current
newt_checkbox_tree_get_multi_selection
Func?ii Newt


newt_checkbox_tree_get_entry_value
newt_checkbox_tree_get_selection
Func?ii Newt
PHP Manual

newt_checkbox_tree_get_multi_selection

(PECL newt >= 0.1)

newt_checkbox_tree_get_multi_selection —

Descrierea

array newt_checkbox_tree_get_multi_selection ( resource $checkboxtree , string $seqnum )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

checkboxtree

seqnum

Valorile întoarse

newt_checkbox_tree_get_entry_value
newt_checkbox_tree_get_selection
Func?ii Newt


newt_checkbox_tree_get_multi_selection
newt_checkbox_tree_multi
Func?ii Newt
PHP Manual

newt_checkbox_tree_get_selection

(PECL newt >= 0.1)

newt_checkbox_tree_get_selection —

Descrierea

array newt_checkbox_tree_get_selection ( resource $checkboxtree )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

checkboxtree

Valorile întoarse

newt_checkbox_tree_get_multi_selection
newt_checkbox_tree_multi
Func?ii Newt


newt_checkbox_tree_get_selection
newt_checkbox_tree_set_current
Func?ii Newt
PHP Manual

newt_checkbox_tree_multi

(PECL newt >= 0.1)

newt_checkbox_tree_multi —

Descrierea

resource newt_checkbox_tree_multi ( int $left , int $top , int $height , string $seq [, int $flags ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

left

top

height

seq

flags

Valorile întoarse

newt_checkbox_tree_get_selection
newt_checkbox_tree_set_current
Func?ii Newt


newt_checkbox_tree_multi
newt_checkbox_tree_set_entry_value
Func?ii Newt
PHP Manual

newt_checkbox_tree_set_current

(PECL newt >= 0.1)

newt_checkbox_tree_set_current —

Descrierea

void newt_checkbox_tree_set_current ( resource $checkboxtree , mixed $data )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

checkboxtree

data

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_checkbox_tree_multi
newt_checkbox_tree_set_entry_value
Func?ii Newt


newt_checkbox_tree_set_current
newt_checkbox_tree_set_entry
Func?ii Newt
PHP Manual

newt_checkbox_tree_set_entry_value

(PECL newt >= 0.1)

newt_checkbox_tree_set_entry_value —

Descrierea

void newt_checkbox_tree_set_entry_value ( resource $checkboxtree , mixed $data , string $value )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

checkboxtree

data

value

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_checkbox_tree_set_current
newt_checkbox_tree_set_entry
Func?ii Newt


newt_checkbox_tree_set_entry_value
newt_checkbox_tree_set_width
Func?ii Newt
PHP Manual

newt_checkbox_tree_set_entry

(PECL newt >= 0.1)

newt_checkbox_tree_set_entry —

Descrierea

void newt_checkbox_tree_set_entry ( resource $checkboxtree , mixed $data , string $text )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

checkboxtree

data

text

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_checkbox_tree_set_entry_value
newt_checkbox_tree_set_width
Func?ii Newt


newt_checkbox_tree_set_entry
newt_checkbox_tree
Func?ii Newt
PHP Manual

newt_checkbox_tree_set_width

(PECL newt >= 0.1)

newt_checkbox_tree_set_width —

Descrierea

void newt_checkbox_tree_set_width ( resource $checkbox_tree , int $width )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

checkbox_tree

width

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_checkbox_tree_set_entry
newt_checkbox_tree
Func?ii Newt


newt_checkbox_tree_set_width
newt_checkbox
Func?ii Newt
PHP Manual

newt_checkbox_tree

(PECL newt >= 0.1)

newt_checkbox_tree —

Descrierea

resource newt_checkbox_tree ( int $left , int $top , int $height [, int $flags ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

left

top

height

flags

Valorile întoarse

newt_checkbox_tree_set_width
newt_checkbox
Func?ii Newt


newt_checkbox_tree
newt_clear_key_buffer
Func?ii Newt
PHP Manual

newt_checkbox

(PECL newt >= 0.1)

newt_checkbox —

Descrierea

resource newt_checkbox ( int $left , int $top , string $text , string $def_value [, string $seq ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

left

top

text

def_value

seq

Valorile întoarse

newt_checkbox_tree
newt_clear_key_buffer
Func?ii Newt


Discards the contents of the terminal's input buffer without waiting for additional input

newt_checkbox
newt_cls
Func?ii Newt
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

Descrierea

void newt_clear_key_buffer ( void )

Discards the contents of the terminal's input buffer without waiting for additional input.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • newt_wait_for_key() - Doesn't return until a key has been pressed

newt_checkbox
newt_cls
Func?ii Newt


newt_clear_key_buffer
newt_compact_button
Func?ii Newt
PHP Manual

newt_cls

(PECL newt >= 0.1)

newt_cls —

Descrierea

void newt_cls ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_clear_key_buffer
newt_compact_button
Func?ii Newt


newt_cls
newt_component_add_callback
Func?ii Newt
PHP Manual

newt_compact_button

(PECL newt >= 0.1)

newt_compact_button —

Descrierea

resource newt_compact_button ( int $left , int $top , string $text )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

left

top

text

Valorile întoarse

newt_cls
newt_component_add_callback
Func?ii Newt


newt_compact_button
newt_component_takes_focus
Func?ii Newt
PHP Manual

newt_component_add_callback

(PECL newt >= 0.1)

newt_component_add_callback —

Descrierea

void newt_component_add_callback ( resource $component , mixed $func_name , mixed $data )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

component

func_name

data

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_compact_button
newt_component_takes_focus
Func?ii Newt


newt_component_add_callback
newt_create_grid
Func?ii Newt
PHP Manual

newt_component_takes_focus

(PECL newt >= 0.1)

newt_component_takes_focus —

Descrierea

void newt_component_takes_focus ( resource $component , bool $takes_focus )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

component

takes_focus

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_component_add_callback
newt_create_grid
Func?ii Newt


newt_component_takes_focus
newt_cursor_off
Func?ii Newt
PHP Manual

newt_create_grid

(PECL newt >= 0.1)

newt_create_grid —

Descrierea

resource newt_create_grid ( int $cols , int $rows )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

cols

rows

Valorile întoarse

newt_component_takes_focus
newt_cursor_off
Func?ii Newt


newt_create_grid
newt_cursor_on
Func?ii Newt
PHP Manual

newt_cursor_off

(PECL newt >= 0.1)

newt_cursor_off —

Descrierea

void newt_cursor_off ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_create_grid
newt_cursor_on
Func?ii Newt


newt_cursor_off
newt_delay
Func?ii Newt
PHP Manual

newt_cursor_on

(PECL newt >= 0.1)

newt_cursor_on —

Descrierea

void newt_cursor_on ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_cursor_off
newt_delay
Func?ii Newt


newt_cursor_on
newt_draw_form
Func?ii Newt
PHP Manual

newt_delay

(PECL newt >= 0.1)

newt_delay —

Descrierea

void newt_delay ( int $microseconds )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

microseconds

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_cursor_on
newt_draw_form
Func?ii Newt


newt_delay
newt_draw_root_text
Func?ii Newt
PHP Manual

newt_draw_form

(PECL newt >= 0.1)

newt_draw_form —

Descrierea

void newt_draw_form ( resource $form )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

form

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_delay
newt_draw_root_text
Func?ii Newt


Displays the string text at the position indicated

newt_draw_form
newt_entry_get_value
Func?ii Newt
PHP Manual

newt_draw_root_text

(PECL newt >= 0.1)

newt_draw_root_text — Displays the string text at the position indicated

Descrierea

void newt_draw_root_text ( int $left , int $top , string $text )

Displays the string text at the position indicated.

Parametri

left

Column number

Nota:

If left is negative, the position is measured from the opposite side of the screen.

top

Line number

Nota:

If top is negative, the position is measured from the opposite side of the screen.

text

Text to display.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

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

A se vedea ?i

  • 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
Func?ii Newt


newt_draw_root_text
newt_entry_set_filter
Func?ii Newt
PHP Manual

newt_entry_get_value

(PECL newt >= 0.1)

newt_entry_get_value —

Descrierea

string newt_entry_get_value ( resource $entry )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

entry

Valorile întoarse

newt_draw_root_text
newt_entry_set_filter
Func?ii Newt


newt_entry_get_value
newt_entry_set_flags
Func?ii Newt
PHP Manual

newt_entry_set_filter

(PECL newt >= 0.1)

newt_entry_set_filter —

Descrierea

void newt_entry_set_filter ( resource $entry , callable $filter , mixed $data )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

entry

filter

data

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_entry_get_value
newt_entry_set_flags
Func?ii Newt


newt_entry_set_filter
newt_entry_set
Func?ii Newt
PHP Manual

newt_entry_set_flags

(PECL newt >= 0.1)

newt_entry_set_flags —

Descrierea

void newt_entry_set_flags ( resource $entry , int $flags , int $sense )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

entry

flags

sense

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_entry_set_filter
newt_entry_set
Func?ii Newt


newt_entry_set_flags
newt_entry
Func?ii Newt
PHP Manual

newt_entry_set

(PECL newt >= 0.1)

newt_entry_set —

Descrierea

void newt_entry_set ( resource $entry , string $value [, bool $cursor_at_end ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

entry

value

cursor_at_end

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_entry_set_flags
newt_entry
Func?ii Newt


newt_entry_set
newt_finished
Func?ii Newt
PHP Manual

newt_entry

(PECL newt >= 0.1)

newt_entry —

Descrierea

resource newt_entry ( int $left , int $top , int $width [, string $init_value [, int $flags ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

left

top

width

init_value

flags

Valorile întoarse

newt_entry_set
newt_finished
Func?ii Newt


Uninitializes newt interface

newt_entry
newt_form_add_component
Func?ii Newt
PHP Manual

newt_finished

(PECL newt >= 0.1)

newt_finished — Uninitializes newt interface

Descrierea

int newt_finished ( void )

Uninitializes newt interface. This function be called, when program is ready to exit.

Valorile întoarse

Returns 1 on success, 0 on failure.

A se vedea ?i

  • newt_init() - Initialize newt

newt_entry
newt_form_add_component
Func?ii Newt


Adds a single component to the form

newt_finished
newt_form_add_components
Func?ii Newt
PHP Manual

newt_form_add_component

(PECL newt >= 0.1)

newt_form_add_component — Adds a single component to the form

Descrierea

void newt_form_add_component ( resource $form , resource $component )

Adds a single component to the form.

Parametri

form

Form to which component will be added

component

Component to add to the form

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);
?>

A se vedea ?i

  • newt_form_add_components() - Add several components to the form

newt_finished
newt_form_add_components
Func?ii Newt


Add several components to the form

newt_form_add_component
newt_form_add_hot_key
Func?ii Newt
PHP Manual

newt_form_add_components

(PECL newt >= 0.1)

newt_form_add_components — Add several components to the form

Descrierea

void newt_form_add_components ( resource $form , array $components )

Adds several components to the form.

Parametri

form

Form to which components will be added

components

Array of components to add to the form

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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));
?>

A se vedea ?i

  • newt_form_add_component() - Adds a single component to the form

newt_form_add_component
newt_form_add_hot_key
Func?ii Newt


newt_form_add_components
newt_form_destroy
Func?ii Newt
PHP Manual

newt_form_add_hot_key

(PECL newt >= 0.1)

newt_form_add_hot_key —

Descrierea

void newt_form_add_hot_key ( resource $form , int $key )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

form

key

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_form_add_components
newt_form_destroy
Func?ii Newt


Destroys a form

newt_form_add_hot_key
newt_form_get_current
Func?ii Newt
PHP Manual

newt_form_destroy

(PECL newt >= 0.1)

newt_form_destroy — Destroys a form

Descrierea

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.

Parametri

form

Form component, which is going to be destroyed

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • newt_form_run() - Runs a form
  • newt_run_form() - Runs a form

newt_form_add_hot_key
newt_form_get_current
Func?ii Newt


newt_form_destroy
newt_form_run
Func?ii Newt
PHP Manual

newt_form_get_current

(PECL newt >= 0.1)

newt_form_get_current —

Descrierea

resource newt_form_get_current ( resource $form )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

form

Valorile întoarse

newt_form_destroy
newt_form_run
Func?ii Newt


Runs a form

newt_form_get_current
newt_form_set_background
Func?ii Newt
PHP Manual

newt_form_run

(PECL newt >= 0.1)

newt_form_run — Runs a form

Descrierea

void newt_form_run ( resource $form , array &$exit_struct )

This function runs the form passed to it.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • newt_run_form() - Runs a form

newt_form_get_current
newt_form_set_background
Func?ii Newt


newt_form_run
newt_form_set_height
Func?ii Newt
PHP Manual

newt_form_set_background

(PECL newt >= 0.1)

newt_form_set_background —

Descrierea

void newt_form_set_background ( resource $from , int $background )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

from

background

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_form_run
newt_form_set_height
Func?ii Newt


newt_form_set_background
newt_form_set_size
Func?ii Newt
PHP Manual

newt_form_set_height

(PECL newt >= 0.1)

newt_form_set_height —

Descrierea

void newt_form_set_height ( resource $form , int $height )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

form

height

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_form_set_background
newt_form_set_size
Func?ii Newt


newt_form_set_height
newt_form_set_timer
Func?ii Newt
PHP Manual

newt_form_set_size

(PECL newt >= 0.1)

newt_form_set_size —

Descrierea

void newt_form_set_size ( resource $form )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

form

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_form_set_height
newt_form_set_timer
Func?ii Newt


newt_form_set_size
newt_form_set_width
Func?ii Newt
PHP Manual

newt_form_set_timer

(PECL newt >= 0.1)

newt_form_set_timer —

Descrierea

void newt_form_set_timer ( resource $form , int $milliseconds )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

form

milliseconds

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_form_set_size
newt_form_set_width
Func?ii Newt


newt_form_set_timer
newt_form_watch_fd
Func?ii Newt
PHP Manual

newt_form_set_width

(PECL newt >= 0.1)

newt_form_set_width —

Descrierea

void newt_form_set_width ( resource $form , int $width )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

form

width

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_form_set_timer
newt_form_watch_fd
Func?ii Newt


newt_form_set_width
newt_form
Func?ii Newt
PHP Manual

newt_form_watch_fd

(PECL newt >= 0.1)

newt_form_watch_fd —

Descrierea

void newt_form_watch_fd ( resource $form , resource $stream [, int $flags ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

form

stream

flags

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_form_set_width
newt_form
Func?ii Newt


Create a form

newt_form_watch_fd
newt_get_screen_size
Func?ii Newt
PHP Manual

newt_form

(PECL newt >= 0.1)

newt_form — Create a form

Descrierea

resource newt_form ([ resource $vert_bar [, string $help [, int $flags ]]] )

Create a new form.

Parametri

vert_bar

Vertical scrollbar which should be associated with the form

help

Help text string

flags

Various flags

Valorile întoarse

Returns a resource link to the created form component, or FALSE on error.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii Newt


Fills in the passed references with the current size of the terminal

newt_form
newt_grid_add_components_to_form
Func?ii Newt
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

Descrierea

void newt_get_screen_size ( int &$cols , int &$rows )

Fills in the passed references with the current size of the terminal.

Parametri

cols

Number of columns in the terminal

rows

Number of rows in the terminal

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

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

Exemplul de mai sus va afi?a:

Your terminal size is: 138x47

newt_form
newt_grid_add_components_to_form
Func?ii Newt


newt_get_screen_size
newt_grid_basic_window
Func?ii Newt
PHP Manual

newt_grid_add_components_to_form

(PECL newt >= 0.1)

newt_grid_add_components_to_form —

Descrierea

void newt_grid_add_components_to_form ( resource $grid , resource $form , bool $recurse )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

grid

form

recurse

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_get_screen_size
newt_grid_basic_window
Func?ii Newt


newt_grid_add_components_to_form
newt_grid_free
Func?ii Newt
PHP Manual

newt_grid_basic_window

(PECL newt >= 0.1)

newt_grid_basic_window —

Descrierea

resource newt_grid_basic_window ( resource $text , resource $middle , resource $buttons )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

text

middle

buttons

Valorile întoarse

newt_grid_add_components_to_form
newt_grid_free
Func?ii Newt


newt_grid_basic_window
newt_grid_get_size
Func?ii Newt
PHP Manual

newt_grid_free

(PECL newt >= 0.1)

newt_grid_free —

Descrierea

void newt_grid_free ( resource $grid , bool $recurse )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

grid

recurse

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_grid_basic_window
newt_grid_get_size
Func?ii Newt


newt_grid_free
newt_grid_h_close_stacked
Func?ii Newt
PHP Manual

newt_grid_get_size

(PECL newt >= 0.1)

newt_grid_get_size —

Descrierea

void newt_grid_get_size ( resouce $grid , int &$width , int &$height )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

grid

width

height

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_grid_free
newt_grid_h_close_stacked
Func?ii Newt


newt_grid_get_size
newt_grid_h_stacked
Func?ii Newt
PHP Manual

newt_grid_h_close_stacked

(PECL newt >= 0.1)

newt_grid_h_close_stacked —

Descrierea

resource newt_grid_h_close_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

element1_type

element1

Valorile întoarse

newt_grid_get_size
newt_grid_h_stacked
Func?ii Newt


newt_grid_h_close_stacked
newt_grid_place
Func?ii Newt
PHP Manual

newt_grid_h_stacked

(PECL newt >= 0.1)

newt_grid_h_stacked —

Descrierea

resource newt_grid_h_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

element1_type

element1

Valorile întoarse

newt_grid_h_close_stacked
newt_grid_place
Func?ii Newt


newt_grid_h_stacked
newt_grid_set_field
Func?ii Newt
PHP Manual

newt_grid_place

(PECL newt >= 0.1)

newt_grid_place —

Descrierea

void newt_grid_place ( resource $grid , int $left , int $top )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

grid

left

top

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_grid_h_stacked
newt_grid_set_field
Func?ii Newt


newt_grid_place
newt_grid_simple_window
Func?ii Newt
PHP Manual

newt_grid_set_field

(PECL newt >= 0.1)

newt_grid_set_field —

Descrierea

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 ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

grid

col

row

type

val

pad_left

pad_top

pad_right

pad_bottom

anchor

flags

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_grid_place
newt_grid_simple_window
Func?ii Newt


newt_grid_set_field
newt_grid_v_close_stacked
Func?ii Newt
PHP Manual

newt_grid_simple_window

(PECL newt >= 0.1)

newt_grid_simple_window —

Descrierea

resource newt_grid_simple_window ( resource $text , resource $middle , resource $buttons )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

text

middle

buttons

Valorile întoarse

newt_grid_set_field
newt_grid_v_close_stacked
Func?ii Newt


newt_grid_simple_window
newt_grid_v_stacked
Func?ii Newt
PHP Manual

newt_grid_v_close_stacked

(PECL newt >= 0.1)

newt_grid_v_close_stacked —

Descrierea

resource newt_grid_v_close_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

element1_type

element1

Valorile întoarse

newt_grid_simple_window
newt_grid_v_stacked
Func?ii Newt


newt_grid_v_close_stacked
newt_grid_wrapped_window_at
Func?ii Newt
PHP Manual

newt_grid_v_stacked

(PECL newt >= 0.1)

newt_grid_v_stacked —

Descrierea

resource newt_grid_v_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

element1_type

element1

Valorile întoarse

newt_grid_v_close_stacked
newt_grid_wrapped_window_at
Func?ii Newt


newt_grid_v_stacked
newt_grid_wrapped_window
Func?ii Newt
PHP Manual

newt_grid_wrapped_window_at

(PECL newt >= 0.1)

newt_grid_wrapped_window_at —

Descrierea

void newt_grid_wrapped_window_at ( resource $grid , string $title , int $left , int $top )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

grid

title

left

top

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_grid_v_stacked
newt_grid_wrapped_window
Func?ii Newt


newt_grid_wrapped_window_at
newt_init
Func?ii Newt
PHP Manual

newt_grid_wrapped_window

(PECL newt >= 0.1)

newt_grid_wrapped_window —

Descrierea

void newt_grid_wrapped_window ( resource $grid , string $title )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

grid

title

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_grid_wrapped_window_at
newt_init
Func?ii Newt


Initialize newt

newt_grid_wrapped_window
newt_label_set_text
Func?ii Newt
PHP Manual

newt_init

(PECL newt >= 0.1)

newt_init — Initialize newt

Descrierea

int newt_init ( void )

Initializes the newt interface. This function must be called before any other newt function.

Valorile întoarse

Returns 1 on success, 0 on failure.

A se vedea ?i

  • newt_finished() - Uninitializes newt interface

newt_grid_wrapped_window
newt_label_set_text
Func?ii Newt


newt_init
newt_label
Func?ii Newt
PHP Manual

newt_label_set_text

(PECL newt >= 0.1)

newt_label_set_text —

Descrierea

void newt_label_set_text ( resource $label , string $text )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

label

text

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_init
newt_label
Func?ii Newt


newt_label_set_text
newt_listbox_append_entry
Func?ii Newt
PHP Manual

newt_label

(PECL newt >= 0.1)

newt_label —

Descrierea

resource newt_label ( int $left , int $top , string $text )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

left

top

text

Valorile întoarse

newt_label_set_text
newt_listbox_append_entry
Func?ii Newt


newt_label
newt_listbox_clear_selection
Func?ii Newt
PHP Manual

newt_listbox_append_entry

(PECL newt >= 0.1)

newt_listbox_append_entry —

Descrierea

void newt_listbox_append_entry ( resource $listbox , string $text , mixed $data )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listbox

text

data

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_label
newt_listbox_clear_selection
Func?ii Newt


newt_listbox_append_entry
newt_listbox_clear
Func?ii Newt
PHP Manual

newt_listbox_clear_selection

(PECL newt >= 0.1)

newt_listbox_clear_selection —

Descrierea

void newt_listbox_clear_selection ( resource $listbox )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listbox

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_listbox_append_entry
newt_listbox_clear
Func?ii Newt


newt_listbox_clear_selection
newt_listbox_delete_entry
Func?ii Newt
PHP Manual

newt_listbox_clear

(PECL newt >= 0.1)

newt_listbox_clear —

Descrierea

void newt_listbox_clear ( resource $listobx )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listobx

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_listbox_clear_selection
newt_listbox_delete_entry
Func?ii Newt


newt_listbox_clear
newt_listbox_get_current
Func?ii Newt
PHP Manual

newt_listbox_delete_entry

(PECL newt >= 0.1)

newt_listbox_delete_entry —

Descrierea

void newt_listbox_delete_entry ( resource $listbox , mixed $key )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listbox

key

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_listbox_clear
newt_listbox_get_current
Func?ii Newt


newt_listbox_delete_entry
newt_listbox_get_selection
Func?ii Newt
PHP Manual

newt_listbox_get_current

(PECL newt >= 0.1)

newt_listbox_get_current —

Descrierea

string newt_listbox_get_current ( resource $listbox )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listbox

Valorile întoarse

newt_listbox_delete_entry
newt_listbox_get_selection
Func?ii Newt


newt_listbox_get_current
newt_listbox_insert_entry
Func?ii Newt
PHP Manual

newt_listbox_get_selection

(PECL newt >= 0.1)

newt_listbox_get_selection —

Descrierea

array newt_listbox_get_selection ( resource $listbox )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listbox

Valorile întoarse

newt_listbox_get_current
newt_listbox_insert_entry
Func?ii Newt


newt_listbox_get_selection
newt_listbox_item_count
Func?ii Newt
PHP Manual

newt_listbox_insert_entry

(PECL newt >= 0.1)

newt_listbox_insert_entry —

Descrierea

void newt_listbox_insert_entry ( resource $listbox , string $text , mixed $data , mixed $key )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listbox

text

data

key

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_listbox_get_selection
newt_listbox_item_count
Func?ii Newt


newt_listbox_insert_entry
newt_listbox_select_item
Func?ii Newt
PHP Manual

newt_listbox_item_count

(PECL newt >= 0.1)

newt_listbox_item_count —

Descrierea

int newt_listbox_item_count ( resource $listbox )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listbox

Valorile întoarse

newt_listbox_insert_entry
newt_listbox_select_item
Func?ii Newt


newt_listbox_item_count
newt_listbox_set_current_by_key
Func?ii Newt
PHP Manual

newt_listbox_select_item

(PECL newt >= 0.1)

newt_listbox_select_item —

Descrierea

void newt_listbox_select_item ( resource $listbox , mixed $key , int $sense )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listbox

key

sense

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_listbox_item_count
newt_listbox_set_current_by_key
Func?ii Newt


newt_listbox_select_item
newt_listbox_set_current
Func?ii Newt
PHP Manual

newt_listbox_set_current_by_key

(PECL newt >= 0.1)

newt_listbox_set_current_by_key —

Descrierea

void newt_listbox_set_current_by_key ( resource $listbox , mixed $key )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listbox

key

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_listbox_select_item
newt_listbox_set_current
Func?ii Newt


newt_listbox_set_current_by_key
newt_listbox_set_data
Func?ii Newt
PHP Manual

newt_listbox_set_current

(PECL newt >= 0.1)

newt_listbox_set_current —

Descrierea

void newt_listbox_set_current ( resource $listbox , int $num )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listbox

num

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_listbox_set_current_by_key
newt_listbox_set_data
Func?ii Newt


newt_listbox_set_current
newt_listbox_set_entry
Func?ii Newt
PHP Manual

newt_listbox_set_data

(PECL newt >= 0.1)

newt_listbox_set_data —

Descrierea

void newt_listbox_set_data ( resource $listbox , int $num , mixed $data )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listbox

num

data

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_listbox_set_current
newt_listbox_set_entry
Func?ii Newt


newt_listbox_set_data
newt_listbox_set_width
Func?ii Newt
PHP Manual

newt_listbox_set_entry

(PECL newt >= 0.1)

newt_listbox_set_entry —

Descrierea

void newt_listbox_set_entry ( resource $listbox , int $num , string $text )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listbox

num

text

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_listbox_set_data
newt_listbox_set_width
Func?ii Newt


newt_listbox_set_entry
newt_listbox
Func?ii Newt
PHP Manual

newt_listbox_set_width

(PECL newt >= 0.1)

newt_listbox_set_width —

Descrierea

void newt_listbox_set_width ( resource $listbox , int $width )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

listbox

width

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_listbox_set_entry
newt_listbox
Func?ii Newt


newt_listbox_set_width
newt_listitem_get_data
Func?ii Newt
PHP Manual

newt_listbox

(PECL newt >= 0.1)

newt_listbox —

Descrierea

resource newt_listbox ( int $left , int $top , int $height [, int $flags ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

left

top

height

flags

Valorile întoarse

newt_listbox_set_width
newt_listitem_get_data
Func?ii Newt


newt_listbox
newt_listitem_set
Func?ii Newt
PHP Manual

newt_listitem_get_data

(PECL newt >= 0.1)

newt_listitem_get_data —

Descrierea

mixed newt_listitem_get_data ( resource $item )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

item

Valorile întoarse

newt_listbox
newt_listitem_set
Func?ii Newt


newt_listitem_get_data
newt_listitem
Func?ii Newt
PHP Manual

newt_listitem_set

(PECL newt >= 0.1)

newt_listitem_set —

Descrierea

void newt_listitem_set ( resource $item , string $text )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

item

text

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_listitem_get_data
newt_listitem
Func?ii Newt


newt_listitem_set
newt_open_window
Func?ii Newt
PHP Manual

newt_listitem

(PECL newt >= 0.1)

newt_listitem —

Descrierea

resource newt_listitem ( int $left , int $top , string $text , bool $is_default , resouce $prev_item , mixed $data [, int $flags ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

left

top

text

is_default

prev_item

data

flags

Valorile întoarse

newt_listitem_set
newt_open_window
Func?ii Newt


Open a window of the specified size and position

newt_listitem
newt_pop_help_line
Func?ii Newt
PHP Manual

newt_open_window

(PECL newt >= 0.1)

newt_open_window — Open a window of the specified size and position

Descrierea

int newt_open_window ( int $left , int $top , int $width , int $height [, string $title ] )

Open a window of the specified size and position.

Parametri

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

Valorile întoarse

Returns 1 on success, 0 on failure.

A se vedea ?i

  • 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
Func?ii Newt


Replaces the current help line with the one from the stack

newt_open_window
newt_pop_window
Func?ii Newt
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

Descrierea

void newt_pop_help_line ( void )

Replaces the current help line with the one from the stack.

Nota:

It's important not to call to newt_pop_help_line() more than newt_push_help_line().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • newt_push_help_line() - Saves the current help line on a stack, and displays the new line

newt_open_window
newt_pop_window
Func?ii Newt


Removes the top window from the display

newt_pop_help_line
newt_push_help_line
Func?ii Newt
PHP Manual

newt_pop_window

(PECL newt >= 0.1)

newt_pop_window — Removes the top window from the display

Descrierea

void newt_pop_window ( void )

Removes the top window from the display, and redraws the display areas which the window overwrote.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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
Func?ii Newt


Saves the current help line on a stack, and displays the new line

newt_pop_window
newt_radio_get_current
Func?ii Newt
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

Descrierea

void newt_push_help_line ([ string $text ] )

Saves the current help line on a stack, and displays the new line.

Parametri

text

New help text message

Nota:

If not specified, the help line is cleared.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • newt_pop_help_line() - Replaces the current help line with the one from the stack

newt_pop_window
newt_radio_get_current
Func?ii Newt


newt_push_help_line
newt_radiobutton
Func?ii Newt
PHP Manual

newt_radio_get_current

(PECL newt >= 0.1)

newt_radio_get_current —

Descrierea

resource newt_radio_get_current ( resource $set_member )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

set_member

Valorile întoarse

newt_push_help_line
newt_radiobutton
Func?ii Newt


newt_radio_get_current
newt_redraw_help_line
Func?ii Newt
PHP Manual

newt_radiobutton

(PECL newt >= 0.1)

newt_radiobutton —

Descrierea

resource newt_radiobutton ( int $left , int $top , string $text , bool $is_default [, resource $prev_button ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

left

top

text

is_default

prev_button

Valorile întoarse

newt_radio_get_current
newt_redraw_help_line
Func?ii Newt


newt_radiobutton
newt_reflow_text
Func?ii Newt
PHP Manual

newt_redraw_help_line

(PECL newt >= 0.1)

newt_redraw_help_line —

Descrierea

void newt_redraw_help_line ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_radiobutton
newt_reflow_text
Func?ii Newt


newt_redraw_help_line
newt_refresh
Func?ii Newt
PHP Manual

newt_reflow_text

(PECL newt >= 0.1)

newt_reflow_text —

Descrierea

string newt_reflow_text ( string $text , int $width , int $flex_down , int $flex_up , int &$actual_width , int &$actual_height )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

text

width

flex_down

flex_up

actual_width

actual_height

Valorile întoarse

newt_redraw_help_line
newt_refresh
Func?ii Newt


Updates modified portions of the screen

newt_reflow_text
newt_resize_screen
Func?ii Newt
PHP Manual

newt_refresh

(PECL newt >= 0.1)

newt_refresh — Updates modified portions of the screen

Descrierea

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_reflow_text
newt_resize_screen
Func?ii Newt


newt_refresh
newt_resume
Func?ii Newt
PHP Manual

newt_resize_screen

(PECL newt >= 0.1)

newt_resize_screen —

Descrierea

void newt_resize_screen ([ bool $redraw ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

redraw

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_refresh
newt_resume
Func?ii Newt


Resume using the newt interface after calling newt_suspend

newt_resize_screen
newt_run_form
Func?ii Newt
PHP Manual

newt_resume

(PECL newt >= 0.1)

newt_resume — Resume using the newt interface after calling newt_suspend()

Descrierea

void newt_resume ( void )

Resume using the newt interface after calling newt_suspend().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • newt_suspend() - Tells newt to return the terminal to its initial state

newt_resize_screen
newt_run_form
Func?ii Newt


Runs a form

newt_resume
newt_scale_set
Func?ii Newt
PHP Manual

newt_run_form

(PECL newt >= 0.1)

newt_run_form — Runs a form

Descrierea

resource newt_run_form ( resource $form )

This function runs the form passed to it.

Parametri

form

Form component

Valorile întoarse

The component which caused the form to stop running.

Nota:

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.

A se vedea ?i

  • newt_form_run() - Runs a form
  • newt_form_destroy() - Destroys a form

newt_resume
newt_scale_set
Func?ii Newt


newt_run_form
newt_scale
Func?ii Newt
PHP Manual

newt_scale_set

(PECL newt >= 0.1)

newt_scale_set —

Descrierea

void newt_scale_set ( resource $scale , int $amount )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

scale

amount

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_run_form
newt_scale
Func?ii Newt


newt_scale_set
newt_scrollbar_set
Func?ii Newt
PHP Manual

newt_scale

(PECL newt >= 0.1)

newt_scale —

Descrierea

resource newt_scale ( int $left , int $top , int $width , int $full_value )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

left

top

width

full_value

Valorile întoarse

newt_scale_set
newt_scrollbar_set
Func?ii Newt


newt_scale
newt_set_help_callback
Func?ii Newt
PHP Manual

newt_scrollbar_set

(PECL newt >= 0.1)

newt_scrollbar_set —

Descrierea

void newt_scrollbar_set ( resource $scrollbar , int $where , int $total )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

scrollbar

where

total

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_scale
newt_set_help_callback
Func?ii Newt


newt_scrollbar_set
newt_set_suspend_callback
Func?ii Newt
PHP Manual

newt_set_help_callback

(PECL newt >= 0.1)

newt_set_help_callback —

Descrierea

void newt_set_help_callback ( mixed $function )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

function

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_scrollbar_set
newt_set_suspend_callback
Func?ii Newt


Set a callback function which gets invoked when user presses the suspend key

newt_set_help_callback
newt_suspend
Func?ii Newt
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

Descrierea

void newt_set_suspend_callback ( callable $function , mixed $data )

Set a callback function which gets invoked when user presses the suspend key (normally ^Z). If no suspend callback is registered, the suspend keystroke is ignored.

Parametri

function

A callback function, which accepts one argument: data

data

This data is been passed to the callback function

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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
Func?ii Newt


Tells newt to return the terminal to its initial state

newt_set_suspend_callback
newt_textbox_get_num_lines
Func?ii Newt
PHP Manual

newt_suspend

(PECL newt >= 0.1)

newt_suspend — Tells newt to return the terminal to its initial state

Descrierea

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

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • newt_resume() - Resume using the newt interface after calling newt_suspend

newt_set_suspend_callback
newt_textbox_get_num_lines
Func?ii Newt


newt_suspend
newt_textbox_reflowed
Func?ii Newt
PHP Manual

newt_textbox_get_num_lines

(PECL newt >= 0.1)

newt_textbox_get_num_lines —

Descrierea

int newt_textbox_get_num_lines ( resource $textbox )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

textbox

Valorile întoarse

newt_suspend
newt_textbox_reflowed
Func?ii Newt


newt_textbox_get_num_lines
newt_textbox_set_height
Func?ii Newt
PHP Manual

newt_textbox_reflowed

(PECL newt >= 0.1)

newt_textbox_reflowed —

Descrierea

resource newt_textbox_reflowed ( int $left , int $top , char $*text , int $width , int $flex_down , int $flex_up [, int $flags ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

left

top

*text

width

flex_down

flex_up

flags

Valorile întoarse

newt_textbox_get_num_lines
newt_textbox_set_height
Func?ii Newt


newt_textbox_reflowed
newt_textbox_set_text
Func?ii Newt
PHP Manual

newt_textbox_set_height

(PECL newt >= 0.1)

newt_textbox_set_height —

Descrierea

void newt_textbox_set_height ( resource $textbox , int $height )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

textbox

height

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_textbox_reflowed
newt_textbox_set_text
Func?ii Newt


newt_textbox_set_height
newt_textbox
Func?ii Newt
PHP Manual

newt_textbox_set_text

(PECL newt >= 0.1)

newt_textbox_set_text —

Descrierea

void newt_textbox_set_text ( resource $textbox , string $text )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

textbox

text

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_textbox_set_height
newt_textbox
Func?ii Newt


newt_textbox_set_text
newt_vertical_scrollbar
Func?ii Newt
PHP Manual

newt_textbox

(PECL newt >= 0.1)

newt_textbox —

Descrierea

resource newt_textbox ( int $left , int $top , int $width , int $height [, int $flags ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

left

top

width

height

flags

Valorile întoarse

newt_textbox_set_text
newt_vertical_scrollbar
Func?ii Newt


newt_textbox
newt_wait_for_key
Func?ii Newt
PHP Manual

newt_vertical_scrollbar

(PECL newt >= 0.1)

newt_vertical_scrollbar —

Descrierea

resource newt_vertical_scrollbar ( int $left , int $top , int $height [, int $normal_colorset [, int $thumb_colorset ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

left

top

height

normal_colorset

thumb_colorset

Valorile întoarse

newt_textbox
newt_wait_for_key
Func?ii Newt


Doesn't return until a key has been pressed

newt_vertical_scrollbar
newt_win_choice
Func?ii Newt
PHP Manual

newt_wait_for_key

(PECL newt >= 0.1)

newt_wait_for_key — Doesn't return until a key has been pressed

Descrierea

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • newt_clear_key_buffer() - Discards the contents of the terminal's input buffer without waiting for additional input

newt_vertical_scrollbar
newt_win_choice
Func?ii Newt


newt_wait_for_key
newt_win_entries
Func?ii Newt
PHP Manual

newt_win_choice

(PECL newt >= 0.1)

newt_win_choice —

Descrierea

int newt_win_choice ( string $title , string $button1_text , string $button2_text , string $format [, mixed $args [, mixed $... ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

title

button1_text

button2_text

format

args

Valorile întoarse

newt_wait_for_key
newt_win_entries
Func?ii Newt


newt_win_choice
newt_win_menu
Func?ii Newt
PHP Manual

newt_win_entries

(PECL newt >= 0.1)

newt_win_entries —

Descrierea

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 $... ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

title

text

suggested_width

flex_down

flex_up

data_width

items

button1

button2

Valorile întoarse

Exemple

Example #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
Func?ii Newt


newt_win_entries
newt_win_message
Func?ii Newt
PHP Manual

newt_win_menu

(PECL newt >= 0.1)

newt_win_menu —

Descrierea

int newt_win_menu ( string $title , string $text , int $suggestedWidth , int $flexDown , int $flexUp , int $maxListHeight , array $items , int &$listItem [, string $button1 [, string $... ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

title

text

suggestedWidth

flexDown

flexUp

maxListHeight

items

listItem

button1

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_win_entries
newt_win_message
Func?ii Newt


newt_win_menu
newt_win_messagev
Func?ii Newt
PHP Manual

newt_win_message

(PECL newt >= 0.1)

newt_win_message —

Descrierea

void newt_win_message ( string $title , string $button_text , string $format [, mixed $args [, mixed $... ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

title

button_text

format

args

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_win_menu
newt_win_messagev
Func?ii Newt


newt_win_message
newt_win_ternary
Func?ii Newt
PHP Manual

newt_win_messagev

(PECL newt >= 0.1)

newt_win_messagev —

Descrierea

void newt_win_messagev ( string $title , string $button_text , string $format , array $args )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

title

button_text

format

args

Valorile întoarse

Nu este întoarsa nici o valoare.

newt_win_message
newt_win_ternary
Func?ii Newt


newt_win_messagev
Readline
Func?ii Newt
PHP Manual

newt_win_ternary

(PECL newt >= 0.1)

newt_win_ternary —

Descrierea

int newt_win_ternary ( string $title , string $button1_text , string $button2_text , string $button3_text , string $format [, mixed $args [, mixed $... ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

title

Its description

button1_text

Its description

button2_text

Its description

button3_text

Its description

format

Its description

args

Its description

Valorile întoarse

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_win_messagev
Readline
Func?ii Newt


GNU Readline

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Readline
    • readline_add_history — Adds a line to the history
    • 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 — Clears the history
    • readline_completion_function — Registers a completion function
    • readline_info — Gets/sets various internal readline variables
    • readline_list_history — Lists the history
    • readline_on_new_line — Inform readline that the cursor has moved to a new line
    • readline_read_history — Reads the history
    • readline_redisplay — Redraws the display
    • readline_write_history — Writes the history
    • readline — Reads a line
newt_win_ternary
Introducere
Extensii specifice liniei de comanda


Introducere

Func?iile readline implementeaza o interfa?a catre biblioteca GNU Readline. Acestea sunt func?ii ce ofera linii de comanda redactabile. Ca exemplu poate servi modul în care Bash va permite utilizarea tastelor-sage?i pentru a insera caractere sau pentru a naviga prin istoricul comenzilor. Din cauza naturii interactive a acestei biblioteci, ea va fi de pu?in folos la scrierea aplica?iilor Web, însa poate fi utila la scrierea script-urilor utilizate în linia de comanda.

Nota: Aceasta extensie nu este disponibila pe platformele Windows.

Readline
Instalarea / configurarea
Readline


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Readline


Necesita?i

Pentru a utiliza func?iile readline, trebuie sa instala?i libreadline. Pute?i gasi libreadline pe pagina de baza a proiectului GNU Readline, la adresa » http://cnswww.cns.cwru.edu/~chet/readline/rltop.html. Ea este între?inuta de Chet Ramey, care este de asemenea autorul Bash.

De asemenea pute?i utiliza aceste func?ii cu biblioteca libedit, un înlocuitor non-GPL al bibliotecii readline. Biblioteca libedit este licen?iata BSD ?i este disponibila pentru descarcare la adresa » http://www.thrysoee.dk/editline/.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Pentru utilizatea acestor func?ii este necesara compilarea versiunii CGI sau CLI a PHP cu sus?inerea readline. Este necesara configurarea PHP cu op?iunea --with-readline[=DIR] . Daca dori?i sa utiliza?i înlocuitorul readline -- libedit -- configura?i PHP cu op?iunea --with-libedit[=DIR] .

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Readline Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
cli.pager | "" | PHP_INI_ALL | Available since PHP 5.4.0.
cli.prompt | "\\b \\> " | PHP_INI_ALL | Available since PHP 5.4.0.

Iata o explica?ie pe scurt a directivelor de configurare.

cli.pager string

External tool to display output from command line.

cli.prompt string

Command line prompt.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii Readline
Readline


Func?ii Readline

Cuprins

  • readline_add_history — Adds a line to the history
  • 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 — Clears the history
  • readline_completion_function — Registers a completion function
  • readline_info — Gets/sets various internal readline variables
  • readline_list_history — Lists the history
  • readline_on_new_line — Inform readline that the cursor has moved to a new line
  • readline_read_history — Reads the history
  • readline_redisplay — Redraws the display
  • readline_write_history — Writes the history
  • readline — Reads a line
Constante predefinite
readline_add_history
Readline


Adds a line to the history

Func?ii Readline
readline_callback_handler_install
Func?ii Readline
PHP Manual

readline_add_history

(PHP 4, PHP 5, PHP 7)

readline_add_history — Adds a line to the history

Descrierea

bool readline_add_history ( string $line )

This function adds a line to the command line history.

Parametri

line

The line to be added in the history.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Func?ii Readline
readline_callback_handler_install
Func?ii Readline


Initializes the readline callback interface and terminal, prints the prompt and returns immediately

readline_add_history
readline_callback_handler_remove
Func?ii Readline
PHP Manual

readline_callback_handler_install

(PHP 5 >= 5.1.0, PHP 7)

readline_callback_handler_install — Initializes the readline callback interface and terminal, prints the prompt and returns immediately

Descrierea

bool readline_callback_handler_install ( string $prompt , callable $callback )

Sets up a readline callback interface then prints prompt and immediately returns. Calling this function twice without removing the previous callback interface will automatically and conveniently overwrite the old interface.

The callback feature is useful when combined with stream_select() as it allows interleaving of IO and user input, unlike readline().

Parametri

prompt

The prompt message.

callback

The callback function takes one parameter; the user input returned.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

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

A se vedea ?i

  • 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
Func?ii Readline


Removes a previously installed callback handler and restores terminal settings

readline_callback_handler_install
readline_callback_read_char
Func?ii Readline
PHP Manual

readline_callback_handler_remove

(PHP 5 >= 5.1.0, PHP 7)

readline_callback_handler_remove — Removes a previously installed callback handler and restores terminal settings

Descrierea

bool readline_callback_handler_remove ( void )

Removes a previously installed callback handler and restores terminal settings.

Valorile întoarse

Returns TRUE if a previously installed callback handler was removed, or FALSE if one could not be found.

Exemple

See readline_callback_handler_install() for an example of how to use the readline callback interface.

A se vedea ?i

  • 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
Func?ii Readline


Reads a character and informs the readline callback interface when a line is received

readline_callback_handler_remove
readline_clear_history
Func?ii Readline
PHP Manual

readline_callback_read_char

(PHP 5 >= 5.1.0, PHP 7)

readline_callback_read_char — Reads a character and informs the readline callback interface when a line is received

Descrierea

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

See readline_callback_handler_install() for an example of how to use the readline callback interface.

A se vedea ?i

  • 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
Func?ii Readline


Clears the history

readline_callback_read_char
readline_completion_function
Func?ii Readline
PHP Manual

readline_clear_history

(PHP 4, PHP 5, PHP 7)

readline_clear_history — Clears the history

Descrierea

bool readline_clear_history ( void )

This function clears the entire command line history.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

readline_callback_read_char
readline_completion_function
Func?ii Readline


Registers a completion function

readline_clear_history
readline_info
Func?ii Readline
PHP Manual

readline_completion_function

(PHP 4, PHP 5, PHP 7)

readline_completion_function — Registers a completion function

Descrierea

bool readline_completion_function ( callable $function )

This function registers a completion function. This is the same kind of functionality you'd get if you hit your tab key while using Bash.

Parametri

function

You must supply the name of an existing function which accepts a partial command line and returns an array of possible matches.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

readline_clear_history
readline_info
Func?ii Readline


Gets/sets various internal readline variables

readline_completion_function
readline_list_history
Func?ii Readline
PHP Manual

readline_info

(PHP 4, PHP 5, PHP 7)

readline_info — Gets/sets various internal readline variables

Descrierea

mixed readline_info ([ string $varname [, string $newvalue ]] )

Gets or sets various internal readline variables.

Parametri

varname

A variable name.

newvalue

If provided, this will be the new value of the setting.

Valorile întoarse

If called with no parameters, this function returns an array of values for all the setting readline uses. The elements will be indexed by the following values: done, end, erase_empty_line, library_version, line_buffer, mark, pending_input, point, prompt, readline_name, and terminal_name.

If called with one or two parameters, the old value is returned.

readline_completion_function
readline_list_history
Func?ii Readline


Lists the history

readline_info
readline_on_new_line
Func?ii Readline
PHP Manual

readline_list_history

(PHP 4, PHP 5, PHP 7)

readline_list_history — Lists the history

Descrierea

array readline_list_history ( void )

Gets the entire command line history.

Valorile întoarse

Returns an array of the entire command line history. The elements are indexed by integers starting at zero.

readline_info
readline_on_new_line
Func?ii Readline


Inform readline that the cursor has moved to a new line

readline_list_history
readline_read_history
Func?ii Readline
PHP Manual

readline_on_new_line

(PHP 5 >= 5.1.0, PHP 7)

readline_on_new_line — Inform readline that the cursor has moved to a new line

Descrierea

void readline_on_new_line ( void )

Tells readline that the cursor has moved to a new line.

Valorile întoarse

Nu este întoarsa nici o valoare.

readline_list_history
readline_read_history
Func?ii Readline


Reads the history

readline_on_new_line
readline_redisplay
Func?ii Readline
PHP Manual

readline_read_history

(PHP 4, PHP 5, PHP 7)

readline_read_history — Reads the history

Descrierea

bool readline_read_history ([ string $filename ] )

This function reads a command history from a file.

Parametri

filename

Path to the filename containing the command history.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

readline_on_new_line
readline_redisplay
Func?ii Readline


Redraws the display

readline_read_history
readline_write_history
Func?ii Readline
PHP Manual

readline_redisplay

(PHP 5 >= 5.1.0, PHP 7)

readline_redisplay — Redraws the display

Descrierea

void readline_redisplay ( void )

Redraws readline to redraw the display.

Valorile întoarse

Nu este întoarsa nici o valoare.

readline_read_history
readline_write_history
Func?ii Readline


Writes the history

readline_redisplay
readline
Func?ii Readline
PHP Manual

readline_write_history

(PHP 4, PHP 5, PHP 7)

readline_write_history — Writes the history

Descrierea

bool readline_write_history ([ string $filename ] )

This function writes the command history to a file.

Parametri

filename

Path to the saved file.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

readline_redisplay
readline
Func?ii Readline


Reads a line

readline_write_history
Extensii de compresie ?i arhivare
Func?ii Readline
PHP Manual

readline

(PHP 4, PHP 5, PHP 7)

readline — Reads a line

Descrierea

string readline ([ string $prompt ] )

Reads a single line from the user. You must add this line to the history yourself using readline_add_history().

Parametri

prompt

You may specify a string with which to prompt the user.

Valorile întoarse

Returns a single string from the user. The line returned has the ending newline removed.

Exemple

Example #1 readline() Example

<?php
//get 3 commands from user
for ($i=0; $i < 3; $i++) {
        $line = readline("Command: ");
        readline_add_history($line);
}

//dump history
print_r(readline_list_history());

//dump variables
print_r(readline_info());
?>

readline_write_history
Extensii de compresie ?i arhivare
Func?ii Readline


Extensii de compresie ?i arhivare

  • Bzip2
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Bzip2
  • LZF
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii LZF
  • Phar
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • 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
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Rar
    • RarArchive — The RarArchive class
    • RarEntry — The RarEntry class
    • RarException — The RarException class
  • Zip
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • ZipArchive — The ZipArchive class
    • Func?ii Zip
  • Zlib — Zlib Compression
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Zlib
readline
Bzip2
Informa?ii de referin?a despre func?ii


Bzip2

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii Bzip2
    • bzclose — Close a bzip2 file
    • bzcompress — Compress a string into bzip2 encoded data
    • bzdecompress — Decompresses bzip2 encoded data
    • bzerrno — Returns a bzip2 error number
    • bzerror — Returns the bzip2 error number and error string in an array
    • bzerrstr — Returns a bzip2 error string
    • bzflush — Force a write of all buffered data
    • bzopen — Opens a bzip2 compressed file
    • bzread — Binary safe bzip2 file read
    • bzwrite — Binary safe bzip2 file write
Extensii de compresie ?i arhivare
Introducere
Extensii de compresie ?i arhivare


Introducere

The bzip2 functions are used to transparently read and write bzip2 (.bz2) compressed files.

Bzip2
Instalarea / configurarea
Bzip2


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Bzip2


Necesita?i

This module uses the functions of the » bzip2 library by Julian Seward. This module requires bzip2/libbzip2 version >= 1.0.x.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Sus?inerea Bzip2 în PHP nu este activata implicit. Trebuie sa utiliza?i op?iunea de configurare --with-bz2[=DIR] la momentul compilarii PHP pentru a activa sus?inerea bzip2.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

This extension defines one resource type: a file pointer identifying the bz2-file to work on.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
Bzip2


Exemple

This example opens a temporary file and writes a test string to it, then prints out the contents of the file.

Example #1 Small bzip2 Example

<?php

$filename = "/tmp/testfile.bz2";
$str = "This is a test string.\n";

// open file for writing
$bz = bzopen($filename, "w");

// write string to file
bzwrite($bz, $str);

// close file
bzclose($bz);

// open file for reading
$bz = bzopen($filename, "r");

// read 10 characters
echo bzread($bz, 10);

// output until end of the file (or the next 1024 char) and close it.
echo bzread($bz);

bzclose($bz);

?>
Constante predefinite
Func?ii Bzip2
Bzip2


Func?ii Bzip2

Cuprins

  • bzclose — Close a bzip2 file
  • bzcompress — Compress a string into bzip2 encoded data
  • bzdecompress — Decompresses bzip2 encoded data
  • bzerrno — Returns a bzip2 error number
  • bzerror — Returns the bzip2 error number and error string in an array
  • bzerrstr — Returns a bzip2 error string
  • bzflush — Force a write of all buffered data
  • bzopen — Opens a bzip2 compressed file
  • bzread — Binary safe bzip2 file read
  • bzwrite — Binary safe bzip2 file write
Exemple
bzclose
Bzip2


Close a bzip2 file

Func?ii Bzip2
bzcompress
Func?ii Bzip2
PHP Manual

bzclose

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzclose — Close a bzip2 file

Descrierea

int bzclose ( resource $bz )

Closes the given bzip2 file pointer.

Parametri

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • bzopen() - Opens a bzip2 compressed file

Func?ii Bzip2
bzcompress
Func?ii Bzip2


Compress a string into bzip2 encoded data

bzclose
bzdecompress
Func?ii Bzip2
PHP Manual

bzcompress

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzcompress — Compress a string into bzip2 encoded data

Descrierea

mixed bzcompress ( string $source [, int $blocksize = 4 [, int $workfactor = 0 ]] )

bzcompress() compresses the given string and returns it as bzip2 encoded data.

Parametri

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.

Valorile întoarse

The compressed string, or an error number if an error occurred.

Exemple

Example #1 Compressing data

<?php
$str = "sample data";
$bzstr = bzcompress($str, 9);
echo $bzstr;
?>

A se vedea ?i

  • bzdecompress() - Decompresses bzip2 encoded data

bzclose
bzdecompress
Func?ii Bzip2


Decompresses bzip2 encoded data

bzcompress
bzerrno
Func?ii Bzip2
PHP Manual

bzdecompress

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzdecompress — Decompresses bzip2 encoded data

Descrierea

mixed bzdecompress ( string $source [, int $small = 0 ] )

bzdecompress() decompresses the given string containing bzip2 encoded data.

Parametri

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.

Valorile întoarse

The decompressed string, or an error number if an error occurred.

Exemple

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

A se vedea ?i

  • bzcompress() - Compress a string into bzip2 encoded data

bzcompress
bzerrno
Func?ii Bzip2


Returns a bzip2 error number

bzdecompress
bzerror
Func?ii Bzip2
PHP Manual

bzerrno

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzerrno — Returns a bzip2 error number

Descrierea

int bzerrno ( resource $bz )

Returns the error number of any bzip2 error returned by the given file pointer.

Parametri

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Valorile întoarse

Returns the error number as an integer.

A se vedea ?i

  • bzerror() - Returns the bzip2 error number and error string in an array
  • bzerrstr() - Returns a bzip2 error string

bzdecompress
bzerror
Func?ii Bzip2


Returns the bzip2 error number and error string in an array

bzerrno
bzerrstr
Func?ii Bzip2
PHP Manual

bzerror

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzerror — Returns the bzip2 error number and error string in an array

Descrierea

array bzerror ( resource $bz )

Returns the error number and error string of any bzip2 error returned by the given file pointer.

Parametri

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Valorile întoarse

Returns an associative array, with the error code in the errno entry, and the error message in the errstr entry.

Exemple

Example #1 bzerror() example

<?php
$error = bzerror($bz);

echo $error["errno"];
echo $error["errstr"];
?>

A se vedea ?i

  • bzerrno() - Returns a bzip2 error number
  • bzerrstr() - Returns a bzip2 error string

bzerrno
bzerrstr
Func?ii Bzip2


Returns a bzip2 error string

bzerror
bzflush
Func?ii Bzip2
PHP Manual

bzerrstr

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzerrstr — Returns a bzip2 error string

Descrierea

string bzerrstr ( resource $bz )

Gets the error string of any bzip2 error returned by the given file pointer.

Parametri

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Valorile întoarse

Returns a string containing the error message.

A se vedea ?i

  • bzerrno() - Returns a bzip2 error number
  • bzerror() - Returns the bzip2 error number and error string in an array

bzerror
bzflush
Func?ii Bzip2


Force a write of all buffered data

bzerrstr
bzopen
Func?ii Bzip2
PHP Manual

bzflush

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzflush — Force a write of all buffered data

Descrierea

bool bzflush ( resource $bz )

Forces a write of all buffered bzip2 data for the file pointer bz.

Parametri

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • bzread() - Binary safe bzip2 file read
  • bzwrite() - Binary safe bzip2 file write

bzerrstr
bzopen
Func?ii Bzip2


Opens a bzip2 compressed file

bzflush
bzread
Func?ii Bzip2
PHP Manual

bzopen

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzopen — Opens a bzip2 compressed file

Descrierea

resource bzopen ( mixed $file , string $mode )

bzopen() opens a bzip2 (.bz2) file for reading or writing.

Parametri

file

The name of the file to open, or an existing stream resource.

mode

The modes 'r' (read), and 'w' (write) are supported. Everything else will cause bzopen() to return FALSE.

Valorile întoarse

If the open fails, bzopen() returns FALSE, otherwise it returns a pointer to the newly opened file.

Exemple

Example #1 bzopen() example

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file for reading");

bzclose($bz);

?>

A se vedea ?i

  • bzclose() - Close a bzip2 file

bzflush
bzread
Func?ii Bzip2


Binary safe bzip2 file read

bzopen
bzwrite
Func?ii Bzip2
PHP Manual

bzread

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzread — Binary safe bzip2 file read

Descrierea

string bzread ( resource $bz [, int $length = 1024 ] )

bzread() reads from the given bzip2 file pointer.

Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.

Parametri

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

length

If not specified, bzread() will read 1024 (uncompressed) bytes at a time. A maximum of 8192 uncompressed bytes will be read at a time.

Valorile întoarse

Returns the uncompressed data, or FALSE on error.

Exemple

Example #1 bzread() example

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file");

$decompressed_file = '';
while (!feof($bz)) {
  $decompressed_file .= bzread($bz, 4096);
}
bzclose($bz);

echo "The contents of $file are: <br />\n";
echo $decompressed_file;

?>

A se vedea ?i

  • bzwrite() - Binary safe bzip2 file write
  • feof() - Tests for end-of-file on a file pointer
  • bzopen() - Opens a bzip2 compressed file

bzopen
bzwrite
Func?ii Bzip2


Binary safe bzip2 file write

bzread
LZF
Func?ii Bzip2
PHP Manual

bzwrite

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzwrite — Binary safe bzip2 file write

Descrierea

int bzwrite ( resource $bz , string $data [, int $length ] )

bzwrite() writes a string into the given bzip2 file stream.

Parametri

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

data

The written data.

length

If supplied, writing will stop after length (uncompressed) bytes have been written or the end of data is reached, whichever comes first.

Valorile întoarse

Returns the number of bytes written, or FALSE on error.

Exemple

Example #1 bzwrite() example

<?php
$str = "uncompressed data";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?>

A se vedea ?i

  • bzread() - Binary safe bzip2 file read
  • bzopen() - Opens a bzip2 compressed file

bzread
LZF
Func?ii Bzip2


LZF

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii LZF
    • lzf_compress — LZF compression
    • lzf_decompress — LZF decompression
    • lzf_optimized_for — Determines what LZF extension was optimized for
bzwrite
Introducere
Extensii de compresie ?i arhivare


Introducere

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
Instalarea / configurarea
LZF


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
LZF


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP. Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » 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. O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii LZF
LZF


Func?ii LZF

Cuprins

  • lzf_compress — LZF compression
  • lzf_decompress — LZF decompression
  • lzf_optimized_for — Determines what LZF extension was optimized for
Constante predefinite
lzf_compress
LZF


LZF compression

Func?ii LZF
lzf_decompress
Func?ii LZF
PHP Manual

lzf_compress

(PECL lzf >= 0.1.0)

lzf_compress — LZF compression

Descrierea

string lzf_compress ( string $data )

lzf_compress() compresses the given data string using LZF encoding.

Parametri

data

The string to compress.

Valorile întoarse

Returns the compressed data or FALSE if an error occurred.

A se vedea ?i

  • lzf_decompress() - LZF decompression

Func?ii LZF
lzf_decompress
Func?ii LZF


LZF decompression

lzf_compress
lzf_optimized_for
Func?ii LZF
PHP Manual

lzf_decompress

(PECL lzf >= 0.1.0)

lzf_decompress — LZF decompression

Descrierea

string lzf_decompress ( string $data )

lzf_compress() decompresses the given data string containing lzf encoded data.

Parametri

data

The compressed string.

Valorile întoarse

Returns the decompressed data or FALSE if an error occurred.

A se vedea ?i

  • lzf_compress() - LZF compression

lzf_compress
lzf_optimized_for
Func?ii LZF


Determines what LZF extension was optimized for

lzf_decompress
Phar
Func?ii LZF
PHP Manual

lzf_optimized_for

(PECL lzf >= 1.0.0)

lzf_optimized_for — Determines what LZF extension was optimized for

Descrierea

int lzf_optimized_for ( void )

Determines what was LZF extension optimized for during compilation.

Valorile întoarse

Returns 1 if LZF was optimized for speed, 0 for compression.

lzf_decompress
Phar
Func?ii LZF


Phar

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • 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 a string 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.
    • 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
Introducere
Extensii de compresie ?i arhivare


Introducere

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

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

Example #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:

Example #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, SHA-1, SHA-256 or SHA-512 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 portmanteau 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
Instalarea / configurarea
Phar


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Phar


Necesita?i

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.

PHP 5.3 configured with --enable-zend-multibyte makes phar dependant on the ini option detect_unicode.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Extensia Phar este încorporata în PHP începând cu PHP de versiunea 5.3.0. Phar poate fi instalat ca extensie PECL în versiunile anterioare ale PHP, iar » Pagina PECL Phar con?ine informa?ii suplimentare ?i istoricul schimbarilor.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Filesystem and Streams Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Nota:

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.

Nota:

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.

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

Example #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

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

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.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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()
Tipurile resurselor
Using Phar Archives
Phar


Using Phar Archives

Cuprins

  • Using Phar Archives: Introduction
  • Using Phar Archives: the phar stream wrapper
  • Using Phar Archives: the Phar and PharData class
Constante predefinite
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

Cuprins

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

Cuprins

  • 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

Sfat

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

Sfat

[2] All write access requires phar.readonly to be disabled in php.ini or on the command-line directly.

Sfat

[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

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Introducere

The Phar class provides a high-level interface to accessing and creating phar archives.

Sinopsisul clasei

Phar extends RecursiveDirectoryIterator implements Countable , ArrayAccess {
/* Metode */
public void addEmptyDir ( string $dirname )
public void addFile ( string $file [, string $localname ] )
public void addFromString ( string $localname , string $contents )
final public static string apiVersion ( void )
public array buildFromDirectory ( string $base_dir [, string $regex ] )
public array buildFromIterator ( Iterator $iter [, string $base_directory ] )
final public static bool canCompress ([ int $type = 0 ] )
final public static bool canWrite ( void )
public object compress ( int $compression [, string $extension ] )
public bool compressAllFilesBZIP2 ( void )
public bool compressAllFilesGZ ( void )
public void compressFiles ( int $compression )
public __construct ( string $fname [, int $flags [, string $alias ]] )
public PharData convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
public Phar convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
public bool copy ( string $oldfile , string $newfile )
public int count ( void )
final public static string createDefaultStub ([ string $indexfile [, string $webindexfile ]] )
public object decompress ([ string $extension ] )
public bool decompressFiles ( void )
public bool delMetadata ( void )
public bool delete ( string $entry )
public bool extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )
public mixed getMetadata ( void )
public bool getModified ( void )
public array getSignature ( void )
public string getStub ( void )
final public static array getSupportedCompression ( void )
final public static array getSupportedSignatures ( void )
public string getVersion ( void )
public bool hasMetadata ( void )
final public static void interceptFileFuncs ( void )
public bool isBuffering ( void )
public mixed isCompressed ( void )
public bool isFileFormat ( int $format )
final public static bool isValidPharFilename ( string $filename [, bool $executable = true ] )
public bool isWritable ( void )
final public static bool loadPhar ( string $filename [, string $alias ] )
final public static bool mapPhar ([ string $alias [, int $dataoffset = 0 ]] )
final public static void mount ( string $pharpath , string $externalpath )
final public static void mungServer ( array $munglist )
public bool offsetExists ( string $offset )
public int offsetGet ( string $offset )
public void offsetSet ( string $offset , string $value )
public bool offsetUnset ( string $offset )
final public static string running ([ bool $retphar = true ] )
public bool setAlias ( string $alias )
public bool setDefaultStub ([ string $index [, string $webindex ]] )
public void setMetadata ( mixed $metadata )
public void setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )
public bool setStub ( string $stub [, int $len = -1 ] )
public void startBuffering ( void )
public void stopBuffering ( void )
public bool uncompressAllFiles ( void )
final public static bool unlinkArchive ( string $archive )
final public static void webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, callable $rewrites ]]]]] )
}

Cuprins

  • 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 a string 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

Descrierea

public void Phar::addEmptyDir ( string $dirname )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

With this method, an empty directory is created with path dirname. This method is similar to ZipArchive::addEmptyDir().

Parametri

dirname

The name of the empty directory to create in the phar archive

Valorile întoarse

no return value, exception is thrown on failure.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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 a string 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

Descrierea

public void Phar::addFile ( string $file [, string $localname ] )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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

Parametri

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.

Valorile întoarse

no return value, exception is thrown on failure.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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 a string to the phar archive
  • Phar::addEmptyDir() - Add an empty directory to the phar archive

Phar::addEmptyDir
Phar::addFromString
Phar


Add a file from a string to the phar archive

Phar::addFile
Phar::apiVersion
Phar
PHP Manual

Phar::addFromString

(Unknown)

Phar::addFromString — Add a file from a string to the phar archive

Descrierea

public void Phar::addFromString ( string $localname , string $contents )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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

Parametri

localname

Path that the file will be stored in the archive.

contents

The file contents to store

Valorile întoarse

no return value, exception is thrown on failure.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

Descrierea

final public static 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.

Parametri

Valorile întoarse

The API version string as in "1.0.0".

Exemple

Example #1 A Phar::apiVersion() example

<?php
echo Phar::apiVersion();
?>

Exemplul de mai sus va afi?a:

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.

Descrierea

public array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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

Parametri

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.

Valorile întoarse

Phar::buildFromDirectory() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Erori/Excep?ii

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

Exemple

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

A se vedea ?i

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

Descrierea

public array Phar::buildFromIterator ( Iterator $iter [, string $base_directory ] )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

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

Valorile întoarse

Phar::buildFromIterator() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Exemple

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

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

Erori/Excep?ii

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.

A se vedea ?i

  • 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

Descrierea

final public static 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.

Parametri

type

Either Phar::GZ or Phar::BZ2 can be used to test whether compression is possible with a specific compression algorithm (zlib or bzip2).

Valorile întoarse

TRUE if compression/decompression is available, FALSE if not.

Exemple

Example #1 A Phar::canCompress() example

<?php
if (Phar::canCompress()) {
    echo file_get_contents('phar://compressedphar.phar/internal/file.txt');
} else {
    echo 'no compression available';
}
?>

A se vedea ?i

  • 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

Descrierea

final public static 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.

Parametri

Valorile întoarse

TRUE if write access is enabled, FALSE if it is disabled.

Exemple

Example #1 A Phar::canWrite() example

<?php
if (Phar::canWrite()) {
    file_put_contents('phar://myphar.phar/file.txt', 'hi there');
}
?>

A se vedea ?i

  • 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

Descrierea

public object Phar::compress ( int $compression [, string $extension ] )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

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.

Valorile întoarse

Returns a Phar object.

Erori/Excep?ii

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

Exemple

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

A se vedea ?i

  • 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

Descrierea

public bool Phar::compressAllFilesBZIP2 ( void )

Nota:

Aceasta metoda a fost eliminata din cadrul extensiei phar începând cu
versiunea 2.0.0. Implementari alternative sunt disponibile utilizând
Phar::compress(), Phar::decompress(),
Phar::compressFiles() ?i
Phar::decompressFiles().

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Exemple

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

Exemplul de mai sus va afi?a:

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)

A se vedea ?i

  • 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

Descrierea

public bool Phar::compressAllFilesGZ ( void )

Nota:

Aceasta metoda a fost eliminata din cadrul extensiei phar începând cu
versiunea 2.0.0. Implementari alternative sunt disponibile utilizând
Phar::compress(), Phar::decompress(),
Phar::compressFiles() ?i
Phar::decompressFiles().

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Exemple

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

Exemplul de mai sus va afi?a:

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)

A se vedea ?i

  • 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

Descrierea

public void Phar::compressFiles ( int $compression )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

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.

Exemple

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

Exemplul de mai sus va afi?a:

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)

A se vedea ?i

  • 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

Descrierea

public Phar::__construct ( string $fname [, int $flags [, string $alias ]] )

Parametri

fname

Path to an existing Phar archive or to-be-created archive. The file name's extension must contain .phar.

flags

Flags to pass to parent class RecursiveDirectoryIterator.

alias

Alias with which this Phar archive should be referred to in calls to stream functionality.

Erori/Excep?ii

Throws BadMethodCallException if called twice, UnexpectedValueException if the phar archive can't be opened.

Exemple

Example #1 A Phar::__construct() example

<?php
try {
    $p = new Phar('/path/to/my.phar', FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::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

Descrierea

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

Parametri

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.

Valorile întoarse

The method returns a PharData object on success and throws an exception on failure.

Erori/Excep?ii

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.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

Descrierea

public Phar Phar::convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

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.

Valorile întoarse

The method returns a Phar object on success and throws an exception on failure.

Erori/Excep?ii

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.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

Descrierea

public bool Phar::copy ( string $oldfile , string $newfile )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

oldfile

newfile

Valorile întoarse

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.

Erori/Excep?ii

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.

Exemple

Example #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

Descrierea

public int Phar::count ( void )

Parametri

Valorile întoarse

The number of files contained within this phar, or 0 (the number zero) if none.

Exemple

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

Exemplul de mai sus va afi?a:

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

Descrierea

final public static 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.

Valorile întoarse

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.

Erori/Excep?ii

Throws UnexpectedValueException if either parameter is longer than 400 bytes.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

Descrierea

public object Phar::decompress ([ string $extension ] )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

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.

Valorile întoarse

A Phar object is returned.

Erori/Excep?ii

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

Exemple

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

A se vedea ?i

  • 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

Descrierea

public bool Phar::decompressFiles ( void )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Exemple

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

Exemplul de mai sus va afi?a:

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)

A se vedea ?i

  • 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

Descrierea

public bool Phar::delMetadata ( void )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

Deletes the global metadata of the phar

Parametri

Valorile întoarse

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Erori/Excep?ii

Throws PharException if errors occur while flushing changes to disk.

Exemple

Example #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
}
?>

Exemplul de mai sus va afi?a:

NULL
string(8) "hi there"
NULL

A se vedea ?i

  • 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

Descrierea

public bool Phar::delete ( string $entry )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

entry

Path within an archive to the file to delete.

Valorile întoarse

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Erori/Excep?ii

Throws PharException if errors occur while flushing changes to disk.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

Descrierea

public bool Phar::extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )

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

Parametri

pathto

Path to extract the given files to

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

Valorile întoarse

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Erori/Excep?ii

Throws PharException if errors occur while flushing changes to disk.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

Descrierea

public mixed Phar::getMetadata ( void )

Retrieve archive meta-data. Meta-data can be any PHP variable that can be serialized.

Parametri

No parameters.

Valorile întoarse

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.

Exemple

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

Exemplul de mai sus va afi?a:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

A se vedea ?i

  • 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

Descrierea

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

Parametri

No parameters.

Valorile întoarse

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

Descrierea

public array Phar::getSignature ( void )

Returns the verification signature of a phar archive in a hexadecimal string.

Parametri

Valorile întoarse

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

Descrierea

public 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

Valorile întoarse

Returns a string containing the contents of the bootstrap loader (stub) of the current Phar archive.

Erori/Excep?ii

Throws RuntimeException if it is not possible to read the stub from the Phar archive.

Exemple

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

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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

Descrierea

final public static array Phar::getSupportedCompression ( void )

Parametri

No parameters.

Valorile întoarse

Returns an array containing any of Phar::GZ or Phar::BZ2, depending on the availability of the zlib extension or the bz2 extension.

A se vedea ?i

  • 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

Descrierea

final public static array Phar::getSupportedSignatures ( void )

Return array of supported signature types

Parametri

No parameters.

Valorile întoarse

Returns an array containing any of MD5, SHA-1, SHA-256, SHA-512, or OpenSSL.

A se vedea ?i

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

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

Descrierea

public string Phar::getVersion ( void )

Returns the API version of an opened Phar archive.

Parametri

Valorile întoarse

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.

A se vedea ?i

  • 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

Descrierea

public bool Phar::hasMetadata ( void )

Returns whether phar has global meta-data set.

Parametri

No parameters.

Valorile întoarse

Returns TRUE if meta-data has been set, and FALSE if not.

Exemple

Example #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
}
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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

Descrierea

final public static 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.

Parametri

No parameters.

Valorile întoarse

Exemple

Example #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:

Example #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

Descrierea

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

Valorile întoarse

Returns TRUE if the write operations are being buffer, FALSE otherwise.

Exemple

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

Exemplul de mai sus va afi?a:

bool(false)
bool(false)
=2=
bool(true)
bool(false)
=3=
bool(false)
bool(false)

A se vedea ?i

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

Descrierea

public mixed Phar::isCompressed ( void )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

No parameters.

Valorile întoarse

Phar::GZ, Phar::BZ2 or FALSE

Exemple

Example #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->compress(Phar::GZ);
    var_dump($phar2->isCompressed() == Phar::GZ);
} catch (Exception $e) {
}
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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

Descrierea

public bool Phar::isFileFormat ( int $format )

Parametri

format

Either Phar::PHAR, Phar::TAR, or Phar::ZIP to test for the format of the archive.

Valorile întoarse

Returns TRUE if the phar archive matches the file format requested by the parameter

Erori/Excep?ii

PharException is thrown if the parameter is an unknown file format specifier.

A se vedea ?i

  • 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

Descrierea

final public static 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.

Parametri

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

Valorile întoarse

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

Descrierea

public bool Phar::isWritable ( void )

This method returns TRUE if phar.readonly is 0, and the actual phar archive on disk is not read-only.

Parametri

No parameters.

Valorile întoarse

Returns TRUE if the phar archive can be modified

A se vedea ?i

  • 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

Descrierea

final public static 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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

PharException is thrown if an alias is passed in and the phar archive already has an explicit alias

Exemple

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

A se vedea ?i

  • 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

Descrierea

final public static 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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Exemple

Example #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();

A se vedea ?i

  • 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

Descrierea

final public static 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.

Parametri

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

Valorile întoarse

No return. PharException is thrown on failure.

Erori/Excep?ii

Throws PharException if any problems occur mounting the path.

Exemple

Example #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

Descrierea

final public static 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.

Parametri

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.

Valorile întoarse

No return.

Erori/Excep?ii

Throws UnexpectedValueException if any problems are found with the passed in data.

Exemple

Example #1 A Phar::mungServer() example

<?php
// example stub
Phar::mungServer(array('REQUEST_URI'));
Phar::webPhar();
__HALT_COMPILER();
?>

A se vedea ?i

  • 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

Descrierea

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

Parametri

offset

The filename (relative path) to look for in a Phar.

Valorile întoarse

Returns TRUE if the file exists within the phar, or FALSE if not.

Exemple

Example #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']));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)

A se vedea ?i

  • 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

Descrierea

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

Parametri

offset

The filename (relative path) to look for in a Phar.

Valorile întoarse

A PharFileInfo object is returned that can be used to iterate over a file's contents or to retrieve information about the current file.

Erori/Excep?ii

This method throws BadMethodCallException if the file does not exist in the Phar archive.

Exemple

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

Exemplul de mai sus va afi?a:

file exists
Entry doesnotexist.txt does not exist

A se vedea ?i

  • 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

Descrierea

public void Phar::offsetSet ( string $offset , string $value )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

offset

The filename (relative path) to modify in a Phar.

value

Content of the file.

Valorile întoarse

No return values.

Erori/Excep?ii

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.

Exemple

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

A se vedea ?i

  • 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

Descrierea

public bool Phar::offsetUnset ( string $offset )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

offset

The filename (relative path) to modify in a Phar.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Exemple

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

A se vedea ?i

  • 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

Descrierea

final public static 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.

Parametri

retphar

If FALSE, the full path on disk to the phar archive is returned. If TRUE, a full phar URL is returned.

Valorile întoarse

Returns the filename if valid, empty string otherwise.

Exemple

Example #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

Descrierea

public bool Phar::setAlias ( string $alias )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

alias

A shorthand string that this archive can be referred to in phar stream wrapper access.

Valorile întoarse

Erori/Excep?ii

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.

Exemple

Example #1 A Phar::setAlias() example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->setAlias('myp.phar');
} catch (Exception $e) {
    // handle error
}
?>

A se vedea ?i

  • 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

Descrierea

public bool Phar::setDefaultStub ([ string $index [, string $webindex ]] )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

This method is a convenience method that combines the functionality of Phar::createDefaultStub() and Phar::setStub().

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

UnexpectedValueException is thrown if phar.readonly is enabled in php.ini. PharException is thrown if any problems are encountered flushing changes to disk.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

Descrierea

public void Phar::setMetadata ( mixed $metadata )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

metadata

Any PHP variable containing information to store that describes the phar archive

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

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

Exemplul de mai sus va afi?a:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

A se vedea ?i

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

Descrierea

public void Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws UnexpectedValueException for many errors, and a PharException if any problems occur flushing changes to disk.

A se vedea ?i

  • 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

Descrierea

public bool Phar::setStub ( string $stub [, int $len = -1 ] )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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

Parametri

stub

A string or an open stream handle to use as the executable stub for this phar archive.

len

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

UnexpectedValueException is thrown if phar.readonly is enabled in php.ini. PharException is thrown if any problems are encountered flushing changes to disk.

Exemple

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

Exemplul de mai sus va afi?a:

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

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added len parameter.

A se vedea ?i

  • 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

Descrierea

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

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

A se vedea ?i

  • 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

Descrierea

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

PharException is thrown if any problems are encountered flushing changes to disk.

Exemple

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

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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

Descrierea

public bool Phar::uncompressAllFiles ( void )

Nota:

Aceasta metoda a fost eliminata din cadrul extensiei phar începând cu
versiunea 2.0.0. Implementari alternative sunt disponibile utilizând
Phar::compress(), Phar::decompress(),
Phar::compressFiles() ?i
Phar::decompressFiles().

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Exemple

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

Exemplul de mai sus va afi?a:

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)

A se vedea ?i

  • 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

Descrierea

final public static bool Phar::unlinkArchive ( string $archive )

Removes a phar archive from disk and memory.

Parametri

archive

The path on disk to the phar archive.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Exemple

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

A se vedea ?i

  • 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

Descrierea

final public static void Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, callable $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).

Parametri

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

The rewrites function is passed a string as its only parameter and must return a string or FALSE.

If you are using fast-cgi or cgi then the parameter passed to the function is the value of the $_SERVER['PATH_INFO'] variable. Otherwise, the parameter passed to the function is the value of the $_SERVER['REQUEST_URI'] variable.

If a string is returned it is used as the internal file path. If FALSE is returned then webPhar() will send a HTTP 403 Denied Code.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

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 an invalid callback is passed into rewrites, then UnexpectedValueException is thrown.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Introducere

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.

Sinopsisul clasei

PharData extends Phar {
/* Metode */
bool addEmptyDir ( string $dirname )
public void Phar::addFile ( string $file [, string $localname ] )
bool addFromString ( string $localname , string $contents )
public 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 ]] )
public void Phar::setMetadata ( mixed $metadata )
public void Phar::setSignatureAlgorithm ( int $sigtype )
bool setStub ( string $stub [, int $len = -1 ] )
/* Metode mo?tenite */
public void Phar::addEmptyDir ( string $dirname )
public void Phar::addFile ( string $file [, string $localname ] )
public void Phar::addFromString ( string $localname , string $contents )
final public static string Phar::apiVersion ( void )
public array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )
public array Phar::buildFromIterator ( Iterator $iter [, string $base_directory ] )
final public static bool Phar::canCompress ([ int $type = 0 ] )
final public static bool Phar::canWrite ( void )
public object Phar::compress ( int $compression [, string $extension ] )
public bool Phar::compressAllFilesBZIP2 ( void )
public bool Phar::compressAllFilesGZ ( void )
public void Phar::compressFiles ( int $compression )
public Phar::__construct ( string $fname [, int $flags [, string $alias ]] )
public PharData Phar::convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
public Phar Phar::convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
public bool Phar::copy ( string $oldfile , string $newfile )
public int Phar::count ( void )
final public static string Phar::createDefaultStub ([ string $indexfile [, string $webindexfile ]] )
public object Phar::decompress ([ string $extension ] )
public bool Phar::decompressFiles ( void )
public bool Phar::delMetadata ( void )
public bool Phar::delete ( string $entry )
public bool Phar::extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )
public mixed Phar::getMetadata ( void )
public bool Phar::getModified ( void )
public array Phar::getSignature ( void )
public string Phar::getStub ( void )
final public static array Phar::getSupportedCompression ( void )
final public static array Phar::getSupportedSignatures ( void )
public string Phar::getVersion ( void )
public bool Phar::hasMetadata ( void )
final public static void Phar::interceptFileFuncs ( void )
public bool Phar::isBuffering ( void )
public mixed Phar::isCompressed ( void )
public bool Phar::isFileFormat ( int $format )
final public static bool Phar::isValidPharFilename ( string $filename [, bool $executable = true ] )
public bool Phar::isWritable ( void )
final public static bool Phar::loadPhar ( string $filename [, string $alias ] )
final public static bool Phar::mapPhar ([ string $alias [, int $dataoffset = 0 ]] )
final public static void Phar::mount ( string $pharpath , string $externalpath )
final public static void Phar::mungServer ( array $munglist )
public bool Phar::offsetExists ( string $offset )
public int Phar::offsetGet ( string $offset )
public void Phar::offsetSet ( string $offset , string $value )
public bool Phar::offsetUnset ( string $offset )
final public static string Phar::running ([ bool $retphar = true ] )
public bool Phar::setAlias ( string $alias )
public bool Phar::setDefaultStub ([ string $index [, string $webindex ]] )
public void Phar::setMetadata ( mixed $metadata )
public void Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )
public bool Phar::setStub ( string $stub [, int $len = -1 ] )
public void Phar::startBuffering ( void )
public void Phar::stopBuffering ( void )
public bool Phar::uncompressAllFiles ( void )
final public static bool Phar::unlinkArchive ( string $archive )
final public static void Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, callable $rewrites ]]]]] )
}

Cuprins

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

Descrierea

bool PharData::addEmptyDir ( string $dirname )

With this method, an empty directory is created with path dirname. This method is similar to ZipArchive::addEmptyDir().

Parametri

dirname

The name of the empty directory to create in the phar archive

Valorile întoarse

no return value, exception is thrown on failure.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

Descrierea

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

Parametri

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.

Valorile întoarse

no return value, exception is thrown on failure.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

Descrierea

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

Parametri

localname

Path that the file will be stored in the archive.

contents

The file contents to store

Valorile întoarse

no return value, exception is thrown on failure.

Exemple

Example #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
}
?>

A se vedea ?i

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

Descrierea

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

Parametri

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.

Valorile întoarse

Phar::buildFromDirectory() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Erori/Excep?ii

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

Exemple

Example #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
$phar2->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
?>

A se vedea ?i

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

Descrierea

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.

Exemple

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

Example #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'),
     )));
?>

Parametri

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

Valorile întoarse

PharData::buildFromIterator() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Erori/Excep?ii

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.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

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.

Valorile întoarse

A PharData object is returned.

Erori/Excep?ii

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

Exemple

Example #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.tar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.tar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.tar already exists
?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Exemple

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

Exemplul de mai sus va afi?a:

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)

A se vedea ?i

  • 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

Descrierea

PharData::__construct ( string $fname [, int $flags [, string $alias [, int $format = Phar::TAR ]]] )

Parametri

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.

Erori/Excep?ii

Throws BadMethodCallException if called twice; UnexpectedValueException if the Phar archive can't be opened.

Exemple

Example #1 A PharData::__construct() example

<?php
try {
    $p = new PharData('/path/to/my.tar', Phar::CURRENT_AS_FILEINFO | Phar::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

Descrierea

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.

Parametri

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.

Valorile întoarse

The method returns a PharData object on success and throws an exception on failure.

Erori/Excep?ii

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.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

Descrierea

Phar PharData::convertToExecutable ([ int $format [, int $compression [, string $extension ]]] )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

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.

Valorile întoarse

The method returns a Phar object on success and throws an exception on failure.

Erori/Excep?ii

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.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

oldfile

newfile

Valorile întoarse

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.

Erori/Excep?ii

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.

Exemple

Example #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

Descrierea

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.

Parametri

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.

Valorile întoarse

A PharData object is returned.

Erori/Excep?ii

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

Exemple

Example #1 A PharData::decompress() example

<?php
$p = new PharData('/path/to/my.tar.gz');
$p->decompress(); // creates /path/to/my.tar
?>

A se vedea ?i

  • 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

Descrierea

bool PharData::decompressFiles ( void )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Exemple

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

Exemplul de mai sus va afi?a:

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)

A se vedea ?i

  • 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

Descrierea

bool PharData::delMetadata ( void )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

Deletes the global metadata of the zip archive

Parametri

Valorile întoarse

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Erori/Excep?ii

Throws PharException if errors occur while flushing changes to disk.

Exemple

Example #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
}
?>

Exemplul de mai sus va afi?a:

NULL
string(8) "hi there"
NULL

A se vedea ?i

  • 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

Descrierea

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.

Parametri

entry

Path within an archive to the file to delete.

Valorile întoarse

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Erori/Excep?ii

Throws PharException if errors occur while flushing changes to disk.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

Descrierea

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

Parametri

pathto

Path to extract the given files to

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

Valorile întoarse

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Erori/Excep?ii

Throws PharException if errors occur while flushing changes to disk.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

No parameters.

Valorile întoarse

Returns TRUE if the tar/zip archive can be modified

A se vedea ?i

  • 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

Descrierea

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.

Parametri

offset

The filename (relative path) to modify in a tar or zip archive.

value

Content of the file.

Valorile întoarse

No return values.

Erori/Excep?ii

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

Exemple

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

A se vedea ?i

  • 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

Descrierea

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.

Parametri

offset

The filename (relative path) to modify in the tar/zip archive.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

Exemple

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

A se vedea ?i

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

Descrierea

bool PharData::setAlias ( string $alias )

Non-executable tar/zip archives cannot have an alias, so this method simply throws an exception.

Parametri

alias

A shorthand string that this archive can be referred to in phar stream wrapper access. This parameter is ignored.

Valorile întoarse

Erori/Excep?ii

Throws PharException on all method calls

A se vedea ?i

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

Descrierea

bool PharData::setDefaultStub ([ string $index [, string $webindex ]] )

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws PharException on all method calls

A se vedea ?i

  • 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

Descrierea

public void Phar::setMetadata ( mixed $metadata )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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.

Parametri

metadata

Any PHP variable containing information to store that describes the phar archive

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

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

Exemplul de mai sus va afi?a:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

A se vedea ?i

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

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.

Descrierea

public void Phar::setSignatureAlgorithm ( int $sigtype )

Nota:

Aceasta metoda necesita ca parametrul php.ini phar.readonly sa fie stabilit în 0 pentru ca obiectele Phar sa func?ioneze. În caz contrar va fi emisa o excep?ie PharException.

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

Parametri

sigtype

    One of Phar::MD5,
Phar::SHA1, Phar::SHA256,
Phar::SHA512, or Phar::PGP

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

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.

A se vedea ?i

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

Descrierea

bool PharData::setStub ( string $stub [, int $len = -1 ] )

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

Parametri

stub

A string or an open stream handle to use as the executable stub for this phar archive. This parameter is ignored.

len

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws PharException on all method calls

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added len parameter.

A se vedea ?i

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive

Phar::setSignatureAlgorithm
PharFileInfo
PharData


The PharFileInfo class

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Introducere

The PharFileInfo class provides a high-level interface to the contents and attributes of a single file within a phar archive.

Sinopsisul clasei

PharFileInfo extends SplFileInfo {
/* Metode */
public void chmod ( int $permissions )
public bool compress ( int $compression )
public __construct ( string $entry )
public bool decompress ( void )
public bool delMetadata ( void )
public int getCRC32 ( void )
public int getCompressedSize ( void )
public mixed getMetadata ( void )
public int getPharFlags ( void )
public bool hasMetadata ( void )
public bool isCRCChecked ( void )
public bool isCompressed ([ int $compression_type = 9021976 ] )
public bool isCompressedBZIP2 ( void )
public bool isCompressedGZ ( void )
public bool setCompressedBZIP2 ( void )
public bool setCompressedGZ ( void )
public void setMetadata ( mixed $metadata )
public bool setUncompressed ( void )
}

Cuprins

  • 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

Descrierea

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

Parametri

permissions

permissions (see chmod())

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

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

Exemplul de mai sus va afi?a:

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

Descrierea

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

Exemple

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

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

A se vedea ?i

  • 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

Descrierea

public PharFileInfo::__construct ( string $entry )

This should not be called directly. Instead, a PharFileInfo object is initialized by calling Phar::offsetGet() through array access.

Parametri

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.

Erori/Excep?ii

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.

Exemple

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

Exemplul de mai sus va afi?a:

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

Descrierea

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

Exemple

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

Exemplul de mai sus va afi?a:

int(4096)
bool(false)

A se vedea ?i

  • 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

Descrierea

public bool PharFileInfo::delMetadata ( void )

Deletes the metadata of the entry, if any.

Parametri

No parameters.

Valorile întoarse

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.

Erori/Excep?ii

Throws PharException if errors occurred while flushing changes to disk, and BadMethodCallException if write access is disabled.

Exemple

Example #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
}
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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

Descrierea

public int PharFileInfo::getCRC32 ( void )

This returns the crc32() checksum of the file within the Phar archive.

Valorile întoarse

The crc32() checksum of the file within the Phar archive.

Erori/Excep?ii

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.

Exemple

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

Exemplul de mai sus va afi?a:

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

Descrierea

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

Valorile întoarse

The size in bytes of the file within the Phar archive on disk.

Exemple

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

Exemplul de mai sus va afi?a:

2

A se vedea ?i

  • 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

Descrierea

public mixed PharFileInfo::getMetadata ( void )

Return meta-data that was saved in the Phar archive's manifest for this file.

Parametri

Valorile întoarse

any PHP variable that can be serialized and is stored as meta-data for the file, or NULL if no meta-data is stored.

Exemple

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

Exemplul de mai sus va afi?a:

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

A se vedea ?i

  • 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

Descrierea

public int PharFileInfo::getPharFlags ( void )

This returns the flags set in the manifest for a Phar. This will always return 0 in the current implementation.

Valorile întoarse

The Phar flags (always 0 in the current implementation)

Exemple

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

Exemplul de mai sus va afi?a:

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

Descrierea

public bool PharFileInfo::hasMetadata ( void )

Returns the metadata of a file within a phar archive.

Parametri

No parameters.

Valorile întoarse

Returns FALSE if no metadata is set or is NULL, TRUE if metadata is not NULL

A se vedea ?i

  • 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

Descrierea

public bool PharFileInfo::isCRCChecked ( void )

This returns whether a file within a Phar archive has had its CRC verified.

Valorile întoarse

TRUE if the file has had its CRC verified, FALSE if not.

Exemple

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

Exemplul de mai sus va afi?a:

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

Descrierea

public bool PharFileInfo::isCompressed ([ int $compression_type = 9021976 ] )

This returns whether a file is compressed within a Phar archive with either Gzip or Bzip2 compression.

Parametri

compression_type

One of Phar::GZ or Phar::BZ2, defaults to any compression.

Valorile întoarse

TRUE if the file is compressed within the Phar archive, FALSE if not.

Exemple

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

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

A se vedea ?i

  • 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

Descrierea

public bool PharFileInfo::isCompressedBZIP2 ( void )

Nota:

Aceasta metoda a fost eliminata din cadrul extensiei phar începând cu
versiunea 2.0.0. Implementari alternative sunt disponibile utilizând
PharFileInfo::isCompressed(),
PharFileInfo::decompress() ?i
PharFileInfo::compress().

This returns whether a file is compressed within a Phar archive with Bzip2 compression.

Valorile întoarse

TRUE if the file is compressed within the Phar archive using Bzip2, FALSE if not.

Exemple

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

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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

Descrierea

public bool PharFileInfo::isCompressedGZ ( void )

Nota:

Aceasta metoda a fost eliminata din cadrul extensiei phar începând cu
versiunea 2.0.0. Implementari alternative sunt disponibile utilizând
PharFileInfo::isCompressed(),
PharFileInfo::decompress() ?i
PharFileInfo::compress().

This returns whether a file is compressed within a Phar archive with Gzip compression.

Valorile întoarse

TRUE if the file is compressed within the Phar archive using Gzip, FALSE if not.

Exemple

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

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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

Descrierea

public bool PharFileInfo::setCompressedBZIP2 ( void )

Nota:

Aceasta metoda a fost eliminata din cadrul extensiei phar începând cu
versiunea 2.0.0. Implementari alternative sunt disponibile utilizând
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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2 extension is not available.

Exemple

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

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

A se vedea ?i

  • 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

Descrierea

public bool PharFileInfo::setCompressedGZ ( void )

Nota:

Aceasta metoda a fost eliminata din cadrul extensiei phar începând cu
versiunea 2.0.0. Implementari alternative sunt disponibile utilizând
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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the zlib extension is not available.

Exemple

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

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

A se vedea ?i

  • 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

Descrierea

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

Parametri

metadata

Any PHP variable containing information to store alongside a file

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

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

Exemplul de mai sus va afi?a:

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

A se vedea ?i

  • 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

Descrierea

public bool PharFileInfo::setUncompressed ( void )

Nota:

Aceasta metoda a fost eliminata din cadrul extensiei phar începând cu
versiunea 2.0.0. Implementari alternative sunt disponibile utilizând
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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

Exemple

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

Exemplul de mai sus va afi?a:

bool(true)
bool(false)

A se vedea ?i

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

Introducere

The PharException class provides a phar-specific exception class for try/catch blocks.

Sinopsisul clasei

PharException extends Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Cuprins

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

Descrierea

PharException
Rar
PharException
PHP Manual


Rar Archiving

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii Rar
    • 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
Introducere
Extensii de compresie ?i arhivare


Introducere

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
Instalarea / configurarea
Rar


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Rar


Instalarea

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:

Example #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. O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

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

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
Exemple
Rar


Exemple

See also the examples under rar:// wrapper.

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

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

Constante predefinite
Func?ii Rar
Rar


Func?ii Rar

Cuprins

  • rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper
Exemple
rar_wrapper_cache_stats
Rar


Cache hits and misses for the URL wrapper

Func?ii Rar
RarArchive
Func?ii Rar
PHP Manual

rar_wrapper_cache_stats

(PECL rar >= 3.0.0)

rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper

Descrierea

string rar_wrapper_cache_stats ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Func?ii Rar
RarArchive
Func?ii Rar


The RarArchive class

(PECL rar >= 2.0.0)

Introducere

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

Sinopsisul clasei

final RarArchive implements Traversable {
/* Metode */
public bool close ( void )
public string getComment ( void )
public array getEntries ( void )
public RarEntry getEntry ( string $entryname )
public bool isBroken ( void )
public bool isSolid ( void )
public static RarArchive open ( string $filename [, string $password = NULL [, callable $volume_callback = NULL ]] )
public bool setAllowBroken ( bool $allow_broken )
public string __toString ( void )
}

Cuprins

  • 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

Descrierea

Stil obiect-orientat (method):

public bool RarArchive::close ( void )

Stil procedural:

bool rar_close ( RarArchive $rarfile )

Close RAR archive and free all allocated resources.

Parametri

rarfile

A RarArchive object, opened with rar_open().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

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

Exemple

Example #1 Stil obiect-orientat

<?php
$rar_arch = RarArchive::open('latest_winrar.rar');
echo $rar_arch."\n";
$rar_arch->close();
echo $rar_arch."\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar"
RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed)

Example #2 Stil procedural

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

Descrierea

Stil obiect-orientat (method):

public string RarArchive::getComment ( void )

Stil procedural:

string rar_comment_get ( RarArchive $rarfile )

Get the (global) comment stored in the RAR archive. It may be up to 64 KiB long.

Nota:

This extension does not support comments at the entry level.

Parametri

rarfile

A RarArchive object, opened with rar_open().

Valorile întoarse

Returns the comment or NULL if there is none.

Nota:

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.

Exemple

Example #1 Stil obiect-orientat

<?php
$rar_arch = RarArchive::open('commented.rar');
echo $rar_arch->getComment();
?>

Exemplul de mai sus va afi?a ceva similar cu:

This is the comment of the file commented.rar.

Example #2 Stil procedural

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

Descrierea

Stil obiect-orientat (method):

public array RarArchive::getEntries ( void )

Stil procedural:

array rar_list ( RarArchive $rarfile )

Get entries list (files and directories) from the RAR archive.

Nota:

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

Parametri

rarfile

A RarArchive object, opened with rar_open().

Valorile întoarse

rar_list() returns array of RarEntry objects sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
3.0.0 | Support for RAR archives with repeated entry names is no longer defective.

Exemple

Example #1 Stil obiect-orientat

<?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 not retrieve entries.");

echo "Found " . count($rar_entries) . " entries.\n";

foreach ($rar_entries as $e) {
    echo $e;
    echo "\n";
}
$rar_arch->close();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Found 2 entries.
RarEntry for file "tese.txt" (23b93a7a)
RarEntry for file "unrardll.txt" (2ed64b6e)

Example #2 Stil procedural

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

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public RarEntry RarArchive::getEntry ( string $entryname )

Stil procedural:

RarEntry rar_entry_get ( RarArchive $rarfile , string $entryname )

Get entry object (file or directory) from the RAR archive.

Nota:

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.

Parametri

rarfile

A RarArchive object, opened with rar_open().

entryname

Path to the entry within the RAR archive.

Nota:

The path must be the same returned by RarEntry::getName().

Valorile întoarse

Returns the matching RarEntry object sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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 not get such entry");
echo get_class($rar_entry)."\n";
echo $rar_entry;
$rar_arch->close();
?>

Exemplul de mai sus va afi?a ceva similar cu:

RarEntry
RarEntry for file "tese.txt" (23b93a7a)

Example #2 Stil procedural

<?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 not get such entry");
echo get_class($rar_entry)."\n";
echo $rar_entry;
rar_close($rar_arch);
?>

A se vedea ?i

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

Descrierea

Stil obiect-orientat (method):

public bool RarArchive::isBroken ( void )

Stil procedural:

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.

Parametri

rarfile

A RarArchive object, opened with rar_open().

Valorile întoarse

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.

Exemple

Example #1 Stil obiect-orientat

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

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)

Example #2 Stil procedural

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

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public bool RarArchive::isSolid ( void )

Stil procedural:

bool rar_solid_is ( RarArchive $rarfile )

Check whether the RAR archive is solid. Individual file extraction is slower on solid archives.

Parametri

rarfile

A RarArchive object, opened with rar_open().

Valorile întoarse

Returns TRUE if the archive is solid, FALSE otherwise.

Exemple

Example #1 Stil obiect-orientat

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

Exemplul de mai sus va afi?a ceva similar cu:

RAR Archive "C:\php_rar\trunk\tests\store_method.rar": no
RAR Archive "C:\php_rar\trunk\tests\solid.rar": yes

Example #2 Stil procedural

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

Descrierea

Stil obiect-orientat (method):

public static RarArchive RarArchive::open ( string $filename [, string $password = NULL [, callable $volume_callback = NULL ]] )

Stil procedural:

RarArchive rar_open ( string $filename [, string $password = NULL [, callable $volume_callback = NULL ]] )

Open specified RAR archive and return RarArchive instance representing it.

Nota:

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.

Parametri

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.

Avertizare

Prior to version 2.0.0, this function would not handle relative paths correctly. Use realpath() as a workaround.

Valorile întoarse

Returns the requested RarArchive instance sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
3.0.0 | volume_callback was added.

Exemple

Example #1 Stil obiect-orientat

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

Exemplul de mai sus va afi?a ceva similar cu:

Found 2 files.
Content of first one follows:
Encrypted file 1 contents.

Example #2 Stil procedural

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

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

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public bool RarArchive::setAllowBroken ( bool $allow_broken )

Stil procedural:

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.

Parametri

rarfile

A RarArchive object, opened with rar_open().

allow_broken

Whether to allow reading broken files (TRUE) or not (FALSE).

Valorile întoarse

Returns TRUE sau FALSE în cazul e?ecului. It will only fail if the file has already been closed.

Exemple

Example #1 Stil obiect-orientat

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

Exemplul de mai sus va afi?a ceva similar cu:

RarEntry for file "file1.txt" (52b28202)
int(1)

Example #2 Stil procedural

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

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A textual representation of this RarArchive object. The content of this representation is unspecified.

Exemple

Example #1 RarArchive::__toString() example

<?php
$rar_arch = RarArchive::open('latest_winrar.rar');
echo $rar_arch."\n";
$rar_arch->close();
echo $rar_arch."\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

(PECL rar >= 0.1)

Introducere

A RAR entry, representing a directory or a compressed file inside a RAR archive.

Sinopsisul clasei

final RarEntry {
/* Constante */
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 ;
/* Metode */
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 )
}

Constante predefinite

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.

Cuprins

  • 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

Descrierea

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.

Parametri

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.

Avertizare

Prior to version 2.0.0, this function would not handle relative paths correctly. Use realpath() as a workaround.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
3.0.0 | extended_data was added.
3.0.0 | Support for RAR archives with repeated entry names is no longer defective.

Exemple

Example #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

?>

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

?>

A se vedea ?i

  • 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

Descrierea

public int RarEntry::getAttr ( void )

Returns the OS-dependent attributes of the archive entry.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the attributes or FALSE on error.

Exemple

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

?>

A se vedea ?i

  • 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

Descrierea

public string RarEntry::getCrc ( void )

Returns an hexadecimal string representation of the CRC of the archive entry.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the CRC of the archive entry or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
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

Descrierea

public string RarEntry::getFileTime ( void )

Gets entry last modification time.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int RarEntry::getHostOs ( void )

Returns the code of the host OS of the archive entry.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the code of the host OS, or FALSE on error.

Exemple

Example #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;
}

?>

Example #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;
}

?>

A se vedea ?i

  • 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

Descrierea

public int RarEntry::getMethod ( void )

RarEntry::getMethod() returns number of the method used when adding current archive entry.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the method number or FALSE on error.

Exemple

Example #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

Descrierea

public string RarEntry::getName ( void )

Returns the name (with path) of the archive entry.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the entry name as a string, or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
2.0.0 | As of version 2.0.0, the returned string is encoded in Unicode/UTF-8.

Exemple

Example #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

Descrierea

public int RarEntry::getPackedSize ( void )

Get packed size of the archive entry.

Nota:

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the packed size, or FALSE on error.

Istoricul schimbarilor

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

Exemple

Example #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

Descrierea

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

Avertizare

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.

Parametri

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

Valorile întoarse

The file handler sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
3.0.0 | Support for RAR archives with repeated entry names is no longer defective.

Exemple

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

?>

A se vedea ?i

  • 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

Descrierea

public int RarEntry::getUnpackedSize ( void )

Get unpacked size of the archive entry.

Nota:

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the unpacked size, or FALSE on error.

Istoricul schimbarilor

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

Valorile întoarse

Example #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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the version or FALSE on error.

Exemple

Example #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

Descrierea

public bool RarEntry::isDirectory ( void )

Tests whether the current entry is a directory.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if this entry is a directory and FALSE otherwise.

Note

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

Descrierea

public bool RarEntry::isEncrypted ( void )

Tests whether the current entry contents are encrypted.

Nota:

The password used may differ between files inside the same RAR archive.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A textual representation for the entry.

RarEntry::isEncrypted
RarException
RarEntry


The RarException class

(PECL rar >= 2.0.0)

Introducere

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

Sinopsisul clasei

final RarException extends Exception {
/* Metode */
public static bool isUsingExceptions ( void )
public static void setUsingExceptions ( bool $using_exceptions )
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Cuprins

  • 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

Descrierea

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

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if exceptions are being used, FALSE otherwise.

Exemple

Example #1 RarException::isUsingExceptions() example

<?php
//The default is not to use exceptions
var_dump(RarException::isUsingExceptions());
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)

A se vedea ?i

  • 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

Descrierea

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

Parametri

using_exceptions

Should be TRUE to activate exception throwing, FALSE to deactivate (the default).

Exemple

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

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • RarException::isUsingExceptions() - Check whether error handling with exceptions is in use

RarException::isUsingExceptions
Zip
RarException


Zip

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • 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::addGlob — Add files from a directory by glob pattern
    • ZipArchive::addPattern — Add files from a directory by PCRE pattern
    • 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::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index
    • ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its 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::setCompressionIndex — Set the compression method of an entry defined by its index
    • ZipArchive::setCompressionName — Set the compression method of an entry defined by its name
    • ZipArchive::setExternalAttributesIndex — Set the external attributes of an entry defined by its index
    • ZipArchive::setExternalAttributesName — Set the external attributes of an entry defined by its name
    • ZipArchive::setPassword — Set the password for the active archive
    • 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.
  • Func?ii Zip
    • 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
Introducere
Extensii de compresie ?i arhivare


Introducere

This extension enables you to transparently read or write ZIP compressed archives and the files inside them.

Zip
Instalarea / configurarea
Zip


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Zip


Necesita?i

This extension requires » libzip which is bundled with PHP.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Linux systems

In order to use these functions you must compile PHP with zip support by using the --enable-zip configure option.

As of PHP 5.6.0 a --with-libzip=DIR configure option has been added to use a system libzip installation. libzip version 0.11 is required, with 0.11.2 or later recommended.

Windows

As of PHP 5.3 this extension is built-in. Before, Windows users need to enable php_zip.dll inside of php.ini in order to use these functions.

Installation via PECL

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/zip.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

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.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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::FL_ENC_GUESS (integer)
Guess string encoding (is default). Available as of PHP 7.0.8.
ZipArchive::FL_ENC_RAW (integer)
Get unmodified string. Available as of PHP 7.0.8.
ZipArchive::FL_ENC_STRICT (integer)
Follow specification strictly. Available as of PHP 7.0.8.
ZipArchive::FL_ENC_UTF_8 (integer)
String is UTF-8 encoded. Available as of PHP 7.0.8.
ZipArchive::FL_ENC_CP437 (integer)
String is CP437 encoded. Available as of PHP 7.0.8.
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
Operating system constants for external attributes
ZipArchive::OPSYS_DOS (integer)
ZipArchive::OPSYS_AMIGA (integer)
ZipArchive::OPSYS_OPENVMS (integer)
ZipArchive::OPSYS_UNIX (integer)
ZipArchive::OPSYS_VM_CMS (integer)
ZipArchive::OPSYS_ATARI_ST (integer)
ZipArchive::OPSYS_OS_2 (integer)
ZipArchive::OPSYS_MACINTOSH (integer)
ZipArchive::OPSYS_Z_SYSTEM (integer)
ZipArchive::OPSYS_CPM (integer)
ZipArchive::OPSYS_WINDOWS_NTFS (integer)
ZipArchive::OPSYS_MVS (integer)
ZipArchive::OPSYS_VSE (integer)
ZipArchive::OPSYS_ACORN_RISC (integer)
ZipArchive::OPSYS_VFAT (integer)
ZipArchive::OPSYS_ALTERNATE_MVS (integer)
ZipArchive::OPSYS_BEOS (integer)
ZipArchive::OPSYS_TANDEM (integer)
ZipArchive::OPSYS_OS_400 (integer)
ZipArchive::OPSYS_OS_X (integer)
ZipArchive::OPSYS_DEFAULT (integer)
Since PHP 5.6.0, PECL zip 1.12.4
Tipurile resurselor
Exemple
Zip


Exemple

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

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

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

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

}
?>
Constante predefinite
ZipArchive
Zip


The ZipArchive class

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

Introducere

A file archive, compressed with Zip.

Sinopsisul clasei

ZipArchive {
/* Proprieta?i */
int $status;
int $statusSys;
int $numFiles;
string $filename;
string $comment;
/* Metode */
bool addEmptyDir ( string $dirname )
bool addFile ( string $filename [, string $localname = NULL [, int $start = 0 [, int $length = 0 ]]] )
bool addFromString ( string $localname , string $contents )
bool addGlob ( string $pattern [, int $flags = 0 [, array $options = array() ]] )
bool addPattern ( string $pattern [, string $path = "." [, array $options = array() ]] )
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 ] )
bool GetExternalAttributesIndex ( int $index , int &$opsys , int &$attr [, int $flags ] )
bool getExternalAttributesName ( string $name , int &$opsys , int &$attr [, int $flags ] )
string getFromIndex ( int $index [, int $length = 0 [, int $flags ]] )
string getFromName ( string $name [, int $length = 0 [, int $flags ]] )
string getNameIndex ( int $index [, int $flags ] )
string getStatusString ( void )
resource getStream ( string $name )
int locateName ( string $name [, int $flags ] )
mixed open ( string $filename [, int $flags ] )
bool renameIndex ( int $index , string $newname )
bool renameName ( string $name , string $newname )
bool setArchiveComment ( string $comment )
bool setCommentIndex ( int $index , string $comment )
bool setCommentName ( string $name , string $comment )
bool setCompressionIndex ( int $index , int $comp_method [, int $comp_flags = 0 ] )
bool setCompressionName ( string $name , int $comp_method [, int $comp_flags = 0 ] )
bool setExternalAttributesIndex ( int $index , int $opsys , int $attr [, int $flags ] )
bool setExternalAttributesName ( string $name , int $opsys , int $attr [, int $flags ] )
public bool setPassword ( string $password )
array statIndex ( int $index [, int $flags ] )
array statName ( string $name [, int $flags ] )
bool unchangeAll ( void )
bool unchangeArchive ( void )
bool unchangeIndex ( int $index )
bool unchangeName ( string $name )
}

Proprieta?i

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

Cuprins

  • 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::addGlob — Add files from a directory by glob pattern
  • ZipArchive::addPattern — Add files from a directory by PCRE pattern
  • 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::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index
  • ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its 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::setCompressionIndex — Set the compression method of an entry defined by its index
  • ZipArchive::setCompressionName — Set the compression method of an entry defined by its name
  • ZipArchive::setExternalAttributesIndex — Set the external attributes of an entry defined by its index
  • ZipArchive::setExternalAttributesName — Set the external attributes of an entry defined by its name
  • ZipArchive::setPassword — Set the password for the active archive
  • 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.
Exemple
ZipArchive::addEmptyDir
Zip


Add a new directory

ZipArchive
ZipArchive::addFile
ZipArchive
PHP Manual

ZipArchive::addEmptyDir

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.8.0)

ZipArchive::addEmptyDir — Add a new directory

Descrierea

bool ZipArchive::addEmptyDir ( string $dirname )

Adds an empty directory in the archive.

Parametri

dirname

The directory to add.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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, PHP 7, PECL zip >= 1.1.0)

ZipArchive::addFile — Adds a file to a ZIP archive from the given path

Descrierea

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.

Nota: For maximum portability, it is recommended to always use forward slashes (/) as directory separator in ZIP filenames.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

This example opens a ZIP file archive test.zip and add the file /path/to/index.txt. as newname.txt.

Example #1 Open and add

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

Note

Nota:

When a file is set to be added to the archive, PHP will lock the file. The lock is only released once the ZipArchive object has been closed, either via ZipArchive::close() or the ZipArchive object being destroyed. This may prevent you from being able to delete the file being added until after the lock has been released.

ZipArchive::addEmptyDir
ZipArchive::addFromString
ZipArchive


Add a file to a ZIP archive using its contents

ZipArchive::addFile
ZipArchive::addGlob
ZipArchive
PHP Manual

ZipArchive::addFromString

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::addFromString — Add a file to a ZIP archive using its contents

Descrierea

bool ZipArchive::addFromString ( string $localname , string $contents )

Add a file to a ZIP archive using its contents.

Nota: For maximum portability, it is recommended to always use forward slashes (/) as directory separator in ZIP filenames.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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';
}
?>

Example #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::addGlob
ZipArchive


Add files from a directory by glob pattern

ZipArchive::addFromString
ZipArchive::addPattern
ZipArchive
PHP Manual

ZipArchive::addGlob

(PHP 5 >= 5.3.0, PHP 7, PECL zip >= 1.9.0)

ZipArchive::addGlob — Add files from a directory by glob pattern

Descrierea

bool ZipArchive::addGlob ( string $pattern [, int $flags = 0 [, array $options = array() ]] )

Add files from a directory which match the glob pattern.

Nota: For maximum portability, it is recommended to always use forward slashes (/) as directory separator in ZIP filenames.

Parametri

pattern

A glob() pattern against which files will be matched.

flags

A bit mask of glob() flags.

options

An associative array of options. Available options are:

  • "add_path"

    Prefix to prepend when translating to the local path of the file within the archive. This is applied after any remove operations defined by the "remove_path" or "remove_all_path" options.

  • "remove_path"

    Prefix to remove from matching file paths before adding to the archive.

  • "remove_all_path"

    TRUE to use the file name only and add to the root of the archive.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ZipArchive::addGlob() example

Add all php scripts and text files from current working directory

<?php
$zip = new ZipArchive();
$ret = $zip->open('application.zip', ZipArchive::OVERWRITE);
if ($ret !== TRUE) {
    printf('Failed with code %d', $ret);
} else {
    $options = array('add_path' => 'sources/', 'remove_all_path' => TRUE);
    $zip->addGlob('*.{php,txt}', GLOB_BRACE, $options);
    $zip->close();
}
?>

A se vedea ?i

  • ZipArchive::addFile() - Adds a file to a ZIP archive from the given path
  • ZipArchive::addPattern() - Add files from a directory by PCRE pattern

ZipArchive::addFromString
ZipArchive::addPattern
ZipArchive


Add files from a directory by PCRE pattern

ZipArchive::addGlob
ZipArchive::close
ZipArchive
PHP Manual

ZipArchive::addPattern

(PHP 5 >= 5.3.0, PHP 7, PECL zip >= 1.9.0)

ZipArchive::addPattern — Add files from a directory by PCRE pattern

Descrierea

bool ZipArchive::addPattern ( string $pattern [, string $path = "." [, array $options = array() ]] )

Add files from a directory which match the regular expression pattern. The operation is not recursive. The pattern will be matched against the file name only.

Parametri

pattern

A PCRE pattern against which files will be matched.

path

The directory that will be scanned. Defaults to the current working directory.

options

An associative array of options accepted by ZipArchive::addGlob().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ZipArchive::addPattern() example

Add all php scripts and text files from current directory

<?php
$zip = new ZipArchive();
$ret = $zip->open('application.zip', ZipArchive::OVERWRITE);
if ($ret !== TRUE) {
    printf('Failed with code %d', $ret);
} else {
    $directory = realpath('.');
    $options = array('add_path' => 'sources/', 'remove_path' => $directory);
    $zip->addPattern('/\.(?:php|txt)$/', $directory, $options);
    $zip->close();
}
?>

A se vedea ?i

  • ZipArchive::addFile() - Adds a file to a ZIP archive from the given path
  • ZipArchive::addGlob() - Add files from a directory by glob pattern

ZipArchive::addGlob
ZipArchive::close
ZipArchive


Close the active archive (opened or newly created)

ZipArchive::addPattern
ZipArchive::deleteIndex
ZipArchive
PHP Manual

ZipArchive::close

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::close — Close the active archive (opened or newly created)

Descrierea

bool ZipArchive::close ( void )

Close opened or created archive and save changes. This method is automatically called at the end of the script.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ZipArchive::addPattern
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, PHP 7, PECL zip >= 1.5.0)

ZipArchive::deleteIndex — delete an entry in the archive using its index

Descrierea

bool ZipArchive::deleteIndex ( int $index )

Delete an entry in the archive using its index.

Parametri

index

Index of the entry to delete.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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, PHP 7, PECL zip >= 1.5.0)

ZipArchive::deleteName — delete an entry in the archive using its name

Descrierea

bool ZipArchive::deleteName ( string $name )

Delete an entry in the archive using its name.

Parametri

name

Name of the entry to delete.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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, PHP 7, PECL zip >= 1.1.0)

ZipArchive::extractTo — Extract the archive contents

Descrierea

bool ZipArchive::extractTo ( string $destination [, mixed $entries ] )

Extract the complete archive or the given files to the specified destination.

Parametri

destination

Location where to extract the files.

entries

The entries to extract. It accepts either a single entry name or an array of names.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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';
}
?>

Example #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, PHP 7, PECL zip >= 1.1.0)

ZipArchive::getArchiveComment — Returns the Zip archive comment

Descrierea

string ZipArchive::getArchiveComment ([ int $flags ] )

Returns the Zip archive comment.

Parametri

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged comment is returned.

Valorile întoarse

Returns the Zip archive comment sau FALSE în cazul e?ecului.

Exemple

Example #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, PHP 7, PECL zip >= 1.4.0)

ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index

Descrierea

string ZipArchive::getCommentIndex ( int $index [, int $flags ] )

Returns the comment of an entry using the entry index.

Parametri

index

Index of the entry

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged comment is returned.

Valorile întoarse

Returns the comment on success sau FALSE în cazul e?ecului.

Exemple

Example #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::getExternalAttributesIndex
ZipArchive
PHP Manual

ZipArchive::getCommentName

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.4.0)

ZipArchive::getCommentName — Returns the comment of an entry using the entry name

Descrierea

string ZipArchive::getCommentName ( string $name [, int $flags ] )

Returns the comment of an entry using the entry name.

Parametri

name

Name of the entry

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged comment is returned.

Valorile întoarse

Returns the comment on success sau FALSE în cazul e?ecului.

Exemple

Example #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::getExternalAttributesIndex
ZipArchive


Retrieve the external attributes of an entry defined by its index

ZipArchive::getCommentName
ZipArchive::getExternalAttributesName
ZipArchive
PHP Manual

ZipArchive::getExternalAttributesIndex

(PHP 5 >= 5.6.0, PHP 7, PECL zip >= 1.12.4)

ZipArchive::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index

Descrierea

bool ZipArchive::GetExternalAttributesIndex ( int $index , int &$opsys , int &$attr [, int $flags ] )

Retrieve the external attributes of an entry defined by its index.

Parametri

index

Index of the entry.

opsys

On success, receive the operating system code defined by one of the ZipArchive::OPSYS_ constants.

attr

On success, receive the external attributes. Value depends on operating system.

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged attributes are returned.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

This example extract all the entries of a ZIP archive test.zip and set the Unix rights from external attributes.

Example #1 Extract all entries with Unix rights

<?php
$zip = new ZipArchive();
if ($zip->open('test.zip') === TRUE) {
    for ($idx=0 ; $s = $zip->statIndex($idx) ; $idx++) {
        if ($zip->extractTo('.', $s['name'])) {
            if ($zip->getExternalAttributesIndex($idx, $opsys, $attr)
                && $opsys==ZipArchive::OPSYS_UNIX) {
               chmod($s['name'], ($attr >> 16) & 0777);
            }
        }
    }
    $zip->close();
    echo "Ok\n";
} else {
    echo "KO\n";
}
?>
ZipArchive::getCommentName
ZipArchive::getExternalAttributesName
ZipArchive


Retrieve the external attributes of an entry defined by its name

ZipArchive::getExternalAttributesIndex
ZipArchive::getFromIndex
ZipArchive
PHP Manual

ZipArchive::getExternalAttributesName

(PHP 5 >= 5.6.0, PHP 7, PECL zip >= 1.12.4)

ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its name

Descrierea

bool ZipArchive::getExternalAttributesName ( string $name , int &$opsys , int &$attr [, int $flags ] )

Retrieve the external attributes of an entry defined by its name.

Parametri

name

Name of the entry.

opsys

On success, receive the operating system code defined by one of the ZipArchive::OPSYS_ constants.

attr

On success, receive the external attributes. Value depends on operating system.

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged attributes are returned.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ZipArchive::getExternalAttributesIndex
ZipArchive::getFromIndex
ZipArchive


Returns the entry contents using its index

ZipArchive::getExternalAttributesName
ZipArchive::getFromName
ZipArchive
PHP Manual

ZipArchive::getFromIndex

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

ZipArchive::getFromIndex — Returns the entry contents using its index

Descrierea

string ZipArchive::getFromIndex ( int $index [, int $length = 0 [, int $flags ]] )

Returns the entry contents using its index.

Parametri

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

Valorile întoarse

Returns the contents of the entry on success sau FALSE în cazul e?ecului.

Exemple

Example #1 Get the file contents

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    echo $zip->getFromIndex(2);
    $zip->close();
} else {
    echo 'failed';
}
?>

A se vedea ?i

  • ZipArchive::getFromName() - Returns the entry contents using its name

ZipArchive::getExternalAttributesName
ZipArchive::getFromName
ZipArchive


Returns the entry contents using its name

ZipArchive::getFromIndex
ZipArchive::getNameIndex
ZipArchive
PHP Manual

ZipArchive::getFromName

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::getFromName — Returns the entry contents using its name

Descrierea

string ZipArchive::getFromName ( string $name [, int $length = 0 [, int $flags ]] )

Returns the entry contents using its name.

Parametri

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 find the entry. The following values may be ORed.

  • ZipArchive::FL_UNCHANGED

  • ZipArchive::FL_COMPRESSED

  • ZipArchive::FL_NOCASE

Valorile întoarse

Returns the contents of the entry on success sau FALSE în cazul e?ecului.

Exemple

Example #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';
}
?>

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

A se vedea ?i

  • ZipArchive::getFromIndex() - Returns the entry contents using its index

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, PHP 7, PECL zip >= 1.5.0)

ZipArchive::getNameIndex — Returns the name of an entry using its index

Descrierea

string ZipArchive::getNameIndex ( int $index [, int $flags ] )

Returns the name of an entry using its index.

Parametri

index

Index of the entry.

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged name is returned.

Valorile întoarse

Returns the name on success sau FALSE în cazul e?ecului.

Exemple

Example #1 ZipArchive::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, PHP 7)

ZipArchive::getStatusString — Returns the status error message, system and/or zip messages

Descrierea

string ZipArchive::getStatusString ( void )

Returns the status error message, system and/or zip messages.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string with the status message on success sau FALSE în cazul e?ecului.

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, PHP 7, PECL zip >= 1.1.0)

ZipArchive::getStream — Get a file handler to the entry defined by its name (read only).

Descrierea

resource ZipArchive::getStream ( string $name )

Get a file handler to the entry defined by its name. For now it only supports read operations.

Parametri

name

The name of the entry to use.

Valorile întoarse

Returns a file pointer (resource) on success sau FALSE în cazul e?ecului.

Exemple

Example #1 Get the entry contents with fread() and store it

<?php
$contents = '';
$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";
}
?>

Example #2 Same as the previous example but with fopen() and the zip stream wrapper

<?php
$contents = '';
$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";
?>

Example #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, PHP 7, PECL zip >= 1.5.0)

ZipArchive::locateName — Returns the index of the entry in the archive

Descrierea

int ZipArchive::locateName ( string $name [, int $flags ] )

Locates an entry using its name.

Parametri

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

Valorile întoarse

Returns the index of the entry on success sau FALSE în cazul e?ecului.

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a:

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, PHP 7, PECL zip >= 1.1.0)

ZipArchive::open — Open a ZIP file archive

Descrierea

mixed ZipArchive::open ( string $filename [, int $flags ] )

Opens a new zip archive for reading, writing or modifying.

Parametri

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

Valorile întoarse

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.

Exemple

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

Example #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, PHP 7, PECL zip >= 1.5.0)

ZipArchive::renameIndex — Renames an entry defined by its index

Descrierea

bool ZipArchive::renameIndex ( int $index , string $newname )

Renames an entry defined by its index.

Parametri

index

Index of the entry to rename.

newname

New name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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, PHP 7, PECL zip >= 1.5.0)

ZipArchive::renameName — Renames an entry defined by its name

Descrierea

bool ZipArchive::renameName ( string $name , string $newname )

Renames an entry defined by its name.

Parametri

name

Name of the entry to rename.

newname

New name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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, PHP 7, PECL zip >= 1.4.0)

ZipArchive::setArchiveComment — Set the comment of a ZIP archive

Descrierea

bool ZipArchive::setArchiveComment ( string $comment )

Set the comment of a ZIP archive.

Parametri

comment

The contents of the comment.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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, PHP 7, PECL zip >= 1.4.0)

ZipArchive::setCommentIndex — Set the comment of an entry defined by its index

Descrierea

bool ZipArchive::setCommentIndex ( int $index , string $comment )

Set the comment of an entry defined by its index.

Parametri

index

Index of the entry.

comment

The contents of the comment.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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::setCompressionIndex
ZipArchive
PHP Manual

ZipArchive::setCommentName

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.4.0)

ZipArchive::setCommentName — Set the comment of an entry defined by its name

Descrierea

bool ZipArchive::setCommentName ( string $name , string $comment )

Set the comment of an entry defined by its name.

Parametri

name

Name of the entry.

comment

The contents of the comment.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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::setCompressionIndex
ZipArchive


Set the compression method of an entry defined by its index

ZipArchive::setCommentName
ZipArchive::setCompressionName
ZipArchive
PHP Manual

ZipArchive::setCompressionIndex

(PHP 7, PECL zip >= 1.13.0)

ZipArchive::setCompressionIndex — Set the compression method of an entry defined by its index

Descrierea

bool ZipArchive::setCompressionIndex ( int $index , int $comp_method [, int $comp_flags = 0 ] )

Set the compression method of an entry defined by its index.

Parametri

index

Index of the entry.

comp_method

The compression method. Either
ZipArchive::CM_DEFAULT,
ZipArchive::CM_STORE or
ZipArchive::CM_DEFLATE.

comp_flags

Compression flags. Currently unused.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Add files with different compression methods to an archive

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('foo', 'Some text');
    $zip->addFromString('bar', 'Some other text');
    $zip->setCompressionIndex(0, ZipArchive::CM_STORE);
    $zip->setCompressionIndex(1, ZipArchive::CM_DEFLATE);
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::setCommentName
ZipArchive::setCompressionName
ZipArchive


Set the compression method of an entry defined by its name

ZipArchive::setCompressionIndex
ZipArchive::setExternalAttributesIndex
ZipArchive
PHP Manual

ZipArchive::setCompressionName

(PHP 7, PECL zip >= 1.13.0)

ZipArchive::setCompressionName — Set the compression method of an entry defined by its name

Descrierea

bool ZipArchive::setCompressionName ( string $name , int $comp_method [, int $comp_flags = 0 ] )

Set the compression method of an entry defined by its name.

Parametri

name

Name of the entry.

comp_method

The compression method. Either
ZipArchive::CM_DEFAULT,
ZipArchive::CM_STORE or
ZipArchive::CM_DEFLATE.

comp_flags

Compression flags. Currently unused.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Add files with different compression methods to an archive

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('foo', 'Some text');
    $zip->addFromString('bar', 'Some other text');
    $zip->setCompressionName('foo', ZipArchive::CM_STORE);
    $zip->setCompressionName('bar', ZipArchive::CM_DEFLATE);
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::setCompressionIndex
ZipArchive::setExternalAttributesIndex
ZipArchive


Set the external attributes of an entry defined by its index

ZipArchive::setCompressionName
ZipArchive::setExternalAttributesName
ZipArchive
PHP Manual

ZipArchive::setExternalAttributesIndex

(PHP 5 >= 5.6.0, PHP 7, PECL zip >= 1.12.4)

ZipArchive::setExternalAttributesIndex — Set the external attributes of an entry defined by its index

Descrierea

bool ZipArchive::setExternalAttributesIndex ( int $index , int $opsys , int $attr [, int $flags ] )

Set the external attributes of an entry defined by its index.

Parametri

index

Index of the entry.

opsys

The operating system code defined by one of the ZipArchive::OPSYS_ constants.

attr

The external attributes. Value depends on operating system.

flags

Optional flags. Currently unused.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ZipArchive::setCompressionName
ZipArchive::setExternalAttributesName
ZipArchive


Set the external attributes of an entry defined by its name

ZipArchive::setExternalAttributesIndex
ZipArchive::setPassword
ZipArchive
PHP Manual

ZipArchive::setExternalAttributesName

(PHP 5 >= 5.6.0, PHP 7, PECL zip >= 1.12.4)

ZipArchive::setExternalAttributesName — Set the external attributes of an entry defined by its name

Descrierea

bool ZipArchive::setExternalAttributesName ( string $name , int $opsys , int $attr [, int $flags ] )

Set the external attributes of an entry defined by its name.

Parametri

name

Name of the entry.

opsys

The operating system code defined by one of the ZipArchive::OPSYS_ constants.

attr

The external attributes. Value depends on operating system.

flags

Optional flags. Currently unused.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

This example opens a ZIP file archive test.zip and add the file test.txt with its Unix rights as external attributes.

Example #1 Archive a file, with its Unix rights

<?php
$zip = new ZipArchive();
$stat = stat($filename='test.txt');
if (is_array($stat) && $zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
    $zip->addFile($filename);
    $zip->setExternalAttributesName($filename, ZipArchive::OPSYS_UNIX, $stat['mode'] << 16);
    $zip->close();
    echo "Ok\n";
} else {
    echo "KO\n";
}
?>
ZipArchive::setExternalAttributesIndex
ZipArchive::setPassword
ZipArchive


Set the password for the active archive

ZipArchive::setExternalAttributesName
ZipArchive::statIndex
ZipArchive
PHP Manual

ZipArchive::setPassword

(PHP 5 >= 5.6.0, PHP 7, PECL zip >= 1.12.4)

ZipArchive::setPassword — Set the password for the active archive

Descrierea

public bool ZipArchive::setPassword ( string $password )

Sets the password for the active archive.

Parametri

password

The password to be used for the archive.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

This function only sets the password to be used to decompress the archive; it does not turn a non-password-protected ZipArchive into a password-protected ZipArchive.

ZipArchive::setExternalAttributesName
ZipArchive::statIndex
ZipArchive


Get the details of an entry defined by its index.

ZipArchive::setPassword
ZipArchive::statName
ZipArchive
PHP Manual

ZipArchive::statIndex

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::statIndex — Get the details of an entry defined by its index.

Descrierea

array ZipArchive::statIndex ( int $index [, int $flags ] )

The function obtains information about the entry defined by its index.

Parametri

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.

Valorile întoarse

Returns an array containing the entry details sau FALSE în cazul e?ecului.

Exemple

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

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [name] => foobar/baz
    [index] => 3
    [crc] => 499465816
    [size] => 27
    [mtime] => 1123164748
    [comp_size] => 24
    [comp_method] => 8
)
ZipArchive::setPassword
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, PHP 7, PECL zip >= 1.5.0)

ZipArchive::statName — Get the details of an entry defined by its name.

Descrierea

array ZipArchive::statName ( string $name [, int $flags ] )

The function obtains information about the entry defined by its name.

Parametri

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

Valorile întoarse

Returns an array containing the entry details sau FALSE în cazul e?ecului.

Exemple

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

Exemplul de mai sus va afi?a ceva similar cu:

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, PHP 7, PECL zip >= 1.1.0)

ZipArchive::unchangeAll — Undo all changes done in the archive

Descrierea

bool ZipArchive::unchangeAll ( void )

Undo all changes done in the archive.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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, PHP 7, PECL zip >= 1.1.0)

ZipArchive::unchangeArchive — Revert all global changes done in the archive.

Descrierea

bool ZipArchive::unchangeArchive ( void )

Revert all global changes to the archive. For now, this only reverts archive comment changes.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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, PHP 7, PECL zip >= 1.1.0)

ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index

Descrierea

bool ZipArchive::unchangeIndex ( int $index )

Revert all changes done to an entry at the given index.

Parametri

index

Index of the entry.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ZipArchive::unchangeArchive
ZipArchive::unchangeName
ZipArchive


Revert all changes done to an entry with the given name.

ZipArchive::unchangeIndex
Func?ii Zip
ZipArchive
PHP Manual

ZipArchive::unchangeName

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.5.0)

ZipArchive::unchangeName — Revert all changes done to an entry with the given name.

Descrierea

bool ZipArchive::unchangeName ( string $name )

Revert all changes done to an entry.

Parametri

name

Name of the entry.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ZipArchive::unchangeIndex
Func?ii Zip
ZipArchive


Func?ii Zip

Cuprins

  • 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

Func?ii Zip
zip_entry_close
Func?ii Zip
PHP Manual

zip_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_close — Close a ZIP file archive

Descrierea

void zip_close ( resource $zip )

Closes the given ZIP file archive.

Parametri

zip

A ZIP file previously opened with zip_open().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

Func?ii Zip
zip_entry_close
Func?ii Zip


Close a directory entry

zip_close
zip_entry_compressedsize
Func?ii Zip
PHP Manual

zip_entry_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_close — Close a directory entry

Descrierea

bool zip_entry_close ( resource $zip_entry )

Closes the specified directory entry.

Parametri

zip_entry

A directory entry previously opened zip_entry_open().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • zip_entry_open() - Open a directory entry for reading
  • zip_entry_read() - Read from an open directory entry

zip_close
zip_entry_compressedsize
Func?ii Zip


Retrieve the compressed size of a directory entry

zip_entry_close
zip_entry_compressionmethod
Func?ii Zip
PHP Manual

zip_entry_compressedsize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_compressedsize — Retrieve the compressed size of a directory entry

Descrierea

int zip_entry_compressedsize ( resource $zip_entry )

Returns the compressed size of the specified directory entry.

Parametri

zip_entry

A directory entry returned by zip_read().

Valorile întoarse

The compressed size.

A se vedea ?i

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

zip_entry_close
zip_entry_compressionmethod
Func?ii Zip


Retrieve the compression method of a directory entry

zip_entry_compressedsize
zip_entry_filesize
Func?ii Zip
PHP Manual

zip_entry_compressionmethod

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_compressionmethod — Retrieve the compression method of a directory entry

Descrierea

string zip_entry_compressionmethod ( resource $zip_entry )

Returns the compression method of the directory entry specified by zip_entry.

Parametri

zip_entry

A directory entry returned by zip_read().

Valorile întoarse

The compression method.

A se vedea ?i

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

zip_entry_compressedsize
zip_entry_filesize
Func?ii Zip


Retrieve the actual file size of a directory entry

zip_entry_compressionmethod
zip_entry_name
Func?ii Zip
PHP Manual

zip_entry_filesize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_filesize — Retrieve the actual file size of a directory entry

Descrierea

int zip_entry_filesize ( resource $zip_entry )

Returns the actual size of the specified directory entry.

Parametri

zip_entry

A directory entry returned by zip_read().

Valorile întoarse

The size of the directory entry.

A se vedea ?i

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

zip_entry_compressionmethod
zip_entry_name
Func?ii Zip


Retrieve the name of a directory entry

zip_entry_filesize
zip_entry_open
Func?ii Zip
PHP Manual

zip_entry_name

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_name — Retrieve the name of a directory entry

Descrierea

string zip_entry_name ( resource $zip_entry )

Returns the name of the specified directory entry.

Parametri

zip_entry

A directory entry returned by zip_read().

Valorile întoarse

The name of the directory entry.

A se vedea ?i

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

zip_entry_filesize
zip_entry_open
Func?ii Zip


Open a directory entry for reading

zip_entry_name
zip_entry_read
Func?ii Zip
PHP Manual

zip_entry_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_open — Open a directory entry for reading

Descrierea

bool zip_entry_open ( resource $zip , resource $zip_entry [, string $mode ] )

Opens a directory entry in a zip file for reading.

Parametri

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

Nota:

Currently, mode is ignored and is always "rb". This is due to the fact that zip support in PHP is read only access.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Nota:

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.

A se vedea ?i

  • zip_entry_close() - Close a directory entry
  • zip_entry_read() - Read from an open directory entry

zip_entry_name
zip_entry_read
Func?ii Zip


Read from an open directory entry

zip_entry_open
zip_open
Func?ii Zip
PHP Manual

zip_entry_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_read — Read from an open directory entry

Descrierea

string zip_entry_read ( resource $zip_entry [, int $length = 1024 ] )

Reads from an open directory entry.

Parametri

zip_entry

A directory entry returned by zip_read().

length

The number of bytes to return.

Nota:

This should be the uncompressed length you wish to read.

Valorile întoarse

Returns the data read, empty string on end of a file, or FALSE on error.

A se vedea ?i

  • 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
Func?ii Zip


Open a ZIP file archive

zip_entry_read
zip_read
Func?ii Zip
PHP Manual

zip_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_open — Open a ZIP file archive

Descrierea

resource zip_open ( string $filename )

Opens a new zip archive for reading.

Parametri

filename

The file name of the ZIP archive to open.

Valorile întoarse

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.

A se vedea ?i

  • zip_read() - Read next entry in a ZIP file archive
  • zip_close() - Close a ZIP file archive

zip_entry_read
zip_read
Func?ii Zip


Read next entry in a ZIP file archive

zip_open
Zlib
Func?ii Zip
PHP Manual

zip_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_read — Read next entry in a ZIP file archive

Descrierea

resource zip_read ( resource $zip )

Reads the next entry in a zip file archive.

Parametri

zip

A ZIP file previously opened with zip_open().

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii Zip


Zlib Compression

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii Zlib
    • deflate_add — Incrementally deflate data
    • deflate_init — Initialize an incremental deflate context
    • 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 — Pseudonim pentru 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
    • inflate_add — Incrementally inflate encoded data
    • inflate_init — Initialize an incremental inflate context
    • readgzfile — Output a gz-file
    • zlib_decode — Uncompress any raw/gzip/zlib encoded data
    • zlib_encode — Compress data with the specified encoding
    • zlib_get_coding_type — Returns the coding type used for output compression
zip_read
Introducere
Extensii de compresie ?i arhivare


Introducere

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

Nota:

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
Instalarea / configurarea
Zlib


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Zlib


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Sus?inerea Zlib în PHP nu este activata în mod implicit. Va trebui sa configura?i PHP cu op?iunea --with-zlib[=DIR]

Versiunea PHP pentru Windows sus?ine implicit aceasta extensie. Nu este nevoie sa încarca?i extensii suplimentare pentru a putea utiliza aceste func?ii.

Nota: Sus?inerea încorporata a zlib în Windows este disponibila începând cu PHP 4.3.0.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în 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
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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

Nota:

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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

This extension defines a file pointer resource returned by gzopen().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

FORCE_GZIP (integer)
FORCE_DEFLATE (integer)
ZLIB_ENCODING_RAW (integer)
Algoritmul DEFLATE conform RFC 1951. Disponibila începând cu PHP 7.0.0.
ZLIB_ENCODING_DEFLATE (integer)
Algoritmul de compresie ZLIB conform RFC 1950. Disponibila începând cu PHP 7.0.0.
ZLIB_ENCODING_GZIP (integer)
Algoritmul GZIP conform RFC 1952. Disponibila începând cu PHP 7.0.0.
ZLIB_FILTERED (integer)
Disponibila începând cu PHP 7.0.0.
ZLIB_HUFFMAN_ONLY (integer)
Disponibila începând cu PHP 7.0.0.
ZLIB_FIXED (integer)
Disponibila începând cu PHP 7.0.0.
ZLIB_RLE (integer)
Disponibila începând cu PHP 7.0.0.
ZLIB_DEFAULT_STRATEGY (integer)
Disponibila începând cu PHP 7.0.0.
ZLIB_BLOCK (integer)
Disponibila începând cu PHP 7.0.0.
ZLIB_NO_FLUSH (integer)
Disponibila începând cu PHP 7.0.0.
ZLIB_PARTIAL_FLUSH (integer)
Disponibila începând cu PHP 7.0.0.
ZLIB_SYNC_FLUSH (integer)
Disponibila începând cu PHP 7.0.0.
ZLIB_FULL_FLUSH (integer)
Disponibila începând cu PHP 7.0.0.
ZLIB_FINISH (integer)
Disponibila începând cu PHP 7.0.0.
Tipurile resurselor
Exemple
Zlib


Exemple

This example opens a temporary file and writes a test string to it, then it prints out the content of this file twice.

Example #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";

?>

Example #2 Working with the incremental compression and decompression API as of PHP 7.0.0

// Perform GZIP compression:
$deflateContext = deflate_init(ZLIB_ENCODING_GZIP);
$compressed = deflate_add($deflateContext, "Data to compress", ZLIB_NO_FLUSH);
$compressed .= deflate_add($deflateContext, ", more data", ZLIB_NO_FLUSH);
$compressed .= deflate_add($deflateContext, ", and even more data!", ZLIB_FINISH);?>

// Perform GZIP decompression:
$inflateContext = inflate_init(ZLIB_ENCODING_GZIP);
$uncompressed = inflate_add($inflateContext, $compressed, ZLIB_NO_FLUSH);
$uncompressed .= inflate_add($inflateContext, NULL, ZLIB_FINISH);
echo $uncompressed;

Exemplul de mai sus va afi?a:

Data to compress, more data, and even more data!
Constante predefinite
Func?ii Zlib
Zlib


Func?ii Zlib

Cuprins

  • deflate_add — Incrementally deflate data
  • deflate_init — Initialize an incremental deflate context
  • 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 — Pseudonim pentru 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
  • inflate_add — Incrementally inflate encoded data
  • inflate_init — Initialize an incremental inflate context
  • readgzfile — Output a gz-file
  • zlib_decode — Uncompress any raw/gzip/zlib encoded data
  • zlib_encode — Compress data with the specified encoding
  • zlib_get_coding_type — Returns the coding type used for output compression
Exemple
deflate_add
Zlib


Incrementally deflate data

Func?ii Zlib
deflate_init
Func?ii Zlib
PHP Manual

deflate_add

(PHP 7)

deflate_add — Incrementally deflate data

Descrierea

string deflate_add ( resource $context , string $data [, int $flush_mode = ZLIB_SYNC_FLUSH ] )

Incrementally deflates data in the specified context.

Parametri

context

A context created with deflate_init().

data

A chunk of data to compress.

flush_mode

One of ZLIB_BLOCK, ZLIB_NO_FLUSH, ZLIB_PARTIAL_FLUSH, ZLIB_SYNC_FLUSH (default), ZLIB_FULL_FLUSH, ZLIB_FINISH. Normally you will want to set ZLIB_NO_FLUSH to maximize compression, and ZLIB_FINISH to terminate with the last chunk of data. See the » zlib manual for a detailed description of these constants.

Valorile întoarse

Returns a chunk of compressed data, sau FALSE în cazul e?ecului.

Erori/Excep?ii

If invalid arguments are given, an error of level E_WARNING is generated.

A se vedea ?i

  • deflate_init() - Initialize an incremental deflate context
Func?ii Zlib
deflate_init
Func?ii Zlib


Initialize an incremental deflate context

deflate_add
gzclose
Func?ii Zlib
PHP Manual

deflate_init

(PHP 7)

deflate_init — Initialize an incremental deflate context

Descrierea

resource deflate_init ( int $encoding [, array $options = array() ] )

Initializes an incremental deflate context using the specified encoding.

Note that the window option here only sets the window size of the algorithm, differently from the zlib filters where the same parameter also sets the encoding to use; the encoding must be set with the encoding parameter.

Limitation: there is currently no way to set the header information on a GZIP compressed stream, which are set as follows: GZIP signature (\x1f\x8B); compression method (\x08 == DEFLATE); 6 zero bytes; the operating system set to the current system (\x00 = Windows, \x03 = Unix, etc.)

Parametri

encoding

One of the ZLIB_ENCODING_* constants.

options

An associative array which may contain the following elements:

level

The compression level in range -1..9; defaults to -1.

memory

The compression memory level in range 1..9; defaults to 8.

window

The zlib window size (logarithmic) in range 8..15; defaults to 15.

strategy

One of ZLIB_FILTERED, ZLIB_HUFFMAN_ONLY, ZLIB_RLE, ZLIB_FIXED or ZLIB_DEFAULT_STRATEGY (the default).

dictionary

A string or an array of strings of the preset dictionary (default: no preset dictionary).

Valorile întoarse

Returns a deflate context resource (zlib.deflate) on success, sau FALSE în cazul e?ecului.

Erori/Excep?ii

If an invalid option is passed to options or the context couldn't be created, an error of level E_WARNING is generated.

A se vedea ?i

  • deflate_add() - Incrementally deflate data
  • inflate_init() - Initialize an incremental inflate context
deflate_add
gzclose
Func?ii Zlib


Close an open gz-file pointer

deflate_init
gzcompress
Func?ii Zlib
PHP Manual

gzclose

(PHP 4, PHP 5, PHP 7)

gzclose — Close an open gz-file pointer

Descrierea

bool gzclose ( resource $zp )

Closes the given gz-file pointer.

Parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 gzclose() example

<?php
$gz = gzopen('somefile.gz','w9');
gzputs ($gz, 'I was added to somefile.gz');
gzclose($gz);
?>

A se vedea ?i

  • gzopen() - Open gz-file

deflate_init
gzcompress
Func?ii Zlib


Compress a string

gzclose
gzdecode
Func?ii Zlib
PHP Manual

gzcompress

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

gzcompress — Compress a string

Descrierea

string gzcompress ( string $data [, int $level = -1 [, int $encoding = ZLIB_ENCODING_DEFLATE ]] )

This function compresses 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).

Nota:

This is not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.

Parametri

data

The data to compress.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression.

If -1 is used, the default compression of the zlib library is used which is 6.

encoding

One of ZLIB_ENCODING_* constants.

Valorile întoarse

The compressed string or FALSE if an error occurred.

Exemple

Example #1 gzcompress() example

<?php
$compressed = gzcompress('Compress me', 9);
echo $compressed;
?>

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added encoding parameter.

A se vedea ?i

  • gzdeflate() - Deflate a string
  • gzinflate() - Inflate a deflated string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

gzclose
gzdecode
Func?ii Zlib


Decodes a gzip compressed string

gzcompress
gzdeflate
Func?ii Zlib
PHP Manual

gzdecode

(PHP 5 >= 5.4.0, PHP 7)

gzdecode — Decodes a gzip compressed string

Descrierea

string gzdecode ( string $data [, int $length ] )

This function returns a decoded version of the input data.

Parametri

data

The data to decode, encoded by gzencode().

length

The maximum length of data to decode.

Valorile întoarse

The decoded string, or FALSE if an error occurred.

A se vedea ?i

  • gzencode() - Create a gzip compressed string

gzcompress
gzdeflate
Func?ii Zlib


Deflate a string

gzdecode
gzencode
Func?ii Zlib
PHP Manual

gzdeflate

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gzdeflate — Deflate a string

Descrierea

string gzdeflate ( string $data [, int $level = -1 [, int $encoding = ZLIB_ENCODING_RAW ]] )

This function compresses 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).

Parametri

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.

encoding

One of ZLIB_ENCODING_* constants.

Valorile întoarse

The deflated string or FALSE if an error occurred.

Exemple

Example #1 gzdeflate() example

<?php
$compressed = gzdeflate('Compress me', 9);
echo $compressed;
?>

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added encoding parameter.

A se vedea ?i

  • gzinflate() - Inflate a deflated string
  • gzcompress() - Compress a string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

gzdecode
gzencode
Func?ii Zlib


Create a gzip compressed string

gzdeflate
gzeof
Func?ii Zlib
PHP Manual

gzencode

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gzencode — Create a gzip compressed string

Descrierea

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

Parametri

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.

Prior to PHP 5.4.0, using FORCE_DEFLATE results in a standard zlib deflated string (inclusive zlib headers) after a gzip file header but without the trailing crc32 checksum.

In PHP 5.4.0 and later, FORCE_DEFLATE generates RFC 1950 compliant output, consisting of a zlib header, the deflated data, and an Adler checksum.

Valorile întoarse

The encoded string, or FALSE if an error occurred.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | FORCE_DEFLATE now generates RFC 1950 compliant output.

Exemple

The resulting data contains the appropriate headers and data structure to make a standard .gz file, e.g.:

Example #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);
?>

A se vedea ?i

  • gzdecode() - Decodes a gzip compressed string
  • gzdeflate() - Deflate a string
  • gzinflate() - Inflate a deflated string
  • gzuncompress() - Uncompress a compressed string
  • gzcompress() - Compress a string
  • » ZLIB Compressed Data Format Specification (RFC 1950)

gzdeflate
gzeof
Func?ii Zlib


Test for EOF on a gz-file pointer

gzencode
gzfile
Func?ii Zlib
PHP Manual

gzeof

(PHP 4, PHP 5, PHP 7)

gzeof — Test for EOF on a gz-file pointer

Descrierea

int gzeof ( resource $zp )

Tests the given GZ file pointer for EOF.

Parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Valorile întoarse

Returns TRUE if the gz-file pointer is at EOF or an error occurs; otherwise returns FALSE.

Exemple

Example #1 gzeof() example

<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?>

gzencode
gzfile
Func?ii Zlib


Read entire gz-file into an array

gzeof
gzgetc
Func?ii Zlib
PHP Manual

gzfile

(PHP 4, PHP 5, PHP 7)

gzfile — Read entire gz-file into an array

Descrierea

array gzfile ( string $filename [, int $use_include_path = 0 ] )

This function is identical to readgzfile(), except that it returns the file in an array.

Parametri

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.

Valorile întoarse

An array containing the file, one line per cell, empty lines included, and with newlines still attached.

Exemple

Example #1 gzfile() example

<?php
$lines = gzfile('somefile.gz');
foreach ($lines as $line) {
    echo $line;
}
?>

A se vedea ?i

  • readgzfile() - Output a gz-file
  • gzopen() - Open gz-file

gzeof
gzgetc
Func?ii Zlib


Get character from gz-file pointer

gzfile
gzgets
Func?ii Zlib
PHP Manual

gzgetc

(PHP 4, PHP 5, PHP 7)

gzgetc — Get character from gz-file pointer

Descrierea

string gzgetc ( resource $zp )

Returns a string containing a single (uncompressed) character read from the given gz-file pointer.

Parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Valorile întoarse

The uncompressed character or FALSE on EOF (unlike gzeof()).

Exemple

Example #1 gzgetc() example

<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?>

A se vedea ?i

  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer

gzfile
gzgets
Func?ii Zlib


Get line from file pointer

gzgetc
gzgetss
Func?ii Zlib
PHP Manual

gzgets

(PHP 4, PHP 5, PHP 7)

gzgets — Get line from file pointer

Descrierea

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

Parametri

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.

Valorile întoarse

The uncompressed string, or FALSE on error.

Exemple

Example #1 gzgets() example

<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
   $buffer = gzgets($handle, 4096);
   echo $buffer;
}
gzclose($handle);
?>

A se vedea ?i

  • gzopen() - Open gz-file
  • gzgetc() - Get character from gz-file pointer
  • gzwrite() - Binary-safe gz-file write

gzgetc
gzgetss
Func?ii Zlib


Get line from gz-file pointer and strip HTML tags

gzgets
gzinflate
Func?ii Zlib
PHP Manual

gzgetss

(PHP 4, PHP 5, PHP 7)

gzgetss — Get line from gz-file pointer and strip HTML tags

Descrierea

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.

Parametri

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.

Valorile întoarse

The uncompressed and stripped string, or FALSE on error.

Exemple

Example #1 gzgetss() example

<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
   $buffer = gzgetss($handle, 4096);
   echo $buffer;
}
gzclose($handle);
?>

A se vedea ?i

  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer
  • strip_tags() - Strip HTML and PHP tags from a string

gzgets
gzinflate
Func?ii Zlib


Inflate a deflated string

gzgetss
gzopen
Func?ii Zlib
PHP Manual

gzinflate

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gzinflate — Inflate a deflated string

Descrierea

string gzinflate ( string $data [, int $length = 0 ] )

This function inflates a deflated string.

Parametri

data

The data compressed by gzdeflate().

length

The maximum length of data to decode.

Valorile întoarse

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.

Exemple

Example #1 gzinflate() example

<?php
$compressed   = gzdeflate('Compress me', 9);
$uncompressed = gzinflate($compressed);
echo $uncompressed;
?>

A se vedea ?i

  • gzdeflate() - Deflate a string
  • gzcompress() - Compress a string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

gzgetss
gzopen
Func?ii Zlib


Open gz-file

gzinflate
gzpassthru
Func?ii Zlib
PHP Manual

gzopen

(PHP 4, PHP 5, PHP 7)

gzopen — Open gz-file

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #1 gzopen() Example

<?php
$fp = gzopen("/tmp/file.gz", "r");
?>

A se vedea ?i

  • gzclose() - Close an open gz-file pointer

gzinflate
gzpassthru
Func?ii Zlib


Output all remaining data on a gz-file pointer

gzopen
gzputs
Func?ii Zlib
PHP Manual

gzpassthru

(PHP 4, PHP 5, PHP 7)

gzpassthru — Output all remaining data on a gz-file pointer

Descrierea

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.

Nota:

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.

Sfat

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.

Parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Valorile întoarse

The number of uncompressed characters read from gz and passed through to the input, or FALSE on error.

Exemple

Example #1 gzpassthru() example

<?php
$fp = gzopen('file.gz', 'r');
gzpassthru($fp);
gzclose($fp);
?>

gzopen
gzputs
Func?ii Zlib


Pseudonim pentru gzwrite

gzpassthru
gzread
Func?ii Zlib
PHP Manual

gzputs

(PHP 4, PHP 5, PHP 7)

gzputs — Pseudonim pentru gzwrite()

Descrierea

Aceasta func?ie este pseudonim pentru: gzwrite().

gzpassthru
gzread
Func?ii Zlib


Binary-safe gz-file read

gzputs
gzrewind
Func?ii Zlib
PHP Manual

gzread

(PHP 4, PHP 5, PHP 7)

gzread — Binary-safe gz-file read

Descrierea

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.

Parametri

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.

Valorile întoarse

The data that have been read.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii Zlib


Rewind the position of a gz-file pointer

gzread
gzseek
Func?ii Zlib
PHP Manual

gzrewind

(PHP 4, PHP 5, PHP 7)

gzrewind — Rewind the position of a gz-file pointer

Descrierea

bool gzrewind ( resource $zp )

Sets the file position indicator of the given gz-file pointer to the beginning of the file stream.

Parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • gzseek() - Seek on a gz-file pointer
  • gztell() - Tell gz-file pointer read/write position

gzread
gzseek
Func?ii Zlib


Seek on a gz-file pointer

gzrewind
gztell
Func?ii Zlib
PHP Manual

gzseek

(PHP 4, PHP 5, PHP 7)

gzseek — Seek on a gz-file pointer

Descrierea

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.

Parametri

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.

Valorile întoarse

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

Exemple

Example #1 gzseek() example

<?php
$gz = gzopen('somefile.gz', 'r');
gzseek($gz,2);
echo gzgetc($gz);
gzclose($gz);
?>

A se vedea ?i

  • gztell() - Tell gz-file pointer read/write position
  • gzrewind() - Rewind the position of a gz-file pointer

gzrewind
gztell
Func?ii Zlib


Tell gz-file pointer read/write position

gzseek
gzuncompress
Func?ii Zlib
PHP Manual

gztell

(PHP 4, PHP 5, PHP 7)

gztell — Tell gz-file pointer read/write position

Descrierea

int gztell ( resource $zp )

Gets the position of the given file pointer; i.e., its offset into the uncompressed file stream.

Parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Valorile întoarse

The position of the file pointer or FALSE if an error occurs.

A se vedea ?i

  • gzopen() - Open gz-file
  • gzseek() - Seek on a gz-file pointer
  • gzrewind() - Rewind the position of a gz-file pointer

gzseek
gzuncompress
Func?ii Zlib


Uncompress a compressed string

gztell
gzwrite
Func?ii Zlib
PHP Manual

gzuncompress

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

gzuncompress — Uncompress a compressed string

Descrierea

string gzuncompress ( string $data [, int $length = 0 ] )

This function uncompress a compressed string.

Parametri

data

The data compressed by gzcompress().

length

The maximum length of data to decode.

Valorile întoarse

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.

Exemple

Example #1 gzuncompress() example

<?php
$compressed   = gzcompress('Compress me', 9);
$uncompressed = gzuncompress($compressed);
echo $uncompressed;
?>

A se vedea ?i

  • gzcompress() - Compress a string
  • gzinflate() - Inflate a deflated string
  • gzdeflate() - Deflate a string
  • gzencode() - Create a gzip compressed string

gztell
gzwrite
Func?ii Zlib


Binary-safe gz-file write

gzuncompress
inflate_add
Func?ii Zlib
PHP Manual

gzwrite

(PHP 4, PHP 5, PHP 7)

gzwrite — Binary-safe gz-file write

Descrierea

int gzwrite ( resource $zp , string $string [, int $length ] )

gzwrite() writes the contents of string to the given gz-file.

Parametri

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.

Nota:

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.

Valorile întoarse

Returns the number of (uncompressed) bytes written to the given gz-file stream.

Exemple

Example #1 gzwrite() example

<?php
$string = 'Some information to compress';
$gz = gzopen('somefile.gz','w9');
gzwrite($gz, $string);
gzclose($gz);
?>

A se vedea ?i

  • gzread() - Binary-safe gz-file read
  • gzopen() - Open gz-file

gzuncompress
inflate_add
Func?ii Zlib


Incrementally inflate encoded data

gzwrite
inflate_init
Func?ii Zlib
PHP Manual

inflate_add

(PHP 7)

inflate_add — Incrementally inflate encoded data

Descrierea

string inflate_add ( resource $context , string $encoded_data [, int $flush_mode = ZLIB_SYNC_FLUSH ] )

Incrementally inflates encoded data in the specified context.

Limitation: header information from GZIP compressed data are not made available.

Parametri

context

A context created with inflate_init().

encoded_data

A chunk of compressed data.

flush_mode

One of ZLIB_BLOCK, ZLIB_NO_FLUSH, ZLIB_PARTIAL_FLUSH, ZLIB_SYNC_FLUSH (default), ZLIB_FULL_FLUSH, ZLIB_FINISH. Normally you will want to set ZLIB_NO_FLUSH to maximize compression, and ZLIB_FINISH to terminate with the last chunk of data. See the » zlib manual for a detailed description of these constants.

Valorile întoarse

Returns a chunk of uncompressed data, sau FALSE în cazul e?ecului.

Erori/Excep?ii

If invalid parameters are given, inflating the data requires a preset dictionary, but none is specified, the compressed stream is corrupt or has an invalid checksum, an error of level E_WARNING is generated.

A se vedea ?i

  • inflate_init() - Initialize an incremental inflate context
gzwrite
inflate_init
Func?ii Zlib


Initialize an incremental inflate context

inflate_add
readgzfile
Func?ii Zlib
PHP Manual

inflate_init

(PHP 7)

inflate_init — Initialize an incremental inflate context

Descrierea

resource inflate_init ( int $encoding [, array $options = array() ] )

Initialize an incremental inflate context with the specified encoding.

Parametri

encoding

One of the ZLIB_ENCODING_* constants.

options

An associative array which may contain the following elements:

level

The compression level in range -1..9; defaults to -1.

memory

The compression memory level in range 1..9; defaults to 8.

window

The zlib window size (logarithmic) in range 8..15; defaults to 15.

strategy

One of ZLIB_FILTERED, ZLIB_HUFFMAN_ONLY, ZLIB_RLE, ZLIB_FIXED or ZLIB_DEFAULT_STRATEGY (the default).

dictionary

A string or an array of strings of the preset dictionary (default: no preset dictionary).

Valorile întoarse

Returns an inflate context resource (zlib.inflate) on success, sau FALSE în cazul e?ecului.

Erori/Excep?ii

If an invalid encoding or option is passed to options, or the context couldn't be created, an error of level E_WARNING is generated.

A se vedea ?i

  • inflate_add() - Incrementally inflate encoded data
  • deflate_init() - Initialize an incremental deflate context
inflate_add
readgzfile
Func?ii Zlib


Output a gz-file

inflate_init
zlib_decode
Func?ii Zlib
PHP Manual

readgzfile

(PHP 4, PHP 5, PHP 7)

readgzfile — Output a gz-file

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • gzpassthru() - Output all remaining data on a gz-file pointer
  • gzfile() - Read entire gz-file into an array
  • gzopen() - Open gz-file

inflate_init
zlib_decode
Func?ii Zlib


Uncompress any raw/gzip/zlib encoded data

readgzfile
zlib_encode
Func?ii Zlib
PHP Manual

zlib_decode

(PHP 5 >= 5.4.0, PHP 7)

zlib_decode — Uncompress any raw/gzip/zlib encoded data

Descrierea

string zlib_decode ( string $data [, string $max_decoded_len ] )

Uncompress any raw/gzip/zlib encoded data.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

data

max_decoded_len

Valorile întoarse

Returns the uncompressed data, sau FALSE în cazul e?ecului.

A se vedea ?i

  • zlib_encode() - Compress data with the specified encoding
readgzfile
zlib_encode
Func?ii Zlib


Compress data with the specified encoding

zlib_decode
zlib_get_coding_type
Func?ii Zlib
PHP Manual

zlib_encode

(PHP 5 >= 5.4.0, PHP 7)

zlib_encode — Compress data with the specified encoding

Descrierea

string zlib_encode ( string $data , string $encoding [, string $level = -1 ] )

Compress data with the specified encoding.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

data

The data to compress.

encoding

The compression algorithm. Either ZLIB_ENCODING_RAW, ZLIB_ENCODING_DEFLATE or ZLIB_ENCODING_GZIP.

level

Valorile întoarse

Exemple

Example #1 zlib_encode() example

<?php
$str = 'hello world';
$enc = zlib_encode($str, ZLIB_ENCODING_DEFLATE);
echo bin2hex($enc);
?>

Exemplul de mai sus va afi?a:

789ccb48cdc9c95728cf2fca4901001a0b045d

A se vedea ?i

  • zlib_decode() - Uncompress any raw/gzip/zlib encoded data
zlib_decode
zlib_get_coding_type
Func?ii Zlib


Returns the coding type used for output compression

zlib_encode
Procesarea cardurilor de credit
Func?ii Zlib
PHP Manual

zlib_get_coding_type

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

zlib_get_coding_type — Returns the coding type used for output compression

Descrierea

string zlib_get_coding_type ( void )

Returns the coding type used for output compression.

Valorile întoarse

Possible return values are gzip, deflate, or FALSE.

A se vedea ?i

  • The zlib.output_compression directive

zlib_encode
Procesarea cardurilor de credit
Func?ii Zlib


Procesarea cardurilor de credit

  • MCVE — MCVE (Monetra) Payment
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii MCVE
zlib_get_coding_type
MCVE
Informa?ii de referin?a despre func?ii


MCVE (Monetra) Payment

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii MCVE
    • 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
Procesarea cardurilor de credit
Introducere
Procesarea cardurilor de credit


Introducere

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.

Nota:

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.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.1.0.

Nota: Aceasta extensie nu este disponibila pe platformele Windows.

MCVE
Instalarea / configurarea
MCVE


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
MCVE


Necesita?i

The LibMonetra (formerly libmcve) library.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/mcve.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

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

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

This extension defines a MCVE_CONN resource returned by m_initconn().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

M_PENDING (integer)
M_DONE (integer)
M_ERROR (integer)
M_FAIL (integer)
M_SUCCESS (integer)
Tipurile resurselor
Func?ii MCVE
MCVE


Func?ii MCVE

A se vedea ?i

Documenta?ia suplimentara despre API-ul PHP MCVE/Monetra poate fi gasita la » http://www.mainstreetsoftworks.com/documentation.html. Documenta?ia "Main Street" este completa ?i trebuie sa serveasca ca referin?a primara pentru func?ii.

Cuprins

  • 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
Constante predefinite
m_checkstatus
MCVE


Check to see if a transaction has completed

Func?ii MCVE
m_completeauthorizations
Func?ii MCVE
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

Descrierea

int m_checkstatus ( resource $conn , int $identifier )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

Valorile întoarse

Func?ii MCVE
m_completeauthorizations
Func?ii MCVE


Number of complete authorizations in queue, returning an array of their identifiers

m_checkstatus
m_connect
Func?ii MCVE
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

Descrierea

int m_completeauthorizations ( resource $conn , int &$array )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

array

Its description

Valorile întoarse

What the function returns, first on success, then on failure. See also the &return.success; entity

m_checkstatus
m_connect
Func?ii MCVE


Establish the connection to MCVE

m_completeauthorizations
m_connectionerror
Func?ii MCVE
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

Descrierea

int m_connect ( resource $conn )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

Valorile întoarse

m_completeauthorizations
m_connectionerror
Func?ii MCVE


Get a textual representation of why a connection failed

m_connect
m_deletetrans
Func?ii MCVE
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

Descrierea

string m_connectionerror ( resource $conn )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

Valorile întoarse

m_connect
m_deletetrans
Func?ii MCVE


Delete specified transaction from MCVE_CONN structure

m_connectionerror
m_destroyconn
Func?ii MCVE
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

Descrierea

bool m_deletetrans ( resource $conn , int $identifier )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

Valorile întoarse

m_connectionerror
m_destroyconn
Func?ii MCVE


Destroy the connection and MCVE_CONN structure

m_deletetrans
m_destroyengine
Func?ii MCVE
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

Descrierea

bool m_destroyconn ( resource $conn )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

Valorile întoarse

Returns TRUE.

A se vedea ?i

  • m_initconn() - Create and initialize an MCVE_CONN structure

m_deletetrans
m_destroyengine
Func?ii MCVE


Free memory associated with IP/SSL connectivity

m_destroyconn
m_getcell
Func?ii MCVE
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

Descrierea

void m_destroyengine ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Valorile întoarse

Nu este întoarsa nici o valoare.

m_destroyconn
m_getcell
Func?ii MCVE


Get a specific cell from a comma delimited response by column name

m_destroyengine
m_getcellbynum
Func?ii MCVE
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

Descrierea

string m_getcell ( resource $conn , int $identifier , string $column , int $row )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

column

row

Valorile întoarse

m_destroyengine
m_getcellbynum
Func?ii MCVE


Get a specific cell from a comma delimited response by column number

m_getcell
m_getcommadelimited
Func?ii MCVE
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

Descrierea

string m_getcellbynum ( resource $conn , int $identifier , int $column , int $row )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

column

row

Valorile întoarse

m_getcell
m_getcommadelimited
Func?ii MCVE


Get the RAW comma delimited data returned from MCVE

m_getcellbynum
m_getheader
Func?ii MCVE
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

Descrierea

string m_getcommadelimited ( resource $conn , int $identifier )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

Valorile întoarse

m_getcellbynum
m_getheader
Func?ii MCVE


Get the name of the column in a comma-delimited response

m_getcommadelimited
m_initconn
Func?ii MCVE
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

Descrierea

string m_getheader ( resource $conn , int $identifier , int $column_num )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

column_num

Valorile întoarse

m_getcommadelimited
m_initconn
Func?ii MCVE


Create and initialize an MCVE_CONN structure

m_getheader
m_initengine
Func?ii MCVE
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

Descrierea

resource m_initconn ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Returns an MCVE_CONN resource.

A se vedea ?i

  • m_destroyconn() - Destroy the connection and MCVE_CONN structure

m_getheader
m_initengine
Func?ii MCVE


Ready the client for IP/SSL Communication

m_initconn
m_iscommadelimited
Func?ii MCVE
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

Descrierea

int m_initengine ( string $location )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

location

Valorile întoarse

m_initconn
m_iscommadelimited
Func?ii MCVE


Checks to see if response is comma delimited

m_initengine
m_maxconntimeout
Func?ii MCVE
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

Descrierea

int m_iscommadelimited ( resource $conn , int $identifier )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

Valorile întoarse

m_initengine
m_maxconntimeout
Func?ii MCVE


The maximum amount of time the API will attempt a connection to MCVE

m_iscommadelimited
m_monitor
Func?ii MCVE
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

Descrierea

bool m_maxconntimeout ( resource $conn , int $secs )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

secs

Valorile întoarse

m_iscommadelimited
m_monitor
Func?ii MCVE


Perform communication with MCVE (send/receive data) Non-blocking

m_maxconntimeout
m_numcolumns
Func?ii MCVE
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

Descrierea

int m_monitor ( resource $conn )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

Valorile întoarse

m_maxconntimeout
m_numcolumns
Func?ii MCVE


Number of columns returned in a comma delimited response

m_monitor
m_numrows
Func?ii MCVE
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

Descrierea

int m_numcolumns ( resource $conn , int $identifier )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

Valorile întoarse

m_monitor
m_numrows
Func?ii MCVE


Number of rows returned in a comma delimited response

m_numcolumns
m_parsecommadelimited
Func?ii MCVE
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

Descrierea

int m_numrows ( resource $conn , int $identifier )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

Valorile întoarse

m_numcolumns
m_parsecommadelimited
Func?ii MCVE


Parse the comma delimited response so m_getcell, etc will work

m_numrows
m_responsekeys
Func?ii MCVE
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

Descrierea

int m_parsecommadelimited ( resource $conn , int $identifier )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

Valorile întoarse

m_numrows
m_responsekeys
Func?ii MCVE


Returns array of strings which represents the keys that can be used for response parameters on this transaction

m_parsecommadelimited
m_responseparam
Func?ii MCVE
PHP Manual

m_responsekeys

(PHP 5 >= 5.0.5, PHP 7, 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

Descrierea

array m_responsekeys ( resource $conn , int $identifier )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

Valorile întoarse

m_parsecommadelimited
m_responseparam
Func?ii MCVE


Get a custom response parameter

m_responsekeys
m_returnstatus
Func?ii MCVE
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

Descrierea

string m_responseparam ( resource $conn , int $identifier , string $key )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

key

Valorile întoarse

m_responsekeys
m_returnstatus
Func?ii MCVE


Check to see if the transaction was successful

m_responseparam
m_setblocking
Func?ii MCVE
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

Descrierea

int m_returnstatus ( resource $conn , int $identifier )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

Valorile întoarse

m_responseparam
m_setblocking
Func?ii MCVE


Set blocking/non-blocking mode for connection

m_returnstatus
m_setdropfile
Func?ii MCVE
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

Descrierea

int m_setblocking ( resource $conn , int $tf )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

tf

Valorile întoarse

m_returnstatus
m_setdropfile
Func?ii MCVE


Set the connection method to Drop-File

m_setblocking
m_setip
Func?ii MCVE
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

Descrierea

int m_setdropfile ( resource $conn , string $directory )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

directory

Valorile întoarse

m_setblocking
m_setip
Func?ii MCVE


Set the connection method to IP

m_setdropfile
m_setssl_cafile
Func?ii MCVE
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

Descrierea

int m_setip ( resource $conn , string $host , int $port )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

host

port

Valorile întoarse

m_setdropfile
m_setssl_cafile
Func?ii MCVE


Set SSL CA (Certificate Authority) file for verification of server certificate

m_setip
m_setssl_files
Func?ii MCVE
PHP Manual

m_setssl_cafile

(PHP 5 >= 5.0.5, PHP 7, PECL mcve >= 1.0.0)

m_setssl_cafile — Set SSL CA (Certificate Authority) file for verification of server certificate

Descrierea

int m_setssl_cafile ( resource $conn , string $cafile )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

cafile

Valorile întoarse

m_setip
m_setssl_files
Func?ii MCVE


Set certificate key files and certificates if server requires client certificate verification

m_setssl_cafile
m_setssl
Func?ii MCVE
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

Descrierea

int m_setssl_files ( resource $conn , string $sslkeyfile , string $sslcertfile )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

sslkeyfile

sslcertfile

Valorile întoarse

m_setssl_cafile
m_setssl
Func?ii MCVE


Set the connection method to SSL

m_setssl_files
m_settimeout
Func?ii MCVE
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

Descrierea

int m_setssl ( resource $conn , string $host , int $port )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

host

port

Valorile întoarse

m_setssl_files
m_settimeout
Func?ii MCVE


Set maximum transaction time (per trans)

m_setssl
m_sslcert_gen_hash
Func?ii MCVE
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)

Descrierea

int m_settimeout ( resource $conn , int $seconds )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

seconds

Valorile întoarse

m_setssl
m_sslcert_gen_hash
Func?ii MCVE


Generate hash for SSL client certificate verification

m_settimeout
m_transactionssent
Func?ii MCVE
PHP Manual

m_sslcert_gen_hash

(PECL mcve >= 5.2.0)

m_sslcert_gen_hash — Generate hash for SSL client certificate verification

Descrierea

string m_sslcert_gen_hash ( string $filename )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

filename

Valorile întoarse

m_settimeout
m_transactionssent
Func?ii MCVE


Check to see if outgoing buffer is clear

m_sslcert_gen_hash
m_transinqueue
Func?ii MCVE
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

Descrierea

int m_transactionssent ( resource $conn )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

Valorile întoarse

m_sslcert_gen_hash
m_transinqueue
Func?ii MCVE


Number of transactions in client-queue

m_transactionssent
m_transkeyval
Func?ii MCVE
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

Descrierea

int m_transinqueue ( resource $conn )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

Valorile întoarse

m_transactionssent
m_transkeyval
Func?ii MCVE


Add key/value pair to a transaction. Replaces deprecated transparam()

m_transinqueue
m_transnew
Func?ii MCVE
PHP Manual

m_transkeyval

(PHP 5 >= 5.0.5, PHP 7, PECL mcve >= 1.0.0)

m_transkeyval — Add key/value pair to a transaction. Replaces deprecated transparam()

Descrierea

int m_transkeyval ( resource $conn , int $identifier , string $key , string $value )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

key

value

Valorile întoarse

m_transinqueue
m_transnew
Func?ii MCVE


Start a new transaction

m_transkeyval
m_transsend
Func?ii MCVE
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

Descrierea

int m_transnew ( resource $conn )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

Valorile întoarse

m_transkeyval
m_transsend
Func?ii MCVE


Finalize and send the transaction

m_transnew
m_uwait
Func?ii MCVE
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

Descrierea

int m_transsend ( resource $conn , int $identifier )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

identifier

Valorile întoarse

m_transnew
m_uwait
Func?ii MCVE


Wait x microsecs

m_transsend
m_validateidentifier
Func?ii MCVE
PHP Manual

m_uwait

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_uwait — Wait x microsecs

Descrierea

int m_uwait ( int $microsecs )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

microsecs

Valorile întoarse

m_transsend
m_validateidentifier
Func?ii MCVE


Whether or not to validate the passed identifier on any transaction it is passed to

m_uwait
m_verifyconnection
Func?ii MCVE
PHP Manual

m_validateidentifier

(PHP 5 >= 5.0.5, PHP 7, PECL mcve >= 1.0.0)

m_validateidentifier — Whether or not to validate the passed identifier on any transaction it is passed to

Descrierea

int m_validateidentifier ( resource $conn , int $tf )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

tf

Valorile întoarse

m_uwait
m_verifyconnection
Func?ii MCVE


Set whether or not to PING upon connect to verify connection

m_validateidentifier
m_verifysslcert
Func?ii MCVE
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

Descrierea

bool m_verifyconnection ( resource $conn , int $tf )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

tf

Valorile întoarse

m_validateidentifier
m_verifysslcert
Func?ii MCVE


Set whether or not to verify the server ssl certificate

m_verifyconnection
Extensii criptografice
Func?ii MCVE
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

Descrierea

bool m_verifysslcert ( resource $conn , int $tf )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

conn

O resursa MCVE_CONN întoarsa de m_initengine().

tf

Valorile întoarse

m_verifyconnection
Extensii criptografice
Func?ii MCVE


Extensii criptografice

  • Crack — Cracklib
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Crack
  • CSPRNG
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii CSPRNG
  • Hash — HASH Message Digest Framework
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Hash
  • Mcrypt
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Mcrypt ciphers
    • Exemple
    • Func?ii Mcrypt
  • Mhash
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Mhash
  • OpenSSL
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Key/Certificate parameters
    • Certificate Verification
    • Func?ii OpenSSL
  • Password Hashing
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii de hash a parolelor
m_verifysslcert
Crack
Informa?ii de referin?a despre func?ii


Cracklib

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii Crack
    • crack_check — Performs an obscure check with the given password
    • crack_closedict — Closes an open CrackLib dictionary
    • crack_getlastmessage — Returns the message from the last obscure check
    • crack_opendict — Opens a new CrackLib dictionary
Extensii criptografice
Introducere
Extensii criptografice


Introducere

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.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.0.0.

Crack
Instalarea / configurarea
Crack


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Crack


Necesita?i

More information regarding CrackLib along with the library can be found at » http://sourceforge.net/projects/cracklib.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP. Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/crack.

In order to use these functions you must compile PHP with Crack support by using the --with-crack[=DIR] configuration option.

Windows users will enable php_crack.dll inside of php.ini in order to use these functions. O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

The CrackLib extension defines a dictionary resource identifier returned by crack_opendict().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
Crack


Exemple

This example shows how to open a CrackLib dictionary, test a given password, retrieve any diagnostic messages, and close the dictionary.

Example #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);
?>

Nota:

If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.

Constante predefinite
Func?ii Crack
Crack


Func?ii Crack

Cuprins

  • crack_check — Performs an obscure check with the given password
  • crack_closedict — Closes an open CrackLib dictionary
  • crack_getlastmessage — Returns the message from the last obscure check
  • crack_opendict — Opens a new CrackLib dictionary
Exemple
crack_check
Crack


Performs an obscure check with the given password

Func?ii Crack
crack_closedict
Func?ii Crack
PHP Manual

crack_check

(PECL crack >= 0.1)

crack_check — Performs an obscure check with the given password

Descrierea

bool crack_check ( resource $dictionary , string $password )
bool crack_check ( string $password , string $username = "" , string $gecos = "" , resource $dictionary = NULL )

Performs an obscure check with the given password on the specified dictionary. The alternative signature also takes into account the username and the GECOS information.

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

dictionary

The crack lib dictionary. If not specified, the last opened dictionary is used.

password

The password to be checked.

username

The username of the account with the password.

gecos

The GECOS information associated with the user account.

Valorile întoarse

Returns TRUE if password is strong, or FALSE otherwise.

Istoricul schimbarilor

Versiune | Descriere
0.3 | The username, gecos and dictionary parameters were added to the alternative signature.

Func?ii Crack
crack_closedict
Func?ii Crack


Closes an open CrackLib dictionary

crack_check
crack_getlastmessage
Func?ii Crack
PHP Manual

crack_closedict

(PECL crack >= 0.1)

crack_closedict — Closes an open CrackLib dictionary

Descrierea

bool crack_closedict ([ resource $dictionary ] )

crack_closedict() closes the specified dictionary identifier.

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

dictionary

The dictionary to close. If not specified, the current dictionary is closed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • crack_opendict() - Opens a new CrackLib dictionary

crack_check
crack_getlastmessage
Func?ii Crack


Returns the message from the last obscure check

crack_closedict
crack_opendict
Func?ii Crack
PHP Manual

crack_getlastmessage

(PECL crack >= 0.1)

crack_getlastmessage — Returns the message from the last obscure check

Descrierea

string crack_getlastmessage ( void )

crack_getlastmessage() returns the message from the last obscure check.

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Valorile întoarse

The message from the last obscure check or FALSE if there was no obscure checks made so far.

The returned message is one of:

  • it's WAY too short
  • it is too short
  • it does not contain enough DIFFERENT characters
  • it is all whitespace
  • it is too simplistic/systematic
  • it looks like a National Insurance number.
  • it is based on a dictionary word
  • it is based on a (reversed) dictionary word
  • strong password

A se vedea ?i

  • crack_check() - Performs an obscure check with the given password

crack_closedict
crack_opendict
Func?ii Crack


Opens a new CrackLib dictionary

crack_getlastmessage
CSPRNG
Func?ii Crack
PHP Manual

crack_opendict

(PECL crack >= 0.1)

crack_opendict — Opens a new CrackLib dictionary

Descrierea

resource crack_opendict ( string $dictionary )

crack_opendict() opens the specified CrackLib dictionary for use with crack_check().

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Nota:

Only one dictionary may be open at a time.

Parametri

dictionary

The path to the Cracklib dictionary.

Valorile întoarse

Returns a dictionary resource identifier on success sau FALSE în cazul e?ecului.

A se vedea ?i

  • crack_check() - Performs an obscure check with the given password
  • crack_closedict() - Closes an open CrackLib dictionary

crack_getlastmessage
CSPRNG
Func?ii Crack


CSPRNG

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii CSPRNG
    • random_bytes — Generates cryptographically secure pseudo-random bytes
    • random_int — Generates cryptographically secure pseudo-random integers
crack_opendict
Introducere
Extensii criptografice


Introducere

API-ul » cryptographically secure pseudo-random number generator (CSPRNG) -- Generatorul de numere pseudo-aleatorii securizat din punct de vedere criptografic -- ofera o modalitate u?oara ?i sigura de a genera numere întregi ?i octe?i aleatorii, siguri din punct de vedere criptografic, pentru a fi utiliza?i în contexte criptografice.

Aceasta exista începând cu PHP 7.0.0 dar de asemenea exista ?i o » implementare în spa?iul utilizatorului pentru PHP >= 5.2.0.

CSPRNG
Instalarea / configurarea
CSPRNG


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
CSPRNG


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii CSPRNG
CSPRNG


Func?ii CSPRNG

Cuprins

  • random_bytes — Generates cryptographically secure pseudo-random bytes
  • random_int — Generates cryptographically secure pseudo-random integers
Constante predefinite
random_bytes
CSPRNG


Generates cryptographically secure pseudo-random bytes

Func?ii CSPRNG
random_int
Func?ii CSPRNG
PHP Manual

random_bytes

(PHP 7)

random_bytes — Generates cryptographically secure pseudo-random bytes

Descrierea

string random_bytes ( int $length )

Generates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.

Sursele de valori aleatorii utilizate pentru aceasta func?ie sunt urmatoarele:

  • Pe Windows se va utiliza întotdeauna » CryptGenRandom().
  • Pe Linux se va utiliza apelul de sistem (syscall) » getrandom(2) daca este disponibil.
  • Pe alte platforme se va utiliza /dev/urandom.
  • Daca nici una din sursele men?ionate nu sunt disponibile, va fi emisa o excep?ie Exception.

Nota: Cu toate ca aceasta func?ie a fost adaugata în PHP 7.0, o » implementare în spa?iul utilizatorului este disponibila pentru PHP de la versiunea 5.2 pâna la 5.6 inclusiv.

Parametri

length

The length of the random string that should be returned in bytes.

Valorile întoarse

Returns a string containing the requested number of cryptographically secure random bytes.

Erori/Excep?ii

  • Daca nu poate fi gasita o sursa potrivita de valori aleatorii, va fi emisa o excep?ie Exception.
  • Daca sunt furniza?i parametri incorec?i, va fi emisa o excep?ie TypeError.
  • If an invalid length of bytes is given, an Error will be thrown.

Exemple

Example #1 random_bytes() example

<?php
$bytes = random_bytes(5);
var_dump(bin2hex($bytes));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(10) "385e33f741"

A se vedea ?i

  • random_int() - Generates cryptographically secure pseudo-random integers
  • openssl_random_pseudo_bytes() - Generate a pseudo-random string of bytes
  • bin2hex() - Convert binary data into hexadecimal representation
Func?ii CSPRNG
random_int
Func?ii CSPRNG


Generates cryptographically secure pseudo-random integers

random_bytes
Hash
Func?ii CSPRNG
PHP Manual

random_int

(PHP 7)

random_int — Generates cryptographically secure pseudo-random integers

Descrierea

int random_int ( int $min , int $max )

Generates cryptographic random integers that are suitable for use where unbiased results are critical, such as when shuffling a deck of cards for a poker game.

Sursele de valori aleatorii utilizate pentru aceasta func?ie sunt urmatoarele:

  • Pe Windows se va utiliza întotdeauna » CryptGenRandom().
  • Pe Linux se va utiliza apelul de sistem (syscall) » getrandom(2) daca este disponibil.
  • Pe alte platforme se va utiliza /dev/urandom.
  • Daca nici una din sursele men?ionate nu sunt disponibile, va fi emisa o excep?ie Exception.

Nota: Cu toate ca aceasta func?ie a fost adaugata în PHP 7.0, o » implementare în spa?iul utilizatorului este disponibila pentru PHP de la versiunea 5.2 pâna la 5.6 inclusiv.

Parametri

min

The lowest value to be returned, which must be PHP_INT_MIN or higher.

max

The highest value to be returned, which must be less than or equal to PHP_INT_MAX.

Valorile întoarse

Returns a cryptographically secure random integer in the range min to max, inclusive.

Erori/Excep?ii

  • Daca nu poate fi gasita o sursa potrivita de valori aleatorii, va fi emisa o excep?ie Exception.
  • Daca sunt furniza?i parametri incorec?i, va fi emisa o excep?ie TypeError.
  • If max is less than min, an Error will be thrown.

Exemple

Example #1 random_int() example

<?php
var_dump(random_int(100, 999));
var_dump(random_int(-1000, 0));
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(248)
int(-898)

A se vedea ?i

  • random_bytes() - Generates cryptographically secure pseudo-random bytes
random_bytes
Hash
Func?ii CSPRNG


HASH Message Digest Framework

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Hash
    • hash_algos — Return a list of registered hashing algorithms
    • hash_copy — Copy hashing context
    • hash_equals — Timing attack safe string comparison
    • 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_pbkdf2 — Generate a PBKDF2 key derivation of a supplied password
    • 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)
random_int
Introducere
Extensii criptografice


Introducere

Message Digest (hash) engine. Allows direct or incremental processing of arbitrary length messages using a variety of hashing algorithms.

Hash
Instalarea / configurarea
Hash


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Hash


Necesita?i

Nu este necesar de a instala ceva suplimentar pentru a utiliza aceste func?ii; ele fac parte din nucleul PHP.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

As of PHP 5.1.2, the Hash extension is bundled and compiled into PHP by default.

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

This extension defines a Hashing Context resource returned by hash_init().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

HASH_HMAC (integer)
Optional flag for hash_init(). Indicates that the HMAC digest-keying algorithm should be applied to the current hashing context.
Tipurile resurselor
Func?ii Hash
Hash


Func?ii Hash

Cuprins

  • hash_algos — Return a list of registered hashing algorithms
  • hash_copy — Copy hashing context
  • hash_equals — Timing attack safe string comparison
  • 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_pbkdf2 — Generate a PBKDF2 key derivation of a supplied password
  • 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)
Constante predefinite
hash_algos
Hash


Return a list of registered hashing algorithms

Func?ii Hash
hash_copy
Func?ii Hash
PHP Manual

hash_algos

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_algos — Return a list of registered hashing algorithms

Descrierea

array hash_algos ( void )

Valorile întoarse

Returns a numerically indexed array containing the list of supported hashing algorithms.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Support for gost-crypto was added. This implements the GOST hash function using the CryptoPro S-box tables as specified by » RFC 4357, section 11.2.
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

Exemple

Example #1 hash_algos() example

As of PHP 5.6.0, hash_algos() will return the following list of algorithm names.

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

Exemplul de mai sus va afi?a ceva similar cu:

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] => gost-crypto
    [23] => adler32
    [24] => crc32
    [25] => crc32b
    [26] => fnv132
    [27] => fnv1a32
    [28] => fnv164
    [29] => fnv1a64
    [30] => joaat
    [31] => haval128,3
    [32] => haval160,3
    [33] => haval192,3
    [34] => haval224,3
    [35] => haval256,3
    [36] => haval128,4
    [37] => haval160,4
    [38] => haval192,4
    [39] => haval224,4
    [40] => haval256,4
    [41] => haval128,5
    [42] => haval160,5
    [43] => haval192,5
    [44] => haval224,5
    [45] => haval256,5
)

Func?ii Hash
hash_copy
Func?ii Hash


Copy hashing context

hash_algos
hash_equals
Func?ii Hash
PHP Manual

hash_copy

(PHP 5 >= 5.3.0, PHP 7)

hash_copy — Copy hashing context

Descrierea

resource hash_copy ( resource $context )

Parametri

context

Hashing context returned by hash_init().

Valorile întoarse

Returns a copy of Hashing Context resource.

Exemple

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

Exemplul de mai sus va afi?a:

8d777f385d3dfec8815d20f7496026dc
511ae0b1c13f95e5f08f1a0dd3da3d93

hash_algos
hash_equals
Func?ii Hash


Timing attack safe string comparison

hash_copy
hash_file
Func?ii Hash
PHP Manual

hash_equals

(PHP 5 >= 5.6.0, PHP 7)

hash_equals — Timing attack safe string comparison

Descrierea

bool hash_equals ( string $known_string , string $user_string )

Compares two strings using the same time whether they're equal or not.

This function should be used to mitigate timing attacks; for instance, when testing crypt() password hashes.

Parametri

known_string

The string of known length to compare against

user_string

The user-supplied string

Valorile întoarse

Returns TRUE when the two strings are equal, FALSE otherwise.

Erori/Excep?ii

Emits an E_WARNING message when either of the supplied parameters is not a string.

Exemple

Example #1 example

<?php
$expected  = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correct   = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrect = crypt('apple',  '$2a$07$usesomesillystringforsalt$');

var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)

Note

Nota:

Both arguments must be of the same length to be compared successfully. When arguments of differing length are supplied, FALSE is returned immediately and the length of the known string may be leaked in case of a timing attack.

Nota:

It is important to provide the user-supplied string as the second parameter, rather than the first.

hash_copy
hash_file
Func?ii Hash


Generate a hash value using the contents of a given file

hash_equals
hash_final
Func?ii Hash
PHP Manual

hash_file

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_file — Generate a hash value using the contents of a given file

Descrierea

string hash_file ( string $algo , string $filename [, bool $raw_output = false ] )

Parametri

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.

Valorile întoarse

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.

Exemple

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

Exemplul de mai sus va afi?a:

5c6ffbdd40d9556b73a21e63c3e0e904

A se vedea ?i

  • 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_equals
hash_final
Func?ii Hash


Finalize an incremental hash and return resulting digest

hash_file
hash_hmac_file
Func?ii Hash
PHP Manual

hash_final

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_final — Finalize an incremental hash and return resulting digest

Descrierea

string hash_final ( resource $context [, bool $raw_output = false ] )

Parametri

context

Hashing context returned by hash_init().

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Valorile întoarse

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.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

c0854fb9fb03c41cce3802cb0d220529e6eef94e

A se vedea ?i

  • 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
Func?ii Hash


Generate a keyed hash value using the HMAC method and the contents of a given file

hash_final
hash_hmac
Func?ii Hash
PHP Manual

hash_hmac_file

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_hmac_file — Generate a keyed hash value using the HMAC method and the contents of a given file

Descrierea

string hash_hmac_file ( string $algo , string $filename , string $key [, bool $raw_output = false ] )

Parametri

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.

Valorile întoarse

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.

Exemple

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

Exemplul de mai sus va afi?a:

7eb2b5c37443418fc77c136dd20e859c

A se vedea ?i

  • 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
Func?ii Hash


Generate a keyed hash value using the HMAC method

hash_hmac_file
hash_init
Func?ii Hash
PHP Manual

hash_hmac

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_hmac — Generate a keyed hash value using the HMAC method

Descrierea

string hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = false ] )

Parametri

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.

Valorile întoarse

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. Returns FALSE when algo is unknown.

Exemple

Example #1 hash_hmac() example

<?php
echo hash_hmac('ripemd160', 'The quick brown fox jumped over the lazy dog.', 'secret');
?>

Exemplul de mai sus va afi?a:

b8e7ae12510bdfb1812e463a7f086122cf37e4f7

A se vedea ?i

  • 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
Func?ii Hash


Initialize an incremental hashing context

hash_hmac
hash_pbkdf2
Func?ii Hash
PHP Manual

hash_init

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_init — Initialize an incremental hashing context

Descrierea

resource hash_init ( string $algo [, int $options = 0 [, string $key = NULL ]] )

Parametri

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..). For a list of supported algorithms see hash_algos().

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.

Valorile întoarse

Returns a Hashing Context resource for use with hash_update(), hash_update_stream(), hash_update_file(), and hash_final().

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

5c6ffbdd40d9556b73a21e63c3e0e904

A se vedea ?i

  • hash() - Generate a hash value (message digest)
  • hash_algos() - Return a list of registered hashing algorithms
  • 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_pbkdf2
Func?ii Hash


Generate a PBKDF2 key derivation of a supplied password

hash_init
hash_update_file
Func?ii Hash
PHP Manual

hash_pbkdf2

(PHP 5 >= 5.5.0, PHP 7)

hash_pbkdf2 — Generate a PBKDF2 key derivation of a supplied password

Descrierea

string hash_pbkdf2 ( string $algo , string $password , string $salt , int $iterations [, int $length = 0 [, bool $raw_output = false ]] )

Parametri

algo

Name of selected hashing algorithm (i.e. md5, sha256, haval160,4, etc..) See hash_algos() for a list of supported algorithms.

password

The password to use for the derivation.

salt

The salt to use for the derivation. This value should be generated randomly.

iterations

The number of internal iterations to perform for the derivation.

length

The length of the output string. If raw_output is TRUE this corresponds to the byte-length of the derived key, if raw_output is FALSE this corresponds to twice the byte-length of the derived key (as every byte of the key is returned as two hexits).

If 0 is passed, the entire output of the supplied algorithm is used.

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Valorile întoarse

Returns a string containing the derived key as lowercase hexits unless raw_output is set to TRUE in which case the raw binary representation of the derived key is returned.

Erori/Excep?ii

An E_WARNING will be raised if the algorithm is unknown, the iterations parameter is less than or equal to 0, the length is less than 0 or the salt is too long (greater than INT_MAX - 4).

Exemple

Example #1 hash_pbkdf2() example, basic usage

<?php
$password = "password";
$iterations = 1000;

// Generate a random IV using mcrypt_create_iv(),
// openssl_random_pseudo_bytes() or another suitable source of randomness
$salt = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);

$hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 20);
echo $hash;
?>

Exemplul de mai sus va afi?a ceva similar cu:

120fb6cffcf8b32c43e7

Note

Precautie

The PBKDF2 method can be used for hashing passwords for storage. However, it should be noted that password_hash() or crypt() with CRYPT_BLOWFISH are better suited for password storage.

A se vedea ?i

  • crypt() - One-way string hashing
  • password_hash() - Creates a password hash
  • 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() - 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
hash_update_file
Func?ii Hash


Pump data into an active hashing context from a file

hash_pbkdf2
hash_update_stream
Func?ii Hash
PHP Manual

hash_update_file

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_update_file — Pump data into an active hashing context from a file

Descrierea

bool hash_update_file ( resource $hcontext , string $filename [, resource $scontext = NULL ] )

Parametri

hcontext

Hashing context returned by hash_init().

filename

URL describing location of file to be hashed; Supports fopen wrappers.

scontext

Stream context as returned by stream_context_create().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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_pbkdf2
hash_update_stream
Func?ii Hash


Pump data into an active hashing context from an open stream

hash_update_file
hash_update
Func?ii Hash
PHP Manual

hash_update_stream

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_update_stream — Pump data into an active hashing context from an open stream

Descrierea

int hash_update_stream ( resource $context , resource $handle [, int $length = -1 ] )

Parametri

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.

Valorile întoarse

Actual number of bytes added to the hashing context from handle.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

5c6ffbdd40d9556b73a21e63c3e0e904

A se vedea ?i

  • 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
Func?ii Hash


Pump data into an active hashing context

hash_update_stream
hash
Func?ii Hash
PHP Manual

hash_update

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_update — Pump data into an active hashing context

Descrierea

bool hash_update ( resource $context , string $data )

Parametri

context

Hashing context returned by hash_init().

data

Message to be included in the hash digest.

Valorile întoarse

Returns TRUE.

A se vedea ?i

  • 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
Func?ii Hash


Generate a hash value (message digest)

hash_update
Mcrypt
Func?ii Hash
PHP Manual

hash

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash — Generate a hash value (message digest)

Descrierea

string hash ( string $algo , string $data [, bool $raw_output = false ] )

Parametri

algo

Name of selected hashing algorithm (e.g. "md5", "sha256", "haval160,4", etc..)

data

Message to be hashed.

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | The tiger algorithm now uses big-endian byte ordering. See also example below.

Exemple

Example #1 A hash() example

<?php
echo hash('ripemd160', 'The quick brown fox jumped over the lazy dog.');
?>

Exemplul de mai sus va afi?a:

ec457d0a974c48d5685a7efa03d137dc8bbde7e3

Example #2 Calculate pre PHP-5.4 tiger hashes with PHP-5.4 and higher

<?php
function old_tiger($data = "", $width=192, $rounds = 3) {
    return substr(
        implode(
            array_map(
                function ($h) {
                    return str_pad(bin2hex(strrev($h)), 16, "0");
                },
                str_split(hash("tiger192,$rounds", $data, true), 8)
            )
        ),
        0, 48-(192-$width)/4
    );
}
echo hash('tiger192,3', 'a-string'), PHP_EOL;
echo old_tiger('a-string'), PHP_EOL;
?>

Exemplul de mai sus va afi?a în PHP 5.3:

146a7492719b3564094efe7abbd40a7416fd900179d02773
64359b7192746a14740ad4bb7afe4e097327d0790190fd16

Exemplul de mai sus va afi?a în PHP 5.4:

64359b7192746a14740ad4bb7afe4e097327d0790190fd16
146a7492719b3564094efe7abbd40a7416fd900179d02773

A se vedea ?i

  • 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
Func?ii Hash


Mcrypt

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Mcrypt ciphers
  • Exemple
  • Func?ii Mcrypt
    • 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
Introducere
Extensii criptografice


Introducere

Avertizare

This extension has been deprecated as of PHP 7.1.0 and moved to PECL as of PHP 7.2.0.

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
Instalarea / configurarea
Mcrypt


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Mcrypt


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Trebuie sa compila?i PHP cu parametrul --with-mcrypt[=DIR] pentru a activa aceasta extensie. DIR este directorul de instalare al mcrypt. Asigura?i-va ca compila?i libmcrypt cu op?iunea --disable-posix-threads .

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Mcrypt configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
mcrypt.algorithms_dir | NULL | PHP_INI_ALL |
mcrypt.modes_dir | NULL | PHP_INI_ALL |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

mcrypt_module_open() returns an encryption descriptor.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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

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

Constante predefinite
Exemple
Mcrypt


Exemple

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.

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.

Example #1 Encrypt an input value with AES with a 256-bit key under 2.4.x and higher in CBC mode

<?php
    $key = hash('sha256', 'this is a secret key', true);
    $input = "Let us meet at 9 o'clock at the secret place.";

    $td = mcrypt_module_open('rijndael-128', '', 'cbc', '');
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_URANDOM);
    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
Func?ii Mcrypt
Mcrypt


Func?ii Mcrypt

Cuprins

  • 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
Exemple
mcrypt_cbc
Mcrypt


Encrypts/decrypts data in CBC mode

Func?ii Mcrypt
mcrypt_cfb
Func?ii Mcrypt
PHP Manual

mcrypt_cbc

(PHP 4, PHP 5)

mcrypt_cbc — Encrypts/decrypts data in CBC mode

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.5.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • mcrypt_decrypt()
  • mcrypt_encrypt()

Descrierea

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.

Func?ii Mcrypt
mcrypt_cfb
Func?ii Mcrypt


Encrypts/decrypts data in CFB mode

mcrypt_cbc
mcrypt_create_iv
Func?ii Mcrypt
PHP Manual

mcrypt_cfb

(PHP 4, PHP 5)

mcrypt_cfb — Encrypts/decrypts data in CFB mode

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.5.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • mcrypt_decrypt()
  • mcrypt_encrypt()

Descrierea

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.

mcrypt_cbc
mcrypt_create_iv
Func?ii Mcrypt


Creates an initialization vector (IV) from a random source

mcrypt_cfb
mcrypt_decrypt
Func?ii Mcrypt
PHP Manual

mcrypt_create_iv

(PHP 4, PHP 5, PHP 7)

mcrypt_create_iv — Creates an initialization vector (IV) from a random source

Avertizare

This function was DEPRECATED in PHP 7.1.0.

Alternatives to this function include:

  • random_bytes()

Descrierea

string mcrypt_create_iv ( int $size [, int $source = MCRYPT_DEV_URANDOM ] )

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.

Parametri

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.

Note that the default value of this parameter was MCRYPT_DEV_RANDOM prior to PHP 5.6.0.

Nota: Note that MCRYPT_DEV_RANDOM may block until more entropy is available.

Valorile întoarse

Returns the initialization vector, or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | MCRYPT_DEV_URANDOM is now the default value of source.
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.

Exemple

Example #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);
?>

A se vedea ?i

  • » 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)
  • random_bytes() - Generates cryptographically secure pseudo-random bytes

mcrypt_cfb
mcrypt_decrypt
Func?ii Mcrypt


Decrypts crypttext with given parameters

mcrypt_create_iv
mcrypt_ecb
Func?ii Mcrypt
PHP Manual

mcrypt_decrypt

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_decrypt — Decrypts crypttext with given parameters

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

string mcrypt_decrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] )

Decrypts the data and returns the unencrypted data.

Parametri

cipher

Una din constantele MCRYPT_ciphername sau denumirea algoritmului ca ?ir de caractere.

key

The key with which the data was encrypted. If the provided key size is not supported by the cipher, the function will emit a warning and return FALSE

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

Una din constantele MCRYPT_MODE_modename sau unul din ?irurile de caractere: "ecb", "cbc", "cfb", "ofb", "nofb" sau "stream".

iv

Utilizat pentru ini?ializare în modurile CBC, CFB, OFB ?i în unii algoritmi în modul STREAM. Daca dimensiunea IV furnizat nu este sus?inuta de modul înlan?uirii, sau daca nu a fost furnizat un IV, însa modul de înlan?uire îl necesita, func?ia va emite o avertizare ?i va întoarce FALSE.

Valorile întoarse

Returns the decrypted data as a string sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Invalid key and iv sizes are no longer accepted. mcrypt_decrypt() will now throw a warning and return FALSE if the inputs are invalid. Previously keys and IVs were padded with '\0' bytes to the next valid size.

A se vedea ?i

  • mcrypt_encrypt() - Encrypts plaintext with given parameters

mcrypt_create_iv
mcrypt_ecb
Func?ii Mcrypt


Deprecated: Encrypts/decrypts data in ECB mode

mcrypt_decrypt
mcrypt_enc_get_algorithms_name
Func?ii Mcrypt
PHP Manual

mcrypt_ecb

(PHP 4, PHP 5)

mcrypt_ecb — Deprecated: Encrypts/decrypts data in ECB mode

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.5.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • mcrypt_decrypt()
  • mcrypt_encrypt()

Descrierea

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.

mcrypt_decrypt
mcrypt_enc_get_algorithms_name
Func?ii Mcrypt


Returns the name of the opened algorithm

mcrypt_ecb
mcrypt_enc_get_block_size
Func?ii Mcrypt
PHP Manual

mcrypt_enc_get_algorithms_name

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_enc_get_algorithms_name — Returns the name of the opened algorithm

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

string mcrypt_enc_get_algorithms_name ( resource $td )

This function returns the name of the algorithm.

Parametri

td

The encryption descriptor.

Valorile întoarse

Returns the name of the opened algorithm as a string.

Exemple

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

Exemplul de mai sus va afi?a:

CAST-256
CAST-256

mcrypt_ecb
mcrypt_enc_get_block_size
Func?ii Mcrypt


Returns the blocksize of the opened algorithm

mcrypt_enc_get_algorithms_name
mcrypt_enc_get_iv_size
Func?ii Mcrypt
PHP Manual

mcrypt_enc_get_block_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_enc_get_block_size — Returns the blocksize of the opened algorithm

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

int mcrypt_enc_get_block_size ( resource $td )

Gets the blocksize of the opened algorithm.

Parametri

td

The encryption descriptor.

Valorile întoarse

Returns the block size of the specified algorithm in bytes.

mcrypt_enc_get_algorithms_name
mcrypt_enc_get_iv_size
Func?ii Mcrypt


Returns the size of the IV of the opened algorithm

mcrypt_enc_get_block_size
mcrypt_enc_get_key_size
Func?ii Mcrypt
PHP Manual

mcrypt_enc_get_iv_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_enc_get_iv_size — Returns the size of the IV of the opened algorithm

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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.

Parametri

td

The encryption descriptor.

Valorile întoarse

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
Func?ii Mcrypt


Returns the maximum supported keysize of the opened mode

mcrypt_enc_get_iv_size
mcrypt_enc_get_modes_name
Func?ii Mcrypt
PHP Manual

mcrypt_enc_get_key_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_enc_get_key_size — Returns the maximum supported keysize of the opened mode

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

int mcrypt_enc_get_key_size ( resource $td )

Gets the maximum supported key size of the algorithm in bytes.

Parametri

td

The encryption descriptor.

Valorile întoarse

Returns the maximum supported key size of the algorithm in bytes.

mcrypt_enc_get_iv_size
mcrypt_enc_get_modes_name
Func?ii Mcrypt


Returns the name of the opened mode

mcrypt_enc_get_key_size
mcrypt_enc_get_supported_key_sizes
Func?ii Mcrypt
PHP Manual

mcrypt_enc_get_modes_name

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_enc_get_modes_name — Returns the name of the opened mode

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

string mcrypt_enc_get_modes_name ( resource $td )

This function returns the name of the mode.

Parametri

td

The encryption descriptor.

Valorile întoarse

Returns the name as a string.

Exemple

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

Exemplul de mai sus va afi?a:

CFB
ECB

mcrypt_enc_get_key_size
mcrypt_enc_get_supported_key_sizes
Func?ii Mcrypt


Returns an array with the supported keysizes of the opened algorithm

mcrypt_enc_get_modes_name
mcrypt_enc_is_block_algorithm_mode
Func?ii Mcrypt
PHP Manual

mcrypt_enc_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_enc_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

array mcrypt_enc_get_supported_key_sizes ( resource $td )

Gets the supported key sizes of the opened algorithm.

Parametri

td

The encryption descriptor.

Valorile întoarse

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.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

array(3) {
  [0]=>
  int(16)
  [1]=>
  int(24)
  [2]=>
  int(32)
}

mcrypt_enc_get_modes_name
mcrypt_enc_is_block_algorithm_mode
Func?ii Mcrypt


Checks whether the encryption of the opened mode works on blocks

mcrypt_enc_get_supported_key_sizes
mcrypt_enc_is_block_algorithm
Func?ii Mcrypt
PHP Manual

mcrypt_enc_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_enc_is_block_algorithm_mode — Checks whether the encryption of the opened mode works on blocks

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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

Parametri

td

The encryption descriptor.

Valorile întoarse

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
Func?ii Mcrypt


Checks whether the algorithm of the opened mode is a block algorithm

mcrypt_enc_is_block_algorithm_mode
mcrypt_enc_is_block_mode
Func?ii Mcrypt
PHP Manual

mcrypt_enc_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

bool mcrypt_enc_is_block_algorithm ( resource $td )

Tells whether the algorithm of the opened mode is a block algorithm.

Parametri

td

The encryption descriptor.

Valorile întoarse

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
Func?ii Mcrypt


Checks whether the opened mode outputs blocks

mcrypt_enc_is_block_algorithm
mcrypt_enc_self_test
Func?ii Mcrypt
PHP Manual

mcrypt_enc_is_block_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_enc_is_block_mode — Checks whether the opened mode outputs blocks

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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

Parametri

td

The encryption descriptor.

Valorile întoarse

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
Func?ii Mcrypt


Runs a self test on the opened module

mcrypt_enc_is_block_mode
mcrypt_encrypt
Func?ii Mcrypt
PHP Manual

mcrypt_enc_self_test

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_enc_self_test — Runs a self test on the opened module

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

int mcrypt_enc_self_test ( resource $td )

This function runs the self test on the algorithm specified by the descriptor td.

Parametri

td

The encryption descriptor.

Valorile întoarse

If the self test succeeds it returns FALSE. In case of an error, it returns TRUE.

mcrypt_enc_is_block_mode
mcrypt_encrypt
Func?ii Mcrypt


Encrypts plaintext with given parameters

mcrypt_enc_self_test
mcrypt_generic_deinit
Func?ii Mcrypt
PHP Manual

mcrypt_encrypt

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_encrypt — Encrypts plaintext with given parameters

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

string mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] )

Encrypts the data and returns it.

Parametri

cipher

Una din constantele MCRYPT_ciphername sau denumirea algoritmului ca ?ir de caractere.

key

The key with which the data will be encrypted. If the provided key size is not supported by the cipher, the function will emit a warning and return FALSE

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

Una din constantele MCRYPT_MODE_modename sau unul din ?irurile de caractere: "ecb", "cbc", "cfb", "ofb", "nofb" sau "stream".

iv

Utilizat pentru ini?ializare în modurile CBC, CFB, OFB ?i în unii algoritmi în modul STREAM. Daca dimensiunea IV furnizat nu este sus?inuta de modul înlan?uirii, sau daca nu a fost furnizat un IV, însa modul de înlan?uire îl necesita, func?ia va emite o avertizare ?i va întoarce FALSE.

Valorile întoarse

Returns the encrypted data as a string sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Invalid key and iv sizes are no longer accepted. mcrypt_encrypt() will now throw a warning and return FALSE if the inputs are invalid. Previously keys and IVs were padded with '\0' bytes to the next valid size.

Exemple

Example #1 mcrypt_encrypt() Example

<?php
    # --- ENCRYPTION ---

    # the key should be random binary, use scrypt, bcrypt or PBKDF2 to
    # convert a string into a key
    # key is specified using hexadecimal
    $key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");

    # show key size use either 16, 24 or 32 byte keys for AES-128, 192
    # and 256 respectively
    $key_size =  strlen($key);
    echo "Key size: " . $key_size . "\n";

    $plaintext = "This string was AES-256 / CBC / ZeroBytePadding encrypted.";

    # create a random IV to use with CBC encoding
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    # creates a cipher text compatible with AES (Rijndael block size = 128)
    # to keep the text confidential
    # only suitable for encoded input that never ends with value 00h
    # (because of default zero padding)
    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
                                 $plaintext, MCRYPT_MODE_CBC, $iv);

    # prepend the IV for it to be available for decryption
    $ciphertext = $iv . $ciphertext;

    # encode the resulting cipher text so it can be represented by a string
    $ciphertext_base64 = base64_encode($ciphertext);

    echo  $ciphertext_base64 . "\n";

    # === WARNING ===

    # Resulting cipher text has no integrity or authenticity added
    # and is not protected against padding oracle attacks.

    # --- DECRYPTION ---

    $ciphertext_dec = base64_decode($ciphertext_base64);

    # retrieves the IV, iv_size should be created using mcrypt_get_iv_size()
    $iv_dec = substr($ciphertext_dec, 0, $iv_size);

    # retrieves the cipher text (everything except the $iv_size in the front)
    $ciphertext_dec = substr($ciphertext_dec, $iv_size);

    # may remove 00h valued characters from end of plain text
    $plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,
                                    $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);

    echo  $plaintext_dec . "\n";
?>

Exemplul de mai sus va afi?a:

Key size: 32
ENJW8mS2KaJoNB5E5CoSAAu0xARgsR1bdzFWpEn+poYw45q+73az5kYi4j+0haevext1dGrcW8Qi59txfCBV8BBj3bzRP3dFCp3CPQSJ8eU=
This string was AES-256 / CBC / ZeroBytePadding encrypted.

A se vedea ?i

  • mcrypt_decrypt() - Decrypts crypttext with given parameters
  • mcrypt_module_open() - Opens the module of the algorithm and the mode to be used

mcrypt_enc_self_test
mcrypt_generic_deinit
Func?ii Mcrypt


This function deinitializes an encryption module

mcrypt_encrypt
mcrypt_generic_end
Func?ii Mcrypt
PHP Manual

mcrypt_generic_deinit

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

mcrypt_generic_deinit — This function deinitializes an encryption module

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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

Parametri

td

The encryption descriptor.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii Mcrypt


This function terminates encryption

mcrypt_generic_deinit
mcrypt_generic_init
Func?ii Mcrypt
PHP Manual

mcrypt_generic_end

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_generic_end — This function terminates encryption

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • mcrypt_generic_deinit()

Descrierea

bool mcrypt_generic_end ( resource $td )

Avertizare

mcrypt_generic_deinit() should be used instead of this function, as 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
Func?ii Mcrypt


This function initializes all buffers needed for encryption

mcrypt_generic_end
mcrypt_generic
Func?ii Mcrypt
PHP Manual

mcrypt_generic_init

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_generic_init — This function initializes all buffers needed for encryption

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • mcrypt_module_open() - Opens the module of the algorithm and the mode to be used

mcrypt_generic_end
mcrypt_generic
Func?ii Mcrypt


This function encrypts data

mcrypt_generic_init
mcrypt_get_block_size
Func?ii Mcrypt
PHP Manual

mcrypt_generic

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_generic — This function encrypts data

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the encrypted data.

A se vedea ?i

  • 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
Func?ii Mcrypt


Gets the block size of the specified cipher

mcrypt_generic
mcrypt_get_cipher_name
Func?ii Mcrypt
PHP Manual

mcrypt_get_block_size

(PHP 4, PHP 5, PHP 7)

mcrypt_get_block_size — Gets the block size of the specified cipher

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

int mcrypt_get_block_size ( int $cipher )
int mcrypt_get_block_size ( string $cipher , string $mode )

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

Parametri

cipher

Una din constantele MCRYPT_ciphername sau denumirea algoritmului ca ?ir de caractere.

mode

Una din constantele MCRYPT_MODE_modename sau unul din ?irurile de caractere: "ecb", "cbc", "cfb", "ofb", "nofb" sau "stream".

Valorile întoarse

Gets the block size, as an integer.

Exemple

Example #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

?>

A se vedea ?i

  • 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
Func?ii Mcrypt


Gets the name of the specified cipher

mcrypt_get_block_size
mcrypt_get_iv_size
Func?ii Mcrypt
PHP Manual

mcrypt_get_cipher_name

(PHP 4, PHP 5, PHP 7)

mcrypt_get_cipher_name — Gets the name of the specified cipher

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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.

Parametri

cipher

Una din constantele MCRYPT_ciphername sau denumirea algoritmului ca ?ir de caractere.

Valorile întoarse

This function returns the name of the cipher or FALSE if the cipher does not exist.

Exemple

Example #1 mcrypt_get_cipher_name() Example

<?php
   $cipher = MCRYPT_TripleDES;

   echo mcrypt_get_cipher_name($cipher);
?>

Exemplul de mai sus va afi?a:

3DES

mcrypt_get_block_size
mcrypt_get_iv_size
Func?ii Mcrypt


Returns the size of the IV belonging to a specific cipher/mode combination

mcrypt_get_cipher_name
mcrypt_get_key_size
Func?ii Mcrypt
PHP Manual

mcrypt_get_iv_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_get_iv_size — Returns the size of the IV belonging to a specific cipher/mode combination

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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

Parametri

cipher

Una din constantele MCRYPT_ciphername sau denumirea algoritmului ca ?ir de caractere.

mode

Una din constantele MCRYPT_MODE_modename sau unul din ?irurile de caractere: "ecb", "cbc", "cfb", "ofb", "nofb" sau "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.

Valorile întoarse

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.

Exemple

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

A se vedea ?i

  • 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
Func?ii Mcrypt


Gets the key size of the specified cipher

mcrypt_get_iv_size
mcrypt_list_algorithms
Func?ii Mcrypt
PHP Manual

mcrypt_get_key_size

(PHP 4, PHP 5, PHP 7)

mcrypt_get_key_size — Gets the key size of the specified cipher

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

int mcrypt_get_key_size ( int $cipher )
int mcrypt_get_key_size ( string $cipher , string $mode )

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

Parametri

cipher

Una din constantele MCRYPT_ciphername sau denumirea algoritmului ca ?ir de caractere.

mode

Una din constantele MCRYPT_MODE_modename sau unul din ?irurile de caractere: "ecb", "cbc", "cfb", "ofb", "nofb" sau "stream".

Valorile întoarse

Returns the maximum supported key size of the algorithm in bytes sau FALSE în cazul e?ecului.

Exemple

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

Exemplul de mai sus va afi?a:

24

A se vedea ?i

  • 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
Func?ii Mcrypt


Gets an array of all supported ciphers

mcrypt_get_key_size
mcrypt_list_modes
Func?ii Mcrypt
PHP Manual

mcrypt_list_algorithms

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_list_algorithms — Gets an array of all supported ciphers

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

array mcrypt_list_algorithms ([ string $lib_dir = ini_get("mcrypt.algorithms_dir") ] )

Gets the list of all supported algorithms in the lib_dir parameter.

Parametri

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.

Valorile întoarse

Returns an array with all the supported algorithms.

Exemple

Example #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
Func?ii Mcrypt


Gets an array of all supported modes

mcrypt_list_algorithms
mcrypt_module_close
Func?ii Mcrypt
PHP Manual

mcrypt_list_modes

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_list_modes — Gets an array of all supported modes

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

array mcrypt_list_modes ([ string $lib_dir = ini_get("mcrypt.modes_dir") ] )

Gets the list of all supported modes in the lib_dir parameter.

Parametri

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.

Valorile întoarse

Returns an array with all the supported modes.

Exemple

Example #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
Func?ii Mcrypt


Closes the mcrypt module

mcrypt_list_modes
mcrypt_module_get_algo_block_size
Func?ii Mcrypt
PHP Manual

mcrypt_module_close

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_module_close — Closes the mcrypt module

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

bool mcrypt_module_close ( resource $td )

Closes the specified encryption handle.

Parametri

td

The encryption descriptor.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • mcrypt_module_open() - Opens the module of the algorithm and the mode to be used

mcrypt_list_modes
mcrypt_module_get_algo_block_size
Func?ii Mcrypt


Returns the blocksize of the specified algorithm

mcrypt_module_close
mcrypt_module_get_algo_key_size
Func?ii Mcrypt
PHP Manual

mcrypt_module_get_algo_block_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_module_get_algo_block_size — Returns the blocksize of the specified algorithm

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

int mcrypt_module_get_algo_block_size ( string $algorithm [, string $lib_dir ] )

Gets the blocksize of the specified algorithm.

Parametri

algorithm

The algorithm name.

lib_dir

This optional parameter can contain the location where the mode module is on the system.

Valorile întoarse

Returns the block size of the algorithm specified in bytes.

mcrypt_module_close
mcrypt_module_get_algo_key_size
Func?ii Mcrypt


Returns the maximum supported keysize of the opened mode

mcrypt_module_get_algo_block_size
mcrypt_module_get_supported_key_sizes
Func?ii Mcrypt
PHP Manual

mcrypt_module_get_algo_key_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_module_get_algo_key_size — Returns the maximum supported keysize of the opened mode

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

int mcrypt_module_get_algo_key_size ( string $algorithm [, string $lib_dir ] )

Gets the maximum supported keysize of the opened mode.

Parametri

algorithm

The algorithm name.

lib_dir

This optional parameter can contain the location where the mode module is on the system.

Valorile întoarse

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
Func?ii Mcrypt


Returns an array with the supported keysizes of the opened algorithm

mcrypt_module_get_algo_key_size
mcrypt_module_is_block_algorithm_mode
Func?ii Mcrypt
PHP Manual

mcrypt_module_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_module_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii Mcrypt


Returns if the specified module is a block algorithm or not

mcrypt_module_get_supported_key_sizes
mcrypt_module_is_block_algorithm
Func?ii Mcrypt
PHP Manual

mcrypt_module_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_module_is_block_algorithm_mode — Returns if the specified module is a block algorithm or not

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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

Parametri

mode

The mode to check.

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Valorile întoarse

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
Func?ii Mcrypt


This function checks whether the specified algorithm is a block algorithm

mcrypt_module_is_block_algorithm_mode
mcrypt_module_is_block_mode
Func?ii Mcrypt
PHP Manual

mcrypt_module_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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.

Parametri

algorithm

The algorithm to check.

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Valorile întoarse

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
Func?ii Mcrypt


Returns if the specified mode outputs blocks or not

mcrypt_module_is_block_algorithm
mcrypt_module_open
Func?ii Mcrypt
PHP Manual

mcrypt_module_is_block_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_module_is_block_mode — Returns if the specified mode outputs blocks or not

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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

Parametri

mode

Una din constantele MCRYPT_MODE_modename sau unul din ?irurile de caractere: "ecb", "cbc", "cfb", "ofb", "nofb" sau "stream".

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Valorile întoarse

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
Func?ii Mcrypt


Opens the module of the algorithm and the mode to be used

mcrypt_module_is_block_mode
mcrypt_module_self_test
Func?ii Mcrypt
PHP Manual

mcrypt_module_open

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_module_open — Opens the module of the algorithm and the mode to be used

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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

Parametri

algorithm

Una din constantele MCRYPT_ciphername sau denumirea algoritmului ca ?ir de caractere.

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

Una din constantele MCRYPT_MODE_modename sau unul din ?irurile de caractere: "ecb", "cbc", "cfb", "ofb", "nofb" sau "stream".

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

Valorile întoarse

Normally it returns an encryption descriptor, or FALSE on error.

Exemple

Example #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 ECB 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.

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

A se vedea ?i

  • 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
Func?ii Mcrypt


This function runs a self test on the specified module

mcrypt_module_open
mcrypt_ofb
Func?ii Mcrypt
PHP Manual

mcrypt_module_self_test

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mcrypt_module_self_test — This function runs a self test on the specified module

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

bool mcrypt_module_self_test ( string $algorithm [, string $lib_dir ] )

This function runs the self test on the algorithm specified.

Parametri

algorithm

Una din constantele MCRYPT_ciphername sau denumirea algoritmului ca ?ir de caractere.

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Valorile întoarse

The function returns TRUE if the self test succeeds, or FALSE when it fails.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)

mcrypt_module_open
mcrypt_ofb
Func?ii Mcrypt


Encrypts/decrypts data in OFB mode

mcrypt_module_self_test
mdecrypt_generic
Func?ii Mcrypt
PHP Manual

mcrypt_ofb

(PHP 4, PHP 5)

mcrypt_ofb — Encrypts/decrypts data in OFB mode

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.5.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • mcrypt_decrypt()
  • mcrypt_encrypt()

Descrierea

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.

mcrypt_module_self_test
mdecrypt_generic
Func?ii Mcrypt


Decrypts data

mcrypt_ofb
Mhash
Func?ii Mcrypt
PHP Manual

mdecrypt_generic

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

mdecrypt_generic — Decrypts data

Avertizare

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Descrierea

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.

Parametri

td

An encryption descriptor returned by mcrypt_module_open()

data

Encrypted data.

Exemple

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

A se vedea ?i

  • 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
Func?ii Mcrypt


Mhash

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii Mhash
    • 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
Introducere
Extensii criptografice


Introducere

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.

Nota:

This extension is obsoleted by Hash.

Mhash
Instalarea / configurarea
Mhash


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Mhash


Necesita?i

To use it, download the mhash distribution from » its web site and follow the included installation instructions.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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

Tipurile resurselor
Exemple
Mhash


Exemple

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

Exemplul de mai sus va afi?a:

The hash is d03cb659cbf9192dcd066272249f8412
The hmac is 750c783e6ab0b503eaa86e310a5db738

Constante predefinite
Func?ii Mhash
Mhash


Func?ii Mhash

Cuprins

  • 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
Exemple
mhash_count
Mhash


Gets the highest available hash ID

Func?ii Mhash
mhash_get_block_size
Func?ii Mhash
PHP Manual

mhash_count

(PHP 4, PHP 5, PHP 7)

mhash_count — Gets the highest available hash ID

Descrierea

int mhash_count ( void )

Gets the highest available hash ID.

Valorile întoarse

Returns the highest available hash ID. Hashes are numbered from 0 to this hash ID.

Exemple

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

Func?ii Mhash
mhash_get_block_size
Func?ii Mhash


Gets the block size of the specified hash

mhash_count
mhash_get_hash_name
Func?ii Mhash
PHP Manual

mhash_get_block_size

(PHP 4, PHP 5, PHP 7)

mhash_get_block_size — Gets the block size of the specified hash

Descrierea

int mhash_get_block_size ( int $hash )

Gets the size of a block of the specified hash.

Parametri

hash

The hash ID. One of the MHASH_hashname constants.

Valorile întoarse

Returns the size in bytes or FALSE, if the hash does not exist.

Exemple

Example #1 mhash_get_block_size() Example

<?php

echo mhash_get_block_size(MHASH_MD5); // 16

?>

mhash_count
mhash_get_hash_name
Func?ii Mhash


Gets the name of the specified hash

mhash_get_block_size
mhash_keygen_s2k
Func?ii Mhash
PHP Manual

mhash_get_hash_name

(PHP 4, PHP 5, PHP 7)

mhash_get_hash_name — Gets the name of the specified hash

Descrierea

string mhash_get_hash_name ( int $hash )

Gets the name of the specified hash.

Parametri

hash

The hash ID. One of the MHASH_hashname constants.

Valorile întoarse

Returns the name of the hash or FALSE, if the hash does not exist.

Exemple

Example #1 mhash_get_hash_name() Example

<?php

echo mhash_get_hash_name(MHASH_MD5); // MD5

?>

mhash_get_block_size
mhash_keygen_s2k
Func?ii Mhash


Generates a key

mhash_get_hash_name
mhash
Func?ii Mhash
PHP Manual

mhash_keygen_s2k

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

mhash_keygen_s2k — Generates a key

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the generated key as a string, or FALSE on error.

mhash_get_hash_name
mhash
Func?ii Mhash


Computes hash

mhash_keygen_s2k
OpenSSL
Func?ii Mhash
PHP Manual

mhash

(PHP 4, PHP 5, PHP 7)

mhash — Computes hash

Descrierea

string mhash ( int $hash , string $data [, string $key ] )

mhash() applies a hash function specified by hash to the data.

Parametri

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.

Valorile întoarse

Returns the resulting hash (also called digest) or HMAC as a string, or FALSE on error.

mhash_keygen_s2k
OpenSSL
Func?ii Mhash


OpenSSL

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
    • 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
  • Func?ii OpenSSL
    • 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_cert_locations — Retrieve the available certificate locations
    • openssl_get_cipher_methods — Gets available cipher methods
    • openssl_get_md_methods — Gets available digest methods
    • openssl_get_privatekey — Pseudonim pentru openssl_pkey_get_private
    • openssl_get_publickey — Pseudonim pentru openssl_pkey_get_public
    • openssl_open — Open sealed data
    • openssl_pbkdf2 — Generates a PKCS5 v2 PBKDF2 string, defaults to SHA-1
    • 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_spki_export_challenge — Exports the challenge assoicated with a signed public key and challenge
    • openssl_spki_export — Exports a valid PEM formatted public key signed public key and challenge
    • openssl_spki_new — Generate a new signed public key and challenge
    • openssl_spki_verify — Verifies a signed public key and challenge
    • 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_fingerprint — Calculates the fingerprint, or digest, of a given X.509 certificate
    • 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
Introducere
Extensii criptografice


Introducere

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
Instalarea / configurarea
OpenSSL


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
OpenSSL


Necesita?i

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.

Avertizare

You are strongly encouraged to use the most recent OpenSSL version, otherwise your web server could be vulnerable to attack.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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.

Nota: Note to Win32 Users

Pentru ca aceasta extensie sa func?ioneze, anumite fi?iere DLL trebuie sa fie accesibile în calea de sistem a Windows din variabila PATH. Pentru informa?ii despre cum poate fi realizat acest lucru, accesa?i FAQ întitulat " Cum sa adaug directorul meu PHP la variabila PATH din Windows" pentru informa?ii despre cum sa realiza?i aceasta. Cu toate ca copierea fi?ierelor DLL din directorul PHP în directorul de sistem al Windows de asemenea func?ioneaza (deoarece directorul de sistem este în mod implicit inclus în variabila PATH), acest lucru nu este recomandabil. Aceasta extensie necesita ca urmatoarele fi?iere sa existe în calea 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. We include a sample configuration file in our win32 binary distributions, in the extras/openssl directory.

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

openssl Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Changelog
openssl.cafile | "" | PHP_INI_PERDIR | Available since PHP 5.6.0.
openssl.capath | "" | PHP_INI_PERDIR | Available since PHP 5.6.0.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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

openssl.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.

See also the SSL stream context options.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Cuprins

  • Purpose checking flags
  • Padding flags for asymmetric encryption
  • Key types
  • PKCS7 Flags/Constants
  • Signature Algorithms
  • Ciphers
  • Version constants
  • Server Name Indication constants

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Tipurile resurselor
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)
Constante predefinite
Padding flags for asymmetric encryption
Constante predefinite


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
Constante predefinite


Key types

OPENSSL_KEYTYPE_RSA (integer)
OPENSSL_KEYTYPE_DSA (integer)
OPENSSL_KEYTYPE_DH (integer)
OPENSSL_KEYTYPE_EC (integer)
This constant is only available when PHP is compiled with OpenSSL 0.9.8+.

Nota:

This constant was added in 5.2.0.

OPENSSL_KEYTYPE_EC

Padding flags for asymmetric encryption
PKCS7 Flags/Constants
Constante predefinite


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

Nota:

These constants were added in 4.0.6.

Key types
Signature Algorithms
Constante predefinite


Signature Algorithms

OPENSSL_ALGO_DSS1 (integer)
OPENSSL_ALGO_SHA1 (integer)
Used as default algorithm by openssl_sign() and openssl_verify().
OPENSSL_ALGO_SHA224 (integer)
OPENSSL_ALGO_SHA256 (integer)
OPENSSL_ALGO_SHA384 (integer)
OPENSSL_ALGO_SHA512 (integer)
OPENSSL_ALGO_RMD160 (integer)
OPENSSL_ALGO_MD5 (integer)
OPENSSL_ALGO_MD4 (integer)
OPENSSL_ALGO_MD2 (integer)
As of PHP 5.2.13 and PHP 5.3.2, this constant is only available if PHP is compiled with MD2 support. This requires passing in the -DHAVE_OPENSSL_MD2_H CFLAG when compiling PHP, and enable-md2 when compiling OpenSSL 1.0.0+.

Nota:

These constants were added in 5.0.0.

OPENSSL_ALGO_MD2, OPENSSL_ALGO_MD4, OPENSSL_ALGO_MD5, OPENSSL_ALGO_SHA1, OPENSSL_ALGO_DSS1

Nota:

These constants were added in 5.4.8.

OPENSSL_ALGO_RMD160, OPENSSL_ALGO_SHA224, OPENSSL_ALGO_SHA256, OPENSSL_ALGO_SHA384, OPENSSL_ALGO_SHA512

PKCS7 Flags/Constants
Ciphers
Constante predefinite


Ciphers

OPENSSL_CIPHER_RC2_40 (integer)
OPENSSL_CIPHER_RC2_128 (integer)
OPENSSL_CIPHER_RC2_64 (integer)
OPENSSL_CIPHER_DES (integer)
OPENSSL_CIPHER_3DES (integer)

Nota:

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)

Nota:

These constants were added in 5.4.0.

Signature Algorithms
Version constants
Constante predefinite


Version constants

OPENSSL_VERSION_TEXT (string)
OPENSSL_VERSION_NUMBER (integer)

Nota:

These constants were added in 5.2.0.

Ciphers
Server Name Indication constants
Constante predefinite


Server Name Indication constants

OPENSSL_TLSEXT_SERVER_NAME (string)
Whether SNI support is available or not.

Nota:

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
Constante predefinite


Key/Certificate parameters

Quite a few of the openssl functions require a key or a certificate parameter. Following methods may be used to get them:

  • 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
Func?ii OpenSSL
OpenSSL


Func?ii OpenSSL

Cuprins

  • 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_cert_locations — Retrieve the available certificate locations
  • openssl_get_cipher_methods — Gets available cipher methods
  • openssl_get_md_methods — Gets available digest methods
  • openssl_get_privatekey — Pseudonim pentru openssl_pkey_get_private
  • openssl_get_publickey — Pseudonim pentru openssl_pkey_get_public
  • openssl_open — Open sealed data
  • openssl_pbkdf2 — Generates a PKCS5 v2 PBKDF2 string, defaults to SHA-1
  • 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_spki_export_challenge — Exports the challenge assoicated with a signed public key and challenge
  • openssl_spki_export — Exports a valid PEM formatted public key signed public key and challenge
  • openssl_spki_new — Generate a new signed public key and challenge
  • openssl_spki_verify — Verifies a signed public key and challenge
  • 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_fingerprint — Calculates the fingerprint, or digest, of a given X.509 certificate
  • 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

Func?ii OpenSSL
openssl_csr_export_to_file
Func?ii OpenSSL
PHP Manual

openssl_cipher_iv_length

(PHP 5 >= PHP 5.3.3, PHP 7)

openssl_cipher_iv_length — Gets the cipher iv length

Descrierea

int openssl_cipher_iv_length ( string $method )

Gets the cipher initialization vector (iv) length.

Parametri

method

The cipher method, see openssl_get_cipher_methods() for a list of potential values.

Valorile întoarse

Returns the cipher length on success, or FALSE on failure.

Erori/Excep?ii

Emits an E_WARNING level error when the cipher algorithm is unknown.

Exemple

Example #1 openssl_cipher_iv_length() example

<?php
$method = 'AES-128-CBC';
$ivlen = openssl_cipher_iv_length($method);

echo $ivlen;
?>

Exemplul de mai sus va afi?a ceva similar cu:

16
Func?ii OpenSSL
openssl_csr_export_to_file
Func?ii OpenSSL


Exports a CSR to a file

openssl_cipher_iv_length
openssl_csr_export
Func?ii OpenSSL
PHP Manual

openssl_csr_export_to_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_csr_export_to_file — Exports a CSR to a file

Descrierea

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.

Parametri

csr

outfilename

Path to the output file.

notext

Parametrul op?ional notext afecteaza detalierea ie?irilor; daca este FALSE atunci informa?ii suplimentare lizibile de catre om sunt incluse în ie?iri. Valoarea implicita a notext este TRUE.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii OpenSSL


Exports a CSR as a string

openssl_csr_export_to_file
openssl_csr_get_public_key
Func?ii OpenSSL
PHP Manual

openssl_csr_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_csr_export — Exports a CSR as a string

Descrierea

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.

Parametri

csr

out

notext

Parametrul op?ional notext afecteaza detalierea ie?irilor; daca este FALSE atunci informa?ii suplimentare lizibile de catre om sunt incluse în ie?iri. Valoarea implicita a notext este TRUE.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii OpenSSL


Returns the public key of a CERT

openssl_csr_export
openssl_csr_get_subject
Func?ii OpenSSL
PHP Manual

openssl_csr_get_public_key

(PHP 5 >= 5.2.0, PHP 7)

openssl_csr_get_public_key — Returns the public key of a CERT

Descrierea

resource openssl_csr_get_public_key ( mixed $csr [, bool $use_shortnames = true ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

openssl_csr_export
openssl_csr_get_subject
Func?ii OpenSSL


Returns the subject of a CERT

openssl_csr_get_public_key
openssl_csr_new
Func?ii OpenSSL
PHP Manual

openssl_csr_get_subject

(PHP 5 >= 5.2.0, PHP 7)

openssl_csr_get_subject — Returns the subject of a CERT

Descrierea

array openssl_csr_get_subject ( mixed $csr [, bool $use_shortnames = true ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

openssl_csr_get_public_key
openssl_csr_new
Func?ii OpenSSL


Generates a CSR

openssl_csr_get_subject
openssl_csr_sign
Func?ii OpenSSL
PHP Manual

openssl_csr_new

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_csr_new — Generates a CSR

Descrierea

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.

Nota: Trebuie sa ave?i un fi?ier openssl.cnf valid instalat pentru ca aceasta func?ie sa opereze corect. Vede?i notele în sec?iunea de instalare pentru informa?ii suplimentare.

Parametri

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.

Valorile întoarse

Returns the CSR.

Exemple

Example #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
Func?ii OpenSSL


Sign a CSR with another certificate (or itself) and generate a certificate

openssl_csr_new
openssl_decrypt
Func?ii OpenSSL
PHP Manual

openssl_csr_sign

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_csr_sign — Sign a CSR with another certificate (or itself) and generate a certificate

Descrierea

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.

Nota: Trebuie sa ave?i un fi?ier openssl.cnf valid instalat pentru ca aceasta func?ie sa opereze corect. Vede?i notele în sec?iunea de instalare pentru informa?ii suplimentare.

Parametri

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.

Valorile întoarse

Returns an x509 certificate resource on success, FALSE on failure.

Exemple

Example #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
Func?ii OpenSSL


Decrypts data

openssl_csr_sign
openssl_dh_compute_key
Func?ii OpenSSL
PHP Manual

openssl_decrypt

(PHP 5 >= 5.3.0, PHP 7)

openssl_decrypt — Decrypts data

Descrierea

string openssl_decrypt ( string $data , string $method , string $password [, int $options = 0 [, string $iv = "" [, string $tag = "" [, string $aad = "" ]]]] )

Takes a raw or base64 encoded string and decrypts it using a given method and key.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

data

The data.

method

The cipher method.

password

The password.

options

options can be one of OPENSSL_RAW_DATA, OPENSSL_ZERO_PADDING.

iv

A non-NULL Initialization Vector.

tag

The authentication tag in AEAD cipher mode. If it is incorrect, the authentication fails and the function returns FALSE.

aad

Additional authentication data.

Valorile întoarse

The decrypted string on success sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Istoricul schimbarilor

Versiune | Descriere
5.3.3 | The iv parameter was added.
5.4.0 | The raw_output was changed to options.
7.1.0 | The tag and aad parameters were added.

A se vedea ?i

  • openssl_encrypt() - Encrypts data

openssl_csr_sign
openssl_dh_compute_key
Func?ii OpenSSL


Computes shared secret for public value of remote DH key and local DH key

openssl_decrypt
openssl_digest
Func?ii OpenSSL
PHP Manual

openssl_dh_compute_key

(PHP 5 >= 5.3.11, PHP 7)

openssl_dh_compute_key — Computes shared secret for public value of remote DH key and local DH key

Descrierea

string openssl_dh_compute_key ( string $pub_key , resource $dh_key )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pub_key

Public key

dh_key

DH key

Valorile întoarse

Returns computed key on success sau FALSE în cazul e?ecului.

openssl_decrypt
openssl_digest
Func?ii OpenSSL


Computes a digest

openssl_dh_compute_key
openssl_encrypt
Func?ii OpenSSL
PHP Manual

openssl_digest

(PHP 5 >= 5.3.0, PHP 7)

openssl_digest — Computes a digest

Descrierea

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.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

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.

Valorile întoarse

Returns the digested hash value on success sau FALSE în cazul e?ecului.

Erori/Excep?ii

Emits an E_WARNING level error if an unknown signature algorithm is passed via the method parameter.

A se vedea ?i

  • openssl_get_md_methods() - Gets available digest methods

openssl_dh_compute_key
openssl_encrypt
Func?ii OpenSSL


Encrypts data

openssl_digest
openssl_error_string
Func?ii OpenSSL
PHP Manual

openssl_encrypt

(PHP 5 >= 5.3.0, PHP 7)

openssl_encrypt — Encrypts data

Descrierea

string openssl_encrypt ( string $data , string $method , string $password [, int $options = 0 [, string $iv = "" [, string &$tag = NULL [, string $aad = "" [, int $tag_length = 16 ]]]]] )

Encrypts given data with given method and key, returns a raw or base64 encoded string

Parametri

data

The data.

method

The cipher method. For a list of available cipher methods, use openssl_get_cipher_methods().

password

The password.

options

options is a bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.

iv

A non-NULL Initialization Vector.

tag

The authentication tag passed by reference when using AEAD cipher mode (GCM or CCM).

aad

Additional authentication data.

tag_length

The length of the authentication tag. Its value can be between 4 and 16 for GCM mode.

Valorile întoarse

Returns the encrypted string on success sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Istoricul schimbarilor

Versiune | Descriere
5.3.3 | The iv parameter was added.
5.4.0 | The raw_output was changed to options.
7.1.0 | The tag, aad and tag_length parameters were added.

A se vedea ?i

  • openssl_decrypt() - Decrypts data

openssl_digest
openssl_error_string
Func?ii OpenSSL


Return openSSL error message

openssl_encrypt
openssl_free_key
Func?ii OpenSSL
PHP Manual

openssl_error_string

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_error_string — Return openSSL error message

Descrierea

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.

Valorile întoarse

Returns an error message string, or FALSE if there are no more error messages to return.

Exemple

Example #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
Func?ii OpenSSL


Free key resource

openssl_error_string
openssl_get_cert_locations
Func?ii OpenSSL
PHP Manual

openssl_free_key

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_free_key — Free key resource

Descrierea

void openssl_free_key ( resource $key_identifier )

openssl_free_key() frees the key associated with the specified key_identifier from memory.

Parametri

key_identifier

Valorile întoarse

Nu este întoarsa nici o valoare.

openssl_error_string
openssl_get_cert_locations
Func?ii OpenSSL


Retrieve the available certificate locations

openssl_free_key
openssl_get_cipher_methods
Func?ii OpenSSL
PHP Manual

openssl_get_cert_locations

(PHP 5 >= 5.6.0, PHP 7)

openssl_get_cert_locations — Retrieve the available certificate locations

Descrierea

array openssl_get_cert_locations ( void )

openssl_get_cert_locations() returns an array with information about the available certificate locations that will be searched for SSL certificates.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array with the available certificate locations.

Exemple

Example #1 openssl_get_cert_locations() example

<?php
var_dump(openssl_get_cert_locations());
?>

Exemplul de mai sus va afi?a:

array(8) {
  ["default_cert_file"]=>
  string(21) "/usr/lib/ssl/cert.pem"
  ["default_cert_file_env"]=>
  string(13) "SSL_CERT_FILE"
  ["default_cert_dir"]=>
  string(18) "/usr/lib/ssl/certs"
  ["default_cert_dir_env"]=>
  string(12) "SSL_CERT_DIR"
  ["default_private_dir"]=>
  string(20) "/usr/lib/ssl/private"
  ["default_default_cert_area"]=>
  string(12) "/usr/lib/ssl"
  ["ini_cafile"]=>
  string(0) ""
  ["ini_capath"]=>
  string(0) ""
}

openssl_free_key
openssl_get_cipher_methods
Func?ii OpenSSL


Gets available cipher methods

openssl_get_cert_locations
openssl_get_md_methods
Func?ii OpenSSL
PHP Manual

openssl_get_cipher_methods

(PHP 5 >= 5.3.0, PHP 7)

openssl_get_cipher_methods — Gets available cipher methods

Descrierea

array openssl_get_cipher_methods ([ bool $aliases = false ] )

Gets a list of available cipher methods.

Parametri

aliases

Set to TRUE if cipher aliases should be included within the returned array.

Valorile întoarse

An array of available cipher methods.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • openssl_get_md_methods() - Gets available digest methods

openssl_get_cert_locations
openssl_get_md_methods
Func?ii OpenSSL


Gets available digest methods

openssl_get_cipher_methods
openssl_get_privatekey
Func?ii OpenSSL
PHP Manual

openssl_get_md_methods

(PHP 5 >= 5.3.0, PHP 7)

openssl_get_md_methods — Gets available digest methods

Descrierea

array openssl_get_md_methods ([ bool $aliases = false ] )

Gets a list of available digest methods.

Parametri

aliases

Set to TRUE if digest aliases should be included within the returned array.

Valorile întoarse

An array of available digest methods.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • openssl_digest() - Computes a digest
  • openssl_get_cipher_methods() - Gets available cipher methods

openssl_get_cipher_methods
openssl_get_privatekey
Func?ii OpenSSL


Pseudonim pentru openssl_pkey_get_private

openssl_get_md_methods
openssl_get_publickey
Func?ii OpenSSL
PHP Manual

openssl_get_privatekey

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_get_privatekey — Pseudonim pentru openssl_pkey_get_private()

Descrierea

Aceasta func?ie este pseudonim pentru: openssl_pkey_get_private().

openssl_get_md_methods
openssl_get_publickey
Func?ii OpenSSL


Pseudonim pentru openssl_pkey_get_public

openssl_get_privatekey
openssl_open
Func?ii OpenSSL
PHP Manual

openssl_get_publickey

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_get_publickey — Pseudonim pentru openssl_pkey_get_public()

Descrierea

Aceasta func?ie este pseudonim pentru: openssl_pkey_get_public().

openssl_get_privatekey
openssl_open
Func?ii OpenSSL


Open sealed data

openssl_get_publickey
openssl_pbkdf2
Func?ii OpenSSL
PHP Manual

openssl_open

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_open — Open sealed data

Descrierea

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.

Parametri

sealed_data

open_data

If the call is successful the opened data is returned in this parameter.

env_key

priv_key_id

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • openssl_seal() - Seal (encrypt) data

openssl_get_publickey
openssl_pbkdf2
Func?ii OpenSSL


Generates a PKCS5 v2 PBKDF2 string, defaults to SHA-1

openssl_open
openssl_pkcs12_export_to_file
Func?ii OpenSSL
PHP Manual

openssl_pbkdf2

(PHP 5 >= 5.5.0, PHP 7)

openssl_pbkdf2 — Generates a PKCS5 v2 PBKDF2 string, defaults to SHA-1

Descrierea

string openssl_pbkdf2 ( string $password , string $salt , int $key_length , int $iterations [, string $digest_algorithm ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

password

salt

key_length

iterations

digest_algorithm

Valorile întoarse

Returns string sau FALSE în cazul e?ecului.

openssl_open
openssl_pkcs12_export_to_file
Func?ii OpenSSL


Exports a PKCS#12 Compatible Certificate Store File

openssl_pbkdf2
openssl_pkcs12_export
Func?ii OpenSSL
PHP Manual

openssl_pkcs12_export_to_file

(PHP 5 >= 5.2.2, PHP 7)

openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File

Descrierea

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.

Parametri

x509

Accesa?i Parametrii cheilor/certificatelor pentru a ob?ine lista valorilor valide.

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

openssl_pbkdf2
openssl_pkcs12_export
Func?ii OpenSSL


Exports a PKCS#12 Compatible Certificate Store File to variable.

openssl_pkcs12_export_to_file
openssl_pkcs12_read
Func?ii OpenSSL
PHP Manual

openssl_pkcs12_export

(PHP 5 >= 5.2.2, PHP 7)

openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable.

Descrierea

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.

Parametri

x509

Accesa?i Parametrii cheilor/certificatelor pentru a ob?ine lista valorilor valide.

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

openssl_pkcs12_export_to_file
openssl_pkcs12_read
Func?ii OpenSSL


Parse a PKCS#12 Certificate Store into an array

openssl_pkcs12_export
openssl_pkcs7_decrypt
Func?ii OpenSSL
PHP Manual

openssl_pkcs12_read

(PHP 5 >= 5.2.2, PHP 7)

openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array

Descrierea

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.

Parametri

pkcs12

The certificate store contents, not its file name.

certs

On success, this will hold the Certificate Store Data.

pass

Encryption password for unlocking the PKCS#12 file.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 openssl_pkcs12_read() example

<?php
if (!$cert_store = file_get_contents("/certs/file.p12")) {
    echo "Error: Unable to read the cert file\n";
    exit;
}

if (openssl_pkcs12_read($cert_store, $cert_info, "my_secret_pass")) {
    echo "Certificate Information\n";
    print_r($cert_info);
} else {
    echo "Error: Unable to read the cert store.\n";
    exit;
}
?>
openssl_pkcs12_export
openssl_pkcs7_decrypt
Func?ii OpenSSL


Decrypts an S/MIME encrypted message

openssl_pkcs12_read
openssl_pkcs7_encrypt
Func?ii OpenSSL
PHP Manual

openssl_pkcs7_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_pkcs7_decrypt — Decrypts an S/MIME encrypted message

Descrierea

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.

Parametri

infilename

outfilename

The decrypted message is written to the file specified by outfilename.

recipcert

recipkey

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii OpenSSL


Encrypt an S/MIME message

openssl_pkcs7_decrypt
openssl_pkcs7_sign
Func?ii OpenSSL
PHP Manual

openssl_pkcs7_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_pkcs7_encrypt — Encrypt an S/MIME message

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii OpenSSL


Sign an S/MIME message

openssl_pkcs7_encrypt
openssl_pkcs7_verify
Func?ii OpenSSL
PHP Manual

openssl_pkcs7_sign

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_pkcs7_sign — Sign an S/MIME message

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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", "file://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
Func?ii OpenSSL


Verifies the signature of an S/MIME signed message

openssl_pkcs7_sign
openssl_pkey_export_to_file
Func?ii OpenSSL
PHP Manual

openssl_pkcs7_verify

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_pkcs7_verify — Verifies the signature of an S/MIME signed message

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | The content parameter was added.

Note

Nota: 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
Func?ii OpenSSL


Gets an exportable representation of a key into a file

openssl_pkcs7_verify
openssl_pkey_export
Func?ii OpenSSL
PHP Manual

openssl_pkey_export_to_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_pkey_export_to_file — Gets an exportable representation of a key into a file

Descrierea

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.

Nota: Trebuie sa ave?i un fi?ier openssl.cnf valid instalat pentru ca aceasta func?ie sa opereze corect. Vede?i notele în sec?iunea de instalare pentru informa?ii suplimentare.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

openssl_pkcs7_verify
openssl_pkey_export
Func?ii OpenSSL


Gets an exportable representation of a key into a string

openssl_pkey_export_to_file
openssl_pkey_free
Func?ii OpenSSL
PHP Manual

openssl_pkey_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_pkey_export — Gets an exportable representation of a key into a string

Descrierea

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).

Nota: Trebuie sa ave?i un fi?ier openssl.cnf valid instalat pentru ca aceasta func?ie sa opereze corect. Vede?i notele în sec?iunea de instalare pentru informa?ii suplimentare.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

openssl_pkey_export_to_file
openssl_pkey_free
Func?ii OpenSSL


Frees a private key

openssl_pkey_export
openssl_pkey_get_details
Func?ii OpenSSL
PHP Manual

openssl_pkey_free

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_pkey_free — Frees a private key

Descrierea

void openssl_pkey_free ( resource $key )

This function frees a private key created by openssl_pkey_new().

Parametri

key

Resource holding the key.

Valorile întoarse

Nu este întoarsa nici o valoare.

openssl_pkey_export
openssl_pkey_get_details
Func?ii OpenSSL


Returns an array with the key details

openssl_pkey_free
openssl_pkey_get_private
Func?ii OpenSSL
PHP Manual

openssl_pkey_get_details

(PHP 5 >= 5.2.0, PHP 7)

openssl_pkey_get_details — Returns an array with the key details

Descrierea

array openssl_pkey_get_details ( resource $key )

This function returns the key details (bits, key, type).

Parametri

key

Resource holding the key.

Valorile întoarse

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 Descriere
    "n"
    "e"
    "d"
    "p"
    "q"
    "dmp1"
    "dmq1"
    "iqmp"
  • OPENSSL_KEYTYPE_DSA, an additional array key named "dsa", containing the key data is returned.
    Key Descriere
    "p"
    "q"
    "g"
    "priv_key"
    "pub_key"
  • OPENSSL_KEYTYPE_DH, an additional array key named "dh", containing the key data is returned.
    Key Descriere
    "p"
    "g"
    "priv_key"
    "pub_key"
openssl_pkey_free
openssl_pkey_get_private
Func?ii OpenSSL


Get a private key

openssl_pkey_get_details
openssl_pkey_get_public
Func?ii OpenSSL
PHP Manual

openssl_pkey_get_private

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_pkey_get_private — Get a private key

Descrierea

resource openssl_pkey_get_private ( mixed $key [, string $passphrase = "" ] )

openssl_get_privatekey() parses key and prepares it for use by other functions.

Parametri

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).

Valorile întoarse

Returns a positive key resource identifier on success, or FALSE on error.

openssl_pkey_get_details
openssl_pkey_get_public
Func?ii OpenSSL


Extract public key from certificate and prepare it for use

openssl_pkey_get_private
openssl_pkey_new
Func?ii OpenSSL
PHP Manual

openssl_pkey_get_public

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_pkey_get_public — Extract public key from certificate and prepare it for use

Descrierea

resource openssl_pkey_get_public ( mixed $certificate )

openssl_get_publickey() extracts the public key from certificate and prepares it for use by other functions.

Parametri

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/public key (it may contain both).
  3. A PEM formatted public key.

Valorile întoarse

Returns a positive key resource identifier on success, or FALSE on error.

openssl_pkey_get_private
openssl_pkey_new
Func?ii OpenSSL


Generates a new private key

openssl_pkey_get_public
openssl_private_decrypt
Func?ii OpenSSL
PHP Manual

openssl_pkey_new

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_pkey_new — Generates a new private key

Descrierea

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().

Nota: Trebuie sa ave?i un fi?ier openssl.cnf valid instalat pentru ca aceasta func?ie sa opereze corect. Vede?i notele în sec?iunea de instalare pentru informa?ii suplimentare.

Parametri

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.

Valorile întoarse

Returns a resource identifier for the pkey on success, or FALSE on error.

openssl_pkey_get_public
openssl_private_decrypt
Func?ii OpenSSL


Decrypts data with private key

openssl_pkey_new
openssl_private_encrypt
Func?ii OpenSSL
PHP Manual

openssl_private_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_private_decrypt — Decrypts data with private key

Descrierea

bool openssl_private_decrypt ( string $data , string &$decrypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] )

openssl_private_decrypt() decrypts data that was previously encrypted via openssl_public_encrypt() and stores the result into decrypted.

You can use this function e.g. to decrypt data which is supposed to only be available to you.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • openssl_public_encrypt() - Encrypts data with public key
  • openssl_public_decrypt() - Decrypts data with public key

openssl_pkey_new
openssl_private_encrypt
Func?ii OpenSSL


Encrypts data with private key

openssl_private_decrypt
openssl_public_decrypt
Func?ii OpenSSL
PHP Manual

openssl_private_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_private_encrypt — Encrypts data with private key

Descrierea

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.

Parametri

data

crypted

key

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • openssl_public_encrypt() - Encrypts data with public key
  • openssl_public_decrypt() - Decrypts data with public key

openssl_private_decrypt
openssl_public_decrypt
Func?ii OpenSSL


Decrypts data with public key

openssl_private_encrypt
openssl_public_encrypt
Func?ii OpenSSL
PHP Manual

openssl_public_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_public_decrypt — Decrypts data with public key

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • openssl_private_encrypt() - Encrypts data with private key
  • openssl_private_decrypt() - Decrypts data with private key

openssl_private_encrypt
openssl_public_encrypt
Func?ii OpenSSL


Encrypts data with public key

openssl_public_decrypt
openssl_random_pseudo_bytes
Func?ii OpenSSL
PHP Manual

openssl_public_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_public_encrypt — Encrypts data with public key

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • openssl_private_encrypt() - Encrypts data with private key
  • openssl_private_decrypt() - Decrypts data with private key

openssl_public_decrypt
openssl_random_pseudo_bytes
Func?ii OpenSSL


Generate a pseudo-random string of bytes

openssl_public_encrypt
openssl_seal
Func?ii OpenSSL
PHP Manual

openssl_random_pseudo_bytes

(PHP 5 >= 5.3.0, PHP 7)

openssl_random_pseudo_bytes — Generate a pseudo-random string of bytes

Descrierea

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.

Parametri

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

Valorile întoarse

Returns the generated string of bytes on success, sau FALSE în cazul e?ecului.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)

A se vedea ?i

  • random_bytes() - Generates cryptographically secure pseudo-random bytes
  • bin2hex() - Convert binary data into hexadecimal representation
  • crypt() - One-way string hashing
  • mt_rand() - Generate a random value via the Mersenne Twister Random Number Generator
  • uniqid() - Generate a unique ID
openssl_public_encrypt
openssl_seal
Func?ii OpenSSL


Seal (encrypt) data

openssl_random_pseudo_bytes
openssl_sign
Func?ii OpenSSL
PHP Manual

openssl_seal

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_seal — Seal (encrypt) data

Descrierea

int openssl_seal ( string $data , string &$sealed_data , array &$env_keys , array $pub_key_ids [, string $method = "RC4" ] )

openssl_seal() seals (encrypts) data by using the given method 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.

Parametri

data

The data to seal.

sealed_data

The sealed data.

env_keys

Array of encrypted keys.

pub_key_ids

Array of public key resource identifiers.

method

The cipher method.

Valorile întoarse

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.

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | The method parameter was added.

A se vedea ?i

  • openssl_open() - Open sealed data

openssl_random_pseudo_bytes
openssl_sign
Func?ii OpenSSL


Generate signature

openssl_seal
openssl_spki_export_challenge
Func?ii OpenSSL
PHP Manual

openssl_sign

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_sign — Generate signature

Descrierea

bool openssl_sign ( string $data , string &$signature , mixed $priv_key_id [, mixed $signature_alg = OPENSSL_ALGO_SHA1 ] )

openssl_sign() computes a signature for the specified data by generating a cryptographic digital signature using the private key associated with priv_key_id. Note that the data itself is not encrypted.

Parametri

data

The string of data you wish to sign

signature

If the call was successful the signature is returned in signature.

priv_key_id

resource - a key, returned by openssl_get_privatekey()

string - a PEM formatted key

signature_alg

int - one of these Signature Algorithms.

string - a valid string returned by openssl_get_md_methods() example, "sha256WithRSAEncryption" or "sha384".

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 openssl_sign() example

<?php
// $data is assumed to contain the data to be signed

// fetch private key from file and ready it
$pkeyid = openssl_pkey_get_private("file://src/openssl-0.9.6/demos/sign/key.pem");

// compute signature
openssl_sign($data, $signature, $pkeyid);

// free the key from memory
openssl_free_key($pkeyid);
?>

Example #2 openssl_sign() example

<?php
//data you want to sign
$data = 'my data';

//create new private and public key
$new_key_pair = openssl_pkey_new(array(
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
));
openssl_pkey_export($new_key_pair, $private_key_pem);

$details = openssl_pkey_get_details($new_key_pair);
$public_key_pem = $details['key'];

//create signature
openssl_sign($data, $signature, $private_key_pem, OPENSSL_ALGO_SHA256);

//save for later
file_put_contents('private_key.pem', $private_key_pem);
file_put_contents('public_key.pem', $public_key_pem);
file_put_contents('signature.dat', $signature);

//verify signature
$r = openssl_verify($data, $signature, $public_key_pem, "sha256WithRSAEncryption");
var_dump($r);
?>

A se vedea ?i

  • openssl_verify() - Verify signature

openssl_seal
openssl_spki_export_challenge
Func?ii OpenSSL


Exports the challenge assoicated with a signed public key and challenge

openssl_sign
openssl_spki_export
Func?ii OpenSSL
PHP Manual

openssl_spki_export_challenge

(PHP 5 >= 5.6.0, PHP 7)

openssl_spki_export_challenge — Exports the challenge assoicated with a signed public key and challenge

Descrierea

string openssl_spki_export_challenge ( string &$spkac )

Exports challenge from encoded signed public key and challenge

Parametri

spkac

Expects a valid signed public key and challenge

Valorile întoarse

Returns the associated challenge string or NULL on failure.

Erori/Excep?ii

Emits an E_WARNING level error if an invalid argument is passed via the spkac parameter.

Exemple

Example #1 openssl_spki_export_challenge() example

Extracts the associated challenge string or NULL on failure.

<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'challenge string');
$challenge = openssl_spki_export_challenge(preg_replace('/SPKAC=/', '', $spkac));
?>

Example #2 openssl_spki_export_challenge() example from <keygen>

Extracts the associated challenge string issued from the <keygen> element

<?php
$challenge = openssl_spki_export_challenge(preg_replace('/SPKAC=/', '', $_POST['spkac']));
?>
<keygen name="spkac" challenge="challenge string" keytype="RSA">

A se vedea ?i

  • openssl_spki_new() - Generate a new signed public key and challenge
  • openssl_spki_verify() - Verifies a signed public key and challenge
  • openssl_spki_export() - Exports a valid PEM formatted public key signed public key and challenge
  • openssl_md_method()
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

openssl_sign
openssl_spki_export
Func?ii OpenSSL


Exports a valid PEM formatted public key signed public key and challenge

openssl_spki_export_challenge
openssl_spki_new
Func?ii OpenSSL
PHP Manual

openssl_spki_export

(PHP 5 >= 5.6.0, PHP 7)

openssl_spki_export — Exports a valid PEM formatted public key signed public key and challenge

Descrierea

string openssl_spki_export ( string &$spkac )

Exports PEM formatted public key from encoded signed public key and challenge

Parametri

spkac

Expects a valid signed public key and challenge

Valorile întoarse

Returns the associated PEM formatted public key or NULL on failure.

Erori/Excep?ii

Emits an E_WARNING level error if an invalid argument is passed via the spkac parameter.

Exemple

Example #1 openssl_spki_export() example

Extracts the associated PEM formatted public key or NULL on failure.

<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'challenge string');
$pubKey = openssl_spki_export(preg_replace('/SPKAC=/', '', $spkac));

if ($pubKey) {
    echo $pubKey;
}
?>

Example #2 openssl_spki_export() example from <keygen>

Extracts the associated PEM formatted public key issued from the <keygen> element

<?php
$spkac = openssl_spki_export(preg_replace('/SPKAC=/', '', $_POST['spkac']));
if ($spkac != NULL) {
    echo $spkac;
} else {
    echo "Extraction of pub key failed";
}
?>
<keygen name="spkac" challenge="challenge string" keytype="RSA">

A se vedea ?i

  • openssl_spki_new() - Generate a new signed public key and challenge
  • openssl_spki_verify() - Verifies a signed public key and challenge
  • openssl_spki_export_challenge() - Exports the challenge assoicated with a signed public key and challenge
  • openssl_md_method()
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

openssl_spki_export_challenge
openssl_spki_new
Func?ii OpenSSL


Generate a new signed public key and challenge

openssl_spki_export
openssl_spki_verify
Func?ii OpenSSL
PHP Manual

openssl_spki_new

(PHP 5 >= 5.6.0, PHP 7)

openssl_spki_new — Generate a new signed public key and challenge

Descrierea

string openssl_spki_new ( resource &$privkey , string &$challenge [, int $algorithm = 0 ] )

Generates a signed public key and challenge using specified hashing algorithm

Parametri

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.

challenge

The challenge associated to associate with the SPKAC

algorithm

The digest algorithm. See openssl_get_md_method().

Valorile întoarse

Returns a signed public key and challenge string or NULL on failure.

Erori/Excep?ii

Emits an E_WARNING level error if an unknown signature algorithm is passed via the algorithm parameter.

Exemple

Example #1 openssl_spki_new() example

Generate a new SPKAC with the default digest (MD5)

<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'testing');

if ($spkac !== NULL) {
    echo $spkac;
} else {
    echo "SPKAC generation failed";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

MIICRzCCAS8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDM3V3sS4o4
mB9dczziRnjGAmSp+JwPrHoYMAFGvDNmZGyiWfU586X4BKs++BAj7e/FsAfno0Hd
hN9FwpCNFSox30L03nQvLYJE7f/WqigwBeMRT7Op/xvFks4sT70xP2HRYv4KqP9a
WRcKU6cFH8VxhFhqM2txEIxZKdFLaL28yT7bEDmcglf4JLDdgNMb9rET1dkgtKE6
dOaJHPGjf1uvnOH4YwkQr7n4sLUR3Kdbh0ZJAFuQVDZulo+LLzxBBkqJJcB6FhF+
oXCdHTKZnqAhpWDz+NXYytAmevab6IYm5TWPWsJUv1YKJA5lg2mXbbloIZlN9Mgc
i9fi03bdw+crAgMBAAEWB3Rlc3RpbmcwDQYJKoZIhvcNAQEEBQADggEBALyUvP/o
pPSoWBlorFyZ2RnGwKf9qMpE0q2IJP7G3oDR4LyK/m933DUiZ+YnqThrH/CWb4Ek
y5I3OCyl3S4wCuU1ibZZwDVwYShr5ELp0J9PEf7qMQZOhNsizoC7k+Czb2xB6hYW
sKfsfTKm3cXBtH3fdgc/Z1Z7VSWnAzYo38snqm72NTf5yFRnrQdphNNXi+kn1zHA
lxXRyFDXHOcYsOnwAWfyXFA4QDHQ0ezz0UoCY8gJXovcZb4GRYqOLUAsF2HcNboy
29WN8VqE29sL9QxVZFlwMcqyoLcNnyw38GvNvAGqSvzzbnEFP2MAQXJVe0H0hdp/
MML5G2iNVgNozAo=

A se vedea ?i

  • openssl_spki_new()
  • openssl_spki_export_challenge() - Exports the challenge assoicated with a signed public key and challenge
  • openssl_spki_export() - Exports a valid PEM formatted public key signed public key and challenge
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

openssl_spki_export
openssl_spki_verify
Func?ii OpenSSL


Verifies a signed public key and challenge

openssl_spki_new
openssl_verify
Func?ii OpenSSL
PHP Manual

openssl_spki_verify

(PHP 5 >= 5.6.0, PHP 7)

openssl_spki_verify — Verifies a signed public key and challenge

Descrierea

string openssl_spki_verify ( string &$spkac )

Validates the supplied signed public key and challenge

Parametri

spkac

Expects a valid signed public key and challenge

Valorile întoarse

Returns a boolean on success or failure.

Erori/Excep?ii

Emits an E_WARNING level error if an invalid argument is passed via the spkac parameter.

Exemple

Example #1 openssl_spki_verify() example

Validates an existing signed public key and challenge

<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'challenge string');

if (openssl_spki_verify(preg_replace('/SPKAC=/', '', $spkac))) {
    echo $spkac;
} else {
    echo "SPKAC validation failed";
}
?>

Example #2 openssl_spki_verify() example from <keygen>

Validates an existing signed public key and challenge issued from the <keygen> element

<?php
if (openssl_spki_verify(preg_replace('/SPKAC=/', '', $_POST['spkac']))) {
    echo $spkac;
} else {
    echo "SPKAC validation failed";
}
?>
<keygen name="spkac" challenge="challenge string" keytype="RSA">

A se vedea ?i

  • openssl_spki_new() - Generate a new signed public key and challenge
  • openssl_spki_export_challenge() - Exports the challenge assoicated with a signed public key and challenge
  • openssl_spki_export() - Exports a valid PEM formatted public key signed public key and challenge
  • openssl_md_method()
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

openssl_spki_new
openssl_verify
Func?ii OpenSSL


Verify signature

openssl_spki_verify
openssl_x509_check_private_key
Func?ii OpenSSL
PHP Manual

openssl_verify

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_verify — Verify signature

Descrierea

int openssl_verify ( string $data , string $signature , mixed $pub_key_id [, mixed $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.

Parametri

data

The string of data used to generate the signature previously

signature

A raw binary string, generated by openssl_sign() or similar means

pub_key_id

resource - a key, returned by openssl_get_publickey()

string - a PEM formatted key, example, "-----BEGIN PUBLIC KEY----- MIIBCgK..."

signature_alg

int - one of these Signature Algorithms.

string - a valid string returned by openssl_get_md_methods() example, "sha1WithRSAEncryption" or "sha512".

Valorile întoarse

Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | The signature_alg parameter was added.

Exemple

Example #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
$pubkeyid = openssl_pkey_get_public("file://src/openssl-0.9.6/demos/sign/cert.pem");

// 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);
?>

Example #2 openssl_verify() example

<?php
//data you want to sign
$data = 'my data';

//create new private and public key
$private_key_res = openssl_pkey_new(array(
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$details = openssl_pkey_get_details($private_key_res);
$public_key_res = openssl_pkey_get_public($details['key']);

//create signature
openssl_sign($data, $signature, $private_key_res, "sha1WithRSAEncryption");

//verify signature
$ok = openssl_verify($data, $signature, $public_key_res, OPENSSL_ALGO_SHA1);
if ($ok == 1) {
    echo "valid";
} elseif ($ok == 0) {
    echo "invalid";
} else {
    echo "error: ".openssl_error_string();
}
?>

A se vedea ?i

  • openssl_sign() - Generate signature

openssl_spki_verify
openssl_x509_check_private_key
Func?ii OpenSSL


Checks if a private key corresponds to a certificate

openssl_verify
openssl_x509_checkpurpose
Func?ii OpenSSL
PHP Manual

openssl_x509_check_private_key

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_x509_check_private_key — Checks if a private key corresponds to a certificate

Descrierea

bool openssl_x509_check_private_key ( mixed $cert , mixed $key )

Checks whether the given key is the private key that corresponds to cert.

Parametri

cert

The certificate.

key

The private key.

Valorile întoarse

Returns TRUE if key is the private key that corresponds to cert, or FALSE otherwise.

openssl_verify
openssl_x509_checkpurpose
Func?ii OpenSSL


Verifies if a certificate can be used for a particular purpose

openssl_x509_check_private_key
openssl_x509_export_to_file
Func?ii OpenSSL
PHP Manual

openssl_x509_checkpurpose

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose

Descrierea

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.

Parametri

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.

Valorile întoarse

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
Func?ii OpenSSL


Exports a certificate to file

openssl_x509_checkpurpose
openssl_x509_export
Func?ii OpenSSL
PHP Manual

openssl_x509_export_to_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_x509_export_to_file — Exports a certificate to file

Descrierea

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.

Parametri

x509

Accesa?i Parametrii cheilor/certificatelor pentru a ob?ine lista valorilor valide.

outfilename

Path to the output file.

notext

Parametrul op?ional notext afecteaza detalierea ie?irilor; daca este FALSE atunci informa?ii suplimentare lizibile de catre om sunt incluse în ie?iri. Valoarea implicita a notext este TRUE.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

openssl_x509_checkpurpose
openssl_x509_export
Func?ii OpenSSL


Exports a certificate as a string

openssl_x509_export_to_file
openssl_x509_fingerprint
Func?ii OpenSSL
PHP Manual

openssl_x509_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_x509_export — Exports a certificate as a string

Descrierea

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.

Parametri

x509

Accesa?i Parametrii cheilor/certificatelor pentru a ob?ine lista valorilor valide.

output

On success, this will hold the PEM.

notext

Parametrul op?ional notext afecteaza detalierea ie?irilor; daca este FALSE atunci informa?ii suplimentare lizibile de catre om sunt incluse în ie?iri. Valoarea implicita a notext este TRUE.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

openssl_x509_export_to_file
openssl_x509_fingerprint
Func?ii OpenSSL


Calculates the fingerprint, or digest, of a given X.509 certificate

openssl_x509_export
openssl_x509_free
Func?ii OpenSSL
PHP Manual

openssl_x509_fingerprint

(PHP 5.6, PHP 7)

openssl_x509_fingerprint — Calculates the fingerprint, or digest, of a given X.509 certificate

Descrierea

bool openssl_x509_fingerprint ( mixed $x509 [, string $hash_algorithm = "sha1" [, bool $raw_output = FALSE ]] )

openssl_x509_fingerprint() returns the digest of x509 as a string.

Parametri

x509

Accesa?i Parametrii cheilor/certificatelor pentru a ob?ine lista valorilor valide.

hash_algorithm

The hash algorithm to use, e.g. "md5" or "sha1"

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Valorile întoarse

Returns a string containing the calculated certificate fingerprint as lowercase hexits unless raw_output is set to TRUE in which case the raw binary representation of the message digest is returned.

Returns FALSE on failure.

openssl_x509_export
openssl_x509_free
Func?ii OpenSSL


Free certificate resource

openssl_x509_fingerprint
openssl_x509_parse
Func?ii OpenSSL
PHP Manual

openssl_x509_free

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_x509_free — Free certificate resource

Descrierea

void openssl_x509_free ( resource $x509cert )

openssl_x509_free() frees the certificate associated with the specified x509cert resource from memory.

Parametri

x509cert

Valorile întoarse

Nu este întoarsa nici o valoare.

openssl_x509_fingerprint
openssl_x509_parse
Func?ii OpenSSL


Parse an X509 certificate and return the information as an array

openssl_x509_free
openssl_x509_read
Func?ii OpenSSL
PHP Manual

openssl_x509_parse

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_x509_parse — Parse an X509 certificate and return the information as an array

Descrierea

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.

Parametri

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.

Valorile întoarse

The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.

openssl_x509_free
openssl_x509_read
Func?ii OpenSSL


Parse an X.509 certificate and return a resource identifier for it

openssl_x509_parse
Password Hashing
Func?ii OpenSSL
PHP Manual

openssl_x509_read

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_x509_read — Parse an X.509 certificate and return a resource identifier for it

Descrierea

resource openssl_x509_read ( mixed $x509certdata )

openssl_x509_read() parses the certificate supplied by x509certdata and returns a resource identifier for it.

Parametri

x509certdata

Valorile întoarse

Returns a resource identifier on success sau FALSE în cazul e?ecului.

openssl_x509_parse
Password Hashing
Func?ii OpenSSL


Password Hashing

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii de hash a parolelor
    • password_get_info — Returns information about the given hash
    • password_hash — Creates a password hash
    • password_needs_rehash — Checks if the given hash matches the given options
    • password_verify — Verifies that a password matches a hash
openssl_x509_read
Introducere
Extensii criptografice


Introducere

The password hashing API provides an easy to use wrapper around crypt() to make it easy to create and manage passwords in a secure manner.

This extension is available since PHP 5.5.0 but there is also an » userland implementation for PHP >= 5.3.7.

Password Hashing
Instalarea / configurarea
Password Hashing


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Password Hashing


Constante predefinite

Constantele de mai jos sunt întotdeauna disponibile ca parte componenta a nucleului PHP.

PASSWORD_BCRYPT (integer)

PASSWORD_BCRYPT is used to create new password hashes using the CRYPT_BLOWFISH algorithm.

This will always result in a hash using the "$2y$" crypt format, which is always 60 characters wide.

Supported Options:

  • salt - to manually provide a salt to use when hashing the password. Note that this will override and prevent a salt from being automatically generated.

    If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation.

  • cost - which denotes the algorithmic cost that should be used. Examples of these values can be found on the crypt() page.

    If ommitted, a default value of 10 will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.

PASSWORD_DEFAULT (integer)

The default algorithm to use for hashing if no algorithm is provided. This may change in newer PHP releases when newer, stronger hashing algorithms are supported.

It is worth noting that over time this constant can (and likely will) change. Therefore you should be aware that the length of the resulting hash can change. Therefore, if you use PASSWORD_DEFAULT you should store the resulting hash in a way that can store more than 60 characters (255 is the recomended width).

Values for this constant:

  • PHP 5.5.0 - PASSWORD_BCRYPT

Tipurile resurselor
Func?ii de hash a parolelor
Password Hashing


Func?ii de hash a parolelor

Cuprins

  • password_get_info — Returns information about the given hash
  • password_hash — Creates a password hash
  • password_needs_rehash — Checks if the given hash matches the given options
  • password_verify — Verifies that a password matches a hash
Constante predefinite
password_get_info
Password Hashing


Returns information about the given hash

Func?ii de hash a parolelor
password_hash
Func?ii de hash a parolelor
PHP Manual

password_get_info

(PHP 5 >= 5.5.0, PHP 7)

password_get_info — Returns information about the given hash

Descrierea

array password_get_info ( string $hash )

When passed in a valid hash created by an algorithm supported by password_hash(), this function will return an array of information about that hash.

Parametri

hash

O valoare de dispersie creata cu password_hash().

Valorile întoarse

Returns an associative array with three elements:

  • algo, which will match a password algorithm constant
  • algoName, which has the human readable name of the algorithm
  • options, which includes the options provided when calling password_hash()

Func?ii de hash a parolelor
password_hash
Func?ii de hash a parolelor


Creates a password hash

password_get_info
password_needs_rehash
Func?ii de hash a parolelor
PHP Manual

password_hash

(PHP 5 >= 5.5.0, PHP 7)

password_hash — Creates a password hash

Descrierea

string password_hash ( string $password , integer $algo [, array $options ] )

password_hash() creates a new password hash using a strong one-way hashing algorithm. password_hash() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_hash().

The following algorithms are currently supported:

  • PASSWORD_DEFAULT - Use the bcrypt algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).
  • PASSWORD_BCRYPT - Use the CRYPT_BLOWFISH algorithm to create the hash. This will produce a standard crypt() compatible hash using the "$2y$" identifier. The result will always be a 60 character string, sau FALSE în cazul e?ecului.

Supported Options:

  • salt - to manually provide a salt to use when hashing the password. Note that this will override and prevent a salt from being automatically generated.

    If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation.

    Avertizare

    The salt option has been deprecated as of PHP 7.0.0. It is now preferred to simply use the salt that is generated by default.

  • cost - which denotes the algorithmic cost that should be used. Examples of these values can be found on the crypt() page.

    If omitted, a default value of 10 will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.

Parametri

password

The user's password.

Precautie

Using the PASSWORD_BCRYPT as the algorithm, will result in the password parameter being truncated to a maximum length of 72 characters.

algo

O constanta a algoritmului de parole ce denota algoritmul ce va fi utilizat pentru dispersarea parolei.

options

Un tablou asociativ ce con?ine op?iuni. Accesa?i constantele algoritmilor pentru parole pentru documenta?ie referitoare la op?iunile fiecarui algoritm.

If omitted, a random salt will be created and the default cost will be used.

Valorile întoarse

Returns the hashed password, sau FALSE în cazul e?ecului.

The used algorithm, cost and salt are returned as part of the hash. Therefore, all information that's needed to verify the hash is included in it. This allows the password_verify() function to verify the hash without needing separate storage for the salt or algorithm information.

Exemple

Example #1 password_hash() example

<?php
/**
 * We just want to hash our password using the current DEFAULT algorithm.
 * This is presently BCRYPT, and will produce a 60 character result.
 *
 * Beware that DEFAULT may change over time, so you would want to prepare
 * By allowing your storage to expand past 60 characters (255 would be good)
 */
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT)."\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

Example #2 password_hash() example setting cost manually

<?php
/**
 * In this case, we want to increase the default cost for BCRYPT to 12.
 * Note that we also switched to BCRYPT, which will always be 60 characters.
 */
$options = [
    'cost' => 12,
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options)."\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

$2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K

Example #3 password_hash() example setting salt manually

<?php
/**
 * Note that the salt here is randomly generated.
 * Never use a static salt or one that is not randomly generated.
 *
 * For the VAST majority of use-cases, let password_hash generate the salt randomly for you
 */
$options = [
    'cost' => 11,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options)."\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

$2y$11$q5MkhSBtlsJcNEVsYh64a.aCluzHnGog7TQAKVmQwO9C8xb.t89F.

Example #4 password_hash() example finding a good cost

<?php
/**
 * This code will benchmark your server to determine how high of a cost you can
 * afford. You want to set the highest cost that you can without slowing down
 * you server too much. 8-10 is a good baseline, and more is good if your servers
 * are fast enough. The code below aims for = 50 milliseconds stretching time,
 * which is a good baseline for systems handling interactive logins.
 */
$timeTarget = 0.05; // 50 milliseconds

$cost = 8;
do {
    $cost++;
    $start = microtime(true);
    password_hash("test", PASSWORD_BCRYPT, ["cost" => $cost]);
    $end = microtime(true);
} while (($end - $start) < $timeTarget);

echo "Appropriate Cost Found: " . $cost . "\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

Appropriate Cost Found: 10

Note

Precautie

It is strongly recommended that you do not generate your own salt for this function. It will create a secure salt automatically for you if you do not specify one.

As noted above, providing the salt option in PHP 7.0 will generate a deprecation warning. Support for providing a salt manually may be removed in a future PHP release.

Nota:

It is recommended that you test this function on your servers, and adjust the cost parameter so that execution of the function takes less than 100 milliseconds on interactive systems. The script in the above example will help you choose a good cost value for your hardware.

Nota: Updates to supported algorithms by this function (or changes to the default one) must follow the following rules:

  • Any new algorithm must be in core for at least 1 full release of PHP prior to becoming default. So if, for example, a new algorithm is added in 7.5.5, it would not be eligible for default until 7.7 (since 7.6 would be the first full release). But if a different algorithm was added in 7.6.0, it would also be eligible for default at 7.7.0.
  • The default should only change in a full release (7.3.0, 8.0.0, etc) and not in a revision release. The only exception to this is in an emergency when a critical security flaw is found in the current default.

A se vedea ?i

  • password_verify() - Verifies that a password matches a hash
  • crypt() - One-way string hashing
  • » userland implementation

password_get_info
password_needs_rehash
Func?ii de hash a parolelor


Checks if the given hash matches the given options

password_hash
password_verify
Func?ii de hash a parolelor
PHP Manual

password_needs_rehash

(PHP 5 >= 5.5.0, PHP 7)

password_needs_rehash — Checks if the given hash matches the given options

Descrierea

boolean password_needs_rehash ( string $hash , integer $algo [, array $options ] )

This function checks to see if the supplied hash implements the algorithm and options provided. If not, it is assumed that the hash needs to be rehashed.

Parametri

hash

O valoare de dispersie creata cu password_hash().

algo

O constanta a algoritmului de parole ce denota algoritmul ce va fi utilizat pentru dispersarea parolei.

options

Un tablou asociativ ce con?ine op?iuni. Accesa?i constantele algoritmilor pentru parole pentru documenta?ie referitoare la op?iunile fiecarui algoritm.

Exemple

Example #1 Usage of password_needs_rehash()

<?php

$password = 'rasmuslerdorf';
$hash = '$2y$10$YCFsG6elYca568hBi2pZ0.3LDL5wjgxct1N8w/oLR/jfHsiQwCqTS';

// The cost parameter can change over time as hardware improves
$options = array('cost' => 11);

// Verify stored hash against plain-text password
if (password_verify($password, $hash)) {
    // Check if a newer hashing algorithm is available
    // or the cost has changed
    if (password_needs_rehash($hash, PASSWORD_DEFAULT, $options)) {
        // If so, create a new hash, and replace the old one
        $newHash = password_hash($password, PASSWORD_DEFAULT, $options);
    }

    // Log user in
}
?>

Valorile întoarse

Returns TRUE if the hash should be rehashed to match the given algo and options, or FALSE otherwise.

password_hash
password_verify
Func?ii de hash a parolelor


Verifies that a password matches a hash

password_needs_rehash
Extensii de lucru cu baze de date
Func?ii de hash a parolelor
PHP Manual

password_verify

(PHP 5 >= 5.5.0, PHP 7)

password_verify — Verifies that a password matches a hash

Descrierea

boolean password_verify ( string $password , string $hash )

Verifies that the given hash matches the given password.

Note that password_hash() returns the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it. This allows the verify function to verify the hash without needing separate storage for the salt or algorithm information.

This function is safe against timing attacks.

Parametri

password

The user's password.

hash

O valoare de dispersie creata cu password_hash().

Valorile întoarse

Returns TRUE if the password and hash match, or FALSE otherwise.

Exemple

Example #1 password_verify() example

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
?>

Exemplul de mai sus va afi?a:

Password is valid!

A se vedea ?i

  • password_hash() - Creates a password hash
  • » userland implementation

password_needs_rehash
Extensii de lucru cu baze de date
Func?ii de hash a parolelor


Extensii de lucru cu baze de date

  • Nivele de abstractizare
    • DBA — Database (dbm-style) Abstraction Layer
    • dbx
    • ODBC — ODBC (Unified)
    • PDO — PHP Data Objects
  • Extensii de lucru cu baze de date specifice anumitor producatori
    • CUBRID
    • DB++
    • dBase
    • filePro
    • Firebird/InterBase
    • FrontBase
    • IBM DB2 — IBM DB2, Cloudscape and Apache Derby
    • Informix
    • Ingres — Ingres DBMS, EDBC, and Enterprise Access Gateways
    • MaxDB
    • Mongo — Driver-ul MongoDB (învechit)
    • MongoDB — MongoDB driver
    • mSQL
    • Mssql — Microsoft SQL Server
    • MySQL — MySQL Drivers and Plugins
    • OCI8 — Oracle OCI8
    • Paradox — Paradox File Access
    • PostgreSQL
    • SQLite
    • SQLite3
    • SQLSRV — Microsoft SQL Server Driver for PHP
    • Sybase
    • tokyo_tyrant
password_verify
Nivele de abstractizare
Informa?ii de referin?a despre func?ii


Nivele de abstractizare

  • DBA — Database (dbm-style) Abstraction Layer
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii DBA
  • dbx
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii dbx
  • ODBC — ODBC (Unified)
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii ODBC
  • PDO — PHP Data Objects
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • 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
Extensii de lucru cu baze de date
DBA
Extensii de lucru cu baze de date


Database (dbm-style) Abstraction Layer

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic usage
  • Func?ii DBA
    • 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
Nivele de abstractizare
Introducere
Nivele de abstractizare


Introducere

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
Instalarea / configurarea
DBA


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
DBA


Necesita?i

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.
tcadb | This is available since PHP 5.4.0. The Tokyo Cabinet library can be loaded from » http://fallabs.com/tokyocabinet/.

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().

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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.

Avertizare

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] .

Nota:

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] .

Nota:

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] .

Nota:

db2 conflicts with db3 and db4.

db3

To enable support for Oracle Berkeley DB 3 add --with-db3[=DIR] .

Nota:

db3 conflicts with db2 and db4.

db4

To enable support for Oracle Berkeley DB 4 or 5 add --with-db4[=DIR] .

Nota:

db4 conflicts with db2 and db3.

Nota:

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] .

Nota:

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 .

Nota:

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 .

Nota:

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] .

Nota:

qdbm conflicts with dbm and gdbm.

Nota:

This was added in PHP 5.0.0. The qdbm library can be loaded from » http://fallabs.com/qdbm/index.html.

tcadb

To enable support for Tokyo Cabinet add --with-tcadb[=DIR] .

Nota:

This was added in PHP 5.4.0. The Tokyo Cabinet library can be loaded from » http://fallabs.com/tokyocabinet/.

Nota:

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

DBA Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
dba.default_handler | DBA_DEFAULT | PHP_INI_ALL |

Iata o explica?ie pe scurt a directivelor de configurare.

dba.default_handler string

The name of the default handler

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

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.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
DBA


Exemple

Cuprins

  • Basic usage
Constante predefinite
Basic usage
DBA


Basic usage

Example #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.

Example #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);
}

?>

Exemple
Func?ii DBA
Exemple


Func?ii DBA

Cuprins

  • 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

Func?ii DBA
dba_delete
Func?ii DBA
PHP Manual

dba_close

(PHP 4, PHP 5, PHP 7)

dba_close — Close a DBA database

Descrierea

void dba_close ( resource $handle )

dba_close() closes the established database and frees all resources of the specified database handle.

Parametri

handle

The database handler, returned by dba_open() or dba_popen().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • dba_open() - Open database
  • dba_popen() - Open database persistently

Func?ii DBA
dba_delete
Func?ii DBA


Delete DBA entry specified by key

dba_close
dba_exists
Func?ii DBA
PHP Manual

dba_delete

(PHP 4, PHP 5, PHP 7)

dba_delete — Delete DBA entry specified by key

Descrierea

bool dba_delete ( string $key , resource $handle )

dba_delete() deletes the specified entry from the database.

Parametri

key

The key of the entry which is deleted.

handle

The database handler, returned by dba_open() or dba_popen().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii DBA


Check whether key exists

dba_delete
dba_fetch
Func?ii DBA
PHP Manual

dba_exists

(PHP 4, PHP 5, PHP 7)

dba_exists — Check whether key exists

Descrierea

bool dba_exists ( string $key , resource $handle )

dba_exists() checks whether the specified key exists in the database.

Parametri

key

The key the check is performed for.

handle

The database handler, returned by dba_open() or dba_popen().

Valorile întoarse

Returns TRUE if the key exists, FALSE otherwise.

A se vedea ?i

  • 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
Func?ii DBA


Fetch data specified by key

dba_exists
dba_firstkey
Func?ii DBA
PHP Manual

dba_fetch

(PHP 4, PHP 5, PHP 7)

dba_fetch — Fetch data specified by key

Descrierea

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.

Parametri

key

The key the data is specified by.

Nota:

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().

Valorile întoarse

Returns the associated string if the key/data pair is found, FALSE otherwise.

Istoricul schimbarilor

Versiune | Descriere
4.3.0 | The skip parameter is available to support cdb's capability of multiple keys having the same name.

A se vedea ?i

  • 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
Func?ii DBA


Fetch first key

dba_fetch
dba_handlers
Func?ii DBA
PHP Manual

dba_firstkey

(PHP 4, PHP 5, PHP 7)

dba_firstkey — Fetch first key

Descrierea

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.

Parametri

handle

The database handler, returned by dba_open() or dba_popen().

Valorile întoarse

Returns the key on success sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii DBA


List all the handlers available

dba_firstkey
dba_insert
Func?ii DBA
PHP Manual

dba_handlers

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

dba_handlers — List all the handlers available

Descrierea

array dba_handlers ([ bool $full_info = false ] )

dba_handlers() list all the handlers supported by this extension.

Parametri

full_info

Turns on/off full information display in the result.

Valorile întoarse

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.

Nota:

When the internal cdb library is used you will see cdb and cdb_make.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
Func?ii DBA


Insert entry

dba_handlers
dba_key_split
Func?ii DBA
PHP Manual

dba_insert

(PHP 4, PHP 5, PHP 7)

dba_insert — Insert entry

Descrierea

bool dba_insert ( string $key , string $value , resource $handle )

dba_insert() inserts the entry described with key and value into the database.

Parametri

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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii DBA


Splits a key in string representation into array representation

dba_insert
dba_list
Func?ii DBA
PHP Manual

dba_key_split

(PHP 5, PHP 7)

dba_key_split — Splits a key in string representation into array representation

Descrierea

mixed dba_key_split ( mixed $key )

dba_key_split() splits a key (string representation) into an array representation.

Parametri

key

The key in string representation.

Valorile întoarse

Returns an array of the form array(0 => group, 1 => value_name). This function will return FALSE if key is NULL or FALSE.

A se vedea ?i

  • dba_firstkey() - Fetch first key
  • dba_nextkey() - Fetch next key
  • dba_fetch() - Fetch data specified by key

dba_insert
dba_list
Func?ii DBA


List all open database files

dba_key_split
dba_nextkey
Func?ii DBA
PHP Manual

dba_list

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

dba_list — List all open database files

Descrierea

array dba_list ( void )

dba_list() list all open database files.

Valorile întoarse

An associative array, in the form resourceid => filename.

dba_key_split
dba_nextkey
Func?ii DBA


Fetch next key

dba_list
dba_open
Func?ii DBA
PHP Manual

dba_nextkey

(PHP 4, PHP 5, PHP 7)

dba_nextkey — Fetch next key

Descrierea

string dba_nextkey ( resource $handle )

dba_nextkey() returns the next key of the database and advances the internal key pointer.

Parametri

handle

The database handler, returned by dba_open() or dba_popen().

Valorile întoarse

Returns the key on success sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii DBA


Open database

dba_nextkey
dba_optimize
Func?ii DBA
PHP Manual

dba_open

(PHP 4, PHP 5, PHP 7)

dba_open — Open database

Descrierea

resource dba_open ( string $path , string $mode [, string $handler [, mixed $... ]] )

dba_open() establishes a database instance for path with mode using handler.

Parametri

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.

Nota:

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.

Valorile întoarse

Returns a positive handle on success sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
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.

A se vedea ?i

  • dba_popen() - Open database persistently
  • dba_close() - Close a DBA database

dba_nextkey
dba_optimize
Func?ii DBA


Optimize database

dba_open
dba_popen
Func?ii DBA
PHP Manual

dba_optimize

(PHP 4, PHP 5, PHP 7)

dba_optimize — Optimize database

Descrierea

bool dba_optimize ( resource $handle )

dba_optimize() optimizes the underlying database.

Parametri

handle

The database handler, returned by dba_open() or dba_popen().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • dba_sync() - Synchronize database

dba_open
dba_popen
Func?ii DBA


Open database persistently

dba_optimize
dba_replace
Func?ii DBA
PHP Manual

dba_popen

(PHP 4, PHP 5, PHP 7)

dba_popen — Open database persistently

Descrierea

resource dba_popen ( string $path , string $mode [, string $handler [, mixed $... ]] )

dba_popen() establishes a persistent database instance for path with mode using handler.

Parametri

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.

Valorile întoarse

Returns a positive handle on success sau FALSE în cazul e?ecului.

A se vedea ?i

  • dba_open() - Open database
  • dba_close() - Close a DBA database

dba_optimize
dba_replace
Func?ii DBA


Replace or insert entry

dba_popen
dba_sync
Func?ii DBA
PHP Manual

dba_replace

(PHP 4, PHP 5, PHP 7)

dba_replace — Replace or insert entry

Descrierea

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.

Parametri

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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii DBA


Synchronize database

dba_replace
dbx
Func?ii DBA
PHP Manual

dba_sync

(PHP 4, PHP 5, PHP 7)

dba_sync — Synchronize database

Descrierea

bool dba_sync ( resource $handle )

dba_sync() synchronizes the database. This will probably trigger a physical write to the disk, if supported.

Parametri

handle

The database handler, returned by dba_open() or dba_popen().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • dba_optimize() - Optimize database

dba_replace
dbx
Func?ii DBA


dbx

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii dbx
    • 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
Introducere
Nivele de abstractizare


Introducere

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.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.1.0.

dbx
Instalarea / configurarea
dbx


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
dbx


Necesita?i

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/.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

DBX Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Available since PHP 4.3.0. Removed in PHP 5.1.0.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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().

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

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.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
Tipurile resurselor
Func?ii dbx
dbx


Func?ii dbx

Cuprins

  • 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
Constante predefinite
dbx_close
dbx


Close an open connection/database

Func?ii dbx
dbx_compare
Func?ii dbx
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

Descrierea

int dbx_close ( object $link_identifier )

Parametri

link_identifier

The DBX link object to close.

Valorile întoarse

Returns 1 on success and 0 on errors.

Exemple

Example #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);
?>

Note

Nota:

Always refer to the module-specific documentation as well.

A se vedea ?i

  • dbx_connect() - Open a connection/database

Func?ii dbx
dbx_compare
Func?ii dbx


Compare two rows for sorting purposes

dbx_close
dbx_connect
Func?ii dbx
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

Descrierea

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.

Parametri

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 (|).

Valorile întoarse

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.

Exemple

Example #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);
?>

A se vedea ?i

  • dbx_sort() - Sort a result from a dbx_query by a custom sort function

dbx_close
dbx_connect
Func?ii dbx


Open a connection/database

dbx_compare
dbx_error
Func?ii dbx
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

Descrierea

object dbx_connect ( mixed $module , string $host , string $database , string $username , string $password [, int $persistent ] )

Opens a connection to a database.

Parametri

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.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
5.0.0 | Introduced DBX_SQLITE.
4.3.0 | Introduced DBX_OCI8.
4.2.0 | Introduced DBX_SYBASECT.
4.1.0 | Introduced DBX_FBSQL.

Exemple

Example #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);
?>

Note

Nota:

Always refer to the module-specific documentation as well.

A se vedea ?i

  • dbx_close() - Close an open connection/database

dbx_compare
dbx_error
Func?ii dbx


Report the error message of the latest function call in the module

dbx_connect
dbx_escape_string
Func?ii dbx
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

Descrierea

string dbx_error ( object $link_identifier )

dbx_error() returns the last error message.

Parametri

link_identifier

The DBX link object returned by dbx_connect()

Valorile întoarse

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.

Exemple

Example #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);
?>

Note

Nota:

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
Func?ii dbx


Escape a string so it can safely be used in an sql-statement

dbx_error
dbx_fetch_row
Func?ii dbx
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

Descrierea

string dbx_escape_string ( object $link_identifier , string $text )

Escape the given string so that it can safely be used in an sql-statement.

Parametri

link_identifier

The DBX link object returned by dbx_connect()

text

The string to escape.

Valorile întoarse

Returns the text, escaped where necessary (such as quotes, backslashes etc). On error, NULL is returned.

Exemple

Example #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);
?>

A se vedea ?i

  • dbx_query() - Send a query and fetch all results (if any)

dbx_error
dbx_fetch_row
Func?ii dbx


Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

dbx_escape_string
dbx_query
Func?ii dbx
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

Descrierea

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().

Parametri

result_identifier

A result set returned by dbx_query().

Valorile întoarse

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).

Exemple

Example #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";
?>

A se vedea ?i

  • dbx_query() - Send a query and fetch all results (if any)

dbx_escape_string
dbx_query
Func?ii dbx


Send a query and fetch all results (if any)

dbx_fetch_row
dbx_sort
Func?ii dbx
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)

Descrierea

mixed dbx_query ( object $link_identifier , string $sql_statement [, int $flags ] )

Sends a query and fetch all results.

Parametri

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.

Valorile întoarse

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.

Example #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"].

Example #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";
?>

Example #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";

?>

Istoricul schimbarilor

Versiune | Descriere
5.0.0 | Introduced DBX_RESULT_UNBUFFERED.
4.3.0 | Introduced DBX_COLNAMES_UNCHANGED, DBX_COLNAMES_UPPERCASE, and DBX_COLNAMES_LOWERCASE.

Exemple

Example #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);
?>

Note

Nota:

Always refer to the module-specific documentation as well.

Column names for queries on an Oracle database are returned in lowercase.

A se vedea ?i

  • 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
Func?ii dbx


Sort a result from a dbx_query by a custom sort function

dbx_query
ODBC
Func?ii dbx
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

Descrierea

bool dbx_sort ( object $result , string $user_compare_function )

Sort a result from a dbx_query() call with a custom sort function.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Note

Nota:

It is always better to use ORDER BY SQL clause instead of dbx_sort() if possible.

A se vedea ?i

  • dbx_compare() - Compare two rows for sorting purposes

dbx_query
ODBC
Func?ii dbx


ODBC (Unified)

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii ODBC
    • 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 — Pseudonim pentru 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 — Pseudonim pentru 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
Introducere
Nivele de abstractizare


Introducere

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.

Nota:

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
Instalarea / configurarea
ODBC


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
ODBC


Necesita?i

To access any of the supported databases you need to have the required libraries installed.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

--with-adabas[=DIR]

Include Adabas D support. DIR is the Adabas base install directory, defaults to /usr/local.

--with-sapdb[=DIR]

Include SAP DB support. DIR is SAP DB base install directory, defaults to /usr/local.

--with-solid[=DIR]

Include Solid support. DIR is the Solid base install directory, defaults to /usr/local/solid.

--with-ibm-db2[=DIR]

Include IBM DB2 support. DIR is the DB2 base install directory, defaults to /home/db2inst1/sqllib.

--with-empress[=DIR]

Include Empress support. DIR is the Empress base install directory, defaults to $EMPRESSPATH. This option only supports Empress Version 8.60 and above.

--with-empress-bcs[=DIR]

Include "Empress Local Access" support. DIR is the Empress base install directory, defaults to $EMPRESSPATH. This option only supports Empress Version 8.60 and above.

--with-birdstep[=DIR]

Include Birdstep support. DIR is the Birdstep base install directory, defaults to /usr/local/birdstep.

--with-custom-odbc[=DIR]

Include a user defined ODBC support. The DIR is ODBC install base directory, which defaults to /usr/local. Make sure to define CUSTOM_ODBC_LIBS and have some odbc.h in your include dirs. E.g., you should define following for Sybase SQL Anywhere 5.5.00 on QNX, prior to run configure script:

   CPPFLAGS="-DODBC_QNX -DSQLANY_BUG"
   LDFLAGS=-lunix
   CUSTOM_ODBC_LIBS="-ldblib -lodbc".

--with-iodbc[=DIR]

Include iODBC support. DIR is the iODBC base install directory, defaults to /usr/local.

--with-esoob[=DIR]

Include Easysoft OOB support. DIR is the OOB base install directory, defaults to /usr/local/easysoft/oob/client.

--with-unixODBC[=DIR]

Include unixODBC support. DIR is the unixODBC base install directory, defaults to /usr/local.

--with-openlink[=DIR]

Include OpenLink ODBC support. DIR is the OpenLink base install directory, defaults to /usr/local. This is the same as iODBC.

--with-dbmaker[=DIR]

Include DBMaker support. DIR is the DBMaker base install directory, defaults to where the latest version of DBMaker is installed (such as /home/dbmaker/3.6).

Versiunea PHP pentru Windows sus?ine implicit aceasta extensie. Nu este nevoie sa încarca?i extensii suplimentare pentru a putea utiliza aceste func?ii.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Unified ODBC Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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

Nota: Entries marked with * are not implemented yet.

Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

În cazul utilizarii unui integer, valoarea este masurata în octe?i. De asemenea poate fi utilizata nota?ia prescurtata, dupa cum este descris în acest 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).

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

This extension defines two resource types: an ODBC connection identifier and an ODBC result identifier.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
Tipurile resurselor
Func?ii ODBC
ODBC


Func?ii ODBC

Cuprins

  • 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 — Pseudonim pentru 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 — Pseudonim pentru 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
Constante predefinite
odbc_autocommit
ODBC


Toggle autocommit behaviour

Func?ii ODBC
odbc_binmode
Func?ii ODBC
PHP Manual

odbc_autocommit

(PHP 4, PHP 5, PHP 7)

odbc_autocommit — Toggle autocommit behaviour

Descrierea

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.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

OnOff

If OnOff is TRUE, auto-commit is enabled, if it is FALSE auto-commit is disabled.

Valorile întoarse

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.

A se vedea ?i

  • odbc_commit() - Commit an ODBC transaction
  • odbc_rollback() - Rollback a transaction

Func?ii ODBC
odbc_binmode
Func?ii ODBC


Handling of binary column data

odbc_autocommit
odbc_close_all
Func?ii ODBC
PHP Manual

odbc_binmode

(PHP 4, PHP 5, PHP 7)

odbc_binmode — Handling of binary column data

Descrierea

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.

Parametri

result_id

The result identifier.

If result_id is 0, the settings apply as default for new results.

Nota: 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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

odbc_autocommit
odbc_close_all
Func?ii ODBC


Close all ODBC connections

odbc_binmode
odbc_close
Func?ii ODBC
PHP Manual

odbc_close_all

(PHP 4, PHP 5, PHP 7)

odbc_close_all — Close all ODBC connections

Descrierea

void odbc_close_all ( void )

odbc_close_all() will close down all connections to database server(s).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Nota:

This function will fail if there are open transactions on a connection. This connection will remain open in this case.

odbc_binmode
odbc_close
Func?ii ODBC


Close an ODBC connection

odbc_close_all
odbc_columnprivileges
Func?ii ODBC
PHP Manual

odbc_close

(PHP 4, PHP 5, PHP 7)

odbc_close — Close an ODBC connection

Descrierea

void odbc_close ( resource $connection_id )

Closes down the connection to the database server.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Nota:

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
Func?ii ODBC


Lists columns and associated privileges for the given table

odbc_close
odbc_columns
Func?ii ODBC
PHP Manual

odbc_columnprivileges

(PHP 4, PHP 5, PHP 7)

odbc_columnprivileges — Lists columns and associated privileges for the given table

Descrierea

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.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

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).

Valorile întoarse

Returns an ODBC result identifier sau FALSE în cazul e?ecului. 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
Func?ii ODBC


Lists the column names in specified tables

odbc_columnprivileges
odbc_commit
Func?ii ODBC
PHP Manual

odbc_columns

(PHP 4, PHP 5, PHP 7)

odbc_columns — Lists the column names in specified tables

Descrierea

resource odbc_columns ( resource $connection_id [, string $qualifier [, string $schema [, string $table_name [, string $column_name ]]]] )

Lists all columns in the requested range.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

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).

Valorile întoarse

Returns an ODBC result identifier sau FALSE în cazul e?ecului.

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.

A se vedea ?i

  • odbc_columnprivileges() - Lists columns and associated privileges for the given table to retrieve associated privileges

odbc_columnprivileges
odbc_commit
Func?ii ODBC


Commit an ODBC transaction

odbc_columns
odbc_connect
Func?ii ODBC
PHP Manual

odbc_commit

(PHP 4, PHP 5, PHP 7)

odbc_commit — Commit an ODBC transaction

Descrierea

bool odbc_commit ( resource $connection_id )

Commits all pending transactions on the connection.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

odbc_columns
odbc_connect
Func?ii ODBC


Connect to a datasource

odbc_commit
odbc_cursor
Func?ii ODBC
PHP Manual

odbc_connect

(PHP 4, PHP 5, PHP 7)

odbc_connect — Connect to a datasource

Descrierea

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.

Parametri

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

Valorile întoarse

Returns an ODBC connection or (FALSE) on error.

Exemple

Example #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" , '', '');
?>

A se vedea ?i

  • For persistent connections: odbc_pconnect() - Open a persistent database connection

odbc_commit
odbc_cursor
Func?ii ODBC


Get cursorname

odbc_connect
odbc_data_source
Func?ii ODBC
PHP Manual

odbc_cursor

(PHP 4, PHP 5, PHP 7)

odbc_cursor — Get cursorname

Descrierea

string odbc_cursor ( resource $result_id )

Gets the cursorname for the given result_id.

Parametri

result_id

The result identifier.

Valorile întoarse

Returns the cursor name, as a string.

odbc_connect
odbc_data_source
Func?ii ODBC


Returns information about a current connection

odbc_cursor
odbc_do
Func?ii ODBC
PHP Manual

odbc_data_source

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

odbc_data_source — Returns information about a current connection

Descrierea

array odbc_data_source ( resource $connection_id , int $fetch_type )

This function will return the list of available DSN (after calling it several times).

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

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.

Valorile întoarse

Returns FALSE on error, and an array upon success.

odbc_cursor
odbc_do
Func?ii ODBC


Pseudonim pentru odbc_exec

odbc_data_source
odbc_error
Func?ii ODBC
PHP Manual

odbc_do

(PHP 4, PHP 5, PHP 7)

odbc_do — Pseudonim pentru odbc_exec()

Descrierea

Aceasta func?ie este pseudonim pentru: odbc_exec().

odbc_data_source
odbc_error
Func?ii ODBC


Get the last error code

odbc_do
odbc_errormsg
Func?ii ODBC
PHP Manual

odbc_error

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

odbc_error — Get the last error code

Descrierea

string odbc_error ([ resource $connection_id ] )

Returns a six-digit ODBC state, or an empty string if there has been no errors.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

Valorile întoarse

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).

A se vedea ?i

  • odbc_errormsg() - Get the last error message
  • odbc_exec() - Prepare and execute an SQL statement

odbc_do
odbc_errormsg
Func?ii ODBC


Get the last error message

odbc_error
odbc_exec
Func?ii ODBC
PHP Manual

odbc_errormsg

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

odbc_errormsg — Get the last error message

Descrierea

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.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

Valorile întoarse

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).

A se vedea ?i

  • odbc_error() - Get the last error code
  • odbc_exec() - Prepare and execute an SQL statement

odbc_error
odbc_exec
Func?ii ODBC


Prepare and execute an SQL statement

odbc_errormsg
odbc_execute
Func?ii ODBC
PHP Manual

odbc_exec

(PHP 4, PHP 5, PHP 7)

odbc_exec — Prepare and execute an SQL statement

Descrierea

resource odbc_exec ( resource $connection_id , string $query_string [, int $flags ] )

Sends an SQL statement to the database server.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

query_string

The SQL statement.

flags

This parameter is currently not used.

Valorile întoarse

Returns an ODBC result identifier if the SQL command was executed successfully, or FALSE on error.

A se vedea ?i

  • odbc_prepare() - Prepares a statement for execution
  • odbc_execute() - Execute a prepared statement

odbc_errormsg
odbc_execute
Func?ii ODBC


Execute a prepared statement

odbc_exec
odbc_fetch_array
Func?ii ODBC
PHP Manual

odbc_execute

(PHP 4, PHP 5, PHP 7)

odbc_execute — Execute a prepared statement

Descrierea

bool odbc_execute ( resource $result_id [, array $parameters_array ] )

Executes a statement prepared with odbc_prepare().

Parametri

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()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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).

Istoricul schimbarilor

Versiune | Descriere
4.2.0 | File reading is now subject to modul securizat and open-basedir restrictions in parameters_array.

A se vedea ?i

  • odbc_prepare() - Prepares a statement for execution

odbc_exec
odbc_fetch_array
Func?ii ODBC


Fetch a result row as an associative array

odbc_execute
odbc_fetch_into
Func?ii ODBC
PHP Manual

odbc_fetch_array

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

odbc_fetch_array — Fetch a result row as an associative array

Descrierea

array odbc_fetch_array ( resource $result [, int $rownumber ] )

Fetch an associative array from an ODBC query.

Parametri

result

The result resource from odbc_exec().

rownumber

Optionally choose which row number to retrieve.

Valorile întoarse

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Note

Nota: This function exists when compiled with DBMaker, IBM DB2 or UnixODBC support.

A se vedea ?i

  • 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
Func?ii ODBC


Fetch one result row into array

odbc_fetch_array
odbc_fetch_object
Func?ii ODBC
PHP Manual

odbc_fetch_into

(PHP 4, PHP 5, PHP 7)

odbc_fetch_into — Fetch one result row into array

Descrierea

int odbc_fetch_into ( resource $result_id , array &$result_array [, int $rownumber ] )

Fetch one result row into array.

Parametri

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.

Valorile întoarse

Returns the number of columns in the result; FALSE on error.

Exemple

Example #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
Func?ii ODBC


Fetch a result row as an object

odbc_fetch_into
odbc_fetch_row
Func?ii ODBC
PHP Manual

odbc_fetch_object

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

odbc_fetch_object — Fetch a result row as an object

Descrierea

object odbc_fetch_object ( resource $result [, int $rownumber ] )

Fetch an object from an ODBC query.

Parametri

result

The result resource from odbc_exec().

rownumber

Optionally choose which row number to retrieve.

Valorile întoarse

Returns an object that corresponds to the fetched row, or FALSE if there are no more rows.

Note

Nota: This function exists when compiled with DBMaker, IBM DB2 or UnixODBC support.

A se vedea ?i

  • 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
Func?ii ODBC


Fetch a row

odbc_fetch_object
odbc_field_len
Func?ii ODBC
PHP Manual

odbc_fetch_row

(PHP 4, PHP 5, PHP 7)

odbc_fetch_row — Fetch a row

Descrierea

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().

Parametri

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.

Valorile întoarse

Returns TRUE if there was a row, FALSE otherwise.

odbc_fetch_object
odbc_field_len
Func?ii ODBC


Get the length (precision) of a field

odbc_fetch_row
odbc_field_name
Func?ii ODBC
PHP Manual

odbc_field_len

(PHP 4, PHP 5, PHP 7)

odbc_field_len — Get the length (precision) of a field

Descrierea

int odbc_field_len ( resource $result_id , int $field_number )

Gets the length of the field referenced by number in the given result identifier.

Parametri

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Valorile întoarse

Returns the field length, or FALSE on error.

A se vedea ?i

  • odbc_field_scale() - Get the scale of a field to get the scale of a floating point number

odbc_fetch_row
odbc_field_name
Func?ii ODBC


Get the columnname

odbc_field_len
odbc_field_num
Func?ii ODBC
PHP Manual

odbc_field_name

(PHP 4, PHP 5, PHP 7)

odbc_field_name — Get the columnname

Descrierea

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.

Parametri

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Valorile întoarse

Returns the field name as a string, or FALSE on error.

odbc_field_len
odbc_field_num
Func?ii ODBC


Return column number

odbc_field_name
odbc_field_precision
Func?ii ODBC
PHP Manual

odbc_field_num

(PHP 4, PHP 5, PHP 7)

odbc_field_num — Return column number

Descrierea

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.

Parametri

result_id

The result identifier.

field_name

The field name.

Valorile întoarse

Returns the field number as a integer, or FALSE on error. Field numbering starts at 1.

odbc_field_name
odbc_field_precision
Func?ii ODBC


Pseudonim pentru odbc_field_len

odbc_field_num
odbc_field_scale
Func?ii ODBC
PHP Manual

odbc_field_precision

(PHP 4, PHP 5, PHP 7)

odbc_field_precision — Pseudonim pentru odbc_field_len()

Descrierea

Aceasta func?ie este pseudonim pentru: odbc_field_len().

A se vedea ?i

  • odbc_field_scale() - Get the scale of a field to get the scale of a floating point number.

odbc_field_num
odbc_field_scale
Func?ii ODBC


Get the scale of a field

odbc_field_precision
odbc_field_type
Func?ii ODBC
PHP Manual

odbc_field_scale

(PHP 4, PHP 5, PHP 7)

odbc_field_scale — Get the scale of a field

Descrierea

int odbc_field_scale ( resource $result_id , int $field_number )

Gets the scale of the field referenced by number in the given result identifier.

Parametri

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Valorile întoarse

Returns the field scale as a integer, or FALSE on error.

odbc_field_precision
odbc_field_type
Func?ii ODBC


Datatype of a field

odbc_field_scale
odbc_foreignkeys
Func?ii ODBC
PHP Manual

odbc_field_type

(PHP 4, PHP 5, PHP 7)

odbc_field_type — Datatype of a field

Descrierea

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.

Parametri

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Valorile întoarse

Returns the field type as a string, or FALSE on error.

odbc_field_scale
odbc_foreignkeys
Func?ii ODBC


Retrieves a list of foreign keys

odbc_field_type
odbc_free_result
Func?ii ODBC
PHP Manual

odbc_foreignkeys

(PHP 4, PHP 5, PHP 7)

odbc_foreignkeys — Retrieves a list of foreign keys

Descrierea

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

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

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.

Valorile întoarse

Returns an ODBC result identifier sau FALSE în cazul e?ecului.

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
Func?ii ODBC


Free resources associated with a result

odbc_foreignkeys
odbc_gettypeinfo
Func?ii ODBC
PHP Manual

odbc_free_result

(PHP 4, PHP 5, PHP 7)

odbc_free_result — Free resources associated with a result

Descrierea

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.

Parametri

result_id

The result identifier.

Valorile întoarse

Always returns TRUE.

Note

Nota:

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
Func?ii ODBC


Retrieves information about data types supported by the data source

odbc_free_result
odbc_longreadlen
Func?ii ODBC
PHP Manual

odbc_gettypeinfo

(PHP 4, PHP 5, PHP 7)

odbc_gettypeinfo — Retrieves information about data types supported by the data source

Descrierea

resource odbc_gettypeinfo ( resource $connection_id [, int $data_type ] )

Retrieves information about data types supported by the data source.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

data_type

The data type, which can be used to restrict the information to a single data type.

Valorile întoarse

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
Func?ii ODBC


Handling of LONG columns

odbc_gettypeinfo
odbc_next_result
Func?ii ODBC
PHP Manual

odbc_longreadlen

(PHP 4, PHP 5, PHP 7)

odbc_longreadlen — Handling of LONG columns

Descrierea

bool odbc_longreadlen ( resource $result_id , int $length )

Enables handling of LONG and LONGVARBINARY columns.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

Handling of LONGVARBINARY columns is also affected by odbc_binmode().

odbc_gettypeinfo
odbc_next_result
Func?ii ODBC


Checks if multiple results are available

odbc_longreadlen
odbc_num_fields
Func?ii ODBC
PHP Manual

odbc_next_result

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

odbc_next_result — Checks if multiple results are available

Descrierea

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.

Parametri

result_id

The result identifier.

Valorile întoarse

Returns TRUE if there are more result sets, FALSE otherwise.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

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
Func?ii ODBC


Number of columns in a result

odbc_next_result
odbc_num_rows
Func?ii ODBC
PHP Manual

odbc_num_fields

(PHP 4, PHP 5, PHP 7)

odbc_num_fields — Number of columns in a result

Descrierea

int odbc_num_fields ( resource $result_id )

Gets the number of fields (columns) in an ODBC result.

Parametri

result_id

The result identifier returned by odbc_exec().

Valorile întoarse

Returns the number of fields, or -1 on error.

odbc_next_result
odbc_num_rows
Func?ii ODBC


Number of rows in a result

odbc_num_fields
odbc_pconnect
Func?ii ODBC
PHP Manual

odbc_num_rows

(PHP 4, PHP 5, PHP 7)

odbc_num_rows — Number of rows in a result

Descrierea

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.

Parametri

result_id

The result identifier returned by odbc_exec().

Valorile întoarse

Returns the number of rows in an ODBC result. This function will return -1 on error.

Note

Nota:

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
Func?ii ODBC


Open a persistent database connection

odbc_num_rows
odbc_prepare
Func?ii ODBC
PHP Manual

odbc_pconnect

(PHP 4, PHP 5, PHP 7)

odbc_pconnect — Open a persistent database connection

Descrierea

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.

Parametri

See odbc_connect() for details.

Valorile întoarse

Returns an ODBC connection id or 0 (FALSE) on error.

Note

Nota: Persistent connections have no effect if PHP is used as a CGI program.

A se vedea ?i

  • odbc_connect() - Connect to a datasource
  • Persistent Database Connections

odbc_num_rows
odbc_prepare
Func?ii ODBC


Prepares a statement for execution

odbc_pconnect
odbc_primarykeys
Func?ii ODBC
PHP Manual

odbc_prepare

(PHP 4, PHP 5, PHP 7)

odbc_prepare — Prepares a statement for execution

Descrierea

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.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

query_string

The query string statement being prepared.

Valorile întoarse

Returns an ODBC result identifier if the SQL command was prepared successfully. Returns FALSE on error.

Exemple

Example #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).

A se vedea ?i

  • odbc_execute() - Execute a prepared statement

odbc_pconnect
odbc_primarykeys
Func?ii ODBC


Gets the primary keys for a table

odbc_prepare
odbc_procedurecolumns
Func?ii ODBC
PHP Manual

odbc_primarykeys

(PHP 4, PHP 5, PHP 7)

odbc_primarykeys — Gets the primary keys for a table

Descrierea

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.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

qualifier

owner

table

Valorile întoarse

Returns an ODBC result identifier sau FALSE în cazul e?ecului.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • COLUMN_NAME
  • KEY_SEQ
  • PK_NAME

odbc_prepare
odbc_procedurecolumns
Func?ii ODBC


Retrieve information about parameters to procedures

odbc_primarykeys
odbc_procedures
Func?ii ODBC
PHP Manual

odbc_procedurecolumns

(PHP 4, PHP 5, PHP 7)

odbc_procedurecolumns — Retrieve information about parameters to procedures

Descrierea

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.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

qualifier

The qualifier.

owner

The owner. Acest parametru accepta urmatoarele ?abloane de cautare: "%" pentru a se potrivi cu zero sau mai multe caractere ?i "_" pentru a se potrivi cu un singur caracter.

proc

The proc. Acest parametru accepta urmatoarele ?abloane de cautare: "%" pentru a se potrivi cu zero sau mai multe caractere ?i "_" pentru a se potrivi cu un singur caracter.

column

The column. Acest parametru accepta urmatoarele ?abloane de cautare: "%" pentru a se potrivi cu zero sau mai multe caractere ?i "_" pentru a se potrivi cu un singur caracter.

Valorile întoarse

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 sau FALSE în cazul e?ecului.

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
Func?ii ODBC


Get the list of procedures stored in a specific data source

odbc_procedurecolumns
odbc_result_all
Func?ii ODBC
PHP Manual

odbc_procedures

(PHP 4, PHP 5, PHP 7)

odbc_procedures — Get the list of procedures stored in a specific data source

Descrierea

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.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

qualifier

The qualifier.

owner

The owner. Acest parametru accepta urmatoarele ?abloane de cautare: "%" pentru a se potrivi cu zero sau mai multe caractere ?i "_" pentru a se potrivi cu un singur caracter.

name

The name. Acest parametru accepta urmatoarele ?abloane de cautare: "%" pentru a se potrivi cu zero sau mai multe caractere ?i "_" pentru a se potrivi cu un singur caracter.

Valorile întoarse

Returns an ODBC result identifier containing the information sau FALSE în cazul e?ecului.

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
Func?ii ODBC


Print result as HTML table

odbc_procedures
odbc_result
Func?ii ODBC
PHP Manual

odbc_result_all

(PHP 4, PHP 5, PHP 7)

odbc_result_all — Print result as HTML table

Descrierea

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.

Parametri

result_id

The result identifier.

format

Additional overall table formatting.

Valorile întoarse

Returns the number of rows in the result or FALSE on error.

odbc_procedures
odbc_result
Func?ii ODBC


Get result data

odbc_result_all
odbc_rollback
Func?ii ODBC
PHP Manual

odbc_result

(PHP 4, PHP 5, PHP 7)

odbc_result — Get result data

Descrierea

mixed odbc_result ( resource $result_id , mixed $field )

Get result data

Parametri

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.

Valorile întoarse

Returns the string contents of the field, FALSE on error, NULL for NULL data, or TRUE for binary data.

Exemple

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.

Example #1 odbc_result() examples

<?php
$item_3   = odbc_result($Query_ID, 3);
$item_val = odbc_result($Query_ID, "val");
?>

Note

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
Func?ii ODBC


Rollback a transaction

odbc_result
odbc_setoption
Func?ii ODBC
PHP Manual

odbc_rollback

(PHP 4, PHP 5, PHP 7)

odbc_rollback — Rollback a transaction

Descrierea

bool odbc_rollback ( resource $connection_id )

Rolls back all pending statements on the connection.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

odbc_result
odbc_setoption
Func?ii ODBC


Adjust ODBC settings

odbc_rollback
odbc_specialcolumns
Func?ii ODBC
PHP Manual

odbc_setoption

(PHP 4, PHP 5, PHP 7)

odbc_setoption — Adjust ODBC settings

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii ODBC


Retrieves special columns

odbc_setoption
odbc_statistics
Func?ii ODBC
PHP Manual

odbc_specialcolumns

(PHP 4, PHP 5, PHP 7)

odbc_specialcolumns — Retrieves special columns

Descrierea

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.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

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.

Valorile întoarse

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
Func?ii ODBC


Retrieve statistics about a table

odbc_specialcolumns
odbc_tableprivileges
Func?ii ODBC
PHP Manual

odbc_statistics

(PHP 4, PHP 5, PHP 7)

odbc_statistics — Retrieve statistics about a table

Descrierea

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.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

qualifier

The qualifier.

owner

The owner.

table_name

The table name.

unique

The unique attribute.

accuracy

The accuracy.

Valorile întoarse

Returns an ODBC result identifier sau FALSE în cazul e?ecului.

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
Func?ii ODBC


Lists tables and the privileges associated with each table

odbc_statistics
odbc_tables
Func?ii ODBC
PHP Manual

odbc_tableprivileges

(PHP 4, PHP 5, PHP 7)

odbc_tableprivileges — Lists tables and the privileges associated with each table

Descrierea

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.

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

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)

Valorile întoarse

An ODBC result identifier sau FALSE în cazul e?ecului.

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
Func?ii ODBC


Get the list of table names stored in a specific data source

odbc_tableprivileges
PDO
Func?ii ODBC
PHP Manual

odbc_tables

(PHP 4, PHP 5, PHP 7)

odbc_tables — Get the list of table names stored in a specific data source

Descrierea

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.)

Parametri

connection_id

Identificatorul conexiunii ODBC, accesa?i odbc_connect() pentru detalii.

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.

Valorile întoarse

Returns an ODBC result identifier containing the information sau FALSE în cazul e?ecului.

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.

A se vedea ?i

  • odbc_tableprivileges() - Lists tables and the privileges associated with each table

odbc_tableprivileges
PDO
Func?ii ODBC


PHP Data Objects

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • 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 (PDO) — Firebird 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
Introducere
Nivele de abstractizare


Introducere

PHP Data Objects (PDO) este o extensie PHP ce define?te o interfa?a u?oara, consistenta pentru accesarea bazelor de date în PHP. Fiecare driver pentru baza de date, care implementeaza interfa?a PDO, poate expune caracteristici specifice bazei de date prin intermediul unor func?ii obi?nuite pentru extindere. Re?ine?i ca dvs. nu pute?i efectua careva opera?iuni cu baza de date folosind doar extensia PDO; trebuie sa utiliza?i un driver PDO specific bazei de date pentru a accesa serverul de baze de date.

PDO ofera un nivel de abstractizare pentru accesarea datelor, ceea ce înseamna ca indiferent de ce baza de date utiliza?i, ve?i folosi acelea?i func?ii pentru a trimite interogari ?i pentru a primi date. PDO nu ofera o abstrac?ie a bazei de date; nu rescrie SQL ?i nici nu emuleaza caracteristici absente în unele baze de date. Ar trebui sa utiliza?i un strat de abstractizare complet, pe deplin dezvoltat, daca ave?i nevoie de aceasta facilitate.

De la versiunea PHP 5.1 PDO este integrat cu PHP, ?i este disponibil ca extensie PECL pentru PHP 5.0; PDO necesita noile caracteristici OOP în nucleul PHP 5, ?i astfel nu va rula cu versiunile anterioare ale PHP.

PDO
Instalarea / configurarea
PDO


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
PDO


Instalarea

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.

    Nota:

    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

    Nota:

    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.

Nota:

Remember that after making changes to your php.ini file you will need to restart PHP for your new configuration directives to take effect.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

PDO Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
pdo.dsn.* |  | php.ini only |

Iata o explica?ie pe scurt a directivelor de configurare.

pdo.dsn.* string

Defines DSN alias. See PDO::__construct() for thorough explanation.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Avertizare

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. Not valid inside PDOStatement::fetchAll().
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.

Nota: 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)
Allows completely customize the way data is treated on the fly (only valid inside PDOStatement::fetchAll()).
PDO::FETCH_GROUP (integer)
Group return by values. Usually combined with PDO::FETCH_COLUMN or PDO::FETCH_KEY_PAIR.
PDO::FETCH_UNIQUE (integer)
Fetch only the unique values.
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. Since PHP 5.3.0 the class constructor is never called if this flag is set.
PDO::FETCH_PROPS_LATE (integer)
Call the constructor before setting properties. 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.

Example #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.
Tipurile resurselor
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).

Example #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().

Example #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();
}
?>

Avertizare

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.

Nota: If there are still other references to this PDO instance (such as from a PDOStatement instance, or from other variables referencing the same PDO instance), these have to be removed also (for instance, by assigning NULL to the variable that references the PDOStatement).

Example #3 Closing a connection

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use the connection here
$sth = $dbh->query('SELECT * FROM foo');

// and now we're done; close it
$sth = null;
$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.

Example #4 Persistent connections

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));
?>

Nota:

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.

Nota:

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.

Constante predefinite
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.

Avertizare

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.

Avertizare

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.

Example #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.

Example #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();
?>

Example #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();
?>

Example #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);
  }
}
?>

Example #4 Calling a stored procedure with an output parameter

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.

<?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";
?>

Example #5 Calling a stored procedure with an input/output parameter

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.

<?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";
?>

Example #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.

Example #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();
}

?>

Nota:

PDO::__construct() will always throw a PDOException if the connection fails regardless of which PDO::ATTR_ERRMODE is currently set. Uncaught Exceptions are fatal.

Example #2 Create a PDO instance and set the error mode from the constructor

<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'googleguy';
$password = 'googleguy';

/*
    Using try/catch around the constructor is still valid even though we set the ERRMODE to WARNING since
    PDO::__construct will always throw a PDOException if the connection fails.
*/
try {
    $dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
    exit;
}

// This will cause PDO to throw an error of level E_WARNING instead of an exception (when the table doesn't exist)
$dbh->query("SELECT wrongcolumn FROM wrongtable");
?>

Exemplul de mai sus va afi?a:

Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.wrongtable' doesn't exist in
/tmp/pdo_test.php on line 18

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.

Example #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);
?>

Example #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();
?>

Example #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);

$db->beginTransaction();
$stmt->execute();
$db->commit();
?>

Errors and error handling
PDO
PDO


The PDO class

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

Introducere

Represents a connection between PHP and a database server.

Sinopsisul clasei

PDO {
public __construct ( string $dsn [, string $username [, string $password [, array $options ]]] )
public bool beginTransaction ( void )
public bool commit ( void )
public mixed errorCode ( void )
public array errorInfo ( void )
public int exec ( string $statement )
public mixed getAttribute ( int $attribute )
public static array getAvailableDrivers ( void )
public bool inTransaction ( void )
public string lastInsertId ([ string $name = NULL ] )
public PDOStatement prepare ( string $statement [, array $driver_options = array() ] )
public PDOStatement query ( string $statement )
public string quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] )
public bool rollBack ( void )
public bool setAttribute ( int $attribute , mixed $value )
}

Cuprins

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDO::beginTransaction — Initiates a transaction

Descrierea

public 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws a PDOException if there is already a transaction started or the driver does not support transactions.

Nota: O excep?ie este emisa chiar atunci când atributul PDO::ATTR_ERRMODE nu are valoarea PDO::ERRMODE_EXCEPTION.

Exemple

Example #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 */
?>

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDO::commit — Commits a transaction

Descrierea

public 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws a PDOException if there is no active transaction.

Nota: O excep?ie este emisa chiar atunci când atributul PDO::ATTR_ERRMODE nu are valoarea PDO::ERRMODE_EXCEPTION.

Exemple

Example #1 Committing a basic transaction

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Insert multiple records on an all-or-nothing basis */
$sql = 'INSERT INTO fruit
    (name, colour, calories)
    VALUES (?, ?, ?)';

$sth = $dbh->prepare($sql);

foreach ($fruits as $fruit) {
    $sth->execute(array(
        $fruit->name,
        $fruit->colour,
        $fruit->calories,
    ));
}

/* Commit the changes */
$dbh->commit();

/* Database connection is now back in autocommit mode */
?>

Example #2 Committing a DDL 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 */
?>

Nota: Not all databases will allow transactions to operate on DDL statements: some will generate errors, whereas others (including MySQL) will automatically commit the transaction after the first DDL statement has been encountered.

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDO::__construct — Creates a PDO instance representing a connection to a database

Descrierea

public PDO::__construct ( string $dsn [, string $username [, string $password [, array $options ]]] )

Creates a PDO instance to represent a connection to the requested database.

Parametri

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.

Nota:

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.

options

A key=>value array of driver-specific connection options.

Valorile întoarse

Returns a PDO object on success.

Erori/Excep?ii

PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails.

Exemple

Example #1 Create a PDO instance via driver invocation

<?php
/* Connect to a MySQL 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();
}

?>

Example #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();
}

?>

Example #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();
}

?>

Nota:

Before PHP5.3, a class which extends PDO and implements __call magic will always receive lower case $method.

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, PHP 7, PECL pdo >= 0.1.0)

PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle

Descrierea

public mixed PDO::errorCode ( void )

Valorile întoarse

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.

Exemple

Example #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(): ", $dbh->errorCode();
?>

Exemplul de mai sus va afi?a:

PDO::errorCode(): 42S02

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle

Descrierea

public array PDO::errorInfo ( void )

Valorile întoarse

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.

Nota:

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.

Exemple

Example #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());
}
?>

Exemplul de mai sus va afi?a:

PDO::errorInfo():
Array
(
    [0] => HY000
    [1] => 1
    [2] => near "bogus": syntax error
)

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDO::exec — Execute an SQL statement and return the number of affected rows

Descrierea

public 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().

Parametri

statement

The SQL statement to prepare and execute.

Data inside the query should be properly escaped.

Valorile întoarse

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.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

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));
?>

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

Deleted 1 rows.

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.2.0)

PDO::getAttribute — Retrieve a database connection attribute

Descrierea

public 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.

Parametri

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

Valorile întoarse

A successful call returns the value of the requested PDO attribute. An unsuccessful call returns null.

Exemple

Example #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";
}
?>

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 1.0.3)

PDO::getAvailableDrivers — Return an array of available PDO drivers

Descrierea

public static 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().

Valorile întoarse

PDO::getAvailableDrivers() returns an array of PDO driver names. If no drivers are available, it returns an empty array.

Exemple

Example #1 A PDO::getAvailableDrivers() example

<?php
print_r(PDO::getAvailableDrivers());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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, PHP 7)

PDO::inTransaction — Checks if inside a transaction

Descrierea

public bool PDO::inTransaction ( void )

Checks if a transaction is currently active within the driver. This method only works for database drivers that support transactions.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7, PECL pdo >= 0.1.0)

PDO::lastInsertId — Returns the ID of the last inserted row or sequence value

Descrierea

public 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.

Nota:

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.

Parametri

name

Name of the sequence object from which the ID should be returned.

Valorile întoarse

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, PHP 7, PECL pdo >= 0.1.0)

PDO::prepare — Prepares a statement for execution and returns a statement object

Descrierea

public 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 more than once in a prepared statement, unless emulation mode is on.

Nota:

Parameter markers can represent a complete data literal only. Neither part of literal, nor keyword, nor identifier, nor whatever arbitrary query part can be bound using parameters. For example, you cannot bind multiple values to a single parameter in 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.

Parametri

statement

This must be a valid SQL statement template 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.

Valorile întoarse

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).

Nota:

Emulated prepared statements does not communicate with the database server so PDO::prepare() does not check the statement.

Exemple

Example #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();
?>

Example #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();
?>

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.2.0)

PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object

Descrierea

public PDOStatement PDO::query ( string $statement )
public PDOStatement PDO::query ( string $statement , int $PDO::FETCH_COLUMN , int $colno )
public PDOStatement PDO::query ( string $statement , int $PDO::FETCH_CLASS , string $classname , array $ctorargs )
public 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().

Nota:

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.

Parametri

statement

The SQL statement to prepare and execute.

Data inside the query should be properly escaped.

Valorile întoarse

PDO::query() returns a PDOStatement object, or FALSE on failure.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

apple   red     150
banana  yellow  250
kiwi    brown   75
lemon   yellow  25
orange  orange  300
pear    green   150
watermelon      pink    90

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.2.1)

PDO::quote — Quotes a string for use in a query.

Descrierea

public 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.

Precautie

Security: the default character set

The character set must be set either on the server level, or within the database connection itself (depending on the driver) for it to affect PDO::quote(). See the driver-specific documentation for more information.

Parametri

string

The string to be quoted.

parameter_type

Provides a data type hint for drivers that have alternate quoting styles.

Valorile întoarse

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.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

Unquoted string: Nice
Quoted string: 'Nice'

Example #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";
?>

Exemplul de mai sus va afi?a:

Unquoted string: Naughty ' string
Quoted string: 'Naughty '' string'

Example #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";
?>

Exemplul de mai sus va afi?a:

Unquoted string: Co'mpl''ex "st'"ring
Quoted string: 'Co''mpl''''ex "st''"ring'

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDO::rollBack — Rolls back a transaction

Descrierea

public bool PDO::rollBack ( void )

Rolls back the current transaction, as initiated by PDO::beginTransaction().

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws a PDOException if there is no active transaction.

Nota: O excep?ie este emisa chiar atunci când atributul PDO::ATTR_ERRMODE nu are valoarea PDO::ERRMODE_EXCEPTION.

Exemple

Example #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 */
?>

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDO::setAttribute — Set an attribute

Descrierea

public 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 its 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 and emulated prepares are supported by the driver), 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDO::rollBack
PDOStatement
PDO


The PDOStatement class

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 1.0.0)

Introducere

Represents a prepared statement and, after the statement is executed, an associated result set.

Sinopsisul clasei

PDOStatement implements Traversable {
/* Proprieta?i */
readonly string $queryString;
/* Metode */
public bool bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed $driverdata ]]] )
public bool bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )
public bool bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )
public bool closeCursor ( void )
public int columnCount ( void )
public void debugDumpParams ( void )
public string errorCode ( void )
public array errorInfo ( void )
public bool execute ([ array $input_parameters ] )
public mixed fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] )
public array fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] )
public mixed fetchColumn ([ int $column_number = 0 ] )
public mixed fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] )
public mixed getAttribute ( int $attribute )
public array getColumnMeta ( int $column )
public bool nextRowset ( void )
public int rowCount ( void )
public bool setAttribute ( int $attribute , mixed $value )
public bool setFetchMode ( int $mode )
}

Proprieta?i

queryString

Used query string.

Cuprins

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::bindColumn — Bind a column to a PHP variable

Descrierea

public 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.

Nota:

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

apple   red     150
banana  yellow  175
kiwi    green   75
orange  orange  150
mango   red     200
strawberry      red     25

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::bindParam — Binds a parameter to the specified variable name

Descrierea

public 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 used 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.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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();
?>

Example #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();
?>

Example #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");
?>

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 1.0.0)

PDOStatement::bindValue — Binds a value to a parameter

Descrierea

public 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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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();
?>

Example #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();
?>

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.9.0)

PDOStatement::closeCursor — Closes the cursor, enabling the statement to be executed again.

Descrierea

public 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);
?>

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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();
?>

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.2.0)

PDOStatement::columnCount — Returns the number of columns in the result set

Descrierea

public 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().

Valorile întoarse

Returns the number of columns in the result set represented by the PDOStatement object, even if the result set is empty. If there is no result set, PDOStatement::columnCount() returns 0.

Exemple

Example #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");

?>

Exemplul de mai sus va afi?a:

Before execute(), result set has 0 columns (should be 0)
After execute(), result set has 2 columns (should be 2)

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.9.0)

PDOStatement::debugDumpParams — Dump an SQL prepared command

Descrierea

public void PDOStatement::debugDumpParams ( void )

Dumps the information 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 key name or position, their name, their position in the query (if this is supported by the PDO driver, otherwise, it will be -1), type (param_type) as an integer, and a boolean value is_param.

This is a debug function, which dumps the data directly to the normal output.

Sfat

La fel ca ?i orice program/script ce afi?eaza rezultatele direct în browser, func?iile de control al ie?irilor pot fi utilizate pentru a capta ie?irea acestei func?ii ?i de a o salva într-un string (spre exemplu).

This will only dump the parameters in the statement at the moment of the dump. Extra parameters are not stored in the statement, and not displayed.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a:

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

Example #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();

?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::errorCode — Fetch the SQLSTATE associated with the last operation on the statement handle

Descrierea

public string PDOStatement::errorCode ( void )

Valorile întoarse

Identical to PDO::errorCode(), except that PDOStatement::errorCode() only retrieves error codes for operations performed with PDOStatement objects.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

PDOStatement::errorCode(): 42S02

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::errorInfo — Fetch extended error information associated with the last operation on the statement handle

Descrierea

public array PDOStatement::errorInfo ( void )

Valorile întoarse

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.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

PDOStatement::errorInfo():
Array
(
    [0] => 42S02
    [1] => -204
    [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
)

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::execute — Executes a prepared statement

Descrierea

public bool PDOStatement::execute ([ array $input_parameters ] )

Execute the prepared statement. If the prepared statement included parameter markers, either:

  • PDOStatement::bindParam() and/or PDOStatement::bindValue() has to be called to bind either variables or values (respectively) to the parameter markers. Bound variables pass their value as input and receive the output value, if any, of their associated parameter markers

  • or an array of input-only parameter values has to be passed

Parametri

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.

Multiple values cannot be bound to a single parameter; for example, it is not allowed to bind two values to a single named parameter in an IN() clause.

Binding more values than specified is not possible; 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #1 Execute a prepared statement with a bound variable and value

<?php
/* Execute a prepared statement by binding a variable and value */
$calories = 150;
$colour = 'gre';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour LIKE :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', "%{$colour}%");
$sth->execute();
?>

Example #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));
?>

Example #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));
?>

Example #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();
?>

Example #5 Execute a prepared statement using array for IN clause

<?php
/* Execute a prepared statement using an array of values for an IN clause */
$params = array(1, 21, 63, 171);
/* Create a string for the parameter placeholders filled to the number of params */
$place_holders = implode(',', array_fill(0, count($params), '?'));

/*
    This prepares the statement with enough unnamed placeholders for every value
    in our $params array. The values of the $params array are then bound to the
    placeholders in the prepared statement when the statement is executed.
    This is not the same thing as using PDOStatement::bindParam() since this
    requires a reference to the variable. PDOStatement::execute() only binds
    by value instead.
*/
$sth = $dbh->prepare("SELECT id, name FROM contacts WHERE id IN ($place_holders)");
$sth->execute($params);
?>

Note

Nota:

Some drivers require to close cursor before executing next statement.

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::fetch — Fetches the next row from a result set

Descrierea

public 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.

Parametri

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, and calling the constructor afterwards, unless PDO::FETCH_PROPS_LATE is also given. 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_NAMED: returns an array with the same form as PDO::FETCH_ASSOC, except that if there are multiple columns with the same name, the value referred to by that key will be an array of all the values in the row that had that column name

  • 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

  • PDO::FETCH_PROPS_LATE: when used with PDO::FETCH_CLASS, the constructor of the class is called before the properties are assigned from the respective column values.

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.

Valorile întoarse

The return value of this function on success depends on the fetch type. In all cases, FALSE is returned on failure.

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

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

Example #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);
?>

Exemplul de mai sus va afi?a:

Reading forwards:
21    10    5
16    0     5
19    20    10

Reading backwards:
19    20    10
16    0     5
21    10    5

Example #3 Construction order

When objects are fetched via PDO::FETCH_CLASS the object properties are assigned first, and then the constructor of the class is invoked. If PDO::FETCH_PROPS_LATE is also given, this order is reversed, i.e. first the constructor is called, and afterwards the properties are assigned.

<?php
class Person
{
    private $name;

    public function __construct()
    {
        $this->tell();
    }

    public function tell()
    {
        if (isset($this->name)) {
            echo "I am {$this->name}.\n";
        } else {
            echo "I don't have a name yet.\n";
        }
    }
}

$sth = $dbh->query("SELECT * FROM people");
$sth->setFetchMode(PDO::FETCH_CLASS, 'Person');
$person = $sth->fetch();
$person->tell();
$sth->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'Person');
$person = $sth->fetch();
$person->tell();
?>

Exemplul de mai sus va afi?a ceva similar cu:

I am Alice.
I am Alice.
I don't have a name yet.
I am Bob.

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::fetchAll — Returns an array containing all of the result set rows

Descrierea

public array PDOStatement::fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] )

Parametri

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 fetch_argument 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 has 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.

Valorile întoarse

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. An empty array is returned if there are zero results to fetch, or FALSE on failure.

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.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

)

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array(3)
(
    [0] =>
    string(5) => apple
    [1] =>
    string(4) => pear
    [2] =>
    string(10) => watermelon
)

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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"
  }
}

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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"
  }
}

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  [0]=>
  string(12) "apple: green"
  [1]=>
  string(12) "pear: yellow"
  [2]=>
  string(16) "watermelon: pink"
}

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.9.0)

PDOStatement::fetchColumn — Returns a single column from the next row of a result set

Descrierea

public mixed 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.

Nota:

PDOStatement::fetchColumn() should not be used to retrieve boolean columns, as it is impossible to distinguish a value of FALSE from there being no more rows to retrieve. Use PDOStatement::fetch() instead.

Parametri

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.

Valorile întoarse

PDOStatement::fetchColumn() returns a single column from the next row of a result set or FALSE if there are no more rows.

Avertizare

There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data.

Exemple

Example #1 Return first column of the next row

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

print("Fetch the first column from the first row in the result set:\n");
$result = $sth->fetchColumn();
print("name = $result\n");

print("Fetch the second column from the second row in the result set:\n");
$result = $sth->fetchColumn(1);
print("colour = $result\n");
?>

Exemplul de mai sus va afi?a:

Fetch the first column from the first row in the result set:
name = lemon
Fetch the second column from the second row in the result set:
colour = red

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.2.4)

PDOStatement::fetchObject — Fetches the next row and returns it as an object.

Descrierea

public 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.

When an object is fetched, its properties are assigned from respective column values, and afterwards its constructor is invoked.

Parametri

class_name

Name of the created class.

ctor_args

Elements of this array are passed to the constructor.

Valorile întoarse

Returns an instance of the required class with property names that correspond to the column names sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.2.0)

PDOStatement::getAttribute — Retrieve a statement attribute

Descrierea

public 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.

Valorile întoarse

Returns the attribute value.

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.2.0)

PDOStatement::getColumnMeta — Returns metadata for a column in a result set

Descrierea

public array PDOStatement::getColumnMeta ( int $column )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Retrieves the metadata for a 0-indexed column in a result set as an associative array.

Avertizare

Not all PDO drivers support PDOStatement::getColumnMeta().

Parametri

column

The 0-indexed column in the result set.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
5.2.3 | table field

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

array(6) {
  ["native_type"]=>
  string(7) "integer"
  ["flags"]=>
  array(0) {
  }
  ["name"]=>
  string(8) "COUNT(*)"
  ["len"]=>
  int(-1)
  ["precision"]=>
  int(0)
  ["pdo_type"]=>
  int(2)
}

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.2.0)

PDOStatement::nextRowset — Advances to the next rowset in a multi-rowset statement handle

Descrierea

public 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement

Descrierea

public 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.

Valorile întoarse

Returns the number of rows.

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

Return number of rows that were deleted:
Deleted 9 rows.

Example #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;
?>

Exemplul de mai sus va afi?a:

apple
banana
orange
pear

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.2.0)

PDOStatement::setAttribute — Set a statement attribute

Descrierea

public 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7, PECL pdo >= 0.2.0)

PDOStatement::setFetchMode — Set the default fetch mode for this statement

Descrierea

public bool PDOStatement::setFetchMode ( int $mode )
public bool PDOStatement::setFetchMode ( int $PDO::FETCH_COLUMN , int $colno )
public bool PDOStatement::setFetchMode ( int $PDO::FETCH_CLASS , string $classname , array $ctorargs )
public bool PDOStatement::setFetchMode ( int $PDO::FETCH_INTO , object $object )

Parametri

mode

The fetch mode must be one of the PDO::FETCH_* constants.

colno

Column number.

classname

Class name.

ctorargs

Constructor arguments.

object

Object.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a:

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

(PHP 5 >= 5.1.0, PHP 7)

Introducere

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.

Sinopsisul clasei

PDOException extends RuntimeException {
/* Proprieta?i */
public array $errorInfo ;
protected string $code ;
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Proprieta?i

errorInfo

Corresponds to PDO::errorInfo() or PDOStatement::errorInfo()

code

SQLSTATE error code. Use Exception::getCode() to access it.

PDOStatement::setFetchMode
PDO Drivers
PDO


PDO Drivers

Cuprins

  • CUBRID (PDO)
  • MS SQL Server (PDO)
  • Firebird (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
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)

Introducere

PDO_CUBRID is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to CUBRID databases.

Nota:

Current version of PDO_CUBRID doesn't support persistent connection now.

Instalarea

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.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows. 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 enabled 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:

Example #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();
?>

Example #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
Collection Data Type PDO_CUBRID supports SET/MULTISET/SEQUENCE data type. If you don't specify data type, the default data type is char,for example:

Example #3 Insert set in CUBRID PDO with default data type.

<?php
$conn_str ="cubrid:dbname=demodb;host=localhost;port=33000";
$cubrid_pdo = new PDO($conn_str, 'dba', '');

$cubrid_pdo->exec("DROP TABLE if exists test_tbl");
$cubrid_pdo->exec("CREATE TABLE test_tbl (col_1 SET(VARCHAR))");

$sql_stmt_insert = "INSERT INTO test_tbl VALUES (?);";
$stmt = $cubrid_pdo->prepare($sql_stmt_insert);
$data = array("abc","def","ghi");
$ret = $stmt->bindParam(1, $data, PDO::PARAM_NULL);
$ret = $stmt->execute();
var_Dump($ret);
?>

Example #4 Specify data type when insert set in CUBRID PDO

<?php
$conn_str ="cubrid:dbname=demodb;host=localhost;port=33000";
$cubrid_pdo = new PDO($conn_str, 'dba', '');

$cubrid_pdo->exec("DROP TABLE if exists test_tbl");
$cubrid_pdo->exec("CREATE TABLE test_tbl (col_1 SET(int))");

$sql_stmt_insert = "INSERT INTO test_tbl VALUES (?);";
$stmt = $cubrid_pdo->prepare($sql_stmt_insert);
$data = array(1,2,3,4);
$ret = $stmt->bindParam(1, $data, 0,0,"int");
$ret = $stmt->execute();
var_Dump($ret);
?>

CUBRID Bind Data Types:(The fifth parameter of PDOStatement::bindParam):
  • CHAR
  • STRING
  • NCHAR
  • VARNCHAR
  • BIT
  • VARBIT
  • NUMERIC
  • NUMBER
  • INT
  • SHORT
  • BIGINT
  • MONETARY
  • FLOAT
  • DOUBLE
  • DATE
  • TIME
  • DATETIME
  • TIMESTAMP

Constante predefinite

Constantele de mai jos sunt definite de acest driver ?i vor fi disponibile doar când aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii. În plus, aceste constante specifice driver-ului trebuie utilizate numai daca utiliza?i acest driver. Utilizarea atributelor specifice unui driver cu un alt driver poate rezulta într-un comportament imprevizibil. PDO::getAttribute() poate fi utilizata pentru a ob?ine atributul PDO_ATTR_DRIVER_NAME , pentru a verifica driver-ul în caz ca codul-sursa al dumneavoastra poate rula cu mai multe driver-e.

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.

Cuprins

  • 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 Git)

PDO_CUBRID DSN — Connecting to CUBRID databases

Descrierea

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.

Note

Nota:

When you estalish the connection to CUBRID, you should give username and password except DSN.

Exemple

Example #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 Git)

PDO::cubrid_schema — Get the requested schema information

Descrierea

public 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 |

Parametri

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.

Valorile întoarse

Array containing the schema information, when process is successful;

FALSE, when process is unsuccessful

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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)

Introducere

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 library.

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.

Cuprins

  • 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 (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

Descrierea

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.

Exemple

Example #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 (PDO)
MS SQL Server (PDO)


Firebird Functions (PDO_FIREBIRD)

Introducere

PDO_FIREBIRD is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Firebird database.

Instalarea

Utiliza?i --with-pdo-firebird[=DIR] pentru a instala extensia PDO Firebird, unde parametrul op?ional [=DIR] este directorul de baza al instalarii Firebird.

$ ./configure --with-pdo-firebird

Constante predefinite

Constantele de mai jos sunt definite de acest driver ?i vor fi disponibile doar când aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii. În plus, aceste constante specifice driver-ului trebuie utilizate numai daca utiliza?i acest driver. Utilizarea atributelor specifice unui driver cu un alt driver poate rezulta într-un comportament imprevizibil. PDO::getAttribute() poate fi utilizata pentru a ob?ine atributul PDO_ATTR_DRIVER_NAME , pentru a verifica driver-ul în caz ca codul-sursa al dumneavoastra poate rula cu mai multe driver-e.

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.

Cuprins

  • PDO_FIREBIRD DSN — Connecting to Firebird databases
PDO_DBLIB DSN
PDO_FIREBIRD DSN
PDO Drivers


Connecting to Firebird databases

Firebird (PDO)
IBM (PDO)
Firebird (PDO)
PHP Manual

PDO_FIREBIRD DSN

(PECL PDO_FIREBIRD >= 0.1.0)

PDO_FIREBIRD DSN — Connecting to Firebird databases

Descrierea

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.

Exemple

Example #1 PDO_FIREBIRD DSN example with path

The following example shows a PDO_FIREBIRD DSN for connecting to Firebird databases:

firebird:dbname=/path/to/DATABASE.FDB

Example #2 PDO_FIREBIRD DSN example with port and path

The following example shows a PDO_FIREBIRD DSN for connecting to a Firebird database using hostname port and path:

firebird:dbname=hostname/port:/path/to/DATABASE.FDB

Example #3 PDO_FIREBIRD DSN example with localhost and path to employee.fdb on Debian system

The following example shows a PDO_FIREBIRD DSN for connecting to a Firebird database employee.fdb using localhost:

firebird:dbname=localhost:/var/lib/firebird/2.5/data/employee.fdb

Firebird (PDO)
IBM (PDO)
Firebird (PDO)


IBM Functions (PDO_IBM)

Introducere

PDO_IBM is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to IBM databases.

Instalarea

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.

Nota: 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.

Cuprins

  • 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

Descrierea

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.

Exemple

Example #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

Example #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)

Introducere

PDO_INFORMIX is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Informix databases.

Instalarea

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.

Cuprins

  • 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

Descrierea

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.

Exemple

Example #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

Example #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)

Introducere

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.

Avertizare

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.

Instalarea

The common Unix distributions include binary versions of PHP that can be installed. Although these binary versions are typically built with support for the MySQL extensions, the extension libraries themselves may need to be installed using an additional package. Check the package manager than comes with your chosen distribution for availability.

For example, on Ubuntu the php5-mysql package installs the ext/mysql, ext/mysqli, and PDO_MYSQL PHP extensions. On CentOS, the php-mysql package also installs these three PHP extensions.

Alternatively, you can compile this extension yourself. Building PHP from source allows you to specify the MySQL extensions you want to use, as well as your choice of client library for each extension.

When compiling, use --with-pdo-mysql[=DIR] to install the PDO MySQL extension, where the optional [=DIR] is the MySQL base library. As of PHP 5.4, mysqlnd is the default library. For details about choosing a library, see Choosing a MySQL library.

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

SSL support is enabled using the appropriate PDO_MySQL constants, which is equivalent to calling the » MySQL C API function mysql_ssl_set(). Also, SSL cannot be enabled with PDO::setAttribute because the connection already exists. See also the MySQL documentation about » connecting to MySQL with SSL.

Jurnal al modificarilor
Versiune | Descriere
5.4.0 | mysqlnd became the default MySQL library when compiling PDO_MYSQL. Previously, libmysqlclient was the default MySQL library.
5.4.0 | MySQL client libraries 4.1 and below are no longer supported.
5.3.9 | Added SSL support with mysqlnd and OpenSSL.
5.3.7 | Added SSL support with libmysqlclient and OpenSSL.

Constante predefinite

Constantele de mai jos sunt definite de acest driver ?i vor fi disponibile doar când aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii. În plus, aceste constante specifice driver-ului trebuie utilizate numai daca utiliza?i acest driver. Utilizarea atributelor specifice unui driver cu un alt driver poate rezulta într-un comportament imprevizibil. PDO::getAttribute() poate fi utilizata pentru a ob?ine atributul PDO_ATTR_DRIVER_NAME , pentru a verifica driver-ul în caz ca codul-sursa al dumneavoastra poate rula cu mai multe driver-e.

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.

Example #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 also supported when compiled against mysqlnd as of PHP 5.3.11.

PDO::MYSQL_ATTR_SSL_CA (integer)

The file path to the SSL certificate authority.

Aceasta exista începând cu PHP 5.3.7.

PDO::MYSQL_ATTR_SSL_CAPATH (integer)

The file path to the directory that contains the trusted SSL CA certificates, which are stored in PEM format.

Aceasta exista începând cu PHP 5.3.7.

PDO::MYSQL_ATTR_SSL_CERT (integer)

The file path to the SSL certificate.

Aceasta exista începând cu PHP 5.3.7.

PDO::MYSQL_ATTR_SSL_CIPHER (integer)

A list of one or more permissible ciphers to use for SSL encryption, in a format understood by OpenSSL. For example: DHE-RSA-AES256-SHA:AES128-SHA

Aceasta exista începând cu PHP 5.3.7.

PDO::MYSQL_ATTR_SSL_KEY (integer)

The file path to the SSL key.

Aceasta exista începând cu PHP 5.3.7.

PDO::MYSQL_ATTR_MULTI_STATEMENTS (integer)

Disables multi query execution in both PDO::prepare() and PDO::query() when set to FALSE.

Note, this constant can only be used in the driver_options array when constructing a new database handle.

Aceasta exista începând cu PHP 5.5.21 and PHP 5.6.5.

Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

PDO_MYSQL Configuration Options
Denumire | Valoare implicita | Poate fi modificata
pdo_mysql.default_socket | "/tmp/mysql.sock" | PHP_INI_SYSTEM
pdo_mysql.debug | NULL | PHP_INI_SYSTEM
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Cuprins

  • 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

Descrierea

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. See the character set concepts documentation for more information.

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.

Avertizare

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.

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
5.3.6 | Prior to version 5.3.6, charset was ignored.

Exemple

Example #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

Note

Nota: 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 libmysqlclient then the location of the socket file is at libmysqlclient'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)

Introducere

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.

Instalarea

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 8 driver files, four of which are for PDO support. If you are running non-thread-safe PHP (PHP 5.3), use the php_pdo_sqlsrv_53_nts.dll file. (You should use a non-thread-safe version if you are using IIS as your web server). If you are running thread-safe PHP, use the php_pdo_sqlsrv_53_ts.dll file. Similarly for PHP 5.4, use the php_pdo_sqlsrv_54_nts.dll or php_pdo_sqlsrv_54_ts.dll depending on whether your PHP installation is non-thread-safe or thread-safe.

The most recent version of the driver is available for download here: » SQLSRV 3.0 download. If you need support for PHP 5.2 and/or PHP compiled with VC6, use the 2.0 release of the driver: » SQLSRV 2.0 download.

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.

Constante predefinite

Constantele de mai jos sunt definite de acest driver ?i vor fi disponibile doar când aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii. În plus, aceste constante specifice driver-ului trebuie utilizate numai daca utiliza?i acest driver. Utilizarea atributelor specifice unui driver cu un alt driver poate rezulta într-un comportament imprevizibil. PDO::getAttribute() poate fi utilizata pentru a ob?ine atributul PDO_ATTR_DRIVER_NAME , pentru a verifica driver-ul în caz ca codul-sursa al dumneavoastra poate rula cu mai multe driver-e.

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.

Cuprins

  • 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 Git)

PDO_SQLSRV DSN — Connecting to MS SQL Server and SQL Azure databases

Descrierea

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.

Exemple

Example #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)

Instalarea

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

Cuprins

  • 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

Descrierea

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.

Exemple

Example #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)

Introducere

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, php_pdo_odbc.dll has to be enabled as extension in php.ini. 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.

Instalarea

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

Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

PDO_ODBC Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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. Aceasta facilitate învechita cu siguran?a va fi eliminata în viitor.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Avertizare

relaxed matching should not be used on a shared server, for security reasons.

Sfat

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.

Cuprins

  • 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

Descrierea

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.

Exemple

Example #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

Example #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;

Example #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)

Introducere

PDO_PGSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to PostgreSQL databases.

Tipurile resurselor

This extension defines a stream resource returned by PDO::pgsqlLOBOpen().

Instalarea

Utiliza?i --with-pdo-pgsql[=DIR] pentru a instala extensia PDO PostgreSQL, unde parametrul op?ional [=DIR] este directorul de baza al instalarii PostgreSQL, sau calea catre pg_config.

$ ./configure --with-pdo-pgsql

Cuprins

  • PDO_PGSQL DSN — Connecting to PostgreSQL databases
  • PDO::pgsqlCopyFromArray — Copy data from PHP array into table
  • PDO::pgsqlCopyFromFile — Copy data from file into table
  • PDO::pgsqlCopyToArray — Copy data from database table into PHP array
  • PDO::pgsqlCopyToFile — Copy data from table into file
  • PDO::pgsqlGetNotify — Get asynchronous notification
  • PDO::pgsqlGetPid — Get the server PID
  • 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::pgsqlCopyFromArray
PostgreSQL (PDO)
PHP Manual

PDO_PGSQL DSN

(PECL PDO_PGSQL >= 0.1.0)

PDO_PGSQL DSN — Connecting to PostgreSQL databases

Descrierea

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.

Nota:

The bytea fields are returned as streams.

Exemple

Example #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::pgsqlCopyFromArray
PostgreSQL (PDO)


Copy data from PHP array into table

PDO_PGSQL DSN
PDO::pgsqlCopyFromFile
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlCopyFromArray

(PHP 5 >= 5.3.3, PHP 7)

PDO::pgsqlCopyFromArray — Copy data from PHP array into table

Descrierea

public bool PDO::pgsqlCopyFromArray ( string $table_name , array $rows [, string $delimiter = '\t' [, string $null_as = "\\\\N" [, string $fields ]]] )

Copies data from rows array to table table_name using delimiter as fields delimiter and fields list

Parametri

table_name

String containing table name

rows

Array of strings with fields separated by delimiter

delimiter

Delimiter used in rows array

null_as

How to interpret null values

fields

List of fields to insert

Valorile întoarse

Returns TRUE on success, sau FALSE în cazul e?ecului.

PDO_PGSQL DSN
PDO::pgsqlCopyFromFile
PostgreSQL (PDO)


Copy data from file into table

PDO::pgsqlCopyFromArray
PDO::pgsqlCopyToArray
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlCopyFromFile

(PHP 5 >= 5.3.3, PHP 7)

PDO::pgsqlCopyFromFile — Copy data from file into table

Descrierea

public bool PDO::pgsqlCopyFromFile ( string $table_name , string $filename [, string $delimiter = '\t' [, string $null_as = "\\\\N" [, string $fields ]]] )

Copies data from file specified by filename into table table_name using delimiter as fields delimiter and fields list

Parametri

table_name

String containing table name

filename

Filename containing data to import

delimiter

Delimiter used in file specified by filename

null_as

How to interpret null values

fields

List of fields to insert

Valorile întoarse

Returns TRUE on success, sau FALSE în cazul e?ecului.

PDO::pgsqlCopyFromArray
PDO::pgsqlCopyToArray
PostgreSQL (PDO)


Copy data from database table into PHP array

PDO::pgsqlCopyFromFile
PDO::pgsqlCopyToFile
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlCopyToArray

(PHP 5 >= 5.3.3, PHP 7)

PDO::pgsqlCopyToArray — Copy data from database table into PHP array

Descrierea

public array PDO::pgsqlCopyToArray ( string $table_name , array $rows [, string $delimiter = '\t' [, string $null_as = "\\\\N" [, string $fields ]]] )

Copies data from table into array using delimiter as fields delimiter and fields list

Parametri

table_name

String containing table name

delimiter

Delimiter used in rows array

null_as

How to interpret null values

fields

List of fields to export

Valorile întoarse

Returns an array of rows, sau FALSE în cazul e?ecului.

PDO::pgsqlCopyFromFile
PDO::pgsqlCopyToFile
PostgreSQL (PDO)


Copy data from table into file

PDO::pgsqlCopyToArray
PDO::pgsqlGetNotify
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlCopyToFile

(PHP 5 >= 5.3.3, PHP 7)

PDO::pgsqlCopyToFile — Copy data from table into file

Descrierea

public bool PDO::pgsqlCopyToFile ( string $table_name , string $filename [, string $delimiter = '\t' [, string $null_as = "\\\\N" [, string $fields ]]] )

Copies data from table into file specified by filename using delimiter as fields delimiter and fields list

Parametri

table_name

String containing table name

filename

Filename to export data

delimiter

Delimiter used in file specified by filename

null_as

How to interpret null values

fields

List of fields to insert

Valorile întoarse

Returns TRUE on success, sau FALSE în cazul e?ecului.

PDO::pgsqlCopyToArray
PDO::pgsqlGetNotify
PostgreSQL (PDO)


Get asynchronous notification

PDO::pgsqlCopyToFile
PDO::pgsqlGetPid
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlGetNotify

(PHP 5 >= 5.6.0, PHP 7)

PDO::pgsqlGetNotify — Get asynchronous notification

Descrierea

public array PDO::pgsqlGetNotify ([ int $result_type = PDO::FETCH_USE_DEFAULT [, int $ms_timeout = 0 ]] )

Returns a result set representing a pending asynchronous notification.

Parametri

result_type

The format the result set should be returned as, represented as a PDO::FETCH_* constant.

ms_timeout

The length of time to wait for a response, in milliseconds.

Valorile întoarse

If one or more notifications is pending, returns a single row, with fields message and pid, otherwise returns FALSE.

PDO::pgsqlCopyToFile
PDO::pgsqlGetPid
PostgreSQL (PDO)


Get the server PID

PDO::pgsqlGetNotify
PDO::pgsqlLOBCreate
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlGetPid

(PHP 5 >= 5.6.0, PHP 7)

PDO::pgsqlGetPid — Get the server PID

Descrierea

public int PDO::pgsqlGetPid ( void )

Returns the server's PID.

Valorile întoarse

The server's PID.

PDO::pgsqlGetNotify
PDO::pgsqlLOBCreate
PostgreSQL (PDO)


Creates a new large object

PDO::pgsqlGetPid
PDO::pgsqlLOBOpen
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlLOBCreate

(PHP 5 >= 5.1.2, PHP 7, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBCreate — Creates a new large object

Descrierea

public 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.

Nota: This function must be called within a transaction.

Parametri

PDO::pgsqlLOBCreate() takes no parameters.

Valorile întoarse

Returns the OID of the newly created large object on success, or FALSE on failure.

Exemple

Example #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();
?>

A se vedea ?i

  • PDO::pgsqlLOBOpen() - Opens an existing large object stream
  • PDO::pgsqlLOBUnlink() - Deletes the large object
  • pg_lo_create() - Create a large object

PDO::pgsqlGetPid
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, PHP 7, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBOpen — Opens an existing large object stream

Descrierea

public 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.

Nota: This function, and all manipulations of the large object, must be called and carried out within a transaction.

Parametri

oid

A large object identifier.

mode

If mode is r, open the stream for reading. If mode is w, open the stream for writing.

Valorile întoarse

Returns a stream resource on success sau FALSE în cazul e?ecului.

Exemple

Example #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', $oid, PDO::PARAM_STR);
$stmt->fetch(PDO::FETCH_BOUND);
$stream = $db->pgsqlLOBOpen($oid, 'r');
header("Content-type: application/octet-stream");
fpassthru($stream);
?>

A se vedea ?i

  • PDO::pgsqlLOBCreate() - Creates a new large object
  • PDO::pgsqlLOBUnlink() - Deletes the large object
  • pg_lo_open() - Open a large object

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, PHP 7, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBUnlink — Deletes the large object

Descrierea

public bool PDO::pgsqlLOBUnlink ( string $oid )

Deletes a large object from the database identified by OID.

Nota: This function must be called within a transaction.

Parametri

oid

A large object identifier

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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();
?>

A se vedea ?i

  • 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)

Introducere

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.

Nota:

PDO_SQLITE allows using strings apart from streams together with PDO::PARAM_LOB.

Instalarea

Driver-ul PDO PDO_SQLITE este activat implicit. Pentru a-l dezactiva, pute?i folosi op?iunea --without-pdo-sqlite[=DIR] , unde op?ionalul [=DIR] este directorul instalarii de baza a sqlite.

Cuprins

  • PDO_SQLITE DSN — Connecting to SQLite databases
  • PDO::sqliteCreateAggregate — Registers an aggregating User Defined Function for use in SQL statements
  • PDO::sqliteCreateCollation — Registers a User Defined Function for use as a collating function 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

Descrierea

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.

Nota:

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.

Exemple

Example #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::sqliteCreateCollation
SQLite (PDO)
PHP Manual

PDO::sqliteCreateAggregate

(PHP 5 >= 5.1.0, PHP 7, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateAggregate — Registers an aggregating User Defined Function for use in SQL statements

Descrierea

public bool PDO::sqliteCreateAggregate ( string $function_name , callable $step_func , callable $finalize_func [, int $num_args ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

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:

mixed 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.

The return value of this function will be used as the context argument in the next call of the step or finalize functions.

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:

mixed 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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.

Sfat

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.

Sfat

You can use PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to override SQLite native SQL functions.

Nota:

This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.

A se vedea ?i

  • 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::sqliteCreateCollation
SQLite (PDO)


Registers a User Defined Function for use as a collating function in SQL statements

PDO::sqliteCreateAggregate
PDO::sqliteCreateFunction
SQLite (PDO)
PHP Manual

PDO::sqliteCreateCollation

(PHP 5 >= 5.3.11, PHP 7)

PDO::sqliteCreateCollation — Registers a User Defined Function for use as a collating function in SQL statements

Descrierea

public bool PDO::sqliteCreateCollation ( string $name , callable $callback )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

name

Name of the SQL collating 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 collation. It should accept two strings and return as strcmp() does, i.e. it should return -1, 1, or 0 if the first string sorts before, sorts after, or is equal to the second.

This function need to be defined as:

int collation ( string $string1 , string $string2 )

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 PDO::sqliteCreateCollation() example

<?php
$db = new PDO('sqlite::memory:');
$db->exec("CREATE TABLE test (col1 string)");
$db->exec("INSERT INTO test VALUES ('a1')");
$db->exec("INSERT INTO test VALUES ('a10')");
$db->exec("INSERT INTO test VALUES ('a2')");

$db->sqliteCreateCollation('NATURAL_CMP', 'strnatcmp');
foreach ($db->query("SELECT col1 FROM test ORDER BY col1") as $row) {
  echo $row['col1'] . "\n";
}
echo "\n";
foreach ($db->query("SELECT col1 FROM test ORDER BY col1 COLLATE NATURAL_CMP") as $row) {
  echo $row['col1'] . "\n";
}
?>

Exemplul de mai sus va afi?a:

a1
a10
a2

a1
a2
a10

Note

Nota:

This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.

PDO::sqliteCreateAggregate
PDO::sqliteCreateFunction
SQLite (PDO)


Registers a User Defined Function for use in SQL statements

PDO::sqliteCreateCollation
4D (PDO)
SQLite (PDO)
PHP Manual

PDO::sqliteCreateFunction

(PHP 5 >= 5.1.0, PHP 7, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateFunction — Registers a User Defined Function for use in SQL statements

Descrierea

public bool PDO::sqliteCreateFunction ( string $function_name , callable $callback [, int $num_args ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

function_name

The name of the function used in SQL statements.

callback

Callback function to handle the defined SQL function.

Nota: 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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.

Sfat

You can use PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to override SQLite native SQL functions.

Nota:

This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.

A se vedea ?i

  • 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::sqliteCreateCollation
4D (PDO)
SQLite (PDO)


4D Functions (PDO_4D)

Introducere

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

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.

Cuprins

  • 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 Git)

PDO_4D DSN — Connecting to 4D SQL server

Descrierea

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.

Exemple

Example #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=Windows-1252
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 Git)

Constants for PDO_4D — Constants for PDO_4D

Constante predefinite

Constantele de mai jos sunt definite de acest driver ?i vor fi disponibile doar când aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii. În plus, aceste constante specifice driver-ului trebuie utilizate numai daca utiliza?i acest driver. Utilizarea atributelor specifice unui driver cu un alt driver poate rezulta într-un comportament imprevizibil. PDO::getAttribute() poate fi utilizata pentru a ob?ine atributul PDO_ATTR_DRIVER_NAME , pentru a verifica driver-ul în caz ca codul-sursa al dumneavoastra poate rula cu mai multe driver-e.

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 Git)

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 Git)

SQL acceptable by 4D — PDO and SQL 4D

Descrierea

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
Extensii de lucru cu baze de date specifice anumitor producatori
4D (PDO)
PHP Manual

Examples with PDO_4D

(No version information available, might only be in Git)

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.

Example #1 Basic example with PDO_4D

<?php
$dsn = '4D:host=localhost;CHARSET=Windows-1252';
$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);
?>

Exemplul de mai sus va afi?a:

    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.

Example #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_TEXT($0)
$0:=Application Version(*)

The PHP code to use the above 4D method is :

<?php
$dsn = '4D:host=localhost;CHARSET=Windows-1252';
$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);
?>

Exemplul de mai sus va afi?a:

(
    [0] => Array
        (
            [<expression>] => F0011140
            [0] => F0011140
        )

)

Example #3 Escaping 4D table names

This examples illustrates how to escape characters in a 4D SQL query.

<?php
$dsn = '4D:host=localhost;CHARSET=Windows-1252';
$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.'];');
}

?>

Exemplul de mai sus va afi?a:

[
]]
[]]
]][
[[
]]]]
[[[
]]]]]]
TBL ]]]]32[23

SQL acceptable by 4D
Extensii de lucru cu baze de date specifice anumitor producatori
4D (PDO)


Extensii de lucru cu baze de date specifice anumitor producatori

  • CUBRID
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii CUBRID
    • Func?ii CUBRID de compatibilitate MySQL
    • Pseudonime ?i func?ii CUBRID învechite
  • DB++
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii DB++
  • dBase
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • dBase Func?ii
  • filePro
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii filePro
  • Firebird/InterBase
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Firebird/InterBase
  • FrontBase
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii FrontBase
  • IBM DB2 — IBM DB2, Cloudscape and Apache Derby
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii IBM DB2
  • Informix
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Informix
  • Ingres — Ingres DBMS, EDBC, and Enterprise Access Gateways
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Ingres
  • MaxDB
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • MaxDB Func?ii
  • Mongo — Driver-ul MongoDB (învechit)
    • Instalarea / configurarea
    • Constante predefinite
    • Manual
    • Clase de baza
    • Types
    • Clase GridFS
    • Clase pentru opera?iuni în lot (batch)
    • Diverse
    • Func?ii Mongo
    • Excep?ii
    • Jurnalul modificarilor
  • MongoDB — MongoDB driver
    • Instalarea / configurarea
    • Ghiduri de utilizare
    • Driver Architecture and Internals — Explains the driver architecure, and special features
    • Security
    • MongoDB\Driver — Clasele driver-ului MongoDB
    • MongoDB\Driver\BSON — Clase ?i func?ii de serializare de tip BSON
    • MongoDB\Driver\Exception — Exception classes
  • mSQL
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii mSQL
  • Mssql — Microsoft SQL Server
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Mssql
  • MySQL — MySQL Drivers and Plugins
    • Overview of the MySQL PHP drivers
    • MySQLi — MySQL Improved Extension
    • MySQL (Original) — API originale ale MySQL
    • 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
    • mysqlnd_mux — Mysqlnd connection multiplexing plugin
    • mysqlnd_memcache — Mysqlnd Memcache plugin
  • OCI8 — Oracle OCI8
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • OCI8 Connection Handling and Connection Pooling
    • OCI8 Fast Application Notification (FAN) Support
    • OCI8 and DTrace Dynamic Tracing
    • Supported Datatypes
    • Func?ii OCI8
    • OCI-Collection — The OCI-Collection class
    • OCI-Lob — The OCI-Lob class
    • Pseudonime ?i func?ii OCI8 învechite
  • Paradox — Paradox File Access
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Paradox Func?ii
  • PostgreSQL
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • PostgreSQL Func?ii
  • SQLite
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • SQLite Func?ii
  • SQLite3
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • SQLite3 — The SQLite3 class
    • SQLite3Stmt — The SQLite3Stmt class
    • SQLite3Result — The SQLite3Result class
  • SQLSRV — Microsoft SQL Server Driver for PHP
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii SQLSRV
  • Sybase
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Sybase
  • tokyo_tyrant
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • 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
Extensii de lucru cu baze de date


CUBRID

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii CUBRID
    • 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 last 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_lob2_bind — Bind a lob object or a string as a lob object to a prepared statement as parameters.
    • cubrid_lob2_close — Close LOB object.
    • cubrid_lob2_export — Export the lob object to a file.
    • cubrid_lob2_import — Import BLOB/CLOB data from a file.
    • cubrid_lob2_new — Create a lob object.
    • cubrid_lob2_read — Read from BLOB/CLOB data.
    • cubrid_lob2_seek64 — Move the cursor of a lob object.
    • cubrid_lob2_seek — Move the cursor of a lob object.
    • cubrid_lob2_size64 — Get a lob object's size.
    • cubrid_lob2_size — Get a lob object's size.
    • cubrid_lob2_tell64 — Tell the cursor position of the LOB object.
    • cubrid_lob2_tell — Tell the cursor position of the LOB object.
    • cubrid_lob2_write — Write to a lob object.
    • 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 a 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
  • Func?ii CUBRID de compatibilitate MySQL
    • cubrid_affected_rows — Return the number of rows affected by the last SQL statement
    • 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 — Fetch the next row and return 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
  • Pseudonime ?i func?ii CUBRID învechite
    • 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
Extensii de lucru cu baze de date specifice anumitor producatori
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

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
Instalarea / configurarea
CUBRID


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
CUBRID


Necesita?i

In order to have these functions available, you must install CUBRID, and compile CUBRID PHP Library with CUBRID support.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/cubrid.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Pentru informa?ii despre instalarea manuala pe sisteme Linux ?i Windows, citi?i fi?ierul build-guide.html inclus în pachet.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

There is no runtime configuration now.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

There are four 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 last two a resource which holds the query results of BLOB/CLOB data types.

connection identifier

A connection identifier returned by cubrid_connect(),
cubrid_connect_with_url(),
cubrid_pconnect() and
cubrid_pconnect_with_url().

request identifier

A request identifier returned by cubrid_prepare() and cubrid_execute().

LOB identifier

A LOB identifier returned by cubrid_lob_get().

LOB2 identifier

A LOB identifier returned by cubrid_lob2_new() or get from the result set.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
CUBRID_LOB | The constant CUBRID_LOB can be used when you want to operate the lob object. It can be passed to cubrid_fetch(), cubrid_fetch_row(), cubrid_fetch_array(), cubrid_fetch_assoc() and cubrid_fetch_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. This flag has been removed from 8.4.1.
CUBRID_NO_MORE_DATA | Returned value of cubrid_move_cursor() function in case of failure. This flag has been removed from 8.4.1.
CUBRID_CURSOR_ERROR | Returned value of cubrid_move_cursor() function in case of failure. This flag has been removed from 8.4.1.

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 occurred in CUBRID dbms.
CUBRID_FACILITY_CAS | The error occurred in CUBRID broker cas.
CUBRID_FACILITY_CCI | The error occurred in CUBRID cci.
CUBRID_FACILITY_CLIENT | The error occurred in CUBRID PHP client.

Tipurile resurselor
Exemple
CUBRID


Exemple

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.

Example #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>

Example #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>
Constante predefinite
Func?ii CUBRID
CUBRID


Func?ii CUBRID

Cuprins

  • 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 last 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_lob2_bind — Bind a lob object or a string as a lob object to a prepared statement as parameters.
  • cubrid_lob2_close — Close LOB object.
  • cubrid_lob2_export — Export the lob object to a file.
  • cubrid_lob2_import — Import BLOB/CLOB data from a file.
  • cubrid_lob2_new — Create a lob object.
  • cubrid_lob2_read — Read from BLOB/CLOB data.
  • cubrid_lob2_seek64 — Move the cursor of a lob object.
  • cubrid_lob2_seek — Move the cursor of a lob object.
  • cubrid_lob2_size64 — Get a lob object's size.
  • cubrid_lob2_size — Get a lob object's size.
  • cubrid_lob2_tell64 — Tell the cursor position of the LOB object.
  • cubrid_lob2_tell — Tell the cursor position of the LOB object.
  • cubrid_lob2_write — Write to a lob object.
  • 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 a 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
Exemple
cubrid_bind
CUBRID


Bind variables to a prepared statement as parameters

Func?ii CUBRID
cubrid_close_prepare
Func?ii CUBRID
PHP Manual

cubrid_bind

(PECL CUBRID >= 8.3.0)

cubrid_bind — Bind variables to a prepared statement as parameters

Descrierea

bool cubrid_bind ( resource $req_identifier , int $bind_index , 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.

Nota:

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.

If the type of data to be bound explicitly is ENUM, the $bind_value argument should be the enum element which is in string format.

In CUBRID shard envrioment, the $bind_value_type must be included in the cubrid_bind function.

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
 | ENUM | ENUM
 | BLOB | BLOB
 | CLOB | CLOB
 | NULL | NULL
Not supported | SET | SET
 | MULTISET | MULTISET
 | SEQUENCE | SEQUENCE

Parametri

req_identifier

Request identifier as a result of cubrid_prepare().

bind_index

Location of binding parameters. It starts with 1.

bind_value

Actual value for binding.

bind_value_type

A type of the value to bind. (It is omitted by default. Thus, the system internally uses 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).

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Istoricul schimbarilor

Versiune | Descriere
8.3.1 | Added BLOB/CLOB data types support.

Exemple

Example #1 cubrid_bind() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$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);
?>

Exemplul de mai sus va afi?a:

--- 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

Example #2 cubrid_bind() BLOB/CLOB example

<?php
$con = cubrid_connect("localhost", 33000, "demodb", "dba", "");
if ($con) {
    cubrid_execute($con,"DROP TABLE if exists php_cubrid_lob_test");
    cubrid_execute($con,"CREATE TABLE php_cubrid_lob_test (doc_content CLOB)");
    $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);
}
?>

Example #3 cubrid_bind() BLOB/CLOB example

<?php
$con = cubrid_connect("localhost", 33000, "demodb", "dba", "");
if ($con) {
    cubrid_execute($con,"DROP TABLE if exists php_cubrid_lob_test");
    cubrid_execute($con,"CREATE TABLE php_cubrid_lob_test (image BLOB)");
    $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);
}
?>

A se vedea ?i

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_prepare() - Prepare a SQL statement for execution

Func?ii CUBRID
cubrid_close_prepare
Func?ii CUBRID


Close the request handle

cubrid_bind
cubrid_close_request
Func?ii CUBRID
PHP Manual

cubrid_close_prepare

(PECL CUBRID >= 8.3.0)

cubrid_close_prepare — Close the request handle

Descrierea

bool 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 an alias of cubrid_close_request().

Parametri

req_identifier

Request identifier.

Valorile întoarse

Return TRUE on success.

Exemple

Example #1 cubrid_close_prepare() example

<?php
$con = cubrid_connect ("localhost", 33000, "demodb", "dba", "");
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);
}
?>

A se vedea ?i

  • cubrid_close_request() - Close the request handle

cubrid_bind
cubrid_close_request
Func?ii CUBRID


Close the request handle

cubrid_close_prepare
cubrid_col_get
Func?ii CUBRID
PHP Manual

cubrid_close_request

(PECL CUBRID >= 8.3.0)

cubrid_close_request — Close the request handle

Descrierea

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 an alias of cubrid_close_prepare().

Parametri

req_identifier

Request identifier.

Valorile întoarse

Return TRUE on success.

Exemple

Example #1 cubrid_close_request() example

<?php
$con = cubrid_connect ("localhost", 33000, "demodb", "dba", "");
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_request($req); // or you can use cubrid_close_prepare($req)
   }
   cubrid_disconnect($con);
}
?>

A se vedea ?i

  • cubrid_close_prepare() - Close the request handle

cubrid_close_prepare
cubrid_col_get
Func?ii CUBRID


Get contents of collection type column using OID

cubrid_close_request
cubrid_col_size
Func?ii CUBRID
PHP Manual

cubrid_col_get

(PECL CUBRID >= 8.3.0)

cubrid_col_get — Get contents of collection type column using OID

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #1 cubrid_col_get() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@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);
?>

Exemplul de mai sus va afi?a:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
int(3)
cubrid_close_request
cubrid_col_size
Func?ii CUBRID


Get the number of elements in collection type column using OID

cubrid_col_get
cubrid_column_names
Func?ii CUBRID
PHP Manual

cubrid_col_size

(PECL CUBRID >= 8.3.0)

cubrid_col_size — Get the number of elements in collection type column using OID

Descrierea

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.

Parametri

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.

Valorile întoarse

Number of elements, when process is successful.

FALSE, when process is unsuccessful.

Istoricul schimbarilor

Versiune | Descriere
8.3.1 | Change return value: when process is unsuccessful, return false, not -1.

Exemple

Example #1 cubrid_col_size() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@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);
?>

Exemplul de mai sus va afi?a:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
int(3)
cubrid_col_get
cubrid_column_names
Func?ii CUBRID


Get the column names in result

cubrid_col_size
cubrid_column_types
Func?ii CUBRID
PHP Manual

cubrid_column_names

(PECL CUBRID >= 8.3.0)

cubrid_column_names — Get the column names in result

Descrierea

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.

Parametri

req_identifier

Request identifier.

Valorile întoarse

Array of string values containing the column names, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_column_names() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$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);
?>

Exemplul de mai sus va afi?a:

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
medal                          char                           1
game_date                      date                           10

A se vedea ?i

  • cubrid_prepare() - Prepare a 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
Func?ii CUBRID


Get column types in result

cubrid_column_names
cubrid_commit
Func?ii CUBRID
PHP Manual

cubrid_column_types

(PECL CUBRID >= 8.3.0)

cubrid_column_types — Get column types in result

Descrierea

array cubrid_column_types ( resource $req_identifier )

The cubrid_column_types() function gets column types of query results by using req_identifier.

Parametri

req_identifier

Request identifier.

Valorile întoarse

Array of string values containing the column types, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_column_types() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$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);
?>

Exemplul de mai sus va afi?a:

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
medal                          char                           1
game_date                      date                           10

A se vedea ?i

  • cubrid_column_names() - Get the column names in result
  • cubrid_prepare() - Prepare a SQL statement for execution
  • cubrid_execute() - Execute a prepared SQL statement

cubrid_column_names
cubrid_commit
Func?ii CUBRID


Commit a transaction

cubrid_column_types
cubrid_connect_with_url
Func?ii CUBRID
PHP Manual

cubrid_commit

(PECL CUBRID >= 8.3.0)

cubrid_commit — Commit a transaction

Descrierea

bool cubrid_commit ( resource $conn_identifier )

The cubrid_commit() function is used to execute commit on the transaction pointed by conn_identifier, currently in progress. Connection to the server is closed after the cubrid_commit() function is called; However, the connection handle is still valid.

In CUBRID PHP, auto-commit mode is disabled by default for transaction management. You can set it by using cubrid_set_autocommit(). You can get its status by using cubrid_get_autocommit(). Before you start a transaction, remember to disable the auto-commit mode.

Parametri

conn_identifier

Connection identifier.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_commit() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@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;
cubrid_set_autocommit($conn,false);
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);
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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
Func?ii CUBRID


Establish the environment for connecting to CUBRID server

cubrid_commit
cubrid_connect
Func?ii CUBRID
PHP Manual

cubrid_connect_with_url

(PECL CUBRID >= 8.3.1)

cubrid_connect_with_url — Establish the environment for connecting to CUBRID server

Descrierea

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> ::= alhosts=<alternative_hosts>[ &rctime=<time>]

<properties> ::= login_timeout=<milli_sec>

<properties> ::= query_timeout=<milli_sec>

<properties> ::= disconnect_on_query_timeout=true|false

<alternative_hosts> ::= <standby_broker1_host>:<port> [,<standby_broker2_host>:<port>]

<host> := HOSTNAME | IP_ADDR

<time> := SECOND

<milli_sec> := MILLI SECOND

  • 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
  • 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.
  • login_timeout : Timeout value (unit: msec.) for database login. The default value is 0, which means infinite postponement.
  • query_timeout : Timeout value (unit: msec.) for query request. Upon timeout, a message to cancel requesting a query transferred to server is sent. The return value can depend on the disconnect_on_query_timeout configuration; even though the message to cancel a request is sent to server, that request may succeed.
  • disconnect_on_query_timeout : Configures a value whether to immediately return an error of function being executed upon timeout. The default value is false.

Nota:

? and : that are used as identifiers in PHP connection URL can't be included in the password. The following is an example of a password that is invalid to use as connection URL because it contains "?:".

$url = "CUBRID:localhost:33000:tdb:dba:12?:?login_timeout=100";

Passwords that contain ? or : may be passed as a separate parameter.

$url = "CUBRID:localhost:33000:tbd:::?login_timeout=100";

$conn = cubrid_connect_with_url($url, "dba", "12?");

If user or password is empty,you can't delete ":",the following is an example.

$url = "CUBRID:localhost:33000:demodb:::";

Parametri

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.

Valorile întoarse

Connection identifier, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_connect_with_url() url without properties example

<?php
$conn_url = "CUBRID:localhost:33000:demodb:dba::";
$con = cubrid_connect_with_url($conn_url);

if ($con) {
   echo "connected successfully";
   cubrid_execute($con, "create table person(id int,name char(16))");
   $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);
}
?>

Example #2 cubrid_connect_with_url() url with properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba::?login_timeout=100"
$con = cubrid_connect_with_url ($conn_url);

if ($con) {
   echo "connected successfully";
   cubrid_execute($con, "create table person(id int,name char(16))");
   $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);
}
?>

A se vedea ?i

  • 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
Func?ii CUBRID


Open a connection to a CUBRID Server

cubrid_connect_with_url
cubrid_current_oid
Func?ii CUBRID
PHP Manual

cubrid_connect

(PECL CUBRID >= 8.3.1)

cubrid_connect — Open a connection to a CUBRID Server

Descrierea

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.

Parametri

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. If not given, the default value is "public".

passwd

User password. If not given, the default value is "".

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.

Valorile întoarse

Connection identifier, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_connect() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

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);
?>

Exemplul de mai sus va afi?a:

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

A se vedea ?i

  • 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
Func?ii CUBRID


Get OID of the current cursor location

cubrid_connect
cubrid_disconnect
Func?ii CUBRID
PHP Manual

cubrid_current_oid

(PECL CUBRID >= 8.3.0)

cubrid_current_oid — Get OID of the current cursor location

Descrierea

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.

Parametri

req_identifier

Request identifier.

Valorile întoarse

Oid of current cursor location, when process is successful

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_current_oid() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$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);
?>

Exemplul de mai sus va afi?a:

Array
(
    [s_name] => X
    [f_name] => Mixed
)

A se vedea ?i

  • cubrid_execute() - Execute a prepared SQL statement

cubrid_connect
cubrid_disconnect
Func?ii CUBRID


Close a database connection

cubrid_current_oid
cubrid_drop
Func?ii CUBRID
PHP Manual

cubrid_disconnect

(PECL CUBRID >= 8.3.0)

cubrid_disconnect — Close a database connection

Descrierea

bool cubrid_disconnect ([ resource $conn_identifier ] )

The cubrid_disconnect() function closes the connection handle and disconnects from server. If any request handle is not closed at this point, it will be closed. It is similar to the CUBRID MySQL compatible function cubrid_close().

Parametri

conn_identifier

Connection identifier.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_disconnect() example

<?php
$con = cubrid_connect ("localhost", 33000, "demodb");
if ($con) {
   echo "connected successfully";

   $req = cubrid_execute( $con, "create table person(id int,name char(10))");
   if ($req) {
      cubrid_close_request($req);
      cubrid_commit($con);
   } else {
      cubrid_rollback($con);
   }

   $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);
}
?>

A se vedea ?i

  • 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
Func?ii CUBRID


Delete an instance using OID

cubrid_disconnect
cubrid_error_code_facility
Func?ii CUBRID
PHP Manual

cubrid_drop

(PECL CUBRID >= 8.3.0)

cubrid_drop — Delete an instance using OID

Descrierea

bool cubrid_drop ( resource $conn_identifier , string $oid )

The cubrid_drop() function is used to delete an instance from database by using the oid of the instance.

Parametri

conn_identifier

Connection identifier.

oid

Oid of the instance that you want to delete.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

--- 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         "
}

A se vedea ?i

  • cubrid_is_instance() - Check whether the instance pointed by OID exists

cubrid_disconnect
cubrid_error_code_facility
Func?ii CUBRID


Get the facility code of error

cubrid_drop
cubrid_error_code
Func?ii CUBRID
PHP Manual

cubrid_error_code_facility

(PECL CUBRID >= 8.3.0)

cubrid_error_code_facility — Get the facility code of error

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Facility code of the error code that occurred: CUBRID_FACILITY_DBMS, CUBRID_FACILITY_CAS, CUBRID_FACILITY_CCI, CUBRID_FACILITY_CLIENT

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

Error facility: 1
Error code: -493
Error msg: Syntax: In line 1, column 15 before END OF STATEMENT
Syntax error: unexpected 'unknown'

A se vedea ?i

  • 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
Func?ii CUBRID


Get error code for the most recent function call

cubrid_error_code_facility
cubrid_error_msg
Func?ii CUBRID
PHP Manual

cubrid_error_code

(PECL CUBRID >= 8.3.0)

cubrid_error_code — Get error code for the most recent function call

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Error code of the error that occurred, or 0 (zero) if no error occurred.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

Error facility: 4
Error code: -30015
Error msg: Some parameter not binded

A se vedea ?i

  • 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
Func?ii CUBRID


Get last error message for the most recent function call

cubrid_error_code
cubrid_execute
Func?ii CUBRID
PHP Manual

cubrid_error_msg

(PECL CUBRID >= 8.3.0)

cubrid_error_msg — Get last error message for the most recent function call

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Error message that occurred.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

Error facility: 2
Error code: -10015
Error msg: Invalid T_CCI_SCH_TYPE value

A se vedea ?i

  • 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
Func?ii CUBRID


Execute a prepared SQL statement

cubrid_error_msg
cubrid_fetch
Func?ii CUBRID
PHP Manual

cubrid_execute

(PECL CUBRID >= 8.3.0)

cubrid_execute — Execute a prepared SQL statement

Descrierea

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.
  • 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.

Parametri

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.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
8.4.0 | Add new option CUBRID_EXEC_QUERY_ALL.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

athlete              host_year score      unit
Phelps Michael       2004      51.25      time

A se vedea ?i

  • cubrid_prepare() - Prepare a 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
Func?ii CUBRID


Fetch the next row from a result set

cubrid_execute
cubrid_free_result
Func?ii CUBRID
PHP Manual

cubrid_fetch

(PECL CUBRID >= 8.3.0)

cubrid_fetch — Fetch the next row from a result set

Descrierea

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.

Parametri

result

result comes from a call to cubrid_execute()

type

Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH, CUBRID_OBJECT. If you want to operate the lob object, you can use CUBRID_LOB.

Valorile întoarse

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.

Exemple

Example #1 cubrid_fetch() example

<?php
$conn = cubrid_connect("localhost", 33000, "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"]);
}

// if you want to operate lob object, you can use cubrid_fetch($req, CUBRID_LOB)

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • cubrid_fetch_row() - Return a numerical array with the values of the current row
  • cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
  • cubrid_fetch_object() - Fetch the next row and return it as an object

cubrid_execute
cubrid_free_result
Func?ii CUBRID


Free the memory occupied by the result data

cubrid_fetch
cubrid_get_autocommit
Func?ii CUBRID
PHP Manual

cubrid_free_result

(PECL CUBRID >= 8.3.0)

cubrid_free_result — Free the memory occupied by the result data

Descrierea

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().

Parametri

req_identifier

This is the request identifier.

Valorile întoarse

TRUE on success.

FALSE on failure.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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
Func?ii CUBRID


Get auto-commit mode of the connection

cubrid_free_result
cubrid_get_charset
Func?ii CUBRID
PHP Manual

cubrid_get_autocommit

(PECL CUBRID >= 8.4.0)

cubrid_get_autocommit — Get auto-commit mode of the connection

Descrierea

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.

For CUBRID 8.4.0, auto-commit mode is disabled by default for transaction management.

For CUBRID 8.4.1, auto-commit mode is enabled by default for transaction management.

Parametri

conn_identifier

Connection identifier.

Valorile întoarse

TRUE, when auto-commit is on.

FALSE, when auto-commit is off.

NULL on error.

A se vedea ?i

  • cubrid_set_autocommit() - Set autocommit mode of the connection
  • cubrid_commit() - Commit a transaction

cubrid_free_result
cubrid_get_charset
Func?ii CUBRID


Return the current CUBRID connection charset

cubrid_get_autocommit
cubrid_get_class_name
Func?ii CUBRID
PHP Manual

cubrid_get_charset

(PECL CUBRID >= 8.3.0)

cubrid_get_charset — Return the current CUBRID connection charset

Descrierea

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().

Parametri

conn_identifier

The CUBRID connection.

Valorile întoarse

A string that represents the CUBRID connection charset; on success.

FALSE on failure.

Exemple

Example #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_get_charset($con));

?>

Exemplul de mai sus va afi?a:

CUBRID current charset: iso8859-1

A se vedea ?i

  • cubrid_client_encoding() - Return the current CUBRID connection charset

cubrid_get_autocommit
cubrid_get_class_name
Func?ii CUBRID


Get the class name using OID

cubrid_get_charset
cubrid_get_client_info
Func?ii CUBRID
PHP Manual

cubrid_get_class_name

(PECL CUBRID >= 8.3.0)

cubrid_get_class_name — Get the class name using OID

Descrierea

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. It doesn't work when selecting data from the system tables, for example db_class.

Parametri

conn_identifier

Connection identifier.

oid

OID of the instance that you want to check the existence.

Valorile întoarse

Class name when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_get_class_name() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$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);
?>

Exemplul de mai sus va afi?a:

code

A se vedea ?i

  • 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
Func?ii CUBRID


Return the client library version

cubrid_get_class_name
cubrid_get_db_parameter
Func?ii CUBRID
PHP Manual

cubrid_get_client_info

(PECL CUBRID >= 8.3.0)

cubrid_get_client_info — Return the client library version

Descrierea

string cubrid_get_client_info ( void )

This function returns a string that represents the client library version.

Parametri

Valorile întoarse

A string that represents the client library version; on success.

FALSE on failure.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1
cubrid_get_class_name
cubrid_get_db_parameter
Func?ii CUBRID


Returns the CUBRID database parameters

cubrid_get_client_info
cubrid_get_query_timeout
Func?ii CUBRID
PHP Manual

cubrid_get_db_parameter

(PECL CUBRID >= 8.3.0)

cubrid_get_db_parameter — Returns the CUBRID database parameters

Descrierea

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, 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.

Parametri

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.

Valorile întoarse

An associative array with CUBRID database parameters; on success.

FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
8.4.0 | Change LOCK_TIMEOUT to PARAM_LOCK_TIMEOUT, and MAX_STRING_LENGTH to PARAM_MAX_STRING_LENGTH in result.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

A se vedea ?i

  • 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
Func?ii CUBRID


Get the query timeout value of the request

cubrid_get_db_parameter
cubrid_get_server_info
Func?ii CUBRID
PHP Manual

cubrid_get_query_timeout

(PECL CUBRID >= 8.4.1)

cubrid_get_query_timeout — Get the query timeout value of the request

Descrierea

int cubrid_get_query_timeout ( resource $req_identifier )

The cubrid_get_query_timeout() function is used to get the query timeout of the request.

Parametri

req_identifier

Request identifier.

Valorile întoarse

Success: the query timeout value of the current request. Units of msec.

Failure: FALSE

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

int(5000)
int(1000)

A se vedea ?i

  • cubrid_set_query_timeout() - Set the timeout time of query execution

cubrid_get_db_parameter
cubrid_get_server_info
Func?ii CUBRID


Return the CUBRID server version

cubrid_get_query_timeout
cubrid_get
Func?ii CUBRID
PHP Manual

cubrid_get_server_info

(PECL CUBRID >= 8.3.0)

cubrid_get_server_info — Return the CUBRID server version

Descrierea

string cubrid_get_server_info ( resource $conn_identifier )

This function returns a string that represents the CUBRID server version.

Parametri

conn_identifier

The CUBRID connection.

Valorile întoarse

A string that represents the CUBRID server version; on success.

FALSE on failure.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1
cubrid_get_query_timeout
cubrid_get
Func?ii CUBRID


Get a column using OID

cubrid_get_server_info
cubrid_insert_id
Func?ii CUBRID
PHP Manual

cubrid_get

(PECL CUBRID >= 8.3.0)

cubrid_get — Get a column using OID

Descrierea

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.

Parametri

conn_identifier

Connection identifier.

oid

OID of the instance that you want to read.

attr

Name of the attribute that you want to read.

Valorile întoarse

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())

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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         "
}

A se vedea ?i

  • cubrid_put() - Update a column using OID

cubrid_get_server_info
cubrid_insert_id
Func?ii CUBRID


Return the ID generated for the last updated AUTO_INCREMENT column

cubrid_get
cubrid_is_instance
Func?ii CUBRID
PHP Manual

cubrid_insert_id

(PECL CUBRID >= 8.3.0)

cubrid_insert_id — Return the ID generated for the last updated AUTO_INCREMENT column

Descrierea

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.

Nota:

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.

Parametri

conn_identifier

The connection identifier previously obtained by a call to cubrid_connect().

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
8.4.0 | Change the return value from an array to string; Remove the first parameter class_name.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

string(2) "19"
cubrid_get
cubrid_is_instance
Func?ii CUBRID


Check whether the instance pointed by OID exists

cubrid_insert_id
cubrid_lob_close
Func?ii CUBRID
PHP Manual

cubrid_is_instance

(PECL CUBRID >= 8.3.0)

cubrid_is_instance — Check whether the instance pointed by OID exists

Descrierea

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.

Parametri

conn_identifier

Connection identifier.

oid

OID of the instance that you want to check the existence.

Valorile întoarse

1, if such instance exists;

0, if such instance does not exist;

-1, in case of error

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

Instance pointed by @0|0|0 doesn't exist.

A se vedea ?i

  • cubrid_drop() - Delete an instance using OID
  • cubrid_get_class_name() - Get the class name using OID

cubrid_insert_id
cubrid_lob_close
Func?ii CUBRID


Close BLOB/CLOB data

cubrid_is_instance
cubrid_lob_export
Func?ii CUBRID
PHP Manual

cubrid_lob_close

(PECL CUBRID >= 8.3.1)

cubrid_lob_close — Close BLOB/CLOB data

Descrierea

bool cubrid_lob_close ( array $lob_identifier_array )

cubrid_lob_close() is used to close all BLOB/CLOB returned from cubrid_lob_get().

Parametri

lob_identifier_array

LOB identifier array return from cubrid_lob_get.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_lob_close() example

<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");
echo "Doc size: ".cubrid_lob_size($lobs[0])." bytes";
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>

A se vedea ?i

  • 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
Func?ii CUBRID


Export BLOB/CLOB data to file

cubrid_lob_close
cubrid_lob_get
Func?ii CUBRID
PHP Manual

cubrid_lob_export

(PECL CUBRID >= 8.3.1)

cubrid_lob_export — Export BLOB/CLOB data to file

Descrierea

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.

Parametri

conn_identifier

Connection identifier.

lob_identifier

LOB identifier.

path_name

Path name of the file.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_lob_export() example

<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");
echo "Doc size: ".cubrid_lob_size($lobs[0])." bytes";
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>

A se vedea ?i

  • 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
Func?ii CUBRID


Get BLOB/CLOB data

cubrid_lob_export
cubrid_lob_send
Func?ii CUBRID
PHP Manual

cubrid_lob_get

(PECL CUBRID >= 8.3.1)

cubrid_lob_get — Get BLOB/CLOB data

Descrierea

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.

Parametri

conn_identifier

Connection identifier.

sql

SQL statement to be executed.

Valorile întoarse

Return an array of LOB resources, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_lob_get() example

<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");
echo "Doc size: ".cubrid_lob_size($lobs[0])." bytes";
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>

A se vedea ?i

  • 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
Func?ii CUBRID


Read BLOB/CLOB data and send straight to browser

cubrid_lob_get
cubrid_lob_size
Func?ii CUBRID
PHP Manual

cubrid_lob_send

(PECL CUBRID >= 8.3.1)

cubrid_lob_send — Read BLOB/CLOB data and send straight to browser

Descrierea

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.

Parametri

conn_identifier

Connection identifier.

lob_identifier

LOB identifier.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_lob_send() example

<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");

cubrid_lob_send($conn, $lobs[0]);
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>

A se vedea ?i

  • 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
Func?ii CUBRID


Get BLOB/CLOB data size

cubrid_lob_send
cubrid_lob2_bind
Func?ii CUBRID
PHP Manual

cubrid_lob_size

(PECL CUBRID >= 8.3.1)

cubrid_lob_size — Get BLOB/CLOB data size

Descrierea

string cubrid_lob_size ( resource $lob_identifier )

cubrid_lob_size() is used to get BLOB/CLOB data size.

Parametri

lob_identifier

LOB identifier.

Valorile întoarse

A string representing LOB data size, when process is successful.

FALSE, when process is unsuccessful.

Istoricul schimbarilor

Versiune | Descriere
8.4.0 | Change return value type from int to string.

Exemple

Example #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);
?>

A se vedea ?i

  • 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_lob2_bind
Func?ii CUBRID


Bind a lob object or a string as a lob object to a prepared statement as parameters.

cubrid_lob_size
cubrid_lob2_close
Func?ii CUBRID
PHP Manual

cubrid_lob2_bind

(PECL CUBRID >= 8.4.1)

cubrid_lob2_bind — Bind a lob object or a string as a lob object to a prepared statement as parameters.

Descrierea

bool cubrid_lob2_bind ( resource $req_identifier , int $bind_index , mixed $bind_value [, string $bind_value_type ] )

The cubrid_lob2_bind() function is used to bind BLOB/CLOB datas to a corresponding question mark placeholder in the SQL statement that was passed to cubrid_prepare(). If bind_value_type is not given, string will be "BLOB" as the default. But if you use cubrid_lob2_new() before, bind_value_type will be consistent with type in cubrid_lob2_new() as the default.

Parametri

req_identifier

Request identifier as a result of cubrid_prepare().

bind_index

Location of binding parameters. It starts with 1.

bind_value

Actual value for binding.

bind_value_type

It must be "BLOB" or "CLOB" and it won't be case-sensitive. If it not be given, the default value is "BLOB".

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_lob2_bind() example

<?php
// Table: test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES (?, ?)");

cubrid_bind($req,1, 3);

$lob = cubrid_lob2_new($conn, 'CLOB');
cubrid_lob2_bind($req, 2, $lob);

cubrid_execute($req);

cubrid_bind($req, 1, 4);

cubrid_lob2_bind($req, 2, 'CUBRID LOB2 TEST', 'CLOB');

cubrid_execute($req);

cubrid_disconnect($conn);
?>

A se vedea ?i

  • cubrid_lob2_new() - Create a lob object.
  • cubrid_lob2_close() - Close LOB object.

cubrid_lob_size
cubrid_lob2_close
Func?ii CUBRID


Close LOB object.

cubrid_lob2_bind
cubrid_lob2_export
Func?ii CUBRID
PHP Manual

cubrid_lob2_close

(PECL CUBRID >= 8.4.1)

cubrid_lob2_close — Close LOB object.

Descrierea

bool cubrid_lob2_close ( resource $lob_identifier )

The cubrid_lob2_close() function is used to close LOB object returned from cubrid_lob2_new() or got from the result set.

Parametri

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

Valorile întoarse

TRUE, on success.

FALSE, on failure.

A se vedea ?i

  • cubrid_lob2_new() - Create a lob object.

cubrid_lob2_bind
cubrid_lob2_export
Func?ii CUBRID


Export the lob object to a file.

cubrid_lob2_close
cubrid_lob2_import
Func?ii CUBRID
PHP Manual

cubrid_lob2_export

(PECL CUBRID >= 8.4.1)

cubrid_lob2_export — Export the lob object to a file.

Descrierea

bool cubrid_lob2_export ( resource $lob_identifier , string $file_name )

The cubrid_lob2_export() function is used to save the contents of BLOB/CLOB data to a file. To use this function, you must use cubrid_lob2_new() or fetch a lob object from CUBRID database first. If the file already exists, the operation will fail. This function will not influence the cursor position of the lob object. It operates the entire lob object.

Parametri

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

filename

File name you want to store BLOB/CLOB data. It also supports the path of the file.

Valorile întoarse

TRUE if the process is successful and FALSE for failure.

Exemple

Example #1 cubrid_lob2_export() example

<?php
// Table: test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$req = cubrid_prepare($conn, "select * from doc");

cubrid_execute($req);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);

$row = cubrid_fetch($req, CUBRID_NUM | CUBRID_LOB);

cubrid_lob2_export($row[1], "doc_3.txt");

cubrid_lob2_close($row[1]);
cubrid_disconnect($conn);
?>

A se vedea ?i

  • cubrid_lob2_new() - Create a lob object.
  • cubrid_lob2_close() - Close LOB object.
  • cubrid_lob2_import() - Import BLOB/CLOB data from a file.
  • cubrid_lob2_bind() - Bind a lob object or a string as a lob object to a prepared statement as parameters.

cubrid_lob2_close
cubrid_lob2_import
Func?ii CUBRID


Import BLOB/CLOB data from a file.

cubrid_lob2_export
cubrid_lob2_new
Func?ii CUBRID
PHP Manual

cubrid_lob2_import

(PECL CUBRID >= 8.4.1)

cubrid_lob2_import — Import BLOB/CLOB data from a file.

Descrierea

bool cubrid_lob2_import ( resource $lob_identifier , string $file_name )

The cubrid_lob2_import() function is used to save the contents of BLOB/CLOB data from a file. To use this function, you must use cubrid_lob2_new() or fetch a lob object from CUBRID database first. If the file already exists, the operation will fail. This function will not influence the cursor position of the lob object. It operates the entire lob object.

Parametri

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

filename

File name you want to import BLOB/CLOB data. It also supports the path of the file.

Valorile întoarse

TRUE if the process is successful and FALSE for failure.

Exemple

Example #1 cubrid_lob2_export() example

<?php

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES (?, ?)");
cubrid_bind($req, 1, 1);

$lob = cubrid_lob2_new($conn, "clob");
cubrid_lob2_import($lob, "doc_1.txt");
cubrid_lob2_bind($req, 2, $lob, 'CLOB'); // or cubrid_lob2_bind($req, 2, $lob);

cubrid_execute($req);

cubrid_lob2_close($lob);
cubrid_disconnect($conn);
?>

A se vedea ?i

  • cubrid_lob2_new() - Create a lob object.
  • cubrid_lob2_close() - Close LOB object.
  • cubrid_lob2_export() - Export the lob object to a file.
  • cubrid_lob2_bind() - Bind a lob object or a string as a lob object to a prepared statement as parameters.

cubrid_lob2_export
cubrid_lob2_new
Func?ii CUBRID


Create a lob object.

cubrid_lob2_import
cubrid_lob2_read
Func?ii CUBRID
PHP Manual

cubrid_lob2_new

(PECL CUBRID >= 8.4.1)

cubrid_lob2_new — Create a lob object.

Descrierea

resource cubrid_lob2_new ([ resource $conn_identifier [, string $type = "BLOB" ]] )

The cubrid_lob2_new() function is used to create a lob object (both BLOB and CLOB). This function should be used before you bind a lob object.

Parametri

conn_identifier

Connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() or cubrid_connect_with_url() is assumed.

type

It may be "BLOB" or "CLOB", it won't be case-sensitive. The default value is "BLOB".

Valorile întoarse

Lob identifier when it is successful.

FALSE on failure.

A se vedea ?i

  • cubrid_lob2_close() - Close LOB object.

cubrid_lob2_import
cubrid_lob2_read
Func?ii CUBRID


Read from BLOB/CLOB data.

cubrid_lob2_new
cubrid_lob2_seek64
Func?ii CUBRID
PHP Manual

cubrid_lob2_read

(PECL CUBRID >= 8.4.1)

cubrid_lob2_read — Read from BLOB/CLOB data.

Descrierea

string cubrid_lob2_read ( resource $lob_identifier , int $len )

The cubrid_lob2_read() function reads len bytes from the LOB data and returns the bytes read.

Parametri

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

len

Length from buffer you want to read from the lob data.

Valorile întoarse

Returns the contents as a string.

FALSE when there is no more data.

NULL on failure.

Exemple

Example #1 cubrid_lob2_read() example 1

<?php
// test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "public", "");

$req = cubrid_execute($conn, "select * from test_lob");

$row = cubrid_fetch_row($req, CUBRID_LOB);

print "position now is " . cubrid_lob2_tell($row[1]) . "\n";

cubrid_lob2_seek($row[1], 10, CUBRID_CURSOR_FIRST);

print "\nposition after moving farword is " . cubrid_lob2_tell($row[1]) . "\n";

$data = cubrid_lob2_read($row[1], 12);

print "\nposition after reading is " . cubrid_lob2_tell($row[1]) . "\n";

print $data . "\n";

cubrid_lob2_seek($row[1], 5, CUBRID_CURSOR_CURRENT);

print "\nposition after moving again is " . cubrid_lob2_tell($row[1]) . "\n";

$data = cubrid_lob2_read($row[1], 20);
print $data . "\n";

cubrid_disconnect($conn);
?>

Example #2 cubrid_lob2_read() example 2

<?php
// test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

$req = cubrid_execute($conn, "select * from test_lob");

$row = cubrid_fetch_row($req, CUBRID_LOB);

while (true) {
    if ($data = cubrid_lob2_read($row[1], 1024)) {
        print $data . "\n";
    }
    elseif ($data === false) {
        print "There is no more data\n";
        break;
    }
    else {
        print "There must some errors\n";
        break;
    }
}

cubrid_disconnect($conn);
?>

A se vedea ?i

  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.
  • cubrid_lob2_size64() - Get a lob object's size.

cubrid_lob2_new
cubrid_lob2_seek64
Func?ii CUBRID


Move the cursor of a lob object.

cubrid_lob2_read
cubrid_lob2_seek
Func?ii CUBRID
PHP Manual

cubrid_lob2_seek64

(PECL CUBRID >= 8.4.1)

cubrid_lob2_seek64 — Move the cursor of a lob object.

Descrierea

bool cubrid_lob2_seek64 ( resource $lob_identifier , string $offset [, int $origin = CUBRID_CURSOR_CURRENT ] )

The cubrid_lob2_seek64() function is used to move the cursor position of a lob object by the value set in the offset argument, to the direction set in the origin argument. If the offset you want to move is larger than an integer data can be stored, you can use this function.

To set the origin argument, you can use CUBRID_CURSOR_FIRST to set the cursor position moving forward offset units from the first beginning. In this case, offset must be a positive value.

If you use CUBRID_CURSOR_CURRENT for origin, you can move forward or backward. and offset can be positive or negative.

If you use CUBRID_CURSOR_LAST for origin, you can move backward offset units from the end of LOB object and offset only can be positive.

Nota:

If you use this function to move the cursor position of the lob object, you should pass offset as a string.

Parametri

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

offset

Number of units you want to move the cursor.

origin

This parameter can be the following values:

CUBRID_CURSOR_FIRST: move forward from the first beginning.

CUBRID_CURSOR_CURRENT: move forward or backward from the current position.

CUBRID_CURSOR_LAST: move backward at the end of LOB object.

Valorile întoarse

TRUE if the process is successful and FALSE for failure.

Exemple

Example #1 cubrid_lob2_seek64() example

<?php
// test_lob (id INT, contents CLOB)
// Data length of doc_1.txt should be greater than 20101029056306120215.

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES (?, ?)");
cubrid_bind($req, 1, 1);

$lob = cubrid_lob2_new($conn, "clob");
cubrid_lob2_import($lob, "doc_1.txt");
cubrid_lob2_bind($req, 2, $lob, 'CLOB'); // or cubrid_lob2_bind($req, 2, $lob);

cubrid_execute($req);

cubrid_lob2_close($lob);

$req = cubrid_execute($conn, "select * from test_lob");
$row = cubrid_fetch_row($req, CUBRID_LOB);
$lob = $row[1];

cubrid_lob2_seek64($lob, "20101029056306120215", CUBRID_CURSOR_FIRST);
$data = cubrid_lob2_read($lob, 20);
echo $data."\n";
cubrid_disconnect($conn);
?>

A se vedea ?i

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.
  • cubrid_lob2_size64() - Get a lob object's size.

cubrid_lob2_read
cubrid_lob2_seek
Func?ii CUBRID


Move the cursor of a lob object.

cubrid_lob2_seek64
cubrid_lob2_size64
Func?ii CUBRID
PHP Manual

cubrid_lob2_seek

(PECL CUBRID >= 8.4.1)

cubrid_lob2_seek — Move the cursor of a lob object.

Descrierea

bool cubrid_lob2_seek ( resource $lob_identifier , int $offset [, int $origin = CUBRID_CURSOR_CURRENT ] )

The cubrid_lob2_seek() function is used to move the cursor position of a lob object 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 to set the cursor position moving forward offset units from the first beginning. In this case, offset must be a positive value.

If you use CUBRID_CURSOR_CURRENT for origin, you can move forward or backward. and offset can be positive or negative.

If you use CUBRID_CURSOR_LAST for origin, you can move backward offset units from the end of LOB object and offset only can be positive.

Parametri

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

offset

Number of units you want to move the cursor.

origin

This parameter can be the following values:

CUBRID_CURSOR_FIRST: move forward from the first beginning.

CUBRID_CURSOR_CURRENT: move forward or backward from the current position.

CUBRID_CURSOR_LAST: move backward at the end of LOB object.

Valorile întoarse

TRUE if the process is successful and FALSE for failure.

Exemple

Example #1 cubrid_lob2_seek() example

<?php
// test_lob (id INT, contents CLOB)
$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");
$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES(2, ?)");

$lob = cubrid_lob2_new($conn, 'CLOB');
$len = cubrid_lob2_write($lob, "Hello world");

cubrid_lob2_seek($lob, 0, CUBRID_CURSOR_LAST);
cubrid_lob2_write($lob, "beautiful");

cubrid_lob2_seek($lob, 15, CUBRID_CURSOR_FIRST);
$data = cubrid_lob2_read($lob, 5);

echo $data."\n";

cubrid_lob2_bind($req, 1, $lob);
cubrid_execute($req);

cubrid_disconnect($conn);
?>

A se vedea ?i

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.
  • cubrid_lob2_size64() - Get a lob object's size.

cubrid_lob2_seek64
cubrid_lob2_size64
Func?ii CUBRID


Get a lob object's size.

cubrid_lob2_seek
cubrid_lob2_size
Func?ii CUBRID
PHP Manual

cubrid_lob2_size64

(PECL CUBRID >= 8.4.1)

cubrid_lob2_size64 — Get a lob object's size.

Descrierea

string cubrid_lob2_size64 ( resource $lob_identifier )

The cubrid_lob2_size64() function is used to get the size of a lob object. If the size of a lob object is larger than an integer data can be stored, you can use this function and it will return the size as a string.

Parametri

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

Valorile întoarse

It will return the size of the LOB object as a string when it processes successfully.

FALSE on failure.

A se vedea ?i

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.

cubrid_lob2_seek
cubrid_lob2_size
Func?ii CUBRID


Get a lob object's size.

cubrid_lob2_size64
cubrid_lob2_tell64
Func?ii CUBRID
PHP Manual

cubrid_lob2_size

(PECL CUBRID >= 8.4.1)

cubrid_lob2_size — Get a lob object's size.

Descrierea

int cubrid_lob2_size ( resource $lob_identifier )

The cubrid_lob2_size() function is used to get the size of a lob object.

Parametri

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

Valorile întoarse

It will return the size of the LOB object when it processes successfully.

FALSE on failure.

A se vedea ?i

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size64() - Get a lob object's size.

cubrid_lob2_size64
cubrid_lob2_tell64
Func?ii CUBRID


Tell the cursor position of the LOB object.

cubrid_lob2_size
cubrid_lob2_tell
Func?ii CUBRID
PHP Manual

cubrid_lob2_tell64

(PECL CUBRID >= 8.4.1)

cubrid_lob2_tell64 — Tell the cursor position of the LOB object.

Descrierea

string cubrid_lob2_tell64 ( resource $lob_identifier )

The cubrid_lob2_tell64() function is used to tell the cursor position of the LOB object. If the size of a lob object is larger than an integer data can be stored, you can use this function and it will return the position information as a string.

Parametri

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

Valorile întoarse

It will return the cursor position on the LOB object as a string when it processes successfully.

FALSE on failure.

A se vedea ?i

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.
  • cubrid_lob2_size64() - Get a lob object's size.

cubrid_lob2_size
cubrid_lob2_tell
Func?ii CUBRID


Tell the cursor position of the LOB object.

cubrid_lob2_tell64
cubrid_lob2_write
Func?ii CUBRID
PHP Manual

cubrid_lob2_tell

(PECL CUBRID >= 8.4.1)

cubrid_lob2_tell — Tell the cursor position of the LOB object.

Descrierea

int cubrid_lob2_tell ( resource $lob_identifier )

The cubrid_lob2_tell() function is used to tell the cursor position of the LOB object.

Parametri

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

Valorile întoarse

It will return the cursor position on the LOB object when it processes successfully.

FALSE on failure.

A se vedea ?i

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.
  • cubrid_lob2_size64() - Get a lob object's size.

cubrid_lob2_tell64
cubrid_lob2_write
Func?ii CUBRID


Write to a lob object.

cubrid_lob2_tell
cubrid_lock_read
Func?ii CUBRID
PHP Manual

cubrid_lob2_write

(PECL CUBRID >= 8.4.1)

cubrid_lob2_write — Write to a lob object.

Descrierea

bool cubrid_lob2_write ( resource $lob_identifier , string $buf )

The cubrid_lob2_write() function reads as much as data from buf and stores it to the LOB object. Note that this function can only append characters now.

Parametri

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

buf

Data that need to be written to the lob object.

Valorile întoarse

TRUE if the process is successful and FALSE for failure.

Exemple

Example #1 cubrid_lob2_write() example 1

<?php
// test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES(2, ?)");

$lob = cubrid_lob2_new($conn, 'CLOB');
$len = cubrid_lob2_write($lob, "Hello world");

cubrid_lob2_bind($req, 1, $lob);
cubrid_execute($req);

cubrid_disconnect($conn);
?>

Example #2 cubrid_lob2_write() example 2

<?php
// test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES(1, ?)");
$lob1 = cubrid_lob2_new($conn, 'CLOB');
$len = cubrid_lob2_write($lob1, "cubrid php driver");
cubrid_lob2_bind($req, 1, $lob1);
cubrid_execute($req);

$req = cubrid_execute($conn, "select * from test_lob");

$row = cubrid_fetch_row($req, CUBRID_LOB);
$lob2 = $row[1];
cubrid_lob2_seek($lob2, 0, CUBRID_CURSOR_LAST);

$pos = cubrid_lob2_tell($lob2);
print "pos before write: $pos\n";

cubrid_lob2_write($lob2, "Hello world");

$pos = cubrid_lob2_tell($lob2);
print "pos after write: $pos\n";

cubrid_disconnect($conn);
?>

A se vedea ?i

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.
  • cubrid_lob2_size64() - Get a lob object's size.

cubrid_lob2_tell
cubrid_lock_read
Func?ii CUBRID


Set a read lock on the given OID

cubrid_lob2_write
cubrid_lock_write
Func?ii CUBRID
PHP Manual

cubrid_lock_read

(PECL CUBRID >= 8.3.0)

cubrid_lock_read — Set a read lock on the given OID

Descrierea

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.

Parametri

conn_identifier

Connection identifier.

oid

OID of the instance that you want to put read lock on.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_lock_read() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@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);
?>

Exemplul de mai sus va afi?a:

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         "
}

A se vedea ?i

  • cubrid_lock_write() - Set a write lock on the given OID

cubrid_lob2_write
cubrid_lock_write
Func?ii CUBRID


Set a write lock on the given OID

cubrid_lock_read
cubrid_move_cursor
Func?ii CUBRID
PHP Manual

cubrid_lock_write

(PECL CUBRID >= 8.3.0)

cubrid_lock_write — Set a write lock on the given OID

Descrierea

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.

Parametri

conn_identifier

Connection identifier.

oid

OID of the instance that you want to put write lock on.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_lock_write() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@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);
?>

Exemplul de mai sus va afi?a:

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"
}

A se vedea ?i

  • cubrid_lock_read() - Set a read lock on the given OID

cubrid_lock_read
cubrid_move_cursor
Func?ii CUBRID


Move the cursor in the result

cubrid_lock_write
cubrid_next_result
Func?ii CUBRID
PHP Manual

cubrid_move_cursor

(PECL CUBRID >= 8.3.0)

cubrid_move_cursor — Move the cursor in the result

Descrierea

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.

Parametri

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.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsucceful.

Exemple

Example #1 cubrid_move_cursor() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb", "dba");

$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);
?>

Exemplul de mai sus va afi?a:

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"
}

A se vedea ?i

  • cubrid_execute() - Execute a prepared SQL statement

cubrid_lock_write
cubrid_next_result
Func?ii CUBRID


Get result of next query when executing multiple SQL statements

cubrid_move_cursor
cubrid_num_cols
Func?ii CUBRID
PHP Manual

cubrid_next_result

(PECL CUBRID >= 8.4.0)

cubrid_next_result — Get result of next query when executing multiple SQL statements

Descrierea

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().

Parametri

result

result comes from a call to cubrid_execute()

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_next_result() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb", "dba");

$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");
}
?>

Exemplul de mai sus va afi?a:

------------ get_result_info --------------------
Row count:                     6
Column count:                  2

Column Names                   Column Types                   Column Len
------------------------------------------------------------------------------
s_name                         char                           1
f_name                         varchar                        6

Last Column Name:              f_name
Last Column Table:             code
Last Column Type:              varchar
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
host_year                      integer                        11
score                          varchar                        10
unit                           varchar                        5

Last Column Name:              unit
Last Column Table:             history
Last Column Type:              varchar
Last Column Len:               5
Second Column Flags:           not_null primary_key unique_key

A se vedea ?i

  • cubrid_execute() - Execute a prepared SQL statement

cubrid_move_cursor
cubrid_num_cols
Func?ii CUBRID


Return the number of columns in the result set

cubrid_next_result
cubrid_num_rows
Func?ii CUBRID
PHP Manual

cubrid_num_cols

(PECL CUBRID >= 8.3.0)

cubrid_num_cols — Return the number of columns in the result set

Descrierea

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.

Parametri

result

Result.

Valorile întoarse

Number of columns, when process is successful.

FALSE, if SQL statement is not SELECT.

Exemple

Example #1 cubrid_num_cols() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$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);
?>

Exemplul de mai sus va afi?a:

Row Num: 6
Column Num: 2

A se vedea ?i

  • 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
Func?ii CUBRID


Get the number of rows in the result set

cubrid_num_cols
cubrid_pconnect_with_url
Func?ii CUBRID
PHP Manual

cubrid_num_rows

(PECL CUBRID >= 8.3.0)

cubrid_num_rows — Get the number of rows in the result set

Descrierea

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.

Parametri

result

result comes from a call to cubrid_execute(), cubrid_query() and cubrid_prepare()

Valorile întoarse

Number of rows, when process is successful.

0 when the query was done in async mode.

-1, if SQL statement is not SELECT.

FALSE when process is unsuccessful.

Exemple

Example #1 cubrid_num_rows() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$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);
?>

Exemplul de mai sus va afi?a:

Row Num: 6
Column Num: 2

A se vedea ?i

  • 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
Func?ii CUBRID


Open a persistent connection to CUBRID server

cubrid_num_rows
cubrid_pconnect
Func?ii CUBRID
PHP Manual

cubrid_pconnect_with_url

(PECL CUBRID >= 8.3.1)

cubrid_pconnect_with_url — Open a persistent connection to CUBRID server

Descrierea

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> ::= alhosts=<alternative_hosts>[ &rctime=<time>]

<properties> ::= login_timeout=<milli_sec>

<properties> ::= query_timeout=<milli_sec>

<properties> ::= disconnect_on_query_timeout=true|false

<alternative_hosts> ::= <standby_broker1_host>:<port> [,<standby_broker2_host>:<port>]

<host> := HOSTNAME | IP_ADDR

<time> := SECOND

<milli_sec> := MILLI SECOND

  • 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
  • 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.
  • login_timeout : Timeout value (unit: msec.) for database login. The default value is 0, which means infinite postponement.
  • query_timeout : Timeout value (unit: msec.) for query request. Upon timeout, a message to cancel requesting a query transferred to server is sent. The return value can depend on the disconnect_on_query_timeout configuration; even though the message to cancel a request is sent to server, that request may succeed.
  • disconnect_on_query_timeout : Configures a value whether to immediately return an error of function being executed upon timeout. The default value is false.

Nota:

? and : that are used as identifiers in PHP connection URL can't be included in the password. The following is an example of a password that is invalid to use as connection URL because it contains "?:".

$url = "CUBRID:localhost:33000:tdb:dba:12?:?login_timeout=100";

Passwords that contain ? or : may be passed as a separate parameter.

$url = "CUBRID:localhost:33000:tbd:::?login_timeout=100";

$conn = cubrid_pconnect_with_url ($url, "dba", "12?");

If user or password is empty,you can't delete ":",the following is an example.

$url = "CUBRID:localhost:33000:demodb:::";

Parametri

conn_url

A character string that contains server connection information.

userid

User name for the database.

passwd

User password.

Valorile întoarse

Connection identifier, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_pconnect_with_url() url without properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba::"
$con = cubrid_pconnect_with_url ($conn_url);

if ($con) {
   echo "connected successfully";
   cubrid_execute($con, "create table person(id int,name char(16))");
   $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);
}
?>

Example #2 cubrid_pconnect_with_url() url with properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba::?althost=10.34.63.132:33088&rctime=100"
$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);
}
?>

A se vedea ?i

  • 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
Func?ii CUBRID


Open a persistent connection to a CUBRID server

cubrid_pconnect_with_url
cubrid_prepare
Func?ii CUBRID
PHP Manual

cubrid_pconnect

(PECL CUBRID >= 8.3.1)

cubrid_pconnect — Open a persistent connection to a CUBRID server

Descrierea

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'.

Parametri

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.

Valorile întoarse

Connection identifier, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_connect() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_pconnect("localhost", 33000, "demodb", "dba");

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);
?>

Exemplul de mai sus va afi?a:

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

A se vedea ?i

  • 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
Func?ii CUBRID


Prepare a SQL statement for execution

cubrid_pconnect
cubrid_put
Func?ii CUBRID
PHP Manual

cubrid_prepare

(PECL CUBRID >= 8.3.0)

cubrid_prepare — Prepare a SQL statement for execution

Descrierea

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 using the cubrid_bind() function only.

Parametri

conn_identifier

Connection identifier.

prepare_stmt

Prepare query.

option

OID return option CUBRID_INCLUDE_OID.

Valorile întoarse

Request identifier, if process is successful;

FALSE, if process is unsuccessful.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

There are 27 event that exits in 2004 olympic but not in 2000. For example:

Event_code      Event_name
----------------------------
20063           +91kg
20070           64kg

A se vedea ?i

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_bind() - Bind variables to a prepared statement as parameters

cubrid_pconnect
cubrid_put
Func?ii CUBRID


Update a column using OID

cubrid_prepare
cubrid_rollback
Func?ii CUBRID
PHP Manual

cubrid_put

(PECL CUBRID >= 8.3.0)

cubrid_put — Update a column using OID

Descrierea

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, floating 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.

Parametri

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.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_put() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@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);
?>

Exemplul de mai sus va afi?a:

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"
}

A se vedea ?i

  • 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
Func?ii CUBRID


Roll back a transaction

cubrid_put
cubrid_schema
Func?ii CUBRID
PHP Manual

cubrid_rollback

(PECL CUBRID >= 8.3.0)

cubrid_rollback — Roll back a transaction

Descrierea

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.

Parametri

conn_identifier

Connection identifier.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_rollback() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb", "dba");
cubrid_set_autocommit($conn,false);

@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);
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • cubrid_commit() - Commit a transaction
  • cubrid_disconnect() - Close a database connection

cubrid_put
cubrid_schema
Func?ii CUBRID


Get the requested schema information

cubrid_rollback
cubrid_seq_drop
Func?ii CUBRID
PHP Manual

cubrid_schema

(PECL CUBRID >= 8.3.0)

cubrid_schema — Get the requested schema information

Descrierea

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 |

Parametri

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.

Valorile întoarse

Array containing the schema information, when process is successful;

FALSE, when process is unsuccessful

Istoricul schimbarilor

Versiune | Descriere
8.3.1 | Change return value: when process is unsuccessful, return false, not -1.

Exemple

Example #1 cubrid_schema() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

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);
?>

Exemplul de mai sus va afi?a:

--- 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
Func?ii CUBRID


Delete an element from sequence type column using OID

cubrid_schema
cubrid_seq_insert
Func?ii CUBRID
PHP Manual

cubrid_seq_drop

(PECL CUBRID >= 8.3.0)

cubrid_seq_drop — Delete an element from sequence type column using OID

Descrierea

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.

Parametri

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).

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_seq_drop() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@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);
?>

Exemplul de mai sus va afi?a:

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"
}

A se vedea ?i

  • 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
Func?ii CUBRID


Insert an element to a sequence type column using OID

cubrid_seq_drop
cubrid_seq_put
Func?ii CUBRID
PHP Manual

cubrid_seq_insert

(PECL CUBRID >= 8.3.0)

cubrid_seq_insert — Insert an element to a sequence type column using OID

Descrierea

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.

Parametri

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.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_seq_insert() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@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);
?>

Exemplul de mai sus va afi?a:

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"
}

A se vedea ?i

  • 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
Func?ii CUBRID


Update the element value of sequence type column using OID

cubrid_seq_insert
cubrid_set_add
Func?ii CUBRID
PHP Manual

cubrid_seq_put

(PECL CUBRID >= 8.3.0)

cubrid_seq_put — Update the element value of sequence type column using OID

Descrierea

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.

Parametri

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.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_seq_put() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@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);
?>

Exemplul de mai sus va afi?a:

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"
}

A se vedea ?i

  • 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
Func?ii CUBRID


Insert a single element to set type column using OID

cubrid_seq_put
cubrid_set_autocommit
Func?ii CUBRID
PHP Manual

cubrid_set_add

(PECL CUBRID >= 8.3.0)

cubrid_set_add — Insert a single element to set type column using OID

Descrierea

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.

Parametri

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.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_set_add() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@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);
?>

Exemplul de mai sus va afi?a:

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"
}

A se vedea ?i

  • cubrid_seq_drop() - Delete an element from sequence type column using OID

cubrid_seq_put
cubrid_set_autocommit
Func?ii CUBRID


Set autocommit mode of the connection

cubrid_set_add
cubrid_set_db_parameter
Func?ii CUBRID
PHP Manual

cubrid_set_autocommit

(PECL CUBRID >= 8.4.0)

cubrid_set_autocommit — Set autocommit mode of the connection

Descrierea

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, 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.

Parametri

conn_identifier

Connection identifier.

mode

Auto-commit mode. The following constants can be used:

  • CUBRID_AUTOCOMMIT_FALSE
  • CUBRID_AUTOCOMMIT_TRUE

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

A se vedea ?i

  • cubrid_get_autocommit() - Get auto-commit mode of the connection
  • cubrid_commit() - Commit a transaction

cubrid_set_add
cubrid_set_db_parameter
Func?ii CUBRID


Sets the CUBRID database parameters

cubrid_set_autocommit
cubrid_set_drop
Func?ii CUBRID
PHP Manual

cubrid_set_db_parameter

(PECL CUBRID >= 8.4.0)

cubrid_set_db_parameter — Sets the CUBRID database parameters

Descrierea

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

Nota:

The auto-commit mode can be set by using cubrid_set_autocommit().

Parametri

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.

Valorile întoarse

TRUE on success.

FALSE on failure.

Exemple

Example #1 cubrid_get_db_parameter() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$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);
?>

Exemplul de mai sus va afi?a:

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)
}

A se vedea ?i

  • cubrid_get_db_parameter() - Returns the CUBRID database parameters
  • cubrid_set_autocommit() - Set autocommit mode of the connection

cubrid_set_autocommit
cubrid_set_drop
Func?ii CUBRID


Delete an element from set type column using OID

cubrid_set_db_parameter
cubrid_set_query_timeout
Func?ii CUBRID
PHP Manual

cubrid_set_drop

(PECL CUBRID >= 8.3.0)

cubrid_set_drop — Delete an element from set type column using OID

Descrierea

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.

Parametri

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.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_set_drop() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@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);
?>

Exemplul de mai sus va afi?a:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
array(2) {
  [0]=>
  string(1) "2"
  [1]=>
  string(1) "3"
}

A se vedea ?i

  • cubrid_set_add() - Insert a single element to set type column using OID

cubrid_set_db_parameter
cubrid_set_query_timeout
Func?ii CUBRID


Set the timeout time of query execution

cubrid_set_drop
cubrid_version
Func?ii CUBRID
PHP Manual

cubrid_set_query_timeout

(PECL CUBRID >= 8.4.1)

cubrid_set_query_timeout — Set the timeout time of query execution

Descrierea

bool cubrid_set_query_timeout ( resource $req_identifier , int $timeout )

The cubrid_set_query_timeout() function is used to set the timeout time of query execution.

Parametri

req_identifier

Request identifier.

timeout

Timeout time, unit of msec.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

A se vedea ?i

  • cubrid_get_query_timeout() - Get the query timeout value of the request

cubrid_set_drop
cubrid_version
Func?ii CUBRID


Get the CUBRID PHP module's version

cubrid_set_query_timeout
Func?ii CUBRID de compatibilitate MySQL
Func?ii CUBRID
PHP Manual

cubrid_version

(PECL CUBRID >= 8.3.0)

cubrid_version — Get the CUBRID PHP module's version

Descrierea

string cubrid_version ( void )

The cubrid_version() function is used to get the CUBRID PHP module's version.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Version information (eg. "8.3.1.0001").

Exemple

Example #1 cubrid_version() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb", "dba");

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);

?>

Exemplul de mai sus va afi?a:

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

A se vedea ?i

  • 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
Func?ii CUBRID de compatibilitate MySQL
Func?ii CUBRID


Func?ii CUBRID de compatibilitate MySQL

Cuprins

  • cubrid_affected_rows — Return the number of rows affected by the last SQL statement
  • 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 — Fetch the next row and return 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_affected_rows
CUBRID


Return the number of rows affected by the last SQL statement

Func?ii CUBRID de compatibilitate MySQL
cubrid_client_encoding
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_affected_rows

(PECL CUBRID >= 8.3.0)

cubrid_affected_rows — Return the number of rows affected by the last SQL statement

Descrierea

int cubrid_affected_rows ([ resource $conn_identifier ] )
int cubrid_affected_rows ([ resource $req_identifier ] )

The cubrid_affected_rows() function is used to get the number of rows affected by the SQL statement (INSERT, DELETE, UPDATE).

Parametri

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opend by cubrid_connect() is assumed.

req_identifier

Request Identifier, could be returned from either cubrid_prepare() or cubrid_execute(). If the request identifier is not specified, the last identifier requested by cubrid_prepare() or cubrid_execute() is assumed.

Valorile întoarse

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.

Exemple

Example #1 cubrid_affected_rows() example

<?php
$conn = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
cubrid_execute($conn, "DROP TABLE IF EXISTS cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (d varchar)");
$sql_stmt = "INSERT INTO cubrid_test(d) VALUES('php-test')";
$req = cubrid_prepare($conn, $sql_stmt);

for ($i = 0; $i < 10; $i++) {
    cubrid_execute($req);
}
cubrid_commit($conn);

$req = cubrid_execute($conn, "DELETE FROM cubrid_test WHERE d='php-test'", CUBRID_ASYNC);
var_dump(cubrid_affected_rows());
var_dump(cubrid_affected_rows($conn));
var_dump(cubrid_affected_rows($req));

cubrid_disconnect($conn);

print "done!";
?>

Exemplul de mai sus va afi?a:

Rows deleted: 5

A se vedea ?i

  • cubrid_execute() - Execute a prepared SQL statement

Func?ii CUBRID de compatibilitate MySQL
cubrid_client_encoding
Func?ii CUBRID de compatibilitate MySQL


Return the current CUBRID connection charset

cubrid_affected_rows
cubrid_close
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_client_encoding

(PECL CUBRID >= 8.3.1)

cubrid_client_encoding — Return the current CUBRID connection charset

Descrierea

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().

Parametri

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.

Valorile întoarse

A string that represents the CUBRID connection charset; on success.

FALSE on failure.

Exemple

Example #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));

?>

Exemplul de mai sus va afi?a:

CUBRID current charset: iso8859-1

A se vedea ?i

  • cubrid_get_charset() - Return the current CUBRID connection charset

cubrid_affected_rows
cubrid_close
Func?ii CUBRID de compatibilitate MySQL


Close CUBRID connection

cubrid_client_encoding
cubrid_data_seek
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_close

(PECL CUBRID >= 8.3.1)

cubrid_close — Close CUBRID connection

Descrierea

bool cubrid_close ([ resource $conn_identifier ] )

The cubrid_close() function ends the transaction currently in process, closes the connection handle and disconnects from server. If there is any request handles not closed yet at this point, they will be closed. It is similar to the CUBRID function cubrid_disconnect().

Parametri

conn_identifier

The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #1 cubrid_close() example

<?php
$con = cubrid_connect ("localhost", 33000, "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);
}
?>

A se vedea ?i

  • 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
Func?ii CUBRID de compatibilitate MySQL


Move the internal row pointer of the CUBRID result

cubrid_close
cubrid_db_name
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_data_seek

(PECL CUBRID >= 8.3.0)

cubrid_data_seek — Move the internal row pointer of the CUBRID result

Descrierea

bool 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.

Parametri

result

The result.

row_number

This is the desired row number of the new result pointer.

Valorile întoarse

Returns TRUE on success or FALSE on failure.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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
Func?ii CUBRID de compatibilitate MySQL


Get db name from results of cubrid_list_dbs

cubrid_data_seek
cubrid_errno
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_db_name

(PECL CUBRID >= 8.3.1)

cubrid_db_name — Get db name from results of cubrid_list_dbs

Descrierea

string cubrid_db_name ( array $result , int $index )

Retrieve the database name from a call to cubrid_list_dbs().

Parametri

result

The result pointer from a call to cubrid_list_dbs().

index

The index into the result set.

Valorile întoarse

Returns the database name on success, and FALSE on failure. If FALSE is returned, use cubrid_error() to determine the nature of the error.

Exemple

Example #1 cubrid_db_name() example

<?php
error_reporting(E_ALL);

$conn = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
$db_list = cubrid_list_dbs($conn);

$i = 0;
$cnt = count($db_list);
while ($i < $cnt) {
    echo cubrid_db_name($db_list, $i) . "\n";
    $i++;
}
?>

Exemplul de mai sus va afi?a:

demodb

A se vedea ?i

  • cubrid_list_dbs() - Return an array with the list of all existing CUBRID databases

cubrid_data_seek
cubrid_errno
Func?ii CUBRID de compatibilitate MySQL


Return the numerical value of the error message from previous CUBRID operation

cubrid_db_name
cubrid_error
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_errno

(PECL CUBRID >= 8.3.1)

cubrid_errno — Return the numerical value of the error message from previous CUBRID operation

Descrierea

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.

Parametri

conn_identifier

The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Valorile întoarse

Returns the error number from the last CUBRID function, or 0 (zero) if no error occurred.

Exemple

Example #1 cubrid_errno() example

<?php
$con = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
$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);
}
?>

Exemplul de mai sus va afi?a:

Error Code: -493 Error Message: Syntax: Unknown class "person". select id, [name] from person

A se vedea ?i

  • 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
Func?ii CUBRID de compatibilitate MySQL


Get the error message

cubrid_errno
cubrid_fetch_array
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_error

(PECL CUBRID >= 8.3.1)

cubrid_error — Get the error message

Descrierea

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.

Parametri

connection

The CUBRID connection.

Valorile întoarse

Error message that occurred.

Exemple

Example #1 cubrid_error() example

<?php
$con = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
$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);
}
?>

Exemplul de mai sus va afi?a:

Error Code: -493 Error Message: Syntax: Unknown class "person". select id, [name] from person

A se vedea ?i

  • 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
Func?ii CUBRID de compatibilitate MySQL


Fetch a result row as an associative array, a numeric array, or both

cubrid_error
cubrid_fetch_assoc
Func?ii CUBRID de compatibilitate MySQL
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

Descrierea

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.

Parametri

result

Result comes from a call to cubrid_execute()

type

Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH. If you need to operate the lob object, you can use CUBRID_LOB.

Valorile întoarse

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)

Exemple

Example #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]);
}

// if you want to operate LOB object, you can use cubrid_fetch_array($req, CUBRID_NUM | CUBRID_LOB)

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_fetch() - Fetch the next row from a result set
  • cubrid_fetch_row() - Return a numerical array with the values of the current row
  • cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
  • cubrid_fetch_object() - Fetch the next row and return it as an object

cubrid_error
cubrid_fetch_assoc
Func?ii CUBRID de compatibilitate MySQL


Return the associative array that corresponds to the fetched row

cubrid_fetch_array
cubrid_fetch_field
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_fetch_assoc

(PECL CUBRID >= 8.3.0)

cubrid_fetch_assoc — Return the associative array that corresponds to the fetched row

Descrierea

array cubrid_fetch_assoc ( resource $result [, int $type ] )

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.

Parametri

result

result comes from a call to cubrid_execute()

type

Type can only be CUBRID_LOB, this parameter will be used only when you need to operate the lob object.

Valorile întoarse

Associative array, when process is successful.

FALSE, when there are no more rows; NULL, when process is unsuccessful.

Exemple

Example #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"]);
}

// if you want to operate LOB object, you can use cubrid_fetch_assoc($req, CUBRID_LOB)

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_fetch() - Fetch the next row from a result set
  • cubrid_fetch_row() - Return a numerical array with the values of the current row
  • cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • cubrid_fetch_object() - Fetch the next row and return it as an object

cubrid_fetch_array
cubrid_fetch_field
Func?ii CUBRID de compatibilitate MySQL


Get column information from a result and return as an object

cubrid_fetch_assoc
cubrid_fetch_lengths
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_fetch_field

(PECL CUBRID >= 8.3.1)

cubrid_fetch_field — Get column information from a result and return as an object

Descrierea

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

Parametri

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.

Valorile întoarse

Object with certain properties of the specific column, when process is successful.

FALSE on failure.

Exemple

Example #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 length:", $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);
?>

Exemplul de mai sus va afi?a:

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 length:                    0
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
Func?ii CUBRID de compatibilitate MySQL


Return an array with the lengths of the values of each field from the current row

cubrid_fetch_field
cubrid_fetch_object
Func?ii CUBRID de compatibilitate MySQL
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

Descrierea

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.

Nota:

If field data type is BLOB/CLOB, you should get its length by using cubrid_lob_size().

Parametri

result

result comes from a call to cubrid_execute()

Valorile întoarse

An numeric array, when process is successful.

FALSE on failure.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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] => 10
)
cubrid_fetch_field
cubrid_fetch_object
Func?ii CUBRID de compatibilitate MySQL


Fetch the next row and return it as an object

cubrid_fetch_lengths
cubrid_fetch_row
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_fetch_object

(PECL CUBRID >= 8.3.0)

cubrid_fetch_object — Fetch the next row and return it as an object

Descrierea

object cubrid_fetch_object ( resource $result [, string $class_name [, array $params [, int $type ]]] )

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.

Parametri

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.

type

Type can only be CUBRID_LOB, this parameter will be used only when you need to operate the lob object.

Valorile întoarse

An object, when process is successful.

FALSE, when there are no more rows; NULL, when process is unsuccessful.

Exemple

Example #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));

// if you want to operate LOB object, you can use cubrid_fetch_object($res, CUBRID_LOB)

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"));

// if you want to operate LOB object, you can use cubrid_fetch_object($res, "demodb_code", CUBRID_LOB)

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')));

// if you want to operate LOB object, you can use cubrid_fetch_object($res, 'demodb_code_construct', array('s_name', 'f_name'), CUBRID_LOB)

var_dump(cubrid_fetch_object($res));

cubrid_close_request($res);
cubrid_disconnect($conn);
?>

Exemplul de mai sus va afi?a:

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"
}

A se vedea ?i

  • 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_row() - Return a numerical array with the values of the current row

cubrid_fetch_lengths
cubrid_fetch_row
Func?ii CUBRID de compatibilitate MySQL


Return a numerical array with the values of the current row

cubrid_fetch_object
cubrid_field_flags
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_fetch_row

(PECL CUBRID >= 8.3.0)

cubrid_fetch_row — Return a numerical array with the values of the current row

Descrierea

array cubrid_fetch_row ( resource $result [, int $type ] )

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.

Parametri

result

result comes from a call to cubrid_execute()

type

Type can only be CUBRID_LOB, this parameter will be used only when you need to operate the lob object.

Valorile întoarse

A numerical array, when process is successful.

FALSE, when there are no more rows; NULL, when process is unsuccessful.

Exemple

Example #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]);
}

// if you want to operate LOB object, you can use cubrid_fetch_row($req, CUBRID_LOB)

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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_object() - Fetch the next row and return it as an object

cubrid_fetch_object
cubrid_field_flags
Func?ii CUBRID de compatibilitate MySQL


Return a string with the flags of the given field offset

cubrid_fetch_row
cubrid_field_len
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_field_flags

(PECL CUBRID >= 8.3.0)

cubrid_field_flags — Return a string with the flags of the given field offset

Descrierea

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.

Parametri

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.

Valorile întoarse

A string with flags, when process is successful.

FALSE when invalid field_offset value.

-1 if SQL sentence is not SELECT.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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
Func?ii CUBRID de compatibilitate MySQL


Get the maximum length of the specified field

cubrid_field_flags
cubrid_field_name
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_field_len

(PECL CUBRID >= 8.3.0)

cubrid_field_len — Get the maximum length of the specified field

Descrierea

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.

Parametri

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.

Valorile întoarse

Maximum length, when process is successful.

FALSE on failure.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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
medal                          char                           1
game_date                      date                           10
cubrid_field_flags
cubrid_field_name
Func?ii CUBRID de compatibilitate MySQL


Return the name of the specified field index

cubrid_field_len
cubrid_field_seek
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_field_name

(PECL CUBRID >= 8.3.0)

cubrid_field_name — Return the name of the specified field index

Descrierea

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.

Parametri

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.

Valorile întoarse

Name of specified field index, on success.

FALSE on failure.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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
Func?ii CUBRID de compatibilitate MySQL


Move the result set cursor to the specified field offset

cubrid_field_name
cubrid_field_table
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_field_seek

(PECL CUBRID >= 8.3.0)

cubrid_field_seek — Move the result set cursor to the specified field offset

Descrierea

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.

Parametri

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.

Valorile întoarse

TRUE on success.

FALSE on failure.

Exemple

Example #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 length:", $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);
?>

Exemplul de mai sus va afi?a:

array(4) {
  [0]=>
  string(5) "20001"
  [1]=>
  string(5) "16132"
  [2]=>
  string(3) "KOR"
  [3]=>
  string(9) "1988-09-30"
}

--- Field Properties ---
name:                          athlete_code
table:                         game
default value:                 ""
max length:                    0
not null:                      1
unique key:                    1
multiple key:                  0
numeric:                       1
type:                          integer
cubrid_field_name
cubrid_field_table
Func?ii CUBRID de compatibilitate MySQL


Return the name of the table of the specified field

cubrid_field_seek
cubrid_field_type
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_field_table

(PECL CUBRID >= 8.3.0)

cubrid_field_table — Return the name of the table of the specified field

Descrierea

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.

Parametri

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.

Valorile întoarse

Name of the table of the specified field, on success.

FALSE when invalid field_offset value.

-1 if SQL sentence is not SELECT.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

Field Table     Field Name      Field Type
code            s_name          char
code            f_name          varchar
cubrid_field_seek
cubrid_field_type
Func?ii CUBRID de compatibilitate MySQL


Return the type of the column corresponding to the given field offset

cubrid_field_table
cubrid_list_dbs
Func?ii CUBRID de compatibilitate MySQL
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Type of the column, on success.

FALSE when invalid field_offset value.

-1 if SQL sentence is not SELECT.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

Field Table     Field Name      Field Type
code            s_name          char
code            f_name          varchar
cubrid_field_table
cubrid_list_dbs
Func?ii CUBRID de compatibilitate MySQL


Return an array with the list of all existing CUBRID databases

cubrid_field_type
cubrid_num_fields
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_list_dbs

(PECL CUBRID >= 8.3.0)

cubrid_list_dbs — Return an array with the list of all existing CUBRID databases

Descrierea

array cubrid_list_dbs ([ resource $conn_identifier ] )

This function returns an array with the list of all existing Cubrid databases.

Parametri

conn_identifier

The CUBRID connection.

Valorile întoarse

An numeric array with all existing Cubrid databases; on success.

FALSE on failure.

Exemple

Example #1 cubrid_list_dbs() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$db_list = cubrid_list_dbs($conn);
var_dump($db_list);

cubrid_disconnect($conn);
?>

Exemplul de mai sus va afi?a:

array(1) {
  [0]=>
  string(6) "demodb"
}
cubrid_field_type
cubrid_num_fields
Func?ii CUBRID de compatibilitate MySQL


Return the number of columns in the result set

cubrid_list_dbs
cubrid_ping
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_num_fields

(PECL CUBRID >= 8.3.0)

cubrid_num_fields — Return the number of columns in the result set

Descrierea

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.

Parametri

result

result comes from a call to cubrid_execute(), cubrid_query() and cubrid_prepare()

Valorile întoarse

Number of columns, on success.

-1 if SQL sentence is not SELECT.

FALSE when process is unsuccessful.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

Row Num: 6
Column Num: 2
cubrid_list_dbs
cubrid_ping
Func?ii CUBRID de compatibilitate MySQL


Ping a server connection or reconnect if there is no connection

cubrid_num_fields
cubrid_query
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_ping

(PECL CUBRID >= 8.3.1)

cubrid_ping — Ping a server connection or reconnect if there is no connection

Descrierea

bool cubrid_ping ([ resource $conn_identifier ] )

Checks whether or not the connection to the server is working.

Parametri

conn_identifier

The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Valorile întoarse

Returns TRUE if the connection to the server CUBRID server is working, otherwise FALSE.

Exemple

Example #1 cubrid_ping() example

<?php
set_time_limit(0);

$conn = cubrid_connect('localhost', 33000, 'demodb');

/* Assuming this query will take a long time */
$sql = "select * from athlete";
$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 */
$sql2 = "select * from code";
$result2 = cubrid_query($sql2);
?>

cubrid_num_fields
cubrid_query
Func?ii CUBRID de compatibilitate MySQL


Send a CUBRID query

cubrid_ping
cubrid_real_escape_string
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_query

(PECL CUBRID >= 8.3.1)

cubrid_query — Send a CUBRID query

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #1 Invalid Query

The following query is syntactically invalid, so cubrid_query() fails and returns FALSE.

<?php
$conn = cubrid_connect('localhost', 33000, 'demodb');

$result = cubrid_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . cubrid_error());
}

?>

Example #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, 'demodb');

cubrid_execute($conn,"DROP TABLE if exists friends");
cubrid_execute($conn,"create table friends(firstname varchar,lastname varchar,address char(24),age int)");
cubrid_execute($conn,"insert into friends values('fred','fox','home-1','20')");
cubrid_execute($conn,"insert into friends values('blue','cat','home-2','21')");
// 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);
?>

A se vedea ?i

  • 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
Func?ii CUBRID de compatibilitate MySQL


Escape special characters in a string for use in an SQL statement

cubrid_query
cubrid_result
Func?ii CUBRID de compatibilitate MySQL
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Escaped string version of the given string, on success.

FALSE on failure.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

array(1) {
  ["t"]=>
  string(95) " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
}
cubrid_query
cubrid_result
Func?ii CUBRID de compatibilitate MySQL


Return the value of a specific field in a specific row

cubrid_real_escape_string
cubrid_unbuffered_query
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_result

(PECL CUBRID >= 8.3.0)

cubrid_result — Return the value of a specific field in a specific row

Descrierea

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.

Parametri

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.

Valorile întoarse

Value of a specific field, on success (NULL if value if null).

FALSE on failure.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

string(1) "X"
string(5) "Mixed"
string(4) "Gold"
cubrid_real_escape_string
cubrid_unbuffered_query
Func?ii CUBRID de compatibilitate MySQL


Perform a query without fetching the results into memory

cubrid_result
Pseudonime ?i func?ii CUBRID învechite
Func?ii CUBRID de compatibilitate MySQL
PHP Manual

cubrid_unbuffered_query

(PECL CUBRID >= 8.3.0)

cubrid_unbuffered_query — Perform a query without fetching the results into memory

Descrierea

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.

Parametri

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.

Valorile întoarse

For SELECT, SHOW, DESCRIBE or EXPLAIN statements returns a request identifier resource on success.

For other type of SQL statements, UPDATE, DELETE, DROP, etc, returns TRUE on success.

FALSE on failure.

Note

Nota:

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().

Exemple

Example #1 cubrid_unbuffered_query() example

<?php
    $link = cubrid_connect("localhost", 30000, "demodb", "dba", "");
    if (!$link)
    {
        die('Could not connect.');
    }
    $query = "select * from code";
    $result = cubrid_unbuffered_query($query, $link);

    while ($row = cubrid_fetch($result))
    {
        var_dump($row);
    }

    cubrid_close_request($result);
    cubrid_disconnect($link);
?>
cubrid_result
Pseudonime ?i func?ii CUBRID învechite
Func?ii CUBRID de compatibilitate MySQL


Pseudonime ?i func?ii CUBRID învechite

Cuprins

  • 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

Pseudonime ?i func?ii CUBRID învechite
cubrid_new_glo
Pseudonime ?i func?ii CUBRID învechite
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

Descrierea

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.

Parametri

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.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #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";
   }
}
?>

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: cubrid_load_from_glo()

Nota:

This function is removed from CUBRID 3.1.

A se vedea ?i

  • 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

Pseudonime ?i func?ii CUBRID învechite
cubrid_new_glo
Pseudonime ?i func?ii CUBRID învechite


Create a glo instance

cubrid_load_from_glo
cubrid_save_to_glo
Pseudonime ?i func?ii CUBRID învechite
PHP Manual

cubrid_new_glo

(PECL CUBRID >= 8.3.0)

cubrid_new_glo — Create a glo instance

Descrierea

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.

Parametri

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.

Valorile întoarse

Oid of the instance created, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #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);
   }
}
?>

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: cubrid_new_glo()

Nota:

This function is removed from CUBRID 3.1.

A se vedea ?i

  • 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
Pseudonime ?i func?ii CUBRID învechite


Save requested file in a GLO instance

cubrid_new_glo
cubrid_send_glo
Pseudonime ?i func?ii CUBRID învechite
PHP Manual

cubrid_save_to_glo

(PECL CUBRID >= 8.3.0)

cubrid_save_to_glo — Save requested file in a GLO instance

Descrierea

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.

Parametri

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.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #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";
   }
}
?>

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: cubrid_save_to_glo()

Nota:

This function is removed from CUBRID 3.1.

A se vedea ?i

  • 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
Pseudonime ?i func?ii CUBRID învechite


Read data from glo and send it to std output

cubrid_save_to_glo
DB++
Pseudonime ?i func?ii CUBRID învechite
PHP Manual

cubrid_send_glo

(PECL CUBRID >= 8.3.0)

cubrid_send_glo — Read data from glo and send it to std output

Descrierea

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.

Parametri

conn_identifier

Connection identifier.

oid

Oid of the glo instance that you want to read data from.

Valorile întoarse

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Exemple

Example #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);
}
?>

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: cubrid_send_glo()

Nota:

This function is removed from CUBRID 3.1.

A se vedea ?i

  • 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++
Pseudonime ?i func?ii CUBRID învechite


DB++

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
    • db++ error codes
  • Func?ii DB++
    • 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
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

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.

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

DB++
Instalarea / configurarea
DB++


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
DB++


Necesita?i

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).

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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 .

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

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.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Cuprins

  • db++ error codes

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Tipurile resurselor
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 |

Constante predefinite
Func?ii DB++
Constante predefinite


Func?ii DB++

Cuprins

  • 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

Func?ii DB++
dbplus_aql
Func?ii DB++
PHP Manual

dbplus_add

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_add — Add a tuple to a relation

Descrierea

int dbplus_add ( resource $relation , array $tuple )

Adds a tuple to a relation.

Parametri

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.

Valorile întoarse

The function will return DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • dbplus_errcode() - Get error string for given errorcode or last error

Func?ii DB++
dbplus_aql
Func?ii DB++


Perform AQL query

dbplus_add
dbplus_chdir
Func?ii DB++
PHP Manual

dbplus_aql

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_aql — Perform AQL query

Descrierea

resource dbplus_aql ( string $query [, string $server [, string $dbpath ]] )

Executes an AQL query on the given server and dbpath.

Parametri

query

The AQL query to be executed. Further information on the AQL (Algebraic Query Language) is provided in the original db++ manual.

server

dbpath

Valorile întoarse

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.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_add
dbplus_chdir
Func?ii DB++


Get/Set database virtual current directory

dbplus_aql
dbplus_close
Func?ii DB++
PHP Manual

dbplus_chdir

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_chdir — Get/Set database virtual current directory

Descrierea

string dbplus_chdir ([ string $newdir ] )

Changes the virtual current directory where relation files will be looked for by dbplus_open().

Parametri

newdir

The new directory for relation files. You can omit this parameter to query the current working directory.

Valorile întoarse

Returns the absolute path of the current directory.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_aql
dbplus_close
Func?ii DB++


Close a relation

dbplus_chdir
dbplus_curr
Func?ii DB++
PHP Manual

dbplus_close

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_close — Close a relation

Descrierea

mixed dbplus_close ( resource $relation )

Closes a relation previously opened by dbplus_open().

Parametri

relation

A relation opened by dbplus_open().

Valorile întoarse

Returns TRUE on success or DBPLUS_ERR_UNKNOWN on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_chdir
dbplus_curr
Func?ii DB++


Get current tuple from relation

dbplus_close
dbplus_errcode
Func?ii DB++
PHP Manual

dbplus_curr

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_curr — Get current tuple from relation

Descrierea

int dbplus_curr ( resource $relation , array &$tuple )

Reads the data for the current tuple for the given relation.

Parametri

relation

A relation opened by dbplus_open().

tuple

The data will be passed back in this parameter, as an associative array.

Valorile întoarse

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • 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
Func?ii DB++


Get error string for given errorcode or last error

dbplus_curr
dbplus_errno
Func?ii DB++
PHP Manual

dbplus_errcode

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_errcode — Get error string for given errorcode or last error

Descrierea

string dbplus_errcode ([ int $errno ] )

Returns a clear error string for the given error code.

Parametri

errno

The error code. If not provided, the result code of the last db++ operation is assumed.

Valorile întoarse

Returns the error message.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_curr
dbplus_errno
Func?ii DB++


Get error code for last operation

dbplus_errcode
dbplus_find
Func?ii DB++
PHP Manual

dbplus_errno

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_errno — Get error code for last operation

Descrierea

int dbplus_errno ( void )

Returns the error code returned by the last db++ operation.

Valorile întoarse

Returns the error code, as an integer.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • dbplus_errcode() - Get error string for given errorcode or last error

dbplus_errcode
dbplus_find
Func?ii DB++


Set a constraint on a relation

dbplus_errno
dbplus_first
Func?ii DB++
PHP Manual

dbplus_find

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_find — Set a constraint on a relation

Descrierea

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.

Parametri

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

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • dbplus_unselect() - Remove a constraint from relation

dbplus_errno
dbplus_first
Func?ii DB++


Get first tuple from relation

dbplus_find
dbplus_flush
Func?ii DB++
PHP Manual

dbplus_first

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_first — Get first tuple from relation

Descrierea

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.

Parametri

relation

A relation opened by dbplus_open().

tuple

Valorile întoarse

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • 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
Func?ii DB++


Flush all changes made on a relation

dbplus_first
dbplus_freealllocks
Func?ii DB++
PHP Manual

dbplus_flush

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_flush — Flush all changes made on a relation

Descrierea

int dbplus_flush ( resource $relation )

Writes all changes applied to relation since the last flush to disk.

Parametri

relation

A relation opened by dbplus_open().

Valorile întoarse

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • dbplus_errcode() - Get error string for given errorcode or last error

dbplus_first
dbplus_freealllocks
Func?ii DB++


Free all locks held by this client

dbplus_flush
dbplus_freelock
Func?ii DB++
PHP Manual

dbplus_freealllocks

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freealllocks — Free all locks held by this client

Descrierea

int dbplus_freealllocks ( void )

Frees all tuple locks held by this client.

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • 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
Func?ii DB++


Release write lock on tuple

dbplus_freealllocks
dbplus_freerlocks
Func?ii DB++
PHP Manual

dbplus_freelock

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freelock — Release write lock on tuple

Descrierea

int dbplus_freelock ( resource $relation , string $tuple )

Releases a write lock on the given tuple previously obtained by dbplus_getlock().

Parametri

relation

A relation opened by dbplus_open().

tuple

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • 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
Func?ii DB++


Free all tuple locks on given relation

dbplus_freelock
dbplus_getlock
Func?ii DB++
PHP Manual

dbplus_freerlocks

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freerlocks — Free all tuple locks on given relation

Descrierea

int dbplus_freerlocks ( resource $relation )

Frees all tuple locks held on the given relation.

Parametri

relation

A relation opened by dbplus_open().

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • 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
Func?ii DB++


Get a write lock on a tuple

dbplus_freerlocks
dbplus_getunique
Func?ii DB++
PHP Manual

dbplus_getlock

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_getlock — Get a write lock on a tuple

Descrierea

int dbplus_getlock ( resource $relation , string $tuple )

Requests a write lock on the specified tuple.

Parametri

relation

A relation opened by dbplus_open().

tuple

Valorile întoarse

Returns zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • 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
Func?ii DB++


Get an id number unique to a relation

dbplus_getlock
dbplus_info
Func?ii DB++
PHP Manual

dbplus_getunique

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_getunique — Get an id number unique to a relation

Descrierea

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.

Parametri

relation

A relation opened by dbplus_open().

uniqueid

Valorile întoarse

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_getlock
dbplus_info
Func?ii DB++


Get information about a relation

dbplus_getunique
dbplus_last
Func?ii DB++
PHP Manual

dbplus_info

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_info — Get information about a relation

Descrierea

int dbplus_info ( resource $relation , string $key , array &$result )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

relation

A relation opened by dbplus_open().

key

result

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_getunique
dbplus_last
Func?ii DB++


Get last tuple from relation

dbplus_info
dbplus_lockrel
Func?ii DB++
PHP Manual

dbplus_last

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_last — Get last tuple from relation

Descrierea

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.

Parametri

relation

A relation opened by dbplus_open().

tuple

Valorile întoarse

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • 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
Func?ii DB++


Request write lock on relation

dbplus_last
dbplus_next
Func?ii DB++
PHP Manual

dbplus_lockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_lockrel — Request write lock on relation

Descrierea

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.

Parametri

relation

A relation opened by dbplus_open().

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_last
dbplus_next
Func?ii DB++


Get next tuple from relation

dbplus_lockrel
dbplus_open
Func?ii DB++
PHP Manual

dbplus_next

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_next — Get next tuple from relation

Descrierea

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.

Parametri

relation

A relation opened by dbplus_open().

tuple

Valorile întoarse

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • 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
Func?ii DB++


Open relation file

dbplus_next
dbplus_prev
Func?ii DB++
PHP Manual

dbplus_open

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_open — Open relation file

Descrierea

resource dbplus_open ( string $name )

Opens the given relation file.

Parametri

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.

Valorile întoarse

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().

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_next
dbplus_prev
Func?ii DB++


Get previous tuple from relation

dbplus_open
dbplus_rchperm
Func?ii DB++
PHP Manual

dbplus_prev

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_prev — Get previous tuple from relation

Descrierea

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.

Parametri

relation

A relation opened by dbplus_open().

tuple

Valorile întoarse

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • 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
Func?ii DB++


Change relation permissions

dbplus_prev
dbplus_rcreate
Func?ii DB++
PHP Manual

dbplus_rchperm

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rchperm — Change relation permissions

Descrierea

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.

Parametri

relation

A relation opened by dbplus_open().

mask

user

group

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_prev
dbplus_rcreate
Func?ii DB++


Creates a new DB++ relation

dbplus_rchperm
dbplus_rcrtexact
Func?ii DB++
PHP Manual

dbplus_rcreate

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rcreate — Creates a new DB++ relation

Descrierea

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.

Parametri

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.

Nota:

This function will also accept a string with space delimited domain description strings, but it is recommended to use an array

overwrite

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_rchperm
dbplus_rcrtexact
Func?ii DB++


Creates an exact but empty copy of a relation including indices

dbplus_rcreate
dbplus_rcrtlike
Func?ii DB++
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_rcreate
dbplus_rcrtlike
Func?ii DB++


Creates an empty copy of a relation with default indices

dbplus_rcrtexact
dbplus_resolve
Func?ii DB++
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_rcrtexact
dbplus_resolve
Func?ii DB++


Resolve host information for relation

dbplus_rcrtlike
dbplus_restorepos
Func?ii DB++
PHP Manual

dbplus_resolve

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_resolve — Resolve host information for relation

Descrierea

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.

Parametri

relation_name

The relation name.

Valorile întoarse

Returns an array containing these values under the keys sid, host and host_path or FALSE on error.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • dbplus_tcl() - Execute TCL code on server side

dbplus_rcrtlike
dbplus_restorepos
Func?ii DB++


Restore position

dbplus_resolve
dbplus_rkeys
Func?ii DB++
PHP Manual

dbplus_restorepos

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_restorepos — Restore position

Descrierea

int dbplus_restorepos ( resource $relation , array $tuple )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

relation

A relation opened by dbplus_open().

tuple

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_resolve
dbplus_rkeys
Func?ii DB++


Specify new primary key for a relation

dbplus_restorepos
dbplus_ropen
Func?ii DB++
PHP Manual

dbplus_rkeys

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rkeys — Specify new primary key for a relation

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_restorepos
dbplus_ropen
Func?ii DB++


Open relation file local

dbplus_rkeys
dbplus_rquery
Func?ii DB++
PHP Manual

dbplus_ropen

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_ropen — Open relation file local

Descrierea

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.

Parametri

name

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_rkeys
dbplus_rquery
Func?ii DB++


Perform local (raw) AQL query

dbplus_ropen
dbplus_rrename
Func?ii DB++
PHP Manual

dbplus_rquery

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rquery — Perform local (raw) AQL query

Descrierea

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.

Parametri

query

dbpath

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_ropen
dbplus_rrename
Func?ii DB++


Rename a relation

dbplus_rquery
dbplus_rsecindex
Func?ii DB++
PHP Manual

dbplus_rrename

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rrename — Rename a relation

Descrierea

int dbplus_rrename ( resource $relation , string $name )

dbplus_rrename() will change the name of relation to name.

Parametri

relation

A relation opened by dbplus_open().

name

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_rquery
dbplus_rsecindex
Func?ii DB++


Create a new secondary index for a relation

dbplus_rrename
dbplus_runlink
Func?ii DB++
PHP Manual

dbplus_rsecindex

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rsecindex — Create a new secondary index for a relation

Descrierea

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

Parametri

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

Valorile întoarse

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_rrename
dbplus_runlink
Func?ii DB++


Remove relation from filesystem

dbplus_rsecindex
dbplus_rzap
Func?ii DB++
PHP Manual

dbplus_runlink

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_runlink — Remove relation from filesystem

Descrierea

int dbplus_runlink ( resource $relation )

dbplus_runlink() will close and remove the relation.

Parametri

relation

A relation opened by dbplus_open().

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_rsecindex
dbplus_rzap
Func?ii DB++


Remove all tuples from relation

dbplus_runlink
dbplus_savepos
Func?ii DB++
PHP Manual

dbplus_rzap

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rzap — Remove all tuples from relation

Descrierea

int dbplus_rzap ( resource $relation )

dbplus_rzap() will remove all tuples from relation.

Parametri

relation

A relation opened by dbplus_open().

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_runlink
dbplus_savepos
Func?ii DB++


Save position

dbplus_rzap
dbplus_setindex
Func?ii DB++
PHP Manual

dbplus_savepos

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_savepos — Save position

Descrierea

int dbplus_savepos ( resource $relation )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

relation

A relation opened by dbplus_open().

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_rzap
dbplus_setindex
Func?ii DB++


Set index

dbplus_savepos
dbplus_setindexbynumber
Func?ii DB++
PHP Manual

dbplus_setindex

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_setindex — Set index

Descrierea

int dbplus_setindex ( resource $relation , string $idx_name )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

relation

A relation opened by dbplus_open().

idx_name

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_savepos
dbplus_setindexbynumber
Func?ii DB++


Set index by number

dbplus_setindex
dbplus_sql
Func?ii DB++
PHP Manual

dbplus_setindexbynumber

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_setindexbynumber — Set index by number

Descrierea

int dbplus_setindexbynumber ( resource $relation , int $idx_number )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

relation

A relation opened by dbplus_open().

idx_number

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_setindex
dbplus_sql
Func?ii DB++


Perform SQL query

dbplus_setindexbynumber
dbplus_tcl
Func?ii DB++
PHP Manual

dbplus_sql

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_sql — Perform SQL query

Descrierea

resource dbplus_sql ( string $query [, string $server [, string $dbpath ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

query

server

dbpath

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_setindexbynumber
dbplus_tcl
Func?ii DB++


Execute TCL code on server side

dbplus_sql
dbplus_tremove
Func?ii DB++
PHP Manual

dbplus_tcl

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_tcl — Execute TCL code on server side

Descrierea

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.

Parametri

sid

script

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • dbplus_resolve() - Resolve host information for relation

dbplus_sql
dbplus_tremove
Func?ii DB++


Remove tuple and return new current tuple

dbplus_tcl
dbplus_undo
Func?ii DB++
PHP Manual

dbplus_tremove

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_tremove — Remove tuple and return new current tuple

Descrierea

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().

Parametri

relation

A relation opened by dbplus_open().

tuple

current

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_tcl
dbplus_undo
Func?ii DB++


Undo

dbplus_tremove
dbplus_undoprepare
Func?ii DB++
PHP Manual

dbplus_undo

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_undo — Undo

Descrierea

int dbplus_undo ( resource $relation )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

relation

A relation opened by dbplus_open().

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_tremove
dbplus_undoprepare
Func?ii DB++


Prepare undo

dbplus_undo
dbplus_unlockrel
Func?ii DB++
PHP Manual

dbplus_undoprepare

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_undoprepare — Prepare undo

Descrierea

int dbplus_undoprepare ( resource $relation )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

relation

A relation opened by dbplus_open().

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_undo
dbplus_unlockrel
Func?ii DB++


Give up write lock on relation

dbplus_undoprepare
dbplus_unselect
Func?ii DB++
PHP Manual

dbplus_unlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_unlockrel — Give up write lock on relation

Descrierea

int dbplus_unlockrel ( resource $relation )

Release a write lock previously obtained by dbplus_lockrel().

Parametri

relation

A relation opened by dbplus_open().

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_undoprepare
dbplus_unselect
Func?ii DB++


Remove a constraint from relation

dbplus_unlockrel
dbplus_update
Func?ii DB++
PHP Manual

dbplus_unselect

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_unselect — Remove a constraint from relation

Descrierea

int dbplus_unselect ( resource $relation )

Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.

Parametri

relation

A relation opened by dbplus_open().

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_unlockrel
dbplus_update
Func?ii DB++


Update specified tuple in relation

dbplus_unselect
dbplus_xlockrel
Func?ii DB++
PHP Manual

dbplus_update

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_update — Update specified tuple in relation

Descrierea

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.

Parametri

relation

A relation opened by dbplus_open().

old

The old tuple.

new

The new tuple.

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_unselect
dbplus_xlockrel
Func?ii DB++


Request exclusive lock on relation

dbplus_update
dbplus_xunlockrel
Func?ii DB++
PHP Manual

dbplus_xlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_xlockrel — Request exclusive lock on relation

Descrierea

int dbplus_xlockrel ( resource $relation )

Request an exclusive lock on relation preventing even read access from other clients.

Parametri

relation

A relation opened by dbplus_open().

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • dbplus_xunlockrel() - Free exclusive lock on relation

dbplus_update
dbplus_xunlockrel
Func?ii DB++


Free exclusive lock on relation

dbplus_xlockrel
dBase
Func?ii DB++
PHP Manual

dbplus_xunlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_xunlockrel — Free exclusive lock on relation

Descrierea

int dbplus_xunlockrel ( resource $relation )

Releases an exclusive lock previously obtained by dbplus_xlockrel().

Parametri

relation

A relation opened by dbplus_open().

Valorile întoarse

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

dbplus_xlockrel
dBase
Func?ii DB++


dBase

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • dBase Func?ii
    • 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
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.3.0.

These functions allow you to access records stored in dBase-format (dbf) databases.

Avertizare

We recommend against using dBase files as your production database. Use » SQLite or 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.

Precautie

As of dbase 7.0.0 the databases are automatically locked via flock(). There has been no support for locking earlier, so two concurrent web server processes modifying the same dBase file would have very likely ruined your database. This can happen even with dbase 7.0.0+ on systems which implement the locks at the process level with multithreaded SAPIs such as ISAPI.

dBase files are simple sequential files of fixed length records. Records are appended to the end of the file and deleted records are kept until you call dbase_pack().

Only dbf file levels 3 (dBASE III+) - 5 (dBASE V) are supported. 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
T | DateTime | YYYYMMDDhhmmss.uuu | (FoxPro) No validity checks are done. Available as of dbase 7.0.0.
N | Number | A number | You must declare a length and a precision (the number of digits after the decimal point).
F | Float | A float number | Same as N. Available as of PHP 5.2.0
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. Overlong strings will be silently truncated when storing data.
L | Boolean | T or Y for TRUE, F or N for FALSE, ? for uninitialized. | As of dbase 7.0.0, returned as a bool (TRUE or FALSE), or NULL for uninitialized fields. Formerly, returned as an int (1 or 0).

Nota:

As of dbase 7.0.0 nullable fields are supported for DBASE_TYPE_FOXPRO databases. If a field is nullable, passing NULL will set the respective flag, and on later retrieval the field value will be NULL.

Nota:

There is no support for indexes or memo fields.

dBase
Instalarea / configurarea
dBase


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
dBase


Instalarea

Pentru a activa biblioteca dbase ?i a utiliza aceste func?ii, PHP trebuie compilat cu op?iunea --enable-dbase .

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

As of dbase 7.0.0, the resource type dbase is defined, which is returned by dbase_open() and dbase_create().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
dBase Func?ii
dBase


dBase Func?ii

Exemple

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().

Cuprins

  • 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
Constante predefinite
dbase_add_record
dBase


Adds a record to a database

dBase Func?ii
dbase_close
dBase Func?ii
PHP Manual

dbase_add_record

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_add_record — Adds a record to a database

Descrierea

bool dbase_add_record ( resource $dbase_identifier , array $record )

Adds the given data to the database.

Parametri

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.

Nota:

If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
dbase 7.0.0 | dbase_identifier is now a resource instead of an int.

Exemple

Example #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);
}

?>

A se vedea ?i

  • dbase_delete_record() - Deletes a record from a database
  • dbase_replace_record() - Replaces a record in a database

dBase Func?ii
dbase_close
dBase Func?ii


Closes a database

dbase_add_record
dbase_create
dBase Func?ii
PHP Manual

dbase_close

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_close — Closes a database

Descrierea

bool dbase_close ( resource $dbase_identifier )

Closes the given database link identifier.

Parametri

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
dbase 7.0.0 | dbase_identifier is now a resource instead of an int.

Exemple

Example #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);
}

?>

A se vedea ?i

  • dbase_open() - Opens a database
  • dbase_create() - Creates a database

dbase_add_record
dbase_create
dBase Func?ii


Creates a database

dbase_close
dbase_delete_record
dBase Func?ii
PHP Manual

dbase_create

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_create — Creates a database

Descrierea

resource dbase_create ( string $filename , array $fields , int $type = DBASE_TYPE_DBASE )

dbase_create() creates a dBase database with the given definition. If the file already exists, it is not truncated. dbase_pack() can be called to force truncation.

Nota: Când este activat modul securizat, PHP verifica daca fi?ierele ?i directoarele cu care se va opera au acela?i UID (proprietar) ca ?i script-ul care se executa.

Nota:

Aceasta func?ie este afectata de open_basedir.

Parametri

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, a precision and a nullable flag. The supported field types are listed in the introduction section.

Nota:

The fieldnames are limited in length and must not exceed 10 chars.

type

The type of database to be created. Either DBASE_TYPE_DBASE or DBASE_TYPE_FOXPRO.

Nota:

The fieldnames are limited in length and must not exceed 10 chars.

Valorile întoarse

Returns a database link identifier if the database is successfully created, or FALSE if an error occurred.

Istoricul schimbarilor

Versiune | Descriere
dbase 7.0.0 | The return value is now a resource instead of an int.

Exemple

Example #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";
}

?>

A se vedea ?i

  • dbase_open() - Opens a database
  • dbase_close() - Closes a database

dbase_close
dbase_delete_record
dBase Func?ii


Deletes a record from a database

dbase_create
dbase_get_header_info
dBase Func?ii
PHP Manual

dbase_delete_record

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_delete_record — Deletes a record from a database

Descrierea

bool dbase_delete_record ( resource $dbase_identifier , int $record_number )

Marks the given record to be deleted from the database.

Nota:

To actually remove the record from the database, you must also call dbase_pack().

Parametri

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()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
dbase 7.0.0 | dbase_identifier is now a resource instead of an int.

A se vedea ?i

  • 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 Func?ii


Gets the header info of a database

dbase_delete_record
dbase_get_record_with_names
dBase Func?ii
PHP Manual

dbase_get_header_info

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_get_header_info — Gets the header info of a database

Descrierea

array dbase_get_header_info ( resource $dbase_identifier )

Returns information on the column structure of the given database link identifier.

Parametri

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Valorile întoarse

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.) The supported field types are listed in the introduction section.
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.

Istoricul schimbarilor

Versiune | Descriere
dbase 7.0.0 | dbase_identifier is now a resource instead of an int.

Exemple

Example #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 Func?ii


Gets a record from a database as an associative array

dbase_get_header_info
dbase_get_record
dBase Func?ii
PHP Manual

dbase_get_record_with_names

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_get_record_with_names — Gets a record from a database as an associative array

Descrierea

array dbase_get_record_with_names ( resource $dbase_identifier , int $record_number )

Gets a record from a dBase database as an associative array.

Parametri

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

The index of the record between 1 and dbase_numrecords($dbase_identifier).

Valorile întoarse

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()). Therefore it is not possible to retrieve the value of a field named deleted with this function.

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings.
  • DateTime values are converted to strings.
  • Integers outside the range PHP_INT_MIN..PHP_INT_MAX are returned as strings.
  • Before dbase 7.0.0, booleans (L) were converted to 1 or 0.

On error, dbase_get_record_with_names() will return FALSE.

Istoricul schimbarilor

Versiune | Descriere
dbase 7.0.0 | dbase_identifier is now a resource instead of an int.

Exemple

Example #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";
      }
  }
}
?>

A se vedea ?i

  • dbase_get_record() - Gets a record from a database as an indexed array

dbase_get_header_info
dbase_get_record
dBase Func?ii


Gets a record from a database as an indexed array

dbase_get_record_with_names
dbase_numfields
dBase Func?ii
PHP Manual

dbase_get_record

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_get_record — Gets a record from a database as an indexed array

Descrierea

array dbase_get_record ( resource $dbase_identifier , int $record_number )

Gets a record from a database as an indexed array.

Parametri

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

The index of the record between 1 and dbase_numrecords($dbase_identifier).

Valorile întoarse

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.
  • DateTime values are converted to strings.
  • Integers outside the range PHP_INT_MIN..PHP_INT_MAX are returned as strings.
  • Before dbase 7.0.0, booleans (L) were converted to 1 or 0.

On error, dbase_get_record() will return FALSE.

Istoricul schimbarilor

Versiune | Descriere
dbase 7.0.0 | dbase_identifier is now a resource instead of an int.

A se vedea ?i

  • dbase_get_record_with_names() - Gets a record from a database as an associative array

dbase_get_record_with_names
dbase_numfields
dBase Func?ii


Gets the number of fields of a database

dbase_get_record
dbase_numrecords
dBase Func?ii
PHP Manual

dbase_numfields

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_numfields — Gets the number of fields of a database

Descrierea

int dbase_numfields ( resource $dbase_identifier )

Gets the number of fields (columns) in the specified database.

Nota:

Field numbers are between 0 and dbase_numfields($db)-1, while record numbers are between 1 and dbase_numrecords($db).

Parametri

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Valorile întoarse

The number of fields in the database, or FALSE if an error occurs.

Istoricul schimbarilor

Versiune | Descriere
dbase 7.0.0 | dbase_identifier is now a resource instead of an int.

Exemple

Example #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";
}

?>

A se vedea ?i

  • dbase_numrecords() - Gets the number of records in a database

dbase_get_record
dbase_numrecords
dBase Func?ii


Gets the number of records in a database

dbase_numfields
dbase_open
dBase Func?ii
PHP Manual

dbase_numrecords

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_numrecords — Gets the number of records in a database

Descrierea

int dbase_numrecords ( resource $dbase_identifier )

Gets the number of records (rows) in the specified database.

Nota:

Record numbers are between 1 and dbase_numrecords($db), while field numbers are between 0 and dbase_numfields($db)-1.

Parametri

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Valorile întoarse

The number of records in the database, or FALSE if an error occurs.

Istoricul schimbarilor

Versiune | Descriere
dbase 7.0.0 | dbase_identifier is now a resource instead of an int.

Exemple

Example #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
  }
}

?>

A se vedea ?i

  • dbase_numfields() - Gets the number of fields of a database

dbase_numfields
dbase_open
dBase Func?ii


Opens a database

dbase_numrecords
dbase_pack
dBase Func?ii
PHP Manual

dbase_open

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_open — Opens a database

Descrierea

resource dbase_open ( string $filename , int $mode )

dbase_open() opens a dBase database with the given access mode.

Nota: Când este activat modul securizat, PHP verifica daca fi?ierele ?i directoarele cu care se va opera au acela?i UID (proprietar) ca ?i script-ul care se executa.

Nota:

Aceasta func?ie este afectata de open_basedir.

Parametri

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).

Nota:

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.

As of dbase 7.0.0 you can use DBASE_RDONLY and DBASE_RDWR, respectively, to specify the mode.

Istoricul schimbarilor

Versiune | Descriere
dbase 7.0.0 | The return value is now a resource instead of an int.

Exemple

Example #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);
}

?>

Valorile întoarse

Returns a database link identifier if the database is successfully opened, or FALSE if an error occurred.

A se vedea ?i

  • dbase_create() - Creates a database
  • dbase_close() - Closes a database

dbase_numrecords
dbase_pack
dBase Func?ii


Packs a database

dbase_open
dbase_replace_record
dBase Func?ii
PHP Manual

dbase_pack

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_pack — Packs a database

Descrierea

bool dbase_pack ( resource $dbase_identifier )

Packs the specified database by permanently deleting all records marked for deletion using dbase_delete_record(). Note that the file will be truncated after successful packing (contrary to dBASE III's PACK command).

Parametri

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
dbase 7.0.0 | dbase_identifier is now a resource instead of an int.

Exemple

Example #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);
}

?>

A se vedea ?i

  • dbase_delete_record() - Deletes a record from a database

dbase_open
dbase_replace_record
dBase Func?ii


Replaces a record in a database

dbase_pack
filePro
dBase Func?ii
PHP Manual

dbase_replace_record

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_replace_record — Replaces a record in a database

Descrierea

bool dbase_replace_record ( resource $dbase_identifier , array $record , int $record_number )

Replaces the given record in the database with the given data.

Parametri

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.

Nota:

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()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
dbase 7.0.0 | dbase_identifier is now a resource instead of an int.

Exemple

Example #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');

  // convert the row to an indexed array
  $row = array_values($row);

  // Replace the record
  dbase_replace_record($db, $row, 1);
  dbase_close($db);
}

?>

Note

Nota:

Boolean fields result in an integer element value (0 or 1) when retrieved via dbase_get_record() or dbase_get_record_with_names(). If they are written back, this results in the value becoming 0, so care has to be taken to properly adjust the values.

A se vedea ?i

  • dbase_add_record() - Adds a record to a database
  • dbase_delete_record() - Deletes a record from a database

dbase_pack
filePro
dBase Func?ii


filePro

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii filePro
    • 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
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

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/.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.2.0.

filePro
Instalarea / configurarea
filePro


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
filePro


Instalarea

Sus?inerea filePro în PHP nu este activata în mod implicit. Pentru a activa sus?inerea filePro în regim numai pentru citire trebuie sa utiliza?i op?iunea de configurare --enable-filepro la compilarea PHP.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii filePro
filePro


Func?ii filePro

Cuprins

  • 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
Constante predefinite
filepro_fieldcount
filePro


Find out how many fields are in a filePro database

Func?ii filePro
filepro_fieldname
Func?ii filePro
PHP Manual

filepro_fieldcount

(PHP 4, PHP 5 <= 5.1.6, PHP 7)

filepro_fieldcount — Find out how many fields are in a filePro database

Descrierea

int filepro_fieldcount ( void )

Returns the number of fields (columns) in the opened filePro database.

Valorile întoarse

Returns the number of fields in the opened filePro database, or FALSE on errors.

A se vedea ?i

  • filepro() - Read and verify the map file

Func?ii filePro
filepro_fieldname
Func?ii filePro


Gets the name of a field

filepro_fieldcount
filepro_fieldtype
Func?ii filePro
PHP Manual

filepro_fieldname

(PHP 4, PHP 5 <= 5.1.6, PHP 7)

filepro_fieldname — Gets the name of a field

Descrierea

string filepro_fieldname ( int $field_number )

Returns the name of the field corresponding to field_number.

Parametri

field_number

The field number.

Valorile întoarse

Returns the name of the field as a string, or FALSE on errors.

filepro_fieldcount
filepro_fieldtype
Func?ii filePro


Gets the type of a field

filepro_fieldname
filepro_fieldwidth
Func?ii filePro
PHP Manual

filepro_fieldtype

(PHP 4, PHP 5 <= 5.1.6, PHP 7)

filepro_fieldtype — Gets the type of a field

Descrierea

string filepro_fieldtype ( int $field_number )

Returns the edit type of the field corresponding to field_number.

Parametri

field_number

The field number.

Valorile întoarse

Returns the edit type of the field as a string, or FALSE on errors.

filepro_fieldname
filepro_fieldwidth
Func?ii filePro


Gets the width of a field

filepro_fieldtype
filepro_retrieve
Func?ii filePro
PHP Manual

filepro_fieldwidth

(PHP 4, PHP 5 <= 5.1.6, PHP 7)

filepro_fieldwidth — Gets the width of a field

Descrierea

int filepro_fieldwidth ( int $field_number )

Returns the width of the field corresponding to field_number.

Parametri

field_number

The field number.

Valorile întoarse

Returns the width of the field as a integer, or FALSE on errors.

filepro_fieldtype
filepro_retrieve
Func?ii filePro


Retrieves data from a filePro database

filepro_fieldwidth
filepro_rowcount
Func?ii filePro
PHP Manual

filepro_retrieve

(PHP 4, PHP 5 <= 5.1.6, PHP 7)

filepro_retrieve — Retrieves data from a filePro database

Descrierea

string filepro_retrieve ( int $row_number , int $field_number )

Returns the data from the specified location in the database.

Nota: Când este activat modul securizat, PHP verifica daca fi?ierele ?i directoarele cu care se va opera au acela?i UID (proprietar) ca ?i script-ul care se executa.

Parametri

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)

Valorile întoarse

Returns the specified data, or FALSE on errors.

filepro_fieldwidth
filepro_rowcount
Func?ii filePro


Find out how many rows are in a filePro database

filepro_retrieve
filepro
Func?ii filePro
PHP Manual

filepro_rowcount

(PHP 4, PHP 5 <= 5.1.6, PHP 7)

filepro_rowcount — Find out how many rows are in a filePro database

Descrierea

int filepro_rowcount ( void )

Returns the number of rows in the opened filePro database.

Nota: Când este activat modul securizat, PHP verifica daca fi?ierele ?i directoarele cu care se va opera au acela?i UID (proprietar) ca ?i script-ul care se executa.

Valorile întoarse

Returns the number of rows in the opened filePro database, or FALSE on errors.

A se vedea ?i

  • filepro() - Read and verify the map file

filepro_retrieve
filepro
Func?ii filePro


Read and verify the map file

filepro_rowcount
Firebird/InterBase
Func?ii filePro
PHP Manual

filepro

(PHP 4, PHP 5 <= 5.1.6, PHP 7)

filepro — Read and verify the map file

Descrierea

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.

Nota: Când este activat modul securizat, PHP verifica daca fi?ierele ?i directoarele cu care se va opera au acela?i UID (proprietar) ca ?i script-ul care se executa.

Parametri

directory

The map directory.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

filepro_rowcount
Firebird/InterBase
Func?ii filePro


Firebird/InterBase

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Firebird/InterBase
    • ibase_add_user — Add a user to a security database
    • 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_blob_add — Add data into a newly created blob
    • ibase_blob_cancel — Cancel creating blob
    • ibase_blob_close — Close blob
    • ibase_blob_create — Create a new blob for adding data
    • ibase_blob_echo — Output blob contents to browser
    • ibase_blob_get — Get len bytes data from open blob
    • ibase_blob_import — Create blob, copy file in it, and close it
    • ibase_blob_info — Return blob length and other useful info
    • ibase_blob_open — Open blob for retrieving data parts
    • ibase_close — Close a connection to an InterBase database
    • ibase_commit_ret — Commit a transaction without closing it
    • ibase_commit — Commit a transaction
    • ibase_connect — Open a connection to a database
    • ibase_db_info — Request statistics about a database
    • ibase_delete_user — Delete a user from a security database
    • ibase_drop_db — Drops a database
    • ibase_errcode — Return an error code
    • ibase_errmsg — Return error messages
    • ibase_execute — Execute a previously prepared query
    • ibase_fetch_assoc — Fetch a result row from a query as an associative array
    • ibase_fetch_object — Get an object from a InterBase database
    • ibase_fetch_row — Fetch a row from an InterBase database
    • ibase_field_info — Get information about a field
    • ibase_free_event_handler — Cancels a registered event handler
    • ibase_free_query — Free memory allocated by a prepared query
    • ibase_free_result — Free a result set
    • ibase_gen_id — Increments the named generator and returns its new value
    • ibase_maintain_db — Execute a maintenance command on the database server
    • ibase_modify_user — Modify a user to a security database
    • ibase_name_result — Assigns a name to a result set
    • ibase_num_fields — Get the number of fields in 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_pconnect — Open a persistent connection to an InterBase database
    • ibase_prepare — Prepare a query for later binding of parameter placeholders and execution
    • ibase_query — Execute a query on an InterBase database
    • ibase_restore — Initiates a restore task in the service manager and returns immediately
    • ibase_rollback_ret — Roll back a transaction without closing it
    • ibase_rollback — Roll back a transaction
    • ibase_server_info — Request information 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_trans — Begin a transaction
    • ibase_wait_event — Wait for an event to be posted by the database
filepro
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

Firebird is a relational database offering many ISO SQL-2003 features that runs on Linux, Windows, and a variety of Unix platforms. Firebird offers excellent concurrency, high performance, and powerful language support for stored procedures and triggers. It has been used in production systems, under a variety of names since 1981.

InterBase is the name of the closed-source variant of this RDBMS that was developed by Embarcadero/Inprise. More information about InterBase is available at » http://www.embarcadero.com/products/interbase.

Firebird is a commercially independent project (fundation) of C++ programmers, technical advisors and supporters developing and enhancing a multi-platform relational database management system based on the source code released by Inprise Corp (now known as Embarcadero) under the InterBase Public License v.1.0 on 25 July, 2000. More information about Firebird is available at » http://www.firebirdsql.org/.

Nota:

This extension supports InterBase versions 6 and up and Firebird version 2.0 and up.

This database uses a single quote (') character for escaping add to your php.ini the following directive(Deprecated in PHP 5.3.0. Removed in PHP 5.4.0):

magic_quotes_sybase = On

Firebird/InterBase
Instalarea / configurarea
Firebird/InterBase


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Firebird/InterBase


Instalarea

To enable Firebird/InterBase support configure PHP --with-interbase[=DIR] , where DIR is the Firebird/InterBase base install directory, which defaults to /usr.

Nota: Note to Win32/Win64 Users

Pentru ca aceasta extensie sa func?ioneze, anumite fi?iere DLL trebuie sa fie accesibile în calea de sistem a Windows din variabila PATH. Pentru informa?ii despre cum poate fi realizat acest lucru, accesa?i FAQ întitulat " Cum sa adaug directorul meu PHP la variabila PATH din Windows" pentru informa?ii despre cum sa realiza?i aceasta. Cu toate ca copierea fi?ierelor DLL din directorul PHP în directorul de sistem al Windows de asemenea func?ioneaza (deoarece directorul de sistem este în mod implicit inclus în variabila PATH), acest lucru nu este recomandabil. Aceasta extensie necesita ca urmatoarele fi?iere sa existe în calea PATH : fbclient.dll,gds32.dll

If you installed the Firebird/InterBase database server on the same machine PHP is running on, you will have this DLL already and fbclient.dll,gds32.dll (gds32.dll is generated from the installer for legacy applications) will already be in the PATH.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

InterBase configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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 | Available since 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 | Available since 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 |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

ibase.allow_persistent boolean

Whether to allow persistent connections to Firebird/InterBase.

ibase.max_persistent integer

The maximum number of persistent Firebird/InterBase connections per process. New connections created with ibase_pconnect() will be non-persistent if this number would be exceeded.

ibase.max_links integer

The maximum number of Firebird/InterBase connections per process, including persistent connections.

ibase.default_db string

The default database to connect to when ibase_[p]connect() is called without specifying a database name. If this value is set and SQL safe mode is enabled, no other connections than to this database will be allowed.

ibase.default_user string

The user name to use when connecting to a database if no user name is specified.

ibase.default_password string

The password to use when connecting to a database if no password is specified.

ibase.default_charset string

The character set to use when connecting to a database if no character set is specified.

ibase.timestampformat string

ibase.dateformat string

ibase.timeformat string

These directives are used to set the date and time formats that are used when returning dates and times from a result set, or when binding arguments to date and time parameters.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

The following constants can be passed to ibase_trans() to specify transaction behaviour.

Firebird/InterBase transaction flags
Constant | Description
IBASE_DEFAULT | The default transaction settings are to be used. This default is determined by the client library, which defines it as IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT in most cases.
IBASE_READ | Starts a read-only transaction.
IBASE_WRITE | Starts a read-write transaction.
IBASE_CONSISTENCY | Starts a transaction with the isolation level set to 'consistency', which means the transaction cannot read from tables that are being modified by other concurrent transactions.
IBASE_CONCURRENCY | Starts a transaction with the isolation level set to 'concurrency' (or 'snapshot'), which means the transaction has access to all tables, but cannot see changes that were committed by other transactions after the transaction was started.
IBASE_COMMITTED | Starts a transaction with the isolation level set to 'read committed'. This flag should be combined with either IBASE_REC_VERSION or IBASE_REC_NO_VERSION. This isolation level allows access to changes that were committed after the transaction was started. If IBASE_REC_NO_VERSION was specified, only the latest version of a row can be read. If IBASE_REC_VERSION was specified, a row can even be read when a modification to it is pending in a concurrent transaction.
IBASE_WAIT | Indicated that a transaction should wait and retry when a conflict occurs.
IBASE_NOWAIT | Indicated that a transaction should fail immediately when a conflict occurs.

The following constants can be passed to ibase_fetch_row(), ibase_fetch_assoc() or ibase_fetch_object() to specify fetch behaviour.

Firebird/InterBase fetch flags
Constant | Description
IBASE_FETCH_BLOBS | Also available as IBASE_TEXTfor backward compatibility. Causes BLOB contents to be fetched inline, instead of being fetched as BLOB identifiers.
IBASE_FETCH_ARRAYS | Causes arrays to be fetched inline. Otherwise, array identifiers are returned. Array identifiers can only be used as arguments to INSERT operations, as no functions to handle array identifiers are currently available.
IBASE_UNIXTIME | Causes date and time fields not to be returned as strings, but as UNIX timestamps (the number of seconds since the epoch, which is 1-Jan-1970 0:00 UTC). Might be problematic if used with dates before 1970 on some systems.

The following constants are used to pass requests and options to the service
API functions (ibase_server_info(), ibase_db_info(),
ibase_backup(), ibase_restore()
and ibase_maintain_db()). Please refer to
the Firebird/InterBase manuals for the meaning of these options.

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
Options to 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
Options to 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
Options to ibase_maintain_db()
IBASE_STS_DATA_PAGES
IBASE_STS_DB_LOG
IBASE_STS_HDR_PAGES
IBASE_STS_IDX_PAGES
IBASE_STS_SYS_RELATIONS
Options to 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
Options to ibase_server_info()

Tipurile resurselor
Func?ii Firebird/InterBase
Firebird/InterBase


Func?ii Firebird/InterBase

Cuprins

  • ibase_add_user — Add a user to a security database
  • 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_blob_add — Add data into a newly created blob
  • ibase_blob_cancel — Cancel creating blob
  • ibase_blob_close — Close blob
  • ibase_blob_create — Create a new blob for adding data
  • ibase_blob_echo — Output blob contents to browser
  • ibase_blob_get — Get len bytes data from open blob
  • ibase_blob_import — Create blob, copy file in it, and close it
  • ibase_blob_info — Return blob length and other useful info
  • ibase_blob_open — Open blob for retrieving data parts
  • ibase_close — Close a connection to an InterBase database
  • ibase_commit_ret — Commit a transaction without closing it
  • ibase_commit — Commit a transaction
  • ibase_connect — Open a connection to a database
  • ibase_db_info — Request statistics about a database
  • ibase_delete_user — Delete a user from a security database
  • ibase_drop_db — Drops a database
  • ibase_errcode — Return an error code
  • ibase_errmsg — Return error messages
  • ibase_execute — Execute a previously prepared query
  • ibase_fetch_assoc — Fetch a result row from a query as an associative array
  • ibase_fetch_object — Get an object from a InterBase database
  • ibase_fetch_row — Fetch a row from an InterBase database
  • ibase_field_info — Get information about a field
  • ibase_free_event_handler — Cancels a registered event handler
  • ibase_free_query — Free memory allocated by a prepared query
  • ibase_free_result — Free a result set
  • ibase_gen_id — Increments the named generator and returns its new value
  • ibase_maintain_db — Execute a maintenance command on the database server
  • ibase_modify_user — Modify a user to a security database
  • ibase_name_result — Assigns a name to a result set
  • ibase_num_fields — Get the number of fields in 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_pconnect — Open a persistent connection to an InterBase database
  • ibase_prepare — Prepare a query for later binding of parameter placeholders and execution
  • ibase_query — Execute a query on an InterBase database
  • ibase_restore — Initiates a restore task in the service manager and returns immediately
  • ibase_rollback_ret — Roll back a transaction without closing it
  • ibase_rollback — Roll back a transaction
  • ibase_server_info — Request information 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_trans — Begin a transaction
  • ibase_wait_event — Wait for an event to be posted by the database
Constante predefinite
ibase_add_user
Firebird/InterBase


Add a user to a security database

Func?ii Firebird/InterBase
ibase_affected_rows
Func?ii Firebird/InterBase
PHP Manual

ibase_add_user

(PHP 5, PHP 7)

ibase_add_user — Add a user to a security database

Descrierea

bool ibase_add_user ( resource $service_handle , string $user_name , string $password [, string $first_name [, string $middle_name [, string $last_name ]]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ibase_modify_user() - Modify a user to a security database
  • ibase_delete_user() - Delete a user from a security database

Func?ii Firebird/InterBase
ibase_affected_rows
Func?ii Firebird/InterBase


Return the number of rows that were affected by the previous query

ibase_add_user
ibase_backup
Func?ii Firebird/InterBase
PHP Manual

ibase_affected_rows

(PHP 5, PHP 7)

ibase_affected_rows — Return the number of rows that were affected by the previous query

Descrierea

int ibase_affected_rows ([ resource $link_identifier ] )

This function returns the number of rows that were affected by the previous query (INSERT, UPDATE or DELETE) that was executed from within the specified transaction context.

Parametri

link_identifier

A transaction context. If link_identifier is a connection resource, its default transaction is used.

Valorile întoarse

Returns the number of rows as an integer.

A se vedea ?i

  • ibase_query() - Execute a query on an InterBase database
  • ibase_execute() - Execute a previously prepared query

ibase_add_user
ibase_backup
Func?ii Firebird/InterBase


Initiates a backup task in the service manager and returns immediately

ibase_affected_rows
ibase_blob_add
Func?ii Firebird/InterBase
PHP Manual

ibase_backup

(PHP 5, PHP 7)

ibase_backup — Initiates a backup task in the service manager and returns immediately

Descrierea

mixed ibase_backup ( resource $service_handle , string $source_db , string $dest_file [, int $options = 0 [, bool $verbose = false ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ibase_affected_rows
ibase_blob_add
Func?ii Firebird/InterBase


Add data into a newly created blob

ibase_backup
ibase_blob_cancel
Func?ii Firebird/InterBase
PHP Manual

ibase_blob_add

(PHP 5, PHP 7)

ibase_blob_add — Add data into a newly created blob

Descrierea

void ibase_blob_add ( resource $blob_handle , string $data )

ibase_blob_add() adds data into a blob created with ibase_blob_create().

Parametri

blob_handle

A blob handle opened with ibase_blob_create().

data

The data to be added.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_close() - Close blob
  • ibase_blob_create() - Create a new blob for adding data
  • ibase_blob_import() - Create blob, copy file in it, and close it

ibase_backup
ibase_blob_cancel
Func?ii Firebird/InterBase


Cancel creating blob

ibase_blob_add
ibase_blob_close
Func?ii Firebird/InterBase
PHP Manual

ibase_blob_cancel

(PHP 5, PHP 7)

ibase_blob_cancel — Cancel creating blob

Descrierea

bool ibase_blob_cancel ( resource $blob_handle )

This function will discard a BLOB if it has not yet been closed by ibase_blob_close().

Parametri

blob_handle

A BLOB handle opened with ibase_blob_create().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ibase_blob_close() - Close blob
  • ibase_blob_create() - Create a new blob for adding data
  • ibase_blob_import() - Create blob, copy file in it, and close it

ibase_blob_add
ibase_blob_close
Func?ii Firebird/InterBase


Close blob

ibase_blob_cancel
ibase_blob_create
Func?ii Firebird/InterBase
PHP Manual

ibase_blob_close

(PHP 5, PHP 7)

ibase_blob_close — Close blob

Descrierea

mixed ibase_blob_close ( resource $blob_handle )

This function closes a BLOB that has either been opened for reading by ibase_blob_open() or has been opened for writing by ibase_blob_create().

Parametri

blob_handle

A BLOB handle opened with ibase_blob_create() or ibase_blob_open().

Valorile întoarse

If the BLOB was being read, this function returns TRUE on success, if the BLOB was being written to, this function returns a string containing the BLOB id that has been assigned to it by the database. On failure, this function returns FALSE.

A se vedea ?i

  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_open() - Open blob for retrieving data parts

ibase_blob_cancel
ibase_blob_create
Func?ii Firebird/InterBase


Create a new blob for adding data

ibase_blob_close
ibase_blob_echo
Func?ii Firebird/InterBase
PHP Manual

ibase_blob_create

(PHP 5, PHP 7)

ibase_blob_create — Create a new blob for adding data

Descrierea

resource ibase_blob_create ([ resource $link_identifier = NULL ] )

ibase_blob_create() creates a new BLOB for filling with data.

Parametri

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

Valorile întoarse

Returns a BLOB handle for later use with ibase_blob_add() sau FALSE în cazul e?ecului.

A se vedea ?i

  • ibase_blob_add() - Add data into a newly created blob
  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_close() - Close blob
  • ibase_blob_import() - Create blob, copy file in it, and close it

ibase_blob_close
ibase_blob_echo
Func?ii Firebird/InterBase


Output blob contents to browser

ibase_blob_create
ibase_blob_get
Func?ii Firebird/InterBase
PHP Manual

ibase_blob_echo

(PHP 5, PHP 7)

ibase_blob_echo — Output blob contents to browser

Descrierea

bool ibase_blob_echo ( string $blob_id )
bool ibase_blob_echo ( resource $link_identifier , string $blob_id )

This function opens a BLOB for reading and sends its contents directly to standard output (the browser, in most cases).

Parametri

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ibase_blob_open() - Open blob for retrieving data parts
  • ibase_blob_close() - Close blob
  • ibase_blob_get() - Get len bytes data from open blob

ibase_blob_create
ibase_blob_get
Func?ii Firebird/InterBase


Get len bytes data from open blob

ibase_blob_echo
ibase_blob_import
Func?ii Firebird/InterBase
PHP Manual

ibase_blob_get

(PHP 5, PHP 7)

ibase_blob_get — Get len bytes data from open blob

Descrierea

string ibase_blob_get ( resource $blob_handle , int $len )

This function returns at most len bytes from a BLOB that has been opened for reading by ibase_blob_open().

Nota:

It is not possible to read from a BLOB that has been opened for writing by ibase_blob_create().

Parametri

blob_handle

A BLOB handle opened with ibase_blob_open().

len

Size of returned data.

Valorile întoarse

Returns at most len bytes from the BLOB, or FALSE on failure.

Exemple

Example #1 ibase_blob_get() example

<?php
$result    = ibase_query("SELECT blob_value FROM table");
$data      = ibase_fetch_object($result);
$blob_data = ibase_blob_info($data->BLOB_VALUE);
$blob_hndl = ibase_blob_open($data->BLOB_VALUE);
echo         ibase_blob_get($blob_hndl, $blob_data[0]);
?>
Whilst this example doesn't do much more than a 'ibase_blob_echo($data->BLOB_VALUE)' would do, it does show you how to get information into a $variable to manipulate as you please.

A se vedea ?i

  • ibase_blob_open() - Open blob for retrieving data parts
  • ibase_blob_close() - Close blob
  • ibase_blob_echo() - Output blob contents to browser

ibase_blob_echo
ibase_blob_import
Func?ii Firebird/InterBase


Create blob, copy file in it, and close it

ibase_blob_get
ibase_blob_info
Func?ii Firebird/InterBase
PHP Manual

ibase_blob_import

(PHP 5, PHP 7)

ibase_blob_import — Create blob, copy file in it, and close it

Descrierea

string ibase_blob_import ( resource $link_identifier , resource $file_handle )
string ibase_blob_import ( resource $file_handle )

This function creates a BLOB, reads an entire file into it, closes it and returns the assigned BLOB id.

Parametri

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

file_handle

The file handle is a handle returned by fopen().

Valorile întoarse

Returns the BLOB id on success, or FALSE on error.

Exemple

Example #1 ibase_blob_import() example

<?php
$dbh = ibase_connect($host, $username, $password);
$filename = '/tmp/bar';

$fd = fopen($filename, 'r');
if ($fd) {

    $blob = ibase_blob_import($dbh, $fd);
    fclose($fd);

    if (!is_string($blob)) {
        // import failed
    } else {
        $query = "INSERT INTO foo (name, data) VALUES ('$filename', ?)";
        $prepared = ibase_prepare($dbh, $query);
        if (!ibase_execute($prepared, $blob)) {
            // record insertion failed
        }
    }
} else {
    // unable to open the data file
}
?>

A se vedea ?i

  • ibase_blob_add() - Add data into a newly created blob
  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_close() - Close blob
  • ibase_blob_create() - Create a new blob for adding data

ibase_blob_get
ibase_blob_info
Func?ii Firebird/InterBase


Return blob length and other useful info

ibase_blob_import
ibase_blob_open
Func?ii Firebird/InterBase
PHP Manual

ibase_blob_info

(PHP 5, PHP 7)

ibase_blob_info — Return blob length and other useful info

Descrierea

array ibase_blob_info ( resource $link_identifier , string $blob_id )
array ibase_blob_info ( string $blob_id )

Returns the BLOB length and other useful information.

Parametri

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

A BLOB id.

Valorile întoarse

Returns an array containing information about a BLOB. The information returned consists of the length of the BLOB, the number of segments it contains, the size of the largest segment, and whether it is a stream BLOB or a segmented BLOB.

ibase_blob_import
ibase_blob_open
Func?ii Firebird/InterBase


Open blob for retrieving data parts

ibase_blob_info
ibase_close
Func?ii Firebird/InterBase
PHP Manual

ibase_blob_open

(PHP 5, PHP 7)

ibase_blob_open — Open blob for retrieving data parts

Descrierea

resource ibase_blob_open ( resource $link_identifier , string $blob_id )
resource ibase_blob_open ( string $blob_id )

Opens an existing BLOB for reading.

Parametri

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

A BLOB id.

Valorile întoarse

Returns a BLOB handle for later use with ibase_blob_get() sau FALSE în cazul e?ecului.

A se vedea ?i

  • ibase_blob_close() - Close blob
  • ibase_blob_echo() - Output blob contents to browser
  • ibase_blob_get() - Get len bytes data from open blob

ibase_blob_info
ibase_close
Func?ii Firebird/InterBase


Close a connection to an InterBase database

ibase_blob_open
ibase_commit_ret
Func?ii Firebird/InterBase
PHP Manual

ibase_close

(PHP 5, PHP 7)

ibase_close — Close a connection to an InterBase database

Descrierea

bool ibase_close ([ resource $connection_id = NULL ] )

Closes the link to an InterBase database that's associated with a connection id returned from ibase_connect(). Default transaction on link is committed, other transactions are rolled back.

Parametri

connection_id

An InterBase link identifier returned from ibase_connect(). If omitted, the last opened link is assumed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ibase_connect() - Open a connection to a database
  • ibase_pconnect() - Open a persistent connection to an InterBase database

ibase_blob_open
ibase_commit_ret
Func?ii Firebird/InterBase


Commit a transaction without closing it

ibase_close
ibase_commit
Func?ii Firebird/InterBase
PHP Manual

ibase_commit_ret

(PHP 5, PHP 7)

ibase_commit_ret — Commit a transaction without closing it

Descrierea

bool ibase_commit_ret ([ resource $link_or_trans_identifier = NULL ] )

Commits a transaction without closing it.

Parametri

link_or_trans_identifier

If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed. The transaction context will be retained, so statements executed from within this transaction will not be invalidated.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ibase_close
ibase_commit
Func?ii Firebird/InterBase


Commit a transaction

ibase_commit_ret
ibase_connect
Func?ii Firebird/InterBase
PHP Manual

ibase_commit

(PHP 5, PHP 7)

ibase_commit — Commit a transaction

Descrierea

bool ibase_commit ([ resource $link_or_trans_identifier = NULL ] )

Commits a transaction.

Parametri

link_or_trans_identifier

If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ibase_commit_ret
ibase_connect
Func?ii Firebird/InterBase


Open a connection to a database

ibase_commit
ibase_db_info
Func?ii Firebird/InterBase
PHP Manual

ibase_connect

(PHP 5, PHP 7)

ibase_connect — Open a connection to a database

Descrierea

resource ibase_connect ([ string $database [, string $username [, string $password [, string $charset [, int $buffers [, int $dialect [, string $role [, int $sync ]]]]]]]] )

Establishes a connection to an Firebird/InterBase server.

In case a second call is made to ibase_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 ibase_close().

Parametri

database

The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), 'hostname/port:' (TCP/IP with interbase server on custom TCP port), '//hostname/' (NetBEUI), depending on the connection protocol used.

username

The user name. Can be set with the ibase.default_user php.ini directive.

password

The password for username. Can be set with the ibase.default_password php.ini directive.

charset

charset is the default character set for a database.

buffers

buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.

dialect

dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries.

role

Functional only with InterBase 5 and up.

sync

Valorile întoarse

Returns an Firebird/InterBase link identifier on success, or FALSE on error.

Erori/Excep?ii

If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

Exemple

Example #1 ibase_connect() example

<?php
$host = 'localhost:/path/to/your.gdb';

$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
    echo $row->email, "\n";
}
ibase_free_result($sth);
ibase_close($dbh);
?>

A se vedea ?i

  • ibase_pconnect() - Open a persistent connection to an InterBase database
  • ibase_close() - Close a connection to an InterBase database

ibase_commit
ibase_db_info
Func?ii Firebird/InterBase


Request statistics about a database

ibase_connect
ibase_delete_user
Func?ii Firebird/InterBase
PHP Manual

ibase_db_info

(PHP 5, PHP 7)

ibase_db_info — Request statistics about a database

Descrierea

string ibase_db_info ( resource $service_handle , string $db , int $action [, int $argument = 0 ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ibase_connect
ibase_delete_user
Func?ii Firebird/InterBase


Delete a user from a security database

ibase_db_info
ibase_drop_db
Func?ii Firebird/InterBase
PHP Manual

ibase_delete_user

(PHP 5, PHP 7)

ibase_delete_user — Delete a user from a security database

Descrierea

bool ibase_delete_user ( resource $service_handle , string $user_name )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ibase_add_user() - Add a user to a security database
  • ibase_modify_user() - Modify a user to a security database

ibase_db_info
ibase_drop_db
Func?ii Firebird/InterBase


Drops a database

ibase_delete_user
ibase_errcode
Func?ii Firebird/InterBase
PHP Manual

ibase_drop_db

(PHP 5, PHP 7)

ibase_drop_db — Drops a database

Descrierea

bool ibase_drop_db ([ resource $connection = NULL ] )

This functions drops a database that was opened by either ibase_connect() or ibase_pconnect(). The database is closed and deleted from the server.

Parametri

connection

An InterBase link identifier. If omitted, the last opened link is assumed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ibase_connect() - Open a connection to a database
  • ibase_pconnect() - Open a persistent connection to an InterBase database

ibase_delete_user
ibase_errcode
Func?ii Firebird/InterBase


Return an error code

ibase_drop_db
ibase_errmsg
Func?ii Firebird/InterBase
PHP Manual

ibase_errcode

(PHP 5, PHP 7)

ibase_errcode — Return an error code

Descrierea

int ibase_errcode ( void )

Returns the error code that resulted from the most recent InterBase function call.

Valorile întoarse

Returns the error code as an integer, or FALSE if no error occurred.

A se vedea ?i

  • ibase_errmsg() - Return error messages

ibase_drop_db
ibase_errmsg
Func?ii Firebird/InterBase


Return error messages

ibase_errcode
ibase_execute
Func?ii Firebird/InterBase
PHP Manual

ibase_errmsg

(PHP 5, PHP 7)

ibase_errmsg — Return error messages

Descrierea

string ibase_errmsg ( void )

Returns the error message that resulted from the most recent InterBase function call.

Valorile întoarse

Returns the error message as a string, or FALSE if no error occurred.

A se vedea ?i

  • ibase_errcode() - Return an error code

ibase_errcode
ibase_execute
Func?ii Firebird/InterBase


Execute a previously prepared query

ibase_errmsg
ibase_fetch_assoc
Func?ii Firebird/InterBase
PHP Manual

ibase_execute

(PHP 5, PHP 7)

ibase_execute — Execute a previously prepared query

Descrierea

resource ibase_execute ( resource $query [, mixed $bind_arg [, mixed $... ]] )

Execute a query prepared by ibase_prepare().

This is a lot more effective than using ibase_query() if you are repeating a same kind of query several times with only some parameters changing.

Parametri

query

An InterBase query prepared by ibase_prepare().

bind_arg

...

Valorile întoarse

If the query raises an error, returns FALSE. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE.

Nota:

This function returns the number of rows affected by the query (if > 0 and applicable to the statement type). A query that succeeded, but did not affect any rows (e.g. an UPDATE of a non-existent record) will return TRUE.

Exemple

Example #1 ibase_execute() example

<?php

$dbh = ibase_connect($host, $username, $password);

$updates = array(
    1 => 'Eric',
    5 => 'Filip',
    7 => 'Larry'
);

$query = ibase_prepare($dbh, "UPDATE FOO SET BAR = ? WHERE BAZ = ?");

foreach ($updates as $baz => $bar) {
    ibase_execute($query, $bar, $baz);
}

?>

A se vedea ?i

  • ibase_query() - Execute a query on an InterBase database

ibase_errmsg
ibase_fetch_assoc
Func?ii Firebird/InterBase


Fetch a result row from a query as an associative array

ibase_execute
ibase_fetch_object
Func?ii Firebird/InterBase
PHP Manual

ibase_fetch_assoc

(PHP 5, PHP 7)

ibase_fetch_assoc — Fetch a result row from a query as an associative array

Descrierea

array ibase_fetch_assoc ( resource $result [, int $fetch_flag = 0 ] )

Fetch a result row from a query as an associative array.

ibase_fetch_assoc() fetches one row of data from the result. 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 ibase_fetch_row() or use alias names in your query.

Parametri

result

The result handle.

fetch_flag

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

Valorile întoarse

Returns an associative array that corresponds to the fetched row. Subsequent calls will return the next row in the result set, or FALSE if there are no more rows.

A se vedea ?i

  • ibase_fetch_row() - Fetch a row from an InterBase database
  • ibase_fetch_object() - Get an object from a InterBase database

ibase_execute
ibase_fetch_object
Func?ii Firebird/InterBase


Get an object from a InterBase database

ibase_fetch_assoc
ibase_fetch_row
Func?ii Firebird/InterBase
PHP Manual

ibase_fetch_object

(PHP 5, PHP 7)

ibase_fetch_object — Get an object from a InterBase database

Descrierea

object ibase_fetch_object ( resource $result_id [, int $fetch_flag = 0 ] )

Fetches a row as a pseudo-object from a given result identifier.

Subsequent calls to ibase_fetch_object() return the next row in the result set.

Parametri

result_id

An InterBase result identifier obtained either by ibase_query() or ibase_execute().

fetch_flag

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

Valorile întoarse

Returns an object with the next row information, or FALSE if there are no more rows.

Exemple

Example #1 ibase_fetch_object() example

<?php
$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
    echo $row->email . "\n";
}
ibase_close($dbh);
?>

A se vedea ?i

  • ibase_fetch_row() - Fetch a row from an InterBase database
  • ibase_fetch_assoc() - Fetch a result row from a query as an associative array

ibase_fetch_assoc
ibase_fetch_row
Func?ii Firebird/InterBase


Fetch a row from an InterBase database

ibase_fetch_object
ibase_field_info
Func?ii Firebird/InterBase
PHP Manual

ibase_fetch_row

(PHP 5, PHP 7)

ibase_fetch_row — Fetch a row from an InterBase database

Descrierea

array ibase_fetch_row ( resource $result_identifier [, int $fetch_flag = 0 ] )

ibase_fetch_row() fetches one row of data from the given result set.

Subsequent calls to ibase_fetch_row() return the next row in the result set, or FALSE if there are no more rows.

Parametri

result_identifier

An InterBase result identifier.

fetch_flag

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

Valorile întoarse

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.

A se vedea ?i

  • ibase_fetch_assoc() - Fetch a result row from a query as an associative array
  • ibase_fetch_object() - Get an object from a InterBase database

ibase_fetch_object
ibase_field_info
Func?ii Firebird/InterBase


Get information about a field

ibase_fetch_row
ibase_free_event_handler
Func?ii Firebird/InterBase
PHP Manual

ibase_field_info

(PHP 5, PHP 7)

ibase_field_info — Get information about a field

Descrierea

array ibase_field_info ( resource $result , int $field_number )

Returns an array with information about a field after a select query has been run.

Parametri

result

An InterBase result identifier.

field_number

Field offset.

Valorile întoarse

Returns an array with the following keys: name, alias, relation, length and type.

Exemple

Example #1 ibase_field_info() example

<?php
$rs = ibase_query("SELECT * FROM tablename");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
    $col_info = ibase_field_info($rs, $i);
    echo "name: ". $col_info['name']. "\n";
    echo "alias: ". $col_info['alias']. "\n";
    echo "relation: ". $col_info['relation']. "\n";
    echo "length: ". $col_info['length']. "\n";
    echo "type: ". $col_info['type']. "\n";
}
?>

A se vedea ?i

  • ibase_num_fields() - Get the number of fields in a result set

ibase_fetch_row
ibase_free_event_handler
Func?ii Firebird/InterBase


Cancels a registered event handler

ibase_field_info
ibase_free_query
Func?ii Firebird/InterBase
PHP Manual

ibase_free_event_handler

(PHP 5, PHP 7)

ibase_free_event_handler — Cancels a registered event handler

Descrierea

bool ibase_free_event_handler ( resource $event )

This function causes the registered event handler specified by event to be cancelled. The callback function will no longer be called for the events it was registered to handle.

Parametri

event

An event resource, created by ibase_set_event_handler().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ibase_set_event_handler() - Register a callback function to be called when events are posted

ibase_field_info
ibase_free_query
Func?ii Firebird/InterBase


Free memory allocated by a prepared query

ibase_free_event_handler
ibase_free_result
Func?ii Firebird/InterBase
PHP Manual

ibase_free_query

(PHP 5, PHP 7)

ibase_free_query — Free memory allocated by a prepared query

Descrierea

bool ibase_free_query ( resource $query )

Frees a prepared query.

Parametri

query

A query prepared with ibase_prepare().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ibase_free_event_handler
ibase_free_result
Func?ii Firebird/InterBase


Free a result set

ibase_free_query
ibase_gen_id
Func?ii Firebird/InterBase
PHP Manual

ibase_free_result

(PHP 5, PHP 7)

ibase_free_result — Free a result set

Descrierea

bool ibase_free_result ( resource $result_identifier )

Frees a result set.

Parametri

result_identifier

A result set created by ibase_query() or ibase_execute().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ibase_free_query
ibase_gen_id
Func?ii Firebird/InterBase


Increments the named generator and returns its new value

ibase_free_result
ibase_maintain_db
Func?ii Firebird/InterBase
PHP Manual

ibase_gen_id

(PHP 5, PHP 7)

ibase_gen_id — Increments the named generator and returns its new value

Descrierea

mixed ibase_gen_id ( string $generator [, int $increment = 1 [, resource $link_identifier = NULL ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Returns new generator value as integer, or as string if the value is too big.

ibase_free_result
ibase_maintain_db
Func?ii Firebird/InterBase


Execute a maintenance command on the database server

ibase_gen_id
ibase_modify_user
Func?ii Firebird/InterBase
PHP Manual

ibase_maintain_db

(PHP 5, PHP 7)

ibase_maintain_db — Execute a maintenance command on the database server

Descrierea

bool ibase_maintain_db ( resource $service_handle , string $db , int $action [, int $argument = 0 ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ibase_gen_id
ibase_modify_user
Func?ii Firebird/InterBase


Modify a user to a security database

ibase_maintain_db
ibase_name_result
Func?ii Firebird/InterBase
PHP Manual

ibase_modify_user

(PHP 5, PHP 7)

ibase_modify_user — Modify a user to a security database

Descrierea

bool ibase_modify_user ( resource $service_handle , string $user_name , string $password [, string $first_name [, string $middle_name [, string $last_name ]]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ibase_add_user() - Add a user to a security database
  • ibase_delete_user() - Delete a user from a security database

ibase_maintain_db
ibase_name_result
Func?ii Firebird/InterBase


Assigns a name to a result set

ibase_modify_user
ibase_num_fields
Func?ii Firebird/InterBase
PHP Manual

ibase_name_result

(PHP 5, PHP 7)

ibase_name_result — Assigns a name to a result set

Descrierea

bool ibase_name_result ( resource $result , string $name )

This function assigns a name to a result set. This name can be used later in UPDATE|DELETE ... WHERE CURRENT OF name statements.

Parametri

result

An InterBase result set.

name

The name to be assigned.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ibase_name_result() example

<?php
$result = ibase_query("SELECT field1,field2 FROM table FOR UPDATE");
ibase_name_result($result, "my_cursor");

$updateqry = ibase_prepare("UPDATE table SET field2 = ? WHERE CURRENT OF my_cursor");

for ($i = 0; ibase_fetch_row($result); ++$i) {
    ibase_execute($updateqry, $i);
}
?>

A se vedea ?i

  • ibase_prepare() - Prepare a query for later binding of parameter placeholders and execution
  • ibase_execute() - Execute a previously prepared query

ibase_modify_user
ibase_num_fields
Func?ii Firebird/InterBase


Get the number of fields in a result set

ibase_name_result
ibase_num_params
Func?ii Firebird/InterBase
PHP Manual

ibase_num_fields

(PHP 5, PHP 7)

ibase_num_fields — Get the number of fields in a result set

Descrierea

int ibase_num_fields ( resource $result_id )

Get the number of fields in a result set.

Parametri

result_id

An InterBase result identifier.

Valorile întoarse

Returns the number of fields as an integer.

Exemple

Example #1 ibase_num_fields() example

<?php
$rs = ibase_query("SELECT * FROM tablename");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
    $col_info = ibase_field_info($rs, $i);
    echo "name: " . $col_info['name'] . "\n";
    echo "alias: " . $col_info['alias'] . "\n";
    echo "relation: " . $col_info['relation'] . "\n";
    echo "length: " . $col_info['length'] . "\n";
    echo "type: " . $col_info['type'] . "\n";
}
?>

A se vedea ?i

  • ibase_field_info() - Get information about a field

ibase_name_result
ibase_num_params
Func?ii Firebird/InterBase


Return the number of parameters in a prepared query

ibase_num_fields
ibase_param_info
Func?ii Firebird/InterBase
PHP Manual

ibase_num_params

(PHP 5, PHP 7)

ibase_num_params — Return the number of parameters in a prepared query

Descrierea

int ibase_num_params ( resource $query )

This function returns the number of parameters in the prepared query specified by query. This is the number of binding arguments that must be present when calling ibase_execute().

Parametri

query

The prepared query handle.

Valorile întoarse

Returns the number of parameters as an integer.

A se vedea ?i

  • ibase_prepare() - Prepare a query for later binding of parameter placeholders and execution
  • ibase_param_info() - Return information about a parameter in a prepared query

ibase_num_fields
ibase_param_info
Func?ii Firebird/InterBase


Return information about a parameter in a prepared query

ibase_num_params
ibase_pconnect
Func?ii Firebird/InterBase
PHP Manual

ibase_param_info

(PHP 5, PHP 7)

ibase_param_info — Return information about a parameter in a prepared query

Descrierea

array ibase_param_info ( resource $query , int $param_number )

Returns an array with information about a parameter after a query has been prepared.

Parametri

query

An InterBase prepared query handle.

param_number

Parameter offset.

Valorile întoarse

Returns an array with the following keys: name, alias, relation, length and type.

A se vedea ?i

  • ibase_field_info() - Get information about a field
  • ibase_num_params() - Return the number of parameters in a prepared query

ibase_num_params
ibase_pconnect
Func?ii Firebird/InterBase


Open a persistent connection to an InterBase database

ibase_param_info
ibase_prepare
Func?ii Firebird/InterBase
PHP Manual

ibase_pconnect

(PHP 5, PHP 7)

ibase_pconnect — Open a persistent connection to an InterBase database

Descrierea

resource ibase_pconnect ([ string $database [, string $username [, string $password [, string $charset [, int $buffers [, int $dialect [, string $role [, int $sync ]]]]]]]] )

Opens a persistent connection to an InterBase database.

ibase_pconnect() acts very much like ibase_connect() with two major differences.

First, when connecting, the function will first try to find a (persistent) link that's 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 InterBase server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ibase_close() will not close links established by ibase_pconnect()). This type of link is therefore called 'persistent'.

Parametri

database

The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI) or 'hostname@' (IPX/SPX), depending on the connection protocol used.

username

The user name. Can be set with the ibase.default_user php.ini directive.

password

The password for username. Can be set with the ibase.default_password php.ini directive.

charset

charset is the default character set for a database.

buffers

buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.

dialect

dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries. Functional only with InterBase 6 and up.

role

Functional only with InterBase 5 and up.

sync

Valorile întoarse

Returns an InterBase link identifier on success, or FALSE on error.

A se vedea ?i

  • ibase_close() - Close a connection to an InterBase database
  • ibase_connect() - Open a connection to a database

ibase_param_info
ibase_prepare
Func?ii Firebird/InterBase


Prepare a query for later binding of parameter placeholders and execution

ibase_pconnect
ibase_query
Func?ii Firebird/InterBase
PHP Manual

ibase_prepare

(PHP 5, PHP 7)

ibase_prepare — Prepare a query for later binding of parameter placeholders and execution

Descrierea

resource ibase_prepare ( string $query )
resource ibase_prepare ( resource $link_identifier , string $query )
resource ibase_prepare ( resource $link_identifier , string $trans , string $query )

Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).

Parametri

query

An InterBase query.

link_identifier

An InterBase link identifier returned from ibase_connect(). If omitted, the last opened link is assumed.

trans

An InterBase transaction handle the query should be associated with. If omitted, the default transaction of the connection is assumed.

Valorile întoarse

Returns a prepared query handle, or FALSE on error.

ibase_pconnect
ibase_query
Func?ii Firebird/InterBase


Execute a query on an InterBase database

ibase_prepare
ibase_restore
Func?ii Firebird/InterBase
PHP Manual

ibase_query

(PHP 5, PHP 7)

ibase_query — Execute a query on an InterBase database

Descrierea

resource ibase_query ([ resource $link_identifier ], string $query [, int $bind_args ] )

Performs a query on an InterBase database.

Parametri

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

query

An InterBase query.

bind_args

Valorile întoarse

If the query raises an error, returns FALSE. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE.

Nota:

In PHP 5.0.0 and up, this function will return the number of rows affected by the query for INSERT, UPDATE and DELETE statements. In order to retain backward compatibility, it will return TRUE for these statements if the query succeeded without affecting any rows.

Erori/Excep?ii

If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

Istoricul schimbarilor

Versiune | Descriere
5.3.1 | On success the function now returns TRUE if there were no affected rows, where it previously returned 0 (a zero followed by an empty space).

Exemple

Example #1 ibase_query() example

<?php

$host = 'localhost:/path/to/your.gdb';

$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';

$sth = ibase_query($dbh, $stmt) or die(ibase_errmsg());

?>

A se vedea ?i

  • ibase_errmsg() - Return error messages
  • ibase_fetch_row() - Fetch a row from an InterBase database
  • ibase_fetch_object() - Get an object from a InterBase database
  • ibase_free_result() - Free a result set

ibase_prepare
ibase_restore
Func?ii Firebird/InterBase


Initiates a restore task in the service manager and returns immediately

ibase_query
ibase_rollback_ret
Func?ii Firebird/InterBase
PHP Manual

ibase_restore

(PHP 5, PHP 7)

ibase_restore — Initiates a restore task in the service manager and returns immediately

Descrierea

mixed ibase_restore ( resource $service_handle , string $source_file , string $dest_db [, int $options = 0 [, bool $verbose = false ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ibase_query
ibase_rollback_ret
Func?ii Firebird/InterBase


Roll back a transaction without closing it

ibase_restore
ibase_rollback
Func?ii Firebird/InterBase
PHP Manual

ibase_rollback_ret

(PHP 5, PHP 7)

ibase_rollback_ret — Roll back a transaction without closing it

Descrierea

bool ibase_rollback_ret ([ resource $link_or_trans_identifier = NULL ] )

Rolls back a transaction without closing it.

Parametri

link_or_trans_identifier

If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back. The transaction context will be retained, so statements executed from within this transaction will not be invalidated.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ibase_restore
ibase_rollback
Func?ii Firebird/InterBase


Roll back a transaction

ibase_rollback_ret
ibase_server_info
Func?ii Firebird/InterBase
PHP Manual

ibase_rollback

(PHP 5, PHP 7)

ibase_rollback — Roll back a transaction

Descrierea

bool ibase_rollback ([ resource $link_or_trans_identifier = NULL ] )

Rolls back a transaction.

Parametri

link_or_trans_identifier

If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ibase_rollback_ret
ibase_server_info
Func?ii Firebird/InterBase


Request information about a database server

ibase_rollback
ibase_service_attach
Func?ii Firebird/InterBase
PHP Manual

ibase_server_info

(PHP 5, PHP 7)

ibase_server_info — Request information about a database server

Descrierea

string ibase_server_info ( resource $service_handle , int $action )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ibase_rollback
ibase_service_attach
Func?ii Firebird/InterBase


Connect to the service manager

ibase_server_info
ibase_service_detach
Func?ii Firebird/InterBase
PHP Manual

ibase_service_attach

(PHP 5, PHP 7)

ibase_service_attach — Connect to the service manager

Descrierea

resource ibase_service_attach ( string $host , string $dba_username , string $dba_password )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ibase_server_info
ibase_service_detach
Func?ii Firebird/InterBase


Disconnect from the service manager

ibase_service_attach
ibase_set_event_handler
Func?ii Firebird/InterBase
PHP Manual

ibase_service_detach

(PHP 5, PHP 7)

ibase_service_detach — Disconnect from the service manager

Descrierea

bool ibase_service_detach ( resource $service_handle )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ibase_service_attach
ibase_set_event_handler
Func?ii Firebird/InterBase


Register a callback function to be called when events are posted

ibase_service_detach
ibase_trans
Func?ii Firebird/InterBase
PHP Manual

ibase_set_event_handler

(PHP 5, PHP 7)

ibase_set_event_handler — Register a callback function to be called when events are posted

Descrierea

resource ibase_set_event_handler ( callable $event_handler , string $event_name1 [, string $event_name2 [, string $... ]] )
resource ibase_set_event_handler ( resource $connection , callable $event_handler , string $event_name1 [, string $event_name2 [, string $... ]] )

This function registers a PHP user function as event handler for the specified events.

Parametri

event_handler

The callback is called with the event name and the link resource as arguments whenever one of the specified events is posted by the database.

The callback must return FALSE if the event handler should be canceled. Any other return value is ignored. This function accepts up to 15 event arguments.

event_name1

An event name.

event_name2

At most 15 events allowed.

Valorile întoarse

The return value is an event resource. This resource can be used to free the event handler using ibase_free_event_handler().

Exemple

Example #1 ibase_set_event_handler() example

<?php

function event_handler($event_name, $link)
{
    if ($event_name == "NEW ORDER") {
        // process new order
        ibase_query($link, "UPDATE orders SET status='handled'");
    } else if ($event_name == "DB_SHUTDOWN") {
        // free event handler
        return false;
    }
}

ibase_set_event_handler($link, "event_handler", "NEW_ORDER", "DB_SHUTDOWN");
?>

A se vedea ?i

  • ibase_free_event_handler() - Cancels a registered event handler
  • ibase_wait_event() - Wait for an event to be posted by the database

ibase_service_detach
ibase_trans
Func?ii Firebird/InterBase


Begin a transaction

ibase_set_event_handler
ibase_wait_event
Func?ii Firebird/InterBase
PHP Manual

ibase_trans

(PHP 5, PHP 7)

ibase_trans — Begin a transaction

Descrierea

resource ibase_trans ([ int $trans_args [, resource $link_identifier ]] )
resource ibase_trans ([ resource $link_identifier [, int $trans_args ]] )

Begins a transaction.

Nota:

The first call to ibase_trans() will not return the default transaction of a connection. All transactions started by ibase_trans() will be rolled back at the end of the script if they were not committed or rolled back by either ibase_commit() or ibase_rollback().

Nota:

This function will accept multiple trans_args and link_identifier arguments. This allows transactions over multiple database connections, which are committed using a 2-phase commit algorithm. This means you can rely on the updates to either succeed in every database, or fail in every database. It does NOT mean you can use tables from different databases in the same query!

If you use transactions over multiple databases, you will have to specify both the link_id and transaction_id in calls to ibase_query() and ibase_prepare().

Parametri

trans_args

trans_args can be a combination of IBASE_READ, IBASE_WRITE, IBASE_COMMITTED, IBASE_CONSISTENCY, IBASE_CONCURRENCY, IBASE_REC_VERSION, IBASE_REC_NO_VERSION, IBASE_WAIT and IBASE_NOWAIT.

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

Valorile întoarse

Returns a transaction handle, or FALSE on error.

ibase_set_event_handler
ibase_wait_event
Func?ii Firebird/InterBase


Wait for an event to be posted by the database

ibase_trans
FrontBase
Func?ii Firebird/InterBase
PHP Manual

ibase_wait_event

(PHP 5, PHP 7)

ibase_wait_event — Wait for an event to be posted by the database

Descrierea

string ibase_wait_event ( string $event_name1 [, string $event_name2 [, string $... ]] )
string ibase_wait_event ( resource $connection , string $event_name1 [, string $event_name2 [, string $... ]] )

This function suspends execution of the script until one of the specified events is posted by the database. The name of the event that was posted is returned. This function accepts up to 15 event arguments.

Parametri

event_name1

The event name.

event_name2

...

Valorile întoarse

Returns the name of the event that was posted.

A se vedea ?i

  • ibase_set_event_handler() - Register a callback function to be called when events are posted
  • ibase_free_event_handler() - Cancels a registered event handler

ibase_trans
FrontBase
Func?ii Firebird/InterBase


FrontBase

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii 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 — Close FrontBase connection
    • fbsql_commit — Commits a transaction to the database
    • fbsql_connect — Open a connection to a FrontBase Server
    • 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 — Get the status for a given database
    • 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 — Get name of the table the specified field is in
    • fbsql_field_type — Get the type of the specified field in a result
    • fbsql_free_result — Free result memory
    • fbsql_get_autostart_info — Descrierea
    • fbsql_hostname — Get or set the host name used with a connection
    • 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 — Get or set the user password used with a connection
    • fbsql_pconnect — Open a persistent connection to a FrontBase Server
    • fbsql_query — Send a FrontBase query
    • 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 — Change input/output character set
    • 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 — Start a database on local or remote server
    • fbsql_stop_db — Stop a database on local or remote server
    • fbsql_table_name — Get table name of field
    • fbsql_tablename — Pseudonim pentru fbsql_table_name
    • fbsql_username — Get or set the username for the connection
    • fbsql_warnings — Enable or disable FrontBase warnings
ibase_wait_event
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

These functions allow you to access FrontBase database servers. More information about FrontBase can be found at » http://www.frontbase.com/.

Documentation for FrontBase can be found at » http://www.frontbase.com/cgi-bin/WebObjects/FBWebSite.woa.

Frontbase support has been added to PHP 4.0.6.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.3.0.

FrontBase
Instalarea / configurarea
FrontBase


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
FrontBase


Necesita?i

You must install the FrontBase database server or at least the fbsql client libraries to use this functions. You can get FrontBase from » http://www.frontbase.com/.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

In order to have these functions available, you must compile PHP with fbsql support by using the --with-fbsql[=DIR] option. If you use this option without specifying the path to fbsql, PHP will search for the fbsql client libraries in the default installation location for the platform. Users who installed FrontBase in a non standard directory should always specify the path to fbsql: --with-fbsql=/path/to/fbsql . This will force PHP to use the client libraries installed by FrontBase, avoiding any conflicts.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

FrontBase configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.autocommit | "1" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_links | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_connections | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_results | "128" | 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.default_host | NULL | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_password | "" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
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.mbatchSize | "1000" | PHP_INI_SYSTEM | Available since PHP 4.0.6. Removed in PHP 4.2.0.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
Tipurile resurselor
Func?ii FrontBase
FrontBase


Func?ii FrontBase

Cuprins

  • 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 — Close FrontBase connection
  • fbsql_commit — Commits a transaction to the database
  • fbsql_connect — Open a connection to a FrontBase Server
  • 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 — Get the status for a given database
  • 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 — Get name of the table the specified field is in
  • fbsql_field_type — Get the type of the specified field in a result
  • fbsql_free_result — Free result memory
  • fbsql_get_autostart_info — Descrierea
  • fbsql_hostname — Get or set the host name used with a connection
  • 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 — Get or set the user password used with a connection
  • fbsql_pconnect — Open a persistent connection to a FrontBase Server
  • fbsql_query — Send a FrontBase query
  • 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 — Change input/output character set
  • 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 — Start a database on local or remote server
  • fbsql_stop_db — Stop a database on local or remote server
  • fbsql_table_name — Get table name of field
  • fbsql_tablename — Pseudonim pentru fbsql_table_name
  • fbsql_username — Get or set the username for the connection
  • fbsql_warnings — Enable or disable FrontBase warnings
Constante predefinite
fbsql_affected_rows
FrontBase


Get number of affected rows in previous FrontBase operation

Func?ii FrontBase
fbsql_autocommit
Func?ii FrontBase
PHP Manual

fbsql_affected_rows

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_affected_rows — Get number of affected rows in previous FrontBase operation

Descrierea

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.

Nota:

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.

Nota:

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.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

If the last query failed, this function will return -1.

A se vedea ?i

  • fbsql_num_rows() - Get number of rows in result

Func?ii FrontBase
fbsql_autocommit
Func?ii FrontBase


Enable or disable autocommit

fbsql_affected_rows
fbsql_blob_size
Func?ii FrontBase
PHP Manual

fbsql_autocommit

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_autocommit — Enable or disable autocommit

Descrierea

bool fbsql_autocommit ( resource $link_identifier [, bool $OnOff ] )

Returns the current autocommit status.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

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().

Valorile întoarse

Returns the current autocommit status, as a boolean.

A se vedea ?i

  • fbsql_commit() - Commits a transaction to the database
  • fbsql_rollback() - Rollback a transaction to the database

fbsql_affected_rows
fbsql_blob_size
Func?ii FrontBase


Get the size of a BLOB

fbsql_autocommit
fbsql_change_user
Func?ii FrontBase
PHP Manual

fbsql_blob_size

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_blob_size — Get the size of a BLOB

Descrierea

int fbsql_blob_size ( string $blob_handle [, resource $link_identifier ] )

Returns the size of the given BLOB.

Parametri

blob_handle

A BLOB handle, returned by fbsql_create_blob().

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Returns the BLOB size as an integer, or FALSE on error.

A se vedea ?i

  • fbsql_clob_size() - Get the size of a CLOB

fbsql_autocommit
fbsql_change_user
Func?ii FrontBase


Change logged in user of the active connection

fbsql_blob_size
fbsql_clob_size
Func?ii FrontBase
PHP Manual

fbsql_change_user

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_change_user — Change logged in user of the active connection

Descrierea

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.

Parametri

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

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

fbsql_blob_size
fbsql_clob_size
Func?ii FrontBase


Get the size of a CLOB

fbsql_change_user
fbsql_close
Func?ii FrontBase
PHP Manual

fbsql_clob_size

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_clob_size — Get the size of a CLOB

Descrierea

int fbsql_clob_size ( string $clob_handle [, resource $link_identifier ] )

Returns the size of the given CLOB.

Parametri

clob_handle

A CLOB handle, returned by fbsql_create_clob().

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Returns the CLOB size as an integer, or FALSE on error.

A se vedea ?i

  • fbsql_blob_size() - Get the size of a BLOB

fbsql_change_user
fbsql_close
Func?ii FrontBase


Close FrontBase connection

fbsql_clob_size
fbsql_commit
Func?ii FrontBase
PHP Manual

fbsql_close

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_close — Close FrontBase connection

Descrierea

bool fbsql_close ([ resource $link_identifier ] )

Closes the connection to the FrontBase server that's associated with the specified link identifier.

Using fbsql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 fbsql_close() example

<?php
$link = fbsql_connect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
echo "Connected successfully";
fbsql_close($link);
?>

A se vedea ?i

  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server

fbsql_clob_size
fbsql_commit
Func?ii FrontBase


Commits a transaction to the database

fbsql_close
fbsql_connect
Func?ii FrontBase
PHP Manual

fbsql_commit

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_commit — Commits a transaction to the database

Descrierea

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.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fbsql_autocommit() - Enable or disable autocommit
  • fbsql_rollback() - Rollback a transaction to the database

fbsql_close
fbsql_connect
Func?ii FrontBase


Open a connection to a FrontBase Server

fbsql_commit
fbsql_create_blob
Func?ii FrontBase
PHP Manual

fbsql_connect

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_connect — Open a connection to a FrontBase Server

Descrierea

 resource fbsql_connect
  ([ string $hostname = ini_get("fbsql.default_host")
 [, string $username = ini_get("fbsql.default_user")
 [, string $password = ini_get("fbsql.default_password")
]]] )

fbsql_connect() establishes a connection to a FrontBase server.

If a second call is made to fbsql_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 fbsql_close().

Parametri

hostname

The server host name.

username

The user name for the connection.

password

The password for the connection.

Valorile întoarse

Returns a positive FrontBase link identifier on success, or FALSE on errors.

Exemple

Example #1 fbsql_connect() example

<?php

$link = fbsql_connect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
echo "Connected successfully";
fbsql_close($link);

?>

A se vedea ?i

  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server
  • fbsql_close() - Close FrontBase connection

fbsql_commit
fbsql_create_blob
Func?ii FrontBase


Create a BLOB

fbsql_connect
fbsql_create_clob
Func?ii FrontBase
PHP Manual

fbsql_create_blob

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_create_blob — Create a BLOB

Descrierea

string fbsql_create_blob ( string $blob_data [, resource $link_identifier ] )

Creates a BLOB from the given data.

Parametri

blob_data

The BLOB data.

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

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.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii FrontBase


Create a CLOB

fbsql_create_blob
fbsql_create_db
Func?ii FrontBase
PHP Manual

fbsql_create_clob

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_create_clob — Create a CLOB

Descrierea

string fbsql_create_clob ( string $clob_data [, resource $link_identifier ] )

Creates a CLOB from the given data.

Parametri

clob_data

The CLOB data.

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

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.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii FrontBase


Create a FrontBase database

fbsql_create_clob
fbsql_data_seek
Func?ii FrontBase
PHP Manual

fbsql_create_db

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_create_db — Create a FrontBase database

Descrierea

bool fbsql_create_db ( string $database_name [, resource $link_identifier [, string $database_options ]] )

Attempts to create a new database on the specified server.

Parametri

database_name

The database name, as a string.

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

database_options

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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());
}
?>

A se vedea ?i

  • fbsql_drop_db() - Drop (delete) a FrontBase database

fbsql_create_clob
fbsql_data_seek
Func?ii FrontBase


Move internal result pointer

fbsql_create_db
fbsql_database_password
Func?ii FrontBase
PHP Manual

fbsql_data_seek

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_data_seek — Move internal result pointer

Descrierea

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.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau fbsql_db_query().

row_number

The row number. Starts at 0.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii FrontBase


Sets or retrieves the password for a FrontBase database

fbsql_data_seek
fbsql_database
Func?ii FrontBase
PHP Manual

fbsql_database_password

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_database_password — Sets or retrieves the password for a FrontBase database

Descrierea

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.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

database_password

The database password, as a string. If given, the function sets the database password for the specified link identifier.

Valorile întoarse

Returns the database password associated with the link identifier.

Exemple

Example #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);
?>

A se vedea ?i

  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server
  • fbsql_select_db() - Select a FrontBase database

fbsql_data_seek
fbsql_database
Func?ii FrontBase


Get or set the database name used with a connection

fbsql_database_password
fbsql_db_query
Func?ii FrontBase
PHP Manual

fbsql_database

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_database — Get or set the database name used with a connection

Descrierea

string fbsql_database ( resource $link_identifier [, string $database ] )

Get or set the database name used with the connection.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

database

The database name. If given, the default database of the connexion will be changed to database.

Valorile întoarse

Returns the name of the database used with this connection.

fbsql_database_password
fbsql_db_query
Func?ii FrontBase


Send a FrontBase query

fbsql_database
fbsql_db_status
Func?ii FrontBase
PHP Manual

fbsql_db_query

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_db_query — Send a FrontBase query

Descrierea

resource fbsql_db_query ( string $database , string $query [, resource $link_identifier ] )

Selects a database and executes a query on it.

Parametri

database

The database to be selected.

query

The SQL query to be executed.

Nota:

The query string shall always end with a semicolon.

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Returns a positive FrontBase result identifier to the query result, or FALSE on error.

A se vedea ?i

  • fbsql_query() - Send a FrontBase query
  • fbsql_connect() - Open a connection to a FrontBase Server

fbsql_database
fbsql_db_status
Func?ii FrontBase


Get the status for a given database

fbsql_db_query
fbsql_drop_db
Func?ii FrontBase
PHP Manual

fbsql_db_status

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

fbsql_db_status — Get the status for a given database

Descrierea

int fbsql_db_status ( string $database_name [, resource $link_identifier ] )

Gets the current status of the specified database.

Parametri

database_name

The database name.

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Returns an integer value with the current status. This can be one of the following constants:

  • FALSE - The exec handler for the host was invalid. This error will occur when the link_identifier connects directly to a database by using a port number. FBExec can be available on the server but no connection has been made for it.
  • FBSQL_UNKNOWN - The Status is unknown.
  • FBSQL_STOPPED - The database is not running. Use fbsql_start_db() to start the database.
  • FBSQL_STARTING - The database is starting.
  • FBSQL_RUNNING - The database is running and can be used to perform SQL operations.
  • FBSQL_STOPPING - The database is stopping.
  • FBSQL_NOEXEC - FBExec is not running on the server and it is not possible to get the status of the database.

A se vedea ?i

  • fbsql_start_db() - Start a database on local or remote server
  • fbsql_stop_db() - Stop a database on local or remote server

fbsql_db_query
fbsql_drop_db
Func?ii FrontBase


Drop (delete) a FrontBase database

fbsql_db_status
fbsql_errno
Func?ii FrontBase
PHP Manual

fbsql_drop_db

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_drop_db — Drop (delete) a FrontBase database

Descrierea

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.

Parametri

database_name

The database name, as a string.

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fbsql_create_db() - Create a FrontBase database

fbsql_db_status
fbsql_errno
Func?ii FrontBase


Returns the error number from previous operation

fbsql_drop_db
fbsql_error
Func?ii FrontBase
PHP Manual

fbsql_errno

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_errno — Returns the error number from previous operation

Descrierea

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.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Returns the error number from the last fbsql function, or 0 (zero) if no error occurred.

Exemple

Example #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 />";
?>

A se vedea ?i

  • fbsql_error() - Returns the error message from previous operation
  • fbsql_warnings() - Enable or disable FrontBase warnings

fbsql_drop_db
fbsql_error
Func?ii FrontBase


Returns the error message from previous operation

fbsql_errno
fbsql_fetch_array
Func?ii FrontBase
PHP Manual

fbsql_error

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_error — Returns the error message from previous operation

Descrierea

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.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Returns the error text from the last fbsql function, or '' (the empty string) if no error occurred.

Exemple

Example #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 />";
?>

A se vedea ?i

  • fbsql_errno() - Returns the error number from previous operation
  • fbsql_warnings() - Enable or disable FrontBase warnings

fbsql_errno
fbsql_fetch_array
Func?ii FrontBase


Fetch a result row as an associative array, a numeric array, or both

fbsql_error
fbsql_fetch_assoc
Func?ii FrontBase
PHP Manual

fbsql_fetch_array

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Descrierea

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.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau 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.

Valorile întoarse

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

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii FrontBase


Fetch a result row as an associative array

fbsql_fetch_array
fbsql_fetch_field
Func?ii FrontBase
PHP Manual

fbsql_fetch_assoc

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_fetch_assoc — Fetch a result row as an associative array

Descrierea

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.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau fbsql_db_query().

Valorile întoarse

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.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii FrontBase


Get column information from a result and return as an object

fbsql_fetch_assoc
fbsql_fetch_lengths
Func?ii FrontBase
PHP Manual

fbsql_fetch_field

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_fetch_field — Get column information from a result and return as an object

Descrierea

object fbsql_fetch_field ( resource $result [, int $field_offset ] )

Used in order to obtain information about fields in a certain query result.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau 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.

Valorile întoarse

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

Exemple

Example #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);
?>

A se vedea ?i

  • fbsql_field_seek() - Set result pointer to a specified field offset

fbsql_fetch_assoc
fbsql_fetch_lengths
Func?ii FrontBase


Get the length of each output in a result

fbsql_fetch_field
fbsql_fetch_object
Func?ii FrontBase
PHP Manual

fbsql_fetch_lengths

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_fetch_lengths — Get the length of each output in a result

Descrierea

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.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau fbsql_db_query().

Valorile întoarse

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.

A se vedea ?i

  • fbsql_fetch_row() - Get a result row as an enumerated array

fbsql_fetch_field
fbsql_fetch_object
Func?ii FrontBase


Fetch a result row as an object

fbsql_fetch_lengths
fbsql_fetch_row
Func?ii FrontBase
PHP Manual

fbsql_fetch_object

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_fetch_object — Fetch a result row as an object

Descrierea

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).

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau fbsql_db_query().

Valorile întoarse

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii FrontBase


Get a result row as an enumerated array

fbsql_fetch_object
fbsql_field_flags
Func?ii FrontBase
PHP Manual

fbsql_fetch_row

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_fetch_row — Get a result row as an enumerated array

Descrierea

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.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau fbsql_db_query().

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii FrontBase


Get the flags associated with the specified field in a result

fbsql_fetch_row
fbsql_field_len
Func?ii FrontBase
PHP Manual

fbsql_field_flags

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_field_flags — Get the flags associated with the specified field in a result

Descrierea

string fbsql_field_flags ( resource $result [, int $field_offset ] )

Gets the flags associated with the specified field in a result.

Parametri

result

A result pointer returned by fbsql_list_fields().

field_offset

The numerical offset of the field. The field index starts at 0.

Valorile întoarse

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
Func?ii FrontBase


Returns the length of the specified field

fbsql_field_flags
fbsql_field_name
Func?ii FrontBase
PHP Manual

fbsql_field_len

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_field_len — Returns the length of the specified field

Descrierea

int fbsql_field_len ( resource $result [, int $field_offset ] )

Returns the length of the specified field.

Parametri

result

A result pointer returned by fbsql_list_fields().

field_offset

The numerical offset of the field. The field index starts at 0.

Valorile întoarse

Returns the length of the specified field.

fbsql_field_flags
fbsql_field_name
Func?ii FrontBase


Get the name of the specified field in a result

fbsql_field_len
fbsql_field_seek
Func?ii FrontBase
PHP Manual

fbsql_field_name

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_field_name — Get the name of the specified field in a result

Descrierea

string fbsql_field_name ( resource $result [, int $field_index ] )

Returns the name of the specified field index.

Parametri

result

A result pointer returned by fbsql_list_fields().

field_index

The numerical offset of the field. The field index starts at 0.

Valorile întoarse

Returns the name as a string, or FALSE if the field doesn't exist.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

user_id
password

A se vedea ?i

  • fbsql_field_type() - Get the type of the specified field in a result

fbsql_field_len
fbsql_field_seek
Func?ii FrontBase


Set result pointer to a specified field offset

fbsql_field_name
fbsql_field_table
Func?ii FrontBase
PHP Manual

fbsql_field_seek

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_field_seek — Set result pointer to a specified field offset

Descrierea

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.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fbsql_fetch_field() - Get column information from a result and return as an object

fbsql_field_name
fbsql_field_table
Func?ii FrontBase


Get name of the table the specified field is in

fbsql_field_seek
fbsql_field_type
Func?ii FrontBase
PHP Manual

fbsql_field_table

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_field_table — Get name of the table the specified field is in

Descrierea

string fbsql_field_table ( resource $result [, int $field_offset ] )

Returns the name of the table that the specified field is in.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Valorile întoarse

Returns the name of the table, as a string.

fbsql_field_seek
fbsql_field_type
Func?ii FrontBase


Get the type of the specified field in a result

fbsql_field_table
fbsql_free_result
Func?ii FrontBase
PHP Manual

fbsql_field_type

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_field_type — Get the type of the specified field in a result

Descrierea

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.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Valorile întoarse

Returns the field type, as a string.

This can be one of int, real, string, blob, and others as detailed in the » FrontBase documentation.

Exemple

Example #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();

?>

A se vedea ?i

  • fbsql_field_name() - Get the name of the specified field in a result

fbsql_field_table
fbsql_free_result
Func?ii FrontBase


Free result memory

fbsql_field_type
fbsql_get_autostart_info
Func?ii FrontBase
PHP Manual

fbsql_free_result

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_free_result — Free result memory

Descrierea

bool fbsql_free_result ( resource $result )

Frees all memory associated with the given result identifier.

fbsql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau fbsql_db_query().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

fbsql_field_type
fbsql_get_autostart_info
Func?ii FrontBase


fbsql_free_result
fbsql_hostname
Func?ii FrontBase
PHP Manual

fbsql_get_autostart_info

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

fbsql_get_autostart_info —

Descrierea

array fbsql_get_autostart_info ([ resource $link_identifier ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

fbsql_free_result
fbsql_hostname
Func?ii FrontBase


Get or set the host name used with a connection

fbsql_get_autostart_info
fbsql_insert_id
Func?ii FrontBase
PHP Manual

fbsql_hostname

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_hostname — Get or set the host name used with a connection

Descrierea

string fbsql_hostname ( resource $link_identifier [, string $host_name ] )

Gets or sets the host name used with a connection.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

host_name

If provided, this will be the new connection host name.

Valorile întoarse

Returns the current host name used for the connection.

A se vedea ?i

  • fbsql_username() - Get or set the username for the connection
  • fbsql_password() - Get or set the user password used with a connection

fbsql_get_autostart_info
fbsql_insert_id
Func?ii FrontBase


Get the id generated from the previous INSERT operation

fbsql_hostname
fbsql_list_dbs
Func?ii FrontBase
PHP Manual

fbsql_insert_id

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_insert_id — Get the id generated from the previous INSERT operation

Descrierea

int fbsql_insert_id ([ resource $link_identifier ] )

Gets the id generated from the previous INSERT operation which created a DEFAULT UNIQUE value.

Nota:

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.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

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.

A se vedea ?i

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation

fbsql_hostname
fbsql_list_dbs
Func?ii FrontBase


List databases available on a FrontBase server

fbsql_insert_id
fbsql_list_fields
Func?ii FrontBase
PHP Manual

fbsql_list_dbs

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_list_dbs — List databases available on a FrontBase server

Descrierea

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.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Returns a result pointer or FALSE on error.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

database1
database2
database3
...

Nota:

The above code would just as easily work with fbsql_fetch_row() or other similar functions.

A se vedea ?i

  • fbsql_list_fields() - List FrontBase result fields
  • fbsql_list_tables() - List tables in a FrontBase database

fbsql_insert_id
fbsql_list_fields
Func?ii FrontBase


List FrontBase result fields

fbsql_list_dbs
fbsql_list_tables
Func?ii FrontBase
PHP Manual

fbsql_list_fields

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_list_fields — List FrontBase result fields

Descrierea

resource fbsql_list_fields ( string $database_name , string $table_name [, resource $link_identifier ] )

Retrieves information about the given table.

Parametri

database_name

The database name.

table_name

The table name.

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Returns a result pointer which can be used with the fbsql_field_xxx functions, or FALSE on error.

Erori/Excep?ii

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.

Exemple

Example #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";;
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

field1
field2
field3
...

A se vedea ?i

  • 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
Func?ii FrontBase


List tables in a FrontBase database

fbsql_list_fields
fbsql_next_result
Func?ii FrontBase
PHP Manual

fbsql_list_tables

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_list_tables — List tables in a FrontBase database

Descrierea

resource fbsql_list_tables ( string $database [, resource $link_identifier ] )

Returns a result pointer describing the database.

Parametri

database

The database name.

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Returns a result pointer which can be used with the fbsql_tablename() function to read the actual table names, or FALSE on error.

A se vedea ?i

  • fbsql_list_fields() - List FrontBase result fields
  • fbsql_list_dbs() - List databases available on a FrontBase server

fbsql_list_fields
fbsql_next_result
Func?ii FrontBase


Move the internal result pointer to the next result

fbsql_list_tables
fbsql_num_fields
Func?ii FrontBase
PHP Manual

fbsql_next_result

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_next_result — Move the internal result pointer to the next result

Descrierea

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.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau fbsql_db_query().

Valorile întoarse

Returns TRUE if an additional result set was available or FALSE otherwise.

Exemple

Example #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
Func?ii FrontBase


Get number of fields in result

fbsql_next_result
fbsql_num_rows
Func?ii FrontBase
PHP Manual

fbsql_num_fields

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_num_fields — Get number of fields in result

Descrierea

int fbsql_num_fields ( resource $result )

Returns the number of fields in the given result set.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau fbsql_db_query().

Valorile întoarse

Returns the number of fields, as an integer.

A se vedea ?i

  • fbsql_db_query() - Send a FrontBase query
  • fbsql_query() - Send a FrontBase query
  • 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
Func?ii FrontBase


Get number of rows in result

fbsql_num_fields
fbsql_password
Func?ii FrontBase
PHP Manual

fbsql_num_rows

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_num_rows — Get number of rows in result

Descrierea

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().

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau fbsql_db_query().

Valorile întoarse

Returns the number of rows returned by the last SELECT statement.

Exemple

Example #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";

?>

A se vedea ?i

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation
  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_select_db() - Select a FrontBase database
  • fbsql_query() - Send a FrontBase query

fbsql_num_fields
fbsql_password
Func?ii FrontBase


Get or set the user password used with a connection

fbsql_num_rows
fbsql_pconnect
Func?ii FrontBase
PHP Manual

fbsql_password

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_password — Get or set the user password used with a connection

Descrierea

string fbsql_password ( resource $link_identifier [, string $password ] )

Get or set the user password used with a connection.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

password

If provided, this will be the new connection password.

Valorile întoarse

Returns the current password used for the connection.

A se vedea ?i

  • fbsql_username() - Get or set the username for the connection
  • fbsql_hostname() - Get or set the host name used with a connection

fbsql_num_rows
fbsql_pconnect
Func?ii FrontBase


Open a persistent connection to a FrontBase Server

fbsql_password
fbsql_query
Func?ii FrontBase
PHP Manual

fbsql_pconnect

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_pconnect — Open a persistent connection to a FrontBase Server

Descrierea

 resource fbsql_pconnect
  ([ string $hostname = ini_get("fbsql.default_host")
 [, string $username = ini_get("fbsql.default_user")
 [, string $password = ini_get("fbsql.default_password")
]]] )

Establishes a persistent connection to a FrontBase server.

To set the server port number, use fbsql_select_db().

fbsql_pconnect() acts very much like fbsql_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.

This type of links is therefore called 'persistent'.

Parametri

hostname

The server host name.

username

The user name for the connection.

password

The password for the connection.

Valorile întoarse

Returns a positive FrontBase persistent link identifier on success, or FALSE on error.

A se vedea ?i

  • fbsql_connect() - Open a connection to a FrontBase Server

fbsql_password
fbsql_query
Func?ii FrontBase


Send a FrontBase query

fbsql_pconnect
fbsql_read_blob
Func?ii FrontBase
PHP Manual

fbsql_query

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_query — Send a FrontBase query

Descrierea

resource fbsql_query ( string $query [, resource $link_identifier [, int $batch_size ]] )

Sends a query to the currently active database on the server.

If the query succeeds, you can call fbsql_num_rows() to find out how many rows were returned for a SELECT statement or fbsql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

Parametri

query

The SQL query to be executed.

Nota:

The query string shall always end with a semicolon.

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

batch_size

Valorile întoarse

fbsql_query() returns TRUE (non-zero) or FALSE to indicate whether or not the query succeeded. A return value of TRUE means that the query was legal and could be executed by the server. It does not indicate anything about the number of rows affected or returned. It is perfectly possible for a query to succeed but affect no rows or return no rows.

For SELECT statements, fbsql_query() returns a new result identifier that you can pass to fbsql_result().

fbsql_query() will also fail and return FALSE if you don't have permission to access the table(s) referenced by the query.

Exemple

The following query is syntactically invalid, so fbsql_query() fails and returns FALSE:

Example #1 fbsql_query() example

<?php
$result = fbsql_query("SELECT * WHERE 1=1")
    or die ("Invalid query");
?>

The following query is semantically invalid if my_col is not a column in the table my_tbl, so fbsql_query() fails and returns FALSE:

Example #2 fbsql_query() example

<?php
$result = fbsql_query ("SELECT my_col FROM my_tbl;")
    or die ("Invalid query");
?>

A se vedea ?i

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation
  • fbsql_db_query() - Send a FrontBase query
  • fbsql_free_result() - Free result memory
  • fbsql_result() - Get result data
  • fbsql_select_db() - Select a FrontBase database
  • fbsql_connect() - Open a connection to a FrontBase Server

fbsql_pconnect
fbsql_read_blob
Func?ii FrontBase


Read a BLOB from the database

fbsql_query
fbsql_read_clob
Func?ii FrontBase
PHP Manual

fbsql_read_blob

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_read_blob — Read a BLOB from the database

Descrierea

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.

Parametri

blob_handle

A BLOB handle, returned by fbsql_create_blob().

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Returns a string containing the specified BLOB data.

Exemple

Example #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);

?>

A se vedea ?i

  • 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
Func?ii FrontBase


Read a CLOB from the database

fbsql_read_blob
fbsql_result
Func?ii FrontBase
PHP Manual

fbsql_read_clob

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_read_clob — Read a CLOB from the database

Descrierea

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.

Parametri

clob_handle

A CLOB handle, returned by fbsql_create_clob().

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Returns a string containing the specified CLOB data.

Exemple

Example #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);

?>

A se vedea ?i

  • 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
Func?ii FrontBase


Get result data

fbsql_read_clob
fbsql_rollback
Func?ii FrontBase
PHP Manual

fbsql_result

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_result — Get result data

Descrierea

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.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau 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.

Nota:

Specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Valorile întoarse

A se vedea ?i

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
Func?ii FrontBase


Rollback a transaction to the database

fbsql_result
fbsql_rows_fetched
Func?ii FrontBase
PHP Manual

fbsql_rollback

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_rollback — Rollback a transaction to the database

Descrierea

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.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fbsql_autocommit() - Enable or disable autocommit
  • fbsql_commit() - Commits a transaction to the database

fbsql_result
fbsql_rows_fetched
Func?ii FrontBase


Get the number of rows affected by the last statement

fbsql_rollback
fbsql_select_db
Func?ii FrontBase
PHP Manual

fbsql_rows_fetched

(PHP 5 >= 5.1.0, PHP 7)

fbsql_rows_fetched — Get the number of rows affected by the last statement

Descrierea

int fbsql_rows_fetched ( resource $result )

Gets the number of rows affected by the last statement.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau fbsql_db_query().

Valorile întoarse

Returns the number of rows, as an integer.

fbsql_rollback
fbsql_select_db
Func?ii FrontBase


Select a FrontBase database

fbsql_rows_fetched
fbsql_set_characterset
Func?ii FrontBase
PHP Manual

fbsql_select_db

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_select_db — Select a FrontBase database

Descrierea

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.

Parametri

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

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server
  • fbsql_database_password() - Sets or retrieves the password for a FrontBase database
  • fbsql_query() - Send a FrontBase query

fbsql_rows_fetched
fbsql_set_characterset
Func?ii FrontBase


Change input/output character set

fbsql_select_db
fbsql_set_lob_mode
Func?ii FrontBase
PHP Manual

fbsql_set_characterset

(PHP 5 >= 5.1.0, PHP 7)

fbsql_set_characterset — Change input/output character set

Descrierea

void fbsql_set_characterset ( resource $link_identifier , int $characterset [, int $in_out_both ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

fbsql_select_db
fbsql_set_lob_mode
Func?ii FrontBase


Set the LOB retrieve mode for a FrontBase result set

fbsql_set_characterset
fbsql_set_password
Func?ii FrontBase
PHP Manual

fbsql_set_lob_mode

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_set_lob_mode — Set the LOB retrieve mode for a FrontBase result set

Descrierea

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.

Parametri

result

Un identificator al rezultatului întors de fbsql_query() sau 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'.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii FrontBase


Change the password for a given user

fbsql_set_lob_mode
fbsql_set_transaction
Func?ii FrontBase
PHP Manual

fbsql_set_password

(PHP 5, PHP 7)

fbsql_set_password — Change the password for a given user

Descrierea

bool fbsql_set_password ( resource $link_identifier , string $user , string $password , string $old_password )

Changes the password for the given user.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

user

The user name.

password

The new password to be set.

old_password

The old password to be replaced.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

fbsql_set_lob_mode
fbsql_set_transaction
Func?ii FrontBase


Set the transaction locking and isolation

fbsql_set_password
fbsql_start_db
Func?ii FrontBase
PHP Manual

fbsql_set_transaction

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_set_transaction — Set the transaction locking and isolation

Descrierea

void fbsql_set_transaction ( resource $link_identifier , int $locking , int $isolation )

Sets the transaction locking and isolation.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

fbsql_set_password
fbsql_start_db
Func?ii FrontBase


Start a database on local or remote server

fbsql_set_transaction
fbsql_stop_db
Func?ii FrontBase
PHP Manual

fbsql_start_db

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_start_db — Start a database on local or remote server

Descrierea

bool fbsql_start_db ( string $database_name [, resource $link_identifier [, string $database_options ]] )

Start a database on local or remote server.

Parametri

database_name

The database name.

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

database_options

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fbsql_db_status() - Get the status for a given database
  • fbsql_stop_db() - Stop a database on local or remote server

fbsql_set_transaction
fbsql_stop_db
Func?ii FrontBase


Stop a database on local or remote server

fbsql_start_db
fbsql_table_name
Func?ii FrontBase
PHP Manual

fbsql_stop_db

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_stop_db — Stop a database on local or remote server

Descrierea

bool fbsql_stop_db ( string $database_name [, resource $link_identifier ] )

Stops a database on local or remote server.

Parametri

database_name

The database name.

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fbsql_db_status() - Get the status for a given database
  • fbsql_start_db() - Start a database on local or remote server

fbsql_start_db
fbsql_table_name
Func?ii FrontBase


Get table name of field

fbsql_stop_db
fbsql_tablename
Func?ii FrontBase
PHP Manual

fbsql_table_name

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_table_name — Get table name of field

Descrierea

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.

Parametri

result

A result pointer returned by fbsql_list_tables().

index

Integer index for the current table.

Valorile întoarse

Returns the name of the table, as a string.

Exemple

Example #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
Func?ii FrontBase


Pseudonim pentru fbsql_table_name

fbsql_table_name
fbsql_username
Func?ii FrontBase
PHP Manual

fbsql_tablename

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_tablename — Pseudonim pentru fbsql_table_name()

Descrierea

Aceasta func?ie este pseudonim pentru: fbsql_table_name().

fbsql_table_name
fbsql_username
Func?ii FrontBase


Get or set the username for the connection

fbsql_tablename
fbsql_warnings
Func?ii FrontBase
PHP Manual

fbsql_username

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_username — Get or set the username for the connection

Descrierea

string fbsql_username ( resource $link_identifier [, string $username ] )

Get or set the username used for the connection.

Parametri

link_identifier

Un identificator de legatura FrontBase întors de fbsql_connect() sau fbsql_pconnect ().

Daca nu este specificat, func?ia va încerca sa gaseasca o legatura deschisa catre serverul FrontBase ?i daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia, ca ?i la apelarea fbsql_connect() fara argumente.

username

If provided, this is the new username to set.

Valorile întoarse

Returns the current username used with the connection, as a string.

A se vedea ?i

  • fbsql_password() - Get or set the user password used with a connection
  • fbsql_hostname() - Get or set the host name used with a connection

fbsql_tablename
fbsql_warnings
Func?ii FrontBase


Enable or disable FrontBase warnings

fbsql_username
IBM DB2
Func?ii FrontBase
PHP Manual

fbsql_warnings

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_warnings — Enable or disable FrontBase warnings

Descrierea

bool fbsql_warnings ([ bool $OnOff ] )

Enables or disables FrontBase warnings.

Parametri

OnOff

Whether to enable warnings or no.

Valorile întoarse

Returns TRUE if warnings is turned on, FALSE otherwise.

A se vedea ?i

  • fbsql_errno() - Returns the error number from previous operation
  • fbsql_error() - Returns the error message from previous operation

fbsql_username
IBM DB2
Func?ii FrontBase


IBM DB2, Cloudscape and Apache Derby

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii IBM DB2
    • 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
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

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
Instalarea / configurarea
IBM DB2


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
IBM DB2


Necesita?i

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).

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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.

Nota: 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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

ibm_db2 Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | 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.

Iata o explica?ie pe scurt a directivelor de configurare.

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 isolation mode used for i5 schema collections in the PHP application (see i5_commit for override).

  • 0 - commitment control is not used

  • 1 - read uncommitted, dirty reads possible.

  • 2 - read committed, dirty reads are not possible.

  • 3 - repeatable read, dirty reads and non-repeatable reads are not possible

  • 4 - serializeable, dirty reads, non-repeatable reads, and phantoms are not possible

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

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

The ibm_db2 extension returns connection resources, statement resources, and result set resources.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
Func?ii IBM DB2
IBM DB2


Func?ii IBM DB2

Cuprins

  • 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
Constante predefinite
db2_autocommit
IBM DB2


Returns or sets the AUTOCOMMIT state for a database connection

Func?ii IBM DB2
db2_bind_param
Func?ii IBM DB2
PHP Manual

db2_autocommit

(PECL ibm_db2 >= 1.0.0)

db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection

Descrierea

mixed db2_autocommit ( resource $connection [, bool $value ] )

Sets or gets the AUTOCOMMIT behavior of the specified connection resource.

Parametri

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.

Valorile întoarse

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. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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.";
}
?>

Exemplul de mai sus va afi?a:

0 -- AUTOCOMMIT is off.

Example #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.";
}
?>

Exemplul de mai sus va afi?a:

Turning AUTOCOMMIT on succeeded.
1 -- AUTOCOMMIT is on.

A se vedea ?i

  • db2_connect() - Returns a connection to a database
  • db2_pconnect() - Returns a persistent connection to a database

Func?ii IBM DB2
db2_bind_param
Func?ii IBM DB2


Binds a PHP variable to an SQL statement parameter

db2_autocommit
db2_client_info
Func?ii IBM DB2
PHP Manual

db2_bind_param

(PECL ibm_db2 >= 1.0.0)

db2_bind_param — Binds a PHP variable to an SQL statement parameter

Descrierea

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().

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

Pook, cat, 3.2
Rickety Ride, goat, 9.7
Peaches, dog, 12.3

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

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

Example #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);
?>

A se vedea ?i

  • db2_execute() - Executes a prepared SQL statement
  • db2_prepare() - Prepares an SQL statement to be executed

db2_autocommit
db2_client_info
Func?ii IBM DB2


Returns an object with properties that describe the DB2 database client

db2_bind_param
db2_close
Func?ii IBM DB2
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

Descrierea

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".

Parametri

connection

Specifies an active DB2 client connection.

Valorile întoarse

Returns an object on a successful call. Returns FALSE on failure.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

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)

A se vedea ?i

  • db2_server_info() - Returns an object with properties that describe the DB2 database server

db2_bind_param
db2_close
Func?ii IBM DB2


Closes a database connection

db2_client_info
db2_column_privileges
Func?ii IBM DB2
PHP Manual

db2_close

(PECL ibm_db2 >= 1.0.0)

db2_close — Closes a database connection

Descrierea

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.

Parametri

connection

Specifies an active DB2 client connection.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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.";
}
?>

Exemplul de mai sus va afi?a:

Connection was successfully closed.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a result set listing the columns and associated privileges for a table

db2_close
db2_columns
Func?ii IBM DB2
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

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a result set listing the columns and associated metadata for a table

db2_column_privileges
db2_commit
Func?ii IBM DB2
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

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Commits a transaction

db2_columns
db2_conn_error
Func?ii IBM DB2
PHP Manual

db2_commit

(PECL ibm_db2 >= 1.0.0)

db2_commit — Commits a transaction

Descrierea

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.

Parametri

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • db2_autocommit() - Returns or sets the AUTOCOMMIT state for a database connection
  • db2_rollback() - Rolls back a transaction

db2_columns
db2_conn_error
Func?ii IBM DB2


Returns a string containing the SQLSTATE returned by the last connection attempt

db2_commit
db2_conn_errormsg
Func?ii IBM DB2
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

Descrierea

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.

Parametri

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

Valorile întoarse

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.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a:

SQLSTATE value: 08001

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns the last connection error message and SQLCODE value

db2_conn_error
db2_connect
Func?ii IBM DB2
PHP Manual

db2_conn_errormsg

(PECL ibm_db2 >= 1.0.0)

db2_conn_errormsg — Returns the last connection error message and SQLCODE value

Descrierea

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.

Parametri

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

Valorile întoarse

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.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a:

[IBM][CLI Driver] SQL1013N  The database alias name
or database name "BADNAME" could not be found.  SQLSTATE=42705
 SQLCODE=-1013

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a connection to a database

db2_conn_errormsg
db2_cursor_type
Func?ii IBM DB2
PHP Manual

db2_connect

(PECL ibm_db2 >= 1.0.0)

db2_connect — Returns a connection to a database

Descrierea

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.

Parametri

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.

Nota:

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".

Nota:

i5_libl calls qsys2/qcmdexc('cmd',cmdlen), which is only available in i5/OS V5R4 and later.

Valorile întoarse

Returns a connection handle resource if the connection attempt is successful. If the connection attempt fails, db2_connect() returns FALSE.

Exemple

Example #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.";
}
?>

Exemplul de mai sus va afi?a:

Connection succeeded.

Example #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.";
}
?>

Exemplul de mai sus va afi?a:

Connection succeeded.

Example #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.";
}
?>

Exemplul de mai sus va afi?a:

Connection succeeded.
Autocommit is off.

Example #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);
?>

Exemplul de mai sus va afi?a:

ANIMALS
NAMES
PICTURES

Example #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";
}
?>

Exemplul de mai sus va afi?a:

Explicit trusted connection succeeded.
User has been switched.

A se vedea ?i

  • db2_close() - Closes a database connection
  • db2_pconnect() - Returns a persistent connection to a database

db2_conn_errormsg
db2_cursor_type
Func?ii IBM DB2


Returns the cursor type used by a statement resource

db2_connect
db2_escape_string
Func?ii IBM DB2
PHP Manual

db2_cursor_type

(PECL ibm_db2 >= 1.0.0)

db2_cursor_type — Returns the cursor type used by a statement resource

Descrierea

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.

Parametri

stmt

A valid statement resource.

Valorile întoarse

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.

A se vedea ?i

  • db2_prepare() - Prepares an SQL statement to be executed

db2_connect
db2_escape_string
Func?ii IBM DB2


Used to escape certain characters

db2_cursor_type
db2_exec
Func?ii IBM DB2
PHP Manual

db2_escape_string

(PECL ibm_db2 >= 1.6.0)

db2_escape_string — Used to escape certain characters

Descrierea

string db2_escape_string ( string $string_literal )

Prepends backslashes to special characters in the string argument.

Parametri

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.

Valorile întoarse

Returns string_literal with the special characters noted above prepended with backslashes.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

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:

A se vedea ?i

  • db2_prepare() - Prepares an SQL statement to be executed

db2_cursor_type
db2_exec
Func?ii IBM DB2


Executes an SQL statement directly

db2_escape_string
db2_execute
Func?ii IBM DB2
PHP Manual

db2_exec

(PECL ibm_db2 >= 1.0.0)

db2_exec — Executes an SQL statement directly

Descrierea

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.

Parametri

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().

Valorile întoarse

Returns a statement resource if the SQL statement was issued successfully, or FALSE if the database failed to execute the SQL statement.

Exemple

Example #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... ";
    }
}
?>

Exemplul de mai sus va afi?a:

Successfully created the table.
Insert... Insert... Insert... Insert... Insert... Insert... Insert...

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

Bubbles
Gizmo
Pook
Rickety Ride

Example #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);

?>

Exemplul de mai sus va afi?a:

1000     Kathy Smith     416-555-1358
1001     Kathy Smith     905-555-7258

Example #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);

?>

Exemplul de mai sus va afi?a:

1001     Kathy Smith     905-555-7258     5002     Shipped

Example #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);

?>

Exemplul de mai sus va afi?a:

<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>

A se vedea ?i

  • db2_execute() - Executes a prepared SQL statement
  • db2_prepare() - Prepares an SQL statement to be executed

db2_escape_string
db2_execute
Func?ii IBM DB2


Executes a prepared SQL statement

db2_exec
db2_fetch_array
Func?ii IBM DB2
PHP Manual

db2_execute

(PECL ibm_db2 >= 1.0.0)

db2_execute — Executes a prepared SQL statement

Descrierea

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().

Parametri

stmt

A prepared statement returned from db2_prepare().

parameters

An array of input parameters matching any parameter markers contained in the prepared statement.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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.";
    }
}
?>

Exemplul de mai sus va afi?a:

Successfully added new pet.

Example #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!";
?>

Exemplul de mai sus va afi?a:

I have 7 pets!

Example #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);

?>

Exemplul de mai sus va afi?a:

1000     Kathy Smith     416-555-1358
1001     Kathy Smith     905-555-7258

Example #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);

?>

Exemplul de mai sus va afi?a:

1001     Kathy Smith     905-555-7258     5002     Shipped

Example #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);

?>

Exemplul de mai sus va afi?a:

<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>

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns an array, indexed by column position, representing a row in a result set

db2_execute
db2_fetch_assoc
Func?ii IBM DB2
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

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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]);
}
?>

Exemplul de mai sus va afi?a:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Example #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;
}
?>

Exemplul de mai sus va afi?a:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns an array, indexed by column name, representing a row in a result set

db2_fetch_array
db2_fetch_both
Func?ii IBM DB2
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

Descrierea

array db2_fetch_assoc ( resource $stmt [, int $row_number = -1 ] )

Returns an array, indexed by column name, representing a row in a result set.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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']);
}
?>

Exemplul de mai sus va afi?a:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Example #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;
}
?>

Exemplul de mai sus va afi?a:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns an array, indexed by both column name and position, representing a row in a result set

db2_fetch_assoc
db2_fetch_object
Func?ii IBM DB2
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

Descrierea

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().

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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]);
}
?>

Exemplul de mai sus va afi?a:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Example #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;
}
?>

Exemplul de mai sus va afi?a:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns an object with properties representing columns in the fetched row

db2_fetch_both
db2_fetch_row
Func?ii IBM DB2
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

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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);
}
?>

Exemplul de mai sus va afi?a:

Come here, Pook, my little cat!

A se vedea ?i

  • 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
Func?ii IBM DB2


Sets the result set pointer to the next row or requested row

db2_fetch_object
db2_field_display_size
Func?ii IBM DB2
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE if the requested row exists in the result set. Returns FALSE if the requested row does not exist in the result set.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

Example #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);
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns the maximum number of bytes required to display a column

db2_fetch_row
db2_field_name
Func?ii IBM DB2
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

Descrierea

int db2_field_display_size ( resource $stmt , mixed $column )

Returns the maximum number of bytes required to display a column in a result set.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns the name of the column in the result set

db2_field_display_size
db2_field_num
Func?ii IBM DB2
PHP Manual

db2_field_name

(PECL ibm_db2 >= 1.0.0)

db2_field_name — Returns the name of the column in the result set

Descrierea

string db2_field_name ( resource $stmt , mixed $column )

Returns the name of the specified column in the result set.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns the position of the named column in a result set

db2_field_name
db2_field_precision
Func?ii IBM DB2
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

Descrierea

int db2_field_num ( resource $stmt , mixed $column )

Returns the position of the named column in a result set.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns the precision of the indicated column in a result set

db2_field_num
db2_field_scale
Func?ii IBM DB2
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

Descrierea

int db2_field_precision ( resource $stmt , mixed $column )

Returns the precision of the indicated column in a result set.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns the scale of the indicated column in a result set

db2_field_precision
db2_field_type
Func?ii IBM DB2
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

Descrierea

int db2_field_scale ( resource $stmt , mixed $column )

Returns the scale of the indicated column in a result set.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns the data type of the indicated column in a result set

db2_field_scale
db2_field_width
Func?ii IBM DB2
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

Descrierea

string db2_field_type ( resource $stmt , mixed $column )

Returns the data type of the indicated column in a result set.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns the width of the current value of the indicated column in a result set

db2_field_type
db2_foreign_keys
Func?ii IBM DB2
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

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a result set listing the foreign keys for a table

db2_field_width
db2_free_result
Func?ii IBM DB2
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

Descrierea

resource db2_foreign_keys ( resource $connection , string $qualifier , string $schema , string $table-name )

Returns a result set listing the foreign keys for a table.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Frees resources associated with a result set

db2_foreign_keys
db2_free_stmt
Func?ii IBM DB2
PHP Manual

db2_free_result

(PECL ibm_db2 >= 1.0.0)

db2_free_result — Frees resources associated with a result set

Descrierea

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.

Parametri

stmt

A valid statement resource.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • db2_free_stmt() - Frees resources associated with the indicated statement resource

db2_foreign_keys
db2_free_stmt
Func?ii IBM DB2


Frees resources associated with the indicated statement resource

db2_free_result
db2_get_option
Func?ii IBM DB2
PHP Manual

db2_free_stmt

(PECL ibm_db2 >= 1.0.0)

db2_free_stmt — Frees resources associated with the indicated statement resource

Descrierea

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.

Parametri

stmt

A valid statement resource.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • db2_free_result() - Frees resources associated with a result set

db2_free_result
db2_get_option
Func?ii IBM DB2


Retrieves an option value for a statement resource or a connection resource

db2_free_stmt
db2_last_insert_id
Func?ii IBM DB2
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

Descrierea

string db2_get_option ( resource $resource , string $option )

Retrieves the value of a specified option value for a statement resource or a connection resource.

Parametri

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().

Nota:

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.

Nota:

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.

Nota:

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.

Nota:

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.

Nota:

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 | -

Valorile întoarse

Returns the current setting of the connection attribute provided on success sau FALSE în cazul e?ecului.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

Client attributes passed through connection string:
db2inst1
account
myapp
workstation
Client attributes passed post-connection:
db2inst1
account
myapp
workstation

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns the auto generated ID of the last insert query that successfully executed on this connection

db2_get_option
db2_lob_read
Func?ii IBM DB2
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the auto generated ID of last insert query that successfully executed on this connection.

Exemple

Example #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.";
}
?>

Exemplul de mai sus va afi?a:

Last Insert ID is : 1

db2_get_option
db2_lob_read
Func?ii IBM DB2


Gets a user defined size of LOB files with each invocation

db2_last_insert_id
db2_next_result
Func?ii IBM DB2
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the amount of data the user specifies. Returns FALSE if the data cannot be retrieved.

Exemple

Example #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();
}

?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Requests the next result set from a stored procedure

db2_lob_read
db2_num_fields
Func?ii IBM DB2
PHP Manual

db2_next_result

(PECL ibm_db2 >= 1.0.0)

db2_next_result — Requests the next result set from a stored procedure

Descrierea

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.

Parametri

stmt

A prepared statement returned from db2_exec() or db2_execute().

Valorile întoarse

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.

Exemple

Example #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);
}
?>

Exemplul de mai sus va afi?a:

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
Func?ii IBM DB2


Returns the number of fields contained in a result set

db2_next_result
db2_num_rows
Func?ii IBM DB2
PHP Manual

db2_num_fields

(PECL ibm_db2 >= 1.0.0)

db2_num_fields — Returns the number of fields contained in a result set

Descrierea

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.

Parametri

stmt

A valid statement resource containing a result set.

Valorile întoarse

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.

Exemple

Example #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.";
?>

Exemplul de mai sus va afi?a:

There are 4 columns in the result set.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns the number of rows affected by an SQL statement

db2_num_fields
db2_pclose
Func?ii IBM DB2
PHP Manual

db2_num_rows

(PECL ibm_db2 >= 1.0.0)

db2_num_rows — Returns the number of rows affected by an SQL statement

Descrierea

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.

Nota:

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.

Parametri

stmt

A valid stmt resource containing a result set.

Valorile întoarse

Returns the number of rows affected by the last SQL statement issued by the specified statement handle.

db2_num_fields
db2_pclose
Func?ii IBM DB2


Closes a persistent database connection

db2_num_rows
db2_pconnect
Func?ii IBM DB2
PHP Manual

db2_pclose

(PECL ibm_db2 >= 1.8.0)

db2_pclose — Closes a persistent database connection

Descrierea

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.

Nota:

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.

Parametri

connection

Specifies an active DB2 client connection.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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.";
}
?>

Exemplul de mai sus va afi?a:

Connection was successfully closed.

A se vedea ?i

  • db2_close() - Closes a database connection
  • db2_pconnect() - Returns a persistent connection to a database

db2_num_rows
db2_pconnect
Func?ii IBM DB2


Returns a persistent connection to a database

db2_pclose
db2_prepare
Func?ii IBM DB2
PHP Manual

db2_pconnect

(PECL ibm_db2 >= 1.0.0)

db2_pconnect — Returns a persistent connection to a database

Descrierea

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 Persistent Database Connections.

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.

Parametri

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.

Sfat

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.

Nota:

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.

Nota:

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".

Nota:

i5_libl calls qsys2/qcmdexc('cmd',cmdlen), which is only available in i5/OS V5R4 and later.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #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.";
}
?>

Exemplul de mai sus va afi?a:

Persistent connection succeeded.
Second persistent connection succeeded.

Example #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";
}
?>

Exemplul de mai sus va afi?a:

Explicit trusted connection succeeded.
User has been switched.

A se vedea ?i

  • db2_connect() - Returns a connection to a database

db2_pclose
db2_prepare
Func?ii IBM DB2


Prepares an SQL statement to be executed

db2_pconnect
db2_primary_keys
Func?ii IBM DB2
PHP Manual

db2_prepare

(PECL ibm_db2 >= 1.0.0)

db2_prepare — Prepares an SQL statement to be executed

Descrierea

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().

Parametri

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().

Valorile întoarse

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().

Exemple

Example #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);
    }
}
?>

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a result set listing primary keys for a table

db2_prepare
db2_procedure_columns
Func?ii IBM DB2
PHP Manual

db2_primary_keys

(PECL ibm_db2 >= 1.0.0)

db2_primary_keys — Returns a result set listing primary keys for a table

Descrierea

resource db2_primary_keys ( resource $connection , string $qualifier , string $schema , string $table-name )

Returns a result set listing the primary keys for a table.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a result set listing stored procedure parameters

db2_primary_keys
db2_procedures
Func?ii IBM DB2
PHP Manual

db2_procedure_columns

(PECL ibm_db2 >= 1.0.0)

db2_procedure_columns — Returns a result set listing stored procedure parameters

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a result set listing the stored procedures registered in a database

db2_procedure_columns
db2_result
Func?ii IBM DB2
PHP Manual

db2_procedures

(PECL ibm_db2 >= 1.0.0)

db2_procedures — Returns a result set listing the stored procedures registered in a database

Descrierea

resource db2_procedures ( resource $connection , string $qualifier , string $schema , string $procedure )

Returns a result set listing the stored procedures registered in a database.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a single column from a row in the result set

db2_procedures
db2_rollback
Func?ii IBM DB2
PHP Manual

db2_result

(PECL ibm_db2 >= 1.0.0)

db2_result — Returns a single column from a row in the result set

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

A se vedea ?i

  • 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
Func?ii IBM DB2


Rolls back a transaction

db2_result
db2_server_info
Func?ii IBM DB2
PHP Manual

db2_rollback

(PECL ibm_db2 >= 1.0.0)

db2_rollback — Rolls back a transaction

Descrierea

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.

Parametri

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
}
?>

Exemplul de mai sus va afi?a:

7
0
7

A se vedea ?i

  • db2_autocommit() - Returns or sets the AUTOCOMMIT state for a database connection
  • db2_commit() - Commits a transaction

db2_result
db2_server_info
Func?ii IBM DB2


Returns an object with properties that describe the DB2 database server

db2_rollback
db2_set_option
Func?ii IBM DB2
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

Descrierea

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.

Parametri

connection

Specifies an active DB2 client connection.

Valorile întoarse

Returns an object on a successful call. Returns FALSE on failure.

Exemple

Example #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);
}
?>

Exemplul de mai sus va afi?a:

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)

A se vedea ?i

  • db2_client_info() - Returns an object with properties that describe the DB2 database client

db2_rollback
db2_set_option
Func?ii IBM DB2


Set options for connection or statement resources

db2_server_info
db2_special_columns
Func?ii IBM DB2
PHP Manual

db2_set_option

(PECL ibm_db2 >= 1.0.0)

db2_set_option — Set options for connection or statement resources

Descrierea

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.

Parametri

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().

Nota:

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.

Nota:

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.

Nota:

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.

Nota:

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.

Nota:

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 | -

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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';
}
?>

Exemplul de mai sus va afi?a:

Options Set Successfully

Example #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';
}
?>

Exemplul de mai sus va afi?a:

Options Set Successfully

Example #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';
}
?>

Exemplul de mai sus va afi?a:

Could Not Set Options

Example #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';
}
?>

Exemplul de mai sus va afi?a:

Could Not Set Options

Example #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';
}
?>

Exemplul de mai sus va afi?a:

Could Not Set Options

Example #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';
}
?>

Exemplul de mai sus va afi?a:

Could Not Set Options

Example #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));

?>

Exemplul de mai sus va afi?a:

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
)

Example #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]}";
    }
  }
?>

Exemplul de mai sus va afi?a:

first2 last2

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a result set listing the unique row identifier columns for a table

db2_set_option
db2_statistics
Func?ii IBM DB2
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

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a result set listing the index and statistics for a table

db2_special_columns
db2_stmt_error
Func?ii IBM DB2
PHP Manual

db2_statistics

(PECL ibm_db2 >= 1.0.0)

db2_statistics — Returns a result set listing the index and statistics for a table

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a string containing the SQLSTATE returned by an SQL statement

db2_statistics
db2_stmt_errormsg
Func?ii IBM DB2
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

Descrierea

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.

Parametri

stmt

A valid statement resource.

Valorile întoarse

Returns a string containing an SQLSTATE value.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a string containing the last SQL statement error message

db2_stmt_error
db2_table_privileges
Func?ii IBM DB2
PHP Manual

db2_stmt_errormsg

(PECL ibm_db2 >= 1.0.0)

db2_stmt_errormsg — Returns a string containing the last SQL statement error message

Descrierea

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().

Parametri

stmt

A valid statement resource.

Valorile întoarse

Returns a string containing the error message and SQLCODE value for the last error that occurred issuing an SQL statement.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a result set listing the tables and associated privileges in a database

db2_stmt_errormsg
db2_tables
Func?ii IBM DB2
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

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Returns a result set listing the tables and associated metadata in a database

db2_table_privileges
Informix
Func?ii IBM DB2
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

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii IBM DB2


Informix

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Informix
    • 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
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

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.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.2.1.

Informix
Instalarea / configurarea
Informix


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Informix


Necesita?i

Nota: 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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Pentru a putea utiliza func?iile definite în acest modul trebuie sa compila?i interpretorul PHP utilizând linia de configurare --with-informix[=DIR] , unde DIR este directorul de baza al instalarii Informix, implicit este nedefinit.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Nota:

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).

Nota: 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").

Nota: 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".

Nota: 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
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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 modul securizat.

ifx.default_user string

The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in modul securizat.

ifx.default_password string

The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in modul securizat.

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().

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
Tipurile resurselor
Func?ii Informix
Informix


Func?ii Informix

Cuprins

  • 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
Constante predefinite
ifx_affected_rows
Informix


Get number of rows affected by a query

Func?ii Informix
ifx_blobinfile_mode
Func?ii Informix
PHP Manual

ifx_affected_rows

(PHP 4, PHP <=5.2.0)

ifx_affected_rows — Get number of rows affected by a query

Descrierea

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.

Parametri

result_id

A valid result id returned by ifx_query() or ifx_prepare().

Valorile întoarse

Returns the number of rows as an integer.

Exemple

Example #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");
}
?>

A se vedea ?i

  • ifx_num_rows() - Count the rows already fetched from a query

Func?ii Informix
ifx_blobinfile_mode
Func?ii Informix


Set the default blob mode for all select queries

ifx_affected_rows
ifx_byteasvarchar
Func?ii Informix
PHP Manual

ifx_blobinfile_mode

(PHP 4, PHP <=5.2.0)

ifx_blobinfile_mode — Set the default blob mode for all select queries

Descrierea

bool ifx_blobinfile_mode ( int $mode )

Set the default blob mode for all select queries.

Parametri

mode

Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ifx_affected_rows
ifx_byteasvarchar
Func?ii Informix


Set the default byte mode

ifx_blobinfile_mode
ifx_close
Func?ii Informix
PHP Manual

ifx_byteasvarchar

(PHP 4, PHP <=5.2.0)

ifx_byteasvarchar — Set the default byte mode

Descrierea

bool ifx_byteasvarchar ( int $mode )

Sets the default byte mode for all select-queries.

Parametri

mode

Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ifx_textasvarchar() - Set the default text mode

ifx_blobinfile_mode
ifx_close
Func?ii Informix


Close Informix connection

ifx_byteasvarchar
ifx_connect
Func?ii Informix
PHP Manual

ifx_close

(PHP 4, PHP <=5.2.0)

ifx_close — Close Informix connection

Descrierea

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().

Parametri

link_identifier

The link identifier. If not specified, the last opened link is assumed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Closing a Informix connection

<?php
$conn_id = ifx_connect ("mydb@ol_srv", "itsme", "mypassword");
/* ... some queries and stuff ... */
ifx_close($conn_id);
?>

A se vedea ?i

  • ifx_connect() - Open Informix server connection
  • ifx_pconnect() - Open persistent Informix connection

ifx_byteasvarchar
ifx_connect
Func?ii Informix


Open Informix server connection

ifx_close
ifx_copy_blob
Func?ii Informix
PHP Manual

ifx_connect

(PHP 4, PHP <=5.2.0)

ifx_connect — Open Informix server connection

Descrierea

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().

Parametri

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.

Valorile întoarse

Returns a connection identifier on success, or FALSE on error.

Exemple

Example #1 Connect to a Informix database

<?php
$conn_id = ifx_connect ("mydb@ol_srv1", "imyself", "mypassword");
?>

A se vedea ?i

  • ifx_pconnect() - Open persistent Informix connection
  • ifx_close() - Close Informix connection

ifx_close
ifx_copy_blob
Func?ii Informix


Duplicates the given blob object

ifx_connect
ifx_create_blob
Func?ii Informix
PHP Manual

ifx_copy_blob

(PHP 4, PHP <=5.2.0)

ifx_copy_blob — Duplicates the given blob object

Descrierea

int ifx_copy_blob ( int $bid )

Duplicates the given blob object.

Parametri

bid

A BLOB identifier.

Valorile întoarse

Returns the new blob object-id, or FALSE on errors.

A se vedea ?i

  • ifx_create_blob() - Creates an blob object
  • ifx_free_blob() - Deletes the blob object

ifx_connect
ifx_create_blob
Func?ii Informix


Creates an blob object

ifx_copy_blob
ifx_create_char
Func?ii Informix
PHP Manual

ifx_create_blob

(PHP 4, PHP <=5.2.0)

ifx_create_blob — Creates an blob object

Descrierea

int ifx_create_blob ( int $type , int $mode , string $param )

Creates a blob object.

Parametri

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.

Valorile întoarse

Returns the new BLOB object-id, or FALSE on errors.

A se vedea ?i

  • ifx_copy_blob() - Duplicates the given blob object
  • ifx_free_blob() - Deletes the blob object

ifx_copy_blob
ifx_create_char
Func?ii Informix


Creates an char object

ifx_create_blob
ifx_do
Func?ii Informix
PHP Manual

ifx_create_char

(PHP 4, PHP <=5.2.0)

ifx_create_char — Creates an char object

Descrierea

int ifx_create_char ( string $param )

Creates an char object.

Parametri

param

The char content.

Valorile întoarse

Returns the new char object id, or FALSE on errors.

A se vedea ?i

  • ifx_free_char() - Deletes the char object

ifx_create_blob
ifx_do
Func?ii Informix


Execute a previously prepared SQL-statement

ifx_create_char
ifx_error
Func?ii Informix
PHP Manual

ifx_do

(PHP 4, PHP <=5.2.0)

ifx_do — Execute a previously prepared SQL-statement

Descrierea

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().

Parametri

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

Example #1 ifx_do() Example

<?php
$conn = fx_connect( "db", "user", "password" );
$result = ifx_prepare("SELECT customer_num, company FROM customer", $conn);
ifx_do($result);
?>

A se vedea ?i

  • ifx_prepare() - Prepare an SQL-statement for execution

ifx_create_char
ifx_error
Func?ii Informix


Returns error code of last Informix call

ifx_do
ifx_errormsg
Func?ii Informix
PHP Manual

ifx_error

(PHP 4, PHP <=5.2.0)

ifx_error — Returns error code of last Informix call

Descrierea

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.

Parametri

link_identifier

The link identifier.

Valorile întoarse

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

A se vedea ?i

  • ifx_errormsg() - Returns error message of last Informix call

ifx_do
ifx_errormsg
Func?ii Informix


Returns error message of last Informix call

ifx_error
ifx_fetch_row
Func?ii Informix
PHP Manual

ifx_errormsg

(PHP 4, PHP <=5.2.0)

ifx_errormsg — Returns error message of last Informix call

Descrierea

string ifx_errormsg ([ int $errorcode ] )

Returns the Informix error message associated with the most recent Informix error.

Parametri

errorcode

If specified, the function will return the message corresponding to the specified code.

Valorile întoarse

Return the error message, as a string.

Exemple

Example #1 ifx_errormsg() example

<?php
printf("%s\n<br>", ifx_errormsg(-201));
?>

A se vedea ?i

  • ifx_error() - Returns error code of last Informix call

ifx_error
ifx_fetch_row
Func?ii Informix


Get row as an associative array

ifx_errormsg
ifx_fieldproperties
Func?ii Informix
PHP Manual

ifx_fetch_row

(PHP 4, PHP <=5.2.0)

ifx_fetch_row — Get row as an associative array

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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
Func?ii Informix


List of SQL fieldproperties

ifx_fetch_row
ifx_fieldtypes
Func?ii Informix
PHP Manual

ifx_fieldproperties

(PHP 4, PHP <=5.2.0)

ifx_fieldproperties — List of SQL fieldproperties

Descrierea

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".

Parametri

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Valorile întoarse

Returns an associative array with fieldnames as key and the SQL fieldproperties as data for a query with result_id. Returns FALSE on errors.

Exemple

Example #1 Informix SQL fieldproperties

<?php
$properties = ifx_fieldproperties($resultid);
if (!isset($properties)) {
    /* ... error ... */
}
foreach ($properties as $fname => $val) {
    echo "$fname:\t property = $val\n";
}
?>

A se vedea ?i

  • ifx_fieldtypes() - List of Informix SQL fields

ifx_fetch_row
ifx_fieldtypes
Func?ii Informix


List of Informix SQL fields

ifx_fieldproperties
ifx_free_blob
Func?ii Informix
PHP Manual

ifx_fieldtypes

(PHP 4, PHP <=5.2.0)

ifx_fieldtypes — List of Informix SQL fields

Descrierea

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.

Parametri

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Valorile întoarse

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.

Exemple

Example #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";
    }
}
?>

A se vedea ?i

  • ifx_fieldproperties() - List of SQL fieldproperties

ifx_fieldproperties
ifx_free_blob
Func?ii Informix


Deletes the blob object

ifx_fieldtypes
ifx_free_char
Func?ii Informix
PHP Manual

ifx_free_blob

(PHP 4, PHP <=5.2.0)

ifx_free_blob — Deletes the blob object

Descrierea

bool ifx_free_blob ( int $bid )

Deletes the blobobject for the given blob object-id.

Parametri

bid

The BLOB object id.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ifx_create_blob() - Creates an blob object

ifx_fieldtypes
ifx_free_char
Func?ii Informix


Deletes the char object

ifx_free_blob
ifx_free_result
Func?ii Informix
PHP Manual

ifx_free_char

(PHP 4, PHP <=5.2.0)

ifx_free_char — Deletes the char object

Descrierea

bool ifx_free_char ( int $bid )

Deletes the charobject for the given char object-id.

Parametri

bid

The char object id.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ifx_create_char() - Creates an char object

ifx_free_blob
ifx_free_result
Func?ii Informix


Releases resources for the query

ifx_free_char
ifx_get_blob
Func?ii Informix
PHP Manual

ifx_free_result

(PHP 4, PHP <=5.2.0)

ifx_free_result — Releases resources for the query

Descrierea

bool ifx_free_result ( resource $result_id )

Releases resources for the query associated with result_id.

Parametri

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ifx_do() - Execute a previously prepared SQL-statement

ifx_free_char
ifx_get_blob
Func?ii Informix


Return the content of a blob object

ifx_free_result
ifx_get_char
Func?ii Informix
PHP Manual

ifx_get_blob

(PHP 4, PHP <=5.2.0)

ifx_get_blob — Return the content of a blob object

Descrierea

string ifx_get_blob ( int $bid )

Returns the content of the blob object.

Parametri

bid

The BLOB object id.

Valorile întoarse

The contents of the BLOB as a string, or FALSE on errors.

A se vedea ?i

  • ifx_get_char() - Return the content of the char object

ifx_free_result
ifx_get_char
Func?ii Informix


Return the content of the char object

ifx_get_blob
ifx_getsqlca
Func?ii Informix
PHP Manual

ifx_get_char

(PHP 4, PHP <=5.2.0)

ifx_get_char — Return the content of the char object

Descrierea

string ifx_get_char ( int $bid )

Returns the content of the char object.

Parametri

bid

The char object-id.

Valorile întoarse

Returns the contents as a string, or FALSE on errors.

A se vedea ?i

  • ifx_get_blob() - Return the content of a blob object

ifx_get_blob
ifx_getsqlca
Func?ii Informix


Get the contents of sqlca.sqlerrd[0..5] after a query

ifx_get_char
ifx_htmltbl_result
Func?ii Informix
PHP Manual

ifx_getsqlca

(PHP 4, PHP <=5.2.0)

ifx_getsqlca — Get the contents of sqlca.sqlerrd[0..5] after a query

Descrierea

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.

Parametri

result_id

result_id is a valid result id returned by ifx_query() or ifx_prepare() (select type queries only!).

Valorile întoarse

Returns an associative array with the following entries: sqlerrd0, sqlerrd1, sqlerrd2, sqlerrd3, sqlerrd4 and sqlerrd5.

Exemple

Example #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
Func?ii Informix


Formats all rows of a query into a HTML table

ifx_getsqlca
ifx_nullformat
Func?ii Informix
PHP Manual

ifx_htmltbl_result

(PHP 4, PHP <=5.2.0)

ifx_htmltbl_result — Formats all rows of a query into a HTML table

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the number of fetched rows, or FALSE on errors.

Exemple

Example #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
Func?ii Informix


Sets the default return value on a fetch row

ifx_htmltbl_result
ifx_num_fields
Func?ii Informix
PHP Manual

ifx_nullformat

(PHP 4, PHP <=5.2.0)

ifx_nullformat — Sets the default return value on a fetch row

Descrierea

bool ifx_nullformat ( int $mode )

Sets the default return value of a NULL-value on a fetch row.

Parametri

mode

Mode "0" returns "", and mode "1" returns "NULL".

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ifx_htmltbl_result
ifx_num_fields
Func?ii Informix


Returns the number of columns in the query

ifx_nullformat
ifx_num_rows
Func?ii Informix
PHP Manual

ifx_num_fields

(PHP 4, PHP <=5.2.0)

ifx_num_fields — Returns the number of columns in the query

Descrierea

int ifx_num_fields ( resource $result_id )

After preparing or executing a query, this call gives you the number of columns in the query.

Parametri

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Valorile întoarse

Returns the number of columns in query for result_id, or FALSE on errors.

Exemple

Example #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);
?>

A se vedea ?i

  • ifx_num_rows() - Count the rows already fetched from a query

ifx_nullformat
ifx_num_rows
Func?ii Informix


Count the rows already fetched from a query

ifx_num_fields
ifx_pconnect
Func?ii Informix
PHP Manual

ifx_num_rows

(PHP 4, PHP <=5.2.0)

ifx_num_rows — Count the rows already fetched from a query

Descrierea

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.

Parametri

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Valorile întoarse

Returns the number of fetched rows or FALSE on errors.

A se vedea ?i

  • ifx_num_fields() - Returns the number of columns in the query

ifx_num_fields
ifx_pconnect
Func?ii Informix


Open persistent Informix connection

ifx_num_rows
ifx_prepare
Func?ii Informix
PHP Manual

ifx_pconnect

(PHP 4, PHP <=5.2.0)

ifx_pconnect — Open persistent Informix connection

Descrierea

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'.

Parametri

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.

Valorile întoarse

Returns: valid Informix persistent link identifier on success, or FALSE on errors.

A se vedea ?i

  • ifx_connect() - Open Informix server connection

ifx_num_rows
ifx_prepare
Func?ii Informix


Prepare an SQL-statement for execution

ifx_pconnect
ifx_query
Func?ii Informix
PHP Manual

ifx_prepare

(PHP 4, PHP <=5.2.0)

ifx_prepare — Prepare an SQL-statement for execution

Descrierea

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).

Parametri

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.

Valorile întoarse

Returns a valid result identifier for use by ifx_do(), or FALSE on errors.

A se vedea ?i

  • ifx_do() - Execute a previously prepared SQL-statement

ifx_pconnect
ifx_query
Func?ii Informix


Send Informix query

ifx_prepare
ifx_textasvarchar
Func?ii Informix
PHP Manual

ifx_query

(PHP 4, PHP <=5.2.0)

ifx_query — Send Informix query

Descrierea

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).

Parametri

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.

Valorile întoarse

Returns valid Informix result identifier on success, or FALSE on errors.

Exemple

Example #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);
?>

Example #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);
?>

A se vedea ?i

  • ifx_connect() - Open Informix server connection

ifx_prepare
ifx_textasvarchar
Func?ii Informix


Set the default text mode

ifx_query
ifx_update_blob
Func?ii Informix
PHP Manual

ifx_textasvarchar

(PHP 4, PHP <=5.2.0)

ifx_textasvarchar — Set the default text mode

Descrierea

bool ifx_textasvarchar ( int $mode )

Sets the default text mode for all select-queries.

Parametri

mode

Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ifx_byteasvarchar() - Set the default byte mode

ifx_query
ifx_update_blob
Func?ii Informix


Updates the content of the blob object

ifx_textasvarchar
ifx_update_char
Func?ii Informix
PHP Manual

ifx_update_blob

(PHP 4, PHP <=5.2.0)

ifx_update_blob — Updates the content of the blob object

Descrierea

bool ifx_update_blob ( int $bid , string $content )

Updates the content of the blob object for the given blob object bid.

Parametri

bid

A BLOB object identifier.

content

The new data, as a string.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ifx_update_char() - Updates the content of the char object

ifx_textasvarchar
ifx_update_char
Func?ii Informix


Updates the content of the char object

ifx_update_blob
ifxus_close_slob
Func?ii Informix
PHP Manual

ifx_update_char

(PHP 4, PHP <=5.2.0)

ifx_update_char — Updates the content of the char object

Descrierea

bool ifx_update_char ( int $bid , string $content )

Updates the content of the char object for the given char object bid.

Parametri

bid

A char object identifier.

content

The new data, as a string.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ifx_update_blob() - Updates the content of the blob object

ifx_update_blob
ifxus_close_slob
Func?ii Informix


Deletes the slob object

ifx_update_char
ifxus_create_slob
Func?ii Informix
PHP Manual

ifxus_close_slob

(PHP 4, PHP <=5.2.0)

ifxus_close_slob — Deletes the slob object

Descrierea

bool ifxus_close_slob ( int $bid )

Deletes the slob object on the given slob object-id bid.

Parametri

bid

An existing slob id.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ifxus_open_slob() - Opens an slob object

ifx_update_char
ifxus_create_slob
Func?ii Informix


Creates an slob object and opens it

ifxus_close_slob
ifxus_free_slob
Func?ii Informix
PHP Manual

ifxus_create_slob

(PHP 4, PHP <=5.2.0)

ifxus_create_slob — Creates an slob object and opens it

Descrierea

int ifxus_create_slob ( int $mode )

Creates an slob object and opens it.

Parametri

mode

A combination of IFX_LO_RDONLY, IFX_LO_WRONLY, IFX_LO_APPEND IFX_LO_RDWR, IFX_LO_BUFFER, IFX_LO_NOBUFFER.

Valorile întoarse

Return the new slob object-id, or FALSE on errors.

A se vedea ?i

  • ifxus_close_slob() - Deletes the slob object
  • ifxus_free_slob() - Deletes the slob object

ifxus_close_slob
ifxus_free_slob
Func?ii Informix


Deletes the slob object

ifxus_create_slob
ifxus_open_slob
Func?ii Informix
PHP Manual

ifxus_free_slob

(PHP 4, PHP <=5.2.0)

ifxus_free_slob — Deletes the slob object

Descrierea

bool ifxus_free_slob ( int $bid )

Deletes the slob object.

Parametri

bid

An existing slob id.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ifxus_close_slob() - Deletes the slob object

ifxus_create_slob
ifxus_open_slob
Func?ii Informix


Opens an slob object

ifxus_free_slob
ifxus_read_slob
Func?ii Informix
PHP Manual

ifxus_open_slob

(PHP 4, PHP <=5.2.0)

ifxus_open_slob — Opens an slob object

Descrierea

int ifxus_open_slob ( int $bid , int $mode )

Opens an slob object. bid should be an existing slob id.

Parametri

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.

Valorile întoarse

Returns the new slob object-id, or FALSE on errors.

A se vedea ?i

  • ifxus_close_slob() - Deletes the slob object
  • ifxus_free_slob() - Deletes the slob object

ifxus_free_slob
ifxus_read_slob
Func?ii Informix


Reads nbytes of the slob object

ifxus_open_slob
ifxus_seek_slob
Func?ii Informix
PHP Manual

ifxus_read_slob

(PHP 4, PHP <=5.2.0)

ifxus_read_slob — Reads nbytes of the slob object

Descrierea

string ifxus_read_slob ( int $bid , int $nbytes )

Reads nbytes of the slob object.

Parametri

bid

An existing slob id.

nbytes

The number of bytes to read.

Valorile întoarse

Returns the slob contents as a string, or FALSE on errors.

A se vedea ?i

  • ifxus_write_slob() - Writes a string into the slob object

ifxus_open_slob
ifxus_seek_slob
Func?ii Informix


Sets the current file or seek position

ifxus_read_slob
ifxus_tell_slob
Func?ii Informix
PHP Manual

ifxus_seek_slob

(PHP 4, PHP <=5.2.0)

ifxus_seek_slob — Sets the current file or seek position

Descrierea

int ifxus_seek_slob ( int $bid , int $mode , int $offset )

Sets the current file or seek position of an open slob object.

Parametri

bid

An existing slob id.

mode

0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END.

offset

A byte offset.

Valorile întoarse

Returns the seek position as an integer, or FALSE on errors.

A se vedea ?i

  • ifxus_tell_slob() - Returns the current file or seek position

ifxus_read_slob
ifxus_tell_slob
Func?ii Informix


Returns the current file or seek position

ifxus_seek_slob
ifxus_write_slob
Func?ii Informix
PHP Manual

ifxus_tell_slob

(PHP 4, PHP <=5.2.0)

ifxus_tell_slob — Returns the current file or seek position

Descrierea

int ifxus_tell_slob ( int $bid )

Returns the current file or seek position of an open slob object

Parametri

bid

An existing slob id.

Valorile întoarse

Returns the seek position as an integer, or FALSE on errors.

A se vedea ?i

  • ifxus_seek_slob() - Sets the current file or seek position

ifxus_seek_slob
ifxus_write_slob
Func?ii Informix


Writes a string into the slob object

ifxus_tell_slob
Ingres
Func?ii Informix
PHP Manual

ifxus_write_slob

(PHP 4, PHP <=5.2.0)

ifxus_write_slob — Writes a string into the slob object

Descrierea

int ifxus_write_slob ( int $bid , string $content )

Writes a string into the slob object.

Parametri

bid

An existing slob id.

content

The content to write, as a string.

Valorile întoarse

Returns the bytes written as an integer, or FALSE on errors.

A se vedea ?i

  • ifxus_read_slob() - Reads nbytes of the slob object

ifxus_tell_slob
Ingres
Func?ii Informix


Ingres DBMS, EDBC, and Enterprise Access Gateways

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic usage
  • Func?ii Ingres
    • ingres_autocommit_state — Test if the connection is using autocommit
    • ingres_autocommit — Switch autocommit on or off
    • ingres_charset — Returns the installation character set
    • ingres_close — Close an Ingres database connection
    • ingres_commit — Commit a transaction
    • ingres_connect — Open a connection to an Ingres database
    • ingres_cursor — Get a cursor name for a given result resource
    • ingres_errno — Get the last Ingres error number generated
    • ingres_error — Get a meaningful error message for the last error generated
    • ingres_errsqlstate — Get the last SQLSTATE error code generated
    • 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 — Get the name of a field in a query result
    • ingres_field_nullable — Test if a field is nullable
    • 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 — Get the number of fields returned by the last query
    • 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 — Roll back a transaction
    • ingres_set_environment — Set environment features controlling output options
    • ingres_unbuffered_query — Send an unbuffered SQL query to Ingres
ifxus_write_slob
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

The Ingres driver for PHP enables you to connect to and query the Ingres DBMS, EDBC, and Enterprise Access Gateways.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.1.0.

Ingres
Instalarea / configurarea
Ingres


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Ingres


Necesita?i

To use or build the PHP extension for Ingres you must have a working Ingres client environment. You can download the client software for Ingres from » http://esd.ingres.com/.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP. Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/ingres.

You can download the DLL for this PECL extension from » http://esd.ingres.com/product/drivers/PHP/.

To have these functions available, you must » download and compile this extension, enabling Ingres support using the --with-ingres[=DIR] option, where DIR is the Ingres base directory. If the II_SYSTEM environment variable is not set correctly you may need to use --with-ingres=DIR to specify your Ingres installation directory.

PHP code written for version 2.x and later is not backward-compatible with earlier versions of this PHP extension. However, it is possible to run two incompatible releases within the same PHP environment using the --enable-ingres2 option. This configuration option renames the extension to ingres2, changing function names, configuration settings, and constants. For example, with this option enabled, ingres_connect() becomes ingres2_connect().

To use this extension the system environment variable II_SYSTEM must be defined. Linux and UNIX users will also need to define the shared library search path, for example, LD_LIBRARY_PATH. When used with the Apache web server these variables must be set explicitly in the startup script for Apache. In addition, the PassEnv directive is required for the Ingres extension to load the correct shared libraries. For example:

Example #1 Example usage of PassEnv for Ingres

<IfModule mod_env.c>
    PassEnv II_SYSTEM
    PassEnv LD_LIBRARY_PATH
</IfModule>

Nota:

For example configurations for different web servers and operating systems see » http://community.ingres.com/wiki/Ingres_Articles#Ingres_and_Web_Servers.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Ingres configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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 modul SQL securizat.

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 modul SQL securizat.

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 modul SQL securizat.

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().

Nota:

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

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

ingres_connect() and ingres_pconnect() return an Ingres link identifier.

ingres_query() and ingres_unbuffered_query() return an Ingres result identifier.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

INGRES_ASSOC (integer)
Columns are returned into the array having the fieldname as the array index. Used with ingres_fetch_array().
INGRES_NUM (integer)
Columns are returned into the array having a numerical index to the fields. By default this index starts at 1, the first field in the result. To change this value, see ingres.array_index_start. Used with ingres_fetch_array().
INGRES_BOTH (integer)
Columns are returned into the array having both a numerical index and the fieldname as the array index. Used with ingres_fetch_array().
INGRES_EXT_VERSION (string)
Specifies the version of the Ingres Extension. Available since version 1.2.0 of the PECL extension.
INGRES_API_VERSION (integer)
Specifies the version of Ingres OpenAPI that the extension was built against. Available since version 1.2.0 of the PECL extension.
INGRES_CURSOR_READONLY (integer)
Specifies that Ingres cursors should be opened in "readonly" mode. Available since version 1.2.0 of the PECL extension. Used with ingres.cursor_mode.
INGRES_CURSOR_UPDATE (integer)
Specifies that Ingres cursors should be opened "for update." Available since version 1.2.0 of the PECL extension. Used with ingres.cursor_mode.
INGRES_DATE_MULTINATIONAL (integer)
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL. Available since version 1.2.0 of the PECL extension. Used with ingres_connect(), ingres_pconnect() and ingres_set_environment(). See options in ingres_set_environment().
INGRES_DATE_MULTINATIONAL4 (integer)
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL4. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_FINNISH (integer)
Equivalent to the II_DATE_FORMAT setting of FINNISH. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_ISO (integer)
Equivalent to the II_DATE_FORMAT setting of ISO. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_ISO4 (integer)
Equivalent to the II_DATE_FORMAT setting of ISO4. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_GERMAN (integer)
Equivalent to the II_DATE_FORMAT setting of GERMAN. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_MDY (integer)
Equivalent to the II_DATE_FORMAT setting of MDY. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_DMY (integer)
Equivalent to the II_DATE_FORMAT setting of DMY. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_YMD (integer)
Equivalent to the II_DATE_FORMAT setting of YMD. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_MONEY_LEADING (integer)
Specifies the currency character that should be placed at the start of a money value. Equivalent to setting II_MONEY_FORMAT to "L:". Available since version 1.2.0 of the PECL extension. Used with ingres_connect(), ingres_pconnect() and ingres_set_environment(). See options in ingres_set_environment().
INGRES_MONEY_TRAILING (integer)
Specifies the currency character that should be placed at the end of a money value. Equivalent to setting II_MONEY_FORMAT to "T:". Available since version 1.2.0 of the PECL extension. Used with ingres_connect(), ingres_pconnect() and ingres_set_environment(). See options in ingres_set_environment().
INGRES_STRUCTURE_BTREE (integer)
Specifies the default table or index structure to BTREE when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CBTREE (integer)
Specifies the default table or index structure to COMPRESSED BTREE when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_HASH (integer)
Specifies the default table or index structure to HASH when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CHASH (integer)
Specifies the default table or index structure to COMPRESSED HASH when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_HEAP (integer)
Specifies the default table structure to HEAP when used in combination with the
options option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CHEAP (integer)
Specifies the default table structure to COMPRESSED HEAP when used in combination with the
options option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_ISAM (integer)
Specifies the default table or index structure to ISAM when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CISAM (integer)
Specifies the default table or index structure to COMPRESSED ISAM when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
Tipurile resurselor
Exemple
Ingres


Exemple

Cuprins

  • Basic usage
Constante predefinite
Basic usage
Ingres


Basic usage

The following simple example shows how to connect to an Ingres database, execute a query, print resulting rows and disconnect from the database.

Example #1 Simple Ingres Example

<?php
// Connecting, selecting database
$link = ingres_connect("database", "user", "password")
    or die("Could not connect: " . ingres_error($link));
echo "Connected successfully";

// Select from a table that exists in all Ingres databases
$query = "SELECT * FROM iitables";
$result = ingres_query($link,$query) or die("Query failed: " .
ingres_error($link));

// Print results in HTML
// relid - table name
// relowner - table owner
echo "<table>\n";
while ($iitables = ingres_fetch_object($result)) {
    echo "\t<tr>\n";
    echo "\t\t<td>" . $iitables->relid . "</td>\n";
    echo "\t\t<td>" . $iitables->relowner . "</td>\n";
    echo "\t</tr>\n";
}
echo "</table>\n";

// Free results
ingres_free_result($result);

// Commit transaction
ingres_commit($link);

// Closing connection
ingres_close($link);
?>

Exemple
Func?ii Ingres
Exemple


Func?ii Ingres

Cuprins

  • ingres_autocommit_state — Test if the connection is using autocommit
  • ingres_autocommit — Switch autocommit on or off
  • ingres_charset — Returns the installation character set
  • ingres_close — Close an Ingres database connection
  • ingres_commit — Commit a transaction
  • ingres_connect — Open a connection to an Ingres database
  • ingres_cursor — Get a cursor name for a given result resource
  • ingres_errno — Get the last Ingres error number generated
  • ingres_error — Get a meaningful error message for the last error generated
  • ingres_errsqlstate — Get the last SQLSTATE error code generated
  • 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 — Get the name of a field in a query result
  • ingres_field_nullable — Test if a field is nullable
  • 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 — Get the number of fields returned by the last query
  • 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 — Roll back a transaction
  • ingres_set_environment — Set environment features controlling output options
  • ingres_unbuffered_query — Send an unbuffered SQL query to Ingres
Basic usage
ingres_autocommit_state
Ingres


Test if the connection is using autocommit

Func?ii Ingres
ingres_autocommit
Func?ii Ingres
PHP Manual

ingres_autocommit_state

(PECL ingres >= 2.0.0)

ingres_autocommit_state — Test if the connection is using autocommit

Descrierea

bool ingres_autocommit_state ( resource $link )

ingres_autocommit_state() is called to determine whether the current link has autocommit enabled or not.

Parametri

link

The connection link identifier

Valorile întoarse

Returns TRUE if autocommit is enabled or FALSE when autocommit is disabled

A se vedea ?i

  • ingres_autocommit() - Switch autocommit on or off
  • ingres_query() - Send an SQL query to Ingres

Func?ii Ingres
ingres_autocommit
Func?ii Ingres


Switch autocommit on or off

ingres_autocommit_state
ingres_charset
Func?ii Ingres
PHP Manual

ingres_autocommit

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_autocommit — Switch autocommit on or off

Descrierea

bool ingres_autocommit ( resource $link )

ingres_autocommit() is called before opening a transaction (before the first call to ingres_query() or just after a call to ingres_rollback() or ingres_commit()) to switch the autocommit mode of the server on or off (when the script begins the autocommit mode is off).

When autocommit mode is on, every query is automatically committed by the server, as if ingres_commit() was called after every call to ingres_query(). To see if autocommit is enabled use, ingres_autocommit_state().

By default Ingres will rollback any uncommitted transactions at the end of a request. Use this function or ingres_commit() to ensure your data is committed to the database.

Parametri

link

The connection link identifier

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ingres_autocommit_state() - Test if the connection is using autocommit
  • ingres_query() - Send an SQL query to Ingres
  • ingres_rollback() - Roll back a transaction
  • ingres_commit() - Commit a transaction

ingres_autocommit_state
ingres_charset
Func?ii Ingres


Returns the installation character set

ingres_autocommit
ingres_close
Func?ii Ingres
PHP Manual

ingres_charset

(PECL ingres >= 2.1.0)

ingres_charset — Returns the installation character set

Descrierea

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).

Nota:

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.

Parametri

link

The connection link identifier

Valorile întoarse

Returns a string with the value for II_CHARSETxx or returns NULL if the value could not be determined.

Exemple

Example #1 ingres_charset() - Get the installation character set

<?php
$link = ingres_connect($database, $user, $password);

echo ingres_charset($link) . "\n";

ingres_close($link);
?>

A se vedea ?i

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_query() - Send an SQL query to Ingres

ingres_autocommit
ingres_close
Func?ii Ingres


Close an Ingres database connection

ingres_charset
ingres_commit
Func?ii Ingres
PHP Manual

ingres_close

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_close — Close an Ingres database connection

Descrierea

bool ingres_close ( resource $link )

ingres_close() closes the connection to the Ingres server that is associated with the specified link.

ingres_close() is usually unnecessary, as it will not close persistent connections and all non-persistent connections are automatically closed at the end of the script.

Parametri

link

The connection link identifier

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_pconnect() - Open a persistent connection to an Ingres database

ingres_charset
ingres_commit
Func?ii Ingres


Commit a transaction

ingres_close
ingres_connect
Func?ii Ingres
PHP Manual

ingres_commit

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_commit — Commit a transaction

Descrierea

bool ingres_commit ( resource $link )

ingres_commit() commits the currently open transaction, making all changes made to the database permanent.

This closes the transaction. A new transaction can be opened by sending a query with ingres_query().

You can also have the server commit automatically after every query by calling ingres_autocommit() before opening the transaction.

By default Ingres will roll back any uncommitted transactions at the end of a request. Use this function or ingres_autocommit() to ensure your that data is committed to the database.

Parametri

link

The connection link identifier

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ingres_query() - Send an SQL query to Ingres
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off

ingres_close
ingres_connect
Func?ii Ingres


Open a connection to an Ingres database

ingres_commit
ingres_cursor
Func?ii 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

Descrierea

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.

Parametri

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

Valorile întoarse

Returns a Ingres link resource on success sau FALSE în cazul e?ecului

Exemple

Example #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);
?>

A se vedea ?i

  • ingres_pconnect() - Open a persistent connection to an Ingres database
  • ingres_close() - Close an Ingres database connection

ingres_commit
ingres_cursor
Func?ii Ingres


Get a cursor name for a given result resource

ingres_connect
ingres_errno
Func?ii Ingres
PHP Manual

ingres_cursor

(PECL ingres >= 1.1.0)

ingres_cursor — Get a cursor name for a given result resource

Descrierea

string ingres_cursor ( resource $result )

Returns a string with the active cursor name. If no cursor is active then NULL is returned.

Parametri

result

The query result identifier

Valorile întoarse

Returns a string containing the active cursor name. If no cursor is active then NULL is returned.

Exemple

Example #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;

?>

A se vedea ?i

  • ingres_prepare() - Prepare a query for later execution
  • ingres_execute() - Execute a prepared query

ingres_connect
ingres_errno
Func?ii Ingres


Get the last Ingres error number generated

ingres_cursor
ingres_error
Func?ii Ingres
PHP Manual

ingres_errno

(PECL ingres >= 1.1.0)

ingres_errno — Get the last Ingres error number generated

Descrierea

int ingres_errno ([ resource $link ] )

Returns an integer containing the last error number. If no error was reported 0 is returned.

If a link resource is passed to ingres_errno() it returns the last error recorded for the link. If no link is passed, then ingres_errno() returns the last error reported using the default link.

The function, ingres_errno(), should always be called after executing a database query. Calling another function before ingres_errno() is called will reset or change any error code from the last Ingres function call.

Parametri

link

The connection link identifier

Valorile întoarse

Returns an integer containing the last error number. If no error was reported, 0 is returned.

Exemple

Example #1 Get the last Ingres error number generated

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

$error_code = ingres_errno($link);

if ( $error_code != 0 ) {
   echo "An error occurred - " . $error_code;
}
?>

A se vedea ?i

  • ingres_error() - Get a meaningful error message for the last error generated
  • ingres_errsqlstate() - Get the last SQLSTATE error code generated
  • ingres_next_error() - Get the next Ingres error

ingres_cursor
ingres_error
Func?ii Ingres


Get a meaningful error message for the last error generated

ingres_errno
ingres_errsqlstate
Func?ii Ingres
PHP Manual

ingres_error

(PECL ingres >= 1.1.0)

ingres_error — Get a meaningful error message for the last error generated

Descrierea

string ingres_error ([ resource $link ] )

Returns a string containing the last error, or NULL if no error has occurred.

If a link resource is passed to ingres_error(), it returns the last error recorded for the link. If no link is passed then ingres_error() returns the last error reported using the default link.

The function, ingres_error(), should always be called after executing any database query. Calling another function before ingres_error() is called will reset or change any error message from the last Ingres function call.

Parametri

link

The connection link identifier

Valorile întoarse

Returns a string containing the last error, or NULL if no error has occurred.

Exemple

Example #1 Get a message for the last error generated

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

$error_text = ingres_error();

if (!is_null($error_text)) {
   echo "An error occurred - " . $error_text;
}
?>

A se vedea ?i

  • ingres_errno() - Get the last Ingres error number generated
  • ingres_errsqlstate() - Get the last SQLSTATE error code generated
  • ingres_next_error() - Get the next Ingres error

ingres_errno
ingres_errsqlstate
Func?ii Ingres


Get the last SQLSTATE error code generated

ingres_error
ingres_escape_string
Func?ii Ingres
PHP Manual

ingres_errsqlstate

(PECL ingres >= 1.1.0)

ingres_errsqlstate — Get the last SQLSTATE error code generated

Descrierea

string ingres_errsqlstate ([ resource $link ] )

Returns a string containing the last SQLSTATE, or NULL if no error has occurred.

If a link resource is passed to ingres_errsqlstate(), it returns the last error recorded for the link. If no link is passed, then ingres_errsqlstate() returns the last error reported using the default link.

The function, ingres_errsqlstate(), should always be called after executing any database query. Calling another function before ingres_errsqlstate() is called will reset or change any error message from the last Ingres function call.

Parametri

link

The connection link identifier

Valorile întoarse

Returns a string containing the last SQLSTATE, or NULL if no error has occurred.

Exemple

Example #1 Get the last SQLSTATE error code generated

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

$error_sqlstate = ingres_errsqlstate($link);

if (!is_null($error_sqlstate)) {
   echo "An error occurred - " . $error_sqlstate;
}
?>

A se vedea ?i

  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated
  • ingres_next_error() - Get the next Ingres error

ingres_error
ingres_escape_string
Func?ii Ingres


Escape special characters for use in a query

ingres_errsqlstate
ingres_execute
Func?ii Ingres
PHP Manual

ingres_escape_string

(PECL ingres >= 2.1.0)

ingres_escape_string — Escape special characters for use in a query

Descrierea

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.

Parametri

link

The connection link identifier

source_string

The source string to be parsed

Valorile întoarse

Returns a string containing the escaped data.

Exemple

Example #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);

?>

A se vedea ?i

  • ingres_query() - Send an SQL query to Ingres

ingres_errsqlstate
ingres_execute
Func?ii Ingres


Execute a prepared query

ingres_escape_string
ingres_fetch_array
Func?ii Ingres
PHP Manual

ingres_execute

(PECL ingres >= 1.1.0)

ingres_execute — Execute a prepared query

Descrierea

bool ingres_execute ( resource $result [, array $params [, string $types ]] )

Execute a query prepared using ingres_prepare().

Nota: Related Configurations

See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated

ingres_escape_string
ingres_fetch_array
Func?ii Ingres


Fetch a row of result into an array

ingres_execute
ingres_fetch_assoc
Func?ii 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

Descrierea

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.

Nota: Related Configurations

See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parametri

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).

Valorile întoarse

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows

Exemple

Example #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];
}
?>

A se vedea ?i

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_field_name() - Get the name of a field in a query result
  • 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
Func?ii Ingres


Fetch a row of result into an associative array

ingres_fetch_array
ingres_fetch_object
Func?ii Ingres
PHP Manual

ingres_fetch_assoc

(PECL ingres >= 2.2.2)

ingres_fetch_assoc — Fetch a row of result into an associative array

Descrierea

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.

Nota: Related Configurations

See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parametri

result

The query result identifier

Valorile întoarse

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows

Exemple

Example #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"];
}
?>

A se vedea ?i

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_field_name() - Get the name of a field in a query result
  • 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
Func?ii Ingres


Fetch a row of result into an object

ingres_fetch_assoc
ingres_fetch_proc_return
Func?ii 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

Descrierea

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).

Nota: Related Configurations

See also the ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parametri

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.

Valorile întoarse

Returns an object that corresponds to the fetched row, or FALSE if there are no more rows

Exemple

Example #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;
}
?>

A se vedea ?i

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_field_name() - Get the name of a field in a query result
  • 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
Func?ii Ingres


Get the return value from a procedure call

ingres_fetch_object
ingres_fetch_row
Func?ii Ingres
PHP Manual

ingres_fetch_proc_return

(PECL ingres >= 1.4.0)

ingres_fetch_proc_return — Get the return value from a procedure call

Descrierea

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).

Nota:

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.

Parametri

result

The result identifier for a query

Valorile întoarse

Returns an integer if there is a return value otherwise it will return NULL.

Exemple

Example #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);

?>

A se vedea ?i

  • 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
Func?ii Ingres


Fetch a row of result into an enumerated array

ingres_fetch_proc_return
ingres_field_length
Func?ii 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

Descrierea

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.

Nota: Related Configurations

See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parametri

result

The query result identifier

Valorile întoarse

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows

Exemple

Example #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];
}
?>

A se vedea ?i

  • ingres_num_fields() - Get the number of fields returned by the last query
  • 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
Func?ii Ingres


Get the length of a field

ingres_fetch_row
ingres_field_name
Func?ii 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

Descrierea

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.

Nota: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parametri

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.

Valorile întoarse

Returns the length of a field.

A se vedea ?i

  • 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
Func?ii Ingres


Get the name of a field in a query result

ingres_field_length
ingres_field_nullable
Func?ii Ingres
PHP Manual

ingres_field_name

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_name — Get the name of a field in a query result

Descrierea

string ingres_field_name ( resource $result , int $index )

ingres_field_name() returns the name of a field in a query result.

Nota: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parametri

result

The query result identifier

index

index is the field whose name 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.

Valorile întoarse

Returns the name of a field in a query result sau FALSE în cazul e?ecului

A se vedea ?i

  • 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
Func?ii Ingres


Test if a field is nullable

ingres_field_name
ingres_field_precision
Func?ii Ingres
PHP Manual

ingres_field_nullable

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_nullable — Test if a field is nullable

Descrierea

bool ingres_field_nullable ( resource $result , int $index )

Test if a field is nullable.

Nota: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parametri

result

The query result identifier

index

index is the field whose nullability 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.

Valorile întoarse

ingres_field_nullable() returns TRUE if the field can be set to the NULL value and FALSE if it cannot

A se vedea ?i

  • 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
Func?ii Ingres


Get the precision of a field

ingres_field_nullable
ingres_field_scale
Func?ii 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

Descrierea

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.

Nota: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parametri

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.

Valorile întoarse

Returns the field precision as an integer

A se vedea ?i

  • 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
Func?ii Ingres


Get the scale of a field

ingres_field_precision
ingres_field_type
Func?ii 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

Descrierea

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.

Nota: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parametri

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.

Valorile întoarse

Returns the scale of the field, as an integer

A se vedea ?i

  • 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
Func?ii Ingres


Get the type of a field in a query result

ingres_field_scale
ingres_free_result
Func?ii 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

Descrierea

string ingres_field_type ( resource $result , int $index )

Get the type of a field in a query result.

Nota: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parametri

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.

Valorile întoarse

ingres_field_type() returns the type of a field in a query result sau FALSE în cazul e?ecului. 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.

A se vedea ?i

  • 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
Func?ii Ingres


Free the resources associated with a result identifier

ingres_field_type
ingres_next_error
Func?ii Ingres
PHP Manual

ingres_free_result

(PECL ingres >= 2.0.0)

ingres_free_result — Free the resources associated with a result identifier

Descrierea

bool ingres_free_result ( resource $result )

Parametri

result

The query result identifier

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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)

?>

A se vedea ?i

  • ingres_query() - Send an SQL query to Ingres

ingres_field_type
ingres_next_error
Func?ii Ingres


Get the next Ingres error

ingres_free_result
ingres_num_fields
Func?ii Ingres
PHP Manual

ingres_next_error

(PECL ingres >= 2.0.0)

ingres_next_error — Get the next Ingres error

Descrierea

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.

Parametri

link

The connection link identifier

Valorile întoarse

ingres_next_error() returns TRUE if there is another error to retrieve or FALSE when there are no more errors

A se vedea ?i

  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated
  • ingres_errsqlstate() - Get the last SQLSTATE error code generated

ingres_free_result
ingres_num_fields
Func?ii Ingres


Get the number of fields returned by the last query

ingres_next_error
ingres_num_rows
Func?ii Ingres
PHP Manual

ingres_num_fields

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_num_fields — Get the number of fields returned by the last query

Descrierea

int ingres_num_fields ( resource $result )

ingres_num_fields() returns the number of fields in the results returned by the Ingres server after a call to ingres_query().

Parametri

result

The query result identifier

Valorile întoarse

Returns the number of fields

A se vedea ?i

  • 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
Func?ii Ingres


Get the number of rows affected or returned by a query

ingres_num_fields
ingres_pconnect
Func?ii 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

Descrierea

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.

Nota:

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.

Parametri

result

The result identifier for a query

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii Ingres


Open a persistent connection to an Ingres database

ingres_num_rows
ingres_prepare
Func?ii 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

Descrierea

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".

Parametri

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

Valorile întoarse

Returns an Ingres link resource on success sau FALSE în cazul e?ecului

A se vedea ?i

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_close() - Close an Ingres database connection

ingres_num_rows
ingres_prepare
Func?ii Ingres


Prepare a query for later execution

ingres_pconnect
ingres_query
Func?ii Ingres
PHP Manual

ingres_prepare

(PECL ingres >= 1.1.0)

ingres_prepare — Prepare a query for later execution

Descrierea

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.

Nota: Related Configurations

See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration.

Parametri

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()

Valorile întoarse

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().

A se vedea ?i

  • 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() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated

ingres_pconnect
ingres_query
Func?ii Ingres


Send an SQL query to Ingres

ingres_prepare
ingres_result_seek
Func?ii 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

Descrierea

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.

Nota: Related Configurations

See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration

Parametri

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

Valorile întoarse

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().

Exemple

Example #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];
}
?>

Example #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];
}
?>

Example #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);
?>

A se vedea ?i

  • 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() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated

ingres_prepare
ingres_result_seek
Func?ii Ingres


Set the row position before fetching data

ingres_query
ingres_rollback
Func?ii Ingres
PHP Manual

ingres_result_seek

(PECL ingres >= 2.1.0)

ingres_result_seek — Set the row position before fetching data

Descrierea

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().

Nota: Related Configurations

See also the ingres.scrollable and ingres.array_index_start directives in Runtime Configuration.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

A se vedea ?i

  • 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
Func?ii Ingres


Roll back a transaction

ingres_result_seek
ingres_set_environment
Func?ii Ingres
PHP Manual

ingres_rollback

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_rollback — Roll back a transaction

Descrierea

bool ingres_rollback ( resource $link )

ingres_rollback() rolls back the currently open transaction, actually cancelling all changes made to the database during the transaction.

This closes the transaction. A new transaction can be opened by sending a query with ingres_query().

Parametri

link

The connection link identifier

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ingres_query() - Send an SQL query to Ingres
  • ingres_commit() - Commit a transaction
  • ingres_autocommit() - Switch autocommit on or off

ingres_result_seek
ingres_set_environment
Func?ii Ingres


Set environment features controlling output options

ingres_rollback
ingres_unbuffered_query
Func?ii Ingres
PHP Manual

ingres_set_environment

(PECL ingres >= 1.2.0)

ingres_set_environment — Set environment features controlling output options

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
    }
}
?>

Example #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";
    }
}
?>

A se vedea ?i

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_query() - Send an SQL query to Ingres

ingres_rollback
ingres_unbuffered_query
Func?ii Ingres


Send an unbuffered SQL query to Ingres

ingres_set_environment
MaxDB
Func?ii Ingres
PHP Manual

ingres_unbuffered_query

(No version information available, might only be in Git)

ingres_unbuffered_query — Send an unbuffered SQL query to Ingres

Descrierea

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.

Nota: Related Configurations

See also the ingres.describe and ingres.utf8 directives in Runtime Configuration.

Parametri

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.

Valorile întoarse

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().

Exemple

Example #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];
}
?>

Example #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];
}
?>

Example #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";
}
?>

A se vedea ?i

  • 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() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated

ingres_set_environment
MaxDB
Func?ii Ingres


MaxDB

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic usage
  • MaxDB Func?ii
    • 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 — Pseudonim pentru maxdb_stmt_bind_param
    • maxdb_bind_result — Pseudonim pentru 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 — Pseudonim pentru maxdb_character_set_name
    • maxdb_close_long_data — Pseudonim pentru 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 — Interzice citirea din stapân
    • maxdb_disable_rpl_parse — Deconecteaza interpretarea RPL
    • maxdb_dump_debug_info — Înscrie informa?ia de depanare în jurnal
    • maxdb_embedded_connect — Deschide o conexiune catre un server MaxDB încorporat
    • maxdb_enable_reads_from_master — Permite citirea din stapân
    • maxdb_enable_rpl_parse — Activeaza interpretarea RPL
    • 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 — Pseudonim pentru maxdb_real_escape_string
    • maxdb_execute — Pseudonim pentru 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 — Pseudonim pentru 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 — Pseudonim pentru 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 — Impune execu?ia unei interpelari catre stapân într-o configura?ie stapân/subordonat
    • 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 — Pseudonim pentru 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 — Verifica daca interpretarea RPL este activata
    • maxdb_rpl_probe — Sonda RPL
    • maxdb_rpl_query_type — Întoarce tipul interpelarii RPL
    • maxdb_select_db — Selects the default database for database queries
    • maxdb_send_long_data — Pseudonim pentru maxdb_stmt_send_long_data
    • maxdb_send_query — Transmite interpelarea ?i întoarce execu?ia
    • maxdb_server_end — Deconecteaza serverul încorporat
    • maxdb_server_init — Ini?ializeaza serverul încorporat
    • maxdb_set_opt — Pseudonim pentru 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 — Anuleaza o declara?ie pregatita anterior
    • 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 — Întoarce informa?ia despre faptul daca protec?ia firelor de execu?ie este activata sau nu
    • 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
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

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
Instalarea / configurarea
MaxDB


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
MaxDB


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Utilizând op?iunea de configurare --with-maxdb[=DIR] îi permite?i PHP sa acceseze baze de date MaxDB. [DIR] indica la directorul ce con?ine pachetul MaxDB SQLDBC instalat.

Utilizatorii Windows vor avea nevoie sa activeze php_maxdb.dll în php.ini.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

MaxDB Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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 |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

This extension defines resources.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.

Tipurile resurselor
Exemple
MaxDB


Exemple

Cuprins

  • Basic usage
Constante predefinite
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.

Example #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.

Example #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.

Example #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);
?>

Exemple
MaxDB Func?ii
Exemple


Basic usage
maxdb_affected_rows
MaxDB
PHP Manual

MaxDB Func?ii

Clase predefinite

maxdb

Represents a connection between PHP and a MaxDB database.

Constructorul

  • maxdb - construct a new maxdb object

Metode

  • 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

Proprieta?i

  • 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.

Metode

  • 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

Proprieta?i

  • 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.

Metode

  • 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

Proprieta?i

  • 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

Cuprins

  • 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 — Pseudonim pentru maxdb_stmt_bind_param
  • maxdb_bind_result — Pseudonim pentru 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 — Pseudonim pentru maxdb_character_set_name
  • maxdb_close_long_data — Pseudonim pentru 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 — Interzice citirea din stapân
  • maxdb_disable_rpl_parse — Deconecteaza interpretarea RPL
  • maxdb_dump_debug_info — Înscrie informa?ia de depanare în jurnal
  • maxdb_embedded_connect — Deschide o conexiune catre un server MaxDB încorporat
  • maxdb_enable_reads_from_master — Permite citirea din stapân
  • maxdb_enable_rpl_parse — Activeaza interpretarea RPL
  • 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 — Pseudonim pentru maxdb_real_escape_string
  • maxdb_execute — Pseudonim pentru 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 — Pseudonim pentru 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 — Pseudonim pentru 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 — Impune execu?ia unei interpelari catre stapân într-o configura?ie stapân/subordonat
  • 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 — Pseudonim pentru 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 — Verifica daca interpretarea RPL este activata
  • maxdb_rpl_probe — Sonda RPL
  • maxdb_rpl_query_type — Întoarce tipul interpelarii RPL
  • maxdb_select_db — Selects the default database for database queries
  • maxdb_send_long_data — Pseudonim pentru maxdb_stmt_send_long_data
  • maxdb_send_query — Transmite interpelarea ?i întoarce execu?ia
  • maxdb_server_end — Deconecteaza serverul încorporat
  • maxdb_server_init — Ini?ializeaza serverul încorporat
  • maxdb_set_opt — Pseudonim pentru 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 — Anuleaza o declara?ie pregatita anterior
  • 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 — Întoarce informa?ia despre faptul daca protec?ia firelor de execu?ie este activata sau nu
  • 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 Func?ii
maxdb_autocommit
MaxDB Func?ii
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

Descrierea

Stil procedural

int maxdb_affected_rows ( resource $link )

Stil obiect-orientat

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.

Nota:

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.

Valorile întoarse

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.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Affected rows (INSERT): 15
Affected rows (UPDATE): 15
Affected rows (DELETE): 0
Affected rows (SELECT): 15

A se vedea ?i

  • maxdb_num_rows() - Gets the number of rows in a result
  • maxdb_info() - Retrieves information about the most recently executed query

MaxDB Func?ii
maxdb_autocommit
MaxDB Func?ii


Turns on or off auto-commiting database modifications

maxdb_affected_rows
maxdb_bind_param
MaxDB Func?ii
PHP Manual

maxdb_autocommit

maxdb::auto_commit

(PECL maxdb >= 1.0)

maxdb_autocommit -- maxdb::auto_commit — Turns on or off auto-commiting database modifications

Descrierea

Stil procedural

bool maxdb_autocommit ( resource $link , bool $mode )

Stil obiect-orientat

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

A se vedea ?i

  • maxdb_commit() - Commits the current transaction
  • maxdb_rollback() - Rolls back current transaction

maxdb_affected_rows
maxdb_bind_param
MaxDB Func?ii


Pseudonim pentru maxdb_stmt_bind_param

maxdb_autocommit
maxdb_bind_result
MaxDB Func?ii
PHP Manual

maxdb_bind_param

(PECL maxdb 1.0)

maxdb_bind_param — Pseudonim pentru maxdb_stmt_bind_param()

Descrierea

Aceasta func?ie este pseudonim pentru: maxdb_stmt_bind_param()

Acest pseudonim al func?iei este învechit ?i exista numai din motivul pastrarii compatibilita?ii cu versiunile anterioare. Utilizarea acestei func?ii nu este recomandata, deoarece ea poate fi eliminata din PHP în viitor.

maxdb_autocommit
maxdb_bind_result
MaxDB Func?ii


Pseudonim pentru maxdb_stmt_bind_result

maxdb_bind_param
maxdb_change_user
MaxDB Func?ii
PHP Manual

maxdb_bind_result

(PECL maxdb 1.0)

maxdb_bind_result — Pseudonim pentru maxdb_stmt_bind_result()

Descrierea

Aceasta func?ie este pseudonim pentru: maxdb_stmt_bind_result().

Acest pseudonim al func?iei este învechit ?i exista numai din motivul pastrarii compatibilita?ii cu versiunile anterioare. Utilizarea acestei func?ii nu este recomandata, deoarece ea poate fi eliminata din PHP în viitor.

maxdb_bind_param
maxdb_change_user
MaxDB Func?ii


Changes the user of the specified database connection

maxdb_bind_result
maxdb_character_set_name
MaxDB Func?ii
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

Descrierea

Stil procedural

bool maxdb_change_user ( resource $link , string $user , string $password , string $database )

Stil obiect-orientat

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.

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Result: a
Database running

A se vedea ?i

  • 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 Func?ii


Returns the default character set for the database connection

maxdb_change_user
maxdb_client_encoding
MaxDB Func?ii
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

Descrierea

Stil procedural

string maxdb_character_set_name ( resource $link )

Stil obiect-orientat

string maxdb::character_set_name ( void )

Returns the current character set for the database connection specified by the link parameter.

Valorile întoarse

The default character set for the current connection, either ascii or unicode.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Current character set is ascii

A se vedea ?i

  • maxdb_client_encoding() - Pseudonim pentru 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 Func?ii


Pseudonim pentru maxdb_character_set_name

maxdb_character_set_name
maxdb_close_long_data
MaxDB Func?ii
PHP Manual

maxdb_client_encoding

(PECL maxdb 1.0)

maxdb_client_encoding — Pseudonim pentru maxdb_character_set_name()

Descrierea

Aceasta func?ie este pseudonim pentru: maxdb_character_set_name().

Acest pseudonim al func?iei este învechit ?i exista numai din motivul pastrarii compatibilita?ii cu versiunile anterioare. Utilizarea acestei func?ii nu este recomandata, deoarece ea poate fi eliminata din PHP în viitor.

maxdb_character_set_name
maxdb_close_long_data
MaxDB Func?ii


Pseudonim pentru maxdb_stmt_close_long_data

maxdb_client_encoding
maxdb_close
MaxDB Func?ii
PHP Manual

maxdb_close_long_data

maxdb::close_long_data

(PECL maxdb >= 1.0)

maxdb_close_long_data -- maxdb::close_long_data — Pseudonim pentru maxdb_stmt_close_long_data()

Descrierea

Aceasta func?ie este pseudonim pentru: maxdb_stmt_close_long_data().

Acest pseudonim al func?iei este învechit ?i exista numai din motivul pastrarii compatibilita?ii cu versiunile anterioare. Utilizarea acestei func?ii nu este recomandata, deoarece ea poate fi eliminata din PHP în viitor.

maxdb_client_encoding
maxdb_close
MaxDB Func?ii


Closes a previously opened database connection

maxdb_close_long_data
maxdb_commit
MaxDB Func?ii
PHP Manual

maxdb_close

maxdb::close

(PECL maxdb >= 1.0)

maxdb_close -- maxdb::close — Closes a previously opened database connection

Descrierea

Stil procedural

bool maxdb_close ( resource $link )

Stil obiect-orientat

bool maxdb::close ( void )

The maxdb_close() function closes a previously opened database connection specified by the link parameter.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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 Func?ii


Commits the current transaction

maxdb_close
maxdb_connect_errno
MaxDB Func?ii
PHP Manual

maxdb_commit

maxdb::commit

(PECL maxdb >= 1.0)

maxdb_commit -- maxdb::commit — Commits the current transaction

Descrierea

Stil procedural

bool maxdb_commit ( resource $link )

Stil obiect-orientat

bool maxdb::commit ( void )

Commits the current transaction for the database connection specified by the link parameter.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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.

A se vedea ?i

  • maxdb_autocommit() - Turns on or off auto-commiting database modifications
  • maxdb_rollback() - Rolls back current transaction

maxdb_close
maxdb_connect_errno
MaxDB Func?ii


Returns the error code from last connect call

maxdb_commit
maxdb_connect_error
MaxDB Func?ii
PHP Manual

maxdb_connect_errno

(PECL maxdb >= 1.0)

maxdb_connect_errno — Returns the error code from last connect call

Descrierea

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 occurred, this function will return zero.

Valorile întoarse

An error code value for the last call to maxdb_connect(), if it failed. zero means no error occurred.

Exemple

Example #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());
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

PHP Warning:  maxdb_connect(): -4008 POS(1) Unknown user name/password combination [08004] <...>
Can't connect to localhost. Errorcode: -4008

A se vedea ?i

  • 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 Func?ii


Returns a string description of the last connect error

maxdb_connect_errno
maxdb_connect
MaxDB Func?ii
PHP Manual

maxdb_connect_error

(PECL maxdb >= 1.0)

maxdb_connect_error — Returns a string description of the last connect error

Descrierea

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 occurred, this function will return an empty string.

Valorile întoarse

A string that describes the error. An empty string if no error occurred.

Exemple

Example #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());
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • 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 Func?ii


Open a new connection to the MaxDB server

maxdb_connect_error
maxdb_data_seek
MaxDB Func?ii
PHP Manual

maxdb_connect

maxdb::__construct

(PECL maxdb >= 1.0)

maxdb_connect -- maxdb::__construct — Open a new connection to the MaxDB server

Descrierea

Stil procedural

resource maxdb_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port = 0 [, string $socket ]]]]]] )

Stil obiect-orientat

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 sau FALSE în cazul e?ecului.

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.

Valorile întoarse

Returns a resource which represents the connection to a MaxDB Server or FALSE if the connection failed.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Host information: localhost
maxdb_connect_error
maxdb_data_seek
MaxDB Func?ii


Adjusts the result pointer to an arbitary row in the result

maxdb_connect
maxdb_debug
MaxDB Func?ii
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

Descrierea

Stil procedural

bool maxdb_data_seek ( resource $result , int $offset )

Stil obiect-orientat

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

City: Irvine  State: CA

A se vedea ?i

  • 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 Func?ii


Performs debugging operations

maxdb_data_seek
maxdb_disable_reads_from_master
MaxDB Func?ii
PHP Manual

maxdb_debug

(PECL maxdb >= 1.0)

maxdb_debug — Performs debugging operations

Descrierea

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.

Valorile întoarse

maxdb_debug() doesn't return any value.

Exemple

Example #1 Stil procedural

<?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 Func?ii


Interzice citirea din stapân

maxdb_debug
maxdb_disable_rpl_parse
MaxDB Func?ii
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 — Interzice citirea din stapân

Descrierea

Stil procedural

bool maxdb_disable_reads_from_master ( resource $link )

Stil obiect-orientat

void maxdb::disable_reads_from_master ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_debug
maxdb_disable_rpl_parse
MaxDB Func?ii


Deconecteaza interpretarea RPL

maxdb_disable_reads_from_master
maxdb_dump_debug_info
MaxDB Func?ii
PHP Manual

maxdb_disable_rpl_parse

(PECL maxdb >= 1.0)

maxdb_disable_rpl_parse — Deconecteaza interpretarea RPL

Descrierea

bool maxdb_disable_rpl_parse ( resource $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_disable_reads_from_master
maxdb_dump_debug_info
MaxDB Func?ii


Înscrie informa?ia de depanare în jurnal

maxdb_disable_rpl_parse
maxdb_embedded_connect
MaxDB Func?ii
PHP Manual

maxdb_dump_debug_info

(PECL maxdb >= 1.0)

maxdb_dump_debug_info — Înscrie informa?ia de depanare în jurnal

Descrierea

bool maxdb_dump_debug_info ( resource $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_disable_rpl_parse
maxdb_embedded_connect
MaxDB Func?ii


Deschide o conexiune catre un server MaxDB încorporat

maxdb_dump_debug_info
maxdb_enable_reads_from_master
MaxDB Func?ii
PHP Manual

maxdb_embedded_connect

(PECL maxdb >= 1.0)

maxdb_embedded_connect — Deschide o conexiune catre un server MaxDB încorporat

Descrierea

resource maxdb_embedded_connect ([ string $dbname ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_dump_debug_info
maxdb_enable_reads_from_master
MaxDB Func?ii


Permite citirea din stapân

maxdb_embedded_connect
maxdb_enable_rpl_parse
MaxDB Func?ii
PHP Manual

maxdb_enable_reads_from_master

(PECL maxdb >= 1.0)

maxdb_enable_reads_from_master — Permite citirea din stapân

Descrierea

bool maxdb_enable_reads_from_master ( resource $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_embedded_connect
maxdb_enable_rpl_parse
MaxDB Func?ii


Activeaza interpretarea RPL

maxdb_enable_reads_from_master
maxdb_errno
MaxDB Func?ii
PHP Manual

maxdb_enable_rpl_parse

(PECL maxdb >= 1.0)

maxdb_enable_rpl_parse — Activeaza interpretarea RPL

Descrierea

bool maxdb_enable_rpl_parse ( resource $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_enable_reads_from_master
maxdb_errno
MaxDB Func?ii


Returns the error code for the most recent function call

maxdb_enable_rpl_parse
maxdb_error
MaxDB Func?ii
PHP Manual

maxdb_errno

maxdb::errno

(PECL maxdb >= 1.0)

maxdb_errno -- maxdb::errno — Returns the error code for the most recent function call

Descrierea

Stil procedural

int maxdb_errno ( resource $link )

Stil obiect-orientat

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 occurred, this function will return zero.

Valorile întoarse

An error code value for the last call, if it failed. zero means no error occurred.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

PHP Warning:  maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000] <...>
Errorcode: -4005

A se vedea ?i

  • 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 Func?ii


Returns a string description of the last error

maxdb_errno
maxdb_escape_string
MaxDB Func?ii
PHP Manual

maxdb_error

maxdb::error

(PECL maxdb >= 1.0)

maxdb_error -- maxdb::error — Returns a string description of the last error

Descrierea

Stil procedural

string maxdb_error ( resource $link )

Stil obiect-orientat

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 occurred, this function will return an empty string.

Valorile întoarse

A string that describes the error. An empty string if no error occurred.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

PHP Warning:  maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000]
Errormessgae: POS(8) Unknown column name:XXX

A se vedea ?i

  • 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 Func?ii


Pseudonim pentru maxdb_real_escape_string

maxdb_error
maxdb_execute
MaxDB Func?ii
PHP Manual

maxdb_escape_string

(PECL maxdb 1.0)

maxdb_escape_string — Pseudonim pentru maxdb_real_escape_string()

Descrierea

Aceasta func?ie este pseudonim pentru: maxdb_real_escape_string().

maxdb_error
maxdb_execute
MaxDB Func?ii


Pseudonim pentru maxdb_stmt_execute

maxdb_escape_string
maxdb_fetch_array
MaxDB Func?ii
PHP Manual

maxdb_execute

(PECL maxdb 1.0)

maxdb_execute — Pseudonim pentru maxdb_stmt_execute()

Descrierea

Aceasta func?ie este pseudonim pentru: maxdb_stmt_execute().

Acest pseudonim al func?iei este învechit ?i exista numai din motivul pastrarii compatibilita?ii cu versiunile anterioare. Utilizarea acestei func?ii nu este recomandata, deoarece ea poate fi eliminata din PHP în viitor.

maxdb_escape_string
maxdb_fetch_array
MaxDB Func?ii


Fetch a result row as an associative, a numeric array, or both

maxdb_execute
maxdb_fetch_assoc
MaxDB Func?ii
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

Descrierea

Stil procedural

mixed maxdb_fetch_array ( resource $result [, int $resulttype ] )

Stil obiect-orientat

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.

Nota: Numele câmpurilor întoarse de aceasta func?ie sunt sensibile la literele majuscule/minuscule.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP 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.

Valorile întoarse

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

New York (NY)
New York (NY)
Long Island (NY)

A se vedea ?i

  • 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 Func?ii


Fetch a result row as an associative array

maxdb_fetch_array
maxdb_fetch_field_direct
MaxDB Func?ii
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

Descrierea

Stil procedural

array maxdb_fetch_assoc ( resource $result )

Stil obiect-orientat

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.

Nota: Numele câmpurilor întoarse de aceasta func?ie sunt sensibile la literele majuscule/minuscule.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

Valorile întoarse

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)

A se vedea ?i

  • 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 Func?ii


Fetch meta-data for a single field

maxdb_fetch_assoc
maxdb_fetch_field
MaxDB Func?ii
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

Descrierea

Stil procedural

mixed maxdb_fetch_field_direct ( resource $result , int $fieldnr )

Stil obiect-orientat

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.

Valorile întoarse

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)

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

A se vedea ?i

  • 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 Func?ii


Returns the next field in the result set

maxdb_fetch_field_direct
maxdb_fetch_fields
MaxDB Func?ii
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

Descrierea

Stil procedural

mixed maxdb_fetch_field ( resource $result )

Stil obiect-orientat

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.

Valorile întoarse

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)

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

A se vedea ?i

  • 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 Func?ii


Returns an array of resources representing the fields in a result set

maxdb_fetch_field
maxdb_fetch_lengths
MaxDB Func?ii
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

Descrierea

Stil procedural

mixed maxdb_fetch_fields ( resource $result )

Stil obiect-orientat

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.

Valorile întoarse

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)

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

A se vedea ?i

  • 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 Func?ii


Returns the lengths of the columns of the current row in the result set

maxdb_fetch_fields
maxdb_fetch_object
MaxDB Func?ii
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

Descrierea

Stil procedural

array maxdb_fetch_lengths ( resource $result )

Stil obiect-orientat

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 sau FALSE în cazul e?ecului.

Valorile întoarse

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.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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 Func?ii


Returns the current row of a result set as an object

maxdb_fetch_lengths
maxdb_fetch_row
MaxDB Func?ii
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

Descrierea

Stil procedural

object maxdb_fetch_object ( object $result )

Stil obiect-orientat

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.

Valorile întoarse

Returns an object that corresponds to the fetched row or NULL if there are no more rows in resultset.

Nota: Numele câmpurilor întoarse de aceasta func?ie sunt sensibile la literele majuscule/minuscule.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)

A se vedea ?i

  • 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 Func?ii


Get a result row as an enumerated array

maxdb_fetch_object
maxdb_fetch
MaxDB Func?ii
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

Descrierea

Stil procedural

mixed maxdb_fetch_row ( resource $result )

Stil obiect-orientat

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.

Valorile întoarse

maxdb_fetch_row() returns an array that corresponds to the fetched row or NULL if there are no more rows in result set.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)

A se vedea ?i

  • 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 Func?ii


Pseudonim pentru maxdb_stmt_fetch

maxdb_fetch_row
maxdb_field_count
MaxDB Func?ii
PHP Manual

maxdb_fetch

(PECL maxdb 1.0)

maxdb_fetch — Pseudonim pentru maxdb_stmt_fetch()

Descrierea

Aceasta func?ie este pseudonim pentru: maxdb_stmt_fetch().

Acest pseudonim al func?iei este învechit ?i exista numai din motivul pastrarii compatibilita?ii cu versiunile anterioare. Utilizarea acestei func?ii nu este recomandata, deoarece ea poate fi eliminata din PHP în viitor.

maxdb_fetch_row
maxdb_field_count
MaxDB Func?ii


Returns the number of columns for the most recent query

maxdb_fetch
maxdb_field_seek
MaxDB Func?ii
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

Descrierea

Stil procedural

int maxdb_field_count ( resource $link )

Stil obiect-orientat

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.

Valorile întoarse

An integer representing the number of fields in a result set.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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 Func?ii


Set result pointer to a specified field offset

maxdb_field_count
maxdb_field_tell
MaxDB Func?ii
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

Descrierea

Stil procedural

bool maxdb_field_seek ( resource $result , int $fieldnr )

Stil obiect-orientat

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.

Nota:

To seek to the beginning of a row, pass an offset value of zero.

Valorile întoarse

maxdb_field_seek() returns previuos value of field cursor.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

A se vedea ?i

  • maxdb_fetch_field() - Returns the next field in the result set

maxdb_field_count
maxdb_field_tell
MaxDB Func?ii


Get current field offset of a result pointer

maxdb_field_seek
maxdb_free_result
MaxDB Func?ii
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

Descrierea

Stil procedural

int maxdb_field_tell ( resource $result )

Stil obiect-orientat

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().

Valorile întoarse

Returns current offset of field cursor.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Column    1:
Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Column    2:
Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

A se vedea ?i

  • 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 Func?ii


Frees the memory associated with a result

maxdb_field_tell
maxdb_get_client_info
MaxDB Func?ii
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

Descrierea

Stil procedural

void maxdb_free_result ( resource $result )

Stil obiect-orientat

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().

Nota:

You should always free your result with maxdb_free_result(), when your result resource is not needed anymore.

Valorile întoarse

This function doesn't return any value.

A se vedea ?i

  • 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 Func?ii


Returns the MaxDB client version as a string

maxdb_free_result
maxdb_get_client_version
MaxDB Func?ii
PHP Manual

maxdb_get_client_info

(PECL maxdb >= 1.0)

maxdb_get_client_info — Returns the MaxDB client version as a string

Descrierea

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.

Valorile întoarse

A string that represents the MaxDB client library version

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Client library version: libSQLDBC <...>

A se vedea ?i

  • 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 Func?ii


Get MaxDB client info

maxdb_get_client_info
maxdb_get_host_info
MaxDB Func?ii
PHP Manual

maxdb_get_client_version

(PECL maxdb >= 1.0)

maxdb_get_client_version — Get MaxDB client info

Descrierea

int maxdb_get_client_version ( void )

Returns client version number as an integer.

Valorile întoarse

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.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Client library version: 7.<...>

A se vedea ?i

  • 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 Func?ii


Returns a string representing the type of connection used

maxdb_get_client_version
maxdb_get_metadata
MaxDB Func?ii
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

Descrierea

Stil procedural

string maxdb_get_host_info ( resource $link )

Stil obiect-orientat

string $maxdb->host_info;

The maxdb_get_host_info() function returns a string describing the connection represented by the link parameter is using.

Valorile întoarse

A character string representing the server hostname and the connection type.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Host info: localhost

A se vedea ?i

  • maxdb_get_proto_info() - Returns the version of the MaxDB protocol used

maxdb_get_client_version
maxdb_get_metadata
MaxDB Func?ii


Pseudonim pentru maxdb_stmt_result_metadata

maxdb_get_host_info
maxdb_get_proto_info
MaxDB Func?ii
PHP Manual

maxdb_get_metadata

(PECL maxdb 1.0)

maxdb_get_metadata — Pseudonim pentru maxdb_stmt_result_metadata()

Descrierea

Aceasta func?ie este pseudonim pentru: maxdb_stmt_result_metadata().

Acest pseudonim al func?iei este învechit ?i exista numai din motivul pastrarii compatibilita?ii cu versiunile anterioare. Utilizarea acestei func?ii nu este recomandata, deoarece ea poate fi eliminata din PHP în viitor.

maxdb_get_host_info
maxdb_get_proto_info
MaxDB Func?ii


Returns the version of the MaxDB protocol used

maxdb_get_metadata
maxdb_get_server_info
MaxDB Func?ii
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

Descrierea

Stil procedural

int maxdb_get_proto_info ( resource $link )

Stil obiect-orientat

string $maxdb->protocol_version;

Returns an integer representing the MaxDB protocol version used by the connection represented by the link parameter.

Valorile întoarse

Returns an integer representing the protocol version (constant 10).

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Protocol version: 10

A se vedea ?i

  • maxdb_get_host_info() - Returns a string representing the type of connection used

maxdb_get_metadata
maxdb_get_server_info
MaxDB Func?ii


Returns the version of the MaxDB server

maxdb_get_proto_info
maxdb_get_server_version
MaxDB Func?ii
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

Descrierea

Stil procedural

string maxdb_get_server_info ( resource $link )

Stil obiect-orientat

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).

Valorile întoarse

A character string representing the server version.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Server version: Kernel    7<...>

A se vedea ?i

  • 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 Func?ii


Returns the version of the MaxDB server as an integer

maxdb_get_server_info
maxdb_info
MaxDB Func?ii
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

Descrierea

Stil procedural

int maxdb_get_server_version ( resource $link )

Stil obiect-orientat

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).

Valorile întoarse

An integer representing the server version.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Server version: 7<...>

A se vedea ?i

  • 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 Func?ii


Retrieves information about the most recently executed query

maxdb_get_server_version
maxdb_init
MaxDB Func?ii
PHP Manual

maxdb_info

maxdb::info

(PECL maxdb >= 1.0)

maxdb_info -- maxdb::info — Retrieves information about the most recently executed query

Descrierea

Stil procedural

string maxdb_info ( resource $link )

Stil obiect-orientat

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

Nota:

Queries which do not fall into one of the above formats are not supported. In these situations, maxdb_info() will return an empty string.

Valorile întoarse

A character string representing additional information about the most recently executed query.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Records: 25 Duplicates: 0 Warnings: 0

A se vedea ?i

  • 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 Func?ii


Initializes MaxDB and returns an resource for use with maxdb_real_connect

maxdb_info
maxdb_insert_id
MaxDB Func?ii
PHP Manual

maxdb_init

(PECL maxdb >= 1.0)

maxdb_init — Initializes MaxDB and returns an resource for use with maxdb_real_connect

Descrierea

resource maxdb_init ( void )

Allocates or initializes a MaxDB resource suitable for maxdb_options() and maxdb_real_connect().

Nota:

Any subsequent calls to any maxdb function (except maxdb_options()) will fail until maxdb_real_connect() was called.

Valorile întoarse

Returns an resource.

A se vedea ?i

  • 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 Func?ii


Returns the auto generated id used in the last query

maxdb_init
maxdb_kill
MaxDB Func?ii
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

Descrierea

Stil procedural

mixed maxdb_insert_id ( resource $link )

Stil obiect-orientat

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.

Valorile întoarse

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.

Nota:

If the number is greater than maximal int value, maxdb_insert_id() will return a string.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

New Record has id 1.
maxdb_init
maxdb_kill
MaxDB Func?ii


Disconnects from a MaxDB server

maxdb_insert_id
maxdb_master_query
MaxDB Func?ii
PHP Manual

maxdb_kill

maxdb::kill

(PECL maxdb >= 1.0)

maxdb_kill -- maxdb::kill — Disconnects from a MaxDB server

Descrierea

Stil procedural

bool maxdb_kill ( resource $link , int $processid )

Stil obiect-orientat

bool maxdb::kill ( int $processid )

This function is used to disconnect from a MaxDB server specified by the processid parameter.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Error: Session not connected

A se vedea ?i

  • maxdb_thread_id() - Returns the thread ID for the current connection

maxdb_insert_id
maxdb_master_query
MaxDB Func?ii


Impune execu?ia unei interpelari catre stapân într-o configura?ie stapân/subordonat

maxdb_kill
maxdb_more_results
MaxDB Func?ii
PHP Manual

maxdb_master_query

(PECL maxdb >= 1.0)

maxdb_master_query — Impune execu?ia unei interpelari catre stapân într-o configura?ie stapân/subordonat

Descrierea

bool maxdb_master_query ( resource $link , string $query )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_kill
maxdb_more_results
MaxDB Func?ii


Check if there any more query results from a multi query

maxdb_master_query
maxdb_multi_query
MaxDB Func?ii
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

Descrierea

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().

Valorile întoarse

Always FALSE.

Exemple

See maxdb_multi_query().

A se vedea ?i

  • 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 Func?ii


Performs a query on the database

maxdb_more_results
maxdb_next_result
MaxDB Func?ii
PHP Manual

maxdb_multi_query

maxdb::multi_query

(PECL maxdb >= 1.0)

maxdb_multi_query -- maxdb::multi_query — Performs a query on the database

Descrierea

Stil procedural

bool maxdb_multi_query ( resource $link , string $query )

Stil obiect-orientat

bool maxdb::multi_query ( string $query )

The maxdb_multi_query() works like the function maxdb_query(). Multiple queries are not yet supported.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

a

A se vedea ?i

  • 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 Func?ii


Prepare next result from multi_query

maxdb_multi_query
maxdb_num_fields
MaxDB Func?ii
PHP Manual

maxdb_next_result

maxdb::next_result

(PECL maxdb >= 1.0)

maxdb_next_result -- maxdb::next_result — Prepare next result from multi_query

Descrierea

bool maxdb_next_result ( resource $link )

Since multiple queries are not yet supported, maxdb_next_result() returns always FALSE.

Valorile întoarse

Returns FALSE.

A se vedea ?i

  • 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 Func?ii


Get the number of fields in a result

maxdb_next_result
maxdb_num_rows
MaxDB Func?ii
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

Descrierea

Stil procedural

int maxdb_num_fields ( resource $result )

Stil obiect-orientat

int $maxdb_result->field_count;

maxdb_num_fields() returns the number of fields from specified result set.

Valorile întoarse

The number of fields from a result set

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Result set has 3 fields.

A se vedea ?i

  • maxdb_fetch_field() - Returns the next field in the result set

maxdb_next_result
maxdb_num_rows
MaxDB Func?ii


Gets the number of rows in a result

maxdb_num_fields
maxdb_options
MaxDB Func?ii
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

Descrierea

Stil procedural

int maxdb_num_rows ( resource $result )

Stil obiect-orientat

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.

Valorile întoarse

Returns number of rows in the result set.

Nota:

If the number of rows is greater than maximal int value, the number will be returned as a string.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Result set has 15 rows.

A se vedea ?i

  • 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 Func?ii


Set options

maxdb_num_rows
maxdb_param_count
MaxDB Func?ii
PHP Manual

maxdb_options

maxdb::options

(PECL maxdb >= 1.0)

maxdb_options -- maxdb::options — Set options

Descrierea

Stil procedural

bool maxdb_options ( resource $link , int $option , mixed $value )

Stil obiect-orientat

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

See maxdb_real_connect().

A se vedea ?i

  • 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 Func?ii


Pseudonim pentru maxdb_stmt_param_count

maxdb_options
maxdb_ping
MaxDB Func?ii
PHP Manual

maxdb_param_count

(PECL maxdb 1.0)

maxdb_param_count — Pseudonim pentru maxdb_stmt_param_count()

Descrierea

Aceasta func?ie este pseudonim pentru: maxdb_stmt_param_count().

Acest pseudonim al func?iei este învechit ?i exista numai din motivul pastrarii compatibilita?ii cu versiunile anterioare. Utilizarea acestei func?ii nu este recomandata, deoarece ea poate fi eliminata din PHP în viitor.

maxdb_options
maxdb_ping
MaxDB Func?ii


Pings a server connection, or tries to reconnect if the connection has gone down

maxdb_param_count
maxdb_prepare
MaxDB Func?ii
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

Descrierea

Stil procedural

bool maxdb_ping ( resource $link )

Stil obiect-orientat

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Our connection is ok!
maxdb_param_count
maxdb_prepare
MaxDB Func?ii


Prepare an SQL statement for execution

maxdb_ping
maxdb_query
MaxDB Func?ii
PHP Manual

maxdb_prepare

maxdb::prepare

(PECL maxdb >= 1.0)

maxdb_prepare -- maxdb::prepare — Prepare an SQL statement for execution

Descrierea

Stil procedural

resource maxdb_prepare ( resource $link , string $query )

Stil obiect-orientat

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.

Nota:

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.

Nota:

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.

Valorile întoarse

maxdb_prepare() returns a statement resource or FALSE if an error occurred.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Rosemont is in district IL

A se vedea ?i

  • 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 Func?ii


Performs a query on the database

maxdb_prepare
maxdb_real_connect
MaxDB Func?ii
PHP Manual

maxdb_query

maxdb::query

(PECL maxdb >= 1.0)

maxdb_query -- maxdb::query — Performs a query on the database

Descrierea

Stil procedural

mixed maxdb_query ( resource $link , string $query [, int $resultmode ] )

Stil obiect-orientat

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. For SELECT, SHOW, DESCRIBE or EXPLAIN maxdb_query() will return a result resource.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Table mycity successfully created.
Select returned 25 rows.

A se vedea ?i

  • 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 Func?ii


Opens a connection to a MaxDB server

maxdb_query
maxdb_real_escape_string
MaxDB Func?ii
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

Descrierea

Stil procedural

bool maxdb_real_connect ( resource $link [, string $hostname [, string $username [, string $passwd [, string $dbname [, int $port = 0 [, string $socket ]]]]]] )

Stil obiect-orientat

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Connection: localhost <...>

A se vedea ?i

  • 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 Func?ii


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 Func?ii
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

Descrierea

Stil procedural

string maxdb_real_escape_string ( resource $link , string $escapestr )

Stil obiect-orientat

string maxdb::real_escape_string ( 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 ', ".

Valorile întoarse

Returns an escaped string.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Warning: maxdb_query(): -5016 POS(43) Missing delimiter: ) <...>
Error: 42000
1 Row inserted.

A se vedea ?i

  • maxdb_character_set_name() - Returns the default character set for the database connection

maxdb_real_connect
maxdb_real_query
MaxDB Func?ii


Execute an SQL query

maxdb_real_escape_string
maxdb_report
MaxDB Func?ii
PHP Manual

maxdb_real_query

maxdb::real_query

(PECL maxdb >= 1.0)

maxdb_real_query -- maxdb::real_query — Execute an SQL query

Descrierea

Stil procedural

bool maxdb_real_query ( resource $link , string $query )

Stil obiect-orientat

bool maxdb::real_query ( string $query )

The maxdb_real_query() is functionally identical with the maxdb_query().

Nota:

In order to determine if a given query should return a result set or not, see maxdb_field_count().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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 Func?ii


Enables or disables internal report functions

maxdb_real_query
maxdb_rollback
MaxDB Func?ii
PHP Manual

maxdb_report

(PECL maxdb 1.0)

maxdb_report — Enables or disables internal report functions

Descrierea

bool maxdb_report ( int $flags )

Parametri

flags

One of the MAXDB_REPORT_XXX constants.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Warning: maxdb_query(): -4004 POS(18) Unknown table name:NONEXISTINGTABLE <...>
maxdb_real_query
maxdb_rollback
MaxDB Func?ii


Rolls back current transaction

maxdb_report
maxdb_rpl_parse_enabled
MaxDB Func?ii
PHP Manual

maxdb_rollback

maxdb::rollback

(PECL maxdb >= 1.0)

maxdb_rollback -- maxdb::rollback — Rolls back current transaction

Descrierea

Stil procedural

bool maxdb_rollback ( resource $link )

Stil obiect-orientat

bool maxdb::rollback ( void )

Rollbacks the current transaction for the database specified by the link parameter.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

0 rows in table mycity.
25 rows in table mycity (after rollback).

A se vedea ?i

  • maxdb_commit() - Commits the current transaction
  • maxdb_autocommit() - Turns on or off auto-commiting database modifications

maxdb_report
maxdb_rpl_parse_enabled
MaxDB Func?ii


Verifica daca interpretarea RPL este activata

maxdb_rollback
maxdb_rpl_probe
MaxDB Func?ii
PHP Manual

maxdb_rpl_parse_enabled

(PECL maxdb >= 1.0)

maxdb_rpl_parse_enabled — Verifica daca interpretarea RPL este activata

Descrierea

int maxdb_rpl_parse_enabled ( resource $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_rollback
maxdb_rpl_probe
MaxDB Func?ii


Sonda RPL

maxdb_rpl_parse_enabled
maxdb_rpl_query_type
MaxDB Func?ii
PHP Manual

maxdb_rpl_probe

(PECL maxdb >= 1.0)

maxdb_rpl_probe — Sonda RPL

Descrierea

bool maxdb_rpl_probe ( resource $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_rpl_parse_enabled
maxdb_rpl_query_type
MaxDB Func?ii


Întoarce tipul interpelarii RPL

maxdb_rpl_probe
maxdb_select_db
MaxDB Func?ii
PHP Manual

maxdb_rpl_query_type

maxdb::rpl_query_type

(PECL maxdb >= 1.0)

maxdb_rpl_query_type -- maxdb::rpl_query_type — Întoarce tipul interpelarii RPL

Descrierea

Stil procedural

int maxdb_rpl_query_type ( resource $link )

Stil obiect-orientat

int maxdb::rpl_query_type ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_rpl_probe
maxdb_select_db
MaxDB Func?ii


Selects the default database for database queries

maxdb_rpl_query_type
maxdb_send_long_data
MaxDB Func?ii
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

Descrierea

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.

Nota:

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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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 [] <...>

A se vedea ?i

  • 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 Func?ii


Pseudonim pentru maxdb_stmt_send_long_data

maxdb_select_db
maxdb_send_query
MaxDB Func?ii
PHP Manual

maxdb_send_long_data

(PECL maxdb >= 1.0)

maxdb_send_long_data — Pseudonim pentru maxdb_stmt_send_long_data()

Descrierea

Aceasta func?ie este pseudonim pentru: maxdb_stmt_send_long_data().

Acest pseudonim al func?iei este învechit ?i exista numai din motivul pastrarii compatibilita?ii cu versiunile anterioare. Utilizarea acestei func?ii nu este recomandata, deoarece ea poate fi eliminata din PHP în viitor.

maxdb_select_db
maxdb_send_query
MaxDB Func?ii


Transmite interpelarea ?i întoarce execu?ia

maxdb_send_long_data
maxdb_server_end
MaxDB Func?ii
PHP Manual

maxdb_send_query

maxdb::send_query

(PECL maxdb >= 1.0)

maxdb_send_query -- maxdb::send_query — Transmite interpelarea ?i întoarce execu?ia

Descrierea

Stil procedural

bool maxdb_send_query ( resource $link , string $query )

Stil obiect-orientat

bool maxdb::send_query ( string $query )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_send_long_data
maxdb_server_end
MaxDB Func?ii


Deconecteaza serverul încorporat

maxdb_send_query
maxdb_server_init
MaxDB Func?ii
PHP Manual

maxdb_server_end

(PECL maxdb >= 1.0)

maxdb_server_end — Deconecteaza serverul încorporat

Descrierea

void maxdb_server_end ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_send_query
maxdb_server_init
MaxDB Func?ii


Ini?ializeaza serverul încorporat

maxdb_server_end
maxdb_set_opt
MaxDB Func?ii
PHP Manual

maxdb_server_init

(PECL maxdb >= 1.0)

maxdb_server_init — Ini?ializeaza serverul încorporat

Descrierea

bool maxdb_server_init ([ array $server [, array $groups ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_server_end
maxdb_set_opt
MaxDB Func?ii


Pseudonim pentru maxdb_options

maxdb_server_init
maxdb_sqlstate
MaxDB Func?ii
PHP Manual

maxdb_set_opt

(PECL maxdb 1.0)

maxdb_set_opt — Pseudonim pentru maxdb_options()

Descrierea

Aceasta func?ie este pseudonim pentru: maxdb_options().

maxdb_server_init
maxdb_sqlstate
MaxDB Func?ii


Returns the SQLSTATE error from previous MaxDB operation

maxdb_set_opt
maxdb_ssl_set
MaxDB Func?ii
PHP Manual

maxdb_sqlstate

maxdb::sqlstate

(PECL maxdb >= 1.0)

maxdb_sqlstate -- maxdb::sqlstate — Returns the SQLSTATE error from previous MaxDB operation

Descrierea

Stil procedural

string maxdb_sqlstate ( resource $link )

Stil obiect-orientat

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.

Nota:

Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Valorile întoarse

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Warning: maxdb_query(): -6000 POS(20) Duplicate table name:CITY [I6000] <...>
Error - SQLSTATE I6000.

A se vedea ?i

  • 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 Func?ii


Used for establishing secure connections using SSL

maxdb_sqlstate
maxdb_stat
MaxDB Func?ii
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

Descrierea

Stil procedural

bool maxdb_ssl_set ( resource $link , string $key , string $cert , string $ca , string $capath , string $cipher )

Stil obiect-orientat

bool maxdb::ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_sqlstate
maxdb_stat
MaxDB Func?ii


Gets the current system status

maxdb_ssl_set
maxdb_stmt_affected_rows
MaxDB Func?ii
PHP Manual

maxdb_stat

maxdb::stat

(PECL maxdb >= 1.0)

maxdb_stat -- maxdb::stat — Gets the current system status

Descrierea

Stil procedural

string maxdb_stat ( resource $link )

Stil obiect-orientat

string maxdb::stat ( void )

maxdb_stat() returns a string containing several information about the MaxDB server running.

Valorile întoarse

A string describing the server status. FALSE if an error occurred.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

System status: Kernel    7<...>

A se vedea ?i

  • maxdb_get_server_info() - Returns the version of the MaxDB server

maxdb_ssl_set
maxdb_stmt_affected_rows
MaxDB Func?ii


Returns the total number of rows changed, deleted, or inserted by the last executed statement

maxdb_stat
maxdb_stmt_bind_param
MaxDB Func?ii
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

Descrierea

Stil procedural

int maxdb_stmt_affected_rows ( resource $stmt )

Stil obiect-orientat

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.

Valorile întoarse

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.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

rows inserted: 4

A se vedea ?i

  • 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 Func?ii


Binds variables to a prepared statement as parameters

maxdb_stmt_affected_rows
maxdb_stmt_bind_result
MaxDB Func?ii
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

Descrierea

Stil procedural

bool maxdb_stmt_bind_param ( resource $stmt , string $types , mixed &$var1 [, mixed &$... ] )

Stil obiect-orientat

bool maxdb_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

Stil procedural (extended syntax):

bool maxdb_stmt_bind_param ( resource $stmt , string $types , array &$var )

Stil obiect-orientat (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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

1 Row inserted.
1 Row deleted.

Example #3 Stil procedural (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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

21.600000

Example #4 Stil procedural (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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

a

Example #5 Stil obiect-orientat (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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

1 Row inserted.
1 Row inserted.
11111 Georgetown NY
22222 New Orleans LA
2 Rows deleted.

A se vedea ?i

  • 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 Func?ii


Binds variables to a prepared statement for result storage

maxdb_stmt_bind_param
maxdb_stmt_close_long_data
MaxDB Func?ii
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

Descrierea

Stil procedural

bool maxdb_stmt_bind_result ( resource $stmt , mixed &$var1 [, mixed &$... ] )

Stil obiect-orientat

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, ....

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();

?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • 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 Func?ii


Ends a sequence of maxdb_stmt_send_long_data

maxdb_stmt_bind_result
maxdb_stmt_close
MaxDB Func?ii
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()

Descrierea

Stil procedural

bool maxdb_stmt_close_long_data ( resource $stmt , int $param_nr )

Stil obiect-orientat

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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 Func?ii


Closes a prepared statement

maxdb_stmt_close_long_data
maxdb_stmt_data_seek
MaxDB Func?ii
PHP Manual

maxdb_stmt_close

maxdb_stmt::close

(PECL maxdb >= 1.0)

maxdb_stmt_close -- maxdb_stmt::close — Closes a prepared statement

Descrierea

Stil procedural

bool maxdb_stmt_close ( resource $stmt )

Stil obiect-orientat

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • maxdb_prepare() - Prepare an SQL statement for execution

maxdb_stmt_close_long_data
maxdb_stmt_data_seek
MaxDB Func?ii


Seeks to an arbitray row in statement result set

maxdb_stmt_close
maxdb_stmt_errno
MaxDB Func?ii
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

Descrierea

Stil procedural

bool maxdb_stmt_data_seek ( resource $statement , int $offset )

Stil obiect-orientat

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

City: Dallas  Zip: 75243

A se vedea ?i

  • maxdb_prepare() - Prepare an SQL statement for execution

maxdb_stmt_close
maxdb_stmt_errno
MaxDB Func?ii


Returns the error code for the most recent statement call

maxdb_stmt_data_seek
maxdb_stmt_error
MaxDB Func?ii
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

Descrierea

Stil procedural

int maxdb_stmt_errno ( resource $stmt )

Stil obiect-orientat

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.

Nota:

For possible error codes see documentation of SQLDBC: » http://maxdb.sap.com/documentation/.

Valorile întoarse

An error code value. Zero means no error occurred.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: -4004.

A se vedea ?i

  • 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 Func?ii


Returns a string description for last statement error

maxdb_stmt_errno
maxdb_stmt_execute
MaxDB Func?ii
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

Descrierea

Stil procedural

string maxdb_stmt_error ( resource $stmt )

Stil obiect-orientat

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.

Valorile întoarse

A string that describes the error. An empty string if no error occurred.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: POS(23) Unknown table name:MYCITY.

A se vedea ?i

  • 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 Func?ii


Executes a prepared Query

maxdb_stmt_error
maxdb_stmt_fetch
MaxDB Func?ii
PHP Manual

maxdb_stmt_execute

maxdb_stmt::execute

(PECL maxdb >= 1.0)

maxdb_stmt_execute -- maxdb_stmt::execute — Executes a prepared Query

Descrierea

Stil procedural

bool maxdb_stmt_execute ( resource $stmt )

Stil obiect-orientat

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.

Nota:

When using maxdb_stmt_execute(), the maxdb_fetch() function must be used to fetch the data prior to preforming any additional queries.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

11111 (Georgetown,NY)
22222 (Hubbatown,CA)

A se vedea ?i

  • 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 Func?ii


Fetch results from a prepared statement into the bound variables

maxdb_stmt_execute
maxdb_stmt_free_result
MaxDB Func?ii
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

Descrierea

Stil procedural

bool maxdb_stmt_fetch ( resource $stmt )

Stil obiect-orientat

bool maxdb_stmt::fetch ( void )

maxdb_stmt_fetch() returns row data using the variables bound by maxdb_stmt_bind_result().

Nota:

Note that all columns must be bound by the application before calling maxdb_stmt_fetch().

Valorile întoarse

Return values
Value | Description
TRUE | Success. Data has been fetched
FALSE | Error occurred
NULL | No more rows/data exists

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)

A se vedea ?i

  • 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 Func?ii


Frees stored result memory for the given statement handle

maxdb_stmt_fetch
maxdb_stmt_init
MaxDB Func?ii
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

Descrierea

Stil procedural

void maxdb_stmt_free_result ( resource $stmt )

Stil obiect-orientat

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().

Valorile întoarse

This function doesn't return any value.

A se vedea ?i

  • maxdb_stmt_store_result() - Transfers a result set from a prepared statement

maxdb_stmt_fetch
maxdb_stmt_init
MaxDB Func?ii


Initializes a statement and returns an resource for use with maxdb_stmt_prepare

maxdb_stmt_free_result
maxdb_stmt_num_rows
MaxDB Func?ii
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

Descrierea

Stil procedural

resource maxdb_stmt_init ( resource $link )

Stil obiect-orientat

object maxdb::stmt_init ( void )

Allocates and initializes a statement resource suitable for maxdb_stmt_prepare().

Nota:

Any subsequent calls to any maxdb_stmt function will fail until maxdb_stmt_prepare() was called.

Valorile întoarse

Returns an resource.

A se vedea ?i

  • maxdb_stmt_prepare() - Prepare an SQL statement for execution

maxdb_stmt_free_result
maxdb_stmt_num_rows
MaxDB Func?ii


Return the number of rows in statements result set

maxdb_stmt_init
maxdb_stmt_param_count
MaxDB Func?ii
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

Descrierea

Stil procedural

int maxdb_stmt_num_rows ( resource $stmt )

Stil obiect-orientat

int $maxdb_stmt->num_rows;

Returns the number of rows in the result set.

Valorile întoarse

An integer representing the number of rows in result set.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Number of rows: 25.

A se vedea ?i

  • 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 Func?ii


Returns the number of parameter for the given statement

maxdb_stmt_num_rows
maxdb_stmt_prepare
MaxDB Func?ii
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

Descrierea

Stil procedural

int maxdb_stmt_param_count ( resource $stmt )

Stil obiect-orientat

int $maxdb_stmt->param_count;

maxdb_stmt_param_count() returns the number of parameter markers present in the prepared statement.

Valorile întoarse

returns an integer representing the number of parameters.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Statement has 2 markers.

A se vedea ?i

  • maxdb_prepare() - Prepare an SQL statement for execution

maxdb_stmt_num_rows
maxdb_stmt_prepare
MaxDB Func?ii


Prepare an SQL statement for execution

maxdb_stmt_param_count
maxdb_stmt_reset
MaxDB Func?ii
PHP Manual

maxdb_stmt_prepare

maxdb_stmt::prepare

(PECL maxdb >= 1.0)

maxdb_stmt_prepare -- maxdb_stmt::prepare — Prepare an SQL statement for execution

Descrierea

Stil procedural

bool maxdb_stmt_prepare ( resource $stmt , string $query )

Stil obiect-orientat

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.

Nota:

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.

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Portland is in district OR

A se vedea ?i

  • 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 Func?ii


Anuleaza o declara?ie pregatita anterior

maxdb_stmt_prepare
maxdb_stmt_result_metadata
MaxDB Func?ii
PHP Manual

maxdb_stmt_reset

maxdb_stmt::reset

(PECL maxdb >= 1.0)

maxdb_stmt_reset -- maxdb_stmt::reset — Anuleaza o declara?ie pregatita anterior

Descrierea

Stil procedural

bool maxdb_stmt_reset ( resource $stmt )

Stil obiect-orientat

bool maxdb_stmt::reset ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

maxdb_stmt_prepare
maxdb_stmt_result_metadata
MaxDB Func?ii


Returns result set metadata from a prepared statement

maxdb_stmt_reset
maxdb_stmt_send_long_data
MaxDB Func?ii
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

Descrierea

Stil procedural

resource maxdb_stmt_result_metadata ( resource $stmt )

Stil obiect-orientat

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.

Nota:

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()

Nota:

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().

Valorile întoarse

maxdb_stmt_result_metadata() returns a result resource or FALSE if an error occurred.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Fieldname: ID

A se vedea ?i

  • 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 Func?ii


Send data in blocks

maxdb_stmt_result_metadata
maxdb_stmt_sqlstate
MaxDB Func?ii
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

Descrierea

Stil procedural

bool maxdb_stmt_send_long_data ( resource $stmt , int $param_nr , string $data )

Stil obiect-orientat

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.

Nota:

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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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 Func?ii


Returns SQLSTATE error from previous statement operation

maxdb_stmt_send_long_data
maxdb_stmt_store_result
MaxDB Func?ii
PHP Manual

maxdb_stmt_sqlstate

(PECL maxdb >= 1.0)

maxdb_stmt_sqlstate — Returns SQLSTATE error from previous statement operation

Descrierea

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.

Nota:

Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Valorile întoarse

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: 42000.

A se vedea ?i

  • 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 Func?ii


Transfers a result set from a prepared statement

maxdb_stmt_sqlstate
maxdb_store_result
MaxDB Func?ii
PHP Manual

maxdb_stmt_store_result

maxdb_stmt::store_result

(PECL maxdb >= 1.0)

maxdb_stmt_store_result -- maxdb_stmt::store_result — Transfers a result set from a prepared statement

Descrierea

Stil procedural

bool maxdb_stmt_store_result ( resource $stmt )

Stil obiect-orientat

object maxdb_stmt::store_result ( void )

maxdb_stmt_store_result() has no functionally effect and should not be used for retrieving data from MaxDB server.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Number of rows: 25.

A se vedea ?i

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_result_metadata() - Returns result set metadata from a prepared statement
  • maxdb_fetch() - Pseudonim pentru maxdb_stmt_fetch

maxdb_stmt_sqlstate
maxdb_store_result
MaxDB Func?ii


Transfers a result set from the last query

maxdb_stmt_store_result
maxdb_thread_id
MaxDB Func?ii
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

Descrierea

Stil procedural

resource maxdb_store_result ( resource $link )

Stil obiect-orientat

object maxdb::store_result ( void )

This function has no functionally effect.

Valorile întoarse

Returns a result resource or FALSE if an error occurred.

Exemple

See maxdb_multi_query().

A se vedea ?i

  • maxdb_real_query() - Execute an SQL query
  • maxdb_use_result() - Initiate a result set retrieval

maxdb_stmt_store_result
maxdb_thread_id
MaxDB Func?ii


Returns the thread ID for the current connection

maxdb_store_result
maxdb_thread_safe
MaxDB Func?ii
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

Descrierea

Stil procedural

int maxdb_thread_id ( resource $link )

Stil obiect-orientat

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.

Nota:

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.

Valorile întoarse

maxdb_thread_id() returns the Thread ID for the current connection.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Warning: maxdb_query(): -10821 Session not connected <...>
Error: Session not connected

A se vedea ?i

  • maxdb_kill() - Disconnects from a MaxDB server

maxdb_store_result
maxdb_thread_safe
MaxDB Func?ii


Întoarce informa?ia despre faptul daca protec?ia firelor de execu?ie este activata sau nu

maxdb_thread_id
maxdb_use_result
MaxDB Func?ii
PHP Manual

maxdb_thread_safe

(PECL maxdb >= 7.6.06.04)

maxdb_thread_safe — Întoarce informa?ia despre faptul daca protec?ia firelor de execu?ie este activata sau nu

Descrierea

bool maxdb_thread_safe ( void )

maxdb_thread_safe() indica daca biblioteca-client este compilata cu protec?ia firelor de execu?ie.

Valorile întoarse

TRUE daca biblioteca-client sus?ine protec?ia firelor de execu?ie, în caz contrar FALSE.

maxdb_thread_id
maxdb_use_result
MaxDB Func?ii


Initiate a result set retrieval

maxdb_thread_safe
maxdb_warning_count
MaxDB Func?ii
PHP Manual

maxdb_use_result

maxdb::use_result

(PECL maxdb >= 1.0)

maxdb_use_result -- maxdb::use_result — Initiate a result set retrieval

Descrierea

Stil procedural

resource maxdb_use_result ( resource $link )

Stil obiect-orientat

resource maxdb::use_result ( void )

maxdb_use_result() has no effect.

Valorile întoarse

Returns result sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

a

A se vedea ?i

  • 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 Func?ii


Returns the number of warnings from the last query for the given link

maxdb_use_result
Mongo
MaxDB Func?ii
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

Descrierea

Stil procedural

int maxdb_warning_count ( resource $link )

Stil obiect-orientat

int $maxdb->warning_count;

maxdb_warning_count() returns the number of warnings from the last query in the connection represented by the link parameter.

Valorile întoarse

Number of warnings or zero if there are no warnings.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Warning: maxdb_query(): -8004 POS(62) Constant must be compatible with column type and length <...>
Number of warning: 0

A se vedea ?i

  • 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 Func?ii


Driver-ul MongoDB (învechit)

  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
  • Constante predefinite
  • Manual
    • Tutorial
    • Read Preferences
    • Write Concerns
    • SQL to Mongo Mapping Chart
    • Connecting
    • Stream Context Options
    • Writes
    • Querying
    • Updates
    • Security
    • Troubleshooting
    • Running the Driver's Tests
  • Clase de baza
    • MongoClient — The MongoClient class
    • MongoDB — The MongoDB class
    • MongoCollection — The MongoCollection class
    • MongoCursor — The MongoCursor class
    • MongoCursorInterface — The MongoCursorInterface interface
    • MongoCommandCursor — The MongoCommandCursor 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
  • Clase GridFS
    • MongoGridFS — The MongoGridFS class
    • MongoGridFSFile — The MongoGridFSFile class
    • MongoGridFSCursor — The MongoGridFSCursor class
  • Clase pentru opera?iuni în lot (batch)
    • MongoWriteBatch — The MongoWriteBatch class
    • MongoInsertBatch — The MongoInsertBatch class
    • MongoUpdateBatch — The MongoUpdateBatch class
    • MongoDeleteBatch — The MongoDeleteBatch class
  • Diverse
    • MongoLog — The MongoLog class
    • MongoPool — The MongoPool class
    • Mongo — The Mongo class [deprecated]
  • Func?ii Mongo
    • bson_decode — Deserializes a BSON object into a PHP array
    • bson_encode — Serializes a PHP variable into a BSON string
  • Excep?ii
    • MongoException — The MongoException class
    • MongoResultException — The MongoResultException class
    • MongoCursorException — The MongoCursorException class
    • MongoCursorTimeoutException — The MongoCursorTimeoutException class
    • MongoConnectionException — The MongoConnectionException class
    • MongoGridFSException — The MongoGridFSException class
    • MongoDuplicateKeyException — The MongoDuplicateKeyException class
    • MongoProtocolException — The MongoProtocolException class
    • MongoExecutionTimeoutException — The MongoExecutionTimeoutException class
    • MongoWriteConcernException — The MongoWriteConcernException class
  • Jurnalul modificarilor
maxdb_warning_count
Instalarea / configurarea
Extensii de lucru cu baze de date specifice anumitor producatori


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
Avertizare

Aceasta extensie este învechita. În loc, trtebuie utilizata extensia MongoDB.

Mongo
Necesita?i
Mongo


Instalarea

Avertizare

Aceasta extensie este învechita. În loc, trtebuie utilizata extensia MongoDB.

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.3 through 5.6 (versions prior to 1.6 also support PHP 5.2).

Aceasta extensie » PECL nu este încorporata în PHP.

  • Manual Installation
  • Installing on *NIX
  • Installing on Windows
  • OS X
  • Gentoo
  • Red Hat
  • Third-Party Installation Instructions

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
$ make all
$ sudo make install

Make the following changes to php.ini:

  • Make sure the extension_dir variable is pointing to the directory containing 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-non-zts-20060613/mongo.so'
    Make sure that it is the same as the PHP extension directory by running:
    $ php -i | grep extension_dir
  extension_dir => /usr/lib/php/extensions/no-debug-non-zts-20060613 =>
                   /usr/lib/php/extensions/no-debug-non-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

Installing on *NIX

Run:

$ sudo pecl install mongo

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 128MB.

Installing on Windows

Precompiled binaries for each release are available from » PECL 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).

Add the following line to your php.ini file:

extension=php_mongo.dll

Nota: Additional DLL dependencies for Windows Users

Pentru ca aceasta extensie sa func?ioneze, anumite fi?iere DLL trebuie sa fie accesibile în calea de sistem a Windows din variabila PATH. Pentru informa?ii despre cum poate fi realizat acest lucru, accesa?i FAQ întitulat " Cum sa adaug directorul meu PHP la variabila PATH din Windows" pentru informa?ii despre cum sa realiza?i aceasta. Cu toate ca copierea fi?ierelor DLL din directorul PHP în directorul de sistem al Windows de asemenea func?ioneaza (deoarece directorul de sistem este în mod implicit inclus în variabila PATH), acest lucru nu este recomandabil. Aceasta extensie necesita ca urmatoarele fi?iere sa existe în calea PATH : libsasl.dll

OS X

In most cases installing from pecl is the easiest way:

$ sudo pecl install mongo

If you are using » Homebrew, the PHP tap includes formulae for the driver. For example, you might install the driver for PHP 5.6 using the following command:

$ brew install php56-mongo

If you are using » XAMPP, note that it has its own pecl binary and php.ini configuration. You should be able to install the driver with the following command:

$ sudo /Applications/XAMPP/xamppfiles/bin/pecl install mongo

Nota: Xcode dependency for compiling on OS X

Compiling the driver on OS X will require Xcode developer tools, which may be installed with xcode-select --install. If that command is not available, you may first need to install the » Command Line Tools package.

Gentoo

Gentoo has a package for the PHP PECL driver called dev-php/pecl-mongo, which can be installed with:

$ sudo emerge -va dev-php/pecl-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
$ sudo 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.)

Third-Party Installation Instructions

A number of people have created excellent tutorials on installing the PHP driver.

  • » (Re)installing PHP on Mac OS X

    This article by Justin Hileman details the process of installing PHP and additional extensions with Homebrew on OS X. This complements the earlier instructions on this page for installing the driver with Homebrew.

  • » PHP 5.3.1 with Xdebug, MongoDB and Lithium on Ubuntu 9.10 / Apache 2.2

    This screencast by Jon Adams demonstrates how to quickly get up and running with PHP 5.3.1, Xdebug, and MongoDB on Ubuntu 9.10 with Apache.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Mongo Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
mongo.allow_empty_keys | 0 | PHP_INI_ALL |
mongo.allow_persistent | 1 | PHP_INI_ALL | Removed in 1.2.0
mongo.chunk_size | 262144 | PHP_INI_ALL |
mongo.cmd | "$" | PHP_INI_ALL |
mongo.default_host | "localhost" | PHP_INI_ALL |
mongo.default_port | 27017 | PHP_INI_ALL |
mongo.is_master_interval | 15 | PHP_INI_ALL | Added in 1.2.10, before 1.3.0 the default value was 60.
mongo.long_as_object | 0 | PHP_INI_ALL |
mongo.native_long | 1 | PHP_INI_ALL | Before 1.5.0, the default value was 0.
mongo.ping_interval | 5 | PHP_INI_ALL | Added in 1.2.10
mongo.utf8 | 1 | PHP_INI_ALL |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

mongo.allow_persistent int

If persistent connections are allowed. (Removed in 1.2.0 - all connections are now persistent).

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.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.is_master_interval int

Added in version 1.2.10.

For replicaset connections: The minimum interval with which the driver will send "isMaster" requests to the MongoDB server. If the value is lower, there will be more requests, but the driver finds faster whether the topology of the replicaset has been changed.

mongo.long_as_object int

Return a BSON_LONG as an instance of MongoInt64 (instead of a primitive type).

mongo.native_long int

The default behavior for this has been changed to TRUE in 1.5.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_long 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.ping_interval int

Added in version 1.2.10.

For replicaset connections: The minimum interval with which the driver will send "ping" requests to the MongoDB server. If the value is lower, there will be more pings, but the driver finds faster whether a node is no longer reachable from the replicaset.

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.

Instalarea
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

MONGO_STREAMS (integer)
Alias of MONGO_SUPPORTS_STREAMS
MONGO_SUPPORTS_STREAMS (integer)
1 when compiled against PHP Streams (default since 1.4.0).
MONGO_SUPPORTS_SSL (integer)
1 when OpenSSL is enabled and available.
MONGO_SUPPORTS_AUTH_MECHANISM_MONGODB_CR (integer)
1 when MongoDB-Challenge/Reponse authentication is compiled in.
MONGO_SUPPORTS_AUTH_MECHANISM_MONGODB_X509 (integer)
1 when x.509 authentication is compiled in.
MONGO_SUPPORTS_AUTH_MECHANISM_GSSAPI (integer)
1 when GSSAPI authentication is compiled in.
MONGO_SUPPORTS_AUTH_MECHANISM_PLAIN (integer)
1 when PLAIN authentication is compiled in.
MONGO_STREAM_NOTIFY_TYPE_IO_INIT (integer)
MONGO_STREAM_NOTIFY_TYPE_LOG (integer)
MONGO_STREAM_NOTIFY_IO_READ (integer)
MONGO_STREAM_NOTIFY_IO_WRITE (integer)
MONGO_STREAM_NOTIFY_IO_PROGRESS (integer)
MONGO_STREAM_NOTIFY_IO_COMPLETED (integer)
MONGO_STREAM_NOTIFY_LOG_INSERT (integer)
MONGO_STREAM_NOTIFY_LOG_QUERY (integer)
MONGO_STREAM_NOTIFY_LOG_UPDATE (integer)
MONGO_STREAM_NOTIFY_LOG_DELETE (integer)
MONGO_STREAM_NOTIFY_LOG_GETMORE (integer)
MONGO_STREAM_NOTIFY_LOG_KILLCURSOR (integer)
MONGO_STREAM_NOTIFY_LOG_BATCHINSERT (integer)
MONGO_STREAM_NOTIFY_LOG_RESPONSE_HEADER (integer)
MONGO_STREAM_NOTIFY_LOG_WRITE_REPLY (integer)
MONGO_STREAM_NOTIFY_LOG_CMD_INSERT (integer)
MONGO_STREAM_NOTIFY_LOG_CMD_UPDATE (integer)
MONGO_STREAM_NOTIFY_LOG_CMD_DELETE (integer)
MONGO_STREAM_NOTIFY_LOG_WRITE_BATCH (integer)

Configura?ia la rulare
Manual
Mongo


Manual

Cuprins

  • Tutorial
  • Read Preferences
  • Write Concerns
  • SQL to Mongo Mapping Chart
  • Connecting
  • Stream Context Options
  • Writes
  • Querying
  • Updates
  • Security
  • Troubleshooting
  • Running the Driver's Tests
Avertizare

Aceasta extensie este învechita. În loc, trtebuie utilizata extensia MongoDB.

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.

Constante predefinite
Tutorial
Mongo


Tutorial

Cuprins

  • Making a Connection
  • Getting a Database
  • Getting A Collection
  • Inserting a Document
  • Finding Documents using MongoCollection::findOne
  • Adding Multiple Documents
  • Counting Documents in A Collection
  • Using a Cursor to Get All of the Documents
  • Setting Criteria for a Query
  • Getting A Set of Documents With a Query
  • Creating An Index
Avertizare

Aceasta extensie este învechita. În loc, trtebuie utilizata extensia MongoDB.

This is the official MongoDB driver for PHP.

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 MongoClient();

// select a database
$db = $m->comedy;

// select a collection (analogous to a relational database's table)
$collection = $db->cartoons;

// add a record
$document = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($document);

// add another record, with a different "shape"
$document = array( "title" => "XKCD", "online" => true );
$collection->insert($document);

// find everything in the collection
$cursor = $collection->find();

// iterate through the results
foreach ($cursor as $document) {
    echo $document["title"] . "\n";
}

?>

Exemplul de mai sus va afi?a:

Calvin and Hobbes
XKCD
Manual
Making a Connection
Manual


Making a Connection

To connect to the database server, use one of the following:

<?php
$connection = new MongoClient(); // connects to localhost:27017
$connection = new MongoClient( "mongodb://example.com" ); // connect to a remote host (default port: 27017)
$connection = new MongoClient( "mongodb://example.com:65432" ); // connect to a remote host at a given port
?>

You do not have to explicitly disconnect from the database. The driver uses persistent connections and will re-use already established connections.

See Also

The chapter on connecting covers different types of connections.

The API documentation on the MongoClient class and MongoClient::__construct() give a comprehensive look at all possible options with a number of examples.

Tutorial
Getting a Database
Tutorial


Getting a Database

To select a database, use:

<?php
$connection = new MongoClient();
$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 (here name is misspelled as anme in the second selection:

<?php
$connection = new MongoClient();

$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.

Making a Connection
Getting A Collection
Tutorial


Getting A Collection

Getting a collection has the same syntax as getting a database:

<?php
$connection = new MongoClient();
$db = $connection->baz;

// select a collection:
$collection = $db->foobar;

// or, directly selecting a database and collection:
$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.

Getting a Database
Inserting a Document
Tutorial


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. The driver will always store an associative array as an object in the database. A numerically indexed array is stored as an array in case the keys start at 0 and are not interrupted, and as an object if the array keys don't start at 0 or have gaps (ie: 0, 1, 4, 5).

To insert this document, use MongoCollection::insert():

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$collection->insert( $doc );
?>

See Also

The API documentation on MongoCollection::insert() contains more information about inserting data.

Getting A Collection
Finding Documents using MongoCollection::findOne
Tutorial


Finding Documents using MongoCollection::findOne

Inserting a Document
Adding Multiple Documents
Tutorial
PHP Manual

Finding Documents using MongoCollection::findOne()

To show that the document we inserted in the previous step is stored in the database, we can do a simple MongoCollection::findOne() operation to get a single document from the collection. This method is useful when there is only one document matching the query or you are only interested in one result.

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$document = $collection->findOne();
var_dump( $document );
?>

Exemplul de mai sus va afi?a:

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
$connection = new MongoClient();
$db = $connection->database;

$db->foo->insert(array("_id" => 1));
// this will throw an exception
$db->foo->insert(array("_id" => 1));

// this is fine, as it is a different collection
$db->bar->insert(array("_id" => 1));
?>

By default the driver will ensure the server has acknowledged the write before returning. You can optionally turn this behaviour off by passing array("w" => 0) as the second argument. This means that the driver should not wait for the database to acknowledge the write and would not throw the duplicate _id exception.

See Also

MongoCollection::findOne() for more information about finding data.

MongoId goes into more detail on unique ids.

The writes section covers writes in more depth, and the Write Concerns chapter goes into details of the various Write Concern options.

Inserting a Document
Adding Multiple Documents
Tutorial


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
$connection = new MongoClient();
$collection = $connection->database->collectionName;

for ( $i = 0; $i < 100; $i++ )
{
    $collection->insert( array( 'i' => $i, "field{$i}" => $i * 2 ) );
}
?>

Notice that we can insert arrays with different keys into the same collection. This aspect is what we mean when we say that MongoDB is "schema-free". In the example above each document has an i field, but also a field name in the form of field + $i.

Finding Documents using MongoCollection::findOne
Counting Documents in A Collection
Tutorial


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
$connection = new MongoClient();
$collection = $connection->database->collectionName;

echo $collection->count();
?>
and it should print 101.

Adding Multiple Documents
Using a Cursor to Get All of the Documents
Tutorial


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
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$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.

Counting Documents in A Collection
Setting Criteria for a Query
Tutorial


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
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$query = array( 'i' => 71 );
$cursor = $collection->find( $query );

while ( $cursor->hasNext() )
{
    var_dump( $cursor->getNext() );
}
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["i"]=>
  int(71)
  ["_ns"]=>
  "testCollection"
}
Using a Cursor to Get All of the Documents
Getting A Set of Documents With a Query
Tutorial


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
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$query = array( "i" => array( '$gt' => 50 ) ); //note the single quotes around '$gt'
$cursor = $collection->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
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$query = array( 'i' => array( '$gt' => 20, "\$lte" => 30 ) );
$cursor = $collection->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.

Setting Criteria for a Query
Creating An Index
Tutorial


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
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$collection->ensureIndex( array( "i" => 1 ) );  // create index on "i"
$collection->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.

Getting A Set of Documents With a Query
Read Preferences
Tutorial


Read Preferences

MongoDB 2.2 and version 1.3.0 of the driver add support for » read preferences, which allow control over how queries are directed to mongod instances in a replica set environment. Read preferences may be specified on either a per-connection, per-database, or per-collection basis. Preferences defined at a higher level will be inherited by default (e.g. MongoCollection will inherit read preferences defined on the corresponding MongoDB instance).

Read preferences are specified with a combination of modes and tag sets. Modes determine how mongod instances are prioritized, while » tag sets specify criteria for eligible mongod instances. Mongod instances are only eligible if they are within a 15ms difference in ping time from the nearest mongod instance.

Read Preference Modes

Avertizare

All read preference modes except MongoClient::RP_PRIMARY may return stale data as secondaries replicate operations from the primary with some delay. Ensure that your application can tolerate stale data if you choose to use a mode other than MongoClient::RP_PRIMARY.

  • MongoClient::RP_PRIMARY

    All read operations use only the current replica set primary. This is the default. If the primary is unavailable, read operations will produce an exception.

    This mode is incompatible with use of tag sets. Specifying a tag set with MongoClient::RP_PRIMARY will result in an exception.

  • MongoClient::RP_PRIMARY_PREFERRED

    In most situations, operations read from the primary member of the set. However, if the primary is unavailable, as is the case during failover situations, operations read from secondary members.

    When the read preference includes a tag set, the client reads first from the primary, if available, and then from secondaries that match the specified tags. If no secondaries have matching tags, the read operation will produce an exception.

    Avertizare

    Version 2.2 of mongos added full support for read preferences. When connecting to older mongos instances, MongoClient::RP_PRIMARY_PREFERRED will send queries to secondaries.

  • MongoClient::RP_SECONDARY

    Operations read only from the secondary members of the set. If no secondaries are available, read operations will produce an exception.

    Most sets have at least one secondary, but there are situations where there may be no available secondary. For example, a set with a primary, a secondary, and an arbiter may not have any secondaries if a member is in recovering state or unavailable.

    When the read preference includes a tag set, the client attempts to find secondary members that match the specified tag set and directs reads to a random secondary from among the nearest group. If no secondaries have matching tags, the read operation will produce an exception.

  • MongoClient::RP_SECONDARY_PREFERRED

    In most situations, operations read from secondary members, but in situations where the set consists of a single primary with no other members, the read operation will use the set's primary.

    When the read preference includes a tag set, the client attempts to find a secondary member that matches the specified tag set and directs reads to a random secondary from among the nearest group. If no secondaries have matching tags, the read operation will produce an exception.

  • MongoClient::RP_NEAREST

    The driver reads from a random member of the set that has a ping time that is less than 15ms slower than the member with the lowest ping time. Reads in the MongoClient::RP_NEAREST mode do not consider the member's type and may read from both primaries and secondaries.

    Set this mode to minimize the effect of network latency on read operations without preference for current or stale data.

    If you specify a tag set, the client attempts to find a member that matches the specified tag set and directs reads to a random node from among the nearest group.

    Nota:

    All operations read from the nearest member of the replica set that matches the specified read preference mode. The MongoClient::RP_NEAREST mode prefers low latency reads over a member's primary or secondary status.

Tag Sets

» Tag sets allow you to specify criteria so that your application can target read operations to specific members, based on custom parameters. Tag sets make it possible to ensure that read operations target members in a particular data center or target mongod instances designated for a particular class of operations, such as reporting or analytics.

You can specify tag sets with the following read preference modes:

  • MongoClient::RP_PRIMARY_PREFERRED

  • MongoClient::RP_SECONDARY

  • MongoClient::RP_SECONDARY_PREFERRED

  • MongoClient::RP_NEAREST

You cannot specify tag sets with the MongoClient::RP_PRIMARY read preference mode. Tags apply only when selecting a secondary member of a set, except for the when in the nearest mode.

Specifying Read Preferences

Read preferences may be specified in either the connection URI provided to MongoClient::__construct(), which uses a query string syntax, or via setter methods on the core classes, which use an array syntax for tag sets.

When specifying read preference modes in a query string, the tag sets for the readPreferenceTags value should be a comma-delimited sequence of colon-delimited key/value pairs.

Nota:

Each tag set defined in the query string will use the readPreferenceTags name. Unlike how PHP might handle URL query strings, successive values for readPreferenceTags will not overwrite each other. The driver will collect tag sets in the order they appear in the query string.

Avertizare

If the driver cannot find a matching tag set the read will fail! It is your responsibility of providing suitable fallback, such as an empty readPreferenceTags value to fallback to "no tag set preference".

Example #1 Connection URI read preferences with query string syntax

<?php
// Prefer the nearest server with no tag preference
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));

// Pick the nearest server in the "east" data center
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east,use:reporting';
$uri .= '&readPreferenceTags=dc:west';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));

// Prefer the nearest server in the "east" data center, then a server in the
// "west" data center, and finally fall back to no tag set preference
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$uri .= '&readPreferenceTags=dc:west';
$uri .= '&readPreferenceTags=';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
?>

Example #2 Setting read preferences with array syntax for tag sets

<?php

$m = new MongoClient('mongodb://rs1.example.com,rs2.example.com', array(
    'replicaSet' => 'rs',
));

// Prefer the nearest server with no tag preference
$m->setReadPreference(MongoClient::RP_NEAREST, array());

// Pick the nearest server in the "east" data center
$m->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east'),
));

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$m->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));

// Prefer the nearest server in the "east" data center, then a server in the
// "west" data center, and finally fall back to no tag set preference
$m->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east'),
    array('dc' => 'west'),
    array(),
));
?>

Creating An Index
Write Concerns
Manual


Write Concerns

MongoDB provides several different ways of selecting how durable a write to the database should be. These ways are called Write Concerns and span everything from completely ignoring all errors, to specifically targetting which servers are required to confirm the write before returning the operation.

When a write (such as with MongoCollection::insert(), MongoCollection::update(), and MongoCollection::remove()) is given a Write Concern option ("w") the driver will send the query to MongoDB and piggy back a getLastError command (GLE) with the Write Concern option at the same time. The server only returns when the Write Concern condition is verified to be fullfilled, or the query times out (controlled with the "wtimeout" option, 10000 milliseconds is the default).

Avertizare

Even though a getLastError command times out the data will most likely have been written to the primary server and will be replicated to all the secondaries once they have cought up.

The typical reasons for a timeout to happen is if you specify a Write Concern which requires confirmation from more servers then you currently have available.

When using acknowledged writes and the replica set has failed over, the driver will automatically disconnect from the primary, throw an exception, and attempt to find a new primary on the next operation (your application must decide whether or not to retry the operation on the new primary).

When using unacknowledged writes (w=0) and the replica set has failed over, there will be no way for the driver to know about the change so it will continue and silently fail to write.

The default Write Concern for the MongoClient is 1: acknowledge write operations.

Available Write Concerns
Write Concern | Meaning | Description
w=0 | Unacknowledged | A write will not be followed up with a GLE call, and therefore not checked ("fire and forget")
w=1 | Acknowledged | The write will be acknowledged by the server (the primary on replica set configuration)
w=N | Replica Set Acknowledged | The write will be acknowledged by the primary server, and replicated to N-1 secondaries.
w=majority | Majority Acknowledged | The write will be acknowledged by the majority of the replica set (including the primary). This is a special reserved string.
w=<tag set> | Replica Set Tag Set Acknowledged | The write will be acknowledged by members of the entire tag set
j=true | Journaled | The write will be acknowledged by primary and the journal flushed to disk

Using WriteConcerns

Each of the methods that causes writes (MongoCollection::insert(), MongoCollection::update(), MongoCollection::remove(), and MongoCollection::batchInsert()) allow an optional argument to send a set of options to the MongoDB server. With this option array you can set the WriteConcern as the following example illustrates:

Example #1 Passing a WriteConcern to a write operation

<?php
// Setting w=0 for insert:
$collection->insert($someDoc, array("w" => 0));

// Setting w=majority for update:
$collection->update($someDoc, $someUpdates, array("w" => "majority"));

// Setting w=5 and j=true for remove:
$collection->update($someDoc, array("w" => 5, "j" => true));

// Setting w="AllDCs" for batchInsert:
$collection->update(array($someDoc1, $someDoc2), array("w" => "AllDCs"));
?>

Besides setting WriteConcerns per operation as an option argument, it is also possible to set a default WriteConcern in different ways.

The first way is through the connection string. The connection string accepts the journal, w, and wTimeoutMS options:

Example #2 Connection string WriteConcerns

<?php
$m = new MongoClient("mongodb://localhost/?journal=true&w=majority&wTimeoutMS=20000");
?>

Since driver version 1.5 it is also possible to call MongoDB::setWriteConcern() and MongoCollection::setWriteConcern() to set a default WriteConcern for all operations created from that specific MongoDB or MongoCollection object:

Example #3 MongoDB::setWriteConcern and MongoCollection::setWriteConcern

<?php
$m = new MongoClient("mongodb://localhost/");
$d = $m->demoDb;
$c = $d->demoCollection;

// Set w=3 on the database object with a timeout of 25000ms
$d->setWriteConcern(3, 25000);

// Set w=majority on the collection object without changing the timeout
$c->setWriteConcern("majority");
?>

Unacknowledged Writes

By not requiring the server to acknowledge writes the 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; or duplicate key errors).

While developing, you should always use acknowledged writes (to protect against inadvertent mistakes, such as syntax errors, invalid operators, duplicate key errors and so on). In production, unacknowledged 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.

It is strongly recommended that you do an acknowledged write at the end of series of unacknowledged writes. Doing so will not incur in a too large performance penalty, but still allow you to catch any errors that may have occurred.

Example #4 Unacknowledged WriteConcern, followed with Acknowledged Write

<?php
$collection->insert($someDoc, array("w" => 0));
$collection->update($criteria, $newObj, array("w" => 0));
$collection->insert($somethingElse, array("w" => 0));
try {
    $collection->remove($something, array("w" => 1));
} catch(MongoCursorException $e) {
    /* Handle the exception.. */
    /* Here we should issue find() queries on the IDs generated for
    $somethingElse and $someDoc to verify they got written to the database and
    attempt to figureout where in the chain something happened. */
}
?>

If the last write throws an exception, you know that there's a problem with your database.

Acknowledged Writes

These type of write operations will make sure that the database has accepted the write operation before returning success. If the write failed, it will throw a MongoCursorException with an explanation of the failure. The MongoClient default behaviour is to acknowledge the write (w=1).

It is possible to specify how many members of an replica set have to acknowledge the write (i.e. have it replicated) before the write is deemed acknowledged and the operation returns.

Example #5 Acknowledged Writes

<?php
// Force acknowledgement from the primary only
$collection->insert($doc, array("w" => 1));

// Force acknowledgement from the primary, and one other member of the
// replica set
$collection->insert($doc, array("w" => 2));

// Force acknowledgement from the primary, and six other members of the
// replica set (you probably never should do this):
$collection->insert($doc, array("w" => 7));
?>

Keep in mind to select your Write Concern carefully. If you have a replica set with 5 members, and you select Write Concern of 4 you will risk the write blocking forever when one member of the replica set goes down for maintenance or a temporary network outage happens.

Avertizare

Passing in a string value for Write Concern has a specific meaning (Replica Set Tag Set Acknowledged). Please be careful of NOT using string values for numbers (i.e. array("w" => "1")) as it will be treated as a tag set name.

Majority Acknowledged Writes

Using the special majority Write Concern option is the recommended way for writes that are required to survive the apocalypse, as it will ensure the majority of your replica set will have the write and will therefore be guaranteed to survive all usual suspect outage scenarios.

Example #6 Majority Acknowledged Write

<?php
$collection->insert($someDoc, array("w" => "majority"));
?>

Journaled Writes

When connecting to a replica set the default Write Concern is only to have the primary server acknowledge the write. There is however a 100ms window until the write gets journaled and flushed to disk. It is possible to force the write to be journaled before acknowledging the write by setting the j option:

Example #7 Acknowledged and Journaled Write

Forcing journal flush

<?php
$options = array(
    "w" => 1,
    "j" => true,
);
try {
    $collection->insert($document, $options);
} catch(MongoCursorException $e) {
    /* handle the exception */
}
?>

A se vedea ?i

  • » MongoDB WriteConcern docs

Istoricul schimbarilor

Versiune | Descriere
1.3.0 | MongoClient was introduced and defaults to acknowledged writes. The deprecated Mongo defaults to unacknowledged writes.
1.3.0 | The "safe" write option has been deprecated and is not available with the new MongoClient class. Use the "w" option instead.
Read Preferences
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 20, 10 | $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"));

Write Concerns
Connecting
Manual


Connecting

Cuprins

  • Connecting over SSL
  • Authentication
  • Replica Sets
  • Sharding
  • Domain Socket Support
  • Persistent Connections (version 1.3.0+)
  • Connection Pooling (version 1.2.0-1.2.12 *only*)
  • Manually Persistent Connections (version up to 1.1.4 *only*)

Connecting to MongoDB can be as easy as new MongoClient, but there are many additional options and configurations. The documentation for MongoClient::__construct() covers all of the API options, but this page gives some more details and advice for practical use cases.

SQL to Mongo Mapping Chart
Connecting over SSL
Manual


Connecting over SSL

The driver supports connecting to » MongoDB over SSL and can optionally use SSL Stream Context options to provide more details, such as verifying certificates against specific certificate chain, or authenticate to » MongoDB using X509 certificates.

Example #1 Connect to MongoDB Instance with SSL Encryption

<?php
$mc = new MongoClient("mongodb://server1", array("ssl" => true));
?>

Example #2 Connect to MongoDB Instance with SSL Encryption, verifying it is who we think it is

<?php
$SSL_DIR = "/vagrant/certs";
$SSL_FILE = "CA_Root_Certificate.pem";

$ctx = stream_context_create(array(
    "ssl" => array(
        /* Certificate Authority the remote server certificate must be signed by */
        "cafile"            => $SSL_DIR . "/" . $SSL_FILE,

        /* Disable self signed certificates */
        "allow_self_signed" => false,

        /* Verify the peer certificate against our provided Certificate Authority root certificate */
        "verify_peer"       => true, /* Default to false pre PHP 5.6 */

        /* Verify the peer name (e.g. hostname validation) */
        /* Will use the hostname used to connec to the node */
        "verify_peer_name"  => true,

        /* Verify the server certificate has not expired */
        "verify_expiry"     => true, /* Only available in the MongoDB PHP Driver */
    ),
);

$mc = new MongoClient(
    "mongodb://server1",
    array("ssl" => true),
    array("context" => $ctx)
);
?>

Nota:

The "verify_peer_name" is new in PHP 5.6.0. The MongoDB driver as of 1.6.5 however has backported this feature into the driver itself, so it works with PHP 5.3 and 5.4 too

Example #3 Connect to MongoDB Instance that Requires Client Certificates

<?php
$SSL_DIR  = "/vagrant/certs";
$SSL_FILE = "CA_Root_Certificate.pem";

$MYCERT   = "/vagrant/certs/ca-signed-client.pem";

$ctx = stream_context_create(array(
    "ssl" => array(
        "local_cert"        => $MYCERT,
        /* If the certificate we are providing was passphrase encoded, we need to set it here */
        "passphrase"        => "My Passphrase for the local_cert",

        /* Optionally verify the server is who he says he is */
        "cafile"            => $SSL_DIR . "/" . $SSL_FILE,
        "allow_self_signed" => false,
        "verify_peer"       => true,
        "verify_peer_name"  => true,
        "verify_expiry"     => true,
    ),
));

$mc = new MongoClient(
    "mongodb://server1/?ssl=true",
    array(),
    array("context" => $ctx)
);
?>

Example #4 Authenticating with X.509 certificates

The username is the certificate subject from the X509, which can be extracted like this:

openssl x509 -in /vagrant/certs/ca-signed-client.pem -inform PEM -subject -nameopt RFC2253
<?php
$ctx = stream_context_create( array(
    "ssl" => array(
        "local_cert" => "/vagrant/certs/ca-signed-client.pem",
    )
) );

$mc = new MongoClient(
    'mongodb://username@server1/?authSource=$external&authMechanism=MONGODB-X509&ssl=true',
    array(),
    array("context" => $ctx)
);
?>

Where username is the certificate subject.

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Added support for X509 authentication.
1.4.0 | Added support for connecting to SSL enabled MongoDB.
Connecting
Authentication
Connecting


Authentication

If MongoDB is started with the --auth or --keyFile options, you must authenticate before you can do any operations with the driver. You may authenticate a connection by specifying the username and password in either the connection URI or the "username" and "password" options for MongoClient::__construct().

Example #1 Authenticating against the "admin" database

<?php
// Specifying the username and password in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost");

// Specifying the username and password via the options array (alternative)
$m = new MongoClient("mongodb://localhost", array("username" => $username, "password" => $password));
?>

By default, the driver will authenticate against the admin database. You may authenticate against a different database by specifying it in either the connection URI or the "db" option for MongoClient::__construct().

Example #2 Authenticating against normal databases

<?php
// Specifying the authentication database in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost/myDatabase");

// Specifying the authentication database via the options array (alternative)
$m = new MongoClient("mongodb://${username}:${password}@localhost", array("db" => "myDatabase"));
?>

If your connection is dropped, the driver will automatically attempt to reconnect and reauthenticate you.

Connecting over SSL
Replica Sets
Connecting


Replica Sets

To connect to a replica set, specify one or more members of the set and use the "replicaSet" option. Multiple servers may be delimited by a comma.

Example #1 ReplicaSet seed list

<?php
// Using multiple servers as the seed list (prefered)
$m = new MongoClient("mongodb://rs1.example.com:27017,rs2.example.com:27017/?replicaSet=myReplSetName");

// Using one server as the seed list
$m = new MongoClient("mongodb://rs1.example.com:27017", array("replicaSet" => "myReplSetName"));

// Using multiple servers as the seed list
$m = new MongoClient("mongodb://rs1.example.com:27017,rs2.example.com:27017", array("replicaSet" => "myReplSetName"));
?>

The PHP driver will query the database server(s) listed to determine the primary. So long as it can connect to at least one host listed and find a primary, the connection will succeed. If it cannot make a connection to any servers listed or cannot find a primary, a MongoConnectionException will be thrown.

Sfat

You should always provide a seed list with more than one member of the ReplicaSet. For highest availability you should seed with at least one server from each of your datacenters.

Avertizare

The host names that you specify in the seed list must match the host names in the replica set configuration. This is because the driver only uses the host names in the replica set configuration to create the hash for its persistent connections.

For example, if an IP address is used in the seed list and the replica set is configured with host names, the driver will discard any seed list connection(s) that differ from the canonical host names reported by the replica set. Effectively, these non-canonical seed list connections will be recreated on each request, greatly reducing the benefit of using persistent connections.

Avertizare

The driver does not support connecting to different replica sets with the same name. This extends beyond one script so make sure to have separate names for each of your replica sets. That also means that you can not do this:

Example #2 Wrong replica set name duplication

<?php
$m = new MongoClient("mongodb://devserver1,devserver2,devserver3/?replicaSet=repset");
$m = new MongoClient("mongodb://prodserver1,prodserver2,prodserver3/?replicaSet=repset");
?>

Instead, you need to have two different names for your replica sets:

Example #3 Correct use of two replica set names

<?php
$m = new MongoClient("mongodb://devserver1,devserver2,devserver3/?replicaSet=devset");
$m = new MongoClient("mongodb://prodserver1,prodserver2,prodserver3/?replicaSet=prodset");
?>

If the primary becomes unavailable, an election will take place and a secondary will be promoted to the role of primary (unless a majority vote cannot be established). During this time (» 20-60 seconds), the connection will not be able to perform any write operations and attempts to do so will result in an exception. Connections to secondaries will still be able to perform reads.

Nota:

The default Read Preference is to only read from the primary. During the election process there is no primary, and all read will therefore fail.

It is recommended to use MongoClient::RP_PRIMARY_PREFERRED Read Preference for applications that require high availability for reads, as reads will only be executed on the secondaries when there simply isn't a primary available.

Once a primary is elected, attempting to perform a read or write will allow the driver to detect the new primary. The driver will make this its primary database connection and continue operating normally.

The health and state of a secondary is checked every 5 seconds (configurable with mongo.ping_interval) or when the next operation occurs after 5 seconds. It will also recheck the configuration when the driver has a problem reaching a server.

Replica set failovers are checked every 60 seconds (configurable with mongo.is_master_interval), and whenever a write operation fails when using acknowledged writes.

Precautie

Secondaries may be behind the primary in operations, so your application must be able to handle out-of-date data when using Read Preferences other then MongoClient::RP_PRIMARY.

For more information on replica sets, see the » core documentation.

A se vedea ?i

  • Read Preferences
  • Write Concerns

Istoricul schimbarilor

Versiune | Descriere
1.0.9 | Added support for connecting to ReplicaSet and automatic failover.
Authentication
Sharding
Connecting


Sharding

To connect to a shard cluster, specify the address of one or more mongos instances in the connection string. Multiple servers may be delimited by a comma.

<?php
// Using one server as the seed list
$m = new MongoClient("mongodb://mongos1.example.com:27017");

// Using multiple servers as the seed list
$m = new MongoClient("mongodb://mongos1.example.com:27017,mongos2.example.com:27017");
?>

Regardless of whether each shard is a stand-alone mongod server or a full replica set, the driver's connection process is the same. All database communication will be routed through mongos.

For more information on sharding with MongoDB, see the » sharding documentation.

Replica Sets
Domain Socket Support
Connecting


Domain Socket Support

MongoDB has built-in support for connecting via Unix Domain Sockets and will open the socket on startup. By default, the socket is located in /tmp/mongodb-<port>.sock.

To connect to the socket file, specify the path in your MongoDB connection string:

<?php
$m = new MongoClient("mongodb:///tmp/mongo-27017.sock");
?>

If you would like to authenticate against a database (as described above) with a socket file, you must specify a port of 0 so that the connection string parser can detect the end of the socket path. Alternatively, you can use the constructor options.

<?php
$m = new MongoClient("mongodb://username:password@/tmp/mongo-27017.sock:0/foo");
?>

Istoricul schimbarilor

Versiune | Descriere
1.0.9 | Added support for Unix Domain Sockets.
Sharding
Persistent Connections (version 1.3.0+)
Connecting


Persistent Connections (version 1.3.0+)

All versions of the driver since 1.3.0 utilize persistent connections to minimize the number of connections made to each database server. These connections are saved by the PHP worker process and may be reused between multiple requests.

Before connecting to a database server, the driver will create a hash for the connection based on its host, port, replica set name (if any), any authentication credentials (e.g. username, password, database), and the process ID. If a connection already exists for that hash, it will be used in lieu of creating a new connection associated with that hash. MongoClient::getConnections() may be used to retrieve info about each persistent connection. Consider the following program:

<?php

$m1 = new MongoClient('mongodb://localhost');
$m2 = new MongoClient('mongodb://localhost');
$m3 = new MongoClient('mongodb://user:pw@localhost');
$m4 = new MongoClient('mongodb://127.0.0.1');
$m5 = new MongoClient('mongodb://rs1.local:30017,rs2.local:30018/?replicaSet=rs');
$m6 = new MongoClient('mongodb://sharding.local:40017');

foreach (MongoClient::getConnections() as $conn) {
    echo $conn['hash'], "\n";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

localhost:27017;-;X;15487
localhost:27017;-;admin/user/c56c…8bbc;15487
127.0.0.1:27017;-;X;15487
rs1.local:30017;rs;X;15487
rs2.local:30018;rs;X;15487
sharding.local:40017;-;X;15487

In this example $m1 and $m2 have the same hash and share a persistent connection. Connections for each other MongoClient instance hash to unique values and use their own sockets. Note that "localhost" and "127.0.0.1" do not share the same hash; DNS resolution is not taken into account.

Domain Socket Support
Connection Pooling (version 1.2.0-1.2.12 *only*)
Connecting


Connection Pooling (version 1.2.0-1.2.12 *only*)

Nota:

This section is no longer relevant as of the 1.3.0 release of the driver and only serves as a historical information on how the pooling used to work.

The latest versions of the driver have no concept of pooling anymore and will maintain only one connection per process, for each connection type (ReplicaSet/standalone/mongos), for each credentials combination.

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 MongoClient, all necessary connections will be taken from their pools (replica sets may require multiple connections, one for each member of the set). When the MongoClient 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 will be created. There are three factors in determining 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 of 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 will indicate how many PHP processes (i.e. 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 (version 1.3.0+)
Manually Persistent Connections (version up to 1.1.4 *only*)
Connecting


Manually Persistent Connections (version up to 1.1.4 *only*)

Nota:

This section is not relevant for 1.2.0+. In 1.2.0+, connections are always persistent and managed automatically by the driver. If you are using a 1.2.x release (but not 1.3.x or later), 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 MongoClient();
}

?>

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 MongoClient("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 authentication credentials (username, password and database, 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.

Connection Pooling (version 1.2.0-1.2.12 *only*)
Stream Context Options
Connecting


Stream Context Options

The PHP MongoDB extension provides Stream Context Support using the mongodb context.

A stream context must be created with stream_context_create() and passed to the MongoClient::__construct() before the actual connection to MongoDB is made. It is not possible to apply a stream context to already created streams.

Additional context options and parameters, such as ssl and notification parameters, are also supported.

The MongoDB context options provide a rich interface to log network traffic between the driver and the MongoDB servers. This interface can be used to provide query logging, profiler, debuggers, or anything that would need to inspect the underlaying commands and protocol options.

A se vedea ?i

  • SSL context options
  • Socket context options
  • Context parameters

Cuprins

  • log_cmd_delete — Callback When Deleting Documents
  • log_cmd_insert — Callback When Inserting Documents
  • log_cmd_update — Callback When Updating Documents
  • log_getmore — Callback When Retrieving Next Cursor Batch
  • log_killcursor — Callback When Executing KILLCURSOR operations
  • log_reply — Callback When Reading the MongoDB reply
  • log_write_batch — Callback When Writing Batches
Manually Persistent Connections (version up to 1.1.4 *only*)
log_cmd_delete
Manual


Callback When Deleting Documents

Stream Context Options
log_cmd_insert
Stream Context Options
PHP Manual

log_cmd_delete

(PECL mongo >= 1.5.0)

log_cmd_delete — Callback When Deleting Documents

Descrierea

log_cmd_delete ( array $server , array $writeOptions , array $deleteOptions , array $protocolOptions )

A callable function, used by the log_cmd_delete context option, when deleteing a document

Nota:

This is not a real function, only a prototype of how the function should be.

Parametri

server

Un tablou cu informa?iile de baza despre serverul ales.

cheie | valoare
hash | hash-ul serverului, de exemplu:localhost:27017;-;X;56052
type | Tipul nodului (primary/secondary/mongos/arbiter): 2
max_bson_size | Dimensiunea maximala BSON prin fir, pe care acest nod o accepta: 16777216
max_message_size | Dimensiunea maximala a mesajului prin fir, pe care acest nod o accepta: 48000000
request_id | Identificatorul interpelarii pentru acest mesaj: 42

writeOptions

cheie | valoare
ordered | Boolean, daca opera?iunea (în cazul unei opera?iuni în set) trebuie executata secven?ial (ordered=true)
writeConcern | Un tablou cu op?iuni writeConcern (a se vedea mai jos)
Valorile tabloului writeConcern
cheie | valoare
fsync | Boolean, for?eaza înscrierea pe disc înainte de a se întoarce
j | Boolean, for?eaza înscrierea jurnalului înainte de a se întoarce
wtimeout | integer, milisecunde, timpul maximal care îi este acordat primarului ca sa verifice replicarea
w | integer=numarul de servere, sau string=eticheta de replicare

deleteOptions

key | value
limit | integer, 1 or 0. If 0, delete all matching documents.
q | Array, the search criteria

protocolOptions

cheie | valoare
message_length | Dimensiunea totala (în octe?i) a mesajului codificat transmis pe fir
request_id | Identificatorul interpelarii pentru acest mesaj: 42
namespace | Spa?iul de nume MongoDB utilizat pentru mesajul de protocol dbname.collectionname

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Only available when connected to MongoDB 2.6.0+
Stream Context Options
log_cmd_insert
Stream Context Options


Callback When Inserting Documents

log_cmd_delete
log_cmd_update
Stream Context Options
PHP Manual

log_cmd_insert

(PECL mongo >= 1.5.0)

log_cmd_insert — Callback When Inserting Documents

Descrierea

log_cmd_insert ( array $server , array $document , array $writeOptions , array $protocolOptions )

A callable function, used by the log_cmd_insert context option, when inserting a document

Nota:

This is not a real function, only a prototype of how the function should be.

Parametri

server

Un tablou cu informa?iile de baza despre serverul ales.

cheie | valoare
hash | hash-ul serverului, de exemplu:localhost:27017;-;X;56052
type | Tipul nodului (primary/secondary/mongos/arbiter): 2
max_bson_size | Dimensiunea maximala BSON prin fir, pe care acest nod o accepta: 16777216
max_message_size | Dimensiunea maximala a mesajului prin fir, pe care acest nod o accepta: 48000000
request_id | Identificatorul interpelarii pentru acest mesaj: 42

document

The document that has been prepared to be inserted

writeOptions

cheie | valoare
ordered | Boolean, daca opera?iunea (în cazul unei opera?iuni în set) trebuie executata secven?ial (ordered=true)
writeConcern | Un tablou cu op?iuni writeConcern (a se vedea mai jos)
Valorile tabloului writeConcern
cheie | valoare
fsync | Boolean, for?eaza înscrierea pe disc înainte de a se întoarce
j | Boolean, for?eaza înscrierea jurnalului înainte de a se întoarce
wtimeout | integer, milisecunde, timpul maximal care îi este acordat primarului ca sa verifice replicarea
w | integer=numarul de servere, sau string=eticheta de replicare

protocolOptions

cheie | valoare
message_length | Dimensiunea totala (în octe?i) a mesajului codificat transmis pe fir
request_id | Identificatorul interpelarii pentru acest mesaj: 42
namespace | Spa?iul de nume MongoDB utilizat pentru mesajul de protocol dbname.collectionname

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Only available when connected to MongoDB 2.6.0+
log_cmd_delete
log_cmd_update
Stream Context Options


Callback When Updating Documents

log_cmd_insert
log_getmore
Stream Context Options
PHP Manual

log_cmd_update

(PECL mongo >= 1.5.0)

log_cmd_update — Callback When Updating Documents

Descrierea

log_cmd_update ( array $server , array $writeOptions , array $updateOptions , array $protocolOptions )

A callable function, used by the log_cmd_update context option, when updateing a document

Nota:

This is not a real function, only a prototype of how the function should be.

Parametri

server

Un tablou cu informa?iile de baza despre serverul ales.

cheie | valoare
hash | hash-ul serverului, de exemplu:localhost:27017;-;X;56052
type | Tipul nodului (primary/secondary/mongos/arbiter): 2
max_bson_size | Dimensiunea maximala BSON prin fir, pe care acest nod o accepta: 16777216
max_message_size | Dimensiunea maximala a mesajului prin fir, pe care acest nod o accepta: 48000000
request_id | Identificatorul interpelarii pentru acest mesaj: 42

writeOptions

cheie | valoare
ordered | Boolean, daca opera?iunea (în cazul unei opera?iuni în set) trebuie executata secven?ial (ordered=true)
writeConcern | Un tablou cu op?iuni writeConcern (a se vedea mai jos)
Valorile tabloului writeConcern
cheie | valoare
fsync | Boolean, for?eaza înscrierea pe disc înainte de a se întoarce
j | Boolean, for?eaza înscrierea jurnalului înainte de a se întoarce
wtimeout | integer, milisecunde, timpul maximal care îi este acordat primarului ca sa verifice replicarea
w | integer=numarul de servere, sau string=eticheta de replicare

updateOptions

key | value
multi | Boolean, true if this update is allowed to update all matched criteria
upsert | Boolean, true if the document should be created if criteria does not match
q | Array, the search criteria
u | Array, the new object/modifications

protocolOptions

cheie | valoare
message_length | Dimensiunea totala (în octe?i) a mesajului codificat transmis pe fir
request_id | Identificatorul interpelarii pentru acest mesaj: 42
namespace | Spa?iul de nume MongoDB utilizat pentru mesajul de protocol dbname.collectionname

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Only available when connected to MongoDB 2.6.0+
log_cmd_insert
log_getmore
Stream Context Options


Callback When Retrieving Next Cursor Batch

log_cmd_update
log_killcursor
Stream Context Options
PHP Manual

log_getmore

(PECL mongo >= 1.5.0)

log_getmore — Callback When Retrieving Next Cursor Batch

Descrierea

log_getmore ( array $server , array $info )

A callable function, used by the log_getmore context option, when executing a GET_MORE operation.

Nota:

This is not a real function, only a prototype of how the function should be.

Parametri

server

Un tablou cu informa?iile de baza despre serverul ales.

cheie | valoare
hash | hash-ul serverului, de exemplu:localhost:27017;-;X;56052
type | Tipul nodului (primary/secondary/mongos/arbiter): 2
max_bson_size | Dimensiunea maximala BSON prin fir, pe care acest nod o accepta: 16777216
max_message_size | Dimensiunea maximala a mesajului prin fir, pe care acest nod o accepta: 48000000
request_id | Identificatorul interpelarii pentru acest mesaj: 42

info

key | value
request_id | integer, the driver request identifier
cursor_id | integer, the cursor identifier being used to fetch more data
batch_size | integer, maximum number of documents being requested

log_cmd_update
log_killcursor
Stream Context Options


Callback When Executing KILLCURSOR operations

log_getmore
log_reply
Stream Context Options
PHP Manual

log_killcursor

(PECL mongo >= 1.5.0)

log_killcursor — Callback When Executing KILLCURSOR operations

Descrierea

log_killcursor ( array $server , array $info )

A callable function, used by the log_killcursor context option, when reading a killcursor from MongoDB.

Nota:

This is not a real function, only a prototype of how the function should be.

Parametri

server

Un tablou cu informa?iile de baza despre serverul ales.

cheie | valoare
hash | hash-ul serverului, de exemplu:localhost:27017;-;X;56052
type | Tipul nodului (primary/secondary/mongos/arbiter): 2
max_bson_size | Dimensiunea maximala BSON prin fir, pe care acest nod o accepta: 16777216
max_message_size | Dimensiunea maximala a mesajului prin fir, pe care acest nod o accepta: 48000000
request_id | Identificatorul interpelarii pentru acest mesaj: 42

info

key | value
cursor_id | integer, the cursor identifier to kill

log_getmore
log_reply
Stream Context Options


Callback When Reading the MongoDB reply

log_killcursor
log_write_batch
Stream Context Options
PHP Manual

log_reply

(PECL mongo >= 1.5.0)

log_reply — Callback When Reading the MongoDB reply

Descrierea

log_reply ( array $server , array $messageHeaders , array $operationHeaders )

A callable function, used by the log_reply context option, when reading a reply from MongoDB.

Nota:

This is not a real function, only a prototype of how the function should be.

Parametri

server

Un tablou cu informa?iile de baza despre serverul ales.

cheie | valoare
hash | hash-ul serverului, de exemplu:localhost:27017;-;X;56052
type | Tipul nodului (primary/secondary/mongos/arbiter): 2
max_bson_size | Dimensiunea maximala BSON prin fir, pe care acest nod o accepta: 16777216
max_message_size | Dimensiunea maximala a mesajului prin fir, pe care acest nod o accepta: 48000000
request_id | Identificatorul interpelarii pentru acest mesaj: 42

messageHeaders

key | value
length | integer, bytes, message reply length
request_id | integer, the server request identifier
response_id | integer, the driver request identifier this message is a response of
opcode | integer, the opcode id

operationHeaders

key | value
flags | integer, bitmask of protocol flags
cursor_id | integer, ID of the cursor created on the server (0 if none created, or its been exhausted)
start | The starting offset of this cursor
returned | integer, how many documents are returned in this trip

A se vedea ?i

  • The » OP_REPLY definition in the Wire Protocol
log_killcursor
log_write_batch
Stream Context Options


Callback When Writing Batches

log_reply
Writes
Stream Context Options
PHP Manual

log_write_batch

(PECL mongo >= 1.5.0)

log_write_batch — Callback When Writing Batches

Descrierea

log_write_batch ( array $server , array $writeOptions , array $batch , array $protocolOptions )

A callable function, used by the log_write_batch context option, when executing a batch operation.

Nota:

This is not a real function, only a prototype of how the function should be.

Parametri

server

Un tablou cu informa?iile de baza despre serverul ales.

cheie | valoare
hash | hash-ul serverului, de exemplu:localhost:27017;-;X;56052
type | Tipul nodului (primary/secondary/mongos/arbiter): 2
max_bson_size | Dimensiunea maximala BSON prin fir, pe care acest nod o accepta: 16777216
max_message_size | Dimensiunea maximala a mesajului prin fir, pe care acest nod o accepta: 48000000
request_id | Identificatorul interpelarii pentru acest mesaj: 42

writeOptions

cheie | valoare
ordered | Boolean, daca opera?iunea (în cazul unei opera?iuni în set) trebuie executata secven?ial (ordered=true)
writeConcern | Un tablou cu op?iuni writeConcern (a se vedea mai jos)
Valorile tabloului writeConcern
cheie | valoare
fsync | Boolean, for?eaza înscrierea pe disc înainte de a se întoarce
j | Boolean, for?eaza înscrierea jurnalului înainte de a se întoarce
wtimeout | integer, milisecunde, timpul maximal care îi este acordat primarului ca sa verifice replicarea
w | integer=numarul de servere, sau string=eticheta de replicare

batch

Array, the actual batch operation.

protocolOptions

cheie | valoare
message_length | Dimensiunea totala (în octe?i) a mesajului codificat transmis pe fir
request_id | Identificatorul interpelarii pentru acest mesaj: 42
namespace | Spa?iul de nume MongoDB utilizat pentru mesajul de protocol dbname.collectionname

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Only available when connected to MongoDB 2.6.0+
log_reply
Writes
Stream Context Options


Writes

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')));

?>
log_write_batch
Querying
Manual


Querying

Distributing queries to secondaries

All queries (reads and writes) are only sent to the primary member of a replica set by default. This is however easily configurable by using the Read Preferences which allow you to set some generic read preferences (such as allowing secondary reads of the nearest server), and also provide ways to specifically target a server in a specific country, datacenter, or even hardware, by the use of replica set tag sets.

Read preferences can be configured at every level of the driver:

  • As a query parameter or option to MongoClient::__construct()
  • Specifically by calling MongoClient::setReadPreference()
  • At the database level with MongoDB::setReadPreference()
  • At the collection level with MongoCollection::setReadPreference()
  • At the cursor level with MongoCursor::setReadPreference() or MongoCommandCursor::setReadPreference()
Each class inherits its read preference setting from the "parent" context.

Example #1 Inheriting read preferences from the database level down to the cursor

<?php
$db->setReadPreference(MongoClient::RP_SECONDARY_PREFERRED);
$c = $db->myCollection;

$cursor = $c->find();
?>

In this example, the the query will be executed against a secondary. The collection inherits MongoClient::RP_SECONDARY_PREFERRED from the database and the cursor inherits it from the collection.

How secondaries are chosen

Each instance of MongoClient chooses its own secondary using the available secondary 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
$options = array("replicaSet" => "setName", "readPreference" => MongoClient::RP_SECONDARY_PREFERRED);

// on the Australian client
$m = new MongoClient("mongodb://primary,australianhost.secondary,europeanhost.secondary", $options);
$cursor = $m->foo->bar->find();
$cursor->getNext();
echo "Reading from: ", $cursor->info()["server"], "\n";

// on the European client
$m = new MongoClient("mongodb://primary,australianhost.secondary,europeanhost.secondary", $options);
$cursor = $m->foo->bar->find();
$cursor->getNext();
echo "Reading from: ", $cursor->info()["server"], "\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

Reading from: australianHost
Reading from: europeanHost

Note that we have to do a query before a secondary is chosen: secondaries are chosen lazily by the driver, and for each query separately.

You can see what the driver thinks is the current status of the set members by running MongoClient::getHosts() or MongoClient::getConnections().

If no secondary is readable, the driver will send reads to the primary as we specified MongoClient::RP_SECONDARY_PREFERRED which will fallback to execute a query on a primary if no secondaries are available. A server is considered readable if its state is 2 (SECONDARY) and its health is 1. You can check this with MongoClient::getHosts() and MongoClient::getConnections().

Random notes

Writes are always sent to the primary—and by default all reads are sent to the primary too.

Querying by _id

Every object inserted is automatically assigned a unique _id field, which is often a useful field to use in queries. This works similarly to "get last insert ID" functionality, except that the _id is chosen by the client.

Suppose that we wish to find the document we just inserted. Inserting adds an _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 attempting 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"))));

?>

Istoricul schimbarilor

Versiune | Descriere
1.3.0 | Introduced the Read Preferences framework to allow more fine grained control over secondary reads.
1.3.0 | Deprecated slaveOkay usage, the alternative is Read Preferences.
1.1.0 | Introduced the possiblity of routing reads to secondaries of replica set members using Mongo::setSlaveOkay()
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
Security
Manual


Security

Request Injection Attacks

If you are passing $_GET (or $_POST) parameters to your queries, make sure that they are cast to strings first. Users can insert associative arrays in GET and POST 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 and $_POST 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.

Nota:

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.

Updates
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.

  • 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 make the driver log all kinds of error messages as E_NOTICE level PHP error messages. Have a look at the MongoLog for an example.

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.

.phpt Tests

.phpt tests are the standard way of testing PHP extensions. After compiling the MongoDB driver with "make" you can then issue "make test" to run the tests. These tests require MongoDB to be working, and hence, you need to configure the test suite itself.

There is more information on running the tests in the contributing guidelines on » GitHub.

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
Clase de baza
Manual


Clase de baza

Cuprins

  • MongoClient
  • MongoDB
  • MongoCollection
  • MongoCursor
  • MongoCursorInterface
  • MongoCommandCursor
Avertizare

Aceasta extensie este învechita. În loc, trtebuie utilizata extensia MongoDB.

Clasele de baza reprezinta cea mai importanta parte componenta a driver-ului.

Running the Driver's Tests
MongoClient
Mongo


The MongoClient class

(PECL mongo >=1.3.0)

Avertizare

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta clasa includ:

  • MongoDB\Driver\Manager

Introducere

A connection manager for PHP and MongoDB.

This class is used to create and manage connections. A typical use is:

Example #1 MongoClient basic usage

<?php

$m = new MongoClient(); // connect
$db = $m->foo; // get the database named "foo"

?>

See MongoClient::__construct() and the section on connecting for more information about creating connections.

Sinopsisul clasei

MongoClient {
/* Constante */
const string VERSION ;
const string DEFAULT_HOST = "localhost" ;
const int DEFAULT_PORT = 27017 ;
const string RP_PRIMARY = "primary" ;
const string RP_PRIMARY_PREFERRED = "primaryPreferred" ;
const string RP_SECONDARY = "secondary" ;
const string RP_SECONDARY_PREFERRED = "secondaryPreferred" ;
const string RP_NEAREST = "nearest" ;
/* Proprieta?i */
public boolean $connected = FALSE ;
public string $status = NULL ;
protected string $server = NULL ;
protected boolean $persistent = NULL ;
/* Metode */
public __construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => TRUE) [, array $driver_options ]]] )
public bool close ([ boolean|string $connection ] )
public bool connect ( void )
public array dropDB ( mixed $db )
public MongoDB __get ( string $dbname )
public static array getConnections ( void )
public array getHosts ( void )
public array getReadPreference ( void )
public array getWriteConcern ( void )
public bool killCursor ( string $server_hash , int|MongoInt64 $id )
public array listDBs ( void )
public MongoCollection selectCollection ( string $db , string $collection )
public MongoDB selectDB ( string $name )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public bool setWriteConcern ( mixed $w [, int $wtimeout ] )
public string __toString ( void )
}

Constante predefinite

MongoClient Constants

MongoClient::VERSION
PHP driver version. May be suffixed with "dev", "+" or "-" if it is in-between versions.
MongoClient::DEFAULT_HOST
"localhost"
Host to connect to if no host is given.
MongoClient::DEFAULT_PORT
27017
Port to connect to if no port is given.
MongoClient::RP_PRIMARY
"primary"
Read preference for the primary replica set member.
MongoClient::RP_PRIMARY_PREFERRED
"primaryPreferred"
Read preference for preferring the primary replica set member.
MongoClient::RP_SECONDARY
"secondary"
Read preference for a secondary replica set member.
MongoClient::RP_SECONDARY_PREFERRED
"secondaryPreferred"
Read preference for preferring a secondary replica set member.
MongoClient::RP_NEAREST
"nearest"
Read preference for the nearest replica set member.

Fields

connected

This property will be set to TRUE if we have a open connection to the database, FALSE otherwise. If the connection is to a replica set, this property will only be TRUE if the driver has a connection to a node matching the current read preference. This property does not take authentication into account.

This property is deprecated since version 1.5.0.

status

This property is no longer used and will be set to NULL In driver versions 1.1.x and earlier, this may be set to a string value (e.g. "recycled", "new") when persistent connections are used.

This property is deprecated since version 1.5.0.

A se vedea ?i

  • Read Preferences
  • Write Concerns
  • Connecting
  • MongoDB core docs on » connecting

Cuprins

  • MongoClient::close — Closes this connection
  • MongoClient::connect — Connects to a database server
  • MongoClient::__construct — Creates a new database connection object
  • MongoClient::dropDB — Drops a database [deprecated]
  • MongoClient::__get — Gets a database
  • MongoClient::getConnections — Return info about all open connections
  • MongoClient::getHosts — Updates status for all associated hosts
  • MongoClient::getReadPreference — Get the read preference for this connection
  • MongoClient::getWriteConcern — Get the write concern for this connection
  • MongoClient::killCursor — Kills a specific cursor on the server
  • MongoClient::listDBs — Lists all of the databases available.
  • MongoClient::selectCollection — Gets a database collection
  • MongoClient::selectDB — Gets a database
  • MongoClient::setReadPreference — Set the read preference for this connection
  • MongoClient::setWriteConcern — Set the write concern for this connection
  • MongoClient::__toString — String representation of this connection
Clase de baza
MongoClient::close
Clase de baza


Closes this connection

MongoClient
MongoClient::connect
MongoClient
PHP Manual

MongoClient::close

(PECL mongo >=1.3.0)

MongoClient::close — Closes this connection

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public bool MongoClient::close ([ boolean|string $connection ] )

The MongoClient::close() method forcefully closes a connection to the database, even if persistent connections are being used. You should never have to do this under normal circumstances.

Parametri

connection

If connection is not given, or FALSE then connection that would be selected for writes would be closed. In a single-node configuration, that is then the whole connection, but if you are connected to a replica set, close() will only close the connection to the primary server.

If connection is TRUE then all connections as known by the connection manager will be closed. This can include connections that are not referenced in the connection string used to create the object that you are calling close on.

If connection is a string argument, then it will only close the connection identified by this hash. Hashes are identifiers for a connection and can be obtained by calling MongoClient::getConnections().

Valorile întoarse

Returns if the connection was successfully closed.

Exemple

Example #1 MongoClient::close() example

This example demonstrates how to selectively close all connections for secondaries only.

<?php
// Connect to a replicaset
$a = new MongoClient("mongodb://whisky:13000/?replicaset=seta");

$connections = $a->getConnections();

foreach ( $connections as $con )
{
    // Loop over all the connections, and when the type is "SECONDARY"
    // we close the connection
    if ( $con['connection']['connection_type_desc'] == "SECONDARY" )
    {
        echo "Closing '{$con['hash']}': ";
        $closed = $a->close( $con['hash'] );
        echo $closed ? "ok" : "failed", "\n";
    }
}
?>

Exemplul de mai sus va afi?a:

Closing 'whisky:13001;X;4948': ok

Istoricul schimbarilor

Versiune | Descriere
1.3.0 | The connection parameter to this function was added in 1.3.0. Before that, only the write connection would be closed by this method.
1.2.0 | Before version 1.2.0 the driver would not use persistent connections by default, and all connections would be closed as soon as a MongoDB connection went out if scope. Since version 1.2.0 this is no longer the case and it is a bad idea to call close as you might end up overloading the server with connections under high load.

A se vedea ?i

  • MongoClient::getConnections() - Return info about all open connections
MongoClient
MongoClient::connect
MongoClient


Connects to a database server

MongoClient::close
MongoClient::__construct
MongoClient
PHP Manual

MongoClient::connect

(PECL mongo >=1.3.0)

MongoClient::connect — Connects to a database server

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public bool MongoClient::connect ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

If the connection was successful.

Erori/Excep?ii

Throws MongoConnectionException if it fails to connect to the database.

MongoClient::close
MongoClient::__construct
MongoClient


Creates a new database connection object

MongoClient::connect
MongoClient::dropDB
MongoClient
PHP Manual

MongoClient::__construct

(PECL mongo >=1.3.0)

MongoClient::__construct — Creates a new database connection object

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\Driver\Manager::__construct()

Descrierea

 public MongoClient::__construct
  ([ string $server = "mongodb://localhost:27017"
 [, array $options = array("connect" => TRUE)
 [, array $driver_options
]]] )

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. Please see the Replica Sets section for information on how to connect to Replica Sets.

If you specified a username and password, you may specify a database to authenticate with. If db is not specified, "admin" will be used.

An optional query string may be used to specify extra options. The same options are supported through the options array as well, and are therefore redescribed there. See the examples below on how to set those options.

One part of the options governs how the driver reads from secondary nodes in a replica set environment. Extra information on how these read preferences work is available as well through the read preferences documentation page.

Parametri

server

The server name.

options

An array of options for the connection. Currently available options include:

  • "authMechanism"

    Available mechanisms are:

    authMechanism | Description | Availability
    MONGODB-CR | Authenticate using Challenge Response mechanism. This is the default value. | All MongoDB versions
    X509 | Authenticates using X509 certificates | MongoDB 2.6. Only available when OpenSSL is enabled
    PLAIN | Authenticates using unencrypted plain username+password. Must be used over SSL connections. Generally used by MongoDB to login via 3rd party LDAP server | MongoDB Enterprise 2.4. The Driver must be compiled against CyrusSASL2
    GSSAPI | Authenticates via kerberos systems | MongoDB Enterprise 2.4. The Driver must be compiled against CyrusSASL2

  • "authSource"

    Should be set to the database name where the user is defined it.

  • "connect"

    If the constructor should connect before returning. Default is TRUE. When set to FALSE the driver will automatically connect to the server whenever it is necessary to do a query. Alternatively, you can run MongoClient::connect() manually.

    Avertizare

    This option is not supported through the connection string.

  • "connectTimeoutMS"

    How long a connection can take to be opened before timing out in milliseconds. Defaults to 60000 (60 seconds).

    If -1 is specified, no connection timeout will be applied and PHP will use default_socket_timeout.

  • "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.

  • "fsync"

    When "fsync" is set, all write operations will block until the database has flushed the changes to disk. This makes the write operations slower, but it guarantees that writes have succeeded and that the operations can be recovered in case of total system failure.

    If the MongoDB server has journaling enabled, this option is identical to "journal". If journaling is not enabled, this option ensures that write operations will be synced to database files on disk.

    Nota: If journaling is enabled, users are strongly encouraged to use the "journal" option instead of "fsync". Do not use "fsync" and "journal" simultaneously, as that will result in an error.

  • "journal"

    When "journal" is set, all write operations will block until the database has flushed the changes to the journal on disk. This makes the write operations slower, but it guarantees that writes have succeeded and that the operations can be recovered in case of total system failure.

    Nota: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "gssapiServiceName"

    Sets the » Kerberos service principal. Only applicable when authMechanism=GSSAPI. Defaults to "mongodb".

  • "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.

  • "readPreference"

    Specifies the read preference type. Read preferences provide you with control from which secondaries data can be read from.

    Allowed values are: MongoClient::RP_PRIMARY,
MongoClient::RP_PRIMARY_PREFERRED,
MongoClient::RP_SECONDARY,
MongoClient::RP_SECONDARY_PREFERRED and
MongoClient::RP_NEAREST.

    See the documentation on read preferences for more information.

  • "readPreferenceTags"

    Specifies the read preference tags as an array of strings. Tags can be used in combination with the readPreference option to further control which secondaries data might be read from.

    See the documentation on read preferences for more information.

  • "replicaSet"

    The name of the replica set to connect to. If this is given, the primary will be automatically be determined. This means that the driver may end up connecting to a server that was not even listed. See the replica set example below for details.

  • "secondaryAcceptableLatencyMS"

    When reading from a secondary (using ReadPreferences), do not read from secondaries known to be more then secondaryAcceptableLatencyMS away from us. Defaults to 15

  • "socketTimeoutMS"

    How long a socket operation (read or write) can take before timing out in milliseconds. Defaults to 30000 (30 seconds).

    If -1 is specified, socket operations may block indefinitely. This option may also be set on a per-operation basis using MongoCursor::timeout() for queries or the "socketTimeoutMS" option for write methods.

    Nota: This is a client-side timeout. If a write operation times out, there is no way to know if the server actually handled the write or not, as a MongoCursorTimeoutException will be thrown in lieu of returning a write result.

  • "ssl"

    A boolean to specify whether you want to enable SSL for the connections to MongoDB. Extra options such as certificates can be set with SSL context options.

  • "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.

  • "w"

    The w option specifies the Write Concern for the driver, which determines how long the driver blocks when writing. The default value is 1.

    This option is applicable when connecting to both single servers and replica sets. A positive value controls how many nodes must acknowledge the write instruction before the driver continues. A value of 1 would require the single server or primary (in a replica set) to acknowledge the write operation. A value of 3 would cause the driver to block until the write has been applied to the primary as well as two secondary servers (in a replica set).

    A string value is used to control which tag sets are taken into account for write concerns. "majority" is special and ensures that the write operation has been applied to the majority (more than 50%) of the participating nodes.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable for write operations where "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "slaveOkay"

    Deprecated. Please use the read preference options.

  • "timeout"

    Deprecated alias for "connectTimeoutMS".

  • "wTimeout"

    Deprecated alias for "wTimeoutMS".

driver_options

An array of options for the MongoDB driver. Options include setting connection context options for SSL or logging callbacks.

  • "context"

    The Stream Context to attach to all new connections. This allows you for example to configure SSL certificates and are described at SSL context options. See the Connecting over SSL tutorial.

Valorile întoarse

Returns a new database connection object.

Erori/Excep?ii

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.

Exemple

Example #1 MongoClient::__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 primary could be any one of these servers.

<?php

// pass a comma-separated list of server names to the constructor
// Note that we don't need to pass in all the members of the replicaset, the driver
// will derive the full list.
$m1 = new MongoClient("mongodb://sf2.example.com,ny1.example.com", array("replicaSet" => "myReplSet"));

?>

If the current primary fails, the driver will figure out which secondary server became the new primary 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.

Example #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 MongoClient("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 MongoClient("mongodb:///tmp/mongodb-27017.sock,localhost:27017");

?>

Example #3 MongoClient::__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 MongoClient("mongodb://testUser:testPass@localhost");

?>

Example #4 MongoClient::__construct() read preference example

<?php

// Prefer the nearest server in the "east" data center
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
?>

See the read preferences section of this manual for further information.

Example #5 MongoClient::__construct() options example

Options can be passed both through the query string in the connection string, or as an array passed as second argument to the constructor.

Here we set the journal option to true and readPreference to secondary preferred as default for all write operations:

<?php
$m = new MongoClient("mongodb://localhost/?journal=true&readPreference=secondary");
?>

And now we do the same, but as an options array:

<?php
$options = array(
    'journal' => true,
    'readPreference' => 'secondary',
);
$m = new MongoClient("mongodb://localhost/", $options);
?>

Example #6 MongoClient::__construct() read preference example

<?php

// Prefer the nearest server in the "east" data center
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
?>

See the read preferences section of this manual for further information.

Istoricul schimbarilor

Versiune | Descriere
1.5.0

Added "authMechanism", "gssapiServiceName", and "secondaryAcceptableLatencyMS".

1.4.0

Added "ssl" option and support for connecting over SSL.

Added "wTimeoutMS" option, which replaces "wTimeout".

Emits E_DEPRECATED when "slaveOkay" or "timeout" is used.

1.5.0

Added "authSource".

1.3.4

Added "connectTimeoutMS" and "socketTimeoutMS" options.

1.3.0

Added "readPreference", "readPreferenceTags", "w", and "wTimeout" options.

1.2.0

Added "username" and "password" options.

Removed "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 MongoClient 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" option now takes a string, not a boolean.

1.0.9 | Added "replicaSet" option.
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.

MongoClient::connect
MongoClient::dropDB
MongoClient


Drops a database [deprecated]

MongoClient::__construct
MongoClient::__get
MongoClient
PHP Manual

MongoClient::dropDB

(PECL mongo >=1.3.0)

MongoClient::dropDB — Drops a database [deprecated]

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie, însa exista o alternativa în biblioteca PHP:

  • » MongoDB\Client::dropDatabase()

Descrierea

public array MongoClient::dropDB ( mixed $db )
Avertizare

Deprecated

Use MongoDB::drop() instead.

Parametri

db

The database to drop. Can be a MongoDB object or the name of the database.

Valorile întoarse

Returns the database response.

MongoClient::__construct
MongoClient::__get
MongoClient


Gets a database

MongoClient::dropDB
MongoClient::getConnections
MongoClient
PHP Manual

MongoClient::__get

(PECL mongo >=1.3.0)

MongoClient::__get — Gets a database

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie, însa exista o alternativa în biblioteca PHP:

  • » MongoDB\Client::__get()

Descrierea

public MongoDB MongoClient::__get ( string $dbname )

This is the cleanest way of getting a database. If the database name has any special characters, MongoClient::selectDB() will need to be used; however, this should be sufficient for most cases.

<?php

$mongo = new MongoClient();

// the following two lines are equivalent
$db = $mongo->selectDB("foo");
$db = $mongo->foo;

?>

Parametri

dbname

The database name.

Valorile întoarse

Returns a new db object.

Erori/Excep?ii

Throws a generic exception if the database name is invalid.

MongoClient::dropDB
MongoClient::getConnections
MongoClient


Return info about all open connections

MongoClient::__get
MongoClient::getHosts
MongoClient
PHP Manual

MongoClient::getConnections

(PECL mongo >=1.3.0)

MongoClient::getConnections — Return info about all open connections

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public static array MongoClient::getConnections ( void )

Returns an array of all open connections, and information about each of the servers

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array of open connections.

Exemple

Example #1 MongoClient::getConnections() example

<?php
$m = new MongoClient;
var_dump($m->getConnections());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [0]=>
  array(3) {
    ["hash"]=>
    string(26) "localhost:27017;-;X;56052"
    ["server"]=>
    array(3) {
      ["host"]=>
      string(10) "localhost"
      ["port"]=>
      int(27017)
      ["pid"]=>
      int(56052)
    }
    ["connection"]=>
    array(8) {
      ["last_ping"]=>
      int(1354076401)
      ["last_ismaster"]=>
      int(0)
      ["ping_ms"]=>
      int(0)
      ["connection_type"]=>
      int(1)
      ["connection_type_desc"]=>
      string(10) "STANDALONE"
      ["max_bson_size"]=>
      int(16777216)
      ["tag_count"]=>
      int(0)
      ["tags"]=>
      array(0) {
      }
    }
  }
}
MongoClient::__get
MongoClient::getHosts
MongoClient


Updates status for all associated hosts

MongoClient::getConnections
MongoClient::getReadPreference
MongoClient
PHP Manual

MongoClient::getHosts

(PECL mongo >=1.3.0)

MongoClient::getHosts — Updates status for all associated hosts

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\Driver\Manager::getServers()

Descrierea

public array MongoClient::getHosts ( void )

This method is only useful with a connection to a replica set. It returns the status of all of the hosts in the set. Without a replica set, it will just return an array with one element containing the host that you are connected to.

See the query section of this manual for information on distributing reads to secondaries.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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(3) {
  ["A:27017"]=>
  array(4) {
    ["host"]=>
    "A"
    ["port"]=>
    27017
    ["health"]=>
    int(1)
    ["state"]=>
    int(2)
    ["ping"]=>
    int(369)
    ["lastPing"]=>
    int(1309470644)
  }
  ["B:27017"]=>
  array(4) {
    ["host"]=>
    "B"
    ["port"]=>
    27017
    ["health"]=>
    int(1)
    ["state"]=>
    int(1)
    ["ping"]=>
    int(139)
    ["lastPing"]=>
    int(1309470644)
  }
  ["C:27017"]=>
  array(4) {
    ["host"]=>
    "C"
    ["port"]=>
    27017
    ["health"]=>
    int(1)
    ["state"]=>
    int(2)
    ["ping"]=>
    int(1012)
    ["lastPing"]=>
    int(1309470644)
  }
}

Istoricul schimbarilor

Versiune | Descriere
1.2.10 | Support for non-replicasets was added. The returned array elements now also include the hostname and port.

A se vedea ?i

  • MongoClient::getConnections() - Return info about all open connections
MongoClient::getConnections
MongoClient::getReadPreference
MongoClient


Get the read preference for this connection

MongoClient::getHosts
MongoClient::getWriteConcern
MongoClient
PHP Manual

MongoClient::getReadPreference

(PECL mongo >=1.3.0)

MongoClient::getReadPreference — Get the read preference for this connection

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public array MongoClient::getReadPreference ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Aceasta func?ie întoarce un tablou ce descrie preferin?a de citire. Tabloul con?ine tipul (type) valorilor pentru ?irul cu modul preferin?ei de citire (ce corespunde constantelor MongoClient), ?i tagsets con?inând lista tuturor criteriilor setului de etichete. Daca nu a fost specificat nici un set de etichete, tagsets nu va fi prezent în tablou.

Istoricul schimbarilor

Versiune | Descriere
1.3.3 | The return value has changed to be consistent with MongoClient::setReadPreference(). The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.

Exemple

Example #1 MongoClient::getReadPreference() return value example

<?php

$m = new MongoClient();
$m->setReadPreference(MongoClient::RP_SECONDARY, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
    array(),
));
var_dump($m->getReadPreference());
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["type"]=>
  string(9) "secondary"
  ["tagsets"]=>
  array(3) {
    [0]=>
    array(2) {
      ["dc"]=>
      string(4) "east"
      ["use"]=>
      string(9) "reporting"
    }
    [1]=>
    array(1) {
      ["dc"]=>
      string(7) "west"
    }
    [2]=>
    array(0) {
    }
  }
}

A se vedea ?i

  • The read preferences documentation.
  • MongoClient::setReadPreference() - Set the read preference for this connection
MongoClient::getHosts
MongoClient::getWriteConcern
MongoClient


Get the write concern for this connection

MongoClient::getReadPreference
MongoClient::killCursor
MongoClient
PHP Manual

MongoClient::getWriteConcern

(PECL mongo >=1.5.0)

MongoClient::getWriteConcern — Get the write concern for this connection

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public array MongoClient::getWriteConcern ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Aceasta func?ie întoarce un tablou ce descrie gradul de participare la înscriere. Tabloul con?ine valorile w pentru un nivel de confirmare întreg sau ca ?ir de caractere ?i wtimeout ce denota numarul maximal de milisecunde de a?teptare pâna când serverul satisface gradul de participare la înscriere.

Exemple

Example #1 MongoClient::getWriteConcern() return value example

<?php

$mc = new MongoClient('mongodb://localhost:27017', array('wTimeoutMS' => 500));
var_dump($mc->getWriteConcern());

$mc->setWriteConcern(1, 1000);
var_dump($mc->getWriteConcern());
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(500)
}
array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(1000)
}

A se vedea ?i

  • The write concern documentation.
  • MongoClient::setWriteConcern() - Set the write concern for this connection
MongoClient::getReadPreference
MongoClient::killCursor
MongoClient


Kills a specific cursor on the server

MongoClient::getWriteConcern
MongoClient::listDBs
MongoClient
PHP Manual

MongoClient::killCursor

(PECL mongo >=1.5.0)

MongoClient::killCursor — Kills a specific cursor on the server

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public bool MongoClient::killCursor ( string $server_hash , int|MongoInt64 $id )

In certain situations it might be needed to kill a cursor on the server. Usually cursors time out after 10 minutes of inactivity, but it is possible to create an immortal cursor with MongoCursor::immortal() that never times out. In order to be able to kill such an immortal cursor, you can call this method with the information supplied by MongoCursor::info().

Parametri

server_hash

The server hash that has the cursor. This can be obtained through MongoCursor::info().

id

The ID of the cursor to kill. You can either supply an int containing the 64 bit cursor ID, or an object of the MongoInt64 class. The latter is necessary on 32 bit platforms (and Windows).

Valorile întoarse

Returns TRUE if the method attempted to kill a cursor, and FALSE if there was something wrong with the arguments (such as a wrong server_hash). The return status does not reflect where the cursor was actually killed as the server does not provide that information.

Erori/Excep?ii

This method displays a warning if the supplied server_hash does not match up with an existing connection. No attempt to kill a cursor is attempted in that case either.

Exemple

Example #1 MongoClient::killCursor() example

This example shows how to connect, do a query, obtain the cursor information and then kill the cursor.

<?php
$m = new MongoClient();
$c = $m->testdb->collection;
$cursor = $c->find();
$result = $cursor->next();

// Now the cursor is valid, so we can get the hash and ID out:
$info = $cursor->info();

// Kill the cursor
MongoClient::killCursor( $info['server'], $info['id'] );
?>
MongoClient::getWriteConcern
MongoClient::listDBs
MongoClient


Lists all of the databases available.

MongoClient::killCursor
MongoClient::selectCollection
MongoClient
PHP Manual

MongoClient::listDBs

(PECL mongo >=1.3.0)

MongoClient::listDBs — Lists all of the databases available.

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie, însa exista o alternativa în biblioteca PHP:

  • » MongoDB\Client::listDatabases()

Descrierea

public array MongoClient::listDBs ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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 th 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.

Exemple

Example #1 MongoClient::listDBs() example

Example demonstrating how to use listDBs and the returned data structure.

<?php

$mongo = new MongoClient();
$dbs = $mongo->listDBs();
print_r($dbs);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [databases] => Array
        (
            [0] => Array
                (
                    [name] => doctrine
                    [sizeOnDisk] => 218103808
                    [empty] =>
                )
        )

    [totalSize] => 218103808
    [ok] => 1
)
MongoClient::killCursor
MongoClient::selectCollection
MongoClient


Gets a database collection

MongoClient::listDBs
MongoClient::selectDB
MongoClient
PHP Manual

MongoClient::selectCollection

(PECL mongo >=1.3.0)

MongoClient::selectCollection — Gets a database collection

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie, însa exista o alternativa în biblioteca PHP:

  • » MongoDB\Client::selectCollection()

Descrierea

public MongoCollection MongoClient::selectCollection ( string $db , string $collection )

Parametri

db

The database name.

collection

The collection name.

Valorile întoarse

Returns a new collection object.

Erori/Excep?ii

Throws Exception if the database or collection name is invalid.

Exemple

Example #1 MongoClient::selectCollection() example

<?php
$m = new MongoClient();

$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
?>
MongoClient::listDBs
MongoClient::selectDB
MongoClient


Gets a database

MongoClient::selectCollection
MongoClient::setReadPreference
MongoClient
PHP Manual

MongoClient::selectDB

(PECL mongo >=1.3.0)

MongoClient::selectDB — Gets a database

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie, însa exista o alternativa în biblioteca PHP:

  • » MongoDB\Client::selectDatabase()

Descrierea

public MongoDB MongoClient::selectDB ( string $name )

Parametri

name

The database name.

Valorile întoarse

Returns a new database object.

Erori/Excep?ii

Throws Exception if the database name is invalid.

MongoClient::selectCollection
MongoClient::setReadPreference
MongoClient


Set the read preference for this connection

MongoClient::selectDB
MongoClient::setWriteConcern
MongoClient
PHP Manual

MongoClient::setReadPreference

(PECL mongo >=1.3.0)

MongoClient::setReadPreference — Set the read preference for this connection

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public bool MongoClient::setReadPreference ( string $read_preference [, array $tags ] )

Parametri

read_preference

Modul preferin?ei de citire:
MongoClient::RP_PRIMARY,
MongoClient::RP_PRIMARY_PREFERRED,
MongoClient::RP_SECONDARY,
MongoClient::RP_SECONDARY_PREFERRED sau
MongoClient::RP_NEAREST.

tags

Un tablou din zero sau mai multe seturi de etichete, unde fiecare set de etichete este la rândul sau un tablou de criterii utilizate pentru a potrivi etichetele pe membrii setului de replicare.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

Erori/Excep?ii

Emite un E_WARNING daca careva parametru nu e valid, sau daca unul sau mai multe seturi de etichete sunt furnizate cu modul preferin?ei de citire MongoClient::RP_PRIMARY.

Exemple

Example #1 MongoClient::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient();

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$m->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));
?>

A se vedea ?i

  • The read preferences documentation.
  • MongoClient::getReadPreference() - Get the read preference for this connection
MongoClient::selectDB
MongoClient::setWriteConcern
MongoClient


Set the write concern for this connection

MongoClient::setReadPreference
MongoClient::__toString
MongoClient
PHP Manual

MongoClient::setWriteConcern

(PECL mongo >=1.5.0)

MongoClient::setWriteConcern — Set the write concern for this connection

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public bool MongoClient::setWriteConcern ( mixed $w [, int $wtimeout ] )

Parametri

w

Gradul de participare la înscriere. Aceasta poate fi un întreg ce denota numarul de servere necesare pentru a confirma opera?iunea de înscriere, sau un mod scris ca ?ir de caractere (de ex. "majority").

wtimeout

Numarul maximal de milisecunde de a?teptare pâna când serverul satisface gradul de participare la înscriere.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

Erori/Excep?ii

Emite un E_WARNING daca parametrul w nu este un întreg sau un ?ir de caractere.

Exemple

Example #1 MongoClient::setWriteConcern() example

<?php

$mc = new MongoClient('mongodb://rs1.example.com,rs2.example.com');

// Require that the majority of servers in the replica set acknowledge writes
// within three seconds.
$mc->setWriteConcern('majority', 3000);
?>

A se vedea ?i

  • The write concern documentation.
  • MongoClient::getWriteConcern() - Get the write concern for this connection
MongoClient::setReadPreference
MongoClient::__toString
MongoClient


String representation of this connection

MongoClient::setWriteConcern
MongoDB
MongoClient
PHP Manual

MongoClient::__toString

(PECL mongo >=1.3.0)

MongoClient::__toString — String representation of this connection

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public string MongoClient::__toString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns hostname and port for this connection.

MongoClient::setWriteConcern
MongoDB
MongoClient


The MongoDB class

(PECL mongo >=0.9.0)

Introducere

Instances of this class are used to interact with a database. To get a database:

Example #1 Selecting a database

<?php

$m = new MongoClient(); // 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 "$".

Sinopsisul clasei

MongoDB {
/* Constante */
const int PROFILING_OFF = 0 ;
const int PROFILING_SLOW = 1 ;
const int PROFILING_ON = 2 ;
/* Fields */
public integer $w = 1 ;
public integer $wtimeout = 10000 ;
/* Metode */
public array authenticate ( string $username , string $password )
public array command ( array $command [, array $options = array() [, string &$hash ]] )
public __construct ( MongoClient $conn , string $name )
public MongoCollection createCollection ( string $name [, array $options ] )
public array createDBRef ( string $collection , mixed $document_or_id )
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 getCollectionInfo ([ array $options = array() ] )
public array getCollectionNames ([ array $options = array() ] )
public array getDBRef ( array $ref )
public MongoGridFS getGridFS ([ string $prefix = "fs" ] )
public int getProfilingLevel ( void )
public array getReadPreference ( void )
public bool getSlaveOkay ( void )
public array getWriteConcern ( void )
public array lastError ( void )
public array listCollections ([ array $options = array() ] )
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 setReadPreference ( string $read_preference [, array $tags ] )
public bool setSlaveOkay ([ bool $ok = true ] )
public bool setWriteConcern ( mixed $w [, int $wtimeout ] )
public string __toString ( void )
}

Constante predefinite

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 need to adjust the acknowledgement level (MongoCollection::insert(), MongoCollection::update(), MongoCollection::remove(), MongoCollection::save(), and MongoCollection::ensureIndex() all support this option). With the default value (1), an acknowledged operation will return once the database server has the operation. If the server goes down before the operation has been replicated to a secondary, it is possible to lose the operation forever. Thus, you can specify w to be higher than one and guarantee that at least one secondary has the operation before it is considered successful.

For example, if w is 2, the primary and one secondary 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 secondaries + primary, but then if one secondary is down the operation will fail and an exception will be thrown, so usually w=2 is safest (primary and one secondary).

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.

A se vedea ?i

MongoDB core docs on » databases.

Cuprins

  • 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 [deprecated]
  • MongoDB::forceError — Creates a database error
  • MongoDB::__get — Gets a collection
  • MongoDB::getCollectionInfo — Returns information about collections in this database
  • MongoDB::getCollectionNames — Gets an array of names for all collections in this database
  • 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::getReadPreference — Get the read preference for this database
  • MongoDB::getSlaveOkay — Get slaveOkay setting for this database
  • MongoDB::getWriteConcern — Get the write concern for this database
  • MongoDB::lastError — Check if there was an error on the most recent db operation performed
  • MongoDB::listCollections — Gets an array of MongoCollection objects for all 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::setReadPreference — Set the read preference for this database
  • MongoDB::setSlaveOkay — Change slaveOkay setting for this database
  • MongoDB::setWriteConcern — Set the write concern for this database
  • MongoDB::__toString — The name of this database
MongoClient::__toString
MongoDB::authenticate
Clase de baza


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

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Instead, you need to provide credentials through the connection string.

Descrierea

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 MongoClient::__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));

?>

Parametri

username

The username.

password

The password (in plaintext).

Valorile întoarse

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).

A se vedea ?i

MongoDB core docs on » authenticate.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used. Please pass in the authentication details to the constructor.

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

Descrierea

public array MongoDB::command ( array $command [, array $options = array() [, string &$hash ]] )

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);
}

?>

Parametri

command

The query to send.

options

An array of options for the index creation. Currently available options include:

  • "socketTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru comunicarea prin socket. Daca serverul nu raspunde în limita intervalului de timp, se va emite o MongoCursorTimeoutException ?i nu va fi nici o posibilitate de a determina daca serverul a efectuat înscrierea, sau nu. Valoarea -1 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 30000 (30 secunde).

The following options are deprecated and should no longer be used:

  • "timeout"

    Un pseudonim învechit pentru "socketTimeoutMS".

hash

Set to the connection hash of the server that executed the command. When the command result is suitable for creating a MongoCommandCursor, the hash is intended to be passed to MongoCommandCursor::createFromDocument().

The hash will also correspond to a connection returned from MongoClient::getConnections().

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Renamed the "timeout" option to "socketTimeoutMS". Emits E_DEPRECATED when "timeout" is used. Added hash by-reference parameter.
1.2.0 | Added options parameter with a single option: "timeout".

Valorile întoarse

Returns database response. Every database response is always maximum one document, which means that the result of a database command can never exceed 16MB. The resulting document's structure depends on the command, but most results will have the ok field to indicate success or failure and results containing an array of each of the resulting documents.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

4
22
87

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

22
87

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

User 47cc67093475061e3d9536d2 had 3 sale(s).
User 49902cde5162504500b45c2c had 14 sale(s).
User 4af467e4fd543cce7b0ea8e2 had 1 sale(s).

Nota: 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.

Nota: 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.

Example #4 MongoDB::command() "geoNear" example

This example shows how to use the geoNear command.

<?php
$m = new MongoClient();
$d = $m->demo;
$c = $d->poiConcat;

$r = $d->command(array(
    'geoNear' => "poiConcat",      // Search in the poiConcat collection
    'near' => array(-0.08, 51.48), // Search near 51.48°N, 0.08°E
    'spherical' => true,           // Enable spherical search
    'num' => 5,                    // Maximum 5 returned documents
));
print_r($r);
?>

A se vedea ?i

  • MongoCollection::aggregate() - Perform an aggregation using the aggregation framework
  • MongoCollection::findAndModify() - Update a document and return it
  • MongoCollection::group() - Performs an operation similar to SQL's GROUP BY command

MongoDB core docs on » database commands.

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

Descrierea

public MongoDB::__construct ( MongoClient $conn , string $name )

This method is not meant to be called directly. The preferred way to create an instance of MongoDB is through MongoClient::__get() or MongoClient::selectDB().

If you're ignoring the previous paragraph and want to call it directly you can do so:

<?php

$m = new MongoClient();
$db = new MongoDB($m, 'mydbname');

?>

But don't. Isn't this much nicer:

<?php

$m = new MongoClient();
$db = $m->mydbname;

// or, if the name contains weird characters:

$db = $m->selectDB('my,db:name');

?>

Parametri

MongoClient conn

Database connection.

name

Database name.

Valorile întoarse

Returns the database.

Erori/Excep?ii

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

Descrierea

public MongoCollection MongoDB::createCollection ( string $name [, array $options ] )

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,
    "capped" => $options["capped"],
    "size" => $options["size"],
    "max" => $options["max"],
    "autoIndexId" => $options["autoIndexId"],
));

?>
See MongoDB::command() for more information about database commands.

Parametri

name

The name of the collection.

options

An array containing options for the collections. Each option is its own element in the options array, with the option name listed below being the key of the element. The supported options depend on the MongoDB server version and storage engine, and the driver passes any option that you give it straight to the server. A few of the supported options are, but you can find a full list in the MongoDB core docs on » createCollection:

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.

autoIndexId

If capped is TRUE you can specify FALSE to disable the automatic index created on the _id field. Before MongoDB 2.2, the default value for autoIndexId was FALSE.

Valorile întoarse

Returns a collection object representing the new collection.

Exemple

Example #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",
    array(
        'capped' => true,
        'size' => 10*1024,
        'max' => 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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Istoricul schimbarilor

Versiune Descriere
1.4.0

In versions before 1.4.0, the options were all arguments to the method. The function synopsis in those older versions is:

public MongoCollection MongoDB::createCollection ( string $name [, bool $capped = FALSE [, int $size = 0 [, int $max = 0 ]]] )

The meaning of the options is the same as described under the options argument above.

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

Descrierea

public array MongoDB::createDBRef ( string $collection , mixed $document_or_id )

This method is a flexible interface for creating database refrences (see MongoDBRef).

Parametri

collection

The collection to which the database reference will point.

document_or_id

If an array or object is given, its _id field will be used as the reference ID. If a MongoId or scalar is given, it will be used as the reference ID.

Valorile întoarse

Returns a database reference array.

If an array without an _id field was provided as the document_or_id parameter, NULL will be returned.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

     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().

Example #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

Descrierea

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));
}

?>

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the database response.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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]

Descrierea

public array MongoDB::dropCollection ( mixed $coll )
Avertizare

Deprecated

Use MongoCollection::drop() instead.

This function leaks memory in version 1.0.7 and earlier!

Parametri

coll

MongoCollection or name of collection to drop.

Valorile întoarse

Returns the database response.

MongoDB::drop
MongoDB::execute
MongoDB


Runs JavaScript code on the database server [deprecated]

MongoDB::dropCollection
MongoDB::forceError
MongoDB
PHP Manual

MongoDB::execute

(PECL mongo >=0.9.3)

MongoDB::execute — Runs JavaScript code on the database server [deprecated]

Descrierea

public array MongoDB::execute ( mixed $code [, array $args = array() ] )
Avertizare

The » eval command, which this method invokes, is deprecated in MongoDB 3.0+.

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 the » eval 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.

Parametri

code

MongoCode or string to execute.

args

Arguments to be passed to code.

Valorile întoarse

Returns the result of the evaluation.

Exemple

Example #1 Simple MongoDB::execute() example

<?php

$response = $db->execute("function() { return 'Hello, world!'; }");
echo $response['retval'];

?>

Exemplul de mai sus va afi?a ceva similar cu:

Hello, world!

Example #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'];

?>

Exemplul de mai sus va afi?a ceva similar cu:

Good bye, Joe!

Example #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'];

?>

Exemplul de mai sus va afi?a ceva similar cu:

Goodbye, Joe, says Fred

A se vedea ?i

  • The MongoDB » eval command docs

Istoricul schimbarilor

Versiune | Descriere
1.7.0 | This method has been deprecated as a result of the underlaying » eval command being deprecated in MongoDB 3.0+.

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

Descrierea

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));
}

?>

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the database response.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

MongoDB::execute
MongoDB::__get
MongoDB


Gets a collection

MongoDB::forceError
MongoDB::getCollectionInfo
MongoDB
PHP Manual

MongoDB::__get

(PECL mongo >=1.0.2)

MongoDB::__get — Gets a collection

Descrierea

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 MongoClient();

// the following two lines are equivalent
$collection = $mongo->selectDB("foo")->selectCollection("bar");
$collection = $mongo->foo->bar;

?>

Parametri

name

The name of the collection.

Valorile întoarse

Returns the collection.

MongoDB::forceError
MongoDB::getCollectionInfo
MongoDB


Returns information about collections in this database

MongoDB::__get
MongoDB::getCollectionNames
MongoDB
PHP Manual

MongoDB::getCollectionInfo

(PECL mongo >=1.6.0)

MongoDB::getCollectionInfo — Returns information about collections in this database

Descrierea

public array MongoDB::getCollectionInfo ([ array $options = array() ] )

Gets a list of all collections in the database and returns them as an array of documents, which contain their names and options.

Nota: Aceasta metoda va utiliza comanda bazei de date » listCollections la comunicarea cu MongoDB 2.8+. Pentru versiunile anterioare ale bazei de date, metoda va interpela colec?ia speciala system.namespaces.

Parametri

options

An array of options for listing the collections. Currently available options include:

  • "filter"

    Criteriu op?ional pentru interpelare. Daca este furnizat, acest criteriu va fi utilizat pentru a filtra colec?ile incluse în rezultat.

    Câmpurile relevante, ce pot fi interpelate, includ "name" (colec?ia name ca ?ir de caractere, fara prefixul cu denumirea bazei de date) ?i "options" (obiect ce con?ine op?iuni utilizate la crearea colec?iei)..

    Nota: MongoDB 2.6 ?i versiunile anterioare necesita ca criteriul "name", daca este specificat, sa fie o valoare string (de ex. potrivirea la egalitate). Aceasta este din cauza ca driver-ul trebuie sa adauge ca prefix la valoare denumirea bazei de date pentru a interpela colec?ia system.namespaces. Versiunile ulterioare ale MongoDB nu au aceasta limitare, deoarece driver-ul va utiliza comanda listCollections.

  • "includeSystemCollections"

    Boolean, implicit este FALSE. Determina daca colec?iile de sistem trebuie incluse în rezultat.

The following option may be used with MongoDB 2.8+:

  • "maxTimeMS"

    Specifica o limita de timp cumulativa în milisecunde pentru procesarea opera?iunii pe server (nu include timpul de a?teptare). Daca opera?iunea nu este terminata pe server în timpul rezervat, va fi emisa o MongoExecutionTimeoutException.

Valorile întoarse

This function returns an array where each element is an array describing a collection. Elements will contain a name key denoting the name of the collection, and optionally contain an options key denoting an array of objects used to create the collection. For example, capped collections will include capped and size options.

Erori/Excep?ii

For MongoDB 2.6 and earlier, MongoException will be thrown if a non-string value was specified for the "filter" option's "name" criteria.

Exemple

Example #1 MongoDB::getCollectionInfo() example

<?php
$m = new MongoClient();
$db = $m->selectDB("demo");
var_dump($db->getCollectionInfo());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(4) "logs"
    ["options"]=>
    array(2) {
      ["capped"]=>
      bool(true)
      ["size"]=>
      int(10240)
    }
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(5) "users"
    ["options"]=>
    array(1) {
      ["flags"]=>
      int(1)
    }
  }
}

A se vedea ?i

  • MongoDB::getCollectionNames() - Gets an array of names for all collections in this database
  • MongoDB::listCollections() - Gets an array of MongoCollection objects for all collections in this database

MongoDB::__get
MongoDB::getCollectionNames
MongoDB


Gets an array of names for all collections in this database

MongoDB::getCollectionInfo
MongoDB::getDBRef
MongoDB
PHP Manual

MongoDB::getCollectionNames

(PECL mongo >=1.3.0)

MongoDB::getCollectionNames — Gets an array of names for all collections in this database

Descrierea

public array MongoDB::getCollectionNames ([ array $options = array() ] )

Gets a list of all collections in the database and returns their names as an array of strings.

Nota: Aceasta metoda va utiliza comanda bazei de date » listCollections la comunicarea cu MongoDB 2.8+. Pentru versiunile anterioare ale bazei de date, metoda va interpela colec?ia speciala system.namespaces.

Parametri

options

An array of options for listing the collections. Currently available options include:

  • "filter"

    Criteriu op?ional pentru interpelare. Daca este furnizat, acest criteriu va fi utilizat pentru a filtra colec?ile incluse în rezultat.

    Câmpurile relevante, ce pot fi interpelate, includ "name" (colec?ia name ca ?ir de caractere, fara prefixul cu denumirea bazei de date) ?i "options" (obiect ce con?ine op?iuni utilizate la crearea colec?iei)..

    Nota: MongoDB 2.6 ?i versiunile anterioare necesita ca criteriul "name", daca este specificat, sa fie o valoare string (de ex. potrivirea la egalitate). Aceasta este din cauza ca driver-ul trebuie sa adauge ca prefix la valoare denumirea bazei de date pentru a interpela colec?ia system.namespaces. Versiunile ulterioare ale MongoDB nu au aceasta limitare, deoarece driver-ul va utiliza comanda listCollections.

  • "includeSystemCollections"

    Boolean, implicit este FALSE. Determina daca colec?iile de sistem trebuie incluse în rezultat.

The following option may be used with MongoDB 2.8+:

  • "maxTimeMS"

    Specifica o limita de timp cumulativa în milisecunde pentru procesarea opera?iunii pe server (nu include timpul de a?teptare). Daca opera?iunea nu este terminata pe server în timpul rezervat, va fi emisa o MongoExecutionTimeoutException.

Valorile întoarse

Returns the collection names as an array of strings.

Erori/Excep?ii

For MongoDB 2.6 and earlier, MongoException will be thrown if a non-string value was specified for the "filter" option's "name" criteria.

Istoricul schimbarilor

Versiune | Descriere
1.6.0 | Changed first parameter to be an array of options. Pre-1.6.0, the first parameter was a boolean indicating the "includeSystemCollections" option.

Exemple

Example #1 MongoDB::getCollectionNames() example

<?php
$m = new MongoClient();
$db = $m->selectDB("demo");
$collections = $db->getCollectionNames();

foreach ($collections as $collectionName) {
    echo "Found collection: ", $collectionName, "\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

...
Found collection: img
Found collection: beer
Found collection: collation
...

A se vedea ?i

  • MongoDB::listCollections() - Gets an array of MongoCollection objects for all collections in this database
  • MongoDB::getCollectionInfo() - Returns information about collections in this database

MongoDB::getCollectionInfo
MongoDB::getDBRef
MongoDB


Fetches the document pointed to by a database reference

MongoDB::getCollectionNames
MongoDB::getGridFS
MongoDB
PHP Manual

MongoDB::getDBRef

(PECL mongo >=0.9.0)

MongoDB::getDBRef — Fetches the document pointed to by a database reference

Descrierea

public array MongoDB::getDBRef ( array $ref )

Parametri

ref

A database reference.

Valorile întoarse

Returns the document pointed to by the reference.

Exemple

Example #1 MongoDB::getDBRef() example

Example demonstrating how to get a database reference and what the expected input is.

<?php

 $ref = array(
   '$ref' => 'profiles',
   '$id' => new MongoId('47cc67093475061e3d9536d2')
 );

 $profile = $db->getDBRef($ref);
 ?>

See MongoDB::createDBRef() for more information about how to programatically create DB references.

MongoDB::getCollectionNames
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

Descrierea

public MongoGridFS MongoDB::getGridFS ([ string $prefix = "fs" ] )

Parametri

prefix

The prefix for the files and chunks collections.

Valorile întoarse

Returns a new gridfs object for this database.

Exemple

Example #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::getReadPreference
MongoDB
PHP Manual

MongoDB::getProfilingLevel

(PECL mongo >=0.9.0)

MongoDB::getProfilingLevel — Gets this database's profiling level

Descrierea

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));
}

?>

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the profiling level.

A se vedea ?i

  • MongoDB core docs on » profiling
  • MongoDB::setProfilingLevel() - Sets this database's profiling level
MongoDB::getGridFS
MongoDB::getReadPreference
MongoDB


Get the read preference for this database

MongoDB::getProfilingLevel
MongoDB::getSlaveOkay
MongoDB
PHP Manual

MongoDB::getReadPreference

(PECL mongo >=1.3.0)

MongoDB::getReadPreference — Get the read preference for this database

Descrierea

public array MongoDB::getReadPreference ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Aceasta func?ie întoarce un tablou ce descrie preferin?a de citire. Tabloul con?ine tipul (type) valorilor pentru ?irul cu modul preferin?ei de citire (ce corespunde constantelor MongoClient), ?i tagsets con?inând lista tuturor criteriilor setului de etichete. Daca nu a fost specificat nici un set de etichete, tagsets nu va fi prezent în tablou.

Istoricul schimbarilor

Versiune | Descriere
1.3.3 | The return value has changed to be consistent with MongoDB::setReadPreference(). The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.

Exemple

Example #1 MongoDB::getReadPreference() return value example

<?php

$m = new MongoClient();
$db = $m->test;
$db->setReadPreference(MongoClient::RP_SECONDARY, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
    array(),
));
var_dump($db->getReadPreference());
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["type"]=>
  string(9) "secondary"
  ["tagsets"]=>
  array(3) {
    [0]=>
    array(2) {
      ["dc"]=>
      string(4) "east"
      ["use"]=>
      string(9) "reporting"
    }
    [1]=>
    array(1) {
      ["dc"]=>
      string(7) "west"
    }
    [2]=>
    array(0) {
    }
  }
}

A se vedea ?i

  • The read preferences documentation.
  • MongoDB::setReadPreference() - Set the read preference for this database
MongoDB::getProfilingLevel
MongoDB::getSlaveOkay
MongoDB


Get slaveOkay setting for this database

MongoDB::getReadPreference
MongoDB::getWriteConcern
MongoDB
PHP Manual

MongoDB::getSlaveOkay

(PECL mongo >=1.1.0)

MongoDB::getSlaveOkay — Get slaveOkay setting for this database

Descrierea

public bool MongoDB::getSlaveOkay ( void )

See the query section of this manual for information on distributing reads to secondaries.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the value of slaveOkay for this instance.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

A se vedea ?i

  • Read Preferences
  • MongoDB::getReadPreference() - Get the read preference for this database
  • MongoDB::setReadPreference() - Set the read preference for this database
MongoDB::getReadPreference
MongoDB::getWriteConcern
MongoDB


Get the write concern for this database

MongoDB::getSlaveOkay
MongoDB::lastError
MongoDB
PHP Manual

MongoDB::getWriteConcern

(PECL mongo >=1.5.0)

MongoDB::getWriteConcern — Get the write concern for this database

Descrierea

public array MongoDB::getWriteConcern ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Aceasta func?ie întoarce un tablou ce descrie gradul de participare la înscriere. Tabloul con?ine valorile w pentru un nivel de confirmare întreg sau ca ?ir de caractere ?i wtimeout ce denota numarul maximal de milisecunde de a?teptare pâna când serverul satisface gradul de participare la înscriere.

Exemple

Example #1 MongoDB::getWriteConcern() return value example

<?php

$mc = new MongoClient('mongodb://localhost:27017', array('wTimeoutMS' => 500));
$db = $mc->selectDB('test');
var_dump($db->getWriteConcern());

$db->setWriteConcern(1, 1000);
var_dump($db->getWriteConcern());
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(500)
}
array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(1000)
}

A se vedea ?i

  • The write concern documentation.
  • MongoDB::setWriteConcern() - Set the write concern for this database
MongoDB::getSlaveOkay
MongoDB::lastError
MongoDB


Check if there was an error on the most recent db operation performed

MongoDB::getWriteConcern
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

Descrierea

public array MongoDB::lastError ( void )

This method is equivalent to:

<?php

public function lastError() {
    return $this->command(array('getlasterror' => 1));
}

?>

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the error, if there was one.

Exemple

Example #1 MongoDB::lastError() NULL error example

<?php
$db->resetError();
var_dump($db->lastError());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  ["err"]=>
  NULL
  ["n"]=>
  int(0)
  ["ok"]=>
  float(1)
}

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  ["err"]=>
  string(64) "E11000 duplicate key errorindex: foo.foo.$_id_  dup key: { : 1 }"
  ["n"]=>
  int(0)
  ["ok"]=>
  float(1)
}
MongoDB::getWriteConcern
MongoDB::listCollections
MongoDB


Gets an array of MongoCollection objects for all collections in this database

MongoDB::lastError
MongoDB::prevError
MongoDB
PHP Manual

MongoDB::listCollections

(PECL mongo >=0.9.0)

MongoDB::listCollections — Gets an array of MongoCollection objects for all collections in this database

Descrierea

public array MongoDB::listCollections ([ array $options = array() ] )

Gets a list of all collections in the database and returns them as an array of MongoCollection objects.

Nota: Aceasta metoda va utiliza comanda bazei de date » listCollections la comunicarea cu MongoDB 2.8+. Pentru versiunile anterioare ale bazei de date, metoda va interpela colec?ia speciala system.namespaces.

Parametri

options

An array of options for listing the collections. Currently available options include:

  • "filter"

    Criteriu op?ional pentru interpelare. Daca este furnizat, acest criteriu va fi utilizat pentru a filtra colec?ile incluse în rezultat.

    Câmpurile relevante, ce pot fi interpelate, includ "name" (colec?ia name ca ?ir de caractere, fara prefixul cu denumirea bazei de date) ?i "options" (obiect ce con?ine op?iuni utilizate la crearea colec?iei)..

    Nota: MongoDB 2.6 ?i versiunile anterioare necesita ca criteriul "name", daca este specificat, sa fie o valoare string (de ex. potrivirea la egalitate). Aceasta este din cauza ca driver-ul trebuie sa adauge ca prefix la valoare denumirea bazei de date pentru a interpela colec?ia system.namespaces. Versiunile ulterioare ale MongoDB nu au aceasta limitare, deoarece driver-ul va utiliza comanda listCollections.

  • "includeSystemCollections"

    Boolean, implicit este FALSE. Determina daca colec?iile de sistem trebuie incluse în rezultat.

The following option may be used with MongoDB 2.8+:

  • "maxTimeMS"

    Specifica o limita de timp cumulativa în milisecunde pentru procesarea opera?iunii pe server (nu include timpul de a?teptare). Daca opera?iunea nu este terminata pe server în timpul rezervat, va fi emisa o MongoExecutionTimeoutException.

Valorile întoarse

Returns an array of MongoCollection objects.

Erori/Excep?ii

For MongoDB 2.6 and earlier, MongoException will be thrown if a non-string value was specified for the "filter" option's "name" criteria.

Istoricul schimbarilor

Versiune | Descriere
1.6.0 | Changed first parameter to be an array of options. Pre-1.6.0, the first parameter was a boolean indicating the "includeSystemCollections" option.
1.3.0 | Added the includeSystemCollections parameter.

Exemple

Example #1 MongoDB::listCollections() example

The following example demonstrates running count on each collection in a database.

<?php

$m = new MongoClient();
$db = $m->selectDB("demo");
$collections = $db->listCollections();

foreach ($collections as $collection) {
    echo "amount of documents in $collection: ";
    echo $collection->count(), "\n";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

...
amount of documents in demo.pubs: 4
amount of documents in demo.elephpants: 3
amount of documents in demo.cities: 22840
...

A se vedea ?i

  • MongoDB::getCollectionNames() - Gets an array of names for all collections in this database
  • MongoDB::getCollectionInfo() - Returns information about collections in this database

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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the error and the number of operations ago it occurred.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

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

Descrierea

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));
}

?>

Parametri

preserve_cloned_files

If cloned files should be kept if the repair fails.

backup_original_files

If original files should be backed up.

Valorile întoarse

Returns db response.

A se vedea ?i

MongoDB core docs on » repairDatabase.

Exemple

Example #1 MongoDB::repair() example

This example demonstrates how to repare and compact a database.

<?php

$db = $mongo->foo;

$response = $db->repair();
print_r($response);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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));
}

?>

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the database response.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

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

Descrierea

public MongoCollection MongoDB::selectCollection ( string $name )

Parametri

name

The collection name.

Valorile întoarse

Returns a new collection object.

Erori/Excep?ii

Throws Exception if the collection name is invalid.

MongoDB::resetError
MongoDB::setProfilingLevel
MongoDB


Sets this database's profiling level

MongoDB::selectCollection
MongoDB::setReadPreference
MongoDB
PHP Manual

MongoDB::setProfilingLevel

(PECL mongo >=0.9.0)

MongoDB::setProfilingLevel — Sets this database's profiling level

Descrierea

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.

Parametri

level

Profiling level.

Valorile întoarse

Returns the previous profiling level.

A se vedea ?i

  • MongoDB core docs on » profiling
  • MongoDB::getProfilingLevel() - Gets this database's profiling level
MongoDB::selectCollection
MongoDB::setReadPreference
MongoDB


Set the read preference for this database

MongoDB::setProfilingLevel
MongoDB::setSlaveOkay
MongoDB
PHP Manual

MongoDB::setReadPreference

(PECL mongo >=1.3.0)

MongoDB::setReadPreference — Set the read preference for this database

Descrierea

public bool MongoDB::setReadPreference ( string $read_preference [, array $tags ] )

Parametri

read_preference

Modul preferin?ei de citire:
MongoClient::RP_PRIMARY,
MongoClient::RP_PRIMARY_PREFERRED,
MongoClient::RP_SECONDARY,
MongoClient::RP_SECONDARY_PREFERRED sau
MongoClient::RP_NEAREST.

tags

Un tablou din zero sau mai multe seturi de etichete, unde fiecare set de etichete este la rândul sau un tablou de criterii utilizate pentru a potrivi etichetele pe membrii setului de replicare.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

Erori/Excep?ii

Emite un E_WARNING daca careva parametru nu e valid, sau daca unul sau mai multe seturi de etichete sunt furnizate cu modul preferin?ei de citire MongoClient::RP_PRIMARY.

Exemple

Example #1 MongoDB::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient();
$db = $m->test;

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$db->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));
?>

A se vedea ?i

  • The read preferences documentation.
  • MongoDB::getReadPreference() - Get the read preference for this database
MongoDB::setProfilingLevel
MongoDB::setSlaveOkay
MongoDB


Change slaveOkay setting for this database

MongoDB::setReadPreference
MongoDB::setWriteConcern
MongoDB
PHP Manual

MongoDB::setSlaveOkay

(PECL mongo >=1.1.0)

MongoDB::setSlaveOkay — Change slaveOkay setting for this database

Descrierea

public bool MongoDB::setSlaveOkay ([ bool $ok = true ] )

See the query section of this manual for information on distributing reads to secondaries.

Parametri

ok

If reads should be sent to secondary members of a replica set for all possible queries using this MongoDB instance.

Valorile întoarse

Returns the former value of slaveOkay for this instance.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

A se vedea ?i

  • Read Preferences
  • MongoDB::setReadPreference() - Set the read preference for this database
  • MongoDB::getReadPreference() - Get the read preference for this database
MongoDB::setReadPreference
MongoDB::setWriteConcern
MongoDB


Set the write concern for this database

MongoDB::setSlaveOkay
MongoDB::__toString
MongoDB
PHP Manual

MongoDB::setWriteConcern

(PECL mongo >=1.5.0)

MongoDB::setWriteConcern — Set the write concern for this database

Descrierea

public bool MongoDB::setWriteConcern ( mixed $w [, int $wtimeout ] )

Parametri

w

Gradul de participare la înscriere. Aceasta poate fi un întreg ce denota numarul de servere necesare pentru a confirma opera?iunea de înscriere, sau un mod scris ca ?ir de caractere (de ex. "majority").

wtimeout

Numarul maximal de milisecunde de a?teptare pâna când serverul satisface gradul de participare la înscriere.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

Erori/Excep?ii

Emite un E_WARNING daca parametrul w nu este un întreg sau un ?ir de caractere.

Exemple

Example #1 MongoDB::setWriteConcern() example

<?php

$mc = new MongoClient('mongodb://rs1.example.com,rs2.example.com');
$db = $mc->selectDB('test');

// Require that the majority of servers in the replica set acknowledge writes
// within three seconds.
$db->setWriteConcern('majority', 3000);
?>

A se vedea ?i

  • The write concern documentation.
  • MongoDB::getWriteConcern() - Get the write concern for this database
MongoDB::setSlaveOkay
MongoDB::__toString
MongoDB


The name of this database

MongoDB::setWriteConcern
MongoCollection
MongoDB
PHP Manual

MongoDB::__toString

(PECL mongo >=0.9.0)

MongoDB::__toString — The name of this database

Descrierea

public string MongoDB::__toString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns this database's name.

MongoDB::setWriteConcern
MongoCollection
MongoDB


The MongoCollection class

(PECL mongo >=0.9.0)

Introducere

Represents a MongoDB 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.

Sinopsisul clasei

MongoCollection {
/* Constante */
const int ASCENDING = 1 ;
const int DESCENDING = -1 ;
/* Fields */
public MongoDB $db = NULL ;
public integer $w ;
public integer $wtimeout ;
/* Metode */
public array aggregate ( array $pipeline [, array $options ] )
public MongoCommandCursor aggregateCursor ( array $command [, array $options ] )
public mixed batchInsert ( array $a [, array $options = array() ] )
public __construct ( MongoDB $db , string $name )
public int count ([ array $query = array() [, array $options = array() ]] )
public array createDBRef ( mixed $document_or_id )
public bool createIndex ( array $keys [, array $options = array() ] )
public array deleteIndex ( string|array $keys )
public array deleteIndexes ( void )
public array distinct ( string $key [, array $query ] )
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 findAndModify ( array $query [, array $update [, array $fields [, array $options ]]] )
 public array findOne
  ([ array $query = array()
 [, array $fields = array()
 [, array $options = array()
]]] )
public MongoCollection __get ( string $name )
public array getDBRef ( array $ref )
public array getIndexInfo ( void )
public string getName ( void )
public array getReadPreference ( void )
public bool getSlaveOkay ( void )
public array getWriteConcern ( void )
public array group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] )
public bool|array insert ( array|object $document [, array $options = array() ] )
public array[MongoCommandCursor] parallelCollectionScan ( int $num_cursors )
public bool|array remove ([ array $criteria = array() [, array $options = array() ]] )
public mixed save ( array|object $document [, array $options = array() ] )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public bool setSlaveOkay ([ bool $ok = true ] )
public bool setWriteConcern ( mixed $w [, int $wtimeout ] )
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 ] )
}

Constante predefinite

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.

A se vedea ?i

MongoDB core docs on » collections.

Cuprins

  • MongoCollection::aggregate — Perform an aggregation using the aggregation framework
  • MongoCollection::aggregateCursor — Execute an aggregation pipeline command and retrieve results through a cursor
  • 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::createIndex — Creates an index on the specified field(s) if it does not already exist.
  • MongoCollection::deleteIndex — Deletes an index from this collection
  • MongoCollection::deleteIndexes — Delete all indices for this collection
  • MongoCollection::distinct — Retrieve a list of distinct values for the given key across a collection.
  • MongoCollection::drop — Drops this collection
  • MongoCollection::ensureIndex — Creates an index on the specified field(s) if it does not already exist.
  • MongoCollection::find — Queries this collection, returning a MongoCursor for the result set
  • MongoCollection::findAndModify — Update a document and return it
  • MongoCollection::findOne — Queries 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::getReadPreference — Get the read preference for this collection
  • MongoCollection::getSlaveOkay — Get slaveOkay setting for this collection
  • MongoCollection::getWriteConcern — Get the write concern for this collection
  • MongoCollection::group — Performs an operation similar to SQL's GROUP BY command
  • MongoCollection::insert — Inserts a document into the collection
  • MongoCollection::parallelCollectionScan — Returns an array of cursors to iterator over a full collection in parallel
  • MongoCollection::remove — Remove records from this collection
  • MongoCollection::save — Saves a document to this collection
  • MongoCollection::setReadPreference — Set the read preference for this collection
  • MongoCollection::setSlaveOkay — Change slaveOkay setting for this collection
  • MongoCollection::setWriteConcern — Set the write concern for this database
  • 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::aggregate
Clase de baza


Perform an aggregation using the aggregation framework

MongoCollection
MongoCollection::aggregateCursor
MongoCollection
PHP Manual

MongoCollection::aggregate

(PECL mongo >=1.3.0)

MongoCollection::aggregate — Perform an aggregation using the aggregation framework

Descrierea

public array MongoCollection::aggregate ( array $pipeline [, array $options ] )
public array MongoCollection::aggregate ( array $op [, array $op [, array $... ]] )

The MongoDB » aggregation framework provides a means to calculate aggregated values without having to use MapReduce. While MapReduce is powerful, it is often more difficult than necessary for many simple aggregation tasks, such as totaling or averaging field values.

This method accepts either a variable amount of pipeline operators, or a single array of operators constituting the pipeline.

Parametri

pipeline

An array of pipeline operators.

options

Options for the aggregation command. Valid options include:

  • "allowDiskUse"

    Allow aggregation stages to write to temporary files

  • "cursor"

    Options controlling the creation of the cursor object. This option causes the command to return a result document suitable for constructing a MongoCommandCursor. If you need to use this option, you should consider using MongoCollection::aggregateCursor().

  • "explain"

    Return information on the processing of the pipeline.

  • "maxTimeMS"

    Specifica o limita de timp cumulativa în milisecunde pentru procesarea opera?iunii pe server (nu include timpul de a?teptare). Daca opera?iunea nu este terminata pe server în timpul rezervat, va fi emisa o MongoExecutionTimeoutException.

Or

op

First pipeline operator.

op

The second pipeline operator.

...

Additional pipeline operators.

Valorile întoarse

The result of the aggregation as an array. The ok will be set to 1 on success, 0 on failure.

Erori/Excep?ii

When an error occurs an array with the following keys will be returned:

  • errmsg - containing the reason for the failure
  • code - the errorcode of the failure
  • ok - will be set to 0.

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Added optional options argument

Exemple

Example #1 MongoCollection::aggregate() example

The following example aggregation operation pivots data to create a set of author names grouped by tags applied to an article. Call the aggregation framework by issuing the following command:

<?php
$m = new MongoClient("localhost");
$c = $m->selectDB("examples")->selectCollection("article");
$data = array (
    'title' => 'this is my title',
    'author' => 'bob',
    'posted' => new MongoDate,
    'pageViews' => 5,
    'tags' => array ( 'fun', 'good', 'fun' ),
    'comments' => array (
      array (
        'author' => 'joe',
        'text' => 'this is cool',
      ),
      array (
        'author' => 'sam',
        'text' => 'this is bad',
      ),
    ),
    'other' =>array (
      'foo' => 5,
    ),
);
$d = $c->insert($data, array("w" => 1));

$ops = array(
    array(
        '$project' => array(
            "author" => 1,
            "tags"   => 1,
        )
    ),
    array('$unwind' => '$tags'),
    array(
        '$group' => array(
            "_id" => array("tags" => '$tags'),
            "authors" => array('$addToSet' => '$author'),
        ),
    ),
);
$results = $c->aggregate($ops);
var_dump($results);
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["result"]=>
  array(2) {
    [0]=>
    array(2) {
      ["_id"]=>
      array(1) {
        ["tags"]=>
        string(4) "good"
      }
      ["authors"]=>
      array(1) {
        [0]=>
        string(3) "bob"
      }
    }
    [1]=>
    array(2) {
      ["_id"]=>
      array(1) {
        ["tags"]=>
        string(3) "fun"
      }
      ["authors"]=>
      array(1) {
        [0]=>
        string(3) "bob"
      }
    }
  }
  ["ok"]=>
  float(1)
}

The following examples use the » zipcode data set. Use mongoimport to load this data set into your mongod instance.

Example #2 MongoCollection::aggregate() example

To return all states with a population greater than 10 million, use the following aggregation operation:

<?php
$m = new MongoClient("localhost");
$c = $m->selectDB("test")->selectCollection("zips");

$pipeline = array(
    array(
        '$group' => array(
            '_id' => array('state' => '$state'),
            'totalPop' => array('$sum' => '$pop')
        )
    ),
    array(
        '$match' => array(
            'totalPop' => array('$gte' => 10 * 1000 * 1000)
        )
    ),
);
$out = $c->aggregate($pipeline);
var_dump($out);
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  ["result"]=>
  array(7) {
    [0]=>
    array(2) {
      ["_id"]=>
      string(2) "TX"
      ["totalPop"]=>
      int(16986510)
    }
    [1]=>
    array(2) {
      ["_id"]=>
      string(2) "PA"
      ["totalPop"]=>
      int(11881643)
    }
    [2]=>
    array(2) {
      ["_id"]=>
      string(2) "NY"
      ["totalPop"]=>
      int(17990455)
    }
    [3]=>
    array(2) {
      ["_id"]=>
      string(2) "IL"
      ["totalPop"]=>
      int(11430602)
    }
    [4]=>
    array(2) {
      ["_id"]=>
      string(2) "CA"
      ["totalPop"]=>
      int(29760021)
    }
    [5]=>
    array(2) {
      ["_id"]=>
      string(2) "OH"
      ["totalPop"]=>
      int(10847115)
    }
    [6]=>
    array(2) {
      ["_id"]=>
      string(2) "FL"
      ["totalPop"]=>
      int(12937926)
    }
  }
  ["ok"]=>
  float(1)
}

Example #3 MongoCollection::aggregate() example

To return the average populations for cities in each state, use the following aggregation operation:

<?php
$m = new MongoClient;
$c = $m->selectDB("test")->selectCollection("zips");

$out = $c->aggregate(
    array(
        '$group' => array(
            '_id' => array('state' => '$state', 'city' => '$city' ),
            'pop' => array('$sum' => '$pop' )
        )
    ),
    array(
        '$group' => array(
            '_id' => '$_id.state',
            'avgCityPop' => array('$avg' => '$pop')
        )
    )
);

var_dump($out);
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  ["result"]=>
  array(51) {
    [0]=>
    array(2) {
      ["_id"]=>
      string(2) "DC"
      ["avgCityPop"]=>
      float(303450)
    }
    [1]=>
    array(2) {
      ["_id"]=>
      string(2) "DE"
      ["avgCityPop"]=>
      float(14481.913043478)
    }
...
    [49]=>
    array(2) {
      ["_id"]=>
      string(2) "WI"
      ["avgCityPop"]=>
      float(7323.0074850299)
    }
    [50]=>
    array(2) {
      ["_id"]=>
      string(2) "WV"
      ["avgCityPop"]=>
      float(2759.1953846154)
    }
  }
  ["ok"]=>
  float(1)
}

Example #4 MongoCollection::aggregate() with command options

To return information on how the pipeline will be processed we use the explain command option:

<?php
$m = new MongoClient;
$c = $m->selectDB("test")->selectCollection("zips");

$pipeline = array(
    array(
        '$group' => array(
            '_id' => '$state',
           'totalPop' => array('$sum' => '$pop'),
        ),
    ),
    array(
        '$match' => array(
            'totalPop' => array('$gte' => 10 * 1000 * 1000)
        )
    ),
    array(
        '$sort' => array("totalPop" => -1),
    ),
);

$options = array("explain" => true);
$out = $c->aggregate($pipeline, $options);
var_dump($out);
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  ["stages"]=>
  array(4) {
    [0]=>
    array(1) {
      ["$cursor"]=>
      array(3) {
        ["query"]=>
        array(0) {
        }
        ["fields"]=>
        array(3) {
          ["pop"]=>
          int(1)
          ["state"]=>
          int(1)
          ["_id"]=>
          int(0)
        }
        ["plan"]=>
        array(4) {
          ["cursor"]=>
          string(11) "BasicCursor"
          ["isMultiKey"]=>
          bool(false)
          ["scanAndOrder"]=>
          bool(false)
          ["allPlans"]=>
          array(1) {
            [0]=>
            array(3) {
              ["cursor"]=>
              string(11) "BasicCursor"
              ["isMultiKey"]=>
              bool(false)
              ["scanAndOrder"]=>
              bool(false)
            }
          }
        }
      }
    }
    [1]=>
    array(1) {
      ["$group"]=>
      array(2) {
        ["_id"]=>
        string(6) "$state"
        ["totalPop"]=>
        array(1) {
          ["$sum"]=>
          string(4) "$pop"
        }
      }
    }
    [2]=>
    array(1) {
      ["$match"]=>
      array(1) {
        ["totalPop"]=>
        array(1) {
          ["$gte"]=>
          int(10000000)
        }
      }
    }
    [3]=>
    array(1) {
      ["$sort"]=>
      array(1) {
        ["sortKey"]=>
        array(1) {
          ["totalPop"]=>
          int(-1)
        }
      }
    }
  }
  ["ok"]=>
  float(1)
}

A se vedea ?i

  • MongoCollection::aggregateCursor() - Execute an aggregation pipeline command and retrieve results through a cursor
  • The MongoDB » aggregation framework
MongoCollection
MongoCollection::aggregateCursor
MongoCollection


Execute an aggregation pipeline command and retrieve results through a cursor

MongoCollection::aggregate
MongoCollection::batchInsert
MongoCollection
PHP Manual

MongoCollection::aggregateCursor

(PECL mongo >=1.5.0)

MongoCollection::aggregateCursor — Execute an aggregation pipeline command and retrieve results through a cursor

Descrierea

public MongoCommandCursor MongoCollection::aggregateCursor ( array $command [, array $options ] )

With this method you can execute Aggregation Framework pipelines and retrieve the results through a cursor, instead of getting just one document back as you would with MongoCollection::aggregate(). This method returns a MongoCommandCursor object. This cursor object implements the Iterator interface just like the MongoCursor objects that are returned by the MongoCollection::find() method.

Nota: The resulting MongoCommandCursor will inherit this collection's read preference. MongoCommandCursor::setReadPreference() may be used to change the read preference before iterating on the cursor.

Parametri

pipeline

The Aggregation Framework pipeline to execute.

options

Options for the aggregation command. Valid options include:

  • "allowDiskUse"

    Allow aggregation stages to write to temporary files

  • "cursor"

    It is possible to configure how many initial documents the server should return with the first result set. The default initial batch size is 101. You can change it by adding the batchSize option:

    <?php
    $collection    ->aggregateCursor(
            $pipeline,
        [     "cursor" => [ "batchSize" => 4 ] ]
    );

    This option only configures the size of the first batch. To configure the size of future batches, please use the MongoCommandCursor::batchSize() method on the returned MongoCommandCursor object.

  • "explain"

    Return information on the processing of the pipeline. This option may cause the command to return a result document that is unsuitable for constructing a MongoCommandCursor. If you need to use this option, you should consider using MongoCollection::aggregate().

  • "maxTimeMS"

    Specifica o limita de timp cumulativa în milisecunde pentru procesarea opera?iunii pe server (nu include timpul de a?teptare). Daca opera?iunea nu este terminata pe server în timpul rezervat, va fi emisa o MongoExecutionTimeoutException.

Valorile întoarse

Returns a MongoCommandCursor object. Because this implements the Iterator interface you can iterate over each of the results as returned by the command query. The MongoCommandCursor also implements the MongoCursorInterface interface which adds the MongoCommandCursor::batchSize(), MongoCommandCursor::dead(), MongoCommandCursor::info() methods.

Exemple

Example #1 MongoCollection::aggregateCursor() example

Finding all of the distinct values for a key.

<?php
$m = new MongoClient;
$db = $m->test;
$people = $db->people;
$people->drop();

$people->insert(array("name" => "Joe", "points" => 4));
$people->insert(array("name" => "Molly", "points" => 43));
$people->insert(array("name" => "Sally", "points" => 22));
$people->insert(array("name" => "Joe", "points" => 22));
$people->insert(array("name" => "Molly", "points" => 87));

$ages = $people->aggregateCursor( [
        [ '$group' => [ '_id' => '$name', 'points' => [ '$sum' => '$points' ] ] ],
        [ '$sort' => [ 'points' => -1 ] ],
] );

foreach ($ages as $person) {
    echo "{$person['_id']}: {$person['points']}\n";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

Molly: 130
Joe: 26
Sally: 22

Example #2 MongoCollection::aggregateCursor() example with different initial batch size

Finding all of the distinct values for a key.

<?php
$m = new MongoClient;
$db = $m->test;
$people = $db->people;
$people->drop();

/* Insert some sample data */
$people->insert(array("name" => "Joe", "points" => 4));
$people->insert(array("name" => "Molly", "points" => 43));
$people->insert(array("name" => "Sally", "points" => 22));
$people->insert(array("name" => "Joe", "points" => 22));
$people->insert(array("name" => "Molly", "points" => 87));

/* Run the command cursor */
$ages = $people->aggregateCursor(
    [
        [ '$group' => [ '_id' => '$name', 'points' => [ '$sum' => '$points' ] ] ],
        [ '$sort' => [ 'points' => -1 ] ],
    ],
    [ "cursor" => [ "batchSize" => 4 ] ]
);

foreach ($ages as $person) {
    echo "{$person['_id']}: {$person['points']}\n";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

Molly: 130
Joe: 26
Sally: 22

A se vedea ?i

  • MongoDB::command() - Execute a database command
  • MongoCommandCursor
  • MongoCommandCursor::batchSize() - Limits the number of elements returned in one batch.
  • MongoCollection::aggregate() - Perform an aggregation using the aggregation framework
  • The MongoDB » aggregation framework

MongoCollection::aggregate
MongoCollection::batchInsert
MongoCollection


Inserts multiple documents into this collection

MongoCollection::aggregateCursor
MongoCollection::__construct
MongoCollection
PHP Manual

MongoCollection::batchInsert

(PECL mongo >=0.9.0)

MongoCollection::batchInsert — Inserts multiple documents into this collection

Descrierea

public mixed MongoCollection::batchInsert ( array $a [, array $options = array() ] )

Parametri

a

An array of arrays or objects. If any objects are used, they may not have protected or private properties.

Nota:

If the documents to insert do not have an _id key or property, a new MongoId instance will be created and assigned to it. See MongoCollection::insert() for additional information on this behavior.

options

An array of options for the batch of insert operations. Currently available options include:

  • "continueOnError"

    Boolean, defaults to FALSE. If set, the database will not stop processing a bulk insert if one fails (eg due to duplicate IDs). This makes bulk insert behave similarly to a series of single inserts, except that calling MongoDB::lastError() will have an error set if any insert fails, not just the last one. If multiple errors occur, only the most recent will be reported by MongoDB::lastError().

    Nota:

    Please note that continueOnError affects errors on the database side only. If you try to insert a document that has errors (for example it contains a key with an empty name), then the document is not even transferred to the database as the driver detects this error and bails out. continueOnError has no effect on errors detected in the documents by the driver.

  • "fsync"

    O valoare boolean-a, valoarea implicita este FALSE. Daca jurnalizarea e activata, ea func?ioneaza exact ca "j". Daca jurnalizarea nu este acticvata, atunci se for?eaza sincronizarea pe disc a opera?iunii de inserare înainte de a întoarce succes. Daca are valoarea TRUE, se presupune efectuarea unei inserari cu confirmare ?i setarea w va fi modificata în 0.

    Nota: Daca jurnalizarea este activata, utilizatorii sunt încuraja?i sa utilizeze op?iunea "j" în loc de "fsync". Nu utiliza?i "fsync" ?i "j" simultan, deoarece aceasta va rezulta în eroare.

  • "j"

    O valoare boolean-a, cu valoarea implicita FALSE. For?eaza sincronizarea cu jurnalul a opera?iunii de inserare, înainte de a întoarce succes. Daca are valoarea TRUE, se presupune efectuarea unei inserari cu confirmare ?i setarea w va fi modificata în 0.

    Nota: Daca aceasta op?iune e utilizata, iar jurnalizarea e dezactivata, MongoDB 2.6+ va emite o eroare ?i înscrierea va e?ua; versiunile mai vechi ale serverului pur ?i simplu vor ignora op?iunea.

  • "socketTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru comunicarea prin socket. Daca serverul nu raspunde în limita intervalului de timp, se va emite o MongoCursorTimeoutException ?i nu va fi nici o posibilitate de a determina daca serverul a efectuat înscrierea, sau nu. Valoarea -1 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 30000 (30 secunde).

  • "w"

    Vede?i WriteConcerns. Valoarea implicita pentru MongoClient este 1.

  • "wTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru confirmarea write concern. Aceasta este aplicabila doar atunci când "w" este mai mare decât 1, deoarece expirarea timpului ?ine de replicare. Daca "write concern" nu este satisfacuta în limita intervalului de timp, se va emite o MongoCursorException. Valoarea 0 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 10000 (zece secunde).

The following options are deprecated and should no longer be used:

  • "safe"

    Învechita. Utiliza?i op?iunea WriteConcern w.

  • "timeout"

    Un pseudonim învechit pentru "socketTimeoutMS".

  • "wtimeout"

    Un pseudonim învechit pentru "wTimeoutMS".

Valorile întoarse

If the w parameter is set to acknowledge the write, returns an associative array with the status of the inserts ("ok") and any error that may have occurred ("err"). Otherwise, returns TRUE if the batch insert was successfully sent, FALSE otherwise.

Erori/Excep?ii

Throws MongoException if any inserted documents are empty or if they contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.

Genereaza o excep?ie MongoCursorException daca op?iunea "w" este stabilita ?i înscrierea e?ueaza.

Genereaza o excep?ie MongoCursorTimeoutException daca op?iunea "w" este stabilita la o valoare mai mare decât unu ?i opera?iunea dureaza mai mult de MongoCursor::$timeout milisecunde. Aceasta nu va întrerupe opera?iunea pe server, este un timeout de partea clientului. Opera?iunea din MongoCollection::$wtimeout este în milisecunde.

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option.
1.2.7 | Added "continueOnError" option.
1.0.9 | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option.
1.0.5 | Added options parameter.

Exemple

Example #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 MongoClient();
$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']);
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

4bf43ac68ead0e1971000000
4bf43ac68ead0e1971010000
4bf43ac68ead0e1971020000
...
string(5) "user1"
string(5) "user2"
string(5) "user3"
...

Example #2 MongoCollection::batchInsert() example with ignoring errors

<?php

$con = new Mongo;
$db = $con->demo;

$doc1 = array(
        '_id' => new MongoId('4cb4ab6d7addf98506010001'),
        'id' => 1,
        'desc' => "ONE",
);
$doc2 = array(
        '_id' => new MongoId('4cb4ab6d7addf98506010002'),
        'id' => 2,
        'desc' => "TWO",
);
$doc3 = array(
        '_id' => new MongoId('4cb4ab6d7addf98506010002'), // same _id as above
        'id' => 3,
        'desc' => "THREE",
);
$doc4 = array(
        '_id' => new MongoId('4cb4ab6d7addf98506010004'),
        'id' => 4,
        'desc' => "FOUR",
);

$c = $db->selectCollection('c');
$c->batchInsert(
    array($doc1, $doc2, $doc3, $doc4),
    array('continueOnError' => true)
);

$docs = $c->find();
foreach ($docs as $doc) {
    var_dump($doc['desc']);
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(3) "ONE"
string(3) "TWO"
string(4) "FOUR"

A se vedea ?i

  • MongoCollection::insert() - Inserts a document into the collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoCollection::find() - Queries this collection, returning a MongoCursor for the result set
  • MongoCollection::remove() - Remove records from this collection
  • MongoDB core docs on » insert.
MongoCollection::aggregateCursor
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

Descrierea

public MongoCollection::__construct ( MongoDB $db , string $name )

Parametri

MongoDB db

Parent database.

name

Name for this collection.

Valorile întoarse

Returns a new collection object.

Erori/Excep?ii

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

Descrierea

 public int MongoCollection::count
  ([ array $query = array()
 [, array $options = array()
]] )

Parametri

query

Associative array or object with fields to match.

options

An array of options for the index creation. Currently available options include:

Denumire | Tip | Descriere
hint mixed

Index to use for the query. If a string is passed, it should correspond to an index name. If an array or object is passed, it should correspond to the specification used to create the index (i.e. the first argument to MongoCollection::createIndex()).

This option is only supported in MongoDB 2.6+.
limit | integer | The maximum number of matching documents to return.
maxTimeMS integer

Specifies a cumulative time limit in milliseconds for processing the operation (does not include idle time). If the operation is not completed within the timeout period, a MongoExecutionTimeoutException will be thrown.

This option is only supported in MongoDB 2.6+.
skip | integer | The number of matching documents to skip before returning results.

Valorile întoarse

Returns the number of documents matching the query.

Erori/Excep?ii

Throws MongoResultException if the server could not execute the command due to an error.

Throws MongoExecutionTimeoutException if command execution was terminated due to maxTimeMS.

Istoricul schimbarilor

Versiune | Descriere
1.6.0 | The second parameter is now an options array. Passing limit and skip as the second and third parameters, respectively, is deprecated.
1.0.7 | Added limit and skip as second and third parameters, respectively.

Exemple

Example #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)));

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)
int(1)
MongoCollection::__construct
MongoCollection::createDBRef
MongoCollection


Creates a database reference

MongoCollection::count
MongoCollection::createIndex
MongoCollection
PHP Manual

MongoCollection::createDBRef

(PECL mongo >=0.9.0)

MongoCollection::createDBRef — Creates a database reference

Descrierea

public array MongoCollection::createDBRef ( mixed $document_or_id )

Parametri

document_or_id

If an array or object is given, its _id field will be used as the reference ID. If a MongoId or scalar is given, it will be used as the reference ID.

Valorile întoarse

Returns a database reference array.

If an array without an _id field was provided as the document_or_id parameter, NULL will be returned.

Exemple

Example #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)));

?>

A se vedea ?i

  • MongoCollection::getDBRef() - Fetches the document pointed to by a database reference

MongoCollection::count
MongoCollection::createIndex
MongoCollection


Creates an index on the specified field(s) if it does not already exist.

MongoCollection::createDBRef
MongoCollection::deleteIndex
MongoCollection
PHP Manual

MongoCollection::createIndex

(PECL mongo >=1.5.0)

MongoCollection::createIndex — Creates an index on the specified field(s) if it does not already exist.

Descrierea

public bool MongoCollection::createIndex ( array $keys [, array $options = array() ] )

Creates an index on the specified field(s) if it does not already exist. Fields may be indexed with a direction (e.g. ascending or descending) or a special type (e.g. text, geospatial, hashed).

Nota:

This method will use the » createIndexes database command when communicating with MongoDB 2.6+. For previous database versions, the method will perform an insert operation on the special system.indexes collection.

Parametri

keys

An array specifying the index's fields as its keys. For each field, the value is either the index direction or » index type. If specifying direction, specify 1 for ascending or -1 for descending.

options

An array of options for the index creation. We pass all given options straight to the server, but a non-exhaustive list of currently available options include:

  • "unique"

    Specifica?i TRUE pentru a crea un indice unic. Valoarea implicita este FALSE. Aceasta op?iune se aplica doar pentru indici ascenden?i/descenden?i.

    Nota:

    Când MongoDB indexeaza un câmp, daca un document nu are valoare pentru acel câmp, o valoare NULL este indexata. Daca mai multe documente nu con?in câmpul, un indice unic va respinge toate documentele în afara de primul. Opiunea "sparse" poate fi utilizata pentru a depa?i aceasta, deoarece ea va preveni indexarea documentelor fara valoarea câmpului.

  • "sparse"

    Specifica?i TRUE pentru a crea un indice distribuit, ce indexeaza doar documente ce con?in un anumit câmp. Valoarea implicita e FALSE.

  • "expireAfterSeconds"

    Valoarea acestei op?iuni ar trebui sa specifice numarul de secunde dupa care un document ar trebui sa fie considerat expirat ?i automat eliminat din colec?ie. Aceasta op?iune este compatibila doar cu indici pe un singur câmp, unde câmpul va con?ine valori MongoDate.

    Nota:

    Aceasta facilitate este disponibila în MongoDB 2.2+. A se vedea » Expirarea Datelor din Colec?ii prin Stabilirea TTL pentru informa?ii suplimentare.

  • "name"

    Un nume op?ional care identifica univoc indicele.

    Nota:

    Implicit driver-ul va genera un nume al indicelui bazat pe câmpurile lui ?i ordinea de sortare sau tip. De exemplu, un indice compus array("x" => 1, "y" => -1) va fi numit "x_1_y_-1" ?i un indice geospa?ial array("loc" => "2dsphere") va fi numit "loc_2dsphere". Pentru indici cu mai multe câmpuri este posibil ca numele generat sa depa?easca » limita pentru denumirile indicilor din MongoDB. Op?iunea "name" poate fi folosita în acest caz pentru a furniza un nume mai scurt.

  • "background"

    Calculeaza indicele în fundal, pentru ca aceasta sa nu blocheze alte activita?i ale bazei de date. Specifica?i TRUE pentru a calcula în fundal. Valoarea implicita e FALSE.

    Avertizare

    Înainte de MongoDB 2.6.0, calculele indicilor erau executate ca opera?iuni în prim plan, indiferent de aceasta op?iune. A se vedea » Calcularea Indicilor cu Seturi de Replici pentru informa?ii suplimentare.

  • "socketTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru comunicarea prin socket. Daca serverul nu raspunde în limita intervalului de timp, se va emite o MongoCursorTimeoutException ?i nu va fi nici o posibilitate de a determina daca serverul a efectuat înscrierea, sau nu. Valoarea -1 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 30000 (30 secunde).

The following option may be used with MongoDB 2.6+:

  • "maxTimeMS"

    Specifica o limita de timp cumulativa în milisecunde pentru procesarea opera?iunii pe server (nu include timpul de a?teptare). Daca opera?iunea nu este terminata pe server în timpul rezervat, va fi emisa o MongoExecutionTimeoutException.

The following options may be used with MongoDB versions before 2.8:

  • "dropDups"

    Specifica?i TRUE pentru a for?a crearea unui indice unic, când colec?ia poate con?ine dubluri pentru o cheie. MongoDB va indexa prima apari?ie a cheii ?i va elimina toate documentele din colec?ie care con?in urmatoarele apari?ii ale acelei chei. Valoarea implicita e FALSE.

    Avertizare

    "dropDups" poate sa elimine date din baza dumneavoastra de date. Folosi?i cu mare precau?ie.

    Nota:

    Aceasta op?iune nu este sus?inuta de MongoDB 2.8+. Crearea indicelui va e?ua daca colec?ia con?ine dubluri.

The following options may be used with MongoDB versions before 2.6:

  • "w"

    Vede?i WriteConcerns. Valoarea implicita pentru MongoClient este 1.

  • "wTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru confirmarea write concern. Aceasta este aplicabila doar atunci când "w" este mai mare decât 1, deoarece expirarea timpului ?ine de replicare. Daca "write concern" nu este satisfacuta în limita intervalului de timp, se va emite o MongoCursorException. Valoarea 0 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 10000 (zece secunde).

The following options are deprecated and should no longer be used:

  • "safe"

    Învechita. Utiliza?i op?iunea WriteConcern w.

  • "timeout"

    Un pseudonim învechit pentru "socketTimeoutMS".

  • "wtimeout"

    Un pseudonim învechit pentru "wTimeoutMS".

Valorile întoarse

Returns an array containing the status of the index creation. The array contains whether the operation succeeded ("ok"), the number of indexes before and after the operation ("numIndexesBefore" and "numIndexesAfter"), and whether the collection that the index belongs to has been created ("createdCollectionAutomatically"). If the index already existed and did not need to be created, a "note" field may be present in lieu of "numIndexesAfter".

With MongoDB 2.4 and earlier, a status document is only returned if the write concern is at least 1. Otherwise, TRUE is returned. The fields in the status document are different, except for the "ok" field, which signals whether the index creation was successful. Additional fields are described in the documentation for MongoCollection::insert().

Erori/Excep?ii

Throws MongoException if the index name is longer than 128 bytes, or if the index specification is not an array.

Throws MongoDuplicateKeyException if the server could not create the unique index due to conflicting documents.

Throws MongoResultException if the server could not create the index due to an error.

Genereaza o excep?ie MongoCursorException daca op?iunea "w" este stabilita ?i înscrierea e?ueaza.

Genereaza o excep?ie MongoCursorTimeoutException daca op?iunea "w" este stabilita la o valoare mai mare decât unu ?i opera?iunea dureaza mai mult de MongoCursor::$timeout milisecunde. Aceasta nu va întrerupe opera?iunea pe server, este un timeout de partea clientului. Opera?iunea din MongoCollection::$wtimeout este în milisecunde.

Exemple

Example #1 MongoCollection::createIndex() example

<?php

$c = new MongoCollection($db, 'foo');

// create an index on 'x' ascending
$c->createIndex(array('x' => 1));

// create a unique index on 'y'
$c->createIndex(array('y' => 1), array('unique' => true));

// create a compound index on 'za' ascending and 'zb' descending
$c->createIndex(array('za' => 1, 'zb' => -1));

?>

Example #2 Geospatial Indexing

Mongo supports geospatial indexes, which allow you to search for documents near a given location or within a shape. The following example creates a geospatial index on the "loc" field:

<?php

$collection->createIndex(array('loc' => '2dsphere'));

?>

Example #3 Drop duplicates example

<?php

$collection->insert(array('username' => 'joeschmoe'));
$collection->insert(array('username' => 'joeschmoe'));

/* Index creation fails, since you cannot create a unique index on a field when
 * duplicates exist.
 */
$collection->createIndex(array('username' => 1), array('unique' => 1));

/* MongoDB will one of the conflicting documents and allow the unique index to
 * be created.
 */
$collection->createIndex(array('username' => 1), array('unique' => 1, 'dropDups' => 1));

/* We now have a unique index and subsequent inserts with the same username will
 * fail.
 */
$collection->insert(array('username' => 'joeschmoe'));

?>

A se vedea ?i

  • MongoCollection::deleteIndex() - Deletes an index from this collection
  • MongoCollection::deleteIndexes() - Delete all indices for this collection
  • The MongoDB » index and » index type documentation.
MongoCollection::createDBRef
MongoCollection::deleteIndex
MongoCollection


Deletes an index from this collection

MongoCollection::createIndex
MongoCollection::deleteIndexes
MongoCollection
PHP Manual

MongoCollection::deleteIndex

(PECL mongo >=0.9.0)

MongoCollection::deleteIndex — Deletes an index from this collection

Descrierea

public array MongoCollection::deleteIndex ( string|array $keys )

This method is identical to:

<?php

public function deleteIndexes($keys) {
  $indexName = $this->toIndexString($keys);

  return $this->db->command(array(
    "deleteIndexes" => $this->getName(),
    "index" => $indexName,
  ));
}

?>

Each index is given a unique name when it is created. This is often generated by the driver based on the index key(s) and order/type, but custom names may also be specified with MongoCollection::createIndex()'s "name" option).

Unfortunately, MongoCollection::deleteIndex() cannot delete custom-named indexes due to a backwards compatibility issue. When a string argument is provided, it is assumed to be the single field name in an ascending index (e.g. the name "x_1" would be used for the argument "x"). If an array or object is provided, an index name is generated just as if that argument was passed to MongoCollection::createIndex().

In order to delete a custom-named index with the PHP driver, the deleteIndexes database command must be used. For instance, an index named "myIndex" could be deleted with the PHP driver by running:

<?php

$db->command(array(
  "deleteIndexes" => $collection->getName(),
  "index" => "myIndex",
));

?>

To determine the name of an index with the PHP driver, you can query the system.indexes collection of a database and look for the "name" field of each result. The "ns" field will indicate the collection to which each index belongs.

Parametri

keys

An array specifying the index's fields as its keys. For each field, the value is either the index direction or » index type. If specifying direction, specify 1 for ascending or -1 for descending.

If a string is provided, it is assumed to be the single field name in an ascending index.

Valorile întoarse

Returns the database response.

Exemple

Example #1 MongoCollection::deleteIndex() example

This example passes the function string and array parameters.

<?php

$m = new MongoClient();
$c = $m->example->indices;

// create and remove a simple index
$c->createIndex(array("i"=>1));
$c->deleteIndex("i");

// create and remove a multi-key index
$c->ensureIndex(array("j" => 1, "k" => 1));
$c->deleteIndex(array("j" => 1, "k" => 1));

?>

A se vedea ?i

  • MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist.
  • MongoCollection::deleteIndexes() - Delete all indices for this collection
  • MongoCollection::toIndexString() - Converts keys specifying an index to its identifying string
  • The MongoDB » index and » index type documentation.
MongoCollection::createIndex
MongoCollection::deleteIndexes
MongoCollection


Delete all indices for this collection

MongoCollection::deleteIndex
MongoCollection::distinct
MongoCollection
PHP Manual

MongoCollection::deleteIndexes

(PECL mongo >=0.9.0)

MongoCollection::deleteIndexes — Delete all indices for this collection

Descrierea

public array MongoCollection::deleteIndexes ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the database response.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [nIndexesWas] => 1
    [msg] => all indexes deleted for collection
    [ok] => 1
)

A se vedea ?i

  • MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist.
  • MongoCollection::deleteIndex() - Deletes an index from this collection
MongoCollection::deleteIndex
MongoCollection::distinct
MongoCollection


Retrieve a list of distinct values for the given key across a collection.

MongoCollection::deleteIndexes
MongoCollection::drop
MongoCollection
PHP Manual

MongoCollection::distinct

(PECL mongo >=1.2.11)

MongoCollection::distinct — Retrieve a list of distinct values for the given key across a collection.

Descrierea

public array MongoCollection::distinct ( string $key [, array $query ] )

The distinct command returns a list of distinct values for the given key across a collection.

Parametri

key

The key to use.

query

An optional query parameters

Valorile întoarse

Returns an array of distinct values, sau FALSE în cazul e?ecului

Exemple

Example #1 MongoCollection::distinct() example

<?php
$m = new Mongo;
$db = $m->selectDB("test");
$db->dropCollection("distinct");
$c = $db->distinct;

$c->insert(array("stuff" => "bar", "zip-code" => 10010));
$c->insert(array("stuff" => "foo", "zip-code" => 10010));
$c->insert(array("stuff" => "bar", "zip-code" => 99701), array("w" => 1));

$retval = $c->distinct("zip-code");
var_dump($retval);

$retval = $c->distinct("zip-code", array("stuff" => "foo"));
var_dump($retval);

$retval = $c->distinct("zip-code", array("stuff" => "bar"));
var_dump($retval);

?>

Exemplul de mai sus va afi?a:

array(2) {
  [0]=>
  int(10010)
  [1]=>
  int(99701)
}
array(1) {
  [0]=>
  int(10010)
}
array(2) {
  [0]=>
  int(10010)
  [1]=>
  int(99701)
}

Example #2 MongoCollection::distinct() example on a embedded document

<?php
$c->insert(array("user" => array("points" => 25)));
$c->insert(array("user" => array("points" => 31)));
$c->insert(array("user" => array("points" => 25)));

$retval = $c->distinct("user.points");
var_dump($retval);

$retval = $c->distinct("user.nonexisting");
var_dump($retval);
?>

Exemplul de mai sus va afi?a:

array(2) {
  [0]=>
  int(25)
  [1]=>
  int(31)
}
array(0) {
}
MongoCollection::deleteIndexes
MongoCollection::drop
MongoCollection


Drops this collection

MongoCollection::distinct
MongoCollection::ensureIndex
MongoCollection
PHP Manual

MongoCollection::drop

(PECL mongo >=0.9.0)

MongoCollection::drop — Drops this collection

Descrierea

public array MongoCollection::drop ( void )

Drops this collection and deletes its indices.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the database response.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [nIndexesWas] => 1
    [msg] => all indexes deleted for collection
    [ns] => my_db.articles
    [ok] => 1
)
MongoCollection::distinct
MongoCollection::ensureIndex
MongoCollection


Creates an index on the specified field(s) if it does not already exist.

MongoCollection::drop
MongoCollection::find
MongoCollection
PHP Manual

MongoCollection::ensureIndex

(PECL mongo >=0.9.0)

MongoCollection::ensureIndex — Creates an index on the specified field(s) if it does not already exist.

Descrierea

public bool MongoCollection::ensureIndex ( string|array $key|keys [, array $options = array() ] )
Avertizare

This method is deprecated since version 1.5.0. Please use MongoCollection::createIndex() instead.

Creates an index on the specified field(s) if it does not already exist. Fields may be indexed with a direction (e.g. ascending or descending) or a special type (e.g. text, geospatial, hashed).

Nota:

This method will use the » createIndexes database command when communicating with MongoDB 2.6+. For previous database versions, the method will perform an insert operation on the special system.indexes collection.

Parametri

keys

An array specifying the index's fields as its keys. For each field, the value is either the index direction or » index type. If specifying direction, specify 1 for ascending or -1 for descending.

options

An array of options for the index creation. Currently available options include:

  • "unique"

    Specifica?i TRUE pentru a crea un indice unic. Valoarea implicita este FALSE. Aceasta op?iune se aplica doar pentru indici ascenden?i/descenden?i.

    Nota:

    Când MongoDB indexeaza un câmp, daca un document nu are valoare pentru acel câmp, o valoare NULL este indexata. Daca mai multe documente nu con?in câmpul, un indice unic va respinge toate documentele în afara de primul. Opiunea "sparse" poate fi utilizata pentru a depa?i aceasta, deoarece ea va preveni indexarea documentelor fara valoarea câmpului.

  • "sparse"

    Specifica?i TRUE pentru a crea un indice distribuit, ce indexeaza doar documente ce con?in un anumit câmp. Valoarea implicita e FALSE.

  • "expireAfterSeconds"

    Valoarea acestei op?iuni ar trebui sa specifice numarul de secunde dupa care un document ar trebui sa fie considerat expirat ?i automat eliminat din colec?ie. Aceasta op?iune este compatibila doar cu indici pe un singur câmp, unde câmpul va con?ine valori MongoDate.

    Nota:

    Aceasta facilitate este disponibila în MongoDB 2.2+. A se vedea » Expirarea Datelor din Colec?ii prin Stabilirea TTL pentru informa?ii suplimentare.

  • "name"

    Un nume op?ional care identifica univoc indicele.

    Nota:

    Implicit driver-ul va genera un nume al indicelui bazat pe câmpurile lui ?i ordinea de sortare sau tip. De exemplu, un indice compus array("x" => 1, "y" => -1) va fi numit "x_1_y_-1" ?i un indice geospa?ial array("loc" => "2dsphere") va fi numit "loc_2dsphere". Pentru indici cu mai multe câmpuri este posibil ca numele generat sa depa?easca » limita pentru denumirile indicilor din MongoDB. Op?iunea "name" poate fi folosita în acest caz pentru a furniza un nume mai scurt.

  • "background"

    Calculeaza indicele în fundal, pentru ca aceasta sa nu blocheze alte activita?i ale bazei de date. Specifica?i TRUE pentru a calcula în fundal. Valoarea implicita e FALSE.

    Avertizare

    Înainte de MongoDB 2.6.0, calculele indicilor erau executate ca opera?iuni în prim plan, indiferent de aceasta op?iune. A se vedea » Calcularea Indicilor cu Seturi de Replici pentru informa?ii suplimentare.

  • "socketTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru comunicarea prin socket. Daca serverul nu raspunde în limita intervalului de timp, se va emite o MongoCursorTimeoutException ?i nu va fi nici o posibilitate de a determina daca serverul a efectuat înscrierea, sau nu. Valoarea -1 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 30000 (30 secunde).

The following option may be used with MongoDB 2.6+:

  • "maxTimeMS"

    Specifica o limita de timp cumulativa în milisecunde pentru procesarea opera?iunii pe server (nu include timpul de a?teptare). Daca opera?iunea nu este terminata pe server în timpul rezervat, va fi emisa o MongoExecutionTimeoutException.

The following options may be used with MongoDB versions before 2.8:

  • "dropDups"

    Specifica?i TRUE pentru a for?a crearea unui indice unic, când colec?ia poate con?ine dubluri pentru o cheie. MongoDB va indexa prima apari?ie a cheii ?i va elimina toate documentele din colec?ie care con?in urmatoarele apari?ii ale acelei chei. Valoarea implicita e FALSE.

    Avertizare

    "dropDups" poate sa elimine date din baza dumneavoastra de date. Folosi?i cu mare precau?ie.

    Nota:

    Aceasta op?iune nu este sus?inuta de MongoDB 2.8+. Crearea indicelui va e?ua daca colec?ia con?ine dubluri.

The following options may be used with MongoDB versions before 2.6:

  • "w"

    Vede?i WriteConcerns. Valoarea implicita pentru MongoClient este 1.

  • "wTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru confirmarea write concern. Aceasta este aplicabila doar atunci când "w" este mai mare decât 1, deoarece expirarea timpului ?ine de replicare. Daca "write concern" nu este satisfacuta în limita intervalului de timp, se va emite o MongoCursorException. Valoarea 0 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 10000 (zece secunde).

The following options are deprecated and should no longer be used:

  • "safe"

    Învechita. Utiliza?i op?iunea WriteConcern w.

  • "timeout"

    Un pseudonim învechit pentru "socketTimeoutMS".

  • "wtimeout"

    Un pseudonim învechit pentru "wTimeoutMS".

Valorile întoarse

Returns an array containing the status of the index creation. The array contains whether the operation succeeded ("ok"), the number of indexes before and after the operation ("numIndexesBefore" and "numIndexesAfter"), and whether the collection that the index belongs to has been created ("createdCollectionAutomatically"). If the index already existed and did not need to be created, a "note" field may be present in lieu of "numIndexesAfter".

With MongoDB 2.4 and earlier, a status document is only returned if the write concern is at least 1. Otherwise, TRUE is returned. The fields in the status document are different, except for the "ok" field, which signals whether the index creation was successful. Additional fields are described in the documentation for MongoCollection::insert().

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Renamed the "wtimeout" option to "wTimeoutMS". Emits E_DEPRECATED when "wtimeout" is used. Renamed the "timeout" option to "socketTimeoutMS". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option. The options parameter no longer accepts a boolean to signify a unique index. Instead, this now has to be done with array('unique' => true).
1.2.11 | Emits E_DEPRECATED when options is scalar.
1.2.0 | Added "timeout" option.
1.0.11 | The "safe" option will trigger a primary failover, if necessary. MongoException will be thrown if the index name (either generated or set) is longer than 128 bytes.
1.0.5 | Added the "name" option to override index name creation.
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.

Erori/Excep?ii

Throws MongoException if the index name is longer than 128 bytes, or if the index specification is not an array.

Throws MongoDuplicateKeyException if the server could not create the unique index due to conflicting documents.

Throws MongoResultException if the server could not create the index due to an error.

Genereaza o excep?ie MongoCursorException daca op?iunea "w" este stabilita ?i înscrierea e?ueaza.

Genereaza o excep?ie MongoCursorTimeoutException daca op?iunea "w" este stabilita la o valoare mai mare decât unu ?i opera?iunea dureaza mai mult de MongoCursor::$timeout milisecunde. Aceasta nu va întrerupe opera?iunea pe server, este un timeout de partea clientului. Opera?iunea din MongoCollection::$wtimeout este în milisecunde.

Exemple

Example #1 MongoCollection::ensureIndex() example

<?php

$c = new MongoCollection($db, 'foo');

// create an index on 'x' ascending
$c->ensureIndex(array('x' => 1));

// create a unique index on 'y'
$c->ensureIndex(array('y' => 1), array('unique' => true));

// create a compound index on 'za' ascending and 'zb' descending
$c->ensureIndex(array('za' => 1, 'zb' => -1));

?>

Example #2 Geospatial Indexing

Mongo supports geospatial indexes, which allow you to search for documents near a given location or within a shape. The following example creates a geospatial index on the "loc" field:

<?php

$collection->ensureIndex(array('loc' => '2dsphere'));

?>

Example #3 Drop duplicates example

<?php

$collection->insert(array('username' => 'joeschmoe'));
$collection->insert(array('username' => 'joeschmoe'));

/* Index creation fails, since you cannot create a unique index on a field when
 * duplicates exist.
 */
$collection->ensureIndex(array('username' => 1), array('unique' => 1));

/* MongoDB will one of the conflicting documents and allow the unique index to
 * be created.
 */
$collection->ensureIndex(array('username' => 1), array('unique' => 1, 'dropDups' => 1));

/* We now have a unique index and subsequent inserts with the same username will
 * fail.
 */
$collection->insert(array('username' => 'joeschmoe'));

?>

A se vedea ?i

  • MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist.
  • MongoCollection::deleteIndex() - Deletes an index from this collection
  • MongoCollection::deleteIndexes() - Delete all indices for this collection
  • The MongoDB » index and » index type documentation.
MongoCollection::drop
MongoCollection::find
MongoCollection


Queries this collection, returning a MongoCursor for the result set

MongoCollection::ensureIndex
MongoCollection::findAndModify
MongoCollection
PHP Manual

MongoCollection::find

(PECL mongo >=0.9.0)

MongoCollection::find — Queries this collection, returning a MongoCursor for the result set

Descrierea

 public MongoCursor MongoCollection::find
  ([ array $query = array()
 [, array $fields = array()
]] )

Parametri

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.

Avertizare

Please make sure that for all special query operators (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.

Valorile întoarse

Returns a cursor for the search results.

Exemple

Example #1 MongoCollection::find() example

This example demonstrates basic search options.

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'produce');

// search for fruits
$fruitQuery = array('Type' => 'Fruit');

$cursor = $collection->find($fruitQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

// search for produce that is sweet. Taste is a child of Details.
$sweetQuery = array('Details.Taste' => 'Sweet');
echo "Sweet\n";
$cursor = $collection->find($sweetQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

?>

Exemplul de mai sus va afi?a:

array(4) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "50a87dd084f045a19b220dd6"
  }
  ["Name"]=>
  string(5) "Apple"
  ["Type"]=>
  string(5) "Fruit"
  ["Details"]=>
  array(2) {
    ["Taste"]=>
    string(5) "Sweet"
    ["Colour"]=>
    string(3) "Red"
  }
}
array(4) {
  ["_id"]=>
  object(MongoId)#8 (1) {
    ["$id"]=>
    string(24) "50a87de084f045a19b220dd7"
  }
  ["Name"]=>
  string(5) "Lemon"
  ["Type"]=>
  string(5) "Fruit"
  ["Details"]=>
  array(2) {
    ["Taste"]=>
    string(4) "Sour"
    ["Colour"]=>
    string(5) "Green"
  }
}

Sweet:
array(4) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "50a87dd084f045a19b220dd6"
  }
  ["Name"]=>
  string(5) "Apple"
  ["Type"]=>
  string(5) "Fruit"
  ["Details"]=>
  array(2) {
    ["Taste"]=>
    string(5) "Sweet"
    ["Colour"]=>
    string(3) "Red"
  }
}

See MongoCursor for more information how to work with cursors.

Example #2 MongoCollection::find() example

This example demonstrates how to search for a range.

<?php

$m = new MongoClient();
$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);
}

?>

Exemplul de mai sus va afi?a:

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.

Example #3 MongoCollection::find() example using $where

This example demonstrates how to search a collection using javascript code to reduce the resultset.

<?php

$m = new MongoClient();
$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);
}

?>

Exemplul de mai sus va afi?a:

array(3) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000002"
  }
  ["name"]=>
  string(3) "Joe"
  ["age"]=>
  int(20)
}

Example #4 MongoCollection::find() example using $in

This example demonstrates how to search a collection using the $in operator.

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$cursor = $collection->find(array(
    'name' => array('$in' => array('Joe', 'Wendy'))
));

?>

Exemplul de mai sus va afi?a:

array(3) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000002"
  }
  ["name"]=>
  string(3) "Joe"
  ["age"]=>
  int(20)
}

Example #5 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 MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$cursor = $collection->find();
$array = iterator_to_array($cursor);

?>

Exemplul de mai sus va afi?a:

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).

A se vedea ?i

  • MongoCollection::findOne() - Queries this collection, returning a single element
  • MongoCollection::insert() - Inserts a document into the collection
  • MongoDB core docs on » find.
MongoCollection::ensureIndex
MongoCollection::findAndModify
MongoCollection


Update a document and return it

MongoCollection::find
MongoCollection::findOne
MongoCollection
PHP Manual

MongoCollection::findAndModify

(PECL mongo >=1.3.0)

MongoCollection::findAndModify — Update a document and return it

Descrierea

public array MongoCollection::findAndModify ( array $query [, array $update [, array $fields [, array $options ]]] )

The findAndModify command atomically modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.

Parametri

query

The query criteria to search for.

update

The update criteria.

fields

Optionally only return these fields.

options

An array of options to apply, such as remove the match document from the DB and return it.

Option | Descriere
sort array | Determines which document the operation will modify if the query selects multiple documents. findAndModify will modify the first document in the sort order specified by this argument.
remove boolean | Optional if update field exists. When TRUE, removes the selected document. The default is FALSE.
update array | Optional if remove field exists. Performs an update of the selected document.
new boolean | Optional. When TRUE, returns the modified document rather than the original. The findAndModify method ignores the new option for remove operations. The default is FALSE.
upsert boolean | Optional. Used in conjunction with the update field. When TRUE, the findAndModify command creates a new document if the query returns no documents. The default is false. In MongoDB 2.2, the findAndModify command returns NULL when upsert is TRUE.

Valorile întoarse

Returns the original document, or the modified document when new is set.

Erori/Excep?ii

Throws MongoResultException on failure.

Exemple

Example #1 MongoCollection::findAndModify() example

<?php
$m = new Mongo;
$col = $m->selectDB("test")->jobs;

$col->insert(array(
     "name" => "Next promo",
     "inprogress" => false,
     "priority" => 0,
     "tasks" => array( "select product", "add inventory", "do placement"),
) );

$col->insert(array(
     "name" => "Biz report",
     "inprogress" => false,
     "priority" => 1,
     "tasks" => array( "run sales report", "email report" )
) );

$col->insert(array(
     "name" => "Biz report",
     "inprogress" => false,
     "priority" => 2,
     "tasks" => array( "run marketing report", "email report" )
    ),
    array("w" => 1)
);

$retval = $col->findAndModify(
     array("inprogress" => false, "name" => "Biz report"),
     array('$set' => array('inprogress' => true, "started" => new MongoDate())),
     null,
     array(
        "sort" => array("priority" => -1),
        "new" => true,
    )
);

var_dump($retval);
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(6) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "5091b5b244415e8cc3000002"
  }
  ["inprogress"]=>
  bool(true)
  ["name"]=>
  string(10) "Biz report"
  ["priority"]=>
  int(2)
  ["started"]=>
  object(MongoDate)#8 (2) {
    ["sec"]=>
    int(1351726514)
    ["usec"]=>
    int(925000)
  }
  ["tasks"]=>
  array(2) {
    [0]=>
    string(20) "run marketing report"
    [1]=>
    string(12) "email report"
  }
}

Example #2 MongoCollection::findAndModify() error handling

<?php
$m = new Mongo;
$col = $m->selectDB("test")->jobs;
try {
    $retval = $col->findAndModify(
         array("inprogress" => false, "name" => "Next promo"),
         array('$pop' => array("tasks" => -1)),
         array("tasks" => array('$pop' => array("stuff"))),
         array("new" => true)
    );
} catch(MongoResultException $e) {
    echo $e->getCode(), " : ", $e->getMessage(), "\n";
    var_dump($e->getDocument());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

13097 : exception: Unsupported projection option: $pop
array(3) {
  ["errmsg"]=>
  string(46) "exception: Unsupported projection option: $pop"
  ["code"]=>
  int(13097)
  ["ok"]=>
  float(0)
}

A se vedea ?i

  • The MongoDB » findAndModify command docs
MongoCollection::find
MongoCollection::findOne
MongoCollection


Queries this collection, returning a single element

MongoCollection::findAndModify
MongoCollection::__get
MongoCollection
PHP Manual

MongoCollection::findOne

(PECL mongo >=0.9.0)

MongoCollection::findOne — Queries this collection, returning a single element

Descrierea

 public array MongoCollection::findOne
  ([ array $query = array()
 [, array $fields = array()
 [, array $options = 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.

Parametri

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.

Avertizare

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.

options

This parameter is an associative array of the form array("name" => <value>, ...). Currently supported options are:

  • "maxTimeMS"

    Specifica o limita de timp cumulativa în milisecunde pentru procesarea opera?iunii pe server (nu include timpul de a?teptare). Daca opera?iunea nu este terminata pe server în timpul rezervat, va fi emisa o MongoExecutionTimeoutException.

Valorile întoarse

Returns record matching the search or NULL.

Erori/Excep?ii

Throws MongoConnectionException if it cannot reach the database.

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Added optional options argument.

Exemple

Example #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')));

?>

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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.

A se vedea ?i

  • MongoCollection::find() - Queries this collection, returning a MongoCursor for the result set
  • MongoCollection::insert() - Inserts a document into the collection
  • MongoDB core docs on » find.
MongoCollection::findAndModify
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

Descrierea

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 MongoClient();

// the following two lines are equivalent
$collection = $mongo->selectDB("foo")->selectCollection("bar.baz");
$collection = $mongo->foo->bar->baz;

?>

Parametri

name

The next string in the collection name.

Valorile întoarse

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

Descrierea

public array MongoCollection::getDBRef ( array $ref )

Parametri

ref

A database reference.

Valorile întoarse

Returns the database document pointed to by the reference.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
    )

A se vedea ?i

  • 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

Descrierea

public array MongoCollection::getIndexInfo ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

This function returns an array in which each element describes an index. Elements will contain the values name for the name of the index, ns for the namespace (a combination of the database and collection name), and key for a list of all fields in the index and their ordering. Additional values may be present for special indexes, such as unique or sparse.

Exemple

Example #1 MongoCollection::getIndexInfo() example

<?php

$m = new MongoClient();
$c = $m->selectCollection('test', 'venues');
var_dump($c->getIndexInfo());

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(4) {
  [0]=>
  array(4) {
    ["v"]=>
    int(1)
    ["key"]=>
    array(1) {
      ["_id"]=>
      int(1)
    }
    ["name"]=>
    string(4) "_id_"
    ["ns"]=>
    string(11) "test.venues"
  }
  [1]=>
  array(4) {
    ["v"]=>
    int(1)
    ["key"]=>
    array(1) {
      ["name"]=>
      float(1)
    }
    ["name"]=>
    string(6) "name_1"
    ["ns"]=>
    string(11) "test.venues"
  }
  [2]=>
  array(4) {
    ["v"]=>
    int(1)
    ["key"]=>
    array(2) {
      ["type"]=>
      float(1)
      ["createdAt"]=>
      float(-1)
    }
    ["name"]=>
    string(19) "type_1_createdAt_-1"
    ["ns"]=>
    string(11) "test.venues"
  }
  [3]=>
  array(5) {
    ["v"]=>
    int(1)
    ["key"]=>
    array(1) {
      ["location"]=>
      string(8) "2dsphere"
    }
    ["name"]=>
    string(17) "location_2dsphere"
    ["ns"]=>
    string(11) "test.venues"
    ["2dsphereIndexVersion"]=>
    int(2)
  }
}

A se vedea ?i

MongoDB core docs on » vanilla indexes and » geospatial indexes.

MongoCollection::getDBRef
MongoCollection::getName
MongoCollection


Returns this collection's name

MongoCollection::getIndexInfo
MongoCollection::getReadPreference
MongoCollection
PHP Manual

MongoCollection::getName

(PECL mongo >=0.9.0)

MongoCollection::getName — Returns this collection's name

Descrierea

public string MongoCollection::getName ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the name of this collection.

Exemple

Example #1 MongoCollection::getName() example

<?php

$m = new MongoClient();
$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";

?>

Exemplul de mai sus va afi?a ceva similar cu:

Working with collection bar.baz.
Working in namespace foo.bar.baz.

MongoCollection::getIndexInfo
MongoCollection::getReadPreference
MongoCollection


Get the read preference for this collection

MongoCollection::getName
MongoCollection::getSlaveOkay
MongoCollection
PHP Manual

MongoCollection::getReadPreference

(PECL mongo >=1.3.0)

MongoCollection::getReadPreference — Get the read preference for this collection

Descrierea

public array MongoCollection::getReadPreference ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Aceasta func?ie întoarce un tablou ce descrie preferin?a de citire. Tabloul con?ine tipul (type) valorilor pentru ?irul cu modul preferin?ei de citire (ce corespunde constantelor MongoClient), ?i tagsets con?inând lista tuturor criteriilor setului de etichete. Daca nu a fost specificat nici un set de etichete, tagsets nu va fi prezent în tablou.

Istoricul schimbarilor

Versiune | Descriere
1.3.3 | The return value has changed to be consistent with MongoCollection::setReadPreference(). The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.

Exemple

Example #1 MongoCollection::getReadPreference() return value example

<?php

$m = new MongoClient();
$c = $m->test->users;
$c->setReadPreference(MongoClient::RP_SECONDARY, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
    array(),
));
var_dump($c->getReadPreference());
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["type"]=>
  string(9) "secondary"
  ["tagsets"]=>
  array(3) {
    [0]=>
    array(2) {
      ["dc"]=>
      string(4) "east"
      ["use"]=>
      string(9) "reporting"
    }
    [1]=>
    array(1) {
      ["dc"]=>
      string(7) "west"
    }
    [2]=>
    array(0) {
    }
  }
}

A se vedea ?i

  • The read preferences documentation.
  • MongoCollection::setReadPreference() - Set the read preference for this collection
MongoCollection::getName
MongoCollection::getSlaveOkay
MongoCollection


Get slaveOkay setting for this collection

MongoCollection::getReadPreference
MongoCollection::getWriteConcern
MongoCollection
PHP Manual

MongoCollection::getSlaveOkay

(PECL mongo >=1.1.0)

MongoCollection::getSlaveOkay — Get slaveOkay setting for this collection

Descrierea

public bool MongoCollection::getSlaveOkay ( void )

See the query section of this manual for information on distributing reads to secondaries.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the value of slaveOkay for this instance.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

A se vedea ?i

  • Read Preferences
  • MongoCollection::getReadPreference() - Get the read preference for this collection
MongoCollection::getReadPreference
MongoCollection::getWriteConcern
MongoCollection


Get the write concern for this collection

MongoCollection::getSlaveOkay
MongoCollection::group
MongoCollection
PHP Manual

MongoCollection::getWriteConcern

(PECL mongo >=1.5.0)

MongoCollection::getWriteConcern — Get the write concern for this collection

Descrierea

public array MongoCollection::getWriteConcern ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Aceasta func?ie întoarce un tablou ce descrie gradul de participare la înscriere. Tabloul con?ine valorile w pentru un nivel de confirmare întreg sau ca ?ir de caractere ?i wtimeout ce denota numarul maximal de milisecunde de a?teptare pâna când serverul satisface gradul de participare la înscriere.

Exemple

Example #1 MongoCollection::getWriteConcern() return value example

<?php

$mc = new MongoClient('mongodb://localhost:27017', array('wTimeoutMS' => 500));
$coll = $mc->selectCollection('test', 'foo');
var_dump($coll->getWriteConcern());

$coll->setWriteConcern(1, 1000);
var_dump($coll->getWriteConcern());
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(500)
}
array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(1000)
}

A se vedea ?i

  • The write concern documentation.
  • MongoCollection::setWriteConcern() - Set the write concern for this database
MongoCollection::getSlaveOkay
MongoCollection::group
MongoCollection


Performs an operation similar to SQL's GROUP BY command

MongoCollection::getWriteConcern
MongoCollection::insert
MongoCollection
PHP Manual

MongoCollection::group

(PECL mongo >=0.9.2)

MongoCollection::group — Performs an operation similar to SQL's GROUP BY command

Descrierea

public array MongoCollection::group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] )

Parametri

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.

  • "maxTimeMS"

    Specifica o limita de timp cumulativa în milisecunde pentru procesarea opera?iunii pe server (nu include timpul de a?teptare). Daca opera?iunea nu este terminata pe server în timpul rezervat, va fi emisa o MongoExecutionTimeoutException.

Valorile întoarse

Returns an array containing the result.

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Added "maxTimeMS" option.
1.2.11 | Emits E_DEPRECATED when options is scalar.

Exemple

Example #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']);

?>

Exemplul de mai sus va afi?a ceva similar cu:

[{"category":"fruit","items":["apple","peach","banana"]},{"category":"veggie","items":["corn","broccoli"]}]

Example #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('condition' => array("a" => array( '$gt' => 1)));

$g = $collection->group($keys, $initial, $reduce, $condition);

var_dump($g);

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(4) {
  ["retval"]=>
  array(1) {
    [0]=>
    array(1) {
      ["count"]=>
      float(1)
    }
  }
  ["count"]=>
  float(1)
  ["keys"]=>
  int(1)
  ["ok"]=>
  float(1)
}

Example #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::getWriteConcern
MongoCollection::insert
MongoCollection


Inserts a document into the collection

MongoCollection::group
MongoCollection::parallelCollectionScan
MongoCollection
PHP Manual

MongoCollection::insert

(PECL mongo >=0.9.0)

MongoCollection::insert — Inserts a document into the collection

Descrierea

public bool|array MongoCollection::insert ( array|object $document [, 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.

Parametri

document

An array or object. If an object is used, it may not have protected or private properties.

Nota:

If the parameter does not have an _id key or property, a new MongoId instance will be created and assigned to it. This special behavior does not mean that the parameter is passed by reference.

options

An array of options for the insert operation. Currently available options include:

  • "fsync"

    O valoare boolean-a, valoarea implicita este FALSE. Daca jurnalizarea e activata, ea func?ioneaza exact ca "j". Daca jurnalizarea nu este acticvata, atunci se for?eaza sincronizarea pe disc a opera?iunii de inserare înainte de a întoarce succes. Daca are valoarea TRUE, se presupune efectuarea unei inserari cu confirmare ?i setarea w va fi modificata în 0.

    Nota: Daca jurnalizarea este activata, utilizatorii sunt încuraja?i sa utilizeze op?iunea "j" în loc de "fsync". Nu utiliza?i "fsync" ?i "j" simultan, deoarece aceasta va rezulta în eroare.

  • "j"

    O valoare boolean-a, cu valoarea implicita FALSE. For?eaza sincronizarea cu jurnalul a opera?iunii de inserare, înainte de a întoarce succes. Daca are valoarea TRUE, se presupune efectuarea unei inserari cu confirmare ?i setarea w va fi modificata în 0.

    Nota: Daca aceasta op?iune e utilizata, iar jurnalizarea e dezactivata, MongoDB 2.6+ va emite o eroare ?i înscrierea va e?ua; versiunile mai vechi ale serverului pur ?i simplu vor ignora op?iunea.

  • "socketTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru comunicarea prin socket. Daca serverul nu raspunde în limita intervalului de timp, se va emite o MongoCursorTimeoutException ?i nu va fi nici o posibilitate de a determina daca serverul a efectuat înscrierea, sau nu. Valoarea -1 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 30000 (30 secunde).

  • "w"

    Vede?i WriteConcerns. Valoarea implicita pentru MongoClient este 1.

  • "wTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru confirmarea write concern. Aceasta este aplicabila doar atunci când "w" este mai mare decât 1, deoarece expirarea timpului ?ine de replicare. Daca "write concern" nu este satisfacuta în limita intervalului de timp, se va emite o MongoCursorException. Valoarea 0 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 10000 (zece secunde).

The following options are deprecated and should no longer be used:

  • "safe"

    Învechita. Utiliza?i op?iunea WriteConcern w.

  • "timeout"

    Un pseudonim învechit pentru "socketTimeoutMS".

  • "wtimeout"

    Un pseudonim învechit pentru "wTimeoutMS".

Valorile întoarse

Returns an array containing the status of the insertion if the "w" option is set. Otherwise, returns TRUE if the inserted array is not empty (a MongoException will be thrown if the inserted array is empty).

If an array is returned, the following keys may be present:

ok

This should almost always 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 update, upsert, or a remove, the number of documents affected will be returned. For insert operations, this value is always 0.

wtimeout

If the previous option timed out waiting for replication.

waited

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 occurred, 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).

Erori/Excep?ii

Throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.

Genereaza o excep?ie MongoCursorException daca op?iunea "w" este stabilita ?i înscrierea e?ueaza.

Genereaza o excep?ie MongoCursorTimeoutException daca op?iunea "w" este stabilita la o valoare mai mare decât unu ?i opera?iunea dureaza mai mult de MongoCursor::$timeout milisecunde. Aceasta nu va întrerupe opera?iunea pe server, este un timeout de partea clientului. Opera?iunea din MongoCollection::$wtimeout este în milisecunde.

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option. The options parameter no longer accepts a boolean to signify an acknowledged write. Instead, this now has to be done with array('w' => 1) (the default behaviour of MongoClient).
1.2.0 | Added "timeout" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.0.9 | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
1.0.2 | Changed second parameter to be an array of options. Pre-1.0.2, the second parameter was a boolean indicating the "safe" option.
1.0.1 | Throw a MongoCursorException if the "safe" option is set and the insert fails.

Exemple

Example #1 MongoCollection::insert() _id example

An _id field will be added to the inserted document if not already present. Depending on how the parameter is passed, a generated _id may or may not be available to calling code.

<?php

$m = new MongoClient();
$collection = $m->selectCollection('test', 'phpmanual');

// If an array literal is used, there is no way to access the generated _id
$collection->insert(array('x' => 1));

// The _id is available on an array passed by value
$a = array('x' => 2);
$collection->insert($a);
var_dump($a);

// The _id is not available on an array passed by reference
$b = array('x' => 3);
$ref = &$b;
$collection->insert($ref);
var_dump($ref);

// The _id is available if a wrapping function does not trigger copy-on-write
function insert_no_cow($collection, $document)
{
    $collection->insert($document);
}

$c = array('x' => 4);
insert_no_cow($collection, $c);
var_dump($c);

// The _id is not available if a wrapping function triggers copy-on-write
function insert_cow($collection, $document)
{
    $document['y'] = 1;
    $collection->insert($document);
}

$d = array('x' => 5);
insert_cow($collection, $d);
var_dump($d);

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  ["x"]=>
  int(2)
  ["_id"]=>
  object(MongoId)#4 (0) {
  }
}
array(1) {
  ["x"]=>
  int(3)
}
array(2) {
  ["x"]=>
  int(4)
  ["_id"]=>
  object(MongoId)#5 (0) {
  }
}
array(1) {
  ["x"]=>
  int(5)
}

Example #2 MongoCollection::insert() acknowledged write example

This example shows inserting two elements with the same _id, which causes a MongoCursorException to be thrown, as w was set.

<?php

$person = array("name" => "Joe", "age" => 20);
$collection->insert($person);

// now $person has an _id field, so if we save it
// again, we will get an exception
try {
    $collection->insert($person, array("w" => 1));
} catch(MongoCursorException $e) {
    echo "Can't save the same person twice!\n";
}

?>

A se vedea ?i

  • MongoCollection::batchInsert() - Inserts multiple documents into this collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoCollection::find() - Queries this collection, returning a MongoCursor for the result set
  • MongoCollection::remove() - Remove records from this collection
  • MongoDB core docs on » insert.
MongoCollection::group
MongoCollection::parallelCollectionScan
MongoCollection


Returns an array of cursors to iterator over a full collection in parallel

MongoCollection::insert
MongoCollection::remove
MongoCollection
PHP Manual

MongoCollection::parallelCollectionScan

(PECL mongo >=1.5.0)

MongoCollection::parallelCollectionScan — Returns an array of cursors to iterator over a full collection in parallel

Descrierea

public array[MongoCommandCursor] MongoCollection::parallelCollectionScan ( int $num_cursors )

This method returns an array of a maximum of num_cursors cursors. An iteration over one of the returned cursors results in a partial set of documents for a collection. Iteration over all the returned cursors results in getting every document back from the collection.

This method is a wrapper for the parallelCollectionScan MongoDB command.

Parametri

num_cursors

The number of cursors to request from the server. Please note, that the server can return less cursors than you requested.

Valorile întoarse

Returns an array of MongoCommandCursor objects.

Exemple

Example #1 MongoCollection::parallelCollectionScan() example

Returning all documents in a collection by using multiple cursors.

<?php
$m = new MongoClient;
$c = $m->demo->cities;

/* Request three cursors */
$cursors = $c->parallelCollectionScan( 3 );

/* Add all the cursors to the MultipleIterator */
$mi = new MultipleIterator( MultipleIterator::MIT_NEED_ANY );
foreach ( $cursors as $cursor )
{
    $mi->attachIterator( $cursor );
}

/* Iterate over all the associated cursors */
foreach ( $mi as $items )
{
    foreach ( $items as $item )
    {
        if ( $item !== NULL )
        {
            echo $item['name'], "\n";
        }
    }
}
?>

A se vedea ?i

  • MultipleIterator
  • MongoCommandCursor
  • MongoDB::command() - Execute a database command

MongoCollection::insert
MongoCollection::remove
MongoCollection


Remove records from this collection

MongoCollection::parallelCollectionScan
MongoCollection::save
MongoCollection
PHP Manual

MongoCollection::remove

(PECL mongo >=0.9.0)

MongoCollection::remove — Remove records from this collection

Descrierea

 public bool|array MongoCollection::remove
  ([ array $criteria = array()
 [, array $options = array()
]] )

Parametri

criteria

Query criteria for the documents to delete.

options

An array of options for the remove operation. Currently available options include:

  • "w"

    Vede?i WriteConcerns. Valoarea implicita pentru MongoClient este 1.

  • "justOne"

    Specify TRUE to limit deletion to just one document. If FALSE or omitted, all documents matching the criteria will be deleted.

  • "fsync"

    O valoare boolean-a, valoarea implicita este FALSE. Daca jurnalizarea e activata, ea func?ioneaza exact ca "j". Daca jurnalizarea nu este acticvata, atunci se for?eaza sincronizarea pe disc a opera?iunii de inserare înainte de a întoarce succes. Daca are valoarea TRUE, se presupune efectuarea unei inserari cu confirmare ?i setarea w va fi modificata în 0.

    Nota: Daca jurnalizarea este activata, utilizatorii sunt încuraja?i sa utilizeze op?iunea "j" în loc de "fsync". Nu utiliza?i "fsync" ?i "j" simultan, deoarece aceasta va rezulta în eroare.

  • "j"

    O valoare boolean-a, cu valoarea implicita FALSE. For?eaza sincronizarea cu jurnalul a opera?iunii de inserare, înainte de a întoarce succes. Daca are valoarea TRUE, se presupune efectuarea unei inserari cu confirmare ?i setarea w va fi modificata în 0.

    Nota: Daca aceasta op?iune e utilizata, iar jurnalizarea e dezactivata, MongoDB 2.6+ va emite o eroare ?i înscrierea va e?ua; versiunile mai vechi ale serverului pur ?i simplu vor ignora op?iunea.

  • "socketTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru comunicarea prin socket. Daca serverul nu raspunde în limita intervalului de timp, se va emite o MongoCursorTimeoutException ?i nu va fi nici o posibilitate de a determina daca serverul a efectuat înscrierea, sau nu. Valoarea -1 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 30000 (30 secunde).

  • "w"

    Vede?i WriteConcerns. Valoarea implicita pentru MongoClient este 1.

  • "wTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru confirmarea write concern. Aceasta este aplicabila doar atunci când "w" este mai mare decât 1, deoarece expirarea timpului ?ine de replicare. Daca "write concern" nu este satisfacuta în limita intervalului de timp, se va emite o MongoCursorException. Valoarea 0 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 10000 (zece secunde).

The following options are deprecated and should no longer be used:

  • "safe"

    Învechita. Utiliza?i op?iunea WriteConcern w.

  • "timeout"

    Un pseudonim învechit pentru "socketTimeoutMS".

  • "wtimeout"

    Un pseudonim învechit pentru "wTimeoutMS".

Valorile întoarse

Returns an array containing the status of the removal if the "w" option is set. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Erori/Excep?ii

Genereaza o excep?ie MongoCursorException daca op?iunea "w" este stabilita ?i înscrierea e?ueaza.

Genereaza o excep?ie MongoCursorTimeoutException daca op?iunea "w" este stabilita la o valoare mai mare decât unu ?i opera?iunea dureaza mai mult de MongoCursor::$timeout milisecunde. Aceasta nu va întrerupe opera?iunea pe server, este un timeout de partea clientului. Opera?iunea din MongoCollection::$wtimeout este în milisecunde.

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Added "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option. The options parameter no longer accepts a boolean to signify "justOne". Instead, this now has to be done with array('justOne' => true).
1.2.11 | Emits E_DEPRECATED when options is scalar.
1.2.0 | Added "timeout" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.0.9 | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
1.0.5 | Changed second parameter to be an array of options. Pre-1.0.5, the second parameter was a boolean indicating the "safe" option.

Exemple

Example #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--;
}

?>

A se vedea ?i

  • MongoCollection::insert() - Inserts a document into the collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoDB core docs on » remove.
MongoCollection::parallelCollectionScan
MongoCollection::save
MongoCollection


Saves a document to this collection

MongoCollection::remove
MongoCollection::setReadPreference
MongoCollection
PHP Manual

MongoCollection::save

(PECL mongo >=0.9.0)

MongoCollection::save — Saves a document to this collection

Descrierea

public mixed MongoCollection::save ( array|object $document [, array $options = array() ] )

If the object is from the database, update the existing database object, otherwise insert this object.

Parametri

document

Array or object to save. If an object is used, it may not have protected or private properties.

Nota:

If the parameter does not have an _id key or property, a new MongoId instance will be created and assigned to it. See MongoCollection::insert() for additional information on this behavior.

options

Options for the save.

  • "fsync"

    O valoare boolean-a, valoarea implicita este FALSE. Daca jurnalizarea e activata, ea func?ioneaza exact ca "j". Daca jurnalizarea nu este acticvata, atunci se for?eaza sincronizarea pe disc a opera?iunii de inserare înainte de a întoarce succes. Daca are valoarea TRUE, se presupune efectuarea unei inserari cu confirmare ?i setarea w va fi modificata în 0.

    Nota: Daca jurnalizarea este activata, utilizatorii sunt încuraja?i sa utilizeze op?iunea "j" în loc de "fsync". Nu utiliza?i "fsync" ?i "j" simultan, deoarece aceasta va rezulta în eroare.

  • "j"

    O valoare boolean-a, cu valoarea implicita FALSE. For?eaza sincronizarea cu jurnalul a opera?iunii de inserare, înainte de a întoarce succes. Daca are valoarea TRUE, se presupune efectuarea unei inserari cu confirmare ?i setarea w va fi modificata în 0.

    Nota: Daca aceasta op?iune e utilizata, iar jurnalizarea e dezactivata, MongoDB 2.6+ va emite o eroare ?i înscrierea va e?ua; versiunile mai vechi ale serverului pur ?i simplu vor ignora op?iunea.

  • "socketTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru comunicarea prin socket. Daca serverul nu raspunde în limita intervalului de timp, se va emite o MongoCursorTimeoutException ?i nu va fi nici o posibilitate de a determina daca serverul a efectuat înscrierea, sau nu. Valoarea -1 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 30000 (30 secunde).

  • "w"

    Vede?i WriteConcerns. Valoarea implicita pentru MongoClient este 1.

  • "wtimeout"

    Un pseudonim învechit pentru "wTimeoutMS".

  • "wTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru confirmarea write concern. Aceasta este aplicabila doar atunci când "w" este mai mare decât 1, deoarece expirarea timpului ?ine de replicare. Daca "write concern" nu este satisfacuta în limita intervalului de timp, se va emite o MongoCursorException. Valoarea 0 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 10000 (zece secunde).

  • "safe"

    Învechita. Utiliza?i op?iunea WriteConcern w.

  • "timeout"

    Un pseudonim învechit pentru "socketTimeoutMS".

Valorile întoarse

If w 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).

Erori/Excep?ii

Throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.

Genereaza o excep?ie MongoCursorException daca op?iunea "w" este stabilita ?i înscrierea e?ueaza.

Genereaza o excep?ie MongoCursorTimeoutException daca op?iunea "w" este stabilita la o valoare mai mare decât unu ?i opera?iunea dureaza mai mult de MongoCursor::$timeout milisecunde. Aceasta nu va întrerupe opera?iunea pe server, este un timeout de partea clientului. Opera?iunea din MongoCollection::$wtimeout este în milisecunde.

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Added "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.2.0 | Added "timeout" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.0.9 | Added "fsync" option.
1.0.5 | Added options parameter.

Exemple

Example #1 MongoCollection::save() example

<?php

$obj = array('x' => 1);

// insert $obj into the db
$collection->save($obj);
var_dump($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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  ["x"]=>
  int(1)
  ["_id"]=>
  object(MongoId)#4 (1) {
    ["$id"]=>
    string(24) "50b6afe544415ed606000000"
  }
}
MongoCollection::remove
MongoCollection::setReadPreference
MongoCollection


Set the read preference for this collection

MongoCollection::save
MongoCollection::setSlaveOkay
MongoCollection
PHP Manual

MongoCollection::setReadPreference

(PECL mongo >=1.3.0)

MongoCollection::setReadPreference — Set the read preference for this collection

Descrierea

public bool MongoCollection::setReadPreference ( string $read_preference [, array $tags ] )

Parametri

read_preference

Modul preferin?ei de citire:
MongoClient::RP_PRIMARY,
MongoClient::RP_PRIMARY_PREFERRED,
MongoClient::RP_SECONDARY,
MongoClient::RP_SECONDARY_PREFERRED sau
MongoClient::RP_NEAREST.

tags

Un tablou din zero sau mai multe seturi de etichete, unde fiecare set de etichete este la rândul sau un tablou de criterii utilizate pentru a potrivi etichetele pe membrii setului de replicare.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

Erori/Excep?ii

Emite un E_WARNING daca careva parametru nu e valid, sau daca unul sau mai multe seturi de etichete sunt furnizate cu modul preferin?ei de citire MongoClient::RP_PRIMARY.

Exemple

Example #1 MongoCollection::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient();
$c = $m->test->users;

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$c->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));
?>

A se vedea ?i

  • The read preferences documentation.
  • MongoCollection::getReadPreference() - Get the read preference for this collection
MongoCollection::save
MongoCollection::setSlaveOkay
MongoCollection


Change slaveOkay setting for this collection

MongoCollection::setReadPreference
MongoCollection::setWriteConcern
MongoCollection
PHP Manual

MongoCollection::setSlaveOkay

(PECL mongo >=1.1.0)

MongoCollection::setSlaveOkay — Change slaveOkay setting for this collection

Descrierea

public bool MongoCollection::setSlaveOkay ([ bool $ok = true ] )

See the query section of this manual for information on distributing reads to secondaries.

Parametri

ok

If reads should be sent to secondary members of a replica set for all possible queries using this MongoCollection instance.

Valorile întoarse

Returns the former value of slaveOkay for this instance.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

A se vedea ?i

  • Read Preferences
  • MongoCollection::setReadPreference() - Set the read preference for this collection
MongoCollection::setReadPreference
MongoCollection::setWriteConcern
MongoCollection


Set the write concern for this database

MongoCollection::setSlaveOkay
MongoCollection::toIndexString
MongoCollection
PHP Manual

MongoCollection::setWriteConcern

(PECL mongo >=1.5.0)

MongoCollection::setWriteConcern — Set the write concern for this database

Descrierea

public bool MongoCollection::setWriteConcern ( mixed $w [, int $wtimeout ] )

Parametri

w

Gradul de participare la înscriere. Aceasta poate fi un întreg ce denota numarul de servere necesare pentru a confirma opera?iunea de înscriere, sau un mod scris ca ?ir de caractere (de ex. "majority").

wtimeout

Numarul maximal de milisecunde de a?teptare pâna când serverul satisface gradul de participare la înscriere.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

Erori/Excep?ii

Emite un E_WARNING daca parametrul w nu este un întreg sau un ?ir de caractere.

Exemple

Example #1 MongoDB::setWriteConcern() example

<?php

$mc = new MongoClient('mongodb://rs1.example.com,rs2.example.com');
$coll = $mc->selectCollection('test', 'foo');

// Require that the majority of servers in the replica set acknowledge writes
// within three seconds.
$coll->setWriteConcern('majority', 3000);
?>

A se vedea ?i

  • The write concern documentation.
  • MongoCollection::getWriteConcern() - Get the write concern for this collection
MongoCollection::setSlaveOkay
MongoCollection::toIndexString
MongoCollection


Converts keys specifying an index to its identifying string

MongoCollection::setWriteConcern
MongoCollection::__toString
MongoCollection
PHP Manual

MongoCollection::toIndexString

(PECL mongo >=0.9.0)

MongoCollection::toIndexString — Converts keys specifying an index to its identifying string

Descrierea

static protected string MongoCollection::toIndexString ( mixed $keys )
Avertizare

This method is deprecated since version 1.5.0.

Parametri

keys

Field or fields to convert to the identifying string

Valorile întoarse

Returns a string that describes the index.

Exemple

Example #1 MongoCollection::toIndexString() example

This example shows how you can create an index name out of keys. Because this is a protected (static) method, you need to overload it in a child class first.

<?php
// Create inherited 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
?>

A se vedea ?i

MongoDB core docs on » indexes.

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | This method has been deprecated.

MongoCollection::setWriteConcern
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

Descrierea

public string MongoCollection::__toString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the full name of this collection.

Exemple

Example #1 MongoCollection::__toString() example

<?php

$m = new MongoClient();

$c1 = $m->foo->bar->baz;
echo "Working with collection $c1.";

$c2 = $m->selectCollection('[]', '&');
echo "Working with collection $c2.";

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

public bool|array MongoCollection::update ( array $criteria , array $new_object [, array $options = array() ] )

Parametri

criteria

Query criteria for the documents to update.

new_object

The object used to update the matched documents. This may either contain update operators (for modifying specific fields) or be a replacement document.

options

An array of options for the update operation. Currently available options include:

  • "upsert"

    If no document matches $criteria, a new document will be inserted.

    If a new document would be inserted and $new_object contains atomic modifiers (i.e. $ operators), those operations will be applied to the $criteria parameter to create the new document. If $new_object does not contain atomic modifiers, it will be used as-is for the inserted document. See the upsert examples below for more information.

  • "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.

  • "fsync"

    O valoare boolean-a, valoarea implicita este FALSE. Daca jurnalizarea e activata, ea func?ioneaza exact ca "j". Daca jurnalizarea nu este acticvata, atunci se for?eaza sincronizarea pe disc a opera?iunii de inserare înainte de a întoarce succes. Daca are valoarea TRUE, se presupune efectuarea unei inserari cu confirmare ?i setarea w va fi modificata în 0.

    Nota: Daca jurnalizarea este activata, utilizatorii sunt încuraja?i sa utilizeze op?iunea "j" în loc de "fsync". Nu utiliza?i "fsync" ?i "j" simultan, deoarece aceasta va rezulta în eroare.

  • "j"

    O valoare boolean-a, cu valoarea implicita FALSE. For?eaza sincronizarea cu jurnalul a opera?iunii de inserare, înainte de a întoarce succes. Daca are valoarea TRUE, se presupune efectuarea unei inserari cu confirmare ?i setarea w va fi modificata în 0.

    Nota: Daca aceasta op?iune e utilizata, iar jurnalizarea e dezactivata, MongoDB 2.6+ va emite o eroare ?i înscrierea va e?ua; versiunile mai vechi ale serverului pur ?i simplu vor ignora op?iunea.

  • "socketTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru comunicarea prin socket. Daca serverul nu raspunde în limita intervalului de timp, se va emite o MongoCursorTimeoutException ?i nu va fi nici o posibilitate de a determina daca serverul a efectuat înscrierea, sau nu. Valoarea -1 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 30000 (30 secunde).

  • "w"

    Vede?i WriteConcerns. Valoarea implicita pentru MongoClient este 1.

  • "wTimeoutMS"

    Aceasta op?iune specifica limita de timp în milisecunde pentru confirmarea write concern. Aceasta este aplicabila doar atunci când "w" este mai mare decât 1, deoarece expirarea timpului ?ine de replicare. Daca "write concern" nu este satisfacuta în limita intervalului de timp, se va emite o MongoCursorException. Valoarea 0 poate fi specificata pentru a suspenda pentru o perioada nedefinita. Valoarea implicita pentru MongoClient este 10000 (zece secunde).

The following options are deprecated and should no longer be used:

  • "safe"

    Învechita. Utiliza?i op?iunea WriteConcern w.

  • "timeout"

    Un pseudonim învechit pentru "socketTimeoutMS".

  • "wtimeout"

    Un pseudonim învechit pentru "wTimeoutMS".

Valorile întoarse

Returns an array containing the status of the update if the "w" option is set. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Erori/Excep?ii

Genereaza o excep?ie MongoCursorException daca op?iunea "w" este stabilita ?i înscrierea e?ueaza.

Genereaza o excep?ie MongoCursorTimeoutException daca op?iunea "w" este stabilita la o valoare mai mare decât unu ?i opera?iunea dureaza mai mult de MongoCursor::$timeout milisecunde. Aceasta nu va întrerupe opera?iunea pe server, este un timeout de partea clientului. Opera?iunea din MongoCollection::$wtimeout este în milisecunde.

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option. The options parameter no longer accepts a boolean to signify an upsert. Instead, this now has to be done with array('upsert' => true).
1.2.11 | Emits E_DEPRECATED when options is scalar.
1.2.0 | Added "timeout" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.0.9 | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
1.0.5 | Added "safe" option.
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.

Exemple

Example #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")));

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(4) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["firstname"]=>
  string(3) "Bob"
  ["lastname"]=>
  string(5) "Jones"
  ["address"]=>
  string(12) "1 Smith Lane"
}

Example #2 MongoCollection::update() upsert examples

Upserts can simplify code, as a single line can create the document if it does not exist (based on $criteria), or update an existing document if it matches.

In the following example, $new_object contains an atomic modifier. Since the collection is empty and upsert must insert a new document, it will apply those operations to the $criteria parameter in order to create the document.

<?php

$c->drop();
$c->update(
    array("uri" => "/summer_pics"),
    array('$inc' => array("page hits" => 1)),
    array("upsert" => true)
);
var_dump($c->findOne());

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  ["_id"]=>
  object(MongoId)#9 (0) {
  }
  ["uri"]=>
  string(12) "/summer_pics"
  ["page hits"]=>
  int(1)
}

If $new_object does not contain atomic modifiers (i.e. $ operators), upsert will use $new_object as-is for the new document. This matches the behavior of a normal update, where not using atomic modifiers causes the 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());

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  ["_id"]=>
  object(MongoId)#10 (0) {
  }
  ["username"]=>
  string(6) "joe312"
  ["createdAt"]=>
  object(MongoDate)#4 (0) {
  }
}

Example #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)
);

?>

A se vedea ?i

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

Descrierea

public array MongoCollection::validate ([ bool $scan_data = FALSE ] )

Parametri

scan_data

Only validate indices, not the base collection.

Valorile întoarse

Returns the database's evaluation of this object.

MongoCollection::update
MongoCursor
MongoCollection


The MongoCursor class

(PECL mongo >=0.9.0)

Introducere

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:

Example #1 MongoCursor basic usage

<?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:

Example #2 Iterating over MongoCursor

<?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.

Example #3 Adding options to MongoCursor

<?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);
?>

Sinopsisul clasei

MongoCursor implements MongoCursorInterface , Iterator {
/* Static Fields */
static boolean $slaveOkay = FALSE ;
static integer $timeout = 30000 ;
/* Metode */
public MongoCursor addOption ( string $key , mixed $value )
public MongoCursor awaitData ([ bool $wait = true ] )
public MongoCursor batchSize ( int $batchSize )
public __construct ( MongoClient $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 array getReadPreference ( void )
public bool hasNext ( void )
public MongoCursor hint ( mixed $index )
public MongoCursor immortal ([ bool $liveForever = true ] )
public array info ( void )
public string|int key ( void )
public MongoCursor limit ( int $num )
public MongoCursor maxTimeMS ( int $ms )
public array next ( void )
public MongoCursor partial ([ bool $okay = true ] )
public void reset ( void )
public void rewind ( void )
public MongoCursor setFlag ( int $flag [, bool $set = true ] )
public MongoCursor setReadPreference ( string $read_preference [, array $tags ] )
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 secondary (secondaries are, by default, just for backup and not queried). Can be overridden with MongoCursor::slaveOkay().

This functionality is deprecated. Please use Read Preferences instead.

timeout

Set timeout in milliseconds for all database responses. Use -1 to wait forever. Can be overridden with MongoCursor::timeout(). This does not cause the MongoDB server to cancel the operation; it only instructs the driver to stop waiting for a response and throw a MongoCursorTimeoutException after a set time.

A se vedea ?i

MongoDB core docs on » cursors.

Cuprins

  • MongoCursor::addOption — Adds a top-level key/value pair to a query
  • MongoCursor::awaitData — Sets whether this cursor will wait for a while for a tailable cursor to return more data
  • MongoCursor::batchSize — Limits the number of elements returned in one batch.
  • 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 results that have not yet been sent from the database
  • 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 — Advances the cursor to the next result, and returns that result
  • MongoCursor::getReadPreference — Get the read preference for this query
  • 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 information about the cursor's creation and iteration
  • MongoCursor::key — Returns the current result's _id, or its index within the result set
  • MongoCursor::limit — Limits the number of results returned
  • MongoCursor::maxTimeMS — Sets a server-side timeout for this query
  • MongoCursor::next — Advances the cursor to the next result, and returns that 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::setFlag — Sets arbitrary flags in case there is no method available the specific flag
  • MongoCursor::setReadPreference — Set the read preference for this query
  • MongoCursor::skip — Skips a number of results
  • MongoCursor::slaveOkay — Sets whether this query can be done on a secondary [deprecated]
  • 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
Clase de baza


Adds a top-level key/value pair to a query

MongoCursor
MongoCursor::awaitData
MongoCursor
PHP Manual

MongoCursor::addOption

(PECL mongo >=1.0.4)

MongoCursor::addOption — Adds a top-level key/value pair to a query

Descrierea

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.

Avertizare

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.

Parametri

key

Fieldname to add.

value

Value to add.

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Throws MongoCursorException if this cursor has started iterating.

Exemple

Example #1 Adding a comment with MongoCursor::addOption() example

MongoDB supports special options to be send to the server. The shell uses the _addSpecial option to send a $comment to the server. This comment will show up in the profiling log (for slow queries f.e.). In the PHP driver, you use the MongoCursor::addOption() method.

<?php
$m = new MongoClient;
$c = $m->demo->demo;
$cursor = $c->find();
$cursor->addOption('$comment', "This comment will show up in the profiling log");

foreach ($cursor as $document) { /* empty */ }
?>

Exemplul de mai sus va afi?a ceva similar cu:

{
    "op" : "query",
    "ns" : "demo.demo",
    "query" : {
        "$query" : {

        },
        "$comment" : "This comment will show up in the profiling log"
    },
    "cursorid" : 168463566447,
    "ntoreturn" : 0,
    "ntoskip" : 0,
    "nscanned" : 101,
    "nscannedObjects" : 101,
    "keyUpdates" : 0,
    "numYield" : 0,
…

Example #2 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::awaitData
MongoCursor


Sets whether this cursor will wait for a while for a tailable cursor to return more data

MongoCursor::addOption
MongoCursor::batchSize
MongoCursor
PHP Manual

MongoCursor::awaitData

(PECL mongo >=1.2.11)

MongoCursor::awaitData — Sets whether this cursor will wait for a while for a tailable cursor to return more data

Descrierea

public MongoCursor MongoCursor::awaitData ([ bool $wait = true ] )

This method is to be used with tailable cursors. If we are at the end of the data, block for a while rather than returning no data. After a timeout period, we do return as normal.

Parametri

wait

If the cursor should wait for more data to become available.

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Throws MongoCursorException if this cursor has started iterating.

Exemple

Example #1 MongoCursor::awaitData() example

In this example we tail the "oplog" and instead of sleeping during every iteration, we set the MongoCursor::awaitData() option. MongoCursor::hasNext() will now block until there is more data available.

<?php
$m = new MongoClient( 'mongodb://localhost:13000', array( 'replSet' => 'seta' ) );
$c = $m->local->selectCollection( 'oplog.rs' );
$cursor = $c->find( array( 'ns' => 'demo.article', 'op' => 'i' ) );
$cursor->tailable( true );
$cursor->awaitData( true );

while (true) {
    if (!$cursor->hasNext()) {
        // we've read all the results, exit
        if ($cursor->dead()) {
            break;
        }
    } else {
        var_dump( $cursor->getNext() );
    }
}
?>

A se vedea ?i

MongoDB core docs on » tailable cursors.

  • MongoCursor::tailable() - Sets whether this cursor will be left open after fetching the last results

MongoCursor::addOption
MongoCursor::batchSize
MongoCursor


Limits the number of elements returned in one batch.

MongoCursor::awaitData
MongoCursor::__construct
MongoCursor
PHP Manual

MongoCursor::batchSize

(PECL mongo >=1.0.11)

MongoCursor::batchSize — Limits the number of elements returned in one batch.

Descrierea

public MongoCursor MongoCursor::batchSize ( int $batchSize )

A cursor typically fetches a batch of result objects and store them locally. This method sets the batchSize value to configure the amount of documents retrieved from the server in one round trip. However, it will never return more documents than fit in the max batch size limit (usually 4MB).

Parametri

batchSize

The number of results to return per batch. Each batch requires a round-trip to the server.

If batchSize is 2 or more, it represents the size of each batch of objects retrieved. It can be adjusted to optimize performance and limit data transfer.

If batchSize is 1 or negative, it will limit of number returned documents to the absolute value of batchSize, and the cursor will be closed. For example if batchSize is -10, then the server will return a maximum of 10 documents and as many as can fit in 4MB, then close the cursor.

Avertizare

A batchSize of 1 is special, and means the same as -1, i.e. a value of 1 makes the cursor only capable of returning one document.

Note that this feature is different from MongoCursor::limit() in that documents must fit within a maximum size, and it removes the need to send a request to close the cursor server-side. The batch size can be changed even after a cursor is iterated, in which case the setting will apply on the next batch retrieval.

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 per batch).

To ensure consistent behavior, the rules of MongoCursor::batchSize() and MongoCursor::limit() behave 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. See below. section for some examples.

Valorile întoarse

Returns this cursor.

Exemple

Example #1 MongoCursor::batchSize() and combinations with MongoCursor::limit()

<?php

// one batch, at most 10 items. The -10 makes the server to return 10 items,
// and then remove the cursor.
$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);

// results are fetched in batches of 10 each, with a maximum of 20 items
// returned (that means two batches of 10).
$cursor->limit(20)->batchSize(10);

// results are fetched in batches of 7 each, with a maximum of 30 items
// returned (that means that the driver requests 4 batches of 7, and one batch
// of 2).
$cursor->limit(30)->batchSize(7)
?>

A se vedea ?i

MongoDB core docs on » batchSize.

  • MongoCursor::limit() - Limits the number of results returned
  • MongoCursorInterface::batchSize() - Limits the number of elements returned in one batch.

Istoricul schimbarilor

Versiune | Descriere
1.4.5 | Before 1.4.5, this method would throw an MongoCursorException if the cursor had already started iterating.

MongoCursor::awaitData
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

Descrierea

public MongoCursor::__construct ( MongoClient $connection , string $ns [, array $query = array() [, array $fields = array() ]] )

Parametri

connection

Database connection.

ns

Full name of database and collection.

query

Database query.

fields

Fields to return.

Valorile întoarse

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

Descrierea

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.

Parametri

foundOnly

Send cursor limit and skip information to the count function, if applicable.

Valorile întoarse

The number of documents returned by this cursor's query.

Exemple

Example #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));

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)
int(3)
int(3)
int(2)

Erori/Excep?ii

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

Descrierea

public array MongoCursor::current ( void )

This returns NULL until MongoCursor::next() is called.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current result document as an associative array. NULL will be returned if there is no result.

A se vedea ?i

  • Iterator::current() - Return the current element
MongoCursor::count
MongoCursor::dead
MongoCursor


Checks if there are results that have not yet been sent from the database

MongoCursor::current
MongoCursor::doQuery
MongoCursor
PHP Manual

MongoCursor::dead

(PECL mongo >=0.9.6)

MongoCursor::dead — Checks if there are results that have not yet been sent from the database

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if there are more results that have not yet been sent to the client, and FALSE otherwise.

A se vedea ?i

  • MongoCursorInterface::dead() - Checks if there are results that have not yet been sent from the database
MongoCursor::current
MongoCursor::doQuery
MongoCursor


Execute the query.

MongoCursor::dead
MongoCursor::explain
MongoCursor
PHP Manual

MongoCursor::doQuery

(PECL mongo >=0.9.0 <1.6.0)

MongoCursor::doQuery — Execute the query.

Descrierea

protected void MongoCursor::doQuery ( void )
Avertizare

Please do not use me.

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).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

NULL.

Erori/Excep?ii

Throws MongoConnectionException if it cannot reach the database.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

Exemple

Example #1 MongoCursor::doQuery() example

You could override this function to attempt a query on a secondary and, if that fails, try it again on the primary.

<?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

Descrierea

public array MongoCursor::explain ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an explanation of the query.

Exemple

Example #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());

?>

Exemplul de mai sus va afi?a ceva similar cu:

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) {
      }
    }
  }
}

Erori/Excep?ii

Throws MongoConnectionException if it cannot reach the database.

A se vedea ?i

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

Descrierea

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));

?>

Parametri

f

Fields to return (or not return).

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Throws MongoCursorException if this cursor has started iterating or a scalar argument is given.

MongoCursor::explain
MongoCursor::getNext
MongoCursor


Advances the cursor to the next result, and returns that result

MongoCursor::fields
MongoCursor::getReadPreference
MongoCursor
PHP Manual

MongoCursor::getNext

(PECL mongo >=0.9.0)

MongoCursor::getNext — Advances the cursor to the next result, and returns that result

Descrierea

public array MongoCursor::getNext ( void )

Nota:

MongoCursor::getNext() is an alias of MongoCursor::next().

MongoCursor::fields
MongoCursor::getReadPreference
MongoCursor


Get the read preference for this query

MongoCursor::getNext
MongoCursor::hasNext
MongoCursor
PHP Manual

MongoCursor::getReadPreference

(PECL mongo >=1.3.3)

MongoCursor::getReadPreference — Get the read preference for this query

Descrierea

public array MongoCursor::getReadPreference ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Aceasta func?ie întoarce un tablou ce descrie preferin?a de citire. Tabloul con?ine tipul (type) valorilor pentru ?irul cu modul preferin?ei de citire (ce corespunde constantelor MongoClient), ?i tagsets con?inând lista tuturor criteriilor setului de etichete. Daca nu a fost specificat nici un set de etichete, tagsets nu va fi prezent în tablou.

Exemple

Example #1 MongoCursor::getReadPreference() return value example

<?php

$m = new MongoClient();
$cursor = $m->test->users->find();
$cursor->setReadPreference(MongoClient::RP_SECONDARY, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
    array(),
));
var_dump($cursor->getReadPreference());
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["type"]=>
  string(9) "secondary"
  ["tagsets"]=>
  array(3) {
    [0]=>
    array(2) {
      ["dc"]=>
      string(4) "east"
      ["use"]=>
      string(9) "reporting"
    }
    [1]=>
    array(1) {
      ["dc"]=>
      string(7) "west"
    }
    [2]=>
    array(0) {
    }
  }
}

A se vedea ?i

  • The read preferences documentation.
  • MongoCursor::setReadPreference() - Set the read preference for this query
  • MongoCursorInterface::getReadPreference() - Get the read preference for this query
MongoCursor::getNext
MongoCursor::hasNext
MongoCursor


Checks if there are any more elements in this cursor

MongoCursor::getReadPreference
MongoCursor::hint
MongoCursor
PHP Manual

MongoCursor::hasNext

(PECL mongo >=0.9.0)

MongoCursor::hasNext — Checks if there are any more elements in this cursor

Descrierea

public bool MongoCursor::hasNext ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns if there is another element.

Erori/Excep?ii

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

MongoCursor::getReadPreference
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

Descrierea

public MongoCursor MongoCursor::hint ( mixed $index )

Parametri

index

Index to use for the query. If a string is passed, it should correspond to an index name. If an array or object is passed, it should correspond to the specification used to create the index (i.e. the first argument to MongoCollection::ensureIndex()).

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Throws MongoCursorException if this cursor has started iterating.

Istoricul schimbarilor

Versiune | Descriere
1.4.0 | The index argument now supports index names as string values. In versions before 1.4.0, only array or object values were accepted.

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

Descrierea

public MongoCursor MongoCursor::immortal ([ bool $liveForever = true ] )

After remaining idle on the server for some amount of time, cursors, 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 MongoCursor::dead() returns TRUE) or the cursor will hang around the database forever, taking up resources.

Parametri

liveForever

If the cursor should be immortal.

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Throws MongoCursorException if this cursor has started iterating.

MongoCursor::hint
MongoCursor::info
MongoCursor


Gets information about the cursor's creation and iteration

MongoCursor::immortal
MongoCursor::key
MongoCursor
PHP Manual

MongoCursor::info

(PECL mongo >=1.0.5)

MongoCursor::info — Gets information about the cursor's creation and iteration

Descrierea

public array MongoCursor::info ( void )

This can be called before or after the cursor has started iterating.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the namespace, batch size, limit, skip, flags, query, and projected fields for this cursor. If the cursor has started iterating, additional information about iteration and the connection will be included.

Istoricul schimbarilor

Versiune | Descriere
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 Read Preferences.
1.0.10 | Added started_iterating field, a boolean indicating if cursor is pre- or post-query.

Exemple

Example #1 MongoCursor::info() example

<?php
$m = new MongoClient();

$cursor = $m->test->foo->find(array("x" => 4), array("y" => 0));

echo "Before iteration started:\n";
var_dump($cursor->info());

echo "\nAfter iteration started:\n";
$cursor->rewind();
var_dump($cursor->info());

?>

Exemplul de mai sus va afi?a ceva similar cu:

Before iteration started:
array(8) {
  ["ns"]=>
  string(8) "test.foo"
  ["limit"]=>
  int(0)
  ["batchSize"]=>
  int(0)
  ["skip"]=>
  int(0)
  ["flags"]=>
  int(0)
  ["query"]=>
  array(1) {
    ["x"]=>
    int(4)
  }
  ["fields"]=>
  array(1) {
    ["y"]=>
    int(0)
  }
  ["started_iterating"]=>
  bool(false)
}

After iteration started:
array(15) {
  ["ns"]=>
  string(8) "test.foo"
  ["limit"]=>
  int(0)
  ["batchSize"]=>
  int(0)
  ["skip"]=>
  int(0)
  ["flags"]=>
  int(0)
  ["query"]=>
  array(1) {
    ["x"]=>
    int(4)
  }
  ["fields"]=>
  array(1) {
    ["y"]=>
    int(0)
  }
  ["started_iterating"]=>
  bool(true)
  ["id"]=>
  int(0)
  ["at"]=>
  int(0)
  ["numReturned"]=>
  int(1)
  ["server"]=>
  string(25) "localhost:27017;-;.;26450"
  ["host"]=>
  string(9) "localhost"
  ["port"]=>
  int(27017)
  ["connection_type_desc"]=>
  string(10) "STANDALONE"
}

A se vedea ?i

  • MongoCursorInterface::info() - Gets information about the cursor's creation and iteration
MongoCursor::immortal
MongoCursor::key
MongoCursor


Returns the current result's _id, or its index within the result set

MongoCursor::info
MongoCursor::limit
MongoCursor
PHP Manual

MongoCursor::key

(PECL mongo >=0.9.0)

MongoCursor::key — Returns the current result's _id, or its index within the result set

Descrierea

public string|int MongoCursor::key ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current result's _id as a string. If the result has no _id, its numeric index within the result set will be returned as an integer.

A se vedea ?i

  • Iterator::key() - Return the key of the current element
MongoCursor::info
MongoCursor::limit
MongoCursor


Limits the number of results returned

MongoCursor::key
MongoCursor::maxTimeMS
MongoCursor
PHP Manual

MongoCursor::limit

(PECL mongo >=0.9.0)

MongoCursor::limit — Limits the number of results returned

Descrierea

public MongoCursor MongoCursor::limit ( int $num )

Parametri

num

The number of results to return.

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Throws MongoCursorException if this cursor has started iterating.

A se vedea ?i

  • MongoDB core docs on » limit.
  • MongoCursor::batchSize() - Limits the number of elements returned in one batch.
  • MongoCursor::skip() - Skips a number of results

MongoCursor::key
MongoCursor::maxTimeMS
MongoCursor


Sets a server-side timeout for this query

MongoCursor::limit
MongoCursor::next
MongoCursor
PHP Manual

MongoCursor::maxTimeMS

(PECL mongo >=1.5.0)

MongoCursor::maxTimeMS — Sets a server-side timeout for this query

Descrierea

public MongoCursor MongoCursor::maxTimeMS ( int $ms )

Specifies a cumulative time limit in milliseconds to be allowed by the server for processing operations on the cursor.

Parametri

ms

Specifies a cumulative time limit in milliseconds to be allowed by the server for processing operations on the cursor.

Valorile întoarse

This cursor.

Erori/Excep?ii

Throws MongoCursorException if this cursor has started iterating.

Causes methods that fetch results to throw a MongoExecutionTimeoutException if the query takes longer than the specified number of milliseconds in processing time.

Exemple

Example #1 MongoCursor::maxTimeMS() example

In the following example, the server will abort the query if the cursor requires more than two seconds in processing time to return its results.

<?php

$cursor = $collection->find();
$cursor->maxTimeMS(2000);

try {
    $results = iterator_to_array($cursor);
} catch (MongoExecutionTimeoutException $e) {
    echo "query took too long!";
}

?>

Note

Avertizare

Unlike MongoCursor::timeout(), which specifies a client-side timeout, MongoCursor::maxTimeMS() can be used to cause the MongoDB server to abort long-running queries. This timeout is cumulative for the lifetime of the cursor (i.e. each batch will contribute to this time limit). The timeout only considers processing time; idle time is not considered.

MongoCursor::limit
MongoCursor::next
MongoCursor


Advances the cursor to the next result, and returns that result

MongoCursor::maxTimeMS
MongoCursor::partial
MongoCursor
PHP Manual

MongoCursor::next

(PECL mongo >=0.9.0)

MongoCursor::next — Advances the cursor to the next result, and returns that result

Descrierea

public array MongoCursor::next ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the next document.

Erori/Excep?ii

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

A se vedea ?i

  • Iterator::next() - Move forward to next element
MongoCursor::maxTimeMS
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

Descrierea

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.

Parametri

okay

If receiving partial results is okay.

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

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

Descrierea

public void MongoCursor::reset ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

NULL.

MongoCursor::partial
MongoCursor::rewind
MongoCursor


Returns the cursor to the beginning of the result set

MongoCursor::reset
MongoCursor::setFlag
MongoCursor
PHP Manual

MongoCursor::rewind

(PECL mongo >=0.9.0)

MongoCursor::rewind — Returns the cursor to the beginning of the result set

Descrierea

public void MongoCursor::rewind ( void )

This is identical to the function:

<?php

public function rewind() {
    $this->reset();
    $this->next();
}

?>

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

NULL.

Erori/Excep?ii

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

A se vedea ?i

  • Iterator::rewind() - Rewind the Iterator to the first element
MongoCursor::reset
MongoCursor::setFlag
MongoCursor


Sets arbitrary flags in case there is no method available the specific flag

MongoCursor::rewind
MongoCursor::setReadPreference
MongoCursor
PHP Manual

MongoCursor::setFlag

(PECL mongo >=1.2.11)

MongoCursor::setFlag — Sets arbitrary flags in case there is no method available the specific flag

Descrierea

public MongoCursor MongoCursor::setFlag ( int $flag [, bool $set = true ] )

The MongoCursor class has several methods for setting flags on the query object. This method is available in case the MongoDB wire protocol has acquired a new flag, and the driver has not been updated with a method for this new flag. In all other cases, the method should be used. See the "See also" section for available methods.

Parametri

flag

Which flag to set. You can not set flag 6 (EXHAUST) as the driver does not know how to handle them. You will get a warning if you try to use this flag. For available flags, please refer to the wire protocol » documentation.

set

Whether the flag should be set (TRUE) or unset (FALSE).

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Shows a warning when an unsupport flag is attempted to be set.

Istoricul schimbarilor

Versiune | Descriere
1.4.0 | Support for flag 3 (OPLOG_REPLAY) is added. Versions before 1.4.0 would throw a warning saying that the flag is unsupported.

Exemple

Example #1 MongoCursor::setFlag() example

<?php
$m = new MongoClient( 'mongodb://localhost:13000', array( 'replSet' => 'seta' ) );
$c = $m->local->selectCollection( 'oplog.rs' );
$cursor = $c->find( array( 'ns' => 'demo.article', 'op' => 'i' ) );
$cursor->setFlag( 1, true ); // sets the tailable flag
$cursor->setFlag( 5, true ); // sets the await data flag
?>

A se vedea ?i

  • MongoCursor::tailable() - Sets whether this cursor will be left open after fetching the last results
  • MongoCursor::immortal() - Sets whether this cursor will timeout
  • MongoCursor::awaitData() - Sets whether this cursor will wait for a while for a tailable cursor to return more data
  • MongoCursor::partial() - If this query should fetch partial results from mongos if a shard is down
  • MongoDB core docs on» wire protocol query flags

MongoCursor::rewind
MongoCursor::setReadPreference
MongoCursor


Set the read preference for this query

MongoCursor::setFlag
MongoCursor::skip
MongoCursor
PHP Manual

MongoCursor::setReadPreference

(PECL mongo >=1.3.3)

MongoCursor::setReadPreference — Set the read preference for this query

Descrierea

public MongoCursor MongoCursor::setReadPreference ( string $read_preference [, array $tags ] )

Parametri

read_preference

Modul preferin?ei de citire:
MongoClient::RP_PRIMARY,
MongoClient::RP_PRIMARY_PREFERRED,
MongoClient::RP_SECONDARY,
MongoClient::RP_SECONDARY_PREFERRED sau
MongoClient::RP_NEAREST.

tags

Un tablou din zero sau mai multe seturi de etichete, unde fiecare set de etichete este la rândul sau un tablou de criterii utilizate pentru a potrivi etichetele pe membrii setului de replicare.

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Emite un E_WARNING daca careva parametru nu e valid, sau daca unul sau mai multe seturi de etichete sunt furnizate cu modul preferin?ei de citire MongoClient::RP_PRIMARY.

Exemple

Example #1 MongoCursor::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient();
$cursor = $m->test->users->find();

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$cursor->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));
?>

A se vedea ?i

  • The read preferences documentation.
  • MongoCursor::getReadPreference() - Get the read preference for this query
  • MongoCursorInterface::setReadPreference() - Set the read preference for this query
MongoCursor::setFlag
MongoCursor::skip
MongoCursor


Skips a number of results

MongoCursor::setReadPreference
MongoCursor::slaveOkay
MongoCursor
PHP Manual

MongoCursor::skip

(PECL mongo >=0.9.0)

MongoCursor::skip — Skips a number of results

Descrierea

public MongoCursor MongoCursor::skip ( int $num )

Parametri

num

The number of results to skip.

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Throws MongoCursorException if this cursor has started iterating.

A se vedea ?i

  • MongoCursor::limit() - Limits the number of results returned

MongoCursor::setReadPreference
MongoCursor::slaveOkay
MongoCursor


Sets whether this query can be done on a secondary [deprecated]

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 secondary [deprecated]

Descrierea

public MongoCursor MongoCursor::slaveOkay ([ bool $okay = true ] )
Avertizare

This method is deprecated since version 1.5.0. Instead, please use MongoCursor::setReadPreference() and Read Preferences.

Calling this will make the driver route reads to secondaries if:

  • You are using a replica set, and
  • You created a MongoClient instance using the option "replicaSet" => "setName", and
  • There is a healthy secondary 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 secondaries. 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().

Parametri

okay

If it is okay to query the secondary.

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Throws MongoCursorException if this cursor has started iterating.

Exemple

Example #1 MongoCursor::slaveOkay() example

<?php

MongoCursor::$slaveOkay = false;

// cannot query secondary
$cursor = $collection->find();

// can query secondary
$cursor = $collection->find()->slaveOkay();

MongoCursor::$slaveOkay = true;

// can query secondary
$cursor = $collection->find();

// cannot query secondary
$cursor = $collection->find()->slaveOkay(false);

?>

A se vedea ?i

  • Read Preferences
  • MongoCursor::setReadPreference() - Set the read preference for this query
  • MongoCursor::getReadPreference() - Get the read preference for this query

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | This method has been deprecated in favour of MongoCursor::setReadPreference() and Read Preferences.

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

Descrierea

public MongoCursor MongoCursor::snapshot ( void )

Use snapshot mode for the query. Snapshot mode ensures that a document will not be returned more than once because an intervening write operation results in a move of the document. Documents inserted or deleted during the lifetime of the cursor may or may not be returned, irrespective of snapshot mode.

Queries with short responses (less than 1MB) are always effectively snapshotted.

Snapshot mode may not be used with sorting, explicit hints, or queries on sharded collections.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Throws MongoCursorException if this cursor has started iterating.

A se vedea ?i

MongoDB core docs on » $snapshot operator.

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

Descrierea

public MongoCursor MongoCursor::sort ( array $fields )

Parametri

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.

Valorile întoarse

Returns the same cursor that this method was called on.

Erori/Excep?ii

Throws MongoCursorException if this cursor has started iterating.

Exemple

Example #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

Descrierea

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().

Parametri

tail

If the cursor should be tailable.

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Throws MongoCursorException if this cursor has started iterating.

Exemple

Example #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();
    }
}

?>

A se vedea ?i

MongoDB core docs on » tailable cursors.

  • MongoCursor::awaitData() - Sets whether this cursor will wait for a while for a tailable cursor to return more data

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

Descrierea

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.

Parametri

ms

The number of milliseconds for the cursor to wait for a response. Use -1 to wait forever. By default, the cursor will wait 30000 milliseconds (30 seconds).

Valorile întoarse

This cursor.

Erori/Excep?ii

Causes methods that fetch results to throw a MongoCursorTimeoutException if the query takes longer than the specified number of milliseconds.

Exemple

Example #1 MongoCursor::timeout() example

In the following example, the driver will wait forever for the initial database response, and then wait 100ms for subsequent responses.

<?php

$cursor = $collection->find();
$cursor->timeout(-1);

/* $cursor->hasNext() executes the query. An infinite timeout has been set, so
 * the driver will wait as long as necessary for a response.
 */
while ($cursor->hasNext()) {
    $cursor->timeout(100);

    /* A timeout has now been set, so if the cursor needs to get more results
     * from the database, it will only wait 100ms for a response.
     */
    try {
        print_r($cursor->getNext());
    } catch (MongoCursorTimeoutException $e) {
        echo "query took too long!";
    }
}

?>

Note

Avertizare

This does not cause the MongoDB server to cancel long-running operations; it only instructs the driver to stop waiting for a response and throw a MongoCursorTimeoutException after a set time. If you need to specify a server-side timeout for a query, consider using MongoCursor::maxTimeMS().

A se vedea ?i

  • MongoCursorInterface::timeout() - Sets a client-side timeout for this query
  • The socketTimeoutMS option for MongoClient::__construct()
MongoCursor::tailable
MongoCursor::valid
MongoCursor


Checks if the cursor is reading a valid result.

MongoCursor::timeout
MongoCursorInterface
MongoCursor
PHP Manual

MongoCursor::valid

(PECL mongo >=0.9.0)

MongoCursor::valid — Checks if the cursor is reading a valid result.

Descrierea

public bool MongoCursor::valid ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the current result is not null, and FALSE otherwise.

A se vedea ?i

  • Iterator::valid() - Checks if current position is valid
MongoCursor::timeout
MongoCursorInterface
MongoCursor


The MongoCursorInterface interface

(PECL mongo >=1.5.0)

Introducere

Interface for cursors, which can be used to iterate through results of a database query or command. This interface is implemented by the MongoCursor and MongoCommandCursor classes.

Nota: Similar to Traversable, this interface cannot be implemented in PHP scripts.

Sinopsisul clasei

MongoCursorInterface extends Iterator {
/* Metode */
abstract public MongoCursorInterface batchSize ( int $batchSize )
abstract public bool dead ( void )
abstract public array getReadPreference ( void )
abstract public array info ( void )
abstract public MongoCursorInterface setReadPreference ( string $read_preference [, array $tags ] )
abstract public MongoCursorInterface timeout ( int $ms )
/* Metode mo?tenite */
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 )
}

Cuprins

  • MongoCursorInterface::batchSize — Limits the number of elements returned in one batch.
  • MongoCursorInterface::dead — Checks if there are results that have not yet been sent from the database
  • MongoCursorInterface::getReadPreference — Get the read preference for this query
  • MongoCursorInterface::info — Gets information about the cursor's creation and iteration
  • MongoCursorInterface::setReadPreference — Set the read preference for this query
  • MongoCursorInterface::timeout — Sets a client-side timeout for this query
MongoCursor::valid
MongoCursorInterface::batchSize
Clase de baza


Limits the number of elements returned in one batch.

MongoCursorInterface
MongoCursorInterface::dead
MongoCursorInterface
PHP Manual

MongoCursorInterface::batchSize

(PECL mongo >=1.5.0)

MongoCursorInterface::batchSize — Limits the number of elements returned in one batch.

Descrierea

abstract public MongoCursorInterface MongoCursorInterface::batchSize ( int $batchSize )

A cursor typically fetches a batch of result objects and stores them locally. This method sets the batch size value to configure the amount of documents retrieved from the server in one round trip.

Parametri

batchSize

The number of results to return per batch.

Valorile întoarse

Returns this cursor.

MongoCursorInterface
MongoCursorInterface::dead
MongoCursorInterface


Checks if there are results that have not yet been sent from the database

MongoCursorInterface::batchSize
MongoCursorInterface::getReadPreference
MongoCursorInterface
PHP Manual

MongoCursorInterface::dead

(PECL mongo >=1.5.0)

MongoCursorInterface::dead — Checks if there are results that have not yet been sent from the database

Descrierea

abstract public bool MongoCursorInterface::dead ( void )

This method checks whether the cursor has been exhausted and the database has no more results to send to the client. A cursor being "dead" does not necessarily mean that there are no more results available for iteration.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if there are more results that have not yet been sent to the client, and FALSE otherwise.

MongoCursorInterface::batchSize
MongoCursorInterface::getReadPreference
MongoCursorInterface


Get the read preference for this query

MongoCursorInterface::dead
MongoCursorInterface::info
MongoCursorInterface
PHP Manual

MongoCursorInterface::getReadPreference

(PECL mongo >=1.6.0)

MongoCursorInterface::getReadPreference — Get the read preference for this query

Descrierea

abstract public array MongoCursorInterface::getReadPreference ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Aceasta func?ie întoarce un tablou ce descrie preferin?a de citire. Tabloul con?ine tipul (type) valorilor pentru ?irul cu modul preferin?ei de citire (ce corespunde constantelor MongoClient), ?i tagsets con?inând lista tuturor criteriilor setului de etichete. Daca nu a fost specificat nici un set de etichete, tagsets nu va fi prezent în tablou.

A se vedea ?i

  • The read preferences documentation.
  • MongoCursorInterface::setReadPreference() - Set the read preference for this query
MongoCursorInterface::dead
MongoCursorInterface::info
MongoCursorInterface


Gets information about the cursor's creation and iteration

MongoCursorInterface::getReadPreference
MongoCursorInterface::setReadPreference
MongoCursorInterface
PHP Manual

MongoCursorInterface::info

(PECL mongo >=1.5.0)

MongoCursorInterface::info — Gets information about the cursor's creation and iteration

Descrierea

abstract public array MongoCursorInterface::info ( void )

Returns information about the cursor's creation and iteration. This can be called before or after the cursor has started iterating.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the namespace, batch size, limit, skip, flags, query, and projected fields for this cursor. If the cursor has started iterating, additional information about iteration and the connection will be included.

MongoCursorInterface::getReadPreference
MongoCursorInterface::setReadPreference
MongoCursorInterface


Set the read preference for this query

MongoCursorInterface::info
MongoCursorInterface::timeout
MongoCursorInterface
PHP Manual

MongoCursorInterface::setReadPreference

(PECL mongo >=1.6.0)

MongoCursorInterface::setReadPreference — Set the read preference for this query

Descrierea

abstract public MongoCursorInterface MongoCursorInterface::setReadPreference ( string $read_preference [, array $tags ] )

Parametri

read_preference

Modul preferin?ei de citire:
MongoClient::RP_PRIMARY,
MongoClient::RP_PRIMARY_PREFERRED,
MongoClient::RP_SECONDARY,
MongoClient::RP_SECONDARY_PREFERRED sau
MongoClient::RP_NEAREST.

tags

Un tablou din zero sau mai multe seturi de etichete, unde fiecare set de etichete este la rândul sau un tablou de criterii utilizate pentru a potrivi etichetele pe membrii setului de replicare.

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Emite un E_WARNING daca careva parametru nu e valid, sau daca unul sau mai multe seturi de etichete sunt furnizate cu modul preferin?ei de citire MongoClient::RP_PRIMARY.

A se vedea ?i

  • The read preferences documentation.
  • MongoCursorInterface::getReadPreference() - Get the read preference for this query
MongoCursorInterface::info
MongoCursorInterface::timeout
MongoCursorInterface


Sets a client-side timeout for this query

MongoCursorInterface::setReadPreference
MongoCommandCursor
MongoCursorInterface
PHP Manual

MongoCursorInterface::timeout

(PECL mongo >=1.5.0)

MongoCursorInterface::timeout — Sets a client-side timeout for this query

Descrierea

abstract public MongoCursorInterface MongoCursorInterface::timeout ( int $ms )

A timeout can be set at any time and will affect subsequent data retrieval associated with this cursor, including fetching more results from the database.

Parametri

ms

The number of milliseconds for the cursor to wait for a response. Use -1 to wait forever. By default, the cursor will wait 30000 milliseconds (30 seconds).

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Causes methods that fetch results to throw a MongoCursorTimeoutException if the data fetch takes longer than the specified number of milliseconds.

A se vedea ?i

  • The socketTimeoutMS option for MongoClient::__construct()
MongoCursorInterface::setReadPreference
MongoCommandCursor
MongoCursorInterface


The MongoCommandCursor class

(PECL mongo >=1.5.0)

Introducere

A command cursor is similar to a MongoCursor except that you use it for iterating through the results of a database command instead of a normal query. Command cursors are useful for iterating over large result sets that might exceed the document size limit (currently 16MB) of a single MongoDB::command() response.

While you can create command cursors using MongoCommandCursor::__construct() or the MongoCommandCursor::createFromDocument() factory method, you will generally want to use command-specific helpers such as MongoCollection::aggregateCursor().

Note that the cursor does not "contain" the database command's results; it just manages iteration through them. Thus, if you print a cursor (f.e. with var_dump() or print_r()), you will see the cursor object but not the result documents.

Cursor Stages

A MongoCommandCursor has two "life stages": pre- and post- command. When a cursor is created, it has not yet contacted the database, so it is in its pre-command state. When the client first attempts to get a result (by calling MongoCommandCursor::rewind(), directly or indirectly), the cursor moves into the post-command state.

The command cursor's batch size and socket timeout may be configured in both the pre- and post- command states.

Example #1 Adding options to MongoCommandCursor

<?php

$cursor = new MongoCommandCursor(...);

$cursor = $cursor->batchSize( 4 );

foreach ($cursor as $result) {
    var_dump($result);
}
?>

Sinopsisul clasei

MongoCommandCursor implements MongoCursorInterface , Iterator {
/* Metode */
public MongoCommandCursor batchSize ( int $batchSize )
public __construct ( MongoClient $connection , string $ns , array $command = array() )
public static MongoCommandCursor createFromDocument ( MongoClient $connection , string $hash , array $document )
public array current ( void )
public bool dead ( void )
public array getReadPreference ( void )
public array info ( void )
public int key ( void )
public void next ( void )
public array rewind ( void )
public MongoCommandCursor setReadPreference ( string $read_preference [, array $tags ] )
public MongoCommandCursor timeout ( int $ms )
public bool valid ( void )
}

A se vedea ?i

  • MongoDB::command()
  • MongoCollection::aggregateCursor()

Cuprins

  • MongoCommandCursor::batchSize — Limits the number of elements returned in one batch.
  • MongoCommandCursor::__construct — Create a new command cursor
  • MongoCommandCursor::createFromDocument — Create a new command cursor from an existing command response document
  • MongoCommandCursor::current — Returns the current element
  • MongoCommandCursor::dead — Checks if there are results that have not yet been sent from the database
  • MongoCommandCursor::getReadPreference — Get the read preference for this command
  • MongoCommandCursor::info — Gets information about the cursor's creation and iteration
  • MongoCommandCursor::key — Returns the current result's index within the result set
  • MongoCommandCursor::next — Advances the cursor to the next result
  • MongoCommandCursor::rewind — Executes the command and resets the cursor to the start of the result set
  • MongoCommandCursor::setReadPreference — Set the read preference for this command
  • MongoCommandCursor::timeout — Sets a client-side timeout for this command
  • MongoCommandCursor::valid — Checks if the cursor is reading a valid result.
MongoCursorInterface::timeout
MongoCommandCursor::batchSize
Clase de baza


Limits the number of elements returned in one batch.

MongoCommandCursor
MongoCommandCursor::__construct
MongoCommandCursor
PHP Manual

MongoCommandCursor::batchSize

(PECL mongo >=1.5.0)

MongoCommandCursor::batchSize — Limits the number of elements returned in one batch.

Descrierea

public MongoCommandCursor MongoCommandCursor::batchSize ( int $batchSize )

A cursor typically fetches a batch of result objects and store them locally. This method sets the batchSize value to configure the amount of documents retrieved from the server in one round trip.

Parametri

batchSize

The number of results to return per batch. Each batch requires a round-trip to the server.

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 per batch).

Valorile întoarse

Returns this cursor.

Exemple

Example #1 MongoCommandCursor::batchSize()

<?php
$commandCursor->batchSize(20);
?>

A se vedea ?i

  • MongoCursorInterface::batchSize() - Limits the number of elements returned in one batch.
MongoCommandCursor
MongoCommandCursor::__construct
MongoCommandCursor


Create a new command cursor

MongoCommandCursor::batchSize
MongoCommandCursor::createFromDocument
MongoCommandCursor
PHP Manual

MongoCommandCursor::__construct

(PECL mongo >=1.5.0)

MongoCommandCursor::__construct — Create a new command cursor

Descrierea

public MongoCommandCursor::__construct ( MongoClient $connection , string $ns , array $command = array() )

Generally, you should not have to construct a MongoCommandCursor manually, as there are helper functions such as MongoCollection::aggregateCursor() and MongoCollection::parallelCollectionScan(); however, if the server introduces new commands that can return cursors, this constructor will be useful in the absence of specific helper methods. You may also consider using MongoCommandCursor::createFromDocument().

Parametri

connection

Database connection.

ns

Full name of the database and collection (e.g. "test.foo")

command

Database command.

Valorile întoarse

Returns the new cursor.

Exemple

Example #1 MongoCommandCursor example

<?php
$m = new MongoClient;

// Define the aggregation pipeline
$pipeline = [
    [ '$group' => [
        '_id' => '$country_code',
        'timezones' => [ '$addToSet' => '$timezone' ]
    ] ],
    [ '$sort' => [ '_id' => 1 ] ],
];

// Construct a MongoCommandCursor object
$cursor = new MongoCommandCursor(
    $m, // MongoClient object
    'demo.cities', // namespace
    [
        'aggregate' => 'cities',
        'pipeline' => $pipeline,
        'cursor' => [ 'batchSize' => 0 ],
    ]
);

foreach($cursor as $result) {
   …
}
?>

A se vedea ?i

  • MongoCommandCursor::createFromDocument() - Create a new command cursor from an existing command response document
  • MongoCollection::aggregateCursor() - Execute an aggregation pipeline command and retrieve results through a cursor
  • MongoCollection::parallelCollectionScan() - Returns an array of cursors to iterator over a full collection in parallel
MongoCommandCursor::batchSize
MongoCommandCursor::createFromDocument
MongoCommandCursor


Create a new command cursor from an existing command response document

MongoCommandCursor::__construct
MongoCommandCursor::current
MongoCommandCursor
PHP Manual

MongoCommandCursor::createFromDocument

(PECL mongo >=1.5.0)

MongoCommandCursor::createFromDocument — Create a new command cursor from an existing command response document

Descrierea

public static MongoCommandCursor MongoCommandCursor::createFromDocument ( MongoClient $connection , string $hash , array $document )

Use this method if you have a raw command result with cursor information in it. Note that cursors created with this method cannot be iterated multiple times, as they will lack the original command necessary for re-execution.

Parametri

connection

Database connection.

hash

The connection hash, as obtained through the third by-reference argument to MongoDB::command().

document

Document with cursor information in it. This document needs to contain the id, ns and firstBatch fields. Such a document is obtained by calling the MongoDB::command() with appropriate arguments to return a cursor, and not just an inline result. See the example below.

Valorile întoarse

Returns the new cursor.

Exemple

Example #1 MongoCommandCursor::createFromDocument()

<?php
$m = new MongoClient;
$d = $m->demo;

// Define the aggregation pipeline
$pipeline = [
    [ '$group' => [
        '_id' => '$country_code',
        'timezones' => [ '$addToSet' => '$timezone' ]
    ] ],
    [ '$sort' => [ '_id' => 1 ] ],
];

// Execute the command. The "cursor" option instructs the server to return
// cursor information in the response instead of inline results.
$r = $d->command(
    [
        'aggregate' => 'cities',
        'pipeline' => $pipeline,
        'cursor' => [ 'batchSize' => 1 ],
    ],
    null,
    $hash
);

// Show result and hash
var_dump( $r, $hash );

// Construct the command cursor
$cursor = MongoCommandCursor::createFromDocument( $m, $hash, $r );
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  ["cursor"]=>
  array(3) {
    ["id"]=>
    object(MongoInt64)#5 (1) {
      ["value"]=>
      string(12) "392143983421"
    }
    ["ns"]=>
    string(11) "demo.cities"
    ["firstBatch"]=>
    array(1) {
      [0]=>
      array(2) {
        ["_id"]=>
        string(2) "AD"
        ["timezones"]=>
        array(1) {
          [0]=>
          string(14) "Europe/Andorra"
        }
      }
    }
  }
  ["ok"]=>
  float(1)
}
string(25) "localhost:27017;-;.;17617"

As you can see, the returned cursor information has the id, ns and firstBatch fields.

A se vedea ?i

  • MongoCommandCursor::__construct() - Create a new command cursor
MongoCommandCursor::__construct
MongoCommandCursor::current
MongoCommandCursor


Returns the current element

MongoCommandCursor::createFromDocument
MongoCommandCursor::dead
MongoCommandCursor
PHP Manual

MongoCommandCursor::current

(PECL mongo >=1.5.0)

MongoCommandCursor::current — Returns the current element

Descrierea

public array MongoCommandCursor::current ( void )

This returns NULL until MongoCommandCursor::rewind() is called.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current result document as an associative array. NULL will be returned if there is no result.

A se vedea ?i

  • Iterator::current() - Return the current element
MongoCommandCursor::createFromDocument
MongoCommandCursor::dead
MongoCommandCursor


Checks if there are results that have not yet been sent from the database

MongoCommandCursor::current
MongoCommandCursor::getReadPreference
MongoCommandCursor
PHP Manual

MongoCommandCursor::dead

(PECL mongo >=1.5.0)

MongoCommandCursor::dead — Checks if there are results that have not yet been sent from the database

Descrierea

public bool MongoCommandCursor::dead ( void )

This method checks whether the MongoCommandCursor cursor has been exhausted and the database has no more results to send to the client. A cursor being "dead" does not necessarily mean that there are no more results available for iteration.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if there are more results that have not yet been sent to the client, and FALSE otherwise.

A se vedea ?i

  • MongoCursorInterface::dead() - Checks if there are results that have not yet been sent from the database
MongoCommandCursor::current
MongoCommandCursor::getReadPreference
MongoCommandCursor


Get the read preference for this command

MongoCommandCursor::dead
MongoCommandCursor::info
MongoCommandCursor
PHP Manual

MongoCommandCursor::getReadPreference

(PECL mongo >=1.6.0)

MongoCommandCursor::getReadPreference — Get the read preference for this command

Descrierea

public array MongoCommandCursor::getReadPreference ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Aceasta func?ie întoarce un tablou ce descrie preferin?a de citire. Tabloul con?ine tipul (type) valorilor pentru ?irul cu modul preferin?ei de citire (ce corespunde constantelor MongoClient), ?i tagsets con?inând lista tuturor criteriilor setului de etichete. Daca nu a fost specificat nici un set de etichete, tagsets nu va fi prezent în tablou.

Exemple

Example #1 MongoCommandCursor::getReadPreference() return value example

<?php

$m = new MongoClient('mongodb://rs1.example.com:27017', array('replicaSet' => 'myReplSetName'));
$collection = $m->selectCollection('test', 'people');

// If a MongoCommandCursor is constructed directly, it will inherit the read
// preference of the MongoClient instance passed to its constructor; however,
// MongoCollection::aggregateCursor() will have the MongoCommandCursor inherit
// the collection's read preference.
$collection->setReadPreference(MongoClient::RP_SECONDARY);

$cursor = $collection->aggregateCursor( [
    [ '$group' => [ '_id' => '$name', 'points' => [ '$sum' => '$points' ] ] ],
    [ '$sort' => [ 'points' => -1 ] ],
] );

var_dump($cursor->getReadPreference());

?>

Exemplul de mai sus va afi?a:

array(1) {
  ["type"]=>
  string(9) "secondary"
}

A se vedea ?i

  • The read preferences documentation.
  • MongoCommandCursor::setReadPreference() - Set the read preference for this command
  • MongoCursorInterface::getReadPreference() - Get the read preference for this query
MongoCommandCursor::dead
MongoCommandCursor::info
MongoCommandCursor


Gets information about the cursor's creation and iteration

MongoCommandCursor::getReadPreference
MongoCommandCursor::key
MongoCommandCursor
PHP Manual

MongoCommandCursor::info

(PECL mongo >=1.5.0)

MongoCommandCursor::info — Gets information about the cursor's creation and iteration

Descrierea

public array MongoCommandCursor::info ( void )

This can be called before or after the cursor has started iterating.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the namespace, batch size, limit, skip, flags, query, and projected fields for this cursor. If the cursor has started iterating, additional information about iteration and the connection will be included.

Exemple

Example #1 MongoCommandCursor::info() example

<?php
$m = new MongoClient();

$cursor = new MongoCommandCursor(
    $m, // MongoClient object
    'demo.cities', // namespace
    [
        'aggregate' => 'cities',
        'pipeline' => [ [ '$match' => [ '_id' => [ '$exists' => true ] ] ] ],
        'cursor' => [ 'batchSize' => 1 ],
    ]
);

echo "Before iteration started:\n";
var_dump($cursor->info());

echo "\nAfter iteration started:\n";
$cursor->rewind();
var_dump($cursor->info());

?>

Exemplul de mai sus va afi?a ceva similar cu:

Before iteration started:
array(8) {
  ["ns"]=>
  string(11) "demo.cities"
  ["limit"]=>
  int(0)
  ["batchSize"]=>
  int(0)
  ["skip"]=>
  int(0)
  ["flags"]=>
  int(0)
  ["query"]=>
  array(3) {
    ["aggregate"]=>
    string(6) "cities"
    ["pipeline"]=>
    array(1) {
      [0]=>
      array(1) {
        ["$match"]=>
        array(1) {
          ["_id"]=>
          array(1) {
            ["$exists"]=>
            bool(true)
          }
        }
      }
    }
    ["cursor"]=>
    array(1) {
      ["batchSize"]=>
      int(1)
    }
  }
  ["fields"]=>
  NULL
  ["started_iterating"]=>
  bool(false)
}

After iteration started:
array(17) {
  ["ns"]=>
  string(11) "demo.cities"
  ["limit"]=>
  int(0)
  ["batchSize"]=>
  int(0)
  ["skip"]=>
  int(0)
  ["flags"]=>
  int(0)
  ["query"]=>
  array(3) {
    ["aggregate"]=>
    string(6) "cities"
    ["pipeline"]=>
    array(1) {
      [0]=>
      array(1) {
        ["$match"]=>
        array(1) {
          ["_id"]=>
          array(1) {
            ["$exists"]=>
            bool(true)
          }
        }
      }
    }
    ["cursor"]=>
    array(1) {
      ["batchSize"]=>
      int(1)
    }
  }
  ["fields"]=>
  NULL
  ["started_iterating"]=>
  bool(true)
  ["id"]=>
  int(185840310129)
  ["at"]=>
  int(0)
  ["numReturned"]=>
  int(0)
  ["server"]=>
  string(25) "localhost:27017;-;.;23991"
  ["host"]=>
  string(9) "localhost"
  ["port"]=>
  int(27017)
  ["connection_type_desc"]=>
  string(10) "STANDALONE"
  ["firstBatchAt"]=>
  int(0)
  ["firstBatchNumReturned"]=>
  int(1)
}

A se vedea ?i

  • MongoCursorInterface::info() - Gets information about the cursor's creation and iteration
MongoCommandCursor::getReadPreference
MongoCommandCursor::key
MongoCommandCursor


Returns the current result's index within the result set

MongoCommandCursor::info
MongoCommandCursor::next
MongoCommandCursor
PHP Manual

MongoCommandCursor::key

(PECL mongo >=1.5.0)

MongoCommandCursor::key — Returns the current result's index within the result set

Descrierea

public int MongoCommandCursor::key ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current result's index within the result set.

A se vedea ?i

  • Iterator::key() - Return the key of the current element
MongoCommandCursor::info
MongoCommandCursor::next
MongoCommandCursor


Advances the cursor to the next result

MongoCommandCursor::key
MongoCommandCursor::rewind
MongoCommandCursor
PHP Manual

MongoCommandCursor::next

(PECL mongo >=1.5.0)

MongoCommandCursor::next — Advances the cursor to the next result

Descrierea

public void MongoCommandCursor::next ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

NULL.

Erori/Excep?ii

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

A se vedea ?i

  • Iterator::next() - Move forward to next element
MongoCommandCursor::key
MongoCommandCursor::rewind
MongoCommandCursor


Executes the command and resets the cursor to the start of the result set

MongoCommandCursor::next
MongoCommandCursor::setReadPreference
MongoCommandCursor
PHP Manual

MongoCommandCursor::rewind

(PECL mongo >=1.5.0)

MongoCommandCursor::rewind — Executes the command and resets the cursor to the start of the result set

Descrierea

public array MongoCommandCursor::rewind ( void )

If the cursor has already started iteration, the command will be re-executed.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The raw server result document.

Erori/Excep?ii

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

Throws MongoCursorException if the cursor was created with MongoCommandCursor::createFromDocument() and has already started iteration. Such cursors cannot be iterated multiple times, as they lack the original command necessary for re-execution.

Exemple

Example #1 MongoCommandCursor::rewind()

<?php
$rawResult = $commandCursor->rewind();

// Command cursor is now reset to the start of the result set

var_dump($rawResult);
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  ["cursor"]=>
  array(3) {
    ["id"]=>
    object(MongoInt64)#5 (1) {
      ["value"]=>
      string(12) "310050110216"
    }
    ["ns"]=>
    string(9) "demo.test"
    ["firstBatch"]=>
    array(1) {
      [0]=>
      array(2) {
        ["_id"]=>
        object(MongoId)#6 (1) {
          ["$id"]=>
          string(24) "52f5691544670a8077b0dc51"
        }
        ["value"]=>
        string(2) "42"
      }
    }
  }
  ["ok"]=>
  float(1)
}

A se vedea ?i

  • Iterator::rewind() - Rewind the Iterator to the first element
MongoCommandCursor::next
MongoCommandCursor::setReadPreference
MongoCommandCursor


Set the read preference for this command

MongoCommandCursor::rewind
MongoCommandCursor::timeout
MongoCommandCursor
PHP Manual

MongoCommandCursor::setReadPreference

(PECL mongo >=1.6.0)

MongoCommandCursor::setReadPreference — Set the read preference for this command

Descrierea

public MongoCommandCursor MongoCommandCursor::setReadPreference ( string $read_preference [, array $tags ] )

Parametri

read_preference

Modul preferin?ei de citire:
MongoClient::RP_PRIMARY,
MongoClient::RP_PRIMARY_PREFERRED,
MongoClient::RP_SECONDARY,
MongoClient::RP_SECONDARY_PREFERRED sau
MongoClient::RP_NEAREST.

tags

Un tablou din zero sau mai multe seturi de etichete, unde fiecare set de etichete este la rândul sau un tablou de criterii utilizate pentru a potrivi etichetele pe membrii setului de replicare.

Valorile întoarse

Returns this cursor.

Erori/Excep?ii

Emite un E_WARNING daca careva parametru nu e valid, sau daca unul sau mai multe seturi de etichete sunt furnizate cu modul preferin?ei de citire MongoClient::RP_PRIMARY.

Exemple

Example #1 MongoCommandCursor::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient('mongodb://rs1.example.com:27017', array('replicaSet' => 'myReplSetName'));
$collection = $m->selectCollection('test', 'people');

$cursor = $collection->aggregateCursor( [
    [ '$group' => [ '_id' => '$name', 'points' => [ '$sum' => '$points' ] ] ],
    [ '$sort' => [ 'points' => -1 ] ],
] );

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$cursor->setReadPreference(MongoClient::RP_NEAREST, [
    [ 'dc' => 'east', 'use' => 'reporting' ],
    [ 'dc' => 'west' ],
] );

foreach ($cursor as $person) {
    // ...
}

// If the read preference is changed, it will be used the next time the cursor
// is rewound and the command is re-executed.
$cursor->setReadPreference(MongoClient::RP_PRIMARY);

foreach ($cursor as $person) {
    // ...
}

?>

A se vedea ?i

  • The read preferences documentation.
  • MongoCommandCursor::getReadPreference() - Get the read preference for this command
  • MongoCursorInterface::setReadPreference() - Set the read preference for this query
MongoCommandCursor::rewind
MongoCommandCursor::timeout
MongoCommandCursor


Sets a client-side timeout for this command

MongoCommandCursor::setReadPreference
MongoCommandCursor::valid
MongoCommandCursor
PHP Manual

MongoCommandCursor::timeout

(PECL mongo >=1.6.0)

MongoCommandCursor::timeout — Sets a client-side timeout for this command

Descrierea

public MongoCommandCursor MongoCommandCursor::timeout ( int $ms )

A timeout can be set at any time and will affect subsequent data retrieval associated with this cursor, including fetching more results from the database.

Parametri

ms

The number of milliseconds for the cursor to wait for a response. Use -1 to wait forever. By default, the cursor will wait 30000 milliseconds (30 seconds).

Valorile întoarse

This cursor.

Erori/Excep?ii

Causes methods that fetch results to throw a MongoCursorTimeoutException if the data fetch takes longer than the specified number of milliseconds.

Exemple

Example #1 MongoCommandCursor::timeout() example

In the following example, the driver will wait for 60 seconds for the first response from the aggregate command. It will also wait for 60 seconds each time the server needs to be polled for more information.

<?php

$m = new MongoClient;
$col = $m->database->collection;

$pipeline = [ … ];

$cursor = $col->aggregateCursor( $pipeline );
$cursor->timeout( 60000 ); // for 60 seconds

foreach ( $cursor as $result ) {
   …
}

?>

Note

Avertizare

This does not cause the MongoDB server to cancel long-running operations; it only instructs the driver to stop waiting for a response and throw a MongoCursorTimeoutException after a set time. If you need to specify a server-side timeout for a command, considering passing the maxTimeMS option to MongoCollection::aggregateCursor().

A se vedea ?i

  • MongoCollection::aggregateCursor() - Execute an aggregation pipeline command and retrieve results through a cursor
  • MongoCursorInterface::timeout() - Sets a client-side timeout for this query
  • The socketTimeoutMS option for MongoClient::__construct()
MongoCommandCursor::setReadPreference
MongoCommandCursor::valid
MongoCommandCursor


Checks if the cursor is reading a valid result.

MongoCommandCursor::timeout
Types
MongoCommandCursor
PHP Manual

MongoCommandCursor::valid

(PECL mongo >=1.5.0)

MongoCommandCursor::valid — Checks if the cursor is reading a valid result.

Descrierea

public bool MongoCommandCursor::valid ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the current result is not null, and FALSE otherwise.

A se vedea ?i

  • Iterator::valid() - Checks if current position is valid
MongoCommandCursor::timeout
Types
MongoCommandCursor


Types

Cuprins

  • 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.

MongoCommandCursor::valid
MongoId
Mongo


The MongoId class

(PECL mongo >=0.8.0)

Avertizare

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta clasa includ:

  • MongoDB\BSON\ObjectID

Introducere

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 (e.g. 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 naturally have one. Autoincrementing does not work well with a sharded database, as it is difficult to determine the next number in the sequence. 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 hexadecimal 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}

Sinopsisul clasei

MongoId {
public string $$id = NULL ;
/* Metode */
public __construct ([ string|MongoId $id = NULL ] )
public static string getHostname ( void )
public int getInc ( void )
public int getPID ( void )
public int getTimestamp ( void )
public static bool isValid ( mixed $value )
public static MongoId __set_state ( array $props )
public string __toString ( void )
}

Fields

$id
This field contains the string representation of this object.

Nota: The property name begins with a $ character. It may be accessed using complex variable parsed syntax (e.g. $mongoId->{'$id'}).

A se vedea ?i

MongoDB core docs on » ObjectIds.

Cuprins

  • 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
  • MongoId::getTimestamp — Gets the number of seconds since the epoch that this id was created
  • MongoId::isValid — Check if a value is a valid ObjectId
  • 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

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\BSON\ObjectID::__construct()

Descrierea

public MongoId::__construct ([ string|MongoId $id = NULL ] )

Parametri

id

A string (must be 24 hexadecimal characters) or a MongoId instance.

Valorile întoarse

Returns a new id.

Istoricul schimbarilor

Versiune | Descriere
1.4.0 | An exception is thrown when passed invalid string

Exemple

Example #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";

  ?>

Exemplul de mai sus va afi?a ceva similar cu:

49a7011a05c677b9a916612a
49a702d5450046d3d515d10d

Example #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);
  ?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)

A se vedea ?i

  • MongoId::__toString() - Returns a hexidecimal representation of this id
  • MongoId::isvalid() - Check if a value is a valid ObjectId

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

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

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();
}

?>

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public int MongoId::getInc ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the incremented value used to create this MongoId.

MongoId::getHostname
MongoId::getPID
MongoId


Gets the process ID

MongoId::getInc
MongoId::getTimestamp
MongoId
PHP Manual

MongoId::getPID

(PECL mongo >= 1.0.11)

MongoId::getPID — Gets the process ID

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public int MongoId::getPID ( void )

Extracts the pid from the Mongo ID

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the PID of the MongoId.

MongoId::getInc
MongoId::getTimestamp
MongoId


Gets the number of seconds since the epoch that this id was created

MongoId::getPID
MongoId::isValid
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

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public int MongoId::getTimestamp ( void )

This returns the same thing as running time() when the id is created.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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::isValid
MongoId


Check if a value is a valid ObjectId

MongoId::getTimestamp
MongoId::__set_state
MongoId
PHP Manual

MongoId::isValid

(PECL mongo >= 1.5.0)

MongoId::isValid — Check if a value is a valid ObjectId

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public static bool MongoId::isValid ( mixed $value )

This method may be used to check a variable before passing it as an argument to MongoId::__construct().

Parametri

value

The value to check for validity.

Valorile întoarse

Returns TRUE if value is a MongoId instance or a string consisting of exactly 24 hexadecimal characters; otherwise, FALSE is returned.

MongoId::getTimestamp
MongoId::__set_state
MongoId


Create a dummy MongoId

MongoId::isValid
MongoId::__toString
MongoId
PHP Manual

MongoId::__set_state

(PECL mongo >= 1.0.8)

MongoId::__set_state — Create a dummy MongoId

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

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");
}

?>

Parametri

props

Theoretically, an array of properties used to create the new id. However, as MongoId instances have no properties, this is not used.

Valorile întoarse

A new id with the value "000000000000000000000000".

MongoId::isValid
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

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\BSON\ObjectID::__toString()

Descrierea

public string MongoId::__toString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

This id.

Exemple

Example #1 MongoId::__toString() example

<?php

$m = new MongoClient();
$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";

?>

Exemplul de mai sus va afi?a ceva similar cu:

49a7011a05c677b9a916612a
49a702d5450046d3d515d10d
MongoId::__set_state
MongoCode
MongoId


The MongoCode class

(PECL mongo >=0.8.3)

Avertizare

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta clasa includ:

  • MongoDB\BSON\JavaScript

Introducere

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.

Sinopsisul clasei

MongoCode {
/* Metode */
public __construct ( string $code [, array $scope = array() ] )
public string __toString ( void )
}

Cuprins

  • 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

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\BSON\JavaScript::__construct()

Descrierea

public MongoCode::__construct ( string $code [, array $scope = array() ] )

Parametri

code

A string of code.

scope

The scope to use for the code.

Valorile întoarse

Returns a new code object.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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; }"
}

Example #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

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei metode în noua extensie.

Descrierea

public string MongoCode::__toString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

This code, the scope is not returned.

Exemple

Example #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";

?>

Exemplul de mai sus va afi?a ceva similar cu:

return x;
function() { for(i=0;i<10;i++) { db.foo.update({x:i}, {x:i+1}); } }
MongoCode::__construct
MongoDate
MongoCode


The MongoDate class

(PECL mongo >=0.8.1)

Avertizare

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta clasa includ:

  • MongoDB\BSON\UTCDateTime

Introducere

Represent date objects for the database. This class should be used to save dates to the database and to query for dates. For example:

Example #1 Storing dates with MongoDate

<?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.

Sinopsisul clasei

MongoDate {
/* Fields */
public int $sec ;
public int $usec ;
/* Metode */
public __construct ([ int $sec = time() [, int $usec = 0 ]] )
public DateTime toDateTime ( void )
public string __toString ( void )
}

Cuprins

  • MongoDate::__construct — Creates a new date.
  • MongoDate::toDateTime — Returns a DateTime object representing this date
  • MongoDate::__toString — Returns a string representation of this date
MongoCode::__toString
MongoDate::__construct
Types


Creates a new date.

MongoDate
MongoDate::toDateTime
MongoDate
PHP Manual

MongoDate::__construct

(PECL mongo >= 0.8.1)

MongoDate::__construct — Creates a new date.

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\BSON\UTCDateTime::__construct()

Descrierea

public MongoDate::__construct ([ int $sec = time() [, int $usec = 0 ]] )

Creates a new date. If no parameters are given, the current time is used.

Parametri

sec

Number of seconds since the epoch (i.e. 1 Jan 1970 00:00:00.000 UTC).

usec

Microseconds. Please be aware though that MongoDB's resolution is milliseconds and not microseconds, which means this value will be truncated to millisecond resolution.

Valorile întoarse

Returns this new date.

Exemple

Example #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";

?>

Exemplul de mai sus va afi?a ceva similar cu:

0.23660600 1235685067
0.00000000 1234567890
0.00000000 1241150401

A se vedea ?i

  • MongoDate::__toString() - Returns a string representation of this date

MongoDate
MongoDate::toDateTime
MongoDate


Returns a DateTime object representing this date

MongoDate::__construct
MongoDate::__toString
MongoDate
PHP Manual

MongoDate::toDateTime

(PECL mongo >= 1.6.0; PHP > 5.3.4)

MongoDate::toDateTime — Returns a DateTime object representing this date

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\BSON\UTCDateTime::toDateTime()

Descrierea

public DateTime MongoDate::toDateTime ( void )

Returns a DateTime object representation of this date.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

This date as a DateTime object.

Exemple

Example #1 MongoDate::toDateTime() example

This example demonstrates creating a DateTime object from a MongoDate object.

<?php
$d = new MongoDate(strtotime("2014-11-18 11:01:25"));
var_dump( $d->toDateTime() );
?>

Exemplul de mai sus va afi?a ceva similar cu:

class DateTime#2 (3) {
  public $date =>
  string(26) "2014-11-18 11:01:25.000000"
  public $timezone_type =>
  int(1)
  public $timezone =>
  string(6) "+00:00"
}
MongoDate::__construct
MongoDate::__toString
MongoDate


Returns a string representation of this date

MongoDate::toDateTime
MongoRegex
MongoDate
PHP Manual

MongoDate::__toString

(PECL mongo >= 0.8.1)

MongoDate::__toString — Returns a string representation of this date

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\BSON\UTCDateTime::__toString()

Descrierea

public string MongoDate::__toString ( void )

Returns a string representation of this date, similar to the representation returned by microtime().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

This date.

MongoDate::toDateTime
MongoRegex
MongoDate


The MongoRegex class

(PECL mongo >=0.8.1)

Avertizare

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta clasa includ:

  • MongoDB\BSON\Regex

Introducere

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.

Regular expressions consist of four parts. First a / as starting delimiter, then the pattern, another / and finally a string containing flags.

Example #1 Regular expression pattern

/pattern/flags

MongoDB 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

Sinopsisul clasei

MongoRegex {
/* Fields */
public string $regex ;
public string $flags ;
/* Metode */
public __construct ( string $regex )
public string __toString ( void )
}

Cuprins

  • 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

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\BSON\Regex::__construct()

Descrierea

public MongoRegex::__construct ( string $regex )

Creates a new regular expression.

Parametri

regex

Regular expression string of the form /expr/flags.

Valorile întoarse

Returns a new regular expression.

Exemple

Example #1 MongoRegex::__construct() example

This example uses a regular expression to query for all documents with a username field starting (^) with an l and a vowel ([aeiouy]), case-insensitive (/i).

<?php
$luke_search = new MongoRegex("/^l[aeiouy]/i");
$cursor = $collection->find(array("username" => $luke_search));
?>

A se vedea ?i

  • 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

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\BSON\Regex::__toString()

Descrierea

public string MongoRegex::__toString ( void )

Returns a string representation of this regular expression.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

This regular expression in the form "/expr/flags".

Exemple

Example #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";

?>

Exemplul de mai sus va afi?a ceva similar cu:

[a-fA-F0-9]{16}
g
/[a-fA-F0-9]{16}/g

MongoRegex::__construct
MongoBinData
MongoRegex


The MongoBinData class

(PECL mongo >= 0.8.1)

Avertizare

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta clasa includ:

  • MongoDB\BSON\Binary

Introducere

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 16MB. For data that is larger than this (movies, music, Henry Kissinger's autobiography), use MongoGridFS. For data that is smaller than 16MB, you may find it easier to embed it within 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"), MongoBinData::GENERIC),
);

$users->save($profile);

?>

This class contains a type field, which currently gives no additional functionality in the PHP driver or the database. There are seven predefined types, which are defined as class constants below. For backwards compatibility, the PHP driver uses MongoBinData::BYTE_ARRAY as the default; however, this may change to MongoBinData::GENERIC in the future. Users are encouraged to specify a type in MongoBinData::__construct().

Sinopsisul clasei

MongoBinData {
/* Constante */
const int GENERIC = 0 ;
const int FUNC = 1 ;
const int BYTE_ARRAY = 2 ;
const int UUID = 3 ;
const int UUID_RFC4122 = 4 ;
const int MD5 = 5 ;
const int CUSTOM = 128 ;
/* Fields */
public string $bin ;
public int $type = 2 ;
/* Metode */
public __construct ( string $data [, int $type = 0 ] )
public string __toString ( void )
}

Constante predefinite

Binary Data Types

MongoBinData::GENERIC
0x00
Generic binary data.
MongoBinData::FUNC
0x01
Function.
MongoBinData::BYTE_ARRAY
0x02
Generic binary data (deprecated in favor of MongoBinData::GENERIC).
MongoBinData::UUID
0x03
Universally unique identifier (deprecated in favor of MongoBinData::UUID_RFC4122).
MongoBinData::UUID_RFC4122
0x04
Universally unique identifier (according to » RFC 4122).
MongoBinData::MD5
0x05
MD5.
MongoBinData::CUSTOM
0x80
User-defined type.

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | Added MongoBinData::GENERIC and MongoBinData::UUID_RFC4122 constants.

Cuprins

  • 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.

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\BSON\Binary::__construct()

Descrierea

public MongoBinData::__construct ( string $data [, int $type = 0 ] )

Creates a new binary data object.

There are seven types of binary data currently recognized by the BSON spec, which are defined as class constants. For backwards compatibility, the PHP driver uses MongoBinData::BYTE_ARRAY as the default; however, this may change to MongoBinData::GENERIC in the future. Users are encouraged to specify a type instead of relying on the default.

Parametri

data

Binary data.

type

Data type.

Valorile întoarse

Returns a new binary data object.

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | The default changed from 2 (MongoBinData::BYTE_ARRAY) to 0 (MongoBinData::GENERIC).
1.2.11 | Emits E_DEPRECATED when the second argument is not used. The default value for type may change in the near future.

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.

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\BSON\Binary::getData()

Descrierea

public string MongoBinData::__toString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the string "<Mongo Binary Data>". To access the contents of a MongoBinData, use the bin field.

MongoBinData::__construct
MongoInt32
MongoBinData


The MongoInt32 class

(PECL mongo >=1.0.9)

Avertizare

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei clase în noua extensie.

Instead, the new extension chooses the appropriate database type depending on the integer's value.

Introducere

The class can be used to save 32-bit integers to the database on a 64-bit system.

Sinopsisul clasei

MongoInt32 {
/* Fields */
public string $value ;
/* Metode */
public __construct ( string $value )
public string __toString ( void )
}

Fields

value
This is the string value of the 32-bit number. For instance, 123's value would be "123".

Cuprins

  • 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.

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei clase în noua extensie.

Instead, the new extension chooses the appropriate database type depending on the integer's value.

Descrierea

public MongoInt32::__construct ( string $value )

Creates a new 32-bit number with the given value.

Parametri

value

A number.

Valorile întoarse

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.

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei clase în noua extensie.

Instead, the new extension chooses the appropriate database type depending on the integer's value.

Descrierea

public string MongoInt32::__toString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the string representation of this integer.

MongoInt32::__construct
MongoInt64
MongoInt32


The MongoInt64 class

(PECL mongo >=1.0.9)

Avertizare

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei clase în noua extensie.

Instead, the new extension chooses the appropriate database type depending on the integer's value.

Introducere

The class can be used to save 64-bit integers to the database on a 32-bit system.

Sinopsisul clasei

MongoInt64 {
/* Fields */
public string $value ;
/* Metode */
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".

Cuprins

  • 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.

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei clase în noua extensie.

Instead, the new extension chooses the appropriate database type depending on the integer's value.

Descrierea

public MongoInt64::__construct ( string $value )

Creates a new 64-bit number with the given value.

Parametri

value

A number.

Valorile întoarse

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.

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei clase în noua extensie.

Instead, the new extension chooses the appropriate database type depending on the integer's value.

Descrierea

public string MongoInt64::__toString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the string representation of this integer.

MongoInt64::__construct
MongoDBRef
MongoInt64


The MongoDBRef class

(PECL mongo >=0.9.0)

Avertizare

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei clase în noua extensie.

The concept of database references, and hence this class, has been deprecated in the database.

Introducere

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:

Example #1 Linking documents

<?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:

Example #2 Creating MongoDBRef links

<?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.

Sinopsisul clasei

MongoDBRef {
/* Metode */
public static array create ( string $collection , mixed $id [, string $database ] )
public static array get ( MongoDB $db , array $ref )
public static bool isRef ( mixed $ref )
}

A se vedea ?i

MongoDB core docs on » databases references.

Cuprins

  • 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

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei clase în noua extensie.

The concept of database references, and hence this class, has been deprecated.

Descrierea

public static array MongoDBRef::create ( string $collection , mixed $id [, string $database ] )

If no database is given, the current database is used.

Parametri

collection

Collection name (without the database name).

id

The _id field of the object to which to link.

database

Database name.

Valorile întoarse

Returns the reference.

Exemple

Example #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);
?>

A se vedea ?i

  • 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

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei clase în noua extensie.

The concept of database references, and hence this class, has been deprecated.

Descrierea

public static array MongoDBRef::get ( MongoDB $db , array $ref )

Parametri

db

Database to use.

ref

Reference to fetch.

Valorile întoarse

Returns the document to which the reference refers or NULL if the document does not exist (the reference is broken).

Exemple

Example #1 MongoCollection::createDBRef() example

<?php

// get $person out of the db
$person = $people->findOne();

// dereference the address
$address = MongoDBRef::get($people->db, $person['address']);

?>

A se vedea ?i

  • 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

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Nu exista un echivalent al acestei clase în noua extensie.

The concept of database references, and hence this class, has been deprecated.

Descrierea

public static bool MongoDBRef::isRef ( mixed $ref )

This method does 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).

Parametri

ref

Array or object to check.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

MongoDBRef::get
MongoMinKey
MongoDBRef


The MongoMinKey class

(PECL mongo >= 1.0.2)

Avertizare

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta clasa includ:

  • MongoDB\BSON\MinKey

Introducere

MongoMinKey is an special type used by the database that compares less than all other possible BSON values. 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" value that can be represented in the database.

Nota: MongoMinKey is used internally by MongoDB for indexing and sharding. There is generally no reason to use this class in an application.

Sinopsisul clasei

MongoMinKey {
}

Using MongoMinKey as a value

<?php

$collection->insert(array("task" => "lunch", "doBy" => new MongoMinKey));
$collection->insert(array("task" => "staff meeting", "doBy" => new MongoDate(strtotime("+4 days"))));

$cursor = $collection->find()->sort(array("doBy" => 1));

?>

The cursor will return the lunch document followed by 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 their "doBy" field).

A se vedea ?i

  • MongoMaxKey
MongoDBRef::isRef
MongoMaxKey
Types


The MongoMaxKey class

(PECL mongo >= 1.0.2)

Avertizare

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta clasa includ:

  • MongoDB\BSON\MaxKey

Introducere

MongoMaxKey is an special type used by the database that compares greater than all other possible BSON values. 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 "greatest" value that can be represented in the database.

Nota: MongoMaxKey is used internally by MongoDB for indexing and sharding. There is generally no reason to use this class in an application.

Sinopsisul clasei

MongoMaxKey {
}

Using MongoMaxKey as a value

<?php

$collection->insert(array("task" => "dishes", "doBy" => new MongoMaxKey));
$collection->insert(array("task" => "staff meeting", "doBy" => new MongoDate(strtotime("+4 days"))));

$cursor = $collection->find()->sort(array("doBy" => 1));

?>

The cursor will return the staff meeting document followed by 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 their "doBy" field).

A se vedea ?i

  • MongoMinKey
MongoMinKey
MongoTimestamp
Types


The MongoTimestamp class

(PECL mongo >=1.0.1)

Avertizare

Extensia care define?te aceasta clasa este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta clasa includ:

  • MongoDB\BSON\Timestamp

Introducere

MongoTimestamp is an internal type used by MongoDB for replication and sharding. It consists of a 4-byte timestamp (i.e. seconds since the epoch) and a 4-byte increment. This type is not intended for storing time or date values (e.g. a "createdAt" field on a document).

Nota: Unless you are writing an application that interacts with MongoDB's replication oplog or sharding internals: stop, go directly to MongoDate, do not pass go, and do not collect 200 dollars. This is not the class you are looking for.

Sinopsisul clasei

MongoTimestamp {
/* Fields */
public int $sec = 0 ;
public int $inc = 0 ;
/* Metode */
public __construct ([ int $sec = time() [, int $inc ]] )
public string __toString ( void )
}

Cuprins

  • 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.

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\BSON\Timestamp::__construct()

Descrierea

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).

Parametri

sec

Number of seconds since the epoch (i.e. 1 Jan 1970 00:00:00.000 UTC).

inc

Increment.

Valorile întoarse

Returns this new timestamp.

A se vedea ?i

  • MongoTimestamp::__toString() - Returns a string representation of this timestamp

MongoTimestamp
MongoTimestamp::__toString
MongoTimestamp


Returns a string representation of this timestamp

MongoTimestamp::__construct
Clase GridFS
MongoTimestamp
PHP Manual

MongoTimestamp::__toString

(PECL mongo >= 1.0.1)

MongoTimestamp::__toString — Returns a string representation of this timestamp

Extensia care define?te aceasta metoda este învechita. În loc, trtebuie utilizata extensia MongoDB. Variante alternative pentru aceasta metoda includ:

  • MongoDB\BSON\Timestamp::__toString()

Descrierea

public string MongoTimestamp::__toString ( void )

Returns the "sec" field of this timestamp.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The seconds since epoch represented by this timestamp.

MongoTimestamp::__construct
Clase GridFS
MongoTimestamp


Clase GridFS

Cuprins

  • MongoGridFS
  • MongoGridFSFile
  • MongoGridFSCursor
MongoTimestamp::__toString
MongoGridFS
Mongo


The MongoGridFS class

(PECL mongo >=0.9.0)

Introducere

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 unwieldy example.

Inter-Language Compatibility

You should be able to use any files created by MongoGridFS with any other drivers, and vice versa. 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.

Sinopsisul clasei

extends MongoCollection {
/* Fields */
public MongoCollection $chunks = NULL ;
protected string $filesName = NULL ;
protected string $chunksName = NULL ;
/* Metode */
public __construct ( MongoDB $db [, string $prefix = "fs" [, mixed $chunks = "fs" ]] )
public bool|array 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 $metadata = array() [, array $options = array() ]] )
public bool|array remove ([ array $criteria = array() [, array $options = array() ]] )
public mixed storeBytes ( string $bytes [, array $metadata = array() [, array $options = array() ]] )
public mixed storeFile ( string|resource $filename [, array $metadata = array() [, array $options = array() ]] )
public mixed storeUpload ( string $name [, array $metadata ] )
}

A se vedea ?i

  • MongoDB core docs on » GridFS
  • LightCube Solutions blog post on » saving user uploads
  • LightCube Solutions blog post on » adding metadata to files

Cuprins

  • MongoGridFS::__construct — Creates new file collections
  • MongoGridFS::delete — Remove a file and its chunks 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 — Remove files and their chunks from the database
  • MongoGridFS::storeBytes — Stores a string of bytes in the database
  • MongoGridFS::storeFile — Stores a file in the database
  • MongoGridFS::storeUpload — Stores an uploaded file in the database
Clase GridFS
MongoGridFS::__construct
Clase GridFS


Creates new file collections

MongoGridFS
MongoGridFS::delete
MongoGridFS
PHP Manual

MongoGridFS::__construct

(PECL mongo >=0.9.0)

MongoGridFS::__construct — Creates new file collections

Descrierea

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.

Parametri

db

Database.

files

Optional collection name prefix.

MongoGridFS
MongoGridFS::delete
MongoGridFS


Remove a file and its chunks from the database

MongoGridFS::__construct
MongoGridFS::drop
MongoGridFS
PHP Manual

MongoGridFS::delete

(PECL mongo >=1.0.8)

MongoGridFS::delete — Remove a file and its chunks from the database

Descrierea

public bool|array MongoGridFS::delete ( mixed $id )

Nota:

MongoGridFS::delete() is a convenience method for calling MongoGridFS::remove() with specific criteria and default options parameters.

Parametri

id

_id of the file to remove.

Valorile întoarse

Returns an array containing the status of the removal (with respect to the files collection) if a write concern is applied. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Erori/Excep?ii

Genereaza o excep?ie MongoCursorException daca op?iunea "w" este stabilita ?i înscrierea e?ueaza.

Genereaza o excep?ie MongoCursorTimeoutException daca op?iunea "w" este stabilita la o valoare mai mare decât unu ?i opera?iunea dureaza mai mult de MongoCursor::$timeout milisecunde. Aceasta nu va întrerupe opera?iunea pe server, este un timeout de partea clientului. Opera?iunea din MongoCollection::$wtimeout este în milisecunde.

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

Descrierea

public array MongoGridFS::drop ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

 public MongoGridFSCursor MongoGridFS::find
  ([ array $query = array()
 [, array $fields = array()
]] )

Parametri

query

The query.

fields

Fields to return.

Valorile întoarse

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

Descrierea

 public MongoGridFSFile MongoGridFS::findOne
  ([ mixed $query = array()
 [, mixed $fields = array()
]] )

Parametri

query

The filename or criteria for which to search.

Valorile întoarse

Returns a MongoGridFSFile or NULL.

Exemple

Example #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.

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

public MongoGridFSFile MongoGridFS::get ( mixed $id )

Parametri

id

_id of the file to find.

Valorile întoarse

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

Descrierea

public mixed MongoGridFS::put ( string $filename [, array $metadata = array() [, array $options = array() ]] )

Nota:

MongoGridFS::put() is an alias of MongoGridFS::storeFile().

Parametri

filename

Name of the file to store.

metadata

Other metadata fields to include in the file document.

Nota:

Aceste câmpuri pot sa le rescrie pe cele create automat de catre driver, dupa cum e descris în documenta?ia de baza MongoDB pentru » colec?ia de fi?iere. Ca un exemplu de utilizare practica a acestui comportament ar fi specificarea unor valori specifice pentru chunkSize sau _id pentru fi?ier.

options

An array of options for the insert operations executed against the chunks and files collections. See MongoCollection::insert() for documentation on these these options.

Valorile întoarse

Întoarce valoarea _id a fi?ierului cu documentul salvat. Acesta va fi un MongoId generat, doar daca un _id nu a fost specificat în mod explicit în parametrul metadata.

Erori/Excep?ii

Throws MongoGridFSException if there is an error reading filename or inserting into the chunks or files collections.

A se vedea ?i

  • MongoGridFS::storeBytes() - Stores a string of bytes in the database
  • MongoGridFS::storeFile() - Stores a file in the database
  • MongoGridFS::storeUpload() - Stores an uploaded file in the database
  • MongoDB core docs on » GridFS
MongoGridFS::get
MongoGridFS::remove
MongoGridFS


Remove files and their chunks from the database

MongoGridFS::put
MongoGridFS::storeBytes
MongoGridFS
PHP Manual

MongoGridFS::remove

(PECL mongo >=0.9.0)

MongoGridFS::remove — Remove files and their chunks from the database

Descrierea

 public bool|array MongoGridFS::remove
  ([ array $criteria = array()
 [, array $options = array()
]] )

Parametri

criteria

The filename or criteria for which to search.

options

An array of options for the remove operations executed against the chunks and files collections. See MongoCollection::remove() for documentation on these options.

Valorile întoarse

Returns an array containing the status of the removal (with respect to the files collection) if the "w" option is set. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Erori/Excep?ii

Genereaza o excep?ie MongoCursorException daca op?iunea "w" este stabilita ?i înscrierea e?ueaza.

Genereaza o excep?ie MongoCursorTimeoutException daca op?iunea "w" este stabilita la o valoare mai mare decât unu ?i opera?iunea dureaza mai mult de MongoCursor::$timeout milisecunde. Aceasta nu va întrerupe opera?iunea pe server, este un timeout de partea clientului. Opera?iunea din MongoCollection::$wtimeout este în milisecunde.

MongoGridFS::put
MongoGridFS::storeBytes
MongoGridFS


Stores a string of bytes in the database

MongoGridFS::remove
MongoGridFS::storeFile
MongoGridFS
PHP Manual

MongoGridFS::storeBytes

(PECL mongo >=0.9.2)

MongoGridFS::storeBytes — Stores a string of bytes in the database

Descrierea

public mixed MongoGridFS::storeBytes ( string $bytes [, array $metadata = array() [, array $options = array() ]] )

Parametri

bytes

String of bytes to store.

metadata

Other metadata fields to include in the file document.

Nota:

Aceste câmpuri pot sa le rescrie pe cele create automat de catre driver, dupa cum e descris în documenta?ia de baza MongoDB pentru » colec?ia de fi?iere. Ca un exemplu de utilizare practica a acestui comportament ar fi specificarea unor valori specifice pentru chunkSize sau _id pentru fi?ier.

options

An array of options for the insert operations executed against the chunks and files collections. See MongoCollection::insert() for documentation on these these options.

Valorile întoarse

Întoarce valoarea _id a fi?ierului cu documentul salvat. Acesta va fi un MongoId generat, doar daca un _id nu a fost specificat în mod explicit în parametrul metadata.

Erori/Excep?ii

Throws MongoGridFSException if there is an error inserting into the chunks or files collections.

Exemple

Example #1 MongoGridFS::storeBytes() with additional metadata

<?php
$m = new MongoClient();
$gridfs = $m->selectDB('test')->getGridFS();

$bytes = 'abcdefghijklmnopqrstuvwxyz';
$id = $gridfs->storeBytes($bytes, array('_id' => 'alphabet'));
$gridfsFile = $gridfs->get($id);

var_dump($gridfsFile->file);
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(7) {
  ["_id"]=>
  string(8) "alphabet"
  ["uploadDate"]=>
  object(MongoDate)#7 (0) {
  }
  ["length"]=>
  int(26)
  ["chunkSize"]=>
  int(262144)
  ["md5"]=>
  string(32) "c3fcd3d76192e4007dfb496cca67e13b"
}

A se vedea ?i

  • MongoGridFS::put() - Stores a file in the database
  • MongoGridFS::storeFile() - Stores a file in the database
  • MongoGridFS::storeUpload() - Stores an uploaded file in the database
  • MongoDB core docs on » GridFS
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

Descrierea

public mixed MongoGridFS::storeFile ( string|resource $filename [, array $metadata = array() [, array $options = array() ]] )

Parametri

filename

Name of the file or a readable stream to store.

metadata

Other metadata fields to include in the file document.

Nota:

Aceste câmpuri pot sa le rescrie pe cele create automat de catre driver, dupa cum e descris în documenta?ia de baza MongoDB pentru » colec?ia de fi?iere. Ca un exemplu de utilizare practica a acestui comportament ar fi specificarea unor valori specifice pentru chunkSize sau _id pentru fi?ier.

options

An array of options for the insert operations executed against the chunks and files collections. See MongoCollection::insert() for documentation on these these options.

Valorile întoarse

Întoarce valoarea _id a fi?ierului cu documentul salvat. Acesta va fi un MongoId generat, doar daca un _id nu a fost specificat în mod explicit în parametrul metadata.

Erori/Excep?ii

Throws MongoGridFSException if there is an error reading filename or inserting into the chunks or files collections.

Exemple

Example #1 MongoGridFS::storeFile() with additional metadata

<?php
$m = new MongoClient();
$gridfs = $m->selectDB('test')->getGridFS();

$id = $gridfs->storeFile('example.txt', array('contentType' => 'plain/text'));
$gridfsFile = $gridfs->get($id);

var_dump($gridfsFile->file);
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(7) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["contentType"]=>
  string(10) "plain/text"
  ["filename"]=>
  string(11) "example.txt"
  ["uploadDate"]=>
  object(MongoDate)#7 (0) {
  }
  ["length"]=>
  int(26)
  ["chunkSize"]=>
  int(262144)
  ["md5"]=>
  string(32) "c3fcd3d76192e4007dfb496cca67e13b"
}

A se vedea ?i

  • MongoGridFS::put() - Stores a file in the database
  • MongoGridFS::storeBytes() - Stores a string of bytes in the database
  • MongoGridFS::storeUpload() - Stores an uploaded file in the database
  • MongoDB core docs on » GridFS
MongoGridFS::storeBytes
MongoGridFS::storeUpload
MongoGridFS


Stores an uploaded file in the database

MongoGridFS::storeFile
MongoGridFSFile
MongoGridFS
PHP Manual

MongoGridFS::storeUpload

(PECL mongo >=0.9.0)

MongoGridFS::storeUpload — Stores an uploaded file in the database

Descrierea

public mixed MongoGridFS::storeUpload ( string $name [, array $metadata ] )

Parametri

name

The name of the uploaded file(s) to store. This should correspond to the file field's name attribute in the HTML form.

metadata

Other metadata fields to include in the file document.

Nota:

Aceste câmpuri pot sa le rescrie pe cele create automat de catre driver, dupa cum e descris în documenta?ia de baza MongoDB pentru » colec?ia de fi?iere. Ca un exemplu de utilizare practica a acestui comportament ar fi specificarea unor valori specifice pentru chunkSize sau _id pentru fi?ier.

Nota:

The filename field will be populated with the client's filename (e.g. $_FILES['foo']['name']).

Valorile întoarse

Întoarce valoarea _id a fi?ierului cu documentul salvat. Acesta va fi un MongoId generat, doar daca un _id nu a fost specificat în mod explicit în parametrul metadata.

Nota:

If multiple files are uploaded using the same field name, this method will not return anything; however, the files themselves will still be processed.

Erori/Excep?ii

Throws MongoGridFSException if there is an error reading the uploaded file(s) or inserting into the chunks or files collections.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #1 MongoGridFS::storeUpload() HTML form example

Suppose you have the following HTML form:

<form method="POST" enctype="multipart/form-data">
    <label for="username">Username:</label>
    <input type="text" name="username" id="username" />

    <label for="pic">Please upload a profile picture:</label>
    <input type="file" name="pic" id="pic" />

    <input type="submit" />
</form>

If you wanted to store the uploaded image in MongoDB, you could do the following in the script handling the form submission:

<?php
$m = new MongoClient();
$gridfs = $m->selectDB('test')->getGridFS();

$gridfs->storeUpload('pic', array('username' => $_POST['username']));
?>

A se vedea ?i

  • MongoGridFS::put() - Stores a file in the database
  • MongoGridFS::storeBytes() - Stores a string of bytes in the database
  • MongoGridFS::storeFile() - Stores a file in the database
  • MongoDB core docs on » GridFS
MongoGridFS::storeFile
MongoGridFSFile
MongoGridFS


The MongoGridFSFile class

(PECL mongo >=0.9.0)

Introducere

A database file object.

Sinopsisul clasei

MongoGridFSFile {
/* Fields */
public array $file = NULL ;
protected MongoGridFS $gridfs = NULL ;
/* Metode */
public MongoGridfsFile::__construct ( MongoGridFS $gridfs , array $file )
public string getBytes ( void )
public string getFilename ( void )
public resource getResource ( void )
public int getSize ( void )
public int write ([ string $filename = NULL ] )
}

Cuprins

  • 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
Clase GridFS


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

Descrierea

public MongoGridfsFile::__construct ( MongoGridFS $gridfs , array $file )

Parametri

gridfs

The parent MongoGridFS instance.

file

A file from the database.

Valorile întoarse

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

Descrierea

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!

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string of the bytes in the file.

Exemple

Example #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

Descrierea

public string MongoGridFSFile::getFilename ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(PECL mongo >=1.3.0)

MongoGridFSFile::getResource — Returns a resource that can be used to read the stored file

Descrierea

public resource MongoGridFSFile::getResource ( void )

This method returns a stream resource that can be used with all file functions in PHP that deal with reading files. 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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a resource that can be used to read the file with

Exemple

Example #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

Descrierea

public int MongoGridFSFile::getSize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int MongoGridFSFile::write ([ string $filename = NULL ] )

Parametri

filename

The location to which to write the file. If none is given, the stored filename will be used.

Valorile întoarse

Returns the number of bytes written.

Exemple

Example #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

(PECL mongo >=0.9.0)

Introducere

Cursor for database file results.

Sinopsisul clasei

extends MongoCursor {
/* Fields */
protected MongoGridFS $gridfs = NULL ;
/* Metode */
public __construct ( MongoGridFS $gridfs , resource $connection , string $ns , array $query , array $fields )
public MongoGridFSFile current ( void )
public MongoGridFSFile getNext ( void )
public string key ( void )
}

Cuprins

  • 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
Clase GridFS


Create a new cursor

MongoGridFSCursor
MongoGridFSCursor::current
MongoGridFSCursor
PHP Manual

MongoGridFSCursor::__construct

(PECL mongo >=0.9.0)

MongoGridFSCursor::__construct — Create a new cursor

Descrierea

public MongoGridFSCursor::__construct ( MongoGridFS $gridfs , resource $connection , string $ns , array $query , array $fields )

Parametri

gridfs

Related GridFS collection.

connection

Database connection.

ns

Full name of database and collection.

query

Database query.

fields

Fields to return.

Valorile întoarse

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

Descrierea

public MongoGridFSFile MongoGridFSCursor::current ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public MongoGridFSFile MongoGridFSCursor::getNext ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the next file.

MongoGridFSCursor::current
MongoGridFSCursor::key
MongoGridFSCursor


Returns the current result's filename

MongoGridFSCursor::getNext
Clase pentru opera?iuni în lot (batch)
MongoGridFSCursor
PHP Manual

MongoGridFSCursor::key

(PECL mongo >=0.9.0)

MongoGridFSCursor::key — Returns the current result's filename

Descrierea

public string MongoGridFSCursor::key ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current result's _id as a string.

Istoricul schimbarilor

Versiune | Descriere
1.3.0 | The document's _id is returned as a string value, since the key should be unique. Pre-1.3.0, filename was returned.

MongoGridFSCursor::getNext
Clase pentru opera?iuni în lot (batch)
MongoGridFSCursor


Clase pentru opera?iuni în lot (batch)

Cuprins

  • MongoWriteBatch
  • MongoInsertBatch
  • MongoUpdateBatch
  • MongoDeleteBatch
MongoGridFSCursor::key
MongoWriteBatch
Mongo


The MongoWriteBatch class

(PECL mongo >=1.5.0)

Introducere

MongoWriteBatch is the base class for the MongoInsertBatch, MongoUpdateBatch and MongoDeleteBatch classes.

MongoWriteBatch allows you to "batch up" multiple operations (of same type) and shipping them all to MongoDB at the same time. This can be especially useful when operating on many documents at the same time to reduce roundtrips.

Prior to version 1.5.0 of the driver it was possible to use MongoCollection::batchInsert(), however, as of 1.5.0 that method is now discouraged.

Note: This class is only available when talking to MongoDB 2.6.0 (and later) servers. It will throw MongoProtocolException if attempting to use it on older MongoDB servers.

Sinopsisul clasei

MongoWriteBatch {
/* Constante */
const int COMMAND_INSERT = 1 ;
const int COMMAND_UPDATE = 2 ;
const int COMMAND_DELETE = 3 ;
/* Metode */
protected __construct ( MongoCollection $collection [, string $batch_type [, array $write_options ]] )
public bool add ( array $item )
final public array execute ( array $write_options )
}

MongoWriteBatch types

MongoWriteBatch::COMMAND_INSERT

Create an Insert Write Batch

MongoWriteBatch::COMMAND_UPDATE

Create an Update Write Batch

MongoWriteBatch::COMMAND_DELETE

Create an Delete Write Batch

Descrierea

When executing a batch by calling MongoWriteBatch::execute(), MongoWriteBatch will send up to maxWriteBatchSize (defaults to 1000) documents or maxBsonObjectSize (defaults to 16777216 bytes), whichever comes first.

Nota:

Documents will never be partially transferred. When adding documents to the batch, that overflows the limit, a new batch will be created and the document put into the new batch.

Erori/Excep?ii

  • Exception on parameter parsing failures
  • Exception on argument validation errors (e.g. missing keys)
  • MongoProtocolException when talking to MongoDB server older then 2.6.0.
  • MongoProtocolException on socket errors.
  • MongoWriteConcernException when a write fails due to WriteConcerns

Exemple

Example #1 MongoWriteBatch example

Adding documents to a Insert batch and then execute it

<?php
$mc = new MongoClient("localhost");

$collection = $mc->selectCollection("test", "test");

$docs = array();
$docs[] = array("my" => "demo");
$docs[] = array("is" => "working");
$docs[] = array("pretty" => "well");

$batch = new MongoInsertBatch($collection);
foreach($docs as $document) {
    $batch->add($document);
}
$retval = $batch->execute(array("w" => 1));
var_dump($retval);
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["nInserted"]=>
  int(3)
  ["ok"]=>
  bool(true)
}

Cuprins

  • MongoWriteBatch::add — Adds a write operation to a batch
  • MongoWriteBatch::__construct — Creates a new batch of write operations
  • MongoWriteBatch::execute — Executes a batch of write operations
Clase pentru opera?iuni în lot (batch)
MongoWriteBatch::add
Clase pentru opera?iuni în lot (batch)


Adds a write operation to a batch

MongoWriteBatch
MongoWriteBatch::__construct
MongoWriteBatch
PHP Manual

MongoWriteBatch::add

(PECL mongo >= 1.5.0)

MongoWriteBatch::add — Adds a write operation to a batch

Descrierea

public bool MongoWriteBatch::add ( array $item )

Adds a write operation to the batch.

If $item causes the batch to exceed the maxWriteBatchSize or maxBsonObjectSize limits, the driver will internally split the batches into multiple write commands upon calling MongoWriteBatch::execute().

Parametri

item

An array that describes a write operation. The structure of this value depends on the batch's operation type.

Batch type | Argument expectation
MongoWriteBatch::COMMAND_INSERT | The document to add.
MongoWriteBatch::COMMAND_UPDATE

Raw update operation.

Required keys are "q" and "u", which correspond to the $criteria and $new_object parameters of MongoCollection::update(), respectively.

Optional keys are "multi" and "upsert", which correspond to the "multiple" and "upsert" options for MongoCollection::update(), respectively. If unspecified, both options default to FALSE.
MongoWriteBatch::COMMAND_DELETE

Raw delete operation.

Required keys are: "q" and "limit", which correspond to the $criteria parameter and "justOne" option of MongoCollection::remove(), respectively.

The "limit" option is an integer; however, MongoDB only supports 0 (i.e. remove all matching documents) and 1 (i.e. remove at most one matching document) at this time.

Valorile întoarse

Returns TRUE on success and throws an exception on failure.

Erori/Excep?ii

  • Exception on parameter parsing failures
  • Exception on argument validation errors (e.g. missing keys)

Exemple

Example #1 MongoWriteBatch::add() example

Batching up multiple insert operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$docs = array();
$docs[] = array("my" => "demo");
$docs[] = array("is" => "working");
$docs[] = array("pretty" => "well");

$batch = new MongoInsertBatch($collection);
foreach($docs as $document) {
    $batch->add($document);
}
$batch->execute(array("w" => 1));
?>

Example #2 MongoWriteBatch::add() example

Batching up multiple update operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$item1 = array(
    "q" => array("my" => "demo"),
    "u" => array('$set' => array("try" => 1)),
    "multi"  => false, /* default value */
    "upsert" => false, /* default value */
);
$item2 = array(
    "q" => array("is" => "working"),
    "u" => array('$set' => array("try" => 2)),
    "multi" => true,
);
$item3 = array(
    "q" => array("created" => "new-document"),
    "u" => array('$set' => array("try" => 3)),
    "upsert" => true,
);

$batch = new MongoUpdateBatch($collection);
$batch->add($item1);
$batch->add($item2);
$batch->add($item3);
$batch->execute(array("w" => 1));

?>

Example #3 MongoWriteBatch::add() example

Batching up multiple delete operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$item1 = array(
    "q" => array("my" => "demo"),
    "limit" => 1,
);
$item2 = array(
    "q" => array("try" => 3),
    "limit" => 1,
);

$batch = new MongoDeleteBatch($collection);
$batch->add($item1);
$batch->add($item2);
$batch->execute(array("w" => 1));
?>
MongoWriteBatch
MongoWriteBatch::__construct
MongoWriteBatch


Creates a new batch of write operations

MongoWriteBatch::add
MongoWriteBatch::execute
MongoWriteBatch
PHP Manual

MongoWriteBatch::__construct

(PECL mongo >= 1.5.0)

MongoWriteBatch::__construct — Creates a new batch of write operations

Descrierea

protected MongoWriteBatch::__construct ( MongoCollection $collection [, string $batch_type [, array $write_options ]] )

Constructs a new MongoWriteBatch.

Nota:

This is a protected constructor. Please use one of the classes inheriting MongoWriteBatch.

Parametri

collection

Clasa MongoCollection asupra careia se executa setul. Gradele ei de participare vor fi copiate ?i folosite ca implicite daca nu au fost furnizate cu $write_options sau în timpul executarii MongoWriteBatch::execute().

batch_type

One of:

  • 0 - make an MongoWriteBatch::COMMAND_INSERT batch
  • 1 - make an MongoWriteBatch::COMMAND_UPDATE batch
  • 2 - make a MongoWriteBatch::COMMAND_DELETE batch

write_options

Un tablou cu Opiuni de Înscriere.

cheia | însemnatatea valorii
w (int|string) | Valoare a Gradului de participare la înscriere
wtimeout (int) | Timpul maximal de a?teptare a replicarii
ordered | Determina daca MongoDB trebuie sa aplice acest set în ordinea stabilita. Înscrierile ordonate se executa secven?ial (adica câte o înregistrare) ?i execu?ia se întrerupe dupa prima eroare. Înscrierile neordonate pot fi executate în paralel ?i execu?ia nu se va stopa dupa prima eroare. Valoarea implicita este TRUE
j (bool) | A?teapta jurnalizarea pe primar. Aceasta valoare e nerecomandata, utiliza?i WriteConcern în loc
fsync (bool) | A?teapta fsync pe primar. Aceasta valoare e nerecomandata, utiliza?i WriteConcern în loc

Valorile întoarse

A new MongoWriteBatch of type batch_type.

A se vedea ?i

  • MongoInsertBatch
  • MongoUpdateBatch
  • MongoDeleteBatch
MongoWriteBatch::add
MongoWriteBatch::execute
MongoWriteBatch


Executes a batch of write operations

MongoWriteBatch::__construct
MongoInsertBatch
MongoWriteBatch
PHP Manual

MongoWriteBatch::execute

(PECL mongo >= 1.5.0)

MongoWriteBatch::execute — Executes a batch of write operations

Descrierea

final public array MongoWriteBatch::execute ( array $write_options )

Executes the batch of write operations.

Parametri

write_options

See MongoWriteBatch::__construct.

Valorile întoarse

Returns an array containing statistical information for the full batch. If the batch had to be split into multiple batches, the return value will aggregate the values from individual batches and return only the totals.

If the batch was empty, an array containing only the 'ok' field is returned (as TRUE) although nothing will be shipped over the wire (NOOP).

Array key | Value meaning | Returned for batch type
nInserted | Number of inserted documents | MongoWriteBatch::COMMAND_INSERT batch
nMatched | Number of documents matching the query criteria | MongoWriteBatch::COMMAND_UPDATE batch
nModified | Number of documents actually needed to be modied | MongoWriteBatch::COMMAND_UPDATE batch
nUpserted | Number of upserted documents | MongoWriteBatch::COMMAND_UPDATE batch
nRemoved | Number of documents removed | MongoWriteBatch::COMMAND_DELETE batch
ok | Command success indicator | All

Erori/Excep?ii

A MongoWriteConcernException exception is thrown on failure.

Exemple

Example #1 MongoWriteBatch::add() example

Batching up multiple insert operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$docs = array();
$docs[] = array("my" => "demo");
$docs[] = array("is" => "working");
$docs[] = array("pretty" => "well");

$batch = new MongoInsertBatch($collection);
foreach($docs as $document) {
    $batch->add($document);
}
$retval = $batch->execute(array("w" => 1));
var_dump($retval);
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["nInserted"]=>
  int(3)
  ["ok"]=>
  bool(true)
}

Example #2 MongoWriteBatch::add() example

Batching up multiple update operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$item1 = array(
    "q" => array("my" => "demo"),
    "u" => array('$set' => array("try" => 1)),
    "multi"  => false, /* default value */
    "upsert" => false, /* default value */
);
$item2 = array(
    "q" => array("is" => "working"),
    "u" => array('$set' => array("try" => 2)),
    "multi" => true,
);
$item3 = array(
    "q" => array("created" => "new-document"),
    "u" => array('$set' => array("try" => 3)),
    "upsert" => true,
);

$batch = new MongoUpdateBatch($collection);
$batch->add($item1);
$batch->add($item2);
$batch->add($item3);
$retval = $batch->execute(array("w" => 1));
var_dump($retval);

?>

Exemplul de mai sus va afi?a:

array(4) {
  ["nMatched"]=>
  int(18)
  ["nModified"]=>
  int(2)
  ["nUpserted"]=>
  int(0)
  ["ok"]=>
  bool(true)
}

Example #3 MongoWriteBatch::add() example

Batching up multiple delete operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$item1 = array(
    "q" => array("my" => "demo"),
    "limit" => 1,
);
$item2 = array(
    "q" => array("try" => 3),
    "limit" => 1,
);

$batch = new MongoDeleteBatch($collection);
$batch->add($item1);
$batch->add($item2);
$retval = $batch->execute(array("w" => 1));
var_dump($retval);
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["nRemoved"]=>
  int(1)
  ["ok"]=>
  bool(true)
}
MongoWriteBatch::__construct
MongoInsertBatch
MongoWriteBatch


The MongoInsertBatch class

(PECL mongo >=1.5.0)

Introducere

Constructs a batch of INSERT operations. See MongoWriteBatch.

Sinopsisul clasei

MongoInsertBatch extends MongoWriteBatch {
/* Metode */
public __construct ( MongoCollection $collection [, array $write_options ] )
/* Metode mo?tenite */
public bool MongoWriteBatch::add ( array $item )
final public array MongoWriteBatch::execute ( array $write_options )
}

Cuprins

  • MongoInsertBatch::__construct — Description
MongoWriteBatch::execute
MongoInsertBatch::__construct
Clase pentru opera?iuni în lot (batch)


Description

MongoInsertBatch
MongoUpdateBatch
MongoInsertBatch
PHP Manual

MongoInsertBatch::__construct

(PECL mongo >= 1.5.0)

MongoInsertBatch::__construct — Description

Descrierea

public MongoInsertBatch::__construct ( MongoCollection $collection [, array $write_options ] )

Constructs a batch of INSERT operations. See MongoWriteBatch.

Parametri

collection

Clasa MongoCollection asupra careia se executa setul. Gradele ei de participare vor fi copiate ?i folosite ca implicite daca nu au fost furnizate cu $write_options sau în timpul executarii MongoWriteBatch::execute().

write_options

Un tablou cu Opiuni de Înscriere.

cheia | însemnatatea valorii
w (int|string) | Valoare a Gradului de participare la înscriere
wtimeout (int) | Timpul maximal de a?teptare a replicarii
ordered | Determina daca MongoDB trebuie sa aplice acest set în ordinea stabilita. Înscrierile ordonate se executa secven?ial (adica câte o înregistrare) ?i execu?ia se întrerupe dupa prima eroare. Înscrierile neordonate pot fi executate în paralel ?i execu?ia nu se va stopa dupa prima eroare. Valoarea implicita este TRUE
j (bool) | A?teapta jurnalizarea pe primar. Aceasta valoare e nerecomandata, utiliza?i WriteConcern în loc
fsync (bool) | A?teapta fsync pe primar. Aceasta valoare e nerecomandata, utiliza?i WriteConcern în loc

Valorile întoarse

A new MongoInsertBatch.

MongoInsertBatch
MongoUpdateBatch
MongoInsertBatch


The MongoUpdateBatch class

(PECL mongo >=1.5.0)

Introducere

Constructs a batch of UPDATE operations. See MongoWriteBatch.

Sinopsisul clasei

MongoUpdateBatch extends MongoWriteBatch {
/* Metode */
public __construct ( MongoCollection $collection [, array $write_options ] )
/* Metode mo?tenite */
public bool MongoWriteBatch::add ( array $item )
final public array MongoWriteBatch::execute ( array $write_options )
}

Cuprins

  • MongoUpdateBatch::__construct — Description
MongoInsertBatch::__construct
MongoUpdateBatch::__construct
Clase pentru opera?iuni în lot (batch)


Description

MongoUpdateBatch
MongoDeleteBatch
MongoUpdateBatch
PHP Manual

MongoUpdateBatch::__construct

(PECL mongo >= 1.5.0)

MongoUpdateBatch::__construct — Description

Descrierea

public MongoUpdateBatch::__construct ( MongoCollection $collection [, array $write_options ] )

Constructs a batch of UPDATE operations. See MongoWriteBatch.

Parametri

collection

Clasa MongoCollection asupra careia se executa setul. Gradele ei de participare vor fi copiate ?i folosite ca implicite daca nu au fost furnizate cu $write_options sau în timpul executarii MongoWriteBatch::execute().

write_options

Un tablou cu Opiuni de Înscriere.

cheia | însemnatatea valorii
w (int|string) | Valoare a Gradului de participare la înscriere
wtimeout (int) | Timpul maximal de a?teptare a replicarii
ordered | Determina daca MongoDB trebuie sa aplice acest set în ordinea stabilita. Înscrierile ordonate se executa secven?ial (adica câte o înregistrare) ?i execu?ia se întrerupe dupa prima eroare. Înscrierile neordonate pot fi executate în paralel ?i execu?ia nu se va stopa dupa prima eroare. Valoarea implicita este TRUE
j (bool) | A?teapta jurnalizarea pe primar. Aceasta valoare e nerecomandata, utiliza?i WriteConcern în loc
fsync (bool) | A?teapta fsync pe primar. Aceasta valoare e nerecomandata, utiliza?i WriteConcern în loc

Valorile întoarse

A new MongoUpdateBatch.

MongoUpdateBatch
MongoDeleteBatch
MongoUpdateBatch


The MongoDeleteBatch class

(PECL mongo >=1.5.0)

Introducere

Constructs a batch of DELETE operations. See MongoWriteBatch.

Sinopsisul clasei

MongoDeleteBatch extends MongoWriteBatch {
/* Metode */
public __construct ( MongoCollection $collection [, array $write_options ] )
/* Metode mo?tenite */
public bool MongoWriteBatch::add ( array $item )
final public array MongoWriteBatch::execute ( array $write_options )
}

Cuprins

  • MongoDeleteBatch::__construct — Description
MongoUpdateBatch::__construct
MongoDeleteBatch::__construct
Clase pentru opera?iuni în lot (batch)


Description

MongoDeleteBatch
Diverse
MongoDeleteBatch
PHP Manual

MongoDeleteBatch::__construct

(PECL mongo >= 1.5.0)

MongoDeleteBatch::__construct — Description

Descrierea

public MongoDeleteBatch::__construct ( MongoCollection $collection [, array $write_options ] )

Constructs a batch of DELETE operations. See MongoWriteBatch.

Parametri

collection

Clasa MongoCollection asupra careia se executa setul. Gradele ei de participare vor fi copiate ?i folosite ca implicite daca nu au fost furnizate cu $write_options sau în timpul executarii MongoWriteBatch::execute().

write_options

Un tablou cu Opiuni de Înscriere.

cheia | însemnatatea valorii
w (int|string) | Valoare a Gradului de participare la înscriere
wtimeout (int) | Timpul maximal de a?teptare a replicarii
ordered | Determina daca MongoDB trebuie sa aplice acest set în ordinea stabilita. Înscrierile ordonate se executa secven?ial (adica câte o înregistrare) ?i execu?ia se întrerupe dupa prima eroare. Înscrierile neordonate pot fi executate în paralel ?i execu?ia nu se va stopa dupa prima eroare. Valoarea implicita este TRUE
j (bool) | A?teapta jurnalizarea pe primar. Aceasta valoare e nerecomandata, utiliza?i WriteConcern în loc
fsync (bool) | A?teapta fsync pe primar. Aceasta valoare e nerecomandata, utiliza?i WriteConcern în loc

Valorile întoarse

A new MongoDeleteBatch.

MongoDeleteBatch
Diverse
MongoDeleteBatch


Diverse

Cuprins

  • MongoLog
  • MongoPool
  • Mongo
MongoDeleteBatch::__construct
MongoLog
Mongo


The MongoLog class

(PECL mongo >=1.2.3)

Introducere

Logging can be used to get detailed information about what the driver is doing. Logging is disabled by default, but this class allows you to activate specific levels of logging for various 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 diagnostic-level events for replica sets and connections
MongoLog::setLevel(MongoLog::INFO|MongoLog::FINE);
MongoLog::setModule(MongoLog::RS|MongoLog::CON);

?>

Nota:

By default, MongoLog emits all log messages as PHP notices. Depending on the SAPI you use, messages may be sent to stderr (for CLI) or the web server's error log. If, after configuring MongoLog, log messages are not appearing as expected, ensure that the E_NOTICE bit is included in error_reporting and that display_errors is on.

Sinopsisul clasei

MongoLog {
/* Constante */
const int NONE = 0 ;
const int ALL = 31 ;
level constants {
const int WARNING = 1 ;
const int INFO = 2 ;
const int FINE = 4 ;
module constants {
const int RS = 1 ;
const int POOL = 1 ;
const int CON = 2 ;
const int IO = 4 ;
const int SERVER = 8 ;
const int PARSE = 16 ;
/* Fields */
private static int $callback ;
private static int $level ;
private static int $module ;
/* Metode */
public static callable getCallback ( void )
public static int getLevel ( void )
public static int getModule ( void )
public static void setCallback ( callable $log_function )
public static void setLevel ( int $level )
public static void setModule ( int $module )
}

Constante predefinite

MongoLog Constants

These constants can be used by both MongoLog::setLevel() and MongoLog::setModule().

MongoLog::NONE
Log nothing.
MongoLog::ALL
Log everything.

MongoLog Level Constants

These constants can be used by MongoLog::setLevel().

MongoLog::WARNING
Log events that are somewhat exceptional, but not quite worthy of an actual exception (e.g. recoverable connection errors).
MongoLog::INFO
Log events that may be of interest to administrators, but are not particularly noteworthy (e.g. option parsing, authentication steps).
MongoLog::FINE
Log most events that the driver performs (e.g. server selection, socket communication). Depending on the module being logged, this can be extremely noisy and is primarily useful for debugging.

MongoLog Module Constants

These constants can be used by MongoLog::setModule().

MongoLog::CON
Log connection activity. Creating new connections, authentication, pinging, timeouts, etc.
MongoLog::IO
Log traffic to/from the database. Unless your program is trivial, this will create an enormous number of log messages.
MongoLog::PARSE
Log parsing of the connection string and options when constructing MongoClient.
MongoLog::POOL
Previously used to log connection pool activity. This option is now a deprecated alias of MongoLog::RS.
MongoLog::RS
Log replica set activity. Failovers, read preference selection, etc.
MongoLog::SERVER
Previously used to log server status changes. This option is deprecated in favor of MongoLog::RS.

Istoricul schimbarilor

Versiune | Descriere
1.3.0 | Added MongoLog::CON and deprecated MongoLog::POOL and MongoLog::SERVER.

Cuprins

  • MongoLog::getCallback — Gets the previously set callback function
  • MongoLog::getLevel — Gets the level(s) currently being logged
  • MongoLog::getModule — Gets the module(s) currently being logged
  • MongoLog::setCallback — Sets a callback function to be invoked for events
  • MongoLog::setLevel — Sets the level(s) to be logged
  • MongoLog::setModule — Sets the module(s) to be logged
Diverse
MongoLog::getCallback
Diverse


Gets the previously set callback function

MongoLog
MongoLog::getLevel
MongoLog
PHP Manual

MongoLog::getCallback

(PECL mongo >= 1.3.0)

MongoLog::getCallback — Gets the previously set callback function

Descrierea

public static callable MongoLog::getCallback ( void )

Retrieves the callback function.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the callback function, or FALSE if not set yet.

Note

Precautie

This function is only available with PHP 5.3.0 and later.

MongoLog
MongoLog::getLevel
MongoLog


Gets the level(s) currently being logged

MongoLog::getCallback
MongoLog::getModule
MongoLog
PHP Manual

MongoLog::getLevel

(PECL mongo >= 1.2.3)

MongoLog::getLevel — Gets the level(s) currently being logged

Descrierea

public static int MongoLog::getLevel ( void )

This function can be used to see which log levels are currently enabled. The returned integer may be compared with the MongoLog level constants using bitwise operators to check for specific log levels.

<?php

if (MongoLog::getLevel() & MongoLog::FINE) {
    echo "lots of 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";
}

?>

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the level(s) currently being logged.

MongoLog::getCallback
MongoLog::getModule
MongoLog


Gets the module(s) currently being logged

MongoLog::getLevel
MongoLog::setCallback
MongoLog
PHP Manual

MongoLog::getModule

(PECL mongo >= 1.2.3)

MongoLog::getModule — Gets the module(s) currently being logged

Descrierea

public static int MongoLog::getModule ( void )

This function can be used to see which driver modules are currently being logged. The returned integer may be compared with the MongoLog module constants using 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";
}

?>

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the module(s) currently being logged.

MongoLog::getLevel
MongoLog::setCallback
MongoLog


Sets a callback function to be invoked for events

MongoLog::getModule
MongoLog::setLevel
MongoLog
PHP Manual

MongoLog::setCallback

(PECL mongo >= 1.3.0)

MongoLog::setCallback — Sets a callback function to be invoked for events

Descrierea

public static void MongoLog::setCallback ( callable $log_function )

This function will set a callback function to be invoked for events in lieu of emitting of PHP notice.

Parametri

log_function

The callback function to be invoked on events. It should have the following prototype:

log_function ( int $module , int $level , string $message )
module
One of the MongoLog module constants.
level
One of the MongoLog level constants.
message
The log message itself.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 MongoLog::setCallback() example

<?php

function module2string($module)
{
    switch ($module) {
        case MongoLog::RS: return "REPLSET";
        case MongoLog::CON: return "CON";
        case MongoLog::IO: return "IO";
        case MongoLog::SERVER: return "SERVER";
        case MongoLog::PARSE: return "PARSE";
        default: return "UNKNOWN";
    }
}

function level2string($level)
{
    switch ($level) {
        case MongoLog::WARNING: return "WARN";
        case MongoLog::INFO: return "INFO";
        case MongoLog::FINE: return "FINE";
        default: return "UNKNOWN";
    }
}

function callback($module, $level, $message)
{
    echo date("Y-m-d H:i:s - ");
    printf("%s (%s): %s\n", module2string($module), level2string($level), $message);
}

MongoLog::setLevel(MongoLog::ALL);
MongoLog::setModule(MongoLog::ALL);

// We specify the function name here, but any callable (e.g. anonymous function) will work
MongoLog::setCallback("callback");

new MongoClient();
?>

Exemplul de mai sus va afi?a ceva similar cu:

2013-07-09 09:41:42 - PARSE (INFO): Parsing localhost:27017
2013-07-09 09:41:42 - PARSE (INFO): - Found node: localhost:27017
2013-07-09 09:41:42 - PARSE (INFO): - Connection type: STANDALONE
2013-07-09 09:41:42 - CON (INFO): mongo_get_read_write_connection: finding a STANDALONE connection
2013-07-09 09:41:42 - CON (INFO): connection_create: creating new connection for localhost:27017
2013-07-09 09:41:42 - CON (INFO): stream_connect: Not establishing SSL for localhost:27017
2013-07-09 09:41:42 - CON (INFO): get_server_flags: start
2013-07-09 09:41:42 - CON (FINE): send_packet: read from header: 36
2013-07-09 09:41:42 - CON (FINE): send_packet: data_size: 95
2013-07-09 09:41:42 - CON (FINE): get_server_flags: setting maxBsonObjectSize to 16777216
2013-07-09 09:41:42 - CON (FINE): get_server_flags: setting maxMessageSizeBytes to 48000000
2013-07-09 09:41:42 - CON (INFO): is_ping: pinging localhost:27017;-;.;1543
2013-07-09 09:41:42 - CON (FINE): send_packet: read from header: 36
2013-07-09 09:41:42 - CON (FINE): send_packet: data_size: 17
2013-07-09 09:41:42 - CON (INFO): is_ping: last pinged at 1373359302; time: 0ms
2013-07-09 09:41:42 - REPLSET (FINE): finding candidate servers
2013-07-09 09:41:42 - REPLSET (FINE): - all servers
2013-07-09 09:41:42 - REPLSET (FINE): filter_connections: adding connections:
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): filter_connections: done
2013-07-09 09:41:42 - REPLSET (FINE): limiting by seeded/discovered servers
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): limiting by seeded/discovered servers: done
2013-07-09 09:41:42 - REPLSET (FINE): limiting by credentials
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): limiting by credentials: done
2013-07-09 09:41:42 - REPLSET (FINE): sorting servers by priority and ping time
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): sorting servers: done
2013-07-09 09:41:42 - REPLSET (FINE): selecting near servers
2013-07-09 09:41:42 - REPLSET (FINE): selecting near servers: nearest is 0ms
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): selecting near server: done
2013-07-09 09:41:42 - REPLSET (INFO): pick server: random element 0
2013-07-09 09:41:42 - REPLSET (INFO): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543

Note

Precautie

This function is only available with PHP 5.3.0 and later.

MongoLog::getModule
MongoLog::setLevel
MongoLog


Sets the level(s) to be logged

MongoLog::setCallback
MongoLog::setModule
MongoLog
PHP Manual

MongoLog::setLevel

(PECL mongo >= 1.2.3)

MongoLog::setLevel — Sets the level(s) to be logged

Descrierea

public static void MongoLog::setLevel ( int $level )

This function can be used to control logging verbosity and the types of activities that should be logged. The MongoLog level constants may be used with bitwise operators to specify multiple levels.

<?php

// first, specify a logging module
MongoLog::setModule(MongoLog::CON);

// log messages for every level
MongoLog::setLevel(MongoLog::ALL);

// log warning and info messages only
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 specify which modules(s) of the driver should log.

Parametri

level

The level(s) you would like to log.

MongoLog::setCallback
MongoLog::setModule
MongoLog


Sets the module(s) to be logged

MongoLog::setLevel
MongoPool
MongoLog
PHP Manual

MongoLog::setModule

(PECL mongo >= 1.2.3)

MongoLog::setModule — Sets the module(s) to be logged

Descrierea

public static void MongoLog::setModule ( int $module )

This function can be used to set which driver modules should be logged. The MongoLog module constants may be used with bitwise operators to specify multiple modules.

<?php

// first, specify a logging level
MongoLog::setLevel(MongoLog::ALL);

// log replica set activity
MongoLog::setModule(MongoLog::RS);

// log replica sets and connection activity
MongoLog::setModule(MongoLog::RS|MongoLog::CON);

// log everything except IO activity
MongoLog::setModule(MongoLog::ALL & (~MongoLog::IO));

?>

Note that you must also call MongoLog::setLevel() to enable logging.

Parametri

module

The module(s) you would like to log.

MongoLog::setLevel
MongoPool
MongoLog


The MongoPool class

(PECL mongo >= 1.2.3)

Introducere

Avertizare

The current (1.3.0+) releases of the driver no longer implements pooling. This class and its methods are therefore deprecated and should not be used.

Sinopsisul clasei

MongoPool {
/* Metode */
public static int getSize ( void )
public array info ( void )
public static bool setSize ( int $size )
}

Istoricul schimbarilor

Versiune | Descriere
1.3.0 | This functionality has been removed and no longer does anything other than emit deprecation warnings. This class is only kept around for backwards compatability and will be removed in the near future.
1.2.11 | Emits E_DEPRECATED when used.

Cuprins

  • 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
Diverse


Get pool size for connection pools

MongoPool
MongoPool::info
MongoPool
PHP Manual

MongoPool::getSize

(PECL mongo >= 1.2.3)

MongoPool::getSize — Get pool size for connection pools

Descrierea

public static int MongoPool::getSize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current pool size.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

Exemple

Example #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());

?>

A se vedea ?i

  • 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

(PECL mongo >= 1.2.3)

MongoPool::info — Returns information about all connection pools.

Descrierea

public array MongoPool::info ( void )

Returns an array of information about all connection pools.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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 MongoClient before we exhausted this pool (assuming no instances of MongoClient 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.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

MongoPool::getSize
MongoPool::setSize
MongoPool


Set the size for future connection pools.

MongoPool::info
Mongo
MongoPool
PHP Manual

MongoPool::setSize

(PECL mongo >= 1.2.3)

MongoPool::setSize — Set the size for future connection pools.

Descrierea

public static bool MongoPool::setSize ( int $size )

Sets the max number of connections new pools will be able to create.

Parametri

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.

Valorile întoarse

Returns the former value of pool size.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • MongoPool::getSize() - Get pool size for connection pools
  • MongoPool::info() - Returns information about all connection pools.
  • The connection documentation.

MongoPool::info
Mongo
MongoPool


The Mongo class [deprecated]

(PECL mongo >=0.9.0)

Introducere

A connection between PHP and MongoDB.

This class extends MongoClient and provides access to several deprecated methods.

For backwards compatibility, it also defaults the "w" option of its constructor argument to 0, which does not require write operations to be acknowledged by the server. See MongoClient::__construct() for more information.

Avertizare

This class has been DEPRECATED as of version 1.3.0. Relying on this feature is highly discouraged. Please use MongoClient instead.

Sinopsisul clasei

Mongo extends MongoClient {
/* Metode */
protected bool connectUtil ( void )
public static int getPoolSize ( void )
public string getSlave ( void )
public bool getSlaveOkay ( void )
public array poolDebug ( void )
public static bool setPoolSize ( int $size )
public bool setSlaveOkay ([ bool $ok = true ] )
public string switchSlave ( void )
/* Metode mo?tenite */
public bool MongoClient::close ([ boolean|string $connection ] )
public bool MongoClient::connect ( void )
public array MongoClient::dropDB ( mixed $db )
public MongoDB MongoClient::__get ( string $dbname )
public static array MongoClient::getConnections ( void )
public array MongoClient::getHosts ( void )
public array MongoClient::getReadPreference ( void )
public array MongoClient::getWriteConcern ( void )
public bool MongoClient::killCursor ( string $server_hash , int|MongoInt64 $id )
public array MongoClient::listDBs ( void )
public MongoCollection MongoClient::selectCollection ( string $db , string $collection )
public MongoDB MongoClient::selectDB ( string $name )
public bool MongoClient::setReadPreference ( string $read_preference [, array $tags ] )
public bool MongoClient::setWriteConcern ( mixed $w [, int $wtimeout ] )
public string MongoClient::__toString ( void )
}

Cuprins

  • Mongo::connectUtil — Connects with a database server
  • Mongo::__construct — The __construct purpose
  • 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::poolDebug — Returns information about all connection pools.
  • Mongo::setPoolSize — Set the size for future connection pools.
  • Mongo::setSlaveOkay — Change slaveOkay setting for this connection
  • Mongo::switchSlave — Choose a new secondary for slaveOkay reads
MongoPool::setSize
Mongo::connectUtil
Diverse


Connects with a database server

Mongo
Mongo::__construct
Mongo
PHP Manual

Mongo::connectUtil

(PECL mongo >=0.9.0)

Mongo::connectUtil — Connects with a database server

Descrierea

protected bool Mongo::connectUtil ( void )
Avertizare

This is an internal function that you should never call yourself.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

If the connection was successful.

Erori/Excep?ii

Throws MongoConnectionException if it fails to connect to the databases.

Mongo
Mongo::__construct
Mongo


The __construct purpose

Mongo::connectUtil
Mongo::getPoolSize
Mongo
PHP Manual

Mongo::__construct

(PECL mongo >=0.9.0)

Mongo::__construct — The __construct purpose

Descrierea

public Mongo::__construct ([ string $server [, array $options ]] )

This method overwrites the MongoClient constructor and turns off acknowledged writes.

Please see MongoClient::__construct() for description of the parameters.

Valorile întoarse

Avertizare

Instanciating this class will emit E_DEPRECATED warning, and turn off acknowledged writes.

Please use the MongoClient instead.

Mongo::connectUtil
Mongo::getPoolSize
Mongo


Get pool size for connection pools

Mongo::__construct
Mongo::getSlave
Mongo
PHP Manual

Mongo::getPoolSize

(PECL mongo >=1.2.0)

Mongo::getPoolSize — Get pool size for connection pools

Descrierea

public static int Mongo::getPoolSize ( void )
Avertizare

This feature has been DEPRECATED as of version 1.2.3. Relying on this feature is highly discouraged. Please use MongoPool::getSize() instead.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current pool size.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

Exemple

Example #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());

?>

A se vedea ?i

  • Mongo::setPoolSize() - Set the size for future connection pools.
  • Mongo::poolDebug() - Returns information about all connection pools.
  • The connection documentation.

Mongo::__construct
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

Descrierea

public string Mongo::getSlave ( void )

This finds the address of the secondary 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 secondary to use. Thus, after you connect, this function will return NULL even if there are secondaries available. When you first do a query with slaveOkay set, at that point the driver will choose a secondary for this connection. At that point, this function will return the chosen secondary.

See the query section of this manual for information on distributing reads to secondaries.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The address of the secondary this connection is using for reads.

This returns NULL if this is not connected to a replica set or not yet initialized.

Erori/Excep?ii

Genereaza o avertizare E_DEPRECATED

The returned results aren't really useful as the secondary selection process is done on each query and database command execution.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

A se vedea ?i

  • MongoCursor::info() - Gets information about the cursor's creation and iteration
Mongo::getPoolSize
Mongo::getSlaveOkay
Mongo


Get slaveOkay setting for this connection

Mongo::getSlave
Mongo::poolDebug
Mongo
PHP Manual

Mongo::getSlaveOkay

(PECL mongo >=1.1.0)

Mongo::getSlaveOkay — Get slaveOkay setting for this connection

Descrierea

public bool Mongo::getSlaveOkay ( void )

See the query section of this manual for information on distributing reads to secondaries.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the value of slaveOkay for this instance.

Erori/Excep?ii

Genereaza o avertizare E_DEPRECATED

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

A se vedea ?i

  • Read Preferences
  • MongoClient::getReadPreference() - Get the read preference for this connection
Mongo::getSlave
Mongo::poolDebug
Mongo


Returns information about all connection pools.

Mongo::getSlaveOkay
Mongo::setPoolSize
Mongo
PHP Manual

Mongo::poolDebug

(PECL mongo >=1.2.0)

Mongo::poolDebug — Returns information about all connection pools.

Descrierea

public array Mongo::poolDebug ( void )
Avertizare

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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 MongoClient 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 MongoClient before we exhausted this pool (assuming no instances of MongoClient 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.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

Mongo::getSlaveOkay
Mongo::setPoolSize
Mongo


Set the size for future connection pools.

Mongo::poolDebug
Mongo::setSlaveOkay
Mongo
PHP Manual

Mongo::setPoolSize

(PECL mongo >=1.2.0)

Mongo::setPoolSize — Set the size for future connection pools.

Descrierea

public static bool Mongo::setPoolSize ( int $size )
Avertizare

This method 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.

Parametri

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.

Valorile întoarse

Returns the former value of pool size.

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • Mongo::getPoolSize() - Get pool size for connection pools
  • Mongo::poolDebug() - Returns information about all connection pools.
  • The connection documentation.

Mongo::poolDebug
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

Descrierea

public bool Mongo::setSlaveOkay ([ bool $ok = true ] )

See the query section of this manual for information on distributing reads to secondaries.

Parametri

ok

If reads should be sent to secondary members of a replica set for all possible queries using this MongoClient instance.

Valorile întoarse

Returns the former value of slaveOkay for this instance.

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

A se vedea ?i

  • Read Preferences
  • MongoClient::setReadPreference() - Set the read preference for this connection
Mongo::setPoolSize
Mongo::switchSlave
Mongo


Choose a new secondary for slaveOkay reads

Mongo::setSlaveOkay
Func?ii Mongo
Mongo
PHP Manual

Mongo::switchSlave

(PECL mongo >=1.1.0)

Mongo::switchSlave — Choose a new secondary for slaveOkay reads

Descrierea

public string Mongo::switchSlave ( void )

This choses a random secondary for a connection to read from. It is called automatically by the driver and should not need to be used. It calls MongoClient::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 secondaries.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The address of the secondary 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.

Erori/Excep?ii

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).

Istoricul schimbarilor

Versiune | Descriere
1.2.11 | Emits E_DEPRECATED when used.

A se vedea ?i

  • Read Preferences
Mongo::setSlaveOkay
Func?ii Mongo
Mongo


Func?ii Mongo

Cuprins

  • bson_decode — Deserializes a BSON object into a PHP array
  • bson_encode — Serializes a PHP variable into a BSON string
Mongo::switchSlave
bson_decode
Mongo


Deserializes a BSON object into a PHP array

Func?ii Mongo
bson_encode
Func?ii Mongo
PHP Manual

bson_decode

(PECL mongo >=1.0.1)

bson_decode — Deserializes a BSON object into a PHP array

Descrierea

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.

Parametri

bson

The BSON to be deserialized.

Valorile întoarse

Returns the deserialized BSON object.

Func?ii Mongo
bson_encode
Func?ii Mongo


Serializes a PHP variable into a BSON string

bson_decode
Excep?ii
Func?ii Mongo
PHP Manual

bson_encode

(PECL mongo >=1.0.1)

bson_encode — Serializes a PHP variable into a BSON string

Descrierea

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.

Parametri

anything

The variable to be serialized.

Valorile întoarse

Returns the serialized string.

bson_decode
Excep?ii
Func?ii Mongo


Excep?ii

Cuprins

  • MongoException
  • MongoResultException
  • MongoCursorException
  • MongoCursorTimeoutException
  • MongoConnectionException
  • MongoGridFSException
  • MongoDuplicateKeyException
  • MongoProtocolException
  • MongoExecutionTimeoutException
  • MongoWriteConcernException

Ciuda?enii ale VMWare

Daca rula?i VMWare pe Windows ?i utiliza?i CIFS, suspendarea ma?inii virtuale va cauza o desincronizare a CIFS ?i va cauza errors bizare la reluarea execu?iei ("Obiectul Mongo nu a fost corect ini?ializat de constructorul sau"). Montarea permanenta a mapelor partajate Windows va corecta aceasta ?i ve?i putea sa suspenda?i ?i sa relua?i execu?ia în orice moment.

Pentru a monta în mod permanent mapele partajate ale Windows executa?i:

$ sudo update-rc.d -f umountnfs.sh remove
$ sudo update-rc.d umountnfs.sh stop 15 0 6 .

Vede?i » documenta?ia Ubuntu pentru cele mai recente instruc?iuni.

bson_encode
MongoException
Mongo


The MongoException class

(PECL mongo >= 1.0.0)

Introducere

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: 9

    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.

Sinopsisul clasei

MongoException extends Exception {
}
Excep?ii
MongoResultException
Excep?ii


The MongoResultException class

(PECL mongo >=1.3.0)

Introducere

The MongoResultException is thrown by several command helpers (such as MongoCollection::findAndModify()) in the event of failure. The original result document is available through MongoResultException::getDocument().

Sinopsisul clasei

MongoResultException extends MongoException {
/* Proprieta?i */
public $document ;
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode */
public array getDocument ( void )
}

Proprieta?i

document

The raw result document as an array.

Cuprins

  • MongoResultException::getDocument — Retrieve the full result document
MongoException
MongoResultException::getDocument
Excep?ii


Retrieve the full result document

MongoResultException
MongoCursorException
MongoResultException
PHP Manual

MongoResultException::getDocument

(PECL mongo >=1.3.0)

MongoResultException::getDocument — Retrieve the full result document

Descrierea

public array MongoResultException::getDocument ( void )

Retrieves the full error result document.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The full result document as an array, including partial data if available and additional keys.

Exemple

Example #1 MongoResultException::getDocument() example

<?php
$mc = new MongoClient("localhost");
$c = $mc->selectCollection("test", "test");

$c->insert(array(
     "name" => "Next promo",
     "inprogress" => false,
     "priority" => 0,
     "tasks" => array( "select product", "add inventory", "do placement"),
) );

$c->insert(array(
     "name" => "Biz report",
     "inprogress" => false,
     "priority" => 1,
     "tasks" => array( "run sales report", "email report" )
) );

$c->insert(array(
     "name" => "Biz report",
     "inprogress" => false,
     "priority" => 2,
     "tasks" => array( "run marketing report", "email report" )
    ),
    array("w" => true)
);

try {
    $retval = $c->findAndModify(
         array("inprogress" => false, "name" => "Biz report"),
         array('$set' => array('$set' => array('inprogress' => true, "started" => new MongoDate()))),
         null,
         array(
            "sort" => array("priority" => -1),
            "new" => true,
        )
    );
} catch(MongoResultException $e) {
    echo $e->getMessage(), "\n";
    $res = $e->getDocument();
    var_dump($res);
}
?>

Exemplele de mai sus vor afi?a ceva similar cu:

$set is not valid for storage.
array(3) {
  ["lastErrorObject"]=>
  array(5) {
    ["connectionId"]=>
    int(6)
    ["err"]=>
    string(30) "$set is not valid for storage."
    ["code"]=>
    int(52)
    ["n"]=>
    int(0)
    ["ok"]=>
    float(1)
  }
  ["ok"]=>
  float(0)
  ["errmsg"]=>
  string(30) "$set is not valid for storage."
}
MongoResultException
MongoCursorException
MongoResultException


The MongoCursorException class

(PECL mongo >= 1.0.0)

Introducere

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 MongoClient() (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("w" => 1));
    $collection->insert(array("_id" => 1), array("w" => 1));
}
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. ach of these will cause the driver to disconnect and attempt to find a new primary. The actual error you get on failover may not be a "not master" error, depending on when the change in primary occurs.

Sinopsisul clasei

MongoCursorException extends MongoException {
}

Cuprins

  • MongoCursorException::getHost — The hostname of the server that encountered the error
MongoResultException::getDocument
MongoCursorException::getHost
Excep?ii


The hostname of the server that encountered the error

MongoCursorException
MongoCursorTimeoutException
MongoCursorException
PHP Manual

MongoCursorException::getHost

(PECL mongo >= 1.0.0)

MongoCursorException::getHost — The hostname of the server that encountered the error

Descrierea

public string MongoCursorException::getHost ( void )

Returns the hostname of the server the query was sent too.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the hostname, or NULL if the hostname is unknown.

MongoCursorException
MongoCursorTimeoutException
MongoCursorException


The MongoCursorTimeoutException class

(PECL mongo >= 1.0.0)

Introducere

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.

Sinopsisul clasei

MongoCursorTimeoutException extends MongoCursorException {
}
MongoCursorException::getHost
MongoConnectionException
Excep?ii


The MongoConnectionException class

(PECL mongo >= 1.0.0)

Introducere

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 candidate servers found

    Thrown when the driver cannot establish a connection to MongoDB (fulfilling the ReadPreferences, if specified).

  • 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

    No server in a replica set connection was identified as the primary.

  • 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.

Sinopsisul clasei

MongoConnectionException extends MongoException {
}
MongoCursorTimeoutException
MongoGridFSException
Excep?ii


The MongoGridFSException class

(PECL mongo >= 1.0.0)

Introducere

Thrown when there are errors reading or writing files to or from the database.

Sinopsisul clasei

MongoGridFSException extends MongoException {
}

Error codes

MongoGridFSException error codes
Code | Message | Reason
3 | Could not open file $filename | Attempting to store an invalid file, such as directory
4 | File $filename is too large: $filesize bytes | Maximum filesize in GridFS is 4GB
5 | could not find filehandle | Resource doesn't have a filehandle
6 | no file is associate with this filehandle | Resource isn't a file resource
7 | error setting up file: $filenames | Could not open file for reading
9 | error reading file $filenames | Failed reading file
10 | error reading filehandle | Failed reading from a resource
11 | could not find uploaded file %s | Filename doesn't seem to be uploaded file
12 | Couldn't find tmp_name in the $_FILES array. Are you sure the upload worked? | Uploaded filename probably failed
13 | tmp_name was not a string or an array | Invalid filename given
14 | couldn't find file size | The length property is missing
15 | Cannot find filename | No filename provided, and no filename property set
16 | could not open destination file %s | Destination filename not writable
17 | error reading chunk of file | Chunk corruption
18 | couldn't create a php_stream | Couldn't create a stream resource
19 | couldn't find property | Chunk corruption
20 | chunk number has wrong size (size) when the max is maxchunksize | Chunk larger then expected
21 | chunk has wrong format | Chunk corruption

MongoConnectionException
MongoDuplicateKeyException
Excep?ii


The MongoDuplicateKeyException class

(PECL mongo >= 1.5.0)

Introducere

Thrown when attempting to insert a document into a collection which already contains the same values for the unique keys.

Sinopsisul clasei

MongoDuplicateKeyException extends MongoWriteConcernException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
public array MongoWriteConcernException::getDocument ( void )
}

Exemple

Example #1 Catching MongoDuplicateKeyException

<?php
$mc = new MongoClient("localhost");

$c = $mc->selectCollection("test", "test");

$c->insert(array('_id' => 1));
try {
    $c->insert(array('_id' => 1));
} catch (MongoWriteConcernException $e) {
    echo $e->getMessage(), "\n";
}
?>

Exemplele de mai sus vor afi?a ceva similar cu:

localhost:27017: insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.test.$_id_  dup key: { : 1 }
MongoGridFSException
MongoProtocolException
Excep?ii


The MongoProtocolException class

(PECL mongo >= 1.5.0)

Introducere

When talking to MongoDB 2.6.0, and later, certain operations (such as writes) may throw MongoProtocolException when the response from the server did not make sense - for example during network failure (we could read the entire response) or data corruption.

This exception is also thrown when attempting to talk newer protocols then the server supports, for example using the MongoWriteBatch when talking to a MongoDB server prior to 2.6.0.

Sinopsisul clasei

MongoProtocolException extends MongoException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}

Exemple

Example #1 Catching MongoProtocolException

Running the following example against MongoDB prior to 2.6.0 will throw an MongoProtocolException

<?php
$mc = new MongoClient("localhost");
$c = $mc->selectCollection("test", "test");

try {
    $batch = new MongoInsertBatch($c);
} catch(MongoProtocolException $e) {
    echo $e->getMessage();
}
?>

Exemplele de mai sus vor afi?a ceva similar cu:

Current primary does not have a Write API
MongoDuplicateKeyException
MongoExecutionTimeoutException
Excep?ii


The MongoExecutionTimeoutException class

(PECL mongo >= 1.5.0)

Introducere

Thrown when a operation times out server side (i.e. in MongoDB).

To configure the operation timeout threshold, use MongoCursor::maxTimeMS() or the "maxTimeMS" command option.

Sinopsisul clasei

MongoExecutionTimeoutException extends MongoException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}
MongoProtocolException
MongoWriteConcernException
Excep?ii


The MongoWriteConcernException class

(PECL mongo >= 1.5.0)

Introducere

MongoWriteConcernException is thrown when a write fails. See Write Concerns for how to set failure thresholds.

Prior to MongoDB 2.6.0, the » getLastError command would determine whether a write failed.

Sinopsisul clasei

MongoWriteConcernException extends MongoCursorException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode */
public array getDocument ( void )
/* Metode mo?tenite */
public string MongoCursorException::getHost ( void )
}

Cuprins

  • MongoWriteConcernException::getDocument — Get the error document
MongoExecutionTimeoutException
MongoWriteConcernException::getDocument
Excep?ii


Get the error document

MongoWriteConcernException
Jurnalul modificarilor
MongoWriteConcernException
PHP Manual

MongoWriteConcernException::getDocument

(PECL mongo >= 1.5.0)

MongoWriteConcernException::getDocument — Get the error document

Descrierea

public array MongoWriteConcernException::getDocument ( void )

Returns the actual response from the server that was interperated as an error.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A MongoDB document, if available, as an array.

MongoWriteConcernException
Jurnalul modificarilor
MongoWriteConcernException


Jurnalul modificarilor

Au fost efectuate urmatoarele modificari ale claselor/func?iilor/metodelor acestei extensii.

MongoDB PHP Driver 1.5.0

It supports all new features for MongoDB 2.6, including:

  • Aggregate can now return a cursor
  • Aggregation pipelines can now be explained
  • Possible to set maxTimeMS for commands and queries
  • Transparent support for the new command-based MongoDB write API
  • New MongoWriteBatch classes (using the new MongoDB write API)
  • Support for MongoDB Enterprise features (e.g. Kerberos, LDAP, X509)
  • Option to tune acceptable server latency for secondary reads (secondaryAcceptableLatencyMS)

With this release, some driver functionality which was previously documented as deprecated will now formally raise deprecation notices. This includes:

  • Instantiating the Mongo class
  • Calling MongoCursor::slaveOkay()
  • "wtimeout" and "safe" options for MongoCollection write operations
  • Manipulating public properties on core classes (such as $collection->w)

Nota:

No previously deprecated features have been removed.

Changes in behaviour:

  • Setting the mongo.native_long INI setting now raises an error on 32-bit platforms, and now defaults to true for 64-bit platforms.

MongoDB PHP Driver 1.4.0

The 1.4 series introduced fundemental changes in how connections are created to the MongoDB servers. The driver now utilizes PHP native streams, so all normal PHP stream options apply. Furthermore, an experimental Stream Context Support was added.

The 1.4.x series also added support for MongoDB 2.4.x.

The most important improvements however deal with the handling of replica sets, especially nodes that timeout and nodes that are unreachable for various reasons. Besides the improvements to replica set handling, this release addresses issues with read preferences through mongos nodes. It also adds support for SSL enabled connections as well as journal and fsync connection string options.

MongoDB PHP Driver 1.3.0

The 1.3 series introduced several major changes to the extension such as completely rewritten connection handling (and removal of the pooling mechanism), support for ReadPreferences and change the default WriteConcerns to be acknowledged by introducing a new class MongoClient which serves as a replacement class for the now deprecated Mongo class.

The driver now also supports connecting to multiple mongos instances (the Mongo Shard router) for loadbalancing.

Other enhancements include improved logging for easier connection handling debugging with MongoLog and support for the » Aggregation Framework via the MongoCollection::aggregate() method.

Changes to existing methods

Following is a list of all improvements to existing methods since their inception.

Version | Function | Description
1.7.0 | MongoDB::execute | This method has been deprecated as a result of the underlaying eval command being deprecated in MongoDB 3.0+.
1.6.0 | MongoCollection::count | The second parameter is now an options array. Passing limit and skip as the second and third parameters, respectively, is deprecated.
 | MongoDB::getCollectionNames | Changed first parameter to be an array of options. Pre-1.6.0, the first parameter was a boolean indicating the "includeSystemCollections" option.
 | MongoDB::listCollections | Changed first parameter to be an array of options. Pre-1.6.0, the first parameter was a boolean indicating the "includeSystemCollections" option.
1.5.0 | log_cmd_delete | Only available when connected to MongoDB 2.6.0+
 | log_cmd_insert | Only available when connected to MongoDB 2.6.0+
 | log_cmd_update | Only available when connected to MongoDB 2.6.0+
 | log_write_batch | Only available when connected to MongoDB 2.6.0+
 | MongoBinData::__construct | The default changed from 2 (MongoBinData::BYTE_ARRAY) to 0 (MongoBinData::GENERIC).
 | MongoClient::__construct | Added "authSource".
 | MongoClient::__construct | Added "authMechanism", "gssapiServiceName", and "secondaryAcceptableLatencyMS".
 | MongoCollection::aggregate | Added optional options argument
 | MongoCollection::batchInsert | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::ensureIndex | Renamed the "wtimeout" option to "wTimeoutMS". Emits E_DEPRECATED when "wtimeout" is used. Renamed the "timeout" option to "socketTimeoutMS". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::findOne | Added optional options argument.
 | MongoCollection::group | Added "maxTimeMS" option.
 | MongoCollection::insert | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::remove | Added "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::save | Added "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::toIndexString | This method has been deprecated.
 | MongoCollection::update | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCursor::slaveOkay | This method has been deprecated in favour of MongoCursor::setReadPreference and .
 | MongoDB::command | Renamed the "timeout" option to "socketTimeoutMS". Emits E_DEPRECATED when "timeout" is used. Added hash by-reference parameter.
1.4.5 | MongoCursor::batchSize | Before 1.4.5, this method would throw an MongoCursorException if the cursor had already started iterating.
1.4.0 | MongoClient::__construct | Added "ssl" option and support for connecting over SSL. Added "wTimeoutMS" option, which replaces "wTimeout". Emits E_DEPRECATED when "slaveOkay" or "timeout" is used.
 | MongoCursor::hint | The index argument now supports index names as string values. In versions before 1.4.0, only array or object values were accepted.
 | MongoCursor::setFlag | Support for flag 3 (OPLOG_REPLAY) is added. Versions before 1.4.0 would throw a warning saying that the flag is unsupported.
 | MongoDB::createCollection | In versions before 1.4.0, the options were all arguments to the method. The function synopsis in those older versions is: public MongoCollectionMongoDB::createCollection stringname boolcappedFALSE intsize0 intmax0 The meaning of the options is the same as described under the options argument above.
 | MongoId::__construct | An exception is thrown when passed invalid string
1.3.4 | MongoClient::__construct | Added "connectTimeoutMS" and "socketTimeoutMS" options.
 | MongoCollection::batchInsert | Added "wtimeout" option.
 | MongoCollection::ensureIndex | Added "wtimeout" option.
 | MongoCollection::insert | Added "wtimeout" option.
 | MongoCollection::remove | Added "wtimeout" option.
 | MongoCollection::update | Added "wtimeout" option.
1.3.3 | MongoClient::getReadPreference | The return value has changed to be consistent with MongoClient::setReadPreference. The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.
 | MongoCollection::getReadPreference | The return value has changed to be consistent with MongoCollection::setReadPreference. The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.
 | MongoDB::getReadPreference | The return value has changed to be consistent with MongoDB::setReadPreference. The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.
1.3.0 | MongoClient::close | The connection parameter to this function was added in 1.3.0. Before that, only the write connection would be closed by this method.
 | MongoClient::__construct | Added "readPreference", "readPreferenceTags", "w", and "wTimeout" options.
 | MongoCollection::batchInsert | Added "w" option.
 | MongoCollection::ensureIndex | Added "w" option. The options parameter no longer accepts a boolean to signify a unique index. Instead, this now has to be done with array('unique' => true).
 | MongoCollection::insert | Added "w" option. The options parameter no longer accepts a boolean to signify an acknowledged write. Instead, this now has to be done with array('w' => 1) (the default behaviour of MongoClient).
 | MongoCollection::remove | Added "w" option. The options parameter no longer accepts a boolean to signify "justOne". Instead, this now has to be done with array('justOne' => true).
 | MongoCollection::update | Added "w" option. The options parameter no longer accepts a boolean to signify an upsert. Instead, this now has to be done with array('upsert' => true).
 | MongoDB::listCollections | Added the includeSystemCollections parameter.
 | MongoGridFSCursor::key | The document's _id is returned as a string value, since the key should be unique. Pre-1.3.0, filename was returned.
1.2.11 | Mongo::getPoolSize | Emits E_DEPRECATED when used.
 | Mongo::getSlave | Emits E_DEPRECATED when used.
 | Mongo::getSlaveOkay | Emits E_DEPRECATED when used.
 | Mongo::poolDebug | Emits E_DEPRECATED when used.
 | Mongo::setSlaveOkay | Emits E_DEPRECATED when used.
 | Mongo::switchSlave | Emits E_DEPRECATED when used.
 | MongoBinData::__construct | Emits E_DEPRECATED when the second argument is not used. The default value for type may change in the near future.
 | MongoCollection::ensureIndex | Emits E_DEPRECATED when options is scalar.
 | MongoCollection::getSlaveOkay | Emits E_DEPRECATED when used.
 | MongoCollection::group | Emits E_DEPRECATED when options is scalar.
 | MongoCollection::remove | Emits E_DEPRECATED when options is scalar.
 | MongoCollection::setSlaveOkay | Emits E_DEPRECATED when used.
 | MongoCollection::update | Emits E_DEPRECATED when options is scalar.
 | MongoCursor::doQuery | Emits E_DEPRECATED when used.
 | MongoDB::authenticate | Emits E_DEPRECATED when used. Please pass in the authentication details to the constructor.
 | MongoDB::forceError | Emits E_DEPRECATED when used.
 | MongoDB::getSlaveOkay | Emits E_DEPRECATED when used.
 | MongoDB::prevError | Emits E_DEPRECATED when used.
 | MongoDB::resetError | Emits E_DEPRECATED when used.
 | MongoDB::setSlaveOkay | Emits E_DEPRECATED when used.
 | MongoPool::getSize | Emits E_DEPRECATED when used.
 | MongoPool::info | Emits E_DEPRECATED when used.
 | MongoPool::setSize | Emits E_DEPRECATED when used.
1.2.10 | MongoClient::getHosts | Support for non-replicasets was added. The returned array elements now also include the hostname and port.
1.2.7 | MongoCollection::batchInsert | Added "continueOnError" option.
1.2.5 | MongoGridFS::storeUpload | Changed second parameter to an array of metadata. Pre-1.2.5, the second parameter was an optional string overriding the filename.
1.2.0 | MongoClient::close | Before version 1.2.0 the driver would not use persistent connections by default, and all connections would be closed as soon as a MongoDB connection went out if scope. Since version 1.2.0 this is no longer the case and it is a bad idea to call close as you might end up overloading the server with connections under high load.
 | MongoClient::__construct | Added "username" and "password" options. Removed "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 MongoClient 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" option now takes a string, not a boolean.
 | MongoCollection::ensureIndex | Added "timeout" option.
 | MongoCollection::insert | Added "timeout" option.
 | MongoCollection::remove | Added "timeout" option.
 | MongoCollection::save | Added "timeout" option.
 | MongoCollection::update | Added "timeout" option.
 | MongoDB::command | Added options parameter with a single option: "timeout".
1.1.0 | MongoCursor::info | 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 .
1.0.11 | MongoCollection::ensureIndex | The "safe" option will trigger a primary failover, if necessary. MongoException will be thrown if the index name (either generated or set) is longer than 128 bytes.
 | MongoCollection::insert | Disconnects on "not master" errors if "safe" is set.
 | MongoCollection::remove | Disconnects on "not master" errors if "safe" is set.
 | MongoCollection::save | Disconnects on "not master" errors if "safe" is set.
 | MongoCollection::update | Disconnects on "not master" errors if "safe" is set.
1.0.10 | MongoCursor::info | Added started_iterating field, a boolean indicating if cursor is pre- or post-query.
1.0.9 | MongoClient::__construct | Added "replicaSet" option.
 | MongoCollection::batchInsert | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option.
 | MongoCollection::insert | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
 | MongoCollection::remove | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
 | MongoCollection::save | Added "fsync" option.
 | MongoCollection::update | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
1.0.7 | MongoCollection::count | Added limit and skip as second and third parameters, respectively.
1.0.5 | MongoCollection::batchInsert | Added options parameter.
 | MongoCollection::ensureIndex | Added the "name" option to override index name creation.
 | MongoCollection::remove | Changed second parameter to be an array of options. Pre-1.0.5, the second parameter was a boolean indicating the "safe" option.
 | MongoCollection::save | Added options parameter.
 | MongoCollection::update | Added "safe" option.
1.0.2 | MongoClient::__construct | 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.
 | MongoCollection::ensureIndex | Changed options parameter from boolean to array. Pre-1.0.2, the second parameter was an optional boolean value specifying a unique index.
 | MongoCollection::insert | Changed second parameter to be an array of options. Pre-1.0.2, the second parameter was a boolean indicating the "safe" option.
1.0.1 | MongoCollection::insert | Throw a MongoCursorException if the "safe" option is set and the insert fails.
 | MongoCollection::update | Changed options parameter from boolean to array. Pre-1.0.1, the second parameter was an optional boolean value specifying an upsert.
MongoWriteConcernException::getDocument
MongoDB
Mongo


MongoDB driver

Unlike the mongo extension, this extension supports both PHP and HHVM and is developed atop the » libmongoc and » libbson libraries. It provides a minimal API for core driver functionality: commands, queries, writes, connection management, and BSON serialization.

Userland PHP libraries that depend on this extension may provide higher level APIs, such as query builders, individual command helper methods, and GridFS. Application developers should consider using this extension in conjunction with the » MongoDB PHP library, which implements the same higher level APIs found in MongoDB drivers for other languages. This separation of concerns allows the driver to focus on essential features for which an extension implementation is paramount for performance.

  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Constante predefinite
  • Ghiduri de utilizare
    • Getting Started with HHVM
    • Using the PHP Library for MongoDB (PHPLIB)
  • Driver Architecture and Internals — Explains the driver architecure, and special features
    • Architecture — Architecture Overview
    • Connections — Connection handling and persistence
    • Persisting Data — Serialization and deserialization of PHP variables into MongoDB
  • Security
    • Request Injection Attacks
    • Script Injection Attacks
  • MongoDB\Driver — Clasele driver-ului MongoDB
    • MongoDB\Driver\Manager — The MongoDB\Driver\Manager class
    • MongoDB\Driver\Command — The MongoDB\Driver\Command class
    • MongoDB\Driver\Query — The MongoDB\Driver\Query class
    • MongoDB\Driver\BulkWrite — The MongoDB\Driver\BulkWrite class
    • MongoDB\Driver\WriteConcern — The MongoDB\Driver\WriteConcern class
    • MongoDB\Driver\ReadPreference — The MongoDB\Driver\ReadPreference class
    • MongoDB\Driver\ReadConcern — The MongoDB\Driver\ReadConcern class
    • MongoDB\Driver\Cursor — The MongoDB\Driver\Cursor class
    • MongoDB\Driver\CursorId — The MongoDB\Driver\CursorId class
    • MongoDB\Driver\Server — The MongoDB\Driver\Server class
    • MongoDB\Driver\WriteConcernError — The MongoDB\Driver\WriteConcernError class
    • MongoDB\Driver\WriteError — The MongoDB\Driver\WriteError class
    • MongoDB\Driver\WriteResult — The MongoDB\Driver\WriteResult class
  • MongoDB\Driver\BSON — Clase ?i func?ii de serializare de tip BSON
    • Func?ii
    • MongoDB\BSON\Binary — The MongoDB\BSON\Binary class
    • MongoDB\BSON\Javascript — The MongoDB\BSON\Javascript class
    • MongoDB\BSON\MaxKey — The MongoDB\BSON\MaxKey class
    • MongoDB\BSON\MinKey — The MongoDB\BSON\MinKey class
    • MongoDB\BSON\ObjectID — The MongoDB\BSON\ObjectID class
    • MongoDB\BSON\Regex — The MongoDB\BSON\Regex class
    • MongoDB\BSON\Timestamp — The MongoDB\BSON\Timestamp class
    • MongoDB\BSON\UTCDateTime — The MongoDB\BSON\UTCDateTime class
    • MongoDB\BSON\Type — The MongoDB\BSON\Type interface
    • MongoDB\BSON\Persistable — The MongoDB\BSON\Persistable interface
    • MongoDB\BSON\Serializable — The MongoDB\BSON\Serializable interface
    • MongoDB\BSON\Unserializable — The MongoDB\BSON\Unserializable interface
  • MongoDB\Driver\Exception — Exception classes
    • MongoDB\Driver\Exception\AuthenticationException — The MongoDB\Driver\Exception\AuthenticationException class
    • MongoDB\Driver\Exception\BulkWriteException — The MongoDB\Driver\Exception\BulkWriteException class
    • MongoDB\Driver\Exception\ConnectionException — The MongoDB\Driver\Exception\ConnectionException class
    • MongoDB\Driver\Exception\ConnectionTimeoutException — The MongoDB\Driver\Exception\ConnectionTimeoutException class
    • MongoDB\Driver\Exception\Exception — The MongoDB\Driver\Exception\Exception interface
    • MongoDB\Driver\Exception\ExecutionTimeoutException — The MongoDB\Driver\Exception\ExecutionTimeoutException class
    • MongoDB\Driver\Exception\InvalidArgumentException — The MongoDB\Driver\Exception\InvalidArgumentException class
    • MongoDB\Driver\Exception\LogicException — The MongoDB\Driver\Exception\LogicException class
    • MongoDB\Driver\Exception\RuntimeException — The MongoDB\Driver\Exception\RuntimeException class
    • MongoDB\Driver\Exception\SSLConnectionException — The MongoDB\Driver\Exception\SSLConnectionException class
    • MongoDB\Driver\Exception\UnexpectedValueException — The MongoDB\Driver\Exception\UnexpectedValueException class
    • MongoDB\Driver\Exception\WriteException — The MongoDB\Driver\Exception\WriteException class
Jurnalul modificarilor
Instalarea / configurarea
Extensii de lucru cu baze de date specifice anumitor producatori


Instalarea / configurarea

  • Necesita?i
  • Instalarea
    • Instalarea driver-ului PHP MongoDB cu PECL
    • Instalarea driver-ului PHP MongoDB pe Mac OS X cu Homebrew
    • Instalarea driver-ului PHP MongoDB pe Windows
    • Instalarea manuala a driver-ului PHP MongoDB
    • Instalarea manuala a driver-ului HHVM MongoDB
  • Configura?ia la rulare
  • Constante predefinite
MongoDB
Necesita?i
MongoDB


Necesita?i

Varianta PHP a driver-ului necesita PHP 5.4 sau ulterior.

Varianta HHVM a driver-ului necesita HHVM 3.9 sau ulterior.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Cuprins

  • Instalarea driver-ului PHP MongoDB cu PECL
  • Instalarea driver-ului PHP MongoDB pe Mac OS X cu Homebrew
  • Instalarea driver-ului PHP MongoDB pe Windows
  • Instalarea manuala a driver-ului PHP MongoDB
  • Instalarea manuala a driver-ului HHVM MongoDB
Necesita?i
Instalarea driver-ului PHP MongoDB cu PECL
Instalarea / configurarea


Instalarea driver-ului PHP MongoDB cu PECL

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/mongodb

Utilizatorii Linux, Unix ?i Mac OS X pot sa execute urmatoarea comanda pentru a instala driver-ul:

$ sudo pecl install mongodb

Este necesar de a adauga urmatoarea linie în fi?ierul de configurare php.ini:

extension=mongodb.so

Instalarea
Instalarea driver-ului PHP MongoDB pe Mac OS X cu Homebrew
Instalarea


Instalarea driver-ului PHP MongoDB pe Mac OS X cu Homebrew

Daca utiliza?i » Homebrew, tap-ul PHP include formulele pentru instalarea driver-ului pe diferite versiuni PHP.

  • php54-mongodb
  • php55-mongodb
  • php56-mongodb
  • php70-mongodb

De exemplu, pute?i instala driver-ul pentru PHP 7.0 cu urmatoarea comanda:

$ brew install php70-mongodb

Instalarea driver-ului PHP MongoDB cu PECL
Instalarea driver-ului PHP MongoDB pe Windows
Instalarea


Instalarea driver-ului PHP MongoDB pe Windows

Binare precompilate pentru fiecare versiune sunt disponibile în » PECL pentru o varietate de combina?ii ale versiunilor, siguran?ei în cazul firelor de execu?ie, bibliotecilor VC. Extrage?i arhiva ?i plasa?i php_mongo.dll în mapa cu extensiile PHP (implicit "ext").

Adauga?i urmatoarea linie în fi?ierul de configurare php.ini:

extension=php_mongo.dll

Instalarea driver-ului PHP MongoDB pe Mac OS X cu Homebrew
Instalarea manuala a driver-ului PHP MongoDB
Instalarea


Instalarea manuala a driver-ului PHP MongoDB

Pentru dezvoltatorii de driver-e ?i alte persoane interesate de ultimele corectari ale erorilor, este posibila compilarea driver-ului din ultimul cod-sursa de pe » Github. Executa?i urmatoarele comenzi pentru a clona ?i compila proiectul:

$ git clone https://github.com/mongodb/mongo-php-driver.git
$ cd mongo-php-driver
$ git submodule sync && git submodule update --init
$ phpize
$ ./configure
$ make all -j 5
$ sudo make install

Ultimul pas va afi?a unde a fost instalat mongodb.so, ca de exemplu:

Installing shared extensions:     /usr/lib/php/extensions/debug-non-zts-20151012/

Asigura?i-va ca op?iunea extension_dir din php.ini indica spre directorul unde mongodb.so a fost instalat. Pute?i afla valoarea op?iunii cu comanda:

$ php -i | grep extension_dir
  extension_dir => /usr/lib/php/extensions/debug-non-zts-20151012 =>
                   /usr/lib/php/extensions/debug-non-zts-20151012

Daca directoarele difera, modifica?i extension_dir în php.ini sau în mod manual transfera?i mongodb.so în directorul corect.

Adauga?i urmatoarea linie în fi?ierul de configurare php.ini:

extension=mongodb.so

Instalarea driver-ului PHP MongoDB pe Windows
Instalarea manuala a driver-ului HHVM MongoDB
Instalarea


Instalarea manuala a driver-ului HHVM MongoDB

La momentul scrierii acestei instruc?iuni, HHVM nu poseda un manager de pachete pentru extensii. Descarca?i ultimul driver de pe » GitHub. Alternativ, pute?i clona repozitarul pentru a compila ultimul cod-sursa:

$ git clone https://github.com/mongodb/mongo-hhvm-driver.git
$ cd mongo-hhvm-driver
$ git submodule sync && git submodule update --init

Genera?i fi?ierele configure pentru bibliotecile incapsulate. Pentru aceasta trebuie sa ave?i instalate pachetele automake, autoconf ?i libtool (de ex. cu apt-get).

$ cd libbson; ./autogen.sh; cd ..
$ cd libmongoc; ./autogen.sh; cd ..

Compila?i ?i instala?i driver-ul cu aceste comenzi:

$ hphpize
$ cmake .
$ make -j 5
$ sudo make install

Nota:

Daca comanda hphpize nu este disponibila, va trebui sa compila?i HHVM din codul-sursa sau sa instala?i pachetul hhvm-dev (de ex. cu apt-get).

La ultimul pas se va afi?a unde a fost instalat mongodb.so. De exemplu:

Installing:     /usr/local/hhvm/3.9.1/lib/hhvm/extensions/20150212/mongodb.so

Adauga?i urmatoarea linie la fi?ierul de configurare php.ini (de obicei localizat în "/etc/hhvm"):

hhvm.dynamic_extension_path=/usr/local/hhvm/3.9.1/lib/hhvm/extensions/20150212
hhvm.dynamic_extensions[mongodb]=mongodb.so

Instalarea manuala a driver-ului PHP MongoDB
Configura?ia la rulare
Instalarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

mongodb Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor | Comments
mongodb.debug | "" | PHP_INI_ALL |  | Only available for the PHP driver, and not the HHVM one

Iata o explica?ie pe scurt a directivelor de configurare.

mongodb.debug string

Store full activity debug log in this directory or stream. The special value "stderr" can be provided to write to STDERR.

Nota:

Not available for HHVM

Instalarea manuala a driver-ului HHVM MongoDB
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

MONGODB_VERSION (string)
x.y.z style version number of the extension
MONGODB_STABILITY (string)
Current stability (alpha/beta/stable)

Configura?ia la rulare
Ghiduri de utilizare
Instalarea / configurarea


Ghiduri de utilizare

În aceasta sec?iune ve?i gasi câteva ghiduri de utilizare a driver-ului MongoDB cu PHP ?i HHVM. Deoarece driver-ele func?ioneaza la fel pe ambele sisteme, ghidurile de utilizare vor fi comune, dar cu sec?iunile de instalare separate.

  • Getting Started with HHVM
  • Using the PHP Library for MongoDB (PHPLIB)
Constante predefinite
Getting Started with HHVM
MongoDB


Getting Started with HHVM

In this section you will learn how to set-up NGINX with HHVM and MongoDB. However, this tutorial is not meant to be an all inclusive guide on how to run NGINX and HHVM in a production environment.

In this tutorial, we will be using a Debian system with NGINX installed through apt-get and HHVM installed from source or pre-built packages into /usr/local/hhvm/3.9.1 (with the binary located at /usr/local/hhvm/3.9.1/bin/hhvm).

Installing NGINX

We simply install NGINX by running apt-get install nginx-full. If NGINX fails to start after installation, it is likely that you already have another web server (e.g. Apache) running on the same port. In that case, you will see the following lines in /var/log/nginx/error.log:

2015/09/29 10:19:27 [emerg] 22445#22445: bind() to 0.0.0.0:80 failed (98:Address already in use)
2015/09/29 10:19:27 [emerg] 22445#22445: bind() to [::]:80 failed (98: Address already in use)

To resolve this, you can either change the default port for NGINX or Apache, stop the Apache process with service apache2 stop, or remove Apache entirely with apt-get remove apache2.

Installing HHVM

This tutorial is written from the perspective of an extension developer, so we've installed HHVM from source to faciliate patch development and ensure that debug symbols are available. That said, the folks at Facebook also provide pre-built packages, which is probably what you will want to use in production and development. You can find installation instructions for these packages on the » HHVM Wiki.

You will need to install both the the hhvm and hhvm-dev packages. The latter is needed so that we can compile the MongoDB HHVM extension later on.

If you are compiling HHVM from source, you will need to create /var/run/hhvm:

sudo mkdir -p /var/run/hhvm
sudo chown www-data.www-data /var/run/hhvm
sudo mkdir /etc/hhvm
sudo touch /etc/hhvm/php.ini
# So that you don't have to ``sudo`` to edit the file
sudo chown derick /etc/hhvm/php.ini
# To see whether it actually works
echo "date.timezone=Europe/London" >> /etc/hhvm/php.ini

HHVM should be started as the www-data user. For the purposes of this tutorial, we can run it in the foreground in server mode as follows:

sudo -u www-data -s /usr/local/hhvm/3.9.1/bin/hhvm \
 --mode server \
 -vServer.Type=fastcgi \
 -vServer.FileSocket=/var/run/hhvm/sock

Making NGINX Talk to HHVM

Once HHVM runs, we need to tell NGINX how to talk to HHVM for executing .php files. Although this is perhaps not the cleanest approach, you can add the following snippet to /etc/nginx/sites-enabled/default, just after the location / { … } section:

location ~ \.php$ {
   fastcgi_pass unix:/var/run/hhvm/sock;
   fastcgi_index index.php;
   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
   include fastcgi_params;
}

After adding that snippet, you should restart NGINX:

sudo service nginx restart

To confirm that everything works so far, we will create a project directory with an index.php file that calls phpinfo():

  • Create the project directory: sudo mkdir -p /var/www/html/my-first-project

  • Change permissions to your user and the www-data group: sudo chown derick.www-data /var/www/html/my-first-project

  • Create the file /var/www/html/my-first-project/index.php. From now on, I will not include the full path /var/www/html/my-first-project/ when I mention file names. Put the following content in this file:

    <?php
    phpinfo    ();
    ?>

Now, in your browser, request the page http://gargleblaster/my-first-project/index.php (but adjust the hostname). This should then show a page starting with "HHVM Version 3.9.1" followed by several tables with information.

Installing the MongoDB Driver for HHVM

The MongoDB driver is the part that links up the PHP in HHVM with the database server. To install and register the driver with HHVM, you need to follow the steps in Instalarea manuala a driver-ului HHVM MongoDB.

After you have installed and enabled the extension, HHVM will need to be restarted. If you have HHVM running in the shell from earlier, stop it with Ctrl-C and restart it again as above:

sudo -u www-data -s /usr/local/hhvm/3.9.1/bin/hhvm \
   --mode server \
   -vServer.Type=fastcgi \
   -vServer.FileSocket=/var/run/hhvm/sock

In order to test that the driver is loaded, edit the index.php file and replace its contents with:

<?php
var_dump(phpversion("mongodb"));
?>

This should output something similar to:

string(5) "x.y.z"

Further Reading

Continue this tutorial by jumping to Using the PHP Library for MongoDB (PHPLIB).

Ghiduri de utilizare
Using the PHP Library for MongoDB (PHPLIB)
Ghiduri de utilizare


Using the PHP Library for MongoDB (PHPLIB)

After the initial driver set-up, we will continue explaining how to get started with the MongoDB driver and corresponding userland library to write our first project.

Installing the PHP Library with Composer

The last thing we still need to install to get started on the application itself, is the PHP library.

The library needs to be installed with » Composer, a package manager for PHP. Instructions for installing Composer on various platforms may be found on its website.

Install the library by running:

$ composer require mongodb/mongodb

It will output something akin to:

./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing mongodb/mongodb (1.0.0)
    Downloading: 100%

Writing lock file
Generating autoload files

Composer will create several files: composer.json, composer.lock, and a vendor directory that will contain the library and any other dependencies your project might require.

Using the PHP Library

In addition to managing your dependencies, Composer will also provide you with an autoloader (for those dependencies' classes). Ensure that it is included at the start of your script or in your application's bootstrap code:

<?php
// This path should point to Composer's autoloader
require 'vendor/autoload.php';

With this done, you can now use any of the functionality as described in the » library documentation.

If you have previously used the old driver (i.e. mongo extension), the library's API should look familiar. It contains a » Client class for connecting to MongoDB, and » Database class for database-level operations (e.g. commands, collection management) and a » Collection class for collection-level operations (e.g. » CRUD methods, index management). Various Collection methods have been renamed for clarity, and to be in accordance with a new language-agnostic » specification.

As an example, this is how you insert a document into the beers collection of the demo database:

<?php
require 'vendor/autoload.php'; // include Composer's autoloader

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;

$result = $collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );

echo "Inserted with Object ID '{$result->getInsertedId()}'";
?>

Instead of injecting the generated _id field into the input document (as was done in the old driver), it is now made available through the result object returned by the insertOne method.

After insertion, you can of course also query the data that you have just inserted. For that, you use the find method, which returns an iterable cursor:

<?php
require 'vendor/autoload.php'; // include Composer's autoloader

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;

$result = $collection->find( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );

foreach ($result as $entry) {
    echo $entry['_id'], ': ', $entry['name'], "\n";
}
?>

While it may not be apparent in the examples, BSON documents and arrays are unserialized as type classes in the library by default. These classes ensure that values preserve their type when being serialized back into BSON, which avoids a caveat in the old driver where arrays might turn into documents, and vice versa. Additionally, the classes extend ArrayObject for enhanced usability. You can find more information on how serialization and deserialization between PHP variables and BSON is handled by the driver and library by reading the Persisting Data specification.

Getting Started with HHVM
Driver Architecture and Internals
Ghiduri de utilizare


Explains the driver architecure, and special features

  • Architecture — Architecture Overview
  • Connections — Connection handling and persistence
  • Persisting Data — Serialization and deserialization of PHP variables into MongoDB
    • Serialization to BSON
    • Deserialization from BSON
Using the PHP Library for MongoDB (PHPLIB)
Architecture
MongoDB


Architecture Overview

This section explains how all the different parts of the driver fit together. From the different language runtimes, through the extensions and to the PHP libraries on top. This new architecture has replaced the old mongo extension. We refer to the new one as the mongodb extension.

At the top of this stack sits a pure » PHP library, which we will distribute as a Composer package. This library will provide an API similar to what users have come to expect from the old mongo driver (e.g. CRUD methods, database and collection objects, command helpers) and we expect it to be a common dependency for most applications built with MongoDB. This library will also implement common » specifications, in the interest of improving API consistency across all of the » drivers maintained by MongoDB (and hopefully some community drivers, too).

Sitting below that library we have the lower level drivers—one per platform. These extensions will effectively form the glue between PHP and HHVM and our system libraries (» libmongoc and » libbson). These extensions will expose an identical public API for the most essential and performance-sensitive functionality:

  • Connection management
  • BSON encoding and decoding
  • Object document serialization (to support ODM libraries)
  • Executing commands and write operations
  • Handling queries and cursors

By decoupling the driver internals and a high-level API into extensions and PHP libraries, respectively, we hope to reduce our maintainence burden and allow for faster iteration on new features. As a welcome side effect, this also makes it easier for anyone to contribute to the driver. Additionally, an identical public API for these extensions will make it that much easier to port an application across PHP runtimes, whether the application uses the low-level driver directly or a higher-level PHP library.

» GridFS is a great example of why we chose this direction. Although we implemented GridFS in C for our old mongo driver, it is actually quite a high-level specification. Its API is just an abstraction for accessing two collections: files (i.e. metadata) and chunks (i.e. blocks of data). Likewise, all of the syntactic sugar found in the old mongo driver, such as processing uploaded files or exposing GridFS files as PHP streams, can be implemented in pure PHP. Provided we have performant methods for reading from and writing to GridFS' collections – and thanks to our low level extensions, we will – shifting this API to PHP is win-win.

Earlier I mentioned that we expect the PHP library to be a common dependency for most applications, but not all. Some users may prefer to stick to the no-frills API offered by the extensions, or create their own high-level abstraction (akin to » Doctrine MongoDB for the old mongo driver). Future libraries could include a PHP library geared for MongoDB administration, which provides an API for various user management and ops commands. The next major version of » Doctrine MongoDB ODM will likely also sit directly atop the extensions.

While we will continue to maintain and support the old mongo driver and its users for the foreseeable future, we invite everyone to use the next-generation driver and consider it for any new projects going forward. You can find all of the essential components across GitHub and JIRA:

Driver Source Code and JIRA Locations
Project | GitHub | JIRA
PHP Library | » mongodb/mongo-php-library | » PHPLIB
PHP 5 and PHP 7 Driver (phongo) | » mongodb/mongo-php-driver | » PHPC
HHVM Driver (hippo) | » mongodb/mongo-hhvm-driver | » HHVM

The existing » PHP project in JIRA will remain open for reporting bugs against the old mongo driver, but we would ask that you use the new projects above for anything pertaining to our next-generation drivers.

Driver Architecture and Internals
Connections
Driver Architecture and Internals


Connection handling and persistence

Sfat

On Unix platforms, the MongoDB driver is sensitive to scripts that use the fork() system call without also calling exec(). Users are advised not to re-use MongoDB\Driver\Manager instances in a forked child process.

Connection and topology persistence (PHP and HHVM versions since 1.2.0)

All versions of the driver since 1.2.0 persist the » libmongoc client object in the PHP worker process, which allows it to re-use database connections, authentication states, and topology information across multiple requests.

When MongoDB\Driver\Manager::__construct() is invoked, a hash is created from its arguments (i.e. URI string and array options). The driver will attempt to find a previously persisted » libmongoc client object for that hash. If an existing client cannot be found for the hash, a new client will be created (and persisted for future use).

Each client contains its own database connections and a view of the server topology (e.g. standalone, replica set, shard cluster). By persisting the client between PHP requests, the driver is able to re-use established database connections and remove the need for » discovering the server topology on each request.

Consider the following example:

<?php

$managers = [
    new MongoDB\Driver\Manager('mongodb://127.0.0.1'),
    new MongoDB\Driver\Manager('mongodb://127.0.0.1'),
    new MongoDB\Driver\Manager('mongodb://127.0.0.1:27017'),
    new MongoDB\Driver\Manager('mongodb://rs1.example.com,rs2.example.com/', ['replicaSet' => 'myReplicaSet']),
];

foreach ($managers as $manager) {
    $manager->executeCommand('test', new MongoDB\Driver\Command(['ping' => 1]));
}

?>

The first two Manager objects will share the same » libmongoc client since their constructor arguments are identical. The third and fourth objects will each use their own client. In total, three clients will be created and the PHP worker executing this script will open two connections to 127.0.0.1 and one connection to each of rs1.example.com and rs2.example.com. If the driver discovers additional members of the replica set after issuing isMaster commands, it will open additional connections to those servers as well.

If the same worker executes the script again in a second request, the three clients will be re-used and no new connections should be made. Depending on how long ago the previous request was served, the driver may need to issue additional isMaster commands to update its view of the topologies.

Socket persistence (PHP versions before 1.2.0)

Versions of the PHP driver before 1.2.0 utilize PHP's Streams API for database connections, using an API within » libmongoc to designate custom handlers for socket communication; however, a new libmongoc client is created for each MongoDB\Driver\Manager. As a result, the driver persists individual database connections but not authentication state or topology information. This means that the driver needs to issue commands at the start of each request to authenticate and » discover the server topology.

Database connections are persisted by a hash derived from the server's host, port, and the URI string used to construct the MongoDB\Driver\Manager. The constructor's array options are not included in this hash.

Nota: Versions of the driver >= 1.1.8 and < 1.2.0 do not persist sockets for SSL connections. See » PHPC-720 for additional information.

Despite its shortcomings with persisting SSL connections when and topology information, this version of the driver supports all SSL context options since it uses PHP's Streams API.

No persistence (HHVM versions before 1.2.0)

Versions of the HHVM driver before 1.2.0 do not persist sockets, authentication state, or topology information. Socket communication uses » libmongoc entirely.

Architecture
Persisting Data
Driver Architecture and Internals


Serialization and deserialization of PHP variables into MongoDB

Cuprins

  • Serialization to BSON
  • Deserialization from BSON

This document discusses the methods how compound structures (documents, arrays, objects) are persisted through the drivers. And how they are brought back into PHP land.

Connections
Serialization to BSON
Driver Architecture and Internals


Serialization to BSON

Arrays

If an array is a packed array — i.e. the keys start at 0 and are sequential without gaps: BSON array.

If the array is not packed — i.e. having associative (string) keys, the keys don't start at 0, or when there are gaps:: BSON object

A top-level (root) document, always serializes as a BSON document.

Examples

These serialize as a BSON array:

[ 8, 5, 2, 3 ] => [ 8, 5, 2, 3 ]
[ 0 => 4, 1 => 9 ] => [ 4, 9 ]

These serialize as a BSON document:

[ 0 => 1, 2 => 8, 3 => 12 ] => { "0" : 1, "2" : 8, "3" : 12 }
[ "foo" => 42 ] => { "foo" : 42 }
[ 1 => 9, 0 => 10 ] => { "1" : 9, "0" : 10 }

Note that the five examples are extracts of a full document, and represent only one value inside a document.

Objects

If an object is of the stdClass class, serialize as a BSON document.

If an object is a supported class that implements MongoDB\BSON\Type, then use the BSON serialization logic for that specific type. MongoDB\BSON\Type instances (excluding MongoDB\BSON\Serializable may only be serialized as a document field value. Attempting to serialize such an object as a root document will throw a MongoDB\Driver\Exception\UnexpectedValueException

If an object is of an unknown class implementing the MongoDB\BSON\Type interface, then throw a MongoDB\Driver\Exception\UnexpectedValueException

If an object is of any other class, without implementing any special interface, serialize as a BSON document. Keep only public properties, and ignore protected and private properties.

If an object is of a class that implements the MongoDB\BSON\Serializable interface, call MongoDB\BSON\Serializable::bsonSerialize() and use the returned array or stdClass to serialize as a BSON document or array. The BSON type will be determined by the following:

  1. Root documents must be serialized as a BSON document.

  2. MongoDB\BSON\Persistable objects must be serialized as a BSON document.

  3. If MongoDB\BSON\Serializable::bsonSerialize() returns a packed array, serialize as a BSON array.

  4. If MongoDB\BSON\Serializable::bsonSerialize() returns a non-packed array or stdClass, serialize as a BSON document.

  5. If MongoDB\BSON\Serializable::bsonSerialize() did not return an array or stdClass, throw an MongoDB\Driver\Exception\UnexpectedValueException exception.

If an object is of a class that implements the MongoDB\BSON\Persistable interface (which implies MongoDB\BSON\Serializable obtain the properties in a similar way as in the previous paragraphs, but also add an additional property __pclass as a Binary value, with subtype 0x80 and data bearing the fully qualified class name of the object that is being serialized.

The __pclass property is added to the array or object returned by MongoDB\BSON\Serializable::bsonSerialize(), which means it will overwrite any __pclass key/property in the MongoDB\BSON\Serializable::bsonSerialize() return value. If you want to avoid this behaviour and set your own __pclass value, you must not implement MongoDB\BSON\Persistable and should instead implement MongoDB\BSON\Serializable directly.

Examples

<?php

class stdClass {
  public $foo = 42;
} // => { "foo" : 42 }

class MyClass {
  public $foo = 42;
  protected $prot = "wine";
  private $fpr = "cheese";
} // => { "foo" : 42 }

class AnotherClass1 implements MongoDB\BSON\Serializable {
  public $foo = 42;
  protected $prot = "wine";
  private $fpr = "cheese";
  function bsonSerialize() {
      return [ 'foo' => $this->foo, 'prot' => $this->prot ];
  }
} // => { "foo" : 42, "prot" : "wine" }

class AnotherClass2 implements MongoDB\BSON\Serializable {
  public $foo = 42;
  function bsonSerialize() {
      return $this;
  }
} // => MongoDB\Driver\Exception\UnexpectedValueException("bsonSerialize() did not return an array or stdClass")

class AnotherClass3 implements MongoDB\BSON\Serializable {
  private $elements = [ 'foo', 'bar' ];
  function bsonSerialize() {
      return $this->elements;
  }
} // => { "0" : "foo", "1" : "bar" }

class ContainerClass implements MongoDB\BSON\Serializable {
  public $things = AnotherClass4 implements MongoDB\BSON\Serializable {
    private $elements = [ 0 => 'foo', 2 => 'bar' ];
    function bsonSerialize() {
      return $this->elements;
    }
  }
  function bsonSerialize() {
      return [ 'things' => $this->things ];
  }
} // => { "things" : { "0" : "foo", "2" : "bar" } }

class ContainerClass implements MongoDB\BSON\Serializable {
  public $things = AnotherClass5 implements MongoDB\BSON\Serializable {
    private $elements = [ 0 => 'foo', 2 => 'bar' ];
    function bsonSerialize() {
      return array_values($this->elements);
    }
  }
  function bsonSerialize() {
      return [ 'things' => $this->things ];
  }
} // => { "things" : [ "foo", "bar" ] }

class ContainerClass implements MongoDB\BSON\Serializable {
  public $things = AnotherClass6 implements MongoDB\BSON\Serializable {
    private $elements = [ 'foo', 'bar' ];
    function bsonSerialize() {
      return (object) $this->elements;
    }
  }
  function bsonSerialize() {
      return [ 'things' => $this->things ];
  }
} // => { "things" : { "0" : "foo", "1" : "bar" } }

class UpperClass implements MongoDB\BSON\Persistable {
  public $foo = 42;
  protected $prot = "wine";
  private $fpr = "cheese";
  function bsonSerialize() {
      return [ 'foo' => $this->foo, 'prot' => $this->prot ];
  }
} // => { "foo" : 42, "prot" : "wine", "__pclass" : { "$type" : "80", "$binary" : "VXBwZXJDbGFzcw==" } }
Persisting Data
Deserialization from BSON
Persisting Data


Deserialization from BSON

For compound types, there are three data types:

root

refers to the top-level BSON document only

document

refers to embedded BSON documents only

array

refers to a BSON array

Each of those three data types can be mapped against different PHP types. The possible mapping values are:

not set or NULL (the is the default)

  • A BSON array will be deserialized as a PHP array.

  • A BSON document (root or embedded) without a __pclass property [1] becomes a PHP stdClass object, with each BSON document key set as a public stdClass property.

  • A BSON document (root or embedded) with a __pclass property [1] becomes a PHP object of the class name as defined by the __pclass property.

    If the named class implements the MongoDB\BSON\Persistable interface, then the properties of the BSON document, including the __pclass property, are sent as an associative array to the MongoDB\BSON\Unserializable::bsonUnserialize() function to initialise the object's properties.

    If the named class does not exist or does not implement the MongoDB\BSON\Persistable interface, stdClass will be used and each BSON document key (including __pclass) will be set as a public stdClass property.

"array"

Turns a BSON array or BSON document into a PHP array. There will be no special treatment of a __pclass property [1], but it may be set as an element in the returned array if it was present in the BSON document.

"object" or "stdClass"

Turns a BSON array or BSON document into a stdClass object. There will be no special treatment of a __pclass property [1], but it may be set as a public property in the returned object if it was present in the BSON document.

any other string

Defines the class name that the BSON array or BSON object should be deserialized as. For BSON objects that include __pclass properties, that class will take priority.

If the named class does not exist, is not concrete (i.e. it is abstract or an interface), or does not implement MongoDB\BSON\Unserializable then an MongoDB\Driver\Exception\InvalidArgumentException exception is thrown.

If the BSON object has a __pclass property and that class exists and implements MongoDB\BSON\Persistable it will supersede the class provided in the type map.

The properties of the BSON document, including the __pclass property if it exists, will be sent as an associative array to the MongoDB\BSON\Unserializable::bsonUnserialize() function to initialise the object's properties.

TypeMaps

TypeMaps can be set through the MongoDB\Driver\Cursor::setTypeMap() method on a MongoDB\Driver\Cursor object, or the $typeMap argument of MongoDB\BSON\toPHP(). Each of the three classes (root, document and array) can be individually set.

If the value in the map is NULL, it means the same as the default value for that item.

Examples

These examples use the following classes:

MyClass

which does not implement any interface

YourClass

which implements MongoDB\BSON\Unserializable

OurClass

which implements MongoDB\BSON\Persistable

TheirClass

which extends OurClass

The MongoDB\BSON\Unserializable::bsonUnserialize() method of YourClass, OurClass, TheirClass iterate over the array and set the properties without modifications. It also sets the $unserialized property to true:

<?php

function bsonUnserialize( array $map )
{
    foreach ( $map as $k => $value )
    {
        $this->$k = $value;
    }
    $this->unserialized = true;
}

/* typemap: [] (all defaults) */
{ "foo": "yes", "bar" : false }
  -> stdClass { $foo => 'yes', $bar => false }

{ "foo": "no", "array" : [ 5, 6 ] }
  -> stdClass { $foo => 'no', $array => [ 5, 6 ] }

{ "foo": "no", "obj" : { "embedded" : 3.14 } }
  -> stdClass { $foo => 'no', $obj => stdClass { $embedded => 3.14 } }

{ "foo": "yes", "__pclass": "MyClass" }
  -> stdClass { $foo => 'yes', $__pclass => 'MyClass' }

{ "foo": "yes", "__pclass": { "$type" : "80", "$binary" : "MyClass" } }
  -> stdClass { $foo => 'yes', $__pclass => Binary(0x80, 'MyClass') }

{ "foo": "yes", "__pclass": { "$type" : "80", "$binary" : "YourClass") }
  -> stdClass { $foo => 'yes', $__pclass => Binary(0x80, 'YourClass') }

{ "foo": "yes", "__pclass": { "$type" : "80", "$binary" : "OurClass") }
  -> OurClass { $foo => 'yes', $__pclass => Binary(0x80, 'OurClass'), $unserialized => true }

{ "foo": "yes", "__pclass": { "$type" : "44", "$binary" : "YourClass") }
  -> stdClass { $foo => 'yes', $__pclass => Binary(0x44, 'YourClass') }

/* typemap: [ "root" => "MissingClass" ] */
{ "foo": "yes" }
  -> MongoDB\Driver\Exception\InvalidArgumentException("MissingClass does not exist")

/* typemap: [ "root" => "MyClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MyClass" } }
  -> MongoDB\Driver\Exception\InvalidArgumentException("MyClass does not implement Unserializable interface")

/* typemap: [ "root" => "MongoDB\BSON\Unserializable" ] */
{ "foo": "yes" }
  -> MongoDB\Driver\Exception\InvalidArgumentException("Unserializable is not a concrete class")

/* typemap: [ "root" => "YourClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MongoDB\BSON\Unserializable" } }
  -> YourClass { $foo => "yes", $__pclass => Binary(0x80, "MongoDB\BSON\Unserializable"), $unserialized => true }

/* typemap: [ "root" => "YourClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MyClass" } }
  -> YourClass { $foo => "yes", $__pclass => Binary(0x80, "MyClass"), $unserialized => true }

/* typemap: [ "root" => "YourClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "OurClass" } }
  -> OurClass { $foo => "yes", $__pclass => Binary(0x80, "OurClass"), $unserialized => true }

/* typemap: [ "root" => "YourClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "TheirClass" } }
  -> TheirClass { $foo => "yes", $__pclass => Binary(0x80, "TheirClass"), $unserialized => true }

/* typemap: [ "root" => "OurClass" ] */
{ foo: "yes", "__pclass" : { "$type": "80", "$binary": "TheirClass" } }
  -> TheirClass { $foo => "yes", $__pclass => Binary(0x80, "TheirClass"), $unserialized => true }

/* typemap: [ 'root' => 'YourClass' ] */
{ foo: "yes", "__pclass" : { "$type": "80", "$binary": "YourClass" } }
  -> YourClass { $foo => 'yes', $__pclass => Binary(0x80, 'YourClass'), $unserialized => true }

/* typemap: [ 'root' => 'array', 'document' => 'array' ] */
{ "foo": "yes", "bar" : false }
  -> [ "foo" => "yes", "bar" => false ]

{ "foo": "no", "array" : [ 5, 6 ] }
  -> [ "foo" => "no", "array" => [ 5, 6 ] ]

{ "foo": "no", "obj" : { "embedded" : 3.14 } }
  -> [ "foo" => "no", "obj" => [ "embedded => 3.14 ] ]

{ "foo": "yes", "__pclass": "MyClass" }
  -> [ "foo" => "yes", "__pclass" => "MyClass" ]

{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MyClass" } }
  -> [ "foo" => "yes", "__pclass" => Binary(0x80, "MyClass") ]

{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "OurClass" } }
  -> [ "foo" => "yes", "__pclass" => Binary(0x80, "OurClass") ]

/* typemap: [ 'root' => 'object', 'document' => 'object' ] */
{ "foo": "yes", "__pclass": { "$type": "80", "$binary": "MyClass" } }
  -> stdClass { $foo => "yes", "__pclass" => Binary(0x80, "MyClass") }

Serialization to BSON
Security
Persisting Data


Security

  • Request Injection Attacks
  • Script Injection Attacks
Deserialization from BSON
Request Injection Attacks
MongoDB


Request Injection Attacks

If you are passing $_GET (or $_POST) parameters to your queries, make sure that they are cast to strings first. Users can insert associative arrays in GET and POST 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 creates the query $q = new \MongoDB\Driver\Query( [ '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 $q = new \MongoDB\Driver\Query( [ 'username' => [ '$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 and $_POST parameters are the type you expect before you send them to the database. PHP has the filter_var() function to assist with this.

Note that this type of attack can be used with any database interaction that locates a document, including updates, upserts, deletes, and findAndModify commands.

See » the main documentation for more information about SQL-injection-like issues with MongoDB.

Security
Script Injection Attacks
Security


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 MongoDB\BSON\Javascript, not interpolated into the JavaScript string. This can come up when using $where clauses in queries, mapReduce and group commands, and any other time you may pass JavaScript into the database.

For example, suppose we have some JavaScript to greet a user in the database logs. We could do:

<?php
$m = new MongoDB\Driver\Manager;

// Don't do this!!!
$username = $_GET['field'];

$cmd = new \MongoDB\Driver\Command( [
    'eval' => "print('Hello, $username!');"
] );

$r = $m->executeCommand( 'dramio', $cmd );
?>

However, what if a malicious user passes in some JavaScript?

<?php
$m = new MongoDB\Driver\Manager;

// Don't do this!!!
$username = $_GET['field'];
// $username is set to "'); db.users.drop(); print('"

$cmd = new \MongoDB\Driver\Command( [
    'eval' => "print('Hello, $username!');"
] );

$r = $m->executeCommand( 'dramio', $cmd );
?>

Now MongoDB executes the JavaScript string "print('Hello, '); db.users.drop(); print('!');". This attack is easy to avoid: use args to pass variables from PHP to JavaScript:

<?php
$m = new MongoDB\Driver\Manager;

$_GET['field'] = 'derick';
$args = [ $_GET['field'] ];

$cmd = new \MongoDB\Driver\Command( [
    'eval' => "function greet(username) { print('Hello, ' + username + '!'); }",
    'args' => $args,
] );

$r = $m->executeCommand( 'dramio', $cmd );
?>

This adds an argument to the JavaScript scope, which gets used as argument for the greet function. Now if someone tries to send malicious code, MongoDB will harmlessly print Hello, '); db.dropDatabase(); print('!.

Using arguments helps to 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! It is best to avoid executing any JavaScript on the server in the first place.

You are strongly recommended to stay clear of the » $where clause with queries, as it impacts performance significantly. Where possible, use either normal query operators, or the » Aggregation Framework.

As alternative to » MapReduce, which uses JavaScript, consider using the » Aggregation Framework. Unlike Map/Reduce, it uses an idiomatic language to construct queries, without having to write, and use, the slower JavaScript approach that Map/Reduce requires.

The » eval command has been deprecated since MongoDB 3.0, and should also be avoided.

Request Injection Attacks
MongoDB\Driver
Security


Clasele driver-ului MongoDB

  • MongoDB\Driver\Manager — The MongoDB\Driver\Manager class
    • MongoDB\Driver\Manager::__construct — Create new MongoDB Manager
    • MongoDB\Driver\Manager::executeBulkWrite — Execute one or more write operations
    • MongoDB\Driver\Manager::executeCommand — Execute a database command
    • MongoDB\Driver\Manager::executeQuery — Execute a database query
    • MongoDB\Driver\Manager::getReadConcern — Return the ReadConcern for the Manager
    • MongoDB\Driver\Manager::getReadPreference — Return the ReadPreference for the Manager
    • MongoDB\Driver\Manager::getServers — Return the servers to which this manager is connected
    • MongoDB\Driver\Manager::getWriteConcern — Return the WriteConcern for the Manager
    • MongoDB\Driver\Manager::selectServer — Select a server matching a read preference
  • MongoDB\Driver\Command — The MongoDB\Driver\Command class
    • MongoDB\Driver\Command::__construct — Create a new Command
  • MongoDB\Driver\Query — The MongoDB\Driver\Query class
    • MongoDB\Driver\Query::__construct — Construct new Query
  • MongoDB\Driver\BulkWrite — The MongoDB\Driver\BulkWrite class
    • MongoDB\Driver\BulkWrite::__construct — Create a new BulkWrite
    • MongoDB\Driver\BulkWrite::count — Count number of write operations in the bulk
    • MongoDB\Driver\BulkWrite::delete — Add a delete operation to the bulk
    • MongoDB\Driver\BulkWrite::insert — Add an insert operation to the bulk
    • MongoDB\Driver\BulkWrite::update — Add an update operation to the bulk
  • MongoDB\Driver\WriteConcern — The MongoDB\Driver\WriteConcern class
    • MongoDB\Driver\WriteConcern::bsonSerialize — Returns an object for BSON serialization
    • MongoDB\Driver\WriteConcern::__construct — Construct immutable WriteConcern
    • MongoDB\Driver\WriteConcern::getJournal — Returns the WriteConcern's "journal" option
    • MongoDB\Driver\WriteConcern::getW — Returns the WriteConcern's "w" option
    • MongoDB\Driver\WriteConcern::getWtimeout — Returns the WriteConcern's "wtimeout" option
  • MongoDB\Driver\ReadPreference — The MongoDB\Driver\ReadPreference class
    • MongoDB\Driver\ReadPreference::bsonSerialize — Returns an object for BSON serialization
    • MongoDB\Driver\ReadPreference::__construct — Construct immutable ReadPreference
    • MongoDB\Driver\ReadPreference::getMaxStalenessSeconds — Returns the ReadPreference's "maxStalenessSeconds" option
    • MongoDB\Driver\ReadPreference::getMode — Returns the ReadPreference's "mode" option
    • MongoDB\Driver\ReadPreference::getTagSets — Returns the ReadPreference's "tagSets" option
  • MongoDB\Driver\ReadConcern — The MongoDB\Driver\ReadConcern class
    • MongoDB\Driver\ReadConcern::bsonSerialize — Returns an object for BSON serialization
    • MongoDB\Driver\ReadConcern::__construct — Construct immutable ReadConcern
    • MongoDB\Driver\ReadConcern::getLevel — Returns the ReadConcern's "level" option
  • MongoDB\Driver\Cursor — The MongoDB\Driver\Cursor class
    • MongoDB\Driver\Cursor::__construct — Create a new Cursor (not used)
    • MongoDB\Driver\Cursor::getId — Returns the ID for this cursor
    • MongoDB\Driver\Cursor::getServer — Returns the server associated with this cursor
    • MongoDB\Driver\Cursor::isDead — Checks if the cursor is still open on the server
    • MongoDB\Driver\Cursor::setTypeMap — Sets a type map to use for BSON unserialization
    • MongoDB\Driver\Cursor::toArray — Returns an array containing all results for this cursor
  • MongoDB\Driver\CursorId — The MongoDB\Driver\CursorId class
    • MongoDB\Driver\CursorId::__construct — Create a new CursorId (not used)
    • MongoDB\Driver\CursorId::__toString — String representation of the cursor ID
  • MongoDB\Driver\Server — The MongoDB\Driver\Server class
    • MongoDB\Driver\Server::__construct — Create a new Server (not used)
    • MongoDB\Driver\Server::executeBulkWrite — Execute one or more write operations on this server
    • MongoDB\Driver\Server::executeCommand — Execute a database command on this server
    • MongoDB\Driver\Server::executeQuery — Execute a database query on this server
    • MongoDB\Driver\Server::getHost — Returns the hostname of this server
    • MongoDB\Driver\Server::getInfo — Returns an array of information about this server
    • MongoDB\Driver\Server::getLatency — Returns the latency of this server
    • MongoDB\Driver\Server::getPort — Returns the port on which this server is listening
    • MongoDB\Driver\Server::getTags — Returns an array of tags describing this server in a replica set
    • MongoDB\Driver\Server::getType — Returns an integer denoting the type of this server
    • MongoDB\Driver\Server::isArbiter — Checks if this server is an arbiter member of a replica set
    • MongoDB\Driver\Server::isHidden — Checks if this server is a hidden member of a replica set
    • MongoDB\Driver\Server::isPassive — Checks if this server is a passive member of a replica set
    • MongoDB\Driver\Server::isPrimary — Checks if this server is a primary member of a replica set
    • MongoDB\Driver\Server::isSecondary — Checks if this server is a secondary member of a replica set
  • MongoDB\Driver\WriteConcernError — The MongoDB\Driver\WriteConcernError class
    • MongoDB\Driver\WriteConcernError::getCode — Returns the WriteConcernError's error code
    • MongoDB\Driver\WriteConcernError::getInfo — Returns additional metadata for the WriteConcernError
    • MongoDB\Driver\WriteConcernError::getMessage — Returns the WriteConcernError's error message
  • MongoDB\Driver\WriteError — The MongoDB\Driver\WriteError class
    • MongoDB\Driver\WriteError::getCode — Returns the WriteError's error code
    • MongoDB\Driver\WriteError::getIndex — Returns the index of the write operation corresponding to this WriteError
    • MongoDB\Driver\WriteError::getInfo — Returns additional metadata for the WriteError
    • MongoDB\Driver\WriteError::getMessage — Returns the WriteError's error message
  • MongoDB\Driver\WriteResult — The MongoDB\Driver\WriteResult class
    • MongoDB\Driver\WriteResult::getDeletedCount — Returns the number of documents deleted
    • MongoDB\Driver\WriteResult::getInsertedCount — Returns the number of documents inserted (excluding upserts)
    • MongoDB\Driver\WriteResult::getMatchedCount — Returns the number of documents selected for update
    • MongoDB\Driver\WriteResult::getModifiedCount — Returns the number of existing documents updated
    • MongoDB\Driver\WriteResult::getServer — Returns the server associated with this write result
    • MongoDB\Driver\WriteResult::getUpsertedCount — Returns the number of documents inserted by an upsert
    • MongoDB\Driver\WriteResult::getUpsertedIds — Returns an array of identifiers for upserted documents
    • MongoDB\Driver\WriteResult::getWriteConcernError — Returns any write concern error that occurred
    • MongoDB\Driver\WriteResult::getWriteErrors — Returns any write errors that occurred
    • MongoDB\Driver\WriteResult::isAcknowledged — Returns whether the write was acknowledged
Script Injection Attacks
MongoDB\Driver\Manager
MongoDB


The MongoDB\Driver\Manager class

(mongodb >=1.0.0)

Introducere

The MongoDB\Driver\Manager is the main entry point to the extension. It is responsible for maintaining connections to MongoDB (be it standalone server, replica set, or sharded cluster).

No connection to MongoDB is made upon instantiating the Manager. This means the MongoDB\Driver\Manager can always be constructed, even though one or more MongoDB servers are down.

Any write or query can throw connection exceptions as connections are created lazily. A MongoDB server may also become unavailable during the life time of the script. It is therefore important that all actions on the Manager to be wrapped in try/catch statements.

Sinopsisul clasei

final MongoDB\Driver\Manager {
/* Metode */
 final public __construct
  ([ string $uri = "mongodb://127.0.0.1/
 [, array $uriOptions = []
 [, array $driverOptions = []
]]] )
final public MongoDB\Driver\WriteResult executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, MongoDB\Driver\WriteConcern $writeConcern ] )
final public MongoDB\Driver\Cursor executeCommand ( string $db , MongoDB\Driver\Command $command [, MongoDB\Driver\ReadPreference $readPreference ] )
final public MongoDB\Driver\Cursor executeQuery ( string $namespace , MongoDB\Driver\Query $query [, MongoDB\Driver\ReadPreference $readPreference ] )
final public MongoDB\Driver\ReadConcern getReadConcern ( void )
final public MongoDB\Driver\ReadPreference getReadPreference ( void )
final public array getServers ( void )
final public MongoDB\Driver\WriteConcern getWriteConcern ( void )
final public MongoDB\Driver\Server selectServer ( MongoDB\Driver\ReadPreference $readPreference )
}

Exemple

Example #1 MongoDB\Driver\Manager::__construct() basic example

var_dump()ing a MongoDB\Driver\Manager will print out various details about the manager that are otherwise not normally exposed. This can be useful to debug how the driver views your MongoDB setup, and which options are used.

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
var_dump($manager);

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(MongoDB\Driver\Manager)#1 (3) {
  ["request_id"]=>
  int(1714636915)
  ["uri"]=>
  string(25) "mongodb://localhost:27017"
  ["cluster"]=>
  array(13) {
    ["mode"]=>
    string(6) "direct"
    ["state"]=>
    string(4) "born"
    ["request_id"]=>
    int(0)
    ["sockettimeoutms"]=>
    int(300000)
    ["last_reconnect"]=>
    int(0)
    ["uri"]=>
    string(25) "mongodb://localhost:27017"
    ["requires_auth"]=>
    int(0)
    ["nodes"]=>
    array(...)
    ["max_bson_size"]=>
    int(16777216)
    ["max_msg_size"]=>
    int(50331648)
    ["sec_latency_ms"]=>
    int(15)
    ["peers"]=>
    array(0) {
    }
    ["replSet"]=>
    NULL
  }
}

Cuprins

  • MongoDB\Driver\Manager::__construct — Create new MongoDB Manager
  • MongoDB\Driver\Manager::executeBulkWrite — Execute one or more write operations
  • MongoDB\Driver\Manager::executeCommand — Execute a database command
  • MongoDB\Driver\Manager::executeQuery — Execute a database query
  • MongoDB\Driver\Manager::getReadConcern — Return the ReadConcern for the Manager
  • MongoDB\Driver\Manager::getReadPreference — Return the ReadPreference for the Manager
  • MongoDB\Driver\Manager::getServers — Return the servers to which this manager is connected
  • MongoDB\Driver\Manager::getWriteConcern — Return the WriteConcern for the Manager
  • MongoDB\Driver\Manager::selectServer — Select a server matching a read preference
MongoDB\Driver
MongoDB\Driver\Manager::__construct
MongoDB\Driver


Create new MongoDB Manager

MongoDB\Driver\Manager
MongoDB\Driver\Manager::executeBulkWrite
MongoDB\Driver\Manager
PHP Manual

MongoDB\Driver\Manager::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Manager::__construct — Create new MongoDB Manager

Descrierea

 final public MongoDB\Driver\Manager::__construct
  ([ string $uri = "mongodb://127.0.0.1/
 [, array $uriOptions = []
 [, array $driverOptions = []
]]] )

Constructs a new MongoDB\Driver\Manager object with the specified options.

Nota: Per the » Server Discovery and Monitoring Specification, this constructor performs no I/O. Connections will be initialized on demand, when the first operation is executed.

Sfat

On Unix platforms, the MongoDB driver is sensitive to scripts that use the fork() system call without also calling exec(). Users are advised not to re-use MongoDB\Driver\Manager instances in a forked child process.

Parametri

uri

A » mongodb:// connection URI:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

For details on supported options, see » Connection String Options in the MongoDB manual. » Connection pool options are not supported, as the PHP driver does not implement connection pools.

The uri is a URL, hence any special characters in its components need to be URL encoded according to » RFC 3986. This is particularly relevant to the username and password, which can often include special characters such as @, :, or %. When connecting via a Unix domain socket, the socket path may contain special characters such as slashes and must be encoded. The rawurlencode() function may be used to encode constituent parts of the URI.

uriOptions

Additional » connection string options, which will overwrite any options with the same name in the uri parameter.

Nota: The "authMechanism" and "authMechanismProperties" options are not supported in uriOptions and must be specified in the uri parameter. For additional details, see » Authentication Options in the MongoDB manual and the » Driver Authentication Specification.

uriOptions
Option | Type | Description
appname string

MongoDB 3.4+ has the ability to annotate connections with metadata provided by the connecting client. This metadata is included in the server's logs upon establishing a connection and also recorded in slow query logs when database profiling is enabled.

This option may be used to specify an application name, which will be included in the metadata. The value cannot exceed 128 characters in length.

authSource string

The database name associated with the user's credentials. Defaults to the database component of the connection URI.

For authentication mechanisms that delegate credential storage to other services (e.g. GSSAPI), this should be "$external".

canonicalizeHostname boolean

If TRUE, the driver will resolve the real hostname for the server IP address before authenticating via SASL. Some underlying GSSAPI layers already do this, but the functionality may be disabled in their config (e.g. krb.conf). Defaults to FALSE.

connectTimeoutMS integer

The time in milliseconds to attempt a connection before timing out. Defaults to 10,000 milliseconds.

gssapiServiceName string

Set the Kerberos service name when connecting to Kerberized MongoDB instances. This value must match the service name set on MongoDB instances (i.e. » saslServiceName server parameter). Defaults to "mongodb".

heartbeatFrequencyMS integer

Specifies the interval in milliseconds between the driver's checks of the MongoDB topology, counted from the end of the previous check until the beginning of the next one. Defaults to 60,000 milliseconds.

Per the » Server Discovery and Monitoring Specification, this value cannot be less than 500 milliseconds.

journal boolean

Corresponds to the write concern's journal parameter. If TRUE, writes will require acknowledgement from MongoDB that the operation has been written to the journal. For details, see MongoDB\Driver\WriteConcern.

localThresholdMS integer

The size in milliseconds of the latency window for selecting among multiple suitable MongoDB instances while resolving a read preference. Defaults to 15 milliseconds.

maxStalenessSeconds integer

Corresponds to the read preference's "maxStalenessSeconds". Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. By default, there is no maximum staleness and clients will not consider a secondary’s lag when choosing where to direct a read operation. For details, see MongoDB\Driver\ReadPreference.

If specified, the max staleness must be a signed 32-bit integer greater than or equal to MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS (i.e. 90 seconds).

password | string | The password for the user being authenticated. This option is useful if the password contains special characters, which would otherwise need to be URL encoded for the connection URI.
readConcernLevel | string | Corresponds to the read concern's level parameter. Specifies the level of read isolation. For details, see MongoDB\Driver\ReadConcern.
readPreference string

Corresponds to the read preferences's mode parameter. Defaults to "primary". For details, see MongoDB\Driver\ReadPreference.

Nota: This accepts a string value (e.g. "primary", "secondaryPreferred"), unlike MongoDB\Driver\ReadPreference::__construct(), which takes an integer.

readPreferenceTags array

Corresponds to the read preferences's tagSets parameter. Tag sets allow you to target read operations to specific members of a replica set. For details, see MongoDB\Driver\ReadPreference.

Nota: When not specified in the URI string, this option is expressed as an array consistent with the format expected by MongoDB\Driver\ReadPreference::__construct().

replicaSet string

Specifies the name of the replica set.

safe boolean

Specifies 1 for the write concern if TRUE, or 0 if FALSE For details, see MongoDB\Driver\WriteConcern.

This option is deprecated and should not be used.

serverSelectionTimeoutMS integer

Specifies how long in milliseconds to block for server selection before throwing an exception. Defaults to 30,000 milliseconds.

serverSelectionTryOnce boolean

When TRUE, instructs the driver to scan the MongoDB deployment exactly once after server selection fails and then either select a server or raise an error. When FALSE, the driver blocks and searches for a server up to the "serverSelectionTimeoutMS" value. Defaults to TRUE.

slaveOk boolean

Specifies "secondaryPreferred" for the read preference mode if TRUE. For details, see MongoDB\Driver\ReadPreference.

This option is deprecated and should not be used.

socketCheckIntervalMS integer

If a socket has not been used recently, the driver must check it via an isMaster command before using it for any operation. Defaults to 5,000 milliseconds.

socketTimeoutMS integer

The time in milliseconds to attempt a send or receive on a socket before timing out. Defaults to 300,000 milliseconds (i.e. five minutes).

ssl boolean

Initiates the connection with TLS/SSL if TRUE. Defaults to FALSE.

username | string | The username for the user being authenticated. This option is useful if the username contains special characters, which would otherwise need to be URL encoded for the connection URI.
w integer|string

Corresponds to the write concern's w parameter. For details, see MongoDB\Driver\WriteConcern.

wTimeoutMS integer|string

Corresponds to the write concern's wtimeout parameter. Specifies a time limit, in milliseconds, for the write concern. For details, see MongoDB\Driver\WriteConcern.

driverOptions

driverOptions
Option | Type | Description
allow_invalid_hostname bool

Disables hostname validation if TRUE. Defaults to FALSE.

Allowing invalid hostnames may expose the driver to a » man-in-the-middle attack.

ca_dir string

Path to a correctly hashed certificate directory. The system certificate store will be used by default.

Falls back to the deprecated "capath" SSL context option if not specified.

ca_file string

Path to a certificate authority file. The system certificate store will be used by default.

Falls back to the deprecated "cafile" SSL context option if not specified.

crl_file | string | Path to a certificate revocation list file.
pem_file string

Path to a PEM encoded certificate to use for client authentication.

Falls back to the deprecated "local_cert" SSL context option if not specified.

pem_pwd string

Passphrase for the PEM encoded certificate (if applicable).

Falls back to the deprecated "passphrase" SSL context option if not specified.

context resource

SSL context options to be used as fallbacks for other driver options (as specified). Note that the driver does not consult the default stream context.

This option is supported for backwards compatibility, but should be considered deprecated.

weak_cert_validation bool

Disables certificate validation if TRUE. Defaults to FALSE

Falls back to the deprecated "allow_self_signed" SSL context option if not specified.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Throws MongoDB\Driver\Exception\RuntimeException if the uri format is invalid

Istoricul schimbarilor

Versiune Descriere
1.2.0

The uri argument defaults to "mongodb://127.0.0.1/". The default port remains 27017.

Added the "appname" URI option.

Added the "allow_invalid_hostname", "ca_file", "ca_dir", "clr_file", "pem_file", "pem_pwd", and "weak_cert_validation" driver options.

The PHP Streams API is no longer used for socket communication. The "connectTimeoutMS" URI option now defaults to 10 seconds instead of default_socket_timeout in previous versions. Additionally, the driver no longer supports all SSL context options via the "context" driver option.

1.1.0

The uri argument is optional and defaults to "mongodb://localhost:27017/".

Exemple

Example #1 MongoDB\Driver\Manager::__construct() basic examples

Connecting to standalone MongoDB node:

<?php

$manager = new MongoDB\Driver\Manager("mongodb://example.com:27017");

?>

Connecting to standalone MongoDB node via a Unix domain socket. The socket path may include special characters such as slashes and should be encoded with rawurlencode().

<?php

$manager = new MongoDB\Driver\Manager("mongodb://" . rawurlencode("/tmp/mongodb-27017.sock"));

?>

Connecting to a replica set:

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

?>

Connecting to a sharded cluster (i.e. one or more mongos instances):

<?php

$manager = new MongoDB\Driver\Manager("mongodb://mongos1.example.com,mongos2.example.com/");

?>

Connecting to MongoDB with authentication credentials for a particular user and database:

<?php

$manager = new MongoDB\Driver\Manager("mongodb://myusername:mypassword@example.com/mydatabase");

?>

Connecting to MongoDB with authentication credentials for a particular user and database, where the username or password includes special characters (e.g. @, :, %). In the following example, the password string myp@ss:w%rd has been manually escaped; however, rawurlencode() may also be used to escape URI components that may contain special characters.

<?php

$manager = new MongoDB\Driver\Manager("mongodb://myusername:myp%40ss%3Aw%25rd@example.com/mydatabase");

?>

Connecting to MongoDB with X509 authentication:

<?php

$manager = new MongoDB\Driver\Manager(
    "mongodb://example.com/?ssl=true&authMechanism=MONGODB-X509",
    [],
    [
        "pem_file" => "/path/to/client.pem",
    ]
);
?>

A se vedea ?i

  • Connection handling and persistence
  • » MongoDB Connection String Format
MongoDB\Driver\Manager
MongoDB\Driver\Manager::executeBulkWrite
MongoDB\Driver\Manager


Execute one or more write operations

MongoDB\Driver\Manager::__construct
MongoDB\Driver\Manager::executeCommand
MongoDB\Driver\Manager
PHP Manual

MongoDB\Driver\Manager::executeBulkWrite

(mongodb >=1.0.0)

MongoDB\Driver\Manager::executeBulkWrite — Execute one or more write operations

Descrierea

final public MongoDB\Driver\WriteResult MongoDB\Driver\Manager::executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, MongoDB\Driver\WriteConcern $writeConcern ] )

Executes one or more write operations on the primary server.

A MongoDB\Driver\BulkWrite can be constructed with one or more write operations of varying types (e.g. updates, deletes, and inserts). The driver will attempt to send operations of the same type to the server in as few requests as possible to optimize round trips.

Parametri

namespace (string)

Un spa?iu de nume complet calificat (de ex. "databaseName.collectionName").

bulk (MongoDB\Driver\BulkWrite)

MongoDB\Driver\BulkWrite spre a fi executata.

writeConcern (MongoDB\Driver\WriteConcern)

Op?ional un MongoDB\Driver\WriteConcern pentru a fi aplicat la opera?iunea de înscrieire. Daca nu este indicat vre-unul, va fi utilizat "write concern" din MongoDB Connection URI.

Valorile întoarse

Întoarce MongoDB\Driver\WriteResult în caz de succes.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\BulkWriteException la orice e?ec de înscriere (de ex. eroare de înscriere, e?ec la aplicarea unui "write concern")
  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Emite MongoDB\Driver\Exception\ConnectionException daca conexiunea catre server e?ueaza (din alte motive decât autentificarea).
  • Emite MongoDB\Driver\Exception\AuthenticationException daca este necesara autentificare ?i aceasta e?ueaza.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

Exemple

Example #1 MongoDB\Driver\Manager::executeBulkWrite() example

<?php

$bulk = new MongoDB\Driver\BulkWrite();

$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);

$bulk->update(['x' => 2], ['$set' => ['x' => 1]], ['multi' => false, 'upsert' => false]);
$bulk->update(['x' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);
$bulk->update(['_id' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);

$bulk->insert(['_id' => 4, 'x' => 2]);

$bulk->delete(['x' => 1], ['limit' => 1]);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
$result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);

printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Matched  %d document(s)\n", $result->getMatchedCount());
printf("Updated  %d document(s)\n", $result->getModifiedCount());
printf("Upserted %d document(s)\n", $result->getUpsertedCount());
printf("Deleted  %d document(s)\n", $result->getDeletedCount());

foreach ($result->getUpsertedIds() as $index => $id) {
    printf('upsertedId[%d]: ', $index);
    var_dump($id);
}

/* If the WriteConcern could not be fulfilled */
if ($writeConcernError = $result->getWriteConcernError()) {
    printf("%s (%d): %s\n", $writeConcernError->getMessage(), $writeConcernError->getCode(), var_export($writeConcernError->getInfo(), true));
}

/* If a write could not happen at all */
foreach ($result->getWriteErrors() as $writeError) {
    printf("Operation#%d: %s (%d)\n", $writeError->getIndex(), $writeError->getMessage(), $writeError->getCode());
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Inserted 3 document(s)
Matched  1 document(s)
Updated  1 document(s)
Upserted 2 document(s)
Deleted  1 document(s)
upsertedId[3]: object(MongoDB\BSON\ObjectID)#5 (1) {
  ["oid"]=>
  string(24) "54d3adc3ce7a792f4d703756"
}
upsertedId[4]: int(3)

A se vedea ?i

  • MongoDB\Driver\BulkWrite
  • MongoDB\Driver\WriteResult
  • MongoDB\Driver\WriteConcern
  • MongoDB\Driver\Server::executeBulkWrite() - Execute one or more write operations on this server
MongoDB\Driver\Manager::__construct
MongoDB\Driver\Manager::executeCommand
MongoDB\Driver\Manager


Execute a database command

MongoDB\Driver\Manager::executeBulkWrite
MongoDB\Driver\Manager::executeQuery
MongoDB\Driver\Manager
PHP Manual

MongoDB\Driver\Manager::executeCommand

(mongodb >=1.0.0)

MongoDB\Driver\Manager::executeCommand — Execute a database command

Descrierea

final public MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeCommand ( string $db , MongoDB\Driver\Command $command [, MongoDB\Driver\ReadPreference $readPreference ] )

Executes command on a server If readPreference is provided, it will be used for server selection; otherwise, the default read preference will be used.

Parametri

db (string)

Denumirea bazei de date asupra careia va fi executata comanda.

command (MongoDB\Driver\Command)

MongoDB\Driver\Command spre a fi executata.

readPreference (MongoDB\Driver\ReadPreference)

Op?ional o MongoDB\Driver\ReadPreference pentru a selecta serverul pentru aceasta opera?iune. Daca nu este indicata vre-una, va fi utilizata preferin?a de citire din MongoDB Connection URI.

Valorile întoarse

Întoarce MongoDB\Driver\Cursor în caz de succes.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Emite MongoDB\Driver\Exception\ConnectionException daca conexiunea catre server e?ueaza (din alte motive decât autentificarea).
  • Emite MongoDB\Driver\Exception\AuthenticationException daca este necesara autentificare ?i aceasta e?ueaza.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command, issuing a write command to a secondary).

Exemple

Example #1 MongoDB\Driver\Manager::executeCommand() with a command returning a single result document

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$command = new MongoDB\Driver\Command(['ping' => 1]);

try {
    $cursor = $manager->executeCommand('admin', $command);
} catch(MongoDB\Driver\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

/* The ping command returns a single result document, so we need to access the
 * first result in the cursor. */
$response = $cursor->toArray()[0];

var_dump($response);

?>

Exemplul de mai sus va afi?a:

array(1) {
  ["ok"]=>
  float(1)
}

Example #2 MongoDB\Driver\Manager::executeCommand() with a command returning a cursor

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1, 'y' => 'foo']);
$bulk->insert(['x' => 2, 'y' => 'bar']);
$bulk->insert(['x' => 3, 'y' => 'bar']);
$manager->executeBulkWrite('db.collection', $bulk);

$command = new MongoDB\Driver\Command([
    'aggregate' => 'collection',
    'pipeline' => [
        ['$group' => ['_id' => '$y', 'sum' => ['$sum' => '$x']]],
    ],
    'cursor' => new stdClass,
]);
$cursor = $manager->executeCommand('db', $command);

/* The aggregate command can optionally return its results in a cursor instead
 * of a single result document. In this case, we can iterate on the cursor
 * directly to access those results. */
foreach ($cursor as $document) {
    var_dump($document);
}

?>

Exemplul de mai sus va afi?a:

object(stdClass)#6 (2) {
  ["_id"]=>
  string(3) "bar"
  ["sum"]=>
  int(10)
}
object(stdClass)#7 (2) {
  ["_id"]=>
  string(3) "foo"
  ["sum"]=>
  int(2)
}

Note

Nota:

This method does not take a MongoDB\Driver\WriteConcern parameter. For write commands (e.g. » findAndModify in MongoDB 3.2+), the write concern should be included in the command document itself.

If a secondary readPreference is used, it is the caller's responsibility to ensure that the command can be executed on a secondary. No validation is done by the driver.

A se vedea ?i

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\ReadPreference
  • MongoDB\Driver\Server::executeCommand() - Execute a database command on this server
MongoDB\Driver\Manager::executeBulkWrite
MongoDB\Driver\Manager::executeQuery
MongoDB\Driver\Manager


Execute a database query

MongoDB\Driver\Manager::executeCommand
MongoDB\Driver\Manager::getReadConcern
MongoDB\Driver\Manager
PHP Manual

MongoDB\Driver\Manager::executeQuery

(mongodb >=1.0.0)

MongoDB\Driver\Manager::executeQuery — Execute a database query

Descrierea

final public MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeQuery ( string $namespace , MongoDB\Driver\Query $query [, MongoDB\Driver\ReadPreference $readPreference ] )

Executes query on a server. If readPreference is provided, it will be used for server selection; otherwise, the default read preference will be used.

Parametri

namespace (string)

Un spa?iu de nume complet calificat (de ex. "databaseName.collectionName").

query (MongoDB\Driver\Query)

MongoDB\Driver\Query spre a fi executata.

readPreference (MongoDB\Driver\ReadPreference)

Op?ional o MongoDB\Driver\ReadPreference pentru a selecta serverul pentru aceasta opera?iune. Daca nu este indicata vre-una, va fi utilizata preferin?a de citire din MongoDB Connection URI.

Valorile întoarse

Întoarce MongoDB\Driver\Cursor în caz de succes.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Emite MongoDB\Driver\Exception\ConnectionException daca conexiunea catre server e?ueaza (din alte motive decât autentificarea).
  • Emite MongoDB\Driver\Exception\AuthenticationException daca este necesara autentificare ?i aceasta e?ueaza.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid query operators).

Exemple

Example #1 MongoDB\Driver\Manager::executeQuery() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$filter = ['x' => ['$gt' => 1]];
$options = [
    'projection' => ['_id' => 0],
    'sort' => ['x' => -1],
];

$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('db.collection', $query);

foreach ($cursor as $document) {
    var_dump($document);
}

?>

Exemplul de mai sus va afi?a:

object(stdClass)#6 (1) {
  ["x"]=>
  int(3)
}
object(stdClass)#7 (1) {
  ["x"]=>
  int(2)
}

A se vedea ?i

  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Query
  • MongoDB\Driver\ReadPreference
  • MongoDB\Driver\Server::executeQuery() - Execute a database query on this server
MongoDB\Driver\Manager::executeCommand
MongoDB\Driver\Manager::getReadConcern
MongoDB\Driver\Manager


Return the ReadConcern for the Manager

MongoDB\Driver\Manager::executeQuery
MongoDB\Driver\Manager::getReadPreference
MongoDB\Driver\Manager
PHP Manual

MongoDB\Driver\Manager::getReadConcern

(mongodb >=1.1.0)

MongoDB\Driver\Manager::getReadConcern — Return the ReadConcern for the Manager

Descrierea

final public MongoDB\Driver\ReadConcern MongoDB\Driver\Manager::getReadConcern ( void )

Returns the MongoDB\Driver\ReadConcern for the Manager, which is derived from its URI options. This is the default read concern for queries and commands executed on the Manager.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The MongoDB\Driver\ReadConcern for the Manager.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Manager::getReadConcern() example

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager->getReadConcern());

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/?readConcernLevel=local');
var_dump($manager->getReadConcern());

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(MongoDB\Driver\ReadConcern)#2 (0) {
}
object(MongoDB\Driver\ReadConcern)#1 (1) {
  ["level"]=>
  string(5) "local"
}

A se vedea ?i

  • MongoDB\Driver\ReadConcern
  • MongoDB\Driver\Manager::__construct() - Create new MongoDB Manager
MongoDB\Driver\Manager::executeQuery
MongoDB\Driver\Manager::getReadPreference
MongoDB\Driver\Manager


Return the ReadPreference for the Manager

MongoDB\Driver\Manager::getReadConcern
MongoDB\Driver\Manager::getServers
MongoDB\Driver\Manager
PHP Manual

MongoDB\Driver\Manager::getReadPreference

(mongodb >=1.0.0)

MongoDB\Driver\Manager::getReadPreference — Return the ReadPreference for the Manager

Descrierea

final public MongoDB\Driver\ReadPreference MongoDB\Driver\Manager::getReadPreference ( void )

Returns the MongoDB\Driver\ReadPreference for the Manager, which is derived from its URI options. This is the default read preference for queries and commands executed on the Manager.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The MongoDB\Driver\ReadPreference for the Manager.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Manager::getReadPreference() example

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager->getReadPreference());

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/?readPreference=secondaryPreferred&readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:ny&readPreferenceTags=');
var_dump($manager->getReadPreference());

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(MongoDB\Driver\ReadPreference)#2 (1) {
  ["mode"]=>
  string(7) "primary"
}
object(MongoDB\Driver\ReadPreference)#1 (2) {
  ["mode"]=>
  string(18) "secondaryPreferred"
  ["tags"]=>
  array(3) {
    [0]=>
    object(stdClass)#3 (2) {
      ["dc"]=>
      string(2) "ny"
      ["rack"]=>
      string(1) "1"
    }
    [1]=>
    object(stdClass)#4 (1) {
      ["dc"]=>
      string(2) "ny"
    }
    [2]=>
    object(stdClass)#5 (0) {
    }
  }
}

A se vedea ?i

  • MongoDB\Driver\ReadPreference
  • MongoDB\Driver\Manager::__construct() - Create new MongoDB Manager
MongoDB\Driver\Manager::getReadConcern
MongoDB\Driver\Manager::getServers
MongoDB\Driver\Manager


Return the servers to which this manager is connected

MongoDB\Driver\Manager::getReadPreference
MongoDB\Driver\Manager::getWriteConcern
MongoDB\Driver\Manager
PHP Manual

MongoDB\Driver\Manager::getServers

(mongodb >=1.0.0)

MongoDB\Driver\Manager::getServers — Return the servers to which this manager is connected

Descrierea

final public array MongoDB\Driver\Manager::getServers ( void )

Returns an array of MongoDB\Driver\Server instances to which this manager is connected.

Nota:

Since the driver connects to the database lazily, this method may return an empty array if called before executing an operation on the MongoDB\Driver\Manager.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array of MongoDB\Driver\Server instances to which this manager is connected.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Manager::getServers() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

/* The driver connects to the database server lazily, so Manager::getServers()
 * may initially return an empty array. */
var_dump($manager->getServers());

$command = new MongoDB\Driver\Command(['ping' => 1]);
$manager->executeCommand('db', $command);

var_dump($manager->getServers());

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(0) {
}
array(1) {
  [0]=>
  object(MongoDB\Driver\Server)#3 (10) {
    ["host"]=>
    string(9) "localhost"
    ["port"]=>
    int(27017)
    ["type"]=>
    int(1)
    ["is_primary"]=>
    bool(false)
    ["is_secondary"]=>
    bool(false)
    ["is_arbiter"]=>
    bool(false)
    ["is_hidden"]=>
    bool(false)
    ["is_passive"]=>
    bool(false)
    ["last_is_master"]=>
    array(8) {
      ["ismaster"]=>
      bool(true)
      ["maxBsonObjectSize"]=>
      int(16777216)
      ["maxMessageSizeBytes"]=>
      int(48000000)
      ["maxWriteBatchSize"]=>
      int(1000)
      ["localTime"]=>
      object(MongoDB\BSON\UTCDateTime)#4 (1) {
        ["milliseconds"]=>
        int(1447267964517)
      }
      ["maxWireVersion"]=>
      int(3)
      ["minWireVersion"]=>
      int(0)
      ["ok"]=>
      float(1)
    }
    ["round_trip_time"]=>
    int(554)
  }
}

A se vedea ?i

  • MongoDB\Driver\Server
  • MongoDB\Driver\Manager::selectServer() - Select a server matching a read preference
MongoDB\Driver\Manager::getReadPreference
MongoDB\Driver\Manager::getWriteConcern
MongoDB\Driver\Manager


Return the WriteConcern for the Manager

MongoDB\Driver\Manager::getServers
MongoDB\Driver\Manager::selectServer
MongoDB\Driver\Manager
PHP Manual

MongoDB\Driver\Manager::getWriteConcern

(mongodb >=1.0.0)

MongoDB\Driver\Manager::getWriteConcern — Return the WriteConcern for the Manager

Descrierea

final public MongoDB\Driver\WriteConcern MongoDB\Driver\Manager::getWriteConcern ( void )

Returns the MongoDB\Driver\WriteConcern for the Manager, which is derived from its URI options. This is the default write concern for writes and commands executed on the Manager.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The MongoDB\Driver\WriteConcern for the Manager.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Manager::getWriteConcern() example

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager->getWriteConcern());

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/?w=majority&wtimeoutMS=2000');
var_dump($manager->getWriteConcern());

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(MongoDB\Driver\WriteConcern)#2 (0) {
}
object(MongoDB\Driver\WriteConcern)#1 (2) {
  ["w"]=>
  string(8) "majority"
  ["wtimeout"]=>
  int(2000)
}

A se vedea ?i

  • MongoDB\Driver\WriteConcern
  • MongoDB\Driver\Manager::__construct() - Create new MongoDB Manager
MongoDB\Driver\Manager::getServers
MongoDB\Driver\Manager::selectServer
MongoDB\Driver\Manager


Select a server matching a read preference

MongoDB\Driver\Manager::getWriteConcern
MongoDB\Driver\Command
MongoDB\Driver\Manager
PHP Manual

MongoDB\Driver\Manager::selectServer

(mongodb >=1.0.0)

MongoDB\Driver\Manager::selectServer — Select a server matching a read preference

Descrierea

final public MongoDB\Driver\Server MongoDB\Driver\Manager::selectServer ( MongoDB\Driver\ReadPreference $readPreference )

Selects a MongoDB\Driver\Server matching readPreference. This may be used to preselect a server in order to perform version checking before executing an operation.

Nota:

Unlike MongoDB\Driver\Manager::getServers(), this method will initialize database connections and perform server discovery if necessary. See the » Server Selection Specification for additional information.

Parametri

readPreference (MongoDB\Driver\ReadPreference)

Op?ional o MongoDB\Driver\ReadPreference pentru a selecta serverul pentru aceasta opera?iune. Daca nu este indicata vre-una, va fi utilizata preferin?a de citire din MongoDB Connection URI.

Valorile întoarse

Returns an MongoDB\Driver\Server matching the read preference.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Emite MongoDB\Driver\Exception\ConnectionException daca conexiunea catre server e?ueaza (din alte motive decât autentificarea).
  • Emite MongoDB\Driver\Exception\AuthenticationException daca este necesara autentificare ?i aceasta e?ueaza.
  • Throws MongoDB\Driver\Exception\RuntimeException if a server matching the read preference could not be found.

A se vedea ?i

  • MongoDB\Driver\Server
  • MongoDB\Driver\Manager::getServers() - Return the servers to which this manager is connected
  • » Server Selection Specification
MongoDB\Driver\Manager::getWriteConcern
MongoDB\Driver\Command
MongoDB\Driver\Manager


The MongoDB\Driver\Command class

(mongodb >=1.0.0)

Introducere

The MongoDB\Driver\Command class is a value object that represents a database command.

To provide "Command Helpers" the MongoDB\Driver\Command object should be composed.

Sinopsisul clasei

final MongoDB\Driver\Command {
/* Metode */
final public __construct ( array|object $document )
}

Exemple

Example #1 Composing MongoDB\Driver\Command to provide a helper to create collections

<?php
class CreateCollection {
    protected $cmd = array();

    function __construct($collectionName) {
        $this->cmd["create"] = (string)$collectionName;
    }
    function setAutoIndexId($bool) {
        $this->cmd["autoIndexId"] = (bool)$bool;
    }
    function setCappedCollection($maxBytes, $maxDocuments = false) {
        $this->cmd["capped"] = true;
        $this->cmd["size"]   = (int)$maxBytes;

        if ($maxDocuments) {
            $this->cmd["max"] = (int)$maxDocuments;
        }
    }
    function usePowerOf2Sizes($bool) {
        if ($bool) {
            $this->cmd["flags"] = 1;
        } else {
            $this->cmd["flags"] = 0;
        }
    }
    function setFlags($flags) {
        $this->cmd["flags"] = (int)$flags;
    }
    function getCommand() {
        return new MongoDB\Driver\Command($this->cmd);
    }
    function getCollectionName() {
        return $this->cmd["create"];
    }
}

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$createCollection = new CreateCollection("cappedCollection");
$createCollection->setCappedCollection(64 * 1024);

try {
    $command = $createCollection->getCommand();
    $cursor = $manager->executeCommand("databaseName", $command);
    $response = $cursor->toArray()[0];
    var_dump($response);

    $collstats = ["collstats" => $createCollection->getCollectionName()];
    $cursor = $manager->executeCommand("databaseName", new MongoDB\Driver\Command($collstats));
    $response = $cursor->toArray()[0];
    var_dump($response);
} catch(MongoDB\Driver\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

?>

Exemplul de mai sus va afi?a:

object(MongoDB\Driver\Command)#3 (1) {
  ["command"]=>
  array(3) {
    ["create"]=>
    string(16) "cappedCollection"
    ["capped"]=>
    bool(true)
    ["size"]=>
    int(65536)
  }
}
array(1) {
  ["ok"]=>
  float(1)
}
array(16) {
  ["ns"]=>
  string(29) "databaseName.cappedCollection"
  ["count"]=>
  int(0)
  ["size"]=>
  int(0)
  ["numExtents"]=>
  int(1)
  ["storageSize"]=>
  int(65536)
  ["nindexes"]=>
  int(1)
  ["lastExtentSize"]=>
  float(65536)
  ["paddingFactor"]=>
  float(1)
  ["paddingFactorNote"]=>
  string(101) "paddingFactor is unused and unmaintained in 2.8. It remains hard coded to 1.0 for compatibility only."
  ["userFlags"]=>
  int(0)
  ["capped"]=>
  bool(true)
  ["max"]=>
  int(9223372036854775807)
  ["maxSize"]=>
  int(65536)
  ["totalIndexSize"]=>
  int(8176)
  ["indexSizes"]=>
  object(stdClass)#4 (1) {
    ["_id_"]=>
    int(8176)
  }
  ["ok"]=>
  float(1)
}

Cuprins

  • MongoDB\Driver\Command::__construct — Create a new Command
MongoDB\Driver\Manager::selectServer
MongoDB\Driver\Command::__construct
MongoDB\Driver


Create a new Command

MongoDB\Driver\Command
MongoDB\Driver\Query
MongoDB\Driver\Command
PHP Manual

MongoDB\Driver\Command::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Command::__construct — Create a new Command

Descrierea

final public MongoDB\Driver\Command::__construct ( array|object $document )

Parametri

document

The complete command to construct

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Command::__construct() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = new MongoDB\Driver\Command(array("buildinfo" => 1));

try {
    $cursor = $manager->executeCommand("admin", $command);
    $response = $cursor->toArray()[0];
} catch(MongoDB\Driver\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}
var_dump($response);

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(13) {
  ["version"]=>
  string(14) "2.8.0-rc2-pre-"
  ["gitVersion"]=>
  string(62) "b743d7158f7642f4da6b7eac8320374b3b88dc2e modules: subscription"
  ["OpenSSLVersion"]=>
  string(25) "OpenSSL 1.0.1f 6 Jan 2014"
  ["sysInfo"]=>
  string(104) "Linux infant 3.16.0-24-generic #32-Ubuntu SMP Tue Oct 28 13:07:32 UTC 2014 x86_64 BOOST_LIB_VERSION=1_49"
  ["loaderFlags"]=>
  string(91) "-fPIC -pthread -Wl,-z,now -rdynamic -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -Wl,-E"
  ["compilerFlags"]=>
  string(301) "-Wnon-virtual-dtor -Woverloaded-virtual -std=c++11 -fPIC -fno-strict-aliasing -ggdb -pthread -Wall -Wsign-compare -Wno-unknown-pragmas -Winvalid-pch -pipe -Werror -O3 -Wno-unused-local-typedefs -Wno-unused-function -Wno-deprecated-declarations -Wno-unused-but-set-variable -fno-builtin-memcmp -std=c99"
  ["allocator"]=>
  string(8) "tcmalloc"
  ["versionArray"]=>
  array(4) {
    [0]=>
    int(2)
    [1]=>
    int(8)
    [2]=>
    int(0)
    [3]=>
    int(-8)
  }
  ["javascriptEngine"]=>
  string(2) "V8"
  ["bits"]=>
  int(64)
  ["debug"]=>
  bool(false)
  ["maxBsonObjectSize"]=>
  int(16777216)
  ["ok"]=>
  float(1)
}

A se vedea ?i

  • MongoDB\Driver\Manager::executeCommand() - Execute a database command
  • MongoDB\Driver\Cursor
MongoDB\Driver\Command
MongoDB\Driver\Query
MongoDB\Driver\Command


The MongoDB\Driver\Query class

(mongodb >=1.0.0)

Introducere

The MongoDB\Driver\Query class is a value object that represents a database query.

Sinopsisul clasei

final MongoDB\Driver\Query {
/* Metode */
final public __construct ( array|object $filter [, array $queryOptions ] )
}

Cuprins

  • MongoDB\Driver\Query::__construct — Construct new Query
MongoDB\Driver\Command::__construct
MongoDB\Driver\Query::__construct
MongoDB\Driver


Construct new Query

MongoDB\Driver\Query
MongoDB\Driver\BulkWrite
MongoDB\Driver\Query
PHP Manual

MongoDB\Driver\Query::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Query::__construct — Construct new Query

Descrierea

final public MongoDB\Driver\Query::__construct ( array|object $filter [, array $queryOptions ] )

Parametri

filter (array|object)

Filtrul de cautare.

queryOptions

queryOptions
Option | Type | Description
allowPartialResults bool

For queries against a sharded collection, returns partial results from the mongos if some shards are unavailable instead of throwing an error.

Falls back to the deprecated "partial" option if not specified.

awaitData | bool | Use in conjunction with the "tailable" option to block a getMore operation on the cursor temporarily if at the end of data rather than returning no data. After a timeout period, the query returns as normal.
batchSize integer

The number of documents to return in the first batch. Defaults to 101. A batch size of 0 means that the cursor will be established, but no documents will be returned in the first batch.

In versions of MongoDB before 3.2, where queries use the legacy wire protocol OP_QUERY, a batch size of 1 will close the cursor irrespective of the number of matched documents.

collation array|object

» Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the "locale" field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document.

If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.

comment string

A comment to attach to the query to help interpret and trace query profile data.

Falls back to the deprecated "$comment" modifier if not specified.

exhaust bool

Stream the data down full blast in multiple "more" packages, on the assumption that the client will fully read all data queried. Faster when you are pulling a lot of data and know you want to pull it all down. Note: the client is not allowed to not read all the data unless it closes the connection.

This option is not supported by the find command in MongoDB 3.2+ and will force the driver to use the legacy wire protocol version (i.e. OP_QUERY).

explain bool

If TRUE, the returned MongoDB\Driver\Cursor will contain a single document that describes the process and indexes used to return the query.

Falls back to the deprecated "$explain" modifier if not specified.

This option is not supported by the find command in MongoDB 3.2+ and will only be respected when using the legacy wire protocol version (i.e. OP_QUERY). The » explain command should be used on MongoDB 3.0+.

hint string|array|object

Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index.

Falls back to the deprecated "hint" option if not specified.

limit integer

The maximum number of documents to return. If unspecified, then defaults to no limit. A limit of 0 is equivalent to setting no limit.

A negative limit is will be interpreted as a positive limit with the "singleBatch" option set to TRUE. This behavior is supported for backwards compatibility, but should be considered deprecated.

max array|object

The exclusive upper bound for a specific index.

Falls back to the deprecated "$max" modifier if not specified.

maxScan integer

Positive integer denoting the maximum number of documents or index keys to scan when executing the query.

Falls back to the deprecated "$maxScan" modifier if not specified.

maxTimeMS integer

The cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.

Falls back to the deprecated "$maxTimeMS" modifier if not specified.

min array|object

The inclusive lower bound for a specific index.

Falls back to the deprecated "$min" modifier if not specified.

modifiers | array | » Meta operators modifying the output or behavior of a query. Use of these operators is deprecated in favor of named options.
noCursorTimeout | bool | Prevents the server from timing out idle cursors after an inactivity period (10 minutes).
oplogReplay bool

Internal use for replica sets. To use oplogReplay, you must include the following condition in the filter:

[ 'ts' => [ '$gte' => <timestamp> ] ]
projection | array|object | The » projection specification to determine which fields to include in the returned documents.
returnKey bool

If TRUE, returns only the index keys in the resulting documents. Default value is FALSE. If TRUE and the find command does not use an index, the returned documents will be empty.

Falls back to the deprecated "$returnKey" modifier if not specified.

showRecordId bool

Determines whether to return the record identifier for each document. If TRUE, adds a top-level "$recordId" field to the returned documents.

Falls back to the deprecated "$showDiskLoc" modifier if not specified.

singleBatch | bool | Determines whether to close the cursor after the first batch. Defaults to FALSE.
readConcern MongoDB\Driver\ReadConcern

Specifies the » read concern. The default level is "local".

To use a read concern level of "majority", you must use the WiredTiger storage engine with MongoDB 3.2+ and enable the feature in the server configuration.

skip | integer | Number of documents to skip. Defaults to 0.
slaveOk | bool | Allow query of replica set secondaries
sort array|object

The sort specification for the ordering of the results.

Falls back to the deprecated "$orderby" modifier if not specified.

snapshot bool

Prevents the cursor from returning a document more than once because of an intervening write operation.

Falls back to the deprecated "$snapshot" modifier if not specified.

tailable | bool | Returns a tailable cursor for a capped collection.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Istoricul schimbarilor

Versiune | Descriere
1.2.0

Added the "allowPartialResults", "collation", "comment", "hint", "max", "maxScan", "maxTimeMS", "min", "returnKey", "showRecordId", and "snapshot" options.

Renamed the "partial" option to "allowPartialResults". For backwards compatibility, "partial" will still be read if "allowPartialResults" is not specified.

Removed the "slaveOk" option, which is obsolete. For queries using the legacy wire protocol OP_QUERY, the driver will set the slaveOk bit as needed in accordance with the » Server Selection Specification.

1.1.0 | Added the "readConcern" option.

Exemple

Example #1 MongoDB\Driver\Query::__construct() example

<?php
/* Select only documents authord by "bjori" with at least 100 views */
$filter = [
    'author' => 'bjori',
    'views' => [
        '$gte' => 100,
    ],
];

$options = [
    /* Only return the following fields in the matching documents */
    'projection' => [
        'title' => 1,
        'article' => 1,
    ],
    /* Return the documents in descending order of views */
    'sort' => [
        'views' => -1
    ],
);

$query = new MongoDB\Driver\Query($filter, $options);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$cursor = $manager->executeQuery('databaseName.collectionName', $query, $readPreference);

foreach($cursor as $document) {
    var_dump($document);
}

?>

A se vedea ?i

  • MongoDB\Driver\Manager::executeQuery() - Execute a database query
  • MongoDB\Driver\Cursor
MongoDB\Driver\Query
MongoDB\Driver\BulkWrite
MongoDB\Driver\Query


The MongoDB\Driver\BulkWrite class

(mongodb >=1.0.0)

Introducere

The MongoDB\Driver\BulkWrite collects one or more write operations that should be sent to the server. After adding any number of insert, update, and delete operations, the collection may be executed via MongoDB\Driver\Manager::executeBulkWrite().

Write operations may either be ordered (default) or unordered. Ordered write operations are sent to the server, in the order provided, for serial execution. If a write fails, any remaining operations will be aborted. Unordered operations are sent to the server in an arbitrary order where they may be executed in parallel. Any errors that occur are reported after all operations have been attempted.

Sinopsisul clasei

final MongoDB\Driver\BulkWrite implements Countable {
/* Metode */
public __construct ([ array $options ] )
public int count ( void )
public void delete ( array|object $filter [, array $deleteOptions ] )
public mixed insert ( array|object $document )
public void update ( array|object $filter , array|object $newObj [, array $updateOptions ] )
}

Exemple

Example #1 Mixed write operations are grouped by type

Mixed write operations (i.e. inserts, updates, and deletes) will be assembled into typed write commands to be sent sequentially to the server.

<?php

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]]);
$bulk->insert(['_id' => 3, 'x' => 3]);
$bulk->delete(['x' => 1]);

?>

Will result in four write commands (i.e. roundtrips) being executed. Since the operations are ordered, the third insertion cannot be sent until the preceding update is executed.

Example #2 Ordered write operations causing an error

<?php

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete([]);
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3, 'hello' => 'world']);
$bulk->update(['_id' => 3], ['$set' => ['hello' => 'earth']]);
$bulk->insert(['_id' => 4, 'hello' => 'pluto']);
$bulk->update(['_id' => 4], ['$set' => ['hello' => 'moon']]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 5]);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);

try {
    $result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
    $result = $e->getWriteResult();

    // Check if the write concern could not be fulfilled
    if ($writeConcernError = $result->getWriteConcernError()) {
        printf("%s (%d): %s\n",
            $writeConcernError->getMessage(),
            $writeConcernError->getCode(),
            var_export($writeConcernError->getInfo(), true)
        );
    }

    // Check if any write operations did not complete at all
    foreach ($result->getWriteErrors() as $writeError) {
        printf("Operation#%d: %s (%d)\n",
            $writeError->getIndex(),
            $writeError->getMessage(),
            $writeError->getCode()
        );
    }
} catch (MongoDB\Driver\Exception\Exception $e) {
    printf("Other error: %s\n", $e->getMessage());
    exit;
}

printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Updated  %d document(s)\n", $result->getModifiedCount());

?>

Exemplul de mai sus va afi?a:

Operation#7: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 3 } (11000)
Inserted 4 document(s)
Updated  2 document(s)

If the write concern could not be fullfilled, the example above would output something like:

waiting for replication timed out (64): array (
  'wtimeout' => true,
)
Operation#7: E11000 duplicate key error index: databaseName.collectionName.$_id_ dup key: { : 3 } (11000)
Inserted 4 document(s)
Updated  2 document(s)

If we execute the example above, but allow for unordered writes:

<?php

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
/* ... */

?>

Exemplul de mai sus va afi?a:

Operation#7: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 3 } (11000)
Operation#8: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 4 } (11000)
Inserted 5 document(s)
Updated  2 document(s)

A se vedea ?i

  • MongoDB\Driver\Manager::executeBulkWrite()
  • MongoDB\Driver\WriteResult
  • MongoDB\Driver\WriteConcern
  • MongoDB\Driver\WriteConcernError
  • MongoDB\Driver\WriteError

Cuprins

  • MongoDB\Driver\BulkWrite::__construct — Create a new BulkWrite
  • MongoDB\Driver\BulkWrite::count — Count number of write operations in the bulk
  • MongoDB\Driver\BulkWrite::delete — Add a delete operation to the bulk
  • MongoDB\Driver\BulkWrite::insert — Add an insert operation to the bulk
  • MongoDB\Driver\BulkWrite::update — Add an update operation to the bulk
MongoDB\Driver\Query::__construct
MongoDB\Driver\BulkWrite::__construct
MongoDB\Driver


Create a new BulkWrite

MongoDB\Driver\BulkWrite
MongoDB\Driver\BulkWrite::count
MongoDB\Driver\BulkWrite
PHP Manual

MongoDB\Driver\BulkWrite::__construct

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::__construct — Create a new BulkWrite

Descrierea

public MongoDB\Driver\BulkWrite::__construct ([ array $options ] )

Constructs a new ordered (default) or unordered MongoDB\Driver\BulkWrite.

Parametri

options (array)

options
Option | Type | Description | Default
ordered | bool | Ordered operations (TRUE) are executed serially on the MongoDB server, while unordered operations (FALSE) are sent to the server in an arbitrary order and may be executed in parallel. | TRUE

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\BulkWrite::__construct() example

<?php

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete([]);
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(
    ['x' => 2],
    ['$set' => ['x' => 1]],
    ['limit' => 1, 'upsert' => false]
);
$bulk->delete(['x' => 1], ['limit' => 1]);
$bulk->update(
    ['_id' => 3],
    ['$set' => ['x' => 3]],
    ['limit' => 1, 'upsert' => true]
);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);

try {
    $result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
    $result = $e->getWriteResult();

    // Check if the write concern could not be fulfilled
    if ($writeConcernError = $result->getWriteConcernError()) {
        printf("%s (%d): %s\n",
            $writeConcernError->getMessage(),
            $writeConcernError->getCode(),
            var_export($writeConcernError->getInfo(), true)
        );
    }

    // Check if any write operations did not complete at all
    foreach ($result->getWriteErrors() as $writeError) {
        printf("Operation#%d: %s (%d)\n",
            $writeError->getIndex(),
            $writeError->getMessage(),
            $writeError->getCode()
        );
    }
} catch (MongoDB\Driver\Exception\Exception $e) {
    printf("Other error: %s\n", $e->getMessage());
    exit;
}

printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Updated  %d document(s)\n", $result->getModifiedCount());
printf("Upserted %d document(s)\n", $result->getUpsertedCount());
printf("Deleted  %d document(s)\n", $result->getDeletedCount());

?>

Exemplul de mai sus va afi?a:

Inserted 2 document(s)
Updated  1 document(s)
Upserted 1 document(s)
Deleted  1 document(s)

A se vedea ?i

  • MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
  • MongoDB\Driver\WriteResult
MongoDB\Driver\BulkWrite
MongoDB\Driver\BulkWrite::count
MongoDB\Driver\BulkWrite


Count number of write operations in the bulk

MongoDB\Driver\BulkWrite::__construct
MongoDB\Driver\BulkWrite::delete
MongoDB\Driver\BulkWrite
PHP Manual

MongoDB\Driver\BulkWrite::count

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::count — Count number of write operations in the bulk

Descrierea

public int MongoDB\Driver\BulkWrite::count ( void )

Returns the number of write operations added to the MongoDB\Driver\BulkWrite object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns number of write operations added to the MongoDB\Driver\BulkWrite object.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Returns the number of write operations added to the MongoDB\Driver\BulkWrite object. Earlier versions returned the expected number of client-to-server roundtrips required to execute all write operations.

Exemple

Example #1 MongoDB\Driver\BulkWrite::count() example

<?php

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]]);
$bulk->delete(['x' => 1]);

var_dump(count($bulk));

?>

Exemplul de mai sus va afi?a:

int(4)
MongoDB\Driver\BulkWrite::__construct
MongoDB\Driver\BulkWrite::delete
MongoDB\Driver\BulkWrite


Add a delete operation to the bulk

MongoDB\Driver\BulkWrite::count
MongoDB\Driver\BulkWrite::insert
MongoDB\Driver\BulkWrite
PHP Manual

MongoDB\Driver\BulkWrite::delete

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::delete — Add a delete operation to the bulk

Descrierea

public void MongoDB\Driver\BulkWrite::delete ( array|object $filter [, array $deleteOptions ] )

Adds a delete operation to the MongoDB\Driver\BulkWrite.

Parametri

filter (array|object)

Filtrul de cautare.

deleteOptions

deleteOptions
Option | Type | Description | Default
collation array|object

» Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the "locale" field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document.

If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.

limit | bool | Delete all matching documents (FALSE), or only the first matching document (TRUE) | FALSE

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Added the "collation" option.

Exemple

Example #1 MongoDB\Driver\BulkWrite::delete() example

<?php

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['x' => 1], ['limit' => 1]);
$bulk->delete(['x' => 2], ['limit' => 0]);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);

?>

A se vedea ?i

  • MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
  • MongoDB\Driver\WriteResult
MongoDB\Driver\BulkWrite::count
MongoDB\Driver\BulkWrite::insert
MongoDB\Driver\BulkWrite


Add an insert operation to the bulk

MongoDB\Driver\BulkWrite::delete
MongoDB\Driver\BulkWrite::update
MongoDB\Driver\BulkWrite
PHP Manual

MongoDB\Driver\BulkWrite::insert

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::insert — Add an insert operation to the bulk

Descrierea

public mixed MongoDB\Driver\BulkWrite::insert ( array|object $document )

Adds an insert operation to the MongoDB\Driver\BulkWrite.

Parametri

document (array|object)

A document to insert.

Valorile întoarse

If the document did not have an _id, a MongoDB\BSON\ObjectID will be generated and returned; otherwise, no value is returned.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\BulkWrite::insert() example

<?php

$bulk = new MongoDB\Driver\BulkWrite;

$document1 = ['title' => 'one'];
$document2 = ['_id' => 'custom ID', 'title' => 'two'];
$document3 = ['_id' => new MongoDB\BSON\ObjectID, 'title' => 'three'];

$_id1 = $bulk->insert($document1);
$_id2 = $bulk->insert($document2);
$_id3 = $bulk->insert($document3);

var_dump($_id1, $_id2, $_id3);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(MongoDB\BSON\ObjectID)#3 (1) {
  ["oid"]=>
  string(24) "54d51146bd21b91405401d92"
}
NULL
NULL

A se vedea ?i

  • MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
  • MongoDB\Driver\WriteResult
  • MongoDB\BSON\ObjectID
  • MongoDB\BSON\Persistable
MongoDB\Driver\BulkWrite::delete
MongoDB\Driver\BulkWrite::update
MongoDB\Driver\BulkWrite


Add an update operation to the bulk

MongoDB\Driver\BulkWrite::insert
MongoDB\Driver\WriteConcern
MongoDB\Driver\BulkWrite
PHP Manual

MongoDB\Driver\BulkWrite::update

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::update — Add an update operation to the bulk

Descrierea

public void MongoDB\Driver\BulkWrite::update ( array|object $filter , array|object $newObj [, array $updateOptions ] )

Adds an update operation to the MongoDB\Driver\BulkWrite.

Parametri

filter (array|object)

Filtrul de cautare.

newObj (array|object)

A document containing either update operators (e.g. $set) or a replacement document (i.e. only field:value expressions).

updateOptions

updateOptions
Option | Type | Description | Default
collation array|object

» Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the "locale" field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document.

If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.

multi | bool | Update only the first matching document (multi=false), or all matching documents (multi=true). | FALSE
upsert | bool | If filter does not match an existing document, insert a single document. The document will be created from newObj if it is a replacement document (i.e. no update operators); otherwise, the operators in newObj will be applied to filter to create the new document. | FALSE

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Added the "collation" option.

Exemple

Example #1 MongoDB\Driver\BulkWrite::update() example

<?php

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
    ['x' => 2],
    ['$set' => ['y' => 3]],
    ['multi' => false, 'upsert' => false]
);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);

?>

A se vedea ?i

  • MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
  • MongoDB\Driver\WriteResult
MongoDB\Driver\BulkWrite::insert
MongoDB\Driver\WriteConcern
MongoDB\Driver\BulkWrite


The MongoDB\Driver\WriteConcern class

(mongodb >=1.0.0)

Introducere

MongoDB\Driver\WriteConcern describes the level of acknowledgement requested from MongoDB for write operations to a standalone mongod or to replica sets or to sharded clusters. In sharded clusters, mongos instances will pass the write concern on to the shards.

Sinopsisul clasei

final MongoDB\Driver\WriteConcern implements MongoDB\BSON\Serializable {
/* Constants */
const string MAJORITY = majority ;
/* Metode */
final public object bsonSerialize ( void )
final public __construct ( string|int $w [, integer $wtimeout [, boolean $journal ]] )
final public bool|null getJournal ( void )
final public string|int|null getW ( void )
final public int getWtimeout ( void )
}

Constante predefinite

MongoDB\Driver\WriteConcern::MAJORITY

Majority of all the members in the set; arbiters, non-voting members, passive members, hidden members and delayed members are all included in the definition of majority write concern.

Cuprins

  • MongoDB\Driver\WriteConcern::bsonSerialize — Returns an object for BSON serialization
  • MongoDB\Driver\WriteConcern::__construct — Construct immutable WriteConcern
  • MongoDB\Driver\WriteConcern::getJournal — Returns the WriteConcern's "journal" option
  • MongoDB\Driver\WriteConcern::getW — Returns the WriteConcern's "w" option
  • MongoDB\Driver\WriteConcern::getWtimeout — Returns the WriteConcern's "wtimeout" option
MongoDB\Driver\BulkWrite::update
MongoDB\Driver\WriteConcern::bsonSerialize
MongoDB\Driver


Returns an object for BSON serialization

MongoDB\Driver\WriteConcern
MongoDB\Driver\WriteConcern::__construct
MongoDB\Driver\WriteConcern
PHP Manual

MongoDB\Driver\WriteConcern::bsonSerialize

(mongodb >=1.2.0)

MongoDB\Driver\WriteConcern::bsonSerialize — Returns an object for BSON serialization

Descrierea

final public object MongoDB\Driver\WriteConcern::bsonSerialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an object for serializing the WriteConcern as BSON.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteConcern::bsonSerialize() with majority write concern

<?php

$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY);
var_dump($wc->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($wc));

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(stdClass)#2 (1) {
  ["w"]=>
  string(8) "majority"
}

{ "w" : "majority" }

Example #2 MongoDB\Driver\WriteConcern::bsonSerialize() with wtimeout and journal

<?php

$wc = new MongoDB\Driver\WriteConcern(2, 1000, true);
var_dump($wc->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($wc));

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(stdClass)#2 (3) {
  ["w"]=>
  int(2)
  ["j"]=>
  bool(true)
  ["wtimeout"]=>
  int(1000)
}

{ "w" : 2, "j" : true, "wtimeout" : 1000 }

A se vedea ?i

  • MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
  • » Write Concern reference
MongoDB\Driver\WriteConcern
MongoDB\Driver\WriteConcern::__construct
MongoDB\Driver\WriteConcern


Construct immutable WriteConcern

MongoDB\Driver\WriteConcern::bsonSerialize
MongoDB\Driver\WriteConcern::getJournal
MongoDB\Driver\WriteConcern
PHP Manual

MongoDB\Driver\WriteConcern::__construct

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcern::__construct — Construct immutable WriteConcern

Descrierea

final public MongoDB\Driver\WriteConcern::__construct ( string|int $w [, integer $wtimeout [, boolean $journal ]] )

Creates a new WriteConcern.

Parametri

w

Write concern
Value | Description
1 | Requests acknowledgement that the write operation has propagated to the standalone mongod or the primary in a replica set. This is the default write concern for MongoDB.
0 | Requests no acknowledgment of the write operation. However, this may return information about socket exceptions and networking errors to the application.
<integer greater than 1> | Numbers greater than 1 are valid only for replica sets to request acknowledgement from specified number of members, including the primary.
MongoDB\Driver\WriteConcern::MAJORITY

Requests acknowledgment that write operations have propagated to the majority of voting nodes, including the primary, and have been written to the on-disk journal for these nodes.

Prior to MongoDB 3.0, this refers to the majority of replica set members (not just voting nodes).

string | A string value is interpereted as a tag set. Requests acknowledgement that the write operations have propagated to a replica set member with the specified tag.

wtimeout

How long to wait (in milliseconds) for secondaries before failing.

wtimeout causes write operations to return with an error (WriteConcernError) after the specified limit, even if the required write concern will eventually succeed. When these write operations return, MongoDB does not undo successful data modifications performed before the write concern exceeded the wtimeout time limit.

Write concern timeout
Value | Description
0 | Block indefinitely. This is the default.
<integer greater than 0> | Milliseconds to wait until returning.

journal

Wait until mongod has applied the write to the journal.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if w is invalid or wtimeout is negative.

Exemple

Example #1 MongoDB\Driver\WriteConcern::__construct() example

<?php

/* Request write acknowledgement from the majority of the replica set nodes */
$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 500);

/* Request write acknowledgement from a node configured with the "MultipleDC" tag */
$wc = new MongoDB\Driver\WriteConcern("MultipleDC", 500);

?>

A se vedea ?i

  • » Write Concern reference
MongoDB\Driver\WriteConcern::bsonSerialize
MongoDB\Driver\WriteConcern::getJournal
MongoDB\Driver\WriteConcern


Returns the WriteConcern's "journal" option

MongoDB\Driver\WriteConcern::__construct
MongoDB\Driver\WriteConcern::getW
MongoDB\Driver\WriteConcern
PHP Manual

MongoDB\Driver\WriteConcern::getJournal

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcern::getJournal — Returns the WriteConcern's "journal" option

Descrierea

final public bool|null MongoDB\Driver\WriteConcern::getJournal ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the WriteConcern's "journal" option.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteConcern::getJournal() example

<?php

$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->getJournal());

$wc = new MongoDB\Driver\WriteConcern(1, 0, true);
var_dump($wc->getJournal());

$wc = new MongoDB\Driver\WriteConcern(1, 0, false);
var_dump($wc->getJournal());

?>

Exemplul de mai sus va afi?a:

NULL
bool(true)
bool(false)

A se vedea ?i

  • » Write Concern reference
MongoDB\Driver\WriteConcern::__construct
MongoDB\Driver\WriteConcern::getW
MongoDB\Driver\WriteConcern


Returns the WriteConcern's "w" option

MongoDB\Driver\WriteConcern::getJournal
MongoDB\Driver\WriteConcern::getWtimeout
MongoDB\Driver\WriteConcern
PHP Manual

MongoDB\Driver\WriteConcern::getW

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcern::getW — Returns the WriteConcern's "w" option

Descrierea

final public string|int|null MongoDB\Driver\WriteConcern::getW ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the WriteConcern's "w" option.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteConcern::getW() example

<?php

$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->getW());

$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY);
var_dump($wc->getW());

?>

Exemplul de mai sus va afi?a:

int(1)
string(8) "majority"

A se vedea ?i

  • » Write Concern reference
MongoDB\Driver\WriteConcern::getJournal
MongoDB\Driver\WriteConcern::getWtimeout
MongoDB\Driver\WriteConcern


Returns the WriteConcern's "wtimeout" option

MongoDB\Driver\WriteConcern::getW
MongoDB\Driver\ReadPreference
MongoDB\Driver\WriteConcern
PHP Manual

MongoDB\Driver\WriteConcern::getWtimeout

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcern::getWtimeout — Returns the WriteConcern's "wtimeout" option

Descrierea

final public int MongoDB\Driver\WriteConcern::getWtimeout ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the WriteConcern's "wtimeout" option.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteConcern::getWtimeout() example

<?php

$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->getWtimeout());

$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 3000);
var_dump($wc->getWtimeout());

?>

Exemplul de mai sus va afi?a:

int(0)
int(3000)

A se vedea ?i

  • » Write Concern reference
MongoDB\Driver\WriteConcern::getW
MongoDB\Driver\ReadPreference
MongoDB\Driver\WriteConcern


The MongoDB\Driver\ReadPreference class

(mongodb >=1.0.0)

Introducere

Sinopsisul clasei

final MongoDB\Driver\ReadPreference implements MongoDB\BSON\Serializable {
/* Constants */
const integer RP_PRIMARY = 1 ;
const integer RP_PRIMARY_PREFERRED = 5 ;
const integer RP_SECONDARY = 2 ;
const integer RP_SECONDARY_PREFERRED = 6 ;
const integer RP_NEAREST = 10 ;
const integer NO_MAX_STALENESS = -1 ;
const integer SMALLEST_MAX_STALENESS_SECONDS = 90 ;
/* Metode */
final public object bsonSerialize ( void )
final public __construct ( int $mode [, array $tagSets = NULL [, array $options = [] ]] )
final public integer getMaxStalenessSeconds ( void )
final public integer getMode ( void )
final public array getTagSets ( void )
}

Constante predefinite

MongoDB\Driver\ReadPreference::RP_PRIMARY

All operations read from the current replica set primary. This is the default read preference for MongoDB.

MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED

In most situations, operations read from the primary but if it is unavailable, operations read from secondary members.

MongoDB\Driver\ReadPreference::RP_SECONDARY

All operations read from the secondary members of the replica set.

MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED

In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.

MongoDB\Driver\ReadPreference::RP_NEAREST

Operations read from member of the replica set with the least network latency, irrespective of the member's type.

MongoDB\Driver\ReadPreference::NO_MAX_STALENESS

The default value for the "maxStalenessSeconds" option is to specify no limit on maximum staleness, which means that the driver will not consider a secondary's lag when choosing where to direct a read operation.

MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS

The minimum value for the "maxStalenessSeconds" option is 90 seconds. The driver estimates secondaries' staleness by periodically checking the latest write date of each replica set member. Since these checks are infrequent, the staleness estimate is coarse. Thus, the driver cannot enforce a max staleness value of less than 90 seconds.

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Added the MongoDB\Driver\ReadPreference::NO_MAX_STALENESS and MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS constants.

Cuprins

  • MongoDB\Driver\ReadPreference::bsonSerialize — Returns an object for BSON serialization
  • MongoDB\Driver\ReadPreference::__construct — Construct immutable ReadPreference
  • MongoDB\Driver\ReadPreference::getMaxStalenessSeconds — Returns the ReadPreference's "maxStalenessSeconds" option
  • MongoDB\Driver\ReadPreference::getMode — Returns the ReadPreference's "mode" option
  • MongoDB\Driver\ReadPreference::getTagSets — Returns the ReadPreference's "tagSets" option
MongoDB\Driver\WriteConcern::getWtimeout
MongoDB\Driver\ReadPreference::bsonSerialize
MongoDB\Driver


Returns an object for BSON serialization

MongoDB\Driver\ReadPreference
MongoDB\Driver\ReadPreference::__construct
MongoDB\Driver\ReadPreference
PHP Manual

MongoDB\Driver\ReadPreference::bsonSerialize

(mongodb >=1.2.0)

MongoDB\Driver\ReadPreference::bsonSerialize — Returns an object for BSON serialization

Descrierea

final public object MongoDB\Driver\ReadPreference::bsonSerialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an object for serializing the ReadPreference as BSON.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\ReadPreference::bsonSerialize() with primary read preference

<?php

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
var_dump($rp->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rp));

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(stdClass)#2 (1) {
  ["mode"]=>
  string(7) "primary"
}

{ "mode" : "primary" }

Example #2 MongoDB\Driver\ReadPreference::bsonSerialize() with secondary read preference and tag sets

<?php

$rp = new MongoDB\Driver\ReadPreference(
    MongoDB\Driver\ReadPreference::RP_SECONDARY,
    [
        ['dc' => 'ny'],
        ['dc' => 'sf', 'use' => 'reporting'],
        []
    ]
);
var_dump($rp->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rp));

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(stdClass)#2 (2) {
  ["mode"]=>
  string(9) "secondary"
  ["tags"]=>
  array(3) {
    [0]=>
    object(stdClass)#1 (1) {
      ["dc"]=>
      string(2) "ny"
    }
    [1]=>
    object(stdClass)#5 (2) {
      ["dc"]=>
      string(2) "sf"
      ["use"]=>
      string(9) "reporting"
    }
    [2]=>
    object(stdClass)#4 (0) {
    }
  }
}

{ "mode" : "secondary", "tags" : [ { "dc" : "ny" }, { "dc" : "sf", "use" : "reporting" }, {  } ] }

Example #3 MongoDB\Driver\ReadPreference::bsonSerialize() with secondary read preference and max staleness

<?php

$rp = new MongoDB\Driver\ReadPreference(
    MongoDB\Driver\ReadPreference::RP_SECONDARY,
    null,
    ['maxStalenessSeconds' => 120]
);
var_dump($rp->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rp));

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(stdClass)#2 (2) {
  ["mode"]=>
  string(9) "secondary"
  ["maxStalenessSeconds"]=>
  int(120)
}

{ "mode" : "secondary", "maxStalenessSeconds" : 120 }

A se vedea ?i

  • MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
  • » Read Preference reference
MongoDB\Driver\ReadPreference
MongoDB\Driver\ReadPreference::__construct
MongoDB\Driver\ReadPreference


Construct immutable ReadPreference

MongoDB\Driver\ReadPreference::bsonSerialize
MongoDB\Driver\ReadPreference::getMaxStalenessSeconds
MongoDB\Driver\ReadPreference
PHP Manual

MongoDB\Driver\ReadPreference::__construct

(mongodb >=1.0.0)

MongoDB\Driver\ReadPreference::__construct — Construct immutable ReadPreference

Descrierea

final public MongoDB\Driver\ReadPreference::__construct ( int $mode [, array $tagSets = NULL [, array $options = [] ]] )

Creates a new ReadPreference.

Parametri

mode

Read preference mode
Value Description
MongoDB\Driver\ReadPreference::RP_PRIMARY

All operations read from the current replica set primary. This is the default read preference for MongoDB.

MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED

In most situations, operations read from the primary but if it is unavailable, operations read from secondary members.

MongoDB\Driver\ReadPreference::RP_SECONDARY

All operations read from the secondary members of the replica set.

MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED

In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.

MongoDB\Driver\ReadPreference::RP_NEAREST

Operations read from member of the replica set with the least network latency, irrespective of the member's type.

tagSets

Tag sets allow you to target read operations to specific members of a replica set. This parameter should be an array of associative arrays, each of which contain zero or more key/value pairs. When selecting a server for a read operation, the driver attempt to select a node having all tags in a set (i.e. the associative array of key/value pairs). If selection fails, the driver will attempt subsequent sets. An empty tag set (array()) will match any node and may be used as a fallback.

Tags are not compatible with the MongoDB\Driver\ReadPreference::RP_PRIMARY mode and, in general, only apply when selecting a secondary member of a set for a read operation. However, the MongoDB\Driver\ReadPreference::RP_NEAREST mode, when combined with a tag set, selects the matching member with the lowest network latency. This member may be a primary or secondary.

options

options
Option Type Description
maxStalenessSeconds integer

Specifies a maximum replication lag, or "staleness", for reads from secondaries. When a secondary's estimated staleness exceeds this value, the driver stops using it for read operations.

If specified, the max staleness must be a signed 32-bit integer greater than or equal to MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS.

Defaults to MongoDB\Driver\ReadPreference::NO_MAX_STALENESS, which means that the driver will not consider a secondary's lag when choosing where to direct a read operation.

This option is not compatible with the MongoDB\Driver\ReadPreference::RP_PRIMARY mode. Specifying a max staleness also requires all MongoDB instances in the deployment to be using MongoDB 3.4+. An exception will be thrown at execution time if any MongoDB instances in the deployment are of an older server version.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if mode is invalid.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if tagSets is provided for a primary read preference or is malformed (i.e. not an array of zero or more documents).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "maxStalenessSeconds" option is provided for a primary read preference or is out of range.

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Added a third options argument, which supports the "maxStalenessSeconds" option.

Exemple

Example #1 MongoDB\Driver\ReadPreference::__construct() example

<?php

/* Prefer a secondary node but fall back to a primary. */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED));

/* Prefer a node in the New York data center with lowest latency. */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_NEAREST, [['dc' => 'ny']]));

/* Require a secondary node whose replication lag is within two minutes of the primary */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, ['maxStalenessSeconds' => 120]));

?>

Exemplul de mai sus va afi?a:

object(MongoDB\Driver\ReadPreference)#1 (1) {
  ["mode"]=>
  string(18) "secondaryPreferred"
}
object(MongoDB\Driver\ReadPreference)#1 (2) {
  ["mode"]=>
  string(7) "nearest"
  ["tags"]=>
  array(1) {
    [0]=>
    object(stdClass)#2 (1) {
      ["dc"]=>
      string(2) "ny"
    }
  }
}
object(MongoDB\Driver\ReadPreference)#1 (2) {
  ["mode"]=>
  string(9) "secondary"
  ["maxStalenessSeconds"]=>
  int(120)
}

A se vedea ?i

  • » Read Preference reference
MongoDB\Driver\ReadPreference::bsonSerialize
MongoDB\Driver\ReadPreference::getMaxStalenessSeconds
MongoDB\Driver\ReadPreference


Returns the ReadPreference's "maxStalenessSeconds" option

MongoDB\Driver\ReadPreference::__construct
MongoDB\Driver\ReadPreference::getMode
MongoDB\Driver\ReadPreference
PHP Manual

MongoDB\Driver\ReadPreference::getMaxStalenessSeconds

(mongodb >=1.2.0)

MongoDB\Driver\ReadPreference::getMaxStalenessSeconds — Returns the ReadPreference's "maxStalenessSeconds" option

Descrierea

final public integer MongoDB\Driver\ReadPreference::getMaxStalenessSeconds ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the ReadPreference's "maxStalenessSeconds" option. If no max staleness has been specified, MongoDB\Driver\ReadPreference::NO_MAX_STALENESS will be returned.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\ReadPreference::getMaxStalenessSeconds() example

<?php

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY);
var_dump($rp->getMaxStalenessSeconds());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, [
    'maxStalenessSeconds' => MongoDB\Driver\ReadPreference::NO_MAX_STALENESS,
]);
var_dump($rp->getMaxStalenessSeconds());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, [
    'maxStalenessSeconds' => MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS,
]);
var_dump($rp->getMaxStalenessSeconds());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, [
    'maxStalenessSeconds' => 1000,
]);
var_dump($rp->getMaxStalenessSeconds());

?>

Exemplul de mai sus va afi?a:

int(-1)
int(-1)
int(90)
int(1000)

A se vedea ?i

  • » Read Preference reference
MongoDB\Driver\ReadPreference::__construct
MongoDB\Driver\ReadPreference::getMode
MongoDB\Driver\ReadPreference


Returns the ReadPreference's "mode" option

MongoDB\Driver\ReadPreference::getMaxStalenessSeconds
MongoDB\Driver\ReadPreference::getTagSets
MongoDB\Driver\ReadPreference
PHP Manual

MongoDB\Driver\ReadPreference::getMode

(mongodb >=1.0.0)

MongoDB\Driver\ReadPreference::getMode — Returns the ReadPreference's "mode" option

Descrierea

final public integer MongoDB\Driver\ReadPreference::getMode ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the ReadPreference's "mode" option.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\ReadPreference::getMode() example

<?php

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_NEAREST);
var_dump($rp->getMode());

?>

Exemplul de mai sus va afi?a:

int(1)
int(5)
int(2)
int(6)
int(10)

A se vedea ?i

  • » Read Preference reference
MongoDB\Driver\ReadPreference::getMaxStalenessSeconds
MongoDB\Driver\ReadPreference::getTagSets
MongoDB\Driver\ReadPreference


Returns the ReadPreference's "tagSets" option

MongoDB\Driver\ReadPreference::getMode
MongoDB\Driver\ReadConcern
MongoDB\Driver\ReadPreference
PHP Manual

MongoDB\Driver\ReadPreference::getTagSets

(mongodb >=1.0.0)

MongoDB\Driver\ReadPreference::getTagSets — Returns the ReadPreference's "tagSets" option

Descrierea

final public array MongoDB\Driver\ReadPreference::getTagSets ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the ReadPreference's "tagSets" option.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\ReadPreference::getTagSets() example

<?php

$mode = MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED);

/* Null and an empty array both denote no tag set preference. */
$rp = new MongoDB\Driver\ReadPreference($mode, null);
var_dump($rp->getTagSets());

$rp = new MongoDB\Driver\ReadPreference($mode, []);
var_dump($rp->getTagSets());

/* Prefer a node in New York, but fall back to any available node. */
$rp = new MongoDB\Driver\ReadPreference($mode, [['dc' => 'ny']]);
var_dump($rp->getTagSets());

/* Prefer a node in the New York, followed by a node in San Francisco that is
   labeled for reporting usage, and finally fall back to any available node. */
$rp = new MongoDB\Driver\ReadPreference($mode, [
  ['dc' => 'ny'],
  ['dc' => 'sf', 'use' => 'reporting'],
  [],
]);
var_dump($rp->getTagSets());

?>

Exemplul de mai sus va afi?a:

array(0) {
}
array(0) {
}
array(2) {
  [0]=>
  array(1) {
    ["dc"]=>
    string(2) "ny"
  }
  [1]=>
  array(0) {
  }
}
array(3) {
  [0]=>
  array(1) {
    ["dc"]=>
    string(2) "ny"
  }
  [1]=>
  array(2) {
    ["dc"]=>
    string(2) "sf"
    ["use"]=>
    string(9) "reporting"
  }
  [2]=>
  array(0) {
  }
}

A se vedea ?i

  • » Read Preference reference
MongoDB\Driver\ReadPreference::getMode
MongoDB\Driver\ReadConcern
MongoDB\Driver\ReadPreference


The MongoDB\Driver\ReadConcern class

(mongodb >=1.1.0)

Introducere

MongoDB\Driver\ReadConcern controls the level of isolation for read operations for replica sets and replica set shards. This option requires the WiredTiger storage engine and MongoDB 3.2 or later.

Sinopsisul clasei

final MongoDB\Driver\ReadConcern implements MongoDB\BSON\Serializable {
/* Constants */
const string LINEARIZABLE = linearizable ;
const string LOCAL = local ;
const string MAJORITY = majority ;
/* Metode */
final public object bsonSerialize ( void )
final public __construct ([ string $level ] )
final public string|null getLevel ( void )
}

Constante predefinite

MongoDB\Driver\ReadConcern::LINEARIZABLE

A linearizable read avoids returning reads from a stale primary (one that has already been superseded by a new primary but doesn't know it yet). It is important to note that this read concern level does not by itself produce linearizable reads; they must be issued in conjunction with MongoDB\Driver\WriteConcern::MAJORITY writes to the same document(s) in order to be linearizable.

MongoDB\Driver\ReadConcern::LOCAL

Queries using this read concern will return the node's most recent copy of the data. This provides no guarantee that the data has been written to a majority of the nodes (i.e. it may be rolled back).

This is the default read concern level.

MongoDB\Driver\ReadConcern::MAJORITY

Queries using this read concern will return the node's most recent copy of the data confirmed as having been written to a majority of the nodes (i.e. the data cannot be rolled back).

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Added the MongoDB\Driver\ReadConcern::LINEARIZABLE constant.

Cuprins

  • MongoDB\Driver\ReadConcern::bsonSerialize — Returns an object for BSON serialization
  • MongoDB\Driver\ReadConcern::__construct — Construct immutable ReadConcern
  • MongoDB\Driver\ReadConcern::getLevel — Returns the ReadConcern's "level" option
MongoDB\Driver\ReadPreference::getTagSets
MongoDB\Driver\ReadConcern::bsonSerialize
MongoDB\Driver


Returns an object for BSON serialization

MongoDB\Driver\ReadConcern
MongoDB\Driver\ReadConcern::__construct
MongoDB\Driver\ReadConcern
PHP Manual

MongoDB\Driver\ReadConcern::bsonSerialize

(mongodb >=1.2.0)

MongoDB\Driver\ReadConcern::bsonSerialize — Returns an object for BSON serialization

Descrierea

final public object MongoDB\Driver\ReadConcern::bsonSerialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an object for serializing the ReadConcern as BSON.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\ReadConcern::bsonSerialize() with empty read concern

<?php

$rc = new MongoDB\Driver\ReadConcern;
var_dump($rc->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rc));

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(stdClass)#2 (0) {
}

{ }

Example #2 MongoDB\Driver\ReadConcern::bsonSerialize() with local read concern

<?php

$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::LOCAL);
var_dump($rc->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rc));

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(stdClass)#2 (1) {
  ["level"]=>
  string(5) "local"
}

{ "level" : "local" }

A se vedea ?i

  • MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
  • » Read Concern reference
MongoDB\Driver\ReadConcern
MongoDB\Driver\ReadConcern::__construct
MongoDB\Driver\ReadConcern


Construct immutable ReadConcern

MongoDB\Driver\ReadConcern::bsonSerialize
MongoDB\Driver\ReadConcern::getLevel
MongoDB\Driver\ReadConcern
PHP Manual

MongoDB\Driver\ReadConcern::__construct

(mongodb >=1.0.0)

MongoDB\Driver\ReadConcern::__construct — Construct immutable ReadConcern

Descrierea

final public MongoDB\Driver\ReadConcern::__construct ([ string $level ] )

Creates a new ReadConcern.

Parametri

level

Read concern
Value | Description
MongoDB\Driver\ReadConcern::LOCAL | Queries using this read concern will return the node's most recent copy of the data. This provides no guarantee that the data has been written to a majority of the nodes (i.e. it may be rolled back). This is the default read concern for MongoDB.
MongoDB\Driver\ReadConcern::MAJORITY | Queries using this read concern will return the node's most recent copy of the data confirmed as having been written to a majority of the nodes (i.e. the data cannot be rolled back).

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\ReadConcern::__construct() example

<?php

/* Unspecified read isolation level (uses the server's default behavior) */
$rc = new MongoDB\Driver\ReadConcern();

/* Request read isolation from a single replica set node */
$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::LOCAL);

/* Request read isolation from a majority of the replica set nodes */
$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::MAJORITY);

?>

A se vedea ?i

  • » Read Concern reference
MongoDB\Driver\ReadConcern::bsonSerialize
MongoDB\Driver\ReadConcern::getLevel
MongoDB\Driver\ReadConcern


Returns the ReadConcern's "level" option

MongoDB\Driver\ReadConcern::__construct
MongoDB\Driver\Cursor
MongoDB\Driver\ReadConcern
PHP Manual

MongoDB\Driver\ReadConcern::getLevel

(mongodb >=1.0.0)

MongoDB\Driver\ReadConcern::getLevel — Returns the ReadConcern's "level" option

Descrierea

final public string|null MongoDB\Driver\ReadConcern::getLevel ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the ReadConcern's "level" option.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\ReadConcern::getLevel() example

<?php

$rc = new MongoDB\Driver\ReadConcern();
var_dump($rc->getLevel());

$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::LOCAL);
var_dump($rc->getLevel());

$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::MAJORITY);
var_dump($rc->getLevel());

?>

Exemplul de mai sus va afi?a:

NULL
string(5) "local"
string(8) "majority"

A se vedea ?i

  • » Read Concern reference
MongoDB\Driver\ReadConcern::__construct
MongoDB\Driver\Cursor
MongoDB\Driver\ReadConcern


The MongoDB\Driver\Cursor class

(mongodb >=1.0.0)

Introducere

The MongoDB\Driver\Cursor class encapsulates the results of a MongoDB command or query and may be returned by MongoDB\Driver\Manager::executeCommand() or MongoDB\Driver\Manager::executeQuery(), respectively.

Sinopsisul clasei

MongoDB\Driver\Cursor implements Traversable {
/* Metode */
final private __construct ( void )
final public MongoDB\Driver\CursorId getId ( void )
final public MongoDB\Driver\Server getServer ( void )
final public bool isDead ( void )
final public void setTypeMap ( array $typemap )
final public array toArray ( void )
}

Cuprins

  • MongoDB\Driver\Cursor::__construct — Create a new Cursor (not used)
  • MongoDB\Driver\Cursor::getId — Returns the ID for this cursor
  • MongoDB\Driver\Cursor::getServer — Returns the server associated with this cursor
  • MongoDB\Driver\Cursor::isDead — Checks if the cursor is still open on the server
  • MongoDB\Driver\Cursor::setTypeMap — Sets a type map to use for BSON unserialization
  • MongoDB\Driver\Cursor::toArray — Returns an array containing all results for this cursor
MongoDB\Driver\ReadConcern::getLevel
MongoDB\Driver\Cursor::__construct
MongoDB\Driver


Create a new Cursor (not used)

MongoDB\Driver\Cursor
MongoDB\Driver\Cursor::getId
MongoDB\Driver\Cursor
PHP Manual

MongoDB\Driver\Cursor::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::__construct — Create a new Cursor (not used)

Descrierea

final private MongoDB\Driver\Cursor::__construct ( void )

MongoDB\Driver\Cursor objects are returned as the result of an executed command or query and cannot be constructed directly.

Parametri

Aceasta func?ie nu are parametri.

A se vedea ?i

  • MongoDB\Driver\Manager::executeCommand() - Execute a database command
  • MongoDB\Driver\Manager::executeQuery() - Execute a database query
  • MongoDB\Driver\Server::executeCommand() - Execute a database command on this server
  • MongoDB\Driver\Server::executeQuery() - Execute a database query on this server
MongoDB\Driver\Cursor
MongoDB\Driver\Cursor::getId
MongoDB\Driver\Cursor


Returns the ID for this cursor

MongoDB\Driver\Cursor::__construct
MongoDB\Driver\Cursor::getServer
MongoDB\Driver\Cursor
PHP Manual

MongoDB\Driver\Cursor::getId

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::getId — Returns the ID for this cursor

Descrierea

final public MongoDB\Driver\CursorId MongoDB\Driver\Cursor::getId ( void )

Returns the MongoDB\Driver\CursorId associated with this cursor. A cursor ID uniquely identifies the cursor on the server.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the MongoDB\Driver\CursorId for this cursor.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Cursor::getId() example

<?php

/* In this example, we insert several documents into the collection and specify
 * a smaller batchSize to ensure that the first batch contains only a subset of
 * our results and the cursor remains open on the server. */
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([], ['batchSize' => 2]);

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$cursor = $manager->executeQuery('db.collection', $query);
var_dump($cursor->getId());

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(MongoDB\Driver\CursorId)#5 (1) {
  ["id"]=>
  int(94810124093)
}

A se vedea ?i

  • MongoDB\Driver\CursorId
  • MongoDB\Driver\CursorId::__toString() - String representation of the cursor ID
MongoDB\Driver\Cursor::__construct
MongoDB\Driver\Cursor::getServer
MongoDB\Driver\Cursor


Returns the server associated with this cursor

MongoDB\Driver\Cursor::getId
MongoDB\Driver\Cursor::isDead
MongoDB\Driver\Cursor
PHP Manual

MongoDB\Driver\Cursor::getServer

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::getServer — Returns the server associated with this cursor

Descrierea

final public MongoDB\Driver\Server MongoDB\Driver\Cursor::getServer ( void )

Returns the MongoDB\Driver\Server associated with this cursor. This is the server that executed the MongoDB\Driver\Query or MongoDB\Driver\Command.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the MongoDB\Driver\Server associated with this cursor.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Cursor::getServer() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([]);

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$manager->executeBulkWrite('db.collection', $bulk);

$cursor = $manager->executeQuery('db.collection', $query);
var_dump($cursor->getServer());

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(MongoDB\Driver\Server)#5 (10) {
  ["host"]=>
  string(9) "localhost"
  ["port"]=>
  int(27017)
  ["type"]=>
  int(1)
  ["is_primary"]=>
  bool(false)
  ["is_secondary"]=>
  bool(false)
  ["is_arbiter"]=>
  bool(false)
  ["is_hidden"]=>
  bool(false)
  ["is_passive"]=>
  bool(false)
  ["last_is_master"]=>
  array(8) {
    ["ismaster"]=>
    bool(true)
    ["maxBsonObjectSize"]=>
    int(16777216)
    ["maxMessageSizeBytes"]=>
    int(48000000)
    ["maxWriteBatchSize"]=>
    int(1000)
    ["localTime"]=>
    object(MongoDB\BSON\UTCDateTime)#6 (1) {
      ["milliseconds"]=>
      int(1446505367907)
    }
    ["maxWireVersion"]=>
    int(3)
    ["minWireVersion"]=>
    int(0)
    ["ok"]=>
    float(1)
  }
  ["round_trip_time"]=>
  int(584)
}

A se vedea ?i

  • MongoDB\Driver\Server
MongoDB\Driver\Cursor::getId
MongoDB\Driver\Cursor::isDead
MongoDB\Driver\Cursor


Checks if the cursor is still open on the server

MongoDB\Driver\Cursor::getServer
MongoDB\Driver\Cursor::setTypeMap
MongoDB\Driver\Cursor
PHP Manual

MongoDB\Driver\Cursor::isDead

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::isDead — Checks if the cursor is still open on the server

Descrierea

final public bool MongoDB\Driver\Cursor::isDead ( void )

Returns whether the cursor is still open on the server (i.e. the server has more results that have yet to be sent to the client).

A cursor being "dead" does not mean that it cannot be iterated further. The database sends responses in batches of documents (up to 4MB of documents per response). The client's cursor may still have results to be iterated even if the server has no more batches to send.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if there are more results that have not yet been sent to the client, and FALSE otherwise.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Cursor::isDead() example

<?php

/* In this example, we insert several documents into the collection and specify
 * a smaller batchSize to ensure that the first batch contains only a subset of
 * our results and the cursor remains open on the server. */
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([], ['batchSize' => 2]);

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$cursor = $manager->executeQuery('db.collection', $query);

var_dump($cursor->isDead());
$cursor->toArray();
var_dump($cursor->isDead());

?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
MongoDB\Driver\Cursor::getServer
MongoDB\Driver\Cursor::setTypeMap
MongoDB\Driver\Cursor


Sets a type map to use for BSON unserialization

MongoDB\Driver\Cursor::isDead
MongoDB\Driver\Cursor::toArray
MongoDB\Driver\Cursor
PHP Manual

MongoDB\Driver\Cursor::setTypeMap

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::setTypeMap — Sets a type map to use for BSON unserialization

Descrierea

final public void MongoDB\Driver\Cursor::setTypeMap ( array $typemap )

Sets the type map configuration to use when unserializing the BSON results into PHP values.

Parametri

typeMap (array)

configura?ia Type map.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Cursor::setTypeMap() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$bulk = new MongoDB\Driver\BulkWrite;
$id = $bulk->insert(['x' => 1]);
$manager->executeBulkWrite('db.collection', $bulk);

$query = new MongoDB\Driver\Query(['_id' => $id]);
$cursor = $manager->executeQuery('db.collection', $query);
$cursor->setTypeMap(['root' => 'array']);

foreach ($cursor as $document) {
    var_dump($document);
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  ["_id"]=>
  object(MongoDB\BSON\ObjectID)#6 (1) {
    ["oid"]=>
    string(24) "56424fb76118fd3267180741"
  }
  ["x"]=>
  int(1)
}

A se vedea ?i

  • Persisting Data
MongoDB\Driver\Cursor::isDead
MongoDB\Driver\Cursor::toArray
MongoDB\Driver\Cursor


Returns an array containing all results for this cursor

MongoDB\Driver\Cursor::setTypeMap
MongoDB\Driver\CursorId
MongoDB\Driver\Cursor
PHP Manual

MongoDB\Driver\Cursor::toArray

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::toArray — Returns an array containing all results for this cursor

Descrierea

final public array MongoDB\Driver\Cursor::toArray ( void )

Iterates the cursor and returns its results in an array. MongoDB\Driver\Cursor::setTypeMap() may be used to control how documents are unserialized into PHP values.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array containing all results for this cursor.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Cursor::toArray() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$query = new MongoDB\Driver\Query([]);
$cursor = $manager->executeQuery('db.collection', $query);

var_dump($cursor->toArray());

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  [0]=>
  object(stdClass)#6 (2) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectID)#5 (1) {
      ["oid"]=>
      string(24) "564259a96118fd40b41bcf61"
    }
    ["x"]=>
    int(1)
  }
  [1]=>
  object(stdClass)#8 (2) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectID)#7 (1) {
      ["oid"]=>
      string(24) "564259a96118fd40b41bcf62"
    }
    ["x"]=>
    int(2)
  }
  [2]=>
  object(stdClass)#10 (2) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectID)#9 (1) {
      ["oid"]=>
      string(24) "564259a96118fd40b41bcf63"
    }
    ["x"]=>
    int(3)
  }
}

A se vedea ?i

  • MongoDB\Driver\Cursor::setTypeMap() - Sets a type map to use for BSON unserialization
MongoDB\Driver\Cursor::setTypeMap
MongoDB\Driver\CursorId
MongoDB\Driver\Cursor


The MongoDB\Driver\CursorId class

(mongodb >=1.0.0)

Introducere

Sinopsisul clasei

final MongoDB\Driver\CursorId {
/* Metode */
final private __construct ( void )
final public string __toString ( void )
}

Cuprins

  • MongoDB\Driver\CursorId::__construct — Create a new CursorId (not used)
  • MongoDB\Driver\CursorId::__toString — String representation of the cursor ID
MongoDB\Driver\Cursor::toArray
MongoDB\Driver\CursorId::__construct
MongoDB\Driver


Create a new CursorId (not used)

MongoDB\Driver\CursorId
MongoDB\Driver\CursorId::__toString
MongoDB\Driver\CursorId
PHP Manual

MongoDB\Driver\CursorId::__construct

(mongodb >=1.0.0)

MongoDB\Driver\CursorId::__construct — Create a new CursorId (not used)

Descrierea

final private MongoDB\Driver\CursorId::__construct ( void )

MongoDB\Driver\CursorId objects are returned from MongoDB\Driver\Cursor::getId() and cannot be constructed directly.

Parametri

Aceasta func?ie nu are parametri.

A se vedea ?i

  • MongoDB\Driver\Cursor::getId() - Returns the ID for this cursor
MongoDB\Driver\CursorId
MongoDB\Driver\CursorId::__toString
MongoDB\Driver\CursorId


String representation of the cursor ID

MongoDB\Driver\CursorId::__construct
MongoDB\Driver\Server
MongoDB\Driver\CursorId
PHP Manual

MongoDB\Driver\CursorId::__toString

(mongodb >=1.0.0)

MongoDB\Driver\CursorId::__toString — String representation of the cursor ID

Descrierea

final public string MongoDB\Driver\CursorId::__toString ( void )

Returns the string representation of the cursor ID.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the string representation of the cursor ID.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\CursorId::__toString() example

<?php

/* In this example, we insert several documents into the collection and specify
 * a smaller batchSize to ensure that the first batch contains only a subset of
 * our results and the cursor remains open on the server. */
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([], ['batchSize' => 2]);

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$cursor = $manager->executeQuery('db.collection', $query);
var_dump((string) $cursor->getId());

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(11) "98061641158"

A se vedea ?i

  • MongoDB\Driver\Cursor::getId() - Returns the ID for this cursor
MongoDB\Driver\CursorId::__construct
MongoDB\Driver\Server
MongoDB\Driver\CursorId


The MongoDB\Driver\Server class

(mongodb >=1.0.0)

Introducere

Sinopsisul clasei

final MongoDB\Driver\Server {
/* Constants */
const integer TYPE_UNKNOWN = 0 ;
const integer TYPE_STANDALONE = 1 ;
const integer TYPE_MONGOS = 2 ;
const integer TYPE_POSSIBLE_PRIMARY = 3 ;
const integer TYPE_RS_PRIMARY = 4 ;
const integer TYPE_RS_SECONDARY = 5 ;
const integer TYPE_RS_ARBITER = 6 ;
const integer TYPE_RS_OTHER = 7 ;
const integer TYPE_RS_GHOST = 8 ;
/* Metode */
final private __construct ( void )
final public MongoDB\Driver\WriteResult executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, MongoDB\Driver\WriteConcern $writeConcern ] )
final public MongoDB\Driver\Cursor executeCommand ( string $db , MongoDB\Driver\Command $command [, MongoDB\Driver\ReadPreference $readPreference ] )
final public MongoDB\Driver\Cursor executeQuery ( string $namespace , MongoDB\Driver\Query $query [, MongoDB\Driver\ReadPreference $readPreference ] )
final public string getHost ( void )
final public array getInfo ( void )
final public string getLatency ( void )
final public int getPort ( void )
final public array getTags ( void )
final public int getType ( void )
final public bool isArbiter ( void )
final public bool isHidden ( void )
final public bool isPassive ( void )
final public bool isPrimary ( void )
final public bool isSecondary ( void )
}

Constante predefinite

MongoDB\Driver\Server::TYPE_UNKNOWN

Unknown server type, returned by MongoDB\Driver\Server::getType().

MongoDB\Driver\Server::TYPE_STANDALONE

Standalone server type, returned by MongoDB\Driver\Server::getType().

MongoDB\Driver\Server::TYPE_MONGOS

Mongos server type, returned by MongoDB\Driver\Server::getType().

MongoDB\Driver\Server::TYPE_POSSIBLE_PRIMARY

Replica set possible primary server type, returned by MongoDB\Driver\Server::getType().

A server may be identified as a possible primary if it has not yet been checked but another memory of the replica set thinks it is the primary.

MongoDB\Driver\Server::TYPE_RS_PRIMARY

Replica set primary server type, returned by MongoDB\Driver\Server::getType().

MongoDB\Driver\Server::TYPE_RS_SECONDARY

Replica set secondary server type, returned by MongoDB\Driver\Server::getType().

MongoDB\Driver\Server::TYPE_RS_ARBITER

Replica set arbiter server type, returned by MongoDB\Driver\Server::getType().

MongoDB\Driver\Server::TYPE_RS_OTHER

Replica set other server type, returned by MongoDB\Driver\Server::getType().

Such servers may be hidden, starting up, or recovering. They cannot be queried, but their hosts lists are useful for discovering the current replica set configuration.

MongoDB\Driver\Server::TYPE_RS_GHOST

Replica set ghost server type, returned by MongoDB\Driver\Server::getType().

Servers may be identified as such in at least three situations: briefly during server startup; in an uninitialized replica set; or when the server is shunned (i.e. removed from the replica set config). They cannot be queried, nor can their host list be used to discover the current replica set configuration; however, the client may monitor this server in hope that it transitions to a more useful state.

Cuprins

  • MongoDB\Driver\Server::__construct — Create a new Server (not used)
  • MongoDB\Driver\Server::executeBulkWrite — Execute one or more write operations on this server
  • MongoDB\Driver\Server::executeCommand — Execute a database command on this server
  • MongoDB\Driver\Server::executeQuery — Execute a database query on this server
  • MongoDB\Driver\Server::getHost — Returns the hostname of this server
  • MongoDB\Driver\Server::getInfo — Returns an array of information about this server
  • MongoDB\Driver\Server::getLatency — Returns the latency of this server
  • MongoDB\Driver\Server::getPort — Returns the port on which this server is listening
  • MongoDB\Driver\Server::getTags — Returns an array of tags describing this server in a replica set
  • MongoDB\Driver\Server::getType — Returns an integer denoting the type of this server
  • MongoDB\Driver\Server::isArbiter — Checks if this server is an arbiter member of a replica set
  • MongoDB\Driver\Server::isHidden — Checks if this server is a hidden member of a replica set
  • MongoDB\Driver\Server::isPassive — Checks if this server is a passive member of a replica set
  • MongoDB\Driver\Server::isPrimary — Checks if this server is a primary member of a replica set
  • MongoDB\Driver\Server::isSecondary — Checks if this server is a secondary member of a replica set
MongoDB\Driver\CursorId::__toString
MongoDB\Driver\Server::__construct
MongoDB\Driver


Create a new Server (not used)

MongoDB\Driver\Server
MongoDB\Driver\Server::executeBulkWrite
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Server::__construct — Create a new Server (not used)

Descrierea

final private MongoDB\Driver\Server::__construct ( void )

MongoDB\Driver\Server objects are created internally by MongoDB\Driver\Manager when a database connection is established and may be returned by MongoDB\Driver\Manager::getServers() and MongoDB\Driver\Manager::selectServer().

Parametri

Aceasta func?ie nu are parametri.

A se vedea ?i

  • MongoDB\Driver\Manager::getServers() - Return the servers to which this manager is connected
  • MongoDB\Driver\Manager::selectServer() - Select a server matching a read preference
MongoDB\Driver\Server
MongoDB\Driver\Server::executeBulkWrite
MongoDB\Driver\Server


Execute one or more write operations on this server

MongoDB\Driver\Server::__construct
MongoDB\Driver\Server::executeCommand
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::executeBulkWrite

(mongodb >=1.0.0)

MongoDB\Driver\Server::executeBulkWrite — Execute one or more write operations on this server

Descrierea

final public MongoDB\Driver\WriteResult MongoDB\Driver\Server::executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, MongoDB\Driver\WriteConcern $writeConcern ] )

Executes one or more write operations on this server.

A MongoDB\Driver\BulkWrite can be constructed with one or more write operations of varying types (e.g. updates, deletes, and inserts). The driver will attempt to send operations of the same type to the server in as few requests as possible to optimize round trips.

Parametri

namespace (string)

Un spa?iu de nume complet calificat (de ex. "databaseName.collectionName").

bulk (MongoDB\Driver\BulkWrite)

MongoDB\Driver\BulkWrite spre a fi executata.

writeConcern (MongoDB\Driver\WriteConcern)

Op?ional un MongoDB\Driver\WriteConcern pentru a fi aplicat la opera?iunea de înscrieire. Daca nu este indicat vre-unul, va fi utilizat "write concern" din MongoDB Connection URI.

Valorile întoarse

Întoarce MongoDB\Driver\WriteResult în caz de succes.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\BulkWriteException la orice e?ec de înscriere (de ex. eroare de înscriere, e?ec la aplicarea unui "write concern")
  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Emite MongoDB\Driver\Exception\ConnectionException daca conexiunea catre server e?ueaza (din alte motive decât autentificarea).
  • Emite MongoDB\Driver\Exception\AuthenticationException daca este necesara autentificare ?i aceasta e?ueaza.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

Note

Nota:

It is the caller's responsibility to ensure that the server is capable of executing the write operation. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

A se vedea ?i

  • MongoDB\Driver\BulkWrite
  • MongoDB\Driver\WriteResult
  • MongoDB\Driver\WriteConcern
  • MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
MongoDB\Driver\Server::__construct
MongoDB\Driver\Server::executeCommand
MongoDB\Driver\Server


Execute a database command on this server

MongoDB\Driver\Server::executeBulkWrite
MongoDB\Driver\Server::executeQuery
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::executeCommand

(mongodb >=1.0.0)

MongoDB\Driver\Server::executeCommand — Execute a database command on this server

Descrierea

final public MongoDB\Driver\Cursor MongoDB\Driver\Server::executeCommand ( string $db , MongoDB\Driver\Command $command [, MongoDB\Driver\ReadPreference $readPreference ] )

Executes command on this server.

Nota:

The readPreference parameter does not control the server to which the driver issues the command; the command will always be executed on this server object. Instead, it may be used when issuing the command to a secondary (from a replica set connection, not standalone) or mongos node to ensure that the driver sets the wire protocol accordingly or adds the read preference to the command document, respectively.

Parametri

db (string)

Denumirea bazei de date asupra careia va fi executata comanda.

command (MongoDB\Driver\Command)

MongoDB\Driver\Command spre a fi executata.

readPreference (MongoDB\Driver\ReadPreference)

Op?ional o MongoDB\Driver\ReadPreference pentru a selecta serverul pentru aceasta opera?iune. Daca nu este indicata vre-una, va fi utilizata preferin?a de citire din MongoDB Connection URI.

Valorile întoarse

Întoarce MongoDB\Driver\Cursor în caz de succes.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Emite MongoDB\Driver\Exception\ConnectionException daca conexiunea catre server e?ueaza (din alte motive decât autentificarea).
  • Emite MongoDB\Driver\Exception\AuthenticationException daca este necesara autentificare ?i aceasta e?ueaza.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command, issuing a write command to a secondary).

Note

Nota:

This method does not take a MongoDB\Driver\WriteConcern parameter. For write commands (e.g. » findAndModify in MongoDB 3.2+), the write concern should be included in the command document itself.

It is the caller's responsibility to ensure that the server is capable of executing the command. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

A se vedea ?i

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\ReadPreference
  • MongoDB\Driver\Manager::executeCommand() - Execute a database command
MongoDB\Driver\Server::executeBulkWrite
MongoDB\Driver\Server::executeQuery
MongoDB\Driver\Server


Execute a database query on this server

MongoDB\Driver\Server::executeCommand
MongoDB\Driver\Server::getHost
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::executeQuery

(mongodb >=1.0.0)

MongoDB\Driver\Server::executeQuery — Execute a database query on this server

Descrierea

final public MongoDB\Driver\Cursor MongoDB\Driver\Server::executeQuery ( string $namespace , MongoDB\Driver\Query $query [, MongoDB\Driver\ReadPreference $readPreference ] )

Executes query on this server.

Nota:

The readPreference parameter does not control the server to which the driver issues the query; the query will always be executed on this server object. Instead, it may be used when issuing the command to a secondary (from a replica set connection, not standalone) or mongos node to ensure that the driver sets the wire protocol accordingly or adds the read preference to the query document, respectively.

Parametri

namespace (string)

Un spa?iu de nume complet calificat (de ex. "databaseName.collectionName").

query (MongoDB\Driver\Query)

MongoDB\Driver\Query spre a fi executata.

readPreference (MongoDB\Driver\ReadPreference)

Op?ional o MongoDB\Driver\ReadPreference pentru a selecta serverul pentru aceasta opera?iune. Daca nu este indicata vre-una, va fi utilizata preferin?a de citire din MongoDB Connection URI.

Valorile întoarse

Întoarce MongoDB\Driver\Cursor în caz de succes.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Emite MongoDB\Driver\Exception\ConnectionException daca conexiunea catre server e?ueaza (din alte motive decât autentificarea).
  • Emite MongoDB\Driver\Exception\AuthenticationException daca este necesara autentificare ?i aceasta e?ueaza.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid query operators).

A se vedea ?i

  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Query
  • MongoDB\Driver\ReadPreference
  • MongoDB\Driver\Manager::executeQuery() - Execute a database query
MongoDB\Driver\Server::executeCommand
MongoDB\Driver\Server::getHost
MongoDB\Driver\Server


Returns the hostname of this server

MongoDB\Driver\Server::executeQuery
MongoDB\Driver\Server::getInfo
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::getHost

(mongodb >=1.0.0)

MongoDB\Driver\Server::getHost — Returns the hostname of this server

Descrierea

final public string MongoDB\Driver\Server::getHost ( void )

Returns the hostname of this server.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the hostname of this server.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Server::getHost() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getHost());

?>

Exemplul de mai sus va afi?a:

string(9) "localhost"

A se vedea ?i

  • MongoDB\Driver\Server::getInfo() - Returns an array of information about this server
MongoDB\Driver\Server::executeQuery
MongoDB\Driver\Server::getInfo
MongoDB\Driver\Server


Returns an array of information about this server

MongoDB\Driver\Server::getHost
MongoDB\Driver\Server::getLatency
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::getInfo

(mongodb >=1.0.0)

MongoDB\Driver\Server::getInfo — Returns an array of information about this server

Descrierea

final public array MongoDB\Driver\Server::getInfo ( void )

Returns an array of information about this server.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array of information about this server.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Server::getInfo() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getInfo());

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(8) {
  ["ismaster"]=>
  bool(true)
  ["maxBsonObjectSize"]=>
  int(16777216)
  ["maxMessageSizeBytes"]=>
  int(48000000)
  ["maxWriteBatchSize"]=>
  int(1000)
  ["localTime"]=>
  object(MongoDB\BSON\UTCDateTime)#4 (1) {
    ["milliseconds"]=>
    int(1447276242774)
  }
  ["maxWireVersion"]=>
  int(3)
  ["minWireVersion"]=>
  int(0)
  ["ok"]=>
  float(1)
}
MongoDB\Driver\Server::getHost
MongoDB\Driver\Server::getLatency
MongoDB\Driver\Server


Returns the latency of this server

MongoDB\Driver\Server::getInfo
MongoDB\Driver\Server::getPort
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::getLatency

(mongodb >=1.0.0)

MongoDB\Driver\Server::getLatency — Returns the latency of this server

Descrierea

final public string MongoDB\Driver\Server::getLatency ( void )

Returns the latency of this server (i.e. the client's measured » round trip time of an ismaster command).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the latency of this server.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Server::getLatency() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getLatency());

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(592)

A se vedea ?i

  • MongoDB\Driver\Server::getInfo() - Returns an array of information about this server
  • » Server Discovery and Monitoring Specification
MongoDB\Driver\Server::getInfo
MongoDB\Driver\Server::getPort
MongoDB\Driver\Server


Returns the port on which this server is listening

MongoDB\Driver\Server::getLatency
MongoDB\Driver\Server::getTags
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::getPort

(mongodb >=1.0.0)

MongoDB\Driver\Server::getPort — Returns the port on which this server is listening

Descrierea

final public int MongoDB\Driver\Server::getPort ( void )

Returns the port on which this server is listening.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the port on which this server is listening.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\Server::getPort() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getPort());

?>

Exemplul de mai sus va afi?a:

int(27017)

A se vedea ?i

  • MongoDB\Driver\Server::getInfo() - Returns an array of information about this server
MongoDB\Driver\Server::getLatency
MongoDB\Driver\Server::getTags
MongoDB\Driver\Server


Returns an array of tags describing this server in a replica set

MongoDB\Driver\Server::getPort
MongoDB\Driver\Server::getType
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::getTags

(mongodb >=1.0.0)

MongoDB\Driver\Server::getTags — Returns an array of tags describing this server in a replica set

Descrierea

final public array MongoDB\Driver\Server::getTags ( void )

Returns an array of » tags used to describe this server in a replica set. The array will contain zero or more string key and value pairs.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array of tags used to describe this server in a replica set.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\Driver\Server::getInfo() - Returns an array of information about this server
MongoDB\Driver\Server::getPort
MongoDB\Driver\Server::getType
MongoDB\Driver\Server


Returns an integer denoting the type of this server

MongoDB\Driver\Server::getTags
MongoDB\Driver\Server::isArbiter
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::getType

(mongodb >=1.0.0)

MongoDB\Driver\Server::getType — Returns an integer denoting the type of this server

Descrierea

final public int MongoDB\Driver\Server::getType ( void )

Returns an integer denoting the type of this server. The value will correlate with a MongoDB\Driver\Server constant.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an integer denoting the type of this server.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\Driver\Server::getInfo() - Returns an array of information about this server
MongoDB\Driver\Server::getTags
MongoDB\Driver\Server::isArbiter
MongoDB\Driver\Server


Checks if this server is an arbiter member of a replica set

MongoDB\Driver\Server::getType
MongoDB\Driver\Server::isHidden
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::isArbiter

(mongodb >=1.0.0)

MongoDB\Driver\Server::isArbiter — Checks if this server is an arbiter member of a replica set

Descrierea

final public bool MongoDB\Driver\Server::isArbiter ( void )

Returns whether this server is an » arbiter member of a replica set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if this server is an arbiter member of a replica set, and FALSE otherwise.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\Driver\Server::getInfo() - Returns an array of information about this server
MongoDB\Driver\Server::getType
MongoDB\Driver\Server::isHidden
MongoDB\Driver\Server


Checks if this server is a hidden member of a replica set

MongoDB\Driver\Server::isArbiter
MongoDB\Driver\Server::isPassive
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::isHidden

(mongodb >=1.0.0)

MongoDB\Driver\Server::isHidden — Checks if this server is a hidden member of a replica set

Descrierea

final public bool MongoDB\Driver\Server::isHidden ( void )

Returns whether this server is a » hidden member of a replica set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if this server is a hidden member of a replica set, and FALSE otherwise.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\Driver\Server::getInfo() - Returns an array of information about this server
MongoDB\Driver\Server::isArbiter
MongoDB\Driver\Server::isPassive
MongoDB\Driver\Server


Checks if this server is a passive member of a replica set

MongoDB\Driver\Server::isHidden
MongoDB\Driver\Server::isPrimary
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::isPassive

(mongodb >=1.0.0)

MongoDB\Driver\Server::isPassive — Checks if this server is a passive member of a replica set

Descrierea

final public bool MongoDB\Driver\Server::isPassive ( void )

Returns whether this server is a » passive member of a replica set (i.e. its priority is 0).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if this server is a passive member of a replica set, and FALSE otherwise.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\Driver\Server::getInfo() - Returns an array of information about this server
MongoDB\Driver\Server::isHidden
MongoDB\Driver\Server::isPrimary
MongoDB\Driver\Server


Checks if this server is a primary member of a replica set

MongoDB\Driver\Server::isPassive
MongoDB\Driver\Server::isSecondary
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::isPrimary

(mongodb >=1.0.0)

MongoDB\Driver\Server::isPrimary — Checks if this server is a primary member of a replica set

Descrierea

final public bool MongoDB\Driver\Server::isPrimary ( void )

Returns whether this server is a » primary member of a replica set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if this server is a primary member of a replica set, and FALSE otherwise.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\Driver\Server::getInfo() - Returns an array of information about this server
MongoDB\Driver\Server::isPassive
MongoDB\Driver\Server::isSecondary
MongoDB\Driver\Server


Checks if this server is a secondary member of a replica set

MongoDB\Driver\Server::isPrimary
MongoDB\Driver\WriteConcernError
MongoDB\Driver\Server
PHP Manual

MongoDB\Driver\Server::isSecondary

(mongodb >=1.0.0)

MongoDB\Driver\Server::isSecondary — Checks if this server is a secondary member of a replica set

Descrierea

final public bool MongoDB\Driver\Server::isSecondary ( void )

Returns whether this server is a » secondary member of a replica set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if this server is a secondary member of a replica set, and FALSE otherwise.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\Driver\Server::getInfo() - Returns an array of information about this server
MongoDB\Driver\Server::isPrimary
MongoDB\Driver\WriteConcernError
MongoDB\Driver\Server


The MongoDB\Driver\WriteConcernError class

(mongodb >=1.0.0)

Introducere

The MongoDB\Driver\WriteConcernError class encapsulates information about a write concern error and may be returned by MongoDB\Driver\WriteResult::getWriteConcernError().

Sinopsisul clasei

final MongoDB\Driver\WriteConcernError {
/* Metode */
final public int getCode ( void )
final public mixed getInfo ( void )
final public string getMessage ( void )
}

Cuprins

  • MongoDB\Driver\WriteConcernError::getCode — Returns the WriteConcernError's error code
  • MongoDB\Driver\WriteConcernError::getInfo — Returns additional metadata for the WriteConcernError
  • MongoDB\Driver\WriteConcernError::getMessage — Returns the WriteConcernError's error message
MongoDB\Driver\Server::isSecondary
MongoDB\Driver\WriteConcernError::getCode
MongoDB\Driver


Returns the WriteConcernError's error code

MongoDB\Driver\WriteConcernError
MongoDB\Driver\WriteConcernError::getInfo
MongoDB\Driver\WriteConcernError
PHP Manual

MongoDB\Driver\WriteConcernError::getCode

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcernError::getCode — Returns the WriteConcernError's error code

Descrierea

final public int MongoDB\Driver\WriteConcernError::getCode ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the WriteConcernError's error code.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteConcernError::getCode() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);

try {
    $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteConcernError()->getCode());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(64)

A se vedea ?i

  • » Write Concern reference
MongoDB\Driver\WriteConcernError
MongoDB\Driver\WriteConcernError::getInfo
MongoDB\Driver\WriteConcernError


Returns additional metadata for the WriteConcernError

MongoDB\Driver\WriteConcernError::getCode
MongoDB\Driver\WriteConcernError::getMessage
MongoDB\Driver\WriteConcernError
PHP Manual

MongoDB\Driver\WriteConcernError::getInfo

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcernError::getInfo — Returns additional metadata for the WriteConcernError

Descrierea

final public mixed MongoDB\Driver\WriteConcernError::getInfo ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns additional metadata for the WriteConcernError, or NULL if no metadata is available.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteConcernError::getInfo() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);

try {
    $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteConcernError()->getInfo());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(stdClass)#1 (1) {
  ["wtimeout"]=>
  bool(true)
}

A se vedea ?i

  • » Write Concern reference
MongoDB\Driver\WriteConcernError::getCode
MongoDB\Driver\WriteConcernError::getMessage
MongoDB\Driver\WriteConcernError


Returns the WriteConcernError's error message

MongoDB\Driver\WriteConcernError::getInfo
MongoDB\Driver\WriteError
MongoDB\Driver\WriteConcernError
PHP Manual

MongoDB\Driver\WriteConcernError::getMessage

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcernError::getMessage — Returns the WriteConcernError's error message

Descrierea

final public string MongoDB\Driver\WriteConcernError::getMessage ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the WriteConcernError's error message.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteConcernError::getMessage() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);

try {
    $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteConcernError()->getMessage());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(33) "waiting for replication timed out"

A se vedea ?i

  • » Write Concern reference
MongoDB\Driver\WriteConcernError::getInfo
MongoDB\Driver\WriteError
MongoDB\Driver\WriteConcernError


The MongoDB\Driver\WriteError class

(mongodb >=1.0.0)

Introducere

The MongoDB\Driver\WriteError class encapsulates information about a write error and may be returned as an array element from MongoDB\Driver\WriteResult::getWriteErrors().

Sinopsisul clasei

final MongoDB\Driver\WriteError {
/* Metode */
final public int getCode ( void )
final public int getIndex ( void )
final public mixed getInfo ( void )
final public string getMessage ( void )
}

Cuprins

  • MongoDB\Driver\WriteError::getCode — Returns the WriteError's error code
  • MongoDB\Driver\WriteError::getIndex — Returns the index of the write operation corresponding to this WriteError
  • MongoDB\Driver\WriteError::getInfo — Returns additional metadata for the WriteError
  • MongoDB\Driver\WriteError::getMessage — Returns the WriteError's error message
MongoDB\Driver\WriteConcernError::getMessage
MongoDB\Driver\WriteError::getCode
MongoDB\Driver


Returns the WriteError's error code

MongoDB\Driver\WriteError
MongoDB\Driver\WriteError::getIndex
MongoDB\Driver\WriteError
PHP Manual

MongoDB\Driver\WriteError::getCode

(mongodb >=1.0.0)

MongoDB\Driver\WriteError::getCode — Returns the WriteError's error code

Descrierea

final public int MongoDB\Driver\WriteError::getCode ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the WriteError's error code.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteError::getCode() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);

try {
    $manager->executeBulkWrite('db.collection', $bulk);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteErrors()[0]->getCode());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(11000)
MongoDB\Driver\WriteError
MongoDB\Driver\WriteError::getIndex
MongoDB\Driver\WriteError


Returns the index of the write operation corresponding to this WriteError

MongoDB\Driver\WriteError::getCode
MongoDB\Driver\WriteError::getInfo
MongoDB\Driver\WriteError
PHP Manual

MongoDB\Driver\WriteError::getIndex

(mongodb >=1.0.0)

MongoDB\Driver\WriteError::getIndex — Returns the index of the write operation corresponding to this WriteError

Descrierea

final public int MongoDB\Driver\WriteError::getIndex ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the index of the write operation (from MongoDB\Driver\BulkWrite) corresponding to this WriteError.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteError::getIndex() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);

try {
    $manager->executeBulkWrite('db.collection', $bulk);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteErrors()[0]->getIndex());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(1)

A se vedea ?i

  • MongoDB\Driver\BulkWrite
MongoDB\Driver\WriteError::getCode
MongoDB\Driver\WriteError::getInfo
MongoDB\Driver\WriteError


Returns additional metadata for the WriteError

MongoDB\Driver\WriteError::getIndex
MongoDB\Driver\WriteError::getMessage
MongoDB\Driver\WriteError
PHP Manual

MongoDB\Driver\WriteError::getInfo

(mongodb >=1.0.0)

MongoDB\Driver\WriteError::getInfo — Returns additional metadata for the WriteError

Descrierea

final public mixed MongoDB\Driver\WriteError::getInfo ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns additional metadata for the WriteError, or NULL if no metadata is available.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
MongoDB\Driver\WriteError::getIndex
MongoDB\Driver\WriteError::getMessage
MongoDB\Driver\WriteError


Returns the WriteError's error message

MongoDB\Driver\WriteError::getInfo
MongoDB\Driver\WriteResult
MongoDB\Driver\WriteError
PHP Manual

MongoDB\Driver\WriteError::getMessage

(mongodb >=1.0.0)

MongoDB\Driver\WriteError::getMessage — Returns the WriteError's error message

Descrierea

final public string MongoDB\Driver\WriteError::getMessage ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the WriteError's error message.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteError::getMessage() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);

try {
    $manager->executeBulkWrite('db.collection', $bulk);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteErrors()[0]->getMessage());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(70) "E11000 duplicate key error index: db.collection.$_id_ dup key: { : 1 }"
MongoDB\Driver\WriteError::getInfo
MongoDB\Driver\WriteResult
MongoDB\Driver\WriteError


The MongoDB\Driver\WriteResult class

(mongodb >=1.0.0)

Introducere

The MongoDB\Driver\WriteResult class encapsulates information about an executed MongoDB\Driver\BulkWrite and may be returned by MongoDB\Driver\Manager::executeBulkWrite().

Sinopsisul clasei

final MongoDB\Driver\WriteResult {
/* Metode */
final public int|null getDeletedCount ( void )
final public int|null getInsertedCount ( void )
final public int|null getMatchedCount ( void )
final public int|null getModifiedCount ( void )
final public MongoDB\Driver\Server getServer ( void )
final public int|null getUpsertedCount ( void )
final public array getUpsertedIds ( void )
final public MongoDB\Driver\WriteConcernError|null getWriteConcernError ( void )
final public array getWriteErrors ( void )
final public bool isAcknowledged ( void )
}

Cuprins

  • MongoDB\Driver\WriteResult::getDeletedCount — Returns the number of documents deleted
  • MongoDB\Driver\WriteResult::getInsertedCount — Returns the number of documents inserted (excluding upserts)
  • MongoDB\Driver\WriteResult::getMatchedCount — Returns the number of documents selected for update
  • MongoDB\Driver\WriteResult::getModifiedCount — Returns the number of existing documents updated
  • MongoDB\Driver\WriteResult::getServer — Returns the server associated with this write result
  • MongoDB\Driver\WriteResult::getUpsertedCount — Returns the number of documents inserted by an upsert
  • MongoDB\Driver\WriteResult::getUpsertedIds — Returns an array of identifiers for upserted documents
  • MongoDB\Driver\WriteResult::getWriteConcernError — Returns any write concern error that occurred
  • MongoDB\Driver\WriteResult::getWriteErrors — Returns any write errors that occurred
  • MongoDB\Driver\WriteResult::isAcknowledged — Returns whether the write was acknowledged
MongoDB\Driver\WriteError::getMessage
MongoDB\Driver\WriteResult::getDeletedCount
MongoDB\Driver


Returns the number of documents deleted

MongoDB\Driver\WriteResult
MongoDB\Driver\WriteResult::getInsertedCount
MongoDB\Driver\WriteResult
PHP Manual

MongoDB\Driver\WriteResult::getDeletedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getDeletedCount — Returns the number of documents deleted

Descrierea

final public int|null MongoDB\Driver\WriteResult::getDeletedCount ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the number of documents deleted, or NULL if the write was not acknowledged.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteResult::getDeletedCount() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getDeletedCount());

?>

Exemplul de mai sus va afi?a:

int(1)

A se vedea ?i

  • MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged
MongoDB\Driver\WriteResult
MongoDB\Driver\WriteResult::getInsertedCount
MongoDB\Driver\WriteResult


Returns the number of documents inserted (excluding upserts)

MongoDB\Driver\WriteResult::getDeletedCount
MongoDB\Driver\WriteResult::getMatchedCount
MongoDB\Driver\WriteResult
PHP Manual

MongoDB\Driver\WriteResult::getInsertedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getInsertedCount — Returns the number of documents inserted (excluding upserts)

Descrierea

final public int|null MongoDB\Driver\WriteResult::getInsertedCount ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the number of documents inserted (excluding upserts), or NULL if the write was not acknowledged.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteResult::getInsertedCount() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getInsertedCount());

?>

Exemplul de mai sus va afi?a:

int(1)

A se vedea ?i

  • MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged
MongoDB\Driver\WriteResult::getDeletedCount
MongoDB\Driver\WriteResult::getMatchedCount
MongoDB\Driver\WriteResult


Returns the number of documents selected for update

MongoDB\Driver\WriteResult::getInsertedCount
MongoDB\Driver\WriteResult::getModifiedCount
MongoDB\Driver\WriteResult
PHP Manual

MongoDB\Driver\WriteResult::getMatchedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getMatchedCount — Returns the number of documents selected for update

Descrierea

final public int|null MongoDB\Driver\WriteResult::getMatchedCount ( void )

If the update operation results in no change to the document (e.g. setting the value of a field to its current value), the matched count may be greater than the value returned by MongoDB\Driver\WriteResult::getModifiedCount().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the number of documents selected for update, or NULL if the write was not acknowledged.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteResult::getMatchedCount() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getMatchedCount());

?>

Exemplul de mai sus va afi?a:

int(1)

A se vedea ?i

  • MongoDB\Driver\WriteResult::getModifiedCount() - Returns the number of existing documents updated
  • MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged
MongoDB\Driver\WriteResult::getInsertedCount
MongoDB\Driver\WriteResult::getModifiedCount
MongoDB\Driver\WriteResult


Returns the number of existing documents updated

MongoDB\Driver\WriteResult::getMatchedCount
MongoDB\Driver\WriteResult::getServer
MongoDB\Driver\WriteResult
PHP Manual

MongoDB\Driver\WriteResult::getModifiedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getModifiedCount — Returns the number of existing documents updated

Descrierea

final public int|null MongoDB\Driver\WriteResult::getModifiedCount ( void )

If the update operation results in no change to the document (e.g. setting the value of a field to its current value), the modified count may be less than the value returned by MongoDB\Driver\WriteResult::getMatchedCount().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the number of existing documents updated, or NULL if the write was not acknowledged.

The modified count is not available on versions of MongoDB before 2.6, which used the legacy wire protocol version (i.e. OP_UPDATE). If this is the case, the modified count will also be NULL.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteResult::getModifiedCount() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getModifiedCount());

?>

Exemplul de mai sus va afi?a:

int(1)

A se vedea ?i

  • MongoDB\Driver\WriteResult::getMatchedCount() - Returns the number of documents selected for update
  • MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged
MongoDB\Driver\WriteResult::getMatchedCount
MongoDB\Driver\WriteResult::getServer
MongoDB\Driver\WriteResult


Returns the server associated with this write result

MongoDB\Driver\WriteResult::getModifiedCount
MongoDB\Driver\WriteResult::getUpsertedCount
MongoDB\Driver\WriteResult
PHP Manual

MongoDB\Driver\WriteResult::getServer

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getServer — Returns the server associated with this write result

Descrierea

final public MongoDB\Driver\Server MongoDB\Driver\WriteResult::getServer ( void )

Returns the MongoDB\Driver\Server associated with this write result. This is the server that executed the MongoDB\Driver\BulkWrite.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the MongoDB\Driver\Server associated with this write result.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteResult::getServer() example

<?php

$manager = new MongoDB\Driver\Manager;
$server = $manager->selectServer(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY));

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$result = $server->executeBulkWrite('db.collection', $bulk);

var_dump($result->getServer() == $server);

?>

Exemplul de mai sus va afi?a:

bool(true)

A se vedea ?i

  • MongoDB\Driver\Server
MongoDB\Driver\WriteResult::getModifiedCount
MongoDB\Driver\WriteResult::getUpsertedCount
MongoDB\Driver\WriteResult


Returns the number of documents inserted by an upsert

MongoDB\Driver\WriteResult::getServer
MongoDB\Driver\WriteResult::getUpsertedIds
MongoDB\Driver\WriteResult
PHP Manual

MongoDB\Driver\WriteResult::getUpsertedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getUpsertedCount — Returns the number of documents inserted by an upsert

Descrierea

final public int|null MongoDB\Driver\WriteResult::getUpsertedCount ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the number of documents inserted by an upsert.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteResult::getUpsertedCount() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getUpsertedCount());

?>

Exemplul de mai sus va afi?a:

int(2)

A se vedea ?i

  • MongoDB\Driver\WriteResult::getUpsertedIds() - Returns an array of identifiers for upserted documents
  • MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged
MongoDB\Driver\WriteResult::getServer
MongoDB\Driver\WriteResult::getUpsertedIds
MongoDB\Driver\WriteResult


Returns an array of identifiers for upserted documents

MongoDB\Driver\WriteResult::getUpsertedCount
MongoDB\Driver\WriteResult::getWriteConcernError
MongoDB\Driver\WriteResult
PHP Manual

MongoDB\Driver\WriteResult::getUpsertedIds

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getUpsertedIds — Returns an array of identifiers for upserted documents

Descrierea

final public array MongoDB\Driver\WriteResult::getUpsertedIds ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array of identifiers (i.e. "_id" field values) for upserted documents. The array keys will correspond to the index of the write operation (from MongoDB\Driver\BulkWrite) responsible for the upsert.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteResult::getUpsertedIds() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getUpsertedIds());

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  [2]=>
  object(MongoDB\BSON\ObjectID)#4 (1) {
    ["oid"]=>
    string(24) "580e62a224f2302f191b880b"
  }
  [3]=>
  object(MongoDB\BSON\ObjectID)#5 (1) {
    ["oid"]=>
    string(24) "580e62a224f2302f191b880c"
  }
}

A se vedea ?i

  • MongoDB\Driver\WriteResult::getUpsertedCount() - Returns the number of documents inserted by an upsert
  • MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged
MongoDB\Driver\WriteResult::getUpsertedCount
MongoDB\Driver\WriteResult::getWriteConcernError
MongoDB\Driver\WriteResult


Returns any write concern error that occurred

MongoDB\Driver\WriteResult::getUpsertedIds
MongoDB\Driver\WriteResult::getWriteErrors
MongoDB\Driver\WriteResult
PHP Manual

MongoDB\Driver\WriteResult::getWriteConcernError

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getWriteConcernError — Returns any write concern error that occurred

Descrierea

final public MongoDB\Driver\WriteConcernError|null MongoDB\Driver\WriteResult::getWriteConcernError ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a MongoDB\Driver\WriteConcernError if a write concern error was encountered during the write operation, and NULL otherwise.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteResult::getWriteConcernError() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);

try {
    $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteConcernError());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(MongoDB\Driver\WriteConcernError)#6 (3) {
  ["message"]=>
  string(33) "waiting for replication timed out"
  ["code"]=>
  int(64)
  ["info"]=>
  object(stdClass)#7 (1) {
    ["wtimeout"]=>
    bool(true)
  }
}

A se vedea ?i

  • MongoDB\Driver\WriteConcern
  • » Write Concern reference
MongoDB\Driver\WriteResult::getUpsertedIds
MongoDB\Driver\WriteResult::getWriteErrors
MongoDB\Driver\WriteResult


Returns any write errors that occurred

MongoDB\Driver\WriteResult::getWriteConcernError
MongoDB\Driver\WriteResult::isAcknowledged
MongoDB\Driver\WriteResult
PHP Manual

MongoDB\Driver\WriteResult::getWriteErrors

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getWriteErrors — Returns any write errors that occurred

Descrierea

final public array MongoDB\Driver\WriteResult::getWriteErrors ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array of MongoDB\Driver\WriteError objects for any write errors encountered during the write operation. The array will be empty if no write errors occurred.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteResult::getWriteErrors() with a single error

<?php

$manager = new MongoDB\Driver\Manager;

/* By default, bulk write operations are executed serially in order and
 * execution will stop after the first error.
 */
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 4]);

try {
    $result = $manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteErrors());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [0]=>
  object(MongoDB\Driver\WriteError)#5 (4) {
    ["message"]=>
    string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 2 }"
    ["code"]=>
    int(11000)
    ["index"]=>
    int(2)
    ["info"]=>
    NULL
  }
}

Example #2 MongoDB\Driver\WriteResult::getWriteErrors() with multiple errors

<?php

$manager = new MongoDB\Driver\Manager;

/* The "ordered" option may be used to allow bulk write operations to continue
 * executing after the first error is encountered.
 */
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 4]);

try {
    $result = $manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteErrors());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  [0]=>
  object(MongoDB\Driver\WriteError)#5 (4) {
    ["message"]=>
    string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 2 }"
    ["code"]=>
    int(11000)
    ["index"]=>
    int(2)
    ["info"]=>
    NULL
  }
  [1]=>
  object(MongoDB\Driver\WriteError)#6 (4) {
    ["message"]=>
    string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 4 }"
    ["code"]=>
    int(11000)
    ["index"]=>
    int(5)
    ["info"]=>
    NULL
  }
}

A se vedea ?i

  • MongoDB\Driver\WriteError
MongoDB\Driver\WriteResult::getWriteConcernError
MongoDB\Driver\WriteResult::isAcknowledged
MongoDB\Driver\WriteResult


Returns whether the write was acknowledged

MongoDB\Driver\WriteResult::getWriteErrors
MongoDB\Driver\BSON
MongoDB\Driver\WriteResult
PHP Manual

MongoDB\Driver\WriteResult::isAcknowledged

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::isAcknowledged — Returns whether the write was acknowledged

Descrierea

final public bool MongoDB\Driver\WriteResult::isAcknowledged ( void )

If the write is acknowledged, other count fields will be available on the MongoDB\Driver\WriteResult object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the write was acknowledged, and FALSE otherwise.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\Driver\WriteResult::isAcknowledged() with acknowledged write concern

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->isAcknowledged());

?>

Exemplul de mai sus va afi?a:

bool(true)

Example #2 MongoDB\Driver\WriteResult::isAcknowledged() with unacknowledged write concern

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk, new MongoDB\Driver\WriteConcern(0));

var_dump($result->isAcknowledged());

?>

Exemplul de mai sus va afi?a:

bool(false)

A se vedea ?i

  • MongoDB\Driver\WriteConcern
  • » Write Concern reference
MongoDB\Driver\WriteResult::getWriteErrors
MongoDB\Driver\BSON
MongoDB\Driver\WriteResult


Clase ?i func?ii de serializare de tip BSON

  • Func?ii
    • MongoDB\BSON\fromJSON — Returns the BSON representation of a JSON value
    • MongoDB\BSON\fromPHP — Returns the BSON representation of a PHP value
    • MongoDB\BSON\toJSON — Returns the JSON representation of a BSON value
    • MongoDB\BSON\toPHP — Returns the PHP representation of a BSON value
  • MongoDB\BSON\Binary — The MongoDB\BSON\Binary class
    • MongoDB\BSON\Binary::__construct — Construct a new Binary
    • MongoDB\BSON\Binary::getData — Returns the Binary's data
    • MongoDB\BSON\Binary::getType — Returns the Binary's type
    • MongoDB\BSON\Binary::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Binary::serialize — Serialize a Binary
    • MongoDB\BSON\Binary::__toString — Returns the Binary's data
    • MongoDB\BSON\Binary::unserialize — Unserialize a Binary
  • MongoDB\BSON\Javascript — The MongoDB\BSON\Javascript class
    • MongoDB\BSON\Javascript::__construct — Construct a new Javascript
    • MongoDB\BSON\Javascript::getCode — Returns the Javascript's code
    • MongoDB\BSON\Javascript::getScope — Returns the Javascript's scope document
    • MongoDB\BSON\Javascript::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Javascript::serialize — Serialize a Javascript
    • MongoDB\BSON\Javascript::__toString — Returns the Javascript's code
    • MongoDB\BSON\Javascript::unserialize — Unserialize a Javascript
  • MongoDB\BSON\MaxKey — The MongoDB\BSON\MaxKey class
    • MongoDB\BSON\MaxKey::__construct — Construct a new MaxKey
    • MongoDB\BSON\MaxKey::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\MaxKey::serialize — Serialize a MaxKey
    • MongoDB\BSON\MaxKey::unserialize — Unserialize a MaxKey
  • MongoDB\BSON\MinKey — The MongoDB\BSON\MinKey class
    • MongoDB\BSON\MinKey::__construct — Construct a new MinKey
    • MongoDB\BSON\MinKey::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\MinKey::serialize — Serialize a MinKey
    • MongoDB\BSON\MinKey::unserialize — Unserialize a MinKey
  • MongoDB\BSON\ObjectID — The MongoDB\BSON\ObjectID class
    • MongoDB\BSON\ObjectID::__construct — Construct a new ObjectID
    • MongoDB\BSON\ObjectID::getTimestamp — Returns the timestamp component of this ObjectID
    • MongoDB\BSON\ObjectID::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\ObjectID::serialize — Serialize an ObjectID
    • MongoDB\BSON\ObjectID::__toString — Returns the hexidecimal representation of this ObjectID
    • MongoDB\BSON\ObjectID::unserialize — Unserialize an ObjectID
  • MongoDB\BSON\Regex — The MongoDB\BSON\Regex class
    • MongoDB\BSON\Regex::__construct — Construct a new Regex
    • MongoDB\BSON\Regex::getFlags — Returns the Regex's flags
    • MongoDB\BSON\Regex::getPattern — Returns the Regex's pattern
    • MongoDB\BSON\Regex::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Regex::serialize — Serialize a Regex
    • MongoDB\BSON\Regex::__toString — Returns the string representation of this Regex
    • MongoDB\BSON\Regex::unserialize — Unserialize a Regex
  • MongoDB\BSON\Timestamp — The MongoDB\BSON\Timestamp class
    • MongoDB\BSON\Timestamp::__construct — Construct a new Timestamp
    • MongoDB\BSON\Timestamp::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Timestamp::serialize — Serialize a Timestamp
    • MongoDB\BSON\Timestamp::__toString — Returns the string representation of this Timestamp
    • MongoDB\BSON\Timestamp::unserialize — Unserialize a Timestamp
  • MongoDB\BSON\UTCDateTime — The MongoDB\BSON\UTCDateTime class
    • MongoDB\BSON\UTCDateTime::__construct — Construct a new UTCDateTime
    • MongoDB\BSON\UTCDateTime::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\UTCDateTime::serialize — Serialize a UTCDateTime
    • MongoDB\BSON\UTCDateTime::toDateTime — Returns the DateTime representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTime::__toString — Returns the string representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTime::unserialize — Unserialize a UTCDateTime
  • MongoDB\BSON\Type — The MongoDB\BSON\Type interface
  • MongoDB\BSON\Persistable — The MongoDB\BSON\Persistable interface
  • MongoDB\BSON\Serializable — The MongoDB\BSON\Serializable interface
    • MongoDB\BSON\Serializable::bsonSerialize — Provides an array or document to serialize as BSON
  • MongoDB\BSON\Unserializable — The MongoDB\BSON\Unserializable interface
    • MongoDB\BSON\Unserializable::bsonUnserialize — Constructs the object from a BSON array or document
MongoDB\Driver\WriteResult::isAcknowledged
Func?ii
MongoDB


Func?ii

Cuprins

  • MongoDB\BSON\fromJSON — Returns the BSON representation of a JSON value
  • MongoDB\BSON\fromPHP — Returns the BSON representation of a PHP value
  • MongoDB\BSON\toJSON — Returns the JSON representation of a BSON value
  • MongoDB\BSON\toPHP — Returns the PHP representation of a BSON value
MongoDB\Driver\BSON
MongoDB\BSON\fromJSON
MongoDB\Driver\BSON


Returns the BSON representation of a JSON value

Func?ii
MongoDB\BSON\fromPHP
Func?ii
PHP Manual

MongoDB\BSON\fromJSON

(mongodb >=1.0.0)

MongoDB\BSON\fromJSON — Returns the BSON representation of a JSON value

Descrierea

string MongoDB\BSON\fromJSON ( string $json )

Converts an » extended JSON string to its BSON representation.

Parametri

json (string)

JSON value to be converted.

Valorile întoarse

The serialized BSON document as a binary string.

Erori/Excep?ii

Throws MongoDB\Driver\Exception\UnexpectedValueException if the JSON value cannot be converted to BSON (e.g. due to a syntax error).

Exemple

Example #1 MongoDB\BSON\fromJSON() example

<?php

$json = '{ "_id": { "$oid": "563143b280d2387c91807965" } }';
$bson = MongoDB\BSON\fromJSON($json);
$value = MongoDB\BSON\toPHP($bson);
var_dump($value);

?>

Exemplul de mai sus va afi?a:

object(stdClass)#2 (1) {
  ["_id"]=>
  object(MongoDB\BSON\ObjectID)#1 (1) {
    ["oid"]=>
    string(24) "563143b280d2387c91807965"
  }
}

A se vedea ?i

  • MongoDB\BSON\toJSON() - Returns the JSON representation of a BSON value
  • » MongoDB Extended JSON
  • » MongoDB BSON
Func?ii
MongoDB\BSON\fromPHP
Func?ii


Returns the BSON representation of a PHP value

MongoDB\BSON\fromJSON
MongoDB\BSON\toJSON
Func?ii
PHP Manual

MongoDB\BSON\fromPHP

(mongodb >=1.0.0)

MongoDB\BSON\fromPHP — Returns the BSON representation of a PHP value

Descrierea

string MongoDB\BSON\fromPHP ( array|object $value )

Serializes a PHP array or object (e.g. document) to its » BSON representation. The returned binary string will describe a BSON document.

Parametri

value (array|object)

PHP value to be serialized.

Valorile întoarse

The serialized BSON document as a binary string.

Erori/Excep?ii

Throws MongoDB\Driver\Exception\UnexpectedValueException if the PHP value cannot be converted to BSON. Possible reasons include, but are not limited to, encountering an unexpected MongoDB\BSON\Type instance or MongoDB\BSON\Serializable::bsonSerialize() failing to return an array or stdClass.

Exemple

Example #1 MongoDB\BSON\fromPHP() example

<?php

$bson = MongoDB\BSON\fromPHP(['foo' => 1]);
echo bin2hex($bson), "\n";

?>

Exemplul de mai sus va afi?a:

0e00000010666f6f000100000000cat

A se vedea ?i

  • MongoDB\BSON\toPHP() - Returns the PHP representation of a BSON value
  • » MongoDB BSON
  • Persisting Data
MongoDB\BSON\fromJSON
MongoDB\BSON\toJSON
Func?ii


Returns the JSON representation of a BSON value

MongoDB\BSON\fromPHP
MongoDB\BSON\toPHP
Func?ii
PHP Manual

MongoDB\BSON\toJSON

(mongodb >=1.0.0)

MongoDB\BSON\toJSON — Returns the JSON representation of a BSON value

Descrierea

string MongoDB\BSON\toJSON ( string $bson )

Converts a BSON string to its » extended JSON representation.

Parametri

bson (string)

BSON value to be converted.

Valorile întoarse

The converted JSON value.

Erori/Excep?ii

Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

Exemple

Example #1 MongoDB\BSON\toJSON() example

<?php

$document = ['_id' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1')];
$bson = MongoDB\BSON\fromPHP($document);
echo MongoDB\BSON\toJSON($bson), "\n";

?>

Exemplul de mai sus va afi?a:

{ "_id" : { "$oid" : "56315a7c6118fd1b920270b1" } }

A se vedea ?i

  • MongoDB\BSON\fromJSON() - Returns the BSON representation of a JSON value
  • » MongoDB Extended JSON
  • » MongoDB BSON
MongoDB\BSON\fromPHP
MongoDB\BSON\toPHP
Func?ii


Returns the PHP representation of a BSON value

MongoDB\BSON\toJSON
MongoDB\BSON\Binary
Func?ii
PHP Manual

MongoDB\BSON\toPHP

(mongodb >=1.0.0)

MongoDB\BSON\toPHP — Returns the PHP representation of a BSON value

Descrierea

array|object MongoDB\BSON\toPHP ( string $bson [, array $typeMap = array() ] )

Unserializes a BSON document (i.e. binary string) to its PHP representation. The typeMap paramater may be used to control the PHP types used for converting BSON arrays and documents (both root and embedded).

Parametri

bson (string)

BSON value to be unserialized.

typeMap (array)

configura?ia Type map.

Valorile întoarse

The unserialized PHP value.

Erori/Excep?ii

Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.

Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

Exemple

Example #1 MongoDB\BSON\toPHP() example

<?php

$bson = hex2bin('0e00000010666f6f000100000000');
$value = MongoDB\BSON\toPHP($bson);
var_dump($value);

?>

Exemplul de mai sus va afi?a:

object(stdClass)#1 (1) {
  ["foo"]=>
  int(1)
}

A se vedea ?i

  • MongoDB\BSON\fromPHP() - Returns the BSON representation of a PHP value
  • » MongoDB BSON
  • Persisting Data
MongoDB\BSON\toJSON
MongoDB\BSON\Binary
Func?ii


The MongoDB\BSON\Binary class

(mongodb >=1.0.0)

Introducere

Sinopsisul clasei

MongoDB\BSON\Binary implements MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Constants */
const integer TYPE_GENERIC = 0 ;
const integer TYPE_FUNCTION = 1 ;
const integer TYPE_OLD_BINARY = 2 ;
const integer TYPE_OLD_UUID = 3 ;
const integer TYPE_UUID = 4 ;
const integer TYPE_MD5 = 5 ;
const integer TYPE_USER_DEFINED = 128 ;
/* Metode */
final public __construct ( string $data , integer $type )
final public string getData ( void )
final public integer getType ( void )
final public mixed jsonSerialize ( void )
final public string serialize ( void )
final public string __toString ( void )
final public void unserialize ( string $serialized )
}

Constante predefinite

MongoDB\BSON\Binary::TYPE_GENERIC

Generic binary data.

MongoDB\BSON\Binary::TYPE_FUNCTION

Function.

MongoDB\BSON\Binary::TYPE_OLD_BINARY

Generic binary data (deprecated in favor of MongoDB\BSON\Binary::TYPE_GENERIC).

MongoDB\BSON\Binary::TYPE_OLD_UUID

Universally unique identifier (deprecated in favor of MongoDB\BSON\Binary::TYPE_UUID). When using this type, the Binary's data should be 16 bytes in length.

Historically, other drivers encoded values with this type based on their language conventions (e.g. varying endianness), which makes it non-portable. The PHP driver applies no special handling for encoding or decoding data with this type.

MongoDB\BSON\Binary::TYPE_UUID

Universally unique identifier. When using this type, the Binary's data should be 16 bytes in length and encoded according to » RFC 4122.

MongoDB\BSON\Binary::TYPE_MD5

MD5 hash. When using this type, the Binary's data should be 16 bytes in length.

MongoDB\BSON\Binary::TYPE_USER_DEFINED

User-defined type. While types between 0 and 127 are predefined or reserved, types between 128 and 255 are user-defined and may be used for anything.

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Implements Serializable and JsonSerializable.

Cuprins

  • MongoDB\BSON\Binary::__construct — Construct a new Binary
  • MongoDB\BSON\Binary::getData — Returns the Binary's data
  • MongoDB\BSON\Binary::getType — Returns the Binary's type
  • MongoDB\BSON\Binary::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Binary::serialize — Serialize a Binary
  • MongoDB\BSON\Binary::__toString — Returns the Binary's data
  • MongoDB\BSON\Binary::unserialize — Unserialize a Binary
MongoDB\BSON\toPHP
MongoDB\BSON\Binary::__construct
MongoDB\Driver\BSON


Construct a new Binary

MongoDB\BSON\Binary
MongoDB\BSON\Binary::getData
MongoDB\BSON\Binary
PHP Manual

MongoDB\BSON\Binary::__construct

(mongodb >=1.0.0)

MongoDB\BSON\Binary::__construct — Construct a new Binary

Descrierea

final public MongoDB\BSON\Binary::__construct ( string $data , integer $type )

Parametri

data (string)

Binary data.

type (integer)

Unsigned 8-bit integer denoting the data's type.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if type is not an unsigned 8-bit integer.

Istoricul schimbarilor

Versiune | Descriere
1.1.3 | MongoDB\Driver\Exception\InvalidArgumentException is thrown if type is not an unsigned 8-bit integer.

Exemple

Example #1 MongoDB\BSON\Binary::__construct() example

<?php

$binary = new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC);
var_dump($binary);

?>

Exemplul de mai sus va afi?a:

object(MongoDB\BSON\Binary)#1 (2) {
  ["data"]=>
  string(3) "foo"
  ["type"]=>
  int(0)
}

A se vedea ?i

  • » BSON Types
MongoDB\BSON\Binary
MongoDB\BSON\Binary::getData
MongoDB\BSON\Binary


Returns the Binary's data

MongoDB\BSON\Binary::__construct
MongoDB\BSON\Binary::getType
MongoDB\BSON\Binary
PHP Manual

MongoDB\BSON\Binary::getData

(mongodb >=1.0.0)

MongoDB\BSON\Binary::getData — Returns the Binary's data

Descrierea

final public string MongoDB\BSON\Binary::getData ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the Binary's data.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\Binary::getData() example

<?php

$binary = new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC);
var_dump($binary->getData());

?>

Exemplul de mai sus va afi?a:

string(3) "foo"

A se vedea ?i

  • » BSON Types
MongoDB\BSON\Binary::__construct
MongoDB\BSON\Binary::getType
MongoDB\BSON\Binary


Returns the Binary's type

MongoDB\BSON\Binary::getData
MongoDB\BSON\Binary::jsonSerialize
MongoDB\BSON\Binary
PHP Manual

MongoDB\BSON\Binary::getType

(mongodb >=1.0.0)

MongoDB\BSON\Binary::getType — Returns the Binary's type

Descrierea

final public integer MongoDB\BSON\Binary::getType ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the Binary's type.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\Binary::getType() example

<?php

$binary = new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC);
var_dump($binary->getType());

?>

Exemplul de mai sus va afi?a:

int(0)

A se vedea ?i

  • » BSON Types
MongoDB\BSON\Binary::getData
MongoDB\BSON\Binary::jsonSerialize
MongoDB\BSON\Binary


Returns a representation that can be converted to JSON

MongoDB\BSON\Binary::getType
MongoDB\BSON\Binary::serialize
MongoDB\BSON\Binary
PHP Manual

MongoDB\BSON\Binary::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Binary::jsonSerialize — Returns a representation that can be converted to JSON

Descrierea

final public mixed MongoDB\BSON\Binary::jsonSerialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns data which can be serialized by json_encode() to produce the » extended JSON representation of the MongoDB\BSON\Binary.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
  • json_encode() - Întoarce o reprezentare JSON pentru valoarea data
  • » MongoDB Extended JSON
MongoDB\BSON\Binary::getType
MongoDB\BSON\Binary::serialize
MongoDB\BSON\Binary


Serialize a Binary

MongoDB\BSON\Binary::jsonSerialize
MongoDB\BSON\Binary::__toString
MongoDB\BSON\Binary
PHP Manual

MongoDB\BSON\Binary::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Binary::serialize — Serialize a Binary

Descrierea

final public string MongoDB\BSON\Binary::serialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the serialized representation of the MongoDB\BSON\Binary.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\BSON\Binary::unserialize() - Unserialize a Binary
  • serialize() - Genereaza o reprezentare ce poate fi stocata a unei valori
  • Serializing Objects
MongoDB\BSON\Binary::jsonSerialize
MongoDB\BSON\Binary::__toString
MongoDB\BSON\Binary


Returns the Binary's data

MongoDB\BSON\Binary::serialize
MongoDB\BSON\Binary::unserialize
MongoDB\BSON\Binary
PHP Manual

MongoDB\BSON\Binary::__toString

(mongodb >=1.2.0)

MongoDB\BSON\Binary::__toString — Returns the Binary's data

Descrierea

final public string MongoDB\BSON\Binary::__toString ( void )

Aceasta metoda este pseudonim pentru: MongoDB\BSON\Binary::getData().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the Binary's code.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\Binary::__toString() example

<?php

var_dump((string) new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC));

?>

Exemplul de mai sus va afi?a:

string(3) "foo"

A se vedea ?i

  • MongoDB\BSON\Binary::getData() - Returns the Binary's data
  • » BSON Types
MongoDB\BSON\Binary::serialize
MongoDB\BSON\Binary::unserialize
MongoDB\BSON\Binary


Unserialize a Binary

MongoDB\BSON\Binary::__toString
MongoDB\BSON\Javascript
MongoDB\BSON\Binary
PHP Manual

MongoDB\BSON\Binary::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Binary::unserialize — Unserialize a Binary

Descrierea

final public void MongoDB\BSON\Binary::unserialize ( string $serialized )

Parametri

serialized

The serialized MongoDB\BSON\Binary.

Valorile întoarse

Returns the unserialized MongoDB\BSON\Binary.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

A se vedea ?i

  • MongoDB\BSON\Binary::serialize() - Serialize a Binary
  • unserialize() - Creeaza o valoare PHP dintr-o reprezentare stocata
  • Serializing Objects
MongoDB\BSON\Binary::__toString
MongoDB\BSON\Javascript
MongoDB\BSON\Binary


The MongoDB\BSON\Javascript class

(mongodb >=1.0.0)

Introducere

Sinopsisul clasei

MongoDB\BSON\Javascript implements MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Metode */
final public __construct ( string $code [, array|object $scope ] )
final public string getCode ( void )
final public object|null getScope ( void )
final public mixed jsonSerialize ( void )
final public string serialize ( void )
final public string __toString ( void )
final public void unserialize ( string $serialized )
}

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Implements Serializable and JsonSerializable.

Cuprins

  • MongoDB\BSON\Javascript::__construct — Construct a new Javascript
  • MongoDB\BSON\Javascript::getCode — Returns the Javascript's code
  • MongoDB\BSON\Javascript::getScope — Returns the Javascript's scope document
  • MongoDB\BSON\Javascript::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Javascript::serialize — Serialize a Javascript
  • MongoDB\BSON\Javascript::__toString — Returns the Javascript's code
  • MongoDB\BSON\Javascript::unserialize — Unserialize a Javascript
MongoDB\BSON\Binary::unserialize
MongoDB\BSON\Javascript::__construct
MongoDB\Driver\BSON


Construct a new Javascript

MongoDB\BSON\Javascript
MongoDB\BSON\Javascript::getCode
MongoDB\BSON\Javascript
PHP Manual

MongoDB\BSON\Javascript::__construct

(mongodb >=1.0.0)

MongoDB\BSON\Javascript::__construct — Construct a new Javascript

Descrierea

final public MongoDB\BSON\Javascript::__construct ( string $code [, array|object $scope ] )

Parametri

code (string)

Javascript code.

scope (array|object)

Javascript scope.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if code contains null bytes.

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | MongoDB\Driver\Exception\InvalidArgumentException is thrown if code contains null bytes. Previously, values would be truncated at the first null byte.

Exemple

Example #1 MongoDB\BSON\Javascript::__construct() example

<?php

$code = new MongoDB\BSON\Javascript('function() { return 1; }');
var_dump($code);

$codews = new MongoDB\BSON\Javascript('function() { return foo; }', ['foo' => 'bar']);
var_dump($codews);

?>

Exemplul de mai sus va afi?a:

object(MongoDB\BSON\Javascript)#1 (2) {
  ["javascript"]=>
  string(24) "function() { return 1; }"
  ["scope"]=>
  object(stdClass)#2 (0) {
  }
}
object(MongoDB\BSON\Javascript)#2 (2) {
  ["javascript"]=>
  string(26) "function() { return foo; }"
  ["scope"]=>
  object(stdClass)#1 (1) {
    ["foo"]=>
    string(3) "bar"
  }
}

A se vedea ?i

  • » BSON Types
MongoDB\BSON\Javascript
MongoDB\BSON\Javascript::getCode
MongoDB\BSON\Javascript


Returns the Javascript's code

MongoDB\BSON\Javascript::__construct
MongoDB\BSON\Javascript::getScope
MongoDB\BSON\Javascript
PHP Manual

MongoDB\BSON\Javascript::getCode

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::getCode — Returns the Javascript's code

Descrierea

final public string MongoDB\BSON\Javascript::getCode ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the Javascript's code.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\Javascript::getCode() example

<?php

$js = new MongoDB\BSON\Javascript('function foo(bar) { return bar; }');
var_dump($js->getCode());

?>

Exemplul de mai sus va afi?a:

string(33) "function foo(bar) { return bar; }"

A se vedea ?i

  • » BSON Types
MongoDB\BSON\Javascript::__construct
MongoDB\BSON\Javascript::getScope
MongoDB\BSON\Javascript


Returns the Javascript's scope document

MongoDB\BSON\Javascript::getCode
MongoDB\BSON\Javascript::jsonSerialize
MongoDB\BSON\Javascript
PHP Manual

MongoDB\BSON\Javascript::getScope

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::getScope — Returns the Javascript's scope document

Descrierea

final public object|null MongoDB\BSON\Javascript::getScope ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the Javascript's scope document.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\Javascript::getScope() example

<?php

$js = new MongoDB\BSON\Javascript('function foo(bar) { return bar; }');
var_dump($js->getScope());

$js = new MongoDB\BSON\Javascript('function foo() { return foo; }', ['foo' => 42]);
var_dump($js->getScope());

?>

Exemplul de mai sus va afi?a:

NULL
object(stdClass)#1 (1) {
  ["foo"]=>
  int(42)
}

A se vedea ?i

  • » BSON Types
MongoDB\BSON\Javascript::getCode
MongoDB\BSON\Javascript::jsonSerialize
MongoDB\BSON\Javascript


Returns a representation that can be converted to JSON

MongoDB\BSON\Javascript::getScope
MongoDB\BSON\Javascript::serialize
MongoDB\BSON\Javascript
PHP Manual

MongoDB\BSON\Javascript::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::jsonSerialize — Returns a representation that can be converted to JSON

Descrierea

final public mixed MongoDB\BSON\Javascript::jsonSerialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns data which can be serialized by json_encode() to produce the » extended JSON representation of the MongoDB\BSON\Javascript.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
  • json_encode() - Întoarce o reprezentare JSON pentru valoarea data
  • » MongoDB Extended JSON
MongoDB\BSON\Javascript::getScope
MongoDB\BSON\Javascript::serialize
MongoDB\BSON\Javascript


Serialize a Javascript

MongoDB\BSON\Javascript::jsonSerialize
MongoDB\BSON\Javascript::__toString
MongoDB\BSON\Javascript
PHP Manual

MongoDB\BSON\Javascript::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::serialize — Serialize a Javascript

Descrierea

final public string MongoDB\BSON\Javascript::serialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the serialized representation of the MongoDB\BSON\Javascript.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\BSON\Javascript::unserialize() - Unserialize a Javascript
  • serialize() - Genereaza o reprezentare ce poate fi stocata a unei valori
  • Serializing Objects
MongoDB\BSON\Javascript::jsonSerialize
MongoDB\BSON\Javascript::__toString
MongoDB\BSON\Javascript


Returns the Javascript's code

MongoDB\BSON\Javascript::serialize
MongoDB\BSON\Javascript::unserialize
MongoDB\BSON\Javascript
PHP Manual

MongoDB\BSON\Javascript::__toString

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::__toString — Returns the Javascript's code

Descrierea

final public string MongoDB\BSON\Javascript::__toString ( void )

Aceasta metoda este pseudonim pentru: MongoDB\BSON\Javascript::getCode().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the Javascript's code.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\Javascript::__toString() example

<?php

var_dump((string) new MongoDB\BSON\Javascript('function foo(bar) { return bar; }'));

?>

Exemplul de mai sus va afi?a:

string(33) "function foo(bar) { return bar; }"

A se vedea ?i

  • MongoDB\BSON\Javascript::getCode() - Returns the Javascript's code
  • » BSON Types
MongoDB\BSON\Javascript::serialize
MongoDB\BSON\Javascript::unserialize
MongoDB\BSON\Javascript


Unserialize a Javascript

MongoDB\BSON\Javascript::__toString
MongoDB\BSON\MaxKey
MongoDB\BSON\Javascript
PHP Manual

MongoDB\BSON\Javascript::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::unserialize — Unserialize a Javascript

Descrierea

final public void MongoDB\BSON\Javascript::unserialize ( string $serialized )

Parametri

serialized

The serialized MongoDB\BSON\Javascript.

Valorile întoarse

Returns the unserialized MongoDB\BSON\Javascript.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

A se vedea ?i

  • MongoDB\BSON\Javascript::serialize() - Serialize a Javascript
  • unserialize() - Creeaza o valoare PHP dintr-o reprezentare stocata
  • Serializing Objects
MongoDB\BSON\Javascript::__toString
MongoDB\BSON\MaxKey
MongoDB\BSON\Javascript


The MongoDB\BSON\MaxKey class

(mongodb >=1.0.0)

Introducere

Sinopsisul clasei

MongoDB\BSON\MaxKey implements MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Metode */
final public __construct ( void )
final public mixed jsonSerialize ( void )
final public string serialize ( void )
final public void unserialize ( string $serialized )
}

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Implements Serializable and JsonSerializable.

Cuprins

  • MongoDB\BSON\MaxKey::__construct — Construct a new MaxKey
  • MongoDB\BSON\MaxKey::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\MaxKey::serialize — Serialize a MaxKey
  • MongoDB\BSON\MaxKey::unserialize — Unserialize a MaxKey
MongoDB\BSON\Javascript::unserialize
MongoDB\BSON\MaxKey::__construct
MongoDB\Driver\BSON


Construct a new MaxKey

MongoDB\BSON\MaxKey
MongoDB\BSON\MaxKey::jsonSerialize
MongoDB\BSON\MaxKey
PHP Manual

MongoDB\BSON\MaxKey::__construct

(mongodb >=1.0.0)

MongoDB\BSON\MaxKey::__construct — Construct a new MaxKey

Descrierea

final public MongoDB\BSON\MaxKey::__construct ( void )

Parametri

Aceasta func?ie nu are parametri.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\MaxKey::__construct() example

<?php

var_dump(new MongoDB\BSON\MaxKey());

?>

Exemplul de mai sus va afi?a:

object(MongoDB\BSON\MaxKey)#1 (0) {
}

A se vedea ?i

  • » BSON Types
MongoDB\BSON\MaxKey
MongoDB\BSON\MaxKey::jsonSerialize
MongoDB\BSON\MaxKey


Returns a representation that can be converted to JSON

MongoDB\BSON\MaxKey::__construct
MongoDB\BSON\MaxKey::serialize
MongoDB\BSON\MaxKey
PHP Manual

MongoDB\BSON\MaxKey::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\MaxKey::jsonSerialize — Returns a representation that can be converted to JSON

Descrierea

final public mixed MongoDB\BSON\MaxKey::jsonSerialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns data which can be serialized by json_encode() to produce the » extended JSON representation of the MongoDB\BSON\MaxKey.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
  • json_encode() - Întoarce o reprezentare JSON pentru valoarea data
  • » MongoDB Extended JSON
MongoDB\BSON\MaxKey::__construct
MongoDB\BSON\MaxKey::serialize
MongoDB\BSON\MaxKey


Serialize a MaxKey

MongoDB\BSON\MaxKey::jsonSerialize
MongoDB\BSON\MaxKey::unserialize
MongoDB\BSON\MaxKey
PHP Manual

MongoDB\BSON\MaxKey::serialize

(mongodb >=1.2.0)

MongoDB\BSON\MaxKey::serialize — Serialize a MaxKey

Descrierea

final public string MongoDB\BSON\MaxKey::serialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the serialized representation of the MongoDB\BSON\MaxKey.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\BSON\MaxKey::unserialize() - Unserialize a MaxKey
  • serialize() - Genereaza o reprezentare ce poate fi stocata a unei valori
  • Serializing Objects
MongoDB\BSON\MaxKey::jsonSerialize
MongoDB\BSON\MaxKey::unserialize
MongoDB\BSON\MaxKey


Unserialize a MaxKey

MongoDB\BSON\MaxKey::serialize
MongoDB\BSON\MinKey
MongoDB\BSON\MaxKey
PHP Manual

MongoDB\BSON\MaxKey::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\MaxKey::unserialize — Unserialize a MaxKey

Descrierea

final public void MongoDB\BSON\MaxKey::unserialize ( string $serialized )

Parametri

serialized

The serialized MongoDB\BSON\MaxKey.

Valorile întoarse

Returns the unserialized MongoDB\BSON\MaxKey.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\BSON\MaxKey::serialize() - Serialize a MaxKey
  • unserialize() - Creeaza o valoare PHP dintr-o reprezentare stocata
  • Serializing Objects
MongoDB\BSON\MaxKey::serialize
MongoDB\BSON\MinKey
MongoDB\BSON\MaxKey


The MongoDB\BSON\MinKey class

(mongodb >=1.0.0)

Introducere

Sinopsisul clasei

MongoDB\BSON\MinKey implements MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Metode */
final public __construct ( void )
final public mixed jsonSerialize ( void )
final public string serialize ( void )
final public void unserialize ( string $serialized )
}

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Implements Serializable and JsonSerializable.

Cuprins

  • MongoDB\BSON\MinKey::__construct — Construct a new MinKey
  • MongoDB\BSON\MinKey::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\MinKey::serialize — Serialize a MinKey
  • MongoDB\BSON\MinKey::unserialize — Unserialize a MinKey
MongoDB\BSON\MaxKey::unserialize
MongoDB\BSON\MinKey::__construct
MongoDB\Driver\BSON


Construct a new MinKey

MongoDB\BSON\MinKey
MongoDB\BSON\MinKey::jsonSerialize
MongoDB\BSON\MinKey
PHP Manual

MongoDB\BSON\MinKey::__construct

(mongodb >=1.0.0)

MongoDB\BSON\MinKey::__construct — Construct a new MinKey

Descrierea

final public MongoDB\BSON\MinKey::__construct ( void )

Parametri

Aceasta func?ie nu are parametri.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\MinKey::__construct() example

<?php

var_dump(new MongoDB\BSON\MinKey());

?>

Exemplul de mai sus va afi?a:

object(MongoDB\BSON\MinKey)#1 (0) {
}

A se vedea ?i

  • » BSON Types
MongoDB\BSON\MinKey
MongoDB\BSON\MinKey::jsonSerialize
MongoDB\BSON\MinKey


Returns a representation that can be converted to JSON

MongoDB\BSON\MinKey::__construct
MongoDB\BSON\MinKey::serialize
MongoDB\BSON\MinKey
PHP Manual

MongoDB\BSON\MinKey::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\MinKey::jsonSerialize — Returns a representation that can be converted to JSON

Descrierea

final public mixed MongoDB\BSON\MinKey::jsonSerialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns data which can be serialized by json_encode() to produce the » extended JSON representation of the MongoDB\BSON\MinKey.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
  • json_encode() - Întoarce o reprezentare JSON pentru valoarea data
  • » MongoDB Extended JSON
MongoDB\BSON\MinKey::__construct
MongoDB\BSON\MinKey::serialize
MongoDB\BSON\MinKey


Serialize a MinKey

MongoDB\BSON\MinKey::jsonSerialize
MongoDB\BSON\MinKey::unserialize
MongoDB\BSON\MinKey
PHP Manual

MongoDB\BSON\MinKey::serialize

(mongodb >=1.2.0)

MongoDB\BSON\MinKey::serialize — Serialize a MinKey

Descrierea

final public string MongoDB\BSON\MinKey::serialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the serialized representation of the MongoDB\BSON\MinKey.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\BSON\MinKey::unserialize() - Unserialize a MinKey
  • serialize() - Genereaza o reprezentare ce poate fi stocata a unei valori
  • Serializing Objects
MongoDB\BSON\MinKey::jsonSerialize
MongoDB\BSON\MinKey::unserialize
MongoDB\BSON\MinKey


Unserialize a MinKey

MongoDB\BSON\MinKey::serialize
MongoDB\BSON\ObjectID
MongoDB\BSON\MinKey
PHP Manual

MongoDB\BSON\MinKey::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\MinKey::unserialize — Unserialize a MinKey

Descrierea

final public void MongoDB\BSON\MinKey::unserialize ( string $serialized )

Parametri

serialized

The serialized MongoDB\BSON\MinKey.

Valorile întoarse

Returns the unserialized MongoDB\BSON\MinKey.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\BSON\MinKey::serialize() - Serialize a MinKey
  • unserialize() - Creeaza o valoare PHP dintr-o reprezentare stocata
  • Serializing Objects
MongoDB\BSON\MinKey::serialize
MongoDB\BSON\ObjectID
MongoDB\BSON\MinKey


The MongoDB\BSON\ObjectID class

(mongodb >=1.0.0)

Introducere

Sinopsisul clasei

MongoDB\BSON\ObjectID implements MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Metode */
final public __construct ([ string $id ] )
final public integer getTimestamp ( void )
final public mixed jsonSerialize ( void )
final public string serialize ( void )
final public string __toString ( void )
final public void unserialize ( string $serialized )
}

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Implements Serializable and JsonSerializable.

Cuprins

  • MongoDB\BSON\ObjectID::__construct — Construct a new ObjectID
  • MongoDB\BSON\ObjectID::getTimestamp — Returns the timestamp component of this ObjectID
  • MongoDB\BSON\ObjectID::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\ObjectID::serialize — Serialize an ObjectID
  • MongoDB\BSON\ObjectID::__toString — Returns the hexidecimal representation of this ObjectID
  • MongoDB\BSON\ObjectID::unserialize — Unserialize an ObjectID
MongoDB\BSON\MinKey::unserialize
MongoDB\BSON\ObjectID::__construct
MongoDB\Driver\BSON


Construct a new ObjectID

MongoDB\BSON\ObjectID
MongoDB\BSON\ObjectID::getTimestamp
MongoDB\BSON\ObjectID
PHP Manual

MongoDB\BSON\ObjectID::__construct

(mongodb >=1.0.0)

MongoDB\BSON\ObjectID::__construct — Construct a new ObjectID

Descrierea

final public MongoDB\BSON\ObjectID::__construct ([ string $id ] )

Parametri

id (string)

A 24-character hexadecimal string. If not provided, the driver will generate an ObjectID.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if id is not a 24-character hexadecimal string.

Exemple

Example #1 MongoDB\BSON\ObjectID::__construct() example

<?php

var_dump(new MongoDB\BSON\ObjectId());

var_dump(new MongoDB\BSON\ObjectId('000000000000000000000001'));

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(MongoDB\BSON\ObjectID)#1 (1) {
  ["oid"]=>
  string(24) "56732d3dda14d81214634921"
}
object(MongoDB\BSON\ObjectID)#1 (1) {
  ["oid"]=>
  string(24) "000000000000000000000001"
}

A se vedea ?i

  • » ObjectID Reference
  • » BSON Types: ObjectID
MongoDB\BSON\ObjectID
MongoDB\BSON\ObjectID::getTimestamp
MongoDB\BSON\ObjectID


Returns the timestamp component of this ObjectID

MongoDB\BSON\ObjectID::__construct
MongoDB\BSON\ObjectID::jsonSerialize
MongoDB\BSON\ObjectID
PHP Manual

MongoDB\BSON\ObjectID::getTimestamp

(mongodb >=1.2.0)

MongoDB\BSON\ObjectID::getTimestamp — Returns the timestamp component of this ObjectID

Descrierea

final public integer MongoDB\BSON\ObjectID::getTimestamp ( void )

The timestamp component of an ObjectID is its first four bytes, which denote the number of seconds since the Unix epoch. This value is read as an unsigned 32-bit integer with big-endian byte order.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the timestamp component of this ObjectID.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\ObjectID::getTimestamp() example

<?php

var_dump((new MongoDB\BSON\ObjectId())->getTimestamp());

var_dump((new MongoDB\BSON\ObjectId('0000002a0000000000000000'))->getTimestamp());

?>

Exemplul de mai sus va afi?a ceva similar cu:

integer(1484854719)
integer(42)

A se vedea ?i

  • » ObjectID Reference
  • » BSON Types: ObjectID
MongoDB\BSON\ObjectID::__construct
MongoDB\BSON\ObjectID::jsonSerialize
MongoDB\BSON\ObjectID


Returns a representation that can be converted to JSON

MongoDB\BSON\ObjectID::getTimestamp
MongoDB\BSON\ObjectID::serialize
MongoDB\BSON\ObjectID
PHP Manual

MongoDB\BSON\ObjectID::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\ObjectID::jsonSerialize — Returns a representation that can be converted to JSON

Descrierea

final public mixed MongoDB\BSON\ObjectID::jsonSerialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns data which can be serialized by json_encode() to produce the » extended JSON representation of the MongoDB\BSON\ObjectID.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
  • json_encode() - Întoarce o reprezentare JSON pentru valoarea data
  • » MongoDB Extended JSON
MongoDB\BSON\ObjectID::getTimestamp
MongoDB\BSON\ObjectID::serialize
MongoDB\BSON\ObjectID


Serialize an ObjectID

MongoDB\BSON\ObjectID::jsonSerialize
MongoDB\BSON\ObjectID::__toString
MongoDB\BSON\ObjectID
PHP Manual

MongoDB\BSON\ObjectID::serialize

(mongodb >=1.2.0)

MongoDB\BSON\ObjectID::serialize — Serialize an ObjectID

Descrierea

final public string MongoDB\BSON\ObjectID::serialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the serialized representation of the MongoDB\BSON\ObjectID.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\BSON\ObjectID::unserialize() - Unserialize an ObjectID
  • serialize() - Genereaza o reprezentare ce poate fi stocata a unei valori
  • Serializing Objects
MongoDB\BSON\ObjectID::jsonSerialize
MongoDB\BSON\ObjectID::__toString
MongoDB\BSON\ObjectID


Returns the hexidecimal representation of this ObjectID

MongoDB\BSON\ObjectID::serialize
MongoDB\BSON\ObjectID::unserialize
MongoDB\BSON\ObjectID
PHP Manual

MongoDB\BSON\ObjectID::__toString

(mongodb >=1.0.0)

MongoDB\BSON\ObjectID::__toString — Returns the hexidecimal representation of this ObjectID

Descrierea

final public string MongoDB\BSON\ObjectID::__toString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the hexidecimal representation of this ObjectID.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\ObjectID::__toString() example

<?php

var_dump((string) new MongoDB\BSON\ObjectId());
var_dump((string) new MongoDB\BSON\ObjectId('000000000000000000000001'));

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(24) "56731b49da14d8747d701211"
string(24) "000000000000000000000001"

A se vedea ?i

  • » ObjectID Reference
  • » BSON Types: ObjectID
MongoDB\BSON\ObjectID::serialize
MongoDB\BSON\ObjectID::unserialize
MongoDB\BSON\ObjectID


Unserialize an ObjectID

MongoDB\BSON\ObjectID::__toString
MongoDB\BSON\Regex
MongoDB\BSON\ObjectID
PHP Manual

MongoDB\BSON\ObjectID::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\ObjectID::unserialize — Unserialize an ObjectID

Descrierea

final public void MongoDB\BSON\ObjectID::unserialize ( string $serialized )

Parametri

serialized

The serialized MongoDB\BSON\ObjectID.

Valorile întoarse

Returns the unserialized MongoDB\BSON\ObjectID.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

A se vedea ?i

  • MongoDB\BSON\ObjectID::serialize() - Serialize an ObjectID
  • unserialize() - Creeaza o valoare PHP dintr-o reprezentare stocata
  • Serializing Objects
MongoDB\BSON\ObjectID::__toString
MongoDB\BSON\Regex
MongoDB\BSON\ObjectID


The MongoDB\BSON\Regex class

(mongodb >=1.0.0)

Introducere

Sinopsisul clasei

MongoDB\BSON\Regex implements MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Metode */
final public __construct ( string $pattern [, string $flags = "" ] )
final public string getFlags ( void )
final public string getPattern ( void )
final public mixed jsonSerialize ( void )
final public string serialize ( void )
final public string __toString ( void )
final public void unserialize ( string $serialized )
}

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Implements Serializable and JsonSerializable.

Cuprins

  • MongoDB\BSON\Regex::__construct — Construct a new Regex
  • MongoDB\BSON\Regex::getFlags — Returns the Regex's flags
  • MongoDB\BSON\Regex::getPattern — Returns the Regex's pattern
  • MongoDB\BSON\Regex::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Regex::serialize — Serialize a Regex
  • MongoDB\BSON\Regex::__toString — Returns the string representation of this Regex
  • MongoDB\BSON\Regex::unserialize — Unserialize a Regex
MongoDB\BSON\ObjectID::unserialize
MongoDB\BSON\Regex::__construct
MongoDB\Driver\BSON


Construct a new Regex

MongoDB\BSON\Regex
MongoDB\BSON\Regex::getFlags
MongoDB\BSON\Regex
PHP Manual

MongoDB\BSON\Regex::__construct

(mongodb >=1.0.0)

MongoDB\BSON\Regex::__construct — Construct a new Regex

Descrierea

final public MongoDB\BSON\Regex::__construct ( string $pattern [, string $flags = "" ] )

Parametri

pattern (string)

The regular expression pattern.

Nota:

The pattern should not be wrapped with delimiter characters.

flags (string)

The » regular expression flags. Characters in this argument will be sorted alphabetically.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if pattern or flags contain null bytes.

Istoricul schimbarilor

Versiune Descriere
1.2.0

The flags argument is optional and defaults to an empty string.

Characters in the flags argument will be sorted alphabetically when a Regex is constructed. Previously, the characters were stored in the order provided.

MongoDB\Driver\Exception\InvalidArgumentException is thrown if pattern or flags contain null bytes. Previously, values would be truncated at the first null byte.

Exemple

Example #1 MongoDB\BSON\Regex::__construct() example

<?php

$regex = new MongoDB\BSON\Regex('^foo', 'i');
var_dump($regex);

?>

Exemplul de mai sus va afi?a:

object(MongoDB\BSON\Regex)#1 (2) {
  ["pattern"]=>
  string(4) "^foo"
  ["flags"]=>
  string(1) "i"
}

A se vedea ?i

  • » BSON Types
  • » Supported regular expression flags
MongoDB\BSON\Regex
MongoDB\BSON\Regex::getFlags
MongoDB\BSON\Regex


Returns the Regex's flags

MongoDB\BSON\Regex::__construct
MongoDB\BSON\Regex::getPattern
MongoDB\BSON\Regex
PHP Manual

MongoDB\BSON\Regex::getFlags

(mongodb >=1.0.0)

MongoDB\BSON\Regex::getFlags — Returns the Regex's flags

Descrierea

final public string MongoDB\BSON\Regex::getFlags ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the Regex's flags.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\Regex::getFlags() example

<?php

$regex = new MongoDB\BSON\Regex('regex', 'i');
var_dump($regex->getFlags());

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "i"

A se vedea ?i

  • » BSON Types
  • » Supported regular expression flags
MongoDB\BSON\Regex::__construct
MongoDB\BSON\Regex::getPattern
MongoDB\BSON\Regex


Returns the Regex's pattern

MongoDB\BSON\Regex::getFlags
MongoDB\BSON\Regex::jsonSerialize
MongoDB\BSON\Regex
PHP Manual

MongoDB\BSON\Regex::getPattern

(mongodb >=1.0.0)

MongoDB\BSON\Regex::getPattern — Returns the Regex's pattern

Descrierea

final public string MongoDB\BSON\Regex::getPattern ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the Regex's pattern.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\Regex::getPattern() example

<?php

$regex = new MongoDB\BSON\Regex('regex', 'i');
var_dump($regex->getPattern());

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(5) "regex"

A se vedea ?i

  • » BSON Types
MongoDB\BSON\Regex::getFlags
MongoDB\BSON\Regex::jsonSerialize
MongoDB\BSON\Regex


Returns a representation that can be converted to JSON

MongoDB\BSON\Regex::getPattern
MongoDB\BSON\Regex::serialize
MongoDB\BSON\Regex
PHP Manual

MongoDB\BSON\Regex::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Regex::jsonSerialize — Returns a representation that can be converted to JSON

Descrierea

final public mixed MongoDB\BSON\Regex::jsonSerialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns data which can be serialized by json_encode() to produce the » extended JSON representation of the MongoDB\BSON\Regex.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
  • json_encode() - Întoarce o reprezentare JSON pentru valoarea data
  • » MongoDB Extended JSON
MongoDB\BSON\Regex::getPattern
MongoDB\BSON\Regex::serialize
MongoDB\BSON\Regex


Serialize a Regex

MongoDB\BSON\Regex::jsonSerialize
MongoDB\BSON\Regex::__toString
MongoDB\BSON\Regex
PHP Manual

MongoDB\BSON\Regex::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Regex::serialize — Serialize a Regex

Descrierea

final public string MongoDB\BSON\Regex::serialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the serialized representation of the MongoDB\BSON\Regex.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\BSON\Regex::unserialize() - Unserialize a Regex
  • serialize() - Genereaza o reprezentare ce poate fi stocata a unei valori
  • Serializing Objects
MongoDB\BSON\Regex::jsonSerialize
MongoDB\BSON\Regex::__toString
MongoDB\BSON\Regex


Returns the string representation of this Regex

MongoDB\BSON\Regex::serialize
MongoDB\BSON\Regex::unserialize
MongoDB\BSON\Regex
PHP Manual

MongoDB\BSON\Regex::__toString

(mongodb >=1.0.0)

MongoDB\BSON\Regex::__toString — Returns the string representation of this Regex

Descrierea

final public string MongoDB\BSON\Regex::__toString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the string representation of this Regex.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\Regex::__toString() example

<?php

$regex = new MongoDB\BSON\Regex('regex', 'i');
var_dump((string) $regex);

?>

Exemplul de mai sus va afi?a:

string(8) "/regex/i"

A se vedea ?i

  • » BSON Types
MongoDB\BSON\Regex::serialize
MongoDB\BSON\Regex::unserialize
MongoDB\BSON\Regex


Unserialize a Regex

MongoDB\BSON\Regex::__toString
MongoDB\BSON\Timestamp
MongoDB\BSON\Regex
PHP Manual

MongoDB\BSON\Regex::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Regex::unserialize — Unserialize a Regex

Descrierea

final public void MongoDB\BSON\Regex::unserialize ( string $serialized )

Parametri

serialized

The serialized MongoDB\BSON\Regex.

Valorile întoarse

Returns the unserialized MongoDB\BSON\Regex.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

A se vedea ?i

  • MongoDB\BSON\Regex::serialize() - Serialize a Regex
  • unserialize() - Creeaza o valoare PHP dintr-o reprezentare stocata
  • Serializing Objects
MongoDB\BSON\Regex::__toString
MongoDB\BSON\Timestamp
MongoDB\BSON\Regex


The MongoDB\BSON\Timestamp class

(mongodb >=1.0.0)

Introducere

Represents a » BSON timestamp, which is an internal MongoDB type not intended for general date storage.

Sinopsisul clasei

MongoDB\BSON\Timestamp implements MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Metode */
final public __construct ( integer $increment , integer $timestamp )
final public mixed jsonSerialize ( void )
final public string serialize ( void )
final public string __toString ( void )
final public void unserialize ( string $serialized )
}

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Implements Serializable and JsonSerializable.

Cuprins

  • MongoDB\BSON\Timestamp::__construct — Construct a new Timestamp
  • MongoDB\BSON\Timestamp::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Timestamp::serialize — Serialize a Timestamp
  • MongoDB\BSON\Timestamp::__toString — Returns the string representation of this Timestamp
  • MongoDB\BSON\Timestamp::unserialize — Unserialize a Timestamp
MongoDB\BSON\Regex::unserialize
MongoDB\BSON\Timestamp::__construct
MongoDB\Driver\BSON


Construct a new Timestamp

MongoDB\BSON\Timestamp
MongoDB\BSON\Timestamp::jsonSerialize
MongoDB\BSON\Timestamp
PHP Manual

MongoDB\BSON\Timestamp::__construct

(mongodb >=1.0.0)

MongoDB\BSON\Timestamp::__construct — Construct a new Timestamp

Descrierea

final public MongoDB\BSON\Timestamp::__construct ( integer $increment , integer $timestamp )

Parametri

increment (integer)

32-bit integer denoting the incrementing ordinal for operations within a given second.

timestamp (integer)

32-bit integer denoting seconds since the Unix epoch.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\Timestamp::__construct() example

<?php

$timestamp = new MongoDB\BSON\Timestamp(1234, 5678);

?>

Exemplul de mai sus va afi?a:

object(MongoDB\BSON\Timestamp)#1 (2) {
  ["increment"]=>
  int(1234)
  ["timestamp"]=>
  int(5678)
}

A se vedea ?i

  • » BSON Types: Timestamps
MongoDB\BSON\Timestamp
MongoDB\BSON\Timestamp::jsonSerialize
MongoDB\BSON\Timestamp


Returns a representation that can be converted to JSON

MongoDB\BSON\Timestamp::__construct
MongoDB\BSON\Timestamp::serialize
MongoDB\BSON\Timestamp
PHP Manual

MongoDB\BSON\Timestamp::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Timestamp::jsonSerialize — Returns a representation that can be converted to JSON

Descrierea

final public mixed MongoDB\BSON\Timestamp::jsonSerialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns data which can be serialized by json_encode() to produce the » extended JSON representation of the MongoDB\BSON\Timestamp.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
  • json_encode() - Întoarce o reprezentare JSON pentru valoarea data
  • » MongoDB Extended JSON
MongoDB\BSON\Timestamp::__construct
MongoDB\BSON\Timestamp::serialize
MongoDB\BSON\Timestamp


Serialize a Timestamp

MongoDB\BSON\Timestamp::jsonSerialize
MongoDB\BSON\Timestamp::__toString
MongoDB\BSON\Timestamp
PHP Manual

MongoDB\BSON\Timestamp::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Timestamp::serialize — Serialize a Timestamp

Descrierea

final public string MongoDB\BSON\Timestamp::serialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the serialized representation of the MongoDB\BSON\Timestamp.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\BSON\Timestamp::unserialize() - Unserialize a Timestamp
  • serialize() - Genereaza o reprezentare ce poate fi stocata a unei valori
  • Serializing Objects
MongoDB\BSON\Timestamp::jsonSerialize
MongoDB\BSON\Timestamp::__toString
MongoDB\BSON\Timestamp


Returns the string representation of this Timestamp

MongoDB\BSON\Timestamp::serialize
MongoDB\BSON\Timestamp::unserialize
MongoDB\BSON\Timestamp
PHP Manual

MongoDB\BSON\Timestamp::__toString

(mongodb >=1.0.0)

MongoDB\BSON\Timestamp::__toString — Returns the string representation of this Timestamp

Descrierea

final public string MongoDB\BSON\Timestamp::__toString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the string representation of this Timestamp.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\Timestamp::__toString() example

<?php

$timestamp = new MongoDB\BSON\Timestamp(1234, 5678);
var_dump((string) $timestamp);

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(11) "[1234:5678]"

A se vedea ?i

  • » BSON Types: Timestamps
MongoDB\BSON\Timestamp::serialize
MongoDB\BSON\Timestamp::unserialize
MongoDB\BSON\Timestamp


Unserialize a Timestamp

MongoDB\BSON\Timestamp::__toString
MongoDB\BSON\UTCDateTime
MongoDB\BSON\Timestamp
PHP Manual

MongoDB\BSON\Timestamp::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Timestamp::unserialize — Unserialize a Timestamp

Descrierea

final public void MongoDB\BSON\Timestamp::unserialize ( string $serialized )

Parametri

serialized

The serialized MongoDB\BSON\Timestamp.

Valorile întoarse

Returns the unserialized MongoDB\BSON\Timestamp.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

A se vedea ?i

  • MongoDB\BSON\Timestamp::serialize() - Serialize a Timestamp
  • unserialize() - Creeaza o valoare PHP dintr-o reprezentare stocata
  • Serializing Objects
MongoDB\BSON\Timestamp::__toString
MongoDB\BSON\UTCDateTime
MongoDB\BSON\Timestamp


The MongoDB\BSON\UTCDateTime class

(mongodb >=1.0.0)

Introducere

Represents a » BSON date.

Sinopsisul clasei

MongoDB\BSON\UTCDateTime implements MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Metode */
final public __construct ([ integer|float|string|DateTimeInterface $milliseconds = NULL ] )
final public mixed jsonSerialize ( void )
final public string serialize ( void )
final public DateTime toDateTime ( void )
final public string __toString ( void )
final public void unserialize ( string $serialized )
}

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | Implements Serializable and JsonSerializable.

Cuprins

  • MongoDB\BSON\UTCDateTime::__construct — Construct a new UTCDateTime
  • MongoDB\BSON\UTCDateTime::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\UTCDateTime::serialize — Serialize a UTCDateTime
  • MongoDB\BSON\UTCDateTime::toDateTime — Returns the DateTime representation of this UTCDateTime
  • MongoDB\BSON\UTCDateTime::__toString — Returns the string representation of this UTCDateTime
  • MongoDB\BSON\UTCDateTime::unserialize — Unserialize a UTCDateTime
MongoDB\BSON\Timestamp::unserialize
MongoDB\BSON\UTCDateTime::__construct
MongoDB\Driver\BSON


Construct a new UTCDateTime

MongoDB\BSON\UTCDateTime
MongoDB\BSON\UTCDateTime::jsonSerialize
MongoDB\BSON\UTCDateTime
PHP Manual

MongoDB\BSON\UTCDateTime::__construct

(mongodb >=1.0.0)

MongoDB\BSON\UTCDateTime::__construct — Construct a new UTCDateTime

Descrierea

final public MongoDB\BSON\UTCDateTime::__construct ([ integer|float|string|DateTimeInterface $milliseconds = NULL ] )

Parametri

milliseconds (integer|float|string|DateTimeInterface)

Number of milliseconds since the Unix epoch (Jan 1, 1970). Negative values represent dates before 1970. This value may be provided as a 64-bit integer. For compatibility on 32-bit systems, this parameter may also be provided as a float or string.

If the argument is a DateTimeInterface, the number of milliseconds since the Unix epoch will be derived from that value. Note that in versions of PHP versions before 7.1.0, DateTime and DateTimeImmutable objects constructed from the current time did not incorporate sub-second precision.

If this argument is NULL, the current time will be used by default.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Istoricul schimbarilor

Versiune | Descriere
1.2.0 | The milliseconds argument is optional and defaults to NULL (i.e. current time). The argument also accepts a DateTimeInterface, which may be used to derive the number of milliseconds since the Unix epoch.

Exemple

Example #1 MongoDB\BSON\UTCDateTime::__construct() example

<?php

var_dump(new MongoDB\BSON\UTCDateTime);

var_dump(new MongoDB\BSON\UTCDateTime(new DateTime));

var_dump(new MongoDB\BSON\UTCDateTime(1416445411987));

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(MongoDB\BSON\UTCDateTime)#1 (1) {
  ["milliseconds"]=>
  string(13) "1484852905560"
}
object(MongoDB\BSON\UTCDateTime)#1 (1) {
  ["milliseconds"]=>
  string(13) "1484852905560"
}
object(MongoDB\BSON\UTCDateTime)#1 (1) {
  ["milliseconds"]=>
  string(13) "1416445411987"
}

A se vedea ?i

  • » BSON Types: Date
MongoDB\BSON\UTCDateTime
MongoDB\BSON\UTCDateTime::jsonSerialize
MongoDB\BSON\UTCDateTime


Returns a representation that can be converted to JSON

MongoDB\BSON\UTCDateTime::__construct
MongoDB\BSON\UTCDateTime::serialize
MongoDB\BSON\UTCDateTime
PHP Manual

MongoDB\BSON\UTCDateTime::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\UTCDateTime::jsonSerialize — Returns a representation that can be converted to JSON

Descrierea

final public mixed MongoDB\BSON\UTCDateTime::jsonSerialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns data which can be serialized by json_encode() to produce the » extended JSON representation of the MongoDB\BSON\UTCDateTime.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • JsonSerializable::jsonSerialize() - Specify data which should be serialized to JSON
  • json_encode() - Întoarce o reprezentare JSON pentru valoarea data
  • » MongoDB Extended JSON
MongoDB\BSON\UTCDateTime::__construct
MongoDB\BSON\UTCDateTime::serialize
MongoDB\BSON\UTCDateTime


Serialize a UTCDateTime

MongoDB\BSON\UTCDateTime::jsonSerialize
MongoDB\BSON\UTCDateTime::toDateTime
MongoDB\BSON\UTCDateTime
PHP Manual

MongoDB\BSON\UTCDateTime::serialize

(mongodb >=1.2.0)

MongoDB\BSON\UTCDateTime::serialize — Serialize a UTCDateTime

Descrierea

final public string MongoDB\BSON\UTCDateTime::serialize ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the serialized representation of the MongoDB\BSON\UTCDateTime.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

A se vedea ?i

  • MongoDB\BSON\UTCDateTime::unserialize() - Unserialize a UTCDateTime
  • serialize() - Genereaza o reprezentare ce poate fi stocata a unei valori
  • Serializing Objects
MongoDB\BSON\UTCDateTime::jsonSerialize
MongoDB\BSON\UTCDateTime::toDateTime
MongoDB\BSON\UTCDateTime


Returns the DateTime representation of this UTCDateTime

MongoDB\BSON\UTCDateTime::serialize
MongoDB\BSON\UTCDateTime::__toString
MongoDB\BSON\UTCDateTime
PHP Manual

MongoDB\BSON\UTCDateTime::toDateTime

(mongodb >=1.0.0)

MongoDB\BSON\UTCDateTime::toDateTime — Returns the DateTime representation of this UTCDateTime

Descrierea

final public DateTime MongoDB\BSON\UTCDateTime::toDateTime ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the DateTime representation of this UTCDateTime. The returned DateTime will use the UTC time zone.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\UTCDatetime::toDateTime() example

<?php

$utcdatetime = new MongoDB\BSON\UTCDateTime(1416445411987);
$datetime = $utcdatetime->toDateTime();
var_dump($datetime->format('r'));
var_dump($datetime->format('U.u'));
var_dump($datetime->getTimezone());

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(31) "Thu, 20 Nov 2014 01:03:31 +0000"
string(17) "1416445411.987000"
object(DateTimeZone)#3 (2) {
  ["timezone_type"]=>
  int(1)
  ["timezone"]=>
  string(6) "+00:00"
}

A se vedea ?i

  • » BSON Types: Date
MongoDB\BSON\UTCDateTime::serialize
MongoDB\BSON\UTCDateTime::__toString
MongoDB\BSON\UTCDateTime


Returns the string representation of this UTCDateTime

MongoDB\BSON\UTCDateTime::toDateTime
MongoDB\BSON\UTCDateTime::unserialize
MongoDB\BSON\UTCDateTime
PHP Manual

MongoDB\BSON\UTCDateTime::__toString

(mongodb >=1.0.0)

MongoDB\BSON\UTCDateTime::__toString — Returns the string representation of this UTCDateTime

Descrierea

final public string MongoDB\BSON\UTCDateTime::__toString ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the string representation of this UTCDateTime.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.

Exemple

Example #1 MongoDB\BSON\UTCDateTime::__toString() example

<?php

$utcdatetime = new MongoDB\BSON\UTCDateTime(1416445411987);
var_dump((string) $utcdatetime);

?>

Exemplul de mai sus va afi?a:

string(13) "1416445411987"

A se vedea ?i

  • » BSON Types: Date
MongoDB\BSON\UTCDateTime::toDateTime
MongoDB\BSON\UTCDateTime::unserialize
MongoDB\BSON\UTCDateTime


Unserialize a UTCDateTime

MongoDB\BSON\UTCDateTime::__toString
MongoDB\BSON\Type
MongoDB\BSON\UTCDateTime
PHP Manual

MongoDB\BSON\UTCDateTime::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\UTCDateTime::unserialize — Unserialize a UTCDateTime

Descrierea

final public void MongoDB\BSON\UTCDateTime::unserialize ( string $serialized )

Parametri

serialized

The serialized MongoDB\BSON\UTCDateTime.

Valorile întoarse

Returns the unserialized MongoDB\BSON\UTCDateTime.

Erori/Excep?ii

  • Emite MongoDB\Driver\Exception\InvalidArgumentException în cazul erorilor la interpretarea argumentelor.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

A se vedea ?i

  • MongoDB\BSON\UTCDateTime::serialize() - Serialize a UTCDateTime
  • unserialize() - Creeaza o valoare PHP dintr-o reprezentare stocata
  • Serializing Objects
MongoDB\BSON\UTCDateTime::__toString
MongoDB\BSON\Type
MongoDB\BSON\UTCDateTime


The MongoDB\BSON\Type interface

(mongodb >=1.0.0)

Introducere

Sinopsisul clasei

MongoDB\BSON\Type {
}
MongoDB\BSON\UTCDateTime::unserialize
MongoDB\BSON\Persistable
MongoDB\Driver\BSON


The MongoDB\BSON\Persistable interface

(mongodb >=1.0.0)

Introducere

Classes may implement this interface to take advantage of automatic ODM (object document mapping) behavior in the driver. During serialization, the driver will inject a __pclass property containing the PHP class name into the data returned by MongoDB\BSON\Serializable::bsonSerialize(). During unserialization, the same __pclass property will then be used to infer the PHP class (independent of any type map configuration) to be constructed before MongoDB\BSON\Unserializable::bsonUnserialize() is invoked. See Persisting Data for additional information.

Nota:

Even if MongoDB\BSON\Serializable::bsonSerialize() would return a sequential array, injection of the __pclass property will cause the object to be serialized as a BSON document.

Sinopsisul clasei

MongoDB\BSON\Persistable implements MongoDB\BSON\Unserializable , MongoDB\BSON\Serializable {
/* Metode mo?tenite */
abstract public array|object MongoDB\BSON\Serializable::bsonSerialize ( void )
abstract public void MongoDB\BSON\Unserializable::bsonUnserialize ( array $data )
}
MongoDB\BSON\Type
MongoDB\BSON\Serializable
MongoDB\Driver\BSON


The MongoDB\BSON\Serializable interface

(mongodb >=1.0.0)

Introducere

Classes that implement this interface may return data to be serialized as a BSON array or document in lieu of the object's public properties.

Sinopsisul clasei

MongoDB\BSON\Serializable implements MongoDB\BSON\Type {
/* Metode */
abstract public array|object bsonSerialize ( void )
}

Cuprins

  • MongoDB\BSON\Serializable::bsonSerialize — Provides an array or document to serialize as BSON
MongoDB\BSON\Persistable
MongoDB\BSON\Serializable::bsonSerialize
MongoDB\Driver\BSON


Provides an array or document to serialize as BSON

MongoDB\BSON\Serializable
MongoDB\BSON\Unserializable
MongoDB\BSON\Serializable
PHP Manual

MongoDB\BSON\Serializable::bsonSerialize

(mongodb >=1.0.0)

MongoDB\BSON\Serializable::bsonSerialize — Provides an array or document to serialize as BSON

Descrierea

abstract public array|object MongoDB\BSON\Serializable::bsonSerialize ( void )

Called during serialization of the object to BSON. The method must return an array or stdClass.

Root documents (e.g. a MongoDB\BSON\Serializable passed to MongoDB\BSON\fromPHP()) will always be serialized as a BSON document. For field values, associative arrays and stdClass instances will be serialized as a BSON document and sequential arrays (i.e. sequential, numeric indexes starting at 0) will be serialized as a BSON array.

Users are encouraged to include an _id property (e.g. a MongoDB\BSON\ObjectID initialized in your constructor) when returning data for a BSON root document; otherwise, the driver or database will need to generate a MongoDB\BSON\ObjectID when inserting or upserting the document, respectively.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array or stdClass to be serialized as a BSON array or document.

Exemple

Example #1 MongoDB\BSON\Serializable::bsonSerialize() returning an associative array for root document

<?php

class MyDocument implements MongoDB\BSON\Serializable
{
    private $id;

    function __construct()
    {
        $this->id = new MongoDB\BSON\ObjectID;
    }

    function bsonSerialize()
    {
        return ['_id' => $this->id, 'foo' => 'bar'];
    }
}

$bson = MongoDB\BSON\fromPHP(new MyDocument);
echo MongoDB\BSON\toJSON($bson), "\n";

?>

Exemplul de mai sus va afi?a ceva similar cu:

{ "_id" : { "$oid" : "56cccdcada14d8755a58c591" }, "foo" : "bar" }

Example #2 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for root document

<?php

class MyArray implements MongoDB\BSON\Serializable
{
    function bsonSerialize()
    {
        return [1, 2, 3];
    }
}

$bson = MongoDB\BSON\fromPHP(new MyArray);
echo MongoDB\BSON\toJSON($bson), "\n";

?>

Exemplul de mai sus va afi?a:

{ "0" : 1, "1" : 2, "2" : 3 }

Example #3 MongoDB\BSON\Serializable::bsonSerialize() returning an associative array for document field

<?php

class MyDocument implements MongoDB\BSON\Serializable
{
    function bsonSerialize()
    {
        return ['foo' => 'bar'];
    }
}

$value = ['document' => new MyDocument];
$bson = MongoDB\BSON\fromPHP($value);
echo MongoDB\BSON\toJSON($bson), "\n";

?>

Exemplul de mai sus va afi?a:

{ "document" : { "foo" : "bar" } }

Example #4 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for document field

<?php

class MyArray implements MongoDB\BSON\Serializable
{
    function bsonSerialize()
    {
        return [1, 2, 3];
    }
}

$value = ['array' => new MyArray];
$bson = MongoDB\BSON\fromPHP($value);
echo MongoDB\BSON\toJSON($bson), "\n";

?>

Exemplul de mai sus va afi?a:

{ "array" : [ 1, 2, 3 ] }

A se vedea ?i

  • MongoDB\BSON\Unserializable::bsonUnserialize() - Constructs the object from a BSON array or document
  • MongoDB\BSON\Persistable
  • Persisting Data
MongoDB\BSON\Serializable
MongoDB\BSON\Unserializable
MongoDB\BSON\Serializable


The MongoDB\BSON\Unserializable interface

(mongodb >=1.0.0)

Introducere

Classes that implement this interface may be specified in a type map for unserializing BSON arrays and documents (both root and embedded).

Sinopsisul clasei

MongoDB\BSON\Unserializable {
/* Metode */
abstract public void bsonUnserialize ( array $data )
}

Cuprins

  • MongoDB\BSON\Unserializable::bsonUnserialize — Constructs the object from a BSON array or document
MongoDB\BSON\Serializable::bsonSerialize
MongoDB\BSON\Unserializable::bsonUnserialize
MongoDB\Driver\BSON


Constructs the object from a BSON array or document

MongoDB\BSON\Unserializable
MongoDB\Driver\Exception
MongoDB\BSON\Unserializable
PHP Manual

MongoDB\BSON\Unserializable::bsonUnserialize

(mongodb >=1.0.0)

MongoDB\BSON\Unserializable::bsonUnserialize — Constructs the object from a BSON array or document

Descrierea

abstract public void MongoDB\BSON\Unserializable::bsonUnserialize ( array $data )

Called during unserialization of the object from BSON. The properties of the BSON array or document will be passed to the method as an array.

Remember to check for an _id property when handling data from a BSON document.

Nota:

This method acts as the constructor of the object. The __construct() method will not be called after this method.

Parametri

data (array)

Properties within the BSON array or document.

Valorile întoarse

The return value from this method is ignored.

Exemple

Example #1 MongoDB\BSON\Unserializable::bsonUnserialize() example

<?php

class MyDocument implements MongoDB\BSON\Unserializable
{
    private $data = [];

    function bsonUnserialize(array $data)
    {
        $this->data = $data;
    }
}

$bson = MongoDB\BSON\fromJSON('{ "foo": "bar" }');
$value = MongoDB\BSON\toPHP($bson, ['root' => 'MyDocument']);
var_dump($value);

?>

Exemplul de mai sus va afi?a:

object(MyDocument)#1 (1) {
  ["data":"MyDocument":private]=>
  array(1) {
    ["foo"]=>
    string(3) "bar"
  }
}

A se vedea ?i

  • MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
  • MongoDB\BSON\Persistable
  • Persisting Data
MongoDB\BSON\Unserializable
MongoDB\Driver\Exception
MongoDB\BSON\Unserializable


Exception classes

  • MongoDB\Driver\Exception\AuthenticationException — The MongoDB\Driver\Exception\AuthenticationException class
  • MongoDB\Driver\Exception\BulkWriteException — The MongoDB\Driver\Exception\BulkWriteException class
  • MongoDB\Driver\Exception\ConnectionException — The MongoDB\Driver\Exception\ConnectionException class
  • MongoDB\Driver\Exception\ConnectionTimeoutException — The MongoDB\Driver\Exception\ConnectionTimeoutException class
  • MongoDB\Driver\Exception\Exception — The MongoDB\Driver\Exception\Exception interface
  • MongoDB\Driver\Exception\ExecutionTimeoutException — The MongoDB\Driver\Exception\ExecutionTimeoutException class
  • MongoDB\Driver\Exception\InvalidArgumentException — The MongoDB\Driver\Exception\InvalidArgumentException class
  • MongoDB\Driver\Exception\LogicException — The MongoDB\Driver\Exception\LogicException class
  • MongoDB\Driver\Exception\RuntimeException — The MongoDB\Driver\Exception\RuntimeException class
  • MongoDB\Driver\Exception\SSLConnectionException — The MongoDB\Driver\Exception\SSLConnectionException class
  • MongoDB\Driver\Exception\UnexpectedValueException — The MongoDB\Driver\Exception\UnexpectedValueException class
  • MongoDB\Driver\Exception\WriteException — The MongoDB\Driver\Exception\WriteException class
    • MongoDB\Driver\Exception\WriteException::getWriteResult — Returns the WriteResult for the failed write operation
MongoDB\BSON\Unserializable::bsonUnserialize
MongoDB\Driver\Exception\AuthenticationException
MongoDB


The MongoDB\Driver\Exception\AuthenticationException class

(mongodb >= 1.0.0)

Introducere

Thrown when the driver fails to authenticate with the server.

Sinopsisul clasei

MongoDB\Driver\Exception\AuthenticationException extends MongoDB\Driver\Exception\ConnectionException implements MongoDB\Driver\Exception\Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
MongoDB\Driver\Exception
MongoDB\Driver\Exception\BulkWriteException
MongoDB\Driver\Exception


The MongoDB\Driver\Exception\BulkWriteException class

(mongodb >= 1.0.0)

Introducere

Thrown when a bulk write operation fails.

Sinopsisul clasei

MongoDB\Driver\Exception\BulkWriteException extends MongoDB\Driver\Exception\WriteException implements MongoDB\Driver\Exception\Exception {
/* Proprieta?i mo?tenite */
protected MongoDB\Driver\WriteResult $writeResult ;
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public MongoDB\Driver\WriteResult MongoDB\Driver\Exception\WriteException::getWriteResult ( void )
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
MongoDB\Driver\Exception\AuthenticationException
MongoDB\Driver\Exception\ConnectionException
MongoDB\Driver\Exception


The MongoDB\Driver\Exception\ConnectionException class

(mongodb >= 1.0.0)

Introducere

Base class for exceptions thrown when the driver fails to establish a database connection.

Sinopsisul clasei

MongoDB\Driver\Exception\ConnectionException extends MongoDB\Driver\Exception\RuntimeException implements MongoDB\Driver\Exception\Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
MongoDB\Driver\Exception\BulkWriteException
MongoDB\Driver\Exception\ConnectionTimeoutException
MongoDB\Driver\Exception


The MongoDB\Driver\Exception\ConnectionTimeoutException class

(mongodb >= 1.0.0)

Introducere

Thrown when the driver fails to establish a database connection within a specified time limit (e.g. » connectTimeoutMS).

Sinopsisul clasei

MongoDB\Driver\Exception\ConnectionTimeoutException extends MongoDB\Driver\Exception\ConnectionException implements MongoDB\Driver\Exception\Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
MongoDB\Driver\Exception\ConnectionException
MongoDB\Driver\Exception\Exception
MongoDB\Driver\Exception


The MongoDB\Driver\Exception\Exception interface

(mongodb >= 1.0.0)

Introducere

Common interface for all driver exceptions. This may be used to catch only exceptions originating from the driver itself.

Sinopsisul clasei

MongoDB\Driver\Exception\Exception {
}
MongoDB\Driver\Exception\ConnectionTimeoutException
MongoDB\Driver\Exception\ExecutionTimeoutException
MongoDB\Driver\Exception


The MongoDB\Driver\Exception\ExecutionTimeoutException class

(mongodb >= 1.0.0)

Introducere

Thrown when a query or command fails to complete within a specified time limit (e.g. » maxTimeMS).

Sinopsisul clasei

MongoDB\Driver\Exception\ExecutionTimeoutException extends MongoDB\Driver\Exception\RuntimeException implements MongoDB\Driver\Exception\Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
MongoDB\Driver\Exception\Exception
MongoDB\Driver\Exception\InvalidArgumentException
MongoDB\Driver\Exception


The MongoDB\Driver\Exception\InvalidArgumentException class

(mongodb >= 1.0.0)

Introducere

Thrown when a driver method is given invalid arguments (e.g. invalid option types).

Sinopsisul clasei

MongoDB\Driver\Exception\InvalidArgumentException extends InvalidArgumentException implements MongoDB\Driver\Exception\Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
MongoDB\Driver\Exception\ExecutionTimeoutException
MongoDB\Driver\Exception\LogicException
MongoDB\Driver\Exception


The MongoDB\Driver\Exception\LogicException class

(mongodb >= 1.0.0)

Introducere

Thrown when the driver is incorrectly used (e.g. rewinding a cursor).

Sinopsisul clasei

MongoDB\Driver\Exception\LogicException extends LogicException implements MongoDB\Driver\Exception\Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
MongoDB\Driver\Exception\InvalidArgumentException
MongoDB\Driver\Exception\RuntimeException
MongoDB\Driver\Exception


The MongoDB\Driver\Exception\RuntimeException class

(mongodb >= 1.0.0)

Introducere

Thrown when the driver encounters a runtime error (e.g. internal error from » libmongoc).

Sinopsisul clasei

MongoDB\Driver\Exception\RuntimeException extends RuntimeException implements MongoDB\Driver\Exception\Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
MongoDB\Driver\Exception\LogicException
MongoDB\Driver\Exception\SSLConnectionException
MongoDB\Driver\Exception


The MongoDB\Driver\Exception\SSLConnectionException class

(mongodb >= 1.0.0)

Introducere

Thrown when the driver fails to establish an SSL connection with the server.

Sinopsisul clasei

MongoDB\Driver\Exception\SSLConnectionException extends MongoDB\Driver\Exception\ConnectionException implements MongoDB\Driver\Exception\Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
MongoDB\Driver\Exception\RuntimeException
MongoDB\Driver\Exception\UnexpectedValueException
MongoDB\Driver\Exception


The MongoDB\Driver\Exception\UnexpectedValueException class

(mongodb >= 1.0.0)

Introducere

Thrown when the driver encounters an unexpected value (e.g. during BSON serialization or deserialization).

Sinopsisul clasei

MongoDB\Driver\Exception\UnexpectedValueException extends UnexpectedValueException implements MongoDB\Driver\Exception\Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
MongoDB\Driver\Exception\SSLConnectionException
MongoDB\Driver\Exception\WriteException
MongoDB\Driver\Exception


The MongoDB\Driver\Exception\WriteException class

(mongodb >= 1.0.0)

Introducere

Base class for exceptions thrown by a failed write operation. The exception encapsulates a MongoDB\Driver\WriteResult object.

Sinopsisul clasei

abstract MongoDB\Driver\Exception\WriteException extends MongoDB\Driver\Exception\RuntimeException implements MongoDB\Driver\Exception\Exception {
/* Proprieta?i */
protected MongoDB\Driver\WriteResult $writeResult ;
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode */
final public MongoDB\Driver\WriteResult getWriteResult ( void )
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Proprieta?i

writeResult

The MongoDB\Driver\WriteResult associated with the failed write operation.

Cuprins

  • MongoDB\Driver\Exception\WriteException::getWriteResult — Returns the WriteResult for the failed write operation
MongoDB\Driver\Exception\UnexpectedValueException
MongoDB\Driver\Exception\WriteException::getWriteResult
MongoDB\Driver\Exception


Returns the WriteResult for the failed write operation

MongoDB\Driver\Exception\WriteException
mSQL
MongoDB\Driver\Exception\WriteException
PHP Manual

MongoDB\Driver\Exception\WriteException::getWriteResult

(mongodb >= 1.0.0)

MongoDB\Driver\Exception\WriteException::getWriteResult — Returns the WriteResult for the failed write operation

Descrierea

final public MongoDB\Driver\WriteResult MongoDB\Driver\Exception\WriteException::getWriteResult ( void )

Returns the MongoDB\Driver\WriteResult for the failed write operation. The MongoDB\Driver\WriteResult::getWriteErrors() and MongoDB\Driver\WriteResult::getWriteConcernError() methods may be used to get more details about the failure.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The MongoDB\Driver\WriteResult for the failed write operation.

Exemple

Example #1 MongoDB\Driver\Exception\WriteException::getWriteResult() example

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost');
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);

try {
    $manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\WriteException $e) {
    $writeResult = $e->getWriteResult();

    if ($writeConcernError = $writeResult->getWriteConcernError()) {
        var_dump($writeConcernError);
    }

    if ($writeErrors = $writeResult->getWriteErrors()) {
        var_dump($writeErrors);
    }
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [0]=>
  object(MongoDB\Driver\WriteError)#5 (4) {
    ["message"]=>
    string(70) "E11000 duplicate key error index: db.collection.$_id_ dup key: { : 1 }"
    ["code"]=>
    int(11000)
    ["index"]=>
    int(1)
    ["info"]=>
    NULL
  }
}

A se vedea ?i

  • MongoDB\Driver\WriteResult
  • MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
MongoDB\Driver\Exception\WriteException
mSQL
MongoDB\Driver\Exception\WriteException


mSQL

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic usage
  • Func?ii mSQL
    • msql_affected_rows — Returns number of affected rows
    • msql_close — Close mSQL connection
    • msql_connect — Open mSQL connection
    • msql_create_db — Create mSQL database
    • msql_createdb — Pseudonim pentru msql_create_db
    • msql_data_seek — Move internal row pointer
    • msql_db_query — Send mSQL query
    • msql_dbname — Pseudonim pentru msql_result
    • msql_drop_db — Drop (delete) mSQL database
    • 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 — Pseudonim al msql_field_flags
    • msql_fieldlen — Pseudonim al msql_field_len
    • msql_fieldname — Pseudonim al msql_field_name
    • msql_fieldtable — Pseudonim al msql_field_table
    • msql_fieldtype — Pseudonim al 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 — Pseudonim al msql_num_fields
    • msql_numrows — Pseudonim al msql_num_rows
    • msql_pconnect — Open persistent mSQL connection
    • msql_query — Send mSQL query
    • msql_regcase — Pseudonim al sql_regcase
    • msql_result — Get result data
    • msql_select_db — Select mSQL database
    • msql_tablename — Pseudonim al msql_result
    • msql — Pseudonim al msql_db_query
MongoDB\Driver\Exception\WriteException::getWriteResult
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

These functions allow you to access mSQL database servers. More information about mSQL can be found at » http://www.hughes.com.au/.

mSQL
Instalarea / configurarea
mSQL


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
mSQL


Instalarea

Pentru ca aceste func?ii sa fie disponibile, PHP trebuie sa fie compilat cu sus?ineara msql, utilizând op?iunea --with-msql[=DIR] . DIR este directorul de baza unde este instalat mSQL, implicit /usr/local/msql3.

Nota: Nota pentru utilizatorii Win32

Pentru ca aceasta extensie sa func?ioneze, anumite fi?iere DLL trebuie sa fie accesibile în calea de sistem a Windows din variabila PATH. Pentru informa?ii despre cum poate fi realizat acest lucru, accesa?i FAQ întitulat " Cum sa adaug directorul meu PHP la variabila PATH din Windows" pentru informa?ii despre cum sa realiza?i aceasta. Cu toate ca copierea fi?ierelor DLL din directorul PHP în directorul de sistem al Windows de asemenea func?ioneaza (deoarece directorul de sistem este în mod implicit inclus în variabila PATH), acest lucru nu este recomandabil. Aceasta extensie necesita ca urmatoarele fi?iere sa existe în calea PATH : msql.dll

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

mSQL configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
msql.allow_persistent | "1" | PHP_INI_ALL |
msql.max_persistent | "-1" | PHP_INI_ALL |
msql.max_links | "-1" | PHP_INI_ALL |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

msql.allow_persistent boolean

Whether to allow persistent mSQL connections.

msql.max_persistent integer

The maximum number of persistent mSQL connections per process.

msql.max_links integer

The maximum number of mSQL connections per process, including persistent connections.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

There are two resource types used in the mSQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

MSQL_ASSOC (integer)
MSQL_NUM (integer)
MSQL_BOTH (integer)
Tipurile resurselor
Exemple
mSQL


Exemple

Cuprins

  • Basic usage
Constante predefinite
Basic usage
mSQL


Basic usage

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a mSQL database.

Example #1 mSQL usage example

<?php
/* Connecting, selecting database */
$link = msql_connect('localhost', 'username', 'password')
    or die('Could not connect : ' . msql_error($link));

msql_select_db('database', $link)
    or die('Could not select database');

/* Issue SQL query */
$query = 'SELECT * FROM my_table';
$result = msql_query($query, $link) or die('Query failed : ' . msql_error());

/* Printing results in 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";

/* Free result set */
msql_free_result($result);

/* Close connection */
msql_close($link);
?>

Exemple
Func?ii mSQL
Exemple


Func?ii mSQL

Cuprins

  • msql_affected_rows — Returns number of affected rows
  • msql_close — Close mSQL connection
  • msql_connect — Open mSQL connection
  • msql_create_db — Create mSQL database
  • msql_createdb — Pseudonim pentru msql_create_db
  • msql_data_seek — Move internal row pointer
  • msql_db_query — Send mSQL query
  • msql_dbname — Pseudonim pentru msql_result
  • msql_drop_db — Drop (delete) mSQL database
  • 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 — Pseudonim al msql_field_flags
  • msql_fieldlen — Pseudonim al msql_field_len
  • msql_fieldname — Pseudonim al msql_field_name
  • msql_fieldtable — Pseudonim al msql_field_table
  • msql_fieldtype — Pseudonim al 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 — Pseudonim al msql_num_fields
  • msql_numrows — Pseudonim al msql_num_rows
  • msql_pconnect — Open persistent mSQL connection
  • msql_query — Send mSQL query
  • msql_regcase — Pseudonim al sql_regcase
  • msql_result — Get result data
  • msql_select_db — Select mSQL database
  • msql_tablename — Pseudonim al msql_result
  • msql — Pseudonim al msql_db_query
Basic usage
msql_affected_rows
mSQL


Returns number of affected rows

Func?ii mSQL
msql_close
Func?ii mSQL
PHP Manual

msql_affected_rows

(PHP 4, PHP 5, PHP 7)

msql_affected_rows — Returns number of affected rows

Descrierea

int msql_affected_rows ( resource $result )

Returns number of affected rows by the last SELECT, UPDATE or DELETE query associated with result.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

Valorile întoarse

Returns the number of affected rows on success, or FALSE on error.

A se vedea ?i

  • msql_query() - Send mSQL query

Func?ii mSQL
msql_close
Func?ii mSQL


Close mSQL connection

msql_affected_rows
msql_connect
Func?ii mSQL
PHP Manual

msql_close

(PHP 4, PHP 5, PHP 7)

msql_close — Close mSQL connection

Descrierea

bool msql_close ([ resource $link_identifier ] )

msql_close() closes the non-persistent connection to the mSQL server that's associated with the specified link identifier.

Using msql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.

Parametri

link_identifier

Conexiunea mSQL. Daca nu este specificata, se presupune ca este ultima legatura deschisa cu msql_connect (). Daca nu se gase?te vre-o legatura de acest fel, func?ia va încerca sa stabileasca o legatura prin apelarea msql_connect() ?i sa o utilizeze pe aceasta.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • msql_connect() - Open mSQL connection
  • msql_pconnect() - Open persistent mSQL connection

msql_affected_rows
msql_connect
Func?ii mSQL


Open mSQL connection

msql_close
msql_create_db
Func?ii mSQL
PHP Manual

msql_connect

(PHP 4, PHP 5, PHP 7)

msql_connect — Open mSQL connection

Descrierea

resource msql_connect ([ string $hostname ] )

msql_connect() establishes a connection to a mSQL server.

If a second call is made to msql_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 msql_close().

Parametri

hostname

The hostname can also include a port number. e.g. hostname,port.

If not specified, the connection is established by the means of a Unix domain socket, being then more efficient then a localhost TCP socket connection.

Nota:

While this function will accept a colon (:) as a host/port separator, a comma (,) is the preferred method.

Valorile întoarse

Returns a positive mSQL link identifier on success, or FALSE on error.

A se vedea ?i

  • msql_pconnect() - Open persistent mSQL connection
  • msql_close() - Close mSQL connection

msql_close
msql_create_db
Func?ii mSQL


Create mSQL database

msql_connect
msql_createdb
Func?ii mSQL
PHP Manual

msql_create_db

(PHP 4, PHP 5, PHP 7)

msql_create_db — Create mSQL database

Descrierea

bool msql_create_db ( string $database_name [, resource $link_identifier ] )

msql_create_db() attempts to create a new database on the mSQL server.

Parametri

database_name

The name of the mSQL database.

link_identifier

Conexiunea mSQL. Daca nu este specificata, se presupune ca este ultima legatura deschisa cu msql_connect (). Daca nu se gase?te vre-o legatura de acest fel, func?ia va încerca sa stabileasca o legatura prin apelarea msql_connect() ?i sa o utilizeze pe aceasta.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • msql_drop_db() - Drop (delete) mSQL database

msql_connect
msql_createdb
Func?ii mSQL


Pseudonim pentru msql_create_db

msql_create_db
msql_data_seek
Func?ii mSQL
PHP Manual

msql_createdb

(PHP 4, PHP 5, PHP 7)

msql_createdb — Pseudonim pentru msql_create_db()

Descrierea

Aceasta func?ie este pseudonim pentru: msql_create_db().

msql_create_db
msql_data_seek
Func?ii mSQL


Move internal row pointer

msql_createdb
msql_db_query
Func?ii mSQL
PHP Manual

msql_data_seek

(PHP 4, PHP 5, PHP 7)

msql_data_seek — Move internal row pointer

Descrierea

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.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

row_number

The seeked row number.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii mSQL


Send mSQL query

msql_data_seek
msql_dbname
Func?ii mSQL
PHP Manual

msql_db_query

(PHP 4, PHP 5, PHP 7)

msql_db_query — Send mSQL query

Descrierea

resource msql_db_query ( string $database , string $query [, resource $link_identifier ] )

msql_db_query() selects a database and executes a query on it.

Parametri

database

The name of the mSQL database.

query

The SQL query.

link_identifier

Conexiunea mSQL. Daca nu este specificata, se presupune ca este ultima legatura deschisa cu msql_connect (). Daca nu se gase?te vre-o legatura de acest fel, func?ia va încerca sa stabileasca o legatura prin apelarea msql_connect() ?i sa o utilizeze pe aceasta.

Valorile întoarse

Returns a positive mSQL query identifier to the query result, or FALSE on error.

A se vedea ?i

  • msql_query() - Send mSQL query

msql_data_seek
msql_dbname
Func?ii mSQL


Pseudonim pentru msql_result

msql_db_query
msql_drop_db
Func?ii mSQL
PHP Manual

msql_dbname

(PHP 4, PHP 5, PHP 7)

msql_dbname — Pseudonim pentru msql_result()

Descrierea

Aceasta func?ie este pseudonim pentru: msql_result().

msql_db_query
msql_drop_db
Func?ii mSQL


Drop (delete) mSQL database

msql_dbname
msql_error
Func?ii mSQL
PHP Manual

msql_drop_db

(PHP 4, PHP 5, PHP 7)

msql_drop_db — Drop (delete) mSQL database

Descrierea

bool msql_drop_db ( string $database_name [, resource $link_identifier ] )

msql_drop_db() attempts to drop (remove) a database from the mSQL server.

Parametri

database_name

The name of the database.

link_identifier

Conexiunea mSQL. Daca nu este specificata, se presupune ca este ultima legatura deschisa cu msql_connect (). Daca nu se gase?te vre-o legatura de acest fel, func?ia va încerca sa stabileasca o legatura prin apelarea msql_connect() ?i sa o utilizeze pe aceasta.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • msql_create_db() - Create mSQL database

msql_dbname
msql_error
Func?ii mSQL


Returns error message of last msql call

msql_drop_db
msql_fetch_array
Func?ii mSQL
PHP Manual

msql_error

(PHP 4, PHP 5, PHP 7)

msql_error — Returns error message of last msql call

Descrierea

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().

Valorile întoarse

The last error message or an empty string if no error was issued.

msql_drop_db
msql_fetch_array
Func?ii mSQL


Fetch row as array

msql_error
msql_fetch_field
Func?ii mSQL
PHP Manual

msql_fetch_array

(PHP 4, PHP 5, PHP 7)

msql_fetch_array — Fetch row as array

Descrierea

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.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre 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.

Valorile întoarse

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

A se vedea ?i

  • 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
Func?ii mSQL


Get field information

msql_fetch_array
msql_fetch_object
Func?ii mSQL
PHP Manual

msql_fetch_field

(PHP 4, PHP 5, PHP 7)

msql_fetch_field — Get field information

Descrierea

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.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

field_offset

The field offset. If not specified, the next field that wasn't yet retrieved by msql_fetch_field() is retrieved.

Valorile întoarse

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

A se vedea ?i

  • msql_field_seek() - Set field offset

msql_fetch_array
msql_fetch_object
Func?ii mSQL


Fetch row as object

msql_fetch_field
msql_fetch_row
Func?ii mSQL
PHP Manual

msql_fetch_object

(PHP 4, PHP 5, PHP 7)

msql_fetch_object — Fetch row as object

Descrierea

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).

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

Valorile întoarse

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

A se vedea ?i

  • 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
Func?ii mSQL


Get row as enumerated array

msql_fetch_object
msql_field_flags
Func?ii mSQL
PHP Manual

msql_fetch_row

(PHP 4, PHP 5, PHP 7)

msql_fetch_row — Get row as enumerated array

Descrierea

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.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

Valorile întoarse

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

A se vedea ?i

  • 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
Func?ii mSQL


Get field flags

msql_fetch_row
msql_field_len
Func?ii mSQL
PHP Manual

msql_field_flags

(PHP 4, PHP 5, PHP 7)

msql_field_flags — Get field flags

Descrierea

string msql_field_flags ( resource $result , int $field_offset )

msql_field_flags() returns the field flags of the specified field.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

field_offset

Deplasamentul numeric al câmpului. field_offset începe de la 1.

Valorile întoarse

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
Func?ii mSQL


Get field length

msql_field_flags
msql_field_name
Func?ii mSQL
PHP Manual

msql_field_len

(PHP 4, PHP 5, PHP 7)

msql_field_len — Get field length

Descrierea

int msql_field_len ( resource $result , int $field_offset )

msql_field_len() returns the length of the specified field.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

field_offset

Deplasamentul numeric al câmpului. field_offset începe de la 1.

Valorile întoarse

Returns the length of the specified field or FALSE on error.

msql_field_flags
msql_field_name
Func?ii mSQL


Get the name of the specified field in a result

msql_field_len
msql_field_seek
Func?ii mSQL
PHP Manual

msql_field_name

(PHP 4, PHP 5, PHP 7)

msql_field_name — Get the name of the specified field in a result

Descrierea

string msql_field_name ( resource $result , int $field_offset )

msql_field_name() gets the name of the specified field index.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

field_offset

Deplasamentul numeric al câmpului. field_offset începe de la 1.

Valorile întoarse

The name of the field sau FALSE în cazul e?ecului.

A se vedea ?i

  • msql_field_len() - Get field length

msql_field_len
msql_field_seek
Func?ii mSQL


Set field offset

msql_field_name
msql_field_table
Func?ii mSQL
PHP Manual

msql_field_seek

(PHP 4, PHP 5, PHP 7)

msql_field_seek — Set field offset

Descrierea

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.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

field_offset

Deplasamentul numeric al câmpului. field_offset începe de la 1.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • msql_fetch_field() - Get field information

msql_field_name
msql_field_table
Func?ii mSQL


Get table name for field

msql_field_seek
msql_field_type
Func?ii mSQL
PHP Manual

msql_field_table

(PHP 4, PHP 5, PHP 7)

msql_field_table — Get table name for field

Descrierea

int msql_field_table ( resource $result , int $field_offset )

Returns the name of the table that the specified field is in.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

field_offset

Deplasamentul numeric al câmpului. field_offset începe de la 1.

Valorile întoarse

The name of the table on success sau FALSE în cazul e?ecului.

msql_field_seek
msql_field_type
Func?ii mSQL


Get field type

msql_field_table
msql_fieldflags
Func?ii mSQL
PHP Manual

msql_field_type

(PHP 4, PHP 5, PHP 7)

msql_field_type — Get field type

Descrierea

string msql_field_type ( resource $result , int $field_offset )

msql_field_type() gets the type of the specified field index.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

field_offset

Deplasamentul numeric al câmpului. field_offset începe de la 1.

Valorile întoarse

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
Func?ii mSQL


Pseudonim al msql_field_flags

msql_field_type
msql_fieldlen
Func?ii mSQL
PHP Manual

msql_fieldflags

(PHP 4, PHP 5, PHP 7)

msql_fieldflags — Pseudonim al msql_field_flags()

Descrierea

Aceasta func?ie este un pseudonim al msql_field_flags().

msql_field_type
msql_fieldlen
Func?ii mSQL


Pseudonim al msql_field_len

msql_fieldflags
msql_fieldname
Func?ii mSQL
PHP Manual

msql_fieldlen

(PHP 4, PHP 5, PHP 7)

msql_fieldlen — Pseudonim al msql_field_len()

Descrierea

Aceasta func?ie este un pseudonim al msql_field_len().

msql_fieldflags
msql_fieldname
Func?ii mSQL


Pseudonim al msql_field_name

msql_fieldlen
msql_fieldtable
Func?ii mSQL
PHP Manual

msql_fieldname

(PHP 4, PHP 5, PHP 7)

msql_fieldname — Pseudonim al msql_field_name()

Descrierea

Aceasta func?ie este un pseudonim al msql_field_name().

msql_fieldlen
msql_fieldtable
Func?ii mSQL


Pseudonim al msql_field_table

msql_fieldname
msql_fieldtype
Func?ii mSQL
PHP Manual

msql_fieldtable

(PHP 4, PHP 5, PHP 7)

msql_fieldtable — Pseudonim al msql_field_table()

Descrierea

Aceasta func?ie este un pseudonim al msql_field_table().

msql_fieldname
msql_fieldtype
Func?ii mSQL


Pseudonim al msql_field_type

msql_fieldtable
msql_free_result
Func?ii mSQL
PHP Manual

msql_fieldtype

(PHP 4, PHP 5, PHP 7)

msql_fieldtype — Pseudonim al msql_field_type()

Descrierea

Aceasta func?ie este un pseudonim al msql_field_type().

msql_fieldtable
msql_free_result
Func?ii mSQL


Free result memory

msql_fieldtype
msql_list_dbs
Func?ii mSQL
PHP Manual

msql_free_result

(PHP 4, PHP 5, PHP 7)

msql_free_result — Free result memory

Descrierea

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.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

msql_fieldtype
msql_list_dbs
Func?ii mSQL


List mSQL databases on server

msql_free_result
msql_list_fields
Func?ii mSQL
PHP Manual

msql_list_dbs

(PHP 4, PHP 5, PHP 7)

msql_list_dbs — List mSQL databases on server

Descrierea

resource msql_list_dbs ([ resource $link_identifier ] )

msql_list_tables() lists the databases available on the specified link_identifier.

Parametri

link_identifier

Conexiunea mSQL. Daca nu este specificata, se presupune ca este ultima legatura deschisa cu msql_connect (). Daca nu se gase?te vre-o legatura de acest fel, func?ia va încerca sa stabileasca o legatura prin apelarea msql_connect() ?i sa o utilizeze pe aceasta.

Valorile întoarse

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.

A se vedea ?i

  • msql_list_tables() - List tables in an mSQL database
  • msql_list_fields() - List result fields

msql_free_result
msql_list_fields
Func?ii mSQL


List result fields

msql_list_dbs
msql_list_tables
Func?ii mSQL
PHP Manual

msql_list_fields

(PHP 4, PHP 5, PHP 7)

msql_list_fields — List result fields

Descrierea

resource msql_list_fields ( string $database , string $tablename [, resource $link_identifier ] )

msql_list_fields() returns information about the given table.

Parametri

database

The name of the database.

tablename

The name of the table.

link_identifier

Conexiunea mSQL. Daca nu este specificata, se presupune ca este ultima legatura deschisa cu msql_connect (). Daca nu se gase?te vre-o legatura de acest fel, func?ia va încerca sa stabileasca o legatura prin apelarea msql_connect() ?i sa o utilizeze pe aceasta.

Valorile întoarse

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.

A se vedea ?i

  • msql_list_tables() - List tables in an mSQL database
  • msql_list_dbs() - List mSQL databases on server

msql_list_dbs
msql_list_tables
Func?ii mSQL


List tables in an mSQL database

msql_list_fields
msql_num_fields
Func?ii mSQL
PHP Manual

msql_list_tables

(PHP 4, PHP 5, PHP 7)

msql_list_tables — List tables in an mSQL database

Descrierea

resource msql_list_tables ( string $database [, resource $link_identifier ] )

msql_list_tables() lists the tables on the specified database.

Parametri

database

The name of the database.

link_identifier

Conexiunea mSQL. Daca nu este specificata, se presupune ca este ultima legatura deschisa cu msql_connect (). Daca nu se gase?te vre-o legatura de acest fel, func?ia va încerca sa stabileasca o legatura prin apelarea msql_connect() ?i sa o utilizeze pe aceasta.

Valorile întoarse

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.

A se vedea ?i

  • msql_list_fields() - List result fields
  • msql_list_dbs() - List mSQL databases on server

msql_list_fields
msql_num_fields
Func?ii mSQL


Get number of fields in result

msql_list_tables
msql_num_rows
Func?ii mSQL
PHP Manual

msql_num_fields

(PHP 4, PHP 5, PHP 7)

msql_num_fields — Get number of fields in result

Descrierea

int msql_num_fields ( resource $result )

msql_num_fields() returns the number of fields in a result set.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

Valorile întoarse

Returns the number of fields in the result set.

A se vedea ?i

  • 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
Func?ii mSQL


Get number of rows in result

msql_num_fields
msql_numfields
Func?ii mSQL
PHP Manual

msql_num_rows

(PHP 4, PHP 5, PHP 7)

msql_num_rows — Get number of rows in result

Descrierea

int msql_num_rows ( resource $query_identifier )

msql_num_rows() returns the number of rows in a result set.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre msql_query ().

Valorile întoarse

Returns the number of rows in the result set.

A se vedea ?i

  • msql_num_fields() - Get number of fields in result

msql_num_fields
msql_numfields
Func?ii mSQL


Pseudonim al msql_num_fields

msql_num_rows
msql_numrows
Func?ii mSQL
PHP Manual

msql_numfields

(PHP 4, PHP 5, PHP 7)

msql_numfields — Pseudonim al msql_num_fields()

Descrierea

Aceasta func?ie este un pseudonim al msql_num_fields().

msql_num_rows
msql_numrows
Func?ii mSQL


Pseudonim al msql_num_rows

msql_numfields
msql_pconnect
Func?ii mSQL
PHP Manual

msql_numrows

(PHP 4, PHP 5, PHP 7)

msql_numrows — Pseudonim al msql_num_rows()

Descrierea

Aceasta func?ie este un pseudonim al msql_num_rows().

msql_numfields
msql_pconnect
Func?ii mSQL


Open persistent mSQL connection

msql_numrows
msql_query
Func?ii mSQL
PHP Manual

msql_pconnect

(PHP 4, PHP 5, PHP 7)

msql_pconnect — Open persistent mSQL connection

Descrierea

resource msql_pconnect ([ string $hostname ] )

msql_pconnect() acts very much like msql_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. 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 (msql_close() will not close links established by this function).

Parametri

hostname

The hostname can also include a port number. e.g. hostname,port.

If not specified, the connection is established by the means of a Unix domain socket, being more efficient than a localhost TCP socket connection.

Nota: While this function will accept a colon (:) as a host/port separator, a comma (,) is the preferred method.

Valorile întoarse

Returns a positive mSQL link identifier on success, or FALSE on error.

A se vedea ?i

  • msql_connect() - Open mSQL connection
  • msql_close() - Close mSQL connection

msql_numrows
msql_query
Func?ii mSQL


Send mSQL query

msql_pconnect
msql_regcase
Func?ii mSQL
PHP Manual

msql_query

(PHP 4, PHP 5, PHP 7)

msql_query — Send mSQL query

Descrierea

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.

Parametri

query

The SQL query.

link_identifier

Conexiunea mSQL. Daca nu este specificata, se presupune ca este ultima legatura deschisa cu msql_connect (). Daca nu se gase?te vre-o legatura de acest fel, func?ia va încerca sa stabileasca o legatura prin apelarea msql_connect() ?i sa o utilizeze pe aceasta.

Valorile întoarse

Returns a positive mSQL query identifier on success, or FALSE on error.

Exemple

Example #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"];
}
?>

A se vedea ?i

  • msql_db_query() - Send mSQL query
  • msql_select_db() - Select mSQL database
  • msql_connect() - Open mSQL connection

msql_pconnect
msql_regcase
Func?ii mSQL


Pseudonim al sql_regcase

msql_query
msql_result
Func?ii mSQL
PHP Manual

msql_regcase

(PHP 4, PHP 5, PHP 7)

msql_regcase — Pseudonim al sql_regcase()

Descrierea

Aceasta func?ie este un pseudonim al sql_regcase().

msql_query
msql_result
Func?ii mSQL


Get result data

msql_regcase
msql_select_db
Func?ii mSQL
PHP Manual

msql_result

(PHP 4, PHP 5, PHP 7)

msql_result — Get result data

Descrierea

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().

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine din apelul catre 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.

Nota:

Specifying a numeric field offset is much quicker than specifying a fieldname or tablename.fieldname.

Valorile întoarse

Returns the contents of the cell at the row and offset in the specified mSQL result set.

msql_regcase
msql_select_db
Func?ii mSQL


Select mSQL database

msql_result
msql_tablename
Func?ii mSQL
PHP Manual

msql_select_db

(PHP 4, PHP 5, PHP 7)

msql_select_db — Select mSQL database

Descrierea

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.

Parametri

database_name

The database name.

link_identifier

Conexiunea mSQL. Daca nu este specificata, se presupune ca este ultima legatura deschisa cu msql_connect (). Daca nu se gase?te vre-o legatura de acest fel, func?ia va încerca sa stabileasca o legatura prin apelarea msql_connect() ?i sa o utilizeze pe aceasta.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • msql_connect() - Open mSQL connection
  • msql_pconnect() - Open persistent mSQL connection
  • msql_query() - Send mSQL query

msql_result
msql_tablename
Func?ii mSQL


Pseudonim al msql_result

msql_select_db
msql
Func?ii mSQL
PHP Manual

msql_tablename

(PHP 4, PHP 5, PHP 7)

msql_tablename — Pseudonim al msql_result()

Descrierea

Aceasta func?ie este un pseudonim al msql_result().

msql_select_db
msql
Func?ii mSQL


Pseudonim al msql_db_query

msql_tablename
Mssql
Func?ii mSQL
PHP Manual

msql

(PHP 4, PHP 5, PHP 7)

msql — Pseudonim al msql_db_query()

Descrierea

Aceasta func?ie este un pseudonim al msql_db_query().

msql_tablename
Mssql
Func?ii mSQL


Microsoft SQL Server

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Mssql
    • mssql_bind — Adds a parameter to a stored procedure or a remote stored procedure
    • mssql_close — Close MS SQL Server connection
    • mssql_connect — Open MS SQL server connection
    • 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 — Returns the last message from the server
    • 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 — Sets the minimum error severity
    • mssql_min_message_severity — Sets the minimum message severity
    • mssql_next_result — Move the internal result pointer to the next result
    • mssql_num_fields — Gets the number of fields in result
    • mssql_num_rows — Gets the number of rows in result
    • mssql_pconnect — Open persistent MS SQL connection
    • mssql_query — Send MS SQL query
    • mssql_result — Get result data
    • mssql_rows_affected — Returns the number of records affected by the query
    • mssql_select_db — Select MS SQL database
msql
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

Avertizare

Aceasta facilitate a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta facilitate sunt:

  • PDO_SQLSRV (Windows only)
  • PDO_ODBC
  • SQLSRV (Windows only)
  • Unified ODBC API

These functions allow you to access MS SQL Server database.

This extension is not available anymore on Windows with PHP 5.3 or later.

SQLSRV, an alternative extension for MS SQL connectivity is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Mssql
Instalarea / configurarea
Mssql


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Mssql


Necesita?i

Requirements for Win32 platforms.

The extension requires the MS SQL Client Tools to be installed on the system where PHP is installed. The Client Tools can be installed from the MS SQL Server CD or by copying ntwdblib.dll from \winnt\system32 on the server to \winnt\system32 on the PHP box. Copying ntwdblib.dll will only provide access through named pipes. Configuration of the client will require installation of all the tools.

This extension is not available anymore on Windows with PHP 5.3 or later.

SqlSrv, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Requirements for Unix/Linux platforms.

To use the MSSQL extension on Unix/Linux, you first need to build and install the FreeTDS library. Source code and installation instructions are available at the FreeTDS home page: » http://www.freetds.org/

Nota:

On Windows, the DBLIB from Microsoft is used. Functions that return a column name are based on the dbcolname() function in DBLIB. DBLIB was developed for SQL Server 6.x where the max identifier length is 30. For this reason, the maximum column length is 30 characters. On platforms where FreeTDS is used (Linux), this is not a problem.

Nota:

On Windows, if you're using MSSQL 2005 or greater you must copy the ntwdblib.dll into the directory where you have installed php and overwrite the one thats already in there. This is due to the version distributed is old and outdated. Alternatively you can use the » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx, ODBC, PDO_DBLIB or PDO_ODBC extensions, to talk to MSSQL.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

The MSSQL extension is enabled by adding extension=php_mssql.dll to php.ini.

To get these functions to work, you have to compile PHP with --with-mssql[=DIR] , where DIR is the FreeTDS install prefix. And FreeTDS should be compiled using --enable-msdblib .

Avertizare

MS SQL functions are aliases to Sybase functions if PHP is compiled with Sybase extension and without MS SQL extension.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

MS SQL Server configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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 | Available since PHP 4.1.0.
mssql.textsize | "-1" | PHP_INI_ALL |
mssql.textlimit | "-1" | PHP_INI_ALL |
mssql.batchsize | "0" | PHP_INI_ALL | Available since PHP 4.0.4.
mssql.datetimeconvert | "1" | PHP_INI_ALL | Available since PHP 4.2.0.
mssql.secure_connection | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.0.
mssql.max_procs | "-1" | PHP_INI_ALL | Available since PHP 4.3.0.
mssql.charset | "" | PHP_INI_ALL | Available since PHP 5.1.2 when built with FreeTDS 7.0 or greater.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

mssql link

A connection link returned by mssql_connect() and mssql_pconnect().

mssql result

A result handle returned by mssql_query() on SELECT queries.

mssql statement

A statement handle returned by mssql_init().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

MSSQL_ASSOC (integer)
Return an associative array. Used on mssql_fetch_array()'s result_type parameter.
MSSQL_NUM (integer)
Return an array with numeric keys. Used on mssql_fetch_array()'s result_type parameter.
MSSQL_BOTH (integer)
Return an array with both numeric keys and keys with their field name. This is the default value for mssql_fetch_array()'s result_type parameter.
SQLTEXT (integer)
Indicates the 'TEXT' type in MSSQL, used by mssql_bind()'s type parameter.
SQLVARCHAR (integer)
Indicates the 'VARCHAR' type in MSSQL, used by mssql_bind()'s type parameter.
SQLCHAR (integer)
Indicates the 'CHAR' type in MSSQL, used by mssql_bind()'s type parameter.
SQLINT1 (integer)
Represents one byte, with a range of -128 to 127.
SQLINT2 (integer)
Represents two bytes, with a range of -32768 to 32767.
SQLINT4 (integer)
Represents four bytes, with a range of -2147483648 to 2147483647.
SQLBIT (integer)
Indicates the 'BIT' type in MSSQL, used by mssql_bind()'s type parameter.
SQLFLT4 (integer)
Represents an four byte float.
SQLFLT8 (integer)
Represents an eight byte float.
Tipurile resurselor
Func?ii Mssql
Mssql


Func?ii Mssql

Cuprins

  • mssql_bind — Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_close — Close MS SQL Server connection
  • mssql_connect — Open MS SQL server connection
  • 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 — Returns the last message from the server
  • 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 — Sets the minimum error severity
  • mssql_min_message_severity — Sets the minimum message severity
  • mssql_next_result — Move the internal result pointer to the next result
  • mssql_num_fields — Gets the number of fields in result
  • mssql_num_rows — Gets the number of rows in result
  • mssql_pconnect — Open persistent MS SQL connection
  • mssql_query — Send MS SQL query
  • mssql_result — Get result data
  • mssql_rows_affected — Returns the number of records affected by the query
  • mssql_select_db — Select MS SQL database
Constante predefinite
mssql_bind
Mssql


Adds a parameter to a stored procedure or a remote stored procedure

Func?ii Mssql
mssql_close
Func?ii 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

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::bindParam()
  • PDOStatement::bindValue()
  • sqlsrv_prepare()
  • odbc_prepare()

Descrierea

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.

Parametri

stmt

Statement resource, obtained with mssql_init().

param_name

The parameter name, as a string.

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • 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

Func?ii Mssql
mssql_close
Func?ii Mssql


Close MS SQL Server connection

mssql_bind
mssql_connect
Func?ii Mssql
PHP Manual

mssql_close

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_close — Close MS SQL Server connection

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • sqlsrv_close()
  • odbc_close()
  • odbc_close_all()

Descrierea

bool mssql_close ([ resource $link_identifier ] )

Closes the link to a MS SQL Server database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

Parametri

link_identifier

A MS SQL link identifier, returned by mssql_connect().

This function will not close persistent links generated by mssql_pconnect().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 mssql_close() example

<?php
// Connect to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Do any related operations here

// Close the link to MSSQL
mssql_close($link);
?>

A se vedea ?i

  • mssql_connect() - Open MS SQL server connection
  • mssql_pconnect() - Open persistent MS SQL connection

mssql_bind
mssql_connect
Func?ii Mssql


Open MS SQL server connection

mssql_close
mssql_data_seek
Func?ii Mssql
PHP Manual

mssql_connect

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_connect — Open MS SQL server connection

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDO::__construct()
  • sqlsrv_connect()
  • odbc_connect()

Descrierea

resource mssql_connect ([ string $servername [, string $username [, string $password [, bool $new_link = false ]]]] )

mssql_connect() establishes a connection to a MS SQL server.

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 mssql_close().

Parametri

servername

The MS SQL server. It can also include a port number, e.g. hostname:port (Linux), or hostname,port (Windows).

username

The username.

password

The password.

new_link

If a second call is made to mssql_connect() 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_connect() always open a new link, even if mssql_connect() was called before with the same parameters.

Valorile întoarse

Returns a MS SQL link identifier on success, or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | The new_link parameter was added

Exemple

Example #1 mssql_connect() example

<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = 'KALLESPC\SQLEXPRESS';

// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'phpfi');

if (!$link) {
    die('Something went wrong while connecting to MSSQL');
}
?>

A se vedea ?i

  • mssql_close() - Close MS SQL Server connection
  • mssql_pconnect() - Open persistent MS SQL connection

mssql_close
mssql_data_seek
Func?ii Mssql


Moves internal row pointer

mssql_connect
mssql_execute
Func?ii Mssql
PHP Manual

mssql_data_seek

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_data_seek — Moves internal row pointer

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • Using an OFFSET clause with a query issued through PDO_SQLSRV, PDO_ODBC, SQLSRV, or the unified ODBC driver.

Descrierea

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.

Parametri

result_identifier

The result resource that is being evaluated.

row_number

The desired row number of the new result pointer.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii Mssql


Executes a stored procedure on a MS SQL server database

mssql_data_seek
mssql_fetch_array
Func?ii 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

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • Using an EXEC query issued through PDO_SQLSRV, PDO_ODBC, SQLSRV, or the unified ODBC driver.

Descrierea

mixed mssql_execute ( resource $stmt [, bool $skip_results = false ] )

Executes a stored procedure on a MS SQL server database

Parametri

stmt

Statement handle obtained with mssql_init().

skip_results

Whenever to skip the results or not.

Exemple

Example #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);
?>

Note

Nota:

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.

A se vedea ?i

  • 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
Func?ii Mssql


Fetch a result row as an associative array, a numeric array, or both

mssql_execute
mssql_fetch_assoc
Func?ii 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

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::fetch()
  • sqlsrv_fetch_array()
  • odbc_fetch_array()

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Exemple

Example #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);
?>

Note

Nota: Numele câmpurilor întoarse de aceasta func?ie sunt sensibile la literele majuscule/minuscule.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

A se vedea ?i

  • mssql_fetch_row() - Get row as enumerated array

mssql_execute
mssql_fetch_assoc
Func?ii Mssql


Returns an associative array of the current row in the result

mssql_fetch_array
mssql_fetch_batch
Func?ii 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

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::fetch()
  • sqlsrv_fetch_array()
  • odbc_fetch_array()

Descrierea

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.

Parametri

result_id

The result resource that is being evaluated. This result comes from a call to mssql_query().

Valorile întoarse

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

Exemple

Example #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
Func?ii Mssql


Returns the next batch of records

mssql_fetch_assoc
mssql_fetch_field
Func?ii 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

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

int mssql_fetch_batch ( resource $result )

Returns the next batch of records.

Parametri

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Valorile întoarse

Returns the number of rows in the returned batch.

Exemple

Example #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
Func?ii Mssql


Get field information

mssql_fetch_batch
mssql_fetch_object
Func?ii Mssql
PHP Manual

mssql_fetch_field

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_field — Get field information

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::getColumnMeta()
  • sqlsrv_field_metadata()
  • The various odbc_field_* functions in the unified ODBC driver.

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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);
?>

A se vedea ?i

  • mssql_field_seek() - Seeks to the specified field offset

mssql_fetch_batch
mssql_fetch_object
Func?ii Mssql


Fetch row as object

mssql_fetch_field
mssql_fetch_row
Func?ii Mssql
PHP Manual

mssql_fetch_object

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_object — Fetch row as object

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::fetchObject()
  • sqlsrv_fetch_object()
  • odbc_fetch_object()

Descrierea

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).

Parametri

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Valorile întoarse

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Exemple

Example #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);
?>

Note

Nota: Numele câmpurilor întoarse de aceasta func?ie sunt sensibile la literele majuscule/minuscule.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

A se vedea ?i

  • 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
Func?ii Mssql


Get row as enumerated array

mssql_fetch_object
mssql_field_length
Func?ii Mssql
PHP Manual

mssql_fetch_row

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_row — Get row as enumerated array

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::fetch()
  • sqlsrv_fetch_array()
  • odbc_fetch_row()

Descrierea

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.

Parametri

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Valorile întoarse

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Exemple

Example #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] . '"';
?>

Exemplul de mai sus va afi?a ceva similar cu:

Quote #42: "The answer to everything..."

Note

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

A se vedea ?i

  • 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
Func?ii Mssql


Get the length of a field

mssql_fetch_row
mssql_field_name
Func?ii Mssql
PHP Manual

mssql_field_length

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_length — Get the length of a field

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::getColumnMeta()
  • sqlsrv_field_metadata()
  • odbc_field_len()

Descrierea

int mssql_field_length ( resource $result [, int $offset = -1 ] )

Returns the length of field no. offset in result.

Parametri

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.

Valorile întoarse

The length of the specified field index on success sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

The field 'age' has a data length of 4

Note

Nota: 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.

A se vedea ?i

  • mssql_field_name() - Get the name of a field
  • mssql_field_type() - Gets the type of a field

mssql_fetch_row
mssql_field_name
Func?ii Mssql


Get the name of a field

mssql_field_length
mssql_field_seek
Func?ii Mssql
PHP Manual

mssql_field_name

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_name — Get the name of a field

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::getColumnMeta()
  • sqlsrv_field_metadata()
  • odbc_field_name()

Descrierea

string mssql_field_name ( resource $result [, int $offset = -1 ] )

Returns the name of field no. offset in result.

Parametri

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.

Valorile întoarse

The name of the specified field index on success sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Result set contains the following field(s):
 - username
 - name
 - email

A se vedea ?i

  • mssql_field_length() - Get the length of a field
  • mssql_field_type() - Gets the type of a field

mssql_field_length
mssql_field_seek
Func?ii Mssql


Seeks to the specified field offset

mssql_field_name
mssql_field_type
Func?ii Mssql
PHP Manual

mssql_field_seek

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_seek — Seeks to the specified field offset

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • mssql_fetch_field() - Get field information

mssql_field_name
mssql_field_type
Func?ii Mssql


Gets the type of a field

mssql_field_seek
mssql_free_result
Func?ii Mssql
PHP Manual

mssql_field_type

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_type — Gets the type of a field

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::getColumnMeta()
  • sqlsrv_field_metadata()
  • odbc_field_type()

Descrierea

string mssql_field_type ( resource $result [, int $offset = -1 ] )

Returns the type of field no. offset in result.

Parametri

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.

Valorile întoarse

The type of the specified field index on success sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

'name' is a type of CHAR(50)

A se vedea ?i

  • mssql_field_length() - Get the length of a field
  • mssql_field_name() - Get the name of a field

mssql_field_seek
mssql_free_result
Func?ii Mssql


Free result memory

mssql_field_type
mssql_free_statement
Func?ii Mssql
PHP Manual

mssql_free_result

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_free_result — Free result memory

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • odbc_free_result()

Descrierea

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.

Parametri

result

The result resource that is being freed. This result comes from a call to mssql_query().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • mssql_free_statement() - Free statement memory

mssql_field_type
mssql_free_statement
Func?ii Mssql


Free statement memory

mssql_free_result
mssql_get_last_message
Func?ii Mssql
PHP Manual

mssql_free_statement

(PHP 4 >= 4.3.2, PHP 5, PECL odbtp >= 1.1.1)

mssql_free_statement — Free statement memory

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • sqlsrv_free_stmt()

Descrierea

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.

Parametri

stmt

Statement resource, obtained with mssql_init().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii Mssql


Returns the last message from the server

mssql_free_statement
mssql_guid_string
Func?ii Mssql
PHP Manual

mssql_get_last_message

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_get_last_message — Returns the last message from the server

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::errorInfo()
  • sqlsrv_errors()
  • odbc_errormsg()

Descrierea

string mssql_get_last_message ( void )

Gets the last message from the MS-SQL server

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns last error message from server, or an empty string if no error messages are returned from MSSQL.

Exemple

Example #1 mssql_get_last_message() example

<?php
// Connect to MSSQL and select the database
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());
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

MSSQL error: Invalid object name 'php.dbo.not-found'.

A se vedea ?i

  • mssql_min_error_severity() - Sets the minimum error severity
  • mssql_min_message_severity() - Sets the minimum message severity

mssql_free_statement
mssql_guid_string
Func?ii Mssql


Converts a 16 byte binary GUID to a string

mssql_get_last_message
mssql_init
Func?ii 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

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

string mssql_guid_string ( string $binary [, bool $short_format = false ] )

Converts a 16 byte binary GUID to a string.

Parametri

binary

A 16 byte binary GUID.

short_format

Whenever to use short format.

Valorile întoarse

Returns the converted string on success.

Exemple

Example #1 mssql_guid_string() example

<?php
$binary = '19555081977808608437941339997619274330352755554827939936';

var_dump(mssql_guid_string($binary));
var_dump(mssql_guid_string($binary, true));
?>

Exemplul de mai sus va afi?a:

string(36) "35353931-3035-3138-3937-373830383630"
string(32) "31393535353038313937373830383630"

mssql_get_last_message
mssql_init
Func?ii Mssql


Initializes a stored procedure or a remote stored procedure

mssql_guid_string
mssql_min_error_severity
Func?ii 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

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • Using an EXEC query issued through PDO_SQLSRV, PDO_ODBC, SQLSRV, or the unified ODBC driver.

Descrierea

resource mssql_init ( string $sp_name [, resource $link_identifier ] )

Initializes a stored procedure or a remote stored procedure.

Parametri

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().

Valorile întoarse

Returns a resource identifier "statement", used in subsequent calls to mssql_bind() and mssql_execute(), or FALSE on errors.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii Mssql


Sets the minimum error severity

mssql_init
mssql_min_message_severity
Func?ii Mssql
PHP Manual

mssql_min_error_severity

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_min_error_severity — Sets the minimum error severity

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

void mssql_min_error_severity ( int $severity )

Sets the minimum error severity.

Parametri

severity

The new error severity.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 mssql_min_error_severity() example

<?php
// Connect to MSSQL and select the database
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
Func?ii Mssql


Sets the minimum message severity

mssql_min_error_severity
mssql_next_result
Func?ii Mssql
PHP Manual

mssql_min_message_severity

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_min_message_severity — Sets the minimum message severity

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

void mssql_min_message_severity ( int $severity )

Sets the minimum message severity.

Parametri

severity

The new message severity.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 mssql_min_message_severity() example

<?php
// Connect to MSSQL
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Set the minimum message severity to 17, this
// will not show any messages issued by the underlaying
// API when we select a non-existent database below
mssql_min_message_severity(17);

// Select a non-existent database
mssql_select_db('THIS_DATABASE_DOES_NOT_EXISTS');
?>

Exemplul de mai sus va afi?a:

mssql_select_db(): Unable to select database:  THIS_DATABASE_DOES_NOT_EXISTS

mssql_min_error_severity
mssql_next_result
Func?ii Mssql


Move the internal result pointer to the next result

mssql_min_message_severity
mssql_num_fields
Func?ii 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

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::nextRowset()
  • sqlsrv_next_result()
  • odbc_next_result()

Descrierea

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.

Parametri

result_id

The result resource that is being evaluated. This result comes from a call to mssql_query().

Valorile întoarse

Returns TRUE if an additional result set was available or FALSE otherwise.

Exemple

Example #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
Func?ii Mssql


Gets the number of fields in result

mssql_next_result
mssql_num_rows
Func?ii Mssql
PHP Manual

mssql_num_fields

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_num_fields — Gets the number of fields in result

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::columnCount()
  • sqlsrv_num_fields()
  • odbc_num_fields()

Descrierea

int mssql_num_fields ( resource $result )

mssql_num_fields() returns the number of fields in a result set.

Parametri

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Valorile întoarse

Returns the number of fields, as an integer.

Exemple

Example #1 mssql_num_fields() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Select some data from our database
$data = mssql_query('SELECT [name], [age] FROM [php].[dbo].[persons]');

// Construct a table
echo '<table border="1">';

$header = false;

// Iterate through returned results
while ($row = mssql_fetch_array($data)) {
    // Build the table header
    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;
    }

    // Build the row
    echo '<tr>';

    foreach($row as $value) {
        echo '<td>' . $value . '</td>';
    }

    echo '</tr>';
}

// Close table
echo '</tbody>';
echo '</table>';

// Clean up
mssql_free_result($data);
mssql_close($link);
?>

A se vedea ?i

  • mssql_query() - Send MS SQL query
  • mssql_fetch_field() - Get field information
  • mssql_num_rows() - Gets the number of rows in result

mssql_next_result
mssql_num_rows
Func?ii Mssql


Gets the number of rows in result

mssql_num_fields
mssql_pconnect
Func?ii Mssql
PHP Manual

mssql_num_rows

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_num_rows — Gets the number of rows in result

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::rowCount()
  • sqlsrv_num_rows()
  • odbc_num_rows()

Descrierea

int mssql_num_rows ( resource $result )

mssql_num_rows() returns the number of rows in a result set.

Parametri

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Valorile întoarse

Returns the number of rows, as an integer.

Exemple

Example #1 mssql_num_rows() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Select all our records from a table
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]');

echo 'Total records in database: ' . mssql_num_rows($query);

// Clean up
mssql_free_result($query);
?>

A se vedea ?i

  • mssql_query() - Send MS SQL query
  • mssql_fetch_row() - Get row as enumerated array

mssql_num_fields
mssql_pconnect
Func?ii Mssql


Open persistent MS SQL connection

mssql_num_rows
mssql_query
Func?ii Mssql
PHP Manual

mssql_pconnect

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_pconnect — Open persistent MS SQL connection

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDO::__construct()
  • sqlsrv_connect()
  • odbc_pconnect()

Descrierea

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'.

Parametri

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.

Valorile întoarse

Returns a positive MS SQL persistent link identifier on success, or FALSE on error.

Exemple

Example #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
Func?ii Mssql


Send MS SQL query

mssql_pconnect
mssql_result
Func?ii Mssql
PHP Manual

mssql_query

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_query — Send MS SQL query

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDO::query()
  • sqlsrv_query()
  • odbc_exec()

Descrierea

mixed mssql_query ( string $query [, resource $link_identifier [, int $batch_size = 0 ]] )

mssql_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parametri

query

An SQL query.

link_identifier

A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect().

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 mssql_connect() was called, and use it.

batch_size

The number of records to batch in the buffer.

Valorile întoarse

Returns a MS SQL result resource on success, TRUE if no rows were returned, or FALSE on error.

Exemple

Example #1 mssql_query() example

<?php
// Connect to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

if (!$link || !mssql_select_db('php', $link)) {
    die('Unable to connect or select database!');
}

// Do a simple query, select the version of
// MSSQL and print it.
$version = mssql_query('SELECT @@VERSION');
$row = mssql_fetch_array($version);

echo $row[0];

// Clean up
mssql_free_result($version);
?>

Note

Nota:

If the query returns multiple results then it is necessary to fetch all results by mssql_next_result() or free the results by mssql_free_result() before executing next query.

A se vedea ?i

  • mssql_select_db() - Select MS SQL database
  • mssql_connect() - Open MS SQL server connection

mssql_pconnect
mssql_result
Func?ii Mssql


Get result data

mssql_query
mssql_rows_affected
Func?ii Mssql
PHP Manual

mssql_result

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_result — Get result data

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • odbc_result()

Descrierea

string mssql_result ( resource $result , int $row , mixed $field )

mssql_result() returns the contents of one cell from a MS SQL result set.

Parametri

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.

Nota:

Specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Valorile întoarse

Returns the contents of the specified cell.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Kalle
Felipe
Emil
Ross

Example #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);
?>

Note

Nota:

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().

A se vedea ?i

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
Func?ii Mssql


Returns the number of records affected by the query

mssql_result
mssql_select_db
Func?ii Mssql
PHP Manual

mssql_rows_affected

(PHP 4 >= 4.0.4, PHP 5, PECL odbtp >= 1.1.1)

mssql_rows_affected — Returns the number of records affected by the query

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDOStatement::rowCount()
  • sqlsrv_rows_affected()

Descrierea

int mssql_rows_affected ( resource $link_identifier )

Returns the number of records affected by the last write query.

Parametri

link_identifier

A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect().

Valorile întoarse

Returns the number of records affected by last operation.

Exemple

Example #1 mssql_rows_affected() example

<?php
// Delete all rows in a table
mssql_query('TRUNCATE TABLE [php].[dbo].[persons]');

echo 'Deleted ' . mssql_rows_affected($link) . ' row(s)';
?>

mssql_result
mssql_select_db
Func?ii Mssql


Select MS SQL database

mssql_rows_affected
MySQL
Func?ii Mssql
PHP Manual

mssql_select_db

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_select_db — Select MS SQL database

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • PDO_SQLSRV DSN
  • PDO_ODBC DSN
  • sqlsrv_connect()
  • odbc_connect()

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Example #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);
?>

A se vedea ?i

  • mssql_connect() - Open MS SQL server connection
  • mssql_pconnect() - Open persistent MS SQL connection
  • mssql_query() - Send MS SQL query

mssql_rows_affected
MySQL
Func?ii 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
    • Concepts
  • MySQLi — MySQL Improved Extension
    • Introducere
    • Overview
    • Quick start guide
    • Instalarea / configurarea
    • The mysqli Extension and Persistent Connections
    • Constante predefinite
    • Notes
    • The MySQLi Extension Function Summary
    • Exemple
    • 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
    • mysqli_sql_exception — The mysqli_sql_exception class
    • Pseudonime ?i Func?ii Mysqli învechite
    • Jurnalul modificarilor
  • MySQL (Original) — API originale ale MySQL
    • Introducere
    • Instalarea / configurarea
    • Jurnalul modificarilor
    • Constante predefinite
    • Exemple
    • Func?ii MySQL
  • Mysqlnd — MySQL Native Driver
    • Introducere
    • Overview
    • Installation
    • Configura?ia la rulare
    • Incompatibilities
    • Persistent Connections
    • Statistics
    • Notes
    • Memory management
    • MySQL Native Driver Plugin API
  • mysqlnd_ms — Mysqlnd replication and load balancing plugin
    • Introducere
    • Quickstart and Examples
    • Concepts
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii mysqlnd_ms
    • Change History
  • mysqlnd_qc — Mysqlnd query result cache plugin
    • Introducere
    • Quickstart and Examples
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii mysqlnd_qc
    • Change History
  • mysqlnd_uh — Mysqlnd user handler plugin
    • Introducere
    • Quickstart and Examples
    • Instalarea / configurarea
    • Constante predefinite
    • MysqlndUhConnection — The MysqlndUhConnection class
    • MysqlndUhPreparedStatement — The MysqlndUhPreparedStatement class
    • Func?ii mysqlnd_uh
    • Change History
  • mysqlnd_mux — Mysqlnd connection multiplexing plugin
    • Introducere
    • Concepts
    • Instalarea / configurarea
    • Constante predefinite
    • Change History
  • mysqlnd_memcache — Mysqlnd Memcache plugin
    • Introducere
    • Quickstart and Examples
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii mysqlnd_memcache
    • Change History
mssql_select_db
Overview of the MySQL PHP drivers
Extensii de lucru cu baze de date specifice anumitor producatori


Overview of the MySQL PHP drivers

Introduction

Depending on the version of PHP, there are either two or three PHP APIs for accessing the MySQL database. PHP 5 users can choose between the deprecated mysql extension, mysqli, or PDO_MySQL. PHP 7 removes the mysql extension, leaving only the latter two options.

This guide explains the terminology used to describe each API, information about choosing which API to use, and also information to help choose which MySQL library to use with the API.

  • Terminology overview
  • Choosing an API
  • Choosing a library
  • Concepts
    • Buffered and Unbuffered queries
    • Character sets
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.

Example #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, as it was deprecated in PHP 5.5.0 and was removed in PHP 7. 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
Included with PHP 7.x | Yes | Yes | No
Development status | Active | Active | Maintenance only in 5.x; removed in 7.x
Lifecycle | Active | Active | Deprecated in 5.x; removed in 7.x
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
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 libmysqlclient 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 libmysqlclient, 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.

Example #1 Configure commands for using mysqlnd or libmysqlclient

// Recommended, compiles with mysqlnd
$ ./configure --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-mysql=mysqlnd

// Alternatively recommended, compiles with mysqlnd as of PHP 5.4
$ ./configure --with-mysqli --with-pdo-mysql --with-mysql

// Not recommended, compiles with libmysqlclient
$ ./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 (libmysqlclient). Both libraries are supported and constantly being improved.

 | MySQL native driver (mysqlnd) | MySQL client server library (libmysqlclient)
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 and above; 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
Uses PHP's native memory management system (e.g., follows PHP memory limits) | 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
Automatic reconnect | No | Optional
Choosing an API
Concepts
Overview of the MySQL PHP drivers


Concepts

Cuprins

  • Buffered and Unbuffered queries
  • Character sets

These concepts are specific to the MySQL drivers for PHP.

Choosing a library
Buffered and Unbuffered queries
Overview of the MySQL PHP drivers


Buffered and Unbuffered queries

Queries are using the buffered mode by default. This means that query results are immediately transferred from the MySQL Server to PHP and then are kept in the memory of the PHP process. This allows additional operations like counting the number of rows, and moving (seeking) the current result pointer. It also allows issuing further queries on the same connection while working on the result set. The downside of the buffered mode is that larger result sets might require quite a lot memory. The memory will be kept occupied till all references to the result set are unset or the result set was explicitly freed, which will automatically happen during request end the latest. The terminology "store result" is also used for buffered mode, as the whole result set is stored at once.

Nota:

When using libmysqlclient as library PHP's memory limit won't count the memory used for result sets unless the data is fetched into PHP variables. With mysqlnd the memory accounted for will include the full result set.

Unbuffered MySQL queries execute the query and then return a resource while the data is still waiting on the MySQL server for being fetched. This uses less memory on the PHP-side, but can increase the load on the server. Unless the full result set was fetched from the server no further queries can be sent over the same connection. Unbuffered queries can also be referred to as "use result".

Following these characteristics buffered queries should be used in cases where you expect only a limited result set or need to know the amount of returned rows before reading all rows. Unbuffered mode should be used when you expect larger results.

Because buffered queries are the default, the examples below will demonstrate how to execute unbuffered queries with each API.

Example #1 Unbuffered query example: mysqli

<?php
$mysqli  = new mysqli("localhost", "my_user", "my_password", "world");
$uresult = $mysqli->query("SELECT Name FROM City", MYSQLI_USE_RESULT);

if ($uresult) {
   while ($row = $uresult->fetch_assoc()) {
       echo $row['Name'] . PHP_EOL;
   }
}
$uresult->close();
?>

Example #2 Unbuffered query example: pdo_mysql

<?php
$pdo = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_pass');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

$uresult = $pdo->query("SELECT Name FROM City");
if ($uresult) {
   while ($row = $uresult->fetch(PDO::FETCH_ASSOC)) {
       echo $row['Name'] . PHP_EOL;
   }
}
?>

Example #3 Unbuffered query example: mysql

<?php
$conn = mysql_connect("localhost", "my_user", "my_pass");
$db   = mysql_select_db("world");

$uresult = mysql_unbuffered_query("SELECT Name FROM City");
if ($uresult) {
   while ($row = mysql_fetch_assoc($uresult)) {
       echo $row['Name'] . PHP_EOL;
   }
}
?>
Concepts
Character sets
Concepts


Character sets

Ideally a proper character set will be set at the server level, and doing this is described within the » Character Set Configuration section of the MySQL Server manual. Alternatively, each MySQL API offers a method to set the character set at runtime.

Precautie

The character set and character escaping

The character set should be understood and defined, as it has an affect on every action, and includes security implications. For example, the escaping mechanism (e.g., mysqli_real_escape_string() for mysqli, mysql_real_escape_string() for mysql, and PDO::quote() for PDO_MySQL) will adhere to this setting. It is important to realize that these functions will not use the character set that is defined with a query, so for example the following will not have an effect on them:

Example #1 Problems with setting the character set with SQL

<?php

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

// Will NOT affect $mysqli->real_escape_string();
$mysqli->query("SET NAMES utf8");

// Will NOT affect $mysqli->real_escape_string();
$mysqli->query("SET CHARACTER SET utf8");

// But, this will affect $mysqli->real_escape_string();
$mysqli->set_charset('utf8');

// But, this will NOT affect it (utf-8 vs utf8) -- don't use dashes here
$mysqli->set_charset('utf-8');

?>

Below are examples that demonstrate how to properly alter the character set at runtime using each API.

Nota: Possible UTF-8 confusion

Because character set names in MySQL do not contain dashes, the string "utf8" is valid in MySQL to set the character set to UTF-8. The string "utf-8" is not valid, as using "utf-8" will fail to change the character set.

Example #2 Setting the character set example: mysqli

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

printf("Initial character set: %s\n", $mysqli->character_set_name());

if (!$mysqli->set_charset('utf8')) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit;
}

echo "New character set information:\n";
print_r( $mysqli->get_charset() );

?>

Example #3 Setting the character set example: pdo_mysql

Note: This only works as of PHP 5.3.6.

<?php
$pdo = new PDO("mysql:host=localhost;dbname=world;charset=utf8", 'my_user', 'my_pass');
?>

Example #4 Setting the character set example: mysql

<?php
$conn = mysql_connect("localhost", "my_user", "my_pass");
$db   = mysql_select_db("world");

echo 'Initial character set: ' .  mysql_client_encoding($conn) . "\n";

if (!mysql_set_charset('utf8', $conn)) {
    echo "Error: Unable to set the character set.\n";
    exit;
}

echo 'Your current character set is: ' .  mysql_client_encoding($conn);
?>
Buffered and Unbuffered queries
MySQLi
Concepts


MySQL Improved Extension

  • Introducere
  • Overview
  • Quick start guide
    • Dual procedural and object-oriented interface
    • Connections
    • Executing statements
    • Prepared Statements
    • Stored Procedures
    • Multiple Statements
    • API support for transactions
    • Metadata
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • The mysqli Extension and Persistent Connections
  • Constante predefinite
  • Notes
  • The MySQLi Extension Function Summary
  • Exemple
    • MySQLi extension basic examples
  • 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-committing database modifications
    • mysqli::begin_transaction — Starts a transaction
    • 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 — Get MySQL client info
    • mysqli::$client_version — Returns the MySQL client version as a string
    • 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::dump_debug_info — Dump debugging information into the log
    • mysqli::$errno — Returns the error code for the most recent function call
    • mysqli::$error_list — Returns a list of errors from the last command executed
    • 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 — Get MySQL client info
    • mysqli_get_client_stats — Returns client per-process statistics
    • mysqli_get_client_version — Returns the MySQL client version as an integer
    • 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 latest 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::release_savepoint — Removes the named savepoint from the set of savepoints of the current transaction
    • mysqli::rollback — Rolls back current transaction
    • mysqli::rpl_query_type — Returns RPL query type
    • mysqli::savepoint — Set a named transaction savepoint
    • 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::__construct — Constructs a new mysqli_stmt object
    • 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_list — Returns a list of errors from the last statement executed
    • 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::more_results — Check if there are more query results from a multiple query
    • mysqli_stmt::next_result — Reads the next result from a multiple query
    • 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 arbitrary 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_driver::$report_mode — Enables or disables internal report functions
  • mysqli_warning — The mysqli_warning class
    • mysqli_warning::__construct — The __construct purpose
    • mysqli_warning::next — The next purpose
  • mysqli_sql_exception — The mysqli_sql_exception class
  • Pseudonime ?i Func?ii Mysqli învechite
    • 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 — Pseudonim pentru mysqli::__construct
    • mysqli::disable_reads_from_master — Disable reads from master
    • 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 — Pseudonim pentru 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_links_stats — Return information about open and cached links
    • 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 — Pseudonim pentru mysqli_driver->report_mode
    • 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 — Pseudonim al mysqli_options
    • mysqli_slave_query — Force execution of a query on a slave in a master/slave setup
  • Jurnalul modificarilor
Character sets
Introducere
MySQL


Introducere

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 use either the » world or » sakila database, which are freely available.

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 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.

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.

Nota:

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 (Original).

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

Nota:

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 libmysqlclient.

However, the interface presented by libmysqlclient was not optimized for communication with PHP applications, as libmysqlclient was originally designed with C applications in mind. For this reason the MySQL Native Driver, mysqlnd, was developed as an alternative to libmysqlclient for PHP applications.

The mysql extension, the mysqli extension and the PDO MySQL driver can each be individually configured to use either libmysqlclient or mysqlnd. As mysqlnd is designed specifically to be utilised in the PHP system it has numerous memory and speed enhancements over libmysqlclient. You are strongly encouraged to take advantage of these improvements.

Nota:

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:

Comparison of MySQL API options for 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
Introducere
Quick start guide
MySQLi


Quick start guide

Cuprins

  • Dual procedural and object-oriented interface
  • Connections
  • Executing statements
  • Prepared Statements
  • Stored Procedures
  • Multiple Statements
  • API support for transactions
  • Metadata

This quick start guide will help with choosing and gaining familiarity with the PHP MySQL API.

This quick start gives an overview on the mysqli extension. Code examples are provided for all major aspects of the API. Database concepts are explained to the degree needed for presenting concepts specific to MySQL.

Required: A familiarity with the PHP programming language, the SQL language, and basic knowledge of the MySQL server.

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 paradigm.

Users migrating from the old mysql extension may prefer the procedural interface. The procedural interface is similar to that of the old mysql extension. In many cases, the 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.

Example #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("example.com", "user", "password");
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'];
?>

Exemplul de mai sus va afi?a:

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.

Example #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'];
?>

Exemplul de mai sus va afi?a:

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.

Example #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'];
}
?>

Exemplul de mai sus va afi?a:

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

Quick start guide
Connections
Quick start guide


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.

Example #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";
?>

Exemplul de mai sus va afi?a:

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 provided, then the extension attempts to use the default values that are set in the PHP configuration file.

Example #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 that is used by the extension. If the client library detects empty or unset parameters, then it may default to the library built-in values.

Built-in connection library defaults

If the host value is unset or empty, then 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, then 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 pipe name. If not given or empty, then the socket (pipe name) defaults to \\.\pipe\MySQL.

If neither a Unix domain socket based not a Windows named pipe based connection is to be established and the port parameter value is unset, the library will default to port 3306.

The mysqlnd library and the MySQL Client Library (libmysqlclient) implement the same logic for determining defaults.

Connection options

Connection options are available to, for example, 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 a unused persistent connection for a given combination of host, username, password, socket, port and default database can not be found in the connection pool, then 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 and 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 artifacts 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 behavior and best performance. Both are valid optimization goals. For ease of use, the safe behavior has been made the default at the expense of maximum performance.

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
Quick start guide


Executing statements

Statements can be executed with the
mysqli_query(), mysqli_real_query()
and mysqli_multi_query() functions.
The mysqli_query() function is the most
common, and combines the executing statement with 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().

Example #1 Connecting to MySQL

<?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. Navigation is fast because the result sets are held in client memory. Please, keep in mind that it is often easier to scale by client than it is to scale the server.

Example #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";
}
?>

Exemplul de mai sus va afi?a:

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.

Example #3 Navigation through unbuffered 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.

Example #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']));
?>

Exemplul de mai sus va afi?a:

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 library. 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.

Example #5 Native data types with mysqlnd and connection 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']));
?>

Exemplul de mai sus va afi?a:

id = 1 (integer)
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
Quick start guide


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 sent 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 ?.

Example #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.

Example #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 sent to the server. The statement is not parsed again. The statement template is not transferred to the server again.

Example #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());
?>

Exemplul de mai sus va afi?a:

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, multi-INSERT requires less round-trips between the server and client than the prepared statement shown above.

Example #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.

Example #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']));
?>

Exemplul de mai sus va afi?a:

id = 1 (integer)
label = a (string)

This behavior differs 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.

Example #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));
}
?>

Exemplul de mai sus va afi?a:

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.

Example #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());
?>

Exemplul de mai sus va afi?a:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    int(1)
    [1]=>
    string(1) "a"
  }
}

Using the mysqli_result interface offers the additional benefit of flexible client-side result set navigation.

Example #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();
?>

Exemplul de mai sus va afi?a:

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 are sent to the server separately from the query and thus cannot interfere with it. The server uses these values directly at the point of execution, after the statement template is parsed. Bound parameters do not need to be escaped as they are never substituted into the query string directly. A hint must be provided to the server for the type of bound variable, to create an appropriate conversion. See the mysqli_stmt_bind_param() function for more information.

Such a separation sometimes considered as the only security feature to prevent SQL injection, but the same degree of security can be achieved with non-prepared statements, if all the values are formatted correctly. It should be noted that correct formatting is not the same as escaping and involves more logic than simple escaping. Thus, prepared statements are simply a more convenient and less error-prone approach to this element of database security.

Client-side prepared statement emulation

The API does not include emulation for client-side prepared statement emulation.

Quick prepared - non-prepared statement comparison

The table below compares server-side prepared and non-prepared statements.

Comparison of 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 flavor | 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
Quick start guide


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.

Example #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());
?>

Exemplul de mai sus va afi?a:

array(1) {
  ["id"]=>
  string(1) "1"
}

INOUT/OUT parameter

The values of INOUT/OUT parameters are accessed using session variables.

Example #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'];
?>

Exemplul de mai sus va afi?a:

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.

Example #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());
?>

Exemplul de mai sus va afi?a:

---
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.

Example #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.

Example #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
Quick start guide


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 separated 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.

Example #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());
?>

Exemplul de mai sus va afi?a:

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.

Example #2 SQL Injection

<?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;
}
?>

Exemplul de mai sus va afi?a:

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 mysql.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
Quick start guide


API support for transactions

The MySQL server supports transactions depending on the storage engine used. Since MySQL 5.5, 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 committing and rolling back transactions.

Example #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.

Example #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 an implicit commit.

See also

  • mysqli::autocommit()
  • mysqli_result::commit()
  • mysqli_result::rollback()

Multiple Statements
Metadata
Quick start guide


Metadata

A MySQL result set contains metadata. The metadata describes the columns found in the result set. All metadata sent by MySQL is accessible through the mysqli interface. The extension performs no or negligible changes to the information it receives. Differences between MySQL server versions are not aligned.

Meta data is access through the mysqli_result interface.

Example #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());
?>

Exemplul de mai sus va afi?a:

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().

Example #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
Instalarea / configurarea
Quick start guide


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Metadata
Necesita?i
MySQLi


Necesita?i

In order to have these functions available, you must compile PHP with support for the mysqli extension.

Nota:

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

The mysqli extension was introduced with PHP version 5.0.0. The MySQL Native Driver was included in PHP version 5.3.0.

Installation on Linux

The common Unix distributions include binary versions of PHP that can be installed. Although these binary versions are typically built with support for the MySQL extensions, the extension libraries themselves may need to be installed using an additional package. Check the package manager that comes with your chosen distribution for availability.

For example, on Ubuntu the php5-mysql package installs the ext/mysql, ext/mysqli, and pdo_mysql PHP extensions. On CentOS, the php-mysql package also installs these three PHP extensions.

Alternatively, you can compile this extension yourself. Building PHP from source allows you to specify the MySQL extensions you want to use, as well as your choice of client library for each extension.

The MySQL Native Driver is the recommended client library option, as it results in improved performance and gives access to features not available when using the MySQL Client Library. Refer to What is PHP's MySQL Native Driver? for a brief overview of the advantages of MySQL Native Driver.

The /path/to/mysql_config represents the location of the mysql_config program that comes with MySQL Server.

mysqli compile time support matrix
PHP Versiune | Valoare implicita | Op?iuni de configurare pentru: mysqlnd | Op?iuni de configurare pentru: libmysqlclient | Jurnal al modificarilor
5.4.x and above | mysqlnd | --with-mysqli | --with-mysqli=/path/to/mysql_config | mysqlnd is the default
5.3.x | libmysqlclient | --with-mysqli=mysqlnd | --with-mysqli=/path/to/mysql_config | mysqlnd is supported
5.0.x, 5.1.x, 5.2.x | libmysqlclient | Nu este disponibil | --with-mysqli=/path/to/mysql_config | mysqlnd is not supported

Note that it is possible to freely mix MySQL extensions and client libraries. For example, it is possible to enable the MySQL extension to use the MySQL Client Library (libmysqlclient), while configuring the mysqli extension to use the MySQL Native Driver. However, all permutations of extension and client library are possible.

Installation on Windows Systems

On Windows, PHP is most commonly installed using the binary installer.

PHP 5.3.0 and newer

On Windows, for PHP versions 5.3 and newer, the mysqli extension is enabled and uses the MySQL Native Driver by default. This means you don't need to worry about configuring access to libmysql.dll.

PHP 5.0, 5.1, 5.2

On these old unsupported PHP versions (PHP 5.2 reached EOL on '6 Jan 2011'), additional configuration procedures are required to enable mysqli and specify the client library you want it to use.

The mysqli extension is not enabled by default, so the php_mysqli.dll DLL must be enabled inside of php.ini. In order to do this you need to find the php.ini file (typically located in c:\php), and make sure you remove the comment (semi-colon) from the start of the line extension=php_mysqli.dll, in the section marked [PHP_MYSQLI].

Also, if you want to use the MySQL Client Library with mysqli, you need to make sure PHP can access the client library file. The MySQL Client Library is included as a file named libmysql.dll in the Windows PHP distribution. This file needs to be available in the Windows system's PATH environment variable, so that it can be successfully loaded. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Copying libmysql.dll to the Windows system directory (typically c:\Windows\system) also works, as the system directory is by default in the system's PATH. However, this practice is strongly discouraged.

As with enabling any PHP extension (such as php_mysqli.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.

Nota:

If when starting the web server an error similar to the following occurs: "Unable to load dynamic library './php_mysqli.dll'", this is because php_mysqli.dll and/or libmysql.dll cannot be found by the system.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

MySQLi Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
mysqli.allow_local_infile | "1" | PHP_INI_SYSTEM | Available since PHP 5.2.4.
mysqli.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqli.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqli.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
mysqli.default_port | "3306" | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_socket | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_host | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_user | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_pw | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.reconnect | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.5.
mysqli.rollback_on_cached_plink | TRUE | PHP_INI_SYSTEM | Available since PHP 5.6.0.
mysqli.cache_size | "2000" | PHP_INI_SYSTEM | Available since PHP 5.3.0.

For further details and definitions of the preceding PHP_INI_* constants, see the chapter on configuration changes.

Iata o explica?ie pe scurt a directivelor de configurare.

mysqli.allow_local_infile integer

Allow accessing, from PHP's perspective, local files with LOAD DATA statements

mysqli.allow_persistent integer

Enable the ability to create persistent connections using mysqli_connect().

mysqli.max_persistent integer

Maximum of persistent connections that can be made. Set to 0 for unlimited.

mysqli.max_links integer

The maximum number of MySQL connections per process.

mysqli.default_port integer

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.

mysqli.default_socket string

The default socket name to use when connecting to a local database server if no other socket name is specified.

mysqli.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 safe mode.

mysqli.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 safe mode.

mysqli.default_pw string

The default password to use when connecting to the database server if no other password is specified. Doesn't apply in safe mode.

mysqli.reconnect integer

Automatically reconnect if the connection was lost.

Nota: This php.ini setting is ignored by the mysqlnd driver.

mysqli.rollback_on_cached_plink bool

Used for rollbacking connections put back into the persistent connection pool.

mysqli.cache_size integer

Disponibil numai cu mysqlnd.

Users cannot set MYSQL_OPT_READ_TIMEOUT through an API call or runtime configuration setting. Note that if it were possible there would be differences between how libmysqlclient and streams would interpret the value of MYSQL_OPT_READ_TIMEOUT.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
The mysqli Extension and Persistent Connections
Instalarea / configurarea


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.

Nota:

The mysqli extension supports persistent connections when using either MySQL Native Driver or MySQL Client Library.

Tipurile resurselor
Constante predefinite
MySQLi


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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 CHAR or BINARY

MYSQLI_TYPE_CHAR

Field is defined as TINYINT. For CHAR, see MYSQLI_TYPE_STRING

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_BINARY_FLAG

Field is defined as BINARY. 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.

MYSQLI_TRANS_COR_AND_CHAIN

Appends "AND CHAIN" to mysqli_commit() or mysqli_rollback().

MYSQLI_TRANS_COR_AND_NO_CHAIN

Appends "AND NO CHAIN" to mysqli_commit() or mysqli_rollback().

MYSQLI_TRANS_COR_RELEASE

Appends "RELEASE" to mysqli_commit() or mysqli_rollback().

MYSQLI_TRANS_COR_NO_RELEASE

Appends "NO RELEASE" to mysqli_commit() or mysqli_rollback().

MYSQLI_TRANS_START_READ_ONLY

Start the transaction as "START TRANSACTION READ ONLY" with mysqli_begin_transaction().

MYSQLI_TRANS_START_READ_WRITE

Start the transaction as "START TRANSACTION READ WRITE" with mysqli_begin_transaction().

MYSQLI_TRANS_START_CONSISTENT_SNAPSHOT

Start the transaction as "START TRANSACTION WITH CONSISTENT SNAPSHOT" with mysqli_begin_transaction().

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 libmysqlclient 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, libmysqlclient 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.

Constante predefinite
The MySQLi Extension Function Summary
MySQLi


The MySQLi Extension Function Summary

Summary of mysqli methods
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-committing 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. Disponibil numai cu 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. Disponibil numai cu mysqlnd.
mysqli::get_cache_stats() | mysqli_get_cache_stats() | N/A | Returns client Zval cache statistics. Disponibil numai cu mysqlnd.
mysqli::get_server_info() | mysqli_get_server_info() | N/A | Returns a string representing the version of the MySQL server that the MySQLi extension is connected to
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
Summary of mysqli_stmt methods
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. Disponibil numai cu mysqlnd.
mysqli_stmt::get_warnings() | mysqli_stmt_get_warnings() | N/A | NOT DOCUMENTED
$mysqli_stmt::more_results() | mysqli_stmt_more_results() | N/A | Checks if there are more query results from a multiple query
$mysqli_stmt::next_result() | mysqli_stmt_next_result() | N/A | Reads the next result from a multiple query
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
Summary of mysqli_result methods
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 arbitrary 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. Disponibil numai cu 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
Summary of mysqli_driver methods
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

Nota:

Alias functions are provided for backward compatibility purposes only. Do not use them in new projects.

Notes
Exemple
MySQLi


Exemple

Cuprins

  • MySQLi extension basic examples
The MySQLi Extension Function Summary
MySQLi extension basic examples
MySQLi


MySQLi extension basic examples

This example shows how to connect, execute a query, use basic error handling, print resulting rows, and disconnect from a MySQL database.

This example uses the freely available Sakila database that can be downloaded from » dev.mysql.com, as described here. To get this example to work, (a) install sakila and (b) modify the connection variables (host, your_user, your_pass).

Example #1 MySQLi extension overview example

<?php
// Let's pass in a $_GET variable to our example, in this case
// it's aid for actor_id in our Sakila database. Let's make it
// default to 1, and cast it to an integer as to avoid SQL injection
// and/or related security problems. Handling all of this goes beyond
// the scope of this simple example. Example:
//   http://example.org/script.php?aid=42
if (isset($_GET['aid']) && is_numeric($_GET['aid'])) {
    $aid = (int) $_GET['aid'];
} else {
    $aid = 1;
}

// Connecting to and selecting a MySQL database named sakila
// Hostname: 127.0.0.1, username: your_user, password: your_pass, db: sakila
$mysqli = new mysqli('127.0.0.1', 'your_user', 'your_pass', 'sakila');

// Oh no! A connect_errno exists so the connection attempt failed!
if ($mysqli->connect_errno) {
    // The connection failed. What do you want to do?
    // You could contact yourself (email?), log the error, show a nice page, etc.
    // You do not want to reveal sensitive information

    // Let's try this:
    echo "Sorry, this website is experiencing problems.";

    // Something you should not do on a public site, but this example will show you
    // anyways, is print out MySQL error related information -- you might log this
    echo "Error: Failed to make a MySQL connection, here is why: \n";
    echo "Errno: " . $mysqli->connect_errno . "\n";
    echo "Error: " . $mysqli->connect_error . "\n";

    // You might want to show them something nice, but we will simply exit
    exit;
}

// Perform an SQL query
$sql = "SELECT actor_id, first_name, last_name FROM actor WHERE actor_id = $aid";
if (!$result = $mysqli->query($sql)) {
    // Oh no! The query failed.
    echo "Sorry, the website is experiencing problems.";

    // Again, do not do this on a public site, but we'll show you how
    // to get the error information
    echo "Error: Our query failed to execute and here is why: \n";
    echo "Query: " . $sql . "\n";
    echo "Errno: " . $mysqli->errno . "\n";
    echo "Error: " . $mysqli->error . "\n";
    exit;
}

// Phew, we made it. We know our MySQL connection and query
// succeeded, but do we have a result?
if ($result->num_rows === 0) {
    // Oh, no rows! Sometimes that's expected and okay, sometimes
    // it is not. You decide. In this case, maybe actor_id was too
    // large?
    echo "We could not find a match for ID $aid, sorry about that. Please try again.";
    exit;
}

// Now, we know only one result will exist in this example so let's
// fetch it into an associated array where the array's keys are the
// table's column names
$actor = $result->fetch_assoc();
echo "Sometimes I see " . $actor['first_name'] . " " . $actor['last_name'] . " on TV.";

// Now, let's fetch five random actors and output their names to a list.
// We'll add less error handling here as you can do that on your own now
$sql = "SELECT actor_id, first_name, last_name FROM actor ORDER BY rand() LIMIT 5";
if (!$result = $mysqli->query($sql)) {
    echo "Sorry, the website is experiencing problems.";
    exit;
}

// Print our 5 random actors in a list, and link to each actor
echo "<ul>\n";
while ($actor = $result->fetch_assoc()) {
    echo "<li><a href='" . $_SERVER['SCRIPT_FILENAME'] . "?aid=" . $actor['actor_id'] . "'>\n";
    echo $actor['first_name'] . ' ' . $actor['last_name'];
    echo "</a></li>\n";
}
echo "</ul>\n";

// The script will automatically free the result and close the MySQL
// connection when it exits, but let's just do it anyways
$result->free();
$mysqli->close();
?>
Exemple
mysqli
Exemple


The mysqli class

(PHP 5, PHP 7)

Introducere

Represents a connection between PHP and a MySQL database.

Sinopsisul clasei

mysqli {
/* Proprieta?i */
int $affected_rows;
string $client_info;
int $client_version;
int $connect_errno;
string $connect_error;
int $errno;
array $error_list;
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;
/* Metode */
 __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")
]]]]]] )
bool autocommit ( bool $mode )
bool change_user ( string $user , string $password , string $database )
string character_set_name ( void )
bool close ( void )
bool commit ([ int $flags [, string $name ]] )
bool debug ( string $message )
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 static 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 ([ int $flags [, string $name ]] )
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 , callable $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 ([ int $option ] )
mysqli_result use_result ( void )
}

Cuprins

  • mysqli::$affected_rows — Gets the number of affected rows in a previous MySQL operation
  • mysqli::autocommit — Turns on or off auto-committing database modifications
  • mysqli::begin_transaction — Starts a transaction
  • 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 — Get MySQL client info
  • mysqli::$client_version — Returns the MySQL client version as a string
  • 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::dump_debug_info — Dump debugging information into the log
  • mysqli::$errno — Returns the error code for the most recent function call
  • mysqli::$error_list — Returns a list of errors from the last command executed
  • 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 — Get MySQL client info
  • mysqli_get_client_stats — Returns client per-process statistics
  • mysqli_get_client_version — Returns the MySQL client version as an integer
  • 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 latest 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::release_savepoint — Removes the named savepoint from the set of savepoints of the current transaction
  • mysqli::rollback — Rolls back current transaction
  • mysqli::rpl_query_type — Returns RPL query type
  • mysqli::savepoint — Set a named transaction savepoint
  • 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 extension basic examples
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, PHP 7)

mysqli::$affected_rows -- mysqli_affected_rows — Gets the number of affected rows in a previous MySQL operation

Descrierea

Stil obiect-orientat

int $mysqli->affected_rows;

Stil procedural

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().

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were 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.

Nota:

If the number of affected rows is greater than the maximum integer value( PHP_INT_MAX ), the number of affected rows will be returned as a string.

Exemple

Example #1 $mysqli->affected_rows example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Affected rows (INSERT): 984
Affected rows (UPDATE): 168
Affected rows (DELETE): 815
Affected rows (SELECT): 169

A se vedea ?i

  • 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-committing database modifications

mysqli::$affected_rows
mysqli::begin_transaction
mysqli
PHP Manual

mysqli::autocommit

mysqli_autocommit

(PHP 5, PHP 7)

mysqli::autocommit -- mysqli_autocommit — Turns on or off auto-committing database modifications

Descrierea

Stil obiect-orientat

bool mysqli::autocommit ( bool $mode )

Stil procedural

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

mode

Whether to turn on auto-commit or not.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

This function doesn't work with non transactional table types (like MyISAM or ISAM).

Exemple

Example #1 mysqli::autocommit() example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Autocommit is 1

A se vedea ?i

  • mysqli_begin_transaction() - Starts a transaction
  • mysqli_commit() - Commits the current transaction
  • mysqli_rollback() - Rolls back current transaction

mysqli::$affected_rows
mysqli::begin_transaction
mysqli


Starts a transaction

mysqli::autocommit
mysqli::change_user
mysqli
PHP Manual

mysqli::begin_transaction

mysqli_begin_transaction

(PHP 5 >= 5.5.0, PHP 7)

mysqli::begin_transaction -- mysqli_begin_transaction — Starts a transaction

Descrierea

Stil obiect-orientat (method):

public bool mysqli::begin_transaction ([ int $flags [, string $name ]] )

Stil procedural:

bool mysqli_begin_transaction ( mysqli $link [, int $flags [, string $name ]] )

Begins a transaction. Requires MySQL 5.6 and above, and the InnoDB engine (it is enabled by default). For additional details about how MySQL transactions work, see » http://dev.mysql.com/doc/mysql/en/commit.html.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

flags

Valid flags are:

  • MYSQLI_TRANS_START_READ_ONLY: Start the transaction as "START TRANSACTION READ ONLY".

  • MYSQLI_TRANS_START_READ_WRITE: Start the transaction as "START TRANSACTION READ WRITE".

  • MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT: Start the transaction as "START TRANSACTION WITH CONSISTENT SNAPSHOT".

name

Savepoint name for the transaction.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 $mysqli->begin_transaction() example

Stil obiect-orientat

<?php
$mysqli = new mysqli("127.0.0.1", "my_user", "my_password", "sakila");

if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$mysqli->begin_transaction(MYSQLI_TRANS_START_READ_ONLY);

$mysqli->query("SELECT first_name, last_name FROM actor");
$mysqli->commit();

$mysqli->close();
?>

Stil procedural

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "sakila");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_begin_transaction($link, MYSQLI_TRANS_START_READ_ONLY);

mysqli_query($link, "SELECT first_name, last_name FROM actor LIMIT 1");
mysqli_commit($link);

mysqli_close($link);
?>

A se vedea ?i

  • mysqli_autocommit() - Turns on or off auto-committing database modifications
  • mysqli_commit() - Commits the current transaction
  • mysqli_rollback() - Rolls back current transaction

mysqli::autocommit
mysqli::change_user
mysqli


Changes the user of the specified database connection

mysqli::begin_transaction
mysqli::character_set_name
mysqli
PHP Manual

mysqli::change_user

mysqli_change_user

(PHP 5, PHP 7)

mysqli::change_user -- mysqli_change_user — Changes the user of the specified database connection

Descrierea

Stil obiect-orientat

bool mysqli::change_user ( string $user , string $password , string $database )

Stil procedural

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

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.

Exemple

Example #1 mysqli::change_user() example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Default database: world
Value of variable a is NULL

A se vedea ?i

  • mysqli_connect() - Pseudonim pentru mysqli::__construct
  • mysqli_select_db() - Selects the default database for database queries

mysqli::begin_transaction
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, PHP 7)

mysqli::character_set_name -- mysqli_character_set_name — Returns the default character set for the database connection

Descrierea

Stil obiect-orientat

string mysqli::character_set_name ( void )

Stil procedural

string mysqli_character_set_name ( mysqli $link )

Returns the current character set for the database connection.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

The default character set for the current connection

Exemple

Example #1 mysqli::character_set_name() example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Current character set is latin1_swedish_ci

A se vedea ?i

  • mysqli_set_charset() - Sets the default client character set
  • 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


Get MySQL client info

mysqli::character_set_name
mysqli::$client_version
mysqli
PHP Manual

mysqli::$client_info

mysqli_get_client_info

(PHP 5, PHP 7)

mysqli::$client_info -- mysqli_get_client_info — Get MySQL client info

Descrierea

Stil obiect-orientat

string $mysqli->client_info;

Stil procedural

string mysqli_get_client_info ( mysqli $link )

Returns a string that represents the MySQL client library version.

Valorile întoarse

A string that represents the MySQL client library version

Exemple

Example #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());
?>

A se vedea ?i

  • mysqli_get_client_version() - Returns the MySQL client version as an integer
  • 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


Returns the MySQL client version as a string

mysqli::$client_info
mysqli::close
mysqli
PHP Manual

mysqli::$client_version

mysqli_get_client_version

(PHP 5, PHP 7)

mysqli::$client_version -- mysqli_get_client_version — Returns the MySQL client version as a string

Descrierea

Stil obiect-orientat

int $mysqli->client_version;

Stil procedural

int mysqli_get_client_version ( mysqli $link )

Returns client version number as an integer.

Valorile întoarse

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.

Exemple

Example #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());
?>

A se vedea ?i

  • mysqli_get_client_info() - 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::$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, PHP 7)

mysqli::close -- mysqli_close — Closes a previously opened database connection

Descrierea

Stil obiect-orientat

bool mysqli::close ( void )

Stil procedural

bool mysqli_close ( mysqli $link )

Closes a previously opened database connection.

Conexiunile MySQL non-persistente deschise ?i seturile de rezultate sunt automat distruse atunci când un script PHP î?i încheie execu?ia. Deci închiderea în mod explicit a conexiunilor deschise ?i eliberarea seturilor de rezultate sunt op?ionale, însa sunt recomandata. Aceasta va întoarce imediat resursele catre PHP ?i MySQL, ceea ce poate îmbunata?i performa?a. Pentru informa?ii suplimentare accesa?i eliberarea resurselor

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

See mysqli_connect().

Note

Nota:

mysqli_close() will not close persistent connections. For additional details, see the manual page on persistent connections.

A se vedea ?i

  • mysqli::__construct() - Open a new connection to the MySQL server
  • 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_free_result() - Frees the memory associated with a result

mysqli::$client_version
mysqli::commit
mysqli


Commits the current transaction

mysqli::close
mysqli::$connect_errno
mysqli
PHP Manual

mysqli::commit

mysqli_commit

(PHP 5, PHP 7)

mysqli::commit -- mysqli_commit — Commits the current transaction

Descrierea

Stil obiect-orientat

bool mysqli::commit ([ int $flags [, string $name ]] )

Stil procedural

bool mysqli_commit ( mysqli $link [, int $flags [, string $name ]] )

Commits the current transaction for the database connection.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

flags

A bitmask of MYSQLI_TRANS_COR_* constants.

name

If provided then COMMIT/*name*/ is executed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | Added flags and name parameters.

Exemple

Example #1 mysqli::commit() example

Stil obiect-orientat

<?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 */
if (!$mysqli->commit()) {
    print("Transaction commit failed\n");
    exit();
}

/* drop table */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

Stil procedural

<?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 */
if (!mysqli_commit($link)) {
    print("Transaction commit failed\n");
    exit();
}

/* close connection */
mysqli_close($link);
?>

A se vedea ?i

  • mysqli_autocommit() - Turns on or off auto-committing database modifications
  • mysqli_begin_transaction() - Starts a transaction
  • mysqli_rollback() - Rolls back current transaction
  • mysqli_savepoint() - Set a named transaction savepoint

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, PHP 7)

mysqli::$connect_errno -- mysqli_connect_errno — Returns the error code from last connect call

Descrierea

Stil obiect-orientat

int $mysqli->connect_errno;

Stil procedural

int mysqli_connect_errno ( void )

Returns the last error code number from the last call to mysqli_connect().

Nota:

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.

Valorile întoarse

An error code value for the last call to mysqli_connect(), if it failed. zero means no error occurred.

Exemple

Example #1 $mysqli->connect_errno example

Stil obiect-orientat

<?php
$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

if ($mysqli->connect_errno) {
    die('Connect Error: ' . $mysqli->connect_errno);
}
?>

Stil procedural

<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error: ' . mysqli_connect_errno());
}
?>

Exemplele de mai sus vor afi?a:

Connect Error: 1045

A se vedea ?i

  • mysqli_connect() - Pseudonim pentru 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, PHP 7)

mysqli::$connect_error -- mysqli_connect_error — Returns a string description of the last connect error

Descrierea

Stil obiect-orientat

string $mysqli->connect_error;

Stil procedural

string mysqli_connect_error ( void )

Returns the last error message string from the last call to mysqli_connect().

Valorile întoarse

A string that describes the error. NULL is returned if no error occurred.

Exemple

Example #1 $mysqli->connect_error example

Stil obiect-orientat

<?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);
}
?>

Stil procedural

<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error: ' . mysqli_connect_error());
}
?>

Exemplele de mai sus vor afi?a:

Connect Error: Access denied for user 'fake_user'@'localhost' (using password: YES)

Note

Avertizare

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.

A se vedea ?i

  • mysqli_connect() - Pseudonim pentru 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, PHP 7)

mysqli::__construct -- mysqli_connect — Open a new connection to the MySQL server

Descrierea

Stil obiect-orientat

 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")
]]]]]] )

Stil procedural

 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.

Parametri

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.

Nota:

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.

Valorile întoarse

Returns an object which represents the connection to a MySQL Server.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Added the ability of persistent connections.

Exemple

Example #1 mysqli::__construct() example

Stil obiect-orientat

<?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();
?>

Stil obiect-orientat 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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Success... MySQL host info: localhost via TCP/IP

Note

Nota:

MySQLnd întotdeauna preia setul de caractere implicit de pe server. Acest set de caractere este transmis în momentul stabilirii parametrilor/autentificarii la conectare ?i este utilizat ulterior de mysqlnd.

Libmysqlclient utilizeaza setul de caractere implicit stabilit în fi?ierul my.cnf sau printr-un apel explicit al func?iei mysqli_options() înainte de apelul mysqli_real_connect(), dar dupa mysqli_init().

Nota:

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.

Nota:

If it is necessary to set options, such as the connection timeout, mysqli_real_connect() must be used instead.

Nota:

Calling the constructor with no parameters is the same as calling mysqli_init().

Nota:

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.

A se vedea ?i

  • 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::dump_debug_info
mysqli
PHP Manual

mysqli::debug

mysqli_debug

(PHP 5, PHP 7)

mysqli::debug -- mysqli_debug — Performs debugging operations

Descrierea

Stil obiect-orientat

bool mysqli::debug ( string $message )

Stil procedural

bool mysqli_debug ( string $message )

Performs debugging operations using the Fred Fish debugging library.

Parametri

message

A string representing the debugging operation to perform

Valorile întoarse

Returns TRUE.

Note

Nota:

To use the mysqli_debug() function you must compile the MySQL client library to support debugging.

Exemple

Example #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");

?>

A se vedea ?i

  • mysqli_dump_debug_info() - Dump debugging information into the log
  • mysqli_report() - Pseudonim pentru mysqli_driver->report_mode

mysqli::__construct
mysqli::dump_debug_info
mysqli


Dump debugging information into the log

mysqli::debug
mysqli::$errno
mysqli
PHP Manual

mysqli::dump_debug_info

mysqli_dump_debug_info

(PHP 5, PHP 7)

mysqli::dump_debug_info -- mysqli_dump_debug_info — Dump debugging information into the log

Descrierea

Stil obiect-orientat

bool mysqli::dump_debug_info ( void )

Stil procedural

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • mysqli_debug() - Performs debugging operations

mysqli::debug
mysqli::$errno
mysqli


Returns the error code for the most recent function call

mysqli::dump_debug_info
mysqli::$error_list
mysqli
PHP Manual

mysqli::$errno

mysqli_errno

(PHP 5, PHP 7)

mysqli::$errno -- mysqli_errno — Returns the error code for the most recent function call

Descrierea

Stil obiect-orientat

int $mysqli->errno;

Stil procedural

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

An error code value for the last call, if it failed. zero means no error occurred.

Exemple

Example #1 $mysqli->errno example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Errorcode: 1193

A se vedea ?i

  • 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_list
mysqli


Returns a list of errors from the last command executed

mysqli::$errno
mysqli::$error
mysqli
PHP Manual

mysqli::$error_list

mysqli_error_list

(PHP 5 >= 5.4.0, PHP 7)

mysqli::$error_list -- mysqli_error_list — Returns a list of errors from the last command executed

Descrierea

Stil obiect-orientat

array $mysqli->error_list;

Stil procedural

array mysqli_error_list ( mysqli $link )

Returns a array of errors for the most recent MySQLi function call that can succeed or fail.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

A list of errors, each as an associative array containing the errno, error, and sqlstate.

Exemple

Example #1 $mysqli->error_list example

Stil obiect-orientat

<?php
$mysqli = new mysqli("localhost", "nobody", "");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$mysqli->query("SET a=1")) {
    print_r($mysqli->error_list);
}

/* close connection */
$mysqli->close();
?>

Stil procedural

<?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")) {
    print_r(mysqli_error_list($link));
}

/* close connection */
mysqli_close($link);
?>

Exemplele de mai sus vor afi?a:

Array
(
    [0] => Array
        (
            [errno] => 1193
            [sqlstate] => HY000
            [error] => Unknown system variable 'a'
        )

)

A se vedea ?i

  • 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::$errno
mysqli::$error
mysqli


Returns a string description of the last error

mysqli::$error_list
mysqli::$field_count
mysqli
PHP Manual

mysqli::$error

mysqli_error

(PHP 5, PHP 7)

mysqli::$error -- mysqli_error — Returns a string description of the last error

Descrierea

Stil obiect-orientat

string $mysqli->error;

Stil procedural

string mysqli_error ( mysqli $link )

Returns the last error message for the most recent MySQLi function call that can succeed or fail.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

A string that describes the error. An empty string if no error occurred.

Exemple

Example #1 $mysqli->error example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Errormessage: Unknown system variable 'a'

A se vedea ?i

  • 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::$error_list
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, PHP 7)

mysqli::$field_count -- mysqli_field_count — Returns the number of columns for the most recent query

Descrierea

Stil obiect-orientat

int $mysqli->field_count;

Stil procedural

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

An integer representing the number of fields in a result set.

Exemple

Example #1 $mysqli->field_count example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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, PHP 7)

mysqli::get_charset -- mysqli_get_charset — Returns a character set object

Descrierea

Stil obiect-orientat

object mysqli::get_charset ( void )

Stil procedural

object mysqli_get_charset ( mysqli $link )

Returns a character set object providing several properties of the current active character set.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

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 (?)

Exemple

Example #1 mysqli::get_charset() example

Stil obiect-orientat

<?php
  $db = mysqli_init();
  $db->real_connect("localhost","root","","test");
  var_dump($db->get_charset());
?>

Stil procedural

<?php
  $db = mysqli_init();
  mysqli_real_connect($db, "localhost","root","","test");
  var_dump(mysqli_get_charset($db));
?>

Exemplele de mai sus vor afi?a:

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)
}

A se vedea ?i

  • 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


Get MySQL client info

mysqli::get_charset
mysqli_get_client_stats
mysqli
PHP Manual

mysqli::get_client_info

mysqli_get_client_info

(PHP 5, PHP 7)

mysqli::get_client_info -- mysqli_get_client_info — Get MySQL client info

Descrierea

Stil obiect-orientat

string mysqli::get_client_info ( void )

Stil procedural

string mysqli_get_client_info ( mysqli $link )

Returns a string that represents the MySQL client library version.

Valorile întoarse

A string that represents the MySQL client library version

Exemple

Example #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());
?>

A se vedea ?i

  • mysqli_get_client_version() - Returns the MySQL client version as an integer
  • 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_get_client_version
mysqli
PHP Manual

mysqli_get_client_stats

(PHP 5 >= 5.3.0, PHP 7)

mysqli_get_client_stats — Returns client per-process statistics

Descrierea

array mysqli_get_client_stats ( void )

Returns client per-process statistics. Disponibil numai cu mysqlnd.

Parametri

Valorile întoarse

Returns an array with client stats if success, FALSE otherwise.

Exemple

Example #1 A mysqli_get_client_stats() example

<?php
$link = mysqli_connect();
print_r(mysqli_get_client_stats());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • Stats description

mysqli::get_client_info
mysqli_get_client_version
mysqli


Returns the MySQL client version as an integer

mysqli_get_client_stats
mysqli::get_connection_stats
mysqli
PHP Manual

mysqli_get_client_version

mysqli::$client_version

(PHP 5, PHP 7)

mysqli_get_client_version -- mysqli::$client_version — Returns the MySQL client version as an integer

Descrierea

Stil obiect-orientat

int $mysqli->client_version;

Stil procedural

int mysqli_get_client_version ( mysqli $link )

Returns client version number as an integer.

Valorile întoarse

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.

Exemple

Example #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());
?>

A se vedea ?i

  • mysqli_get_client_info() - 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_client_stats
mysqli::get_connection_stats
mysqli


Returns statistics about the client connection

mysqli_get_client_version
mysqli::$host_info
mysqli
PHP Manual

mysqli::get_connection_stats

mysqli_get_connection_stats

(PHP 5 >= 5.3.0, PHP 7)

mysqli::get_connection_stats -- mysqli_get_connection_stats — Returns statistics about the client connection

Descrierea

Stil obiect-orientat

bool mysqli::get_connection_stats ( void )

Stil procedural

array mysqli_get_connection_stats ( mysqli $link )

Returns statistics about the client connection. Disponibil numai cu mysqlnd.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Returns an array with connection stats if success, FALSE otherwise.

Exemple

Example #1 A mysqli_get_connection_stats() example

<?php
$link = mysqli_connect();
print_r(mysqli_get_connection_stats($link));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • Stats description

mysqli_get_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, PHP 7)

mysqli::$host_info -- mysqli_get_host_info — Returns a string representing the type of connection used

Descrierea

Stil obiect-orientat

string $mysqli->host_info;

Stil procedural

string mysqli_get_host_info ( mysqli $link )

Returns a string describing the connection represented by the link parameter (including the server host name).

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

A character string representing the server hostname and the connection type.

Exemple

Example #1 $mysqli->host_info example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Host info: Localhost via UNIX socket

A se vedea ?i

  • 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, PHP 7)

mysqli::$protocol_version -- mysqli_get_proto_info — Returns the version of the MySQL protocol used

Descrierea

Stil obiect-orientat

string $mysqli->protocol_version;

Stil procedural

int mysqli_get_proto_info ( mysqli $link )

Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Returns an integer representing the protocol version.

Exemple

Example #1 $mysqli->protocol_version example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Protocol version: 10

A se vedea ?i

  • 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, PHP 7)

mysqli::$server_info -- mysqli_get_server_info — Returns the version of the MySQL server

Descrierea

Stil obiect-orientat

string $mysqli->server_info;

Stil procedural

string mysqli_get_server_info ( mysqli $link )

Returns a string representing the version of the MySQL server that the MySQLi extension is connected to.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

A character string representing the server version.

Exemple

Example #1 $mysqli->server_info example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Server version: 4.1.2-alpha-debug

A se vedea ?i

  • mysqli_get_client_info() - Get MySQL client info
  • mysqli_get_client_version() - Returns the MySQL client version as an integer
  • 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, PHP 7)

mysqli::$server_version -- mysqli_get_server_version — Returns the version of the MySQL server as an integer

Descrierea

Stil obiect-orientat

int $mysqli->server_version;

Stil procedural

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

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).

Exemple

Example #1 $mysqli->server_version example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Server version: 40102

A se vedea ?i

  • mysqli_get_client_info() - Get MySQL client info
  • mysqli_get_client_version() - Returns the MySQL client version as an integer
  • 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, PHP 7)

mysqli::get_warnings -- mysqli_get_warnings — Get result of SHOW WARNINGS

Descrierea

Stil obiect-orientat

mysqli_warning mysqli::get_warnings ( void )

Stil procedural

mysqli_warning mysqli_get_warnings ( mysqli $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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, PHP 7)

mysqli::$info -- mysqli_info — Retrieves information about the most recently executed query

Descrierea

Stil obiect-orientat

string $mysqli->info;

Stil procedural

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

Nota:

Queries which do not fall into one of the preceding formats are not supported. In these situations, mysqli_info() will return an empty string.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

A character string representing additional information about the most recently executed query.

Exemple

Example #1 $mysqli->info example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Records: 150  Duplicates: 0  Warnings: 0

A se vedea ?i

  • 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, PHP 7)

mysqli::init -- mysqli_init — Initializes MySQLi and returns a resource for use with mysqli_real_connect()

Descrierea

Stil obiect-orientat

mysqli mysqli::init ( void )

Stil procedural

mysqli mysqli_init ( void )

Allocates or initializes a MYSQL object suitable for mysqli_options() and mysqli_real_connect().

Nota:

Any subsequent calls to any mysqli function (except mysqli_options()) will fail until mysqli_real_connect() was called.

Valorile întoarse

Returns an object.

Exemple

See mysqli_real_connect().

A se vedea ?i

  • mysqli_options() - Set options
  • mysqli_close() - Closes a previously opened database connection
  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_connect() - Pseudonim pentru mysqli::__construct

mysqli::$info
mysqli::$insert_id
mysqli


Returns the auto generated id used in the latest query

mysqli::init
mysqli::kill
mysqli
PHP Manual

mysqli::$insert_id

mysqli_insert_id

(PHP 5, PHP 7)

mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the latest query

Descrierea

Stil obiect-orientat

mixed $mysqli->insert_id;

Stil procedural

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.

Nota:

Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id() function.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

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.

Nota:

If the number is greater than maximal int value, mysqli_insert_id() will return a string.

Exemple

Example #1 $mysqli->insert_id example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

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, PHP 7)

mysqli::kill -- mysqli_kill — Asks the server to kill a MySQL thread

Descrierea

Stil obiect-orientat

bool mysqli::kill ( int $processid )

Stil procedural

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 mysqli::kill() example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Error: MySQL server has gone away

A se vedea ?i

  • 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, PHP 7)

mysqli::more_results -- mysqli_more_results — Check if there are any more query results from a multi query

Descrierea

Stil obiect-orientat

bool mysqli::more_results ( void )

Stil procedural

bool mysqli_more_results ( mysqli $link )

Indicates if one or more result sets are available from a previous call to mysqli_multi_query().

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Returns TRUE if one or more result sets are available from a previous call to mysqli_multi_query(), otherwise FALSE.

Exemple

See mysqli_multi_query().

A se vedea ?i

  • 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, PHP 7)

mysqli::multi_query -- mysqli_multi_query — Performs a query on the database

Descrierea

Stil obiect-orientat

bool mysqli::multi_query ( string $query )

Stil procedural

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().

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

query

The query, as a string.

Data inside the query should be properly escaped.

Valorile întoarse

Returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.

Exemple

Example #1 mysqli::multi_query() example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a ceva similar cu:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

A se vedea ?i

  • mysqli_query() - Performs a query on the database
  • 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, PHP 7)

mysqli::next_result -- mysqli_next_result — Prepare next result from multi_query

Descrierea

Stil obiect-orientat

bool mysqli::next_result ( void )

Stil procedural

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().

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

See mysqli_multi_query().

A se vedea ?i

  • 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, PHP 7)

mysqli::options -- mysqli_options — Set options

Descrierea

Stil obiect-orientat

bool mysqli::options ( int $option , mixed $value )

Stil procedural

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().

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau 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.
MYSQLI_SERVER_PUBLIC_KEY | RSA public key file used with the SHA-256 based authentication.
MYSQLI_OPT_NET_CMD_BUFFER_SIZE | The size of the internal command/network buffer. Only valid for mysqlnd.
MYSQLI_OPT_NET_READ_BUFFER_SIZE | Maximum read chunk size in bytes when reading the body of a MySQL command packet. Only valid for mysqlnd.
MYSQLI_OPT_INT_AND_FLOAT_NATIVE | Convert integer and float columns back to PHP numbers. Only valid for mysqlnd.
MYSQLI_OPT_SSL_VERIFY_SERVER_CERT

value

The value for the option.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | The MYSQLI_SERVER_PUBLIC_KEY and MYSQLI_SERVER_PUBLIC_KEY options were added.
5.3.0 | The MYSQLI_OPT_INT_AND_FLOAT_NATIVE, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, MYSQLI_OPT_NET_READ_BUFFER_SIZE, and MYSQLI_OPT_SSL_VERIFY_SERVER_CERT options were added.

Exemple

See mysqli_real_connect().

Note

Nota:

MySQLnd întotdeauna preia setul de caractere implicit de pe server. Acest set de caractere este transmis în momentul stabilirii parametrilor/autentificarii la conectare ?i este utilizat ulterior de mysqlnd.

Libmysqlclient utilizeaza setul de caractere implicit stabilit în fi?ierul my.cnf sau printr-un apel explicit al func?iei mysqli_options() înainte de apelul mysqli_real_connect(), dar dupa mysqli_init().

A se vedea ?i

  • 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, PHP 7)

mysqli::ping -- mysqli_ping — Pings a server connection, or tries to reconnect if the connection has gone down

Descrierea

Stil obiect-orientat

bool mysqli::ping ( void )

Stil procedural

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.

Nota: The php.ini setting mysqli.reconnect is ignored by the mysqlnd driver, so automatic reconnection is never 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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 mysqli::ping() example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

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, PHP 7)

mysqli::poll -- mysqli_poll — Poll connections

Descrierea

Stil obiect-orientat

public static int mysqli::poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec ] )

Stil procedural

int mysqli_poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec ] )

Poll connections. Disponibil numai cu mysqlnd. The method can be used as static.

Parametri

read

List of connections to check for outstanding results that can be read.

error

List of connections on which an error occured, for example, query failure or lost connection.

reject

List of connections rejected because no asynchronous query has been run on for which the function could poll results.

sec

Number of seconds to wait, must be non-negative.

usec

Number of microseconds to wait, must be non-negative.

Valorile întoarse

Returns number of ready connections upon success, FALSE otherwise.

Exemple

Example #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());
            if (is_object($result))
                mysqli_free_result($result);
        } else die(sprintf("MySQLi Error: %s", mysqli_error($link)));
        $processed++;
    }
} while ($processed < count($all_links));
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => test
)

A se vedea ?i

  • 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, PHP 7)

mysqli::prepare -- mysqli_prepare — Prepare an SQL statement for execution

Descrierea

Stil obiect-orientat

mysqli_stmt mysqli::prepare ( string $query )

Stil procedural

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

query

The query, as a string.

Nota:

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.

Nota:

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.

Valorile întoarse

mysqli_prepare() returns a statement object or FALSE if an error occurred.

Exemple

Example #1 mysqli::prepare() example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Amersfoort is in district Utrecht

A se vedea ?i

  • 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, PHP 7)

mysqli::query -- mysqli_query — Performs a query on the database

Descrierea

Stil obiect-orientat

mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

Stil procedural

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

Performs a query against the database.

For non-DML queries (not INSERT, UPDATE or DELETE),
this function is similar to calling
mysqli_real_query() followed by either
mysqli_use_result() or
mysqli_store_result().

Nota:

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 (libmysqlclient). 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".

  • libmysqlclient on all platforms returns an error code 2006. This error message means "server has gone away".

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau 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.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Added the ability of async queries.

Exemple

Example #1 mysqli::query() example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Table myCity successfully created.
Select returned 10 rows.
Error: Commands out of sync;  You can't run this command now

A se vedea ?i

  • 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, PHP 7)

mysqli::real_connect -- mysqli_real_connect — Opens a connection to a mysql server

Descrierea

Stil obiect-orientat

bool mysqli::real_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] )

Stil procedural

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau 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.

Nota:

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)
MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT | Like MYSQLI_CLIENT_SSL, but disables validation of the provided SSL certificate. This is only for installations using MySQL Native Driver and MySQL 5.6 or later.

Nota:

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.

Istoricul schimbarilor

Versiune | Descriere
5.6.16 | Added the MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT flag for MySQL Native Driver

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 mysqli::real_connect() example

Stil obiect-orientat

<?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();
?>

Stil obiect-orientat 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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Success... MySQL host info: localhost via TCP/IP

Note

Nota:

MySQLnd întotdeauna preia setul de caractere implicit de pe server. Acest set de caractere este transmis în momentul stabilirii parametrilor/autentificarii la conectare ?i este utilizat ulterior de mysqlnd.

Libmysqlclient utilizeaza setul de caractere implicit stabilit în fi?ierul my.cnf sau printr-un apel explicit al func?iei mysqli_options() înainte de apelul mysqli_real_connect(), dar dupa mysqli_init().

A se vedea ?i

  • mysqli_connect() - Pseudonim pentru 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, PHP 7)

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

Descrierea

Stil obiect-orientat

string mysqli::escape_string ( string $escapestr )
string mysqli::real_escape_string ( string $escapestr )

Stil procedural

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.

Precautie

Security: the default character set

The character set must be set either at the server level, or with the API function mysqli_set_charset() for it to affect mysqli_real_escape_string(). See the concepts section on character sets for more information.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

escapestr

The string to be escaped.

Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

Valorile întoarse

Returns an escaped string.

Exemple

Example #1 mysqli::real_escape_string() example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Error: 42000
1 Row inserted.

Note

Nota:

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().

A se vedea ?i

  • mysqli_set_charset() - Sets the default client character set
  • 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, PHP 7)

mysqli::real_query -- mysqli_real_query — Execute an SQL query

Descrierea

Stil obiect-orientat

bool mysqli::real_query ( string $query )

Stil procedural

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().

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

query

The query, as a string.

Data inside the query should be properly escaped.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

mysqli::reap_async_query -- mysqli_reap_async_query — Get result from async query

Descrierea

Stil obiect-orientat

public mysqli_result mysqli::reap_async_query ( void )

Stil procedural

mysqli_result mysqli_reap_async_query ( mysqli $link )

Get result from async query. Disponibil numai cu mysqlnd.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Returns mysqli_result in success, FALSE otherwise.

A se vedea ?i

  • mysqli_poll() - Poll connections

mysqli::real_query
mysqli::refresh
mysqli


Refreshes

mysqli::reap_async_query
mysqli::release_savepoint
mysqli
PHP Manual

mysqli::refresh

mysqli_refresh

(PHP 5 <= 5.3.0)

mysqli::refresh -- mysqli_refresh — Refreshes

Descrierea

Stil obiect-orientat

public bool mysqli::refresh ( int $options )

Stil procedural

int mysqli_refresh ( resource $link , int $options )

Flushes tables or caches, or resets the replication server information.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau 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.

Valorile întoarse

TRUE if the refresh was a success, otherwise FALSE

A se vedea ?i

  • mysqli_poll() - Poll connections

mysqli::reap_async_query
mysqli::release_savepoint
mysqli


Removes the named savepoint from the set of savepoints of the current transaction

mysqli::refresh
mysqli::rollback
mysqli
PHP Manual

mysqli::release_savepoint

mysqli_release_savepoint

(PHP 5 >= 5.5.0, PHP 7)

mysqli::release_savepoint -- mysqli_release_savepoint — Removes the named savepoint from the set of savepoints of the current transaction

Descrierea

Stil obiect-orientat (method):

public bool mysqli::release_savepoint ( string $name )

Stil procedural:

bool mysqli_release_savepoint ( mysqli $link , string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

name

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • mysqli_rollback() - Rolls back current transaction

mysqli::refresh
mysqli::rollback
mysqli


Rolls back current transaction

mysqli::release_savepoint
mysqli::rpl_query_type
mysqli
PHP Manual

mysqli::rollback

mysqli_rollback

(PHP 5, PHP 7)

mysqli::rollback -- mysqli_rollback — Rolls back current transaction

Descrierea

Stil obiect-orientat

bool mysqli::rollback ([ int $flags [, string $name ]] )

Stil procedural

bool mysqli_rollback ( mysqli $link [, int $flags [, string $name ]] )

Rollbacks the current transaction for the database.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

flags

A bitmask of MYSQLI_TRANS_COR_* constants.

name

If provided then ROLLBACK/*name*/ is executed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | Added flags and name parameters.

Exemple

Example #1 mysqli::rollback() example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

0 rows in table myCity.
50 rows in table myCity (after rollback).

A se vedea ?i

  • mysqli_begin_transaction() - Starts a transaction
  • mysqli_commit() - Commits the current transaction
  • mysqli_autocommit() - Turns on or off auto-committing database modifications
  • mysqli_release_savepoint() - Removes the named savepoint from the set of savepoints of the current transaction

mysqli::release_savepoint
mysqli::rpl_query_type
mysqli


Returns RPL query type

mysqli::rollback
mysqli::savepoint
mysqli
PHP Manual

mysqli::rpl_query_type

mysqli_rpl_query_type

(PHP 5, PHP 7)

mysqli::rpl_query_type -- mysqli_rpl_query_type — Returns RPL query type

Descrierea

Stil obiect-orientat

int mysqli::rpl_query_type ( string $query )

Stil procedural

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.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Avertizare

Aceasta func?ie este ÎNVECHITA ?i este ELIMINATA începând cu PHP 5.3.0.

mysqli::rollback
mysqli::savepoint
mysqli


Set a named transaction savepoint

mysqli::rpl_query_type
mysqli::select_db
mysqli
PHP Manual

mysqli::savepoint

mysqli_savepoint

(PHP 5 >= 5.5.0, PHP 7)

mysqli::savepoint -- mysqli_savepoint — Set a named transaction savepoint

Descrierea

Stil obiect-orientat (method):

public bool mysqli::savepoint ( string $name )

Stil procedural:

bool mysqli_savepoint ( mysqli $link , string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

name

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • mysqli_commit() - Commits the current transaction

mysqli::rpl_query_type
mysqli::select_db
mysqli


Selects the default database for database queries

mysqli::savepoint
mysqli::send_query
mysqli
PHP Manual

mysqli::select_db

mysqli_select_db

(PHP 5, PHP 7)

mysqli::select_db -- mysqli_select_db — Selects the default database for database queries

Descrierea

Stil obiect-orientat

bool mysqli::select_db ( string $dbname )

Stil procedural

bool mysqli_select_db ( mysqli $link , string $dbname )

Selects the default database to be used when performing queries against the database connection.

Nota:

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().

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

dbname

The database name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 mysqli::select_db() example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Default database is test.
Default database is world.

A se vedea ?i

  • mysqli_connect() - Pseudonim pentru mysqli::__construct
  • mysqli_real_connect() - Opens a connection to a mysql server

mysqli::savepoint
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, PHP 7)

mysqli::send_query -- mysqli_send_query — Send the query and return

Descrierea

Stil obiect-orientat

bool mysqli::send_query ( string $query )

Stil procedural

bool mysqli_send_query ( mysqli $link , string $query )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Avertizare

Aceasta func?ie este ÎNVECHITA ?i este ELIMINATA începând cu 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, PHP 7)

mysqli::set_charset -- mysqli_set_charset — Sets the default client character set

Descrierea

Stil obiect-orientat

bool mysqli::set_charset ( string $charset )

Stil procedural

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

charset

The charset to be set as default.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

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).

Nota:

This is the preferred way to change the charset. Using mysqli_query() to set it (such as SET NAMES utf8) is not recommended. See the MySQL character set concepts section for more information.

Exemple

Example #1 mysqli::set_charset() example

Stil obiect-orientat

<?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();
}

printf("Initial character set: %s\n", $mysqli->character_set_name());

/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit();
} else {
    printf("Current character set: %s\n", $mysqli->character_set_name());
}

$mysqli->close();
?>

Stil procedural

<?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();
}

printf("Initial character set: %s\n", mysqli_character_set_name($link));

/* change character set to utf8 */
if (!mysqli_set_charset($link, "utf8")) {
    printf("Error loading character set utf8: %s\n", mysqli_error($link));
    exit();
} else {
    printf("Current character set: %s\n", mysqli_character_set_name($link));
}

mysqli_close($link);
?>

Exemplele de mai sus vor afi?a ceva similar cu:

Initial character set: latin1
Current character set: utf8

A se vedea ?i

  • 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
  • MySQL character set concepts
  • » 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, PHP 7)

mysqli::set_local_infile_default -- mysqli_set_local_infile_default — Unsets user defined handler for load local infile command

Descrierea

void mysqli_set_local_infile_default ( mysqli $link )

Deactivates a LOAD DATA INFILE LOCAL handler previously set with mysqli_set_local_infile_handler().

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

See mysqli_set_local_infile_handler() examples

A se vedea ?i

  • 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, PHP 7)

mysqli::set_local_infile_handler -- mysqli_set_local_infile_handler — Set callback function for LOAD DATA LOCAL INFILE command

Descrierea

Stil obiect-orientat

bool mysqli::set_local_infile_handler ( mysqli $link , callable $read_func )

Stil procedural

bool mysqli_set_local_infile_handler ( mysqli $link , callable $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

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 mysqli::set_local_infile_handler() example

Stil obiect-orientat

<?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";
  }
?>

Stil procedural

<?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";
  }
?>

Exemplele de mai sus vor afi?a:

Input:
23,foo
42,bar

Output:
23,FOO
42,BAR

A se vedea ?i

  • 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, PHP 7)

mysqli::$sqlstate -- mysqli_sqlstate — Returns the SQLSTATE error from previous MySQL operation

Descrierea

Stil obiect-orientat

string $mysqli->sqlstate;

Stil procedural

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.

Nota:

Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Exemple

Example #1 $mysqli->sqlstate example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Error - SQLSTATE 42S01.

A se vedea ?i

  • 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, PHP 7)

mysqli::ssl_set -- mysqli_ssl_set — Used for establishing secure connections using SSL

Descrierea

Stil obiect-orientat

bool mysqli::ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )

Stil procedural

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau 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

Valorile întoarse

This function always returns TRUE value. If SSL setup is incorrect mysqli_real_connect() will return an error when you attempt to connect.

A se vedea ?i

  • 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, PHP 7)

mysqli::stat -- mysqli_stat — Gets the current system status

Descrierea

Stil obiect-orientat

string mysqli::stat ( void )

Stil procedural

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

A string describing the server status. FALSE if an error occurred.

Exemple

Example #1 mysqli::stat() example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

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

A se vedea ?i

  • 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, PHP 7)

mysqli::stmt_init -- mysqli_stmt_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare

Descrierea

Stil obiect-orientat

mysqli_stmt mysqli::stmt_init ( void )

Stil procedural

mysqli_stmt mysqli_stmt_init ( mysqli $link )

Allocates and initializes a statement object suitable for mysqli_stmt_prepare().

Nota:

Any subsequent calls to any mysqli_stmt function will fail until mysqli_stmt_prepare() was called.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Returns an object.

A se vedea ?i

  • 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, PHP 7)

mysqli::store_result -- mysqli_store_result — Transfers a result set from the last query

Descrierea

Stil obiect-orientat

mysqli_result mysqli::store_result ([ int $option ] )

Stil procedural

mysqli_result mysqli_store_result ( mysqli $link [, int $option ] )

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

option

The option that you want to set. It can be one of the following values:

Valid options
Name | Description
MYSQLI_STORE_RESULT_COPY_DATA | Copy results from the internal mysqlnd buffer into the PHP variables fetched. By default, mysqlnd will use a reference logic to avoid copying and duplicating results held in memory. For certain result sets, for example, result sets with many small rows, the copy approach can reduce the overall memory usage because PHP variables holding results may be released earlier (available with mysqlnd only, since PHP 5.6.0)

Valorile întoarse

Returns a buffered result object or FALSE if an error occurred.

Nota:

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.

Note

Nota:

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.

Exemple

See mysqli_multi_query().

A se vedea ?i

  • 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, PHP 7)

mysqli::$thread_id -- mysqli_thread_id — Returns the thread ID for the current connection

Descrierea

Stil obiect-orientat

int $mysqli->thread_id;

Stil procedural

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.

Nota:

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.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Returns the Thread ID for the current connection.

Exemple

Example #1 $mysqli->thread_id example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Error: MySQL server has gone away

A se vedea ?i

  • 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, PHP 7)

mysqli::thread_safe -- mysqli_thread_safe — Returns whether thread safety is given or not

Descrierea

Stil procedural

bool mysqli_thread_safe ( void )

Tells whether the client library is compiled as thread-safe.

Valorile întoarse

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, PHP 7)

mysqli::use_result -- mysqli_use_result — Initiate a result set retrieval

Descrierea

Stil obiect-orientat

mysqli_result mysqli::use_result ( void )

Stil procedural

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.

Nota:

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.

Valorile întoarse

Returns an unbuffered result object or FALSE if an error occurred.

Exemple

Example #1 mysqli::use_result() example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

A se vedea ?i

  • 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, PHP 7)

mysqli::$warning_count -- mysqli_warning_count — Returns the number of warnings from the last query for the given link

Descrierea

Stil obiect-orientat

int $mysqli->warning_count;

Stil procedural

int mysqli_warning_count ( mysqli $link )

Returns the number of warnings from the last query in the connection.

Nota:

For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count].

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

Valorile întoarse

Number of warnings or zero if there are no warnings.

Exemple

Example #1 $mysqli->warning_count example

Stil obiect-orientat

<?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();
?>

Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Warning (1264): Data truncated for column 'Name' at row 1

A se vedea ?i

  • 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

(PHP 5, PHP 7)

Introducere

Represents a prepared statement.

Sinopsisul clasei

mysqli_stmt {
/* Proprieta?i */
int $affected_rows;
int $errno;
array $error_list;
string $error;
int $field_count;
int $insert_id;
int $num_rows;
int $param_count;
string $sqlstate;
/* Metode */
__construct ( mysqli $link [, string $query ] )
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 )
}

Cuprins

  • 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::__construct — Constructs a new mysqli_stmt object
  • 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_list — Returns a list of errors from the last statement executed
  • 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::more_results — Check if there are more query results from a multiple query
  • mysqli_stmt::next_result — Reads the next result from a multiple query
  • 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, PHP 7)

mysqli_stmt::$affected_rows -- mysqli_stmt_affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement

Descrierea

Stil obiect-orientat

int $mysqli_stmt->affected_rows;

Stil procedural

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.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

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.

Nota:

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.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

rows inserted: 17

A se vedea ?i

  • 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, PHP 7)

mysqli_stmt::attr_get -- mysqli_stmt_attr_get — Used to get the current value of a statement attribute

Descrierea

Stil obiect-orientat

int mysqli_stmt::attr_get ( int $attr )

Stil procedural

int mysqli_stmt_attr_get ( mysqli_stmt $stmt , int $attr )

Gets the current value of a statement attribute.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

attr

The attribute that you want to get.

Valorile întoarse

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, PHP 7)

mysqli_stmt::attr_set -- mysqli_stmt_attr_set — Used to modify the behavior of a prepared statement

Descrierea

Stil obiect-orientat

bool mysqli_stmt::attr_set ( int $attr , int $mode )

Stil procedural

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.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de 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 | Setting to TRUE 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.

A se vedea ?i

  • » Connector/MySQL mysql_stmt_attr_set()

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, PHP 7)

mysqli_stmt::bind_param -- mysqli_stmt_bind_param — Binds variables to a prepared statement as parameters

Descrierea

Stil obiect-orientat

bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

Stil procedural

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().

Nota:

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.

Nota:

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.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

1 Row inserted.
1 Row deleted.

A se vedea ?i

  • 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, PHP 7)

mysqli_stmt::bind_result -- mysqli_stmt_bind_result — Binds variables to a prepared statement for result storage

Descrierea

Stil obiect-orientat

bool mysqli_stmt::bind_result ( mixed &$var1 [, mixed &$... ] )

Stil procedural

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, ....

Nota:

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.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

var1

The variable to be bound.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();

?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

AFG Afghanistan
ALB Albania
DZA Algeria
ASM American Samoa
AND Andorra

A se vedea ?i

  • mysqli_stmt_get_result() - Gets a result set from a prepared statement
  • 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::__construct
mysqli_stmt
PHP Manual

mysqli_stmt::close

mysqli_stmt_close

(PHP 5, PHP 7)

mysqli_stmt::close -- mysqli_stmt_close — Closes a prepared statement

Descrierea

Stil obiect-orientat

bool mysqli_stmt::close ( void )

Stil procedural

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.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • mysqli_prepare() - Prepare an SQL statement for execution

mysqli_stmt::bind_result
mysqli_stmt::__construct
mysqli_stmt


Constructs a new mysqli_stmt object

mysqli_stmt::close
mysqli_stmt::data_seek
mysqli_stmt
PHP Manual

mysqli_stmt::__construct

(PHP 5, PHP 7)

mysqli_stmt::__construct — Constructs a new mysqli_stmt object

Descrierea

mysqli_stmt::__construct ( mysqli $link [, string $query ] )

This method constructs a new mysqli_stmt object.

Nota:

In general, you should use either mysqli_prepare() or mysqli_stmt_init() to create a mysqli_stmt object, rather than directly instantiating the object with new mysqli_stmt. This method (and the ability to directly instantiate mysqli_stmt objects) may be deprecated and removed in the future.

Parametri

link

Numai stilul procedural: Un identificator al legaturii întors de mysqli_connect() sau mysqli_init()

query

The query, as a string. If this parameter is omitted, then the constructor behaves identically to mysqli_stmt_init(), if provided, then it behaves as per mysqli_prepare().

A se vedea ?i

  • mysqli_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::close
mysqli_stmt::data_seek
mysqli_stmt


Seeks to an arbitrary row in statement result set

mysqli_stmt::__construct
mysqli_stmt::$errno
mysqli_stmt
PHP Manual

mysqli_stmt::data_seek

mysqli_stmt_data_seek

(PHP 5, PHP 7)

mysqli_stmt::data_seek -- mysqli_stmt_data_seek — Seeks to an arbitrary row in statement result set

Descrierea

Stil obiect-orientat

void mysqli_stmt::data_seek ( int $offset )

Stil procedural

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().

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

offset

Must be between zero and the total number of rows minus one (0.. mysqli_stmt_num_rows() - 1).

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

City: Benin City  Countrycode: NGA

A se vedea ?i

  • mysqli_prepare() - Prepare an SQL statement for execution

mysqli_stmt::__construct
mysqli_stmt::$errno
mysqli_stmt


Returns the error code for the most recent statement call

mysqli_stmt::data_seek
mysqli_stmt::$error_list
mysqli_stmt
PHP Manual

mysqli_stmt::$errno

mysqli_stmt_errno

(PHP 5, PHP 7)

mysqli_stmt::$errno -- mysqli_stmt_errno — Returns the error code for the most recent statement call

Descrierea

Stil obiect-orientat

int $mysqli_stmt->errno;

Stil procedural

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.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

An error code value. Zero means no error occurred.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Error: 1146.

A se vedea ?i

  • 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_list
mysqli_stmt


Returns a list of errors from the last statement executed

mysqli_stmt::$errno
mysqli_stmt::$error
mysqli_stmt
PHP Manual

mysqli_stmt::$error_list

mysqli_stmt_error_list

(PHP 5 >= 5.4.0, PHP 7)

mysqli_stmt::$error_list -- mysqli_stmt_error_list — Returns a list of errors from the last statement executed

Descrierea

Stil obiect-orientat

array $mysqli_stmt->error_list;

Stil procedural

array mysqli_stmt_error_list ( mysqli_stmt $stmt )

Returns an array of errors for the most recently invoked statement function that can succeed or fail.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

A list of errors, each as an associative array containing the errno, error, and sqlstate.

Exemple

Example #1 Stil obiect-orientat

<?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();

    echo "Error:\n";
    print_r($stmt->error_list);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Stil procedural

<?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);

    echo "Error:\n";
    print_r(mysql_stmt_error_list($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Exemplele de mai sus vor afi?a:

Array
(
    [0] => Array
        (
            [errno] => 1146
            [sqlstate] => 42S02
            [error] => Table 'world.myCountry' doesn't exist
        )

)

A se vedea ?i

  • mysqli_stmt_error() - Returns a string description for last statement error
  • 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::$error
mysqli_stmt


Returns a string description for last statement error

mysqli_stmt::$error_list
mysqli_stmt::execute
mysqli_stmt
PHP Manual

mysqli_stmt::$error

mysqli_stmt_error

(PHP 5, PHP 7)

mysqli_stmt::$error -- mysqli_stmt_error — Returns a string description for last statement error

Descrierea

Stil obiect-orientat

string $mysqli_stmt->error;

Stil procedural

string mysqli_stmt_error ( mysqli_stmt $stmt )

Returns a string containing the error message for the most recently invoked statement function that can succeed or fail.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

A string that describes the error. An empty string if no error occurred.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Error: Table 'world.myCountry' doesn't exist.

A se vedea ?i

  • 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::$error_list
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, PHP 7)

mysqli_stmt::execute -- mysqli_stmt_execute — Executes a prepared Query

Descrierea

Stil obiect-orientat

bool mysqli_stmt::execute ( void )

Stil procedural

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.

Nota:

When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Stuttgart (DEU,Baden-Wuerttemberg)
Bordeaux (FRA,Aquitaine)

A se vedea ?i

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_get_result() - Gets a result set from a prepared statement

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, PHP 7)

mysqli_stmt::fetch -- mysqli_stmt_fetch — Fetch results from a prepared statement into the bound variables

Descrierea

Stil obiect-orientat

bool mysqli_stmt::fetch ( void )

Stil procedural

bool mysqli_stmt_fetch ( mysqli_stmt $stmt )

Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result().

Nota:

Note that all columns must be bound by the application before calling mysqli_stmt_fetch().

Nota:

Data are transferred unbuffered without calling mysqli_stmt_store_result() which can decrease performance (but reduces memory cost).

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

Valorile întoarse
Value | Description
TRUE | Success. Data has been fetched
FALSE | Error occurred
NULL | No more rows/data exists or data truncation occurred

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Rockford (USA)
Tallahassee (USA)
Salinas (USA)
Santa Clarita (USA)
Springfield (USA)

A se vedea ?i

  • 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, PHP 7)

mysqli_stmt::$field_count -- mysqli_stmt_field_count — Returns the number of field in the given statement

Descrierea

Stil obiect-orientat

int $mysqli_stmt->field_count;

Stil procedural

int mysqli_stmt_field_count ( mysqli_stmt $stmt )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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, PHP 7)

mysqli_stmt::free_result -- mysqli_stmt_free_result — Frees stored result memory for the given statement handle

Descrierea

Stil obiect-orientat

void mysqli_stmt::free_result ( void )

Stil procedural

void mysqli_stmt_free_result ( mysqli_stmt $stmt )

Frees the result memory associated with the statement, which was allocated by mysqli_stmt_store_result().

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

mysqli_stmt::get_result -- mysqli_stmt_get_result — Gets a result set from a prepared statement

Descrierea

Stil obiect-orientat

mysqli_result mysqli_stmt::get_result ( void )

Stil procedural

mysqli_result mysqli_stmt_get_result ( mysqli_stmt $stmt )

Call to return a result set from a prepared statement query.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

Returns a resultset for successful SELECT queries, or FALSE for other DML queries or on failure. The mysqli_errno() function can be used to distinguish between the two types of failure.

Doar driver-ul original al MySQL

Disponibil numai cu mysqlnd.

Exemple

Example #1 Stil obiect-orientat

<?php

$mysqli = new mysqli("127.0.0.1", "user", "password", "world");

if($mysqli->connect_error)
{
    die("$mysqli->connect_errno: $mysqli->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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Albania 3401200 Europe
Algeria 31471000 Africa
Afghanistan 22720000 Asia
Anguilla 8000 North America

A se vedea ?i

  • 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_errno() - Returns the error code for the most recent function call

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, PHP 7)

mysqli_stmt::get_warnings -- mysqli_stmt_get_warnings — Get result of SHOW WARNINGS

Descrierea

Stil obiect-orientat

object mysqli_stmt::get_warnings ( mysqli_stmt $stmt )

Stil procedural

object mysqli_stmt_get_warnings ( mysqli_stmt $stmt )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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::more_results
mysqli_stmt
PHP Manual

mysqli_stmt::$insert_id

mysqli_stmt_insert_id

(PHP 5, PHP 7)

mysqli_stmt::$insert_id -- mysqli_stmt_insert_id — Get the ID generated from the previous INSERT operation

Descrierea

Stil obiect-orientat

int $mysqli_stmt->insert_id;

Stil procedural

mixed mysqli_stmt_insert_id ( mysqli_stmt $stmt )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

mysqli_stmt::get_warnings
mysqli_stmt::more_results
mysqli_stmt


Check if there are more query results from a multiple query

mysqli_stmt::$insert_id
mysqli_stmt::next_result
mysqli_stmt
PHP Manual

mysqli_stmt::more_results

mysqli_stmt_more_results

(PHP 5 >= 5.3.0, PHP 7)

mysqli_stmt::more_results -- mysqli_stmt_more_results — Check if there are more query results from a multiple query

Descrierea

Stil obiect-orientat (method):

public bool mysqli_stmt::more_results ( void )

Stil procedural:

bool mysqli_stmt_more_results ( mysql_stmt $stmt )

Checks if there are more query results from a multiple query.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

Returns TRUE if more results exist, otherwise FALSE.

Doar driver-ul original al MySQL

Disponibil numai cu mysqlnd.

A se vedea ?i

  • mysqli_stmt::next_result() - Reads the next result from a multiple query
  • mysqli::multi_query() - Performs a query on the database

mysqli_stmt::$insert_id
mysqli_stmt::next_result
mysqli_stmt


Reads the next result from a multiple query

mysqli_stmt::more_results
mysqli_stmt::$num_rows
mysqli_stmt
PHP Manual

mysqli_stmt::next_result

mysqli_stmt_next_result

(PHP 5 >= 5.3.0, PHP 7)

mysqli_stmt::next_result -- mysqli_stmt_next_result — Reads the next result from a multiple query

Descrierea

Stil obiect-orientat (method):

public bool mysqli_stmt::next_result ( void )

Stil procedural:

bool mysqli_stmt_next_result ( mysql_stmt $stmt )

Reads the next result from a multiple query.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Emits an E_STRICT level error if a result set does not exist, and suggests using mysqli_stmt::more_results() in these cases, before calling mysqli_stmt::next_result().

Doar driver-ul original al MySQL

Disponibil numai cu mysqlnd.

A se vedea ?i

  • mysqli_stmt::more_results() - Check if there are more query results from a multiple query
  • mysqli::multi_query() - Performs a query on the database

mysqli_stmt::more_results
mysqli_stmt::$num_rows
mysqli_stmt


Return the number of rows in statements result set

mysqli_stmt::next_result
mysqli_stmt::$param_count
mysqli_stmt
PHP Manual

mysqli_stmt::$num_rows

mysqli_stmt_num_rows

(PHP 5, PHP 7)

mysqli_stmt::$num_rows -- mysqli_stmt_num_rows — Return the number of rows in statements result set

Descrierea

Stil obiect-orientat

int $mysqli_stmt->num_rows;

Stil procedural

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.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

An integer representing the number of rows in result set.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Number of rows: 20.

A se vedea ?i

  • 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::next_result
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, PHP 7)

mysqli_stmt::$param_count -- mysqli_stmt_param_count — Returns the number of parameter for the given statement

Descrierea

Stil obiect-orientat

int $mysqli_stmt->param_count;

Stil procedural

int mysqli_stmt_param_count ( mysqli_stmt $stmt )

Returns the number of parameter markers present in the prepared statement.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

Returns an integer representing the number of parameters.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Statement has 2 markers.

A se vedea ?i

  • 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, PHP 7)

mysqli_stmt::prepare -- mysqli_stmt_prepare — Prepare an SQL statement for execution

Descrierea

Stil obiect-orientat

mixed mysqli_stmt::prepare ( string $query )

Stil procedural

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.

Nota:

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 (libmysqlclient). 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".

  • libmysqlclient on all platforms returns an error code 2006. This error message means "server has gone away".

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de 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.

Nota:

You should not add a terminating semicolon or \g to the statement.

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Amersfoort is in district Utrecht

A se vedea ?i

  • 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_get_result() - Gets a result set from a prepared statement
  • 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, PHP 7)

mysqli_stmt::reset -- mysqli_stmt_reset — Resets a prepared statement

Descrierea

Stil obiect-orientat

bool mysqli_stmt::reset ( void )

Stil procedural

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().

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

mysqli_stmt::result_metadata -- mysqli_stmt_result_metadata — Returns result set metadata from a prepared statement

Descrierea

Stil obiect-orientat

mysqli_result mysqli_stmt::result_metadata ( void )

Stil procedural

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.

Nota:

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()

Nota:

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().

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

Returns a result object or FALSE if an error occurred.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

A se vedea ?i

  • 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, PHP 7)

mysqli_stmt::send_long_data -- mysqli_stmt_send_long_data — Send data in blocks

Descrierea

Stil obiect-orientat

bool mysqli_stmt::send_long_data ( int $param_nr , string $data )

Stil procedural

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.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

A se vedea ?i

  • 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, PHP 7)

mysqli_stmt::$sqlstate -- mysqli_stmt_sqlstate — Returns SQLSTATE error from previous statement operation

Descrierea

Stil obiect-orientat

string $mysqli_stmt->sqlstate;

Stil procedural

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.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Note

Nota:

Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Error: 42S02.

A se vedea ?i

  • 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, PHP 7)

mysqli_stmt::store_result -- mysqli_stmt_store_result — Transfers a result set from a prepared statement

Descrierea

Stil obiect-orientat

bool mysqli_stmt::store_result ( void )

Stil procedural

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), if 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.

Nota:

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 loss in all cases. You can detect whether the query produced a result set by checking if mysqli_stmt_result_metadata() returns NULL.

Parametri

stmt

Numai stilul procedural: Un identificator al declara?iei întors de mysqli_stmt_init().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Number of rows: 20.

A se vedea ?i

  • 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

(PHP 5, PHP 7)

Introducere

Represents the result set obtained from a query against the database.

Jurnal al modificarilor

Jurnal al modificarilor
Versiune | Descriere
5.4.0 | Iterator support was added, as mysqli_result now implements Traversable.

Sinopsisul clasei

mysqli_result implements Traversable {
/* Proprieta?i */
int $current_field ;
int $field_count;
array $lengths;
int $num_rows;
/* Metode */
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 = "stdClass" [, array $params ]] )
mixed fetch_row ( void )
bool field_seek ( int $fieldnr )
void free ( void )
}

Cuprins

  • mysqli_result::$current_field — Get current field offset of a result pointer
  • mysqli_result::data_seek — Adjusts the result pointer to an arbitrary 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, PHP 7)

mysqli_result::$current_field -- mysqli_field_tell — Get current field offset of a result pointer

Descrierea

Stil obiect-orientat

int $mysqli_result->current_field ;

Stil procedural

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().

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau mysqli_use_result ().

Valorile întoarse

Returns current offset of field cursor.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

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

A se vedea ?i

  • 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 arbitrary 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, PHP 7)

mysqli_result::data_seek -- mysqli_data_seek — Adjusts the result pointer to an arbitrary row in the result

Descrierea

Stil obiect-orientat

bool mysqli_result::data_seek ( int $offset )

Stil procedural

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.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau mysqli_use_result ().

offset

The field offset. Must be between zero and the total number of rows minus one (0..mysqli_num_rows() - 1).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

This function can only be used with buffered results attained from the use of the mysqli_store_result() or mysqli_query() functions.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

City: Benin City  Countrycode: NGA

A se vedea ?i

  • 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, PHP 7)

mysqli_result::fetch_all -- mysqli_fetch_all — Fetches all result rows as an associative array, a numeric array, or both

Descrierea

Stil obiect-orientat

mixed mysqli_result::fetch_all ([ int $resulttype = MYSQLI_NUM ] )

Stil procedural

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.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau 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.

Valorile întoarse

Returns an array of associative or numeric arrays holding result rows.

Doar driver-ul original al MySQL

Disponibil numai cu 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.

A se vedea ?i

  • 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, PHP 7)

mysqli_result::fetch_array -- mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both

Descrierea

Stil obiect-orientat

mixed mysqli_result::fetch_array ([ int $resulttype = MYSQLI_BOTH ] )

Stil procedural

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.

Nota: Numele câmpurilor întoarse de aceasta func?ie sunt sensibile la literele majuscule/minuscule.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP 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.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau 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.

Valorile întoarse

Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset.

Exemple

Example #1 Stil obiect-orientat

<?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->free();

/* close connection */
$mysqli->close();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Kabul (AFG)
Qandahar (AFG)
Herat (AFG)

A se vedea ?i

  • 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 arbitrary 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, PHP 7)

mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row as an associative array

Descrierea

Stil obiect-orientat

array mysqli_result::fetch_assoc ( void )

Stil procedural

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.

Nota: Numele câmpurilor întoarse de aceasta func?ie sunt sensibile la literele majuscule/minuscule.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau mysqli_use_result ().

Valorile întoarse

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.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

Example #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']);
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

'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'

A se vedea ?i

  • 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 arbitrary 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, PHP 7)

mysqli_result::fetch_field_direct -- mysqli_fetch_field_direct — Fetch meta-data for a single field

Descrierea

Stil obiect-orientat

object mysqli_result::fetch_field_direct ( int $fieldnr )

Stil procedural

object mysqli_fetch_field_direct ( mysqli_result $result , int $fieldnr )

Returns an object which contains field definition information from the specified result set.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau mysqli_use_result ().

fieldnr

The field number. This value must be in the range from 0 to number of fields - 1.

Valorile întoarse

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 numeric fields)

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

A se vedea ?i

  • 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, PHP 7)

mysqli_result::fetch_field -- mysqli_fetch_field — Returns the next field in the result set

Descrierea

Stil obiect-orientat

object mysqli_result::fetch_field ( void )

Stil procedural

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.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau mysqli_use_result ().

Valorile întoarse

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)

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

A se vedea ?i

  • 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, PHP 7)

mysqli_result::fetch_fields -- mysqli_fetch_fields — Returns an array of objects representing the fields in a result set

Descrierea

Stil obiect-orientat

array mysqli_result::fetch_fields ( void )

Stil procedural

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.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau mysqli_use_result ().

Valorile întoarse

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, in bytes, as specified in the table definition. Note that this number (bytes) might differ from your table definition value (characters), depending on the character set you use. For example, the character set utf8 has 3 bytes per character, so varchar(10) will return a length of 30 for utf8 (10*3), but return 10 for latin1 (10*1).
charsetnr | The character set number (id) 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)

Exemple

Example #1 Stil obiect-orientat

<?php
$mysqli = new mysqli("127.0.0.1", "root", "foofoo", "sakila");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

foreach (array('latin1', 'utf8') as $charset) {

    // Set character set, to show its impact on some values (e.g., length in bytes)
    $mysqli->set_charset($charset);

    $query = "SELECT actor_id, last_name from actor ORDER BY actor_id";

    echo "======================\n";
    echo "Character Set: $charset\n";
    echo "======================\n";

    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("Length:    %d\n",   $val->length);
            printf("charsetnr: %d\n",   $val->charsetnr);
            printf("Flags:     %d\n",   $val->flags);
            printf("Type:      %d\n\n", $val->type);
        }
        $result->free();
    }
}
$mysqli->close();
?>

Example #2 Stil procedural

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "sakila");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

foreach (array('latin1', 'utf8') as $charset) {

    // Set character set, to show its impact on some values (e.g., length in bytes)
    mysqli_set_charset($link, $charset);

    $query = "SELECT actor_id, last_name from actor ORDER BY actor_id";

    echo "======================\n";
    echo "Character Set: $charset\n";
    echo "======================\n";

    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("Length:    %d\n",   $val->length);
            printf("charsetnr: %d\n",   $val->charsetnr);
            printf("Flags:     %d\n",   $val->flags);
            printf("Type:      %d\n\n", $val->type);
        }
        mysqli_free_result($result);
    }
}

mysqli_close($link);
?>

Exemplele de mai sus vor afi?a:

======================
Character Set: latin1
======================
Name:      actor_id
Table:     actor
Max. Len:  3
Length:    5
charsetnr: 63
Flags:     49699
Type:      2

Name:      last_name
Table:     actor
Max. Len:  12
Length:    45
charsetnr: 8
Flags:     20489
Type:      253

======================
Character Set: utf8
======================
Name:      actor_id
Table:     actor
Max. Len:  3
Length:    5
charsetnr: 63
Flags:     49699
Type:      2

Name:      last_name
Table:     actor
Max. Len:  12
Length:    135
charsetnr: 33
Flags:     20489

A se vedea ?i

  • 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, PHP 7)

mysqli_result::fetch_object -- mysqli_fetch_object — Returns the current row of a result set as an object

Descrierea

Stil obiect-orientat

object mysqli_result::fetch_object ([ string $class_name = "stdClass" [, array $params ]] )

Stil procedural

object mysqli_fetch_object ( mysqli_result $result [, string $class_name = "stdClass" [, 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.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau 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.

Valorile întoarse

Returns an object with string properties that corresponds to the fetched row or NULL if there are no more rows in resultset.

Nota: Numele câmpurilor întoarse de aceasta func?ie sunt sensibile la literele majuscule/minuscule.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

A se vedea ?i

  • 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 arbitrary 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, PHP 7)

mysqli_result::fetch_row -- mysqli_fetch_row — Get a result row as an enumerated array

Descrierea

Stil obiect-orientat

mixed mysqli_result::fetch_row ( void )

Stil procedural

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.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau mysqli_use_result ().

Valorile întoarse

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.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

A se vedea ?i

  • 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 arbitrary 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, PHP 7)

mysqli_result::$field_count -- mysqli_num_fields — Get the number of fields in a result

Descrierea

Stil obiect-orientat

int $mysqli_result->field_count;

Stil procedural

int mysqli_num_fields ( mysqli_result $result )

Returns the number of fields from specified result set.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau mysqli_use_result ().

Valorile întoarse

The number of fields from a result set.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Result set has 5 fields.

A se vedea ?i

  • 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, PHP 7)

mysqli_result::field_seek -- mysqli_field_seek — Set result pointer to a specified field offset

Descrierea

Stil obiect-orientat

bool mysqli_result::field_seek ( int $fieldnr )

Stil procedural

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.

Nota:

To seek to the beginning of a row, pass an offset value of zero.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau mysqli_use_result ().

fieldnr

The field number. This value must be in the range from 0 to number of fields - 1.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

A se vedea ?i

  • 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, PHP 7)

mysqli_result::free -- mysqli_free_result — Frees the memory associated with a result

Descrierea

Stil obiect-orientat

void mysqli_result::free ( void )
void mysqli_result::close ( void )
void mysqli_result::free_result ( void )

Stil procedural

void mysqli_free_result ( mysqli_result $result )

Frees the memory associated with the result.

Nota:

You should always free your result with mysqli_free_result(), when your result object is not needed anymore.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau mysqli_use_result ().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

mysqli_result::$lengths -- mysqli_fetch_lengths — Returns the lengths of the columns of the current row in the result set

Descrierea

Stil obiect-orientat

array $mysqli_result->lengths;

Stil procedural

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.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau mysqli_use_result ().

Valorile întoarse

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.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

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, PHP 7)

mysqli_result::$num_rows -- mysqli_num_rows — Gets the number of rows in a result

Descrierea

Stil obiect-orientat

int $mysqli_result->num_rows;

Stil procedural

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.

Parametri

result

Numai stilul procedural: Un identificator al setului de rezultate întors de mysqli_query(), mysqli_store_result() sau mysqli_use_result ().

Valorile întoarse

Returns number of rows in the result set.

Nota:

If the number of rows is greater than PHP_INT_MAX, the number will be returned as a string.

Exemple

Example #1 Stil obiect-orientat

<?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();
?>

Example #2 Stil procedural

<?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);
?>

Exemplele de mai sus vor afi?a:

Result set has 239 rows.

A se vedea ?i

  • 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

(PHP 5, PHP 7)

Introducere

MySQLi Driver.

Sinopsisul clasei

mysqli_driver {
/* Proprieta?i */
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 ;
/* Metode */
void embedded_server_end ( void )
bool embedded_server_start ( bool $start , array $arguments , array $groups )
}

Proprieta?i

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().

Cuprins

  • mysqli_driver::embedded_server_end — Stop embedded server
  • mysqli_driver::embedded_server_start — Initialize and start embedded server
  • mysqli_driver::$report_mode — Enables or disables internal report functions
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, PHP 7)

mysqli_driver::embedded_server_end -- mysqli_embedded_server_end — Stop embedded server

Descrierea

Stil obiect-orientat

void mysqli_driver::embedded_server_end ( void )

Stil procedural

void mysqli_embedded_server_end ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

mysqli_driver
mysqli_driver::embedded_server_start
mysqli_driver


Initialize and start embedded server

mysqli_driver::embedded_server_end
mysqli_driver::$report_mode
mysqli_driver
PHP Manual

mysqli_driver::embedded_server_start

mysqli_embedded_server_start

(PHP 5, PHP 7)

mysqli_driver::embedded_server_start -- mysqli_embedded_server_start — Initialize and start embedded server

Descrierea

Stil obiect-orientat

bool mysqli_driver::embedded_server_start ( bool $start , array $arguments , array $groups )

Stil procedural

bool mysqli_embedded_server_start ( bool $start , array $arguments , array $groups )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

mysqli_driver::embedded_server_end
mysqli_driver::$report_mode
mysqli_driver


Enables or disables internal report functions

mysqli_driver::embedded_server_start
mysqli_warning
mysqli_driver
PHP Manual

mysqli_driver::$report_mode

mysqli_report

(PHP 5, PHP 7)

mysqli_driver::$report_mode -- mysqli_report — Enables or disables internal report functions

Descrierea

Stil obiect-orientat

int $mysqli_driver->report_mode ;

Stil procedural

bool mysqli_report ( int $flags )

A function helpful in improving queries during code development and testing. Depending on the flags, it reports errors from mysqli function calls or queries that don't use an index (or use a bad index).

Parametri

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)

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.4 | Changing the reporting mode is now be per-request, rather than per-process.
5.2.15 | Changing the reporting mode is now be per-request, rather than per-process.

Exemple

Example #1 Stil obiect-orientat

<?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();
}

/* activate reporting */
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;

try {

    /* 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();

} catch (mysqli_sql_exception $e) {

    echo $e->__toString();
}
?>

Example #2 Stil procedural

<?php
/* activate reporting */
mysqli_report(MYSQLI_REPORT_ALL);

$link = mysqli_connect("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");

mysqli_free_result($result);

mysqli_close($link);
?>

A se vedea ?i

  • mysqli_debug() - Performs debugging operations
  • mysqli_dump_debug_info() - Dump debugging information into the log
  • mysqli_sql_exception
  • set_exception_handler() - Sets a user-defined exception handler function
  • error_reporting() - Stabile?te ce erori PHP vor fi raportate

mysqli_driver::embedded_server_start
mysqli_warning
mysqli_driver


The mysqli_warning class

(PHP 5, PHP 7)

Introducere

Represents a MySQL warning.

Sinopsisul clasei

mysqli_warning {
/* Proprieta?i */
public $message ;
public $sqlstate ;
public $errno ;
/* Metode */
protected __construct ( void )
public void next ( void )
}

Proprieta?i

message

Message string

sqlstate

SQL state

errno

Error number

Cuprins

  • mysqli_warning::__construct — The __construct purpose
  • mysqli_warning::next — The next purpose
mysqli_driver::$report_mode
mysqli_warning::__construct
MySQLi


The __construct purpose

mysqli_warning
mysqli_warning::next
mysqli_warning
PHP Manual

mysqli_warning::__construct

(PHP 5, PHP 7)

mysqli_warning::__construct — The __construct purpose

Descrierea

protected mysqli_warning::__construct ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

mysqli_warning
mysqli_warning::next
mysqli_warning


The next purpose

mysqli_warning::__construct
mysqli_sql_exception
mysqli_warning
PHP Manual

mysqli_warning::next

(PHP 5, PHP 7)

mysqli_warning::next — The next purpose

Descrierea

public void mysqli_warning::next ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

mysqli_warning::__construct
mysqli_sql_exception
mysqli_warning


The mysqli_sql_exception class

(PHP 5, PHP 7)

Introducere

The mysqli exception handling class.

Sinopsisul clasei

mysqli_sql_exception extends RuntimeException {
/* Proprieta?i */
protected string $sqlstate ;
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}

Proprieta?i

sqlstate

The sql state with the error.

mysqli_warning::next
Pseudonime ?i Func?ii Mysqli învechite
MySQLi


Pseudonime ?i Func?ii Mysqli învechite

Cuprins

  • 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 — Pseudonim pentru mysqli::__construct
  • mysqli::disable_reads_from_master — Disable reads from master
  • 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 — Pseudonim pentru 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_links_stats — Return information about open and cached links
  • 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 — Pseudonim pentru mysqli_driver->report_mode
  • 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 — Pseudonim al mysqli_options
  • mysqli_slave_query — Force execution of a query on a slave in a master/slave setup
mysqli_sql_exception
mysqli_bind_param
MySQLi


Alias for mysqli_stmt_bind_param

Pseudonime ?i Func?ii Mysqli învechite
mysqli_bind_result
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_bind_param

(PHP 5 < 5.4.0)

mysqli_bind_param — Alias for mysqli_stmt_bind_param()

Descrierea

This function is an alias of mysqli_stmt_bind_param().

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

A se vedea ?i

  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters

Pseudonime ?i Func?ii Mysqli învechite
mysqli_bind_result
Pseudonime ?i Func?ii Mysqli învechite


Alias for mysqli_stmt_bind_result

mysqli_bind_param
mysqli_client_encoding
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_bind_result

(PHP 5 < 5.4.0)

mysqli_bind_result — Alias for mysqli_stmt_bind_result()

Descrierea

This function is an alias of mysqli_stmt_bind_result().

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

A se vedea ?i

  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage

mysqli_bind_param
mysqli_client_encoding
Pseudonime ?i Func?ii Mysqli învechite


Alias of mysqli_character_set_name

mysqli_bind_result
mysqli_connect
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_client_encoding

(PHP 5 < 5.4.0)

mysqli_client_encoding — Alias of mysqli_character_set_name()

Descrierea

This function is an alias of mysqli_character_set_name().

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

A se vedea ?i

  • 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
Pseudonime ?i Func?ii Mysqli învechite


Pseudonim pentru mysqli::__construct

mysqli_client_encoding
mysqli::disable_reads_from_master
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_connect

(PHP 5, PHP 7)

mysqli_connect — Pseudonim pentru mysqli::__construct()

Descrierea

Aceasta func?ie este pseudonim pentru: mysqli::__construct()

Cu toate ca documenta?ia mysqli::__construct() include ?i exemplele procedurale ce utilizeaza func?ia mysqli_connect(), iata un scurt exemplu:

Exemple

Example #1 Exemplu mysqli_connect()

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

if (!$link) {
    echo "Eroare: Nu a fost posibila conectarea la MySQL." . PHP_EOL;
    echo "Valoarea errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Valoarea error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

echo "Succes: Conexiunea la MySQL a fost stabilita! Baza de date my_db este minunata." . PHP_EOL;
echo "Informa?ie despre host: " . mysqli_get_host_info($link) . PHP_EOL;

mysqli_close($link);
?>

Exemplele de mai sus vor afi?a:

Succes: Conexiunea la MySQL a fost stabilita! Baza de date my_db este minunata.
Informa?ie despre host: localhost via TCP/IP
mysqli_client_encoding
mysqli::disable_reads_from_master
Pseudonime ?i Func?ii Mysqli învechite


Disable reads from master

mysqli_connect
mysqli_disable_rpl_parse
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli::disable_reads_from_master

mysqli_disable_reads_from_master

(PHP 5 < 5.3.0)

mysqli::disable_reads_from_master -- mysqli_disable_reads_from_master — Disable reads from master

Descrierea

Stil obiect-orientat

void mysqli::disable_reads_from_master ( void )

Stil procedural

bool mysqli_disable_reads_from_master ( mysqli $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Avertizare

Aceasta func?ie este ÎNVECHITA ?i este ELIMINATA începând cu PHP 5.3.0.

mysqli_connect
mysqli_disable_rpl_parse
Pseudonime ?i Func?ii Mysqli învechite


Disable RPL parse

mysqli::disable_reads_from_master
mysqli_enable_reads_from_master
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_disable_rpl_parse

(PHP 5 < 5.3.0)

mysqli_disable_rpl_parse — Disable RPL parse

Descrierea

bool mysqli_disable_rpl_parse ( mysqli $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Avertizare

Aceasta func?ie este ÎNVECHITA ?i este ELIMINATA începând cu PHP 5.3.0.

mysqli::disable_reads_from_master
mysqli_enable_reads_from_master
Pseudonime ?i Func?ii Mysqli învechite


Enable reads from master

mysqli_disable_rpl_parse
mysqli_enable_rpl_parse
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_enable_reads_from_master

(PHP 5 < 5.3.0)

mysqli_enable_reads_from_master — Enable reads from master

Descrierea

bool mysqli_enable_reads_from_master ( mysqli $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Avertizare

Aceasta func?ie este ÎNVECHITA ?i este ELIMINATA începând cu PHP 5.3.0.

mysqli_disable_rpl_parse
mysqli_enable_rpl_parse
Pseudonime ?i Func?ii Mysqli învechite


Enable RPL parse

mysqli_enable_reads_from_master
mysqli_escape_string
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_enable_rpl_parse

(PHP 5 < 5.3.0)

mysqli_enable_rpl_parse — Enable RPL parse

Descrierea

bool mysqli_enable_rpl_parse ( mysqli $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Avertizare

Aceasta func?ie este ÎNVECHITA ?i este ELIMINATA începând cu PHP 5.3.0.

mysqli_enable_reads_from_master
mysqli_escape_string
Pseudonime ?i Func?ii Mysqli învechite


Pseudonim pentru mysqli_real_escape_string

mysqli_enable_rpl_parse
mysqli_execute
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_escape_string

(PHP 5, PHP 7)

mysqli_escape_string — Pseudonim pentru mysqli_real_escape_string()

Descrierea

Aceasta func?ie este pseudonim pentru: mysqli_real_escape_string().

mysqli_enable_rpl_parse
mysqli_execute
Pseudonime ?i Func?ii Mysqli învechite


Alias for mysqli_stmt_execute

mysqli_escape_string
mysqli_fetch
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_execute

(PHP 5, PHP 7)

mysqli_execute — Alias for mysqli_stmt_execute()

Descrierea

This function is an alias of mysqli_stmt_execute().

Note

Nota:

mysqli_execute() is deprecated and will be removed.

A se vedea ?i

  • mysqli_stmt_execute() - Executes a prepared Query

mysqli_escape_string
mysqli_fetch
Pseudonime ?i Func?ii Mysqli învechite


Alias for mysqli_stmt_fetch

mysqli_execute
mysqli_get_cache_stats
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_fetch

(PHP 5 < 5.4.0)

mysqli_fetch — Alias for mysqli_stmt_fetch()

Descrierea

This function is an alias of mysqli_stmt_fetch().

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

A se vedea ?i

  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables

mysqli_execute
mysqli_get_cache_stats
Pseudonime ?i Func?ii Mysqli învechite


Returns client Zval cache statistics

mysqli_fetch
mysqli_get_links_stats
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_get_cache_stats

(PHP 5 >= 5.3.0 and < 5.4.0)

mysqli_get_cache_stats — Returns client Zval cache statistics

Avertizare

This function has been REMOVED as of PHP 5.4.0.

Descrierea

array mysqli_get_cache_stats ( void )

Returns an empty array. Disponibil numai cu mysqlnd.

Parametri

Valorile întoarse

Returns an empty array on success, FALSE otherwise.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | The mysqli_get_cache_stats() was removed.
5.3.0 | The mysqli_get_cache_stats() was added as stub.

mysqli_fetch
mysqli_get_links_stats
Pseudonime ?i Func?ii Mysqli învechite


Return information about open and cached links

mysqli_get_cache_stats
mysqli_get_metadata
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_get_links_stats

(PHP 5 >= 5.6.0, PHP 7)

mysqli_get_links_stats — Return information about open and cached links

Descrierea

array mysqli_get_links_stats ( void )

mysqli_get_links_stats() returns information about open and cached MySQL links.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

mysqli_get_links_stats() returns an associative array with three elements, keyed as follows:

total

An integer indicating the total number of open links in any state.

active_plinks

An integer representing the number of active persistent connections.

cached_plinks

An integer representing the number of inactive persistent connections.

mysqli_get_cache_stats
mysqli_get_metadata
Pseudonime ?i Func?ii Mysqli învechite


Alias for mysqli_stmt_result_metadata

mysqli_get_links_stats
mysqli_master_query
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_get_metadata

(PHP 5 < 5.4.0)

mysqli_get_metadata — Alias for mysqli_stmt_result_metadata()

Descrierea

This function is an alias of mysqli_stmt_result_metadata().

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

A se vedea ?i

  • mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement

mysqli_get_links_stats
mysqli_master_query
Pseudonime ?i Func?ii Mysqli învechite


Enforce execution of a query on the master in a master/slave setup

mysqli_get_metadata
mysqli_param_count
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_master_query

(PHP 5 < 5.3.0)

mysqli_master_query — Enforce execution of a query on the master in a master/slave setup

Descrierea

bool mysqli_master_query ( mysqli $link , string $query )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Avertizare

Aceasta func?ie este ÎNVECHITA ?i este ELIMINATA începând cu PHP 5.3.0.

mysqli_get_metadata
mysqli_param_count
Pseudonime ?i Func?ii Mysqli învechite


Alias for mysqli_stmt_param_count

mysqli_master_query
mysqli_report
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_param_count

(PHP 5 < 5.4.0)

mysqli_param_count — Alias for mysqli_stmt_param_count()

Descrierea

This function is an alias of mysqli_stmt_param_count().

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

A se vedea ?i

  • mysqli_stmt_param_count() - Returns the number of parameter for the given statement

mysqli_master_query
mysqli_report
Pseudonime ?i Func?ii Mysqli învechite


Pseudonim pentru mysqli_driver->report_mode

mysqli_param_count
mysqli_rpl_parse_enabled
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_report

(PHP 5, PHP 7)

mysqli_report — Pseudonim pentru mysqli_driver->report_mode

Descrierea

Aceasta func?ie este pseudonim pentru: mysqli_driver->report_mode

mysqli_param_count
mysqli_rpl_parse_enabled
Pseudonime ?i Func?ii Mysqli învechite


Check if RPL parse is enabled

mysqli_report
mysqli_rpl_probe
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_rpl_parse_enabled

(PHP 5 < 5.3.0)

mysqli_rpl_parse_enabled — Check if RPL parse is enabled

Descrierea

int mysqli_rpl_parse_enabled ( mysqli $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Avertizare

Aceasta func?ie este ÎNVECHITA ?i este ELIMINATA începând cu PHP 5.3.0.

mysqli_report
mysqli_rpl_probe
Pseudonime ?i Func?ii Mysqli învechite


RPL probe

mysqli_rpl_parse_enabled
mysqli_send_long_data
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_rpl_probe

(PHP 5 < 5.3.0)

mysqli_rpl_probe — RPL probe

Descrierea

bool mysqli_rpl_probe ( mysqli $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Avertizare

Aceasta func?ie este ÎNVECHITA ?i este ELIMINATA începând cu PHP 5.3.0.

mysqli_rpl_parse_enabled
mysqli_send_long_data
Pseudonime ?i Func?ii Mysqli învechite


Alias for mysqli_stmt_send_long_data

mysqli_rpl_probe
mysqli::set_opt
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_send_long_data

(PHP 5 < 5.4.0)

mysqli_send_long_data — Alias for mysqli_stmt_send_long_data()

Descrierea

This function is an alias of mysqli_stmt_send_long_data().

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

A se vedea ?i

  • mysqli_stmt_send_long_data() - Send data in blocks

mysqli_rpl_probe
mysqli::set_opt
Pseudonime ?i Func?ii Mysqli învechite


Pseudonim al mysqli_options

mysqli_send_long_data
mysqli_slave_query
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli::set_opt

mysqli_set_opt

(PHP 5, PHP 7)

mysqli::set_opt -- mysqli_set_opt — Pseudonim al mysqli_options()

Descrierea

Aceasta func?ie este un pseudonim al mysqli_options().

mysqli_send_long_data
mysqli_slave_query
Pseudonime ?i Func?ii Mysqli învechite


Force execution of a query on a slave in a master/slave setup

mysqli::set_opt
Jurnalul modificarilor
Pseudonime ?i Func?ii Mysqli învechite
PHP Manual

mysqli_slave_query

(PHP 5 < 5.3.0)

mysqli_slave_query — Force execution of a query on a slave in a master/slave setup

Descrierea

bool mysqli_slave_query ( mysqli $link , string $query )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Avertizare

Aceasta func?ie este ÎNVECHITA ?i este ELIMINATA începând cu PHP 5.3.0.

mysqli::set_opt
Jurnalul modificarilor
Pseudonime ?i Func?ii Mysqli învechite


Jurnalul modificarilor

Au fost efectuate urmatoarele modificari ale claselor/func?iilor/metodelor acestei extensii.

Version | Function | Description
5.6.16 | mysqli::real_connect | Added the MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT flag for MySQL Native Driver
5.5.0 | mysqli::commit | Added flags and name parameters.
 | mysqli::options | The MYSQLI_SERVER_PUBLIC_KEY and MYSQLI_SERVER_PUBLIC_KEY options were added.
 | mysqli::rollback | Added flags and name parameters.
5.4.0 | mysqli_get_cache_stats | The mysqli_get_cache_stats was removed.
5.3.4 | mysqli_driver::$report_mode | Changing the reporting mode is now be per-request, rather than per-process.
5.3.0 | mysqli_get_cache_stats | The mysqli_get_cache_stats was added as stub.
 | mysqli::__construct | Added the ability of persistent connections.
 | mysqli::options | The MYSQLI_OPT_INT_AND_FLOAT_NATIVE, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, MYSQLI_OPT_NET_READ_BUFFER_SIZE, and MYSQLI_OPT_SSL_VERIFY_SERVER_CERT options were added.
 | mysqli::query | Added the ability of async queries.
5.2.15 | mysqli_driver::$report_mode | Changing the reporting mode is now be per-request, rather than per-process.
mysqli_slave_query
MySQL (Original)
MySQLi


API originale ale MySQL

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Jurnalul modificarilor
  • Constante predefinite
  • Exemple
    • Exemplu de ansamblu pentru extensia MySQL
  • Func?ii MySQL
    • mysql_affected_rows — Ob?ine numarul de rânduri afectate de precedenta opera?iune MySQL
    • mysql_client_encoding — Întoarce denumirea setului de caractere
    • mysql_close — Închide conexiunea MySQL
    • mysql_connect — Deschide o conexiune la un server MySQL
    • mysql_create_db — Creeaza o baza de date MySQL
    • mysql_data_seek — Move internal result pointer
    • mysql_db_name — Retrieves database name from the call to mysql_list_dbs
    • mysql_db_query — Selects a database and executes a query on it
    • mysql_drop_db — Drop (delete) a MySQL database
    • mysql_errno — Returns the numerical value of the error message from previous MySQL operation
    • mysql_error — Returns the text of the error message from previous MySQL operation
    • mysql_escape_string — Escapeaza un string pentru fi folosit in mysql_query
    • mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
    • mysql_fetch_assoc — Fetch a result row as an associative array
    • mysql_fetch_field — Get column information from a result and return as an object
    • mysql_fetch_lengths — Get the length of each output in a result
    • mysql_fetch_object — Fetch a result row as an object
    • mysql_fetch_row — Get a result row as an enumerated array
    • mysql_field_flags — Get the flags associated with the specified field in a result
    • mysql_field_len — Returns the length of the specified field
    • mysql_field_name — Get the name of the specified field in a result
    • mysql_field_seek — Stabile?te indicatorul rezultatului la deplasamentul câmpului specificat
    • mysql_field_table — Get name of the table the specified field is in
    • mysql_field_type — Get the type of the specified field in a result
    • mysql_free_result — Free result memory
    • mysql_get_client_info — Ob?ine informa?ia clientului MySQL
    • mysql_get_host_info — Get MySQL host info
    • mysql_get_proto_info — Get MySQL protocol info
    • mysql_get_server_info — Get MySQL server info
    • mysql_info — Get information about the most recent query
    • mysql_insert_id — Get the ID generated in the last query
    • mysql_list_dbs — List databases available on a MySQL server
    • mysql_list_fields — List MySQL table fields
    • mysql_list_processes — List MySQL processes
    • mysql_list_tables — List tables in a MySQL database
    • mysql_num_fields — Get number of fields in result
    • mysql_num_rows — Get number of rows in result
    • mysql_pconnect — Open a persistent connection to a MySQL server
    • mysql_ping — Ping a server connection or reconnect if there is no connection
    • mysql_query — Send a MySQL query
    • mysql_real_escape_string — Escapes special characters in a string for use in an SQL statement
    • mysql_result — Get result data
    • mysql_select_db — Select a MySQL database
    • mysql_set_charset — Sets the client character set
    • mysql_stat — Get current system status
    • mysql_tablename — Get table name of field
    • mysql_thread_id — Return the current thread ID
    • mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the result rows.
Jurnalul modificarilor
Introducere
MySQL


Introducere

Aceasta extensie este învechita începând cu PHP 5.5.0, ?i a fost eliminata începând cu PHP 7.0.0. În loc, folosi?i extensia mysqli sau PDO_MySQL. A se vedea de asemenea Privire de ansamblu asupra MySQL API pentru ajutor suplimentar în alegerea unui API MySQL.

Aceste func?ii va permit accesarea serverelor de baze de date MySQL. Informa?ii suplimentare despre MySQL pot fi gasite la » http://www.mysql.com/.

Documenta?ia pentru MySQL poate fi gasita la » http://dev.mysql.com/doc/.

MySQL (Original)
Instalarea / configurarea
MySQL (Original)


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
MySQL (Original)


Necesita?i

Pentru ca aceste func?ii sa devina disponibile trebuie sa compila?i PHP cu sus?inerea MySQL.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

Pentru compilare, pur ?i simplu utiliza?i op?iunea de configurare --with-mysql[=DIR] , unde parametrul op?ional [DIR] indica directorul unde a fost instalat MySQL.

Cu toate ca aceasta extensie MySQL este compatibila cu MySQL 4.1.0 ?i versiunile ulterioare, ea nu sus?ine func?ionalitatea suplimentara oferita de aceste versiuni. Pentru aceasta utiliza?i extensia MySQLi.

Daca dori?i sa instala?i extensia mysql împreuna cu extensia mysqli, trebuie sa utiliza?i aceea?i biblioteca-client pentru a evita conflicte.

Instalarea pe sisteme Linux

Nota: [DIR] este calea catre fi?ierele bibliotecilor-client MySQL (antetele ?i bibliotecile), care pot fi descarcate din » MySQL.

matricea de suport la compilare a ext/mysql
Versiune PHP | Valoare implicita | Op?iuni de configurare pentru: mysqlnd | Op?iuni de configurare pentru: libmysqlclient | Jurnal al modificarilor
4.x.x | libmysqlclient | Nu este disponibil | --without-mysql pentru a dezactiva | MySQL este activat implicit, bibliotecile-client MySQL sunt încorporate
5.0.x, 5.1.x, 5.2.x | libmysqlclient | Nu este disponibil | --with-mysql=[DIR] | MySQL nu este activat implicit ?i bibliotecile-client MySQL nu mai sunt încorporate
5.3.x | libmysqlclient | --with-mysql=mysqlnd | --with-mysql=[DIR] | mysqlnd este acum disponibil
5.4.x | mysqlnd | --with-mysql | --with-mysql=[DIR] | mysqlnd este acum utilizat implicit

Instalarea pe sisteme Windows

PHP 4

Extensia PHP MySQL este compilata în PHP.

PHP 5.0.x, 5.1.x, 5.2.x

MySQL nu mai este activat implicit, deci biblioteca DLL php_mysql.dll trebuie activata în php.ini. De asemenea PHP are nevoie de access la biblioteca-client MySQL. Un fi?ier numit libmysql.dll este inclus în distributivul PHP pentru Windows ?i pentru ca PHP sa poata comunica cu MySQL, acest fi?ier trebuie sa fie disponibil în caile din variabila PATH a sistemului Windows. Accesa?i ?i FAQ întitulat "Cum sa adaug directorul PHP în variabila PATH din Windows" pentru informa?ii despre cum sa realiza?i acest lucru. Cu toate ca copierea libmysql.dll în directorul de sistem al Windows de asemenea func?ioneaza (deoarece directorul de sistem se afla implicit înscris în variabila PATH a sistemului), aceasta nu e recomandabil.

Ca ?i în cazul activarii oricarei extensii PHP (cum ar fi php_mysql.dll), directiva PHP extension_dir trebuie sa fie stabilita catre directorul unde sunt amplasate extensiile PHP. Accesa?i de asemenea Instruc?iunile de instalare manuala în Windows. O valoare-exemplu a extension_dir pentru PHP 5 ar putea fi c:\php\ext

Nota:

Daca la startarea server-ului web apare o eroare similara cu aceasta: "Unable to load dynamic library './php_mysql.dll'", aceasta este din cauza ca php_mysql.dll ?i/sau libmysql.dll nu pot fi gasite de catre sistem.

PHP 5.3.0+

Driver-ul MySQL Înnascut este activat implicit. Include?i php_mysql.dll, iar libmysql.dll nu mai este necesar sau folosit.

Note la instalarea MySQL

Avertizare

Pot fi întâlnite prabu?iri ?i alte probleme la startarea PHP atunci când aceasta extensie este încarcata împreuna cu extensia recode. Accesa?i extensia recode pentru informa?ii suplimentare.

Nota:

Daca ave?i nevoie se seturi de caractere ce difera de latin (implicit), trebuie sa instala?i biblioteca externa libmysqlclient compilata pentru a sus?ine setul de caractere dorit.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Op?iuni de configurare MySQL
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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 | Disponibil începând cu PHP 4.3.0.
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL | Disponibil începând cu 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 în PHP <= 4.3.2. Disponibil începând cu PHP 4.3.0.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

mysql.allow_local_infile integer

Permite accesul, din perspectiva PHP, la fi?iere locale cu interpelari LOAD DATA

mysql.allow_persistent boolean

Indica daca vor fi permise conexiuni persistente la MySQL.

mysql.max_persistent integer

Numarul maximal de conexiuni persistente la MySQL per proces.

mysql.max_links integer

Numarul maximal de conexiuni MySQL per proces, inclusiv conexiuni persistente.

mysql.trace_mode boolean

Modul de trasare. Când mysql.trace_mode este activat, vor fi afi?ate avertizari pentru scanari ale tabelelor/indicilor, seturi de rezultate neeliberate ?i erori SQL. (Introdus în PHP 4.3.0)

mysql.default_port string

Numarul implicit al portului TCP utilizat pentru conectarea la serverul de baze de date, daca nu este specificat un alt port. Daca nu este specificata o valoare implicita, numarul portului va fi ob?inut din variabila de mediu MYSQL_TCP_PORT, înregistrarea mysql-tcp din /etc/services, sau din constanta MYSQL_PORT de la momentul compilarii în aceasta ordine. Win32 va utiliza numai constanta MYSQL_PORT.

mysql.default_socket string

Numele implicit al socket-ului utilizat pentru conectarea la un server de baze de date local, daca nu este specificat numele unui alt socket.

mysql.default_host string

Denumirea implicita a serverului de baze de date, în caz ca nu se specifica o alta denumire. Nu se aplica în modul SQL securizat.

mysql.default_user string

Numele implicit al utilizatorului pentru a fi utilizat la conectarea la serverul de baze de date, daca nu este specificat un alt nume. Nu se aplica în modul SQL securizat.

mysql.default_password string

Parola implicita pentru a fi utilizata la conectarea la serverul de baze de date, daca nu este specificata o alta parola. Nu se aplica în modul SQL securizat.

mysql.connect_timeout integer

Timeout-ul la conectare în secunde. Pe Linux acest timeout este de asemenea utilizat la a?teptarea primului raspuns de la server.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Exista doua tipuri de resurse utilizate în modulul MySQL. Primul este identificatorul legaturii pentru o conexiune la baza de date, al doilea este o resursa care men?ine rezultatul unei interpelari.

Configura?ia la rulare
Jurnalul modificarilor
Instalarea / configurarea


Jurnalul modificarilor

Au fost efectuate urmatoarele modificari ale claselor/func?iilor/metodelor acestei extensii.

General Changelog for the ext/mysql extension

This changelog references the ext/mysql extension.

Global ext/mysql changes

The following is a list of changes to the entire ext/mysql extension.

Versiune | Descriere
7.0.0 | This extension was removed from PHP. For details, see Choosing an API.
5.5.0 | This extension has been deprecated. Connecting to a MySQL database via mysql_connect(), mysql_pconnect() or an implicit connection via any other mysql_* function will generate an E_DEPRECATED error.
5.5.0 | All of the old deprecated functions and aliases now emit E_DEPRECATED errors. These functions are: mysql(), mysql_fieldname(), mysql_fieldtable(), mysql_fieldlen(), mysql_fieldtype(), mysql_fieldflags(), mysql_selectdb(), mysql_createdb(), mysql_dropdb(), mysql_freeresult(), mysql_numfields(), mysql_numrows(), mysql_listdbs(), mysql_listtables(), mysql_listfields(), mysql_db_name(), mysql_dbname(), mysql_tablename(), and mysql_table_name().

Changes to existing functions

The following list is a compilation of changelog entries from the ext/mysql functions.

Version | Function | Description
5.5.0 | mysql_connect | Aceasta func?ie va genera o eroare E_DEPRECATED.
 | mysql_db_name | The mysql_list_dbs function is deprecated, and emits an E_DEPRECATED level error.
 | mysql_pconnect | This function will generate an E_DEPRECATED error.
 | mysql_tablename | The mysql_tablename function is deprecated, and emits an E_DEPRECATED level error.
5.3.0 | mysql_db_query | This function now throws an E_DEPRECATED notice.
 | mysql_escape_string | Aceasta functie returneaza o notificare de tip E_DEPRECATED.
4.3.7 | mysql_list_tables | This function became deprecated.
4.3.0 | mysql_escape_string | Aceasta functie este scoasa din uz, nu o mai folositi. In locul ei, folositi mysql_real_escape_string.
Tipurile resurselor
Constante predefinite
MySQL (Original)


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Începând cu PHP 4.3.0 este posibil de specificat fanioane-client suplimentare pentru func?iile mysql_connect() ?i mysql_pconnect(). Urmatoarele constante sunt definite:

Constante ale clientului MySQL
Constanta | Descriere
MYSQL_CLIENT_COMPRESS | Utilizeaza protocolul de compresie
MYSQL_CLIENT_IGNORE_SPACE | Permite spa?iu dupa denumirea func?iei
MYSQL_CLIENT_INTERACTIVE | Permite o inactivitate cu durata de interactive_timeout secunde (în loc de wait_timeout) înainte de a închide conexiunea.
MYSQL_CLIENT_SSL | Utilizeaza criptarea SSL. Acest fanion este disponibil numai începând cu versiunea 4.x sau ulterioara a bibliotecii-client MySQL. Versiunea 3.23.x este inclusa atât în PHP 4, cât ?i în binarele Windows ale PHP 5.

Func?ia mysql_fetch_array() utilizeaza o constanta pentru diferite tipuri ale tablourilor rezultante. Urmatoarele constante sunt definite:

Constante MySQL fetch
Constanta | Descriere
MYSQL_ASSOC | Coloanele sunt întoarse într-un tablou având în calitate de indice denumirea câmpului.
MYSQL_BOTH | Coloanele sunt întoarse într-un tablou având atât un indice numeric, cât ?i denumirea câmpului în calitate de indice.
MYSQL_NUM | Coloanele sunt întoarse într-un tablou având un indice numeric catre câmpuri. Acest indice începe cu 0, primul câmp din rezultat.

Jurnalul modificarilor
Exemple
MySQL (Original)


Exemple

Cuprins

  • Exemplu de ansamblu pentru extensia MySQL
Constante predefinite
Exemplu de ansamblu pentru extensia MySQL
MySQL (Original)


Exemplu de ansamblu pentru extensia MySQL

Acest exemplu simplu demonstreaza connectarea, executarea unei interpelari, afi?area rândurilor rezultante ?i deconectarea de la o baza de date MySQL.

Example #1 Exemplu general de utilizare a extensiei MySQL

<?php
// Connectarea, selectarea bazei de date
$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');

// Efectuarea interpelarii SQL
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

// Afi?area rezultatelor în 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";

// Eliberarea setului de rezultate
mysql_free_result($result);

// Închiderea conexiunii
mysql_close($link);
?>

Exemple
Func?ii MySQL
Exemple


Func?ii MySQL

Note

Nota:

Majoritatea func?iilor MySQL functions accepta link_identifier ca ultimul parametru op?ional. Daca el nu este specificat, ultima conexiune deschisa este utilizata. Daca ea nu exista, se încearca stabilirea conexiunii cu parametrii implici?i defini?i în php.ini. Daca conexiunea nu se efectueaza cu succes, func?iile întorc FALSE.

Cuprins

  • mysql_affected_rows — Ob?ine numarul de rânduri afectate de precedenta opera?iune MySQL
  • mysql_client_encoding — Întoarce denumirea setului de caractere
  • mysql_close — Închide conexiunea MySQL
  • mysql_connect — Deschide o conexiune la un server MySQL
  • mysql_create_db — Creeaza o baza de date MySQL
  • mysql_data_seek — Move internal result pointer
  • mysql_db_name — Retrieves database name from the call to mysql_list_dbs
  • mysql_db_query — Selects a database and executes a query on it
  • mysql_drop_db — Drop (delete) a MySQL database
  • mysql_errno — Returns the numerical value of the error message from previous MySQL operation
  • mysql_error — Returns the text of the error message from previous MySQL operation
  • mysql_escape_string — Escapeaza un string pentru fi folosit in mysql_query
  • mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
  • mysql_fetch_assoc — Fetch a result row as an associative array
  • mysql_fetch_field — Get column information from a result and return as an object
  • mysql_fetch_lengths — Get the length of each output in a result
  • mysql_fetch_object — Fetch a result row as an object
  • mysql_fetch_row — Get a result row as an enumerated array
  • mysql_field_flags — Get the flags associated with the specified field in a result
  • mysql_field_len — Returns the length of the specified field
  • mysql_field_name — Get the name of the specified field in a result
  • mysql_field_seek — Stabile?te indicatorul rezultatului la deplasamentul câmpului specificat
  • mysql_field_table — Get name of the table the specified field is in
  • mysql_field_type — Get the type of the specified field in a result
  • mysql_free_result — Free result memory
  • mysql_get_client_info — Ob?ine informa?ia clientului MySQL
  • mysql_get_host_info — Get MySQL host info
  • mysql_get_proto_info — Get MySQL protocol info
  • mysql_get_server_info — Get MySQL server info
  • mysql_info — Get information about the most recent query
  • mysql_insert_id — Get the ID generated in the last query
  • mysql_list_dbs — List databases available on a MySQL server
  • mysql_list_fields — List MySQL table fields
  • mysql_list_processes — List MySQL processes
  • mysql_list_tables — List tables in a MySQL database
  • mysql_num_fields — Get number of fields in result
  • mysql_num_rows — Get number of rows in result
  • mysql_pconnect — Open a persistent connection to a MySQL server
  • mysql_ping — Ping a server connection or reconnect if there is no connection
  • mysql_query — Send a MySQL query
  • mysql_real_escape_string — Escapes special characters in a string for use in an SQL statement
  • mysql_result — Get result data
  • mysql_select_db — Select a MySQL database
  • mysql_set_charset — Sets the client character set
  • mysql_stat — Get current system status
  • mysql_tablename — Get table name of field
  • mysql_thread_id — Return the current thread ID
  • mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the result rows.
Exemplu de ansamblu pentru extensia MySQL
mysql_affected_rows
MySQL (Original)


Ob?ine numarul de rânduri afectate de precedenta opera?iune MySQL

Func?ii MySQL
mysql_client_encoding
Func?ii MySQL
PHP Manual

mysql_affected_rows

(PHP 4, PHP 5)

mysql_affected_rows — Ob?ine numarul de rânduri afectate de precedenta opera?iune MySQL

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_affected_rows()
  • PDOStatement::rowCount()

Descrierea

int mysql_affected_rows ([ resource $link_identifier = NULL ] )

Ob?ine numarul de rânduri afectate de ultima interpelare INSERT, UPDATE, REPLACE sau DELETE asociata cu link_identifier.

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Întoarce numarul de rânduri afectate în caz de succes ?i -1 daca ultima interpelare a e?uat.

Daca ultima interpelare a fost o interpelare DELETE fara o clauza WHERE, atunci toate rândurile din tabel au fost eliminate, dar aceasta func?ie va întoarce zero în cazul versiunilor MySQL înainte de 4.1.2.

La utilizarea UPDATE, MySQL nu va reînnoi coloanele unde valoarea noua coincide cu cea veche. Aceasta creaza posibilitatea ca mysql_affected_rows() nu va coincide cu numarul de rânduri ce se potrivesc condi?iei de selectare, dar va fi doar numarul de rânduri ce au fost direct afectate de interpelare.

Interpelarea REPLACE întâi elimina înregistrarea cu aceea?i cheie primara, apoi insereaza noua înregistrare. Aceasta func?ie întoarce numarul înregistrarilor eliminate plus numarul înregistrarilor inserate.

În cazul interpelarilor de tip "INSERT ... ON DUPLICATE KEY UPDATE", valoarea întoarsa va fi 1 daca a fost efectuata inserare, sau 2 daca a fost actualizat un rând existent.

Exemple

Example #1 Exemplu mysql_affected_rows()

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('A e?uat conectarea: ' . mysql_error());
}
mysql_select_db('mydb');

/* aceasta ar trebui sa întoarca numerele corecte ale înregistrarilor eliminate */
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Înregistrari eliminate: %d\n", mysql_affected_rows());

/* cu o clauza WHERE care nici o data nu este adevarata, aceasta ar trebui sa întoarca 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Înregistrari eliminate: %d\n", mysql_affected_rows());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Înregistrari eliminate: 10
Înregistrari eliminate: 0

Example #2 Exemplu mysql_affected_rows() utilizând tranzac?ii

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('A e?uat conectarea: ' . mysql_error());
}
mysql_select_db('mydb');

/* Reînnoie?te înregistrarile */
mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
printf ("Înregistrari reînnoite: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
?>

Exemplul de mai sus va afi?a ceva similar cu:

Înregistrari reînnoite: 10

Note

Nota: Tranzac?ii

Daca utiliza?i tranzac?ii trebuie sa apela?i mysql_affected_rows() dupa interpelarea INSERT, UPDATE sau DELETE, ?i nu dupa COMMIT.

Nota: Interpelari SELECT

Pentru a capata numarul de rânduri întoarse de un SELECT, utiliza?i mysql_num_rows().

Nota: Cheile externe în cascada

mysql_affected_rows() nu numara înregistrarile afectate implicit prin utilizarea ON DELETE CASCADE ?i/sau ON UPDATE CASCADE în constrângerile cu chei externe.

A se vedea ?i

  • mysql_num_rows() - Get number of rows in result
  • mysql_info() - Get information about the most recent query

Func?ii MySQL
mysql_client_encoding
Func?ii MySQL


Întoarce denumirea setului de caractere

mysql_affected_rows
mysql_close
Func?ii MySQL
PHP Manual

mysql_client_encoding

(PHP 4 >= 4.3.0, PHP 5)

mysql_client_encoding — Întoarce denumirea setului de caractere

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_character_set_name()

Descrierea

string mysql_client_encoding ([ resource $link_identifier = NULL ] )

Întoarce valoarea variabilei character_set din MySQL.

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Întoarce denumirea setului de caractere implicit pentru conexiunea curenta.

Exemple

Example #1 Exemplu mysql_client_encoding()

<?php
$link    = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$charset = mysql_client_encoding($link);

echo "Setul de caractere curent este: $charset\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

Setul de caractere curent este: latin1

A se vedea ?i

  • mysql_set_charset() - Sets the client character set
  • mysql_real_escape_string() - Escapes special characters in a string for use in an SQL statement

mysql_affected_rows
mysql_close
Func?ii MySQL


Închide conexiunea MySQL

mysql_client_encoding
mysql_connect
Func?ii MySQL
PHP Manual

mysql_close

(PHP 4, PHP 5)

mysql_close — Închide conexiunea MySQL

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_close()
  • PDO: Atribui?i valoarea NULL obiectului PDO

Descrierea

bool mysql_close ([ resource $link_identifier = NULL ] )

mysql_close() închide conexiunea non-persistenta catre serverul MySQL, care este asociata cu identificatorul conexiunii specificat. Daca link_identifier nu este specificat, este utilizata ultima conexiune deschisa.

Conexiunile MySQL non-persistente deschise ?i seturile de rezultate sunt automat distruse atunci când un script PHP î?i încheie execu?ia. Deci închiderea în mod explicit a conexiunilor deschise ?i eliberarea seturilor de rezultate sunt op?ionale, însa sunt recomandata. Aceasta va întoarce imediat resursele catre PHP ?i MySQL, ceea ce poate îmbunata?i performa?a. Pentru informa?ii suplimentare accesa?i eliberarea resurselor

Parametri

link_identifier

Conexiunea MySQL. Daca link identifier nu este specificat, se subîn?elege ultima referin?a deschisa cu ajutorul mysql_connect(). Daca nu este gasita sau stabilita nici o conexiune, este generata o eroare de tip E_WARNING.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Exemplu mysql_close()

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Conexiunea a e?uat: ' . mysql_error());
}
echo 'Conexiunea a fost realizata cu succes';
mysql_close($link);
?>

Exemplul de mai sus va afi?a:

Conexiunea a fost realizata cu succes

Note

Nota:

mysql_close() nu va închide conexiuni persistente create cu mysql_pconnect(). Pentru detalii suplimentare, accesa?i pagina manualului despre conexiuni persistente.

A se vedea ?i

  • mysql_connect() - Deschide o conexiune la un server MySQL
  • mysql_free_result() - Free result memory

mysql_client_encoding
mysql_connect
Func?ii MySQL


Deschide o conexiune la un server MySQL

mysql_close
mysql_create_db
Func?ii MySQL
PHP Manual

mysql_connect

(PHP 4, PHP 5)

mysql_connect — Deschide o conexiune la un server MySQL

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_connect()
  • PDO::__construct()

Descrierea

resource mysql_connect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, bool $new_link = false [, int $client_flags = 0 ]]]]] )

Deschide sau reutilizeaza o conexiune la un server MySQL.

Parametri

server

Serverul MySQL. De asemenea se poate include ?i numarul portului. De ex. "hostname:port" sau o cale catre un socket local de ex. ":/calea/spre/socket" pentru localhost.

Daca directiva PHP mysql.default_host nu este definita (implicit), atunci valoarea implicita este 'localhost:3306'. În modul SQL securizat acest parametru e ignorat ?i este utilizata întotdeauna valoarea 'localhost:3306'.

username

Numele de utilizator. Valoarea implicita este definita de mysql.default_user. În modul SQL securizat acest parametru e ignorat ?i este utilizat numele utilizatorului sub care ruleaza serverul.

password

Parola. Valoarea implicita este definita de mysql.default_password. În modul SQL securizat acest parametru e ignorat ?i este utilizata o parola vida.

new_link

Daca se efectueaza un apel repetat al mysql_connect() cu acelea?i argumente, nu se creaza o legatura noua, dar va fi întors identificatorul legaturii deja deschise. Parametrul new_link modifica acest comportament ?i indica mysql_connect() întotdeauna sa deschida o legatura noua, chiar daca mysql_connect() a fost apelat anterior cu aceia?i parametri. În modul SQL securizat acest parametru este ignorat.

client_flags

Parametrul client_flags poate fi o combina?ie a urmatoarelor constante: 128 (permite prelucrarea LOAD DATA LOCAL), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE sau MYSQL_CLIENT_INTERACTIVE. Citi?i sec?iunea despre Constante ale clientului MySQL pentru informa?ii suplimentare. În modul SQL securizat acest parametru este ignorat.

Valorile întoarse

Întoarce un identificator al legaturii MySQL în cazul succesului, sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | Aceasta func?ie va genera o eroare E_DEPRECATED.

Exemple

Example #1 Exemplu mysql_connect()

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('E?ec la conectare: ' . mysql_error());
}
echo 'Conectat cu succes';
mysql_close($link);
?>

Example #2 Exemplu mysql_connect() utilizând sintaxa hostname:port

<?php
// ne conectam la example.com ?i portul 3307
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
    die('E?ec la conectare: ' . mysql_error());
}
echo 'Conectat cu succes';
mysql_close($link);

// ne conectam la localhost la portul 3307
$link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');
if (!$link) {
    die('E?ec la conectare: ' . mysql_error());
}
echo 'Conectat cu succes';
mysql_close($link);
?>

Example #3 Exemplu mysql_connect() utilizând sintaxa ":/calea/spre/socket"

<?php
// ne conectam la localhost prin socket de ex. /tmp/mysql.sock

// varianta 1: omitem localhost
$link = mysql_connect(':/tmp/mysql', 'mysql_user', 'mysql_password');
if (!$link) {
    die('E?ec la conectare: ' . mysql_error());
}
echo 'Conectat cu succes';
mysql_close($link);

// varianta 2: cu localhost
$link = mysql_connect('localhost:/tmp/mysql.sock', 'mysql_user', 'mysql_password');
if (!$link) {
    die('E?ec la conectare: ' . mysql_error());
}
echo 'Conectat cu succes';
mysql_close($link);
?>

Note

Nota:

Atunci când specifica?i "localhost" sau "localhost:port" în calitate de server, biblioteca-client MySQL va anula aceasta ?i va încerca sa se conecteze la un socket local (?eava cu nume (named pipe) în Windows). Daca dori?i sa utiliza?i TCP/IP, utiliza?i "127.0.0.1" în loc de "localhost". Daca biblioteca-client MySQL încearca sa se conecteze la un socket local gre?it, trebuie sa stabili?i calea corecta în în configura?ia PHP ?i sa lasa?i câmpul server vid.

Nota:

Legatura catre server va fi închisa îndata ce se va încheia execu?ia script-ului, daca nu a fost închisa anterior prin apelarea explicita a func?iei mysql_close().

Nota:

Pute?i suprima mesajul de eroare în cazul e?ecului adaugând un @ înainte de denumirea func?iei.

Nota:

Eroarea "Can't create TCP/IP socket (10106)" de obicei înseamna ca directiva de configurare variables_order nu con?ine caracterul E. În Windows, daca variabilele de mediu nu sunt încarcate, va lipsi variabila SYSTEMROOT ?i PHP va avea probleme la încarcarea Winsock.

A se vedea ?i

  • mysql_pconnect() - Open a persistent connection to a MySQL server
  • mysql_close() - Închide conexiunea MySQL

mysql_close
mysql_create_db
Func?ii MySQL


Creeaza o baza de date MySQL

mysql_connect
mysql_data_seek
Func?ii MySQL
PHP Manual

mysql_create_db

(PHP 4, PHP 5)

mysql_create_db — Creeaza o baza de date MySQL

Avertizare

Aceasta func?ie a devenit învechita în PHP 4.3.0, ?i a fost eliminata în PHP 7.0.0, împreuna cu întreaga extensie MySQL originala. În locul ei trebuie utilizata extensia activ dezvoltata MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_query()
  • PDO::query()

Descrierea

bool mysql_create_db ( string $database_name [, resource $link_identifier = NULL ] )

mysql_create_db() încearca sa creeze o baza de date noua pe serverul asociat cu identificatorul conexiunii specificat.

Parametri

database_name

Denumirea bazei de date ce va fi creata.

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Un exemplu alternativ mysql_create_db()

Func?ia mysql_create_db() este învechita. Este preferabil de a utiliza mysql_query() pentru a efectua o interpelare SQL CREATE DATABASE.

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('E?ec la conectare: ' . mysql_error());
}

$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
    echo "Baza de date my_db a fost creata cu succes\n";
} else {
    echo 'Eroare la crearea bazei de date: ' . mysql_error() . "\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Baza de date my_db a fost creata cu succes

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_createdb()

Nota:

Aceasta func?ie nu va fi disponibila daca extensia MySQL a fost asamblata cu biblioteca-client MySQL 4.x.

A se vedea ?i

  • mysql_query() - Send a MySQL query
  • mysql_select_db() - Select a MySQL database

mysql_connect
mysql_data_seek
Func?ii MySQL


Move internal result pointer

mysql_create_db
mysql_db_name
Func?ii MySQL
PHP Manual

mysql_data_seek

(PHP 4, PHP 5)

mysql_data_seek — Move internal result pointer

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_data_seek()
  • PDO::FETCH_ORI_ABS

Descrierea

bool mysql_data_seek ( resource $result , int $row_number )

mysql_data_seek() moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number. The next call to a MySQL fetch function, such as mysql_fetch_assoc(), would return that row.

row_number starts at 0. The row_number should be a value in the range from 0 to mysql_num_rows() - 1. However if the result set is empty (mysql_num_rows() == 0), a seek to 0 will fail with a E_WARNING and mysql_data_seek() will return FALSE.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

row_number

The desired row number of the new result pointer.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 mysql_data_seek() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sample_db');
if (!$db_selected) {
    die('Could not select database: ' . mysql_error());
}
$query = 'SELECT last_name, first_name FROM friends';
$result = mysql_query($query);
if (!$result) {
    die('Query failed: ' . mysql_error());
}
/* fetch rows in reverse order */
for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
    if (!mysql_data_seek($result, $i)) {
        echo "Cannot seek to row $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);
?>

Note

Nota:

The function mysql_data_seek() can be used in conjunction only with mysql_query(), not with mysql_unbuffered_query().

A se vedea ?i

  • mysql_query() - Send a MySQL query
  • mysql_num_rows() - Get number of rows in result
  • mysql_fetch_row() - Get a result row as an enumerated array
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mysql_fetch_object() - Fetch a result row as an object

mysql_create_db
mysql_db_name
Func?ii MySQL


Retrieves database name from the call to mysql_list_dbs

mysql_data_seek
mysql_db_query
Func?ii MySQL
PHP Manual

mysql_db_name

(PHP 4, PHP 5)

mysql_db_name — Retrieves database name from the call to mysql_list_dbs()

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • Query: SELECT DATABASE()

Descrierea

string mysql_db_name ( resource $result , int $row [, mixed $field = NULL ] )

Retrieve the database name from a call to mysql_list_dbs().

Parametri

result

The result pointer from a call to mysql_list_dbs().

row

The index into the result set.

field

The field name.

Valorile întoarse

Returns the database name on success, and FALSE on failure. If FALSE is returned, use mysql_error() to determine the nature of the error.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | The mysql_list_dbs() function is deprecated, and emits an E_DEPRECATED level error.

Exemple

Example #1 mysql_db_name() example

<?php
error_reporting(E_ALL);

$link = mysql_connect('dbhost', 'username', 'password');
$db_list = mysql_list_dbs($link);

$i = 0;
$cnt = mysql_num_rows($db_list);
while ($i < $cnt) {
    echo mysql_db_name($db_list, $i) . "\n";
    $i++;
}
?>

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_dbname()

A se vedea ?i

  • mysql_list_dbs() - List databases available on a MySQL server
  • mysql_tablename() - Get table name of field

mysql_data_seek
mysql_db_query
Func?ii MySQL


Selects a database and executes a query on it

mysql_db_name
mysql_drop_db
Func?ii MySQL
PHP Manual

mysql_db_query

(PHP 4, PHP 5)

mysql_db_query — Selects a database and executes a query on it

Avertizare

Aceasta func?ie a devenit învechita în PHP 5.3.0, ?i a fost eliminata în PHP 7.0.0, împreuna cu întreaga extensie MySQL originala. În locul ei trebuie utilizata extensia activ dezvoltata MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_select_db() then the query
  • PDO::__construct()

Descrierea

resource mysql_db_query ( string $database , string $query [, resource $link_identifier = NULL ] )

mysql_db_query() selects a database, and executes a query on it.

Parametri

database

The name of the database that will be selected.

query

The MySQL query.

Data inside the query should be properly escaped.

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Returns a positive MySQL result resource to the query result, or FALSE on error. The function also returns TRUE/FALSE for INSERT/UPDATE/DELETE queries to indicate success/failure.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function now throws an E_DEPRECATED notice.

Exemple

Example #1 mysql_db_query() alternative example

<?php

if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
    echo 'Could not connect to mysql';
    exit;
}

if (!mysql_select_db('mysql_dbname', $link)) {
    echo 'Could not select database';
    exit;
}

$sql    = 'SELECT foo FROM bar WHERE id = 42';
$result = mysql_query($sql, $link);

if (!$result) {
    echo "DB Error, could not query the database\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_assoc($result)) {
    echo $row['foo'];
}

mysql_free_result($result);

?>

Note

Nota:

Be aware that this function does NOT switch back to the database you were connected before. In other words, you can't use this function to temporarily run a sql query on another database, you would have to manually switch back. Users are strongly encouraged to use the database.table syntax in their sql queries or mysql_select_db() instead of this function.

A se vedea ?i

  • mysql_query() - Send a MySQL query
  • mysql_select_db() - Select a MySQL database

mysql_db_name
mysql_drop_db
Func?ii MySQL


Drop (delete) a MySQL database

mysql_db_query
mysql_errno
Func?ii MySQL
PHP Manual

mysql_drop_db

(PHP 4, PHP 5)

mysql_drop_db — Drop (delete) a MySQL database

Avertizare

Aceasta func?ie a devenit învechita în PHP 4.3.0, ?i a fost eliminata în PHP 7.0.0, împreuna cu întreaga extensie MySQL originala. În locul ei trebuie utilizata extensia activ dezvoltata MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • Execute a DROP DATABASE query

Descrierea

bool mysql_drop_db ( string $database_name [, resource $link_identifier = NULL ] )

mysql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier. This function is deprecated, it is preferable to use mysql_query() to issue an sql DROP DATABASE statement instead.

Parametri

database_name

The name of the database that will be deleted.

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 mysql_drop_db() alternative example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

$sql = 'DROP DATABASE my_db';
if (mysql_query($sql, $link)) {
    echo "Database my_db was successfully dropped\n";
} else {
    echo 'Error dropping database: ' . mysql_error() . "\n";
}
?>

Note

Avertizare

This function will not be available if the MySQL extension was built against a MySQL 4.x client library.

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_dropdb()

A se vedea ?i

  • mysql_query() - Send a MySQL query

mysql_db_query
mysql_errno
Func?ii MySQL


Returns the numerical value of the error message from previous MySQL operation

mysql_drop_db
mysql_error
Func?ii MySQL
PHP Manual

mysql_errno

(PHP 4, PHP 5)

mysql_errno — Returns the numerical value of the error message from previous MySQL operation

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_errno()
  • PDO::errorCode()

Descrierea

int mysql_errno ([ resource $link_identifier = NULL ] )

Returns the error number from the last MySQL function.

Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Returns the error number from the last MySQL function, or 0 (zero) if no error occurred.

Exemple

Example #1 mysql_errno() example

<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");

if (!mysql_select_db("nonexistentdb", $link)) {
    echo mysql_errno($link) . ": " . mysql_error($link). "\n";
}

mysql_select_db("kossu", $link);
if (!mysql_query("SELECT * FROM nonexistenttable", $link)) {
    echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

A se vedea ?i

  • mysql_error() - Returns the text of the error message from previous MySQL operation
  • » MySQL error codes

mysql_drop_db
mysql_error
Func?ii MySQL


Returns the text of the error message from previous MySQL operation

mysql_errno
mysql_escape_string
Func?ii MySQL
PHP Manual

mysql_error

(PHP 4, PHP 5)

mysql_error — Returns the text of the error message from previous MySQL operation

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_error()
  • PDO::errorInfo()

Descrierea

string mysql_error ([ resource $link_identifier = NULL ] )

Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Returns the error text from the last MySQL function, or '' (empty string) if no error occurred.

Exemple

Example #1 mysql_error() example

<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");

mysql_select_db("nonexistentdb", $link);
echo mysql_errno($link) . ": " . mysql_error($link). "\n";

mysql_select_db("kossu", $link);
mysql_query("SELECT * FROM nonexistenttable", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

A se vedea ?i

  • mysql_errno() - Returns the numerical value of the error message from previous MySQL operation
  • » MySQL error codes

mysql_errno
mysql_escape_string
Func?ii MySQL


Escapeaza un string pentru fi folosit in mysql_query

mysql_error
mysql_fetch_array
Func?ii MySQL
PHP Manual

mysql_escape_string

(PHP 4 >= 4.0.3, PHP 5)

mysql_escape_string — Escapeaza un string pentru fi folosit in mysql_query

Avertizare

Aceasta func?ie a devenit învechita în PHP 4.3.0, ?i a fost eliminata în PHP 7.0.0, împreuna cu întreaga extensie MySQL originala. În locul ei trebuie utilizata extensia activ dezvoltata MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_escape_string()
  • PDO::quote()

Descrierea

string mysql_escape_string ( string $unescaped_string )

Aceasta functie va escapa variabila unescaped_string, asa incat sa poata fi folosita in functia mysql_query() intr-un mod securizat. Aceasta functie este va fi scoasa din uz.

Aceasta functie este identica cu mysql_real_escape_string() cu exceptia ca mysql_real_escape_string() se foloseste de conexiunea curenta si escapeaza string-ul in fuctie de encodingul (charset-ul) setat. mysql_escape_string() nu ia ca argument conexiunea curenta si nu respecta encodingul setat la momentul respectiv.

Parametri

unescaped_string

String-ul ce urmeaza sa fie escapat.

Valorile întoarse

Returneaza string-ul escapat.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Aceasta functie returneaza o notificare de tip E_DEPRECATED.
4.3.0 | Aceasta functie este scoasa din uz, nu o mai folositi. In locul ei, folositi mysql_real_escape_string().

Exemple

Example #1 exemplu de uz al functiei mysql_escape_string()

<?php
$item = "Zak's Laptop";
$escaped_item = mysql_escape_string($item);
printf("Escaped string: %s\n", $escaped_item);
?>

Exemplul de mai sus va afi?a:

Escaped string: Zak\'s Laptop

Note

Nota:

mysql_escape_string() nu escapeaza caracterele % si _.

A se vedea ?i

  • mysql_real_escape_string() - Escapes special characters in a string for use in an SQL statement
  • addslashes() - Quote string with slashes
  • Directiva magic_quotes_gpc.

mysql_error
mysql_fetch_array
Func?ii MySQL


Fetch a result row as an associative array, a numeric array, or both

mysql_escape_string
mysql_fetch_assoc
Func?ii MySQL
PHP Manual

mysql_fetch_array

(PHP 4, PHP 5)

mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_fetch_array()
  • PDOStatement::fetch()

Descrierea

array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )

Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

result_type

The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.

Valorile întoarse

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).

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 the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name.

Exemple

Example #1 Query with aliased duplicate field names

SELECT table1.field AS foo, table2.field AS bar FROM table1, table2

Example #2 mysql_fetch_array() with MYSQL_NUM

<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
    die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    printf("ID: %s  Name: %s", $row[0], $row[1]);
}

mysql_free_result($result);
?>

Example #3 mysql_fetch_array() with MYSQL_ASSOC

<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
    die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    printf("ID: %s  Name: %s", $row["id"], $row["name"]);
}

mysql_free_result($result);
?>

Example #4 mysql_fetch_array() with MYSQL_BOTH

<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
    die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
    printf ("ID: %s  Name: %s", $row[0], $row["name"]);
}

mysql_free_result($result);
?>

Note

Nota: Performance

An important thing to note is that using mysql_fetch_array() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value.

Nota: Numele câmpurilor întoarse de aceasta func?ie sunt sensibile la literele majuscule/minuscule.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

A se vedea ?i

  • mysql_fetch_row() - Get a result row as an enumerated array
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_data_seek() - Move internal result pointer
  • mysql_query() - Send a MySQL query

mysql_escape_string
mysql_fetch_assoc
Func?ii MySQL


Fetch a result row as an associative array

mysql_fetch_array
mysql_fetch_field
Func?ii MySQL
PHP Manual

mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc — Fetch a result row as an associative array

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_fetch_assoc()
  • PDOStatement::fetch(PDO::FETCH_ASSOC)

Descrierea

array mysql_fetch_assoc ( resource $result )

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

Valorile întoarse

Returns an associative array of strings 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 either need to access the result with numeric indices by using mysql_fetch_row() or add alias names. See the example at the mysql_fetch_array() description about aliases.

Exemple

Example #1 An expanded mysql_fetch_assoc() example

<?php

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");

if (!$conn) {
    echo "Unable to connect to DB: " . mysql_error();
    exit;
}

if (!mysql_select_db("mydbname")) {
    echo "Unable to select mydbname: " . mysql_error();
    exit;
}

$sql = "SELECT id as userid, fullname, userstatus
        FROM   sometable
        WHERE  userstatus = 1";

$result = mysql_query($sql);

if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
//       then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

mysql_free_result($result);

?>

Note

Nota: Performance

An important thing to note is that using mysql_fetch_assoc() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value.

Nota: Numele câmpurilor întoarse de aceasta func?ie sunt sensibile la literele majuscule/minuscule.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

A se vedea ?i

  • mysql_fetch_row() - Get a result row as an enumerated array
  • mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mysql_data_seek() - Move internal result pointer
  • mysql_query() - Send a MySQL query
  • mysql_error() - Returns the text of the error message from previous MySQL operation

mysql_fetch_array
mysql_fetch_field
Func?ii MySQL


Get column information from a result and return as an object

mysql_fetch_assoc
mysql_fetch_lengths
Func?ii MySQL
PHP Manual

mysql_fetch_field

(PHP 4, PHP 5)

mysql_fetch_field — Get column information from a result and return as an object

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_fetch_field()
  • PDOStatement::getColumnMeta()

Descrierea

object mysql_fetch_field ( resource $result [, int $field_offset = 0 ] )

Returns an object containing field information. This function can be used to obtain information about fields in the provided query result.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_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.

Valorile întoarse

Returns an object containing field information. The properties of the object are:

  • name - column name
  • table - name of the table the column belongs to, which is the alias name if one is defined
  • 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 a 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

Exemple

Example #1 mysql_fetch_field() example

<?php
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$conn) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('database');
$result = mysql_query('select * from table');
if (!$result) {
    die('Query failed: ' . mysql_error());
}
/* get column metadata */
$i = 0;
while ($i < mysql_num_fields($result)) {
    echo "Information for column $i:<br />\n";
    $meta = mysql_fetch_field($result, $i);
    if (!$meta) {
        echo "No information available<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);
?>

Note

Nota: Numele câmpurilor întoarse de aceasta func?ie sunt sensibile la literele majuscule/minuscule.

Nota:

If field or tablenames are aliased in the SQL query the aliased name will be returned. The original name can be retrieved for instance by using mysqli_result::fetch_field().

A se vedea ?i

  • mysql_field_seek() - Stabile?te indicatorul rezultatului la deplasamentul câmpului specificat

mysql_fetch_assoc
mysql_fetch_lengths
Func?ii MySQL


Get the length of each output in a result

mysql_fetch_field
mysql_fetch_object
Func?ii MySQL
PHP Manual

mysql_fetch_lengths

(PHP 4, PHP 5)

mysql_fetch_lengths — Get the length of each output in a result

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_fetch_lengths()
  • PDOStatement::getColumnMeta()

Descrierea

array mysql_fetch_lengths ( resource $result )

Returns an array that corresponds to the lengths of each field in the last row fetched by MySQL.

mysql_fetch_lengths() stores the lengths of
each result column in the last row returned by
mysql_fetch_row(),
mysql_fetch_assoc(),
mysql_fetch_array(), and
mysql_fetch_object() in an array, starting at
offset 0.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

Valorile întoarse

An array of lengths on success sau FALSE în cazul e?ecului.

Exemple

Example #1 A mysql_fetch_lengths() example

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row     = mysql_fetch_assoc($result);
$lengths = mysql_fetch_lengths($result);

print_r($row);
print_r($lengths);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [id] => 42
    [email] => user@example.com
)
Array
(
    [0] => 2
    [1] => 16
)

A se vedea ?i

  • mysql_field_len() - Returns the length of the specified field
  • mysql_fetch_row() - Get a result row as an enumerated array
  • strlen() - Get string length

mysql_fetch_field
mysql_fetch_object
Func?ii MySQL


Fetch a result row as an object

mysql_fetch_lengths
mysql_fetch_row
Func?ii MySQL
PHP Manual

mysql_fetch_object

(PHP 4, PHP 5)

mysql_fetch_object — Fetch a result row as an object

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_fetch_object()
  • PDOStatement::fetch(PDO::FETCH_OBJ)

Descrierea

object mysql_fetch_object ( resource $result [, string $class_name [, array $params ]] )

Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

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.

Valorile întoarse

Returns an object with string properties that correspond to the fetched row, or FALSE if there are no more rows.

Exemple

Example #1 mysql_fetch_object() example

<?php
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
mysql_free_result($result);
?>

Example #2 mysql_fetch_object() example

<?php
class foo {
    public $name;
}

mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");

$result = mysql_query("select name from mytable limit 1");
$obj = mysql_fetch_object($result, 'foo');
var_dump($obj);
?>

Note

Nota: Performance

Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant).

Nota:

mysql_fetch_object() is similar to mysql_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).

Nota: Numele câmpurilor întoarse de aceasta func?ie sunt sensibile la literele majuscule/minuscule.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

A se vedea ?i

  • mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_fetch_row() - Get a result row as an enumerated array
  • mysql_data_seek() - Move internal result pointer
  • mysql_query() - Send a MySQL query

mysql_fetch_lengths
mysql_fetch_row
Func?ii MySQL


Get a result row as an enumerated array

mysql_fetch_object
mysql_field_flags
Func?ii MySQL
PHP Manual

mysql_fetch_row

(PHP 4, PHP 5)

mysql_fetch_row — Get a result row as an enumerated array

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_fetch_row()
  • PDOStatement::fetch(PDO::FETCH_NUM)

Descrierea

array mysql_fetch_row ( resource $result )

Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

Valorile întoarse

Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there are no more rows.

mysql_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.

Exemple

Example #1 Fetching one row with mysql_fetch_row()

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value
?>

Note

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

A se vedea ?i

  • mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_fetch_object() - Fetch a result row as an object
  • mysql_data_seek() - Move internal result pointer
  • mysql_fetch_lengths() - Get the length of each output in a result
  • mysql_result() - Get result data

mysql_fetch_object
mysql_field_flags
Func?ii MySQL


Get the flags associated with the specified field in a result

mysql_fetch_row
mysql_field_len
Func?ii MySQL
PHP Manual

mysql_field_flags

(PHP 4, PHP 5)

mysql_field_flags — Get the flags associated with the specified field in a result

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_fetch_field_direct() [flags]
  • PDOStatement::getColumnMeta() [flags]

Descrierea

string mysql_field_flags ( resource $result , int $field_offset )

mysql_field_flags() returns the field flags of the specified field. The flags are reported as a single word per flag separated by a single space, so that you can split the returned value using explode().

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

field_offset

Deplasamentul numeric al câmpului. field_offset începe de la 0. Daca field_offset nu exista, se genereaza de asemenea o eroare de nivel E_WARNING.

Valorile întoarse

Returns a string of flags associated with the result sau FALSE în cazul e?ecului.

The following flags are reported, if your version of MySQL is current enough to support them: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment" and "timestamp".

Exemple

Example #1 A mysql_field_flags() example

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$flags = mysql_field_flags($result, 0);

echo $flags;
print_r(explode(' ', $flags));
?>

Exemplul de mai sus va afi?a ceva similar cu:

not_null primary_key auto_increment
Array
(
    [0] => not_null
    [1] => primary_key
    [2] => auto_increment
)

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_fieldflags()

A se vedea ?i

  • mysql_field_type() - Get the type of the specified field in a result
  • mysql_field_len() - Returns the length of the specified field

mysql_fetch_row
mysql_field_len
Func?ii MySQL


Returns the length of the specified field

mysql_field_flags
mysql_field_name
Func?ii MySQL
PHP Manual

mysql_field_len

(PHP 4, PHP 5)

mysql_field_len — Returns the length of the specified field

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_fetch_field_direct() [length]
  • PDOStatement::getColumnMeta() [len]

Descrierea

int mysql_field_len ( resource $result , int $field_offset )

mysql_field_len() returns the length of the specified field.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

field_offset

Deplasamentul numeric al câmpului. field_offset începe de la 0. Daca field_offset nu exista, se genereaza de asemenea o eroare de nivel E_WARNING.

Valorile întoarse

The length of the specified field index on success sau FALSE în cazul e?ecului.

Exemple

Example #1 mysql_field_len() example

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}

// Will get the length of the id field as specified in the database
// schema.
$length = mysql_field_len($result, 0);
echo $length;
?>

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_fieldlen()

A se vedea ?i

  • mysql_fetch_lengths() - Get the length of each output in a result
  • strlen() - Get string length

mysql_field_flags
mysql_field_name
Func?ii MySQL


Get the name of the specified field in a result

mysql_field_len
mysql_field_seek
Func?ii MySQL
PHP Manual

mysql_field_name

(PHP 4, PHP 5)

mysql_field_name — Get the name of the specified field in a result

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_fetch_field_direct() [name] or [orgname]
  • PDOStatement::getColumnMeta() [name]

Descrierea

string mysql_field_name ( resource $result , int $field_offset )

mysql_field_name() returns the name of the specified field index.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

field_offset

Deplasamentul numeric al câmpului. field_offset începe de la 0. Daca field_offset nu exista, se genereaza de asemenea o eroare de nivel E_WARNING.

Valorile întoarse

The name of the specified field index on success sau FALSE în cazul e?ecului.

Exemple

Example #1 mysql_field_name() example

<?php
/* The users table consists of three fields:
 *   user_id
 *   username
 *   password.
 */
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'mydb';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
    die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from users', $link);

echo mysql_field_name($res, 0) . "\n";
echo mysql_field_name($res, 2);
?>

Exemplul de mai sus va afi?a:

user_id
password

Note

Nota: Numele câmpurilor întoarse de aceasta func?ie sunt sensibile la literele majuscule/minuscule.

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_fieldname()

A se vedea ?i

  • mysql_field_type() - Get the type of the specified field in a result
  • mysql_field_len() - Returns the length of the specified field

mysql_field_len
mysql_field_seek
Func?ii MySQL


Stabile?te indicatorul rezultatului la deplasamentul câmpului specificat

mysql_field_name
mysql_field_table
Func?ii MySQL
PHP Manual

mysql_field_seek

(PHP 4, PHP 5)

mysql_field_seek — Stabile?te indicatorul rezultatului la deplasamentul câmpului specificat

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_field_seek()
  • PDOStatement::fetch() utilizând parametrii cursor_orientation ?i offset

Descrierea

bool mysql_field_seek ( resource $result , int $field_offset )

Trece la deplasamentul câmpului specificat. Daca urmatorul apel la mysql_fetch_field() nu include un deplasament al câmpului, deplasamentul câmpului specificat în mysql_field_seek() va fi întors.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

field_offset

Deplasamentul numeric al câmpului. field_offset începe de la 0. Daca field_offset nu exista, se genereaza de asemenea o eroare de nivel E_WARNING.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • mysql_fetch_field() - Get column information from a result and return as an object

mysql_field_name
mysql_field_table
Func?ii MySQL


Get name of the table the specified field is in

mysql_field_seek
mysql_field_type
Func?ii MySQL
PHP Manual

mysql_field_table

(PHP 4, PHP 5)

mysql_field_table — Get name of the table the specified field is in

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_fetch_field_direct() [table] or [orgtable]
  • PDOStatement::getColumnMeta() [table]

Descrierea

string mysql_field_table ( resource $result , int $field_offset )

Returns the name of the table that the specified field is in.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

field_offset

Deplasamentul numeric al câmpului. field_offset începe de la 0. Daca field_offset nu exista, se genereaza de asemenea o eroare de nivel E_WARNING.

Valorile întoarse

The name of the table on success.

Exemple

Example #1 A mysql_field_table() example

<?php

$query = "SELECT account.*, country.* FROM account, country WHERE country.name = 'Portugal' AND account.country_id = country.id";

// get the result from the DB
$result = mysql_query($query);

// Lists the table name and then the field name
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";
}

?>

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_fieldtable()

A se vedea ?i

  • mysql_list_tables() - List tables in a MySQL database

mysql_field_seek
mysql_field_type
Func?ii MySQL


Get the type of the specified field in a result

mysql_field_table
mysql_free_result
Func?ii MySQL
PHP Manual

mysql_field_type

(PHP 4, PHP 5)

mysql_field_type — Get the type of the specified field in a result

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_fetch_field_direct() [type]
  • PDOStatement::getColumnMeta() [driver:decl_type] or [pdo_type]

Descrierea

string mysql_field_type ( resource $result , int $field_offset )

mysql_field_type() is similar to the mysql_field_name() function. The arguments are identical, but the field type is returned instead.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

field_offset

Deplasamentul numeric al câmpului. field_offset începe de la 0. Daca field_offset nu exista, se genereaza de asemenea o eroare de nivel E_WARNING.

Valorile întoarse

The returned field type will be one of "int", "real", "string", "blob", and others as detailed in the » MySQL documentation.

Exemple

Example #1 mysql_field_type() example

<?php
mysql_connect("localhost", "mysql_username", "mysql_password");
mysql_select_db("mysql");
$result = mysql_query("SELECT * FROM func");
$fields = mysql_num_fields($result);
$rows   = mysql_num_rows($result);
$table  = mysql_field_table($result, 0);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " record(s)\n";
echo "The table has the following fields:\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";
}
mysql_free_result($result);
mysql_close();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Your 'func' table has 4 fields and 1 record(s)
The table has the following fields:
string name 64 not_null primary_key binary
int ret 1 not_null
string dl 128 not_null
string type 9 not_null enum

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_fieldtype()

A se vedea ?i

  • mysql_field_name() - Get the name of the specified field in a result
  • mysql_field_len() - Returns the length of the specified field

mysql_field_table
mysql_free_result
Func?ii MySQL


Free result memory

mysql_field_type
mysql_get_client_info
Func?ii MySQL
PHP Manual

mysql_free_result

(PHP 4, PHP 5)

mysql_free_result — Free result memory

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_free_result()
  • Assign the value of NULL to the PDO object, or PDOStatement::closeCursor()

Descrierea

bool mysql_free_result ( resource $result )

mysql_free_result() will free all memory associated with the result identifier result.

mysql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

If a non-resource is used for the result, an error of level E_WARNING will be emitted. It's worth noting that mysql_query() only returns a resource for SELECT, SHOW, EXPLAIN, and DESCRIBE queries.

Exemple

Example #1 A mysql_free_result() example

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
/* Use the result, assuming we're done with it afterwards */
$row = mysql_fetch_assoc($result);

/* Now we free up the result and continue on with our script */
mysql_free_result($result);

echo $row['id'];
echo $row['email'];
?>

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_freeresult()

A se vedea ?i

  • mysql_query() - Send a MySQL query
  • is_resource() - Determina daca o variabila este o resursa

mysql_field_type
mysql_get_client_info
Func?ii MySQL


Ob?ine informa?ia clientului MySQL

mysql_free_result
mysql_get_host_info
Func?ii MySQL
PHP Manual

mysql_get_client_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_client_info — Ob?ine informa?ia clientului MySQL

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_get_client_info()
  • PDO::getAttribute(PDO::ATTR_CLIENT_VERSION)

Descrierea

string mysql_get_client_info ( void )

mysql_get_client_info() întoarce un string care reprezinta versiunea bibliotecii client.

Valorile întoarse

Versiunea clientului MySQL.

Exemple

Example #1 Exemplu mysql_get_client_info()

<?php
printf("MySQL client info: %s\n", mysql_get_client_info());
?>

Exemplul de mai sus va afi?a ceva similar cu:

MySQL client info: 3.23.39

A se vedea ?i

  • mysql_get_host_info() - Get MySQL host info
  • mysql_get_proto_info() - Get MySQL protocol info
  • mysql_get_server_info() - Get MySQL server info

mysql_free_result
mysql_get_host_info
Func?ii MySQL


Get MySQL host info

mysql_get_client_info
mysql_get_proto_info
Func?ii MySQL
PHP Manual

mysql_get_host_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_host_info — Get MySQL host info

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_get_host_info()
  • PDO::getAttribute(PDO::ATTR_CONNECTION_STATUS)

Descrierea

string mysql_get_host_info ([ resource $link_identifier = NULL ] )

Describes the type of connection in use for the connection, including the server host name.

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Returns a string describing the type of MySQL connection in use for the connection sau FALSE în cazul e?ecului.

Exemple

Example #1 mysql_get_host_info() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
printf("MySQL host info: %s\n", mysql_get_host_info());
?>

Exemplul de mai sus va afi?a ceva similar cu:

MySQL host info: Localhost via UNIX socket

A se vedea ?i

  • mysql_get_client_info() - Ob?ine informa?ia clientului MySQL
  • mysql_get_proto_info() - Get MySQL protocol info
  • mysql_get_server_info() - Get MySQL server info

mysql_get_client_info
mysql_get_proto_info
Func?ii MySQL


Get MySQL protocol info

mysql_get_host_info
mysql_get_server_info
Func?ii MySQL
PHP Manual

mysql_get_proto_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_proto_info — Get MySQL protocol info

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_get_proto_info()

Descrierea

int mysql_get_proto_info ([ resource $link_identifier = NULL ] )

Retrieves the MySQL protocol.

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Returns the MySQL protocol on success sau FALSE în cazul e?ecului.

Exemple

Example #1 mysql_get_proto_info() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
printf("MySQL protocol version: %s\n", mysql_get_proto_info());
?>

Exemplul de mai sus va afi?a ceva similar cu:

MySQL protocol version: 10

A se vedea ?i

  • mysql_get_client_info() - Ob?ine informa?ia clientului MySQL
  • mysql_get_host_info() - Get MySQL host info
  • mysql_get_server_info() - Get MySQL server info

mysql_get_host_info
mysql_get_server_info
Func?ii MySQL


Get MySQL server info

mysql_get_proto_info
mysql_info
Func?ii MySQL
PHP Manual

mysql_get_server_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_server_info — Get MySQL server info

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_get_server_info()
  • PDO::getAttribute(PDO::ATTR_SERVER_VERSION)

Descrierea

string mysql_get_server_info ([ resource $link_identifier = NULL ] )

Retrieves the MySQL server version.

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Returns the MySQL server version on success sau FALSE în cazul e?ecului.

Exemple

Example #1 mysql_get_server_info() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
printf("MySQL server version: %s\n", mysql_get_server_info());
?>

Exemplul de mai sus va afi?a ceva similar cu:

MySQL server version: 4.0.1-alpha

A se vedea ?i

  • mysql_get_client_info() - Ob?ine informa?ia clientului MySQL
  • mysql_get_host_info() - Get MySQL host info
  • mysql_get_proto_info() - Get MySQL protocol info
  • phpversion() - Gets the current PHP version

mysql_get_proto_info
mysql_info
Func?ii MySQL


Get information about the most recent query

mysql_get_server_info
mysql_insert_id
Func?ii MySQL
PHP Manual

mysql_info

(PHP 4 >= 4.3.0, PHP 5)

mysql_info — Get information about the most recent query

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_info()

Descrierea

string mysql_info ([ resource $link_identifier = NULL ] )

Returns detailed information about the last query.

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Returns information about the statement on success, or FALSE on failure. See the example below for which statements provide information, and what the returned value may look like. Statements that are not listed will return FALSE.

Exemple

Example #1 Relevant MySQL Statements

Statements that return string values. The numbers are only for illustrating purpose; their values will correspond to the query.

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

Note

Nota:

mysql_info() returns a non-FALSE value for the INSERT ... VALUES statement only if multiple value lists are specified in the statement.

A se vedea ?i

  • mysql_affected_rows() - Ob?ine numarul de rânduri afectate de precedenta opera?iune MySQL
  • mysql_insert_id() - Get the ID generated in the last query
  • mysql_stat() - Get current system status

mysql_get_server_info
mysql_insert_id
Func?ii MySQL


Get the ID generated in the last query

mysql_info
mysql_list_dbs
Func?ii MySQL
PHP Manual

mysql_insert_id

(PHP 4, PHP 5)

mysql_insert_id — Get the ID generated in the last query

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_insert_id()
  • PDO::lastInsertId()

Descrierea

int mysql_insert_id ([ resource $link_identifier = NULL ] )

Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.

Exemple

Example #1 mysql_insert_id() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>

Note

Precautie

mysql_insert_id() will convert the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query. For more information about PHP's maximum integer values, please see the integer documentation.

Nota:

Because mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.

Nota:

The value of the MySQL SQL function LAST_INSERT_ID() always contains the most recently generated AUTO_INCREMENT value, and is not reset between queries.

A se vedea ?i

  • mysql_query() - Send a MySQL query
  • mysql_info() - Get information about the most recent query

mysql_info
mysql_list_dbs
Func?ii MySQL


List databases available on a MySQL server

mysql_insert_id
mysql_list_fields
Func?ii MySQL
PHP Manual

mysql_list_dbs

(PHP 4, PHP 5)

mysql_list_dbs — List databases available on a MySQL server

Avertizare

Aceasta func?ie a devenit învechita în PHP 5.4.0, ?i a fost eliminata în PHP 7.0.0, împreuna cu întreaga extensie MySQL originala. În locul ei trebuie utilizata extensia activ dezvoltata MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • SQL Query: SHOW DATABASES

Descrierea

resource mysql_list_dbs ([ resource $link_identifier = NULL ] )

Returns a result pointer containing the databases available from the current mysql daemon.

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Returns a result pointer resource on success, or FALSE on failure. Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

Exemple

Example #1 mysql_list_dbs() example

<?php
// Usage without mysql_list_dbs()
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$res = mysql_query("SHOW DATABASES");

while ($row = mysql_fetch_assoc($res)) {
    echo $row['Database'] . "\n";
}

// Deprecated as of PHP 5.4.0
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);

while ($row = mysql_fetch_object($db_list)) {
     echo $row->Database . "\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

database1
database2
database3

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_listdbs()

A se vedea ?i

  • mysql_db_name() - Retrieves database name from the call to mysql_list_dbs
  • mysql_select_db() - Select a MySQL database

mysql_insert_id
mysql_list_fields
Func?ii MySQL


List MySQL table fields

mysql_list_dbs
mysql_list_processes
Func?ii MySQL
PHP Manual

mysql_list_fields

(PHP 4, PHP 5)

mysql_list_fields — List MySQL table fields

Avertizare

Aceasta func?ie a devenit învechita în PHP 5.4.0, ?i a fost eliminata în PHP 7.0.0, împreuna cu întreaga extensie MySQL originala. În locul ei trebuie utilizata extensia activ dezvoltata MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • SQL Query: SHOW COLUMNS FROM sometable

Descrierea

resource mysql_list_fields ( string $database_name , string $table_name [, resource $link_identifier = NULL ] )

Retrieves information about the given table name.

This function is deprecated. It is preferable to use mysql_query() to issue an SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead.

Parametri

database_name

The name of the database that's being queried.

table_name

The name of the table that's being queried.

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

A result pointer resource on success, or FALSE on failure.

The returned result can be used with mysql_field_flags(),
mysql_field_len(),
mysql_field_name() ?i
mysql_field_type().

Exemple

Example #1 Alternate to deprecated mysql_list_fields()

<?php
$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        print_r($row);
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [Field] => id
    [Type] => int(7)
    [Null] =>
    [Key] => PRI
    [Default] =>
    [Extra] => auto_increment
)
Array
(
    [Field] => email
    [Type] => varchar(100)
    [Null] =>
    [Key] =>
    [Default] =>
    [Extra] =>
)

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_listfields()

A se vedea ?i

  • mysql_field_flags() - Get the flags associated with the specified field in a result
  • mysql_info() - Get information about the most recent query

mysql_list_dbs
mysql_list_processes
Func?ii MySQL


List MySQL processes

mysql_list_fields
mysql_list_tables
Func?ii MySQL
PHP Manual

mysql_list_processes

(PHP 4 >= 4.3.0, PHP 5)

mysql_list_processes — List MySQL processes

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_thread_id()

Descrierea

resource mysql_list_processes ([ resource $link_identifier = NULL ] )

Retrieves the current MySQL server threads.

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

A result pointer resource on success sau FALSE în cazul e?ecului.

Exemple

Example #1 mysql_list_processes() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

$result = mysql_list_processes($link);
while ($row = mysql_fetch_assoc($result)){
    printf("%s %s %s %s %s\n", $row["Id"], $row["Host"], $row["db"],
        $row["Command"], $row["Time"]);
}
mysql_free_result($result);
?>

Exemplul de mai sus va afi?a ceva similar cu:

1 localhost test Processlist 0
4 localhost mysql sleep 5

A se vedea ?i

  • mysql_thread_id() - Return the current thread ID
  • mysql_stat() - Get current system status

mysql_list_fields
mysql_list_tables
Func?ii MySQL


List tables in a MySQL database

mysql_list_processes
mysql_num_fields
Func?ii MySQL
PHP Manual

mysql_list_tables

(PHP 4, PHP 5)

mysql_list_tables — List tables in a MySQL database

Avertizare

Aceasta func?ie a devenit învechita în PHP 4.3.0, ?i a fost eliminata în PHP 7.0.0, împreuna cu întreaga extensie MySQL originala. În locul ei trebuie utilizata extensia activ dezvoltata MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • SQL Query: SHOW TABLES FROM dbname

Descrierea

resource mysql_list_tables ( string $database [, resource $link_identifier = NULL ] )

Retrieves a list of table names from a MySQL database.

This function is deprecated. It is preferable to use mysql_query() to issue an SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead.

Parametri

database

The name of the database

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

A result pointer resource on success sau FALSE în cazul e?ecului.

Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

Istoricul schimbarilor

Versiune | Descriere
4.3.7 | This function became deprecated.

Exemple

Example #1 mysql_list_tables() alternative example

<?php
$dbname = 'mysql_dbname';

if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
    echo 'Could not connect to mysql';
    exit;
}

$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);

if (!$result) {
    echo "DB Error, could not list tables\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_row($result)) {
    echo "Table: {$row[0]}\n";
}

mysql_free_result($result);
?>

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_listtables()

A se vedea ?i

  • mysql_list_dbs() - List databases available on a MySQL server
  • mysql_tablename() - Get table name of field

mysql_list_processes
mysql_num_fields
Func?ii MySQL


Get number of fields in result

mysql_list_tables
mysql_num_rows
Func?ii MySQL
PHP Manual

mysql_num_fields

(PHP 4, PHP 5)

mysql_num_fields — Get number of fields in result

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_num_fields()
  • PDOStatement::columnCount()

Descrierea

int mysql_num_fields ( resource $result )

Retrieves the number of fields from a query.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

Valorile întoarse

Returns the number of fields in the result set resource on success sau FALSE în cazul e?ecului.

Exemple

Example #1 A mysql_num_fields() example

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}

/* returns 2 because id,email === two fields */
echo mysql_num_fields($result);
?>

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_numfields()

A se vedea ?i

  • mysql_select_db() - Select a MySQL database
  • mysql_query() - Send a MySQL query
  • mysql_fetch_field() - Get column information from a result and return as an object
  • mysql_num_rows() - Get number of rows in result

mysql_list_tables
mysql_num_rows
Func?ii MySQL


Get number of rows in result

mysql_num_fields
mysql_pconnect
Func?ii MySQL
PHP Manual

mysql_num_rows

(PHP 4, PHP 5)

mysql_num_rows — Get number of rows in result

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_num_rows()
  • mysqli_stmt_num_rows()
  • PDOStatement::rowCount()

Descrierea

int mysql_num_rows ( resource $result )

Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

Valorile întoarse

The number of rows in a result set on success sau FALSE în cazul e?ecului.

Exemple

Example #1 mysql_num_rows() example

<?php

$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);

echo "$num_rows Rows\n";

?>

Note

Nota:

If you use mysql_unbuffered_query(), mysql_num_rows() will not return the correct value until all the rows in the result set have been retrieved.

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_numrows()

A se vedea ?i

  • mysql_affected_rows() - Ob?ine numarul de rânduri afectate de precedenta opera?iune MySQL
  • mysql_connect() - Deschide o conexiune la un server MySQL
  • mysql_data_seek() - Move internal result pointer
  • mysql_select_db() - Select a MySQL database
  • mysql_query() - Send a MySQL query

mysql_num_fields
mysql_pconnect
Func?ii MySQL


Open a persistent connection to a MySQL server

mysql_num_rows
mysql_ping
Func?ii MySQL
PHP Manual

mysql_pconnect

(PHP 4, PHP 5)

mysql_pconnect — Open a persistent connection to a MySQL server

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_connect() with p: host prefix
  • PDO::__construct() with PDO::ATTR_PERSISTENT as a driver option

Descrierea

resource mysql_pconnect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, int $client_flags = 0 ]]]] )

Establishes a persistent connection to a MySQL server.

mysql_pconnect() acts very much like mysql_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 (mysql_close() will not close links established by mysql_pconnect()).

This type of link is therefore called 'persistent'.

Parametri

server

The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost.

If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'

username

The username. Default value is the name of the user that owns the server process.

password

The password. Default value is an empty password.

client_flags

The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE.

Valorile întoarse

Returns a MySQL persistent link identifier on success, or FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | This function will generate an E_DEPRECATED error.

Note

Nota:

Note, that these kind of links only work if you are using a module version of PHP. See the Persistent Database Connections section for more information.

Avertizare

Using persistent connections can require a bit of tuning of your Apache and MySQL configurations to ensure that you do not exceed the number of connections allowed by MySQL.

Nota:

You can suppress the error message on failure by prepending a @ to the function name.

A se vedea ?i

  • mysql_connect() - Deschide o conexiune la un server MySQL
  • Persistent Database Connections

mysql_num_rows
mysql_ping
Func?ii MySQL


Ping a server connection or reconnect if there is no connection

mysql_pconnect
mysql_query
Func?ii MySQL
PHP Manual

mysql_ping

(PHP 4 >= 4.3.0, PHP 5)

mysql_ping — Ping a server connection or reconnect if there is no connection

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_ping()

Descrierea

bool mysql_ping ([ resource $link_identifier = NULL ] )

Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted. This function can be used by scripts that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary.

Nota:

Automatic reconnection is disabled by default in versions of MySQL >= 5.0.3.

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Returns TRUE if the connection to the server MySQL server is working, otherwise FALSE.

Exemple

Example #1 A mysql_ping() example

<?php
set_time_limit(0);

$conn = mysql_connect('localhost', 'mysqluser', 'mypass');
$db   = mysql_select_db('mydb');

/* Assuming this query will take a long time */
$result = mysql_query($sql);
if (!$result) {
    echo 'Query #1 failed, exiting.';
    exit;
}

/* Make sure the connection is still alive, if not, try to reconnect */
if (!mysql_ping($conn)) {
    echo 'Lost connection, exiting after query #1';
    exit;
}
mysql_free_result($result);

/* So the connection is still alive, let's run another query */
$result2 = mysql_query($sql2);
?>

A se vedea ?i

  • mysql_thread_id() - Return the current thread ID
  • mysql_list_processes() - List MySQL processes

mysql_pconnect
mysql_query
Func?ii MySQL


Send a MySQL query

mysql_ping
mysql_real_escape_string
Func?ii MySQL
PHP Manual

mysql_query

(PHP 4, PHP 5)

mysql_query — Send a MySQL query

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_query()
  • PDO::query()

Descrierea

mixed mysql_query ( string $query [, resource $link_identifier = NULL ] )

mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.

Parametri

query

An SQL query

The query string should not end with a semicolon. Data inside the query should be properly escaped.

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query.

Exemple

Example #1 Invalid Query

The following query is syntactically invalid, so mysql_query() fails and returns FALSE.

<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

?>

Example #2 Valid Query

The following query is valid, so mysql_query() returns a resource.

<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname  = 'fox';

// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
    WHERE firstname='%s' AND lastname='%s'",
    mysql_real_escape_string($firstname),
    mysql_real_escape_string($lastname));

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_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 mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_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
mysql_free_result($result);
?>

A se vedea ?i

  • mysql_connect() - Deschide o conexiune la un server MySQL
  • mysql_error() - Returns the text of the error message from previous MySQL operation
  • mysql_real_escape_string() - Escapes special characters in a string for use in an SQL statement
  • mysql_result() - Get result data
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_unbuffered_query() - Send an SQL query to MySQL without fetching and buffering the result rows.

mysql_ping
mysql_real_escape_string
Func?ii MySQL


Escapes special characters in a string for use in an SQL statement

mysql_query
mysql_result
Func?ii MySQL
PHP Manual

mysql_real_escape_string

(PHP 4 >= 4.3.0, PHP 5)

mysql_real_escape_string — Escapes special characters in a string for use in an SQL statement

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_real_escape_string()
  • PDO::quote()

Descrierea

string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] )

Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used.

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.

This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.

Precautie

Security: the default character set

The character set must be set either at the server level, or with the API function mysql_set_charset() for it to affect mysql_real_escape_string(). See the concepts section on character sets for more information.

Parametri

unescaped_string

The string that is to be escaped.

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Returns the escaped string, or FALSE on error.

Erori/Excep?ii

Executing this function without a MySQL connection present will also emit E_WARNING level PHP errors. Only execute this function with a valid MySQL connection present.

Exemple

Example #1 Simple mysql_real_escape_string() example

<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
            mysql_real_escape_string($user),
            mysql_real_escape_string($password));
?>

Example #2 mysql_real_escape_string() requires a connection example

This example demonstrates what happens if a MySQL connection is not present when calling this function.

<?php
// We have not connected to MySQL

$lastname  = "O'Reilly";
$_lastname = mysql_real_escape_string($lastname);

$query = "SELECT * FROM actors WHERE last_name = '$_lastname'";

var_dump($_lastname);
var_dump($query);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Warning: mysql_real_escape_string(): No such file or directory in /this/test/script.php on line 5
Warning: mysql_real_escape_string(): A link to the server could not be established in /this/test/script.php on line 5

bool(false)
string(41) "SELECT * FROM actors WHERE last_name = ''"

Example #3 An example SQL Injection Attack

<?php
// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// This means the query sent to MySQL would be:
echo $query;
?>

The query sent to MySQL:

SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

This would allow anyone to log in without a valid password.

Note

Nota:

A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.

Nota:

If magic_quotes_gpc is enabled, first apply stripslashes() to the data. Using this function on data which has already been escaped will escape the data twice.

Nota:

If this function is not used to escape data, the query is vulnerable to SQL Injection Attacks.

Nota: mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.

A se vedea ?i

  • mysql_set_charset() - Sets the client character set
  • mysql_client_encoding() - Întoarce denumirea setului de caractere
  • 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
Func?ii MySQL


Get result data

mysql_real_escape_string
mysql_select_db
Func?ii MySQL
PHP Manual

mysql_result

(PHP 4, PHP 5)

mysql_result — Get result data

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_data_seek() in conjunction with
mysqli_field_seek() and
mysqli_fetch_field()
  • PDOStatement::fetchColumn()

Descrierea

string mysql_result ( resource $result , int $row [, mixed $field = 0 ] )

Retrieves the contents of one cell from a MySQL 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 mysql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Parametri

result

Rezultatul de tip resource, care este evaluat. Acest rezultat provine de la apelul func?iei mysql_query ().

row

The row number from the result that's 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.

Valorile întoarse

The contents of one cell from a MySQL result set on success, or FALSE on failure.

Exemple

Example #1 mysql_result() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('database_name')) {
    die('Could not select database: ' . mysql_error());
}
$result = mysql_query('SELECT name FROM work.employee');
if (!$result) {
    die('Could not query:' . mysql_error());
}
echo mysql_result($result, 2); // outputs third employee's name

mysql_close($link);
?>

Note

Nota:

Calls to mysql_result() should not be mixed with calls to other functions that deal with the result set.

A se vedea ?i

  • mysql_fetch_row() - Get a result row as an enumerated array
  • mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_fetch_object() - Fetch a result row as an object

mysql_real_escape_string
mysql_select_db
Func?ii MySQL


Select a MySQL database

mysql_result
mysql_set_charset
Func?ii MySQL
PHP Manual

mysql_select_db

(PHP 4, PHP 5)

mysql_select_db — Select a MySQL database

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_select_db()
  • PDO::__construct() (part of dsn)

Descrierea

bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )

Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database.

Parametri

database_name

The name of the database that is to be selected.

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 mysql_select_db() example

<?php

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}
?>

Note

Nota:

Pentru compatibilitatea cu versiunile anterioare, urmatorul pseudonim învechit poate fi utilizat: mysql_selectdb()

A se vedea ?i

  • mysql_connect() - Deschide o conexiune la un server MySQL
  • mysql_pconnect() - Open a persistent connection to a MySQL server
  • mysql_query() - Send a MySQL query

mysql_result
mysql_set_charset
Func?ii MySQL


Sets the client character set

mysql_select_db
mysql_stat
Func?ii MySQL
PHP Manual

mysql_set_charset

(PHP 5 >= 5.2.3)

mysql_set_charset — Sets the client character set

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_set_charset()
  • PDO: Add charset to the connection string, such as charset=utf8

Descrierea

bool mysql_set_charset ( string $charset [, resource $link_identifier = NULL ] )

Sets the default character set for the current connection.

Parametri

charset

A valid character set name.

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

This function requires MySQL 5.0.7 or later.

Nota:

This is the preferred way to change the charset. Using mysql_query() to set it (such as SET NAMES utf8) is not recommended. See the MySQL character set concepts section for more information.

A se vedea ?i

  • Setting character sets in MySQL
  • » List of character sets that MySQL supports
  • mysql_client_encoding() - Întoarce denumirea setului de caractere

mysql_select_db
mysql_stat
Func?ii MySQL


Get current system status

mysql_set_charset
mysql_tablename
Func?ii MySQL
PHP Manual

mysql_stat

(PHP 4 >= 4.3.0, PHP 5)

mysql_stat — Get current system status

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_stat()
  • PDO::getAttribute(PDO::ATTR_SERVER_INFO)

Descrierea

string mysql_stat ([ resource $link_identifier = NULL ] )

mysql_stat() returns the current server status.

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Returns a string with the status for uptime, threads, queries, open tables, flush tables and queries per second. For a complete list of other status variables, you have to use the SHOW STATUS SQL command. If link_identifier is invalid, NULL is returned.

Exemple

Example #1 mysql_stat() example

<?php
$link   = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$status = explode('  ', mysql_stat($link));
print_r($status);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => Uptime: 5380
    [1] => Threads: 2
    [2] => Questions: 1321299
    [3] => Slow queries: 0
    [4] => Opens: 26
    [5] => Flush tables: 1
    [6] => Open tables: 17
    [7] => Queries per second avg: 245.595
)

Example #2 Alternative mysql_stat() example

<?php
$link   = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$result = mysql_query('SHOW STATUS', $link);
while ($row = mysql_fetch_assoc($result)) {
    echo $row['Variable_name'] . ' = ' . $row['Value'] . "\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

back_log = 50
basedir = /usr/local/
bdb_cache_size = 8388600
bdb_log_buffer_size = 32768
bdb_home = /var/db/mysql/
bdb_max_lock = 10000
bdb_logdir =
bdb_shared_data = OFF
bdb_tmpdir = /var/tmp/
...

A se vedea ?i

  • mysql_get_server_info() - Get MySQL server info
  • mysql_list_processes() - List MySQL processes

mysql_set_charset
mysql_tablename
Func?ii MySQL


Get table name of field

mysql_stat
mysql_thread_id
Func?ii MySQL
PHP Manual

mysql_tablename

(PHP 4, PHP 5)

mysql_tablename — Get table name of field

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • SQL Query: SHOW TABLES

Descrierea

string mysql_tablename ( resource $result , int $i )

Retrieves the table name from a result.

This function is deprecated. It is preferable to use mysql_query() to issue an SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead.

Parametri

result

A result pointer resource that's returned from mysql_list_tables().

i

The integer index (row/table number)

Valorile întoarse

The name of the table on success sau FALSE în cazul e?ecului.

Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | The mysql_tablename() function is deprecated, and emits an E_DEPRECATED level error.

Exemple

Example #1 mysql_tablename() example

<?php
mysql_connect("localhost", "mysql_user", "mysql_password");
$result = mysql_list_tables("mydb");
$num_rows = mysql_num_rows($result);
for ($i = 0; $i < $num_rows; $i++) {
    echo "Table: ", mysql_tablename($result, $i), "\n";
}

mysql_free_result($result);
?>

Note

Nota:

The mysql_num_rows() function may be used to determine the number of tables in the result pointer.

A se vedea ?i

  • mysql_list_tables() - List tables in a MySQL database
  • mysql_field_table() - Get name of the table the specified field is in
  • mysql_db_name() - Retrieves database name from the call to mysql_list_dbs

mysql_stat
mysql_thread_id
Func?ii MySQL


Return the current thread ID

mysql_tablename
mysql_unbuffered_query
Func?ii MySQL
PHP Manual

mysql_thread_id

(PHP 4 >= 4.3.0, PHP 5)

mysql_thread_id — Return the current thread ID

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • mysqli_thread_id()

Descrierea

int mysql_thread_id ([ resource $link_identifier = NULL ] )

Retrieves the current thread ID. If the connection is lost, and a reconnect with mysql_ping() is executed, the thread ID will change. This means only retrieve the thread ID when needed.

Parametri

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

The thread ID on success sau FALSE în cazul e?ecului.

Exemple

Example #1 mysql_thread_id() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$thread_id = mysql_thread_id($link);
if ($thread_id){
    printf("current thread id is %d\n", $thread_id);
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

current thread id is 73

A se vedea ?i

  • mysql_ping() - Ping a server connection or reconnect if there is no connection
  • mysql_list_processes() - List MySQL processes

mysql_tablename
mysql_unbuffered_query
Func?ii MySQL


Send an SQL query to MySQL without fetching and buffering the result rows.

mysql_thread_id
Mysqlnd
Func?ii MySQL
PHP Manual

mysql_unbuffered_query

(PHP 4 >= 4.0.6, PHP 5)

mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the result rows.

Avertizare

Aceasta extensie a devenit învechita în PHP 5.5.0 ?i a fost eliminata în PHP 7.0.0. În locul ei trebuie utilizata extensia MySQLi sau PDO_MySQL. Accesa?i de asemenea ghidul MySQL: selectarea unei API ?i FAQ asociat pentru informa?ii suplimentare. Variante alternative pentru aceasta func?ie includ:

  • See: Buffered and Unbuffered queries

Descrierea

resource mysql_unbuffered_query ( string $query [, resource $link_identifier = NULL ] )

mysql_unbuffered_query() sends the SQL query query to MySQL without automatically fetching and buffering the result rows as mysql_query() does. This saves a considerable amount of memory with SQL queries that produce large result sets, and you can start working on the result set immediately after the first row has been retrieved as you don't have to wait until the complete SQL query has been performed. To use mysql_unbuffered_query() while multiple database connections are open, you must specify the optional parameter link_identifier to identify which connection you want to use.

Parametri

query

The SQL query to execute.

Data inside the query should be properly escaped.

link_identifier

Conexiunea MySQL. Daca identificatorul legaturii nu este specificat, se presupune ca este ultima legatura deschisa cu ajutorul mysql_connect(). Daca nu este gasita nici o astfel de legatura, se va încerca crearea uneia prin apelul mysql_connect () fara argumente. În caz ca nici o conexiune nu este gasita sau stabilita, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

For SELECT, SHOW, DESCRIBE or EXPLAIN statements, mysql_unbuffered_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, UPDATE, DELETE, DROP, etc, mysql_unbuffered_query() returns TRUE on success or FALSE on error.

Note

Nota:

The benefits of mysql_unbuffered_query() come at a cost: you cannot use mysql_num_rows() and mysql_data_seek() on a result set returned from mysql_unbuffered_query(), until all rows are fetched. You also have to fetch all result rows from an unbuffered SQL query before you can send a new SQL query to MySQL, using the same link_identifier.

A se vedea ?i

  • mysql_query() - Send a MySQL query

mysql_thread_id
Mysqlnd
Func?ii MySQL


MySQL Native Driver

  • Introducere
  • Overview
  • Installation
  • Configura?ia la rulare
  • Incompatibilities
  • Persistent Connections
  • Statistics
  • Notes
  • Memory management
  • 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
mysql_unbuffered_query
Introducere
MySQL


Introducere

MySQL Native Driver is a replacement for the MySQL Client Library (libmysqlclient). 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.

Mysqlnd
Overview
Mysqlnd


Overview

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.

Nota: Reporting memory usage

Because MySQL Native Driver uses the PHP memory management system, its memory usage can be tracked with memory_get_usage(). This is not possible with libmysqlclient because it uses the C function malloc() instead.

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.

Introducere
Installation
Mysqlnd


Installation

Jurnal al modificarilor

Jurnal al modificarilor
Versiune | Descriere
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.
5.5.0 | SHA-256 Authentication Plugin support was added

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.

SHA-256 Authentication Plugin support

The MySQL Native Driver requires the OpenSSL functionality of PHP to be loaded and enabled to connect to MySQL through accounts that use the MySQL SHA-256 Authentication Plugin. For example, PHP could be configured using:

./configure --with-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
--with-openssl
[other options]
Overview
Configura?ia la rulare
Mysqlnd


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

MySQL Native Driver Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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 | "" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.log_mask | 0 | PHP_INI_ALL | Available since PHP 5.3.0
mysqlnd.mempool_default_size | 16000 | PHP_INI_ALL | Available since PHP 5.3.3
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.
mysqlnd.sha256_server_public_key | "" | PHP_INI_PERDIR | Available since PHP 5.5.0.
mysqlnd.fetch_data_copy | 0 | PHP_INI_ALL | Available since PHP 5.6.0.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

  • m - Trace memory allocation and deallocation related calls.

Example:

d:t:x:O,/tmp/mysqlnd.trace

Nota:

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.log_mask integer

Defines which queries will be logged. The default 0, which disables logging. Define using an integer, and not with PHP constants. For example, a value of 48 (16 + 32) will log slow queries which either use 'no good index' (SERVER_QUERY_NO_GOOD_INDEX_USED = 16) or no index at all (SERVER_QUERY_NO_INDEX_USED = 32). A value of 2043 (1 + 2 + 8 + ... + 1024) will log all slow query types.

The types are as follows: SERVER_STATUS_IN_TRANS=1, SERVER_STATUS_AUTOCOMMIT=2,
SERVER_MORE_RESULTS_EXISTS=8, SERVER_QUERY_NO_GOOD_INDEX_USED=16, SERVER_QUERY_NO_INDEX_USED=32,
SERVER_STATUS_CURSOR_EXISTS=64, SERVER_STATUS_LAST_ROW_SENT=128, SERVER_STATUS_DB_DROPPED=256,
SERVER_STATUS_NO_BACKSLASH_ESCAPES=512, and SERVER_QUERY_WAS_SLOW=1024.

mysqlnd.mempool_default_size integer

Default size of the mysqlnd memory pool, which is used by result sets.

mysqlnd.net_read_timeout integer

mysqlnd and the MySQL Client Library, libmysqlclient use different networking APIs. mysqlnd uses PHP streams, whereas libmysqlclient 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.

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_options(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).

mysqlnd.sha256_server_public_key string

SHA-256 Authentication Plugin related. File with the MySQL server public RSA key.

Clients can either omit setting a public RSA key, specify the key through this PHP configuration setting or set the key at runtime using mysqli_options(). If not public RSA key file is given by the client, then the key will be exchanged as part of the standard SHA-256 Authentication Plugin authentication procedure.

mysqlnd.fetch_data_copy long

Enforce copying result sets from the internal result set buffers into PHP variables instead of using the default reference and copy-on-write logic. Please, see the memory management implementation notes for further details.

Copying result sets instead of having PHP variables reference them allows releasing the memory occupied for the PHP variables earlier. Depending on the user API code, the actual database quries and the size of their result sets this may reduce the memory footprint of mysqlnd.

Do not set if using PDO_MySQL. PDO_MySQL has not yet been updated to support the new fetch mode.

Installation
Incompatibilities
Mysqlnd


Incompatibilities

MySQL Native Driver is in most cases compatible with MySQL Client Library (libmysql). This section documents incompatibilities between these libraries.

  • Values of bit data type are returned as binary strings (e.g. "\0" or "\x1F") with libmysql and as decimal strings (e.g. "0" or "31") with mysqlnd. If you want the code to be compatible with both libraries then always return bit fields as numbers from MySQL with a query like this: SELECT bit + 0 FROM table.

Configura?ia la rulare
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.

Incompatibilities
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 two main types:

  • Client statistics

  • Connection statistics

If you are using the mysqli extension, these statistics can be obtained through two API calls:

  • mysqli_get_client_stats()

  • mysqli_get_connection_stats()

Nota:

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.

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() and mysqli_get_connection_stats() functions.

Returned mysqlnd statistics: 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 subtracting 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 that is recorded 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

Returned mysqlnd statistics: 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. 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 higher 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 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 successfully 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.
Returned mysqlnd statistics: 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.
Returned mysqlnd statistics: COM_* Command
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

Returned mysqlnd statistics: 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
Memory management
Mysqlnd


Memory management

Introduction

The MySQL Native Driver manages memory different than the MySQL Client Library. The libraries differ in the way memory is allocated and released, how memory is allocated in chunks while reading results from MySQL, which debug and development options exist, and how results read from MySQL are linked to PHP user variables.

The following notes are intended as an introduction and summary to users interested at understanding the MySQL Native Driver at the C code level.

Memory management functions used

All memory allocation and deallocation is done using the PHP memory management functions. Therefore, the memory consumption of mysqlnd can be tracked using PHP API calls, such as memory_get_usage(). Because memory is allocated and released using the PHP memory management, the changes may not immediately become visible at the operating system level. The PHP memory management acts as a proxy which may delay releasing memory towards the system. Due to this, comparing the memory usage of the MySQL Native Driver and the MySQL Client Library is difficult. The MySQL Client Library is using the operating system memory management calls directly, hence the effects can be observed immediately at the operating system level.

Any memory limit enforced by PHP also affects the MySQL Native Driver. This may cause out of memory errors when fetching large result sets that exceed the size of the remaining memory made available by PHP. Because the MySQL Client Library is not using PHP memory management functions, it does not comply to any PHP memory limit set. If using the MySQL Client Library, depending on the deployment model, the memory footprint of the PHP process may grow beyond the PHP memory limit. But also PHP scripts may be able to process larger result sets as parts of the memory allocated to hold the result sets are beyond the control of the PHP engine.

PHP memory management functions are invoked by the MySQL Native Driver through a lightweight wrapper. Among others, the wrapper makes debugging easier.

Handling of result sets

The various MySQL Server and the various client APIs differentiate between buffered and unbuffered result sets. Unbuffered result sets are transferred row-by-row from MySQL to the client as the client iterates over the results. Buffered results are fetched in their entirety by the client library before passing them on to the client.

The MySQL Native Driver is using PHP Streams for the network communication with the MySQL Server. Results sent by MySQL are fetched from the PHP Streams network buffers into the result buffer of mysqlnd. The result buffer is made of zvals. In a second step the results are made available to the PHP script. This final transfer from the result buffer into PHP variables impacts the memory consumption and is mostly noticible when using buffered result sets.

By default the MySQL Native Driver tries to avoid holding buffered results twice in memory. Results are kept only once in the internal result buffers and their zvals. When results are fetched into PHP variables by the PHP script, the variables will reference the internal result buffers. Database query results are not copied and kept in memory only once. Should the user modify the contents of a variable holding the database results a copy-on-write must be performed to avoid changing the referenced internal result buffer. The contents of the buffer must not be modified because the user may decide to read the result set a second time. The copy-on-write mechanism is implemented using an additional reference management list and the use of standard zval reference counters. Copy-on-write must also be done if the user reads a result set into PHP variables and frees a result set before the variables are unset.

Generally speaking, this pattern works well for scripts that read a result set once and do not modify variables holding results. Its major drawback is the memory overhead caused by the additional reference management which comes primarily from the fact that user variables holding results cannot be entirely released until the mysqlnd reference management stops referencing them. The MySQL Native driver removes the reference to the user variables when the result set is freed or a copy-on-write is performed. An observer will see the total memory consumption grow until the result set is released. Use the statistics to check whether a script does release result sets explicitly or the driver is does implicit releases and thus memory is used for a time longer than necessary. Statistics also help to see how many copy-on-write operations happened.

A PHP script reading many small rows of a buffered result set using a code snippet equal or equivalent to while ($row = $res->fetch_assoc()) { ... } may optimize memory consumption by requesting copies instead of references. Albeit requesting copies means keeping results twice in memory, it allows PHP to free the copy contained in $row as the result set is being iterated and prior to releasing the result set itself. On a loaded server optimizing peak memory usage may help improving the overall system performace although for an individual script the copy approach may be slower due to additional allocations and memory copy operations.

The copy mode can be enforced by setting mysqlnd.fetch_data_copy=1.

Monitoring and debugging

There are multiple ways of tracking the memory usage of the MySQL Native Driver. If the goal is to get a quick high level overview or to verify the memory efficiency of PHP scripts, then check the statistics collected by the library. The statistics allow you, for example, to catch SQL statements which generate more results than are processed by a PHP script.

The debug trace log can be configured to record memory management calls. This helps to see when memory is allocated or free'd. However, the size of the requested memory chunks may not be listed.

Some, recent versions of the MySQL Native Driver feature the emulation of random out of memory situations. This feature is meant to be used by the C developers of the library or mysqlnd plugin authors only. Please, search the source code for corresponding PHP configuration settings and further details. The feature is considered private and may be modified at any time without prior notice.

Notes
MySQL Native Driver Plugin API
Mysqlnd


MySQL Native Driver Plugin API

Cuprins

  • 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.

Memory management
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 libmysqlclient 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 Git, or through source snapshot downloads.

The following table shows PHP versions and the corresponding mysqlnd version contained within.

The bundled mysqlnd version per PHP release
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:

MYSQLND_VERSION_ID calculation table
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:

The mysqlnd organization chart, per module
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 original 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.

Nota:

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:

Pointer calculations for mysqlnd
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.

Constructor status
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 status
 | 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.

Precautie

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 original 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

  • Introducere
  • Quickstart and Examples
    • Setup
    • Running statements
    • Connection state
    • SQL Hints
    • Local transactions
    • XA/Distributed Transactions
    • Service level and consistency
    • Global transaction IDs
    • Cache integration
    • Failover
    • Partitioning and Sharding
    • MySQL Fabric
  • Concepts
    • Architecture
    • Connection pooling and switching
    • Local transaction handling
    • Error handling
    • Transient errors
    • Failover
    • Load balancing
    • Read-write splitting
    • Filter
    • Service level and consistency
    • Global transaction IDs
    • Cache integration
    • Supported clusters
    • XA/Distributed transactions
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Plugin configuration file (>=1.1.x)
  • Constante predefinite
  • Func?ii mysqlnd_ms
    • mysqlnd_ms_dump_servers — Returns a list of currently configured servers
    • mysqlnd_ms_fabric_select_global — Switch to global sharding server for a given table
    • mysqlnd_ms_fabric_select_shard — Switch to shard
    • 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_ms_xa_begin — Starts a distributed/XA transaction among MySQL servers
    • mysqlnd_ms_xa_commit — Commits a distributed/XA transaction among MySQL servers
    • mysqlnd_ms_xa_gc — Garbage collects unfinished XA transactions after severe errors
    • mysqlnd_ms_xa_rollback — Rolls back a distributed/XA transaction among MySQL servers
  • Change History
    • PECL/mysqlnd_ms 1.6 series
    • PECL/mysqlnd_ms 1.5 series
    • PECL/mysqlnd_ms 1.4 series
    • PECL/mysqlnd_ms 1.3 series
    • PECL/mysqlnd_ms 1.2 series
    • PECL/mysqlnd_ms 1.1 series
    • PECL/mysqlnd_ms 1.0 series
Getting started building a mysqlnd plugin
Introducere
MySQL


Introducere

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 (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.

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.

  • Can be used with any MySQL clustering solution.

    • MySQL Replication: Read-write splitting is done by the plugin. Primary focus of the plugin.

    • MySQL Cluster: Read-write splitting can be disabled. Configuration of multiple masters possible

    • Third-party solutions: the plugin is optimized for MySQL Replication but can be used with any other kind of MySQL clustering solution.

  • 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.

    • Weighted load balancing: servers can be assigned different priorities, for example, to direct more requests to a powerful machine than to another less powerful machine. Or, to prefer nearby machines to reduce latency.

  • Global transaction ID

    • Client-side emulation. Makes manual master server failover and slave promotion easier with asynchronous clusters, such as MySQL Replication.

    • Support for built-in global transaction identifier feature of MySQL 5.6.5 or newer.

    • Supports using transaction ids to identify up-to-date asynchronous slaves for reading when session consistency is required. Please, note the restrictions mentioned in the manual.

    • Throttling: optionally, the plugin can wait for a slave to become "synchronous" before continuing.

  • Service and consistency levels

    • Applications can request eventual, session and strong consistency service levels for connections. Appropriate cluster nodes will be searched automatically.

    • Eventual consistent MySQL Replication slave accesses can be replaced with fast local cache accesses transparently to reduce server load.

  • Partitioning and sharding

    • Servers of a replication cluster can be organized into groups. SQL hints can be used to manually direct queries to a specific group. Grouping can be used to partition (shard) the data, or to cure the issue of hotspots with updates.

    • MySQL Replication filters are supported through the table filter.

  • MySQL Fabric

    • Experimental support for MySQL Fabric is included.

Limitations

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.

Nota:

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

Cuprins

  • Setup
  • Running statements
  • Connection state
  • SQL Hints
  • Local transactions
  • XA/Distributed Transactions
  • Service level and consistency
  • Global transaction IDs
  • Cache integration
  • Failover
  • Partitioning and Sharding
  • MySQL Fabric

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, namely 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.

Introducere
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.

Example #1 Enabling the plugin (php.ini)

mysqlnd_ms.enable=1
mysqlnd_ms.config_file=/path/to/mysqlnd_ms_plugin.ini

The plugin uses its own configuration file. Use the PHP configuration directive mysqlnd_ms.config_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). Please note, the configuration directive mysqlnd_ms.config_file superseeds mysqlnd_ms.ini_file since 1.4.0. It is a common pitfall to use the old, no longer available configuration directive.

Create a plugin-specific configuration file. Save the file to the path set by the PHP configuration directive mysqlnd_ms.config_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.

Example #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.

Example #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.

Example #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"
            }
        }
    }
}

The plugin attempts to notify you of invalid configurations. Since 1.5.0 it will throw a warning during PHP startup if the configuration file cannot be read, is empty or parsing the JSON failed. Depending on your PHP settings those errors may appear in some log files only. Further validation is done when a connection is to be established and the configuration file is searched for valid sections. Setting mysqlnd_ms.force_config_usage may help debugging a faulty setup. Please, see also configuration file debugging notes.

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

Example #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"
            }
        }
    }
}

Example #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.

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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.

Example #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"
            }
        }
    }
}

Example #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();
?>

Exemplul de mai sus va afi?a:

@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_LAST_USED_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.

Example #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"
            }
        }
    }
}

Example #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();
?>

Exemplul de mai sus va afi?a:

@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.

Example #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.

Example #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
Local transactions
Quickstart and Examples


Local transactions

The current version of the plugin is not transaction safe by default, because it is not aware of running transactions in all cases. SQL transactions are units of work to be run on a single server. The plugin does not always 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.

No kind of MySQL load balancer can detect transaction boundaries without any kind of hint from the application.

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 transactions, see below.

Example #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"
            }
        }
    }
}

Example #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. In this case, you do not need to use SQL hints.

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.

API based transaction boundary detection has been improved with PHP 5.5.0 and PECL/mysqlnd_ms 1.5.0 to cover not only calls to mysqli_autocommit() but also mysqli_begin(), mysqli_commit() and mysqli_rollback().

Example #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"
    }
}

Example #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();
?>

Nota: Version requirement

The plugin configuration option trx_stickiness=master requires PHP 5.4.0 or newer.

Please note the restrictions outlined in the transaction handling concepts section.

SQL Hints
XA/Distributed Transactions
Quickstart and Examples


XA/Distributed Transactions

Nota: Version requirement

XA related functions have been introduced in PECL mysqlnd_ms version 1.6.0-alpha.

Nota: Early adaptors wanted

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments, although early lab tests indicate reasonable quality.

Please, contact the development team if you are interested in this feature. We are looking for real life feedback to complement the feature.

XA transactions are a standardized method for executing transactions across multiple resources. Those resources can be databases or other transactional systems. The MySQL server supports XA SQL statements which allows users to carry out a distributed SQL transaction that spawns multiple database servers or any kind as long as they support the SQL statements too. In such a scenario it is in the responsibility of the user to coordinate the participating servers.

PECL/mysqlnd_ms can act as a transaction coordinator for a global (distributed, XA) transaction carried out on MySQL servers only. As a transaction coordinator, the plugin tracks all servers involved in a global transaction and transparently issues appropriate SQL statements on the participants. The global transactions are controlled with mysqlnd_ms_xa_begin(), mysqlnd_ms_xa_commit() and mysqlnd_ms_xa_rollback(). SQL details are mostly hidden from the application as is the need to track and coordinate participants.

Example #1 General pattern for XA 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()));
}

/* start a global transaction */
$gtrid_id = "12345";
if (!mysqlnd_ms_xa_begin($mysqli, $gtrid_id)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* run queries as usual: XA BEGIN will be injected upon running a query */
if (!$mysqli->query("INSERT INTO orders(order_id, item) VALUES (1, 'christmas tree, 1.8m')")) {
    /* Either INSERT failed or the injected XA BEGIN failed */
    if ('XA' == substr($mysqli->sqlstate, 0, 2)) {
        printf("Global transaction/XA related failure, [%d] %s\n", $mysqli->errno, $mysqli->error);
    } else {
        printf("INSERT failed, [%d] %s\n", $mysqli->errno, $mysqli->error);
    }
    /* rollback global transaction */
    mysqlnd_ms_xa_rollback($mysqli, $xid);
    die("Stopping.");
}

/* continue carrying out queries on other servers, e.g. other shards */

/* commit the global transaction */
if (!mysqlnd_ms_xa_commit($mysqli, $xa_id)) {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
?>

Unlike with local transactions, which are carried out on a single server, XA transactions have an identifier (xid) associated with them. The XA transaction identifier is composed of a global transaction identifier (gtrid), a branch qualifier (bqual) a format identifier (formatID). Only the global transaction identifier can and must be given when calling any of the plugins XA functions.

Once a global transaction has been started, the plugin begins tracking servers until the global transaction ends. When a server is picked for query execution, the plugin injects the SQL statement XA BEGIN prior to executing the actual SQL statement on the server. XA BEGIN makes the server participate in the global transaction. If the injected SQL statement fails, the plugin will report the issue in reply to the query execution function that was used. In the above example, $mysqli->query("INSERT INTO orders(order_id, item) VALUES (1, 'christmas tree, 1.8m')") would indicate such an error. You may want to check the errors SQL state code to determine whether the actual query (here: INSERT) has failed or the error is related to the global transaction. It is up to you to ignore the failure to start the global transaction on a server and continue execution without having the server participate in the global transaction.

Example #2 Local and global transactions are mutually exclusive

<?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()));
}

/* start a local transaction */
if (!$mysqli->begin_transaction()) {
    die(sprintf("[%d/%s] %s\n", $mysqli->errno, $mysqli->sqlstate, $mysqli->error));
}

/* cannot start global transaction now - must end local transaction first */
$gtrid_id = "12345";
if (!mysqlnd_ms_xa_begin($mysqli, $gtrid_id)) {
    die(sprintf("[%d/%s] %s\n", $mysqli->errno, $mysqli->sqlstate, $mysqli->error));
}
?>

Exemplul de mai sus va afi?a:

Warning: mysqlnd_ms_xa_begin(): (mysqlnd_ms) Some work is done outside global transaction. You must end the active local transaction first in ... on line ...
[1400/XAE09] (mysqlnd_ms) Some work is done outside global transaction. You must end the active local transaction first

A global transaction cannot be started when a local transaction is active. The plugin tries to detect this situation as early as possible, that is when mysqlnd_ms_xa_begin() is called. If using API calls only to control transactions, the plugin will know that a local transaction is open and return an error for mysqlnd_ms_xa_begin(). However, note the plugins limitations on detecting transaction boundaries.. In the worst case, if using direct SQL for local transactions (BEGIN, COMMIT, ...), it may happen that an error is delayed until some SQL is executed on a server.

To end a global transaction invoke mysqlnd_ms_xa_commit() or mysqlnd_ms_xa_rollback(). When a global transaction is ended all participants must be informed of the end. Therefore, PECL/mysqlnd_ms transparently issues appropriate XA related SQL statements on some or all of them. Any failure during this phase will cause an implicit rollback. The XA related API is intentionally kept simple here. A more complex API that gave more control would bare few, if any, advantages over a user implementation that issues all lower level XA SQL statements itself.

XA transactions use the two-phase commit protocol. The two-phase commit protocol is a blocking protocol. There are cases when no progress can be made, not even when using timeouts. Transaction coordinators should survive their own failure, be able to detect blockades and break ties. PECL/mysqlnd_ms takes the role of a transaction coordinator and can be configured to survive its own crash to avoid issues with blocked MySQL servers. Therefore, the plugin can and should be configured to use a persistent and crash-safe state to allow garbage collection of unfinished, aborted global transactions. A global transaction can be aborted in an open state if either the plugin fails (crashes) or a connection from the plugin to a global transaction participant fails.

Example #3 Transaction coordinator state store

{
    "myapp": {
        "xa": {
            "state_store": {
                "participant_localhost_ip": "192.168.2.12",
                "mysql": {
                    "host": "192.168.2.13",
                    "user": "root",
                    "password": "",
                    "db": "test",
                    "port": "3312",
                    "socket": null
                }
            }
        },
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.14",
                "port": "3306"
            }
        }
    }
}

Currently, PECL/mysqlnd_ms supports only using MySQL database tables as a state store. The SQL definitions of the tables are given in the plugin configuration section. Please, make sure to use a transactional and crash-safe storage engine for the tables, such as InnoDB. InnoDB is the default table engine in recent versions of the MySQL server. Make also sure the database server itself is highly available.

If a state store has been configured, the plugin can perform a garbage collection. During garbage collection it may be necessary to connect to a participant of a failed global transaction. Thus, the state store holds a list of participants and, among others, their host names. If the garbage collection is run on another host but the one that has written a participant entry with the host name localhost, then localhost resolves to different machines. There are two solutions to the problem. Either you do not configure any servers with the host name localhost but configure an IP address (and port) or, you hint the garbage collection. In the above example, localhost is used for master_0, hence it may not resolve to the correct host during garbage collection. However, participant_localhost_ip is also set to hint the garbage collection that localhost stands for the IP 192.168.2.12.

Local transactions
Service level and consistency
Quickstart and Examples


Service level and consistency

Nota: 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.

Example #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"
            }
        }
    }
}

Example #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.

Example #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"
    }
}

Example #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.

Nota: 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.

Example #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"
            }
        }
    }
}

Example #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));
}
?>

Exemplul de mai sus va afi?a:

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

XA/Distributed Transactions
Global transaction IDs
Quickstart and Examples


Global transaction IDs

Nota: Version requirement

A client-side 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.

As of MySQL 5.6.5-m8 release candidate the MySQL server features built-in global transaction identifiers. The MySQL built-in global transaction ID feature is supported by PECL/mysqlnd_ms 1.3.0-alpha or later. However, the final feature set found in MySQL 5.6 production releases to date is not sufficient to support the ideas discussed below in all cases. Please, see also the concepts section.

PECL/mysqlnd_ms can either use its own global transaction ID emulation or the global transaction ID feature built-in to MySQL 5.6.5-m8 or later. From a developer perspective the client-side and server-side approach offer the same features with regards to service levels provided by PECL/mysqlnd_ms. Their differences are discussed in the concepts section.

The quickstart first demonstrates the use of the client-side global transaction ID emulation built-in to PECL/mysqlnd_ms before its show how to use the server-side counterpart. The order ensures that the underlying idea is discussed first.

Idea and client-side emulation

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 committed on the master. Slaves replicate the table. The counter serves two purposes. 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 committed 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 querying 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.

Example #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.

Example #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
        }
    }
}

Example #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());
?>

Exemplul de mai sus va afi?a:

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.

Nota: 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.

Example #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
        }
    }
}

Example #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));
?>

Exemplul de mai sus va afi?a:

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.

Example #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
        }
    }
}

Example #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.

Use of the server-side global transaction ID feature

Nota: Insufficient server support in MySQL 5.6

The plugin has been developed against a pre-production version of MySQL 5.6. It turns out that all released production versions of MySQL 5.6 do not provide clients with enough information to enforce session consistency based on GTIDs. Please, read the concepts section for details.

Starting with MySQL 5.6.5-m8 the MySQL Replication system features server-side global transaction IDs. Transaction identifiers are automatically generated and maintained by the server. Users do not need to take care of maintaining them. There is no need to setup any tables in advance, or for setting on_commit. A client-side emulation is no longer needed.

Clients can continue to use global transaction identifier to achieve session consistency when reading from MySQL Replication slaves in some cases but not all! The algorithm works as described above. Different SQL statements must be configured for fetch_last_gtid and check_for_gtid. The statements are given below. Please note, MySQL 5.6.5-m8 is a development version. Details of the server implementation may change in the future and require adoption of the SQL statements shown.

Using the following configuration any of the above described functionality can be used together with the server-side global transaction ID feature. mysqlnd_ms_get_last_gtid() and mysqlnd_ms_set_qos() continue to work as described above. The only difference is that the server does not use a simple sequence number but a string containing of a server identifier and a sequence number. Thus, users cannot easily derive an order from GTIDs returned by mysqlnd_ms_get_last_gtid().

Example #8 Plugin config: using MySQL 5.6.5-m8 built-in GTID feature

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "global_transaction_id_injection":{
            "fetch_last_gtid" : "SELECT @@GLOBAL.GTID_DONE AS trx_id FROM DUAL",
            "check_for_gtid" : "SELECT GTID_SUBSET('#GTID', @@GLOBAL.GTID_DONE) AS trx_id FROM DUAL",
            "report_error":true
        }
    }
}

Service level and consistency
Cache integration
Quickstart and Examples


Cache integration

Nota: Version requirement, dependencies and status

Please, find more about version requirements, extension load order dependencies and the current status in the concepts section!

Databases clusters can deliver different levels of consistency. As of PECL/mysqlnd_ms 1.2.0 it is possible to advice the plugin to consider only cluster nodes that can deliver the consistency level requested. For example, if using asynchronous MySQL Replication with its cluster-wide eventual consistency, it is possible to request session consistency (read your writes) at any time using mysqlnd_ms_set_quos(). Please, see also the service level and consistency introduction.

Example #1 Recap: quality of service to request read your writes

/* 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));

Assuming PECL/mysqlnd has been explicitly told to deliver no consistency level higher than eventual consistency, it is possible to replace a database node read access with a client-side cache using time-to-live (TTL) as its invalidation strategy. Both the database node and the cache may or may not serve current data as this is what eventual consistency defines.

Replacing a database node read access with a local cache access can improve overall performance and lower the database load. If the cache entry is every reused by other clients than the one creating the cache entry, a database access is saved and thus database load is lowered. Furthermore, system performance can become better if computation and delivery of a database query is slower than a local cache access.

Example #2 Plugin config: no special entries for caching

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
    }
}

Example #3 Caching a slave request

<?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()));
}

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));
}

/* Explicitly allow eventual consistency and caching (TTL <= 60 seconds) */
if (false == mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL, MYSQLND_MS_QOS_OPTION_CACHE, 60)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* To make this example work, we must wait for a slave to catch up. Brute force style. */
$attempts = 0;
do {
    /* check if slave has the table */
    if ($res = $mysqli->query("SELECT id FROM test")) {
        break;
    } else if ($mysqli->errno) {
        die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
    }
    /* wait for slave to catch up */
    usleep(200000);
} while ($attempts++ < 10);

/* Query has been run on a slave, result is in the cache */
assert($res);
var_dump($res->fetch_assoc());

/* Served from cache */
$res = $mysqli->query("SELECT id FROM test");
?>

The example shows how to use the cache feature. First, you have to set the quality of service to eventual consistency and explicitly allow for caching. This is done by calling mysqlnd_ms_set_qos(). Then, the result set of every read-only statement is cached for upto that many seconds as allowed with mysqlnd_ms_set_qos().

The actual TTL is lower or equal to the value set with mysqlnd_ms_set_qos(). The value passed to the function sets the maximum age (seconds) of the data delivered. To calculate the actual TTL value the replication lag on a slave is checked and subtracted from the given value. If, for example, the maximum age is set to 60 seconds and the slave reports a lag of 10 seconds the resulting TTL is 50 seconds. The TTL is calculated individually for every cached query.

Example #4 Read your writes and caching 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()));
}

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));
}

/* Explicitly allow eventual consistency and caching (TTL <= 60 seconds) */
if (false == mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL, MYSQLND_MS_QOS_OPTION_CACHE, 60)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* To make this example work, we must wait for a slave to catch up. Brute force style. */
$attempts = 0;
do {
    /* check if slave has the table */
    if ($res = $mysqli->query("SELECT id FROM test")) {
        break;
    } else if ($mysqli->errno) {
        die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
    }
    /* wait for slave to catch up */
    usleep(200000);
} while ($attempts++ < 10);

assert($res);

/* Query has been run on a slave, result is in the cache */
var_dump($res->fetch_assoc());

/* Served from cache */
if (!($res = $mysqli->query("SELECT id FROM test"))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
var_dump($res->fetch_assoc());

/* Update on master */
if (!$mysqli->query("UPDATE test SET id = 2")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Read your writes */
if (false == mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Fetch latest data */
if (!($res = $mysqli->query("SELECT id FROM test"))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
var_dump($res->fetch_assoc());
?>

The quality of service can be changed at any time to avoid further cache usage. If needed, you can switch to read your writes (session consistency). In that case, the cache will not be used and fresh data is read.

Global transaction IDs
Failover
Quickstart and Examples


Failover

By default, the plugin does not attempt to fail over if connecting to a host fails. This prevents pitfalls related to connection state. It is recommended to manually handle connection errors in a way similar to a failed transaction. You should catch the error, rebuild the connection state and rerun your query as shown below.

If connection state is no issue to you, you can alternatively enable automatic and silent failover. Depending on the configuration, the automatic and silent failover will either attempt to fail over to the master before issuing and error or, try to connect to other slaves, given the query allowes for it, before attempting to connect to a master. Because automatic failover is not fool-proof, it is not discussed in the quickstart. Instead, details are given in the concepts section below.

Example #1 Manual failover, automatic optional

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "simulate_slave_failure",
                "port": "0"
            },
            "slave_1": {
                "host": "127.0.0.1",
                "port": 3311
            }
        },
       "filters": { "roundrobin": [] }
    }
 }

Example #2 Manual failover

<?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()));
}

$sql = "SELECT 1 FROM DUAL";

/* error handling as it should be done regardless of the plugin */
if (!($res = $link->query($sql))) {
    /* plugin specific: check for connection error */
    switch ($link->errno) {
    case 2002:
    case 2003:
    case 2005:
        printf("Connection error - trying next slave!\n");
        /* load balancer will pick next slave */
        $res = $link->query($sql);
        break;
    default:
        /* no connection error, failover is unlikely to help */
        die(sprintf("SQL error: [%d] %s", $link->errno, $link->error));
        break;
    }
}
if ($res) {
    var_dump($res->fetch_assoc());
}
?>

Cache integration
Partitioning and Sharding
Quickstart and Examples


Partitioning and Sharding

Database clustering is done for various reasons. Clusters can improve availability, fault tolerance, and increase performance by applying a divide and conquer approach as work is distributed over many machines. Clustering is sometimes combined with partitioning and sharding to further break up a large complex task into smaller, more manageable units.

The mysqlnd_ms plugin aims to support a wide variety of MySQL database clusters. Some flavors of MySQL database clusters have built-in methods for partitioning and sharding, which could be transparent to use. The plugin supports the two most common approaches: MySQL Replication table filtering, and Sharding (application based partitioning).

MySQL Replication supports partitioning as filters that allow you to create slaves that replicate all or specific databases of the master, or tables. It is then in the responsibility of the application to choose a slave according to the filter rules. You can either use the mysqlnd_ms node_groups filter to manually support this, or use the experimental table filter.

Manual partitioning or sharding is supported through the node grouping filter, and SQL hints as of 1.5.0. The node_groups filter lets you assign a symbolic name to a group of master and slave servers. In the example, the master master_0 and slave_0 form a group with the name Partition_A. It is entirely up to you to decide what makes up a group. For example, you may use node groups for sharding, and use the group names to address shards like Shard_A_Range_0_100.

Example #1 Cluster node groups

{
  "myapp": {
       "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "simulate_slave_failure",
                "port": "0"
            },
            "slave_1": {
                "host": "127.0.0.1",
                "port": 3311
            }
        },
        "filters": {
            "node_groups": {
                "Partition_A" : {
                    "master": ["master_0"],
                    "slave": ["slave_0"]
                }
            },
           "roundrobin": []
        }
    }
}

Example #2 Manual partitioning using SQL hints

<?php
function select($mysqli, $msg, $hint = '')
{
    /* Note: weak test, two connections to two servers may have the same thread id */
    $sql = sprintf("SELECT CONNECTION_ID() AS _thread, '%s' AS _hint FROM DUAL", $msg);
    if ($hint) {
        $sql = $hint . $sql;
    }
    if (!($res = $mysqli->query($sql))) {
        printf("[%d] %s", $mysqli->errno, $mysqli->error);
        return false;
    }
    $row =  $res->fetch_assoc();
    printf("%d - %s - %s\n", $row['_thread'], $row['_hint'], $sql);
    return true;
}

$mysqli = new mysqli("myapp", "user", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* All slaves allowed */
select($mysqli, "slave_0");
select($mysqli, "slave_1");

/* only servers of node group "Partition_A" allowed */
select($mysqli, "slave_1", "/*Partition_A*/");
select($mysqli, "slave_1", "/*Partition_A*/");
?>
6804 - slave_0 - SELECT CONNECTION_ID() AS _thread, 'slave1' AS _hint FROM DUAL
2442 - slave_1 - SELECT CONNECTION_ID() AS _thread, 'slave2' AS _hint FROM DUAL
6804 - slave_0 - /*Partition_A*/SELECT CONNECTION_ID() AS _thread, 'slave1' AS _hint FROM DUAL
6804 - slave_0 - /*Partition_A*/SELECT CONNECTION_ID() AS _thread, 'slave1' AS _hint FROM DUAL

By default, the plugin will use all configured master and slave servers for query execution. But if a query begins with a SQL hint like /*node_group*/, the plugin will only consider the servers listed in the node_group for query execution. Thus, SELECT queries prefixed with /*Partition_A*/ will only be executed on slave_0.

Failover
MySQL Fabric
Quickstart and Examples


MySQL Fabric

Nota: Version requirement and status

Work on supporting MySQL Fabric started in version 1.6. Please, consider the support to be of pre-alpha quality. The manual may not list all features or feature limitations. This is work in progress.

Sharding is the only use case supported by the plugin to date.

Nota: MySQL Fabric concepts

Please, check the MySQL reference manual for more information about MySQL Fabric and how to set it up. The PHP manual assumes that you are familiar with the basic concepts and ideas of MySQL Fabric.

MySQL Fabric is a system for managing farms of MySQL servers to achive High Availability and optionally support sharding. Technically, it is a middleware to manage and monitor MySQL servers.

Clients query MySQL Fabric to obtain lists of MySQL servers, their state and their roles. For example, clients can request a list of slaves for a MySQL Replication group and whether they are ready to handle SQL requests. Another example is a cluster of sharded MySQL servers where the client seeks to know which shard to query for a given table and shard key. If configured to use Fabric, the plugin uses XML RCP over HTTP to obtain the list at runtime from a MySQL Fabric host. The XML remote procedure call itself is done in the background and transparent from a developers point of view.

Instead of listing MySQL servers directly in the plugins configuration file it contains a list of one or more MySQL Fabric hosts

Example #1 Plugin config: Fabric hosts instead of MySQL servers

{
    "myapp": {
        "fabric": {
            "hosts": [
                {
                    "host" : "127.0.0.1",
                    "port" : 8080
                }
            ]
        }
    }
}

Users utilize the new functions mysqlnd_ms_fabric_select_shard() and mysqlnd_ms_fabric_select_global() to switch to the set of servers responsible for a given shard key. Then, the plugin picks an appropriate server for running queries on. When doing so, the plugin takes care of additional load balancing rules set.

The below example assumes that MySQL Fabric has been setup to shard the table test.fabrictest using the id column of the table as a shard key.

Example #2 Manual partitioning using SQL hints

<?php
$mysqli = new mysqli("myapp", "user", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* Create a global table - a table available on all shards */
mysqlnd_ms_fabric_select_global($mysqli, "test.fabrictest");
if (!$mysqli->query("CREATE TABLE test.fabrictest(id INT NOT NULL PRIMARY KEY)")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Switch connection to appropriate shard and insert record */
mysqlnd_ms_fabric_select_shard($mysqli, "test.fabrictest", 10);
if (!($res = $mysqli->query("INSERT INTO fabrictest(id) VALUES (10)"))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Try to read newly inserted record */
mysqlnd_ms_fabric_select_shard($mysqli, "test.fabrictest", 10);
if (!($res = $mysqli->query("SELECT id FROM test WHERE id = 10"))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
?>

The example creates the sharded table, inserts a record and reads the record thereafter. All SQL data definition language (DDL) operations on a sharded table must be applied to the so called global server group. Prior to creating or altering a sharded table, mysqlnd_ms_fabric_select_global() is called to switch the given connection to the corresponding servers of the global group. Data manipulation (DML) SQL statements must be sent to the shards directly. The mysqlnd_ms_fabric_select_shard() switches a connection to shards handling a certain shard key.

Partitioning and Sharding
Concepts
Quickstart and Examples


Concepts

Cuprins

  • Architecture
  • Connection pooling and switching
  • Local transaction handling
  • Error handling
  • Transient errors
  • Failover
  • Load balancing
  • Read-write splitting
  • Filter
  • Service level and consistency
  • Global transaction IDs
  • Cache integration
  • Supported clusters
  • XA/Distributed transactions

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.

MySQL Fabric
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 behavior 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 behavior 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.

Nota: 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.
Precautie

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.

Charsets and string escaping

Due to the use of lazy connections, which are a default, it can happen that an application tries to escape a string for use within SQL statements before a connection has been established. In this case string escaping is not possible. The string escape function does not know what charset to use before a connection has been established.

To overcome the problem a new configuration setting server_charset has been introduced in version 1.4.0.

Attention has to be paid on escaping strings with a certain charset but using the result on a connection that uses a different charset. Please note, that PECL/mysqlnd_ms manipulates connections and one application level connection represents a pool of multiple connections that all may have different default charsets. It is recommended to configure the servers involved to use the same default charsets. The configuration setting server_charset does help with this situation as well. If using server_charset, the plugin will set the given charset on all newly opened connections.

Architecture
Local transaction handling
Concepts


Local 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.

Any kind of MySQL load balancer must be hinted about the begin and end of a transaction. Hinting can either be done implicitly by monitoring API calls or using SQL hints. Both options are supported by the plugin, depending on your PHP version. API monitoring requires PHP 5.4.0 or newer. The plugin, like any other MySQL load balancer, cannot detect transaction boundaries based on the MySQL Client Server Protocol. Thus, entirely transparent transaction aware load balancing is not possible. The least intrusive option is API monitoring, which requires little to no application changes, depending on your application.

Please, find examples of using SQL hints or the API monitoring in the examples section. The details behind the API monitoring, which makes the plugin transaction aware, are described below.

Beginning with 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.

The PHP MySQL extensions either issue a query (such as SET AUTOCOMMIT=0|1), or use the mysqlnd library call set_autocommit() 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.

An application that does not want to set SQL hints for transactions but wants to use the transparent API monitoring to avoid application changes must make sure that the autocommit settings is changed exclusively through the listed API calls.

API based transaction boundary detection has been improved with PHP 5.5.0 and PECL/mysqlnd_ms 1.5.0 to cover not only calls to mysqli_autocommit() but also mysqli_begin(), mysqli_commit() and mysqli_rollback().

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.

Example #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.

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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.

Example #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.

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

[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.

Local transaction handling
Transient errors
Concepts


Transient errors

Some distributed database clusters make use of transient errors. A transient error is a temporary error that is likely to disappear soon. By definition it is safe for a client to ignore a transient error and retry the failed operation on the same database server. The retry is free of side effects. Clients are not forced to abort their work or to fail over to another database server immediately. They may enter a retry loop before to wait for the error to disappear before giving up on the database server. Transient errors can be seen, for example, when using MySQL Cluster. But they are not bound to any specific clustering solution per se.

PECL/mysqlnd_ms can perform an automatic retry loop in case of a transient error. This increases distribution transparency and thus makes it easier to migrate an application running on a single database server to run on a cluster of database servers without having to change the source of the application.

The automatic retry loop will repeat the requested operation up to a user configurable number of times and pause between the attempts for a configurable amount of time. If the error disappears during the loop, the application will never see it. If not, the error is forwarded to the application for handling.

In the example below a duplicate key error is provoked to make the plugin retry the failing query two times before the error is passed to the application. Between the two attempts the plugin sleeps for 100 milliseconds.

Example #1 Provoking a transient error

mysqlnd_ms.enable=1
mysqlnd_ms.collect_statistics=1
{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
       },
       "transient_error": {
          "mysql_error_codes": [
            1062
          ],
          "max_retries": 2,
          "usleep_retry": 100
       }
    }
}

Example #2 Transient error retry loop

<?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()));

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT PRIMARY KEY)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1))")) {
  printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Retry loop is completely transparent. Checking statistics is
 the only way to know about implicit retries */
$stats = mysqlnd_ms_get_stats();
printf("Transient error retries before error: %d\n", $stats['transient_error_retries']);

/* Provoking duplicate key error to see statistics change */
if (!$mysqli->query("INSERT INTO test(id) VALUES (1))")) {
  printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

$stats = mysqlnd_ms_get_stats();
printf("Transient error retries after error: %d\n", $stats['transient_error_retries']);

$mysqli->close();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Transient error retries before error: 0
[1062] Duplicate entry '1' for key 'PRIMARY'
Transient error retries before error: 2

Because the execution of the retry loop is transparent from a users point of view, the example checks the statistics provided by the plugin to learn about it.

As the example shows, the plugin can be instructed to consider any error transient regardless of the database servers error semantics. The only error that a stock MySQL server considers temporary has the error code 1297. When configuring other error codes but 1297 make sure your configuration reflects the semantics of your clusters error codes.

The following mysqlnd C API calls are monitored by the plugin to check
for transient errors: query(),
change_user(), select_db(),
set_charset(), set_server_option()
prepare(), execute(),
set_autocommit(),
tx_begin(), tx_commit(),
tx_rollback(), tx_commit_or_rollback().
The corresponding user API calls have similar names.

The maximum time the plugin may sleep during the retry loop depends on the function in question. The a retry loop for query(), prepare() or execute() will sleep for up to max_retries * usleep_retry milliseconds.

However, functions that control connection state are dispatched to all connections. The retry loop settings are applied to every connection on which the command is to be run. Thus, such a function may interrupt program execution for longer than a function that is run on one server only. For example, set_autocommit() is dispatched to connections and may sleep up to (max_retries * usleep_retry) * number_of_open_connections) milliseconds. Please, keep this in mind when setting long sleep times and large retry numbers. Using the default settings of max_retries=1, usleep_retry=100 and lazy_connections=1 it is unlikely that you will ever see a delay of more than 1 second.

Error handling
Failover
Concepts


Failover

By default, 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.

Default: manual failover

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 failover. Please note, that automatic failover logic is limited to connection attempts. Automatic failover is not used for already established connections. There is no way to instruct the plugin to attempt failover on a connection that has been connected to MySQL already in the past.

Automatic failover

The failover policy is configured in the plugins configuration file, by using the failover configuration directive.

Automatic and silent failover can be enabled through the failover configuration directive. Automatic failover can either be configured to try exactly one master after a slave failure or, alternatively, loop over slaves and masters before returning an error to the user. The number of connection attempts can be limited and failed hosts can be excluded from future load balancing attempts. Limiting the number of retries and remembering failed hosts are considered experimental features, albeit being reasonable stable. Syntax and semantics may change in future versions.

Please note, since version 1.5.0 automatic failover is disabled for the duration of a transaction if transaction stickiness is enabled and transaction boundaries have been detected. The plugin will not switch connections for the duration of a transaction. It will also not perform automatic and silent failover. Instead an error will be thrown. It is then left to the user to handle the failure of the transaction. Please check, the trx_stickiness documentation how to do this.

A basic manual failover example is provided within the error handling section.

Standby servers

Using weighted load balancing, introduced in PECL/mysqlnd 1.4.0, it is possible to configure standby servers that are sparsely used during normal operations. A standby server that is primarily used as a worst-case standby failover target can be assigned a very low weight/priority in relation to all other servers. As long as all servers are up and running the majority of the workload is assigned to the servers which have hight weight values. Few requests will be directed to the standby system which has a very low weight value.

Upon failure of the servers with a high priority, you can still failover to the standby, which has been given a low load balancing priority by assigning a low weight to it. Failover can be some manually or automatically. If done automatically, you may want to combine it with the remember_failed option.

At this point, it is not possible to instruct the load balancer to direct no requests at all to a standby. This may not be much of a limitation given that the highest weight you can assign to a server is 65535. Given two slaves, of which one shall act as a standby and has been assigned a weight of 1, the standby will have to handle far less than one percent of the overall workload.

Failover and primary copy

Please note, if using a primary copy cluster, such as MySQL Replication, it is difficult to do connection failover in case of a master failure. At any time there is only one master in the cluster for a given dataset. The master is a single point of failure. If the master fails, clients have no target to fail over write requests. In case of a master outage the database administrator must take care of the situation and update the client configurations, if need be.

Transient errors
Load balancing
Concepts


Load balancing

Four load balancing strategies are supported to distribute 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.

Servers can be prioritized assigning a weight. A server that has been given a weight of two will get twice as many requests as a server that has been given the default weight of one. Prioritization can be handy in heterogenous environments. For example, you may want to assign more requests to a powerful machine than to a less powerful. Or, you may have configured servers that are close or far from the client, thus expose different latencies.

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().

Nota:

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

Nota: 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.

Nota: 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 behavior. 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 the 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.

Nota: 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

Nota: 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 committed 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 asynchronous 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 slightly 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

Throttling

The quality of service filter can be combined with Global transaction IDs to throttle clients. Throttling does reduce the write load on the master by slowing down clients. If session consistency is requested and global transactions identifier are used to check the status of a slave, the check can be done in two ways. By default a slave is checked and skipped immediately if it does not match the criteria for session consistency. Alternatively, the plugin can wait for a slave to catch up to the master until session consistency is possible. To enable the throttling, you have to set wait_for_gtid_timeout configuration option.

Filter
Global transaction IDs
Concepts


Global transaction IDs

Nota: 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.

As of MySQL 5.6.5-m8 the MySQL server features built-in global transaction identifiers. The MySQL built-in global transaction ID feature is supported by PECL/mysqlnd_ms 1.3.0-alpha or later. Neither are client-side transaction boundary monitoring nor any setup activities required if using the server feature.

Please note, all MySQL 5.6 production versions do not provide clients with enough information to use GTIDs for enforcing session consistency. In the worst case, the plugin will choose the master only.

Idea and client-side emulation

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 promoting 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.

  • Global transaction ID tables must be deployed on all masters and replicas.
  • 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.

Using server-side global transaction identifier

Starting with PECL/mysqlnd_ms 1.3.0-alpha the MySQL 5.6.5-m8 or newer built-in global transaction identifier feature is supported. Use of the server feature lifts all of the above listed limitations. Please, see the MySQL Reference Manual for limitations and preconditions for using server built-in global transaction identifiers.

Whether to use the client-side emulation or the server built-in functionality is a question not directly related to the plugin, thus it is not discussed in depth. There are no plans to remove the client-side emulation and you can continue to use it, if the server-side solution is no option. This may be the case in heterogenous environments with old MySQL server or, if any of the server-side solution limitations is not acceptable.

From an applications perspective there is hardly a difference in using one or the other approach. The following properties differ.

  • Client-side emulation, as shown in the manual, is using an easy to compare sequence number for global transactions. Multi-master is not handled to keep the manual examples easy. Server-side built-in feature is using a combination of a server identifier and a sequence number as a global transaction identifier. Comparison cannot use numeric algebra. Instead a SQL function must be used. Please, see the MySQL Reference Manual for details. Server-side built-in feature of MySQL 5.6 cannot be used to ensure session consistency under all circumstances. Do not use it for the quality-of-service feature. Here is a simple example why it will not give reliable results. There are more edge cases that cannot be covered with limited functionality exported by the server. Currently, clients can ask a MySQL replication master for a list of all executed global transaction IDs only. If a slave is configured not to replicate all transactions, for example, because replication filters are set, then the slave will never show the same set of executed global transaction IDs. Albeit the slave may have replicated a clients writes and it may be a candidate for a consistent read, it will never be considered by the plugin. Upon write the plugin learns from the master that the servers complete transaction history consists of GTID=1..3. There is no way for the plugin to ask for the GTID of the write transaction itself, say GTID=3. Assume that a slave does not replicate the transactions GTID=1..2 but only GTID=3 because of a replication feature. Then, the slaves transaction history is GTID=3. However, the plugin tries to find a node which has a transaction history of GITD=1...3. Albeit the slave has replicated the clients write and session consistency may be achieved when reading from the slave, it will not be considered by the plugin. This is not a fault of the plugin implementation but a feature gap on the server side. Please note, this is a trivial case to illustrate the issue there are other issues. In sum you are asked not to attempt using MySQL 5.6 built-in GTIDs for enforcing session consistency. Sooner or later the load balancing will stop working properly and the plugin will direct all session consistency requests to the master.
  • Plugin global transaction ID statistics are only available with client-side emulation because they monitor the emulation.

Nota: Global transaction identifiers in distributed systems

Global transaction identifiers can serve multiple purposes in the context of distributed systems, such as a database cluster. Global transaction identifiers can be used for, for example, system wide identification of transactions, global ordering of transactions, heartbeat mechanism and for checking the replication status of replicas. PECL/mysqlnd_ms, a clientside driver based software, does focus on using GTIDs for tasks that can be handled at the client, such as checking the replication status of replicas for asynchronous replication setups.

Service level and consistency
Cache integration
Concepts


Cache integration

Nota: Version requirement

The feature requires use of PECL/mysqlnd_ms 1.3.0-beta or later, and PECL/mysqlnd_qc 1.1.0-alpha or newer. PECL/mysqlnd_ms must be compiled to support the feature. PHP 5.4.0 or newer is required.

Nota: Setup: extension load order

PECL/mysqlnd_ms must be loaded before PECL/mysqlnd_qc, when using shared extensions.

Nota: Feature stability

The cache integration is of beta quality.

Nota: Suitable MySQL clusters

The feature is targeted for use with MySQL Replication (primary copy). Currently, no other kinds of MySQL clusters are supported. Users of such cluster must control PECL/mysqlnd_qc manually if they are interested in client-side query caching.

Support for MySQL replication clusters (asynchronous primary copy) is the main focus of PECL/mysqlnd_ms. The slaves of a MySQL replication cluster may or may not reflect the latest updates from the master. Slaves are asynchronous and can lag behind the master. A read from a slave is eventual consistent from a cluster-wide perspective.

The same level of consistency is offered by a local cache using time-to-live (TTL) invalidation strategy. Current data or stale data may be served. Eventually, data searched for in the cache is not available and the source of the cache needs to be accessed.

Given that both a MySQL Replication slave (asynchronous secondary) and a local TTL-driven cache deliver the same level of service it is possible to transparently replace a remote database access with a local cache access to gain better possibility.

As of PECL/mysqlnd_ms 1.3.0-beta the plugin is capable of transparently controlling PECL/mysqlnd_ms 1.1.0-alpha or newer to cache a read-only query if explicitly allowed by setting an appropriate quality of service through mysqlnd_ms_set_qos(). P lease, see the quickstart for a code example. Both plugins must be installed, PECL/mysqlnd_ms must be compiled to support the cache feature and PHP 5.4.0 or newer has to be used.

Applications have full control of cache usage and can request fresh data at any time, if need be. The cache usage can be enabled and disabled time during the execution of a script. The cache will be used if mysqlnd_ms_set_qos() sets the quality of service to eventual consistency and enables cache usage. Cache usage is disabled by requesting higher consistency levels, for example, session consistency (read your writes). Once the quality of service has been relaxed to eventual consistency the cache can be used again.

If caching is enabled for a read-only statement, PECL/mysqlnd_ms may inject SQL hints to control caching by PECL/mysqlnd_qc. It may modify the SQL statement it got from the application. Subsequent SQL processors are supposed to ignore the SQL hints. A SQL hint is a SQL comment. Comments must not be ignored, for example, by the database server.

The TTL of a cache entry is computed on a per statement basis. Applications set an maximum age for the data they want to retrieve using mysqlnd_ms_set_qos(). The age sets an approximate upper limit of how many seconds the data returned may lag behind the master.

The following logic is used to compute the actual TTL if caching is enabled. The logic takes the estimated slave lag into account for choosing a TTL. If, for example, there are two slaves lagging 5 and 10 seconds behind and the maximum age allowed is 60 seconds, the TTL is set to 50 seconds. Please note, the age setting is no more than an estimated guess.

  • Check whether the statement is read-only. If not, don't cache.
  • If caching is enabled, check the slave lag of all configured slaves. Establish slave connections if none exist so far and lazy connections are used.
  • Send SHOW SLAVE STATUS to all slaves. Do not wait for the first slave to reply before sending to the second slave. Clients often wait long for replies, thus we send out all requests in a burst before fetching in a second stage.
  • Loop over all slaves. For every slave wait for its reply. Do not start checking another slave before the currently waited for slave has replied. Check for Slave_IO_Running=Yes and Slave_SQL_Running=Yes. If both conditions hold true, fetch the value of Seconds_Behind_Master. In case of any errors or if conditions fail, set an error on the slave connection. Skip any such slave connection for the rest of connection filtering.
  • Search for the maximum value of Seconds_Behind_Master from all slaves that passed the previous conditions. Subtract the value from the maximum age provided by the user with mysqlnd_ms_set_qos(). Use the result as a TTL.
  • The filtering may sort out all slaves. If so, the maximum age is used as TTL, because the maximum lag found equals zero. It is perfectly valid to sort out all slaves. In the following it is up to subsequent filter to decide what to do. The built-in load balancing filter will pick the master.
  • Inject the appropriate SQL hints to enable caching by PECL/mysqlnd_qc.
  • Proceed with the connection filtering, e.g. apply load balancing rules to pick a slave.
  • PECL/mysqlnd_qc is loaded after PECL/mysqlnd_ms by PHP. Thus, it will see all query modifications of PECL/mysqlnd_ms and cache the query if instructed to do so.

The algorithm may seem expensive. SHOW SLAVE STATUS is a very fast operation. Given a sufficient number of requests and cache hits per second the cost of checking the slaves lag can easily outweigh the costs of the cache decision.

Suggestions on a better algorithm are always welcome.

Global transaction IDs
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 (primary copy). When using classical, asynchronous MySQL replication all of the above listed tasks need to be mastered at the client side.

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 (multi-master, update-all). If all nodes in the cluster are synchronous, they automatically provide the highest possible quality of service which makes choosing a node easier. In this case, the plugin may serve the application after some reconfiguration to disable certain features, such as built-in read-write splitting.

Nota: Documentation focus

The documentation focusses describing the use of the plugin with classical asynchronous MySQL replication clusters (primary copy). 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.

Primary copy (MySQL Replication)

This is the primary use case of the plugin. Follow the hints given in the descriptions of each feature.

  • Configure one master and one or more slaves. Server configuration details are given in the setup section.
  • Use random load balancing policy together with the sticky flag.
  • If you do not plan to use the service level API calls, add the master on write flag.
  • Please, make yourself aware of the properties of automatic failover before adding a failover directive.
  • Consider the use of trx_stickiness to execute transactions on the primary only. Please, read carefully how it works before you rely on it.

Example #1 Enabling the plugin (php.ini)

mysqlnd_ms.enable=1
mysqlnd_ms.config_file=/path/to/mysqlnd_ms_plugin.ini

Example #2 Basic plugin configuration (mysqlnd_ms_plugin.ini) for MySQL Replication

{
  "myapp": {
    "master": {
      "master_1": {
        "host": "localhost",
        "socket": "\/tmp\/mysql57.sock"
      }
    },
    "slave": {
      "slave_0": {
        "host": "127.0.0.1",
        "port": 3308
      },
      "slave_1": {
        "host": "192.168.2.28",
        "port": 3306
      }
    },
    "filters": {
      "random": {
        "sticky": "1"
      }
    }
  }
}

Primary copy with multi primaries (MMM - MySQL Multi Master)

MySQL Replication allows you to create cluster topologies with multiple masters (primaries). Write-write conflicts are not handled by the replication system. This is no update anywhere setup. Thus, data must be partitioned manually and clients must redirected in accordance to the partitioning rules. The recommended setup is equal to the sharding setup below.

Manual sharding, possibly combined with primary copy and multiple primaries

Use SQL hints and the node group filter for clusters that use data partitioning but leave query redirection to the client. The example configuration shows a multi master setup with two shards.

Example #3 Multiple primaries - multi master (php.ini)

mysqlnd_ms.enable=1
mysqlnd_ms.config_file=/path/to/mysqlnd_ms_plugin.ini
mysqlnd_ms.multi_master=1

Example #4 Primary copy with multiple primaries and paritioning

{
  "myapp": {
    "master": {
      "master_1": {
        "host": "localhost",
        "socket": "\/tmp\/mysql57.sock"
      }
      "master_2": {
        "host": "192.168.2.27",
        "socket": "3306"
      }
    },
    "slave": {
      "slave_1": {
        "host": "127.0.0.1",
        "port": 3308
      },
      "slave_2": {
        "host": "192.168.2.28",
        "port": 3306
      }
    },
    "filters": {
      "node_groups": {
        "Partition_A" : {
          "master": ["master_1"],
          "slave": ["slave_1"]
        },
        "Partition_B" : {
          "master": ["master_2"],
          "slave": ["slave_2"]
        }
      },
      "roundrobin": []
    }
  }
}

The plugin can also be used with a loose collection of unrelated shards. For such a cluster, configure masters only and disable read write splitting. The nodes of such a cluster are called masters in the plugin configuration as they accept both reads and writes for their partition.

Using synchronous update everywhere 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 appropriate 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=loop_before_master in the plugins configuration file to avoid warnings about the empty slave list and to make the failover logic loop over all configured masters before emitting an error. Please, note the warnings about automatic failover given in the previous sections.

Example #5 Multiple primaries - multi master (php.ini)

mysqlnd_ms.enable=1
mysqlnd_ms.config_file=/path/to/mysqlnd_ms_plugin.ini
mysqlnd_ms.multi_master=1
mysqlnd_ms.disable_rw_split=1

Example #6 Synchronous update anywhere cluster

"myapp": {
    "master": {
      "master_1": {
        "host": "localhost",
        "socket": "\/tmp\/mysql57.sock"
      },
      "master_2": {
        "host": "192.168.2.28",
        "port": 3306
      }
    },
    "slave": {
    },
    "filters": {
      "roundrobin": {
      }
    },
    "failover": {
      "strategy": "loop_before_master",
      "remember_failed": true
    }
  }
}

If running an update everywhere cluster that has no built-in partitioning to avoid hot spots and high collision rates, consider using the node groups filter to keep updates on a frequently accessed table on one of the nodes. This may help to reduce collision rates and thus improve performance.

Cache integration
XA/Distributed transactions
Concepts


XA/Distributed transactions

Nota: Version requirement

XA related functions have been introduced in PECL/mysqlnd_ms version 1.6.0-alpha.

Nota: Early adaptors wanted

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments, although early lab tests indicate reasonable quality.

Please, contact the development team if you are interested in this feature. We are looking for real life feedback to complement the feature.

Below is a list of some feature restrictions.

  • The feature is not yet compatible with the MySQL Fabric support . This limitation is soon to be lifted.

    XA transaction identifier are currently restricted to numbers. This limitation will be lifted upon request, it is a simplification used during the initial implementation.

Nota: MySQL server restrictions

The XA support by the MySQL server has some restrictions. Most noteably, the servers binary log may lack changes made by XA transactions in case of certain errors. Please, see the MySQL manual for details.

XA/Distributed transactions can spawn multiple MySQL servers. Thus, they may seem like a perfect tool for sharded MySQL clusters, for example, clusters managed with MySQL Fabric. PECL/mysqlnd_ms hides most of the SQL commands to control XA transactions and performs automatic administrative tasks in cases of errors, to provide the user with a comprehensive API. Users should setup the plugin carefully and be well aware of server restrictions prior to using the feature.

Example #1 General pattern for XA transactions

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");

/* BEGIN */
mysqlnd_ms_xa_begin($mysqli, 1 /* xa id */);

/* run queries on various servers */
$mysqli->query("UPDATE some_table SET col_a = 1");
...

/* COMMIT */
mysqlnd_ms_xa_commit($link, 1);
?>

XA transactions use the two-phase commit protocol. The two-phase commit protocol is a blocking protocol. During the first phase participating servers begin a transaction and the client carries out its work. This phase is followed by a second voting phase. During voting, the servers first make a firm promise that they are ready to commit the work even in case of their possible unexpected failure. Should a server crash in this phase, it will still recall the aborted transaction after recover and wait for the client to decide on whether it shall be committed or rolled back.

Should a client that has initiated a global transaction crash after all the participating servers gave their promise to be ready to commit, then the servers must wait for a decision. The servers are not allowed to unilaterally decide on the transaction.

A client crash or disconnect from a participant, a server crash or server error during the fist phase of the protocol is uncritical. In most cases, the server will forget about the XA transaction and its work is rolled back. Additionally, the plugin tries to reach out to as many participants as it can to instruct the server to roll back the work immediately. It is not possible to disable this implicit rollback carried out by PECL/mysqlnd_ms in case of errors during the first phase of the protocol. This design decision has been made to keep the implementation simple.

An error during the second phase of the commit protocol can develop into a more severe situation. The servers will not forget about prepared but unfinished transactions in all cases. The plugin will not attempt to solve these cases immediately but waits for optional background garbage collection to ensure progress of the commit protocol. It is assumed that a solution will take significant time as it may include waiting for a participating server to recover from a crash. This time span may be longer than a developer and end user expects when trying to commit a global transaction with mysqlnd_ms_xa_commit(). Thus, the function returns with the unfinished global transaction still requiring attention. Please, be warned that at this point, it is not yet clear whether the global transaction will be committed or rolled back later on.

Errors during the second phase can be ignored, handled by yourself or solved by the build-int garbage collection logic. Ignoring them is not recommended as you may experience unfinished global transactions on your servers that block resources virtually indefinitely. Handling the errors requires knowing the participants, checking their state and issuing appropriate SQL commands on them. There are no user API calls to expose this very information. You will have to configure a state store and make the plugin record its actions in it to receive the desired facts.

Please, see the quickstart and related plugin configuration file settings for an example how to configure a state. In addition to configuring a state store, you have to setup some SQL tables. The table definitions are given in the description of the plugin configuration settings.

Setting up and configuring a state store is also a precondition for using the built-in garbage collection for XA transactions that fail during the second commit phase. Recording information about ongoing XA transactions is an unavoidable extra task. The extra task consists of updating the state store after each and every operation that changes the state of the global transaction itself (started, committed, rolled back, errors and aborts), the addition of participants (host, optionally user and password required to connect) and any changes to a participants state. Please note, depending on configuration and your security policies, these recordings may be considered sensitive. It is therefore recommended to restrict access to the state store. Unless the state store itself becomes overloaded, writing the state information may contribute noteworthy to the runtime but should overall be only a minor factor.

It is possible that the effort it takes to implement your own routines for handling XA transactions that failed during the second commit phase exceeds the benefits of using the XA feature of PECL/mysqlnd_ms in the first place. Thus, the manual focussed on using the built-on garbage collection only.

Garbage collection can be triggered manually or automatically in the background. You may want to call mysqlnd_ms_xa_gc() immediately after a commit failure to attempt to solve any failed but still open global transactions as soon as possible. You may also decide to disable the automatic background garbage collection, implement your own rule set for invoking the built-in garbage collection and trigger it when desired.

By default the plugin will start the garbage collection with a certain probability in the extensions internal RSHUTDOWN method. The request shutdown is called after your script finished. Whether the garbage collection will be triggered is determined by computing a random value between 1...1000 and comparing it with the configuration setting probability (default: 5). If the setting is greater or equal to the random value, the garbage collection will be triggered.

Once started, the garbage collection acts upon up to max_transactions_per_run (default: 100) global transactions recorded. Records include successfully finished but also unfinished XA transactions. Records for successful transactions are removed and unfinished transactions are attempted to be solved. There are no statistics that help you finding the right balance between keeping garbage collection runs short by limiting the number of transactions considered per run and preventing the garbage collection to fall behind, resulting in many records.

For each failed XA transaction the garbage collection makes max_retries (default: 5) attempts to finish it. After that PECL/mysqlnd_ms gives up. There are two possible reasons for this. Either a participating server crashed and has not become accessible again within max_retries invocations of the garbage collection, or there is a situation that the built-in garbage collection cannot cope with. Likely, the latter would be considered a bug. However, you can manually force more garbage collection runs calling mysqlnd_ms_xa_gc() with the appropriate parameter set. Should even those function runs fail to solve the situation, then the problem must be solved by an operator.

The function mysqlnd_ms_get_stats() provides some statistics on how many XA transactions have been started, committed, failed or rolled back.

Supported clusters
Instalarea / configurarea
Concepts


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Plugin configuration file (>=1.1.x)
XA/Distributed transactions
Necesita?i
mysqlnd_ms


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/mysqlnd_ms

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Mysqlnd_ms Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.config_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 |

Iata o explica?ie pe scurt a directivelor de configurare.

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.

This setting is not only useful to restrict PHP to certain servers but also to debug configuration file problems. The configuration file validity is checked at two different stages. The first check is performed when PHP begins to handle a web request. At this point the plugin reads and decodes the configuration file. Errors thrown at this early stage in an extensions life cycle may not be shown properly to the user. Thus, the plugin buffers the errors, if any, and additionally displays them when establishing a connection to MySQL. By default a buffered startup error will emit an error of type E_WARNING. If force_config_usage is set, the error type used is E_RECOVERABLE_ERROR.

Please, see also configuration file debugging notes.

mysqlnd_ms.ini_file string

Plugin specific configuration file. This setting has been renamed to mysqlnd_ms.config_file in version 1.4.0.

mysqlnd_ms.config_file string

Plugin specific configuration file. This setting superseeds mysqlnd_ms.ini_file since 1.4.0.

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.

Nota: 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.

Instalarea
Plugin configuration file (>=1.1.x)
Instalarea / configurarea


Plugin configuration file (>=1.1.x)

The following documentation applies to PECL/mysqlnd_ms >= 1.1.0-beta. It is not valid for prior versions. For documentation covering earlier versions, see the configuration documentation for mysqlnd_ms 1.0.x and below.

Introduction

Nota: 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.config_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.

Example #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));
?>

Exemplul de mai sus va afi?a:

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.

Example #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 asynchronous 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.

Example #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.

Example #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.

Example #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.

Example #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().

Example #7 The user filter replaces mysqlnd_ms_set_user_pick_server()

"filters": {
    "user": {
        "callback": "pick_server"
    }
}

The validity of the configuration file is checked both when reading the configuration file and later when establishing a connection. The configuration file is read during PHP request startup. At this early stage a PHP extension may not display error messages properly. In the worst case, no error is shown and a connection attempt fails without an adequate error message. This problem has been cured in version 1.5.0.

Example #8 Common error message in case of configuration file issues (upto version 1.5.0)

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
?>

Exemplul de mai sus va afi?a:

Warning: mysqli::mysqli(): (mysqlnd_ms) (mysqlnd_ms) Failed to parse config file [s1.json]. Please, verify the JSON in Command line code

Warning: mysqli::mysqli(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: Name or service not known in Command line code on line 1

Warning: mysqli::query(): Couldn't fetch mysqli in Command line code on line 1

Fatal error: Call to a member function fetch_assoc() on a non-object in Command line code on line 1

Since version 1.5.0 startup errors are additionally buffered and emitted when a connection attempt is made. Use the configuration directive mysqlnd_ms.force_config_usage to set the error type used to display buffered errors. By default an error of type E_WARNING will be emitted.

Example #9 Improved configuration file validation since 1.5.0

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
?>

Exemplul de mai sus va afi?a:

Warning: mysqli::mysqli(): (mysqlnd_ms) (mysqlnd_ms) Failed to parse config file [s1.json]. Please, verify the JSON in Command line code on line 1

It can be useful to set mysqlnd_ms.force_config_usage = 1 when debugging potential configuration file errors. This will not only turn the type of buffered startup errors into E_RECOVERABLE_ERROR but also help detecting misspelled section names.

Example #10 Possibly more precise error due to mysqlnd_ms.force_config_usage=1

mysqlnd_ms.force_config_usage=1
<?php
$mysqli = new mysqli("invalid_section", "username", "password", "database");
?>

Exemplul de mai sus va afi?a:

Warning: mysqli::mysqli(): (mysqlnd_ms) Exclusive usage of configuration enforced but did not find the correct INI file section (invalid_section) in Command line code on line 1 line 1

Configuration Directives

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.

global_transaction_id_injection array or object

Global transaction identifier configuration related to both the use of the server built-in global transaction ID feature and the client-side emulation.

Keyword Description Version
fetch_last_gtid

SQL statement for accessing the latest global transaction identifier. The SQL statement is run if the plugin needs to know the most recent global transaction identifier. This can be the case, for example, when checking MySQL Replication slave status. Also used with mysqlnd_ms_get_last_gtid().

Since 1.2.0.
check_for_gtid

SQL statement for checking if a replica has replicated all transactions up to and including ones searched for. The SQL statement is run when searching for replicas which can offer a higher level of consistency than eventual consistency. The statement must contain a placeholder #GTID which is to be replaced with the global transaction identifier searched for by the plugin. Please, check the quickstart for examples.

Since 1.2.0.
report_errors

Whether to emit an error of type warning if an issue occurs while executing any of the configured SQL statements.

Since 1.2.0.
on_commit

Client-side global transaction ID emulation only. SQL statement to run when a transaction finished to update the global transaction identifier sequence number on the master. Please, see the quickstart for examples.

Since 1.2.0.
wait_for_gtid_timeout

Instructs the plugin to wait up to wait_for_gtid_timeout seconds for a slave to catch up when searching for slaves that can deliver session consistency. The setting limits the time spend for polling the slave status. If polling the status takes very long, the total clock time spend waiting may exceed wait_for_gtid_timeout. The plugin calls sleep(1) to sleep one second between each two polls.

The setting can be used both with the plugins client-side emulation and the server-side global transaction identifier feature of MySQL 5.6.

Waiting for a slave to replicate a certain GTID needed for session consistency also means throttling the client. By throttling the client the write load on the master is reduced indirectly. A primary copy based replication system, such as MySQL Replication, is given more time to reach a consistent state. This can be desired, for example, to increase the number of data copies for high availability considerations or to prevent the master from being overloaded.

Since 1.4.0.
fabric object

MySQL Fabric related settings. If the plugin is used together with MySQL Fabric, then the plugins configuration file no longer contains lists of MySQL servers. Instead, the plugin will ask MySQL Fabric which list of servers to use to perform a certain task.

A minimum plugin configuration for use with MySQL Fabric contains a list of one or more MySQL Fabric hosts that the plugin can query. If more than one MySQL Fabric host is configured, the plugin will use a roundrobin strategy to choose among them. Other strategies are currently not available.

Example #11 Minimum pluging configuration for use with MySQL Fabric

{
    "myapp": {
        "fabric": {
            "hosts": [
                {
                    "host" : "127.0.0.1",
                    "port" : 8080
                }
            ]
        }
    }
}

Each MySQL Fabric host is described using a JSON object with the following members.

Keyword Description Version
host

Host name of the MySQL Fabric host.

Since 1.6.0.
port

The TCP/IP port on which the MySQL Fabric host listens for remote procedure calls sent by clients such as the plugin.

Since 1.6.0.

The plugin is using PHP streams to communicate with MySQL Fabric through XML RPC over HTTP. By default no timeouts are set for the network communication. Thus, the plugin defaults to PHP stream default timeouts. Those defaults are out of control of the plugin itself.

An optional timeout value can be set to overrule the PHP streams default timeout setting. Setting the timeout in the plugins configuration file has the same effect as setting a timeout for a PHP user space HTTP connection established through PHP streams.

The plugins Fabric timeout value unit is seconds. The allowed value range is from 0 to 65535. The setting exists since version 1.6.

Example #12 Optional timeout for communication with Fabric

{
    "myapp": {
        "fabric": {
            "hosts": [
                {
                    "host" : "127.0.0.1",
                    "port" : 8080
                }
            ],
            "timeout": 2
        }
    }
}

Transaction stickiness and MySQL Fabric logic can collide. The stickiness option disables switching between servers for the duration of a transaction. When using Fabric and sharding the user may (erroneously) start a local transaction on one share and then attempt to switch to a different shard using either mysqlnd_ms_fabric_select_shard() or mysqlnd_ms_fabric_select_global(). In this case, the plugin will not reject the request to switch servers in the middle of a transaction but allow the user to switch to another server regardless of the transaction stickiness setting used. It is clearly a user error to write such code.

If transaction stickiness is enabled and you would like to get an error of type warning when calling mysqlnd_ms_fabric_select_shard() or mysqlnd_ms_fabric_select_global(), set the boolean flag trx_warn_server_list_changes.

Example #13 Warnings about the violation of transaction boundaries

{
    "myapp": {
        "fabric": {
            "hosts": [
                {
                    "host" : "127.0.0.1",
                    "port" : 8080
                }
            ],
            "trx_warn_serverlist_changes": 1
        },
        "trx_stickiness": "on"
    }
}
<?php
$link = new mysqli("myapp", "root", "", "test");
/*
  For the demo the call may fail.
  Failed or not we get into the state
  needed for the example.
*/
@mysqlnd_ms_fabric_select_global($link, 1);
$link->begin_transaction();
@$link->query("DROP TABLE IF EXISTS test");
/*
  Switching servers/shards is a mistake due to open
  local transaction!
*/
mysqlnd_ms_select_global($link, 1);
?>

Exemplul de mai sus va afi?a:

PHP Warning: mysqlnd_ms_fabric_select_global(): (mysqlnd_ms) Fabric server exchange in the middle of a transaction in %s on line %d

Please, consider the feature experimental. Changes to syntax and semantics may happen.

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. Furthermore, 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.

Example #14 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");
?>

Exemplul de mai sus va afi?a:

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.

Example #15 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.

Example #16 Random once load balancing with random filter

{
    "filters": {
        "random": {
            "sticky": "1"
        }
    }
}

Both the random and roundrobin filters support setting a priority, a weight for a server, since PECL/mysqlnd_ms 1.4.0. If the weight argument is passed to the filter, it must assign a weight for all servers. Servers must be given an alias name in the slave respectively master server lists. The alias must be used to reference servers for assigning a priority with weight.

Example #17 Referencing error

[E_RECOVERABLE_ERROR] mysqli_real_connect(): (mysqlnd_ms) Unknown server 'slave3' in 'random' filter configuration. Stopping in %s on line %d

Using a wrong alias name with weight may result in an error similar to the shown above.

If weight is omitted, the default weight of all servers is one.

Example #18 Assigning a weight for load balancing

{
   "myapp": {
       "master": {
           "master1":{
               "host":"localhost",
               "socket":"\/var\/run\/mysql\/mysql.sock"
           }
       },
       "slave": {
           "slave1": {
               "host":"192.168.2.28",
               "port":3306
           },
           "slave2": {
               "host":"192.168.2.29",
               "port":3306
           },
           "slave3": {
               "host":"192.0.43.10",
               "port":3306
           },
       },
       "filters": {
           "random": {
               "weights": {
                   "slave1":8,
                   "slave2":4,
                   "slave3":1,
                   "master1":1
               }
           }
       }
   }
}

At the average a server assigned a weight of two will be selected twice as often as a server assigned a weight of one. Different weights can be assigned to reflect differently sized machines, to prefer co-located slaves which have a low network latency or, to configure a standby failover server. In the latter case, you may want to assign the standby server a very low weight in relation to the other servers. For example, given the configuration above slave3 will get only some eight percent of the requests in the average. As long as slave1 and slave2 are running, it will be used sparsely, similar to a standby failover server. Upon failure of slave1 and slave2, the usage of slave3 increases. Please, check the notes on failover before using weight this way.

Valid weight values range from 1 to 65535.

Unknown arguments are ignored by the filter. No warning or error is given.

The filter 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.

List of filter arguments.

Keyword Description Version
sticky

Enables or disabled random once load balancing policy. See above.

Since 1.2.0.
weight

Assigns a load balancing weight/priority to a server. Please, see above for a description.

Since 1.4.0.
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.

Example #19 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.

List of filter arguments.

Keyword Description Version
weight

Assigns a load balancing weight/priority to a server. Please, find a description above.

Since 1.4.0.
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 chooses 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.

Example #20 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 whether 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 before PHP 5.4.0. Please, see connection pooling and switching concepts discussion for further details.

Since 1.1.0.

Example #21 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();
?>

Exemplul de mai sus va afi?a:

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 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.

Example #22 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 behavior 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: node_groups object

The node_groups filter lets you group cluster nodes and query selected groups, for example, to support data partitioning. Data partitioning can be required for manual sharding, primary copy based clusters running multiple masters, or to avoid hot spots in update everywhere clusters that have no built-in partitioning. The filter 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.

Keyword Description Version
user defined node group name

One or more node groups must be defined. A node group can have an arbitrary user defined name. The name is used in combination with a SQL hint to restrict query execution to the nodes listed for the node group. To run a query on any of the servers of a node group, the query must begin with the SQL hint /*user defined node group name*/. Please note, no white space is allowed around user defined node group name. Because user defined node group name is used as-is as part of a SQL hint, you should choose the name that is compliant with the SQL language.

Each node group entry must contain a list of master servers. Additional slave servers are allowed. Failing to provide a list of master for a node group name_of_group may cause an error of type E_RECOVERABLE_ERROR like (mysqlnd_ms) No masters configured in node group 'name_of_group' for 'node_groups' filter.

The list of master and slave servers must reference corresponding entries in the global master respectively slave server list. Referencing an unknown server in either of the both server lists may cause an E_RECOVERABLE_ERROR error like (mysqlnd_ms) Unknown master 'server_alias_name' (section 'name_of_group') in 'node_groups' filter configuration.

Example #23 Manual partitioning

{
  "myapp": {
       "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.28",
                "port": 3306
            },
            "slave_1": {
                "host": "127.0.0.1",
                "port": 3311
            }
        },
        "filters": {
            "node_groups": {
                "Partition_A" : {
                    "master": ["master_0"],
                    "slave": ["slave_0"]
                }
            },
           "roundrobin": []
        }
    }
}

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.

Since 1.5.0.
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 replication lag is measure using SHOW SLAVE STATUS. If the plugin fails to fetch the replication lag, the slave tested is skipped. Implementation details and tips 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.

Example #24 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 caught 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 continue operation at a lower consistency level after it has done some critical reads.

Since 1.1.0.
strong_consistency

Request strong consistency. Only masters will be used.

Since 1.2.0.
failover Up to and including 1.3.x: string. Since 1.4.0: object.

Failover policy. Supported policies: disabled (default), master, loop_before_master (Since 1.4.0).

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.

Please note, the automatic failover logic is applied when opening connections only. Once a connection has been opened no automatic attempts are made to reopen it in case of an error. If, for example, the server a connection is connected to is shut down and the user attempts to run a statement on the connection, no automatic failover will be tried. Instead, an error will be reported.

If using failover=master the plugin will implicitly failover to a master, if available. Please check the concepts documentation to learn about potential pitfalls and risks of using failover=master.

Example #25 Optional master failover when failing to connect to slave (PECL/mysqlnd_ms < 1.4.0)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "failover": "master"
    }
}

Since PECL/mysqlnd_ms 1.4.0 the failover configuration keyword refers to an object.

Example #26 New syntax since 1.4.0

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "failover": {"strategy": "master" }
    }
}

Keyword Description Version
strategy

Failover policy. Possible values: disabled (default), master, loop_before_master

A value of disabled disables automatic failover.

Setting master instructs the plugin to try to connect to a master in case of a slave connection error. If the master connection attempt fails, the plugin exists the failover loop and returns an error to the user.

If using loop_before_master and a slave request is made, the plugin tries to connect to other slaves before failing over to a master. If multiple master are given and multi master is enabled, the plugin also loops over the list of masters and attempts to connect before returning an error to the user.

Since 1.4.0.
remember_failed

Remember failures for the duration of a web request. Default: false.

If set to true the plugin will remember failed hosts and skip the hosts in all future load balancing made for the duration of the current web request.

Since 1.4.0. The feature is only available together with the random and roundrobin load balancing filter. Use of the setting is recommended.
max_retries

Maximum number of connection attempts before skipping host. Default: 0 (no limit).

The setting is used to prevent hosts from being dropped of the host list upon the first failure. If set to n > 0, the plugin will keep the node in the node list even after a failed connection attempt. The node will not be removed immediately from the slave respectively master lists after the first connection failure but instead be tried to connect to up to n times in future load balancing rounds before being removed.

Since 1.4.0. The feature is only available together with the random and roundrobin load balancing filter.

Setting failover to any other value but disabled, master or loop_before_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.

Example #27 Disabling lazy connection

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "lazy_connections": 0
    }
}

Please, see also server_charset to overcome potential problems with string escaping and servers using different default charsets.

server_charset string

The setting has been introduced in 1.4.0. It is recommended to set it if using lazy connections.

The server_charset setting serves two purposes. It acts as a fallback charset to be used for string escaping done before a connection has been established and it helps to avoid escaping pitfalls in heterogeneous environments which servers using different default charsets.

String escaping takes a connections charset into account. String escaping is not possible before a connection has been opened and the connections charset is known. The use of lazy connections delays the actual opening of connections until a statement is send.

An application using lazy connections may attempt to escape a string before sending a statement. In fact, this should be a common case as the statement string may contain the string that is to be escaped. However, due to the lazy connection feature no connection has been opened yet and escaping fails. The plugin may report an error of the type E_WARNING and a message like (mysqlnd_ms) string escaping doesn't work without established connection. Possible solution is to add server_charset to your configuration to inform you of the pitfall.

Setting server_charset makes the plugin use the given charset for string escaping done on lazy connection handles before establishing a network connection to MySQL. Furthermore, the plugin will enforce the use of the charset when the connection is established.

Enforcing the use of the configured charset used for escaping is done to prevent tapping into the pitfall of using a different charset for escaping than used later for the connection. This has the additional benefit of removing the need to align the charset configuration of all servers used. No matter what the default charset on any of the servers is, the plugin will set the configured one as a default.

The plugin does not stop the user from changing the charset at any time using the set_charset() call or corresponding SQL statements. Please, note that the use of SQL is not recommended as it cannot be monitored by the plugin. The user can, for example, change the charset on a lazy connection handle after escaping a string and before the actual connection is opened. The charset set by the user will be used for any subsequent escaping before the connection is established. The connection will be established using the configured charset, no matter what the server charset is or what the user has set before. Once a connection has been opened, set_charset is of no meaning anymore.

Example #28 String escaping on a lazy connection handle

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "lazy_connections": 1,
        "server_charset" : "utf8"
    }
}
<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
$mysqli->real_escape("this will be escaped using the server_charset setting - utf8");
$mysqli->set_charset("latin1");
$mysqli->real_escape("this will be escaped using latin1");
/* server_charset implicitly set - utf8 connection */
$mysqli->query("SELECT 'This connection will be set to server_charset upon establishing' AS _msg FROM DUAL");
/* latin1 used from now on */
$mysqli->set_charset("latin1");
?>

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.

Example #29 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.

All transaction stickiness settings, including trx_stickiness=on, are overruled by master_on_write=1.

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 trx_stickiness=master, the plugin cannot be made aware of autocommit mode changes caused by SQL statements such as SET AUTOCOMMIT=0 or BEGIN.

As of PHP 5.5.0, the mysqlnd library features additional C API calls to control transactions. The level of control matches the one offered by SQL statements. The mysqli API has been modified to use these calls. Since version 1.5.0, PECL/mysqlnd_ms can monitor not only mysqli_autocommit(), but also mysqli_begin(), mysqli_commit() and mysqli_rollback() to detect transaction boundaries and stop load balancing for the duration of a transaction.

Example #30 Using master to execute transactions

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "trx_stickiness": "master"
    }
}

Since version 1.5.0 automatic and silent failover is disabled for the duration of a transaction. If the boundaries of a transaction have been properly detected, transaction stickiness is enabled and a server fails, the plugin will not attempt to fail over to the next server, if any, regardless of the failover policy configured. The user must handle the error manually. Depending on the configuration, the plugin may emit an error of type E_WARNING reading like (mysqlnd_ms) Automatic failover is not permitted in the middle of a transaction. This error may then be overwritten by follow up errors such as (mysqlnd_ms) No connection selected by the last filter. Those errors will be generated by the failing query function.

Example #31 No automatic failover, error handling pitfall

<?php
/* assumption: automatic failover configured */
$mysqli = new mysqli("myapp", "username", "password", "database");

/* sets plugin internal state in_trx = 1 */
$mysqli->autocommit(false);

/* assumption: server fails */
if (!($res = $mysqli->query("SELECT 'Assume this query fails' AS _msg FROM DUAL"))) {
 /* handle failure of transaction, plugin internal state is still in_trx = 1 */
 printf("[%d] %s", $mysqli->errno, $mysqli->error);
 /*
  If using autocommit() based transaction detection it is a
  MUST to call autocommit(true). Otherwise the plugin assumes
  the current transaction continues and connection
  changes remain forbidden.
 */
 $mysqli->autocommit(true);
 /* Likewise, you'll want to start a new transaction */
 $mysqli->autocommit(false);
}
/* latin1 used from now on */
$mysqli->set_charset("latin1");
?>

If a server fails in the middle of a transaction the plugin continues to refuse to switch connections until the current transaction has been finished. Recall that the plugin monitors API calls to detect transaction boundaries. Thus, you have to, for example, enable auto commit mode to end the current transaction before the plugin continues load balancing and switches the server. Likewise, you will want to start a new transaction immediately thereafter and disable auto commit mode again.

Not handling failed queries and not ending a failed transaction using API calls may cause all following commands emit errors such as Commands out of sync; you can't run this command now. Thus, it is important to handle all errors.

transient_error object

The setting has been introduced in 1.6.0.

A database cluster node may reply a transient error to a client. The client can then repeat the operation on the same node, fail over to a different node or abort the operation. Per definition is it safe for a client to retry the same operation on the same node before giving up.

PECL/mysqlnd_ms can perform the retry loop on behalf of the application. By configuring transient_error the plugin can be instructed to repeat operations failing with a certain error code for a certain maximum number of times with a pause between the retries. If the transient error disappears during loop execution, it is hidden from the application. Otherwise, the error is forwarded to the application by the end of the loop.

Example #32 Retry loop for transient errors

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
       },
       "transient_error": {
          "mysql_error_codes": [
            1297
          ],
          "max_retries": 2,
          "usleep_retry": 100
       }
    }
}

Keyword Description Version
mysql_error_codes

List of transient error codes. You may add any MySQL error code to the list. It is possible to consider any error as transient not only 1297 (HY000 (ER_GET_TEMPORARY_ERRMSG), Message: Got temporary error %d '%s' from %s). Before adding other codes but 1297 to the list, make sure your cluster supports a new attempt without impacting the state of your application.

Since 1.6.0.
max_retries

How often to retry an operation which fails with a transient error before forwarding the failure to the user.

Default: 1

Since 1.6.0.
usleep_retry

Milliseconds to sleep between transient error retries. The value is passed to the C function usleep(), hence the name.

Default: 100

Since 1.6.0.
xa object

The setting has been introduced in 1.6.0.

Nota: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

state_store
record_participant_credentials

Whether to store the username and password of a global transaction participant in the participants table. If disabled, the garbage collection will use the default username and password when connecting to the participants. Unless you are using a different username and password for each of your MySQL servers, you can use the default and avoid storing the sensible information in state store.

Please note, username and password are stored in clear text when using the MySQL state store, which is the only one available. It is in your responsibility to protect this sensible information.

Default: false

participant_localhost_ip

During XA garbage collection the plugin may find a participant server for which the host localhost has been recorded. If the garbage collection takes place on another host but the host that has written the participant record to the state store, the host name localhost now resolves to a different host. Therefore, when recording a participant servers host name in the state store, a value of localhost must be replaced with the actual IP address of localhost.

Setting participant_localhost_ip should be considered only if using localhost cannot be avoided. From a garbage collection point of view only, it is preferrable not to configure any socket connection but to provide an IP address and port for a node.

mysql

The MySQL state store is the only state store available.

global_trx_table

Name of the MySQL table used to store the state of an ongoing or aborted global transaction. Use the below SQL statement to create the table. Make sure to edit the table name to match your configuration.

Default: mysqlnd_ms_xa_trx

Example #33 SQL definition for the MySQL state store transaction table

CREATE TABLE mysqlnd_ms_xa_trx (
  store_trx_id int(11) NOT NULL AUTO_INCREMENT,
  gtrid int(11) NOT NULL,
  format_id int(10) unsigned NOT NULL DEFAULT '1',
  state enum('XA_NON_EXISTING','XA_ACTIVE','XA_IDLE','XA_PREPARED','XA_COMMIT','XA_ROLLBACK') NOT NULL DEFAULT 'XA_NON_EXISTING',
  intend enum('XA_NON_EXISTING','XA_ACTIVE','XA_IDLE','XA_PREPARED','XA_COMMIT','XA_ROLLBACK') DEFAULT 'XA_NON_EXISTING',
  finished enum('NO','SUCCESS','FAILURE') NOT NULL DEFAULT 'NO',
  modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  started datetime DEFAULT NULL,
  timeout datetime DEFAULT NULL,
  PRIMARY KEY (store_trx_id),
  KEY idx_xa_id (gtrid,format_id,finished),
  KEY idx_state (state)
) ENGINE=InnoDB

participant_table

Name of the MySQL table used to store participants of an ongoing or aborted global transaction. Use the below SQL statement to create the table. Make sure to edit the table name to match your configuration.

Storing credentials can be enabled and disabled using record_participant_credentials

Default: mysqlnd_ms_xa_participants

Example #34 SQL definition for the MySQL state store transaction table

CREATE TABLE mysqlnd_ms_xa_participants (
  fk_store_trx_id int(11) NOT NULL,
  bqual varbinary(64) NOT NULL DEFAULT '',
  participant_id int(10) unsigned NOT NULL AUTO_INCREMENT,
  server_uuid varchar(127) DEFAULT NULL,
  scheme varchar(1024) NOT NULL,
  host varchar(127) DEFAULT NULL,
  port smallint(5) unsigned DEFAULT NULL,
  socket varchar(127) DEFAULT NULL,
  user varchar(127) DEFAULT NULL,
  password varchar(127) DEFAULT NULL,
  state enum('XA_NON_EXISTING','XA_ACTIVE','XA_IDLE','XA_PREPARED','XA_COMMIT','XA_ROLLBACK')
   NOT NULL DEFAULT 'XA_NON_EXISTING',
  health enum('OK','GC_DONE','CLIENT ERROR','SERVER ERROR') NOT NULL DEFAULT 'OK',
  connection_id int(10) unsigned DEFAULT NULL,
  client_errno smallint(5) unsigned DEFAULT NULL,
  client_error varchar(1024) DEFAULT NULL,
  modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (participant_id),
  KEY idx_xa_bqual (bqual),
  KEY idx_store_trx (fk_store_trx_id),
  CONSTRAINT mysqlnd_ms_xa_participants_ibfk_1 FOREIGN KEY (fk_store_trx_id)
    REFERENCES mysqlnd_ms_xa_trx (store_trx_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB
garbage_collection_table

Name of the MySQL table used to track and synchronize garbage collection runs. Use the below SQL statement to create the table. Make sure to edit the table name to match your configuration.

Default: mysqlnd_ms_xa_gc

Example #35 SQL definition for the MySQL state store garbage collection table

CREATE TABLE mysqlnd_ms_xa_gc (
  gc_id int(10) unsigned NOT NULL AUTO_INCREMENT,
  gtrid int(11) NOT NULL,
  format_id int(10) unsigned NOT NULL DEFAULT '1',
  fk_store_trx_id int(11) DEFAULT NULL,
  modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  attempts smallint(5) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (gc_id),
  KEY idx_store_trx (gtrid,format_id,fk_store_trx_id)
) ENGINE=InnoDB
host

Host name of the MySQL server.

user

Name of the user used to connect to the MySQL server.

password

Password for the MySQL server user.

db

Database that holds the garbage collection tables. Please note, you have to create the garbage collection tables prior to using the plugin. The tables will not be created implicitly during runtime but garbage collection will fail if the tables to not exist.

port

Port of the MySQL server.

socket

Unix domain socket of the MySQL server. Please note, if you have multiple PHP servers each of them will try to carry out garbage collection and need to be able to connect to the state store. In this case, you may prefer configuring an IP address and a port for the MySQL state store server to ensure all PHP servers can reach it.

rollback_on_close

Whether to automatically rollback an open global transaction when a connection is closed. If enabled, it mimics the default behaviour of local transactions. Should a client disconnect, the server rolls back any open and unfinished transactions.

Default: true

garbage_collection
max_retries

Maximum number of garbage collection runs before giving up. Allowed values are from 0 to 100. A setting of 0 means no limit, unless the state store enforces a limit. Should the state store enforce a limit, it can be supposed to be significantly higher than 100. Available since 1.6.0.

Please note, it is important to end failed XA transactions within reasonable time to make participating servers free resources bound to the transaction. The built-in garbage collection is not expected to fail for a long period as long as crashed servers become available again quickly. Still, a situation may arise where a human is required to act because the built-in garbage collection stopped or failed. In this case, you may first want to check if the transaction still cannot be fixed by forcing mysqlnd_ms_xa_gc() to ignore the setting, prior to handling it manually.

Default: 5

probability

Garbage collection probability. Allowed values are from 0 to 1000. A setting of 0 disables automatic background garbage collection. Despite a setting of 0 it is still possible to trigger garbage collection by calling mysqlnd_ms_gc(). Available since 1.6.0.

The automatic garbage collection of stalled XA transaction is only available if a state store have been configured. The state store is responsible to keep track of XA transactions. Based on its recordings it can find blocked XA transactions where the client has crashed, connect to the participants and rollback the unfinished transactions.

The garbage collection is triggered as part of PHP's request shutdown procedure at the end of a web request. That is after your PHP script has finished working. Do decide whether to run the garbage collection a random value between 0 and 1000 is computed. If the probability value is higher or equal to the random value, the state stores garbage collection routines are invoked.

Default: 5

max_transactions_per_run

Maximum number of unfinished XA transactions considered by the garbage collection during one run. Allowed values are from 1 to 32768. Available since 1.6.0.

Cleaning up an unfinished XA transaction takes considerable amounts of time and resources. The garbage collection routine may have to connect to several participants of a failed global transaction to issue the SQL commands for rolling back the unfinished tranaction.

Default: 100

Plugin configuration file (<= 1.0.x)

Nota:

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.

Example #36 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.

Example #37 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.

Testing

Nota:

The section applies to mysqlnd_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 distinct 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"));

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

Nota:

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.

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 performance 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.

Example #38 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.

Example #39 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");
?>

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

SQL hint related

Example #1 Example demonstrating the usage of mysqlnd_ms constants

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);
?>

Exemplele de mai sus vor afi?a:

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 happen to have replicated the latest 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.

Plugin configuration file (>=1.1.x)
Func?ii mysqlnd_ms
mysqlnd_ms


Func?ii mysqlnd_ms

Cuprins

  • mysqlnd_ms_dump_servers — Returns a list of currently configured servers
  • mysqlnd_ms_fabric_select_global — Switch to global sharding server for a given table
  • mysqlnd_ms_fabric_select_shard — Switch to shard
  • 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_ms_xa_begin — Starts a distributed/XA transaction among MySQL servers
  • mysqlnd_ms_xa_commit — Commits a distributed/XA transaction among MySQL servers
  • mysqlnd_ms_xa_gc — Garbage collects unfinished XA transactions after severe errors
  • mysqlnd_ms_xa_rollback — Rolls back a distributed/XA transaction among MySQL servers
Constante predefinite
mysqlnd_ms_dump_servers
mysqlnd_ms


Returns a list of currently configured servers

Func?ii mysqlnd_ms
mysqlnd_ms_fabric_select_global
Func?ii mysqlnd_ms
PHP Manual

mysqlnd_ms_dump_servers

(No version information available, might only be in Git)

mysqlnd_ms_dump_servers — Returns a list of currently configured servers

Descrierea

array mysqlnd_ms_dump_servers ( mixed $connection )

Returns a list of currently configured servers.

Parametri

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

Valorile întoarse

FALSE on error. Otherwise, returns an array with two entries masters and slaves each of which contains an array listing all corresponding servers.

The function can be used to check and debug the list of servers currently used by the plugin. It is mostly useful when the list of servers changes at runtime, for example, when using MySQL Fabric.

masters and slaves server entries

Key | Description | Version
name_from_config | Server entry name from config, if appliciable. NULL if no configuration name is available. | Since 1.6.0.
hostname | Host name of the server. | Since 1.6.0.
user | Database user used to authenticate against the server. | Since 1.6.0.
port | TCP/IP port of the server. | Since 1.6.0.
socket | Unix domain socket of the server. | Since 1.6.0.

Note

Nota:

mysqlnd_ms_dump_servers() requires PECL mysqlnd_ms >> 1.6.0.

Exemple

Example #1 mysqlnd_ms_dump_servers() example

{
    "myapp": {
        "master": {
            "master1": {
                "host":"master1_host",
                "port":"master1_port",
                "socket":"master1_socket",
                "db":"master1_db",
                "user":"master1_user",
                "password":"master1_pw"
            }
        },
        "slave": {
             "slave_0": {
                 "host":"slave0_host",
                 "port":"slave0_port",
                 "socket":"slave0_socket",
                 "db":"slave0_db",
                 "user":"slave0_user",
                 "password":"slave0_pw"
             },
             "slave_1": {
                 "host":"slave1_host"
             }
        }
    }
}
<?php
$link = mysqli_connect("myapp", "global_user", "global_pass", "global_db", 1234, "global_socket");
var_dump(mysqlnd_ms_dump_servers($link);
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["masters"]=>
  array(1) {
    [0]=>
    array(5) {
      ["name_from_config"]=>
      string(7) "master1"
      ["hostname"]=>
      string(12) "master1_host"
      ["user"]=>
      string(12) "master1_user"
      ["port"]=>
      int(3306)
      ["socket"]=>
      string(14) "master1_socket"
    }
  }
  ["slaves"]=>
  array(2) {
    [0]=>
    array(5) {
      ["name_from_config"]=>
      string(7) "slave_0"
      ["hostname"]=>
      string(11) "slave0_host"
      ["user"]=>
      string(11) "slave0_user"
      ["port"]=>
      int(3306)
      ["socket"]=>
      string(13) "slave0_socket"
    }
    [1]=>
    array(5) {
      ["name_from_config"]=>
      string(7) "slave_1"
      ["hostname"]=>
      string(11) "slave1_host"
      ["user"]=>
      string(12) "gloabal_user"
      ["port"]=>
      int(1234)
      ["socket"]=>
      string(13) "global_socket"
    }
  }
}

Func?ii mysqlnd_ms
mysqlnd_ms_fabric_select_global
Func?ii mysqlnd_ms


Switch to global sharding server for a given table

mysqlnd_ms_dump_servers
mysqlnd_ms_fabric_select_shard
Func?ii mysqlnd_ms
PHP Manual

mysqlnd_ms_fabric_select_global

(No version information available, might only be in Git)

mysqlnd_ms_fabric_select_global — Switch to global sharding server for a given table

Descrierea

array mysqlnd_ms_fabric_select_global ( mixed $connection , mixed $table_name )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

MySQL Fabric related.

Switch the connection to the nodes handling global sharding queries for the given table name.

Parametri

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

table_name

The table name to ask Fabric about.

Valorile întoarse

FALSE on error. Otherwise, TRUE

Note

Nota:

mysqlnd_ms_fabric_select_global() requires PECL mysqlnd_ms >> 1.6.0.

mysqlnd_ms_dump_servers
mysqlnd_ms_fabric_select_shard
Func?ii mysqlnd_ms


Switch to shard

mysqlnd_ms_fabric_select_global
mysqlnd_ms_get_last_gtid
Func?ii mysqlnd_ms
PHP Manual

mysqlnd_ms_fabric_select_shard

(No version information available, might only be in Git)

mysqlnd_ms_fabric_select_shard — Switch to shard

Descrierea

array mysqlnd_ms_fabric_select_shard ( mixed $connection , mixed $table_name , mixed $shard_key )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

MySQL Fabric related.

Switch the connection to the shards responsible for the given table name and shard key.

Parametri

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

table_name

The table name to ask Fabric about.

shard_key

The shard key to ask Fabric about.

Valorile întoarse

FALSE on error. Otherwise, TRUE

Note

Nota:

mysqlnd_ms_fabric_select_shard() requires PECL mysqlnd_ms >> 1.6.0.

mysqlnd_ms_fabric_select_global
mysqlnd_ms_get_last_gtid
Func?ii mysqlnd_ms


Returns the latest global transaction ID

mysqlnd_ms_fabric_select_shard
mysqlnd_ms_get_last_used_connection
Func?ii mysqlnd_ms
PHP Manual

mysqlnd_ms_get_last_gtid

(PECL mysqlnd_ms >= 1.2.0)

mysqlnd_ms_get_last_gtid — Returns the latest global transaction ID

Descrierea

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.

Parametri

connection

A PECL/mysqlnd_ms connection handle to a MySQL server of the type PDO_MYSQL, mysqli> or ext/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 above three MySQL driver extensions.

Valorile întoarse

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.

Note

Nota:

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.

Please note, all MySQL 5.6 production versions do not provide clients with enough information to use GTIDs for enforcing session consistency. In the worst case, the plugin will choose the master only.

Exemple

Example #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));
?>

A se vedea ?i

  • Global Transaction IDs

mysqlnd_ms_fabric_select_shard
mysqlnd_ms_get_last_used_connection
Func?ii mysqlnd_ms


Returns an array which describes the last used connection

mysqlnd_ms_get_last_gtid
mysqlnd_ms_get_stats
Func?ii mysqlnd_ms
PHP Manual

mysqlnd_ms_get_last_used_connection

(PECL mysqlnd_ms >= 1.1.0)

mysqlnd_ms_get_last_used_connection — Returns an array which describes the last used connection

Descrierea

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.

Parametri

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

Valorile întoarse

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.

Note

Nota:

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.

Exemple

The example assumes that myapp refers to a plugin configuration file section and represents a connection pool.

Example #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));
?>

Exemplul de mai sus va afi?a:

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
Func?ii mysqlnd_ms


Returns query distribution and connection statistics

mysqlnd_ms_get_last_used_connection
mysqlnd_ms_match_wild
Func?ii mysqlnd_ms
PHP Manual

mysqlnd_ms_get_stats

(PECL mysqlnd_ms >= 1.0.0)

mysqlnd_ms_get_stats — Returns query distribution and connection statistics

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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 statistics 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 statement, which 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 statement, which 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 executed 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 executed 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 statements 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. Another sequence causing an implicit commit is begin(), query(), begin(). The second call to begin() will implicitly commit the transaction started by the first call to begin(). begin() refers to internal library calls not actual PHP user API calls. | 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.
transient_error_retries | How often an operation has been retried when a transient error was detected. See also, transient_error plugin configuration file setting. | Since 1.6.0.
fabric_sharding_lookup_servers_success | Number of successful sharding.lookup_servers remote procedure calls to MySQL Fabric. A call is considered successful if the plugin could reach MySQL Fabric and got any reply. The reply itself may or may not be understood by the plugin. Success refers to the network transport only. If the reply was not understood or indicates a valid error condition, fabric_sharding_lookup_servers_xml_failure gets incremented. | Since 1.6.0.
fabric_sharding_lookup_servers_failure | Number of failed sharding.lookup_servers remote procedure calls to MySQL Fabric. A remote procedure call is considered failed if there was a network error in connecting to, writing to or reading from MySQL Fabric. | Since 1.6.0.
fabric_sharding_lookup_servers_time_total | Time spent connecting to,writing to and reading from MySQL Fabrich during the sharding.lookup_servers remote procedure call. The value is aggregated for all calls. Time is measured in microseconds. | Since 1.6.0.
fabric_sharding_lookup_servers_bytes_total | Total number of bytes received from MySQL Fabric in reply to sharding.lookup_servers calls. | Since 1.6.0.
fabric_sharding_lookup_servers_xml_failure | How often a reply from MySQL Fabric to sharding.lookup_servers calls was not understood. Please note, the current experimental implementation does not distinguish between valid errors returned and malformed replies. | Since 1.6.0.
xa_begin | How many XA/distributed transactions have been started using mysqlnd_ms_xa_begin(). | Since 1.6.0.
xa_commit_success | How many XA/distributed transactions have been successfully committed using mysqlnd_ms_xa_commit(). | Since 1.6.0.
xa_commit_failure | How many XA/distributed transactions failed to commit during mysqlnd_ms_xa_commit(). | Since 1.6.0.
xa_rollback_success | How many XA/distributed transactions have been successfully rolled back using mysqlnd_ms_xa_rollback(). The figure does not include implict rollbacks performed as a result of mysqlnd_ms_xa_commit() failure. | Since 1.6.0.
xa_rollback_failure | How many XA/distributed transactions could not be rolled back. This includes failures of mysqlnd_ms_xa_rollback() but also failured during rollback when closing a connection, if rollback_on_close is set. Please, see also xa_rollback_on_close below. | Since 1.6.0.
xa_participants | Total number of participants in any XA transaction started with mysqlnd_ms_xa_begin(). | Since 1.6.0.
xa_rollback_on_close | How many XA transactions have been rolled back implicitly when a connection was close and rollback_on_close is set. Depending on your coding policies, this may hint a flaw in your code as you may prefer to explicitly clean up resources. | Since 1.6.0.
pool_masters_total | Number of master servers (connections) in the internal connection pool. | Since 1.6.0.
pool_slaves_total | Number of slave servers (connections) in the internal connection pool. | Since 1.6.0.
pool_masters_active | Number of master servers (connections) from the internal connection pool which are currently used for picking a connection. | Since 1.6.0.
pool_slaves_active | Number of slave servers (connections) from the internal connection pool which are currently used for picking a connection. | Since 1.6.0.
pool_updates | How often the active connection list has been replaced and a new set of master and slave servers had been installed. | Since 1.6.0.
pool_master_reactivated | How often a master connection has been reused after being flushed from the active list. | Since 1.6.0.
pool_slave_reactivated | How often a slave connection has been reused after being flushed from the active list. | Since 1.6.0.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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"
  ["transient_error_retries"]=>
  string(1) "0"
}

A se vedea ?i

  • Runtime configuration
  • mysqlnd_ms.collect_statistics
  • mysqlnd_ms.enable
  • Monitoring

mysqlnd_ms_get_last_used_connection
mysqlnd_ms_match_wild
Func?ii mysqlnd_ms


Finds whether a table name matches a wildcard pattern or not

mysqlnd_ms_get_stats
mysqlnd_ms_query_is_select
Func?ii mysqlnd_ms
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

Descrierea

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.

Parametri

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 \.

Valorile întoarse

Returns TRUE table_name is matched by wildcard. Otherwise, returns FALSE

Exemple

Example #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"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)

mysqlnd_ms_get_stats
mysqlnd_ms_query_is_select
Func?ii mysqlnd_ms


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
Func?ii mysqlnd_ms
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

Descrierea

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.

Parametri

query

Query string to test.

Valorile întoarse

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 function will always return MYSQLND_MS_QUERY_USE_MASTER or MYSQLND_MS_QUERY_USE_LAST_USED.

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • Predefined Constants
  • user filter
  • Runtime configuration
  • mysqlnd_ms.disable_rw_split
  • mysqlnd_ms.enable

mysqlnd_ms_match_wild
mysqlnd_ms_set_qos
Func?ii mysqlnd_ms


Sets the quality of service needed from the cluster

mysqlnd_ms_query_is_select
mysqlnd_ms_set_user_pick_server
Func?ii mysqlnd_ms
PHP Manual

mysqlnd_ms_set_qos

(PECL mysqlnd_ms < 1.2.0)

mysqlnd_ms_set_qos — Sets the quality of service needed from the cluster

Descrierea

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 runtime 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 less refined 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.

Since 1.5.0 calls will fail when done in the middle of a transaction if transaction stickiness is enabled and transaction boundaries have been detected. properly.

Parametri

connection

A PECL/mysqlnd_ms connection handle to a MySQL server of the type PDO_MYSQL, mysqli or ext/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 above three MySQL driver 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 achieve session consistency. A slave is considered up-to-date and checked 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 MYSQLND_MS_QOS_OPTION_AGE option can be combined 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 only consider slaves for reading if 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 the service_level_option parameter.

Valorile întoarse

Returns TRUE if the connections service level has been switched to the requested. Otherwise, returns FALSE

Note

Nota:

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.

Please note, all MySQL 5.6 production versions do not provide clients with enough information to use GTIDs for enforcing session consistency. In the worst case, the plugin will choose the master only.

Exemple

Example #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));
?>

A se vedea ?i

  • 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
Func?ii mysqlnd_ms


Sets a callback for user-defined read/write splitting

mysqlnd_ms_set_qos
mysqlnd_ms_xa_begin
Func?ii mysqlnd_ms
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

Descrierea

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 chooses 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.

Parametri

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.

Valorile întoarse

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.

Note

Nota:

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.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

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'

A se vedea ?i

  • 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
mysqlnd_ms_xa_begin
Func?ii mysqlnd_ms


Starts a distributed/XA transaction among MySQL servers

mysqlnd_ms_set_user_pick_server
mysqlnd_ms_xa_commit
Func?ii mysqlnd_ms
PHP Manual

mysqlnd_ms_xa_begin

(PECL mysqlnd_ms < 1.6.0)

mysqlnd_ms_xa_begin — Starts a distributed/XA transaction among MySQL servers

Descrierea

int mysqlnd_ms_xa_begin ( mixed $connection , string $gtrid [, int $timeout ] )

Starts a XA transaction among MySQL servers. PECL/mysqlnd_ms acts as a transaction coordinator the distributed transaction.

Once a global transaction has been started, the plugin injects appropriate XA BEGIN SQL statements on all MySQL servers used in the following. The global transaction is either ended by calling mysqlnd_ms_xa_commit(), mysqlnd_ms_xa_rollback() or by an implicit rollback in case of an error.

During a global transaction, the plugin tracks all server switches, for example, when switching from one MySQL shard to another MySQL shard. Immediately before a query is run on a server that has not been participating in the global transaction yet, XA BEGIN is executed on the server. From a users perspective the injection happens during a call to a query execution function such as mysqli_query(). Should the injection fail an error is reported to the caller of the query execution function. The failing server does not become a participant in the global transaction. The user may retry executing a query on the server and hereby retry injecting XA BEGIN, abort the global transaction because not all required servers can participate, or ignore and continue the global without the failed server.

Reasons to fail executing XA BEGIN include but are not limited to a server being unreachable or the server having an open, concurrent XA transaction using the same xid.

Please note, global and local transactions are mutually exclusive. You cannot start a XA transaction when you have a local transaction open. The local transaction must be ended first. The plugin tries to detect this conflict as early as possible. It monitors API calls for controlling local transactions to learn about the current state. However, if using SQL statements for local transactions such as BEGIN, the plugin may not know the current state and the conflict is not detected before XA BEGIN is injected and executed.

The use of other XA resources but MySQL servers is not supported by the function. To carry out a global transaction among, for example, a MySQL server and another vendors database system, you should issue the systems SQL commands yourself.

Nota: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

Parametri

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

gtrid

Global transaction identifier (gtrid). The gtrid is a binary string up to 64 bytes long. Please note, depending on your character set settings, 64 characters may require more than 64 bytes to store.

In accordance with the MySQL SQL syntax, XA transactions use identifiers made of three parts. An xid consists of a global transaction identifier (gtrid), a branch qualifier (bqual) and a format identifier (formatID). Only the global transaction identifier can and needs to be set.

The branch qualifier and format identifier are set automatically. The details should be considered implementation dependent, which may change without prior notice. In version 1.6 the branch qualifier is consecutive number which is incremented whenever a participant joins the global transaction.

timeout

Timeout in seconds. The default value is 60 seconds.

The timeout is a hint to the garbage collection. If a transaction is recorded to take longer than expected, the garbage collection begins checking the transactions status.

Setting a low value may make the garbage collection check the progress too often. Please note, checking the status of a global transaction may involve connecting to all recorded participants and possibly issuing queries on the servers.

Valorile întoarse

Returns TRUE if there is no open local or global transaction and a new global transaction can be started. Otherwise, returns FALSE

A se vedea ?i

  • Quickstart XA/Distributed transactions
  • Runtime configuration
  • mysqlnd_ms_get_stats() - Returns query distribution and connection statistics

mysqlnd_ms_set_user_pick_server
mysqlnd_ms_xa_commit
Func?ii mysqlnd_ms


Commits a distributed/XA transaction among MySQL servers

mysqlnd_ms_xa_begin
mysqlnd_ms_xa_gc
Func?ii mysqlnd_ms
PHP Manual

mysqlnd_ms_xa_commit

(PECL mysqlnd_ms < 1.6.0)

mysqlnd_ms_xa_commit — Commits a distributed/XA transaction among MySQL servers

Descrierea

int mysqlnd_ms_xa_commit ( mixed $connection , string $gtrid )

Commits a global transaction among MySQL servers started by mysqlnd_ms_xa_begin().

If any of the global transaction participants fails to commit an implicit rollback is performed. It may happen that not all cases can be handled during the rollback. For example, no attempts will be made to reconnect to a participant after the connection to the participant has been lost. Solving cases that cannot easily be rolled back is left to the garbage collection.

Nota: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

Parametri

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

gtrid

Global transaction identifier (gtrid).

Valorile întoarse

Returns TRUE if the global transaction has been committed. Otherwise, returns FALSE

A se vedea ?i

  • Quickstart XA/Distributed transactions
  • Runtime configuration
  • mysqlnd_ms_get_stats() - Returns query distribution and connection statistics

mysqlnd_ms_xa_begin
mysqlnd_ms_xa_gc
Func?ii mysqlnd_ms


Garbage collects unfinished XA transactions after severe errors

mysqlnd_ms_xa_commit
mysqlnd_ms_xa_rollback
Func?ii mysqlnd_ms
PHP Manual

mysqlnd_ms_xa_gc

(PECL mysqlnd_ms < 1.6.0)

mysqlnd_ms_xa_gc — Garbage collects unfinished XA transactions after severe errors

Descrierea

int mysqlnd_ms_xa_gc ( mixed $connection [, string $gtrid [, boolean $ignore_max_retries ]] )

Garbage collects unfinished XA transactions.

The XA protocol is a blocking protocol. There exist cases when servers participating in a global transaction cannot make progress when the transaction coordinator crashes or disconnects. In such a case, the MySQL servers keep waiting for instructions to finish the XA transaction in question. Because transactions occupy resources, transactions should always be terminated properly.

Garbage collection requires configuring a state store to track global transactions. Should a PHP client crash in the middle of a transaction and a new PHP client be started, then the built-in garbage collection can learn about the aborted global transaction and terminate it. If you do not configure a state store, the garbage collection cannot perform any cleanup tasks.

The state store should be crash-safe and be highly available to survive its own crash. Currently, only MySQL is supported as a state store.

Garbage collection can also be performed automatically in the background. See the plugin configuration directive garbage_collection for details.

Nota: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

Parametri

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

gtrid

Global transaction identifier (gtrid). If given, the garbage collection considers the transaction only. Otherwise, the state store is scanned for any unfinished transaction.

ignore_max_retries

Whether to ignore the plugin configuration max_retries setting. If garbage collection continuously fails and the max_retries limit is reached prior to finishing the failed global transaction, you can attempt further runs prior to investigating the cause and solving the issue manually by issuing appropriate SQL statements on the participants. Setting the parameter has the same effect as temporarily setting max_retries = 0.

Valorile întoarse

Returns TRUE if garbage collection was successful. Otherwise, returns FALSE

A se vedea ?i

  • Quickstart XA/Distributed transactions
  • Runtime configuration
  • State store configuration
  • mysqlnd_ms_get_stats() - Returns query distribution and connection statistics

mysqlnd_ms_xa_commit
mysqlnd_ms_xa_rollback
Func?ii mysqlnd_ms


Rolls back a distributed/XA transaction among MySQL servers

mysqlnd_ms_xa_gc
Change History
Func?ii mysqlnd_ms
PHP Manual

mysqlnd_ms_xa_rollback

(PECL mysqlnd_ms < 1.6.0)

mysqlnd_ms_xa_rollback — Rolls back a distributed/XA transaction among MySQL servers

Descrierea

int mysqlnd_ms_xa_rollback ( mixed $connection , string $gtrid )

Rolls back a global transaction among MySQL servers started by mysqlnd_ms_xa_begin().

If any of the global transaction participants fails to rollback the situation is left to be solved by the garbage collection.

Nota: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

Parametri

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

gtrid

Global transaction identifier (gtrid).

Valorile întoarse

Returns TRUE if the global transaction has been rolled back. Otherwise, returns FALSE

A se vedea ?i

  • Quickstart XA/Distributed transactions
  • Runtime configuration
  • mysqlnd_ms_get_stats() - Returns query distribution and connection statistics

mysqlnd_ms_xa_gc
Change History
Func?ii mysqlnd_ms


Change History

Cuprins

  • PECL/mysqlnd_ms 1.6 series
  • PECL/mysqlnd_ms 1.5 series
  • PECL/mysqlnd_ms 1.4 series
  • PECL/mysqlnd_ms 1.3 series
  • 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_xa_rollback
PECL/mysqlnd_ms 1.6 series
mysqlnd_ms


PECL/mysqlnd_ms 1.6 series

1.6.0-alpha

  • Release date: TBD
  • Motto/theme: Maintenance and initial MySQL Fabric support

Nota:

This is the current development series. All features are at an early stage. Changes may happen at any time without prior notice. Please, do not use this version in production environments.

The documentation may not reflect all changes yet.

Bug fixes

  • Won't fix: #66616 R/W split fails: QOS with mysqlnd_get_last_gtid with built-in MySQL GTID

    This is not a bug in the plugins implementation but a server side feature limitation not considered and documented before. MySQL 5.6 built-in GTIDs cannot be used to ensure session consistency when reading from slaves in all cases. In the worst case the plugin will not consider using the slaves and fallback to using the master. There will be no wrong results but no benefit from doing GTID checks either.

  • Fixed #66064 - Random once load balancer ignoring weights

    Due to a config parsing bug random load balancing has ignored node weights if, and only if, the sticky flag was set (random once).

  • Fixed #65496 - Wrong check for slave delay

    The quality of service filter has erroneously ignored slaves that lag for zero (0) seconds if a any maximum lag had been set. Although a slave was not lagging behind, it was excluded from the load balancing list if a maximum age was set by the QoS filter. This was due to using the wrong comparison operator in the source of the filter.

  • Fixed #65408 - Compile failure with -Werror=format-security

Feature changes

  • Introduced an internal connection pool. When using Fabric and switching from shard group A to shard group B, we are replacing the entire list of masters and slaves. This troubles the connections state alignment logic and some filters. Some filters cache information on the master and slave lists. The new internal connection pool abstraction allows us to inform the filters of changes, hence they can update their caches.

    Later on, the pool can also be used to reduce connection overhead. Assume you are switching from a shard group to another and back again. Whenever the switch is done, the pool's active server (and connection) lists are replaced. However, no longer used connections are not necessarily closed immediately but can be kept in the pool for later reuse.

    Please note, the connection pool is internalat this point. There are some new statistics to monitor it. However, you cannot yet configure pool size of behaviour.

  • Added a basic distributed transaction abstraction. XA transactions can are supported ever since using standard SQL calls. This is inconvenient as XA participants must be managed manually. PECL/mysqlnd_ms introduces API calls to control XA transaction among MySQL servers. When using the new functions, PECL/mysqlnd_ms acts as a transaction coordinator. After starting a distributed transaction, the plugin tracks all servers involved until the transaction is ended and issues appropriate SQL statements on the XA participants.

    This is useful, for example, when using Fabric and sharding. When using Fabric the actual shard servers involved in a business transaction may not be known in advance. Thus, manually controlling a transaction that spawns multiple shards becomes difficult. Please, be warned about current limitations.

  • Introduced automatic retry loop for transient errors and corresponding statistic to count the number of implicit retries. Some distributed database clusters use transient errors to hint a client to retry its operation in a bit. Most often, the client is then supposed to halt execution (sleep) for a short moment before retrying the desired operation. Immediately failing over to another node is not necessary in response to the error. Instead, a retry loop can be performed. Common situation when using MySQL Cluster.

  • Introduced automatic retry loop for transient errors and corresponding statistic to count the number of implicit retries. Some distributed database clusters use transient errors to hint a client to retry its operation in a bit. Most often, the client is then supposed to halt execution (sleep) for a short moment before retrying the desired operation. Immediately failing over to another node is not necessary in response to the error. Instead, a retry loop can be performed. Common situation when using MySQL Cluster.

  • Introduced most basic support for the MySQL Fabric High Availability and sharding framework.

    Please, consider this pre-alpha quality. Both the server side framework and the client side code is supposed to work flawless considering the MySQL Fabric quickstart examples only. However, testing has not been performed to the level of prior plugin alpha releases. Either sides are moving targets, API changes may happen at any time without prior warning.

    As this is work in progress, the manual may not yet reflect allow feature limitations and known bugs.

  • New statistics to monitor the Fabric XML RPC call sharding.lookup_servers: fabric_sharding_lookup_servers_success, fabric_sharding_lookup_servers_failure, fabric_sharding_lookup_servers_time_total, fabric_sharding_lookup_servers_bytes_total, fabric_sharding_lookup_servers_xml_failure.

  • New functions related to MySQL Fabric:
mysqlnd_ms_fabric_select_shard(),
mysqlnd_ms_fabric_select_global(),
mysqlnd_ms_dump_servers().

Change History
PECL/mysqlnd_ms 1.5 series
Change History


PECL/mysqlnd_ms 1.5 series

1.5.1-stable

  • Release date: 06/2013
  • Motto/theme: Sharding support, improved transaction support

Nota:

This is the current stable series. Use this version in production environments.

The documentation is complete.

1.5.0-alpha

  • Release date: 03/2013
  • Motto/theme: Sharding support, improved transaction support

Bug fixes

  • Fixed #60605 PHP segmentation fault when mysqlnd_ms is enabled.

  • Setting transaction stickiness disables all load balancing, including automatic failover, for the duration of a transaction. So far connection switches could have happened in the middle of a transaction in multi-master configurations and during automatic failover although transaction monitoring had detected transaction boundaries properly.

  • BC break and bug fix. SQL hints enforcing the use of a specific kind of server (MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH, MYSQLND_MS_LAST_USED_SWITCH) are ignored for the duration of a transaction of transaction stickiness is enabled and transaction boundaries have been detected properly.

    This is a change in behaviour. However, it is also a bug fix and a step to align behaviour. If, in previous versions, transaction stickiness, one of the above listed SQL hints and the quality of service filtering was combined it could happened that the SQL hints got ignored. In some case the SQL hints did work, in other cases they did not. The new behaviour is more consistent. SQL hints will always be ignore for the duration of a transaction, if transaction stickiness is enabled.

    Please note, transaction boundary detection continues to be based on API call monitoring. SQL commands controlling transactions are not monitored.

  • BC break and bug fix. Calls to mysqlnd_ms_set_qos() will fail when done in the middle of a transaction if transaction stickiness is enabled. Connection switches are not allowed for the duration of a transaction. Changing the quality of service likely results on a different set of servers qualifying for query execution, possibly making it necessary to switch connections. Thus, the call is not allowed in during an active transaction. The quality of server can, however, be changed in between transactions.

Feature changes

  • Introduced the node_group filter. The filter lets you organize servers (master and slaves) into groups. Queries can be directed to a certain group of servers by prefixing the query statement with a SQL hint/comment that contains the groups configured name. Grouping can be used for partitioning and sharding, and also to optimize for local caching. In the case of sharding, a group name can be thought of like a shard key. All queries for a given shard key will be executed on the configured shard. Note: both the client and server must support sharding for sharding to function with mysqlnd_ms.

  • Extended configuration file validation during PHP startup (RINIT). An E_WARNING level error will be thrown if the configuration file can not be read (permissions), is empty, or the file (JSON) could not be parsed. Warnings may appear in log files, which depending on how PHP is configured.

    Distributions that aim to provide a pre-configured setup, including a configuration file stub, are asked to put {} into the configuration file to prevent this warning about an invalid configuration file.

    Further configuration file validation is done when parsing sections upon opening a connection. Please, note that there may still be situations when an invalid plugin configuration file does not lead to proper error messages but a failure to connect.

  • As of PHP 5.5.0, improved support for transaction boundaries detection was added for mysqli. The mysqli extension has been modified to use the new C API calls of the mysqlnd library to begin, commit, and rollback a transaction or savepoint. If trx_stickiness is used to enable transaction aware load balancing, the mysqli_begin(), mysqli_commit() and mysqli_rollback() functions will now be monitered by the plugin, to go along with the mysqli_autocommit() function that was already supported. All SQL features to control transactions are also available through the improved mysqli transaction control related functions. This means that it is not required to issue SQL statements instead of using API calls. Applications using the appropriate API calls can be load balanced by PECL/mysqlnd_ms in a completely transaction-aware way.

    Please note, PDO_MySQL has not been updated yet to utilize the new mysqlnd API calls. Thus, transaction boundary detection with PDO_MySQL continues to be limited to the monitoring by passing in PDO::ATTR_AUTOCOMMIT to PDO::setAttribute().

  • Introduced trx_stickiness=on. This trx_stickiness option differs from trx_stickiness=master as it tries to execute a read-only transaction on a slave, if quality of service (consistency level) allows the use of a slave. Read-only transactions were introduced in MySQL 5.6, and they offer performance gains.

  • Query cache support is considered beta if used with the mysqli API. It should work fine with primary copy based clusters. For all other APIs, this feature continues to be called experimental.

  • The code examples in the mysqlnd_ms source were updated.

PECL/mysqlnd_ms 1.6 series
PECL/mysqlnd_ms 1.4 series
Change History


PECL/mysqlnd_ms 1.4 series

1.4.2-stable

  • Release date: 08/2012
  • Motto/theme: Tweaking based on user feedback

1.4.1-beta

  • Release date: 08/2012
  • Motto/theme: Tweaking based on user feedback

Bug fixes

  • Fixed build with PHP 5.5

1.4.0-alpha

  • Release date: 07/2012
  • Motto/theme: Tweaking based on user feedback

Feature changes

  • BC break: Renamed plugin configuration setting ini_file to config_file. In early versions the plugin configuration file used ini style. Back then the configuration setting was named accordingly. It has now been renamed to reflect the newer file format and to distinguish it from PHP's own ini file (configuration directives file).

  • Introduced new default charset setting server_charset to allow proper escaping before a connection is opened. This is most useful when using lazy connections, which are a default.

  • Introduced wait_for_gtid_timeout setting to throttle slave reads that need session consistency. If global transaction identifier are used and the service level is set to session consistency, the plugin tries to find up-to-date slaves. The slave status check is done by a SQL statement. If nothing else is set, the slave status is checked only one can the search for more up-to-date slaves continues immediately thereafter. Setting wait_for_gtid_timeout instructs the plugin to poll a slaves status for wait_for_gtid_timeout seconds if the first execution of the SQL statement has shown that the slave is not up-to-date yet. The poll will be done once per second. This way, the plugin will wait for slaves to catch up and throttle the client.

  • New failover strategy loop_before_master. By default the plugin does no failover. It is possible to enable automatic failover if a connection attempt fails. Upto version 1.3 only master strategy existed to failover to a master if a slave connection fails. loop_before_master is similar but tries all other slaves before attempting to connect to the master if a slave connection fails.

    The number of attempts can be limited using the max_retries option. Failed hosts can be remembered and skipped in load balancing for the rest of the web request. max_retries and remember_failed are considered experimental although decent stability is given. Syntax and semantics may change in the future without prior notice.

PECL/mysqlnd_ms 1.5 series
PECL/mysqlnd_ms 1.3 series
Change History


PECL/mysqlnd_ms 1.3 series

1.3.2-stable

  • Release date: 04/2012
  • Motto/theme: see 1.3.0-alpha

Bug fixes

  • Fixed problem with multi-master where although in a transaction the queries to the master weren't sticky and were spread all over the masters (RR). Still not sticky for Random. Random_once is not affected.

1.3.1-beta

  • Release date: 04/2012
  • Motto/theme: see 1.3.0-alpha

Bug fixes

  • Fixed problem with building together with QC.

1.3.0-alpha

  • Release date: 04/2012
  • Motto/theme: Query caching through quality-of-service concept

The 1.3 series aims to improve the performance of applications and the overall load of an asynchronous MySQL cluster, for example, a MySQL cluster using MySQL Replication. This is done by transparently replacing a slave access with a local cache access, if the application allows it by setting an appropriate quality of service flag. When using MySQL replication a slave can serve stale data. An application using MySQL replication must continue to work correctly with stale data. Given that the application is know to work correctly with stale data, the slave access can transparently be replace with a local cache access.

PECL/mysqlnd_qc serves as a cache backend. PECL/mysqlnd_qc supports use of various storage locations, among others main memory, APC and MEMCACHE.

Feature changes

  • Added cache option to quality-of-service (QoS) filter.

    • New configure option enable-mysqlnd-ms-cache-support
    • New constant MYSQLND_MS_HAVE_CACHE_SUPPORT.
    • New constant MYSQLND_MS_QOS_OPTION_CACHE to be used with mysqlnd_ms_set_qos().

  • Support for built-in global transaction identifier feature of MySQL 5.6.5-m8 or newer.

PECL/mysqlnd_ms 1.4 series
PECL/mysqlnd_ms 1.2 series
Change History


PECL/mysqlnd_ms 1.2 series

1.2.1-beta

  • Release date: 01/2012
  • Motto/theme: see 1.2.0-alpha

Minor test changes.

1.2.0-alpha

  • Release date: 11/2011
  • 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 the mysqlnd_ms_set_qos() function to set the required connection quality at runtime. The new constants related to mysqlnd_ms_set_qos() are:

    • 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 the last global transaction id.

  • Enabled support for multi master without slaves.

PECL/mysqlnd_ms 1.3 series
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

  • Introducere
  • 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
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
  • Constante predefinite
  • Func?ii mysqlnd_qc
    • 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_cache_condition — Set conditions for automatic caching
    • 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.2 series
    • PECL/mysqlnd_qc 1.1 series
    • PECL/mysqlnd_qc 1.0 series
PECL/mysqlnd_ms 1.0 series
Introducere
MySQL


Introducere

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

  • Built-in slam defense to prevent cache stampeding.

Limitations

The current 1.0.1 release of PECL mysqlnd_qc does not support PHP 5.4. Version 1.1.0-alpha lifts this limitation.

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

Cuprins

  • 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.

Introducere
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 issued 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 storage in a persistent cache, and then unserialized when fetching. The mysqlnd query cache stores the raw wire protocol data sent from MySQL to PHP in its cache and replays 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 serialize 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.

Example #1 Enabling the plugin (php.ini)

mysqlnd_qc.enable_qc=1

Architecture and Concepts
Caching queries
Quickstart and Examples


Caching queries

There are four ways to trigger caching of a query.

  • Use of SQL hints on a per query basis
  • User supplied callbacks to decide on a per query basis, for example, using mysqlnd_qc_is_select()
  • mysqlnd_set_cache_condition() for rule based automatic per query decisions
  • mysqlnd_qc.cache_by_default = 1 to cache all queries blindly

Use of SQL hints and mysqlnd_qc.cache_by_default = 1 are explained below. Please, refer to the function reference on mysqlnd_qc_is_select() for a description of using a callback and, mysqlnd_qc_set_cache_condition() on how to set rules for automatic caching.

A SQL hint is a SQL standards compliant comment. As a SQL comment it is ignored by the database. A statement is considered eligible 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 eligible for caching and not cached: INSERT INTO test(id) VALUES (1)

  • not eligible for caching and not cached: SHOW ENGINES

  • eligible for caching but uncached: SELECT id FROM test

  • eligible 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.

Example #1 Using the MYSQLND_QC_ENABLE_SWITCH SQL hint

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);
?>

Exemplele de mai sus vor afi?a ceva similar cu:

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 deployment 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.

Example #2 Using the MYSQLND_QC_DISABLE_SWITCH SQL hint

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();
?>

Exemplele de mai sus vor afi?a:

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.

Example #3 Example showing which type of statements are not cached

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);
}
?>

Exemplele de mai sus vor afi?a ceva similar cu:

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.

Example #4 Enabling caching for all statements using the mysqlnd_qc.cache_no_table ini setting

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);
}
?>

Exemplele de mai sus vor afi?a ceva similar cu:

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

Nota:

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.

Example #1 Setting the TTL with the mysqlnd_qc.ttl ini setting

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);
}
?>

Exemplele de mai sus vor afi?a ceva similar cu:

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.

A user-defined cache storage handler can implement any invalidation strategy to work around this limitation.

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.

Example #2 Setting TTL with SQL hints

<?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);
?>

Exemplele de mai sus vor afi?a ceva similar cu:

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 approach 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 be 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 numerical value it is used as the TTL instead of the global default.

Example #1 Setting a callback with mysqlnd_qc_set_is_select()

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']);
?>

Exemplele de mai sus vor afi?a ceva similar cu:

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 stampeding).

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.

Example #1 Enabling the slam defense mechanism

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.

Example #1 Collecting a query trace

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());
?>

Exemplele de mai sus vor afi?a:

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.

Example #2 Setting the backtrace depth with the mysqlnd_qc.query_trace_bt_depth ini setting

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']);
}
?>

Exemplele de mai sus vor afi?a ceva similar cu:

                    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 statistics 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. Data collection is disabled by default for performance considerations. It is configurable with the mysqlnd_qc.time_statistics option, which determines if timing information should be collected. 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 outweighs any potential performance penalty of the additional system calls.

Example #1 Collecting statistics data with the mysqlnd_qc.time_statistics ini setting

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());
?>

Exemplele de mai sus vor afi?a ceva similar cu:

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.

Example #2 Example mysqlnd_qc_get_cache_info() usage

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());
?>

Exemplele de mai sus vor afi?a ceva similar cu:

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 = ?.

Example #3 Example mysqlnd_qc_get_normalized_query_trace_log() usage

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());
?>

Exemplele de mai sus vor afi?a ceva similar cu:

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.

Example #1 Using a user-defined storage handler

<?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();
?>

Exemplele de mai sus vor afi?a ceva similar cu:

        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
Instalarea / configurarea
Quickstart and Examples


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
Beyond TTL: user-defined storage
Necesita?i
mysqlnd_qc


Necesita?i

PHP 5.3.3 or a newer version of PHP.

PECL/mysqlnd_qc is a mysqlnd plugin. It plugs into the mysqlnd library. To use you this plugin with a PHP MySQL extension, the extension (mysqli, mysql, or PDO_MYSQL) must enable the mysqlnd library.

For using the APC storage handler with PECL/mysqlnd_qc 1.0 APC 3.1.3p1-beta or newer. PECL/mysqlnd_qc 1.2 has been tested with APC 3.1.13-beta. The APC storage handler cannot be used with a shared build. You cannot use the PHP configuration directive extension to load the APC and PECL/mysqlnd_qc extensions if PECL/mysqlnd_qc will use APC as a storage handler. For using the APC storage handler, you have to statically compile PHP with APC and PECL/mysqlnd_qc support into PHP.

For using MEMCACHE storage handler: Use libmemcache 0.38 or newer. PECL/mysqlnd_qc 1.2 has been tested with libmemcache 1.4.0.

For using sqlite storage handler: Use the sqlite3 extension that bundled with PHP.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/mysqlnd_qc

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

mysqlnd_qc Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.collect_normalized_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.ignore_sql_comments | 1 | PHP_INI_ALL |
mysqlnd_qc.slam_defense | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.slam_defense_ttl | 30 | 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 |

Iata o explica?ie pe scurt a directivelor de configurare.

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

Whether to cache queries with no table name in any of columns meta data of their result set, for example, SELECT SLEEP(1), SELECT NOW(), SELECT SUBSTRING().

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. Therefore, 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 writable 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.ignore_sql_comments integer

Whether to remove SQL comments from a query string before hashing it to generate a cache key. Disable if you do not want two statemts such as SELECT /*my_source_ip=123*/ id FROM test and SELECT /*my_source_ip=456*/ id FROM test to refer to the same cache entry.

Since 1.1.0.

mysqlnd_qc.slam_defense integer

Activates handler based slam defense (cache stampeding protection) 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.

Instalarea
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

SQL hint related

Example #1 Using SQL hint constants

The query cache is controlled 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);
?>

Exemplele de mai sus vor afi?a:

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.
MYSQLND_QC_SERVER_ID_SWITCH (string)
This SQL hint should not be used in general. It is needed by PECL/mysqlnd_ms to group cache entries for one statement but originating from different physical connections. If the hint is used connection settings such as user, hostname and charset are not considered for generating a cache key of a query. Instead the given value and the query string are used as input to the hashing function that generates the key. PECL/mysqlnd_ms may, if instructed, cache results from MySQL Replication slaves. Because it can hold many connections to the slave the cache key shall not be formed from the user, hostname or other settings that may vary for the various slave connections. Instead, PECL/mysqlnd_ms provides an identifier which refers to the group of slave connections that shall be enabled to share cache entries no matter which physical slave connection was to generate the cache entry. Use of this feature outside of PECL/mysqlnd_ms is not recommended.

mysqlnd_qc_set_cache_condition() related

Example #2 Example mysqlnd_qc_set_cache_condition() usage

The function mysqlnd_qc_set_cache_condition() allows setting conditions for automatic caching of statements which don't begin with the SQL hints necessary to manually enable caching.

<?php
/* Cache all accesses to tables with the name "new%" in schema/database "db_example" for 1 second */
if (!mysqlnd_qc_set_cache_condition(MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN, "db_example.new%", 1)) {
  die("Failed to set cache condition!");
}

$mysqli = new mysqli("host", "user", "password", "db_example", "port");
/* cached although no SQL hint given  */
$mysqli->query("SELECT id, title FROM news");

$pdo_mysql = new PDO("mysql:host=host;dbname=db_example;port=port", "user", "password");
/* not cached: no SQL hint, no pattern match */
$pdo_mysql->query("SELECT id, title FROM latest_news");
/* cached: TTL 1 second, pattern match */
$pdo_mysql->query("SELECT id, title FROM news");
?>

MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN (int)
Used as a parameter of mysqlnd_qc_set_cache_condition() to set conditions for schema based automatic caching.

Other

The plugin version number can be obtained using either MYSQLND_QC_VERSION, which is the string representation of the numerical version number, or MYSQLND_QC_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_QC_VERSION_ID | 10000

MYSQLND_QC_VERSION (string)
Plugin version string, for example, "1.0.0-prototype".

MYSQLND_QC_VERSION_ID (int)
Plugin version number, for example, 10000.

Configura?ia la rulare
Func?ii mysqlnd_qc
mysqlnd_qc


Func?ii mysqlnd_qc

Cuprins

  • 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_cache_condition — Set conditions for automatic caching
  • 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
Constante predefinite
mysqlnd_qc_clear_cache
mysqlnd_qc


Flush all cache contents

Func?ii mysqlnd_qc
mysqlnd_qc_get_available_handlers
Func?ii mysqlnd_qc
PHP Manual

mysqlnd_qc_clear_cache

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_clear_cache — Flush all cache contents

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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.

Func?ii mysqlnd_qc
mysqlnd_qc_get_available_handlers
Func?ii mysqlnd_qc


Returns a list of available storage handler

mysqlnd_qc_clear_cache
mysqlnd_qc_get_cache_info
Func?ii mysqlnd_qc
PHP Manual

mysqlnd_qc_get_available_handlers

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_available_handlers — Returns a list of available storage handler

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array of available built-in storage handler. For each storage handler the version number and version string is given.

Exemple

Example #1 mysqlnd_qc_get_available_handlers() example

<?php
var_dump(mysqlnd_qc_get_available_handlers());
?>

Exemplele de mai sus vor afi?a:

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)
  }
}

A se vedea ?i

  • Installation
  • mysqlnd_qc_set_storage_handler() - Change current storage handler

mysqlnd_qc_clear_cache
mysqlnd_qc_get_cache_info
Func?ii mysqlnd_qc


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
Func?ii mysqlnd_qc
PHP Manual

mysqlnd_qc_get_cache_info

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_cache_info — Returns information on the current handler, the number of cache entries and cache entries, if available

Descrierea

array mysqlnd_qc_get_cache_info ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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. Depending 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 identifier 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 calculating 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 | Minimum run time of the cached statement. How long it took to find the statement in the cache. | Since 1.0.0.
min_store_time | Minimum 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.
valid_until | Timestamp when the cache entry expires. | Since 1.1.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.

Exemple

Example #1 mysqlnd_qc_get_cache_info() example

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());
?>

Exemplele de mai sus vor afi?a:

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)
       }
     }
   }
 }
}

A se vedea ?i

  • mysqlnd_qc_get_core_stats() - Statistics collected by the core of the query cache

mysqlnd_qc_get_available_handlers
mysqlnd_qc_get_core_stats
Func?ii mysqlnd_qc


Statistics collected by the core of the query cache

mysqlnd_qc_get_cache_info
mysqlnd_qc_get_normalized_query_trace_log
Func?ii mysqlnd_qc
PHP Manual

mysqlnd_qc_get_core_stats

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_core_stats — Statistics collected by the core of the query cache

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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 considered 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.

Exemple

Example #1 mysqlnd_qc_get_core_stats() example

<?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 statistics */
var_dump(mysqlnd_qc_get_core_stats());
?>

Exemplele de mai sus vor afi?a:

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)
}

A se vedea ?i

  • 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
Func?ii mysqlnd_qc


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
Func?ii mysqlnd_qc
PHP Manual

mysqlnd_qc_get_normalized_query_trace_log

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_normalized_query_trace_log — Returns a normalized query trace log for each query inspected by the query cache

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Exemple

Example #1 mysqlnd_qc_get_normalized_query_trace_log() example

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());
?>

Exemplele de mai sus vor afi?a:

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)
  }
}

A se vedea ?i

  • 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
Func?ii mysqlnd_qc


Returns a backtrace for each query inspected by the query cache

mysqlnd_qc_get_normalized_query_trace_log
mysqlnd_qc_set_cache_condition
Func?ii mysqlnd_qc
PHP Manual

mysqlnd_qc_get_query_trace_log

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_query_trace_log — Returns a backtrace for each query inspected by the query cache

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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 cacheable 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.

Exemple

Example #1 mysqlnd_qc_get_query_trace_log() example

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());
?>

Exemplele de mai sus vor afi?a:

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)
  }
}

A se vedea ?i

  • 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_cache_condition
Func?ii mysqlnd_qc


Set conditions for automatic caching

mysqlnd_qc_get_query_trace_log
mysqlnd_qc_set_is_select
Func?ii mysqlnd_qc
PHP Manual

mysqlnd_qc_set_cache_condition

(PECL mysqlnd_qc >= 1.1.0)

mysqlnd_qc_set_cache_condition — Set conditions for automatic caching

Descrierea

bool mysqlnd_qc_set_cache_condition ( int $condition_type , mixed $condition , mixed $condition_option )

Sets a condition for automatic caching of statements which do not contain the necessary SQL hints to enable caching of them.

Parametri

condition_type

Type of the condition. The only allowed value is MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN.

condition

Parameter for the condition set with condition_type. Parameter type and structure depend on condition_type

If condition_type equals MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN condition must be a string. The string sets a pattern. Statements are cached if table and database meta data entry of their result sets match the pattern. The pattern is checked for a match with the db and org_table meta data entries provided by the underlying MySQL client server library. Please, check the MySQL Reference manual for details about the two entries. The db and org_table values are concatenated with a dot (.) before matched against condition. Pattern matching supports the wildcards % and _. The wildcard % will match one or many arbitrary characters. _ will match one arbitrary character. The escape symbol is backslash.

condition_option

Option for condition. Type and structure depend on condition_type.

If condition_type equals MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN condition_options is the TTL to be used.

Exemple

Example #1 mysqlnd_qc_set_cache_condition() example

<?php
/* Cache all accesses to tables with the name "new%" in schema/database "db_example" for 1 second */
if (!mysqlnd_qc_set_cache_condition(MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN, "db_example.new%", 1)) {
  die("Failed to set cache condition!");
}

$mysqli = new mysqli("host", "user", "password", "db_example", "port");
/* cached although no SQL hint given  */
$mysqli->query("SELECT id, title FROM news");

$pdo_mysql = new PDO("mysql:host=host;dbname=db_example;port=port", "user", "password");
/* not cached: no SQL hint, no pattern match */
$pdo_mysql->query("SELECT id, title FROM latest_news");
/* cached: TTL 1 second, pattern match */
$pdo_mysql->query("SELECT id, title FROM news");
?>

Valorile întoarse

Returns TRUE on success or FALSE on FAILURE.

A se vedea ?i

  • Quickstart: pattern based caching

mysqlnd_qc_get_query_trace_log
mysqlnd_qc_set_is_select
Func?ii mysqlnd_qc


Installs a callback which decides whether a statement is cached

mysqlnd_qc_set_cache_condition
mysqlnd_qc_set_storage_handler
Func?ii mysqlnd_qc
PHP Manual

mysqlnd_qc_set_is_select

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_set_is_select — Installs a callback which decides whether a statement is cached

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 mysqlnd_qc_set_is_select() example

<?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");
?>

Exemplele de mai sus vor afi?a:

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

A se vedea ?i

  • 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_set_cache_condition
mysqlnd_qc_set_storage_handler
Func?ii mysqlnd_qc


Change current storage handler

mysqlnd_qc_set_is_select
mysqlnd_qc_set_user_handlers
Func?ii mysqlnd_qc
PHP Manual

mysqlnd_qc_set_storage_handler

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_set_storage_handler — Change current storage handler

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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.

Exemple

Example #1 mysqlnd_qc_set_storage_handler() example

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"));
?>

Exemplele de mai sus vor afi?a:

bool(true)
Default storage handler activated
Catchable fatal error: mysqlnd_qc_set_storage_handler(): Unknown handler 'unknown' in (file) on line (line)

A se vedea ?i

  • Installation
  • mysqlnd_qc_get_available_handlers() - Returns a list of available storage handler

mysqlnd_qc_set_is_select
mysqlnd_qc_set_user_handlers
Func?ii mysqlnd_qc


Sets the callback functions for a user-defined procedural storage handler

mysqlnd_qc_set_storage_handler
Change History
Func?ii mysqlnd_qc
PHP Manual

mysqlnd_qc_set_user_handlers

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_set_user_handlers — Sets the callback functions for a user-defined procedural storage handler

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE on success or FALSE on FAILURE.

A se vedea ?i

  • Procedural user-defined storage handler example

mysqlnd_qc_set_storage_handler
Change History
Func?ii mysqlnd_qc


Change History

Cuprins

  • PECL/mysqlnd_qc 1.2 series
  • 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.2 series
mysqlnd_qc


PECL/mysqlnd_qc 1.2 series

1.2.0 - alpha

  • Release date: 03/2013
  • Motto/theme: PHP 5.5 compatibility

Feature changes

  • Update build for PHP 5.5 (Credits: Remi Collet)

  • APC storage handler update

    • Fix build for APC 3.1.13-beta and trunk

  • Introduced MYSQLND_QC_VERSION and MYSQLND_QC_VERSION_ID.

Change History
PECL/mysqlnd_qc 1.1 series
Change History


PECL/mysqlnd_qc 1.1 series

1.1.0 - stable

  • Release date: 04/2012
  • Motto/theme: PHP 5.4 compatibility, schema pattern based caching and mysqlnd_ms support

1.1.0 - beta

  • Release date: 04/2012
  • Motto/theme: PHP 5.4 compatibility, schema pattern based caching and mysqlnd_ms support

1.1.0 - alpha

  • Release date: 04/2012
  • Motto/theme: PHP 5.4 compatibility, schema pattern based caching and mysqlnd_ms support

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 directives

    • mysqlnd_qc.collect_statistics_log_file. Aggregated cache statistics log file written after every 10th request served by the PHP process.
    • mysqlnd_qc.ignore_sql_comments. Control whether SQL comments are ignored for cache key hash generation.

  • New constants and SQL hints

    • MYSQLND_QC_SERVER_ID_SWITCH allows grouping of cache entries from different physical connections. This is needed by PECL/mysqlnd_ms.
    • MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN to be used with mysqlnd_qc_set_cache_condition().

  • New function mysqlnd_qc_set_cache_condition() for built-in schema pattern based caching. Likely to support a wider range of conditions in the future.

  • Report valid_until timestamp for cache entries of the default handler through mysqlnd_qc_get_cache_info().

  • Include charset number for cache entry hashing. This should prevent serving result sets which have the wrong charset.

    API change: get_hash_key expects new "charsetnr" (int) parameter after "port".

  • API change: changing is_select() signature from bool is_select() to mixed is_select(). Mixed can be either boolean or array(long ttl, string server_id). This is needed by PECL/mysqlnd_ms.

Other

  • Support acting as a cache backend for PECL/mysqlnd_ms 1.3.0-beta or later to transparently replace MySQL Replication slave reads with cache accesses, if the user explicitly allows.

Bug fixes

  • Fixed Bug #59959 (config.m4, wrong library - 64bit memcached handler builds) (Credits: Remi Collet)

PECL/mysqlnd_qc 1.2 series
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

  • Introducere
  • Quickstart and Examples
    • Setup
    • How it works
    • Installing a proxy
    • Basic query monitoring
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • 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-committing 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
  • Func?ii mysqlnd_uh
    • 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
Introducere
MySQL


Introducere

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 executed by any of the PHP MySQL extensions

    • Prepared statements executing by any of the PHP MySQL extensions

  • Auditing

    • Detection of database usage

    • SQL injection protection using black and white lists

  • Assorted

    • Load Balancing connections

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.

Nota: Status

The mysqlnd user handler plugin is in alpha status. Take appropriate care before using it in production environments.

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 mysqlnd_uh functions are briefly described because the mysqli extension is a thin abstraction layer on top of the MySQL C API that the mysqlnd library provides. Therefore, the corresponding mysqli documentation (along with the MySQL reference manual) can be consulted to receive more information about a particular function.

On the name

The shortcut mysqlnd_uh stands for mysqlnd user handler, and has been the name since early development.

mysqlnd_uh
Quickstart and Examples
mysqlnd_uh


Quickstart and Examples

Cuprins

  • 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.

Nota:

The internal mysqlnd function calls are not designed to be 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 the Mysqlnd_uh Op?iuni de configurare pentru.

Introducere
Setup
mysqlnd_uh


Setup

The plugin is implemented as a PHP extension. See 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.

Example #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

This describes the background and inner workings of the mysqlnd_uh extension.

Two classes are provided by the extension: MysqlndUhConnection and MysqlndUhPreparedStatement. MysqlndUhConnection 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 extension 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. For example, mysqli_connect() invokes mysqlnd_conn__connect, so 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 exactly like the original mysqlnd function they replace. The code below illustrates in pseudo-code what the extension does.

Example #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().

Example #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");
?>

Exemplul de mai sus va afi?a:

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.

See also the How it works guide to learn about the inner workings of this extension.

Connection 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.

Example #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 controls whether a proxy may be set. If disabled, the extension will throw errors of type E_WARNING

Example #2 Proxy installation disabled

mysqlnd_uh.enable=0
<?php
mysqlnd_uh_set_connection_proxy(new MysqlndUhConnection());
$mysqli = new mysqli("localhost", "root", "", "test");
?>

Exemplul de mai sus va afi?a:

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.

Example #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", "");
?>

Exemplul de mai sus va afi?a:

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().

Example #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");
?>

Exemplul de mai sus va afi?a:

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 refactoring to find code still accessing deprecated databases or tables. The latter may be a complicated matter to do otherwise, especially if the application uses auto-generated queries.

Example #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");
?>

Exemplul de mai sus va afi?a:

#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
Instalarea / configurarea
Quickstart and Examples


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Basic query monitoring
Necesita?i
mysqlnd_uh


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/mysqlnd-uh

PECL/mysqlnd_uh nu este disponibil pentru Windows la moment. Codul-sursa al extensiei utilizeaza construc?ii C99 ce nu sunt admise în versiunile PHP pentru Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Mysqlnd_uh Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
mysqlnd_uh.enable | 1 | PHP_INI_SYSTEM |
mysqlnd_uh.report_wrong_types | 1 | PHP_INI_ALL |

Iata o explica?ie pe scurt a directivelor de configurare.

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

Whether to report wrong return value types of user hooks as E_WARNING level errors. This is recommended for detecting errors.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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: authentication.
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)
Implicitly closed, 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: whether 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: Whether 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: Whether to report data truncation.
MYSQLND_UH_MYSQLND_OPT_RECONNECT (integer)
Option: Whether 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 authentication method.
MYSQLND_UH_SERVER_OPTION_SET_CLIENT_IP (integer)
TODO
MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET (integer)
Option: maximum allowed 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.

Tipurile resurselor
MysqlndUhConnection
mysqlnd_uh


The MysqlndUhConnection class

(PECL mysqlnd-uh >= 1.0.0-alpha)

Introducere

Sinopsisul clasei

MysqlndUhConnection {
/* Metode */
public bool changeUser ( mysqlnd_connection $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 )
}

Cuprins

  • 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-committing 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
Constante predefinite
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

Descrierea

public bool MysqlndUhConnection::changeUser ( mysqlnd_connection $connection , string $user , string $password , string $database , bool $silent , int $passwd_len )

Changes the user of the specified mysqlnd database connection

Parametri

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.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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"));
?>

Exemplul de mai sus va afi?a:

proxy::changeUser(array (
  0 => NULL,
  1 => 'root',
  2 => 'bar',
  3 => 'test',
  4 => false,
  5 => 3,
))
proxy::changeUser returns false
bool(false)

A se vedea ?i

  • 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

Descrierea

public string MysqlndUhConnection::charsetName ( mysqlnd_connection $connection )

Returns the default character set for the database connection.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

The default character set.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

proxy::charsetName(array (
  0 => NULL,
))
proxy::charsetName returns 'latin1'
string(6) "latin1"

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::close ( mysqlnd_connection $connection , int $close_type )

Closes a previously opened database connection.

Nota:

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.

Parametri

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.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

proxy::close(array (
  0 => NULL,
  1 => 0,
))
close_type = MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT
proxy::close returns true

A se vedea ?i

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_close() - Closes a previously opened database connection
  • mysql_close() - Închide conexiunea 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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

proxy::connect(array (
  0 => NULL,
  1 => 'localhost',
  2 => 'root',
  3 => '',
  4 => 'test',
  5 => 3306,
  6 => NULL,
  7 => 131072,
))
proxy::connect returns true

A se vedea ?i

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_connect() - Pseudonim pentru mysqli::__construct
  • mysql_connect() - Deschide o conexiune la un server 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

Descrierea

public MysqlndUhConnection::__construct ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool MysqlndUhConnection::endPSession ( mysqlnd_connection $connection )

End a persistent connection

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

proxy::endPSession(array (
  0 => NULL,
))
proxy::endPSession returns true

A se vedea ?i

  • 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

Descrierea

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.

Parametri

MYSQLND_UH_RES_MYSQLND_NAME

Mysqlnd connection handle. Do not modify!

escape_string

The string to be escaped.

Valorile întoarse

The escaped string.

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

proxy::escapeString(array (
  0 => NULL,
  1 => 'test0\'test',
))
proxy::escapeString returns 'test0\\\'test'

A se vedea ?i

  • 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() - Escapes special characters in a string for use in an SQL statement

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

Descrierea

public int MysqlndUhConnection::getAffectedRows ( mysqlnd_connection $connection )

Gets the number of affected rows in a previous MySQL operation.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Number of affected rows.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::getAffectedRows(array (
  0 => NULL,
))
proxy::getAffectedRows returns 1
int(1)

A se vedea ?i

  • 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() - Ob?ine numarul de rânduri afectate de precedenta opera?iune 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

Descrierea

public int MysqlndUhConnection::getErrorNumber ( mysqlnd_connection $connection )

Returns the error code for the most recent function call.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Error code for the most recent function call.

Exemple

MysqlndUhConnection::getErrorNumber() is not only executed after the invocation of a user space API call which maps directly to it but also called internally.

Example #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();
?>

Exemplul de mai sus va afi?a:

connect...
proxy::getErrorNumber(array (
  0 => NULL,
))
proxy::getErrorNumber returns 0
query...
errno...
proxy::getErrorNumber(array (
  0 => NULL,
))
proxy::getErrorNumber returns 1064
int(1064)
close...

A se vedea ?i

  • 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() - Returns the numerical value of the error message from previous MySQL operation

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

Descrierea

public string MysqlndUhConnection::getErrorString ( mysqlnd_connection $connection )

Returns a string description of the last error.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Error string for the most recent function call.

Exemple

MysqlndUhConnection::getErrorString() is not only executed after the invocation of a user space API call which maps directly to it but also called internally.

Example #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();
?>

Exemplul de mai sus va afi?a:

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...

A se vedea ?i

  • 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() - Returns the text of the error message from previous MySQL operation

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

Descrierea

public int MysqlndUhConnection::getFieldCount ( mysqlnd_connection $connection )

Returns the number of columns for the most recent query.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Number of columns.

Exemple

MysqlndUhConnection::getFieldCount() is not only executed after the invocation of a user space API call which maps directly to it but also called internally.

Example #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);
?>

Exemplul de mai sus va afi?a:

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)

A se vedea ?i

  • 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

Descrierea

public string MysqlndUhConnection::getHostInformation ( mysqlnd_connection $connection )

Returns a string representing the type of connection used.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Connection description.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::getHostInformation(array (
  0 => NULL,
))
proxy::getHostInformation returns 'Localhost via UNIX socket'
string(25) "Localhost via UNIX socket"

A se vedea ?i

  • 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() - Get MySQL host info

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.

Descrierea

public int MysqlndUhConnection::getLastInsertId ( mysqlnd_connection $connection )

Returns the auto generated id used in the last query.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Last insert id.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::getLastInsertId(array (
  0 => NULL,
))
proxy::getLastInsertId returns 1
int(1)

A se vedea ?i

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_insert_id() - Returns the auto generated id used in the latest query
  • mysql_insert_id() - Get the ID generated in the last query

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

Descrierea

public void MysqlndUhConnection::getLastMessage ( mysqlnd_connection $connection )

Retrieves information about the most recently executed query.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

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.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::getLastMessage(array (
  0 => NULL,
))
proxy::getLastMessage returns ''
string(0) ""
proxy::getLastMessage(array (
  0 => NULL,
))
proxy::getLastMessage returns ''
string(0) ""

A se vedea ?i

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_info() - Retrieves information about the most recently executed query
  • mysql_info() - Get information about the most recent query

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

Descrierea

public string MysqlndUhConnection::getProtocolInformation ( mysqlnd_connection $connection )

Returns the version of the MySQL protocol used.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

The protocol version.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::getProtocolInformation(array (
  0 => NULL,
))
proxy::getProtocolInformation returns 10
int(10)

A se vedea ?i

  • 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() - Get MySQL protocol info

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

Descrierea

public string MysqlndUhConnection::getServerInformation ( mysqlnd_connection $connection )

Returns the version of the MySQL server.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

The server version.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::getServerInformation(array (
  0 => NULL,
))
proxy::getServerInformation returns '5.1.45-debug-log'
string(16) "5.1.45-debug-log"

A se vedea ?i

  • 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() - Get MySQL server info

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

Descrierea

public string MysqlndUhConnection::getServerStatistics ( mysqlnd_connection $connection )

Gets the current system status.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

The system status message.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

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"

A se vedea ?i

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_stat() - Gets the current system status
  • mysql_stat() - Get current system status

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

Descrierea

public int MysqlndUhConnection::getServerVersion ( mysqlnd_connection $connection )

Returns the version of the MySQL server as an integer.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

The MySQL version.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::getServerVersion(array (
  0 => NULL,
))
proxy::getServerVersion returns 50145
int(50145)

A se vedea ?i

  • 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

Descrierea

public string MysqlndUhConnection::getSqlstate ( mysqlnd_connection $connection )

Returns the SQLSTATE error from previous MySQL operation.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

The SQLSTATE code.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::getSqlstate(array (
  0 => NULL,
))
proxy::getSqlstate returns '00000'
string(5) "00000"
proxy::getSqlstate(array (
  0 => NULL,
))
proxy::getSqlstate returns '42000'
string(5) "42000"

A se vedea ?i

  • 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.

Descrierea

public array MysqlndUhConnection::getStatistics ( mysqlnd_connection $connection )

Returns statistics about the client connection.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Connection statistics collected by mysqlnd.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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"
}

A se vedea ?i

  • 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

Descrierea

public int MysqlndUhConnection::getThreadId ( mysqlnd_connection $connection )

Returns the thread ID for the current connection.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Connection thread id.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::getThreadId(array (
  0 => NULL,
))
proxy::getThreadId returns 27646
int(27646)

A se vedea ?i

  • 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() - Return the current thread ID

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

Descrierea

public int MysqlndUhConnection::getWarningCount ( mysqlnd_connection $connection )

Returns the number of warnings from the last query for the given link.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Number of warnings.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::getWarningCount(array (
  0 => NULL,
))
proxy::getWarningCount returns 0
int(0)

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::init ( mysqlnd_connection $connection )

Initialize mysqlnd connection. This is an mysqlnd internal call to initialize the connection object.

Nota:

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.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

proxy::init(array (
  0 => NULL,
))
proxy::init returns true

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::killConnection ( mysqlnd_connection $connection , int $pid )

Asks the server to kill a MySQL thread.

Parametri

connection

Mysqlnd connection handle. Do not modify!

pid

Thread Id of the connection to be killed.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::killConnection(array (
  0 => NULL,
  1 => 27650,
))
proxy::killConnection returns true

A se vedea ?i

  • 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

Descrierea

public array MysqlndUhConnection::listFields ( mysqlnd_connection $connection , string $table , string $achtung_wild )

List MySQL table fields.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

connection

Mysqlnd connection handle. Do not modify!

table

The name of the table that's being queried.

pattern

Name pattern.

Valorile întoarse

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::listFields(array (
  0 => NULL,
  1 => 'test_a',
  2 => '',
))
proxy::listFields returns NULL
num_rows = 0

A se vedea ?i

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysql_list_fields() - List MySQL table fields

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

Descrierea

public void MysqlndUhConnection::listMethod ( mysqlnd_connection $connection , string $query , string $achtung_wild , string $par1 )

Wrapper for assorted list commands.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

connection

Mysqlnd connection handle. Do not modify!

query

SHOW command to be executed.

achtung_wild

par1

Valorile întoarse

Valorile întoarse

TODO

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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"
}

A se vedea ?i

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysql_list_dbs() - List databases available on a MySQL server

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

Descrierea

public bool MysqlndUhConnection::moreResults ( mysqlnd_connection $connection )

Check if there are any more query results from a multi query.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::nextResult ( mysqlnd_connection $connection )

Prepare next result from multi_query.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

array(1) {
  ["_one"]=>
  string(1) "1"
}
----------------------------------------
proxy::nextResult(array (
  0 => NULL,
))
proxy::nextResult returns true
array(1) {
  ["_two"]=>
  string(1) "2"
}
----------------------------------------

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::ping ( mysqlnd_connection $connection )

Pings a server connection, or tries to reconnect if the connection has gone down.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

proxy::ping(array (
  0 => NULL,
))
proxy::ping returns true

A se vedea ?i

  • 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() - Ping a server connection or reconnect if there is no connection

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

Descrierea

public bool MysqlndUhConnection::query ( mysqlnd_connection $connection , string $query )

Performs a query on the database (COM_QUERY).

Parametri

connection

Mysqlnd connection handle. Do not modify!

query

The query string.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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?"
}

A se vedea ?i

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_query() - Performs a query on the database
  • mysql_query() - Send a MySQL query

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

Descrierea

public bool MysqlndUhConnection::queryReadResultsetHeader ( mysqlnd_connection $connection , mysqlnd_statement $mysqlnd_stmt )

Read a result set header.

Parametri

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.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

proxy::queryReadResultsetHeader(array (
  0 => NULL,
  1 => NULL,
))
proxy::queryReadResultsetHeader returns true
array(1) {
  ["Welcome mysqlnd_uh!"]=>
  string(19) "Welcome mysqlnd_uh!"
}

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::reapQuery ( mysqlnd_connection $connection )

Get result from async query.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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"
}

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::refreshServer ( mysqlnd_connection $connection , int $options )

Flush or reset tables and caches.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

connection

Mysqlnd connection handle. Do not modify!

options

What to refresh.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::refreshServer(array (
  0 => NULL,
  1 => 1,
))
proxy::refreshServer returns false

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::restartPSession ( mysqlnd_connection $connection )

Restart a persistent mysqlnd connection.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

proxy::restartPSession(array (
  0 => NULL,
))
proxy::restartPSession returns true

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::selectDb ( mysqlnd_connection $connection , string $database )

Selects the default database for database queries.

Parametri

connection

Mysqlnd connection handle. Do not modify!

database

The database name.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

proxy::selectDb(array (
  0 => NULL,
  1 => 'mysql',
))
proxy::selectDb returns true

A se vedea ?i

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_select_db() - Selects the default database for database queries
  • mysql_select_db() - Select a MySQL database

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

Descrierea

public bool MysqlndUhConnection::sendClose ( mysqlnd_connection $connection )

Sends a close command to MySQL.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

proxy::sendClose(array (
  0 => NULL,
))
proxy::sendClose returns true
proxy::sendClose(array (
  0 => NULL,
))
proxy::sendClose returns true

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::sendQuery ( mysqlnd_connection $connection , string $query )

Sends a query to MySQL.

Parametri

connection

Mysqlnd connection handle. Do not modify!

query

The query string.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

proxy::sendQuery(array (
  0 => NULL,
  1 => 'SELECT 1',
))
proxy::sendQuery returns true

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::serverDumpDebugInformation ( mysqlnd_connection $connection )

Dump debugging information into the log for the MySQL server.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

proxy::serverDumpDebugInformation(array (
  0 => NULL,
))
proxy::serverDumpDebugInformation returns true

A se vedea ?i

  • 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-committing 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-committing database modifications

Descrierea

public bool MysqlndUhConnection::setAutocommit ( mysqlnd_connection $connection , int $mode )

Turns on or off auto-committing database modifications

Parametri

connection

Mysqlnd connection handle. Do not modify!

mode

Whether to turn on auto-commit or not.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

proxy::setAutocommit(array (
  0 => NULL,
  1 => 0,
))
proxy::setAutocommit returns true
proxy::setAutocommit(array (
  0 => NULL,
  1 => 1,
))
proxy::setAutocommit returns true

A se vedea ?i

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_autocommit() - Turns on or off auto-committing 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

Descrierea

public bool MysqlndUhConnection::setCharset ( mysqlnd_connection $connection , string $charset )

Sets the default client character set.

Parametri

connection

Mysqlnd connection handle. Do not modify!

charset

The charset to be set as default.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

proxy::setCharset(array (
  0 => NULL,
  1 => 'latin1',
))
proxy::setCharset returns true

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::setClientOption ( mysqlnd_connection $connection , int $option , int $value )

Sets a client option.

Parametri

connection

Mysqlnd connection handle. Do not modify!

option

The option to be set.

value

Optional option value, if required.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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

Descrierea

public void MysqlndUhConnection::setServerOption ( mysqlnd_connection $connection , int $option )

Sets a server option.

Parametri

connection

Mysqlnd connection handle. Do not modify!

option

The option to be set.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

proxy::setServerOption(array (
  0 => NULL,
  1 => 0,
))
Option 'MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON' set
proxy::setServerOption returns true

A se vedea ?i

  • 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

Descrierea

public void MysqlndUhConnection::shutdownServer ( string $MYSQLND_UH_RES_MYSQLND_NAME , string $"level" )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

MYSQLND_UH_RES_MYSQLND_NAME

"level"

Valorile întoarse

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::sslSet ( mysqlnd_connection $connection , string $key , string $cert , string $ca , string $capath , string $cipher )

Used for establishing secure connections using SSL.

Parametri

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.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #1 MysqlndUhConnection::sslSet() example

<?php
class proxy extends MysqlndUhConnection {
 public function sslSet($conn, $key, $cert, $ca, $capath, $cipher) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::sslSet($conn, $key, $cert, $ca, $capath, $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");
?>

Exemplul de mai sus va afi?a:

proxy::sslSet(array (
  0 => NULL,
  1 => 'key',
  2 => 'cert',
  3 => 'ca',
  4 => 'capath',
  5 => 'cipher',
))
proxy::sslSet returns true

A se vedea ?i

  • 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

Descrierea

public resource MysqlndUhConnection::stmtInit ( mysqlnd_connection $connection )

Initializes a statement and returns a resource for use with mysqli_statement::prepare.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

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.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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)

A se vedea ?i

  • 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

Descrierea

public resource MysqlndUhConnection::storeResult ( mysqlnd_connection $connection )

Transfers a result set from the last query.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

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.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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!"
}

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::txCommit ( mysqlnd_connection $connection )

Commits the current transaction.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

proxy::txCommit(array (
  0 => NULL,
))
proxy::txCommit returns true

A se vedea ?i

  • 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

Descrierea

public bool MysqlndUhConnection::txRollback ( mysqlnd_connection $connection )

Rolls back current transaction.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

proxy::txRollback(array (
  0 => NULL,
))
proxy::txRollback returns true

A se vedea ?i

  • 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

Descrierea

public resource MysqlndUhConnection::useResult ( mysqlnd_connection $connection )

Initiate a result set retrieval.

Parametri

connection

Mysqlnd connection handle. Do not modify!

Valorile întoarse

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.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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!"
}

A se vedea ?i

  • 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

(PECL mysqlnd-uh >= 1.0.0-alpha)

Introducere

Sinopsisul clasei

MysqlndUhPreparedStatement {
/* Metode */
public __construct ( void )
public bool execute ( mysqlnd_prepared_statement $statement )
public bool prepare ( mysqlnd_prepared_statement $statement , string $query )
}

Cuprins

  • 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

Descrierea

public MysqlndUhPreparedStatement::__construct ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool MysqlndUhPreparedStatement::execute ( mysqlnd_prepared_statement $statement )

Executes a prepared Query.

Parametri

statement

Mysqlnd prepared statement handle. Do not modify! Resource of type Mysqlnd Prepared Statement (internal only - you must not modify it!).

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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"

A se vedea ?i

  • 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
Func?ii mysqlnd_uh
MysqlndUhPreparedStatement
PHP Manual

MysqlndUhPreparedStatement::prepare

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhPreparedStatement::prepare — Prepare an SQL statement for execution

Descrierea

public bool MysqlndUhPreparedStatement::prepare ( mysqlnd_prepared_statement $statement , string $query )

Prepare an SQL statement for execution.

Parametri

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.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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"

A se vedea ?i

  • 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
Func?ii mysqlnd_uh
MysqlndUhPreparedStatement


Func?ii mysqlnd_uh

Cuprins

  • 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

Func?ii mysqlnd_uh
mysqlnd_uh_set_connection_proxy
Func?ii mysqlnd_uh
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

Descrierea

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 [...].

Parametri

MySQL connection handle

A MySQL connection handle of type mysql, mysqli or PDO_MySQL.

Valorile întoarse

A mysqlnd connection handle.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | The mysql_connection parameter can now be of type mysql, PDO_MySQL, or mysqli. Before, only the mysqli type was allowed.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

int(27054)
array(1) {
  [0]=>
  array(2) {
    ["CONNECTION_ID()"]=>
    string(5) "27054"
    [0]=>
    string(5) "27054"
  }
}

A se vedea ?i

  • mysqlnd_uh.enable

Func?ii mysqlnd_uh
mysqlnd_uh_set_connection_proxy
Func?ii mysqlnd_uh


Installs a proxy for mysqlnd connections

mysqlnd_uh_convert_to_mysqlnd
mysqlnd_uh_set_statement_proxy
Func?ii mysqlnd_uh
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

Descrierea

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 [...].

Parametri

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.

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

Exemple

Example #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!'");
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • mysqlnd_uh_set_statement_proxy() - Installs a proxy for mysqlnd statements
  • mysqlnd_uh.enable

mysqlnd_uh_convert_to_mysqlnd
mysqlnd_uh_set_statement_proxy
Func?ii mysqlnd_uh


Installs a proxy for mysqlnd statements

mysqlnd_uh_set_connection_proxy
Change History
Func?ii mysqlnd_uh
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

Descrierea

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 [...].

Parametri

statement_proxy

The mysqlnd statement proxy object of type MysqlndUhStatement

Valorile întoarse

Returns TRUE on success. Otherwise, returns FALSE

A se vedea ?i

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqlnd_uh.enable

mysqlnd_uh_set_connection_proxy
Change History
Func?ii mysqlnd_uh


Change History

Cuprins

  • 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. See also the CHANGES file contained in the source for additional changelog information. The commit history is also available.

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
mysqlnd_mux
Change History


Mysqlnd connection multiplexing plugin

  • Introducere
  • Concepts
    • Architecture
    • Connection pool
    • Sharing connections
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
  • Constante predefinite
  • Change History
    • PECL/mysqlnd_mux 1.0 series
PECL/mysqlnd_uh 1.0 series
Introducere
MySQL


Introducere

The mysqlnd multiplexing plugin (mysqlnd_mux) multiplexes MySQL connections established by all PHP MySQL extensions that use the MySQL native driver (mysqlnd) for PHP.

The MySQL native driver for PHP features an internal C API for plugins, such as the connection multiplexing plugin, which can extend the functionality of mysqlnd. See the mysqlnd for additional details about its benefits over the MySQL Client Library libmysqlclient.

Mysqlnd plugins like mysqlnd_mux operate, for the most part, transparently from a user perspective. The connection multiplexing 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.

Nota:

This is a proof-of-concept. All features are at an early stage. Not all kinds of queries are handled by the plugin yet. Thus, it cannot be used in a drop-in fashion at the moment.

Please, do not use this version in production environments.

Key Features

The key features of mysqlnd_mux are as follows:

  • Transparent and therefore easy to use:

    • Supports all of the PHP MySQL extensions.

    • Little to no application changes are required, dependent on the required usage scenario.

  • Reduces server load and connection establishment latency:

    • Opens less connections to the MySQL server.

    • Less connections to MySQL mean less work for the MySQL server. In a client-server environment scaling the server is often more difficult than scaling the client. Multiplexing helps with horizontal scale-out (scale-by-client).

    • Pooling saves connection time.

    • Multiplexed connection: multiple user handles share the same network connection. Once opened, a network connection is cached and shared among multiple user handles. There is a 1:n relationship between internal network connection and user connection handles.

    • Persistent connection: a network connection is kept open at the end of the web request, if the PHP deployment model allows. Thus, subsequently web requests can reuse a previously opened connection. Like other resources, network connections are bound to the scope of a process. Thus, they can be reused for all web requests served by a process.

Limitations

The proof-of-concept does not support unbuffered queries, prepared statements, and asynchronous queries.

The connection pool is using a combination of the transport method and hostname as keys. As a consequence, two connections to the same host using the same transport method (TCP/IP, Unix socket, Windows named pipe) will be linked to the same pooled connection even if username and password differ. Be aware of the possible security implications.

The proof-of-concept is transaction agnostic. It does not know about SQL transactions.

Nota:

Applications must be aware of the consequences of connection sharing connections.

About the name mysqlnd_mux

The shortcut mysqlnd_mux stands for mysqlnd connection multiplexing plugin.

mysqlnd_mux
Concepts
mysqlnd_mux


Concepts

Cuprins

  • Architecture
  • Connection pool
  • Sharing connections

This explains the architecture and related concepts for this plugin. Reading and understanding these concepts is required to successfully use this plugin.

Introducere
Architecture
mysqlnd_mux


Architecture

The mysqlnd connection multiplexing 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 initialization phase of the PHP engine, it gets registered as a mysqlnd plugin to replace specific mysqlnd C methods.

The mysqlnd library uses PHP streams to communicate with the MySQL server. PHP streams are accessed by the mysqlnd library through its net module. The mysqlnd connection multiplexing plugin proxies methods of the mysqlnd library net module to control opening and closing of network streams.

Upon opening a user connection to MySQL using the appropriate connection functions of either mysqli, PDO_MYSQL or ext/mysql, the plugin will search its connection pool for an open network connection. If the pool contains a network connection to the host specified by the connect function using the transport method requested (TCP/IP, Unix domain socket, Windows named pipe), the pooled connection is linked to the user handle. Otherwise, a new network connection is opened, put into the poolm and associated with the user connection handle. This way, multiple user handles can be linked to the same network connection.

Concepts
Connection pool
Concepts


Connection pool

The plugins connection pool is created when PHP initializes its modules (MINIT) and free'd when PHP shuts down the modules (MSHUTDOWN). This is the same as for persistent MySQL connections.

Depending on the deployment model, the pool is used for the duration of one or multiple web requests. Network connections are bound to the lifespan of an operating system level process. If the PHP process serves multiple web requests as it is the case for Fast-CGI or threaded web server deployments, then the pooled connections can be reused over multiple connections. Because multiplexing means sharing connections, it can even happen with a threaded deployment that two threads or two distinct web requests are linked to one pooled network connections.

A pooled connection is explicitly closed once the last reference to it is released. An implicit close happens when PHP shuts down its modules.

Architecture
Sharing connections
Concepts


Sharing connections

The PHP mysqlnd connection multiplexing plugin changes the relationship between a users connection handle and the underlying MySQL connection. Without the plugin, every MySQL connection belongs to exactly one user connection at a time. The multiplexing plugin changes. A MySQL connection is shared among multiple user handles. There no one-to-one relation if using the plugin.

Sharing pooled connections has an impact on the connection state. State changing operations from multiple user handles pointing to one MySQL connection are not isolated from each other. If, for example, a session variable is set through one user connection handle, the session variable becomes visible to all other user handles that reference the same underlying MySQL connection.

This is similar in concept to connection state related phenomens described for the PHP mysqlnd replication and load balancing plugin. Please, check the PECL/mysqlnd_ms documentation for more details on the state of a connection.

The proof-of-concept takes no measures to isolate multiplexed connections from each other.

Connection pool
Instalarea / configurarea
Concepts


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
Sharing connections
Necesita?i
mysqlnd_mux


Necesita?i

PHP 5.5.0 or newer. Some advanced functionality requires PHP 5.5.0 or newer.

The mysqlnd_mux 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_mux plugin for mysqlnd.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/mysqlnd_mux

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Mysqlnd_mux Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
mysqlnd_mux.enable | 0 | PHP_INI_SYSTEM |

Iata o explica?ie pe scurt a directivelor de configurare.

mysqlnd_mux.enable integer

Enables or disables the plugin. If disabled, the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.

Instalarea
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Other

The plugins version number can be obtained using MYSQLND_MUX_VERSION or MYSQLND_MUX_VERSION_ID. MYSQLND_MUX_VERSION is the string representation of the numerical version number MYSQLND_MUX_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_MUX_VERSION_ID | 10000

MYSQLND_MUX_VERSION (string)
Plugin version string, for example, "1.0.0-prototype".
MYSQLND_MUX_VERSION_ID (integer)
Plugin version number, for example, 10000.

Configura?ia la rulare
Change History
mysqlnd_mux


Change History

Cuprins

  • PECL/mysqlnd_mux 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.

Constante predefinite
PECL/mysqlnd_mux 1.0 series
mysqlnd_mux


PECL/mysqlnd_mux 1.0 series

1.0.0-pre-alpha

  • Release date: no package released, initial check-in 09/2012
  • Motto/theme: Proof of concept

Initial check-in. Essentially a demo of the mysqlnd plugin API.

Nota:

This is the current development series. All features are at an early stage. Changes may happen at any time without prior notice. Please, do not use this version in production environments.

The documentation may not reflect all changes yet.

Change History
mysqlnd_memcache
Change History


Mysqlnd Memcache plugin

  • Introducere
  • Quickstart and Examples
    • Setup
    • Usage
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
  • Constante predefinite
  • Func?ii mysqlnd_memcache
    • mysqlnd_memcache_get_config — Returns information about the plugin configuration
    • mysqlnd_memcache_set — Associate a MySQL connection with a Memcache connection
  • Change History
    • PECL/mysqlnd_memcache 1.0 series
PECL/mysqlnd_mux 1.0 series
Introducere
MySQL


Introducere

The mysqlnd memcache plugin (mysqlnd_memcache) is an PHP extension for transparently translating SQL into requests for the MySQL InnoDB Memcached Daemon Plugin (server plugin). It includes experimental support for the MySQL Cluster Memcached Daemon. The server plugin provides access to data stored inside MySQL InnoDB (respectively MySQL Cluster NDB) tables using the Memcache protocol. This PHP extension, which supports all PHP MySQL extensions that use mysqlnd, will identify tables exported in this way and will translate specific SELECT queries into Memcache requests.

mysqlnd_memcache data flow

Nota:

This plugin depends on the MySQL InnoDB Memcached Daemon Plugin. It is not provided to be used with a stand-alone Memcached. For a generic query cache using Memcached look at the mysqlnd query cache plugin. For direct Memcache access look at the memcache and memcached extensions.

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 (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.

The mysqlnd_mmemcache operates, for the most part, transparently from a user perspective. The mysqlnd memcache 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.

The MySQL Memcache plugins add key-value style access method for data stored in InnoDB resp. NDB (MySQL Cluster) SQL tables through the Memcache protocol. This type of key-value access if often faster than using SQL.

Key Features

The key features of PECL/mysqlnd_memcache are as follows.

  • Possible performance benefits

    • Client-side: light-weight protocol.

    • Server-side: no SQL parsing, direct access to the storage.

    • Please, run your own benchmarks! Actual performance results are highly dependent on setup and hardware used.

Limitations

The initial version is not binary safe. Due to the way the MySQL Memcache plugins works there are restrictions related to separators.

Prepared statements and asynchronous queries are not supported. Result set meta data support is limited.

The mapping information for tables accessible via Memcache is not cached in the plugin between requests but fetched from the MySQL server each time a MySQL connection is associated with a Memcache connection. See mysqlnd_memcache_set() for details.

On the name

The shortcut mysqlnd_memcache stands for mysqlnd memcache plugin. Memcache refers to support of the MySQL Memcache plugins for InnoDB and NDB (MySQL Cluster). The plugin is not related to the Memcached cache server.

mysqlnd_memcache
Quickstart and Examples
mysqlnd_memcache


Quickstart and Examples

Cuprins

  • Setup
  • Usage

The mysqlnd memcache 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.

Introducere
Setup
mysqlnd_memcache


Setup

The plugin is implemented as a PHP extension. See also the installation instructions to install this extension.

Compile or configure the PHP MySQL extension (API) (mysqli, PDO_MYSQL, mysql). That extension must use the mysqlnd library as because mysqlnd_memcache is a plugin for the mysqlnd library. For additional information, refer to the mysqlnd_memcache installation instructions.

Then, load this extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_memcache.enable.

Example #1 Enabling the plugin (php.ini)

; On Windows the filename is php_mysqnd_memcache.dll
; Load the extension
extension=mysqlnd_memcache.so
; Enable it
mysqlnd_memcache.enable=1

Follow the instructions given in the » MySQL Reference Manual on installing the Memcache plugins for the MySQL server. Activate the plugins and configure Memcache access for SQL tables.

The examples in this quickguide assume that the following table exists, and that Memcache is configured with access to it.

Example #2 SQL table used for the Quickstart

CREATE TABLE test(
  id CHAR(16),
  f1 VARCHAR(255),
  f2 VARCHAR(255),
  f3 VARCHAR(255),
  flags INT NOT NULL,
  cas_column INT,
  expire_time_column INT,
  PRIMARY KEY(id)
  ) ENGINE=InnoDB;

INSERT INTO test (id, f1, f2, f3) VALUES (1, 'Hello', 'World', '!');
INSERT INTO test (id, f1, f2, f3) VALUES (2, 'Lady', 'and', 'the tramp');

INSERT INTO innodb_memcache.containers(
  name, db_schema, db_table, key_columns, value_columns,
  flags, cas_column, expire_time_column, unique_idx_name_on_key)
VALUES (
  'plugin_test', 'test', 'test', 'id', 'f1,f2,f3',
  'flags', 'cas_column', 'expire_time_column', 'PRIMARY KEY');

Quickstart and Examples
Usage
Quickstart and Examples


Usage

After associating a MySQL connection with a Memcache connection using mysqnd_memcache_set() the plugin attempts to transparently replace SQL SELECT statements by a memcache access. For that purpose the plugin monitors all SQL statements executed and tries to match the statement string against MYSQLND_MEMCACHE_DEFAULT_REGEXP. In case of a match, the mysqlnd memcache plugin checks whether the SELECT is accessing only columns of a mapped table and the WHERE clause is limited to a single key lookup.

In case of the example SQL table, the plugin will use the Memcache interface of the MySQL server to fetch results for a SQL query like SELECT f1, f2, f3 WHERE id = n.

Example #1 Basic example.

<?php
$mysqli = new mysqli("host", "user", "passwd", "database");
$memc = new Memcached();
$memc->addServer("host", 11211);
mysqlnd_memcache_set($mysqli, $memc);

/*
   This is a query which queries table test using id as key in the WHERE part
   and is accessing fields f1, f2 and f3. Therefore, mysqlnd_memcache
   will intercept it and route it via memcache.
*/
$result = $mysqli->query("SELECT f1, f2, f3 FROM test WHERE id = 1");
while ($row = $result->fetch_row()) {
    print_r($row);
}

/*
   This is a query which queries table test but using f1 in the WHERE clause.
   Therefore, mysqlnd_memcache can't intercept it. This will be executed
   using the MySQL protocol
*/
$mysqli->query("SELECT id FROM test WHERE f1 = 'Lady'");
while ($row = $result->fetch_row()) {
    print_r($row);
}
?>

Exemplul de mai sus va afi?a:

array(
    [f1] => Hello
    [f2] => World
    [f3] => !
)
array(
    [id] => 2
)

Setup
Instalarea / configurarea
Quickstart and Examples


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
Usage
Necesita?i
mysqlnd_memcache


Necesita?i

PHP: this extension requires PHP 5.4+, version PHP 5.4.4 or never. The required PHP extensions are PCRE (enabled by default), and the memcached extension version 2.0.x.

The mysqlnd_memcache Memcache plugin supports all PHP applications and all available PHP MySQL extensions (mysqli, mysql, PDO_MYSQL). The PHP MySQL extension must be configured with mysqlnd support.

For accessing InnoDB tables, this PHP extension requires MySQL Server 5.6.6 or newer with the InnoDB Memcache Daemon Plugin enabled.

For accessing MySQL Cluster NDB tables, this PHP extension requires MySQL Cluster 7.2 or newer with the NDB Memcache API nodes enabled.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/mysqlnd_memcache

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Mysqlnd_memcache Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
mysqlnd_memcache.enable | 1 | PHP_INI_SYSTEM | Available since 1.0.0

Iata o explica?ie pe scurt a directivelor de configurare.

mysqlnd_memcache.enable integer

Enables or disables the plugin. If disabled, the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.

Nota:

This option is mainly used by developers to build this extension statically into PHP. General users are encouraged to build this extension as a shared object, and to unload it completely when it is not needed.

Instalarea
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

MySQL Memcache Plugin related

MYSQLND_MEMCACHE_DEFAULT_REGEXP (string)
Default regular expression (PCRE style) used for matching SELECT statements that will be mapped into a MySQL Memcache Plugin access point, if possible. It is also possible to use mysqlnd_memcache_set(), but the default approach is using this regular expression for pattern matching.

Assorted

The version number of this plugin can be obtained by using MYSQLND_MEMCACHE_VERSION or MYSQLND_MEMCACHE_VERSION_ID. MYSQLND_MEMCACHE_VERSION is the string representation of the numerical version number MYSQLND_MEMCACHE_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_MEMCACHE_VERSION_ID | 10000

MYSQLND_MEMCACHE_VERSION (string)
Plugin version string, for example, "1.0.0-alpha".
MYSQLND_MEMCACHE_VERSION_ID (integer)
Plugin version number, for example, 10000.

Configura?ia la rulare
Func?ii mysqlnd_memcache
mysqlnd_memcache


Func?ii mysqlnd_memcache

Cuprins

  • mysqlnd_memcache_get_config — Returns information about the plugin configuration
  • mysqlnd_memcache_set — Associate a MySQL connection with a Memcache connection
Constante predefinite
mysqlnd_memcache_get_config
mysqlnd_memcache


Returns information about the plugin configuration

Func?ii mysqlnd_memcache
mysqlnd_memcache_set
Func?ii mysqlnd_memcache
PHP Manual

mysqlnd_memcache_get_config

(PECL mysqlnd_memcache >= 1.0.0)

mysqlnd_memcache_get_config — Returns information about the plugin configuration

Descrierea

array mysqlnd_memcache_get_config ( mixed $connection )

This function returns an array of all mysqlnd_memcache related configuration information that is attached to the MySQL connection. This includes MySQL, the Memcache object provided via mysqlnd_memcache_set(), and the table mapping configuration that was automatically collected from the MySQL Server.

Parametri

connection

A handle to a MySQL Server using one of the MySQL API extensions for PHP, which are PDO_MYSQL, mysqli or ext/mysql.

Valorile întoarse

An array of mysqlnd_memcache configuration information on success, otherwise FALSE.

The returned array has these elements:

mysqlnd_memcache_get_config() array structure
Array Key | Description
memcached | Instance of Memcached associated to this MySQL connection by mysqlnd_memcache_set(). You can use this to change settings of the memcache connection, or directly by querying the server on this connection.
pattern | The PCRE regular expression used to match the SQL query sent to the server. Queries matching this pattern will be further analyzed to decide whether the query can be intercepted and sent via the memcache interface or whether the query is sent using the general MySQL protocol to the server. The pattern is either the default pattern (MYSQLND_MEMCACHE_DEFAULT_REGEXP) or it is set via mysqlnd_memcache_set().
mappings | An associative array with a list of all configured containers as they were discovered by this plugin. The key for these elements is the name of the container in the MySQL configuration. The value is described below. The contents of this field is created by querying the MySQL Server during association to MySQL and a memcache connection using mysqlnd_memcache_set().
mapping_query | An SQL query used during mysqlnd_memcache_set() to identify the available containers and mappings. The result of that query is provided in the mappings element.
Mapping entry structure
Array Key | Description
prefix | A prefix used while accessing data via memcache. With the MySQL InnoDB Memcache Deamon plugin, this usually begins with @@ and ends with a configurable separator. This prefix is placed in front of the key value while using the memcache protocol.
schema_name | Name of the schema (database) which contains the table being accessed.
table_name | Name of the table which contains the data accessible via memcache protocol.
id_field_name | Name of the database field (column) with the id used as key when accessing the table via memcache. Often this is the database field having a primary key.
separator The separator used to split the different field values. This is needed as memcache only provides access to a single value while MySQL can map multiple columns to this value.

Nota:

The separator, which can be set in the MySQL Server configuration, should not be part of any value retrieved via memcache because proper mapping can't be guaranteed.

fields | An array with the name of all fields available for this mapping.

Exemple

Example #1 mysqlnd_memcache_get_config() example

<?php
$mysqli = new mysqli("host", "user", "passwd", "database");
$memc = new Memcached();
$memc->addServer("host", 11211);
mysqlnd_memcache_set($mysqli, $memc);

var_dump(mysqlnd_memcache_get_config($mysqli));
?>

Exemplul de mai sus va afi?a:

array(4) {
  ["memcached"]=>
  object(Memcached)#2 (0) {
  }
  ["pattern"]=>
  string(125) "/^\s*SELECT\s*(.+?)\s*FROM\s*`?([a-z0-9_]+)`?\s*WHERE\s*`?([a-z0-9_]+)`?\s*=\s*(?(?=["'])["']([^"']*)["']|([0-9e\.]*))\s*$/is"
  ["mappings"]=>
  array(1) {
    ["mymem_test"]=>
    array(6) {
      ["prefix"]=>
      string(13) "@@mymem_test."
      ["schema_name"]=>
      string(4) "test"
      ["table_name"]=>
      string(10) "mymem_test"
      ["id_field_name"]=>
      string(2) "id"
      ["separator"]=>
      string(1) "|"
      ["fields"]=>
      array(3) {
        [0]=>
        string(2) "f1"
        [1]=>
        string(2) "f2"
        [2]=>
        string(2) "f3"
      }
    }
  }
  ["mapping_query"]=>
  string(209) "    SELECT c.name,
                          CONCAT('@@', c.name, (SELECT value FROM innodb_memcache.config_options WHERE name = 'table_map_delimiter')) AS key_prefix,
                          c.db_schema,
                          c.db_table,
                          c.key_columns,
                          c.value_columns,
                          (SELECT value FROM innodb_memcache.config_options WHERE name = 'separator') AS sep
                     FROM innodb_memcache.containers c"
}

A se vedea ?i

  • mysqlnd_memcache_set() - Associate a MySQL connection with a Memcache connection

Func?ii mysqlnd_memcache
mysqlnd_memcache_set
Func?ii mysqlnd_memcache


Associate a MySQL connection with a Memcache connection

mysqlnd_memcache_get_config
Change History
Func?ii mysqlnd_memcache
PHP Manual

mysqlnd_memcache_set

(PECL mysqlnd_memcache >= 1.0.0)

mysqlnd_memcache_set — Associate a MySQL connection with a Memcache connection

Descrierea

bool mysqlnd_memcache_set ( mixed $mysql_connection [, Memcached $memcache_connection [, string $pattern [, callback $callback ]]] )

Associate mysql_connection with memcache_connection using pattern as a PCRE regular expression, and callback as a notification callback or to unset the association of mysql_connection.

While associating a MySQL connection with a Memcache connection, this function will query the MySQL Server for its configuration. It will automatically detect whether the server is configured to use the InnoDB Memcache Daemon Plugin or MySQL Cluster NDB Memcache support. It will also query the server to automatically identify exported tables and other configuration options. The results of this automatic configuration can be retrieved using mysqlnd_memcache_get_config().

Parametri

mysql_connection

A handle to a MySQL Server using one of the MySQL API extensions for PHP, which are PDO_MYSQL, mysqli or ext/mysql.

memcache_connection

A Memcached instance with a connection to the MySQL Memcache Daemon plugin. If this parameter is omitted, then mysql_connection will be unassociated from any memcache connection. And if a previous association exists, then it will be replaced.

pattern

A regular expression in Perl Compatible Regular Expression syntax used to identify potential Memcache-queries. The query should have three sub patterns. The first subpattern contains the requested field list, the second the name of the ID column from the query and the third the requested value. If this parameter is omitted or os set to NULL, then a default pattern will be used.

callback

A callback which will be used whenever a query is being sent to MySQL. The callback will receive a single boolean parameter telling if a query was sent via Memcache.

Valorile întoarse

TRUE if the association or disassociation is successful, otherwise FALSE if there is an error.

Exemple

Example #1 mysqlnd_memcache_set() example with var_dump() as a simple debugging callback.

<?php
$mysqli = new mysqli("host", "user", "passwd", "database");
$memc = new Memcached();
$memc->addServer("host", 11211);
mysqlnd_memcache_set($mysqli, $memc, NULL, 'var_dump');

/* This query will be intercepted and executed via Memcache protocol */
echo "Sending query for id via Memcache: ";
$mysqli->query("SELECT f1, f2, f3 FROM test WHERE id = 1");

/* f1 is not configured as valid key field, this won't be sent via Memcache */
echo "Sending query for f1 via Memcache: ";
$mysqli->query("SELECT id FROM test WHERE f1 = 1");

mysqlnd_memcache_set($mysqli);

/* Now the regular MySQL protocol will be used */
echo "var_dump won't be invoked: ";
$mysqli->query("SELECT f1, f2, f3 WHERE id = 1");

?>

Exemplul de mai sus va afi?a:

Sending query for id via Memcache: bool(true)
Sending query for f1 via Memcache: bool(false)
var_dump won't be invoked:

A se vedea ?i

  • mysqlnd_memcache_get_config() - Returns information about the plugin configuration

mysqlnd_memcache_get_config
Change History
Func?ii mysqlnd_memcache


Change History

Cuprins

  • PECL/mysqlnd_memcache 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_memcache_set
PECL/mysqlnd_memcache 1.0 series
mysqlnd_memcache


PECL/mysqlnd_memcache 1.0 series

1.0.0-alpha

  • Release date: TBD
  • Motto/theme: Basic mapping of SQL SELECT to a MySQL Memcache plugin access.

The initial release does map basic SQL SELECT statements to a MySQL Memcache plugin access. This bares potential performance benefits as the direct key-value access to MySQL storage using the Memcache protocol is usually faster than using SQL access.

Change History
OCI8
Change History


Oracle OCI8

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Testing
    • Configura?ia la rulare
  • Constante predefinite
  • Exemple
  • OCI8 Connection Handling and Connection Pooling
  • OCI8 Fast Application Notification (FAN) Support
  • OCI8 and DTrace Dynamic Tracing
  • Supported Datatypes
  • Func?ii OCI8
    • 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 — Cancels reading from cursor
    • 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 a field in the currently fetched row 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 a field's data type name
    • oci_free_descriptor — Frees a descriptor
    • oci_free_statement — Frees all resources associated with statement or cursor
    • oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets
    • 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
  • OCI-Collection — The OCI-Collection class
    • 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 — The OCI-Lob class
    • OCI-Lob::append — Adauga datele dintr-un obiect de tip LOB în alt obiect de tip LOB
    • OCI-Lob::close — Închide un descriptor LOB
    • 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 — Gole?te/scrie zona-tampon LOB pe 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 — Pseudonim pentru 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 — Scrie un LOB temporar
    • OCI-Lob::writeToFile — Pseudonim pentru OCI-Lob::export
  • Pseudonime ?i func?ii OCI8 învechite
    • ocibindbyname — Pseudonim pentru oci_bind_by_name
    • ocicancel — Pseudonim pentru oci_cancel
    • ocicloselob — Pseudonim pentru OCI-Lob::close
    • ocicollappend — Pseudonim pentru OCI-Collection::append
    • ocicollassign — Pseudonim pentru OCI-Collection::assign
    • ocicollassignelem — Pseudonim pentru OCI-Collection::assignElem
    • ocicollgetelem — Pseudonim pentru OCI-Collection::getElem
    • ocicollmax — Pseudonim pentru OCI-Collection::max
    • ocicollsize — Pseudonim pentru OCI-Collection::size
    • ocicolltrim — Pseudonim pentru OCI-Collection::trim
    • ocicolumnisnull — Pseudonim pentru oci_field_is_null
    • ocicolumnname — Pseudonim pentru oci_field_name
    • ocicolumnprecision — Pseudonim pentru oci_field_precision
    • ocicolumnscale — Pseudonim pentru oci_field_scale
    • ocicolumnsize — Pseudonim pentru oci_field_size
    • ocicolumntype — Pseudonim pentru oci_field_type
    • ocicolumntyperaw — Pseudonim pentru oci_field_type_raw
    • ocicommit — Pseudonim pentru oci_commit
    • ocidefinebyname — Pseudonim pentru oci_define_by_name
    • ocierror — Pseudonim pentru oci_error
    • ociexecute — Pseudonim pentru oci_execute
    • ocifetch — Pseudonim pentru oci_fetch
    • ocifetchinto — Varianta învechita a oci_fetch_array, oci_fetch_object, oci_fetch_assoc ?i oci_fetch_row
    • ocifetchstatement — Pseudonim pentru oci_fetch_all
    • ocifreecollection — Pseudonim pentru OCI-Collection::free
    • ocifreecursor — Pseudonim pentru oci_free_statement
    • ocifreedesc — Pseudonim pentru OCI-Lob::free
    • ocifreestatement — Pseudonim pentru oci_free_statement
    • ociinternaldebug — Pseudonim pentru oci_internal_debug
    • ociloadlob — Pseudonim pentru OCI-Lob::load
    • ocilogoff — Pseudonim pentru oci_close
    • ocilogon — Pseudonim pentru oci_connect
    • ocinewcollection — Pseudonim pentru oci_new_collection
    • ocinewcursor — Pseudonim pentru oci_new_cursor
    • ocinewdescriptor — Pseudonim pentru oci_new_descriptor
    • ocinlogon — Pseudonim pentru oci_new_connect
    • ocinumcols — Pseudonim pentru oci_num_fields
    • ociparse — Pseudonim pentru oci_parse
    • ociplogon — Pseudonim pentru oci_pconnect
    • ociresult — Pseudonim pentru oci_result
    • ocirollback — Pseudonim pentru oci_rollback
    • ocirowcount — Pseudonim pentru oci_num_rows
    • ocisavelob — Pseudonim pentru OCI-Lob::save
    • ocisavelobfile — Pseudonim pentru OCI-Lob::import
    • ociserverversion — Pseudonim pentru oci_server_version
    • ocisetprefetch — Pseudonim pentru oci_set_prefetch
    • ocistatementtype — Pseudonim pentru oci_statement_type
    • ociwritelobtofile — Pseudonim pentru OCI-Lob::export
    • ociwritetemporarylob — Pseudonim pentru OCI-Lob::writeTemporary
PECL/mysqlnd_memcache 1.0 series
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

These functions allow you to access Oracle Database 12c, 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
Instalarea / configurarea
OCI8


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Testing
  • Configura?ia la rulare
Introducere
Necesita?i
OCI8


Necesita?i

The OCI8 1.4 extension is included with PHP 5.3, PHP 5.4 and PHP 5.5. It is also available from » PECL. A newer OCI8 2.0 version is available only from » PECL. OCI8 1.4 requires Oracle 12c, 11g, 10g or 9iR2 client libraries and will install on PHP 4.3.9 onwards. OCI8 2.0 requires Oracle 12c, 11g or 10g client libraries and will install on PHP 5.2 onwards.

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.

You must run PHP with the same, or a more recent, version of the Oracle libraries that OCI8 was built with.

On Windows, the php_oci8 DLL needs Oracle 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. The php_oci8_12c DLL from PECL requires Oracle 12cR1 client libraries. With some versions of Instant Client you may additionally need mfc71.dll and msvcr71.dll libraries.

Nota:

If OCI8 uses 9iR2 client libraries, then PHP can connect to Oracle Database 8i, 9iR2, 10g or 11g. If OCI8 uses 10gR2 client libraries, the database can be 9iR2, 10g, 11g or 12c. If OCI8 uses 11g client libraries, the database can be 9iR2, 10g, 11g or 12c. If OCI8 uses 12c client libraries, the database can be 10gR2, 11g or 12c.

Nota:

Full OCI8 feature support is only available when using the most recent versions of the Oracle client libraries and database.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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 must be set before any PHP process starts.

The PHP binary must link 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. PHP applications can connect to other versions of Oracle Database, since Oracle has client-server cross-version compatibility.

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 the free » Oracle Instant Client libraries, 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 first, for example ln -s libclntsh.so.12.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/12.1/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 PHP to include 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 » PECL.

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 when the pecl command is not available, download the PECL OCI8 package, e.g. oci8-1.4.10.tgz.

  • Extract the package:

    tar -zxf oci8-1.4.10.tgz
cd oci8-1.4.10

  • 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

When using Oracle 10gR2 client libraries on Windows, uncomment the php.ini line extension=php_oci8.dll. When using Oracle 11gR2 or later client libraries, uncomment extension=php_oci8_11g.dll or extension=php_oci8.dll. With Oracle 12c libraries use extension=php_oci8_12c.dll or extension=php_oci8_11g.dll or extension=php_oci8.dll. Only one of these DLLs may be enabled at a time. DLLs with higher versions may contain more functionality. Not all DLLs may be available for all versions of PHP. 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.

Nota:

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 available 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.

Nota: 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.

Necesita?i
Testing
Instalarea / configurarea


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 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

Instalarea
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

OCI8 Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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).

Iata o explica?ie pe scurt a directivelor de configurare.

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.

When using Oracle Database 12c, the prefetch value set by PHP can be overridden by Oracle's client oraaccess.xml configuration file. Refer to Oracle documentation for more detail.

Nota: 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().

Nota: 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. If there is more than one PHP process then each must individually be activated in order to trigger expiry of its idle resources. 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.

Nota: 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.

Nota: 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.

Nota: 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.

When using Oracle Database 12c, this value can be overridden and automatically tuned by Oracle's client oraaccess.xml file. Refer to Oracle documentation for more detail.

Testing
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Func?ii ?i Metode OCI8
Constanta | Descriere
OCI_ASSOC | Folosit cu func?ia oci_fetch_all() ?i oci_fetch_array() pentru preluarea de rezultate sub forma unui array asociativ.
OCI_BOTH | Folosit cu func?ia oci_fetch_all() ?i oci_fetch_array() pentru preluarea rezultatelor sub forma unui array cu indec?i atât asociativi cât ?i numerici.
OCI_COMMIT_ON_SUCCESS | Modul de execu?ie a statementului Oracle pentru apelul la oci_execute(). Modificarile vor fi salvate automat daca statementul a fost executat cu succes.
OCI_CRED_EXT | Folosit cu func?ia oci_connect() pentru a folosi metoda de autentificare externa Oracle sau a sistemului de operare. Introdusa în PHP 5.3 ?i PECL OCI8 1.3.4.
OCI_DEFAULT | Vede?i descrierea OCI_NO_AUTO_COMMIT.
OCI_DESCRIBE_ONLY | Modul de execu?ie a statementului Oracle pentru apelul la oci_execute(). Acest mod poate fi folosit daca se dore?te preluarea de meta date, cum ar fi numele coloanelor, dar nu se dore?te preluarea efectiva de rânduri din rezultat.
OCI_EXACT_FETCH | Învechita. Modul de execu?ie a statementului Oracle. Folosit când aplica?ia ?tie câte rânduri va prelua. Acest mod opre?te preluarea automata de rânduri pentru Oracle versiunea 8 sau mai noua. Setul de rezultate este distrus dupa ce rândurile specificate sunt preluate rezultând în mic?orarea resurselor folosite pe server.
OCI_FETCHSTATEMENT_BY_COLUMN | Modul implicit pentru func?ia oci_fetch_all().
OCI_FETCHSTATEMENT_BY_ROW | Modul alternativ pentru func?ia oci_fetch_all().
OCI_LOB_BUFFER_FREE | Folosit cu func?ia OCI-Lob::flush pentru eliberarea zonelor tampon.
OCI_NO_AUTO_COMMIT | Modul de execu?ie a statementului Oracle pentru apelul la oci_execute(). Tranzac?ia nu este executata automat când se folose?te acest mod. Pentru claritate în cod nou, folosi?i aceasta constanta în loc de constanta învechita echivalenta OCI_DEFAULT. Introdusa în PHP 5.3.2 (PECL OCI8 1.4).
OCI_NUM | Folosita cu func?ia oci_fetch_all() ?i oci_fetch_array() pentru preluarea rezultatului ca un array indexat numeric.
OCI_RETURN_LOBS | Folosita cu func?ia oci_fetch_array() pentru preluarea datelor din LOB în locul descriptorului.
OCI_RETURN_NULLS | Folosita cu func?ia oci_fetch_array() pentru a fi întoarse elemente goale în array atunci când valoarea din baza de date este NULL.
OCI_SEEK_CUR | Folosita cu func?ia OCI-Lob::seek pentru a cauta pozi?ia.
OCI_SEEK_END | Folosita cu func?ia OCI-Lob::seek pentru a cauta pozi?ia.
OCI_SEEK_SET | Folosita cu func?ia OCI-Lob::seek pentru a cauta pozi?ia.
OCI_SYSDATE | Învechita.
OCI_SYSDBA | Folosita cu func?ia oci_connect() pentru conectarea cu privilegii SYSDBA. Op?iunea din php.ini oci8.privileged_connect trebuie activata pentru a se putea folosi aceasta constanta.
OCI_SYSOPER | Folosita cu func?ia oci_connect() pentru a se conecta cu privilegii SYSOPER. Op?iunea din php.ini oci8.privileged_connect trebuie activata pentru a se putea folosi aceasta constanta.
OCI_TEMP_BLOB | Folosita cu func?ia OCI-Lob::writeTemporary pentru a indica crearea unui obiect BLOB temporar.
OCI_TEMP_CLOB | Folosita cu OCI-Lob::writeTemporary pentru a indica crearea unui obiect CLOB temporar.
Mapari OCI8 ?i definire tipuri
Constanta | Descriere
OCI_B_BFILE | Folosita cu func?ia oci_bind_by_name() la maparea cu obiecte BFILE.
OCI_B_BIN | Folosita cu func?ia oci_bind_by_name() la maparea cu valori RAW.
OCI_B_BLOB | Folosita cu func?ia oci_bind_by_name() la maparea de obiecte BLOB.
OCI_B_BOL | Folosita cu func?ia oci_bind_by_name() pentru a mapa o variabila PL/SQL BOOLEAN.
OCI_B_CFILEE | Folosita cu func?ia oci_bind_by_name() la maparea cu obiecte CFILE.
OCI_B_CLOB | Folosita cu func?ia oci_bind_by_name() la maparea cu obiecte CLOB.
OCI_B_CURSOR | Folosita cu func?ia oci_bind_by_name() la maparea cursorilor, construi?i în prealabil cu oci_new_descriptor().
OCI_B_INT | Folosita cu func?ia oci_bind_array_by_name() la maparea array-urilor de tip INTEGER.
OCI_B_NTY | Folosita cu func?ia oci_bind_by_name() la maparea tipurilor de date numite. Nota: în PHP < 5.0 se numea OCI_B_SQLT_NTY.
OCI_B_NUM | Folosita cu func?ia oci_bind_array_by_name() la maparea array-urilor de tip NUMBER.
OCI_B_ROWID | Folosita cu func?ia oci_bind_by_name() la maparea ROWID.
SQLT_AFC | Folosita cu func?ia oci_bind_array_by_name() la maparea array-urilor de tip CHAR.
SQLT_AVC | Folosita cu func?ia oci_bind_array_by_name() la maparea array-urilor de tip VARCHAR2.
SQLT_BDOUBLE | Nu este disponibila.
SQLT_BFILEE | La fel ca OCI_B_BFILE.
SQLT_BFLOAT | Nu este disponibila.
SQLT_BIN | La fel ca OCI_B_BIN.
SQLT_BLOB | La fel ca OCI_B_BLOB.
SQLT_BOL | La fel ca OCI_B_BOL.
SQLT_CFILEE | La fel ca OCI_B_CFILEE.
SQLT_CHR | Folosita cu func?ia oci_bind_array_by_name() la maparea array-urilor de tip VARCHAR2. De asemenea folosita ?i cu func?ia oci_bind_by_name().
SQLT_CLOB | La fel ca OCI_B_CLOB.
SQLT_FLT | La fel ca oci_bind_array_by_name() la maparea array-urilor de tip FLOAT.
SQLT_INT | La fel ca OCI_B_INT.
SQLT_LBI | Folosita cu func?ia oci_bind_by_name() la maparea cu valori LONG RAW.
SQLT_LNG | Folosita cu func?ia oci_bind_by_name() la maparea cu valori LONG.
SQLT_LVC | Folosita cu func?ia oci_bind_array_by_name() la maparea array-urilor cu valori LONG VARCHAR.
SQLT_NTY | La fel ca OCI_B_NTY.
SQLT_NUM | La fel ca OCI_B_NUM.
SQLT_ODT | Folosita cu func?ia oci_bind_array_by_name() la maparea array-urilor cu valori LONG.
SQLT_RDD | La fel ca OCI_B_ROWID.
SQLT_RSET | La fel ca OCI_B_CURSOR.
SQLT_STR | Folosita cu func?ia oci_bind_array_by_name() la maparea array-urilor cu valori STRING.
SQLT_UIN | Nu este disponibila.
SQLT_VCS | Folosita cu func?ia oci_bind_array_by_name() la maparea array-urilor cu valori VARCHAR.
Tipuri de descriptor OCI8
Constanta | Descriere
OCI_DTYPE_FILE | Aceasta op?iune semnalizeaza func?iei oci_new_descriptor() sa ini?ializeze un descriptor nou de tip FILE.
OCI_DTYPE_LOB | Aceasta op?iune semnalizeaza func?iei oci_new_descriptor() sa ini?ializeze un descriptor nou de tip LOB..
OCI_DTYPE_ROWID | Aceasta op?iune semnalizeaza func?iei oci_new_descriptor() sa ini?ializeze un descriptor nou de tip ROWID.
OCI_D_FILE | La fel ca OCI_DTYPE_FILE.
OCI_D_LOB | La fel ca OCI_DTYPE_LOB.
OCI_D_ROWID | La fel ca OCI_DTYPE_ROWID.
Configura?ia la rulare
Exemple
OCI8


Exemple

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.

Example #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);

?>

Example #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);

?>

Example #3 Binding in the WHERE clause of a query

This shows a single scalar bind.

<?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 department_id = :didbv ORDER BY last_name';
$stid = oci_parse($conn, $sql);
$didbv = 60;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
    echo $row['LAST_NAME'] ."<br>\n";
}

// Output is
//    Austin
//    Ernst
//    Hunold
//    Lorentz
//    Pataballa

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 Inserting and fetching a CLOB

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+OCI_RETURN_LOBS)) {
    print '<tr><td>'.$row['MYCLOB'].'</td></tr>';
    // In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
    unset($row);
}
print '</table>';

?>

Example #5 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);

?>

Example #6 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);

?>

Example #7 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);

?>
Constante predefinite
OCI8 Connection Handling and Connection Pooling
OCI8


OCI8 Connection Handling and Connection Pooling

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 Database Resident Connection Pooling (in Oracle Database 11g or later), 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 FCGI, 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 from 5.3 (PECL OCI8 1.3) supports Oracle 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 or greater.

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 (or later) extension and Oracle 11g (or later) 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 (or later) database.

Nota:

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.

From OCI8 1.3, persistent connections can 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 FCGI 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.

Exemple
OCI8 Fast Application Notification (FAN) Support
OCI8


OCI8 Fast Application Notification (FAN) Support

FAN support gives fast connection failover, an Oracle Database 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 later.

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 OCI8, build PHP OCI8 with Oracle 10gR2 or later 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 Oracle Database 10gR2 or later.

OCI8 Connection Handling and Connection Pooling
OCI8 and DTrace Dynamic Tracing
OCI8


OCI8 and DTrace Dynamic Tracing

OCI8 2.0 introduced static DTrace probes that can be used on operating systems that support DTrace. See DTrace Dynamic Tracing for an overview of PHP and DTrace.

Installing OCI8 with DTrace Support

To enable DTrace support in PHP OCI8, build OCI8 as a shared extension after setting PHP_DTRACE.

$ export PHP_DTRACE=yes
$ pecl install oci8

Edit php.ini, set extension_dir to the directory with the created oci8.so and also enable the extension by adding:

extension=oci8.so

If you install PHP OCI8 2.0 from PECL using phpize and configure (instead of pecl), you will still need to set PHP_DTRACE=yes. This is because the --enable-dtrace option will be ignored by the limited configure script of a PECL bundle.

See Installation of PECL extensions for general PECL installation instructions.

DTrace Static Probes in PHP OCI8

The following static probes are available in PHP OCI8
Probe Name | Probe Description | Probe Arguments
oci8-connect-entry | Initiated by oci_connect(), oci_pconnect() and oci_new_connect(). Fires before database connection is established. | char *username, char *dbname, char *charset, long session_mode, int persistent, int exclusive
oci8-connect-return | Fires at the end of connection. | void *connection
oci8-check-connection | Fires if an Oracle error might have caused the connection to become invalid. | void *connection, char *client_id, int is_open, long errcode, unsigned long server_status
oci8-sqltext | Fires when oci_parse() is executed. | void *connection, char *client_id, void *statement, char *sql
oci8-connection-close | Fires when the connection to the database is completely destroyed. | void *connection
oci8-error | Fires if an Oracle error occurs. | int status, long errcode
oci8-execute-mode | Fires at oci_execute() to show the execution mode. | void *connection, char *client_id, void *statement, unsigned int mode

These probes are useful for tracing OCI8 scripts.

The connection and statement are the pointers to internal structures used for tracking PHP connections and executed statements.

The client_id is the value set by oci_set_client_identifier().

Core PHP also has static probes. See DTrace Static Probes in Core PHP.

Internal Debugging DTrace Probes in OCI8
Probe Name
oci8-connect-expiry
oci8-connect-lookup
oci8-connect-p-dtor-close
oci8-connect-p-dtor-release
oci8-connect-type
oci8-sesspool-create
oci8-sesspool-stats
oci8-sesspool-type

These probes are useful for OCI8 maintainers. Refer to the OCI8 source code for arguments and to see when the will fire.

Listing DTrace Static Probes in PHP OCI8

To list available probes, start a PHP process and then run:

# dtrace -l

The output will be similar to:

   ID   PROVIDER            MODULE                          FUNCTION NAME
   [ . . . ]
   17 phpoci22116           oci8.so   php_oci_dtrace_check_connection oci8-check-connection
   18 phpoci22116           oci8.so                php_oci_do_connect oci8-connect-entry
   19 phpoci22116           oci8.so         php_oci_persistent_helper oci8-connect-expiry
   20 phpoci22116           oci8.so             php_oci_do_connect_ex oci8-connect-lookup
   21 phpoci22116           oci8.so  php_oci_pconnection_list_np_dtor oci8-connect-p-dtor-close
   22 phpoci22116           oci8.so  php_oci_pconnection_list_np_dtor oci8-connect-p-dtor-release
   23 phpoci22116           oci8.so                php_oci_do_connect oci8-connect-return
   24 phpoci22116           oci8.so             php_oci_do_connect_ex oci8-connect-type
   25 phpoci22116           oci8.so          php_oci_connection_close oci8-connection-close
   26 phpoci22116           oci8.so                     php_oci_error oci8-error
   27 phpoci22116           oci8.so         php_oci_statement_execute oci8-execute-mode
   28 phpoci22116           oci8.so              php_oci_create_spool oci8-sesspool-create
   29 phpoci22116           oci8.so            php_oci_create_session oci8-sesspool-stats
   30 phpoci22116           oci8.so            php_oci_create_session oci8-sesspool-type
   31 phpoci22116           oci8.so          php_oci_statement_create oci8-sqltext

The Provider column values consist of phpoci and the process id of the currently running PHP process.

The Function column refers to PHP's internal C implementation function names where each provider is located.

If a PHP process is not running, then no PHP probes will be shown.

DTrace with PHP OCI8 Example

This example shows the basics of the DTrace D scripting language.

Example #1 user_oci8_probes.d for tracing all user-level PHP OCI8 Static Probes with DTrace

#!/usr/sbin/dtrace -Zs

#pragma D option quiet

php*:::oci8-connect-entry
{
    printf("%lld: PHP connect-entry\n", walltimestamp);
    printf("  credentials=\"%s@%s\"\n", arg0 ? copyinstr(arg0) : "", arg1 ? copyinstr(arg1) : "");
    printf("  charset=\"%s\"\n", arg2 ? copyinstr(arg2) : "");
    printf("  session_mode=%ld\n", (long)arg3);
    printf("  persistent=%d\n", (int)arg4);
    printf("  exclusive=%d\n", (int)arg5);
}

php*:::oci8-connect-return
{
    printf("%lld: PHP oci8-connect-return\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
}

php*:::oci8-connection-close
{
    printf("%lld: PHP oci8-connect-close\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
}

php*:::oci8-error
{
    printf("%lld: PHP oci8-error\n", walltimestamp);
    printf("  status=%d\n", (int)arg0);
    printf("  errcode=%ld\n", (long)arg1);
}

php*:::oci8-check-connection
{
    printf("%lld: PHP oci8-check-connection\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
    printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
    printf("  is_open=%d\n", arg2);
    printf("  errcode=%ld\n", (long)arg3);
    printf("  server_status=%lu\n", (unsigned long)arg4);
}

php*:::oci8-sqltext
{
    printf("%lld: PHP oci8-sqltext\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
    printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
    printf("  statement=0x%p\n", (void *)arg2);
    printf("  sql=\"%s\"\n", arg3 ? copyinstr(arg3) : "");
}

php*:::oci8-execute-mode
{
    printf("%lld: PHP oci8-execute-mode\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
    printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
    printf("  statement=0x%p\n", (void *)arg2);
    printf("  mode=0x%x\n", arg3);
}

This script uses the -Z option to dtrace, allowing it to be run when there is no PHP process executing. If this option were omitted the script would immediately terminate when no PHP executable was running because it knows none of the probes to be monitored are in existence.

On multi-CPU machines the probe ordering might not appear to be sequential. This depends on which CPU was processing the probes, and how threads migrate across CPUs. Displaying probe time stamps helps reduce confusion.

The script traces all user-level PHP OCI8 static probe points throughout the duration of a running PHP script. Run the D script:

# ./user_oci8_probes.d

Run a PHP script or application. The monitoring D script will output each probe's arguments as it fires. For example, a simple PHP script that queries a table might produce the following trace output:

1381794982092854582: PHP connect-entry
  credentials="hr@localhost/pdborcl"
  charset=""
  session_mode=0
  persistent=0
  exclusive=0
1381794982183158766: PHP oci8-connect-return
  connection=0x7f4a7907bfb8
1381794982183594576: PHP oci8-sqltext
  connection=0x7f4a7907bfb8
  client_id="Chris"
  statement=0x7f4a7907c2a0
  sql="select * from employees"
1381794982183783706: PHP oci8-execute-mode
  connection=0x7f4a7907bfb8
  client_id="Chris"
  statement=0x7f4a7907c2a0
  mode=0x20
1381794982444344390: PHP oci8-connect-close
  connection=0x7f4a7907bfb8

When monitoring is complete, the D script can be terminated with a ^C.

See Also

  • DTrace Dynamic Tracing
OCI8 Fast Application Notification (FAN) Support
Supported Datatypes
OCI8


Supported Datatypes

The driver supports the following types when binding parameters using the 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_BOL | Bind the PHP parameter to a PL/SQL BOOLEAN
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
OCI8 and DTrace Dynamic Tracing
Func?ii OCI8
OCI8


Func?ii OCI8

Cuprins

  • 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 — Cancels reading from cursor
  • 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 a field in the currently fetched row 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 a field's data type name
  • oci_free_descriptor — Frees a descriptor
  • oci_free_statement — Frees all resources associated with statement or cursor
  • oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets
  • 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_bind_array_by_name
OCI8


Binds a PHP array to an Oracle PL/SQL array parameter

Func?ii OCI8
oci_bind_by_name
Func?ii OCI8
PHP Manual

oci_bind_array_by_name

(PHP 5 >= 5.1.2, PHP 7, PECL OCI8 >= 1.2.0)

oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 oci_bind_array_by_name() example

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$create = "CREATE TABLE bind_example(name VARCHAR(20))";
$stid = oci_parse($conn, $create);
oci_execute($stid);

$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;";
$stid = oci_parse($conn, $create_pkg);
oci_execute($stid);

$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
    -- Bulk Insert
    FORALL i IN INDICES OF c1
      INSERT INTO bind_example VALUES (c1(i));

    -- Fetch and reverse
    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;";
$stid = oci_parse($conn, $create_pkg_body);
oci_execute($stid);

$stid = oci_parse($conn, "BEGIN arraybindpkg1.iobind(:c1); END;");
$array = array("one", "two", "three", "four", "five");
oci_bind_array_by_name($stid, ":c1", $array, 5, -1, SQLT_CHR);
oci_execute($stid);

var_dump($array);

?>

Func?ii OCI8
oci_bind_by_name
Func?ii OCI8


Binds a PHP variable to an Oracle placeholder

oci_bind_array_by_name
oci_cancel
Func?ii OCI8
PHP Manual

oci_bind_by_name

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_bind_by_name — Binds a PHP variable to an Oracle placeholder

Descrierea

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.

Parametri

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();

  • SQLT_BOL or OCI_B_BOL - for PL/SQL BOOLEANs (Requires OCI8 2.0.7 and Oracle Database 12c)

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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     '

?>

Example #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);

?>

Example #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);

?>

Example #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 department_id = :didbv ORDER BY last_name';
$stid = oci_parse($conn, $sql);
$didbv = 60;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
    echo $row['LAST_NAME'] ."<br>\n";
}

// Output is
//    Austin
//    Ernst
//    Hunold
//    Lorentz
//    Pataballa

oci_free_statement($stid);
oci_close($conn);

?>

Example #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);

?>

Example #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.

Example #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);

?>

Example #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);

?>

Example #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);

?>

Example #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);

?>

Example #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);

?>

Example #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+OCI_RETURN_LOBS)) {
    print '<tr><td>'.$row['MYCLOB'].'</td></tr>';
    // In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
    unset($row);
}
print '</table>';

?>

Example #13 Binding a PL/SQL BOOLEAN

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$plsql =
  "begin
    :output1 := true;
    :output2 := false;
   end;";

$s = oci_parse($c, $plsql);
oci_bind_by_name($s, ':output1', $output1, -1, OCI_B_BOL);
oci_bind_by_name($s, ':output2', $output2, -1, OCI_B_BOL);
oci_execute($s);
var_dump($output1);  // true
var_dump($output2);  // false

?>

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Avertizare

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.

Nota:

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.

Nota:

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]);
}
?>

A se vedea ?i

  • 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
Func?ii OCI8


Cancels reading from cursor

oci_bind_by_name
oci_client_version
Func?ii OCI8
PHP Manual

oci_cancel

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_cancel — Cancels reading from cursor

Descrierea

bool oci_cancel ( resource $statement )

Invalidates a cursor, freeing all associated resources and cancels the ability to read from it.

Parametri

statement

An OCI statement.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

oci_bind_by_name
oci_client_version
Func?ii OCI8


Returns the Oracle client library version

oci_cancel
oci_close
Func?ii OCI8
PHP Manual

oci_client_version

(PHP 5.3.7, PHP 7, PECL OCI8 >= 1.4.6)

oci_client_version — Returns the Oracle client library version

Descrierea

string oci_client_version ( void )

Returns a string containing the version number of the Oracle C client library that PHP is linked with.

Parametri

None

Valorile întoarse

Returns the version number as a string.

Exemple

Example #1 oci_client_version() example

<?php
    echo "Client Version: " . oci_client_version(); // Client version: 11.2.0.2
?>

Note

Nota:

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.

A se vedea ?i

  • oci_server_version() - Returns the Oracle Database version

oci_cancel
oci_close
Func?ii OCI8


Closes an Oracle connection

oci_client_version
oci_commit
Func?ii OCI8
PHP Manual

oci_close

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_close — Closes an Oracle connection

Descrierea

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.

Parametri

connection

An Oracle connection identifier returned by oci_connect(), oci_pconnect(), or oci_new_connect().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Example #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 longer 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);

?>

Example #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

?>

Example #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"

?>

Note

Nota:

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.

Nota:

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.

Nota:

The oci_close() function does not close the underlying database connections created with oci_pconnect().

A se vedea ?i

  • oci_connect() - Connect to an Oracle database
  • oci_free_statement() - Frees all resources associated with statement or cursor

oci_client_version
oci_commit
Func?ii OCI8


Commits the outstanding database transaction

oci_close
oci_connect
Func?ii OCI8
PHP Manual

oci_commit

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_commit — Commits the outstanding database transaction

Descrierea

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.

Parametri

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
}

?>

Note

Nota:

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.

A se vedea ?i

  • oci_execute() - Executes a statement
  • oci_rollback() - Rolls back the outstanding database transaction

oci_close
oci_connect
Func?ii OCI8


Connect to an Oracle database

oci_commit
oci_define_by_name
Func?ii OCI8
PHP Manual

oci_connect

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_connect — Connect to an Oracle database

Descrierea

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.

Parametri

username

The Oracle user name.

password

The password for username.

connection_string

Con?ine instan?a Oracle la care se efectueaza conectarea. Poate fi un » ?ir Easy Connect, sau o Denumire de conexiune din fi?ierul tnsnames.ora, sau denumirea unei instan?e locale Oracle.

Daca nu este specificat, PHP utilizeaza variabile de mediu, cum ar fi TWO_TASK (în Linux) sau LOCAL (în Windows) ?i ORACLE_SID pentru a determina instan?a Oracle la care trebuie efectuata conexiunea.

Pentru a utiliza metoda Easy Connect, PHP trebuie sa fie legat cu bibliotecile-client Oracle 10g sau ulterioare. ?irul Easy Connect pentru Oracle 10g este de forma: [//]host_name[:port][/service_name]. Pentru Oracle 11g sintaxa este: [//]host_name[:port][/service_name][:server_type][/instance_name]. Denumirile serviciilor pot fi gasite rulând utilitara Oracle lsnrctl status pe ma?ina unde ruleaza serverul de baze de date.

Fi?ierul tnsnames.ora poate fi în calea de cautare Oracle Net, care include $ORACLE_HOME/network/admin ?i /etc. Ca alternativa, poate fi stabilit TNS_ADMIN astfel încât $TNS_ADMIN/tnsnames.ora este citit. Asigura?i-va ca serviciul web poseda dreptul de citire a acestui fi?ier.

character_set

Determina setul de caractere utilizat de bibliotecile-client Oracle. Setul de caractere nu trebuie în mod obligatoriu sa se potriveasca cu setul de caractere al bazei de date. Daca nu se potrive?te, Oracle va face tot posibilul sa converteasca datele din ?i în setul de caractere al bazei de date. În dependen?a de seturile de caractere aceasta poate sa duca la rezultate incorecte. Convertirea de asemenea impune un timp marit de prelucrare.

Daca nu este specificat, bibliotecile-client Oracle determina setul de caractere din variabila de mediu NLS_LANG.

Transmiterea acestui parametru poate reduce timpul necesar pentru conectare.

session_mode

Acest parametru este disponibil începând cu versiunea PHP 5 (PECL OCI8 1.1) ?i accepta urmatoarele valori: OCI_DEFAULT, OCI_SYSOPER ?i OCI_SYSDBA. Daca sunt specificate OCI_SYSOPER sau OCI_SYSDBA, aceasta func?ie va încerca sa stabileasca o conexiune privilegiata utilizând creden?iale externe. Conexiunile privilegiate sunt dezactivate implicit. Pentru a le activa trebuie sa stabili?i oci8.privileged_connect în On.

PHP 5.3 (PECL OCI8 1.3.4) a introdus valoarea modului OCI_CRED_EXT. Aceasta indica Oracle sa utilizeze autentificare Externa sau la nivel de S.O., ceea ce trebuie configurat în baza de date. Fanionul OCI_CRED_EXT poate fi utilizat doar cu numele utilizatorului "/" ?i o parola vida. oci8.privileged_connect poate fi On sau Off.

OCI_CRED_EXT poate fi combinat cu modul OCI_SYSOPER sau OCI_SYSDBA.

OCI_CRED_EXT nu este sus?inut pe Windows din motive de securitate.

Valorile întoarse

Returns a connection identifier or FALSE on error.

Exemple

Example #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";

?>

Example #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";

?>

Example #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";

?>

Example #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

?>

Note

Nota:

An incorrectly installed or configured OCI8 extension will often manifest itself as a connection problem or error. See Installing/Configuring for troubleshooting information.

A se vedea ?i

  • 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
Func?ii OCI8


Associates a PHP variable with a column for query fetches

oci_connect
oci_error
Func?ii OCI8
PHP Manual

oci_define_by_name

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_define_by_name — Associates a PHP variable with a column for query fetches

Descrierea

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().

Parametri

statement

Un identificator valid de instruc?iune OCI8 creat cu oci_parse() ?i executat de oci_execute(), sau un identificator de instruc?iune REF CURSOR.

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Example #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);

?>

Example #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);

?>

Example #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);

?>

A se vedea ?i

  • 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
Func?ii OCI8


Returns the last error found

oci_define_by_name
oci_execute
Func?ii OCI8
PHP Manual

oci_error

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_error — Returns the last error found

Descrierea

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.

Parametri

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.

Valorile întoarse

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 | Descriere
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.

Exemple

Example #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);
}
?>

Example #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);
}
?>

Example #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";
}
?>

oci_define_by_name
oci_execute
Func?ii OCI8


Executes a statement

oci_error
oci_fetch_all
Func?ii OCI8
PHP Manual

oci_execute

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_execute — Executes a statement

Descrierea

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().

Parametri

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_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 equivalent to OCI_NO_AUTO_COMMIT.

Using OCI_NO_AUTO_COMMIT mode starts or continues 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";

?>

Example #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

?>

Example #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

?>

Example #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

?>

Example #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";
}

?>

Note

Nota:

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.

Nota:

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.

A se vedea ?i

  • oci_parse() - Prepares an Oracle statement for execution

oci_error
oci_fetch_all
Func?ii OCI8


Fetches multiple rows from a query into a two-dimensional array

oci_execute
oci_fetch_array
Func?ii OCI8
PHP Manual

oci_fetch_all

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array

Descrierea

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().

Parametri

statement

Un identificator valid de instruc?iune OCI8 creat cu oci_parse() ?i executat de oci_execute(), sau un identificator de instruc?iune REF CURSOR.

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 either by column heading or numerically. Only one index mode will be returned.

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.

Valorile întoarse

Returns the number of rows in output, which may be 0 or more, sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Example #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);

?>

Example #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);

?>

Note

Nota:

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.

Nota:

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.

Nota:

În cazul interpelarilor ce întorc un numar mare de înregistrari, performan?a poate fi îmbunata?ita substan?ial marind valoarea oci8.default_prefetch sau utilizând oci_set_prefetch().

Nota:

Will not return rows from Oracle Database 12c Implicit Result Sets. Use oci_fetch_array() instead.

A se vedea ?i

  • 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
Func?ii OCI8


Returns the next row from a query as an associative or numeric array

oci_fetch_all
oci_fetch_assoc
Func?ii OCI8
PHP Manual

oci_fetch_array

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_fetch_array — Returns the next row from a query as an associative or numeric array

Descrierea

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.

If statement corresponds to a PL/SQL block returning Oracle Database 12c Implicit Result Sets, then rows from all sets are consecutively fetched. If statement is returned by oci_get_implicit_resultset(), then only the subset of rows for one child query are returned.

Pentru detalii despre coresponden?ele transformarilor tipurilor de date efectuate de extensia OCI8, accesa?i tipurile de date sus?inute de driver

Parametri

statement

Un identificator valid de instruc?iune OCI8 creat cu oci_parse() ?i executat de oci_execute(), sau un identificator de instruc?iune REF CURSOR.

Can also be a statement identifier returned by oci_get_implicit_resultset().

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.

Valorile întoarse

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.

The table name is not included in the array index. If your query contains two different columns with the same name, use OCI_NUM or add a column alias to the query to ensure name uniqueness, see example #7. Otherwise only one column will be returned via PHP.

Exemple

Example #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)) != false) {
    // 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);

?>

Example #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)) != false) {
    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);

?>

Example #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)) != false) {
    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);

?>

Example #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)) != false) { // 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)) != false) { // Fetch NULLs
    var_dump($row);
}

/*
The above code prints:
  array(2) {
    [1]=>
    string(1) "1"
    ["NULL"]=>
    NULL
  }
*/

?>

Example #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)) != false) {
    echo $row['ID'] . "<br>\n";
    echo $row['DESCRIPTION'] . "<br>\n"; // this contains all of DESCRIPTION
    // In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
    unset($row);
}

// Output is:
//    1
//    A very long string

oci_free_statement($stid);
oci_close($conn);

?>

Example #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);

?>

Example #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);

?>

Example #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);

?>

Example #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)) != false) {
    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);

?>

Example #10 Pagination with oci_fetch_array() using 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);
}

// Find the version of the database
preg_match('/Release ([0-9]+)\./', oci_server_version($conn), $matches);
$oracleversion = $matches[1];

// This is the query you want to "page" through
$sql = 'SELECT city, postal_code FROM locations ORDER BY city';

if ($oracleversion >= 12) {
    // Make use of Oracle 12c OFFSET / FETCH NEXT syntax
    $sql = $sql . ' OFFSET :offset ROWS FETCH NEXT :numrows ROWS ONLY';
} else {
    // Older Oracle versions need a nested query selecting a subset
    // from $sql.  Or, if the SQL statement is known at development
    // time, consider using a row_number() function instead of this
    // nested solution.  In production environments, be careful to
    // avoid SQL Injection issues with concatenation.
    $sql = "SELECT * FROM (SELECT a.*, ROWNUM AS my_rnum
                           FROM ($sql) a
                           WHERE ROWNUM <= :offset + :numrows)
            WHERE my_rnum > :offset";
}

$offset  = 0;  // skip this many rows
$numrows = 5;  // return 5 rows
$stid = oci_parse($conn, $sql);
oci_bind_by_name($stid, ':numrows', $numrows);
oci_bind_by_name($stid, ':offset', $offset);
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) != false) {
    echo $row['CITY'] . " " . $row['POSTAL_CODE'] . "<br>\n";
}

// Output is:
//    Beijing 190518
//    Bern 3095
//    Bombay 490231
//    Geneva 1730
//    Hiroshima 6823

oci_free_statement($stid);
oci_close($conn);

?>

Example #11 oci_fetch_array() with Oracle Database 12c Implicit Result Sets

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Requires OCI8 2.0 and Oracle Database 12c
// Also see oci_get_implicit_resultset()
$sql = 'DECLARE
           c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
           OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

// Note: oci_fetch_all and oci_fetch() cannot be used in this manner
echo "<table>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "  <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

// Output is:
//    Beijing 190518
//    Bern    3095
//    Bombay  490231
//    CN
//    CH
//    IN

oci_free_statement($stid);
oci_close($conn);

?>

Note

Nota:

Associative array indices need to be in uppercase for standard Oracle columns that were created with case insensitive names.

Nota:

În cazul interpelarilor ce întorc un numar mare de înregistrari, performan?a poate fi îmbunata?ita substan?ial marind valoarea oci8.default_prefetch sau utilizând oci_set_prefetch().

Nota:

The function oci_fetch_array() is insignificantly slower than oci_fetch_assoc() or oci_fetch_row(), but is more flexible.

A se vedea ?i

  • 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
Func?ii OCI8


Returns the next row from a query as an associative array

oci_fetch_array
oci_fetch_object
Func?ii OCI8
PHP Manual

oci_fetch_assoc

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_fetch_assoc — Returns the next row from a query as an associative array

Descrierea

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.

Parametri

statement

Un identificator valid de instruc?iune OCI8 creat cu oci_parse() ?i executat de oci_execute(), sau un identificator de instruc?iune REF CURSOR.

Valorile întoarse

Returns an associative array. If there are no more rows in the statement then FALSE is returned.

Exemple

Example #1 oci_fetch_assoc() 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 department_id, department_name FROM departments');
oci_execute($stid);

while (($row = oci_fetch_assoc($stid)) != false) {
    echo $row['DEPARTMENT_ID'] . " " . $row['DEPARTMENT_NAME'] . "<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Note

Nota:

See oci_fetch_array() for more examples of fetching rows.

A se vedea ?i

  • 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
Func?ii OCI8


Returns the next row from a query as an object

oci_fetch_assoc
oci_fetch_row
Func?ii OCI8
PHP Manual

oci_fetch_object

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_fetch_object — Returns the next row from a query as an object

Descrierea

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.

Pentru detalii despre coresponden?ele transformarilor tipurilor de date efectuate de extensia OCI8, accesa?i tipurile de date sus?inute de driver

Parametri

statement

Un identificator valid de instruc?iune OCI8 creat cu oci_parse() ?i executat de oci_execute(), sau un identificator de instruc?iune REF CURSOR.

Valorile întoarse

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 for attribute access.

Attribute values will be NULL for any NULL data fields.

Exemple

Example #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)) != false) {
    // 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);

?>

Example #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)) != false) {
    // 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);

?>

Example #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)) != false) {
    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);

?>

A se vedea ?i

  • 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
Func?ii OCI8


Returns the next row from a query as a numeric array

oci_fetch_object
oci_fetch
Func?ii OCI8
PHP Manual

oci_fetch_row

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_fetch_row — Returns the next row from a query as a numeric array

Descrierea

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.

Parametri

statement

Un identificator valid de instruc?iune OCI8 creat cu oci_parse() ?i executat de oci_execute(), sau un identificator de instruc?iune REF CURSOR.

Valorile întoarse

Returns a numerically indexed array. If there are no more rows in the statement then FALSE is returned.

Exemple

Example #1 oci_fetch_row() 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 department_id, department_name FROM departments');
oci_execute($stid);

while (($row = oci_fetch_row($stid)) != false) {
    echo $row[0] . " " . $row[1] . "<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Note

Nota:

See oci_fetch_array() for more examples of fetching rows.

A se vedea ?i

  • 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
Func?ii OCI8


Fetches the next row from a query into internal buffers

oci_fetch_row
oci_field_is_null
Func?ii OCI8
PHP Manual

oci_fetch

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_fetch — Fetches the next row from a query into internal buffers

Descrierea

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.

Parametri

statement

Un identificator valid de instruc?iune OCI8 creat cu oci_parse() ?i executat de oci_execute(), sau un identificator de instruc?iune REF CURSOR.

Valorile întoarse

Returns TRUE on success or FALSE if there are no more rows in the statement.

Exemple

Example #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);

?>

Example #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);

?>

Note

Nota:

Will not return rows from Oracle Database 12c Implicit Result Sets. Use oci_fetch_array() instead.

A se vedea ?i

  • 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
Func?ii OCI8


Checks if a field in the currently fetched row is NULL

oci_fetch
oci_field_name
Func?ii OCI8
PHP Manual

oci_field_is_null

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_is_null — Checks if a field in the currently fetched row is NULL

Descrierea

bool oci_field_is_null ( resource $statement , mixed $field )

Checks if the given field from the current row of statement is NULL.

Parametri

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Valorile întoarse

Returns TRUE if field is NULL, FALSE otherwise.

Exemple

Example #1 oci_field_name() example

<?php

// Create the table with:
//   CREATE TABLE mytab (c1 NUMBER);
//   INSERT INTO mytab VALUES (1);
//   INSERT INTO mytab VALUES (NULL);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_RETURN_NULLS)) != false) {
    $ncols = oci_num_fields($stid);
    for ($col = 1; $col <= $ncols; $col++) {
        var_dump(oci_field_is_null($stid, $col));
    }
}

// Outputs:
//    bool(false)
//    bool(true)

oci_free_statement($stid);
oci_close($conn);

?>

Note

Nota:

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
Func?ii OCI8


Returns the name of a field from the statement

oci_field_is_null
oci_field_precision
Func?ii OCI8
PHP Manual

oci_field_name

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_name — Returns the name of a field from the statement

Descrierea

string oci_field_name ( resource $statement , mixed $field )

Returns the name of the field.

Parametri

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Valorile întoarse

Returns the name as a string, or FALSE on errors.

Exemple

Example #1 oci_field_name() example

<?php

// Create the table with:
//   CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
//                       clob_col CLOB, date_col DATE);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";

$ncols = oci_num_fields($stid);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stid, $i);
    $column_type  = oci_field_type($stid, $i);

    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "</tr>\n";
}

echo "</table>\n";

// Outputs:
//    Name           Type
//    NUMBER_COL    NUMBER
//    VARCHAR2_COL  VARCHAR2
//    CLOB_COL      CLOB
//    DATE_COL      DATE

oci_free_statement($stid);
oci_close($conn);

?>

Note

Nota:

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.

A se vedea ?i

  • oci_num_fields() - Returns the number of result columns in a statement
  • oci_field_type() - Returns a field's data type name
  • oci_field_size() - Returns field's size

oci_field_is_null
oci_field_precision
Func?ii OCI8


Tell the precision of a field

oci_field_name
oci_field_scale
Func?ii OCI8
PHP Manual

oci_field_precision

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_precision — Tell the precision of a field

Descrierea

int oci_field_precision ( resource $statement , mixed $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).

Parametri

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Valorile întoarse

Returns the precision as an integer, or FALSE on errors.

Exemple

Example #1 oci_field_precision() Example

<?php

// Create the table with:
//   CREATE TABLE mytab (c1 NUMBER, c2 FLOAT, c3 NUMBER(4), c4 NUMBER(5,3));

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
    echo oci_field_name($stid, $i) . " "
        . oci_field_precision($stid, $i) . " "
        . oci_field_scale($stid, $i) . "<br>\n";
}

// Outputs:
//   C1    0 -127
//   C2  126 -127
//   C3    4    0
//   C4    5    3

oci_free_statement($stid);
oci_close($conn);

?>

Note

Nota:

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.

A se vedea ?i

  • oci_field_scale() - Tell the scale of the field
  • oci_field_type() - Returns a field's data type name

oci_field_name
oci_field_scale
Func?ii OCI8


Tell the scale of the field

oci_field_precision
oci_field_size
Func?ii OCI8
PHP Manual

oci_field_scale

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_scale — Tell the scale of the field

Descrierea

int oci_field_scale ( resource $statement , mixed $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).

Parametri

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Valorile întoarse

Returns the scale as an integer, or FALSE on errors.

Exemple

Example #1 oci_field_scale() Example

<?php

// Create the table with:
//   CREATE TABLE mytab (c1 NUMBER, c2 FLOAT, c3 NUMBER(4), c4 NUMBER(5,3));

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
    echo oci_field_name($stid, $i) . " "
        . oci_field_precision($stid, $i) . " "
        . oci_field_scale($stid, $i) . "<br>\n";
}

// Outputs:
//   C1    0 -127
//   C2  126 -127
//   C3    4    0
//   C4    5    3

oci_free_statement($stid);
oci_close($conn);

?>

Note

Nota:

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.

A se vedea ?i

  • oci_field_precision() - Tell the precision of a field
  • oci_field_type() - Returns a field's data type name

oci_field_precision
oci_field_size
Func?ii OCI8


Returns field's size

oci_field_scale
oci_field_type_raw
Func?ii OCI8
PHP Manual

oci_field_size

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_size — Returns field's size

Descrierea

int oci_field_size ( resource $statement , mixed $field )

Returns the size of a field.

Parametri

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Valorile întoarse

Returns the size of a field in bytes, or FALSE on errors.

Exemple

Example #1 oci_field_size() example

<?php

// Create the table with:
//   CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
//                       clob_col CLOB, date_col DATE);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";

$ncols = oci_num_fields($stid);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stid, $i);
    $column_type  = oci_field_type($stid, $i);
    $column_size  = oci_field_size($stid, $i);

    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "<td>$column_size</td>";
    echo "</tr>\n";
}

echo "</table>\n";

// Outputs:
//    Name           Type       Length
//    NUMBER_COL    NUMBER        22
//    VARCHAR2_COL  VARCHAR2       1
//    CLOB_COL      CLOB        4000
//    DATE_COL      DATE           7

oci_free_statement($stid);
oci_close($conn);

?>

Note

Nota:

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.

A se vedea ?i

  • 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
Func?ii OCI8


Tell the raw Oracle data type of the field

oci_field_size
oci_field_type
Func?ii OCI8
PHP Manual

oci_field_type_raw

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_type_raw — Tell the raw Oracle data type of the field

Descrierea

int oci_field_type_raw ( resource $statement , mixed $field )

Returns Oracle's raw "SQLT" data type of the field.

If you want a field's type name, then use oci_field_type() instead.

Parametri

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Valorile întoarse

Returns Oracle's raw data type as a number, or FALSE on errors.

Exemple

Example #1 oci_field_type_raw() Example

<?php

// Create the table with:
//   CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1), clob_col CLOB, date_col DATE);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'select * from mytab');
oci_execute($stid, OCI_DESCRIBE_ONLY);  // Use OCI_DESCRIBE_ONLY if not fetching rows
$n = oci_num_fields($stid);
for ($i = 1; $i <= $n; ++$i) {
    echo oci_field_name($stid, $i) . " is raw type: " . oci_field_type_raw($stid, $i) . "<br>\n";
}

// Output is:
//    NUMBER_COL is raw type: 2
//    VARCHAR2_COL is raw type: 1
//    CLOB_COL is raw type: 112
//    DATE_COL is raw type: 12

oci_free_statement($stid);
oci_close($conn);

?>

Note

Nota:

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
Func?ii OCI8


Returns a field's data type name

oci_field_type_raw
oci_free_descriptor
Func?ii OCI8
PHP Manual

oci_field_type

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_type — Returns a field's data type name

Descrierea

mixed oci_field_type ( resource $statement , mixed $field )

Returns a field's data type name.

Parametri

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Valorile întoarse

Returns the field data type as a string, or FALSE on errors.

Exemple

Example #1 oci_field_type() example

<?php

// Create the table with:
//   CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
//                       clob_col CLOB, date_col DATE);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";

$ncols = oci_num_fields($stid);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stid, $i);
    $column_type  = oci_field_type($stid, $i);
    $column_size  = oci_field_size($stid, $i);

    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "<td>$column_size</td>";
    echo "</tr>\n";
}

echo "</table>\n";

// Outputs:
//    Name           Type       Length
//    NUMBER_COL    NUMBER        22
//    VARCHAR2_COL  VARCHAR2       1
//    CLOB_COL      CLOB        4000
//    DATE_COL      DATE           7

oci_free_statement($stid);
oci_close($conn);

?>

Note

Nota:

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.

A se vedea ?i

  • 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_descriptor
Func?ii OCI8


Frees a descriptor

oci_field_type
oci_free_statement
Func?ii OCI8
PHP Manual

oci_free_descriptor

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_free_descriptor — Frees a descriptor

Descrierea

bool oci_free_descriptor ( resource $descriptor )

Frees a descriptor allocated by oci_new_descriptor().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

This function is commonly used as a method OCI-LOB::free.

A se vedea ?i

  • OCI-LOB::free

oci_field_type
oci_free_statement
Func?ii OCI8


Frees all resources associated with statement or cursor

oci_free_descriptor
oci_get_implicit_resultset
Func?ii OCI8
PHP Manual

oci_free_statement

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_free_statement — Frees all resources associated with statement or cursor

Descrierea

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.

Parametri

statement

A valid OCI statement identifier.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

oci_free_descriptor
oci_get_implicit_resultset
Func?ii OCI8


Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets

oci_free_statement
oci_internal_debug
Func?ii OCI8
PHP Manual

oci_get_implicit_resultset

(PECL OCI8 >= 2.0.0)

oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets

Descrierea

resource oci_get_implicit_resultset ( resource $statement )

Used to fetch consectutive sets of query results after the execution of a stored or anonymous Oracle PL/SQL block where that block returns query results with Oracle's DBMS_SQL.RETURN_RESULT PL/SQL function. This allows PL/SQL blocks to easily return query results.

The child statement can be used with any of the OCI8 fetching
functions: oci_fetch(), oci_fetch_all(),
oci_fetch_array(), oci_fetch_object(),
oci_fetch_assoc() or oci_fetch_row()

Child statements inherit their parent statement's prefetch value, or it can be explicitly set with oci_set_prefetch().

Parametri

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(). The statement identifier may or may not be associated with a SQL statement that returns Implicit Result Sets.

Valorile întoarse

Returns a statement handle for the next child statement available on statement. Returns FALSE when child statements do not exist, or all child statements have been returned by previous calls to oci_get_implicit_resultset().

Exemple

Example #1 Fetching Implicit Result Sets in a loop

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'DECLARE
            c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
           OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

while (($stid_c = oci_get_implicit_resultset($stid))) {
    echo "<h2>New Implicit Result Set:</h2>\n";
    echo "<table>\n";
    while (($row = oci_fetch_array($stid_c, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
        echo "<tr>\n";
        foreach ($row as $item) {
            echo "  <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
        }
        echo "</tr>\n";
    }
    echo "</table>\n";
}

// Output is:
//    New Implicit Result Set:
//     Beijing 190518
//     Bern    3095
//     Bombay  490231
//    New Implicit Result Set:
//     CN
//     CH
//     IN

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Getting child statement handles individually

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'DECLARE
            c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
           OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

$stid_1 = oci_get_implicit_resultset($stid);
$stid_2 = oci_get_implicit_resultset($stid);

$row = oci_fetch_array($stid_1, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_2, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_1, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_2, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);

// Output is:
//    array(2) {
//      ["CITY"]=>
//      string(7) "Beijing"
//      ["POSTAL_CODE"]=>
//      string(6) "190518"
//    }
//    array(1) {
//      ["COUNTRY_ID"]=>
//      string(2) "CN"
//    }
//    array(2) {
//      ["CITY"]=>
//      string(4) "Bern"
//      ["POSTAL_CODE"]=>
//      string(4) "3095"
//    }
//    array(1) {
//      ["COUNTRY_ID"]=>
//      string(2) "CH"
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 Explicitly setting the Prefetch Count

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'DECLARE
            c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

$stid_c = oci_get_implicit_resultset($stid);
oci_set_prefetch($stid_c, 200);   // Set the prefetch before fetching from the child statement
echo "<table>\n";
while (($row = oci_fetch_array($stid_c, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "  <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 Implicit Result Set example without using oci_get_implicit_resultset()

All results from all queries are returned consecutively.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'DECLARE
            c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
           OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

// Note: oci_fetch_all and oci_fetch() cannot be used in this manner
echo "<table>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "  <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

// Output is:
//    Beijing 190518
//    Bern 3095
//    Bombay 490231
//    CN
//    CH
//    IN

oci_free_statement($stid);
oci_close($conn);

?>

Note

Nota:

În cazul interpelarilor ce întorc un numar mare de înregistrari, performan?a poate fi îmbunata?ita substan?ial marind valoarea oci8.default_prefetch sau utilizând oci_set_prefetch().

oci_free_statement
oci_internal_debug
Func?ii OCI8


Enables or disables internal debug output

oci_get_implicit_resultset
oci_lob_copy
Func?ii OCI8
PHP Manual

oci_internal_debug

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_internal_debug — Enables or disables internal debug output

Descrierea

void oci_internal_debug ( bool $onoff )

Enables or disables internal debug output.

Parametri

onoff

Set this to FALSE to turn debug output off or TRUE to turn it on.

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Nota:

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_get_implicit_resultset
oci_lob_copy
Func?ii OCI8


Copies large object

oci_internal_debug
oci_lob_is_equal
Func?ii OCI8
PHP Manual

oci_lob_copy

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_lob_copy — Copies large object

Descrierea

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.

Parametri

lob_to

The destination LOB.

lob_from

The copied LOB.

length

Indicates the length of data to be copied.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

oci_internal_debug
oci_lob_is_equal
Func?ii OCI8


Compares two LOB/FILE locators for equality

oci_lob_copy
oci_new_collection
Func?ii OCI8
PHP Manual

oci_lob_is_equal

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_lob_is_equal — Compares two LOB/FILE locators for equality

Descrierea

bool oci_lob_is_equal ( OCI-Lob $lob1 , OCI-Lob $lob2 )

Compares two LOB/FILE locators.

Parametri

lob1

A LOB identifier.

lob2

A LOB identifier.

Valorile întoarse

Returns TRUE if these objects are equal, FALSE otherwise.

oci_lob_copy
oci_new_collection
Func?ii OCI8


Allocates new collection object

oci_lob_is_equal
oci_new_connect
Func?ii OCI8
PHP Manual

oci_new_collection

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_new_collection — Allocates new collection object

Descrierea

OCI-Collection oci_new_collection ( resource $connection , string $tdo [, string $schema = NULL ] )

Allocates a new collection object.

Parametri

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.

Valorile întoarse

Returns a new OCICollection object or FALSE on error.

Note

Nota:

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
Func?ii OCI8


Connect to the Oracle server using a unique connection

oci_new_collection
oci_new_cursor
Func?ii OCI8
PHP Manual

oci_new_connect

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_new_connect — Connect to the Oracle server using a unique connection

Descrierea

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.

Parametri

username

The Oracle user name.

password

The password for username.

connection_string

Con?ine instan?a Oracle la care se efectueaza conectarea. Poate fi un » ?ir Easy Connect, sau o Denumire de conexiune din fi?ierul tnsnames.ora, sau denumirea unei instan?e locale Oracle.

Daca nu este specificat, PHP utilizeaza variabile de mediu, cum ar fi TWO_TASK (în Linux) sau LOCAL (în Windows) ?i ORACLE_SID pentru a determina instan?a Oracle la care trebuie efectuata conexiunea.

Pentru a utiliza metoda Easy Connect, PHP trebuie sa fie legat cu bibliotecile-client Oracle 10g sau ulterioare. ?irul Easy Connect pentru Oracle 10g este de forma: [//]host_name[:port][/service_name]. Pentru Oracle 11g sintaxa este: [//]host_name[:port][/service_name][:server_type][/instance_name]. Denumirile serviciilor pot fi gasite rulând utilitara Oracle lsnrctl status pe ma?ina unde ruleaza serverul de baze de date.

Fi?ierul tnsnames.ora poate fi în calea de cautare Oracle Net, care include $ORACLE_HOME/network/admin ?i /etc. Ca alternativa, poate fi stabilit TNS_ADMIN astfel încât $TNS_ADMIN/tnsnames.ora este citit. Asigura?i-va ca serviciul web poseda dreptul de citire a acestui fi?ier.

character_set

Determina setul de caractere utilizat de bibliotecile-client Oracle. Setul de caractere nu trebuie în mod obligatoriu sa se potriveasca cu setul de caractere al bazei de date. Daca nu se potrive?te, Oracle va face tot posibilul sa converteasca datele din ?i în setul de caractere al bazei de date. În dependen?a de seturile de caractere aceasta poate sa duca la rezultate incorecte. Convertirea de asemenea impune un timp marit de prelucrare.

Daca nu este specificat, bibliotecile-client Oracle determina setul de caractere din variabila de mediu NLS_LANG.

Transmiterea acestui parametru poate reduce timpul necesar pentru conectare.

session_mode

Acest parametru este disponibil începând cu versiunea PHP 5 (PECL OCI8 1.1) ?i accepta urmatoarele valori: OCI_DEFAULT, OCI_SYSOPER ?i OCI_SYSDBA. Daca sunt specificate OCI_SYSOPER sau OCI_SYSDBA, aceasta func?ie va încerca sa stabileasca o conexiune privilegiata utilizând creden?iale externe. Conexiunile privilegiate sunt dezactivate implicit. Pentru a le activa trebuie sa stabili?i oci8.privileged_connect în On.

PHP 5.3 (PECL OCI8 1.3.4) a introdus valoarea modului OCI_CRED_EXT. Aceasta indica Oracle sa utilizeze autentificare Externa sau la nivel de S.O., ceea ce trebuie configurat în baza de date. Fanionul OCI_CRED_EXT poate fi utilizat doar cu numele utilizatorului "/" ?i o parola vida. oci8.privileged_connect poate fi On sau Off.

OCI_CRED_EXT poate fi combinat cu modul OCI_SYSOPER sau OCI_SYSDBA.

OCI_CRED_EXT nu este sus?inut pe Windows din motive de securitate.

Valorile întoarse

Returns a connection identifier or FALSE on error.

Exemple

The following demonstrates how you can separate connections.

Example #1 oci_new_connect() example

<?php

// create table mytab (mycol number);

function query($name, $c)
{
    echo "Querying $name\n";
    $s = oci_parse($c, "select * from mytab");
    oci_execute($s, OCI_NO_AUTO_COMMIT);
    $row = oci_fetch_array($s, OCI_ASSOC);
    if (!$row) {
        echo "No rows\n";
    } else {
        do {
            foreach ($row as $item)
                echo $item . " ";
            echo "\n";
        } while (($row = oci_fetch_array($s, OCI_ASSOC)) != false);
    }
}

$c1 = oci_connect("hr", "welcome", "localhost/orcl");
$c2 = oci_new_connect("hr", "welcome", "localhost/orcl");

$s = oci_parse($c1, "insert into mytab values(1234)");
oci_execute($s, OCI_NO_AUTO_COMMIT);

query("basic connection", $c1);
query("new connection", $c2);
oci_commit($c1);
query("new connection after commit", $c2);

// Output is:
//   Querying basic connection
//   1234
//   Querying new connection
//   No rows
//   Querying new connection after commit
//   1234

?>

See oci_connect() for further examples of parameter usage.

A se vedea ?i

  • oci_connect() - Connect to an Oracle database
  • oci_pconnect() - Connect to an Oracle database using a persistent connection

oci_new_collection
oci_new_cursor
Func?ii OCI8


Allocates and returns a new cursor (statement handle)

oci_new_connect
oci_new_descriptor
Func?ii OCI8
PHP Manual

oci_new_cursor

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_new_cursor — Allocates and returns a new cursor (statement handle)

Descrierea

resource oci_new_cursor ( resource $connection )

Allocates a new statement handle on the specified connection.

Parametri

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

Valorile întoarse

Returns a new statement handle, or FALSE on error.

Exemple

Example #1 Binding a REF CURSOR in an Oracle stored procedure call

<?php

// Precreate:
//   create or replace procedure myproc(myrc out sys_refcursor) as
//   begin
//     open myrc for select first_name from employees;
//   end;

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$curs = oci_new_cursor($conn);
$stid = oci_parse($conn, "begin myproc(:cursbv); end;");
oci_bind_by_name($stid, ":cursbv", $curs, -1, OCI_B_CURSOR);
oci_execute($stid);

oci_execute($curs);  // Execute the REF CURSOR like a normal statement id
while (($row = oci_fetch_array($curs, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo $row['FIRST_NAME'] . "<br />\n";
}

oci_free_statement($stid);
oci_free_statement($curs);
oci_close($conn);

?>

Note

Nota:

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
Func?ii OCI8


Initializes a new empty LOB or FILE descriptor

oci_new_cursor
oci_num_fields
Func?ii OCI8
PHP Manual

oci_new_descriptor

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_new_descriptor — Initializes a new empty LOB or FILE descriptor

Descrierea

OCI-Lob oci_new_descriptor ( resource $connection [, int $type = OCI_DTYPE_LOB ] )

Allocates resources to hold descriptor or LOB locator.

Parametri

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.

Valorile întoarse

Returns a new LOB or FILE descriptor on success, FALSE on error.

Exemple

Example #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";
     }
     $lob->free();
     oci_free_statement($stmt);
     oci_close($conn);
  }
?>

Example #2 oci_new_descriptor() example

<?php
/* Calling PL/SQL stored procedures which contain clobs as input
 * parameters.
 * 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);
?>

Note

Nota:

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.

A se vedea ?i

  • oci_bind_by_name() - Binds a PHP variable to an Oracle placeholder

oci_new_cursor
oci_num_fields
Func?ii OCI8


Returns the number of result columns in a statement

oci_new_descriptor
oci_num_rows
Func?ii OCI8
PHP Manual

oci_num_fields

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_num_fields — Returns the number of result columns in a statement

Descrierea

int oci_num_fields ( resource $statement )

Gets the number of columns in the given statement.

Parametri

statement

A valid OCI statement identifier.

Valorile întoarse

Returns the number of columns as an integer, or FALSE on errors.

Exemple

Example #1 oci_num_fields() example

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER, quantity NUMBER);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
    echo oci_field_name($stid, $i) . " " . oci_field_type($stid, $i) . "<br>\n";
}

// Outputs:
//    ID NUMBER
//    QUANTITY NUMBER

oci_free_statement($stid);
oci_close($conn);

?>

Note

Nota:

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
Func?ii OCI8


Returns number of rows affected during statement execution

oci_num_fields
oci_parse
Func?ii OCI8
PHP Manual

oci_num_rows

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_num_rows — Returns number of rows affected during statement execution

Descrierea

int oci_num_rows ( resource $statement )

Gets the number of rows affected during statement execution.

Parametri

statement

A valid OCI statement identifier.

Valorile întoarse

Returns the number of rows affected as an integer, or FALSE on errors.

Exemple

Example #1 oci_num_rows() example

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "create table emp2 as select * from employees");
oci_execute($stid);
echo oci_num_rows($stid) . " rows inserted.<br />\n";
oci_free_statement($stid);

$stid = oci_parse($conn, "delete from emp2");
oci_execute($stid, OCI_DEFAULT);
echo oci_num_rows($stid) . " rows deleted.<br />\n";
oci_commit($conn);
oci_free_statement($stid);

$stid = oci_parse($conn, "drop table emp2");
oci_execute($stid);
oci_free_statement($stid);

oci_close($conn);

?>

Note

Nota:

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.

Nota:

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
Func?ii OCI8


Prepares an Oracle statement for execution

oci_num_rows
oci_password_change
Func?ii OCI8
PHP Manual

oci_parse

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_parse — Prepares an Oracle statement for execution

Descrierea

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.

Parametri

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 (";").

Valorile întoarse

Returns a statement handle on success, or FALSE on error.

Exemple

Example #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";

?>

Example #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);

?>

Note

Nota:

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.

A se vedea ?i

  • oci_execute() - Executes a statement
  • oci_free_statement() - Frees all resources associated with statement or cursor

oci_num_rows
oci_password_change
Func?ii OCI8


Changes password of Oracle's user

oci_parse
oci_pconnect
Func?ii OCI8
PHP Manual

oci_password_change

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_password_change — Changes password of Oracle's user

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 oci_password_change() example changing the password of an already connected user

<?php

$dbase      = 'localhost/orcl';
$user       = 'cj';
$current_pw = 'welcome';
$new_pw     = 'geelong';

$c = oci_pconnect($user, $current_pw, $dbase);
oci_password_change($c, $user, $current_pw, $new_pw);
echo "New password is : " . $new_pw . "\n";

?>

Example #2 oci_password_change() example of connecting and changing the password in one step

<?php

$dbase      = 'localhost/orcl';
$user       = 'cj';
$current_pw = 'welcome';
$new_pw     = 'geelong';

$c = oci_pconnect($user, $current_pw, $dbase);
if (!$c) {
    $m = oci_error();
    if ($m['code'] == 28001) { // "ORA-28001: the password has expired"
        // Login and reset password at the same time
        $c = oci_password_change($dbase, $user, $current_pw, $new_pw);
        if ($c) {
            echo "New password is : " . $new_pw . "\n";
        }
    }
}

if (!$c) {  // The original error wasn't 28001, or the password change failed
    $m = oci_error();
    trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR);
}

// Use the connection $c
...

?>

Note

Nota:

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.

Nota:

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.

Nota:

The second oci_password_change() syntax is available since OCI8 version 1.1.

Nota:

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
Func?ii OCI8


Connect to an Oracle database using a persistent connection

oci_password_change
oci_result
Func?ii OCI8
PHP Manual

oci_pconnect

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_pconnect — Connect to an Oracle database using a persistent connection

Descrierea

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.

Parametri

username

The Oracle user name.

password

The password for username.

connection_string

Con?ine instan?a Oracle la care se efectueaza conectarea. Poate fi un » ?ir Easy Connect, sau o Denumire de conexiune din fi?ierul tnsnames.ora, sau denumirea unei instan?e locale Oracle.

Daca nu este specificat, PHP utilizeaza variabile de mediu, cum ar fi TWO_TASK (în Linux) sau LOCAL (în Windows) ?i ORACLE_SID pentru a determina instan?a Oracle la care trebuie efectuata conexiunea.

Pentru a utiliza metoda Easy Connect, PHP trebuie sa fie legat cu bibliotecile-client Oracle 10g sau ulterioare. ?irul Easy Connect pentru Oracle 10g este de forma: [//]host_name[:port][/service_name]. Pentru Oracle 11g sintaxa este: [//]host_name[:port][/service_name][:server_type][/instance_name]. Denumirile serviciilor pot fi gasite rulând utilitara Oracle lsnrctl status pe ma?ina unde ruleaza serverul de baze de date.

Fi?ierul tnsnames.ora poate fi în calea de cautare Oracle Net, care include $ORACLE_HOME/network/admin ?i /etc. Ca alternativa, poate fi stabilit TNS_ADMIN astfel încât $TNS_ADMIN/tnsnames.ora este citit. Asigura?i-va ca serviciul web poseda dreptul de citire a acestui fi?ier.

character_set

Determina setul de caractere utilizat de bibliotecile-client Oracle. Setul de caractere nu trebuie în mod obligatoriu sa se potriveasca cu setul de caractere al bazei de date. Daca nu se potrive?te, Oracle va face tot posibilul sa converteasca datele din ?i în setul de caractere al bazei de date. În dependen?a de seturile de caractere aceasta poate sa duca la rezultate incorecte. Convertirea de asemenea impune un timp marit de prelucrare.

Daca nu este specificat, bibliotecile-client Oracle determina setul de caractere din variabila de mediu NLS_LANG.

Transmiterea acestui parametru poate reduce timpul necesar pentru conectare.

session_mode

Acest parametru este disponibil începând cu versiunea PHP 5 (PECL OCI8 1.1) ?i accepta urmatoarele valori: OCI_DEFAULT, OCI_SYSOPER ?i OCI_SYSDBA. Daca sunt specificate OCI_SYSOPER sau OCI_SYSDBA, aceasta func?ie va încerca sa stabileasca o conexiune privilegiata utilizând creden?iale externe. Conexiunile privilegiate sunt dezactivate implicit. Pentru a le activa trebuie sa stabili?i oci8.privileged_connect în On.

PHP 5.3 (PECL OCI8 1.3.4) a introdus valoarea modului OCI_CRED_EXT. Aceasta indica Oracle sa utilizeze autentificare Externa sau la nivel de S.O., ceea ce trebuie configurat în baza de date. Fanionul OCI_CRED_EXT poate fi utilizat doar cu numele utilizatorului "/" ?i o parola vida. oci8.privileged_connect poate fi On sau Off.

OCI_CRED_EXT poate fi combinat cu modul OCI_SYSOPER sau OCI_SYSDBA.

OCI_CRED_EXT nu este sus?inut pe Windows din motive de securitate.

Valorile întoarse

Returns a connection identifier or FALSE on error.

Exemple

Example #1 Basic oci_pconnect() Example using Easy Connect syntax

<?php

// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_pconnect('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";

?>

See oci_connect() for further examples of parameter usage.

Note

Nota: Starting with PHP 5.1.2 and PECL OCI8 1.1, the lifetime and maximum number of persistent Oracle connections per PHP process can be tuned by setting the following configuration values: oci8.persistent_timeout, oci8.ping_interval and oci8.max_persistent.

A se vedea ?i

  • oci_connect() - Connect to an Oracle database
  • oci_new_connect() - Connect to the Oracle server using a unique connection

oci_password_change
oci_result
Func?ii OCI8


Returns field's value from the fetched row

oci_pconnect
oci_rollback
Func?ii OCI8
PHP Manual

oci_result

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_result — Returns field's value from the fetched row

Descrierea

mixed oci_result ( resource $statement , mixed $field )

Returns the data from field in the current row, fetched by oci_fetch().

Pentru detalii despre coresponden?ele transformarilor tipurilor de date efectuate de extensia OCI8, accesa?i tipurile de date sus?inute de driver

Parametri

statement

field

Can be either use the column number (1-based) or the column name. The case of the column name must be the case that Oracle meta data describes the column as, which is uppercase for columns created case insensitively.

Valorile întoarse

Returns everything as strings except for abstract types (ROWIDs, LOBs and FILEs). Returns FALSE on error.

Exemple

Example #1 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);

?>

Note

Nota:

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.

A se vedea ?i

  • 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
Func?ii OCI8


Rolls back the outstanding database transaction

oci_result
oci_server_version
Func?ii OCI8
PHP Manual

oci_rollback

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_rollback — Rolls back the outstanding database transaction

Descrierea

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.

Parametri

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect() or oci_new_connect().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
}

?>

Example #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
?>

Note

Nota:

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.

A se vedea ?i

  • oci_commit() - Commits the outstanding database transaction
  • oci_execute() - Executes a statement

oci_result
oci_server_version
Func?ii OCI8


Returns the Oracle Database version

oci_rollback
oci_set_action
Func?ii OCI8
PHP Manual

oci_server_version

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_server_version — Returns the Oracle Database version

Descrierea

string oci_server_version ( resource $connection )

Returns a string with the Oracle Database version and available options

Parametri

connection

Valorile întoarse

Returns the version information as a string or FALSE on error.

Exemple

Example #1 oci_server_version() example

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
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);

?>

Note

Nota:

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.

A se vedea ?i

  • oci_client_version() - Returns the Oracle client library version

oci_rollback
oci_set_action
Func?ii OCI8


Sets the action name

oci_server_version
oci_set_client_identifier
Func?ii OCI8
PHP Manual

oci_set_action

(PHP 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)

oci_set_action — Sets the action name

Descrierea

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.

Parametri

connection

Un identificator al conexiunii Oracle, întors de oci_connect(), oci_pconnect() sau oci_new_connect().

action_name

User chosen string up to 32 bytes long.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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;

Note

Nota: Versiune Oracle necesara

Aceasta func?ie este disponibila atunci când PHP este compilat cu bibliotecile Oracle Database de versiunea 10g sau ulterioare.

Sfat

Performan?a

Cu versiuni mai vechi ale OCI8 sau ale Oracle Database, informa?ia clientului poate fi transmisa utilizând pachetul Oracle DBMS_APPLICATION_INFO. Aceasta este mai pu?in eficient decât utilizarea oci_set_client_info().

Precautie

Capcane dus-întors

Unele func?ii OCI8, dar nu toate, cauzeaza cai dus-întors. Caile dus-întors catre baza de date pot sa nu aiba loc în cazul interpelarilor, atunci când buferizarea rezultatelor este activata.

A se vedea ?i

  • 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
Func?ii OCI8


Sets the client identifier

oci_set_action
oci_set_client_info
Func?ii OCI8
PHP Manual

oci_set_client_identifier

(PHP 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)

oci_set_client_identifier — Sets the client identifier

Descrierea

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, for example with SELECT SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER') FROM DUAL. Database administration views such as V$SESSION will also contain the value. It can be used with DBMS_MONITOR.CLIENT_ID_TRACE_ENABLE for tracing and can also be used for auditing.

The value may be retained across page requests that use the same persistent connection.

Parametri

connection

Un identificator al conexiunii Oracle, întors de oci_connect(), oci_pconnect() sau oci_new_connect().

client_identifier

User chosen string up to 64 bytes long.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

// ...

?>

Note

Precautie

Capcane dus-întors

Unele func?ii OCI8, dar nu toate, cauzeaza cai dus-întors. Caile dus-întors catre baza de date pot sa nu aiba loc în cazul interpelarilor, atunci când buferizarea rezultatelor este activata.

A se vedea ?i

  • 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
Func?ii OCI8


Sets the client information

oci_set_client_identifier
oci_set_edition
Func?ii OCI8
PHP Manual

oci_set_client_info

(PHP 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)

oci_set_client_info — Sets the client information

Descrierea

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.

Parametri

connection

Un identificator al conexiunii Oracle, întors de oci_connect(), oci_pconnect() sau oci_new_connect().

client_info

User chosen string up to 64 bytes long.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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;

Note

Nota: Versiune Oracle necesara

Aceasta func?ie este disponibila atunci când PHP este compilat cu bibliotecile Oracle Database de versiunea 10g sau ulterioare.

Sfat

Performan?a

Cu versiuni mai vechi ale OCI8 sau ale Oracle Database, informa?ia clientului poate fi transmisa utilizând pachetul Oracle DBMS_APPLICATION_INFO. Aceasta este mai pu?in eficient decât utilizarea oci_set_client_info().

Precautie

Capcane dus-întors

Unele func?ii OCI8, dar nu toate, cauzeaza cai dus-întors. Caile dus-întors catre baza de date pot sa nu aiba loc în cazul interpelarilor, atunci când buferizarea rezultatelor este activata.

A se vedea ?i

  • 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
Func?ii OCI8


Sets the database edition

oci_set_client_info
oci_set_module_name
Func?ii OCI8
PHP Manual

oci_set_edition

(PHP 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)

oci_set_edition — Sets the database edition

Descrierea

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

Parametri

edition

Oracle Database edition name previously created with the SQL "CREATE EDITION" command.

Note

Nota: Oracle version requirement

This function is available from Oracle 11gR2 onwards.

Precautie

Persistent connections

To avoid inconsistencies and unexpected errors, do not use ALTER SESSION SET EDITION to change the edition on persistent connections.

Precautie

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii OCI8


Sets the module name

oci_set_edition
oci_set_prefetch
Func?ii OCI8
PHP Manual

oci_set_module_name

(PHP 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)

oci_set_module_name — Sets the module name

Descrierea

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.

Parametri

connection

Un identificator al conexiunii Oracle, întors de oci_connect(), oci_pconnect() sau oci_new_connect().

module_name

User chosen string up to 48 bytes long.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota: Versiune Oracle necesara

Aceasta func?ie este disponibila atunci când PHP este compilat cu bibliotecile Oracle Database de versiunea 10g sau ulterioare.

Sfat

Performan?a

Cu versiuni mai vechi ale OCI8 sau ale Oracle Database, informa?ia clientului poate fi transmisa utilizând pachetul Oracle DBMS_APPLICATION_INFO. Aceasta este mai pu?in eficient decât utilizarea oci_set_client_info().

Precautie

Capcane dus-întors

Unele func?ii OCI8, dar nu toate, cauzeaza cai dus-întors. Caile dus-întors catre baza de date pot sa nu aiba loc în cazul interpelarilor, atunci când buferizarea rezultatelor este activata.

Exemple

Example #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;

A se vedea ?i

  • 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
Func?ii OCI8


Sets number of rows to be prefetched by queries

oci_set_module_name
oci_statement_type
Func?ii OCI8
PHP Manual

oci_set_prefetch

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_set_prefetch — Sets number of rows to be prefetched by queries

Descrierea

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 (or later) Client libraries. Nested cursor prefetching was introduced in Oracle 11gR2 and requires both the Oracle Client libraries and the database to be version 11gR2 or greater.

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.

When using Oracle Database 12c, the prefetch value set by PHP can be overridden by Oracle's client oraaccess.xml configuration file. Refer to Oracle documentation for more detail.

Parametri

statement

Un identificator valid de instruc?iune OCI8 creat cu oci_parse() ?i executat de oci_execute(), sau un identificator de instruc?iune REF CURSOR.

rows

The number of rows to be prefetched, >= 0

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.2 (PECL OCI8 1.4) | Before this release, rows must be >= 1.
5.3.0 (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.

Exemple

Example #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);

?>

Example #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 or later 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.

Example #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);

?>

A se vedea ?i

  • oci8.default_prefetch ini option

oci_set_module_name
oci_statement_type
Func?ii OCI8


Returns the type of a statement

oci_set_prefetch
OCI-Collection
Func?ii OCI8
PHP Manual

oci_statement_type

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_statement_type — Returns the type of a statement

Descrierea

string oci_statement_type ( resource $statement )

Returns a keyword identifying the type of the OCI8 statement.

Parametri

statement

A valid OCI8 statement identifier from oci_parse().

Valorile întoarse

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.

Exemple

Example #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);

?>

oci_set_prefetch
OCI-Collection
Func?ii OCI8


The OCI-Collection class

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

Introducere

OCI8 Collection functionality.

Sinopsisul clasei

OCI-Collection {
/* Metode */
bool append ( mixed $value )
bool assign ( OCI-Collection $from )
bool assignElem ( int $index , mixed $value )
bool free ( void )
mixed getElem ( int $index )
int max ( void )
int size ( void )
bool trim ( int $num )
}

Cuprins

  • 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_statement_type
OCI-Collection::append
OCI8


Appends element to the collection

OCI-Collection
OCI-Collection::assign
OCI-Collection
PHP Manual

OCI-Collection::append

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::append — Appends element to the collection

Descrierea

bool OCI-Collection::append ( mixed $value )

Appends element to the end of the collection.

Parametri

value

The value to be added to the collection. Can be a string or a number.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Collection::assign

OCI-Collection
OCI-Collection::assign
OCI-Collection


Assigns a value to the collection from another existing collection

OCI-Collection::append
OCI-Collection::assignElem
OCI-Collection
PHP Manual

OCI-Collection::assign

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::assign — Assigns a value to the collection from another existing collection

Descrierea

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.

Parametri

from

An instance of OCI-Collection.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Collection::append

OCI-Collection::append
OCI-Collection::assignElem
OCI-Collection


Assigns a value to the element of the collection

OCI-Collection::assign
OCI-Collection::free
OCI-Collection
PHP Manual

OCI-Collection::assignElem

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::assignElem — Assigns a value to the element of the collection

Descrierea

bool OCI-Collection::assignElem ( int $index , mixed $value )

Assigns a value to the element with index index.

Parametri

index

The element index. First index is 0.

value

Can be a string or a number.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Collection::getElem

OCI-Collection::assign
OCI-Collection::free
OCI-Collection


Frees the resources associated with the collection object

OCI-Collection::assignElem
OCI-Collection::getElem
OCI-Collection
PHP Manual

OCI-Collection::free

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::free — Frees the resources associated with the collection object

Descrierea

bool OCI-Collection::free ( void )

Frees the resources associated with the collection object.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • oci_new_collection

OCI-Collection::assignElem
OCI-Collection::getElem
OCI-Collection


Returns value of the element

OCI-Collection::free
OCI-Collection::max
OCI-Collection
PHP Manual

OCI-Collection::getElem

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::getElem — Returns value of the element

Descrierea

mixed OCI-Collection::getElem ( int $index )

Returns element's value with the index index (0-based).

Parametri

index

The element index. First index is 0.

Valorile întoarse

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.

A se vedea ?i

  • OCI-Collection::assignElem

OCI-Collection::free
OCI-Collection::max
OCI-Collection


Returns the maximum number of elements in the collection

OCI-Collection::getElem
OCI-Collection::size
OCI-Collection
PHP Manual

OCI-Collection::max

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::max — Returns the maximum number of elements in the collection

Descrierea

int OCI-Collection::max ( void )

Returns the maximum number of elements in the collection.

Valorile întoarse

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.

A se vedea ?i

  • OCI-Collection::size

OCI-Collection::getElem
OCI-Collection::size
OCI-Collection


Returns size of the collection

OCI-Collection::max
OCI-Collection::trim
OCI-Collection
PHP Manual

OCI-Collection::size

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::size — Returns size of the collection

Descrierea

int OCI-Collection::size ( void )

Returns the size of the collection.

Valorile întoarse

Returns the number of elements in the collection or FALSE on error.

A se vedea ?i

  • OCI-Collection::max

OCI-Collection::max
OCI-Collection::trim
OCI-Collection


Trims elements from the end of the collection

OCI-Collection::size
OCI-Lob
OCI-Collection
PHP Manual

OCI-Collection::trim

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::trim — Trims elements from the end of the collection

Descrierea

bool OCI-Collection::trim ( int $num )

Trims num of elements from the end of the collection.

Parametri

num

The number of elements to be trimmed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Collection::size

OCI-Collection::size
OCI-Lob
OCI-Collection


The OCI-Lob class

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

Introducere

OCI8 LOB functionality for large binary (BLOB) and character (CLOB) objects.

Sinopsisul clasei

OCI-Lob {
/* Metode */
bool append ( OCI-Lob $lob_from )
bool close ( void )
bool eof ( void )
int erase ([ int $offset [, int $length ]] )
bool export ( string $filename [, int $start [, int $length ]] )
bool flush ([ int $flag ] )
bool free ( void )
bool getBuffering ( void )
bool import ( string $filename )
string load ( void )
string read ( int $length )
bool rewind ( void )
bool save ( string $data [, int $offset ] )
bool seek ( int $offset [, int $whence = OCI_SEEK_SET ] )
bool setBuffering ( bool $on_off )
int size ( void )
int tell ( void )
bool truncate ([ int $length = 0 ] )
int write ( string $data [, int $length ] )
bool writeTemporary ( string $data [, int $lob_type = OCI_TEMP_CLOB ] )
}

Cuprins

  • OCI-Lob::append — Adauga datele dintr-un obiect de tip LOB în alt obiect de tip LOB
  • OCI-Lob::close — Închide un descriptor LOB
  • 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 — Gole?te/scrie zona-tampon LOB pe 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 — Pseudonim pentru 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 — Scrie un LOB temporar
  • OCI-Lob::writeToFile — Pseudonim pentru OCI-Lob::export
OCI-Collection::trim
OCI-Lob::append
OCI8


Adauga datele dintr-un obiect de tip LOB în alt obiect de tip LOB

OCI-Lob
OCI-Lob::close
OCI-Lob
PHP Manual

OCI-Lob::append

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::append — Adauga datele dintr-un obiect de tip LOB în alt obiect de tip LOB

Descrierea

bool OCI-Lob::append ( OCI-Lob $lob_from )

Adauga datele dintr-un obiect LOB la sfâr?itul unui alt obiect de tip LOB.

Scrierea într-un obiect de tip LOB cu aceasta metoda va e?ua daca zona tampon este activa. Înainte de adaugare trebuie sa dezactiva?i zona tampon. Este posibil sa fi nevoie sa goliti zona tampon cu OCI-Lob::flush îninate de a o dezactiva.

Parametri

lob_from

Obiectul LOB din care se va copia.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Lob::flush
  • OCI-Lob::setBuffering
  • OCI-Lob::getBuffering

OCI-Lob
OCI-Lob::close
OCI-Lob


Închide un descriptor LOB

OCI-Lob::append
OCI-Lob::eof
OCI-Lob
PHP Manual

OCI-Lob::close

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::close — Închide un descriptor LOB

Descrierea

bool OCI-Lob::close ( void )

Închide un descriptor LOB sau FILE. Aceasta func?ie ar trebui folosita numai cu OCI-Lob::writeTemporary.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Lob::writeTemporary

OCI-Lob::append
OCI-Lob::eof
OCI-Lob


Tests for end-of-file on a large object's descriptor

OCI-Lob::close
OCI-Lob::erase
OCI-Lob
PHP Manual

OCI-Lob::eof

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::eof — Tests for end-of-file on a large object's descriptor

Descrierea

bool OCI-Lob::eof ( void )

Tells whether the internal pointer of large object is at the end of LOB.

Valorile întoarse

Returns TRUE if internal pointer of large object is at the end of LOB. Otherwise returns FALSE.

Note

Nota:

This function will return an Oracle error if OCI-Lob::setBuffering is enabled on the LOB.

A se vedea ?i

  • OCI-Lob::size

OCI-Lob::close
OCI-Lob::erase
OCI-Lob


Erases a specified portion of the internal LOB data

OCI-Lob::eof
OCI-Lob::export
OCI-Lob
PHP Manual

OCI-Lob::erase

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::erase — Erases a specified portion of the internal LOB data

Descrierea

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.

Parametri

offset

length

Valorile întoarse

Returns the actual number of characters/bytes erased sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Lob::truncate

OCI-Lob::eof
OCI-Lob::export
OCI-Lob


Exports LOB's contents to a file

OCI-Lob::erase
OCI-Lob::flush
OCI-Lob
PHP Manual

OCI-Lob::export

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::export — Exports LOB's contents to a file

Descrierea

bool OCI-Lob::export ( string $filename [, int $start [, int $length ]] )

Exports LOB contents to a file.

Parametri

filename

Path to the file.

start

Indicates from where to start exporting.

length

Indicates the length of data to be exported.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Lob::import

OCI-Lob::erase
OCI-Lob::flush
OCI-Lob


Gole?te/scrie zona-tampon LOB pe server

OCI-Lob::export
OCI-Lob::free
OCI-Lob
PHP Manual

OCI-Lob::flush

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::flush — Gole?te/scrie zona-tampon LOB pe server

Descrierea

bool OCI-Lob::flush ([ int $flag ] )

OCI-Lob::flush() scrie datele pe server.

Parametri

flag

Implicit, resursele nu sunt eliberate, folosind op?iunea OCI_LOB_BUFFER_FREE se poate face explicit. Folose?te aceasta op?iune numai daca ?tii ce faci - pentru urmatoarea opera?iune de citire/scriere în LOB va fi necesar ini?ializarea unei noi zone-tampon. Este recomandata folosirea op?iunii OCI_LOB_BUFFER_FREE atunci când nu mai ave?i de lucrat cu obiectul LOB.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Întoarce FALSE daca zona-tampon nu a fost activata sau a aparut o eroare.

A se vedea ?i

  • OCI-Lob::getBuffering
  • OCI-Lob::setBuffering

OCI-Lob::export
OCI-Lob::free
OCI-Lob


Frees resources associated with the LOB descriptor

OCI-Lob::flush
OCI-Lob::getBuffering
OCI-Lob
PHP Manual

OCI-Lob::free

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::free — Frees resources associated with the LOB descriptor

Descrierea

bool OCI-Lob::free ( void )

Frees resources associated with the descriptor, previously allocated with oci_new_descriptor().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

OCI-Lob::flush
OCI-Lob::getBuffering
OCI-Lob


Returns current state of buffering for the large object

OCI-Lob::free
OCI-Lob::import
OCI-Lob
PHP Manual

OCI-Lob::getBuffering

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::getBuffering — Returns current state of buffering for the large object

Descrierea

bool OCI-Lob::getBuffering ( void )

Tells whether the buffering for the large object is on or off.

Valorile întoarse

Returns FALSE if buffering for the large object is off and TRUE if buffering is used.

A se vedea ?i

  • OCI-Lob::setBuffering

OCI-Lob::free
OCI-Lob::import
OCI-Lob


Imports file data to the LOB

OCI-Lob::getBuffering
OCI-Lob::load
OCI-Lob
PHP Manual

OCI-Lob::import

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::import — Imports file data to the LOB

Descrierea

bool OCI-Lob::import ( string $filename )

Writes data from the filename in to the current position of large object.

Parametri

filename

Path to the file.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Lob::export
  • OCI-Lob::write

OCI-Lob::getBuffering
OCI-Lob::load
OCI-Lob


Returns large object's contents

OCI-Lob::import
OCI-Lob::read
OCI-Lob
PHP Manual

OCI-Lob::load

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::load — Returns large object's contents

Descrierea

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.

Valorile întoarse

Returns the contents of the object, or FALSE on errors.

A se vedea ?i

  • OCI-Lob::read

OCI-Lob::import
OCI-Lob::read
OCI-Lob


Reads part of the large object

OCI-Lob::load
OCI-Lob::rewind
OCI-Lob
PHP Manual

OCI-Lob::read

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::read — Reads part of the large object

Descrierea

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.

Parametri

length

The length of data to read, in bytes. Large values will be rounded down to 1 MB.

Valorile întoarse

Returns the contents as a string, sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Lob::load
  • OCI-Lob::write

OCI-Lob::load
OCI-Lob::rewind
OCI-Lob


Moves the internal pointer to the beginning of the large object

OCI-Lob::read
OCI-Lob::save
OCI-Lob
PHP Manual

OCI-Lob::rewind

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::rewind — Moves the internal pointer to the beginning of the large object

Descrierea

bool OCI-Lob::rewind ( void )

Sets the internal pointer to the beginning of the large object.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Lob::seek
  • OCI-Lob::tell

OCI-Lob::read
OCI-Lob::save
OCI-Lob


Saves data to the large object

OCI-Lob::rewind
OCI-Lob::saveFile
OCI-Lob
PHP Manual

OCI-Lob::save

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::save — Saves data to the large object

Descrierea

bool OCI-Lob::save ( string $data [, int $offset ] )

Saves data to the large object.

Parametri

data

The data to be saved.

offset

Can be used to indicate offset from the beginning of the large object.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Lob::write
  • OCI-Lob::import

OCI-Lob::rewind
OCI-Lob::saveFile
OCI-Lob


Pseudonim pentru OCI-Lob::import

OCI-Lob::save
OCI-Lob::seek
OCI-Lob
PHP Manual

OCI-Lob::saveFile

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::saveFile — Pseudonim pentru OCI-Lob::import()

Descrierea

Aceasta func?ie este pseudonim pentru: OCI-Lob::import().

OCI-Lob::save
OCI-Lob::seek
OCI-Lob


Sets the internal pointer of the large object

OCI-Lob::saveFile
OCI-Lob::setBuffering
OCI-Lob
PHP Manual

OCI-Lob::seek

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::seek — Sets the internal pointer of the large object

Descrierea

bool OCI-Lob::seek ( int $offset [, int $whence = OCI_SEEK_SET ] )

Sets the internal pointer of the large object.

Parametri

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)

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Lob::rewind
  • OCI-Lob::tell
  • OCI-Lob::eof

OCI-Lob::saveFile
OCI-Lob::setBuffering
OCI-Lob


Changes current state of buffering for the large object

OCI-Lob::seek
OCI-Lob::size
OCI-Lob
PHP Manual

OCI-Lob::setBuffering

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::setBuffering — Changes current state of buffering for the large object

Descrierea

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.

Parametri

on_off

TRUE for on and FALSE for off.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Repeated calls to this method with the same flag will return TRUE.

A se vedea ?i

  • OCI-Lob::getBuffering

OCI-Lob::seek
OCI-Lob::size
OCI-Lob


Returns size of large object

OCI-Lob::setBuffering
OCI-Lob::tell
OCI-Lob
PHP Manual

OCI-Lob::size

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::size — Returns size of large object

Descrierea

int OCI-Lob::size ( void )

Gets the size of the large object.

Valorile întoarse

Returns length of large object value sau FALSE în cazul e?ecului. Empty objects have zero length.

OCI-Lob::setBuffering
OCI-Lob::tell
OCI-Lob


Returns the current position of internal pointer of large object

OCI-Lob::size
OCI-Lob::truncate
OCI-Lob
PHP Manual

OCI-Lob::tell

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::tell — Returns the current position of internal pointer of large object

Descrierea

int OCI-Lob::tell ( void )

Gets the current position of a LOB's internal pointer.

Valorile întoarse

Returns current position of a LOB's internal pointer or FALSE if an error occurred.

A se vedea ?i

  • OCI-Lob::rewind
  • OCI-Lob::size
  • OCI-Lob::eof

OCI-Lob::size
OCI-Lob::truncate
OCI-Lob


Truncates large object

OCI-Lob::tell
OCI-Lob::write
OCI-Lob
PHP Manual

OCI-Lob::truncate

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::truncate — Truncates large object

Descrierea

bool OCI-Lob::truncate ([ int $length = 0 ] )

Truncates the LOB.

Parametri

length

If provided, this method will truncate the LOB to length bytes. Otherwise, it will completely purge the LOB.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Lob::erase

OCI-Lob::tell
OCI-Lob::write
OCI-Lob


Writes data to the large object

OCI-Lob::truncate
OCI-Lob::writeTemporary
OCI-Lob
PHP Manual

OCI-Lob::write

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::write — Writes data to the large object

Descrierea

int OCI-Lob::write ( string $data [, int $length ] )

Writes data from the parameter data into the current position of LOB's internal pointer.

Parametri

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.

Valorile întoarse

Returns the number of bytes written sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Lob::read

OCI-Lob::truncate
OCI-Lob::writeTemporary
OCI-Lob


Scrie un LOB temporar

OCI-Lob::write
OCI-Lob::writeToFile
OCI-Lob
PHP Manual

OCI-Lob::writeTemporary

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::writeTemporary — Scrie un LOB temporar

Descrierea

bool OCI-Lob::writeTemporary ( string $data [, int $lob_type = OCI_TEMP_CLOB ] )

Creaza un LOB temporar ?i scrie data în el.

Dupa ce termina?i lucrul cu acest obiect trebuie sa folosi?i OCI-Lob::close.

Parametri

data

Datele ce vor fi scrise.

lob_type

Poate fi unul din urmatoarele:

  • OCI_TEMP_BLOB folosit pentru a crea un BLOB temporar
  • OCI_TEMP_CLOB folosit pentru a crea un CLOB temporar

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • OCI-Lob::close

OCI-Lob::write
OCI-Lob::writeToFile
OCI-Lob


Pseudonim pentru OCI-Lob::export

OCI-Lob::writeTemporary
Pseudonime ?i func?ii OCI8 învechite
OCI-Lob
PHP Manual

OCI-Lob::writeToFile

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::writeToFile — Pseudonim pentru OCI-Lob::export()

Descrierea

Aceasta func?ie este pseudonim pentru: OCI-Lob::export().

OCI-Lob::writeTemporary
Pseudonime ?i func?ii OCI8 învechite
OCI-Lob


Pseudonime ?i func?ii OCI8 învechite

Cuprins

  • ocibindbyname — Pseudonim pentru oci_bind_by_name
  • ocicancel — Pseudonim pentru oci_cancel
  • ocicloselob — Pseudonim pentru OCI-Lob::close
  • ocicollappend — Pseudonim pentru OCI-Collection::append
  • ocicollassign — Pseudonim pentru OCI-Collection::assign
  • ocicollassignelem — Pseudonim pentru OCI-Collection::assignElem
  • ocicollgetelem — Pseudonim pentru OCI-Collection::getElem
  • ocicollmax — Pseudonim pentru OCI-Collection::max
  • ocicollsize — Pseudonim pentru OCI-Collection::size
  • ocicolltrim — Pseudonim pentru OCI-Collection::trim
  • ocicolumnisnull — Pseudonim pentru oci_field_is_null
  • ocicolumnname — Pseudonim pentru oci_field_name
  • ocicolumnprecision — Pseudonim pentru oci_field_precision
  • ocicolumnscale — Pseudonim pentru oci_field_scale
  • ocicolumnsize — Pseudonim pentru oci_field_size
  • ocicolumntype — Pseudonim pentru oci_field_type
  • ocicolumntyperaw — Pseudonim pentru oci_field_type_raw
  • ocicommit — Pseudonim pentru oci_commit
  • ocidefinebyname — Pseudonim pentru oci_define_by_name
  • ocierror — Pseudonim pentru oci_error
  • ociexecute — Pseudonim pentru oci_execute
  • ocifetch — Pseudonim pentru oci_fetch
  • ocifetchinto — Varianta învechita a oci_fetch_array, oci_fetch_object, oci_fetch_assoc ?i oci_fetch_row
  • ocifetchstatement — Pseudonim pentru oci_fetch_all
  • ocifreecollection — Pseudonim pentru OCI-Collection::free
  • ocifreecursor — Pseudonim pentru oci_free_statement
  • ocifreedesc — Pseudonim pentru OCI-Lob::free
  • ocifreestatement — Pseudonim pentru oci_free_statement
  • ociinternaldebug — Pseudonim pentru oci_internal_debug
  • ociloadlob — Pseudonim pentru OCI-Lob::load
  • ocilogoff — Pseudonim pentru oci_close
  • ocilogon — Pseudonim pentru oci_connect
  • ocinewcollection — Pseudonim pentru oci_new_collection
  • ocinewcursor — Pseudonim pentru oci_new_cursor
  • ocinewdescriptor — Pseudonim pentru oci_new_descriptor
  • ocinlogon — Pseudonim pentru oci_new_connect
  • ocinumcols — Pseudonim pentru oci_num_fields
  • ociparse — Pseudonim pentru oci_parse
  • ociplogon — Pseudonim pentru oci_pconnect
  • ociresult — Pseudonim pentru oci_result
  • ocirollback — Pseudonim pentru oci_rollback
  • ocirowcount — Pseudonim pentru oci_num_rows
  • ocisavelob — Pseudonim pentru OCI-Lob::save
  • ocisavelobfile — Pseudonim pentru OCI-Lob::import
  • ociserverversion — Pseudonim pentru oci_server_version
  • ocisetprefetch — Pseudonim pentru oci_set_prefetch
  • ocistatementtype — Pseudonim pentru oci_statement_type
  • ociwritelobtofile — Pseudonim pentru OCI-Lob::export
  • ociwritetemporarylob — Pseudonim pentru OCI-Lob::writeTemporary
OCI-Lob::writeToFile
ocibindbyname
OCI8


Pseudonim pentru oci_bind_by_name

Pseudonime ?i func?ii OCI8 învechite
ocicancel
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocibindbyname

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocibindbyname — Pseudonim pentru oci_bind_by_name()

Descrierea

Pseudonim pentru oci_bind_by_name()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

Pseudonime ?i func?ii OCI8 învechite
ocicancel
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_cancel

ocibindbyname
ocicloselob
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicancel

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicancel — Pseudonim pentru oci_cancel()

Descrierea

Pseudonim pentru oci_cancel()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocibindbyname
ocicloselob
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Lob::close

ocicancel
ocicollappend
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicloselob

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ocicloselob — Pseudonim pentru OCI-Lob::close()

Descrierea

Pseudonim pentru OCI-Lob::close()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicancel
ocicollappend
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Collection::append

ocicloselob
ocicollassign
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicollappend

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollappend — Pseudonim pentru OCI-Collection::append()

Descrierea

Pseudonim pentru OCI-Collection::append()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicloselob
ocicollassign
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Collection::assign

ocicollappend
ocicollassignelem
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicollassign

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ocicollassign — Pseudonim pentru OCI-Collection::assign()

Descrierea

Pseudonim pentru OCI-Collection::assign()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicollappend
ocicollassignelem
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Collection::assignElem

ocicollassign
ocicollgetelem
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicollassignelem

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollassignelem — Pseudonim pentru OCI-Collection::assignElem()

Descrierea

Pseudonim pentru OCI-Collection::assignElem()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicollassign
ocicollgetelem
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Collection::getElem

ocicollassignelem
ocicollmax
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicollgetelem

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollgetelem — Pseudonim pentru OCI-Collection::getElem()

Descrierea

Pseudonim pentru OCI-Collection::getElem()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicollassignelem
ocicollmax
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Collection::max

ocicollgetelem
ocicollsize
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicollmax

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollmax — Pseudonim pentru OCI-Collection::max()

Descrierea

Pseudonim pentru OCI-Collection::max()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicollgetelem
ocicollsize
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Collection::size

ocicollmax
ocicolltrim
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicollsize

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollsize — Pseudonim pentru OCI-Collection::size()

Descrierea

Pseudonim pentru OCI-Collection::size()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicollmax
ocicolltrim
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Collection::trim

ocicollsize
ocicolumnisnull
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicolltrim

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolltrim — Pseudonim pentru OCI-Collection::trim()

Descrierea

Pseudonim pentru OCI-Collection::trim()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicollsize
ocicolumnisnull
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_field_is_null

ocicolltrim
ocicolumnname
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicolumnisnull

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumnisnull — Pseudonim pentru oci_field_is_null()

Descrierea

Pseudonim pentru oci_field_is_null()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicolltrim
ocicolumnname
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_field_name

ocicolumnisnull
ocicolumnprecision
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicolumnname

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumnname — Pseudonim pentru oci_field_name()

Descrierea

Pseudonim pentru oci_field_name()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicolumnisnull
ocicolumnprecision
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_field_precision

ocicolumnname
ocicolumnscale
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicolumnprecision

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumnprecision — Pseudonim pentru oci_field_precision()

Descrierea

Pseudonim pentru oci_field_precision()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicolumnname
ocicolumnscale
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_field_scale

ocicolumnprecision
ocicolumnsize
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicolumnscale

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumnscale — Pseudonim pentru oci_field_scale()

Descrierea

Pseudonim pentru oci_field_scale()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicolumnprecision
ocicolumnsize
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_field_size

ocicolumnscale
ocicolumntype
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicolumnsize

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumnsize — Pseudonim pentru oci_field_size()

Descrierea

Pseudonim pentru oci_field_size()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicolumnscale
ocicolumntype
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_field_type

ocicolumnsize
ocicolumntyperaw
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicolumntype

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumntype — Pseudonim pentru oci_field_type()

Descrierea

Pseudonim pentru oci_field_type()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicolumnsize
ocicolumntyperaw
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_field_type_raw

ocicolumntype
ocicommit
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicolumntyperaw

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumntyperaw — Pseudonim pentru oci_field_type_raw()

Descrierea

Pseudonim pentru oci_field_type_raw()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicolumntype
ocicommit
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_commit

ocicolumntyperaw
ocidefinebyname
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocicommit

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicommit — Pseudonim pentru oci_commit()

Descrierea

Pseudonim pentru oci_commit()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicolumntyperaw
ocidefinebyname
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_define_by_name

ocicommit
ocierror
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocidefinebyname

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocidefinebyname — Pseudonim pentru oci_define_by_name()

Descrierea

Pseudonim pentru oci_define_by_name()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocicommit
ocierror
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_error

ocidefinebyname
ociexecute
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocierror

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocierror — Pseudonim pentru oci_error()

Descrierea

Pseudonim pentru oci_error()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocidefinebyname
ociexecute
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_execute

ocierror
ocifetch
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ociexecute

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociexecute — Pseudonim pentru oci_execute()

Descrierea

Pseudonim pentru oci_execute()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocierror
ocifetch
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_fetch

ociexecute
ocifetchinto
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocifetch

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifetch — Pseudonim pentru oci_fetch()

Descrierea

Pseudonim pentru oci_fetch()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ociexecute
ocifetchinto
Pseudonime ?i func?ii OCI8 învechite


Varianta învechita a oci_fetch_array, oci_fetch_object, oci_fetch_assoc ?i oci_fetch_row

ocifetch
ocifetchstatement
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocifetchinto

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifetchinto — Varianta învechita a oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() ?i oci_fetch_row()

Descrierea

Varianta învechita a oci_fetch_array(), oci_fetch_object(),
  oci_fetch_assoc() ?i
  oci_fetch_row()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocifetch
ocifetchstatement
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_fetch_all

ocifetchinto
ocifreecollection
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocifetchstatement

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifetchstatement — Pseudonim pentru oci_fetch_all()

Descrierea

Pseudonim pentru oci_fetch_all()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocifetchinto
ocifreecollection
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Collection::free

ocifetchstatement
ocifreecursor
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocifreecollection

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifreecollection — Pseudonim pentru OCI-Collection::free()

Descrierea

Pseudonim pentru OCI-Collection::free()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocifetchstatement
ocifreecursor
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_free_statement

ocifreecollection
ocifreedesc
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocifreecursor

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifreecursor — Pseudonim pentru oci_free_statement()

Descrierea

Pseudonim pentru oci_free_statement()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocifreecollection
ocifreedesc
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Lob::free

ocifreecursor
ocifreestatement
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocifreedesc

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifreedesc — Pseudonim pentru OCI-Lob::free()

Descrierea

Pseudonim pentru OCI-Lob::free()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocifreecursor
ocifreestatement
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_free_statement

ocifreedesc
ociinternaldebug
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocifreestatement

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifreestatement — Pseudonim pentru oci_free_statement()

Descrierea

Pseudonim pentru oci_free_statement()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocifreedesc
ociinternaldebug
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_internal_debug

ocifreestatement
ociloadlob
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ociinternaldebug

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociinternaldebug — Pseudonim pentru oci_internal_debug()

Descrierea

Pseudonim pentru oci_internal_debug()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocifreestatement
ociloadlob
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Lob::load

ociinternaldebug
ocilogoff
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ociloadlob

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociloadlob — Pseudonim pentru OCI-Lob::load()

Descrierea

Pseudonim pentru OCI-Lob::load()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ociinternaldebug
ocilogoff
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_close

ociloadlob
ocilogon
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocilogoff

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocilogoff — Pseudonim pentru oci_close()

Descrierea

Pseudonim pentru oci_close()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ociloadlob
ocilogon
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_connect

ocilogoff
ocinewcollection
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocilogon

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocilogon — Pseudonim pentru oci_connect()

Descrierea

Pseudonim pentru oci_connect()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocilogoff
ocinewcollection
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_new_collection

ocilogon
ocinewcursor
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocinewcollection

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocinewcollection — Pseudonim pentru oci_new_collection()

Descrierea

Pseudonim pentru oci_new_collection()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocilogon
ocinewcursor
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_new_cursor

ocinewcollection
ocinewdescriptor
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocinewcursor

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocinewcursor — Pseudonim pentru oci_new_cursor()

Descrierea

Pseudonim pentru oci_new_cursor()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocinewcollection
ocinewdescriptor
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_new_descriptor

ocinewcursor
ocinlogon
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocinewdescriptor

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocinewdescriptor — Pseudonim pentru oci_new_descriptor()

Descrierea

Pseudonim pentru oci_new_descriptor()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocinewcursor
ocinlogon
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_new_connect

ocinewdescriptor
ocinumcols
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocinlogon

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocinlogon — Pseudonim pentru oci_new_connect()

Descrierea

Pseudonim pentru oci_new_connect()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocinewdescriptor
ocinumcols
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_num_fields

ocinlogon
ociparse
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocinumcols

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocinumcols — Pseudonim pentru oci_num_fields()

Descrierea

Pseudonim pentru oci_num_fields()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocinlogon
ociparse
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_parse

ocinumcols
ociplogon
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ociparse

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociparse — Pseudonim pentru oci_parse()

Descrierea

Pseudonim pentru oci_parse()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocinumcols
ociplogon
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_pconnect

ociparse
ociresult
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ociplogon

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociplogon — Pseudonim pentru oci_pconnect()

Descrierea

Pseudonim pentru oci_pconnect()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ociparse
ociresult
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_result

ociplogon
ocirollback
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ociresult

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociresult — Pseudonim pentru oci_result()

Descrierea

Pseudonim pentru oci_result()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ociplogon
ocirollback
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_rollback

ociresult
ocirowcount
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocirollback

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocirollback — Pseudonim pentru oci_rollback()

Descrierea

Pseudonim pentru oci_rollback()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ociresult
ocirowcount
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_num_rows

ocirollback
ocisavelob
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocirowcount

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocirowcount — Pseudonim pentru oci_num_rows()

Descrierea

Pseudonim pentru oci_num_rows()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocirollback
ocisavelob
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Lob::save

ocirowcount
ocisavelobfile
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocisavelob

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocisavelob — Pseudonim pentru OCI-Lob::save()

Descrierea

Pseudonim pentru OCI-Lob::save()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocirowcount
ocisavelobfile
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Lob::import

ocisavelob
ociserverversion
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocisavelobfile

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocisavelobfile — Pseudonim pentru OCI-Lob::import()

Descrierea

Pseudonim pentru OCI-Lob::import()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocisavelob
ociserverversion
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_server_version

ocisavelobfile
ocisetprefetch
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ociserverversion

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociserverversion — Pseudonim pentru oci_server_version()

Descrierea

Pseudonim pentru oci_server_version()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocisavelobfile
ocisetprefetch
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_set_prefetch

ociserverversion
ocistatementtype
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocisetprefetch

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocisetprefetch — Pseudonim pentru oci_set_prefetch()

Descrierea

Pseudonim pentru oci_set_prefetch()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ociserverversion
ocistatementtype
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru oci_statement_type

ocisetprefetch
ociwritelobtofile
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ocistatementtype

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocistatementtype — Pseudonim pentru oci_statement_type()

Descrierea

Pseudonim pentru oci_statement_type()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocisetprefetch
ociwritelobtofile
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Lob::export

ocistatementtype
ociwritetemporarylob
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ociwritelobtofile

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociwritelobtofile — Pseudonim pentru OCI-Lob::export()

Descrierea

Pseudonim pentru OCI-Lob::export()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ocistatementtype
ociwritetemporarylob
Pseudonime ?i func?ii OCI8 învechite


Pseudonim pentru OCI-Lob::writeTemporary

ociwritelobtofile
Paradox
Pseudonime ?i func?ii OCI8 învechite
PHP Manual

ociwritetemporarylob

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ociwritetemporarylob — Pseudonim pentru OCI-Lob::writeTemporary()

Descrierea

Pseudonim pentru OCI-Lob::writeTemporary()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.4.0. Utilizarea acestui pseudonim este foarte nerecomandabila.

ociwritelobtofile
Paradox
Pseudonime ?i func?ii OCI8 învechite


Paradox File Access

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Paradox Func?ii
    • 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
ociwritetemporarylob
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

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.

Nota:

This module is also in development and may change, though major changes to the API are not expected.

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

Paradox
Instalarea / configurarea
Paradox


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Paradox


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/paradox

Asigura?i-va ca ave?i instalata biblioteca pxlib în prealabil. Daca instala?i pxlib dintr-un rpm sau un pachet debian, nu uita?i sa instala?i de asemenea ?i pachetele de dezvoltare.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

px_new() creates a new Paradox object required by all Paradox functions.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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

Tipurile resurselor
Paradox Func?ii
Paradox


Paradox Func?ii

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()

Cuprins

  • 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
Constante predefinite
px_close
Paradox


Closes a paradox database

Paradox Func?ii
px_create_fp
Paradox Func?ii
PHP Manual

px_close

(PECL paradox >= 1.0.0)

px_close — Closes a paradox database

Descrierea

bool px_close ( resource $pxdoc )

Closes the paradox database. This function will not close the file. You will have to call fclose() afterwards.

Parametri

pxdoc

Resource identifier of the paradox database as returned by px_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • px_open_fp() - Open paradox database
  • The example at px_new() - Create a new paradox object

Paradox Func?ii
px_create_fp
Paradox Func?ii


Create a new paradox database

px_close
px_date2string
Paradox Func?ii
PHP Manual

px_create_fp

(PECL paradox >= 1.0.0)

px_create_fp — Create a new paradox database

Descrierea

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.

Nota:

Calling this functions issues a warning about an empty tablename which can be safely ignored. Just set the tablename afterwards with px_set_parameter().

Nota:

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • px_new() - Create a new paradox object
  • px_put_record() - Stores record into paradox database
  • fopen() - Opens file or URL

px_close
px_date2string
Paradox Func?ii


Converts a date into a string.

px_create_fp
px_delete_record
Paradox Func?ii
PHP Manual

px_date2string

(PECL paradox >= 1.4.0)

px_date2string — Converts a date into a string.

Descrierea

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.

Parametri

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

7/15/1917
7/15/1917

A se vedea ?i

  • px_timestamp2string() - Converts the timestamp into a string.
  • jdtogregorian() - Converts Julian Day Count to Gregorian date

px_create_fp
px_delete_record
Paradox Func?ii


Deletes record from paradox database

px_date2string
px_delete
Paradox Func?ii
PHP Manual

px_delete_record

(PECL paradox >= 1.4.0)

px_delete_record — Deletes record from paradox database

Descrierea

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.

Nota:

This function is only available if pxlib >= 0.6.0 is used.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

px_date2string
px_delete
Paradox Func?ii


Deletes resource of paradox database

px_delete_record
px_get_field
Paradox Func?ii
PHP Manual

px_delete

(PECL paradox >= 1.0.0)

px_delete — Deletes resource of paradox database

Descrierea

bool px_delete ( resource $pxdoc )

Deletes the resource of the paradox file and frees all memory.

Parametri

pxdoc

Resource identifier of the paradox database as returned by px_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

px_delete_record
px_get_field
Paradox Func?ii


Returns the specification of a single field

px_delete
px_get_info
Paradox Func?ii
PHP Manual

px_get_field

(PECL paradox >= 1.0.0)

px_get_field — Returns the specification of a single field

Descrierea

array px_get_field ( resource $pxdoc , int $fieldno )

Parametri

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.

Valorile întoarse

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 Func?ii


Return lots of information about a paradox file

px_get_field
px_get_parameter
Paradox Func?ii
PHP Manual

px_get_info

(PECL paradox >= 1.0.0)

px_get_info — Return lots of information about a paradox file

Descrierea

array px_get_info ( resource $pxdoc )

Parametri

pxdoc

Resource identifier of the paradox database as returned by px_new().

Valorile întoarse

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().

A se vedea ?i

  • 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 Func?ii


Gets a parameter

px_get_info
px_get_record
Paradox Func?ii
PHP Manual

px_get_parameter

(PECL paradox >= 1.1.0)

px_get_parameter — Gets a parameter

Descrierea

string px_get_parameter ( resource $pxdoc , string $name )

Gets various parameters.

Parametri

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.

Valorile întoarse

Returns the value of the parameter sau FALSE în cazul e?ecului.

px_get_info
px_get_record
Paradox Func?ii


Returns record of paradox database

px_get_parameter
px_get_schema
Paradox Func?ii
PHP Manual

px_get_record

(PECL paradox >= 1.0.0)

px_get_record — Returns record of paradox database

Descrierea

array px_get_record ( resource $pxdoc , int $num [, int $mode = 0 ] )

Parametri

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.

Valorile întoarse

Returns the num'th record from the paradox database. The record is returned as an associated array with its keys being the field names.

A se vedea ?i

  • px_retrieve_record() - Returns record of paradox database

px_get_parameter
px_get_schema
Paradox Func?ii


Returns the database schema

px_get_record
px_get_value
Paradox Func?ii
PHP Manual

px_get_schema

(PECL paradox >= 1.0.0)

px_get_schema — Returns the database schema

Descrierea

array px_get_schema ( resource $pxdoc [, int $mode = 0 ] )

px_get_schema() returns the database schema.

Parametri

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.

Valorile întoarse

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 Func?ii


Gets a value

px_get_schema
px_insert_record
Paradox Func?ii
PHP Manual

px_get_value

(PECL paradox >= 1.1.0)

px_get_value — Gets a value

Descrierea

float px_get_value ( resource $pxdoc , string $name )

Gets various values.

Parametri

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.

Valorile întoarse

Returns the value of the parameter sau FALSE în cazul e?ecului.

px_get_schema
px_insert_record
Paradox Func?ii


Inserts record into paradox database

px_get_value
px_new
Paradox Func?ii
PHP Manual

px_insert_record

(PECL paradox >= 1.4.0)

px_insert_record — Inserts record into paradox database

Descrierea

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.

Nota:

This function is only available if pxlib >= 0.6.0 is used.

Parametri

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().

Valorile întoarse

Returns FALSE on failure or the record number in case of success.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

px_update_record() - Updates record in paradox database

px_get_value
px_new
Paradox Func?ii


Create a new paradox object

px_insert_record
px_numfields
Paradox Func?ii
PHP Manual

px_new

(PECL paradox >= 1.0.0)

px_new — Create a new paradox object

Descrierea

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.

Valorile întoarse

Returns FALSE on failure.

Exemple

Example #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.

Example #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);
?>

A se vedea ?i

  • px_delete() - Deletes resource of paradox database
  • px_open_fp() - Open paradox database

px_insert_record
px_numfields
Paradox Func?ii


Returns number of fields in a database

px_new
px_numrecords
Paradox Func?ii
PHP Manual

px_numfields

(PECL paradox >= 1.0.0)

px_numfields — Returns number of fields in a database

Descrierea

int px_numfields ( resource $pxdoc )

Get the number of fields in a database file.

Parametri

pxdoc

Resource identifier of the paradox database as returned by px_new().

Valorile întoarse

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 Func?ii


Returns number of records in a database

px_numfields
px_open_fp
Paradox Func?ii
PHP Manual

px_numrecords

(PECL paradox >= 1.0.0)

px_numrecords — Returns number of records in a database

Descrierea

int px_numrecords ( resource $pxdoc )

Get the number of records in a database file.

Parametri

pxdoc

Resource identifier of the paradox database as returned by px_new().

Valorile întoarse

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 Func?ii


Open paradox database

px_numrecords
px_put_record
Paradox Func?ii
PHP Manual

px_open_fp

(PECL paradox >= 1.0.0)

px_open_fp — Open paradox database

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fopen() - Opens file or URL
  • The example at px_new() - Create a new paradox object

px_numrecords
px_put_record
Paradox Func?ii


Stores record into paradox database

px_open_fp
px_retrieve_record
Paradox Func?ii
PHP Manual

px_put_record

(PECL paradox >= 1.0.0)

px_put_record — Stores record into paradox database

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

px_open_fp
px_retrieve_record
Paradox Func?ii


Returns record of paradox database

px_put_record
px_set_blob_file
Paradox Func?ii
PHP Manual

px_retrieve_record

(PECL paradox >= 1.4.0)

px_retrieve_record — Returns record of paradox database

Descrierea

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.

Nota:

This function is only available if pxlib >= 0.6.0 is used.

Parametri

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.

Valorile întoarse

Returns the num'th record from the paradox database. The record is returned as an associated array with its keys being the field names.

A se vedea ?i

  • px_get_record() - Returns record of paradox database

px_put_record
px_set_blob_file
Paradox Func?ii


Sets the file where blobs are read from

px_retrieve_record
px_set_parameter
Paradox Func?ii
PHP Manual

px_set_blob_file

(PECL paradox >= 1.3.0)

px_set_blob_file — Sets the file where blobs are read from

Descrierea

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.

Parametri

pxdoc

Resource identifier of the paradox database as returned by px_new().

filename

The name of the file. Its extension should be .MB.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

px_retrieve_record
px_set_parameter
Paradox Func?ii


Sets a parameter

px_set_blob_file
px_set_tablename
Paradox Func?ii
PHP Manual

px_set_parameter

(PECL paradox >= 1.1.0)

px_set_parameter — Sets a parameter

Descrierea

bool px_set_parameter ( resource $pxdoc , string $name , string $value )

Sets various parameters.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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 Func?ii


Sets the name of a table (deprecated)

px_set_parameter
px_set_targetencoding
Paradox Func?ii
PHP Manual

px_set_tablename

(PECL paradox >= 1.0.0)

px_set_tablename — Sets the name of a table (deprecated)

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns NULL on success sau FALSE în cazul e?ecului.

A se vedea ?i

px_set_parameter() - Sets a parameter

px_set_parameter
px_set_targetencoding
Paradox Func?ii


Sets the encoding for character fields (deprecated)

px_set_tablename
px_set_value
Paradox Func?ii
PHP Manual

px_set_targetencoding

(PECL paradox >= 1.0.0)

px_set_targetencoding — Sets the encoding for character fields (deprecated)

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

px_set_parameter() - Sets a parameter

px_set_tablename
px_set_value
Paradox Func?ii


Sets a value

px_set_targetencoding
px_timestamp2string
Paradox Func?ii
PHP Manual

px_set_value

(PECL paradox >= 1.1.0)

px_set_value — Sets a value

Descrierea

bool px_set_value ( resource $pxdoc , string $name , float $value )

Sets various values.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

px_set_parameter() - Sets a parameter

px_set_targetencoding
px_timestamp2string
Paradox Func?ii


Converts the timestamp into a string.

px_set_value
px_update_record
Paradox Func?ii
PHP Manual

px_timestamp2string

(PECL paradox >= 1.4.0)

px_timestamp2string — Converts the timestamp into a string.

Descrierea

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.

Parametri

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • px_date2string() - Converts a date into a string.
  • jdtogregorian() - Converts Julian Day Count to Gregorian date

px_set_value
px_update_record
Paradox Func?ii


Updates record in paradox database

px_timestamp2string
PostgreSQL
Paradox Func?ii
PHP Manual

px_update_record

(PECL paradox >= 1.4.0)

px_update_record — Updates record in paradox database

Descrierea

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.

Nota:

This function is only available if pxlib >= 0.6.0 is used.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

px_insert_record() - Inserts record into paradox database

px_timestamp2string
PostgreSQL
Paradox Func?ii


PostgreSQL

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic usage
  • PostgreSQL Func?ii
    • pg_affected_rows — Returns number of affected records (tuples)
    • pg_cancel_query — Cancel an asynchronous query
    • pg_client_encoding — Gets the client encoding
    • pg_close — Closes a PostgreSQL connection
    • pg_connect_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt.
    • pg_connect — Open a PostgreSQL connection
    • pg_connection_busy — Get connection is busy or not
    • pg_connection_reset — Reset connection (reconnect)
    • pg_connection_status — Get connection status
    • pg_consume_input — Reads input on the connection
    • pg_convert — Convert associative array values into suitable for SQL statement
    • pg_copy_from — Insert records into a table from an array
    • pg_copy_to — Copy a table to an array
    • pg_dbname — Get the database name
    • pg_delete — Deletes records
    • pg_end_copy — Sync with PostgreSQL backend
    • pg_escape_bytea — Escape a string for insertion into a bytea field
    • 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 — Escape a string for query
    • 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 — Fetch a row as an array
    • pg_fetch_assoc — Fetch a row as an associative array
    • pg_fetch_object — Fetch a row as an object
    • pg_fetch_result — Returns values from a result resource
    • pg_fetch_row — Get a row as an enumerated array
    • pg_field_is_null — Test if a field is SQL NULL
    • pg_field_name — Returns the name of a field
    • pg_field_num — Returns the field number of the named field
    • pg_field_prtlen — Returns the printed length
    • pg_field_size — Returns the internal storage size of the named field
    • 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 — Returns the type name for the corresponding field number
    • pg_flush — Flush outbound query data on the connection
    • pg_free_result — Free result memory
    • pg_get_notify — Gets SQL NOTIFY message
    • pg_get_pid — Gets the backend's process ID
    • pg_get_result — Get asynchronous query result
    • pg_host — Returns the host name associated with the connection
    • pg_insert — Insert array into table
    • pg_last_error — Get the last error message string of a connection
    • pg_last_notice — Returns the last notice message from PostgreSQL server
    • pg_last_oid — Returns the last row's OID
    • pg_lo_close — Close a large object
    • pg_lo_create — Create a large object
    • pg_lo_export — Export a large object to file
    • pg_lo_import — Import a large object from file
    • pg_lo_open — Open a large object
    • pg_lo_read_all — Reads an entire large object and send straight to browser
    • pg_lo_read — Read a large object
    • pg_lo_seek — Seeks position within a large object
    • pg_lo_tell — Returns current seek position a of large object
    • pg_lo_truncate — Truncates a large object
    • pg_lo_unlink — Delete a large object
    • pg_lo_write — Write to a large object
    • pg_meta_data — Get meta data for table
    • pg_num_fields — Returns the number of fields in a result
    • pg_num_rows — Returns the number of rows in a result
    • pg_options — Get the options associated with the connection
    • pg_parameter_status — Looks up a current parameter setting of the server.
    • pg_pconnect — Open a persistent PostgreSQL connection
    • pg_ping — Ping database connection
    • pg_port — Return the port number associated with the connection
    • pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion.
    • pg_put_line — Send a NULL-terminated string to PostgreSQL backend
    • 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 — Execute a query
    • pg_result_error_field — Returns an individual field of an error report.
    • pg_result_error — Get error message associated with result
    • pg_result_seek — Set internal row offset in result resource
    • pg_result_status — Get status of query result
    • pg_select — Select records
    • 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 — Sends asynchronous query
    • pg_set_client_encoding — Set the client encoding
    • pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error and pg_result_error.
    • pg_socket — Get a read only handle to the socket underlying a PostgreSQL connection
    • pg_trace — Enable tracing a PostgreSQL connection
    • pg_transaction_status — Returns the current in-transaction status of the server.
    • pg_tty — Return the TTY name associated with the connection
    • pg_unescape_bytea — Unescape binary for bytea type
    • pg_untrace — Disable tracing of a PostgreSQL connection
    • pg_update — Update table
    • pg_version — Returns an array with client, protocol and server version (when available)
px_update_record
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

PostgreSQL database is an Open Source product and available without cost. Postgres, developed originally in the UC Berkeley Computer Science Department, pioneered many of the object-relational concepts now becoming available in some commercial databases. It provides SQL92/SQL99 language support, transactions, referential integrity, stored procedures and type extensibility. PostgreSQL is an open source descendant of this original Berkeley code.

PostgreSQL
Instalarea / configurarea
PostgreSQL


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
PostgreSQL


Necesita?i

To use PostgreSQL support, you need PostgreSQL 6.5 or later, PostgreSQL 8.0 or later to enable all PostgreSQL module features. PostgreSQL supports many character encodings including multibyte character encoding. The current version and more information about PostgreSQL is available at » http://www.postgresql.org/ and the » PostgreSQL Documentation.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

In order to enable PostgreSQL support, --with-pgsql[=DIR] is required when you compile PHP. DIR is the PostgreSQL base install directory, defaults to /usr/local/pgsql. If shared object module is available, PostgreSQL module may be loaded using extension directive in php.ini or dl() function.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

PostgreSQL configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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 | 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.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

pgsql.allow_persistent boolean

Whether to allow persistent Postgres connections.

pgsql.max_persistent integer

The maximum number of persistent Postgres connections per process.

pgsql.max_links integer

The maximum number of Postgres connections per process, including persistent connections.

pgsql.auto_reset_persistent integer

Detect broken persistent links with pg_pconnect(). Needs a little overhead.

pgsql.ignore_notice integer

Whether or not to ignore PostgreSQL backend notices.

pgsql.log_notice integer

Whether or not to log PostgreSQL backends notice messages. The PHP directive pgsql.ignore_notice must be off in order to log notice messages.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

There are two resource types used in the PostgreSQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

PGSQL_LIBPQ_VERSION (string)
Short libpq version that contains only numbers and dots.
PGSQL_LIBPQ_VERSION_STR (string)
Long libpq version that includes compiler information.
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_CONNECT_ASYNC (integer)
Passed to pg_connect() to create an asynchronous connection. Added in PHP 5.6.0.
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.
PGSQL_DML_NO_CONV (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). All parameters passed as is. Manual escape is required if parameters contain user supplied data. Use pg_escape_string() for it.
PGSQL_DML_EXEC (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Execute query by these functions.
PGSQL_DML_ASYNC (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Execute asynchronous query by these functions.
PGSQL_DML_STRING (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Return executed query string.
PGSQL_DML_ESCAPE (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Apply escape to all parameters instead of calling pg_convert() internally. This option omits meta data look up. Query could be as fast as pg_query() and pg_send_query().
PGSQL_POLLING_FAILED (integer)
Returned by pg_connect_poll() to indicate that the connection attempt failed.
PGSQL_POLLING_READING (integer)
Returned by pg_connect_poll() to indicate that the connection is waiting for the PostgreSQL socket to be readable.
PGSQL_POLLING_WRITING (integer)
Returned by pg_connect_poll() to indicate that the connection is waiting for the PostgreSQL socket to be writable.
PGSQL_POLLING_OK (integer)
Returned by pg_connect_poll() to indicate that the connection is ready to be used.
PGSQL_POLLING_ACTIVE (integer)
Returned by pg_connect_poll() to indicate that the connection is currently active.
Tipurile resurselor
Exemple
PostgreSQL


Exemple

Cuprins

  • Basic usage
Constante predefinite
Basic usage
PostgreSQL


Basic usage

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a PostgreSQL database.

Example #1 PostgreSQL extension overview example

<?php
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo")
    or die('Could not connect: ' . pg_last_error());

// Performing SQL query
$query = 'SELECT * FROM authors';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());

// Printing results in 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";

// Free resultset
pg_free_result($result);

// Closing connection
pg_close($dbconn);
?>

Exemple
PostgreSQL Func?ii
Exemple


PostgreSQL Func?ii

Note

Nota:

Not all functions are supported by all builds. It depends on your libpq (The PostgreSQL C client library) version and how libpq is compiled. If PHP PostgreSQL extensions are missing, then it is because your libpq version does not support them.

Nota:

Most PostgreSQL functions accept connection as the optional first parameter. If it is not provided, the last opened connection is used. If it doesn't exist, functions return FALSE.

Nota:

PostgreSQL automatically folds all identifiers (e.g. table/column names) to lower-case values at object creation time and at query time. To force the use of mixed or upper case identifiers, you must escape the identifier using double quotes ("").

Nota:

PostgreSQL does not have special commands for fetching database schema information (eg. all the tables in the current database). Instead, there is a standard schema named information_schema in PostgreSQL 7.4 and above containing system views with all the necessary information, in an easily queryable form. See the » PostgreSQL Documentation for full details.

Cuprins

  • pg_affected_rows — Returns number of affected records (tuples)
  • pg_cancel_query — Cancel an asynchronous query
  • pg_client_encoding — Gets the client encoding
  • pg_close — Closes a PostgreSQL connection
  • pg_connect_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt.
  • pg_connect — Open a PostgreSQL connection
  • pg_connection_busy — Get connection is busy or not
  • pg_connection_reset — Reset connection (reconnect)
  • pg_connection_status — Get connection status
  • pg_consume_input — Reads input on the connection
  • pg_convert — Convert associative array values into suitable for SQL statement
  • pg_copy_from — Insert records into a table from an array
  • pg_copy_to — Copy a table to an array
  • pg_dbname — Get the database name
  • pg_delete — Deletes records
  • pg_end_copy — Sync with PostgreSQL backend
  • pg_escape_bytea — Escape a string for insertion into a bytea field
  • 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 — Escape a string for query
  • 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 — Fetch a row as an array
  • pg_fetch_assoc — Fetch a row as an associative array
  • pg_fetch_object — Fetch a row as an object
  • pg_fetch_result — Returns values from a result resource
  • pg_fetch_row — Get a row as an enumerated array
  • pg_field_is_null — Test if a field is SQL NULL
  • pg_field_name — Returns the name of a field
  • pg_field_num — Returns the field number of the named field
  • pg_field_prtlen — Returns the printed length
  • pg_field_size — Returns the internal storage size of the named field
  • 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 — Returns the type name for the corresponding field number
  • pg_flush — Flush outbound query data on the connection
  • pg_free_result — Free result memory
  • pg_get_notify — Gets SQL NOTIFY message
  • pg_get_pid — Gets the backend's process ID
  • pg_get_result — Get asynchronous query result
  • pg_host — Returns the host name associated with the connection
  • pg_insert — Insert array into table
  • pg_last_error — Get the last error message string of a connection
  • pg_last_notice — Returns the last notice message from PostgreSQL server
  • pg_last_oid — Returns the last row's OID
  • pg_lo_close — Close a large object
  • pg_lo_create — Create a large object
  • pg_lo_export — Export a large object to file
  • pg_lo_import — Import a large object from file
  • pg_lo_open — Open a large object
  • pg_lo_read_all — Reads an entire large object and send straight to browser
  • pg_lo_read — Read a large object
  • pg_lo_seek — Seeks position within a large object
  • pg_lo_tell — Returns current seek position a of large object
  • pg_lo_truncate — Truncates a large object
  • pg_lo_unlink — Delete a large object
  • pg_lo_write — Write to a large object
  • pg_meta_data — Get meta data for table
  • pg_num_fields — Returns the number of fields in a result
  • pg_num_rows — Returns the number of rows in a result
  • pg_options — Get the options associated with the connection
  • pg_parameter_status — Looks up a current parameter setting of the server.
  • pg_pconnect — Open a persistent PostgreSQL connection
  • pg_ping — Ping database connection
  • pg_port — Return the port number associated with the connection
  • pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion.
  • pg_put_line — Send a NULL-terminated string to PostgreSQL backend
  • 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 — Execute a query
  • pg_result_error_field — Returns an individual field of an error report.
  • pg_result_error — Get error message associated with result
  • pg_result_seek — Set internal row offset in result resource
  • pg_result_status — Get status of query result
  • pg_select — Select records
  • 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 — Sends asynchronous query
  • pg_set_client_encoding — Set the client encoding
  • pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error and pg_result_error.
  • pg_socket — Get a read only handle to the socket underlying a PostgreSQL connection
  • pg_trace — Enable tracing a PostgreSQL connection
  • pg_transaction_status — Returns the current in-transaction status of the server.
  • pg_tty — Return the TTY name associated with the connection
  • pg_unescape_bytea — Unescape binary for bytea type
  • pg_untrace — Disable tracing of a PostgreSQL connection
  • pg_update — Update table
  • pg_version — Returns an array with client, protocol and server version (when available)
Basic usage
pg_affected_rows
PostgreSQL


Returns number of affected records (tuples)

PostgreSQL Func?ii
pg_cancel_query
PostgreSQL Func?ii
PHP Manual

pg_affected_rows

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_affected_rows — Returns number of affected records (tuples)

Descrierea

int pg_affected_rows ( resource $result )

pg_affected_rows() returns the number of tuples (instances/records/rows) affected by INSERT, UPDATE, and DELETE queries.

Since PostgreSQL 9.0 and above, the server returns the number of SELECTed rows. Older PostgreSQL return 0 for SELECT.

Nota:

This function used to be called pg_cmdtuples().

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Valorile întoarse

The number of rows affected by the query. If no tuple is affected, it will return 0.

Exemple

Example #1 pg_affected_rows() example

<?php
$result = pg_query($conn, "INSERT INTO authors VALUES ('Orwell', 2002, 'Animal Farm')");

$cmdtuples = pg_affected_rows($result);

echo $cmdtuples . " tuples are affected.\n";
?>

Exemplul de mai sus va afi?a:

1 tuples are affected.

A se vedea ?i

  • pg_query() - Execute a query
  • 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() - Returns the number of rows in a result

PostgreSQL Func?ii
pg_cancel_query
PostgreSQL Func?ii


Cancel an asynchronous query

pg_affected_rows
pg_client_encoding
PostgreSQL Func?ii
PHP Manual

pg_cancel_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_cancel_query — Cancel an asynchronous query

Descrierea

bool pg_cancel_query ( resource $connection )

pg_cancel_query() cancels an asynchronous query sent with pg_send_query(), pg_send_query_params() or pg_send_execute(). You cannot cancel a query executed using pg_query().

Parametri

connection

PostgreSQL database connection resource.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_cancel_query() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
  }

  $res1 = pg_get_result($dbconn);
  echo "First call to pg_get_result(): $res1\n";
  $rows1 = pg_num_rows($res1);
  echo "$res1 has $rows1 records\n\n";

  // Cancel the currently running query.  Will be the second query if it is
  // still running.
  pg_cancel_query($dbconn);
?>

Exemplul de mai sus va afi?a:

First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records

A se vedea ?i

  • pg_send_query() - Sends asynchronous query
  • pg_connection_busy() - Get connection is busy or not

pg_affected_rows
pg_client_encoding
PostgreSQL Func?ii


Gets the client encoding

pg_cancel_query
pg_close
PostgreSQL Func?ii
PHP Manual

pg_client_encoding

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pg_client_encoding — Gets the client encoding

Descrierea

string pg_client_encoding ([ resource $connection ] )

PostgreSQL supports automatic character set conversion between server and client for certain character sets. pg_client_encoding() returns the client encoding as a string. The returned string will be one of the standard PostgreSQL encoding identifiers.

Nota:

This function requires PHP 4.0.3 or higher and PostgreSQL 7.0 or higher. If libpq is compiled without multibyte encoding support, pg_client_encoding() always returns SQL_ASCII. Supported encoding depends on PostgreSQL version. Refer to the PostgreSQL Documentation supported encodings.

The function used to be called pg_clientencoding().

Parametri

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().

Valorile întoarse

The client encoding, or FALSE on error.

Exemple

Example #1 pg_client_encoding() example

<?php
// Assume $conn is a connection to a ISO-8859-1 database
$encoding = pg_client_encoding($conn);

echo "Client encoding is: ", $encoding, "\n";
?>

Exemplul de mai sus va afi?a:

Client encoding is: ISO-8859-1

A se vedea ?i

  • pg_set_client_encoding() - Set the client encoding

pg_cancel_query
pg_close
PostgreSQL Func?ii


Closes a PostgreSQL connection

pg_client_encoding
pg_connect_poll
PostgreSQL Func?ii
PHP Manual

pg_close

(PHP 4, PHP 5, PHP 7)

pg_close — Closes a PostgreSQL connection

Descrierea

bool pg_close ([ resource $connection ] )

pg_close() closes the non-persistent connection to a PostgreSQL database associated with the given connection resource.

Nota:

Using pg_close() is not usually necessary, as non-persistent open connections are automatically closed at the end of the script.

If there is open large object resource on the connection, do not close the connection before closing all large object resources.

Parametri

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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_close() example

<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=mary")
   or die("Could not connect");
echo "Connected successfully";
pg_close($dbconn);
?>

Exemplul de mai sus va afi?a:

Connected successfully

A se vedea ?i

  • pg_connect() - Open a PostgreSQL connection

pg_client_encoding
pg_connect_poll
PostgreSQL Func?ii


Poll the status of an in-progress asynchronous PostgreSQL connection attempt.

pg_close
pg_connect
PostgreSQL Func?ii
PHP Manual

pg_connect_poll

(PHP 5 >= 5.6.0, PHP 7)

pg_connect_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt.

Descrierea

int pg_connect_poll ([ resource $connection ] )

pg_connect_poll() polls the status of a PostgreSQL connection created by calling pg_connect() with the PGSQL_CONNECT_ASYNC option.

Parametri

connection

PostgreSQL database connection resource.

Valorile întoarse

Returns PGSQL_POLLING_FAILED, PGSQL_POLLING_READING, PGSQL_POLLING_WRITING, PGSQL_POLLING_OK, or PGSQL_POLLING_ACTIVE.

pg_close
pg_connect
PostgreSQL Func?ii


Open a PostgreSQL connection

pg_connect_poll
pg_connection_busy
PostgreSQL Func?ii
PHP Manual

pg_connect

(PHP 4, PHP 5, PHP 7)

pg_connect — Open a PostgreSQL connection

Descrierea

resource pg_connect ( string $connection_string [, int $connect_type ] )

pg_connect() opens a connection to a PostgreSQL database specified by the connection_string.

If a second call is made to pg_connect() with the same connection_string as an existing connection, the existing connection will be returned unless you pass PGSQL_CONNECT_FORCE_NEW as connect_type.

The old syntax with multiple parameters $conn = pg_connect("host", "port", "options", "tty", "dbname") has been deprecated.

Parametri

connection_string

The connection_string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form keyword = value. Spaces around the equal sign are optional. To write an empty value or a value containing spaces, surround it with single quotes, e.g., keyword = 'a value'. Single quotes and backslashes within the value must be escaped with a backslash, i.e., \' and \\.

The currently recognized parameter keywords are: host, hostaddr, port, dbname (defaults to value of user), user, password, connect_timeout, options, tty (ignored), sslmode, requiressl (deprecated in favor of sslmode), and service. Which of these arguments exist depends on your PostgreSQL version.

The options parameter can be used to set command line parameters to be invoked by the server.

connect_type

If PGSQL_CONNECT_FORCE_NEW is passed, then a new connection is created, even if the connection_string is identical to an existing connection.

If PGSQL_CONNECT_ASYNC is given, then the connection is established asynchronously. The state of the connection can then be checked via pg_connect_poll() or pg_connection_status().

Valorile întoarse

PostgreSQL connection resource on success, FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Support for giving the PGSQL_CONNECT_ASYNC constant as the connect_type was added.

Exemple

Example #1 Using pg_connect()

<?php
$dbconn = pg_connect("dbname=mary");
//connect to a database named "mary"

$dbconn2 = pg_connect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"

$dbconn3 = pg_connect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password

$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_connect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password

$dbconn5 = pg_connect("host=localhost options='--client_encoding=UTF8'");
//connect to a database on "localhost" and set the command line parameter which tells the encoding is in UTF-8
?>

A se vedea ?i

  • pg_pconnect() - Open a persistent PostgreSQL connection
  • pg_close() - Closes a PostgreSQL connection
  • pg_host() - Returns the host name associated with the connection
  • pg_port() - Return the port number associated with the connection
  • pg_tty() - Return the TTY name associated with the connection
  • pg_options() - Get the options associated with the connection
  • pg_dbname() - Get the database name

pg_connect_poll
pg_connection_busy
PostgreSQL Func?ii


Get connection is busy or not

pg_connect
pg_connection_reset
PostgreSQL Func?ii
PHP Manual

pg_connection_busy

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_connection_busy — Get connection is busy or not

Descrierea

bool pg_connection_busy ( resource $connection )

pg_connection_busy() determines whether or not a connection is busy. If it is busy, a previous query is still executing. If pg_get_result() is used on the connection, it will be blocked.

Parametri

connection

PostgreSQL database connection resource.

Valorile întoarse

Returns TRUE if the connection is busy, FALSE otherwise.

Exemple

Example #1 pg_connection_busy() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $bs = pg_connection_busy($dbconn);
  if ($bs) {
      echo 'connection is busy';
  } else {
     echo 'connection is not busy';
  }
?>

A se vedea ?i

  • pg_connection_status() - Get connection status
  • pg_get_result() - Get asynchronous query result

pg_connect
pg_connection_reset
PostgreSQL Func?ii


Reset connection (reconnect)

pg_connection_busy
pg_connection_status
PostgreSQL Func?ii
PHP Manual

pg_connection_reset

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_connection_reset — Reset connection (reconnect)

Descrierea

bool pg_connection_reset ( resource $connection )

pg_connection_reset() resets the connection. It is useful for error recovery.

Parametri

connection

PostgreSQL database connection resource.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_connection_reset() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $dbconn2 = pg_connection_reset($dbconn);
  if ($dbconn2) {
      echo "reset successful\n";
  } else {
      echo "reset failed\n";
  }
?>

A se vedea ?i

  • pg_connect() - Open a PostgreSQL connection
  • pg_pconnect() - Open a persistent PostgreSQL connection
  • pg_connection_status() - Get connection status

pg_connection_busy
pg_connection_status
PostgreSQL Func?ii


Get connection status

pg_connection_reset
pg_consume_input
PostgreSQL Func?ii
PHP Manual

pg_connection_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_connection_status — Get connection status

Descrierea

int pg_connection_status ( resource $connection )

pg_connection_status() returns the status of the specified connection.

Parametri

connection

PostgreSQL database connection resource.

Valorile întoarse

PGSQL_CONNECTION_OK or PGSQL_CONNECTION_BAD.

Exemple

Example #1 pg_connection_status() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $stat = pg_connection_status($dbconn);
  if ($stat === PGSQL_CONNECTION_OK) {
      echo 'Connection status ok';
  } else {
      echo 'Connection status bad';
  }
?>

A se vedea ?i

  • pg_connection_busy() - Get connection is busy or not

pg_connection_reset
pg_consume_input
PostgreSQL Func?ii


Reads input on the connection

pg_connection_status
pg_convert
PostgreSQL Func?ii
PHP Manual

pg_consume_input

(PHP 5 >= 5.6.0, PHP 7)

pg_consume_input — Reads input on the connection

Descrierea

bool pg_consume_input ( resource $connection )

pg_consume_input() consumes any input waiting to be read from the database server.

Parametri

connection

PostgreSQL database connection resource.

Valorile întoarse

TRUE if no error occurred, or FALSE if there was an error. Note that TRUE does not necessarily indicate that input was waiting to be read.

pg_connection_status
pg_convert
PostgreSQL Func?ii


Convert associative array values into suitable for SQL statement

pg_consume_input
pg_copy_from
PostgreSQL Func?ii
PHP Manual

pg_convert

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_convert — Convert associative array values into suitable for SQL statement

Descrierea

array pg_convert ( resource $connection , string $table_name , array $assoc_array [, int $options = 0 ] )

pg_convert() checks and converts the values in assoc_array into suitable values for use in an SQL statement. Precondition for pg_convert() is the existence of a table table_name which has at least as many columns as assoc_array has elements. The fieldnames in table_name must match the indices in assoc_array and the corresponding datatypes must be compatible. Returns an array with the converted values on success, FALSE otherwise.

Nota:

Since PHP 5.6.0, it accepts boolean values. It converted to PostgreSQL boolean. String representations of boolean value is also supported. NULL is converted to PostgreSQL NULL.

Prior to PHP 5.6.0, if there are boolean fields in table_name don't use the constant TRUE in assoc_array. It will be converted to the string 'TRUE' which is no valid entry for boolean fields in PostgreSQL. Use one of t, true, 1, y, yes instead.

Parametri

connection

PostgreSQL database connection resource.

table_name

Name of the table against which to convert types.

assoc_array

Data to be converted.

options

Any number of PGSQL_CONV_IGNORE_DEFAULT, PGSQL_CONV_FORCE_NULL or PGSQL_CONV_IGNORE_NOT_NULL, combined.

Valorile întoarse

An array of converted values, or FALSE on error.

Exemple

Example #1 pg_convert() example

<?php
  $dbconn = pg_connect('dbname=foo');

  $tmp = array(
      'author' => 'Joe Thackery',
      'year' => 2005,
      'title' => 'My Life, by Joe Thackery'
  );

  $vals = pg_convert($dbconn, 'authors', $tmp);
?>

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | No longer experimental. Boolean/NULL data types are supported. Unknown/unsupported data types are escaped without validation. pg_convert() could be used with any data types.

A se vedea ?i

  • pg_meta_data() - Get meta data for table
  • pg_insert() - Insert array into table
  • pg_select() - Select records
  • pg_update() - Update table
  • pg_delete() - Deletes records

pg_consume_input
pg_copy_from
PostgreSQL Func?ii


Insert records into a table from an array

pg_convert
pg_copy_to
PostgreSQL Func?ii
PHP Manual

pg_copy_from

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_copy_from — Insert records into a table from an array

Descrierea

bool pg_copy_from ( resource $connection , string $table_name , array $rows [, string $delimiter [, string $null_as ]] )

pg_copy_from() inserts records into a table from rows. It issues a COPY FROM SQL command internally to insert records.

Parametri

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to copy the rows.

rows

An array of data to be copied into table_name. Each value in rows becomes a row in table_name. Each value in rows should be a delimited string of the values to insert into each field. Values should be linefeed terminated.

delimiter

The token that separates values for each field in each element of rows. Default is TAB.

null_as

How SQL NULL values are represented in the rows. Default is \N ("\\N").

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_copy_from() example

<?php
   $db = pg_connect("dbname=publisher") or die("Could not connect");

   $rows = pg_copy_to($db, $table_name);

   pg_query($db, "DELETE FROM $table_name");

   pg_copy_from($db, $table_name, $rows);
?>

A se vedea ?i

  • pg_copy_to() - Copy a table to an array

pg_convert
pg_copy_to
PostgreSQL Func?ii


Copy a table to an array

pg_copy_from
pg_dbname
PostgreSQL Func?ii
PHP Manual

pg_copy_to

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_copy_to — Copy a table to an array

Descrierea

array pg_copy_to ( resource $connection , string $table_name [, string $delimiter [, string $null_as ]] )

pg_copy_to() copies a table to an array. It issues COPY TO SQL command internally to retrieve records.

Parametri

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to copy the data into rows.

delimiter

The token that separates values for each field in each element of rows. Default is TAB.

null_as

How SQL NULL values are represented in the rows. Default is \N ("\\N").

Valorile întoarse

An array with one element for each line of COPY data. It returns FALSE on failure.

Exemple

Example #1 pg_copy_to() example

<?php
   $db = pg_connect("dbname=publisher") or die("Could not connect");

   $rows = pg_copy_to($db, $table_name);

   pg_query($db, "DELETE FROM $table_name");

   pg_copy_from($db, $table_name, $rows);
?>

A se vedea ?i

  • pg_copy_from() - Insert records into a table from an array

pg_copy_from
pg_dbname
PostgreSQL Func?ii


Get the database name

pg_copy_to
pg_delete
PostgreSQL Func?ii
PHP Manual

pg_dbname

(PHP 4, PHP 5, PHP 7)

pg_dbname — Get the database name

Descrierea

string pg_dbname ([ resource $connection ] )

pg_dbname() returns the name of the database that the given PostgreSQL connection resource.

Parametri

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().

Valorile întoarse

A string containing the name of the database the connection is to, or FALSE on error.

Exemple

Example #1 pg_dbname() example

<?php
  error_reporting(E_ALL);

  pg_connect("host=localhost port=5432 dbname=mary");
  echo pg_dbname(); // mary
?>

pg_copy_to
pg_delete
PostgreSQL Func?ii


Deletes records

pg_dbname
pg_end_copy
PostgreSQL Func?ii
PHP Manual

pg_delete

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_delete — Deletes records

Descrierea

mixed pg_delete ( resource $connection , string $table_name , array $assoc_array [, int $options = PGSQL_DML_EXEC ] )

pg_delete() deletes records from a table specified by the keys and values in assoc_array. If options is specified, pg_convert() is applied to assoc_array with the specified options.

Parametri

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to delete rows.

assoc_array

An array whose keys are field names in the table table_name, and whose values are the values of those fields that are to be deleted.

options

Any number of PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_ESCAPE, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned. When PGSQL_DML_NO_CONV or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Returns string if PGSQL_DML_STRING is passed via options.

Exemple

Example #1 pg_delete() example

<?php
  $db = pg_connect('dbname=foo');
  // This is safe, since $_POST is converted automatically
  $res = pg_delete($db, 'post_log', $_POST);
  if ($res) {
      echo "POST data is deleted: $res\n";
  } else {
      echo "User must have sent wrong inputs\n";
  }
?>

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

A se vedea ?i

  • pg_convert() - Convert associative array values into suitable for SQL statement

pg_dbname
pg_end_copy
PostgreSQL Func?ii


Sync with PostgreSQL backend

pg_delete
pg_escape_bytea
PostgreSQL Func?ii
PHP Manual

pg_end_copy

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pg_end_copy — Sync with PostgreSQL backend

Descrierea

bool pg_end_copy ([ resource $connection ] )

pg_end_copy() syncs the PostgreSQL frontend (usually a web server process) with the PostgreSQL server after doing a copy operation performed by pg_put_line(). pg_end_copy() must be issued, otherwise the PostgreSQL server may get out of sync with the frontend and will report an error.

Parametri

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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_end_copy() example

<?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);
?>

A se vedea ?i

  • pg_put_line() - Send a NULL-terminated string to PostgreSQL backend

pg_delete
pg_escape_bytea
PostgreSQL Func?ii


Escape a string for insertion into a bytea field

pg_end_copy
pg_escape_identifier
PostgreSQL Func?ii
PHP Manual

pg_escape_bytea

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_escape_bytea — Escape a string for insertion into a bytea field

Descrierea

string pg_escape_bytea ([ resource $connection ], string $data )

pg_escape_bytea() escapes string for bytea datatype. It returns escaped string.

Nota:

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.

Parametri

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 or binary data to be inserted into a bytea column.

Valorile întoarse

A string containing the escaped data.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | connection added

Exemple

Example #1 pg_escape_bytea() example

<?php
  // Connect to the database
  $dbconn = pg_connect('dbname=foo');

  // Read in a binary file
  $data = file_get_contents('image1.jpg');

  // Escape the binary data
  $escaped = pg_escape_bytea($data);

  // Insert it into the database
  pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', '{$escaped}')");
?>

A se vedea ?i

  • pg_unescape_bytea() - Unescape binary for bytea type
  • pg_escape_string() - Escape a string for query

pg_end_copy
pg_escape_identifier
PostgreSQL Func?ii


Escape a identifier for insertion into a text field

pg_escape_bytea
pg_escape_literal
PostgreSQL Func?ii
PHP Manual

pg_escape_identifier

(PHP 5 >= 5.4.4, PHP 7)

pg_escape_identifier — Escape a identifier for insertion into a text field

Descrierea

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() must be used. For bytea type fields, pg_escape_bytea() must be used instead.

Nota:

This function has internal escape code and can also be used with PostgreSQL 8.4 or less.

Parametri

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.

Valorile întoarse

A string containing the escaped data.

Exemple

Example #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};");
?>

A se vedea ?i

  • pg_escape_literal() - Escape a literal for insertion into a text field
  • pg_escape_bytea() - Escape a string for insertion into a bytea field
  • pg_escape_string() - Escape a string for query

pg_escape_bytea
pg_escape_literal
PostgreSQL Func?ii


Escape a literal for insertion into a text field

pg_escape_identifier
pg_escape_string
PostgreSQL Func?ii
PHP Manual

pg_escape_literal

(PHP 5 >= 5.4.4, PHP 7)

pg_escape_literal — Escape a literal for insertion into a text field

Descrierea

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.

Nota:

This function has internal escape code and can also be used with PostgreSQL 8.4 or less.

Parametri

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(). When there is no default connection, it raises E_WARNING and returns FALSE.

data

A string containing text to be escaped.

Valorile întoarse

A string containing the escaped data.

Exemple

Example #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})");
?>

A se vedea ?i

  • pg_escape_identifier() - Escape a identifier for insertion into a text field
  • pg_escape_bytea() - Escape a string for insertion into a bytea field
  • pg_escape_string() - Escape a string for query

pg_escape_identifier
pg_escape_string
PostgreSQL Func?ii


Escape a string for query

pg_escape_literal
pg_execute
PostgreSQL Func?ii
PHP Manual

pg_escape_string

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_escape_string — Escape a string for query

Descrierea

string pg_escape_string ([ resource $connection ], string $data )

pg_escape_string() escapes a string for querying the database. It returns an escaped string in the PostgreSQL format without quotes. pg_escape_literal() is more preferred way to escape SQL parameters for PostgreSQL. addslashes() must not be used with PostgreSQL. If the type of the column is bytea, pg_escape_bytea() must be used instead. pg_escape_identifier() must be used to escape identifiers (e.g. table names, field names)

Nota:

This function requires PostgreSQL 7.2 or later.

Parametri

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.

Valorile întoarse

A string containing the escaped data.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | connection added

Exemple

Example #1 pg_escape_string() 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_string($data);

  // Insert it into the database
  pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', '{$escaped}')");
?>

A se vedea ?i

  • pg_escape_bytea() - Escape a string for insertion into a bytea field

pg_escape_literal
pg_execute
PostgreSQL Func?ii


Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_escape_string
pg_fetch_all_columns
PostgreSQL Func?ii
PHP Manual

pg_execute

(PHP 5 >= 5.1.0, PHP 7)

pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result.

Descrierea

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.

Parametri

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.

Avertizare

Elements are converted to strings by calling this function.

Valorile întoarse

A query result resource on success sau FALSE în cazul e?ecului.

Exemple

Example #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"));

?>

A se vedea ?i

  • 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
PostgreSQL Func?ii


Fetches all rows in a particular result column as an array

pg_execute
pg_fetch_all
PostgreSQL Func?ii
PHP Manual

pg_fetch_all_columns

(PHP 5 >= 5.1.0, PHP 7)

pg_fetch_all_columns — Fetches all rows in a particular result column as an array

Descrierea

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.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #1 pg_fetch_all_columns() example

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

// Get an array of all author names
$arr = pg_fetch_all_columns($result, 1);

var_dump($arr);

?>

A se vedea ?i

  • pg_fetch_all() - Fetches all rows from a result as an array

pg_execute
pg_fetch_all
PostgreSQL Func?ii


Fetches all rows from a result as an array

pg_fetch_all_columns
pg_fetch_array
PostgreSQL Func?ii
PHP Manual

pg_fetch_all

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_fetch_all — Fetches all rows from a result as an array

Descrierea

array pg_fetch_all ( resource $result )

pg_fetch_all() returns an array that contains all rows (records) in the result resource.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Valorile întoarse

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.

Exemple

Example #1 PostgreSQL fetch all

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
    echo "An error occurred.\n";
    exit;
}

$result = pg_query($conn, "SELECT * FROM authors");
if (!$result) {
    echo "An error occurred.\n";
    exit;
}

$arr = pg_fetch_all($result);

print_r($arr);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Fred
        )

    [1] => Array
        (
            [id] => 2
            [name] => Bob
        )

)

A se vedea ?i

  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

pg_fetch_all_columns
pg_fetch_array
PostgreSQL Func?ii


Fetch a row as an array

pg_fetch_all
pg_fetch_assoc
PostgreSQL Func?ii
PHP Manual

pg_fetch_array

(PHP 4, PHP 5, PHP 7)

pg_fetch_array — Fetch a row as an array

Descrierea

array pg_fetch_array ( resource $result [, int $row [, int $result_type = PGSQL_BOTH ]] )

pg_fetch_array() returns an array that corresponds to the fetched row (record).

pg_fetch_array() is an extended version of pg_fetch_row(). In addition to storing the data in the numeric indices (field number) to the result array, it can also store the data using associative indices (field name). It stores both indicies by default.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

pg_fetch_array() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.

Parametri

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.

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_fetch_array() 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.

Valorile întoarse

An array indexed numerically (beginning with 0) or associatively (indexed by field name), or both. 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.

Exemple

Example #1 pg_fetch_array() example

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

$arr = pg_fetch_array($result, 0, PGSQL_NUM);
echo $arr[0] . " <- Row 1 Author\n";
echo $arr[1] . " <- Row 1 E-mail\n";

// The row parameter is optional; NULL can be passed instead,
// to pass a result_type.  Successive calls to pg_fetch_array
// will return the next row.
$arr = pg_fetch_array($result, NULL, PGSQL_ASSOC);
echo $arr["author"] . " <- Row 2 Author\n";
echo $arr["email"] . " <- Row 2 E-mail\n";

$arr = pg_fetch_array($result);
echo $arr["author"] . " <- Row 3 Author\n";
echo $arr[1] . " <- Row 3 E-mail\n";

?>

A se vedea ?i

  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

pg_fetch_all
pg_fetch_assoc
PostgreSQL Func?ii


Fetch a row as an associative array

pg_fetch_array
pg_fetch_object
PostgreSQL Func?ii
PHP Manual

pg_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_fetch_assoc — Fetch a row as an associative array

Descrierea

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().

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

pg_fetch_assoc() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #1 pg_fetch_assoc() example

<?php
$conn = pg_connect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

$result = pg_query($conn, "SELECT id, author, email FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

while ($row = pg_fetch_assoc($result)) {
  echo $row['id'];
  echo $row['author'];
  echo $row['email'];
}
?>

A se vedea ?i

  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

pg_fetch_array
pg_fetch_object
PostgreSQL Func?ii


Fetch a row as an object

pg_fetch_assoc
pg_fetch_result
PostgreSQL Func?ii
PHP Manual

pg_fetch_object

(PHP 4, PHP 5, PHP 7)

pg_fetch_object — Fetch a row as an object

Descrierea

object pg_fetch_object ( resource $result [, int $row [, int $result_type = PGSQL_ASSOC ]] )
object pg_fetch_object ( resource $result [, int $row [, string $class_name [, array $params ]]] )

pg_fetch_object() returns an object with properties that correspond to the fetched row's field names. It can optionally instantiate an object of a specific class, and pass parameters to that class's constructor.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

Speed-wise, the function is identical to pg_fetch_array(), and almost as fast as pg_fetch_row() (the difference is insignificant).

Parametri

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.

result_type

Ignored and deprecated.

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.

Valorile întoarse

An object with one attribute for each field name in the result. 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.

Exemple

Example #1 pg_fetch_object() example

<?php

$database = "store";

$db_conn = pg_connect("host=localhost port=5432 dbname=$database");
if (!$db_conn) {
  echo "Failed connecting to postgres database $database\n";
  exit;
}

$qu = pg_query($db_conn, "SELECT * FROM books ORDER BY author");

while ($data = pg_fetch_object($qu)) {
  echo $data->author . " (";
  echo $data->year . "): ";
  echo $data->title . "<br />";
}

pg_free_result($qu);
pg_close($db_conn);

?>

A se vedea ?i

  • pg_query() - Execute a query
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_assoc() - Fetch a row as an associative array
  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_result() - Returns values from a result resource

pg_fetch_assoc
pg_fetch_result
PostgreSQL Func?ii


Returns values from a result resource

pg_fetch_object
pg_fetch_row
PostgreSQL Func?ii
PHP Manual

pg_fetch_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_fetch_result — Returns values from a result resource

Descrierea

string pg_fetch_result ( resource $result , int $row , mixed $field )
string pg_fetch_result ( resource $result , mixed $field )

pg_fetch_result() returns the value of a particular row and field (column) in a PostgreSQL result resource.

Nota:

This function used to be called pg_result().

Parametri

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, next row is fetched.

field

A string representing the name of the field (column) to fetch, otherwise an int representing the field number to fetch. Fields are numbered from 0 upwards.

Valorile întoarse

Boolean is returned as "t" or "f". All other types, including arrays are returned as strings formatted in the same default PostgreSQL manner that you would see in the psql program. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, or on any other error.

Exemple

Example #1 pg_fetch_result() example

<?php
$db = pg_connect("dbname=users user=me") || die();

$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");

$val = pg_fetch_result($res, 1, 0);

echo "First field in the second row is: ", $val, "\n";
?>

Exemplul de mai sus va afi?a:

First field in the second row is: 2

A se vedea ?i

  • pg_query() - Execute a query
  • pg_fetch_array() - Fetch a row as an array

pg_fetch_object
pg_fetch_row
PostgreSQL Func?ii


Get a row as an enumerated array

pg_fetch_result
pg_field_is_null
PostgreSQL Func?ii
PHP Manual

pg_fetch_row

(PHP 4, PHP 5, PHP 7)

pg_fetch_row — Get a row as an enumerated array

Descrierea

array pg_fetch_row ( resource $result [, int $row ] )

pg_fetch_row() fetches one row of data from the result associated with the specified result resource.

Nota: Aceasta func?ie stabile?te câmpurile NULL la valoarea PHP NULL.

Parametri

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.

Valorile întoarse

An array, indexed from 0 upwards, with each value 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.

Exemple

Example #1 pg_fetch_row() example

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}

?>

A se vedea ?i

  • pg_query() - Execute a query
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

pg_fetch_result
pg_field_is_null
PostgreSQL Func?ii


Test if a field is SQL NULL

pg_fetch_row
pg_field_name
PostgreSQL Func?ii
PHP Manual

pg_field_is_null

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_is_null — Test if a field is SQL NULL

Descrierea

int pg_field_is_null ( resource $result , int $row , mixed $field )
int pg_field_is_null ( resource $result , mixed $field )

pg_field_is_null() tests if a field in a PostgreSQL result resource is SQL NULL or not.

Nota:

This function used to be called pg_fieldisnull().

Parametri

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, current row is fetched.

field

Field number (starting from 0) as an integer or the field name as a string.

Valorile întoarse

Returns 1 if the field in the given row is SQL NULL, 0 if not. FALSE is returned if the row is out of range, or upon any other error.

Exemple

Example #1 pg_field_is_null() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die ("Could not connect");
  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  if ($res) {
      if (pg_field_is_null($res, 0, "year") == 1) {
          echo "The value of the field year is null.\n";
      }
      if (pg_field_is_null($res, 0, "year") == 0) {
          echo "The value of the field year is not null.\n";
    }
 }
?>

pg_fetch_row
pg_field_name
PostgreSQL Func?ii


Returns the name of a field

pg_field_is_null
pg_field_num
PostgreSQL Func?ii
PHP Manual

pg_field_name

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_name — Returns the name of a field

Descrierea

string pg_field_name ( resource $result , int $field_number )

pg_field_name() returns the name of the field occupying the given field_number in the given PostgreSQL result resource. Field numbering starts from 0.

Nota:

This function used to be called pg_fieldname().

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Valorile întoarse

The field name, or FALSE on error.

Exemple

Example #1 Getting information about fields

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  $i = pg_num_fields($res);
  for ($j = 0; $j < $i; $j++) {
      echo "column $j\n";
      $fieldname = pg_field_name($res, $j);
      echo "fieldname: $fieldname\n";
      echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
      echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
      echo "field type: " . pg_field_type($res, $j) . " \n\n";
  }
?>

Exemplul de mai sus va afi?a:

column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar

column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2

column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar

A se vedea ?i

  • pg_field_num() - Returns the field number of the named field

pg_field_is_null
pg_field_num
PostgreSQL Func?ii


Returns the field number of the named field

pg_field_name
pg_field_prtlen
PostgreSQL Func?ii
PHP Manual

pg_field_num

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_num — Returns the field number of the named field

Descrierea

int pg_field_num ( resource $result , string $field_name )

pg_field_num() will return the number of the field number that corresponds to the field_name in the given PostgreSQL result resource.

Nota:

This function used to be called pg_fieldnum().

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_name

The name of the field.

Valorile întoarse

The field number (numbered from 0), or -1 on error.

Exemple

Example #1 Getting information about fields

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select author, year, title from authors where author = 'Orwell'");

  echo "Column 'title' is field number: ", pg_field_num($res, 'title');
?>

Exemplul de mai sus va afi?a:

Column 'title' is field number: 2

A se vedea ?i

  • pg_field_name() - Returns the name of a field

pg_field_name
pg_field_prtlen
PostgreSQL Func?ii


Returns the printed length

pg_field_num
pg_field_size
PostgreSQL Func?ii
PHP Manual

pg_field_prtlen

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_prtlen — Returns the printed length

Descrierea

int pg_field_prtlen ( resource $result , int $row_number , mixed $field_name_or_number )
int pg_field_prtlen ( resource $result , mixed $field_name_or_number )

pg_field_prtlen() returns the actual printed length (number of characters) of a specific value in a PostgreSQL result. Row numbering starts at 0. This function will return FALSE on an error.

field_name_or_number can be passed either as an integer or as a string. If it is passed as an integer, PHP recognises it as the field number, otherwise as field name.

See the example given at the pg_field_name() page.

Nota:

This function used to be called pg_fieldprtlen().

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result. Rows are numbered from 0 upwards. If omitted, current row is fetched.

Valorile întoarse

The field printed length, or FALSE on error.

Exemple

Example #1 Getting information about fields

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  $i = pg_num_fields($res);
  for ($j = 0; $j < $i; $j++) {
      echo "column $j\n";
      $fieldname = pg_field_name($res, $j);
      echo "fieldname: $fieldname\n";
      echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
      echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
      echo "field type: " . pg_field_type($res, $j) . " \n\n";
  }
?>

Exemplul de mai sus va afi?a:

column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar

column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2

column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar

A se vedea ?i

  • pg_field_size() - Returns the internal storage size of the named field

pg_field_num
pg_field_size
PostgreSQL Func?ii


Returns the internal storage size of the named field

pg_field_prtlen
pg_field_table
PostgreSQL Func?ii
PHP Manual

pg_field_size

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_size — Returns the internal storage size of the named field

Descrierea

int pg_field_size ( resource $result , int $field_number )

pg_field_size() returns the internal storage size (in bytes) of the field number in the given PostgreSQL result.

Nota:

This function used to be called pg_fieldsize().

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Valorile întoarse

The internal field storage size (in bytes). -1 indicates a variable length field. FALSE is returned on error.

Exemple

Example #1 Getting information about fields

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  $i = pg_num_fields($res);
  for ($j = 0; $j < $i; $j++) {
      echo "column $j\n";
      $fieldname = pg_field_name($res, $j);
      echo "fieldname: $fieldname\n";
      echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
      echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
      echo "field type: " . pg_field_type($res, $j) . " \n\n";
  }
?>

Exemplul de mai sus va afi?a:

column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar

column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2

column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar

A se vedea ?i

  • pg_field_prtlen() - Returns the printed length
  • pg_field_type() - Returns the type name for the corresponding field number

pg_field_prtlen
pg_field_table
PostgreSQL Func?ii


Returns the name or oid of the tables field

pg_field_size
pg_field_type_oid
PostgreSQL Func?ii
PHP Manual

pg_field_table

(PHP 5 >= 5.2.0, PHP 7)

pg_field_table — Returns the name or oid of the tables field

Descrierea

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.

Parametri

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.

Valorile întoarse

On success either the fields table name or oid. Or, FALSE on failure.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

foo
14379580

bool(false)

Note

Nota:

Returning the oid is much faster than returning the table name because fetching the table name requires a query to the database system table.

A se vedea ?i

  • pg_field_name() - Returns the name of a field
  • pg_field_type() - Returns the type name for the corresponding field number

pg_field_size
pg_field_type_oid
PostgreSQL Func?ii


Returns the type ID (OID) for the corresponding field number

pg_field_table
pg_field_type
PostgreSQL Func?ii
PHP Manual

pg_field_type_oid

(PHP 5 >= 5.1.0, PHP 7)

pg_field_type_oid — Returns the type ID (OID) for the corresponding field number

Descrierea

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.

Nota:

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.

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Valorile întoarse

The OID of the field's base type. FALSE is returned on error.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

Title field type OID: 1043

A se vedea ?i

  • pg_field_type() - Returns the type name for the corresponding field number
  • pg_field_prtlen() - Returns the printed length
  • pg_field_name() - Returns the name of a field

pg_field_table
pg_field_type
PostgreSQL Func?ii


Returns the type name for the corresponding field number

pg_field_type_oid
pg_flush
PostgreSQL Func?ii
PHP Manual

pg_field_type

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_type — Returns the type name for the corresponding field number

Descrierea

string pg_field_type ( resource $result , int $field_number )

pg_field_type() returns a string containing the base type name of the given field_number in the given PostgreSQL result resource.

Nota:

If the field uses a PostgreSQL domain (rather than a basic type), it is the name of the domain's underlying type that is returned, rather than the name of the domain itself.

Nota:

This function used to be called pg_fieldtype().

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Valorile întoarse

A string containing the base name of the field's type, or FALSE on error.

Exemple

Example #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: ", pg_field_type($res, 0);
?>

Exemplul de mai sus va afi?a:

Title field type: varchar

A se vedea ?i

  • pg_field_prtlen() - Returns the printed length
  • pg_field_name() - Returns the name of a field
  • pg_field_type_oid() - Returns the type ID (OID) for the corresponding field number

pg_field_type_oid
pg_flush
PostgreSQL Func?ii


Flush outbound query data on the connection

pg_field_type
pg_free_result
PostgreSQL Func?ii
PHP Manual

pg_flush

(PHP 5 >= 5.6.0, PHP 7)

pg_flush — Flush outbound query data on the connection

Descrierea

mixed pg_flush ( resource $connection )

pg_flush() flushes any outbound query data waiting to be sent on the connection.

Parametri

connection

PostgreSQL database connection resource.

Valorile întoarse

Returns TRUE if the flush was successful or no data was waiting to be flushed, 0 if part of the pending data was flushed but more remains sau FALSE în cazul e?ecului.

pg_field_type
pg_free_result
PostgreSQL Func?ii


Free result memory

pg_flush
pg_get_notify
PostgreSQL Func?ii
PHP Manual

pg_free_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_free_result — Free result memory

Descrierea

bool pg_free_result ( resource $result )

pg_free_result() frees the memory and data associated with the specified PostgreSQL query result resource.

This function need only be called if memory consumption during script execution is a problem. Otherwise, all result memory will be automatically freed when the script ends.

Nota:

This function used to be called pg_freeresult().

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_free_result() example

<?php
$db = pg_connect("dbname=users user=me") || die();

$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");

$val = pg_fetch_result($res, 1, 0);

echo "First field in the second row is: ", $val, "\n";

pg_free_result($res);
?>

Exemplul de mai sus va afi?a:

First field in the second row is: 2

A se vedea ?i

  • pg_query() - Execute a query
  • 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_flush
pg_get_notify
PostgreSQL Func?ii


Gets SQL NOTIFY message

pg_free_result
pg_get_pid
PostgreSQL Func?ii
PHP Manual

pg_get_notify

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_get_notify — Gets SQL NOTIFY message

Descrierea

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.

Parametri

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.

Valorile întoarse

An array containing the NOTIFY message name and backend PID. As of PHP 5.4.0 and if supported by the server, the array also contains the server version and the payload. Otherwise if no NOTIFY is waiting, then FALSE is returned.

Exemple

Example #1 PostgreSQL NOTIFY message

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\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);
}
?>

A se vedea ?i

  • pg_get_pid() - Gets the backend's process ID

pg_free_result
pg_get_pid
PostgreSQL Func?ii


Gets the backend's process ID

pg_get_notify
pg_get_result
PostgreSQL Func?ii
PHP Manual

pg_get_pid

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_get_pid — Gets the backend's process ID

Descrierea

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.

Parametri

connection

PostgreSQL database connection resource.

Valorile întoarse

The backend database process ID.

Exemple

Example #1 PostgreSQL backend PID

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

// Backend process PID. Use PID with pg_get_notify()
$pid = pg_get_pid($conn);
?>

A se vedea ?i

  • pg_get_notify() - Gets SQL NOTIFY message

pg_get_notify
pg_get_result
PostgreSQL Func?ii


Get asynchronous query result

pg_get_pid
pg_host
PostgreSQL Func?ii
PHP Manual

pg_get_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_get_result — Get asynchronous query result

Descrierea

resource pg_get_result ([ resource $connection ] )

pg_get_result() gets the result resource from an asynchronous query executed by pg_send_query(), pg_send_query_params() or pg_send_execute().

pg_send_query() and the other asynchronous query functions can send multiple queries to a PostgreSQL server and pg_get_result() is used to get each query's results, one by one.

Parametri

connection

PostgreSQL database connection resource.

Valorile întoarse

The result resource, or FALSE if no more results are available.

Exemple

Example #1 pg_get_result() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
  }

  $res1 = pg_get_result($dbconn);
  echo "First call to pg_get_result(): $res1\n";
  $rows1 = pg_num_rows($res1);
  echo "$res1 has $rows1 records\n\n";

  $res2 = pg_get_result($dbconn);
  echo "Second call to pg_get_result(): $res2\n";
  $rows2 = pg_num_rows($res2);
  echo "$res2 has $rows2 records\n";
?>

Exemplul de mai sus va afi?a:

First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records

Second call to pg_get_result(): Resource id #4
Resource id #4 has 1 records

A se vedea ?i

  • pg_send_query() - Sends asynchronous query

pg_get_pid
pg_host
PostgreSQL Func?ii


Returns the host name associated with the connection

pg_get_result
pg_insert
PostgreSQL Func?ii
PHP Manual

pg_host

(PHP 4, PHP 5, PHP 7)

pg_host — Returns the host name associated with the connection

Descrierea

string pg_host ([ resource $connection ] )

pg_host() returns the host name of the given PostgreSQL connection resource is connected to.

Parametri

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().

Valorile întoarse

A string containing the name of the host the connection is to, or FALSE on error.

Exemple

Example #1 pg_host() example

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   print "Successfully connected to: " . pg_host($pgsql_conn) . "<br/>\n";
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?>

A se vedea ?i

  • pg_connect() - Open a PostgreSQL connection
  • pg_pconnect() - Open a persistent PostgreSQL connection

pg_get_result
pg_insert
PostgreSQL Func?ii


Insert array into table

pg_host
pg_last_error
PostgreSQL Func?ii
PHP Manual

pg_insert

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_insert — Insert array into table

Descrierea

mixed pg_insert ( resource $connection , string $table_name , array $assoc_array [, int $options = PGSQL_DML_EXEC ] )

pg_insert() inserts the values of assoc_array into the table specified by table_name. If options is specified, pg_convert() is applied to assoc_array with the specified options.

Parametri

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to insert rows. The table table_name must at least have as many columns as assoc_array has elements.

assoc_array

An array whose keys are field names in the table table_name, and whose values are the values of those fields that are to be inserted.

options

Any number of PGSQL_CONV_OPTS, PGSQL_DML_NO_CONV, PGSQL_DML_ESCAPE, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned. When PGSQL_DML_NO_CONV or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.

Valorile întoarse

Returns the connection resource on success, sau FALSE în cazul e?ecului. Returns string if PGSQL_DML_STRING is passed via options.

Exemple

Example #1 pg_insert() example

<?php
  $dbconn = pg_connect('dbname=foo');
  // This is safe, since $_POST is converted automatically
  $res = pg_insert($dbconn, 'post_log', $_POST);
  if ($res) {
      echo "POST data is successfully logged\n";
  } else {
      echo "User must have sent wrong inputs\n";
  }
?>

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Unless PGSQL_DML_STRING is passed, the function now returns the connection resource instead of TRUE on success.
5.6.0 | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

A se vedea ?i

  • pg_convert() - Convert associative array values into suitable for SQL statement

pg_host
pg_last_error
PostgreSQL Func?ii


Get the last error message string of a connection

pg_insert
pg_last_notice
PostgreSQL Func?ii
PHP Manual

pg_last_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_last_error — Get the last error message string of a connection

Descrierea

string pg_last_error ([ resource $connection ] )

pg_last_error() returns the last error message for a given connection.

Error messages may be overwritten by internal PostgreSQL (libpq) function calls. It may not return an appropriate error message if multiple errors occur inside a PostgreSQL module function.

Use pg_result_error(), pg_result_error_field(),
pg_result_status() and
pg_connection_status() for better error handling.

Nota:

This function used to be called pg_errormessage().

Parametri

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().

Valorile întoarse

A string containing the last error message on the given connection, or FALSE on error.

Exemple

Example #1 pg_last_error() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Query that fails
  $res = pg_query($dbconn, "select * from doesnotexist");

  echo pg_last_error($dbconn);
?>

A se vedea ?i

  • pg_result_error() - Get error message associated with result
  • pg_result_error_field() - Returns an individual field of an error report.

pg_insert
pg_last_notice
PostgreSQL Func?ii


Returns the last notice message from PostgreSQL server

pg_last_error
pg_last_oid
PostgreSQL Func?ii
PHP Manual

pg_last_notice

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

pg_last_notice — Returns the last notice message from PostgreSQL server

Descrierea

string pg_last_notice ( resource $connection )

pg_last_notice() returns the last notice message from the PostgreSQL server on the specified connection. The PostgreSQL server sends notice messages in several cases, for instance when creating a SERIAL column in a table.

With pg_last_notice(), you can avoid issuing useless queries by checking whether or not the notice is related to your transaction.

Notice message tracking can be set to optional by setting 1 for pgsql.ignore_notice in php.ini.

Notice message logging can be set to optional by setting 0 for pgsql.log_notice in php.ini. Unless pgsql.ignore_notice is set to 0, notice message cannot be logged.

Parametri

connection

PostgreSQL database connection resource.

Valorile întoarse

A string containing the last notice on the given connection, or FALSE on error.

Exemple

Example #1 pg_last_notice() example

<?php
  $pgsql_conn = pg_connect("dbname=mark host=localhost");

  $res = pg_query("CREATE TABLE test (id SERIAL)");

  $notice = pg_last_notice($pgsql_conn);

  echo $notice;
?>

Exemplul de mai sus va afi?a:

CREATE TABLE will create implicit sequence "test_id_seq" for "serial" column "test.id"

A se vedea ?i

  • pg_query() - Execute a query
  • pg_last_error() - Get the last error message string of a connection

pg_last_error
pg_last_oid
PostgreSQL Func?ii


Returns the last row's OID

pg_last_notice
pg_lo_close
PostgreSQL Func?ii
PHP Manual

pg_last_oid

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_last_oid — Returns the last row's OID

Descrierea

string pg_last_oid ( resource $result )

pg_last_oid() is used to retrieve the OID assigned to an inserted row.

OID field became an optional field from PostgreSQL 7.2 and will not be present by default in PostgreSQL 8.1. When the OID field is not present in a table, the programmer must use pg_result_status() to check for successful insertion.

To get the value of a SERIAL field in an inserted row, it is necessary to use the PostgreSQL CURRVAL function, naming the sequence whose last value is required. If the name of the sequence is unknown, the pg_get_serial_sequence PostgreSQL 8.0 function is necessary.

PostgreSQL 8.1 has a function LASTVAL that returns the value of the most recently used sequence in the session. This avoids the need for naming the sequence, table or column altogether.

Nota:

This function used to be called pg_getlastoid().

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Valorile întoarse

A string containing the OID assigned to the most recently inserted row in the specified connection, or FALSE on error or no available OID.

Exemple

Example #1 pg_last_oid() example

<?php
  // Connect to the database
  pg_connect("dbname=mark host=localhost");

  // Create a sample table
  pg_query("CREATE TABLE test (a INTEGER) WITH OIDS");

  // Insert some data into it
  $res = pg_query("INSERT INTO test VALUES (1)");

  $oid = pg_last_oid($res);
?>

A se vedea ?i

  • pg_query() - Execute a query
  • pg_result_status() - Get status of query result

pg_last_notice
pg_lo_close
PostgreSQL Func?ii


Close a large object

pg_last_oid
pg_lo_create
PostgreSQL Func?ii
PHP Manual

pg_lo_close

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_close — Close a large object

Descrierea

bool pg_lo_close ( resource $large_object )

pg_lo_close() closes a large object. large_object is a resource for the large object from pg_lo_open().

To use the large object interface, it is necessary to enclose it within a transaction block.

Nota:

This function used to be called pg_loclose().

Parametri

result

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_lo_close() example

<?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_create($database);
   echo "$oid\n";
   $handle = pg_lo_open($database, $oid, "w");
   echo "$handle\n";
   pg_lo_write($handle, "large object data");
   pg_lo_close($handle);
   pg_query($database, "commit");
?>

A se vedea ?i

  • pg_lo_open() - Open a large object
  • pg_lo_create() - Create a large object
  • pg_lo_import() - Import a large object from file

pg_last_oid
pg_lo_create
PostgreSQL Func?ii


Create a large object

pg_lo_close
pg_lo_export
PostgreSQL Func?ii
PHP Manual

pg_lo_create

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_create — Create a large object

Descrierea

int pg_lo_create ([ resource $connection [, mixed $object_id ]] )
int pg_lo_create ( mixed $object_id )

pg_lo_create() creates a large object and returns the OID of the large object. PostgreSQL access modes INV_READ, INV_WRITE, and INV_ARCHIVE are not supported, the object is created always with both read and write access. INV_ARCHIVE has been removed from PostgreSQL itself (version 6.3 and above).

To use the large object interface, it is necessary to enclose it within a transaction block.

Instead of using the large object interface (which has no access controls and is cumbersome to use), try PostgreSQL's bytea column type and pg_escape_bytea().

Nota:

This function used to be called pg_locreate().

Parametri

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().

object_id

If an object_id is given the function will try to create a large object with this id, else a free object id is assigned by the server. The parameter was added in PHP 5.3 and relies on functionality that first appeared in PostgreSQL 8.1.

Valorile întoarse

A large object OID or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | The optional object_id was added.

Exemple

Example #1 pg_lo_create() example

<?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_create($database);
   echo "$oid\n";
   $handle = pg_lo_open($database, $oid, "w");
   echo "$handle\n";
   pg_lo_write($handle, "large object data");
   pg_lo_close($handle);
   pg_query($database, "commit");
?>

pg_lo_close
pg_lo_export
PostgreSQL Func?ii


Export a large object to file

pg_lo_create
pg_lo_import
PostgreSQL Func?ii
PHP Manual

pg_lo_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_export — Export a large object to file

Descrierea

bool pg_lo_export ([ resource $connection ], int $oid , string $pathname )

pg_lo_export() takes a large object in a PostgreSQL database and saves its contents to a file on the local filesystem.

To use the large object interface, it is necessary to enclose it within a transaction block.

Nota:

This function used to be called pg_loexport().

Parametri

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().

oid

The OID of the large object in the database.

pathname

The full path and file name of the file in which to write the large object on the client filesystem.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_lo_export() example

<?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_create($database);
   $handle = pg_lo_open($database, $oid, "w");
   pg_lo_write($handle, "large object data");
   pg_lo_close($handle);
   pg_lo_export($database, $oid, '/tmp/lob.dat');
   pg_query($database, "commit");
?>

A se vedea ?i

  • pg_lo_import() - Import a large object from file

pg_lo_create
pg_lo_import
PostgreSQL Func?ii


Import a large object from file

pg_lo_export
pg_lo_open
PostgreSQL Func?ii
PHP Manual

pg_lo_import

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_import — Import a large object from file

Descrierea

int pg_lo_import ([ resource $connection ], string $pathname [, mixed $object_id ] )

pg_lo_import() creates a new large object in the database using a file on the filesystem as its data source.

To use the large object interface, it is necessary to enclose it within a transaction block.

Nota: Când este activat modul securizat, PHP verifica daca fi?ierele ?i directoarele cu care se va opera au acela?i UID (proprietar) ca ?i script-ul care se executa.

Nota:

This function used to be called pg_loimport().

Parametri

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().

pathname

The full path and file name of the file on the client filesystem from which to read the large object data.

object_id

If an object_id is given the function will try to create a large object with this id, else a free object id is assigned by the server. The parameter was added in PHP 5.3 and relies on functionality that first appeared in PostgreSQL 8.1.

Valorile întoarse

The OID of the newly created large object, or FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | The optional object_id was added.

Exemple

Example #1 pg_lo_import() example

<?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_import($database, '/tmp/lob.dat');
   pg_query($database, "commit");
?>

A se vedea ?i

  • pg_lo_export() - Export a large object to file
  • pg_lo_open() - Open a large object

pg_lo_export
pg_lo_open
PostgreSQL Func?ii


Open a large object

pg_lo_import
pg_lo_read_all
PostgreSQL Func?ii
PHP Manual

pg_lo_open

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_open — Open a large object

Descrierea

resource pg_lo_open ( resource $connection , int $oid , string $mode )

pg_lo_open() opens a large object in the database and returns large object resource so that it can be manipulated.

Avertizare

Do not close the database connection before closing the large object resource.

To use the large object interface, it is necessary to enclose it within a transaction block.

Nota:

This function used to be called pg_loopen().

Parametri

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().

oid

The OID of the large object in the database.

mode

Can be either "r" for read-only, "w" for write only or "rw" for read and write.

Valorile întoarse

A large object resource or FALSE on error.

Exemple

Example #1 pg_lo_open() example

<?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_create($database);
   echo "$oid\n";
   $handle = pg_lo_open($database, $oid, "w");
   echo "$handle\n";
   pg_lo_write($handle, "large object data");
   pg_lo_close($handle);
   pg_query($database, "commit");
?>

A se vedea ?i

  • pg_lo_close() - Close a large object
  • pg_lo_create() - Create a large object

pg_lo_import
pg_lo_read_all
PostgreSQL Func?ii


Reads an entire large object and send straight to browser

pg_lo_open
pg_lo_read
PostgreSQL Func?ii
PHP Manual

pg_lo_read_all

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_read_all — Reads an entire large object and send straight to browser

Descrierea

int pg_lo_read_all ( resource $large_object )

pg_lo_read_all() reads a large object and passes it straight through to the browser after sending all pending headers. Mainly intended for sending binary data like images or sound.

To use the large object interface, it is necessary to enclose it within a transaction block.

Nota:

This function used to be called pg_loreadall().

Parametri

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Valorile întoarse

Number of bytes read or FALSE on error.

Exemple

Example #1 pg_lo_read_all() example

<?php
   header('Content-type: image/jpeg');
   $image_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $image_oid, "r");
   pg_lo_read_all($handle);
   pg_query($database, "commit");
?>

A se vedea ?i

  • pg_lo_read() - Read a large object

pg_lo_open
pg_lo_read
PostgreSQL Func?ii


Read a large object

pg_lo_read_all
pg_lo_seek
PostgreSQL Func?ii
PHP Manual

pg_lo_read

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_read — Read a large object

Descrierea

string pg_lo_read ( resource $large_object [, int $len = 8192 ] )

pg_lo_read() reads at most len bytes from a large object and returns it as a string.

To use the large object interface, it is necessary to enclose it within a transaction block.

Nota:

This function used to be called pg_loread().

Parametri

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

len

An optional maximum number of bytes to return.

Valorile întoarse

A string containing len bytes from the large object, or FALSE on error.

Exemple

Example #1 pg_lo_read() example

<?php
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "r");
   $data = pg_lo_read($handle, 50000);
   pg_query($database, "commit");
   echo $data;
?>

A se vedea ?i

  • pg_lo_read_all() - Reads an entire large object and send straight to browser

pg_lo_read_all
pg_lo_seek
PostgreSQL Func?ii


Seeks position within a large object

pg_lo_read
pg_lo_tell
PostgreSQL Func?ii
PHP Manual

pg_lo_seek

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_seek — Seeks position within a large object

Descrierea

bool pg_lo_seek ( resource $large_object , int $offset [, int $whence = PGSQL_SEEK_CUR ] )

pg_lo_seek() seeks a position within a large object resource.

To use the large object interface, it is necessary to enclose it within a transaction block.

Parametri

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

offset

The number of bytes to seek.

whence

One of the constants PGSQL_SEEK_SET (seek from object start), PGSQL_SEEK_CUR (seek from current position) or PGSQL_SEEK_END (seek from object end) .

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_lo_seek() example

<?php
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "r");
   // Skip first 50000 bytes
   pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);
   // Read the next 10000 bytes
   $data = pg_lo_read($handle, 10000);
   pg_query($database, "commit");
   echo $data;
?>

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.

A se vedea ?i

  • pg_lo_tell() - Returns current seek position a of large object

pg_lo_read
pg_lo_tell
PostgreSQL Func?ii


Returns current seek position a of large object

pg_lo_seek
pg_lo_truncate
PostgreSQL Func?ii
PHP Manual

pg_lo_tell

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_tell — Returns current seek position a of large object

Descrierea

int pg_lo_tell ( resource $large_object )

pg_lo_tell() returns the current position (offset from the beginning) of a large object.

To use the large object interface, it is necessary to enclose it within a transaction block.

Parametri

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Valorile întoarse

The current seek offset (in number of bytes) from the beginning of the large object. If there is an error, the return value is negative.

Exemple

Example #1 pg_lo_tell() example

<?php
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "r");
   // Skip first 50000 bytes
   pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);
   // See how far we've skipped
   $offset = pg_lo_tell($handle);
   echo "Seek position is: $offset";
   pg_query($database, "commit");
?>

Exemplul de mai sus va afi?a:

Seek position is: 50000

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.

A se vedea ?i

  • pg_lo_seek() - Seeks position within a large object

pg_lo_seek
pg_lo_truncate
PostgreSQL Func?ii


Truncates a large object

pg_lo_tell
pg_lo_unlink
PostgreSQL Func?ii
PHP Manual

pg_lo_truncate

(No version information available, might only be in Git)

pg_lo_truncate — Truncates a large object

Descrierea

bool pg_lo_truncate ( resource $large_object , int $size )

pg_lo_truncate() truncates a large object resource.

To use the large object interface, it is necessary to enclose it within a transaction block.

Parametri

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

size

The number of bytes to truncate.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_lo_truncate() example

<?php
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "r");
   // Truncate to 0
   pg_lo_truncate($handle, 0);
   pg_query($database, "commit");
   echo $data;
?>

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Added truncate function. It supports PostgreSQL 9.3's 64bit large object. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.

A se vedea ?i

  • pg_lo_tell() - Returns current seek position a of large object

pg_lo_tell
pg_lo_unlink
PostgreSQL Func?ii


Delete a large object

pg_lo_truncate
pg_lo_write
PostgreSQL Func?ii
PHP Manual

pg_lo_unlink

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_unlink — Delete a large object

Descrierea

bool pg_lo_unlink ( resource $connection , int $oid )

pg_lo_unlink() deletes a large object with the oid. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

To use the large object interface, it is necessary to enclose it within a transaction block.

Nota:

This function used to be called pg_lounlink().

Parametri

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().

oid

The OID of the large object in the database.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_lo_unlink() example

<?php
   // OID of the large object to delete
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   pg_lo_unlink($database, $doc_oid);
   pg_query($database, "commit");
?>

A se vedea ?i

  • pg_lo_create() - Create a large object
  • pg_lo_import() - Import a large object from file

pg_lo_truncate
pg_lo_write
PostgreSQL Func?ii


Write to a large object

pg_lo_unlink
pg_meta_data
PostgreSQL Func?ii
PHP Manual

pg_lo_write

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_write — Write to a large object

Descrierea

int pg_lo_write ( resource $large_object , string $data [, int $len ] )

pg_lo_write() writes data into a large object at the current seek position.

To use the large object interface, it is necessary to enclose it within a transaction block.

Nota:

This function used to be called pg_lowrite().

Parametri

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

data

The data to be written to the large object. If len is specified and is less than the length of data, only len bytes will be written.

len

An optional maximum number of bytes to write. Must be greater than zero and no greater than the length of data. Defaults to the length of data.

Valorile întoarse

The number of bytes written to the large object, or FALSE on error.

Exemple

Example #1 pg_lo_write() example

<?php
   $doc_oid = 189762345;
   $data = "This will overwrite the start of the large object.";
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "w");
   $data = pg_lo_write($handle, $data);
   pg_query($database, "commit");
?>

A se vedea ?i

  • pg_lo_create() - Create a large object
  • pg_lo_open() - Open a large object

pg_lo_unlink
pg_meta_data
PostgreSQL Func?ii


Get meta data for table

pg_lo_write
pg_num_fields
PostgreSQL Func?ii
PHP Manual

pg_meta_data

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_meta_data — Get meta data for table

Descrierea

array pg_meta_data ( resource $connection , string $table_name [, bool $extended ] )

pg_meta_data() returns table definition for table_name as an array.

Parametri

connection

PostgreSQL database connection resource.

table_name

The name of the table.

extended

Flag for returning extended meta data. Default to FALSE.

Valorile întoarse

An array of the table definition, or FALSE on error.

Exemple

Example #1 Getting table metadata

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $meta = pg_meta_data($dbconn, 'authors');
  if (is_array($meta)) {
      echo '<pre>';
      var_dump($meta);
      echo '</pre>';
  }
?>

Exemplul de mai sus va afi?a:

array(3) {
["author"]=>
array(5) {
  ["num"]=>
  int(1)
  ["type"]=>
  string(7) "varchar"
  ["len"]=>
  int(-1)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
["year"]=>
array(5) {
  ["num"]=>
  int(2)
  ["type"]=>
  string(4) "int2"
  ["len"]=>
  int(2)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
["title"]=>
array(5) {
  ["num"]=>
  int(3)
  ["type"]=>
  string(7) "varchar"
  ["len"]=>
  int(-1)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
}

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | No longer experimental. Added "is enum" as default attribute. extended flag is added.

A se vedea ?i

  • pg_convert() - Convert associative array values into suitable for SQL statement

pg_lo_write
pg_num_fields
PostgreSQL Func?ii


Returns the number of fields in a result

pg_meta_data
pg_num_rows
PostgreSQL Func?ii
PHP Manual

pg_num_fields

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_num_fields — Returns the number of fields in a result

Descrierea

int pg_num_fields ( resource $result )

pg_num_fields() returns the number of fields (columns) in a PostgreSQL result resource.

Nota:

This function used to be called pg_numfields().

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Valorile întoarse

The number of fields (columns) in the result. On error, -1 is returned.

Exemple

Example #1 pg_num_fields() example

<?php
$result = pg_query($conn, "SELECT 1, 2");

$num = pg_num_fields($result);

echo $num . " field(s) returned.\n";
?>

Exemplul de mai sus va afi?a:

2 field(s) returned.

A se vedea ?i

  • pg_num_rows() - Returns the number of rows in a result
  • pg_affected_rows() - Returns number of affected records (tuples)

pg_meta_data
pg_num_rows
PostgreSQL Func?ii


Returns the number of rows in a result

pg_num_fields
pg_options
PostgreSQL Func?ii
PHP Manual

pg_num_rows

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_num_rows — Returns the number of rows in a result

Descrierea

int pg_num_rows ( resource $result )

pg_num_rows() will return the number of rows in a PostgreSQL result resource.

Nota:

This function used to be called pg_numrows().

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Valorile întoarse

The number of rows in the result. On error, -1 is returned.

Exemple

Example #1 pg_num_rows() example

<?php
$result = pg_query($conn, "SELECT 1");

$rows = pg_num_rows($result);

echo $rows . " row(s) returned.\n";
?>

Exemplul de mai sus va afi?a:

1 row(s) returned.

A se vedea ?i

  • pg_num_fields() - Returns the number of fields in a result
  • pg_affected_rows() - Returns number of affected records (tuples)

pg_num_fields
pg_options
PostgreSQL Func?ii


Get the options associated with the connection

pg_num_rows
pg_parameter_status
PostgreSQL Func?ii
PHP Manual

pg_options

(PHP 4, PHP 5, PHP 7)

pg_options — Get the options associated with the connection

Descrierea

string pg_options ([ resource $connection ] )

pg_options() will return a string containing the options specified on the given PostgreSQL connection resource.

Parametri

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().

Valorile întoarse

A string containing the connection options, or FALSE on error.

Exemple

Example #1 pg_options() example

<?php
   $pgsql_conn = pg_connect("dbname=mark host=localhost");
   echo pg_options($pgsql_conn);
?>

A se vedea ?i

  • pg_connect() - Open a PostgreSQL connection

pg_num_rows
pg_parameter_status
PostgreSQL Func?ii


Looks up a current parameter setting of the server.

pg_options
pg_pconnect
PostgreSQL Func?ii
PHP Manual

pg_parameter_status

(PHP 5, PHP 7)

pg_parameter_status — Looks up a current parameter setting of the server.

Descrierea

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.

Precautie

On a pre-7.4 PostgreSQL server, changing client_encoding via SET after connection startup will not be reflected by pg_parameter_status().

Parametri

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.

Valorile întoarse

A string containing the value of the parameter, FALSE on failure or invalid param_name.

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

Server encoding: SQL_ASCII

pg_options
pg_pconnect
PostgreSQL Func?ii


Open a persistent PostgreSQL connection

pg_parameter_status
pg_ping
PostgreSQL Func?ii
PHP Manual

pg_pconnect

(PHP 4, PHP 5, PHP 7)

pg_pconnect — Open a persistent PostgreSQL connection

Descrierea

resource pg_pconnect ( string $connection_string [, int $connect_type ] )

pg_pconnect() opens a connection to a PostgreSQL database. It returns a connection resource that is needed by other PostgreSQL functions.

If a second call is made to pg_pconnect() with the same connection_string as an existing connection, the existing connection will be returned unless you pass PGSQL_CONNECT_FORCE_NEW as connect_type.

To enable persistent connection, the pgsql.allow_persistent php.ini directive must be set to "On" (which is the default). The maximum number of persistent connection can be defined with the pgsql.max_persistent php.ini directive (defaults to -1 for no limit). The total number of connections can be set with the pgsql.max_links php.ini directive.

pg_close() will not close persistent links generated by pg_pconnect().

Parametri

connection_string

The connection_string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form keyword = value. Spaces around the equal sign are optional. To write an empty value or a value containing spaces, surround it with single quotes, e.g., keyword = 'a value'. Single quotes and backslashes within the value must be escaped with a backslash, i.e., \' and \\.

The currently recognized parameter keywords are: host, hostaddr, port, dbname, user, password, connect_timeout, options, tty (ignored), sslmode, requiressl (deprecated in favor of sslmode), and service. Which of these arguments exist depends on your PostgreSQL version.

connect_type

If PGSQL_CONNECT_FORCE_NEW is passed, then a new connection is created, even if the connection_string is identical to an existing connection.

Valorile întoarse

PostgreSQL connection resource on success, FALSE on failure.

Exemple

Example #1 Using pg_pconnect()

<?php
$dbconn = pg_pconnect("dbname=mary");
//connect to a database named "mary"

$dbconn2 = pg_pconnect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"

$dbconn3 = pg_pconnect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password

$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_pconnect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password
?>

A se vedea ?i

  • pg_connect() - Open a PostgreSQL connection
  • Persistent Database Connections

pg_parameter_status
pg_ping
PostgreSQL Func?ii


Ping database connection

pg_pconnect
pg_port
PostgreSQL Func?ii
PHP Manual

pg_ping

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_ping — Ping database connection

Descrierea

bool pg_ping ([ resource $connection ] )

pg_ping() pings a database connection and tries to reconnect it if it is broken.

Parametri

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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_ping() example

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

if (!pg_ping($conn))
  die("Connection is broken\n");
?>

A se vedea ?i

  • pg_connection_status() - Get connection status
  • pg_connection_reset() - Reset connection (reconnect)

pg_pconnect
pg_port
PostgreSQL Func?ii


Return the port number associated with the connection

pg_ping
pg_prepare
PostgreSQL Func?ii
PHP Manual

pg_port

(PHP 4, PHP 5, PHP 7)

pg_port — Return the port number associated with the connection

Descrierea

int pg_port ([ resource $connection ] )

pg_port() returns the port number that the given PostgreSQL connection resource is connected to.

Parametri

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().

Valorile întoarse

An int containing the port number of the database server the connection is to, or FALSE on error.

Exemple

Example #1 pg_port() example

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   print "Successfully connected to port: " . pg_port($pgsql_conn) . "<br/>\n";
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?>

pg_ping
pg_prepare
PostgreSQL Func?ii


Submits a request to create a prepared statement with the given parameters, and waits for completion.

pg_port
pg_put_line
PostgreSQL Func?ii
PHP Manual

pg_prepare

(PHP 5 >= 5.1.0, PHP 7)

pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion.

Descrierea

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.

Parametri

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.

Valorile întoarse

A query result resource on success sau FALSE în cazul e?ecului.

Exemple

Example #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"));

?>

A se vedea ?i

  • 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
PostgreSQL Func?ii


Send a NULL-terminated string to PostgreSQL backend

pg_prepare
pg_query_params
PostgreSQL Func?ii
PHP Manual

pg_put_line

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pg_put_line — Send a NULL-terminated string to PostgreSQL backend

Descrierea

bool pg_put_line ([ resource $connection ], string $data )

pg_put_line() sends a NULL-terminated string to the PostgreSQL backend server. This is needed in conjunction with PostgreSQL's COPY FROM command.

COPY is a high-speed data loading interface supported by PostgreSQL. Data is passed in without being parsed, and in a single transaction.

An alternative to using raw pg_put_line() commands is to use pg_copy_from(). This is a far simpler interface.

Nota:

The application must explicitly send the two characters "\." on the last line to indicate to the backend that it has finished sending its data, before issuing pg_end_copy().

Avertizare

Use of the pg_put_line() causes most large object operations, including pg_lo_read() and pg_lo_tell(), to subsequently fail. You can use pg_copy_from() and pg_copy_to() instead.

Parametri

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 line of text to be sent directly to the PostgreSQL backend. A NULL terminator is added automatically.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_put_line() example

<?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);
?>

A se vedea ?i

  • pg_end_copy() - Sync with PostgreSQL backend

pg_prepare
pg_query_params
PostgreSQL Func?ii


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
PostgreSQL Func?ii
PHP Manual

pg_query_params

(PHP 5 >= 5.1.0, PHP 7)

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.

Descrierea

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. The same parameter may appear more than once in the query; the same value will be used in that case. 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.)

Parametri

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.

User-supplied values should always be passed as parameters, not interpolated into the query string, where they form possible SQL injection attack vectors and introduce bugs when handling data containing quotes. If for some reason you cannot use a parameter, ensure that interpolated values are properly escaped.

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.

Values intended for bytea fields are not supported as parameters. Use pg_escape_bytea() instead, or use the large object functions.

Valorile întoarse

A query result resource on success sau FALSE în cazul e?ecului.

Exemple

Example #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}'");

?>

A se vedea ?i

  • pg_query() - Execute a query

pg_put_line
pg_query
PostgreSQL Func?ii


Execute a query

pg_query_params
pg_result_error_field
PostgreSQL Func?ii
PHP Manual

pg_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_query — Execute a query

Descrierea

resource pg_query ([ resource $connection ], string $query )

pg_query() executes the query on the specified database connection. pg_query_params() should be preferred in most cases.

If an error occurs, and FALSE is returned, details of the error can be retrieved using the pg_last_error() function if the connection is valid.

Nota: Although connection can be omitted, it is not recommended, since it can be the cause of hard to find bugs in scripts.

Nota:

This function used to be called pg_exec(). pg_exec() is still available for compatibility reasons, but users are encouraged to use the newer name.

Parametri

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 SQL statement or statements to be executed. When multiple statements are passed to the function, they are automatically executed as one transaction, unless there are explicit BEGIN/COMMIT commands included in the query string. However, using multiple transactions in one function call is not recommended.

Avertizare

String interpolation of user-supplied data is extremely dangerous and is likely to lead to SQL injection vulnerabilities. In most cases pg_query_params() should be preferred, passing user-supplied values as parameters rather than substituting them into the query string.

Any user-supplied data substituted directly into a query string should be properly escaped.

Valorile întoarse

A query result resource on success sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_query() example

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}

?>

Example #2 Using pg_query() with multiple statements

<?php

$conn = pg_pconnect("dbname=publisher");

// these statements will be executed as one transaction

$query = "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
$query .= "UPDATE authors SET author=NULL WHERE id=3;";

pg_query($conn, $query);

?>

A se vedea ?i

  • pg_connect() - Open a PostgreSQL connection
  • pg_pconnect() - Open a persistent PostgreSQL connection
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_num_rows() - Returns the number of rows in a result
  • pg_affected_rows() - Returns number of affected records (tuples)

pg_query_params
pg_result_error_field
PostgreSQL Func?ii


Returns an individual field of an error report.

pg_query
pg_result_error
PostgreSQL Func?ii
PHP Manual

pg_result_error_field

(PHP 5 >= 5.1.0, PHP 7)

pg_result_error_field — Returns an individual field of an error report.

Descrierea

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.

Parametri

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.

Valorile întoarse

A string containing the contents of the error field, NULL if the field does not exist or FALSE on failure.

Exemple

Example #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);
?>

A se vedea ?i

  • pg_result_error() - Get error message associated with result

pg_query
pg_result_error
PostgreSQL Func?ii


Get error message associated with result

pg_result_error_field
pg_result_seek
PostgreSQL Func?ii
PHP Manual

pg_result_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_result_error — Get error message associated with result

Descrierea

string pg_result_error ( resource $result )

pg_result_error() returns any error message associated with the result resource. Therefore, the user has a better chance of getting the correct error message than with pg_last_error().

The function pg_result_error_field() can give much greater detail on result errors than pg_result_error().

Because pg_query() returns FALSE if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Valorile întoarse

Returns a string. Returns empty string if there is no error. If there is an error associated with the result parameter, returns FALSE.

Exemple

Example #1 pg_result_error() 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($res1);
?>

A se vedea ?i

  • pg_result_error_field() - Returns an individual field of an error report.
  • pg_query() - Execute a query
  • pg_send_query() - Sends asynchronous query
  • pg_get_result() - Get asynchronous query result
  • pg_last_error() - Get the last error message string of a connection
  • pg_last_notice() - Returns the last notice message from PostgreSQL server

pg_result_error_field
pg_result_seek
PostgreSQL Func?ii


Set internal row offset in result resource

pg_result_error
pg_result_status
PostgreSQL Func?ii
PHP Manual

pg_result_seek

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_result_seek — Set internal row offset in result resource

Descrierea

bool pg_result_seek ( resource $result , int $offset )

pg_result_seek() sets the internal row offset in a result resource.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

A se vedea ?i

  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_assoc() - Fetch a row as an associative array
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

pg_result_error
pg_result_status
PostgreSQL Func?ii


Get status of query result

pg_result_seek
pg_select
PostgreSQL Func?ii
PHP Manual

pg_result_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_result_status — Get status of query result

Descrierea

mixed pg_result_status ( resource $result [, int $type = PGSQL_STATUS_LONG ] )

pg_result_status() returns the status of a result resource, or the PostgreSQL command completion tag associated with the result

Parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

type

Either PGSQL_STATUS_LONG to return the numeric status of the result, or PGSQL_STATUS_STRING to return the command tag of the result. If not specified, PGSQL_STATUS_LONG is the default.

Valorile întoarse

Possible return values are PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK, PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR if PGSQL_STATUS_LONG is specified. Otherwise, a string containing the PostgreSQL command tag is returned.

Exemple

Example #1 pg_result_status() example

<?php

// Connect to the database
$conn = pg_pconnect("dbname=publisher");

// Execute a COPY
$result = pg_query($conn, "COPY authors FROM STDIN;");

// Get the result status
$status = pg_result_status($result);

// Determine status
if ($status == PGSQL_COPY_IN)
   echo "Copy began.";
else
   echo "Copy failed.";

?>

Exemplul de mai sus va afi?a:

Copy began.

A se vedea ?i

  • pg_connection_status() - Get connection status

pg_result_seek
pg_select
PostgreSQL Func?ii


Select records

pg_result_status
pg_send_execute
PostgreSQL Func?ii
PHP Manual

pg_select

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_select — Select records

Descrierea

mixed pg_select ( resource $connection , string $table_name , array $assoc_array [, int $options = PGSQL_DML_EXEC ] )

pg_select() selects records specified by assoc_array which has field=>value. For a successful query, it returns an array containing all records and fields that match the condition specified by assoc_array.

If options is specified, pg_convert() is applied to assoc_array with the specified flags.

Parametri

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to select rows.

assoc_array

An array whose keys are field names in the table table_name, and whose values are the conditions that a row must meet to be retrieved.

options

Any number of PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_ESCAPE, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned. When PGSQL_DML_NO_CONV or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Returns string if PGSQL_DML_STRING is passed via options.

Exemple

Example #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";
  }
?>

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

A se vedea ?i

  • pg_convert() - Convert associative array values into suitable for SQL statement

pg_result_status
pg_send_execute
PostgreSQL Func?ii


Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

pg_select
pg_send_prepare
PostgreSQL Func?ii
PHP Manual

pg_send_execute

(PHP 5 >= 5.1.0, PHP 7)

pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.

Exemple

Example #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);
  }

?>

A se vedea ?i

  • 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
PostgreSQL Func?ii


Sends a request to create a prepared statement with the given parameters, without waiting for completion.

pg_send_execute
pg_send_query_params
PostgreSQL Func?ii
PHP Manual

pg_send_prepare

(PHP 5 >= 5.1.0, PHP 7)

pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion.

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.

Exemple

Example #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);
  }

?>

A se vedea ?i

  • pg_connect() - Open a PostgreSQL connection
  • pg_pconnect() - Open a persistent PostgreSQL connection
  • 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
PostgreSQL Func?ii


Submits a command and separate parameters to the server without waiting for the result(s).

pg_send_prepare
pg_send_query
PostgreSQL Func?ii
PHP Manual

pg_send_query_params

(PHP 5 >= 5.1.0, PHP 7)

pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s).

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Use pg_get_result() to determine the query result.

Exemple

Example #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}'");
?>

A se vedea ?i

  • pg_send_query() - Sends asynchronous query

pg_send_prepare
pg_send_query
PostgreSQL Func?ii


Sends asynchronous query

pg_send_query_params
pg_set_client_encoding
PostgreSQL Func?ii
PHP Manual

pg_send_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_send_query — Sends asynchronous query

Descrierea

bool pg_send_query ( resource $connection , string $query )

pg_send_query() sends a query or queries asynchronously to the connection. Unlike pg_query(), it can send multiple queries at once to PostgreSQL and get the results one by one using pg_get_result().

Script execution is not blocked while the queries are executing. Use pg_connection_busy() to check if the connection is busy (i.e. the query is executing). Queries may be cancelled using pg_cancel_query().

Although the user can send multiple queries at once, multiple queries cannot be sent over a busy connection. If a query is sent while the connection is busy, it waits until the last query is finished and discards all its results.

Parametri

connection

PostgreSQL database connection resource.

query

The SQL statement or statements to be executed.

Data inside the query should be properly escaped.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Use pg_get_result() to determine the query result.

Exemple

Example #1 pg_send_query() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
  }

  $res1 = pg_get_result($dbconn);
  echo "First call to pg_get_result(): $res1\n";
  $rows1 = pg_num_rows($res1);
  echo "$res1 has $rows1 records\n\n";

  $res2 = pg_get_result($dbconn);
  echo "Second call to pg_get_result(): $res2\n";
  $rows2 = pg_num_rows($res2);
  echo "$res2 has $rows2 records\n";
?>

Exemplul de mai sus va afi?a:

First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records

Second call to pg_get_result(): Resource id #4
Resource id #4 has 1 records

A se vedea ?i

  • pg_query() - Execute a query
  • pg_cancel_query() - Cancel an asynchronous query
  • pg_get_result() - Get asynchronous query result
  • pg_connection_busy() - Get connection is busy or not

pg_send_query_params
pg_set_client_encoding
PostgreSQL Func?ii


Set the client encoding

pg_send_query
pg_set_error_verbosity
PostgreSQL Func?ii
PHP Manual

pg_set_client_encoding

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pg_set_client_encoding — Set the client encoding

Descrierea

int pg_set_client_encoding ([ resource $connection ], string $encoding )

pg_set_client_encoding() sets the client encoding and returns 0 if success or -1 if error.

PostgreSQL will automatically convert data in the backend database encoding into the frontend encoding.

Nota:

The function used to be called pg_setclientencoding().

Parametri

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().

encoding

The required client encoding. One of SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5 or WIN1250.

The exact list of available encodings depends on your PostgreSQL version, so check your PostgreSQL manual for a more specific list.

Valorile întoarse

Returns 0 on success or -1 on error.

Exemple

Example #1 pg_set_client_encoding() example

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

// Set the client encoding to UNICODE.  Data will be automatically
// converted from the backend encoding to the frontend.
pg_set_client_encoding($conn, "UNICODE");

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

// Write out UTF-8 data
while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}

?>

A se vedea ?i

  • pg_client_encoding() - Gets the client encoding

pg_send_query
pg_set_error_verbosity
PostgreSQL Func?ii


Determines the verbosity of messages returned by pg_last_error and pg_result_error.

pg_set_client_encoding
pg_socket
PostgreSQL Func?ii
PHP Manual

pg_set_error_verbosity

(PHP 5 >= 5.1.0, PHP 7)

pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error() and pg_result_error().

Descrierea

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.

Parametri

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.

Valorile întoarse

The previous verbosity level: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.

Exemple

Example #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);
?>

A se vedea ?i

  • pg_last_error() - Get the last error message string of a connection
  • pg_result_error() - Get error message associated with result

pg_set_client_encoding
pg_socket
PostgreSQL Func?ii


Get a read only handle to the socket underlying a PostgreSQL connection

pg_set_error_verbosity
pg_trace
PostgreSQL Func?ii
PHP Manual

pg_socket

(PHP 5 >= 5.6.0, PHP 7)

pg_socket — Get a read only handle to the socket underlying a PostgreSQL connection

Descrierea

resource pg_socket ( resource $connection )

pg_socket() returns a read only resource corresponding to the socket underlying the given PostgreSQL connection.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

connection

PostgreSQL database connection resource.

Valorile întoarse

A socket resource on success sau FALSE în cazul e?ecului.

pg_set_error_verbosity
pg_trace
PostgreSQL Func?ii


Enable tracing a PostgreSQL connection

pg_socket
pg_transaction_status
PostgreSQL Func?ii
PHP Manual

pg_trace

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

pg_trace — Enable tracing a PostgreSQL connection

Descrierea

bool pg_trace ( string $pathname [, string $mode = "w" [, resource $connection ]] )

pg_trace() enables tracing of the PostgreSQL frontend/backend communication to a file. To fully understand the results, one needs to be familiar with the internals of PostgreSQL communication protocol.

For those who are not, it can still be useful for tracing errors in queries sent to the server, you could do for example grep '^To backend' trace.log and see what queries actually were sent to the PostgreSQL server. For more information, refer to the » PostgreSQL Documentation.

Parametri

pathname

The full path and file name of the file in which to write the trace log. Same as in fopen().

mode

An optional file access mode, same as for fopen().

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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pg_trace() example

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   pg_trace('/tmp/trace.log', 'w', $pgsql_conn);
   pg_query("SELECT 1");
   pg_untrace($pgsql_conn);
   // Now /tmp/trace.log will contain backend communication
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?>

A se vedea ?i

  • fopen() - Opens file or URL
  • pg_untrace() - Disable tracing of a PostgreSQL connection

pg_socket
pg_transaction_status
PostgreSQL Func?ii


Returns the current in-transaction status of the server.

pg_trace
pg_tty
PostgreSQL Func?ii
PHP Manual

pg_transaction_status

(PHP 5 >= 5.1.0, PHP 7)

pg_transaction_status — Returns the current in-transaction status of the server.

Descrierea

int pg_transaction_status ( resource $connection )

Returns the current in-transaction status of the server.

Precautie

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.

Parametri

connection

PostgreSQL database connection resource.

Valorile întoarse

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.

Exemple

Example #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
PostgreSQL Func?ii


Return the TTY name associated with the connection

pg_transaction_status
pg_unescape_bytea
PostgreSQL Func?ii
PHP Manual

pg_tty

(PHP 4, PHP 5, PHP 7)

pg_tty — Return the TTY name associated with the connection

Descrierea

string pg_tty ([ resource $connection ] )

pg_tty() returns the TTY name that server side debugging output is sent to on the given PostgreSQL connection resource.

Nota:

pg_tty() is obsolete, since the server no longer pays attention to the TTY setting, but the function remains for backwards compatibility.

Parametri

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().

Valorile întoarse

A string containing the debug TTY of the connection, or FALSE on error.

Exemple

Example #1 pg_tty() example

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   print "Server debug TTY is: " . pg_tty($pgsql_conn) . "<br/>\n";
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?>

pg_transaction_status
pg_unescape_bytea
PostgreSQL Func?ii


Unescape binary for bytea type

pg_tty
pg_untrace
PostgreSQL Func?ii
PHP Manual

pg_unescape_bytea

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_unescape_bytea — Unescape binary for bytea type

Descrierea

string pg_unescape_bytea ( string $data )

pg_unescape_bytea() unescapes PostgreSQL bytea data values. It returns the unescaped string, possibly containing binary data.

Nota:

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.

Parametri

data

A string containing PostgreSQL bytea data to be converted into a PHP binary string.

Valorile întoarse

A string containing the unescaped data.

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
5.5.1 | A warning is thrown if the input string is invalid.

A se vedea ?i

  • pg_escape_bytea() - Escape a string for insertion into a bytea field
  • pg_escape_string() - Escape a string for query

pg_tty
pg_untrace
PostgreSQL Func?ii


Disable tracing of a PostgreSQL connection

pg_unescape_bytea
pg_update
PostgreSQL Func?ii
PHP Manual

pg_untrace

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

pg_untrace — Disable tracing of a PostgreSQL connection

Descrierea

bool pg_untrace ([ resource $connection ] )

Stop tracing started by pg_trace().

Parametri

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().

Valorile întoarse

Always returns TRUE.

Exemple

Example #1 pg_untrace() example

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   pg_trace('/tmp/trace.log', 'w', $pgsql_conn);
   pg_query("SELECT 1");
   pg_untrace($pgsql_conn);
   // Now tracing of backend communication is disabled
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?>

A se vedea ?i

  • pg_trace() - Enable tracing a PostgreSQL connection

pg_unescape_bytea
pg_update
PostgreSQL Func?ii


Update table

pg_untrace
pg_version
PostgreSQL Func?ii
PHP Manual

pg_update

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_update — Update table

Descrierea

mixed pg_update ( resource $connection , string $table_name , array $data , array $condition [, int $options = PGSQL_DML_EXEC ] )

pg_update() updates records that matches condition with data. If options is specified, pg_convert() is applied to data with specified options.

Parametri

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to update rows.

data

An array whose keys are field names in the table table_name, and whose values are what matched rows are to be updated to.

condition

An array whose keys are field names in the table table_name, and whose values are the conditions that a row must meet to be updated.

options

Any number of PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_ESCAPE, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned. When PGSQL_DML_NO_CONV or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Returns string if PGSQL_DML_STRING is passed via options.

Exemple

Example #1 pg_update() example

<?php
  $db = pg_connect('dbname=foo');
  $data = array('field1'=>'AA', 'field2'=>'BB');

  // This is safe, since $_POST is converted automatically
  $res = pg_update($db, 'post_log', $_POST, $data);
  if ($res) {
      echo "Data is updated: $res\n";
  } else {
      echo "User must have sent wrong inputs\n";
  }
?>

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

A se vedea ?i

  • pg_convert() - Convert associative array values into suitable for SQL statement

pg_untrace
pg_version
PostgreSQL Func?ii


Returns an array with client, protocol and server version (when available)

pg_update
SQLite
PostgreSQL Func?ii
PHP Manual

pg_version

(PHP 5, PHP 7)

pg_version — Returns an array with client, protocol and server version (when available)

Descrierea

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().

Parametri

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().

Valorile întoarse

Returns an array with client, protocol and server keys and values (if available). Returns FALSE on error or invalid connection.

Exemple

Example #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'];
?>

Exemplul de mai sus va afi?a:

7.4

A se vedea ?i

  • pg_parameter_status() - Looks up a current parameter setting of the server.

pg_update
SQLite
PostgreSQL Func?ii


SQLite

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • SQLite Func?ii
    • 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 — Pseudonim pentru 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
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

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.

Nota:

For further information see the SQLite Website (» http://sqlite.org/).

Nota: This extension offers support for SQLite 2.x. Sqlite 3.x is supported by the SQLite3 extension.

SQLite
Instalarea / configurarea
SQLite


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SQLite


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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. O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

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.

Nota: 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

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

SQLite Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Changelog
sqlite.assoc_case | "0" | PHP_INI_ALL | Available since PHP 5.0.0.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

There are two resources used in the SQLite Interface. The first one is the database connection, the second one the result set.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
SQLite Func?ii
SQLite


SQLite Func?ii

Clase predefinite

SQLiteDatabase

Represents an opened SQLite database.

Constructorul

  • __construct - construct a new SQLiteDatabase object

Metode

  • 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.

Metode

  • 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.

Metode

  • 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

Cuprins

  • 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 — Pseudonim pentru 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
Constante predefinite
sqlite_array_query
SQLite


Execute a query against a given database and returns an array

SQLite Func?ii
sqlite_busy_timeout
SQLite Func?ii
PHP Manual

sqlite_array_query

SQLiteDatabase::arrayQuery

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_array_query -- SQLiteDatabase::arrayQuery — Execute a query against a given database and returns an array

Descrierea

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 ]] )

Stil obiect-orientat (method):

public 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.

Sfat

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.

Parametri

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

Parametrul op?ional result_type accepta o constanta ?i determina cum tablouul întors va fi indexat. Utilizând SQLITE_ASSOC vor fi întor?i numai indici asociativi (câmpuri denumite) în timp ce cu SQLITE_NUM vor fi întor?i numai indici numerici (numerele de ordine ale câmpurilor). Cu SQLITE_BOTH vor fi întor?i atât indici associativi, cât ?i numerici. SQLITE_BOTH este valoarea implicita pentru aceasta func?ie.

decode_binary

Când parametrul decode_binary este stabilit în TRUE (implicit), PHP va decodifica codificarea binara pe care a aplicat-o asupra datelor, daca acestea au fost codificate cu sqlite_escape_string (). În mod normal ar trebui sa lasa?i valoarea implicita, daca nu interopera?i cu baze de date create de alte aplica?ii capabile sa lucreze cu sqlite.

Nota: Doua sintaxe alternative sunt sus?inute pentru compatibilitate cu alte extensii de baze de date (cum ar fi MySQL). Forma preferata este cea dintâi, unde parametrul dbhandle este primul parametru pentru func?ie.

Valorile întoarse

Returns an array of the entire result set; FALSE otherwise.

În denumirile coloanelor întoarse de SQLITE_ASSOC ?i SQLITE_BOTH vor fi utilizate litere majuscule/minuscule în corespundere cu valoarea op?iunii de configurare sqlite.assoc_case.

Exemple

Example #1 Stil procedural

<?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'];
}
?>

Example #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'];
}
?>

A se vedea ?i

  • 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() - Pseudonim pentru sqlite_fetch_single

SQLite Func?ii
sqlite_busy_timeout
SQLite Func?ii


Set busy timeout duration, or disable busy handlers

sqlite_array_query
sqlite_changes
SQLite Func?ii
PHP Manual

sqlite_busy_timeout

SQLiteDatabase::busyTimeout

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_busy_timeout -- SQLiteDatabase::busyTimeout — Set busy timeout duration, or disable busy handlers

Descrierea

void sqlite_busy_timeout ( resource $dbhandle , int $milliseconds )

Stil obiect-orientat (method):

public void SQLiteDatabase::busyTimeout ( int $milliseconds )

Set the maximum time, in milliseconds, that SQLite will wait for a dbhandle to become ready for use.

Parametri

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.

Nota:

There are one thousand (1000) milliseconds in one second.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil procedural

<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_busy_timeout($dbhandle, 10000); // set timeout to 10 seconds
sqlite_busy_timeout($dbhandle, 0); // disable busy handler
?>

Example #2 Stil obiect-orientat

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->busyTimeout(10000); // 10 seconds
$dbhandle->busyTimeout(0); // disable
?>

A se vedea ?i

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist

sqlite_array_query
sqlite_changes
SQLite Func?ii


Returns the number of rows that were changed by the most recent SQL statement

sqlite_busy_timeout
sqlite_close
SQLite Func?ii
PHP Manual

sqlite_changes

SQLiteDatabase::changes

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_changes -- SQLiteDatabase::changes — Returns the number of rows that were changed by the most recent SQL statement

Descrierea

int sqlite_changes ( resource $dbhandle )

Stil obiect-orientat (method):

public int SQLiteDatabase::changes ( void )

Returns the numbers of rows that were changed by the most recent SQL statement executed against the dbhandle database handle.

Parametri

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Valorile întoarse

Returns the number of changed rows.

Exemple

Example #1 Stil procedural

<?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);
}
?>

Example #2 Stil obiect-orientat

<?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();
}
?>

A se vedea ?i

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist

sqlite_busy_timeout
sqlite_close
SQLite Func?ii


Closes an open SQLite database

sqlite_changes
sqlite_column
SQLite Func?ii
PHP Manual

sqlite_close

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_close — Closes an open SQLite database

Descrierea

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.

Parametri

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 sqlite_close() example

<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_close($dbhandle);
?>

A se vedea ?i

  • 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 Func?ii


Fetches a column from the current row of a result set

sqlite_close
sqlite_create_aggregate
SQLite Func?ii
PHP Manual

sqlite_column

SQLiteResult::column

SQLiteUnbuffered::column

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_column -- SQLiteResult::column -- SQLiteUnbuffered::column — Fetches a column from the current row of a result set

Descrierea

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.

Parametri

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

Când parametrul decode_binary este stabilit în TRUE (implicit), PHP va decodifica codificarea binara pe care a aplicat-o asupra datelor, daca acestea au fost codificate cu sqlite_escape_string (). În mod normal ar trebui sa lasa?i valoarea implicita, daca nu interopera?i cu baze de date create de alte aplica?ii capabile sa lucreze cu sqlite.

Valorile întoarse

Returns the column value.

Note

Nota:

Use this function when you are iterating a large result set with many columns, or with columns that contain large amounts of data.

A se vedea ?i

  • sqlite_fetch_string() - Pseudonim pentru sqlite_fetch_single

sqlite_close
sqlite_create_aggregate
SQLite Func?ii


Register an aggregating UDF for use in SQL statements

sqlite_column
sqlite_create_function
SQLite Func?ii
PHP Manual

sqlite_create_aggregate

SQLiteDatabase::createAggregate

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_create_aggregate -- SQLiteDatabase::createAggregate — Register an aggregating UDF for use in SQL statements

Descrierea

void sqlite_create_aggregate ( resource $dbhandle , string $function_name , callable $step_func , callable $finalize_func [, int $num_args = -1 ] )

Stil obiect-orientat (method):

public void SQLiteDatabase::createAggregate ( string $function_name , callable $step_func , callable $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).

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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.

Nota:

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.

Sfat

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.

Sfat

You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

A se vedea ?i

  • 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 Func?ii


Registers a "regular" User Defined Function for use in SQL statements

sqlite_create_aggregate
sqlite_current
SQLite Func?ii
PHP Manual

sqlite_create_function

SQLiteDatabase::createFunction

(PHP 5 < 5.4.0, sqlite >= 1.0.0)

sqlite_create_function -- SQLiteDatabase::createFunction — Registers a "regular" User Defined Function for use in SQL statements

Descrierea

void sqlite_create_function ( resource $dbhandle , string $function_name , callable $callback [, int $num_args = -1 ] )

Stil obiect-orientat (method):

public void SQLiteDatabase::createFunction ( string $function_name , callable $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.

Parametri

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.

Nota: 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.

Nota: Doua sintaxe alternative sunt sus?inute pentru compatibilitate cu alte extensii de baze de date (cum ar fi MySQL). Forma preferata este cea dintâi, unde parametrul dbhandle este primul parametru pentru func?ie.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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.

Example #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

Nota:

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.

Sfat

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.

Sfat

You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

A se vedea ?i

  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

sqlite_create_aggregate
sqlite_current
SQLite Func?ii


Fetches the current row from a result set as an array

sqlite_create_function
sqlite_error_string
SQLite Func?ii
PHP Manual

sqlite_current

SQLiteResult::current

SQLiteUnbuffered::current

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_current -- SQLiteResult::current -- SQLiteUnbuffered::current — Fetches the current row from a result set as an array

Descrierea

array sqlite_current ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Stil obiect-orientat (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.

Parametri

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

Parametrul op?ional result_type accepta o constanta ?i determina cum tablouul întors va fi indexat. Utilizând SQLITE_ASSOC vor fi întor?i numai indici asociativi (câmpuri denumite) în timp ce cu SQLITE_NUM vor fi întor?i numai indici numerici (numerele de ordine ale câmpurilor). Cu SQLITE_BOTH vor fi întor?i atât indici associativi, cât ?i numerici. SQLITE_BOTH este valoarea implicita pentru aceasta func?ie.

decode_binary

Când parametrul decode_binary este stabilit în TRUE (implicit), PHP va decodifica codificarea binara pe care a aplicat-o asupra datelor, daca acestea au fost codificate cu sqlite_escape_string (). În mod normal ar trebui sa lasa?i valoarea implicita, daca nu interopera?i cu baze de date create de alte aplica?ii capabile sa lucreze cu sqlite.

Valorile întoarse

Returns an array of the current row from a result set; FALSE if the current position is beyond the final row.

În denumirile coloanelor întoarse de SQLITE_ASSOC ?i SQLITE_BOTH vor fi utilizate litere majuscule/minuscule în corespundere cu valoarea op?iunii de configurare sqlite.assoc_case.

A se vedea ?i

  • 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 Func?ii


Returns the textual description of an error code

sqlite_current
sqlite_escape_string
SQLite Func?ii
PHP Manual

sqlite_error_string

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_error_string — Returns the textual description of an error code

Descrierea

string sqlite_error_string ( int $error_code )

Returns a human readable description of the error_code returned from sqlite_last_error().

Parametri

error_code

The error code being used, which might be passed in from sqlite_last_error().

Valorile întoarse

Returns a human readable description of the error_code, as a string.

A se vedea ?i

  • sqlite_last_error() - Returns the error code of the last error for a database

sqlite_current
sqlite_escape_string
SQLite Func?ii


Escapes a string for use as a query parameter

sqlite_error_string
sqlite_exec
SQLite Func?ii
PHP Manual

sqlite_escape_string

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_escape_string — Escapes a string for use as a query parameter

Descrierea

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).

Parametri

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.

Valorile întoarse

Returns an escaped string for use in an SQLite SQL statement.

Note

Nota:

    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.

Avertizare

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

A se vedea ?i

  • sqlite_udf_encode_binary() - Encode binary data before returning it from an UDF

sqlite_error_string
sqlite_exec
SQLite Func?ii


Executes a result-less query against a given database

sqlite_escape_string
sqlite_factory
SQLite Func?ii
PHP Manual

sqlite_exec

SQLiteDatabase::exec

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.3)

sqlite_exec -- SQLiteDatabase::exec — Executes a result-less query against a given database

Descrierea

bool sqlite_exec ( resource $dbhandle , string $query [, string &$error_msg ] )
bool sqlite_exec ( string $query , resource $dbhandle )

Stil obiect-orientat (method):

public 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).

Avertizare

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.

Parametri

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.

Nota: Doua sintaxe alternative sunt sus?inute pentru compatibilitate cu alte extensii de baze de date (cum ar fi MySQL). Forma preferata este cea dintâi, unde parametrul dbhandle este primul parametru pentru func?ie.

Valorile întoarse

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().

În denumirile coloanelor întoarse de SQLITE_ASSOC ?i SQLITE_BOTH vor fi utilizate litere majuscule/minuscule în corespundere cu valoarea op?iunii de configurare sqlite.assoc_case.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Added the error_msg parameter

Exemple

Example #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);
}
?>

Example #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();
}
?>

A se vedea ?i

  • 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 Func?ii


Opens an SQLite database and returns an SQLiteDatabase object

sqlite_exec
sqlite_fetch_all
SQLite Func?ii
PHP Manual

sqlite_factory

(PHP 5 < 5.4.0)

sqlite_factory — Opens an SQLite database and returns an SQLiteDatabase object

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns an SQLiteDatabase object on success, NULL on error.

Exemple

Example #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');

?>

A se vedea ?i

  • 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 Func?ii


Fetches all rows from a result set as an array of arrays

sqlite_factory
sqlite_fetch_array
SQLite Func?ii
PHP Manual

sqlite_fetch_all

SQLiteResult::fetchAll

SQLiteUnbuffered::fetchAll

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_fetch_all -- SQLiteResult::fetchAll -- SQLiteUnbuffered::fetchAll — Fetches all rows from a result set as an array of arrays

Descrierea

array sqlite_fetch_all ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Stil obiect-orientat (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.

Parametri

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

Parametrul op?ional result_type accepta o constanta ?i determina cum tablouul întors va fi indexat. Utilizând SQLITE_ASSOC vor fi întor?i numai indici asociativi (câmpuri denumite) în timp ce cu SQLITE_NUM vor fi întor?i numai indici numerici (numerele de ordine ale câmpurilor). Cu SQLITE_BOTH vor fi întor?i atât indici associativi, cât ?i numerici. SQLITE_BOTH este valoarea implicita pentru aceasta func?ie.

decode_binary

Când parametrul decode_binary este stabilit în TRUE (implicit), PHP va decodifica codificarea binara pe care a aplicat-o asupra datelor, daca acestea au fost codificate cu sqlite_escape_string (). În mod normal ar trebui sa lasa?i valoarea implicita, daca nu interopera?i cu baze de date create de alte aplica?ii capabile sa lucreze cu sqlite.

Valorile întoarse

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.

În denumirile coloanelor întoarse de SQLITE_ASSOC ?i SQLITE_BOTH vor fi utilizate litere majuscule/minuscule în corespundere cu valoarea op?iunii de configurare sqlite.assoc_case.

Exemple

Example #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'];
}
?>

Example #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'];
}
?>

A se vedea ?i

  • sqlite_fetch_array() - Fetches the next row from a result set as an array

sqlite_factory
sqlite_fetch_array
SQLite Func?ii


Fetches the next row from a result set as an array

sqlite_fetch_all
sqlite_fetch_column_types
SQLite Func?ii
PHP Manual

sqlite_fetch_array

SQLiteResult::fetch

SQLiteUnbuffered::fetch

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_fetch_array -- SQLiteResult::fetch -- SQLiteUnbuffered::fetch — Fetches the next row from a result set as an array

Descrierea

array sqlite_fetch_array ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Stil obiect-orientat (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.

Parametri

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

Parametrul op?ional result_type accepta o constanta ?i determina cum tablouul întors va fi indexat. Utilizând SQLITE_ASSOC vor fi întor?i numai indici asociativi (câmpuri denumite) în timp ce cu SQLITE_NUM vor fi întor?i numai indici numerici (numerele de ordine ale câmpurilor). Cu SQLITE_BOTH vor fi întor?i atât indici associativi, cât ?i numerici. SQLITE_BOTH este valoarea implicita pentru aceasta func?ie.

decode_binary

Când parametrul decode_binary este stabilit în TRUE (implicit), PHP va decodifica codificarea binara pe care a aplicat-o asupra datelor, daca acestea au fost codificate cu sqlite_escape_string (). În mod normal ar trebui sa lasa?i valoarea implicita, daca nu interopera?i cu baze de date create de alte aplica?ii capabile sa lucreze cu sqlite.

Valorile întoarse

Returns an array of the next row from a result set; FALSE if the next position is beyond the final row.

În denumirile coloanelor întoarse de SQLITE_ASSOC ?i SQLITE_BOTH vor fi utilizate litere majuscule/minuscule în corespundere cu valoarea op?iunii de configurare sqlite.assoc_case.

Exemple

Example #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'];
}
?>

Example #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'];
}
?>

A se vedea ?i

  • sqlite_array_query() - Execute a query against a given database and returns an array
  • sqlite_fetch_string() - Pseudonim pentru sqlite_fetch_single

sqlite_fetch_all
sqlite_fetch_column_types
SQLite Func?ii


Return an array of column types from a particular table

sqlite_fetch_array
sqlite_fetch_object
SQLite Func?ii
PHP Manual

sqlite_fetch_column_types

SQLiteDatabase::fetchColumnTypes

(PHP 5 < 5.4.0)

sqlite_fetch_column_types -- SQLiteDatabase::fetchColumnTypes — Return an array of column types from a particular table

Descrierea

array sqlite_fetch_column_types ( string $table_name , resource $dbhandle [, int $result_type = SQLITE_ASSOC ] )

Stil obiect-orientat (method):

public 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.

Parametri

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.

Valorile întoarse

Returns an array of column data types; FALSE on error.

În denumirile coloanelor întoarse de SQLITE_ASSOC ?i SQLITE_BOTH vor fi utilizate litere majuscule/minuscule în corespundere cu valoarea op?iunii de configurare sqlite.assoc_case.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Added result_type

Exemple

Example #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";
}
?>

Example #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";
}
?>

Exemplul de mai sus va afi?a:

Column: bar  Type: VARCHAR
Column: arf  Type: TEXT

sqlite_fetch_array
sqlite_fetch_object
SQLite Func?ii


Fetches the next row from a result set as an object

sqlite_fetch_column_types
sqlite_fetch_single
SQLite Func?ii
PHP Manual

sqlite_fetch_object

SQLiteResult::fetchObject

SQLiteUnbuffered::fetchObject

(PHP 5 < 5.4.0)

sqlite_fetch_object -- SQLiteResult::fetchObject -- SQLiteUnbuffered::fetchObject — Fetches the next row from a result set as an object

Descrierea

object sqlite_fetch_object ( resource $result [, string $class_name [, array $ctor_params [, bool $decode_binary = true ]]] )

Stil obiect-orientat (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 ]]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

sqlite_fetch_column_types
sqlite_fetch_single
SQLite Func?ii


Fetches the first column of a result set as a string

sqlite_fetch_object
sqlite_fetch_string
SQLite Func?ii
PHP Manual

sqlite_fetch_single

SQLiteResult::fetchSingle

SQLiteUnbuffered::fetchSingle

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.1)

sqlite_fetch_single -- SQLiteResult::fetchSingle -- SQLiteUnbuffered::fetchSingle — Fetches the first column of a result set as a string

Descrierea

string sqlite_fetch_single ( resource $result [, bool $decode_binary = true ] )

Stil obiect-orientat (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.

Parametri

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

decode_binary

Când parametrul decode_binary este stabilit în TRUE (implicit), PHP va decodifica codificarea binara pe care a aplicat-o asupra datelor, daca acestea au fost codificate cu sqlite_escape_string (). În mod normal ar trebui sa lasa?i valoarea implicita, daca nu interopera?i cu baze de date create de alte aplica?ii capabile sa lucreze cu sqlite.

Valorile întoarse

Returns the first column value, as a string.

Exemple

Example #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);
}
?>

A se vedea ?i

  • sqlite_fetch_array() - Fetches the next row from a result set as an array

sqlite_fetch_object
sqlite_fetch_string
SQLite Func?ii


Pseudonim pentru sqlite_fetch_single

sqlite_fetch_single
sqlite_field_name
SQLite Func?ii
PHP Manual

sqlite_fetch_string

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_fetch_string — Pseudonim pentru sqlite_fetch_single()

Descrierea

Aceasta func?ie este pseudonim pentru: sqlite_fetch_single().

sqlite_fetch_single
sqlite_field_name
SQLite Func?ii


Returns the name of a particular field

sqlite_fetch_string
sqlite_has_more
SQLite Func?ii
PHP Manual

sqlite_field_name

SQLiteResult::fieldName

SQLiteUnbuffered::fieldName

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_field_name -- SQLiteResult::fieldName -- SQLiteUnbuffered::fieldName — Returns the name of a particular field

Descrierea

string sqlite_field_name ( resource $result , int $field_index )

Stil obiect-orientat (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.

Parametri

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.

Valorile întoarse

Returns the name of a field in an SQLite result set, given the ordinal column number; FALSE on error.

În denumirile coloanelor întoarse de SQLITE_ASSOC ?i SQLITE_BOTH vor fi utilizate litere majuscule/minuscule în corespundere cu valoarea op?iunii de configurare sqlite.assoc_case.

sqlite_fetch_string
sqlite_has_more
SQLite Func?ii


Finds whether or not more rows are available

sqlite_field_name
sqlite_has_prev
SQLite Func?ii
PHP Manual

sqlite_has_more

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_has_more — Finds whether or not more rows are available

Descrierea

bool sqlite_has_more ( resource $result )

Finds whether more rows are available from the given result set.

Parametri

result

The SQLite result resource.

Valorile întoarse

Returns TRUE if there are more rows available from the result handle, or FALSE otherwise.

A se vedea ?i

  • 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 Func?ii


Returns whether or not a previous row is available

sqlite_has_more
sqlite_key
SQLite Func?ii
PHP Manual

sqlite_has_prev

SQLiteResult::hasPrev

(PHP 5 < 5.4.0)

sqlite_has_prev -- SQLiteResult::hasPrev — Returns whether or not a previous row is available

Descrierea

bool sqlite_has_prev ( resource $result )

Stil obiect-orientat (method):

bool SQLiteResult::hasPrev ( void )

Find whether there are more previous rows from the given result handle.

Parametri

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Nota:

Aceasta func?ie nu poate fi utilizata cu indicatori de rezultate nebuferiza?i.

Valorile întoarse

Returns TRUE if there are more previous rows available from the result handle, or FALSE otherwise.

A se vedea ?i

  • 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 Func?ii


Returns the current row index

sqlite_has_prev
sqlite_last_error
SQLite Func?ii
PHP Manual

sqlite_key

SQLiteResult::key

(PHP 5 >= 5.1.0 and < 5.4.0)

sqlite_key -- SQLiteResult::key — Returns the current row index

Descrierea

Stil obiect-orientat (method):

int SQLiteResult::key ( void )

SQLiteResult::key() returns the current row index of the buffered result set result.

Unlike all other SQLite functions, this function does not have a procedural version, and can only be called as a method on a SQLiteResult object.

Valorile întoarse

Returns the current row index of the buffered result set result.

A se vedea ?i

  • 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 Func?ii


Returns the error code of the last error for a database

sqlite_key
sqlite_last_insert_rowid
SQLite Func?ii
PHP Manual

sqlite_last_error

SQLiteDatabase::lastError

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_last_error -- SQLiteDatabase::lastError — Returns the error code of the last error for a database

Descrierea

int sqlite_last_error ( resource $dbhandle )

Stil obiect-orientat (method):

public 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().

Parametri

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Valorile întoarse

Returns an error code, or 0 if no error occurred.

A se vedea ?i

  • sqlite_error_string() - Returns the textual description of an error code

sqlite_key
sqlite_last_insert_rowid
SQLite Func?ii


Returns the rowid of the most recently inserted row

sqlite_last_error
sqlite_libencoding
SQLite Func?ii
PHP Manual

sqlite_last_insert_rowid

SQLiteDatabase::lastInsertRowid

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_last_insert_rowid -- SQLiteDatabase::lastInsertRowid — Returns the rowid of the most recently inserted row

Descrierea

int sqlite_last_insert_rowid ( resource $dbhandle )

Stil obiect-orientat (method):

public 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.

Sfat

You can create auto-increment fields in SQLite by declaring them as INTEGER PRIMARY KEY in your table schema.

Parametri

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Valorile întoarse

Returns the row id, as an integer.

sqlite_last_error
sqlite_libencoding
SQLite Func?ii


Returns the encoding of the linked SQLite library

sqlite_last_insert_rowid
sqlite_libversion
SQLite Func?ii
PHP Manual

sqlite_libencoding

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_libencoding — Returns the encoding of the linked SQLite library

Descrierea

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.

Avertizare

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.

Avertizare

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.

Valorile întoarse

Returns the library encoding.

A se vedea ?i

  • sqlite_lib_version()

sqlite_last_insert_rowid
sqlite_libversion
SQLite Func?ii


Returns the version of the linked SQLite library

sqlite_libencoding
sqlite_next
SQLite Func?ii
PHP Manual

sqlite_libversion

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_libversion — Returns the version of the linked SQLite library

Descrierea

string sqlite_libversion ( void )

Returns the version of the linked SQLite library.

Valorile întoarse

Returns the library version, as a string.

A se vedea ?i

  • sqlite_libencoding() - Returns the encoding of the linked SQLite library

sqlite_libencoding
sqlite_next
SQLite Func?ii


Seek to the next row number

sqlite_libversion
sqlite_num_fields
SQLite Func?ii
PHP Manual

sqlite_next

SQLiteResult::next

SQLiteUnbuffered::next

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_next -- SQLiteResult::next -- SQLiteUnbuffered::next — Seek to the next row number

Descrierea

bool sqlite_next ( resource $result )

Stil obiect-orientat (method):

bool SQLiteResult::next ( void )
bool SQLiteUnbuffered::next ( void )

sqlite_next() advances the result handle result to the next row.

Parametri

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Valorile întoarse

Returns TRUE on success, or FALSE if there are no more rows.

A se vedea ?i

  • 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 Func?ii


Returns the number of fields in a result set

sqlite_next
sqlite_num_rows
SQLite Func?ii
PHP Manual

sqlite_num_fields

SQLiteResult::numFields

SQLiteUnbuffered::numFields

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_num_fields -- SQLiteResult::numFields -- SQLiteUnbuffered::numFields — Returns the number of fields in a result set

Descrierea

int sqlite_num_fields ( resource $result )

Stil obiect-orientat (method):

int SQLiteResult::numFields ( void )
int SQLiteUnbuffered::numFields ( void )

Returns the number of fields in the result set.

Parametri

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Valorile întoarse

Returns the number of fields, as an integer.

A se vedea ?i

  • 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 Func?ii


Returns the number of rows in a buffered result set

sqlite_num_fields
sqlite_open
SQLite Func?ii
PHP Manual

sqlite_num_rows

SQLiteResult::numRows

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_num_rows -- SQLiteResult::numRows — Returns the number of rows in a buffered result set

Descrierea

int sqlite_num_rows ( resource $result )

Stil obiect-orientat (method):

int SQLiteResult::numRows ( void )

Returns the number of rows in the buffered result set.

Parametri

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Nota:

Aceasta func?ie nu poate fi utilizata cu indicatori de rezultate nebuferiza?i.

Valorile întoarse

Returns the number of rows, as an integer.

Exemple

Example #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";
?>

Example #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";
?>

A se vedea ?i

  • 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 Func?ii


Opens an SQLite database and create the database if it does not exist

sqlite_num_rows
sqlite_popen
SQLite Func?ii
PHP Manual

sqlite_open

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_open — Opens an SQLite database and create the database if it does not exist

Descrierea

resource sqlite_open ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

Stil obiect-orientat (constructor):

final public SQLiteDatabase::__construct ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

Opens an SQLite database or creates the database if it does not exist.

Parametri

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.

Valorile întoarse

Returns a resource (database handle) on success, FALSE on error.

Exemple

Example #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);
}
?>

Note

Sfat

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.

Sfat

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.

Nota: 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.

Nota: SQLite is modul securizat and open_basedir aware.

A se vedea ?i

  • 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 Func?ii


Opens a persistent handle to an SQLite database and create the database if it does not exist

sqlite_open
sqlite_prev
SQLite Func?ii
PHP Manual

sqlite_popen

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_popen — Opens a persistent handle to an SQLite database and create the database if it does not exist

Descrierea

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).

Nota: 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.

Parametri

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.

Valorile întoarse

Returns a resource (database handle) on success, FALSE on error.

A se vedea ?i

  • 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 Func?ii


Seek to the previous row number of a result set

sqlite_popen
sqlite_query
SQLite Func?ii
PHP Manual

sqlite_prev

SQLiteResult::prev

(PHP 5 < 5.4.0)

sqlite_prev -- SQLiteResult::prev — Seek to the previous row number of a result set

Descrierea

bool sqlite_prev ( resource $result )

Stil obiect-orientat (method):

bool SQLiteResult::prev ( void )

sqlite_prev() seeks back the result handle to the previous row.

Parametri

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Nota:

Aceasta func?ie nu poate fi utilizata cu indicatori de rezultate nebuferiza?i.

Valorile întoarse

Returns TRUE on success, or FALSE if there are no more previous rows.

A se vedea ?i

  • 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 Func?ii


Executes a query against a given database and returns a result handle

sqlite_prev
sqlite_rewind
SQLite Func?ii
PHP Manual

sqlite_query

SQLiteDatabase::query

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_query -- SQLiteDatabase::query — Executes a query against a given database and returns a result handle

Descrierea

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 ]] )

Stil obiect-orientat (method):

public 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.

Parametri

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

Parametrul op?ional result_type accepta o constanta ?i determina cum tablouul întors va fi indexat. Utilizând SQLITE_ASSOC vor fi întor?i numai indici asociativi (câmpuri denumite) în timp ce cu SQLITE_NUM vor fi întor?i numai indici numerici (numerele de ordine ale câmpurilor). Cu SQLITE_BOTH vor fi întor?i atât indici associativi, cât ?i numerici. SQLITE_BOTH este valoarea implicita pentru aceasta func?ie.

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.

Nota: Doua sintaxe alternative sunt sus?inute pentru compatibilitate cu alte extensii de baze de date (cum ar fi MySQL). Forma preferata este cea dintâi, unde parametrul dbhandle este primul parametru pentru func?ie.

Valorile întoarse

This function will return a result handle sau FALSE în cazul e?ecului. 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.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Added the error_msg parameter

Note

Avertizare

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).

A se vedea ?i

  • 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 Func?ii


Seek to the first row number

sqlite_query
sqlite_seek
SQLite Func?ii
PHP Manual

sqlite_rewind

SQLiteResult::rewind

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_rewind -- SQLiteResult::rewind — Seek to the first row number

Descrierea

bool sqlite_rewind ( resource $result )

Stil obiect-orientat (method):

bool SQLiteResult::rewind ( void )

sqlite_rewind() seeks back to the first row in the given result set.

Parametri

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Nota:

Aceasta func?ie nu poate fi utilizata cu indicatori de rezultate nebuferiza?i.

Valorile întoarse

Returns FALSE if there are no rows in the result set, TRUE otherwise.

A se vedea ?i

  • 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 Func?ii


Seek to a particular row number of a buffered result set

sqlite_rewind
sqlite_single_query
SQLite Func?ii
PHP Manual

sqlite_seek

SQLiteResult::seek

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_seek -- SQLiteResult::seek — Seek to a particular row number of a buffered result set

Descrierea

bool sqlite_seek ( resource $result , int $rownum )

Stil obiect-orientat (method):

bool SQLiteResult::seek ( int $rownum )

sqlite_seek() seeks to the row given by the parameter rownum.

Parametri

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Nota:

Aceasta func?ie nu poate fi utilizata cu indicatori de rezultate nebuferiza?i.

rownum

The ordinal row number to seek to. The row number is zero-based (0 is the first row).

Nota:

Aceasta func?ie nu poate fi utilizata cu indicatori de rezultate nebuferiza?i.

Valorile întoarse

Returns FALSE if the row does not exist, TRUE otherwise.

A se vedea ?i

  • 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 Func?ii


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 Func?ii
PHP Manual

sqlite_single_query

SQLiteDatabase::singleQuery

(PHP 5 < 5.4.0, 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

Descrierea

array sqlite_single_query ( resource $db , string $query [, bool $first_row_only [, bool $decode_binary ]] )

Stil obiect-orientat (method):

public array SQLiteDatabase::singleQuery ( string $query [, bool $first_row_only [, bool $decode_binary ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

sqlite_seek
sqlite_udf_decode_binary
SQLite Func?ii


Decode binary data passed as parameters to an UDF

sqlite_single_query
sqlite_udf_encode_binary
SQLite Func?ii
PHP Manual

sqlite_udf_decode_binary

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_udf_decode_binary — Decode binary data passed as parameters to an UDF

Descrierea

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.

Parametri

data

The encoded data that will be decoded, data that was applied by either sqlite_udf_encode_binary() or sqlite_escape_string().

Valorile întoarse

The decoded string.

Exemple

Example #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'));

?>

A se vedea ?i

  • 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 Func?ii


Encode binary data before returning it from an UDF

sqlite_udf_decode_binary
sqlite_unbuffered_query
SQLite Func?ii
PHP Manual

sqlite_udf_encode_binary

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_udf_encode_binary — Encode binary data before returning it from an UDF

Descrierea

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.

Nota:

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!

Parametri

data

The string being encoded.

Valorile întoarse

The encoded string.

A se vedea ?i

  • 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 Func?ii


Execute a query that does not prefetch and buffer all data

sqlite_udf_encode_binary
sqlite_valid
SQLite Func?ii
PHP Manual

sqlite_unbuffered_query

SQLiteDatabase::unbufferedQuery

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_unbuffered_query -- SQLiteDatabase::unbufferedQuery — Execute a query that does not prefetch and buffer all data

Descrierea

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 ]] )

Stil obiect-orientat (method):

public 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.

Nota:

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().

Parametri

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

Parametrul op?ional result_type accepta o constanta ?i determina cum tablouul întors va fi indexat. Utilizând SQLITE_ASSOC vor fi întor?i numai indici asociativi (câmpuri denumite) în timp ce cu SQLITE_NUM vor fi întor?i numai indici numerici (numerele de ordine ale câmpurilor). Cu SQLITE_BOTH vor fi întor?i atât indici associativi, cât ?i numerici. SQLITE_BOTH este valoarea implicita pentru aceasta func?ie.

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.

Nota: Doua sintaxe alternative sunt sus?inute pentru compatibilitate cu alte extensii de baze de date (cum ar fi MySQL). Forma preferata este cea dintâi, unde parametrul dbhandle este primul parametru pentru func?ie.

Valorile întoarse

Returns a result handle sau FALSE în cazul e?ecului.

sqlite_unbuffered_query() returns a sequential forward-only result set that can only be used to read each row, one after the other.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Added the error_msg parameter

A se vedea ?i

  • sqlite_query() - Executes a query against a given database and returns a result handle

sqlite_udf_encode_binary
sqlite_valid
SQLite Func?ii


Returns whether more rows are available

sqlite_unbuffered_query
SQLite3
SQLite Func?ii
PHP Manual

sqlite_valid

SQLiteResult::valid

SQLiteUnbuffered::valid

(PHP 5 < 5.4.0)

sqlite_valid -- SQLiteResult::valid -- SQLiteUnbuffered::valid — Returns whether more rows are available

Descrierea

bool sqlite_valid ( resource $result )

Stil obiect-orientat (method):

bool SQLiteResult::valid ( void )
bool SQLiteUnbuffered::valid ( void )

Finds whether more rows are available from the given result handle.

Parametri

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Nota:

Aceasta func?ie nu poate fi utilizata cu indicatori de rezultate nebuferiza?i.

Valorile întoarse

Returns TRUE if there are more rows available from the result handle, or FALSE otherwise.

A se vedea ?i

  • 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 Func?ii


SQLite3

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • 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::createCollation — Registers a PHP function for use as an SQL collating function
    • SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
    • SQLite3::enableExceptions — Enable throwing exceptions
    • 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::openBlob — Opens a stream resource to read a BLOB
    • 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::readOnly() — Returns whether a statement is definitely read only
    • 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
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

Sus?inerea bazelor de date SQLite de versiunea 3.

SQLite3
Instalarea / configurarea
SQLite3


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SQLite3


Instalarea

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.

Nota:

This extension was briefly a PECL extension but that version is only recommended for experimental use.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

SQLite3 Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Changelog
sqlite3.extension_dir | NULL | PHP_INI_SYSTEM |

Iata o explica?ie pe scurt a directivelor de configurare.

sqlite3.extension_dir string

Path to the directory where the loadable extensions for SQLite reside.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.

Tipurile resurselor
SQLite3
SQLite3


The SQLite3 class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

A class that interfaces SQLite 3 databases.

Sinopsisul clasei

SQLite3 {
/* Metode */
public bool busyTimeout ( int $msecs )
public int changes ( void )
public bool close ( void )
public __construct ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key = null ]] )
public bool createAggregate ( string $name , mixed $step_callback , mixed $final_callback [, int $argument_count = -1 ] )
public bool createCollation ( string $name , callable $callback )
public bool createFunction ( string $name , mixed $callback [, int $argument_count = -1 ] )
bool enableExceptions ([ bool $enableExceptions = false ] )
public static 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 = null ]] )
public resource open ( string $table , string $column , int $rowid [, string $dbname = "main" ] )
public SQLite3Stmt prepare ( string $query )
public SQLite3Result query ( string $query )
public mixed querySingle ( string $query [, bool $entire_row = false ] )
public static array version ( void )
}

Cuprins

  • 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::createCollation — Registers a PHP function for use as an SQL collating function
  • SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
  • SQLite3::enableExceptions — Enable throwing exceptions
  • 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::openBlob — Opens a stream resource to read a BLOB
  • 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
Constante predefinite
SQLite3::busyTimeout
SQLite3


Sets the busy connection handler

SQLite3
SQLite3::changes
SQLite3
PHP Manual

SQLite3::busyTimeout

(PHP 5 >= 5.3.3, PHP 7)

SQLite3::busyTimeout — Sets the busy connection handler

Descrierea

public bool SQLite3::busyTimeout ( int $msecs )

Sets a busy handler that will sleep until the database is not locked or the timeout is reached.

Parametri

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.

Valorile întoarse

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, PHP 7)

SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

Descrierea

public int SQLite3::changes ( void )

Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an integer value corresponding to the number of database rows changed (or inserted or deleted) by the most recent SQL statement.

Exemple

Example #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, PHP 7)

SQLite3::close — Closes the database connection

Descrierea

public bool SQLite3::close ( void )

Closes the database connection.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success, FALSE on failure.

Exemple

Example #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, PHP 7)

SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database

Descrierea

public SQLite3::__construct ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key = null ]] )

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.

Parametri

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. If the SQLite encryption module is not installed, this parameter will have no effect.

Valorile întoarse

Returns an SQLite3 object on success.

Erori/Excep?ii

Throws an Exception on failure.

Exemple

Example #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::createCollation
SQLite3
PHP Manual

SQLite3::createAggregate

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE upon successful creation of the aggregate, FALSE on failure.

SQLite3::__construct
SQLite3::createCollation
SQLite3


Registers a PHP function for use as an SQL collating function

SQLite3::createAggregate
SQLite3::createFunction
SQLite3
PHP Manual

SQLite3::createCollation

(PHP 5 >= 5.3.11, PHP 7)

SQLite3::createCollation — Registers a PHP function for use as an SQL collating function

Descrierea

public bool SQLite3::createCollation ( string $name , callable $callback )

Registers a PHP function or user-defined function for use as a collating function within SQL statements.

Parametri

name

Name of the SQL collating 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 collation. It should accept two strings and return as strcmp() does, i.e. it should return -1, 1, or 0 if the first string sorts before, sorts after, or is equal to the second.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 SQLite3::createCollation() example

Register the PHP function strnatcmp() as a collating sequence in the SQLite3 database.

<?php

$db = new SQLite3(":memory:");
$db->exec("CREATE TABLE test (col1 string)");
$db->exec("INSERT INTO test VALUES ('a1')");
$db->exec("INSERT INTO test VALUES ('a10')");
$db->exec("INSERT INTO test VALUES ('a2')");

$db->createCollation('NATURAL_CMP', 'strnatcmp');

$defaultSort = $db->query("SELECT col1 FROM test ORDER BY col1");
$naturalSort = $db->query("SELECT col1 FROM test ORDER BY col1 COLLATE NATURAL_CMP");

echo "default:\n";
while ($row = $defaultSort->fetchArray()){
    echo $row['col1'], "\n";
}

echo "\nnatural:\n";
while ($row = $naturalSort->fetchArray()){
    echo $row['col1'], "\n";
}

$db->close();

?>

Exemplul de mai sus va afi?a:

default:
a1
a10
a2

natural:
a1
a2
a10

A se vedea ?i

  • The SQLite collation documentation: » http://sqlite.org/datatype3.html#collation
SQLite3::createAggregate
SQLite3::createFunction
SQLite3


Registers a PHP function for use as an SQL scalar function

SQLite3::createCollation
SQLite3::enableExceptions
SQLite3
PHP Manual

SQLite3::createFunction

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE upon successful creation of the function, FALSE on failure.

Exemple

Example #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")'));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(32) "098f6bcd4621d373cade4e832627b4f6"

SQLite3::createCollation
SQLite3::enableExceptions
SQLite3


Enable throwing exceptions

SQLite3::createFunction
SQLite3::escapeString
SQLite3
PHP Manual

SQLite3::enableExceptions

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::enableExceptions — Enable throwing exceptions

Descrierea

bool SQLite3::enableExceptions ([ bool $enableExceptions = false ] )

Controls whether the SQLite3 instance will throw exceptions or warnings on error.

Parametri

enable

When TRUE, the SQLite3 instance, and SQLite3Stmt and SQLite3Result instances derived from it, will throw exceptions on error.

When FALSE, the SQLite3 instance, and SQLite3Stmt and SQLite3Result instances derived from it, will raise warnings on error.

For either mode, the error code and message, if any, will be available via SQLite3::lastErrorCode() and SQLite3::lastErrorMsg() respectively.

Valorile întoarse

Returns the old value; TRUE if exceptions were enabled, FALSE otherwise.

Exemple

Example #1 SQLite3::enableExceptions() example

<?php
$sqlite = new SQLite3(':memory:');
try {
    $sqlite->exec('create table foo');
    $sqlite->enableExceptions(true);
    $sqlite->exec('create table bar');
} catch (Exception $e) {
    echo 'Caught exception: ' . $e->getMessage();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Warning: SQLite3::exec(): near "foo": syntax error in example.php on line 4
Caught exception: near "bar": syntax error
SQLite3::createFunction
SQLite3::escapeString
SQLite3


Returns a string that has been properly escaped

SQLite3::enableExceptions
SQLite3::exec
SQLite3
PHP Manual

SQLite3::escapeString

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::escapeString — Returns a string that has been properly escaped

Descrierea

public static string SQLite3::escapeString ( string $value )

Returns a string that has been properly escaped for safe inclusion in an SQL statement.

Avertizare

Aceasta func?ie nu func?ioneaza stabil (deocamdata) cu date binare!

To properly handle BLOB fields which may contain NUL characters, use SQLite3Stmt::bindParam() instead.

Parametri

value

The string to be escaped.

Valorile întoarse

Returns a properly escaped string that may be used safely in an SQL statement.

Note

Avertizare

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

SQLite3::enableExceptions
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, PHP 7)

SQLite3::exec — Executes a result-less query against a given database

Descrierea

public bool SQLite3::exec ( string $query )

Executes a result-less query against a given database.

Parametri

query

The SQL query to execute (typically an INSERT, UPDATE, or DELETE query).

Valorile întoarse

Returns TRUE if the query succeeded, FALSE on failure.

Exemple

Example #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, PHP 7)

SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request

Descrierea

public int SQLite3::lastErrorCode ( void )

Returns the numeric result code of the most recent failed SQLite request.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request

Descrierea

public string SQLite3::lastErrorMsg ( void )

Returns English text describing the most recent failed SQLite request.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database

Descrierea

public int SQLite3::lastInsertRowID ( void )

Returns the row ID of the most recent INSERT into the database.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SQLite3::loadExtension — Attempts to load an SQLite extension library

Descrierea

public bool SQLite3::loadExtension ( string $shared_library )

Attempts to load an SQLite extension library.

Parametri

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.

Valorile întoarse

Returns TRUE if the extension is successfully loaded, FALSE on failure.

Exemple

Example #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::openBlob
SQLite3
PHP Manual

SQLite3::open

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::open — Opens an SQLite database

Descrierea

public void SQLite3::open ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key = null ]] )

Opens an SQLite 3 Database. If the build includes encryption, then it will attempt to use the key.

Parametri

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. If the SQLite encryption module is not installed, this parameter will have no effect.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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::openBlob
SQLite3


Opens a stream resource to read a BLOB

SQLite3::open
SQLite3::prepare
SQLite3
PHP Manual

SQLite3::openBlob

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::openBlob — Opens a stream resource to read a BLOB

Descrierea

public resource SQLite3::open ( string $table , string $column , int $rowid [, string $dbname = "main" ] )

Opens a stream resource to read a BLOB, which would be selected by:

SELECT column FROM dbname.table WHERE rowid = rowid

Parametri

table

The table name.

column

The column name.

rowid

The row ID.

dbname

The symbolic name of the DB

Valorile întoarse

Returns a stream resource, sau FALSE în cazul e?ecului.

Exemple

Example #1 SQLite3::openBlob() example

<?php
$conn = new SQLite3(':memory:');
$conn->exec('CREATE TABLE test (text text)');
$conn->exec("INSERT INTO test VALUES ('Lorem ipsum')");
$stream = $conn->openBlob('test', 'text', 1);
echo stream_get_contents($stream);
fclose($stream); // mandatory, otherwise the next line would fail
$conn->close();
?>

Exemplul de mai sus va afi?a:

Lorem ipsum

SQLite3::open
SQLite3::prepare
SQLite3


Prepares an SQL statement for execution

SQLite3::openBlob
SQLite3::query
SQLite3
PHP Manual

SQLite3::prepare

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::prepare — Prepares an SQL statement for execution

Descrierea

public SQLite3Stmt SQLite3::prepare ( string $query )

Prepares an SQL statement for execution and returns an SQLite3Stmt object.

Parametri

query

The SQL query to prepare.

Valorile întoarse

Returns an SQLite3Stmt object on success sau FALSE în cazul e?ecului.

Exemple

Example #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::openBlob
SQLite3::query
SQLite3


Executes an SQL query

SQLite3::prepare
SQLite3::querySingle
SQLite3
PHP Manual

SQLite3::query

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::query — Executes an SQL query

Descrierea

public SQLite3Result SQLite3::query ( string $query )

Executes an SQL query, returning an SQLite3Result object if the query returns results.

Parametri

query

The SQL query to execute.

Valorile întoarse

Returns an SQLite3Result object if the query returns results. Otherwise, returns TRUE if the query succeeded, FALSE on failure.

Exemple

Example #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, PHP 7)

SQLite3::querySingle — Executes a query and returns a single result

Descrierea

public mixed SQLite3::querySingle ( string $query [, bool $entire_row = false ] )

Executes a query and returns a single result.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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, PHP 7)

SQLite3::version — Returns the SQLite3 library version as a string constant and as a number

Descrierea

public static array SQLite3::version ( void )

Returns the SQLite3 library version as a string constant and as a number.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an associative array with the keys "versionString" and "versionNumber".

Exemple

Example #1 SQLite3::version() example

<?php
print_r(SQLite3::version());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [versionString] => 3.5.9
    [versionNumber] => 3005009
)

SQLite3::querySingle
SQLite3Stmt
SQLite3


The SQLite3Stmt class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

A class that handles prepared statements for the SQLite 3 extension.

Sinopsisul clasei

SQLite3Stmt {
/* Metode */
public bool bindParam ( mixed $sql_param , mixed &$param [, int $type ] )
public bool bindValue ( mixed $sql_param , mixed $value [, int $type ] )
public bool clear ( void )
public bool close ( void )
public SQLite3Result execute ( void )
public int paramCount ( void )
public bool readOnly ( void )
public bool reset ( void )
}

Cuprins

  • 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::readOnly() — Returns whether a statement is definitely read only
  • 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, PHP 7)

SQLite3Stmt::bindParam — Binds a parameter to a statement variable

Descrierea

public bool SQLite3Stmt::bindParam ( mixed $sql_param , mixed &$param [, int $type ] )

Binds a parameter to a statement variable.

Parametri

sql_param

Either a string or an int 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.

Valorile întoarse

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, PHP 7)

SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable

Descrierea

public bool SQLite3Stmt::bindValue ( mixed $sql_param , mixed $value [, int $type ] )

Binds the value of a parameter to a statement variable.

Parametri

sql_param

Either a string or an int 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.

Valorile întoarse

Returns TRUE if the value is bound to the statement variable, FALSE on failure.

Exemple

Example #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, PHP 7)

SQLite3Stmt::clear — Clears all current bound parameters

Descrierea

public bool SQLite3Stmt::clear ( void )

Clears all current bound parameters.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SQLite3Stmt::close — Closes the prepared statement

Descrierea

public bool SQLite3Stmt::close ( void )

Closes the prepared statement.

Nota: Note that all SQLite3Results that have been retrieved by executing this statement will be invalidated when the statement is closed.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SQLite3Stmt::execute — Executes a prepared statement and returns a result set object

Descrierea

public SQLite3Result SQLite3Stmt::execute ( void )

Executes a prepared statement and returns a result set object.

Precautie

Result set objects retrieved by calling this method on the same statement object are not independent, but rather share the same underlying structure. Therefore it is recommended to call SQLite3Result::finalize(), before calling SQLite3Stmt::execute() on the same statement object again.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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::readOnly()
SQLite3Stmt
PHP Manual

SQLite3Stmt::paramCount

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement

Descrierea

public int SQLite3Stmt::paramCount ( void )

Returns the number of parameters within the prepared statement.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the number of parameters within the prepared statement.

SQLite3Stmt::execute
SQLite3Stmt::readOnly()
SQLite3Stmt


Returns whether a statement is definitely read only

SQLite3Stmt::paramCount
SQLite3Stmt::reset
SQLite3Stmt
PHP Manual

SQLite3Stmt::readOnly()

(PHP 5 >= 5.3.6, PHP 7)

SQLite3Stmt::readOnly() — Returns whether a statement is definitely read only

Descrierea

public bool SQLite3Stmt::readOnly ( void )

Returns whether a statement is definitely read only. A statement is considered read only, if it makes no direct changes to the content of the database file. Note that user defined SQL functions might change the database indirectly as a side effect.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if a statement is definitely read only, FALSE otherwise.

SQLite3Stmt::paramCount
SQLite3Stmt::reset
SQLite3Stmt


Resets the prepared statement

SQLite3Stmt::readOnly()
SQLite3Result
SQLite3Stmt
PHP Manual

SQLite3Stmt::reset

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::reset — Resets the prepared statement

Descrierea

public bool SQLite3Stmt::reset ( void )

Resets the prepared statement to its state prior to execution. All bindings remain intact after reset.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the statement is successfully reset, FALSE on failure.

SQLite3Stmt::readOnly()
SQLite3Result
SQLite3Stmt


The SQLite3Result class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

A class that handles result sets for the SQLite 3 extension.

Sinopsisul clasei

SQLite3Result {
/* Metode */
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 )
}

Cuprins

  • 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, PHP 7)

SQLite3Result::columnName — Returns the name of the nth column

Descrierea

public string SQLite3Result::columnName ( int $column_number )

Returns the name of the column specified by the column_number.

Parametri

column_number

The numeric zero-based index of the column.

Valorile întoarse

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, PHP 7)

SQLite3Result::columnType — Returns the type of the nth column

Descrierea

public int SQLite3Result::columnType ( int $column_number )

Returns the type of the column identified by column_number.

Parametri

column_number

The numeric zero-based index of the column.

Valorile întoarse

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, PHP 7)

SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both

Descrierea

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.

Parametri

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

Valorile întoarse

Returns a result row as an associatively or numerically indexed array or both. Alternately will return FALSE if there are no more rows.

The types of the values of the returned array are mapped from SQLite3 types as follows: integers are mapped to integer if they fit into the range PHP_INT_MIN..PHP_INT_MAX, and to string otherwise. Floats are mapped to float, NULL values are mapped to null, and strings and blobs are mapped to string.

SQLite3Result::columnType
SQLite3Result::finalize
SQLite3Result


Closes the result set

SQLite3Result::fetchArray
SQLite3Result::numColumns
SQLite3Result
PHP Manual

SQLite3Result::finalize

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Result::finalize — Closes the result set

Descrierea

public bool SQLite3Result::finalize ( void )

Closes the result set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SQLite3Result::numColumns — Returns the number of columns in the result set

Descrierea

public int SQLite3Result::numColumns ( void )

Returns the number of columns in the result set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SQLite3Result::reset — Resets the result set back to the first row

Descrierea

public bool SQLite3Result::reset ( void )

Resets the result set back to the first row.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii SQLSRV
    • 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
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

The SQLSRV extension allows you to access Microsoft SQL Server and SQL Azure databases when running PHP on Windows. The 3.0 release of the driver supports SQL Server, beginning with SQL Server 2005, including SQL Server 2012 and SQL Server 2012 LocalDB. (For more information about LocalDB, see » PHP Driver for SQL Server Support for LocalDB and » SQL Server 2012 Express LocalDB.)

The SQLSRV extension is supported by Microsoft and available for download here: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx. SQL Server 2012 LocalDB can be downloaded here: » http://go.microsoft.com/fwlink/?LinkID=237665.

SQLSRV
Instalarea / configurarea
SQLSRV


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SQLSRV


Necesita?i

The SQLSRV extension can be used on the following operating systems:

  • Windows Vista Service Pack 2 or later
  • Windows Server 2008 Service Pack 2 or later
  • Windows Server 2008 R2
  • Windows 7

The SQLSRV extension requires that the Microsoft SQL Server 2012 Native Client be installed on the same computer that is running PHP. If the Microsoft SQL Server 2012 Native Client is not already installed, click the appropriate link below to download it:

  • » Download the x86 package
  • » Download the x64 package

The SQLSRV download comes 8 driver files, four of which are for PDO support. If you are running non-thread-safe PHP (PHP 5.3), use the php_sqlsrv_53_nts.dll file. (You should use a non-thread-safe version if you are using IIS as your web server). If you are running thread-safe PHP, use the php_sqlsrv_53_ts.dll file. Similarly for PHP 5.4, use the php_sqlsrv_54_nts.dll or php_sqlsrv_54_ts.dll depending on whether your PHP installation is non-thread-safe or thread-safe.

The most recent version of the driver is available for download here: » SQLSRV 3.0 download. If you need support for PHP 5.2 and/or PHP compiled with VC6, use the 2.0 release of the driver: » SQLSRV 2.0 download.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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 8 driver files, four of which are for PDO support. If you are running non-thread-safe PHP (PHP 5.3), use the php_sqlsrv_53_nts.dll file. (You should use a non-thread-safe version if you are using IIS as your web server). If you are running thread-safe PHP, use the php_sqlsrv_53_ts.dll file. Similarly for PHP 5.4, use the php_sqlsrv_54_nts.dll or php_sqlsrv_54_ts.dll depending on whether your PHP installation is non-thread-safe or thread-safe.

The most recent version of the driver is available for download here: » SQLSRV 3.0 download. If you need support for PHP 5.2 and/or PHP compiled with VC6, use the 2.0 release of the driver: » SQLSRV 2.0 download.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

The SQLSRV extension is only compatible with PHP running on Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în 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 Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | 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

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Connection resource

A connection resource returned by sqlsrv_connect().

Statement resource

A statement resource returned by sqlsrv_query() or by sqlsrv_prepare().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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 » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_STATIC (integer)
Inidicates a static cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_DYNAMIC (integer)
Inidicates a dynamic cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_KEYSET (integer)
Inidicates a keyset cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_BUFFERED (integer)
Creates a client-side cursor query. Lets you access rows in any order. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_NEXT (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_PRIOR (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_FIRST (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_LAST (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_ABSOLUTE (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_RELATIVE (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.

Tipurile resurselor
Func?ii SQLSRV
SQLSRV


Func?ii SQLSRV

Cuprins

  • 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
Constante predefinite
sqlsrv_begin_transaction
SQLSRV


Begins a database transaction

Func?ii SQLSRV
sqlsrv_cancel
Func?ii SQLSRV
PHP Manual

sqlsrv_begin_transaction

(No version information available, might only be in Git)

sqlsrv_begin_transaction — Begins a database transaction

Descrierea

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.

Parametri

conn

The connection resource returned by a call to sqlsrv_connect().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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 />";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

A se vedea ?i

  • 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

Func?ii SQLSRV
sqlsrv_cancel
Func?ii SQLSRV


Cancels a statement

sqlsrv_begin_transaction
sqlsrv_client_info
Func?ii SQLSRV
PHP Manual

sqlsrv_cancel

(No version information available, might only be in Git)

sqlsrv_cancel — Cancels a statement

Descrierea

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.

Parametri

stmt

The statement resource to be cancelled.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Note

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.

A se vedea ?i

  • sqlsrv_free_stmt() - Frees all resources for the specified statement
  • sqlsrv_prepare() - Prepares a query for execution

sqlsrv_begin_transaction
sqlsrv_client_info
Func?ii SQLSRV


Returns information about the client and specified connection

sqlsrv_cancel
sqlsrv_close
Func?ii SQLSRV
PHP Manual

sqlsrv_client_info

(No version information available, might only be in Git)

sqlsrv_client_info — Returns information about the client and specified connection

Descrierea

array sqlsrv_client_info ( resource $conn )

Returns information about the client and specified connection

Parametri

conn

The connection about which information is returned.

Valorile întoarse

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)

Exemple

Example #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 />";
}
?>

A se vedea ?i

  • sqlsrv_server_info() - Returns information about the server

sqlsrv_cancel
sqlsrv_close
Func?ii SQLSRV


Closes an open connection and releases resourses associated with the connection

sqlsrv_client_info
sqlsrv_commit
Func?ii SQLSRV
PHP Manual

sqlsrv_close

(No version information available, might only be in Git)

sqlsrv_close — Closes an open connection and releases resourses associated with the connection

Descrierea

bool sqlsrv_close ( resource $conn )

Closes an open connection and releases resourses associated with the connection.

Parametri

conn

The connection to be closed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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 );
?>

A se vedea ?i

  • sqlsrv_connect() - Opens a connection to a Microsoft SQL Server database

sqlsrv_client_info
sqlsrv_commit
Func?ii SQLSRV


Commits a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_close
sqlsrv_configure
Func?ii SQLSRV
PHP Manual

sqlsrv_commit

(No version information available, might only be in Git)

sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction()

Descrierea

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.

Parametri

conn

The connection on which the transaction is to be committed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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 />";
}
?>

A se vedea ?i

  • sqlsrv_begin_transaction() - Begins a database transaction
  • sqlsrv_rollback() - Rolls back a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_close
sqlsrv_configure
Func?ii SQLSRV


Changes the driver error handling and logging configurations

sqlsrv_commit
sqlsrv_connect
Func?ii SQLSRV
PHP Manual

sqlsrv_configure

(No version information available, might only be in Git)

sqlsrv_configure — Changes the driver error handling and logging configurations

Descrierea

bool sqlsrv_configure ( string $setting , mixed $value )

Changes the driver error handling and logging configurations.

Parametri

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)

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • » SQLSRV Error Handling.
  • » Logging SQLSRV Activity.

sqlsrv_commit
sqlsrv_connect
Func?ii SQLSRV


Opens a connection to a Microsoft SQL Server database

sqlsrv_configure
sqlsrv_errors
Func?ii SQLSRV
PHP Manual

sqlsrv_connect

(No version information available, might only be in Git)

sqlsrv_connect — Opens a connection to a Microsoft SQL Server database

Descrierea

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.

Parametri

serverName

The name of the server to which a connection is established. To connect to a specific instance, follow the server name with a backward 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.

Valorile întoarse

A connection resource. If a connection cannot be successfully opened, FALSE is returned.

Exemple

Example #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));
}
?>

Example #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));
}
?>

Example #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));
}
?>

Note

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")).

A se vedea ?i

  • 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
Func?ii SQLSRV


Returns error and warning information about the last SQLSRV operation performed

sqlsrv_connect
sqlsrv_execute
Func?ii SQLSRV
PHP Manual

sqlsrv_errors

(No version information available, might only be in Git)

sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed

Descrierea

mixed sqlsrv_errors ([ int $errorsOrWarnings ] )

Returns error and warning information about the last SQLSRV operation performed.

Parametri

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.

Valorile întoarse

If errors and/or warnings occurred on the last sqlsrv operation, an array of arrays containing error information is returned. If no errors and/or warnings occurred 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.

Exemple

Example #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 />";
        }
    }
}
?>

Note

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.

A se vedea ?i

  • sqlsrv_configure() - Changes the driver error handling and logging configurations

sqlsrv_connect
sqlsrv_execute
Func?ii SQLSRV


Executes a statement prepared with sqlsrv_prepare

sqlsrv_errors
sqlsrv_fetch_array
Func?ii SQLSRV
PHP Manual

sqlsrv_execute

(No version information available, might only be in Git)

sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare()

Descrierea

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.

Parametri

stmt

A statement resource returned by sqlsrv_prepare().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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));
    }
}
?>

Note

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().

A se vedea ?i

  • sqlsrv_prepare() - Prepares a query for execution
  • sqlsrv_query() - Prepares and executes a query.

sqlsrv_errors
sqlsrv_fetch_array
Func?ii SQLSRV


Returns a row as an array

sqlsrv_execute
sqlsrv_fetch_object
Func?ii SQLSRV
PHP Manual

sqlsrv_fetch_array

(No version information available, might only be in Git)

sqlsrv_fetch_array — Returns a row as an array

Descrierea

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).

Parametri

stmt

A statement resource returned by sqlsrv_query or sqlsrv_prepare.

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.

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.

Valorile întoarse

Returns an array on success, NULL if there are no more rows to return, and FALSE if an error occurs.

Exemple

Example #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);
?>

Example #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);
?>

Note

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 ("").

A se vedea ?i

  • 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
Func?ii SQLSRV


Retrieves the next row of data in a result set as an object

sqlsrv_fetch_array
sqlsrv_fetch
Func?ii SQLSRV
PHP Manual

sqlsrv_fetch_object

(No version information available, might only be in Git)

sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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 />";
}
?>

Note

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().

A se vedea ?i

  • 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
Func?ii SQLSRV


Makes the next row in a result set available for reading

sqlsrv_fetch_object
sqlsrv_field_metadata
Func?ii SQLSRV
PHP Manual

sqlsrv_fetch

(No version information available, might only be in Git)

sqlsrv_fetch — Makes the next row in a result set available for reading

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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;
?>

A se vedea ?i

  • 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
Func?ii SQLSRV


Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query

sqlsrv_fetch
sqlsrv_free_stmt
Func?ii SQLSRV
PHP Manual

sqlsrv_field_metadata

(No version information available, might only be in Git)

sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare() or sqlsrv_query()

Descrierea

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.

Parametri

stmt

The statment resource for which metadata is returned.

Valorile întoarse

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.

Exemple

Example #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 />";
}
?>

A se vedea ?i

  • sqlsrv_client_info() - Returns information about the client and specified connection

sqlsrv_fetch
sqlsrv_free_stmt
Func?ii SQLSRV


Frees all resources for the specified statement

sqlsrv_field_metadata
sqlsrv_get_config
Func?ii SQLSRV
PHP Manual

sqlsrv_free_stmt

(No version information available, might only be in Git)

sqlsrv_free_stmt — Frees all resources for the specified statement

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Note

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.

A se vedea ?i

  • sqlsrv_cancel() - Cancels a statement

sqlsrv_field_metadata
sqlsrv_get_config
Func?ii SQLSRV


Returns the value of the specified configuration setting

sqlsrv_free_stmt
sqlsrv_get_field
Func?ii SQLSRV
PHP Manual

sqlsrv_get_config

(No version information available, might only be in Git)

sqlsrv_get_config — Returns the value of the specified configuration setting

Descrierea

mixed sqlsrv_get_config ( string $setting )

Returns the value of the specified configuration setting.

Parametri

setting

The name of the setting for which the value is returned. For a list of configurable settings, see sqlsrv_configure().

Valorile întoarse

Returns the value of the specified setting. If an invalid setting is specified, FALSE is returned.

A se vedea ?i

  • sqlsrv_configure() - Changes the driver error handling and logging configurations

sqlsrv_free_stmt
sqlsrv_get_field
Func?ii SQLSRV


Gets field data from the currently selected row

sqlsrv_get_config
sqlsrv_has_rows
Func?ii SQLSRV
PHP Manual

sqlsrv_get_field

(No version information available, might only be in Git)

sqlsrv_get_field — Gets field data from the currently selected row

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns data from the specified field on success. Returns FALSE otherwise.

Exemple

Example #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;
?>

A se vedea ?i

  • 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
Func?ii SQLSRV


Indicates whether the specified statement has rows

sqlsrv_get_field
sqlsrv_next_result
Func?ii SQLSRV
PHP Manual

sqlsrv_has_rows

(No version information available, might only be in Git)

sqlsrv_has_rows — Indicates whether the specified statement has rows

Descrierea

bool sqlsrv_has_rows ( resource $stmt )

Indicates whether the specified statement has rows.

Parametri

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

Valorile întoarse

Returns TRUE if the specified statement has rows and FALSE if the statement does not have rows or if an error occurred.

Exemple

Example #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 />";
}
?>

A se vedea ?i

  • 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
Func?ii SQLSRV


Makes the next result of the specified statement active

sqlsrv_has_rows
sqlsrv_num_fields
Func?ii SQLSRV
PHP Manual

sqlsrv_next_result

(No version information available, might only be in Git)

sqlsrv_next_result — Makes the next result of the specified statement active

Descrierea

mixed sqlsrv_next_result ( resource $stmt )

Makes the next result of the specified statement active. Results include result sets, row counts, and output parameters.

Parametri

stmt

The statment on which the next result is being called.

Valorile întoarse

Returns TRUE if the next result was successfully retrieved, FALSE if an error occurred, and NULL if there are no more results to retrieve.

Exemple

Example #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));
}
?>

A se vedea ?i

  • 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
Func?ii SQLSRV


Retrieves the number of fields (columns) on a statement

sqlsrv_next_result
sqlsrv_num_rows
Func?ii SQLSRV
PHP Manual

sqlsrv_num_fields

(No version information available, might only be in Git)

sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement

Descrierea

mixed sqlsrv_num_fields ( resource $stmt )

Retrieves the number of fields (columns) on a statement.

Parametri

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.

Valorile întoarse

Returns the number of fields on success. Returns FALSE otherwise.

Exemple

Example #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 />";
}
?>

A se vedea ?i

  • 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
Func?ii SQLSRV


Retrieves the number of rows in a result set

sqlsrv_num_fields
sqlsrv_prepare
Func?ii SQLSRV
PHP Manual

sqlsrv_num_rows

(No version information available, might only be in Git)

sqlsrv_num_rows — Retrieves the number of rows in a result set

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the number of rows retrieved on success and FALSE if an error occurred. If a forward cursor (the default) or dynamic cursor is used, FALSE is returned.

Exemple

Example #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;
?>

A se vedea ?i

  • 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
Func?ii SQLSRV


Prepares a query for execution

sqlsrv_num_rows
sqlsrv_query
Func?ii SQLSRV
PHP Manual

sqlsrv_prepare

(No version information available, might only be in Git)

sqlsrv_prepare — Prepares a query for execution

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a statement resource on success and FALSE if an error occurred.

Exemple

Example #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));
    }
}
?>

Note

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().

A se vedea ?i

  • sqlsrv_execute() - Executes a statement prepared with sqlsrv_prepare
  • sqlsrv_query() - Prepares and executes a query.

sqlsrv_num_rows
sqlsrv_query
Func?ii SQLSRV


Prepares and executes a query.

sqlsrv_prepare
sqlsrv_rollback
Func?ii SQLSRV
PHP Manual

sqlsrv_query

(No version information available, might only be in Git)

sqlsrv_query — Prepares and executes a query.

Descrierea

mixed sqlsrv_query ( resource $conn , string $sql [, array $params [, array $options ]] )

Prepares and executes a query.

Parametri

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.

Valorile întoarse

Returns a statement resource on success and FALSE if an error occurred.

Exemple

Example #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));
}
?>

Note

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().

A se vedea ?i

  • sqlsrv_prepare() - Prepares a query for execution
  • sqlsrv_execute() - Executes a statement prepared with sqlsrv_prepare

sqlsrv_prepare
sqlsrv_rollback
Func?ii SQLSRV


Rolls back a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_query
sqlsrv_rows_affected
Func?ii SQLSRV
PHP Manual

sqlsrv_rollback

(No version information available, might only be in Git)

sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction()

Descrierea

bool sqlsrv_rollback ( resource $conn )

Rolls back a transaction that was begun with sqlsrv_begin_transaction() and returns the connection to auto-commit mode.

Parametri

conn

The connection resource returned by a call to sqlsrv_connect().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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 />";
}
?>

A se vedea ?i

  • sqlsrv_begin_transaction() - Begins a database transaction
  • sqlsrv_commit() - Commits a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_query
sqlsrv_rows_affected
Func?ii SQLSRV


Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

sqlsrv_rollback
sqlsrv_send_stream_data
Func?ii SQLSRV
PHP Manual

sqlsrv_rows_affected

(No version information available, might only be in Git)

sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

Descrierea

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().

Parametri

stmt

The executed statement resource for which the number of affected rows is returned.

Valorile întoarse

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 occurred, FALSE is returned.

Exemple

Example #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 />";
}
?>

A se vedea ?i

  • sqlsrv_num_rows() - Retrieves the number of rows in a result set

sqlsrv_rollback
sqlsrv_send_stream_data
Func?ii SQLSRV


Sends data from parameter streams to the server

sqlsrv_rows_affected
sqlsrv_server_info
Func?ii SQLSRV
PHP Manual

sqlsrv_send_stream_data

(No version information available, might only be in Git)

sqlsrv_send_stream_data — Sends data from parameter streams to the server

Descrierea

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.

Parametri

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

Valorile întoarse

Returns TRUE if there is more data to send and FALSE if there is not.

Exemple

Example #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.";
?>

A se vedea ?i

  • sqlsrv_prepare() - Prepares a query for execution
  • sqlsrv_query() - Prepares and executes a query.

sqlsrv_rows_affected
sqlsrv_server_info
Func?ii SQLSRV


Returns information about the server

sqlsrv_send_stream_data
Sybase
Func?ii SQLSRV
PHP Manual

sqlsrv_server_info

(No version information available, might only be in Git)

sqlsrv_server_info — Returns information about the server

Descrierea

array sqlsrv_server_info ( resource $conn )

Returns information about the server.

Parametri

conn

The connection resource that connects the client and the server.

Valorile întoarse

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.

Exemple

Example #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));
}
?>

A se vedea ?i

  • sqlsrv_client_info() - Returns information about the client and specified connection

sqlsrv_send_stream_data
Sybase
Func?ii SQLSRV


Sybase

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Sybase
    • 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
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

Sybase
Instalarea / configurarea
Sybase


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Sybase


Instalarea

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.

Nota:

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.

As of PHP 7.0.0, the sybase_ct extension has been removed.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Sybase configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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. Removed in PHP 5.4.0.

Iata o explica?ie pe scurt a directivelor de configurare.

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().

Nota:

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.

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

Sybase-CT configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
sybct.deadlock_retry_count | "0" | PHP_INI_ALL | Available since PHP 4.3.0.

Iata o explica?ie pe scurt a directivelor de configurare.

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.deadlock_retry_count int

Allows you to define how often deadlocks are to be retried. The default is 0, value -1 means "forever".

Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii Sybase
Sybase


Func?ii Sybase

Cuprins

  • 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
Constante predefinite
sybase_affected_rows
Sybase


Gets number of affected rows in last query

Func?ii Sybase
sybase_close
Func?ii Sybase
PHP Manual

sybase_affected_rows

(PHP 4, PHP 5)

sybase_affected_rows — Gets number of affected rows in last query

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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().

Parametri

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Valorile întoarse

Returns the number of affected rows, as an integer.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

Records deleted: 10

A se vedea ?i

  • sybase_num_rows() - Get number of rows in a result set

Func?ii Sybase
sybase_close
Func?ii Sybase


Closes a Sybase connection

sybase_affected_rows
sybase_connect
Func?ii Sybase
PHP Manual

sybase_close

(PHP 4, PHP 5)

sybase_close — Closes a Sybase connection

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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().

Parametri

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • sybase_connect() - Opens a Sybase server connection
  • sybase_pconnect() - Open persistent Sybase connection

sybase_affected_rows
sybase_connect
Func?ii Sybase


Opens a Sybase server connection

sybase_close
sybase_data_seek
Func?ii Sybase
PHP Manual

sybase_connect

(PHP 4, PHP 5)

sybase_connect — Opens a Sybase server connection

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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().

Parametri

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.

Valorile întoarse

Returns a positive Sybase link identifier on success, or FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | The new parameter was added.

Exemple

Example #1 sybase_connect() example

<?php
$link = sybase_connect('SYBASE', '', '')
        or die("Could not connect !");
echo "Connected successfully";
sybase_close($link);
?>

A se vedea ?i

  • sybase_pconnect() - Open persistent Sybase connection
  • sybase_close() - Closes a Sybase connection

sybase_close
sybase_data_seek
Func?ii Sybase


Moves internal row pointer

sybase_connect
sybase_deadlock_retry_count
Func?ii Sybase
PHP Manual

sybase_data_seek

(PHP 4, PHP 5)

sybase_data_seek — Moves internal row pointer

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Parametri

result_identifier

row_number

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • sybase_fetch_row() - Get a result row as an enumerated array

sybase_connect
sybase_deadlock_retry_count
Func?ii Sybase


Sets the deadlock retry count

sybase_data_seek
sybase_fetch_array
Func?ii Sybase
PHP Manual

sybase_deadlock_retry_count

(PHP 4 >= 4.3.0, PHP 5)

sybase_deadlock_retry_count — Sets the deadlock retry count

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Parametri

retry_count

Values for retry_count
-1 | Retry forever (default)
0 | Do not retry
n | Retry n times

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Nota: Aceasta func?ie este disponibila numai în cazul utilizarii bibliotecii de interfa?a CT catre Sybase, ?i nu a bibliotecii DB.

sybase_data_seek
sybase_fetch_array
Func?ii Sybase


Fetch row as array

sybase_deadlock_retry_count
sybase_fetch_assoc
Func?ii Sybase
PHP Manual

sybase_fetch_array

(PHP 4, PHP 5)

sybase_fetch_array — Fetch row as array

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Parametri

result

Valorile întoarse

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Nota:

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.

Exemple

Example #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)
}

A se vedea ?i

  • 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
Func?ii Sybase


Fetch a result row as an associative array

sybase_fetch_array
sybase_fetch_field
Func?ii Sybase
PHP Manual

sybase_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

sybase_fetch_assoc — Fetch a result row as an associative array

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Parametri

result

Valorile întoarse

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Note

Nota: Aceasta func?ie este disponibila numai în cazul utilizarii bibliotecii de interfa?a CT catre Sybase, ?i nu a bibliotecii DB.

A se vedea ?i

  • 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
Func?ii Sybase


Get field information from a result

sybase_fetch_assoc
sybase_fetch_object
Func?ii Sybase
PHP Manual

sybase_fetch_field

(PHP 4, PHP 5)

sybase_fetch_field — Get field information from a result

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Parametri

result

field_offset

If the field offset isn't specified, the next field that wasn't yet retrieved by sybase_fetch_field() is retrieved.

Valorile întoarse

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

A se vedea ?i

  • sybase_field_seek() - Sets field offset

sybase_fetch_assoc
sybase_fetch_object
Func?ii Sybase


Fetch a row as an object

sybase_fetch_field
sybase_fetch_row
Func?ii Sybase
PHP Manual

sybase_fetch_object

(PHP 4, PHP 5)

sybase_fetch_object — Fetch a row as an object

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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).

Parametri

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.

Valorile întoarse

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Exemple

Example #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());
    // {...]
?>

A se vedea ?i

  • sybase_fetch_array() - Fetch row as array
  • sybase_fetch_row() - Get a result row as an enumerated array

sybase_fetch_field
sybase_fetch_row
Func?ii Sybase


Get a result row as an enumerated array

sybase_fetch_object
sybase_field_seek
Func?ii Sybase
PHP Manual

sybase_fetch_row

(PHP 4, PHP 5)

sybase_fetch_row — Get a result row as an enumerated array

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Parametri

result

Valorile întoarse

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

A se vedea ?i

  • 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
Func?ii Sybase


Sets field offset

sybase_fetch_row
sybase_free_result
Func?ii Sybase
PHP Manual

sybase_field_seek

(PHP 4, PHP 5)

sybase_field_seek — Sets field offset

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Parametri

result

field_offset

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • sybase_fetch_field() - Get field information from a result

sybase_fetch_row
sybase_free_result
Func?ii Sybase


Frees result memory

sybase_field_seek
sybase_get_last_message
Func?ii Sybase
PHP Manual

sybase_free_result

(PHP 4, PHP 5)

sybase_free_result — Frees result memory

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Parametri

result

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

sybase_field_seek
sybase_get_last_message
Func?ii Sybase


Returns the last message from the server

sybase_free_result
sybase_min_client_severity
Func?ii Sybase
PHP Manual

sybase_get_last_message

(PHP 4, PHP 5)

sybase_get_last_message — Returns the last message from the server

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

string sybase_get_last_message ( void )

sybase_get_last_message() returns the last message reported by the server.

Valorile întoarse

Returns the message as a string.

A se vedea ?i

  • sybase_min_message_severity() - Sets minimum message severity

sybase_free_result
sybase_min_client_severity
Func?ii Sybase


Sets minimum client severity

sybase_get_last_message
sybase_min_error_severity
Func?ii Sybase
PHP Manual

sybase_min_client_severity

(PHP 4, PHP 5)

sybase_min_client_severity — Sets minimum client severity

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

void sybase_min_client_severity ( int $severity )

sybase_min_client_severity() sets the minimum client severity level.

Parametri

severity

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Nota: Aceasta func?ie este disponibila numai în cazul utilizarii bibliotecii de interfa?a CT catre Sybase, ?i nu a bibliotecii DB.

A se vedea ?i

  • sybase_min_server_severity() - Sets minimum server severity

sybase_get_last_message
sybase_min_error_severity
Func?ii Sybase


Sets minimum error severity

sybase_min_client_severity
sybase_min_message_severity
Func?ii Sybase
PHP Manual

sybase_min_error_severity

(PHP 4, PHP 5)

sybase_min_error_severity — Sets minimum error severity

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

void sybase_min_error_severity ( int $severity )

sybase_min_error_severity() sets the minimum error severity level.

Parametri

severity

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Nota: Aceasta func?ie este disponibila numai în cazul utilizarii bibliotecii de interfa?a CT catre Sybase, ?i nu a bibliotecii DB.

A se vedea ?i

  • sybase_min_message_severity() - Sets minimum message severity

sybase_min_client_severity
sybase_min_message_severity
Func?ii Sybase


Sets minimum message severity

sybase_min_error_severity
sybase_min_server_severity
Func?ii Sybase
PHP Manual

sybase_min_message_severity

(PHP 4, PHP 5)

sybase_min_message_severity — Sets minimum message severity

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

void sybase_min_message_severity ( int $severity )

sybase_min_message_severity() sets the minimum message severity level.

Parametri

severity

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Nota: Aceasta func?ie este disponibila numai în cazul utilizarii bibliotecii de interfa?a DB catre Sybase, ?i nu a bibliotecii CT.

A se vedea ?i

  • sybase_min_error_severity() - Sets minimum error severity

sybase_min_error_severity
sybase_min_server_severity
Func?ii Sybase


Sets minimum server severity

sybase_min_message_severity
sybase_num_fields
Func?ii Sybase
PHP Manual

sybase_min_server_severity

(PHP 4, PHP 5)

sybase_min_server_severity — Sets minimum server severity

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

void sybase_min_server_severity ( int $severity )

sybase_min_server_severity() sets the minimum server severity level.

Parametri

severity

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Nota: Aceasta func?ie este disponibila numai în cazul utilizarii bibliotecii de interfa?a CT catre Sybase, ?i nu a bibliotecii DB.

A se vedea ?i

  • sybase_min_client_severity() - Sets minimum client severity

sybase_min_message_severity
sybase_num_fields
Func?ii Sybase


Gets the number of fields in a result set

sybase_min_server_severity
sybase_num_rows
Func?ii Sybase
PHP Manual

sybase_num_fields

(PHP 4, PHP 5)

sybase_num_fields — Gets the number of fields in a result set

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

int sybase_num_fields ( resource $result )

sybase_num_fields() returns the number of fields in a result set.

Parametri

result

Valorile întoarse

Returns the number of fields as an integer.

A se vedea ?i

  • 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
Func?ii Sybase


Get number of rows in a result set

sybase_num_fields
sybase_pconnect
Func?ii Sybase
PHP Manual

sybase_num_rows

(PHP 4, PHP 5)

sybase_num_rows — Get number of rows in a result set

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

int sybase_num_rows ( resource $result )

sybase_num_rows() returns the number of rows in a result set.

Parametri

result

Valorile întoarse

Returns the number of rows as an integer.

A se vedea ?i

  • 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
Func?ii Sybase


Open persistent Sybase connection

sybase_num_rows
sybase_query
Func?ii Sybase
PHP Manual

sybase_pconnect

(PHP 4, PHP 5)

sybase_pconnect — Open persistent Sybase connection

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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'.

Parametri

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.

Valorile întoarse

Returns a positive Sybase persistent link identifier on success, or FALSE on error.

A se vedea ?i

  • sybase_connect() - Opens a Sybase server connection

sybase_num_rows
sybase_query
Func?ii Sybase


Sends a Sybase query

sybase_pconnect
sybase_result
Func?ii Sybase
PHP Manual

sybase_query

(PHP 4, PHP 5)

sybase_query — Sends a Sybase query

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a positive Sybase result identifier on success, FALSE on error, or TRUE if the query was successful but didn't return any columns.

A se vedea ?i

  • sybase_select_db() - Selects a Sybase database
  • sybase_connect() - Opens a Sybase server connection

sybase_pconnect
sybase_result
Func?ii Sybase


Get result data

sybase_query
sybase_select_db
Func?ii Sybase
PHP Manual

sybase_result

(PHP 4, PHP 5)

sybase_result — Get result data

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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().

Parametri

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.

Valorile întoarse

sybase_result() returns the contents of one cell from a Sybase result set.

sybase_query
sybase_select_db
Func?ii Sybase


Selects a Sybase database

sybase_result
sybase_set_message_handler
Func?ii Sybase
PHP Manual

sybase_select_db

(PHP 4, PHP 5)

sybase_select_db — Selects a Sybase database

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii Sybase


Sets the handler called when a server message is raised

sybase_select_db
sybase_unbuffered_query
Func?ii Sybase
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

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

bool sybase_set_message_handler ( callable $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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');
?>

Example #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'));
?>

Example #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');
?>

Note

Nota: Aceasta func?ie este disponibila numai în cazul utilizarii bibliotecii de interfa?a CT catre Sybase, ?i nu a bibliotecii DB.

sybase_select_db
sybase_unbuffered_query
Func?ii Sybase


Send a Sybase query and do not block

sybase_set_message_handler
tokyo_tyrant
Func?ii Sybase
PHP Manual

sybase_unbuffered_query

(PHP 4 >= 4.3.0, PHP 5)

sybase_unbuffered_query — Send a Sybase query and do not block

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Nota:

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.

Parametri

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.

Valorile întoarse

Returns a positive Sybase result identifier on success, or FALSE on error.

Exemple

Example #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);

?>

Note

Nota: Aceasta func?ie este disponibila numai în cazul utilizarii bibliotecii de interfa?a CT catre Sybase, ?i nu a bibliotecii DB.

A se vedea ?i

  • sybase_query() - Sends a Sybase query

sybase_set_message_handler
tokyo_tyrant
Func?ii Sybase


tokyo_tyrant

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • 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
Introducere
Extensii de lucru cu baze de date specifice anumitor producatori


Introducere

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
Instalarea / configurarea
tokyo_tyrant


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
tokyo_tyrant


Necesita?i

Before using this extension Tokyo Cabinet and Tokyo Tyrant must be installed.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » 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'

Nota: 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"

Nota: 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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

tokyo_tyrant Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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 |

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constante TokyoTyrant

Tipurile resurselor
Exemple
tokyo_tyrant


Exemple

Utilizarea de baza

Example #1 Stabilirea ?i ob?inerea perechilor cheie-valoare

<?php
$tt = new TokyoTyrant("localhost");
$tt->put("key", "value");
echo $tt->get("key");
?>

Exemplul de mai sus va afi?a:

value
Constante predefinite
TokyoTyrant
tokyo_tyrant


The TokyoTyrant class

(PECL tokyo_tyrant >= 0.1.0)

Introducere

The main Tokyo Tyrant class

Sinopsisul clasei

TokyoTyrant {
/* Constante */
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 ;
/* Metode */
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 )
}

Constante predefinite

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

Cuprins

  • 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
Exemple
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the new value on success

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

6.5

A se vedea ?i

  • 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

Descrierea

public TokyoTyrant TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] )

Connects to a remote database

Parametri

host

The hostname

port

The port. Default: 1978

options

Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)

Valorile întoarse

This method returns the current object and throws TokyoTyrantException on failure.

Exemple

Example #1 TokyoTyrant::connect() example

<?php
$tt = new TokyoTyrant();
$tt->connect("localhost", TokyoTyrant::RDBDEF_PORT)->put("test", "value");
?>

A se vedea ?i

  • 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

Descrierea

public TokyoTyrant TokyoTyrant::connectUri ( string $uri )

Connects to a database using an uri

Parametri

uri

An URI to the database. For example tcp://localhost:1979/

Valorile întoarse

This method returns the current object and throws TokyoTyrantException on failure.

Exemple

Example #1 TokyoTyrant::connectUri() example

<?php
$tt = new TokyoTyrant();
$tt->connectUri("tcp://localhost:1978/")->put("test", "hi");
?>

A se vedea ?i

  • 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

Descrierea

public TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )

Constructs a new TokyoTyrant object and optionally connects to the database

Parametri

host

The hostname. Default: NULL

port

port number. Default: 1978

options

Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)

Valorile întoarse

Throws TokyoTyrantException if connection to database fails

A se vedea ?i

  • 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

Descrierea

public TokyoTyrant TokyoTyrant::copy ( string $path )

Makes a copy of the current database

Parametri

path

Path to where to copy the database. The user running the remote database must have a write access to the directory.

Valorile întoarse

This method returns the current object and throws TokyoTyrantException on failure.

Exemple

Example #1 TokyoTyrant::copy() example

<?php
$tt = new TokyoTyrant("localhost", 1978);
$tt->copy("/tmp/foobar.tct");
?>

A se vedea ?i

  • 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

Descrierea

public string TokyoTyrant::ext ( string $name , int $options , string $key , string $value )

Executes a remote script extension.

Parametri

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

Valorile întoarse

Returns the result of the script function

Exemple

Example #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

Descrierea

public array TokyoTyrant::fwmKeys ( string $prefix , int $max_recs )

Returns the forward matching keys from the database

Parametri

prefix

Prefix of the keys

max_recs

Maximum records to return

Valorile întoarse

Returns an array of matching keys. The values are not returned

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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.

Parametri

keys

A string key or an array of string keys

Valorile întoarse

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.

Exemple

Example #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"));
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["key1"]=>
  string(6) "value1"
  ["key2"]=>
  string(6) "value2"
}
string(6) "value1"

A se vedea ?i

  • 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 Git)

TokyoTyrant::getIterator — Get an iterator

Descrierea

public TokyoTyrantIterator TokyoTyrant::getIterator ( void )

Gets an iterator for iterating all keys / values in the database.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.

Exemple

Example #1 TokyoTyrant::getIterator() example

<?php
$tt = new TokyoTyrant("localhost");
$it = $tt->getIterator();

foreach ($it as $k => $v) {

}
?>

A se vedea ?i

  • 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

Descrierea

public int TokyoTyrant::num ( void )

Returns the number of records in the database

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns number of records in the database

Exemple

Example #1 TokyoTyrant::num() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Echo the number of records */
echo $tt->num();
?>

Exemplul de mai sus va afi?a ceva similar cu:

1234

A se vedea ?i

  • 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

Descrierea

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.

Parametri

keys

A string key or an array of string keys

Valorile întoarse

This method returns the current object and throws TokyoTyrantException on failure.

Exemple

Example #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"));
?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Valorile întoarse

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

value2

A se vedea ?i

  • 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

Descrierea

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.

Parametri

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Valorile întoarse

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

value has more data

A se vedea ?i

  • 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

Descrierea

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.

Parametri

keys

A string key or an array of key-value pairs

value

The string value

Valorile întoarse

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

Existing record! Not modified
value

A se vedea ?i

  • 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

Descrierea

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.

Parametri

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Valorile întoarse

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

value1

A se vedea ?i

  • 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

Descrierea

public mixed TokyoTyrant::putShl ( string $key , string $value , int $width )

Concatenate to a record and shift to left.

Parametri

key

A string key

value

The value to concatenate

width

The width of the record

Valorile întoarse

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

data and string

A se vedea ?i

  • 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

Descrierea

public mixed TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = true ] )

Restore the database from the update log.

Avertizare

This method is not supported on 32bit platforms.

Parametri

log_dir

Directory where the log is

timestamp

Beginning timestamp with microseconds

check_consistency

Whether to check consistency: Default: TRUE

Valorile întoarse

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

Descrierea

public mixed TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = true ] )

Sets the replication master of the database

Avertizare

This method is not supported on 32bit platforms.

Parametri

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.

Valorile întoarse

This method returns the current object and throws TokyoTyrantException on failure.

Exemple

Example #1 TokyoTyrant::setMaster() example

<?php
/* Connect to a database */
$tt = new TokyoTyrant("tokyotyrant.example.com");

/* Disable the replication */
$tt->setMaster(NULL, 0, 0);
?>

A se vedea ?i

  • 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

Descrierea

public int TokyoTyrant::size ( string $key )

Returns the size of a value by key

Parametri

key

The key of which size to fetch

Valorile întoarse

Returns the size of the key or throw TokyoTyrantException on error

Exemple

Example #1 TokyoTyrant::size() example

<?php
$tt = new TokyoTyrant("localhost");

$tt->put("test_key", "12345");

echo $tt->size("test_key");
?>

Exemplul de mai sus va afi?a:

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

Descrierea

public array TokyoTyrant::stat ( void )

Returns statistics of the remote database

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array of key value pairs describing the statistics

Exemple

Example #1 TokyoTyrant::stat() example

<?php
$tt = new TokyoTyrant("localhost");

var_dump($tt->stat());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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"
}

A se vedea ?i

  • 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

Descrierea

public mixed TokyoTyrant::sync ( void )

Synchronizes the database on to the physical device

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public TokyoTyrant TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] )

Tunes database connection options.

Parametri

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.

Valorile întoarse

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

Descrierea

public mixed TokyoTyrant::vanish ( void )

Empties a remote database

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

This method returns the current object and throws TokyoTyrantException on failure.

Exemple

Example #1 TokyoTyrant::vanish() example

<?php
$tt = new TokyoTyrant("localhost");
$tt->vanish();
?>

A se vedea ?i

  • TokyoTyrant::out() - Removes records

TokyoTyrant::tune
TokyoTyrantTable
TokyoTyrant


The TokyoTyrantTable class

(PECL tokyo_tyrant >= 0.1.0)

Introducere

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.

Sinopsisul clasei

TokyoTyrantTable extends TokyoTyrant {
/* Metode */
public void add ( string $key , mixed $increment [, string $type ] )
public int genUid ( void )
public array 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 )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

public void TokyoTyrantTable::add ( string $key , mixed $increment [, string $type ] )

This method is not supported with table databases.

Parametri

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.

Valorile întoarse

This method throws an TokyoTyrantException if used through this class.

A se vedea ?i

  • 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

Descrierea

public int TokyoTyrantTable::genUid ( void )

Generates an unique id inside the table database. In table databases rows are referenced using a numeric primary key.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an unique id or throws TokyoTyrantException on error

Exemple

Example #1 TokyoTyrantTable::genUid() example

<?php
$tt = new TokyoTyrantTable("localhost", 1122);

echo $tt->genUid();
?>

Exemplul de mai sus va afi?a ceva similar cu:

4

A se vedea ?i

  • 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

Descrierea

public array 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.

Parametri

keys

The primary key, can be a string or an integer

Valorile întoarse

Returns the row as an array

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}

Note

Nota:

Starting from version 0.3.0 this method accepts array as parameter. Please note that multi-get on tables is not binary-safe.

A se vedea ?i

  • 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 Git)

TokyoTyrantTable::getIterator — Get an iterator

Descrierea

public TokyoTyrantIterator TokyoTyrantTable::getIterator ( void )

Gets an iterator for iterating all keys / values in the database.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.

Exemple

Example #1 TokyoTyrantTable::getIterator() example

<?php
$tt = new TokyoTyrantTable("localhost");
$it = $tt->getIterator();

foreach ($it as $k => $v) {
  var_dump($k, $v);
}
?>

A se vedea ?i

  • 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

Descrierea

public TokyoTyrantQuery TokyoTyrantTable::getQuery ( void )

Get a query object to execute searches on the database

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TokyoTyrantQuery on success and throws TokyoTyrantException on error

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [11]=>
  array(2) {
    ["something"]=>
    string(5) "value"
    ["data"]=>
    string(9) "good data"
  }
}

A se vedea ?i

  • 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

Descrierea

public void TokyoTyrantTable::out ( mixed $keys )

Removes records from a table database.

Parametri

keys

A single integer key or an array of integers

Valorile întoarse

This method returns the current object and throws TokyoTyrantException on failure.

Exemple

Example #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);
?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

key

The primary key of the row

columns

The row contents

Valorile întoarse

Returns the primary key on success and throws TokyoTyrantException on error

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}
array(2) {
  ["column1"]=>
  string(10) "other data"
  ["column2"]=>
  string(11) "better data"
}

A se vedea ?i

  • 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

Descrierea

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.

Parametri

key

The primary key of the row or NULL

columns

Array of row contents

Valorile întoarse

Returns the primary key and throws TokyoTyrantException on error.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

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"
}

A se vedea ?i

  • 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

Descrierea

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.

Parametri

key

The primary key of the row or NULL

columns

Array of the row contents

Valorile întoarse

Returns the primary key and throws TokyoTyrantException on error.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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"
}

A se vedea ?i

  • 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

Descrierea

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.

Parametri

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Valorile întoarse

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

key

A string key

value

The value to concatenate

width

The width of the record

Valorile întoarse

This method is not supported on table databases.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

column

The name of the column

type

The index type

Valorile întoarse

This method returns the current object and throws TokyoTyrantException on failure.

TokyoTyrantTable::putShl
TokyoTyrantQuery
TokyoTyrantTable


The TokyoTyrantQuery class

(PECL tokyo_tyrant >= 0.1.0)

Introducere

This class is used to query the table databases

Sinopsisul clasei

TokyoTyrantQuery implements Iterator {
/* Metode */
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 )
}

Cuprins

  • 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

Descrierea

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.

Parametri

name

Name of the column in the condition

op

The operator. One of the TokyoTyrant::RDBQC_* constants

expr

The expression

Valorile întoarse

This method returns the current object and throws TokyoTyrantException on failure.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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"
  }
}

A se vedea ?i

  • 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

Descrierea

public TokyoTyrantQuery::__construct ( TokyoTyrantTable $table )

Construct a new query object

Parametri

table

TokyoTyrantTable object with active database connection

Valorile întoarse

Returns a new TokyoTyrantQuery object and throws TokyoTyrantException on error

Exemple

Example #1 TokyoTyrantQuery::__construct() example

<?php
$tt = new TokyoTyrantTable("localhost", 1979);

$query = new TokyoTyrantQuery($tt);

/* Work with $query */
?>

A se vedea ?i

  • 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 Git)

TokyoTyrantQuery::count — Counts records

Descrierea

public int TokyoTyrantQuery::count ( void )

Returns a count of how many records a query returns.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a count of matching rows and throws TokyoTyrantException on error

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

int(2)

A se vedea ?i

  • 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

Descrierea

public array TokyoTyrantQuery::current ( void )

Returns the current element. Part of Iterator interface

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current row

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

pk: 1, columns: 2
pk: 4, columns: 2

A se vedea ?i

  • 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 Git)

TokyoTyrantQuery::hint — Get the hint string of the query

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

This method always returns a string

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(72) "
scanning the whole table
result set size: 11
leaving the natural order
"

A se vedea ?i

  • 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

Descrierea

public string TokyoTyrantQuery::key ( void )

Returns the current key. Part of the Iterator interface

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current key and throws TokyoTyrantException on error

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

pk: 1, columns: 2
pk: 4, columns: 2

A se vedea ?i

  • 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 Git)

TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries

Descrierea

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.

Parametri

queries

Array of TokyoTyrantQuery objects

type

One of the TokyoTyrant::RDBMS_* constants

Valorile întoarse

Returns the matching rows and throws TokyoTyrantException on error

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

array(3) {
  ["cherry"]=>
  array(1) {
    ["color"]=>
    string(3) "red"
  }
  ["strawberry"]=>
  array(1) {
    ["color"]=>
    string(3) "red"
  }
  ["lemon"]=>
  array(1) {
    ["color"]=>
    string(6) "yellow"
  }
}

A se vedea ?i

  • 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

Descrierea

public array TokyoTyrantQuery::next ( void )

Returns the next result in the resultset. Part of the Iterator interface.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the next row and throws TokyoTyrantException on error.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

pk: 1, columns: 2
pk: 4, columns: 2

A se vedea ?i

  • 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

Descrierea

public TokyoTyrantQuery TokyoTyrantQuery::out ( void )

Removes all records that match the query. Works exactly like search but removes the records instead of returning them.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

This method returns the current object and throws TokyoTyrantException on failure.

Exemple

Example #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();
?>

A se vedea ?i

  • 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

Descrierea

public bool TokyoTyrantQuery::rewind ( void )

Rewind the resultset and executes the query if it has not been executed. Part of the Iterator interface.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

pk: 1, columns: 2
pk: 4, columns: 2

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the matching rows and throws TokyoTyrantException on error

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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"
  }
}

A se vedea ?i

  • 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

Descrierea

public mixed TokyoTyrantQuery::setLimit ([ int $max [, int $skip ]] )

Set the maximum amount of records to return on a query.

Parametri

max

Maximum amount of records. Default: -1

skip

How many records to skip from the start. Default: -1

Valorile întoarse

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

Descrierea

public mixed TokyoTyrantQuery::setOrder ( string $name , int $type )

Sets the order of a query

Parametri

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

Valorile întoarse

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

Descrierea

public bool TokyoTyrantQuery::valid ( void )

Checks if the current item is valid. Part of the Iterator interface

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the current item is valid and FALSE if not.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

pk: 1, columns: 2
pk: 4, columns: 2

A se vedea ?i

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

TokyoTyrantQuery::setOrder
TokyoTyrantIterator
TokyoTyrantQuery


The TokyoTyrantIterator class

(PECL tokyo_tyrant >= 0.2.0)

Introducere

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.

Sinopsisul clasei

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 )
}

Cuprins

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Throws an exception if iterator initialization fails.

Exemple

Example #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);
}
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}

A se vedea ?i

  • 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

Descrierea

public mixed TokyoTyrantIterator::current ( void )

Returns the current value during iteration.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current value on success and false on failure.

A se vedea ?i

  • 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

Descrierea

public mixed TokyoTyrantIterator::key ( void )

Returns the current key.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current key on success and false on failure.

A se vedea ?i

  • 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

Descrierea

public mixed TokyoTyrantIterator::next ( void )

Move to next key during iteration and return it's value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the next value on success and false on failure.

A se vedea ?i

  • 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

Descrierea

public void TokyoTyrantIterator::rewind ( void )

Rewinds the iterator for new iteration. Called automatically at the beginning of foreach.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Throws TokyoTyrantException if iterator initialization fails.

A se vedea ?i

  • 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

Descrierea

public bool TokyoTyrantIterator::valid ( void )

Checks whether the internal pointer points to valid element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the current item is valid and FALSE if not.

A se vedea ?i

  • 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

(PECL tokyo_tyrant >= 0.1.0)

Introducere

TokyoTyrantException

Sinopsisul clasei

tokyotyrantexception extends Exception {
/* Proprieta?i */
protected int $code ;
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Proprieta?i

code

The exception code. This can be compared to TokyoTyrant::TTE_* constants

TokyoTyrantIterator::valid
Extensii referitoare la data ?i ora
tokyo_tyrant


Extensii referitoare la data ?i ora

  • Calendar
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii de calendar
  • Date/Time — Date and Time
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • DateTime — The DateTime class
    • DateTimeImmutable — The DateTimeImmutable class
    • DateTimeInterface — The DateTimeInterface interface
    • DateTimeZone — The DateTimeZone class
    • DateInterval — The DateInterval class
    • DatePeriod — The DatePeriod class
    • Func?ii de Data/Timp
    • Supported Date and Time Formats
    • Lista zonelor orare sus?inute
  • HRTime — High resolution timing
    • Introducere
    • Instalarea / configurarea
    • Exemple
    • HRTime\PerformanceCounter — The HRTime\PerformanceCounter class
    • HRTime\StopWatch — The HRTime\StopWatch class
    • HRTime\Unit — The HRTime\Unit class
TokyoTyrantException
Calendar
Informa?ii de referin?a despre func?ii


Calendar

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii de calendar
    • 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
Extensii referitoare la data ?i ora
Introducere
Extensii referitoare la data ?i ora


Introducere

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
Instalarea / configurarea
Calendar


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Calendar


Instalarea

Pentru ca aceste func?ii sa func?ioneze este necesar de a compila PHP cu op?iunea --enable-calendar .

Versiunea PHP pentru Windows sus?ine implicit aceasta extensie. Nu este nevoie sa încarca?i extensii suplimentare pentru a putea utiliza aceste func?ii.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

CAL_EASTER_DEFAULT (integer)
CAL_EASTER_ROMAN (integer)
CAL_EASTER_ALWAYS_GREGORIAN (integer)
CAL_EASTER_ALWAYS_JULIAN (integer)
CAL_GREGORIAN (integer)
CAL_JULIAN (integer)
CAL_JEWISH (integer)
CAL_JEWISH_ADD_ALAFIM_GERESH (integer)
CAL_JEWISH_ADD_ALAFIM (integer)
CAL_JEWISH_ADD_GERESHAYIM (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)
Tipurile resurselor
Func?ii de calendar
Calendar


Func?ii de calendar

Cuprins

  • 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
Constante predefinite
cal_days_in_month
Calendar


Return the number of days in a month for a given year and calendar

Func?ii de calendar
cal_from_jd
Func?ii de calendar
PHP Manual

cal_days_in_month

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

cal_days_in_month — Return the number of days in a month for a given year and calendar

Descrierea

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.

Parametri

calendar

Calendar to use for calculation

month

Month in the selected calendar

year

Year in the selected calendar

Valorile întoarse

The length in days of the selected month in the given calendar

Exemple

Example #1 cal_days_in_month() example

<?php
$number = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There were {$number} days in August 2003";
?>

Func?ii de calendar
cal_from_jd
Func?ii de calendar


Converts from Julian Day Count to a supported calendar

cal_days_in_month
cal_info
Func?ii de calendar
PHP Manual

cal_from_jd

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

cal_from_jd — Converts from Julian Day Count to a supported calendar

Descrierea

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.

Parametri

jd

Julian day as integer

calendar

Calendar to convert to

Valorile întoarse

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".

Exemple

Example #1 cal_from_jd() example

<?php
$today = unixtojd(mktime(0, 0, 0, 8, 16, 2003));
print_r(cal_from_jd($today, CAL_GREGORIAN));
?>

Exemplul de mai sus va afi?a:

Array
(
    [date] => 8/16/2003
    [month] => 8
    [day] => 16
    [year] => 2003
    [dow] => 6
    [abbrevdayname] => Sat
    [dayname] => Saturday
    [abbrevmonth] => Aug
    [monthname] => August
)

A se vedea ?i

  • 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
Func?ii de calendar


Returns information about a particular calendar

cal_from_jd
cal_to_jd
Func?ii de calendar
PHP Manual

cal_info

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

cal_info — Returns information about a particular calendar

Descrierea

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.

Parametri

calendar

Calendar to return information for. If no calendar is specified information about all calendars is returned.

Valorile întoarse

Exemple

Example #1 cal_info() example

<?php
$info = cal_info(0);
print_r($info);
?>

Exemplul de mai sus va afi?a:

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
Func?ii de calendar


Converts from a supported calendar to Julian Day Count

cal_info
easter_date
Func?ii de calendar
PHP Manual

cal_to_jd

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

cal_to_jd — Converts from a supported calendar to Julian Day Count

Descrierea

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.

Parametri

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

Valorile întoarse

A Julian Day number.

A se vedea ?i

  • 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
Func?ii de calendar


Get Unix timestamp for midnight on Easter of a given year

cal_to_jd
easter_days
Func?ii de calendar
PHP Manual

easter_date

(PHP 4, PHP 5, PHP 7)

easter_date — Get Unix timestamp for midnight on Easter of a given year

Descrierea

int easter_date ([ int $year = date("Y") ] )

Returns the Unix timestamp corresponding to midnight on Easter of the given year.

Avertizare

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.

Parametri

year

The year as a number between 1970 an 2037. If omitted, defaults to the current year according to the local time.

Valorile întoarse

The easter date as a unix timestamp.

Exemple

Example #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

?>

Note

Nota:

easter_date() relies on your system's C library time functions, rather than using PHP's internal date and time functions. As a consequence, easter_date() uses the TZ environment variable to determine the time zone it should operate in, rather than using PHP's default time zone, which may result in unexpected behaviour when using this function in conjunction with other date functions in PHP.

As a workaround, you can use the easter_days() with DateTime and DateInterval to calculate the start of Easter in your PHP time zone as follows:

<?php
function get_easter_datetime($year) {
    $base = new DateTime("$year-03-21");
    $days = easter_days($year);

    return $base->add(new DateInterval("P{$days}D"));
}

foreach (range(2012, 2015) as $year) {
    printf("Easter in %d is on %s\n",
           $year,
           get_easter_datetime($year)->format('F j'));
}
?>

Exemplul de mai sus va afi?a:

Easter in 2012 is on April 8
Easter in 2013 is on March 31
Easter in 2014 is on April 20
Easter in 2015 is on April 5

A se vedea ?i

  • 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
Func?ii de calendar


Get number of days after March 21 on which Easter falls for a given year

easter_date
frenchtojd
Func?ii de calendar
PHP Manual

easter_days

(PHP 4, PHP 5, PHP 7)

easter_days — Get number of days after March 21 on which Easter falls for a given year

Descrierea

int easter_days ([ int $year = date("Y") [, 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.

Parametri

year

The year as a positive number. If omitted, defaults to the current year according to the local time.

method

Allows Easter dates to be calculated based on the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants.

Valorile întoarse

The number of days after March 21st that the Easter Sunday is in the given year.

Exemple

Example #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

?>

A se vedea ?i

  • easter_date() - Get Unix timestamp for midnight on Easter of a given year

easter_date
frenchtojd
Func?ii de calendar


Converts a date from the French Republican Calendar to a Julian Day Count

easter_days
gregoriantojd
Func?ii de calendar
PHP Manual

frenchtojd

(PHP 4, PHP 5, PHP 7)

frenchtojd — Converts a date from the French Republican Calendar to a Julian Day Count

Descrierea

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.

Parametri

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

Valorile întoarse

The julian day for the given french revolution date as an integer.

A se vedea ?i

  • 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
Func?ii de calendar


Converts a Gregorian date to Julian Day Count

frenchtojd
jddayofweek
Func?ii de calendar
PHP Manual

gregoriantojd

(PHP 4, PHP 5, PHP 7)

gregoriantojd — Converts a Gregorian date to Julian Day Count

Descrierea

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.

Parametri

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

Valorile întoarse

The julian day for the given gregorian date as an integer.

Exemple

Example #1 Calendar functions

<?php
$jd = GregorianToJD(10, 11, 1970);
echo "$jd\n";
$gregorian = JDToGregorian($jd);
echo "$gregorian\n";
?>

A se vedea ?i

  • jdtogregorian() - Converts Julian Day Count to Gregorian date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count

frenchtojd
jddayofweek
Func?ii de calendar


Returns the day of the week

gregoriantojd
jdmonthname
Func?ii de calendar
PHP Manual

jddayofweek

(PHP 4, PHP 5, PHP 7)

jddayofweek — Returns the day of the week

Descrierea

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.

Parametri

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)

Valorile întoarse

The gregorian weekday as either an integer or string.

gregoriantojd
jdmonthname
Func?ii de calendar


Returns a month name

jddayofweek
jdtofrench
Func?ii de calendar
PHP Manual

jdmonthname

(PHP 4, PHP 5, PHP 7)

jdmonthname — Returns a month name

Descrierea

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

Parametri

jday

The Julian Day to operate on

calendar

The calendar to take the month name from

Valorile întoarse

The month name for the given Julian Day and calendar.

jddayofweek
jdtofrench
Func?ii de calendar


Converts a Julian Day Count to the French Republican Calendar

jdmonthname
jdtogregorian
Func?ii de calendar
PHP Manual

jdtofrench

(PHP 4, PHP 5, PHP 7)

jdtofrench — Converts a Julian Day Count to the French Republican Calendar

Descrierea

string jdtofrench ( int $juliandaycount )

Converts a Julian Day Count to the French Republican Calendar.

Parametri

julianday

A julian day number as integer

Valorile întoarse

The french revolution date as a string in the form "month/day/year"

A se vedea ?i

  • 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
Func?ii de calendar


Converts Julian Day Count to Gregorian date

jdtofrench
jdtojewish
Func?ii de calendar
PHP Manual

jdtogregorian

(PHP 4, PHP 5, PHP 7)

jdtogregorian — Converts Julian Day Count to Gregorian date

Descrierea

string jdtogregorian ( int $julianday )

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".

Parametri

julianday

A julian day number as integer

Valorile întoarse

The gregorian date as a string in the form "month/day/year"

A se vedea ?i

  • gregoriantojd() - Converts a Gregorian date to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar

jdtofrench
jdtojewish
Func?ii de calendar


Converts a Julian day count to a Jewish calendar date

jdtogregorian
jdtojulian
Func?ii de calendar
PHP Manual

jdtojewish

(PHP 4, PHP 5, PHP 7)

jdtojewish — Converts a Julian day count to a Jewish calendar date

Descrierea

string jdtojewish ( int $juliandaycount [, bool $hebrew = false [, int $fl = 0 ]] )

Converts a Julian Day Count to the Jewish Calendar.

Parametri

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.

Valorile întoarse

The jewish date as a string in the form "month/day/year"

Exemple

Example #1 jdtojewish() Example

<?php
echo jdtojewish(gregoriantojd(10, 8, 2002), true,
       CAL_JEWISH_ADD_GERESHAYIM + CAL_JEWISH_ADD_ALAFIM + CAL_JEWISH_ADD_ALAFIM_GERESH);
?>

A se vedea ?i

  • 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
Func?ii de calendar


Converts a Julian Day Count to a Julian Calendar Date

jdtojewish
jdtounix
Func?ii de calendar
PHP Manual

jdtojulian

(PHP 4, PHP 5, PHP 7)

jdtojulian — Converts a Julian Day Count to a Julian Calendar Date

Descrierea

string jdtojulian ( int $julianday )

Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".

Parametri

julianday

A julian day number as integer

Valorile întoarse

The julian date as a string in the form "month/day/year"

A se vedea ?i

  • juliantojd() - Converts a Julian Calendar date to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar

jdtojewish
jdtounix
Func?ii de calendar


Convert Julian Day to Unix timestamp

jdtojulian
jewishtojd
Func?ii de calendar
PHP Manual

jdtounix

(PHP 4, PHP 5, PHP 7)

jdtounix — Convert Julian Day to Unix timestamp

Descrierea

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).

Parametri

jday

A julian day number between 2440588 and 2465342.

Valorile întoarse

The unix timestamp for the start of the given julian day.

A se vedea ?i

  • unixtojd() - Convert Unix timestamp to Julian Day

jdtojulian
jewishtojd
Func?ii de calendar


Converts a date in the Jewish Calendar to Julian Day Count

jdtounix
juliantojd
Func?ii de calendar
PHP Manual

jewishtojd

(PHP 4, PHP 5, PHP 7)

jewishtojd — Converts a date in the Jewish Calendar to Julian Day Count

Descrierea

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.

Parametri

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

Valorile întoarse

The julian day for the given jewish date as an integer.

A se vedea ?i

  • 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
Func?ii de calendar


Converts a Julian Calendar date to Julian Day Count

jewishtojd
unixtojd
Func?ii de calendar
PHP Manual

juliantojd

(PHP 4, PHP 5, PHP 7)

juliantojd — Converts a Julian Calendar date to Julian Day Count

Descrierea

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.

Precautie

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.

Parametri

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

Valorile întoarse

The julian day for the given julian date as an integer.

A se vedea ?i

  • 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
Func?ii de calendar


Convert Unix timestamp to Julian Day

juliantojd
Date/Time
Func?ii de calendar
PHP Manual

unixtojd

(PHP 4, PHP 5, PHP 7)

unixtojd — Convert Unix timestamp to Julian Day

Descrierea

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.

Parametri

timestamp

A unix timestamp to convert.

Valorile întoarse

A julian day number as integer.

A se vedea ?i

  • jdtounix() - Convert Julian Day to Unix timestamp

juliantojd
Date/Time
Func?ii de calendar


Date and Time

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • DateTime Arithmetic
  • 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 — Parses a time string according to a specified format
    • DateTime::getLastErrors — Returns the warnings and errors
    • 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
  • DateTimeImmutable — The DateTimeImmutable class
    • DateTimeImmutable::add — Adds an amount of days, months, years, hours, minutes and seconds
    • DateTimeImmutable::__construct — Returns new DateTimeImmutable object
    • DateTimeImmutable::createFromFormat — Returns new DateTimeImmutable object formatted according to the specified format
    • DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable object encapsulating the given DateTime object
    • DateTimeImmutable::getLastErrors — Returns the warnings and errors
    • DateTimeImmutable::modify — Creates a new object with modified timestamp
    • DateTimeImmutable::__set_state — The __set_state handler
    • DateTimeImmutable::setDate — Sets the date
    • DateTimeImmutable::setISODate — Sets the ISO date
    • DateTimeImmutable::setTime — Sets the time
    • DateTimeImmutable::setTimestamp — Sets the date and time based on an Unix timestamp
    • DateTimeImmutable::setTimezone — Sets the time zone
    • DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds
  • DateTimeInterface — The DateTimeInterface interface
    • DateTime::diff — Returns the difference between two DateTime objects
    • DateTime::format — Returns date formatted according to given format
    • DateTime::getOffset — Returns the timezone offset
    • DateTime::getTimestamp — Gets the Unix timestamp
    • DateTime::getTimezone — Return time zone relative to given DateTime
    • 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 a numerically indexed array containing all defined timezone identifiers
  • DateInterval — The DateInterval class
    • DateInterval::__construct — Creates a 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 a new DatePeriod object
    • DatePeriod::getDateInterval — Gets the interval
    • DatePeriod::getEndDate — Gets the end date
    • DatePeriod::getStartDate — Gets the start date
  • Func?ii de Data/Timp
    • checkdate — Valideaza o data Gregoriana
    • date_add — Pseudonim pentru DateTime::add
    • date_create_from_format — Pseudonim pentru DateTime::createFromFormat
    • date_create_immutable_from_format — Pseudonim pentru DateTimeImmutable::createFromFormat
    • date_create_immutable — Pseudonim pentru DateTimeImmutable::__construct
    • date_create — Pseudonim pentru DateTime::__construct
    • date_date_set — Pseudonim pentru 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 — Pseudonim pentru DateTime::diff
    • date_format — Pseudonim pentru DateTime::format
    • date_get_last_errors — Pseudonim pentru DateTime::getLastErrors
    • date_interval_create_from_date_string — Pseudonim pentru DateInterval::createFromDateString
    • date_interval_format — Pseudonim pentru DateInterval::format
    • date_isodate_set — Pseudonim pentru DateTime::setISODate
    • date_modify — Pseudonim pentru DateTime::modify
    • date_offset_get — Pseudonim pentru 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 — Pseudonim pentru 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 — Pseudonim pentru DateTime::setTime
    • date_timestamp_get — Pseudonim pentru DateTime::getTimestamp
    • date_timestamp_set — Pseudonim pentru DateTime::setTimestamp
    • date_timezone_get — Pseudonim pentru DateTime::getTimezone
    • date_timezone_set — Pseudonim pentru DateTime::setTimezone
    • date — Formateaza o ora/data
    • getdate — Ob?ine informa?ia despre data/ora
    • gettimeofday — Ob?ine timpul curent
    • gmdate — Formateaza o data/ora GMT/UTC
    • gmmktime — Ob?ine momentul de timp Unix pentru o data GMT
    • gmstrftime — Formateaza o data/ora GMT/UTC în conformitate cu setarile locale
    • idate — Format a local time/date as integer
    • localtime — Ob?ine timpul local
    • microtime — Întoarce timpul curent Unix cu microsecunde
    • mktime — Ob?ine timestamp-ul Unix pentru o data ?i ora
    • strftime — Formateaza o ora/data locala în conformitate cu setarile locale
    • strptime — Parse a time/date generated with strftime
    • strtotime — Transleaza aproape orice descriere textuala în limba engleza a datei ?i orei într-un timestamp Unix
    • time — Întoarce timpul curent Unix
    • timezone_abbreviations_list — Pseudonim pentru DateTimeZone::listAbbreviations
    • timezone_identifiers_list — Pseudonim pentru DateTimeZone::listIdentifiers
    • timezone_location_get — Pseudonim pentru DateTimeZone::getLocation
    • timezone_name_from_abbr — Returns the timezone name from abbreviation
    • timezone_name_get — Pseudonim pentru DateTimeZone::getName
    • timezone_offset_get — Pseudonim pentru DateTimeZone::getOffset
    • timezone_open — Pseudonim pentru DateTimeZone::__construct
    • timezone_transitions_get — Pseudonim pentru 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 zonelor orare sus?inute
    • Africa
    • America
    • Antarctica
    • Arctica
    • Asia
    • Atlantica
    • Australia
    • Europa
    • India
    • Pacificul
    • Altele
unixtojd
Introducere
Extensii referitoare la data ?i ora


Introducere

These functions allow you to get the date and time from the server where your PHP scripts are running. You can use these functions to format the date and time in many different ways.

The date and time information is internally stored as a 64-bit number so all conceivably useful dates (including negative years) are supported. The range is from about 292 billion years in the past to the same in the future.

Nota: Please keep in mind that these functions are dependent on the locale settings of your server. Make sure to take daylight saving time (use e.g. $date = strtotime('+7 days', $date) and not $date += 7*24*60*60) and leap years into consideration when working with these functions.

Nota: The timezones referenced in this section can be found in the Lista zonelor orare sus?inute.

Date/Time
Instalarea / configurarea
Date/Time


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Date/Time


Instalarea

Nu este necesar de a instala ceva suplimentar pentru a utiliza aceste func?ii; ele fac parte din nucleul PHP.

Nota: Getting the latest timezone database

The latest version of the timezone database can be installed via PECL's » timezonedb.

Nota: Experimental DateTime support in PHP 5.1.x

Although the DateTime class (and related functions) are enabled by default since PHP 5.2.0, it is possible to add experimental support into PHP 5.1.x by using the following flag before configure/compile: CFLAGS=-DEXPERIMENTAL_DATE_SUPPORT=1

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Date/Time Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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 zonelor orare sus?inute for a list of supported timezones.

Nota: The first four configuration options are currently only used by date_sunrise() and date_sunset().

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

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)
Tipurile resurselor
Exemple
Date/Time


Exemple

Cuprins

  • DateTime Arithmetic
Constante predefinite
DateTime Arithmetic
Date/Time


DateTime Arithmetic

The following examples show some pitfalls of DateTime arithmetic with regard to DST transitions and months having different numbers of days.

Example #1 DateTime::add/sub add intervals which cover elapsed time

Adding PT24H over a DST transition will appear to add 23/25 hours (for most timezones).

<?php
$dt = new DateTime("2015-11-01 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt->add(new DateInterval("PT3H"));
echo "End:   ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>

Exemplul de mai sus va afi?a:

Start: 2015-11-01 00:00:00 -04:00
End:   2015-11-01 02:00:00 -05:00

Example #2 DateTime::modify and strtotime increment or decrement individual component values

Adding +24 hours over a DST transition will add exactly 24 hours as seen in the date/time string (unless the start or end time is on a transition point).

<?php
$dt = new DateTime("2015-11-01 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt->modify("+24 hours");
echo "End:   ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>

Exemplul de mai sus va afi?a:

Start: 2015-11-01 00:00:00 -04:00
End:   2015-11-02 00:00:00 -05:00

Example #3 Adding or subtracting times can over- or underflow dates

Like where January 31st + 1 month will result in March 2nd (leap year) or 3rd (normal year).

<?php
echo "Normal year:\n"; // February has 28 days
$dt = new DateTime("2015-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt->modify("+1 month");
echo "End:   ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;

echo "Leap year:\n"; // February has 29 days
$dt = new DateTime("2016-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt->modify("+1 month");
echo "End:   ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>

Exemplul de mai sus va afi?a:

Normal year:
Start: 2015-01-31 00:00:00 -05:00
End:   2015-03-03 00:00:00 -05:00
Leap year:
Start: 2016-01-31 00:00:00 -05:00
End:   2016-03-02 00:00:00 -05:00

To get the last day of the next month (i.e. to prevent the overflow), the last day of format is available as of PHP 5.3.0.

<?php
echo "Normal year:\n"; // February has 28 days
$dt = new DateTime("2015-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt->modify("last day of next month");
echo "End:   ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;

echo "Leap year:\n"; // February has 29 days
$dt = new DateTime("2016-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt->modify("last day of next month");
echo "End:   ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>

Exemplul de mai sus va afi?a:

Normal year:
Start: 2015-01-31 00:00:00 -05:00
End:   2015-02-28 00:00:00 -05:00
Leap year:
Start: 2016-01-31 00:00:00 -05:00
End:   2016-02-29 00:00:00 -05:00

Exemple
DateTime
Exemple


The DateTime class

(PHP 5 >= 5.2.0, PHP 7)

Introducere

Representation of date and time.

Sinopsisul clasei

DateTime implements DateTimeInterface {
/* Constante */
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" ;
/* Metode */
public __construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
public DateTime add ( DateInterval $interval )
public static DateTime createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )
public static array getLastErrors ( 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 DateInterval diff ( DateTimeInterface $datetime2 [, bool $absolute = false ] )
public string format ( string $format )
public int getOffset ( void )
public int getTimestamp ( void )
public DateTimeZone getTimezone ( void )
public __wakeup ( void )
}

Constante predefinite

DateTime::ATOM
DATE_ATOM
Atom (example: 2005-08-15T15:52:01+00:00)
DateTime::COOKIE
DATE_COOKIE
HTTP Cookies (example: Monday, 15-Aug-2005 15:52:01 UTC)
DateTime::ISO8601
DATE_ISO8601
ISO-8601 (example: 2005-08-15T15:52:01+0000)

Nota: This format is not compatible with ISO-8601, but is left this way for backward compatibility reasons. Use DateTime::ATOM or DATE_ATOM for compatibility with ISO-8601 instead.

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 (example: 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 (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::W3C
DATE_W3C
World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | The class now implements DateTimeInterface.
5.4.24 | The COOKIE constant was changed to reflect RFC 1036 using a four digit year rather than a two digit year (RFC 850) as prior versions.
5.2.2 | DateTime object comparison with the comparison operators changed to work as expected. Previously, all DateTime objects were considered equal (using ==).

Cuprins

  • 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 — Parses a time string according to a specified format
  • DateTime::getLastErrors — Returns the warnings and errors
  • 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 Arithmetic
DateTime::add
Date/Time


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, PHP 7)

DateTime::add -- date_add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

Descrierea

Stil obiect-orientat

public DateTime DateTime::add ( DateInterval $interval )

Stil procedural

DateTime date_add ( DateTime $object , DateInterval $interval )

Adds the specified DateInterval object to the specified DateTime object.

Parametri

object

Doar stilul procedural: Un obiect DateTime întors de date_create(). Func?ia modifica acest obiect.

interval

A DateInterval object

Valorile întoarse

Întoarce obiectul DateTime pentru înlan?uirea metodelor sau FALSE în cazul e?ecului.

Exemple

Example #1 DateTime::add() example

Stil obiect-orientat

<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>

Stil procedural

<?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');
?>

Exemplele de mai sus vor afi?a:

2000-01-11

Example #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";
?>

Exemplul de mai sus va afi?a:

2000-01-01 10:00:30
2007-06-05 04:03:02

Example #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";
?>

Exemplul de mai sus va afi?a:

2001-01-31
2001-03-03

Note

DateTime::modify() is an alternative when using PHP 5.2.

A se vedea ?i

  • 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, PHP 7)

DateTime::__construct -- date_create — Returns new DateTime object

Descrierea

Stil obiect-orientat

public DateTime::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Stil procedural

DateTime date_create ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Returns new DateTime object.

Parametri

time

Un ?ir data/ora. Formatele valide sunt explicate în Formatele datelor ?i orelor.

Enter NULL here to obtain the current time when using the $timezone parameter.

timezone

A DateTimeZone object representing the timezone of $time.

If $timezone is omitted, the current timezone will be used.

Nota:

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).

Valorile întoarse

Returns a new DateTime instance. Stil procedural întoarce FALSE în caz de e?ec.

Erori/Excep?ii

Emits Exception in case of an error.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | If time contains an invalid date/time format, then an exception is now thrown. Previously an error was emitted.

Exemple

Example #1 DateTime::__construct() example

Stil obiect-orientat

<?php
try {
    $date = new DateTime('2000-01-01');
} catch (Exception $e) {
    echo $e->getMessage();
    exit(1);
}

echo $date->format('Y-m-d');
?>

Stil procedural

<?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');
?>

Exemplele de mai sus vor afi?a:

2000-01-01

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • DateTime::createFromFormat() - Parses a time string according to a 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() - Valideaza o data Gregoriana
DateTime::add
DateTime::createFromFormat
DateTime


Parses a time string according to a specified format

DateTime::__construct
DateTime::getLastErrors
DateTime
PHP Manual

DateTime::createFromFormat

date_create_from_format

(PHP 5 >= 5.3.0, PHP 7)

DateTime::createFromFormat -- date_create_from_format — Parses a time string according to a specified format

Descrierea

Stil obiect-orientat

public static DateTime DateTime::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )

Stil procedural

DateTime date_create_from_format ( string $format , string $time [, DateTimeZone $timezone ] )

Returns a new DateTime object representing the date and time specified by the time string, which was formatted in the given format.

Parametri

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 (which is assumed to be in the range 1970-2069, inclusive) | Examples: 99 or 03 (which will be interpreted as 1999 and 2003, respectively)
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 characters 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().

To include literal characters in format, you have to escape them with a backslash (\).

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.

Nota:

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).

Valorile întoarse

Returns a new DateTime instance sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.9 | The + format specifier has been added.

Exemple

Example #1 DateTime::createFromFormat() example

Stil obiect-orientat

<?php
$date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $date->format('Y-m-d');
?>

Stil procedural

<?php
$date = date_create_from_format('j-M-Y', '15-Feb-2009');
echo date_format($date, 'Y-m-d');
?>

Exemplele de mai sus vor afi?a:

2009-02-15

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Example #3 Format string with literal characters

<?php
echo DateTime::createFromFormat('H\h i\m s\s','23h 15m 03s')->format('H:i:s');
?>

Exemplul de mai sus va afi?a ceva similar cu:

23:15:03

A se vedea ?i

  • DateTime::__construct() - Returns new DateTime object
  • DateTime::getLastErrors() - Returns the warnings and errors
  • checkdate() - Valideaza o data Gregoriana
  • strptime() - Parse a time/date generated with strftime
DateTime::__construct
DateTime::getLastErrors
DateTime


Returns the warnings and errors

DateTime::createFromFormat
DateTime::modify
DateTime
PHP Manual

DateTime::getLastErrors

date_get_last_errors

(PHP 5 >= 5.3.0, PHP 7)

DateTime::getLastErrors -- date_get_last_errors — Returns the warnings and errors

Descrierea

Stil obiect-orientat

public static array DateTime::getLastErrors ( void )

Stil procedural

array date_get_last_errors ( void )

Returns an array of warnings and errors found while parsing a date/time string.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns array containing info about warnings and errors.

Exemple

Example #1 DateTime::getLastErrors() example

Stil obiect-orientat

<?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();
}
?>

Stil procedural

<?php
$date = date_create('asdfasdf');
print_r(date_get_last_errors());
?>

Exemplele de mai sus vor afi?a:

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
       )

)

The indexes 6, and 0 in the example output refer to the character index in the string where the error occurred.

DateTime::createFromFormat
DateTime::modify
DateTime


Alters the timestamp

DateTime::getLastErrors
DateTime::__set_state
DateTime
PHP Manual

DateTime::modify

date_modify

(PHP 5 >= 5.2.0, PHP 7)

DateTime::modify -- date_modify — Alters the timestamp

Descrierea

Stil obiect-orientat

public DateTime DateTime::modify ( string $modify )

Stil procedural

DateTime date_modify ( DateTime $object , string $modify )

Alter the timestamp of a DateTime object by incrementing or decrementing in a format accepted by strtotime().

Parametri

object

Doar stilul procedural: Un obiect DateTime întors de date_create(). Func?ia modifica acest obiect.

modify

Un ?ir data/ora. Formatele valide sunt explicate în Formatele datelor ?i orelor.

Valorile întoarse

Întoarce obiectul DateTime pentru înlan?uirea metodelor sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.6 | Absolute date/time statements now take effect. Previously, only relative parts were used.
5.3.0 | A fost schimbata valoarea întoarsa în caz de succes din NULL în DateTime.

Exemple

Example #1 DateTime::modify() example

Stil obiect-orientat

<?php
$date = new DateTime('2006-12-12');
$date->modify('+1 day');
echo $date->format('Y-m-d');
?>

Stil procedural

<?php
$date = date_create('2006-12-12');
date_modify($date, '+1 day');
echo date_format($date, 'Y-m-d');
?>

Exemplele de mai sus vor afi?a:

2006-12-13

Example #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";
?>

Exemplul de mai sus va afi?a:

2001-01-31
2001-03-03

A se vedea ?i

  • strtotime() - Transleaza aproape orice descriere textuala în limba engleza a datei ?i orei într-un timestamp Unix
  • 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::getLastErrors
DateTime::__set_state
DateTime


The __set_state handler

DateTime::modify
DateTime::setDate
DateTime
PHP Manual

DateTime::__set_state

(PHP 5 >= 5.2.0, PHP 7)

DateTime::__set_state — The __set_state handler

Descrierea

public static DateTime DateTime::__set_state ( array $array )

The __set_state() handler.

Parametri

array

Initialization array.

Valorile întoarse

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, PHP 7)

DateTime::setDate -- date_date_set — Sets the date

Descrierea

Stil obiect-orientat

public DateTime DateTime::setDate ( int $year , int $month , int $day )

Stil procedural

DateTime date_date_set ( DateTime $object , int $year , int $month , int $day )

Resets the current date of the DateTime object to a different date.

Parametri

object

Doar stilul procedural: Un obiect DateTime întors de date_create(). Func?ia modifica acest obiect.

year

Year of the date.

month

Month of the date.

day

Day of the date.

Valorile întoarse

Întoarce obiectul DateTime pentru înlan?uirea metodelor sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | A fost schimbata valoarea întoarsa în caz de succes din NULL în DateTime.

Exemple

Example #1 DateTime::setDate() example

Stil obiect-orientat

<?php
$date = new DateTime();
$date->setDate(2001, 2, 3);
echo $date->format('Y-m-d');
?>

Stil procedural

<?php
$date = date_create();
date_date_set($date, 2001, 2, 3);
echo date_format($date, 'Y-m-d');
?>

Exemplele de mai sus vor afi?a:

2001-02-03

Example #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";
?>

Exemplul de mai sus va afi?a:

2001-02-28
2001-03-01
2002-02-03

A se vedea ?i

  • 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, PHP 7)

DateTime::setISODate -- date_isodate_set — Sets the ISO date

Descrierea

Stil obiect-orientat

public DateTime DateTime::setISODate ( int $year , int $week [, int $day = 1 ] )

Stil procedural

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.

Parametri

object

Doar stilul procedural: Un obiect DateTime întors de date_create(). Func?ia modifica acest obiect.

year

Year of the date.

week

Week of the date.

day

Offset from the first day of the week.

Valorile întoarse

Întoarce obiectul DateTime pentru înlan?uirea metodelor sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | A fost schimbata valoarea întoarsa în caz de succes din NULL în DateTime.

Exemple

Example #1 DateTime::setISODate() example

Stil obiect-orientat

<?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";
?>

Stil procedural

<?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";
?>

Exemplele de mai sus vor afi?a:

2008-01-07
2008-01-13

Example #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";
?>

Exemplul de mai sus va afi?a:

2008-01-13
2008-01-14
2009-01-04

Example #3 Finding the month a week is in

<?php
$date = new DateTime();
$date->setISODate(2008, 14);
echo $date->format('n');
?>

Exemplele de mai sus vor afi?a:

3

A se vedea ?i

  • 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, PHP 7)

DateTime::setTime -- date_time_set — Sets the time

Descrierea

Stil obiect-orientat

public DateTime DateTime::setTime ( int $hour , int $minute [, int $second = 0 ] )

Stil procedural

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.

Parametri

object

Doar stilul procedural: Un obiect DateTime întors de date_create(). Func?ia modifica acest obiect.

hour

Hour of the time.

minute

Minute of the time.

second

Second of the time.

Valorile întoarse

Întoarce obiectul DateTime pentru înlan?uirea metodelor sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | A fost schimbata valoarea întoarsa în caz de succes din NULL în DateTime.

Exemple

Example #1 DateTime::setTime() example

Stil obiect-orientat

<?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";
?>

Stil procedural

<?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";
?>

Exemplele de mai sus vor afi?a ceva similar cu:

2001-01-01 14:55:00
2001-01-01 14:55:24

Example #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";
?>

Exemplul de mai sus va afi?a:

2001-01-01 14:55:24
2001-01-01 14:56:05
2001-01-01 15:05:24
2001-01-02 01:55:24

A se vedea ?i

  • 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, PHP 7)

DateTime::setTimestamp -- date_timestamp_set — Sets the date and time based on an Unix timestamp

Descrierea

Stil obiect-orientat

public DateTime DateTime::setTimestamp ( int $unixtimestamp )

Stil procedural

DateTime date_timestamp_set ( DateTime $object , int $unixtimestamp )

Sets the date and time based on an Unix timestamp.

Parametri

object

Doar stilul procedural: Un obiect DateTime întors de date_create(). Func?ia modifica acest obiect.

unixtimestamp

Unix timestamp representing the date.

Valorile întoarse

Întoarce obiectul DateTime pentru înlan?uirea metodelor sau FALSE în cazul e?ecului.

Exemple

Example #1 DateTime::setTimestamp() example

Stil obiect-orientat

<?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";
?>

Stil procedural

<?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";
?>

Exemplele de mai sus vor afi?a ceva similar cu:

1272508903 = 2010-04-28 22:41:43
1171502725 = 2007-02-14 20:25:25

Note

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.

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

1171502725 = 2007-02-14 20:25:25

A se vedea ?i

  • 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, PHP 7)

DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object

Descrierea

Stil obiect-orientat

public DateTime DateTime::setTimezone ( DateTimeZone $timezone )

Stil procedural

DateTime date_timezone_set ( DateTime $object , DateTimeZone $timezone )

Sets a new timezone for a DateTime object.

Parametri

object

Doar stilul procedural: Un obiect DateTime întors de date_create(). Func?ia modifica acest obiect.

timezone

A DateTimeZone object representing the desired time zone.

Valorile întoarse

Întoarce obiectul DateTime pentru înlan?uirea metodelor sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | A fost schimbata valoarea întoarsa în caz de succes din NULL în DateTime.

Exemple

Example #1 DateTime::setTimeZone() example

Stil obiect-orientat

<?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";
?>

Stil procedural

<?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";
?>

Exemplele de mai sus vor afi?a:

2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45

A se vedea ?i

  • 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
DateTimeImmutable
DateTime
PHP Manual

DateTime::sub

date_sub

(PHP 5 >= 5.3.0, PHP 7)

DateTime::sub -- date_sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

Descrierea

Stil obiect-orientat

public DateTime DateTime::sub ( DateInterval $interval )

Stil procedural

DateTime date_sub ( DateTime $object , DateInterval $interval )

Subtracts the specified DateInterval object from the specified DateTime object.

Parametri

object

Doar stilul procedural: Un obiect DateTime întors de date_create(). Func?ia modifica acest obiect.

interval

A DateInterval object

Valorile întoarse

Întoarce obiectul DateTime pentru înlan?uirea metodelor sau FALSE în cazul e?ecului.

Exemple

Example #1 DateTime::sub() example

Stil obiect-orientat

<?php
$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>

Stil procedural

<?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');
?>

Exemplele de mai sus vor afi?a:

2000-01-10

Example #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";
?>

Exemplul de mai sus va afi?a:

2000-01-19 13:59:30
1992-08-15 19:56:58

Example #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";
?>

Exemplul de mai sus va afi?a:

2001-03-30
2001-03-02

Note

DateTime::modify() is an alternative when using PHP 5.2.

A se vedea ?i

  • 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
DateTimeImmutable
DateTime


The DateTimeImmutable class

(PHP 5 >= 5.5.0, PHP 7)

Introducere

This class behaves the same as DateTime except it never modifies itself but returns a new object instead.

Sinopsisul clasei

DateTimeImmutable implements DateTimeInterface {
/* Metode */
public __construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
public DateTimeImmutable add ( DateInterval $interval )
public static DateTimeImmutable createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )
public static DateTimeImmutable createFromMutable ( DateTime $datetime )
public static array getLastErrors ( void )
public DateTimeImmutable modify ( string $modify )
public static DateTimeImmutable __set_state ( array $array )
public DateTimeImmutable setDate ( int $year , int $month , int $day )
public DateTimeImmutable setISODate ( int $year , int $week [, int $day = 1 ] )
public DateTimeImmutable setTime ( int $hour , int $minute [, int $second = 0 ] )
public DateTimeImmutable setTimestamp ( int $unixtimestamp )
public DateTimeImmutable setTimezone ( DateTimeZone $timezone )
public DateTimeImmutable sub ( DateInterval $interval )
public DateInterval diff ( DateTimeInterface $datetime2 [, bool $absolute = false ] )
public string format ( string $format )
public int getOffset ( void )
public int getTimestamp ( void )
public DateTimeZone getTimezone ( void )
public __wakeup ( void )
}

Cuprins

  • DateTimeImmutable::add — Adds an amount of days, months, years, hours, minutes and seconds
  • DateTimeImmutable::__construct — Returns new DateTimeImmutable object
  • DateTimeImmutable::createFromFormat — Returns new DateTimeImmutable object formatted according to the specified format
  • DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable object encapsulating the given DateTime object
  • DateTimeImmutable::getLastErrors — Returns the warnings and errors
  • DateTimeImmutable::modify — Creates a new object with modified timestamp
  • DateTimeImmutable::__set_state — The __set_state handler
  • DateTimeImmutable::setDate — Sets the date
  • DateTimeImmutable::setISODate — Sets the ISO date
  • DateTimeImmutable::setTime — Sets the time
  • DateTimeImmutable::setTimestamp — Sets the date and time based on an Unix timestamp
  • DateTimeImmutable::setTimezone — Sets the time zone
  • DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds
DateTime::sub
DateTimeImmutable::add
Date/Time


Adds an amount of days, months, years, hours, minutes and seconds

DateTimeImmutable
DateTimeImmutable::__construct
DateTimeImmutable
PHP Manual

DateTimeImmutable::add

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::add — Adds an amount of days, months, years, hours, minutes and seconds

Descrierea

public DateTimeImmutable DateTimeImmutable::add ( DateInterval $interval )

Like DateTime::add() but works with DateTimeImmutable.

DateTimeImmutable
DateTimeImmutable::__construct
DateTimeImmutable


Returns new DateTimeImmutable object

DateTimeImmutable::add
DateTimeImmutable::createFromFormat
DateTimeImmutable
PHP Manual

DateTimeImmutable::__construct

date_create_immutable

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::__construct -- date_create_immutable — Returns new DateTimeImmutable object

Descrierea

Stil obiect-orientat

public DateTimeImmutable::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Stil procedural

DateTimeImmutable date_create_immutable ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Like DateTime::__construct() but works with DateTimeImmutable.

DateTimeImmutable::add
DateTimeImmutable::createFromFormat
DateTimeImmutable


Returns new DateTimeImmutable object formatted according to the specified format

DateTimeImmutable::__construct
DateTimeImmutable::createFromMutable
DateTimeImmutable
PHP Manual

DateTimeImmutable::createFromFormat

date_create_immutable_from_format

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::createFromFormat -- date_create_immutable_from_format — Returns new DateTimeImmutable object formatted according to the specified format

Descrierea

Stil obiect-orientat

public static DateTimeImmutable DateTimeImmutable::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )

Stil procedural

DateTimeImmutable date_create_immutable_from_format ( string $format , string $time [, DateTimeZone $timezone ] )

Like DateTime::createFromFormat() but works with DateTimeImmutable.

DateTimeImmutable::__construct
DateTimeImmutable::createFromMutable
DateTimeImmutable


Returns new DateTimeImmutable object encapsulating the given DateTime object

DateTimeImmutable::createFromFormat
DateTimeImmutable::getLastErrors
DateTimeImmutable
PHP Manual

DateTimeImmutable::createFromMutable

(PHP 5 >= 5.6.0, PHP 7)

DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable object encapsulating the given DateTime object

Descrierea

public static DateTimeImmutable DateTimeImmutable::createFromMutable ( DateTime $datetime )

Parametri

datetime

The mutable DateTime object that you want to convert to an immutable version. This object is not modified, but instead a new DateTimeImmutable object is created containing the same date time and timezone information.

Exemple

Example #1 Creating an immutable date time object

<?php
$date = new DateTime("2014-06-20 11:45 Europe/London");

$immutable = DateTimeImmutable::createFromMutable( $date );
?>

Valorile întoarse

Returns a new DateTimeImmutable instance.

DateTimeImmutable::createFromFormat
DateTimeImmutable::getLastErrors
DateTimeImmutable


Returns the warnings and errors

DateTimeImmutable::createFromMutable
DateTimeImmutable::modify
DateTimeImmutable
PHP Manual

DateTimeImmutable::getLastErrors

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::getLastErrors — Returns the warnings and errors

Descrierea

public static array DateTimeImmutable::getLastErrors ( void )

Like DateTime::getLastErrors() but works with DateTimeImmutable.

DateTimeImmutable::createFromMutable
DateTimeImmutable::modify
DateTimeImmutable


Creates a new object with modified timestamp

DateTimeImmutable::getLastErrors
DateTimeImmutable::__set_state
DateTimeImmutable
PHP Manual

DateTimeImmutable::modify

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::modify — Creates a new object with modified timestamp

Descrierea

public DateTimeImmutable DateTimeImmutable::modify ( string $modify )

Creates a new DateTimeImmutable object with modified timestamp. The original object is not modified.

Parametri

object

Doar stilul procedural: Un obiect DateTime întors de date_create(). Func?ia modifica acest obiect.

modify

Un ?ir data/ora. Formatele valide sunt explicate în Formatele datelor ?i orelor.

Valorile întoarse

Returns the newly created object sau FALSE în cazul e?ecului.

DateTimeImmutable::getLastErrors
DateTimeImmutable::__set_state
DateTimeImmutable


The __set_state handler

DateTimeImmutable::modify
DateTimeImmutable::setDate
DateTimeImmutable
PHP Manual

DateTimeImmutable::__set_state

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::__set_state — The __set_state handler

Descrierea

public static DateTimeImmutable DateTimeImmutable::__set_state ( array $array )

Like DateTime::__set_state() but works with DateTimeImmutable.

DateTimeImmutable::modify
DateTimeImmutable::setDate
DateTimeImmutable


Sets the date

DateTimeImmutable::__set_state
DateTimeImmutable::setISODate
DateTimeImmutable
PHP Manual

DateTimeImmutable::setDate

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setDate — Sets the date

Descrierea

public DateTimeImmutable DateTimeImmutable::setDate ( int $year , int $month , int $day )

Like DateTime::setDate() but works with DateTimeImmutable.

DateTimeImmutable::__set_state
DateTimeImmutable::setISODate
DateTimeImmutable


Sets the ISO date

DateTimeImmutable::setDate
DateTimeImmutable::setTime
DateTimeImmutable
PHP Manual

DateTimeImmutable::setISODate

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setISODate — Sets the ISO date

Descrierea

public DateTimeImmutable DateTimeImmutable::setISODate ( int $year , int $week [, int $day = 1 ] )

Like DateTime::setISODate() but works with DateTimeImmutable.

DateTimeImmutable::setDate
DateTimeImmutable::setTime
DateTimeImmutable


Sets the time

DateTimeImmutable::setISODate
DateTimeImmutable::setTimestamp
DateTimeImmutable
PHP Manual

DateTimeImmutable::setTime

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setTime — Sets the time

Descrierea

public DateTimeImmutable DateTimeImmutable::setTime ( int $hour , int $minute [, int $second = 0 ] )

Like DateTime::setTime() but works with DateTimeImmutable.

DateTimeImmutable::setISODate
DateTimeImmutable::setTimestamp
DateTimeImmutable


Sets the date and time based on an Unix timestamp

DateTimeImmutable::setTime
DateTimeImmutable::setTimezone
DateTimeImmutable
PHP Manual

DateTimeImmutable::setTimestamp

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setTimestamp — Sets the date and time based on an Unix timestamp

Descrierea

public DateTimeImmutable DateTimeImmutable::setTimestamp ( int $unixtimestamp )

Like DateTime::setTimestamp() but works with DateTimeImmutable.

DateTimeImmutable::setTime
DateTimeImmutable::setTimezone
DateTimeImmutable


Sets the time zone

DateTimeImmutable::setTimestamp
DateTimeImmutable::sub
DateTimeImmutable
PHP Manual

DateTimeImmutable::setTimezone

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setTimezone — Sets the time zone

Descrierea

public DateTimeImmutable DateTimeImmutable::setTimezone ( DateTimeZone $timezone )

Like DateTime::setTimezone() but works with DateTimeImmutable.

DateTimeImmutable::setTimestamp
DateTimeImmutable::sub
DateTimeImmutable


Subtracts an amount of days, months, years, hours, minutes and seconds

DateTimeImmutable::setTimezone
DateTimeInterface
DateTimeImmutable
PHP Manual

DateTimeImmutable::sub

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds

Descrierea

public DateTimeImmutable DateTimeImmutable::sub ( DateInterval $interval )

Like DateTime::sub() but works with DateTimeImmutable.

DateTimeImmutable::setTimezone
DateTimeInterface
DateTimeImmutable


The DateTimeInterface interface

(PHP 5 >= 5.5.0, PHP 7)

Introducere

DateTimeInterface is meant so that both DateTime and DateTimeImmutable can be type hinted for. It is not possible to implement this interface with userland classes.

Sinopsisul clasei

DateTimeInterface {
/* Metode */
public DateInterval diff ( DateTimeInterface $datetime2 [, bool $absolute = false ] )
public string format ( string $format )
public int getOffset ( void )
public int getTimestamp ( void )
public DateTimeZone getTimezone ( void )
public __wakeup ( void )
}

Istoricul schimbarilor

Versiune | Descriere
5.5.8 | Trying to implement DateTimeInterface raises a fatal error now. Formerly implementing the interface didn't raise an error, but the behavior was erroneous.

Cuprins

  • DateTime::diff — Returns the difference between two DateTime objects
  • DateTime::format — Returns date formatted according to given format
  • DateTime::getOffset — Returns the timezone offset
  • DateTime::getTimestamp — Gets the Unix timestamp
  • DateTime::getTimezone — Return time zone relative to given DateTime
  • DateTime::__wakeup — The __wakeup handler
DateTimeImmutable::sub
DateTime::diff
Date/Time


Returns the difference between two DateTime objects

DateTimeInterface
DateTime::format
DateTimeInterface
PHP Manual

DateTime::diff

DateTimeImmutable::diff

DateTimeInterface::diff

date_diff

(PHP 5 >= 5.3.0, PHP 7)

DateTime::diff -- DateTimeImmutable::diff -- DateTimeInterface::diff -- date_diff — Returns the difference between two DateTime objects

Descrierea

Stil obiect-orientat

public DateInterval DateTime::diff ( DateTimeInterface $datetime2 [, bool $absolute = false ] )
public DateInterval DateTimeImmutable::diff ( DateTimeInterface $datetime2 [, bool $absolute = false ] )
public DateInterval DateTimeInterface::diff ( DateTimeInterface $datetime2 [, bool $absolute = false ] )

Stil procedural

DateInterval date_diff ( DateTimeInterface $datetime1 , DateTimeInterface $datetime2 [, bool $absolute = false ] )

Returns the difference between two DateTimeInterface objects.

Parametri

datetime

The date to compare to.

absolute

Should the interval be forced to be positive?

Valorile întoarse

The DateInterval object representing the difference between the two dates sau FALSE în cazul e?ecului.

Exemple

Example #1 DateTime::diff() example

Stil obiect-orientat

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

Stil procedural

<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>

Exemplele de mai sus vor afi?a:

+2 days

Example #2 DateTime object comparison

Nota:

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);
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
bool(false)

A se vedea ?i

  • 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
DateTimeInterface
DateTime::format
DateTimeInterface


Returns date formatted according to given format

DateTime::diff
DateTime::getOffset
DateTimeInterface
PHP Manual

DateTime::format

DateTimeImmutable::format

DateTimeInterface::format

date_format

(PHP 5 >= 5.2.0, PHP 7)

DateTime::format -- DateTimeImmutable::format -- DateTimeInterface::format -- date_format — Returns date formatted according to given format

Descrierea

Stil obiect-orientat

public string DateTime::format ( string $format )
public string DateTimeImmutable::format ( string $format )
public string DateTimeInterface::format ( string $format )

Stil procedural

string date_format ( DateTimeInterface $object , string $format )

Returns date formatted according to given format.

Parametri

object

Doar pentru stilul procedural: Un obiect DateTime întors de func?ia date_create()

format

Format accepted by date().

Valorile întoarse

Returns the formatted date string on success sau FALSE în cazul e?ecului.

Exemple

Example #1 DateTime::format() example

Stil obiect-orientat

<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

Stil procedural

<?php
$date = date_create('2000-01-01');
echo date_format($date, 'Y-m-d H:i:s');
?>

Exemplul de mai sus va afi?a:

2000-01-01 00:00:00

Note

This method does not use locales. All output is in English.

A se vedea ?i

  • date() - Formateaza o ora/data
DateTime::diff
DateTime::getOffset
DateTimeInterface


Returns the timezone offset

DateTime::format
DateTime::getTimestamp
DateTimeInterface
PHP Manual

DateTime::getOffset

DateTimeImmutable::getOffset

DateTimeInterface::getOffset

date_offset_get

(PHP 5 >= 5.2.0, PHP 7)

DateTime::getOffset -- DateTimeImmutable::getOffset -- DateTimeInterface::getOffset -- date_offset_get — Returns the timezone offset

Descrierea

Stil obiect-orientat

public int DateTime::getOffset ( void )
public int DateTimeImmutable::getOffset ( void )
public int DateTimeInterface::getOffset ( void )

Stil procedural

int date_offset_get ( DateTimeInterface $object )

Returns the timezone offset.

Parametri

object

Doar pentru stilul procedural: Un obiect DateTime întors de func?ia date_create()

Valorile întoarse

Returns the timezone offset in seconds from UTC on success sau FALSE în cazul e?ecului.

Exemple

Example #1 DateTime::getOffset() example

Stil obiect-orientat

<?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";
?>

Stil procedural

<?php
$winter = date_create('2010-12-21', timezone_open('America/New_York'));
$summer = date_create('2008-06-21', timezone_open('America/New_York'));

echo date_offset_get($winter) . "\n";
echo date_offset_get($summer) . "\n";
?>

Exemplele de mai sus vor afi?a:

-18000
-14400

Note: -18000 = -5 hours, -14400 = -4 hours.

DateTime::format
DateTime::getTimestamp
DateTimeInterface


Gets the Unix timestamp

DateTime::getOffset
DateTime::getTimezone
DateTimeInterface
PHP Manual

DateTime::getTimestamp

DateTimeImmutable::getTimestamp

DateTimeInterface::getTimestamp

date_timestamp_get

(PHP 5 >= 5.3.0, PHP 7)

DateTime::getTimestamp -- DateTimeImmutable::getTimestamp -- DateTimeInterface::getTimestamp -- date_timestamp_get — Gets the Unix timestamp

Descrierea

Stil obiect-orientat

public int DateTime::getTimestamp ( void )
public int DateTimeImmutable::getTimestamp ( void )
public int DateTimeInterface::getTimestamp ( void )

Stil procedural

int date_timestamp_get ( DateTimeInterface $object )

Gets the Unix timestamp.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the Unix timestamp representing the date.

Exemple

Example #1 DateTime::getTimestamp() example

Stil obiect-orientat

<?php
$date = new DateTime();
echo $date->getTimestamp();
?>

Stil procedural

<?php
$date = date_create();
echo date_timestamp_get($date);
?>

Exemplele de mai sus vor afi?a ceva similar cu:

1272509157

Note

Using U as the parameter to DateTime::format() is an alternative when using PHP 5.2.

A se vedea ?i

  • 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
DateTimeInterface


Return time zone relative to given DateTime

DateTime::getTimestamp
DateTime::__wakeup
DateTimeInterface
PHP Manual

DateTime::getTimezone

DateTimeImmutable::getTimezone

DateTimeInterface::getTimezone

date_timezone_get

(PHP 5 >= 5.2.0, PHP 7)

DateTime::getTimezone -- DateTimeImmutable::getTimezone -- DateTimeInterface::getTimezone -- date_timezone_get — Return time zone relative to given DateTime

Descrierea

Stil obiect-orientat

public DateTimeZone DateTime::getTimezone ( void )
public DateTimeZone DateTimeImmutable::getTimezone ( void )
public DateTimeZone DateTimeInterface::getTimezone ( void )

Stil procedural

DateTimeZone date_timezone_get ( DateTimeInterface $object )

Return time zone relative to given DateTime.

Parametri

object

Doar pentru stilul procedural: Un obiect DateTime întors de func?ia date_create()

Valorile întoarse

Returns a DateTimeZone object on success sau FALSE în cazul e?ecului.

Exemple

Example #1 DateTime::getTimezone() example

Stil obiect-orientat

<?php
$date = new DateTime(null, new DateTimeZone('Europe/London'));
$tz = $date->getTimezone();
echo $tz->getName();
?>

Stil procedural

<?php
$date = date_create(null, timezone_open('Europe/London'));
$tz = date_timezone_get($date);
echo timezone_name_get($tz);
?>

Exemplele de mai sus vor afi?a:

Europe/London

A se vedea ?i

  • DateTime::setTimezone() - Sets the time zone for the DateTime object
DateTime::getTimestamp
DateTime::__wakeup
DateTimeInterface


The __wakeup handler

DateTime::getTimezone
DateTimeZone
DateTimeInterface
PHP Manual

DateTime::__wakeup

DateTimeImmutable::__wakeup

DateTimeInterface::__wakeup

(PHP 5 >= 5.2.0, PHP 7)

DateTime::__wakeup -- DateTimeImmutable::__wakeup -- DateTimeInterface::__wakeup — The __wakeup handler

Descrierea

public DateTime::__wakeup ( void )
public DateTimeImmutable::__wakeup ( void )
public DateTimeInterface::__wakeup ( void )

The __wakeup() handler.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Initializes a DateTime object.

DateTime::getTimezone
DateTimeZone
DateTimeInterface


The DateTimeZone class

(PHP 5 >= 5.2.0, PHP 7)

Introducere

Representation of time zone.

Sinopsisul clasei

DateTimeZone {
/* Constante */
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 ;
/* Metode */
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 ]] )
}

Constante predefinite

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.

Cuprins

  • 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 a numerically indexed array containing all defined timezone identifiers
DateTime::__wakeup
DateTimeZone::__construct
Date/Time


Creates new DateTimeZone object

DateTimeZone
DateTimeZone::getLocation
DateTimeZone
PHP Manual

DateTimeZone::__construct

timezone_open

(PHP 5 >= 5.2.0, PHP 7)

DateTimeZone::__construct -- timezone_open — Creates new DateTimeZone object

Descrierea

Stil obiect-orientat

public DateTimeZone::__construct ( string $timezone )

Stil procedural

DateTimeZone timezone_open ( string $timezone )

Creates new DateTimeZone object.

Parametri

timezone

One of the supported timezone names.

Valorile întoarse

Returns DateTimeZone on success. Stil procedural întoarce FALSE în caz de e?ec.

Erori/Excep?ii

This method throws Exception if the timezone supplied is not recognised as a valid timezone.

Exemple

Example #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 />';
    }
}
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

DateTimeZone::getLocation -- timezone_location_get — Returns location information for a timezone

Descrierea

Stil obiect-orientat

public array DateTimeZone::getLocation ( void )

Stil procedural

array timezone_location_get ( DateTimeZone $object )

Returns location information for a timezone, including country code, latitude/longitude and comments.

Parametri

object

Doar pentru stilul procedural: Un obiect DateTimeZone întors de func?ia timezone_open()

Valorile întoarse

Array containing location information about timezone.

Exemple

Example #1 DateTimeZone::getLocation() example

<?php
$tz = new DateTimeZone("Europe/Prague");
print_r($tz->getLocation());
print_r(timezone_location_get($tz));
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

DateTimeZone::getName -- timezone_name_get — Returns the name of the timezone

Descrierea

Stil obiect-orientat

public string DateTimeZone::getName ( void )

Stil procedural

string timezone_name_get ( DateTimeZone $object )

Returns the name of the timezone.

Parametri

object

The DateTimeZone for which to get a name.

Valorile întoarse

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, PHP 7)

DateTimeZone::getOffset -- timezone_offset_get — Returns the timezone offset from GMT

Descrierea

Stil obiect-orientat

public int DateTimeZone::getOffset ( DateTime $datetime )

Stil procedural

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.

Parametri

object

Doar pentru stilul procedural: Un obiect DateTimeZone întors de func?ia timezone_open()

datetime

DateTime that contains the date/time to compute the offset from.

Valorile întoarse

Returns time zone offset in seconds on success sau FALSE în cazul e?ecului.

Exemple

Example #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, PHP 7)

DateTimeZone::getTransitions -- timezone_transitions_get — Returns all transitions for the timezone

Descrierea

Stil obiect-orientat

public array DateTimeZone::getTransitions ([ int $timestamp_begin [, int $timestamp_end ]] )

Stil procedural

array timezone_transitions_get ( DateTimeZone $object [, int $timestamp_begin [, int $timestamp_end ]] )

Parametri

object

Doar pentru stilul procedural: Un obiect DateTimeZone întors de func?ia timezone_open()

timestamp_begin

Begin timestamp.

timestamp_end

End timestamp.

Valorile întoarse

Returns numerically indexed array containing associative array with all transitions on success sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | The optional timestamp_begin and timestamp_end were added.

Exemple

Example #1 A timezone_transitions_get() example

<?php
$timezone = new DateTimeZone("Europe/London");
$transitions = $timezone->getTransitions();
print_r(array_slice($transitions, 0, 3));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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, PHP 7)

DateTimeZone::listAbbreviations -- timezone_abbreviations_list — Returns associative array containing dst, offset and the timezone name

Descrierea

Stil obiect-orientat

public static array DateTimeZone::listAbbreviations ( void )

Stil procedural

array timezone_abbreviations_list ( void )

Valorile întoarse

Returns array on success sau FALSE în cazul e?ecului.

Exemple

Example #1 A timezone_abbreviations_list() example

<?php
$timezone_abbreviations = DateTimeZone::listAbbreviations();
print_r($timezone_abbreviations["acst"]);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

)

A se vedea ?i

  • timezone_identifiers_list() - Pseudonim pentru DateTimeZone::listIdentifiers

DateTimeZone::getTransitions
DateTimeZone::listIdentifiers
DateTimeZone


Returns a numerically indexed array containing all defined timezone identifiers

DateTimeZone::listAbbreviations
DateInterval
DateTimeZone
PHP Manual

DateTimeZone::listIdentifiers

timezone_identifiers_list

(PHP 5 >= 5.2.0, PHP 7)

DateTimeZone::listIdentifiers -- timezone_identifiers_list — Returns a numerically indexed array containing all defined timezone identifiers

Descrierea

Stil obiect-orientat

public static array DateTimeZone::listIdentifiers ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )

Stil procedural

array timezone_identifiers_list ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )

Parametri

what

One of DateTimeZone class constants.

country

A two-letter ISO 3166-1 compatible country code.

Nota: This option is only used when what is set to DateTimeZone::PER_COUNTRY.

Valorile întoarse

Returns array on success sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Added the optional what and country parameters.

Exemple

Example #1 A timezone_identifiers_list() example

<?php
$timezone_identifiers = DateTimeZone::listIdentifiers();
for ($i=0; $i < 5; $i++) {
    echo "$timezone_identifiers[$i]\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara

A se vedea ?i

  • timezone_abbreviations_list() - Pseudonim pentru DateTimeZone::listAbbreviations

DateTimeZone::listAbbreviations
DateInterval
DateTimeZone


The DateInterval class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

Represents a 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.

Sinopsisul clasei

DateInterval {
/* Proprieta?i */
public integer $y ;
public integer $m ;
public integer $d ;
public integer $h ;
public integer $i ;
public integer $s ;
public integer $invert ;
public mixed $days ;
/* Metode */
public __construct ( string $interval_spec )
public static DateInterval createFromDateString ( string $time )
public string format ( string $format )
}

Proprieta?i

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 represents a negative time period and 0 otherwise. See DateInterval::format().

days

If the DateInterval object was created by DateTime::diff(), then this is the total number of days between the start and end dates. Otherwise, days will be FALSE.

Before PHP 5.4.20/5.5.4 instead of FALSE you will receive -99999 upon accessing the property.

Cuprins

  • DateInterval::__construct — Creates a 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
Date/Time


Creates a new DateInterval object

DateInterval
DateInterval::createFromDateString
DateInterval
PHP Manual

DateInterval::__construct

(PHP 5 >= 5.3.0, PHP 7)

DateInterval::__construct — Creates a new DateInterval object

Descrierea

public DateInterval::__construct ( string $interval_spec )

Creates a new DateInterval object.

Parametri

interval_spec

An 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.

Nota:

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.

Erori/Excep?ii

Throws an Exception when the interval_spec cannot be parsed as an interval.

Exemple

Example #1 DateInterval example

<?php

$interval = new DateInterval('P2Y4DT6H8M');
var_dump($interval);

?>

Exemplul de mai sus va afi?a:

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)
}

A se vedea ?i

  • 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, PHP 7)

DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string

Descrierea

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.

Parametri

time

A date with relative parts. Specifically, the relative formats supported by the parser used for strtotime() and DateTime will be used to construct the DateInterval.

Exemple

Example #1 Parsing valid date intervals

<?php
// Each set of intervals is equal.
$i = new DateInterval('P1D');
$i = DateInterval::createFromDateString('1 day');

$i = new DateInterval('P2W');
$i = DateInterval::createFromDateString('2 weeks');

$i = new DateInterval('P3M');
$i = DateInterval::createFromDateString('3 months');

$i = new DateInterval('P4Y');
$i = DateInterval::createFromDateString('4 years');

$i = new DateInterval('P1Y1D');
$i = DateInterval::createFromDateString('1 year + 1 day');

$i = new DateInterval('P1DT12H');
$i = DateInterval::createFromDateString('1 day + 12 hours');

$i = new DateInterval('PT3600S');
$i = DateInterval::createFromDateString('3600 seconds');
?>

Valorile întoarse

Returns a new DateInterval instance.

DateInterval::__construct
DateInterval::format
DateInterval


Formats the interval

DateInterval::createFromDateString
DatePeriod
DateInterval
PHP Manual

DateInterval::format

(PHP 5 >= 5.3.0, PHP 7)

DateInterval::format — Formats the interval

Descrierea

public string DateInterval::format ( string $format )

Formats the interval.

Parametri

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 number of days as a result of a DateTime::diff() or (unknown) otherwise | 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 -,

Valorile întoarse

Returns the formatted interval.

Note

Nota:

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".

Exemple

Example #1 DateInterval example

<?php

$interval = new DateInterval('P2Y4DT6H8M');
echo $interval->format('%d days');

?>

Exemplul de mai sus va afi?a:

4 days

Example #2 DateInterval and carry over points

<?php

$interval = new DateInterval('P32D');
echo $interval->format('%d days');

?>

Exemplul de mai sus va afi?a:

32 days

Example #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');

?>

Exemplul de mai sus va afi?a:

31 total days
1 month, 0 days

A se vedea ?i

  • DateTime::diff() - Returns the difference between two DateTime objects

DateInterval::createFromDateString
DatePeriod
DateInterval


The DatePeriod class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

Represents a date period.

A date period allows iteration over a set of dates and times, recurring at regular intervals, over a given period.

Sinopsisul clasei

DatePeriod implements Traversable {
/* Constante */
const integer EXCLUDE_START_DATE = 1 ;
/* Metode */
public __construct ( DateTimeInterface $start , DateInterval $interval , int $recurrences [, int $options ] )
public __construct ( DateTimeInterface $start , DateInterval $interval , DateTimeInterface $end [, int $options ] )
public __construct ( string $isostr [, int $options ] )
public DateInterval getDateInterval ( void )
public DateTimeInterface getEndDate ( void )
public DateTimeInterface getStartDate ( void )
}

Constante predefinite

DatePeriod::EXCLUDE_START_DATE

Exclude start date, used in DatePeriod::__construct().

Cuprins

  • DatePeriod::__construct — Creates a new DatePeriod object
  • DatePeriod::getDateInterval — Gets the interval
  • DatePeriod::getEndDate — Gets the end date
  • DatePeriod::getStartDate — Gets the start date
DateInterval::format
DatePeriod::__construct
Date/Time


Creates a new DatePeriod object

DatePeriod
DatePeriod::getDateInterval
DatePeriod
PHP Manual

DatePeriod::__construct

(PHP 5 >= 5.3.0, PHP 7)

DatePeriod::__construct — Creates a new DatePeriod object

Descrierea

public DatePeriod::__construct ( DateTimeInterface $start , DateInterval $interval , int $recurrences [, int $options ] )
public DatePeriod::__construct ( DateTimeInterface $start , DateInterval $interval , DateTimeInterface $end [, int $options ] )
public DatePeriod::__construct ( string $isostr [, int $options ] )

Creates a new DatePeriod object.

Parametri

start

The start date of the period.

interval

The interval between recurrences within the period.

recurrences

The number of recurrences.

end

The end date of the period.

isostr

An ISO 8601 repeating interval specification.

options

Can be set to DatePeriod::EXCLUDE_START_DATE to exclude the start date from the set of recurring dates within the period.

Istoricul schimbarilor

Versiune | Descriere
5.5.8 | end type changed to DateTimeInterface. Previously, DateTime.
5.5.0 | start type changed to DateTimeInterface. Previously, DateTime.

Exemple

Example #1 DatePeriod example

<?php
$start = new DateTime('2012-07-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2012-07-31');
$recurrences = 4;
$iso = 'R4/2012-07-01T00:00:00Z/P7D';

// All of these periods are equivalent.
$period = new DatePeriod($start, $interval, $recurrences);
$period = new DatePeriod($start, $interval, $end);
$period = new DatePeriod($iso);

// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
foreach ($period as $date) {
    echo $date->format('Y-m-d')."\n";
}
?>

Exemplul de mai sus va afi?a:

2012-07-01
2012-07-08
2012-07-15
2012-07-22
2012-07-29

Example #2 DatePeriod example with DatePeriod::EXCLUDE_START_DATE

<?php
$start = new DateTime('2012-07-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2012-07-31');

$period = new DatePeriod($start, $interval, $end,
                         DatePeriod::EXCLUDE_START_DATE);

// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
// Note that, in this case, 2012-07-01 is not printed.
foreach ($period as $date) {
    echo $date->format('Y-m-d')."\n";
}
?>

Exemplul de mai sus va afi?a:

2012-07-08
2012-07-15
2012-07-22
2012-07-29

Note

Unbound numbers of repetitions as specified by ISO 8601 section 4.5 "Recurring time interval" are not supported, i.e. neither passing "R/..." as isostr nor passing NULL as end would work.

DatePeriod
DatePeriod::getDateInterval
DatePeriod


Gets the interval

DatePeriod::__construct
DatePeriod::getEndDate
DatePeriod
PHP Manual

DatePeriod::getDateInterval

(PHP 5 >= 5.6.5, PHP 7)

DatePeriod::getDateInterval — Gets the interval

Descrierea

Stil obiect-orientat

public DateInterval DatePeriod::getDateInterval ( void )

Gets a DateInterval object representing the interval used for the period.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a DateInterval object

Exemple

Example #1 DatePeriod::getDateInterval() example

<?php
$period = new DatePeriod('R7/2016-05-16T00:00:00Z/P1D');
$interval = $period->getDateInterval();
echo $interval->format('%d day');
?>

Exemplul de mai sus va afi?a:

1 day

A se vedea ?i

  • DatePeriod::getStartDate() - Gets the start date
  • DatePeriod::getEndDate() - Gets the end date
DatePeriod::__construct
DatePeriod::getEndDate
DatePeriod


Gets the end date

DatePeriod::getDateInterval
DatePeriod::getStartDate
DatePeriod
PHP Manual

DatePeriod::getEndDate

(PHP 5 >= 5.6.5, PHP 7)

DatePeriod::getEndDate — Gets the end date

Descrierea

Stil obiect-orientat

public DateTimeInterface DatePeriod::getEndDate ( void )

Gets the end date of the period.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns NULL if the DatePeriod does not have an end date. For example, when initialized with the recurrences parameter, or the isostr parameter without an end date.

Returns a DateTimeImmutable object when the DatePeriod is initialized with a DateTimeImmutable object as the end parameter.

Returns a DateTime object otherwise.

Exemple

Example #1 DatePeriod::getEndDate() example

<?php
$period = new DatePeriod(
    new DateTime('2016-05-16T00:00:00Z'),
    new DateInterval('P1D'),
    new DateTime('2016-05-20T00:00:00Z')
);
$start = $period->getEndDate();
echo $start->format(DateTime::ISO8601);
?>

Exemplele de mai sus vor afi?a:

2016-05-20T00:00:00+0000

Example #2 DatePeriod::getEndDate() without an end date

<?php
$period = new DatePeriod(
    new DateTime('2016-05-16T00:00:00Z'),
    new DateInterval('P1D'),
    7
);
var_dump($period->getEndDate());
?>

Exemplul de mai sus va afi?a:

NULL

A se vedea ?i

  • DatePeriod::getStartDate() - Gets the start date
  • DatePeriod::getDateInterval() - Gets the interval
DatePeriod::getDateInterval
DatePeriod::getStartDate
DatePeriod


Gets the start date

DatePeriod::getEndDate
Func?ii de Data/Timp
DatePeriod
PHP Manual

DatePeriod::getStartDate

(PHP 5 >= 5.6.5, PHP 7)

DatePeriod::getStartDate — Gets the start date

Descrierea

Stil obiect-orientat

public DateTimeInterface DatePeriod::getStartDate ( void )

Gets the start date of the period.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a DateTimeImmutable object when the DatePeriod is initialized with a DateTimeImmutable object as the start parameter.

Returns a DateTime object otherwise.

Exemple

Example #1 DatePeriod::getStartDate() example

<?php
$period = new DatePeriod('R7/2016-05-16T00:00:00Z/P1D');
$start = $period->getStartDate();
echo $start->format(DateTime::ISO8601);
?>

Exemplul de mai sus va afi?a:

2016-05-16T00:00:00+0000

A se vedea ?i

  • DatePeriod::getEndDate() - Gets the end date
  • DatePeriod::getDateInterval() - Gets the interval
DatePeriod::getEndDate
Func?ii de Data/Timp
DatePeriod


Func?ii de Data/Timp

Cuprins

  • checkdate — Valideaza o data Gregoriana
  • date_add — Pseudonim pentru DateTime::add
  • date_create_from_format — Pseudonim pentru DateTime::createFromFormat
  • date_create_immutable_from_format — Pseudonim pentru DateTimeImmutable::createFromFormat
  • date_create_immutable — Pseudonim pentru DateTimeImmutable::__construct
  • date_create — Pseudonim pentru DateTime::__construct
  • date_date_set — Pseudonim pentru 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 — Pseudonim pentru DateTime::diff
  • date_format — Pseudonim pentru DateTime::format
  • date_get_last_errors — Pseudonim pentru DateTime::getLastErrors
  • date_interval_create_from_date_string — Pseudonim pentru DateInterval::createFromDateString
  • date_interval_format — Pseudonim pentru DateInterval::format
  • date_isodate_set — Pseudonim pentru DateTime::setISODate
  • date_modify — Pseudonim pentru DateTime::modify
  • date_offset_get — Pseudonim pentru 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 — Pseudonim pentru 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 — Pseudonim pentru DateTime::setTime
  • date_timestamp_get — Pseudonim pentru DateTime::getTimestamp
  • date_timestamp_set — Pseudonim pentru DateTime::setTimestamp
  • date_timezone_get — Pseudonim pentru DateTime::getTimezone
  • date_timezone_set — Pseudonim pentru DateTime::setTimezone
  • date — Formateaza o ora/data
  • getdate — Ob?ine informa?ia despre data/ora
  • gettimeofday — Ob?ine timpul curent
  • gmdate — Formateaza o data/ora GMT/UTC
  • gmmktime — Ob?ine momentul de timp Unix pentru o data GMT
  • gmstrftime — Formateaza o data/ora GMT/UTC în conformitate cu setarile locale
  • idate — Format a local time/date as integer
  • localtime — Ob?ine timpul local
  • microtime — Întoarce timpul curent Unix cu microsecunde
  • mktime — Ob?ine timestamp-ul Unix pentru o data ?i ora
  • strftime — Formateaza o ora/data locala în conformitate cu setarile locale
  • strptime — Parse a time/date generated with strftime
  • strtotime — Transleaza aproape orice descriere textuala în limba engleza a datei ?i orei într-un timestamp Unix
  • time — Întoarce timpul curent Unix
  • timezone_abbreviations_list — Pseudonim pentru DateTimeZone::listAbbreviations
  • timezone_identifiers_list — Pseudonim pentru DateTimeZone::listIdentifiers
  • timezone_location_get — Pseudonim pentru DateTimeZone::getLocation
  • timezone_name_from_abbr — Returns the timezone name from abbreviation
  • timezone_name_get — Pseudonim pentru DateTimeZone::getName
  • timezone_offset_get — Pseudonim pentru DateTimeZone::getOffset
  • timezone_open — Pseudonim pentru DateTimeZone::__construct
  • timezone_transitions_get — Pseudonim pentru DateTimeZone::getTransitions
  • timezone_version_get — Gets the version of the timezonedb
DatePeriod::getStartDate
checkdate
Date/Time


Valideaza o data Gregoriana

Func?ii de Data/Timp
date_add
Func?ii de Data/Timp
PHP Manual

checkdate

(PHP 4, PHP 5, PHP 7)

checkdate — Valideaza o data Gregoriana

Descrierea

bool checkdate ( int $month , int $day , int $year )

Verifica validitatea datei formate din argumen?i. O data este considerata valida daca fiecare parametru este definit corespunzator.

Parametri

month

Luna este între 1 ?i 12 inclusiv.

day

Ziua este cuprinsa în domeniul zilelor permise pentru luna respectiva. Anii bisec?i sunt lua?i în considerare.

year

Anul este între 1 ?i 32767 inclusiv.

Valorile întoarse

Întoarce TRUE daca data este valida; în caz contrar întoarce FALSE.

Exemple

Example #1 Exemplu checkdate()

<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)

A se vedea ?i

  • mktime() - Ob?ine timestamp-ul Unix pentru o data ?i ora
  • strtotime() - Transleaza aproape orice descriere textuala în limba engleza a datei ?i orei într-un timestamp Unix

Func?ii de Data/Timp
date_add
Func?ii de Data/Timp


Pseudonim pentru DateTime::add

checkdate
date_create_from_format
Func?ii de Data/Timp
PHP Manual

date_add

(PHP 5 >= 5.3.0, PHP 7)

date_add — Pseudonim pentru DateTime::add()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::add()

checkdate
date_create_from_format
Func?ii de Data/Timp


Pseudonim pentru DateTime::createFromFormat

date_add
date_create_immutable_from_format
Func?ii de Data/Timp
PHP Manual

date_create_from_format

(PHP 5 >= 5.3.0, PHP 7)

date_create_from_format — Pseudonim pentru DateTime::createFromFormat()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::createFromFormat()

date_add
date_create_immutable_from_format
Func?ii de Data/Timp


Pseudonim pentru DateTimeImmutable::createFromFormat

date_create_from_format
date_create_immutable
Func?ii de Data/Timp
PHP Manual

date_create_immutable_from_format

(PHP 5 >= 5.5.0, PHP 7)

date_create_immutable_from_format — Pseudonim pentru DateTimeImmutable::createFromFormat()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTimeImmutable::createFromFormat()

date_create_from_format
date_create_immutable
Func?ii de Data/Timp


Pseudonim pentru DateTimeImmutable::__construct

date_create_immutable_from_format
date_create
Func?ii de Data/Timp
PHP Manual

date_create_immutable

(PHP 5 >= 5.5.0, PHP 7)

date_create_immutable — Pseudonim pentru DateTimeImmutable::__construct()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTimeImmutable::__construct()

date_create_immutable_from_format
date_create
Func?ii de Data/Timp


Pseudonim pentru DateTime::__construct

date_create_immutable
date_date_set
Func?ii de Data/Timp
PHP Manual

date_create

(PHP 5 >= 5.2.0, PHP 7)

date_create — Pseudonim pentru DateTime::__construct()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::__construct()

date_create_immutable
date_date_set
Func?ii de Data/Timp


Pseudonim pentru DateTime::setDate

date_create
date_default_timezone_get
Func?ii de Data/Timp
PHP Manual

date_date_set

(PHP 5 >= 5.2.0, PHP 7)

date_date_set — Pseudonim pentru DateTime::setDate()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::setDate()

date_create
date_default_timezone_get
Func?ii de Data/Timp


Gets the default timezone used by all date/time functions in a script

date_date_set
date_default_timezone_set
Func?ii de Data/Timp
PHP Manual

date_default_timezone_get

(PHP 5 >= 5.1.0, PHP 7)

date_default_timezone_get — Gets the default timezone used by all date/time functions in a script

Descrierea

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.

Valorile întoarse

Returns a string.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #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');
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

date_default_timezone_set: Europe/London
date.timezone: Europe/London

Example #2 Getting the abbreviation of a timezone

<?php
date_default_timezone_set('America/Los_Angeles');
echo date_default_timezone_get() . ' => ' . date('e') . ' => ' . date('T');
?>

Exemplul de mai sus va afi?a:

America/Los_Angeles => America/Los_Angeles => PST

A se vedea ?i

  • date_default_timezone_set() - Sets the default timezone used by all date/time functions in a script
  • Lista zonelor orare sus?inute

date_date_set
date_default_timezone_set
Func?ii de Data/Timp


Sets the default timezone used by all date/time functions in a script

date_default_timezone_get
date_diff
Func?ii de Data/Timp
PHP Manual

date_default_timezone_set

(PHP 5 >= 5.1.0, PHP 7)

date_default_timezone_set — Sets the default timezone used by all date/time functions in a script

Descrierea

bool date_default_timezone_set ( string $timezone_identifier )

date_default_timezone_set() sets the default timezone used by all date/time functions.

Nota:

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.

Parametri

timezone_identifier

The timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available in the Lista zonelor orare sus?inute.

Valorile întoarse

This function returns FALSE if the timezone_identifier isn't valid, or TRUE otherwise.

Exemple

Example #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.';
}
?>

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Now throws E_WARNING rather than E_STRICT.
5.1.2 | The function started to validate the timezone_identifier parameter.

A se vedea ?i

  • date_default_timezone_get() - Gets the default timezone used by all date/time functions in a script
  • Lista zonelor orare sus?inute

date_default_timezone_get
date_diff
Func?ii de Data/Timp


Pseudonim pentru DateTime::diff

date_default_timezone_set
date_format
Func?ii de Data/Timp
PHP Manual

date_diff

(PHP 5 >= 5.3.0, PHP 7)

date_diff — Pseudonim pentru DateTime::diff()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::diff()

date_default_timezone_set
date_format
Func?ii de Data/Timp


Pseudonim pentru DateTime::format

date_diff
date_get_last_errors
Func?ii de Data/Timp
PHP Manual

date_format

(PHP 5 >= 5.2.0, PHP 7)

date_format — Pseudonim pentru DateTime::format()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::format()

date_diff
date_get_last_errors
Func?ii de Data/Timp


Pseudonim pentru DateTime::getLastErrors

date_format
date_interval_create_from_date_string
Func?ii de Data/Timp
PHP Manual

date_get_last_errors

(PHP 5 >= 5.3.0, PHP 7)

date_get_last_errors — Pseudonim pentru DateTime::getLastErrors()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::getLastErrors()

date_format
date_interval_create_from_date_string
Func?ii de Data/Timp


Pseudonim pentru DateInterval::createFromDateString

date_get_last_errors
date_interval_format
Func?ii de Data/Timp
PHP Manual

date_interval_create_from_date_string

(PHP 5 >= 5.3.0, PHP 7)

date_interval_create_from_date_string — Pseudonim pentru DateInterval::createFromDateString()

Descrierea

Aceasta func?ie este pseudonim pentru: DateInterval::createFromDateString()

date_get_last_errors
date_interval_format
Func?ii de Data/Timp


Pseudonim pentru DateInterval::format

date_interval_create_from_date_string
date_isodate_set
Func?ii de Data/Timp
PHP Manual

date_interval_format

(PHP 5 >= 5.3.0, PHP 7)

date_interval_format — Pseudonim pentru DateInterval::format()

Descrierea

Aceasta func?ie este pseudonim pentru: DateInterval::format()

date_interval_create_from_date_string
date_isodate_set
Func?ii de Data/Timp


Pseudonim pentru DateTime::setISODate

date_interval_format
date_modify
Func?ii de Data/Timp
PHP Manual

date_isodate_set

(PHP 5 >= 5.2.0, PHP 7)

date_isodate_set — Pseudonim pentru DateTime::setISODate()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::setISODate()

date_interval_format
date_modify
Func?ii de Data/Timp


Pseudonim pentru DateTime::modify

date_isodate_set
date_offset_get
Func?ii de Data/Timp
PHP Manual

date_modify

(PHP 5 >= 5.2.0, PHP 7)

date_modify — Pseudonim pentru DateTime::modify()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::modify()

date_isodate_set
date_offset_get
Func?ii de Data/Timp


Pseudonim pentru DateTime::getOffset

date_modify
date_parse_from_format
Func?ii de Data/Timp
PHP Manual

date_offset_get

(PHP 5 >= 5.2.0, PHP 7)

date_offset_get — Pseudonim pentru DateTime::getOffset()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::getOffset()

date_modify
date_parse_from_format
Func?ii de Data/Timp


Get info about given date formatted according to the specified format

date_offset_get
date_parse
Func?ii de Data/Timp
PHP Manual

date_parse_from_format

(PHP 5 >= 5.3.0, PHP 7)

date_parse_from_format — Get info about given date formatted according to the specified format

Descrierea

array date_parse_from_format ( string $format , string $date )

Returns associative array with detailed info about given date.

Parametri

format

Format accepted by DateTime::createFromFormat().

date

String representing the date.

Valorile întoarse

Returns associative array with detailed info about given date.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

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] =>
)

A se vedea ?i

  • DateTime::createFromFormat() - Parses a time string according to a specified format
  • checkdate() - Valideaza o data Gregoriana

date_offset_get
date_parse
Func?ii de Data/Timp


Returns associative array with detailed info about given date

date_parse_from_format
date_sub
Func?ii de Data/Timp
PHP Manual

date_parse

(PHP 5 >= 5.2.0, PHP 7)

date_parse — Returns associative array with detailed info about given date

Descrierea

array date_parse ( string $date )

Parametri

date

Date in format accepted by strtotime().

Valorile întoarse

Returns array with information about the parsed date on success sau FALSE în cazul e?ecului.

Erori/Excep?ii

In case the date format has an error, the element 'errors' will contains the error messages.

Exemple

Example #1 A date_parse() example

<?php
print_r(date_parse("2006-12-12 10:00:00.5"));
?>

Exemplul de mai sus va afi?a:

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] =>
)

Relative formats do not influence the values parsed from absolute formats, but are parsed into the "relative" element.

Example #2 date_parse() with relative formats

<?php
print_r(date_parse("2006-12-12 10:00:00.5 +1 week +1 hour"));
?>

Exemplul de mai sus va afi?a:

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] =>
    [relative] => Array
        (
            [year] => 0
            [month] => 0
            [day] => 7
            [hour] => 1
            [minute] => 0
            [second] => 0
        )

)

A se vedea ?i

  • checkdate() - Valideaza o data Gregoriana
  • getdate() - Ob?ine informa?ia despre data/ora

date_parse_from_format
date_sub
Func?ii de Data/Timp


Pseudonim pentru DateTime::sub

date_parse
date_sun_info
Func?ii de Data/Timp
PHP Manual

date_sub

(PHP 5 >= 5.3.0, PHP 7)

date_sub — Pseudonim pentru DateTime::sub()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::sub()

date_parse
date_sun_info
Func?ii de Data/Timp


Returns an array with information about sunset/sunrise and twilight begin/end

date_sub
date_sunrise
Func?ii de Data/Timp
PHP Manual

date_sun_info

(PHP 5 >= 5.1.2, PHP 7)

date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end

Descrierea

array date_sun_info ( int $time , float $latitude , float $longitude )

Parametri

time

Timestamp.

latitude

Latitude in degrees.

longitude

Longitude in degrees.

Valorile întoarse

Returns array on success sau FALSE în cazul e?ecului.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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
Func?ii de Data/Timp


Returns time of sunrise for a given day and location

date_sun_info
date_sunset
Func?ii de Data/Timp
PHP Manual

date_sunrise

(PHP 5, PHP 7)

date_sunrise — Returns time of sunrise for a given day and location

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the sunrise time in a specified format on success sau FALSE în cazul e?ecului.

Erori/Excep?ii

Fiecare apel al unei func?ii de data/ora va genera o E_NOTICE daca zona orara nu este valida ?i/sau un mesaj E_STRICT sau E_WARNING daca se utilizeaza setarile sistemului sau variabila de mediu TZ. Vede?i de asemenea date_default_timezone_set()

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Mon Dec 20 2004, sunrise time : 08:54

A se vedea ?i

  • date_sunset() - Returns time of sunset for a given day and location

date_sun_info
date_sunset
Func?ii de Data/Timp


Returns time of sunset for a given day and location

date_sunrise
date_time_set
Func?ii de Data/Timp
PHP Manual

date_sunset

(PHP 5, PHP 7)

date_sunset — Returns time of sunset for a given day and location

Descrierea

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.

Parametri

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.

Erori/Excep?ii

Fiecare apel al unei func?ii de data/ora va genera o E_NOTICE daca zona orara nu este valida ?i/sau un mesaj E_STRICT sau E_WARNING daca se utilizeaza setarile sistemului sau variabila de mediu TZ. Vede?i de asemenea date_default_timezone_set()

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.

Valorile întoarse

Returns the sunset time in a specified format on success sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Mon Dec 20 2004, sunset time : 18:13

A se vedea ?i

  • date_sunrise() - Returns time of sunrise for a given day and location

date_sunrise
date_time_set
Func?ii de Data/Timp


Pseudonim pentru DateTime::setTime

date_sunset
date_timestamp_get
Func?ii de Data/Timp
PHP Manual

date_time_set

(PHP 5 >= 5.2.0, PHP 7)

date_time_set — Pseudonim pentru DateTime::setTime()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::setTime()

date_sunset
date_timestamp_get
Func?ii de Data/Timp


Pseudonim pentru DateTime::getTimestamp

date_time_set
date_timestamp_set
Func?ii de Data/Timp
PHP Manual

date_timestamp_get

(PHP 5 >= 5.3.0, PHP 7)

date_timestamp_get — Pseudonim pentru DateTime::getTimestamp()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::getTimestamp()

date_time_set
date_timestamp_set
Func?ii de Data/Timp


Pseudonim pentru DateTime::setTimestamp

date_timestamp_get
date_timezone_get
Func?ii de Data/Timp
PHP Manual

date_timestamp_set

(PHP 5 >= 5.3.0, PHP 7)

date_timestamp_set — Pseudonim pentru DateTime::setTimestamp()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::setTimestamp()

date_timestamp_get
date_timezone_get
Func?ii de Data/Timp


Pseudonim pentru DateTime::getTimezone

date_timestamp_set
date_timezone_set
Func?ii de Data/Timp
PHP Manual

date_timezone_get

(PHP 5 >= 5.2.0, PHP 7)

date_timezone_get — Pseudonim pentru DateTime::getTimezone()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::getTimezone()

date_timestamp_set
date_timezone_set
Func?ii de Data/Timp


Pseudonim pentru DateTime::setTimezone

date_timezone_get
date
Func?ii de Data/Timp
PHP Manual

date_timezone_set

(PHP 5 >= 5.2.0, PHP 7)

date_timezone_set — Pseudonim pentru DateTime::setTimezone()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTime::setTimezone()

date_timezone_get
date
Func?ii de Data/Timp


Formateaza o ora/data

date_timezone_set
getdate
Func?ii de Data/Timp
PHP Manual

date

(PHP 4, PHP 5, PHP 7)

date — Formateaza o ora/data

Descrierea

string date ( string $format [, int $timestamp = time() ] )

Întoarce un string formatat în conformitate cu string-ul de formatare dat, utilizând timestamp-ul întreg dat, sau data ?i ora curenta daca nu este furnizat nici un timestamp. Cu alte cuvinte, timestamp este op?ional ?i implicit are valoarea întoarsa de time().

Parametri

format

Reprezinta formatul string-ului din care se ob?ine data la ie?ire. Vede?i op?iunile de formatare de mai jos. Exista de asemenea ?i câteva constante predefinite ale datelor ce pot fi utilizate în loc, deci spre exemplu DATE_RSS con?ine ?irul de formatare 'D, d M Y H:i:s'.

Urmatoarele caractere sunt recunoscute în parametrul format
Caracterul de format | Descriere | Exemple de valori întoarse
Ziua --- ---
d | Ziua lunii, 2 cifre cu zero la început | De la 01 pâna la 31
D | Reprezentarea textuala a zilei în limba engleza, trei litere | De la Mon pâna la Sun
j | Ziua lunii fara zero la început | De la 1 pâna la 31
l (litera minuscula 'L') | Reprezentarea textuala deplina a zilei saptamânii în limba engleza | De la Sunday pâna la Saturday
N | Reprezentarea numerica a zilei saptamânii conform standardului ISO-8601 (adaugat în PHP 5.1.0) | De la 1 (pentru Luni) pâna la 7 (pentru Duminica)
S | Sufixul ordinal al zilei din luna în limba engleza, 2 caractere | st, nd, rd sau th. Func?ioneaza bine cu j
w | Reprezentarea numerica a zilei saptamânii | De la 0 (pentru Duminica) pâna la 6 (pentru Sâmbata)
z | Ziua anului (începând de la 0) | De la 0 pâna la 365
Saptamâna --- ---
W | Numarul saptamânii în an conform standardului ISO-8601, saptamânile încep Luni (adaugat în PHP 4.1.0) | Exemplu: 42 (a 42-a saptamâna a anului)
Luna --- ---
F | Reprezentarea textuala deplina a lunii în limba engleza | De la January pâna la December
m | Reprezentarea numerica a lunii, cu zero la început | De la 01 pâna la 12
M | Reprezentarea textuala prescurtata a lunii în limba engleza, trei litere | De la Jan pâna la Dec
n | Reprezentarea numerica a lunii, fara zero la început | De la 1 pâna la 12
t | Numarul de zile în luna data | De la 28 pâna la 31
Anul --- ---
L | Indica daca anul este bisect | 1 daca anul este bisect, 0 în caz contrar.
o | Reprezentarea numerica a anului conform standardului ISO-8601. Aceasta are aceea?i valoare ca ?i Y, cu excep?ia ca daca numarul saptamânii dupa ISO (W) apar?ine anului precedent sau urmator, acel an este considerat în loc. (adaugat în PHP 5.1.0) | Exemple: 1999 sau 2003
Y | Reprezentarea numerica deplina a anului, 4 cifre | Exemple: 1999 sau 2003
y | Reprezentarea din doua cifre a anului | Exemple: 99 sau 03
Ora --- ---
a | Ante meridiem sau Post meridiem cu litere minuscule | am sau pm
A | Ante meridiem sau Post meridiem cu litere majuscule | AM sau PM
B | Ora Swatch Internet | De la 000 pâna la 999
g | Reprezentarea orei în format de 12 ore, fara zero la început | De la 1 pâna la 12
G | Reprezentarea orei în format de 24 ore, fara zero la început | De la 0 pâna la 23
h | Reprezentarea orei în format de 12 ore, cu zero la început | De la 01 pâna la 12
H | Reprezentarea orei în format de 24 ore, cu zero la început | De la 00 pâna la 23
i | Minutele cu zero la început | De la 00 pâna la 59
s | Secundele cu zero la început | De la 00 pâna la 59
u | Microsecundele (adaugat în PHP 5.2.2). Atrage?i aten?ia ca date() întotdeauna va genera 000000, deoarece ea prime?te un parametru integer, iar metoda DateTime::format() sus?ine microsecundele daca DateTime a fost creata cu microsecunde. | Exemplu: 654321
Fusul orar --- ---
e | Identificatorul fusului orar (adaugat în PHP 5.1.0) | Exemple: UTC, GMT, Atlantic/Azores
I (litera majuscula i) | Determina daca este activ timpul de vara | 1 daca este activ timpul de vara, 0 în caz contrar.
O | Diferen?a fa?a de ora Greenwich (GMT) în ore | Exemplu: +0200
P | Diferen?a fa?a de ora Greenwich (GMT) cu doua puncte între ore ?i minute (adaugat în PHP 5.1.3) | Exemplu: +02:00
T | Abreviatura fusului orar | Exemple: EST, MDT ...
Z | Deplasamentul în secunde a fusului orar. Deplasamentul fuselor orare dinspre Vest de UTC este întotdeauna negativ, iar a celor dinspre Est de UTC este întotdeauna pozitiv. | De la -43200 pâna la 50400
Data/Ora deplina --- ---
c | Data în reprezentare ISO 8601 (adaugata în PHP 5) | 2004-02-12T15:19:21+00:00
r | Data formatata conform » RFC 2822 | Exemplu: Thu, 21 Dec 2000 16:01:07 +0200
U | Secunde de la Epoca Unix (1 Ianuarie 1970 00:00:00 GMT) | Vezi de asemenea time()

Caracterele nerecunoscute din string-ul de formatare vor fi afi?ate a?a cum sunt. Formatul Z întotdeauna va întoarce 0 la utilizarea gmdate().

Nota:

Deoarece aceasta func?ie accepta doar timestamp-uri integer, caracterul de formatare u este util doar când se utilizeaza func?ia date_format() cu timestamp-uri ale utilizatorului create cu date_create().

timestamp

Parametrul op?ional timestamp este un integer ?i este un moment de timp Unix ?i are valoarea implicita a orei locale, daca parametrul timestamp nu este indicat. Cu alte cuvinte, valoarea implicita este cea a func?iei time().

Valorile întoarse

Întoarce un string cu data formatat. Daca este utilizata o valoare non-numerica pentru timestamp, este întors FALSE ?i este emisa o eroare de nivel E_WARNING.

Erori/Excep?ii

Fiecare apel al unei func?ii de data/ora va genera o E_NOTICE daca zona orara nu este valida ?i/sau un mesaj E_STRICT sau E_WARNING daca se utilizeaza setarile sistemului sau variabila de mediu TZ. Vede?i de asemenea date_default_timezone_set()

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Domeniul valid al unui timestamp este de obicei de la Fri, 13 Dec 1901 20:45:54 GMT pâna la Tue, 19 Jan 2038 03:14:07 GMT. (Acestea sunt datele ce corespund valorilor minima ?i maxima pentru un întreg cu semn pe 32 de bi?i). Însa înainte de PHP 5.1.0 acest domeniu era limitat de la 01-01-1970 pâna la 19-01-2038 pe unele sisteme (de ex. Windows).
5.1.0 | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.
5.1.1 | Exista constante utile pentru formate standarde de date/ore, ce pot fi utilizate pentru a specifica parametrul format.

Exemple

Example #1 Exemple date()

<?php
// Stabile?te fusul orar implicit. Disponibil începând cu PHP 5.1
date_default_timezone_set('UTC');

// Afi?eaza ceva de felul: Monday
echo date("l");

// Afi?eaza ceva de felul: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// Afi?eaza: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

/* utilizarea constantelor în parametrul format */
// Afi?eaza ceva de felul: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);

// Afi?eaza ceva de felul: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>

Pute?i preveni ca un caracter recunoscut în string-ul de formatare sa fie expandat prin prefixarea lui cu un backslash. Daca caracterul cu backslash de acum este o secven?a speciala, va trebui de asemenea sa prefixa?i backslash-ul.

Example #2 Evadarea caracterelor în date()

<?php
// Afi?eaza ceva de felul: Wednesday the 15th
echo date('l \t\h\e jS');
?>

Este posibil de utilizat date() ?i mktime() împreuna pentru a afla date din trecut sau viitor.

Example #3 Exemplu date() ?i mktime()

<?php
$tomorrow  = mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
$nextyear  = mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1);
?>

Nota:

Aceasta poate fi mai sigur decât simpla adaugare sau scadere a numarului de secunde în zi sau luna la un timestamp din cauza timpului de vara.

Unele exemple de formatare date(). Observa?i ca trebuie sa evada?i caracterele suplimentare, deoarece cele ce au o însemnatate speciala vor produce rezultate nedorite, iar celelalte caractere pot capata o însemnatate speciala în versiunile viitoare ale PHP. Când evada?i, ave?i grija sa utiliza?i ghilimele singulare pentru a preveni caractere ca \n sa devina newline.

Example #4 Formatarea date()

<?php
// Presupunem ca astazi este: March 10th, 2001, 5:16:18 pm
// ?i ne aflam în fusul orar Mountain Standard Time (MST)

$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today = date("H:i:s");                         // 17:16:18
$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (formatul MySQL DATETIME)
?>

Pentru a formata date în alte limbi, trebuie sa utiliza?i func?iile setlocale() ?i strftime() în loc de date().

Note

Nota:

Pentru a genera un timestamp dintr-o reprezentare string a datei, pute?i utiliza strtotime(). În plus, unele baze de date au func?ii pentru a converti formatele lor de date în timestamp-uri (cum ar fi func?ia » UNIX_TIMESTAMP la MySQL).

Sfat

Timestamp-ul începutului interpelarii este disponibil în variabila $_SERVER['REQUEST_TIME'] începând cu PHP 5.1.

A se vedea ?i

  • gmdate() - Formateaza o data/ora GMT/UTC
  • idate() - Format a local time/date as integer
  • getdate() - Ob?ine informa?ia despre data/ora
  • getlastmod() - Gets time of last page modification
  • mktime() - Ob?ine timestamp-ul Unix pentru o data ?i ora
  • strftime() - Formateaza o ora/data locala în conformitate cu setarile locale
  • time() - Întoarce timpul curent Unix
  • strtotime() - Transleaza aproape orice descriere textuala în limba engleza a datei ?i orei într-un timestamp Unix
  • Constante DateTime predefinite

date_timezone_set
getdate
Func?ii de Data/Timp


Ob?ine informa?ia despre data/ora

date
gettimeofday
Func?ii de Data/Timp
PHP Manual

getdate

(PHP 4, PHP 5, PHP 7)

getdate — Ob?ine informa?ia despre data/ora

Descrierea

array getdate ([ int $timestamp = time() ] )

Întoarce un array asociativ con?inând informa?ia despre data ?i ora a parametrului timestamp, sau a datei/orei locale în caz ca parametrul timestamp nu este furnizat.

Parametri

timestamp

Parametrul op?ional timestamp este un integer ?i este un moment de timp Unix ?i are valoarea implicita a orei locale, daca parametrul timestamp nu este indicat. Cu alte cuvinte, valoarea implicita este cea a func?iei time().

Valorile întoarse

Întoarce un array asociativ cu informa?ii ce ?in de parametrul timestamp. Elementele tabloului asociativ întors sunt urmatoarele:

Elementele-cheie ale tabloului asociativ întors
Cheie | Descriere | Exemplu de valori întoarse
"seconds" | Reprezentarea numerica a secundelor | De la 0 pâna la 59
"minutes" | Reprezentarea numerica a minutelor | De la 0 pâna la 59
"hours" | Reprezentarea numerica a orelor | De la 0 pâna la 23
"mday" | Reprezentarea numerica a zilei lunii | De la 1 pâna la 31
"wday" | Reprezentarea numerica a zilei saptamânii | De la 0 (Duminica) pâna la 6 (Sâmbata)
"mon" | Reprezentarea numerica a lunii | De la 1 pâna la 12
"year" | Reprezentarea numerica deplina a anului, 4 cifre | Exemple: 1999 sau 2003
"yday" | Reprezentarea numerica a zilei anului | De la 0 pâna la 365
"weekday" | Reprezentarea textuala deplina a zilei saptamânii în limba engleza | De la Sunday pâna la Saturday
"month" | Reprezentarea textuala deplina a lunii în limba engleza, cum ar fi January sau March | De la January pâna la December
0 | Secunde de la Epoca Unix, similare cu valorile întoarse de time() ?i utilizate de date(). | Depinde de sistem, de obicei de la -2147483648 pâna la 2147483647.

Exemple

Example #1 Exemplu getdate()

<?php
$today = getdate();
print_r($today);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [seconds] => 40
    [minutes] => 58
    [hours]   => 21
    [mday]    => 17
    [wday]    => 2
    [mon]     => 6
    [year]    => 2003
    [yday]    => 167
    [weekday] => Tuesday
    [month]   => June
    [0]       => 1055901520
)

A se vedea ?i

  • date() - Formateaza o ora/data
  • idate() - Format a local time/date as integer
  • localtime() - Ob?ine timpul local
  • time() - Întoarce timpul curent Unix
  • setlocale() - Set locale information

date
gettimeofday
Func?ii de Data/Timp


Ob?ine timpul curent

getdate
gmdate
Func?ii de Data/Timp
PHP Manual

gettimeofday

(PHP 4, PHP 5, PHP 7)

gettimeofday — Ob?ine timpul curent

Descrierea

mixed gettimeofday ([ bool $return_float = false ] )

Aceasta este o interfa?a pentru gettimeofday(2). Ea întoarce un tablou asociativ ce con?ine datele întoarse în rezultatul apelului func?iei de sistem.

Parametri

return_float

Când este stabilit în TRUE, este întors un float în locul unui tablou.

Valorile întoarse

Implicit este întors un array. Daca return_float este stabilit, este întors un float.

Cheile tabloului:

  • "sec" - secunde începând cu Epoca Unix
  • "usec" - microsecunde
  • "minuteswest" - minute de la Vest de Greenwich
  • "dsttime" - tipul ajustarii la timpul de vara

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | A fost adaugat parametrul return_float.

Exemple

Example #1 Exemplu gettimeofday()

<?php
print_r(gettimeofday());

echo gettimeofday(true);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [sec] => 1073504408
    [usec] => 238215
    [minuteswest] => 0
    [dsttime] => 1
)

1073504408.23910

getdate
gmdate
Func?ii de Data/Timp


Formateaza o data/ora GMT/UTC

gettimeofday
gmmktime
Func?ii de Data/Timp
PHP Manual

gmdate

(PHP 4, PHP 5, PHP 7)

gmdate — Formateaza o data/ora GMT/UTC

Descrierea

string gmdate ( string $format [, int $timestamp = time() ] )

Identica cu func?ia date() cu excep?ia ca ora întoarsa este dupa Greenwich Mean Time (GMT) - Ora Medie Greenwich.

Parametri

format

Formatul în care va fi afi?at string-ul datei. Vede?i op?iunile de formatare pentru func?ia date().

timestamp

Parametrul op?ional timestamp este un integer ?i este un moment de timp Unix ?i are valoarea implicita a orei locale, daca parametrul timestamp nu este indicat. Cu alte cuvinte, valoarea implicita este cea a func?iei time().

Valorile întoarse

Întoarce un string cu data formatata. Daca este utilizata o valoare non-numerica pentru timestamp, este întors FALSE ?i o eroare de nivel E_WARNING este emisa.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Domeniul valid al unui timestamp este de obicei de la Fri, 13 Dec 1901 20:45:54 GMT pâna la Tue, 19 Jan 2038 03:14:07 GMT. (Acestea sunt datele ce corespund valorilor minima ?i maxima a unui integer pe 32 de bi?i). Însa pâna la PHP 5.1.0 acest domeniu era limitat de la 01-01-1970 pâna la 19-01-2038 pe unele sisteme (de ex. Windows).
5.1.1 | Exista constante utile a unor formate standarde ale datei/orei ce pot fi utilizate pentru a specifica parametrul format.

Exemple

Example #1 Exemple gmdate()

Când exemplul este rulat în Finlanda (GMT +0200), prima linie de mai jos afi?eaza "Jan 01 1998 00:00:00", în timp ce a doua afi?eaza "Dec 31 1997 22:00:00".

<?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));
?>

A se vedea ?i

  • date() - Formateaza o ora/data
  • mktime() - Ob?ine timestamp-ul Unix pentru o data ?i ora
  • gmmktime() - Ob?ine momentul de timp Unix pentru o data GMT
  • strftime() - Formateaza o ora/data locala în conformitate cu setarile locale

gettimeofday
gmmktime
Func?ii de Data/Timp


Ob?ine momentul de timp Unix pentru o data GMT

gmdate
gmstrftime
Func?ii de Data/Timp
PHP Manual

gmmktime

(PHP 4, PHP 5, PHP 7)

gmmktime — Ob?ine momentul de timp Unix pentru o data GMT

Descrierea

 int gmmktime
  ([ int $hour = gmdate("H")
 [, int $minute = gmdate("i")
 [, int $second = gmdate("s")
 [, int $month = gmdate("n")
 [, int $day = gmdate("j")
 [, int $year = gmdate("Y")
 [, int $is_dst = -1
]]]]]]] )

Este identica cu mktime() cu excep?ia ca parametrii furniza?i reprezinta o data GMT. gmmktime() în interior utilizeaza mktime(), deci numai orele valide în timp local derivat pot fi utilizate.

Ca ?i la mktime() argumentele pot fi omise de la dreapta spre stânga, cu fiecare argument omis stabilit la valoarea GMT curenta corespunzatoare.

Parametri

hour

Numarul orei relativ cu începutul zilei determinat de month, day ?i year. Valorile negative se refera la ora înainte de miezul nop?ii a zilei în cauza. Valorile mai mari decât 23 se refera la ora corespunzatoare a zilei (zilelor) urmatoare.

minute

Numarul minutului relativ cu începutul orei determinat de hour. Valorile negative se refera la minutul orei precedente. Valorile mai mari decât 59 se refera la minutul corespunzator a orei (orelor) urmatoare.

second

Numarul de secunde relativ cu începutul minutului determinat de minute. Valorile negative se refera la secunda minutului precedent. Valorile mai mari decât 59 se refera la secunda corespunzatoare ale minutului (minutelor) urmatoare.

month

Numarul lunii relativ cu sfâr?itul anului precedent. Valorile de la 1 pâna la 12 se refera la lunile normale ale anului în cauza. Valorile mai mici decât 1 (inclusiv valorile negative) se refera la lunile anului precedent în ordine inversa, deci 0 este Decembrie, -1 este Noiembrie, etc. Valorile mai mari decât 12 se refera la luna corespunzatoare a anului (anilor) urmator.

day

Numarul zilei relativ cu sfâr?itul lunii precedente. Valorile de la 1 pâna la 28, 29, 30 sau 31 (în dependen?a de luna) se refera la zilele normale ale lunii în cauza. Valorile mai mici decât 1 (inclusiv valorile negative) se refera la zilele lunii precedente, deci 0 este ultima zi a lunii precedente, -1 este penultima zi, etc. Valorile mai mari decât numarul de zile din luna respectiva se refera la ziua corespunzatoare din luna (lunile) urmatoare.

year

Anul

is_dst

Parametrii întotdeauna reprezinta o data GMT, deci is_dst nu influen?eaza rezultatul.

Nota:

Acest parametru a fost eliminat în PHP 7.0.0.

Valorile întoarse

Întoarce un moment de timp Unix de tip integer.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | Parametrul is_dst a fost eliminat.
5.1.0 | Începând cu PHP 5.1.0, parametrul is_dst a devenit învechit. În rezultat, trabuie utilizata în loc noua facilitate de manipulare cu fusul orar.

Exemple

Example #1 Exemplu simplu gmmktime()

<?php
// Afi?eaza: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", gmmktime(0, 0, 0, 7, 1, 2000));
?>

A se vedea ?i

  • mktime() - Ob?ine timestamp-ul Unix pentru o data ?i ora
  • date() - Formateaza o ora/data
  • time() - Întoarce timpul curent Unix

gmdate
gmstrftime
Func?ii de Data/Timp


Formateaza o data/ora GMT/UTC în conformitate cu setarile locale

gmmktime
idate
Func?ii de Data/Timp
PHP Manual

gmstrftime

(PHP 4, PHP 5, PHP 7)

gmstrftime — Formateaza o data/ora GMT/UTC în conformitate cu setarile locale

Descrierea

string gmstrftime ( string $format [, int $timestamp = time() ] )

Se comporta în acela?i mod ca ?i strftime() cu excep?ia ca ora întoarsa este Greenwich Mean Time (GMT) - Ora Medie Greenwich. Spre exemplu, când se ruleaza în Eastern Standard Time (GMT -0500), prima linie de mai jos afi?eaza "Dec 31 1998 20:00:00", în timp ce a doua afi?eaza "Jan 01 1999 01:00:00".

Parametri

format

Vezi descrierea în strftime().

timestamp

Parametrul op?ional timestamp este un integer ?i este un moment de timp Unix ?i are valoarea implicita a orei locale, daca parametrul timestamp nu este indicat. Cu alte cuvinte, valoarea implicita este cea a func?iei time().

Valorile întoarse

Întoarce un string formatat în conformitate cu string-ul format, utilizând timestamp-ul dat sau ora locala curenta, daca nu este dat un timestamp. Denumirile lunilor ?i zilelor saptamânii ?i alte string-uri ce depind de limba respecta setarile locale stabilite cu ajutorul setlocale().

Exemple

Example #1 Exemplu 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";
?>

A se vedea ?i

  • strftime() - Formateaza o ora/data locala în conformitate cu setarile locale

gmmktime
idate
Func?ii de Data/Timp


Format a local time/date as integer

gmstrftime
localtime
Func?ii de Data/Timp
PHP Manual

idate

(PHP 5, PHP 7)

idate — Format a local time/date as integer

Descrierea

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.

Parametri

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

Parametrul op?ional timestamp este un integer ?i este un moment de timp Unix ?i are valoarea implicita a orei locale, daca parametrul timestamp nu este indicat. Cu alte cuvinte, valoarea implicita este cea a func?iei time().

Valorile întoarse

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.

Erori/Excep?ii

Fiecare apel al unei func?ii de data/ora va genera o E_NOTICE daca zona orara nu este valida ?i/sau un mesaj E_STRICT sau E_WARNING daca se utilizeaza setarile sistemului sau variabila de mediu TZ. Vede?i de asemenea date_default_timezone_set()

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.

Exemple

Example #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);
?>

A se vedea ?i

  • date() - Formateaza o ora/data
  • getdate() - Ob?ine informa?ia despre data/ora
  • time() - Întoarce timpul curent Unix

gmstrftime
localtime
Func?ii de Data/Timp


Ob?ine timpul local

idate
microtime
Func?ii de Data/Timp
PHP Manual

localtime

(PHP 4, PHP 5, PHP 7)

localtime — Ob?ine timpul local

Descrierea

array localtime ([ int $timestamp = time() [, bool $is_associative = false ]] )

Func?ia localtime() întoarce un tablou identic ca structura cu cel întors de func?ia C.

Parametri

timestamp

Parametrul op?ional timestamp este un integer ?i este un moment de timp Unix ?i are valoarea implicita a orei locale, daca parametrul timestamp nu este indicat. Cu alte cuvinte, valoarea implicita este cea a func?iei time().

is_associative

Daca este stabilit în FALSE sau nu este furnizat, atunci tabloul întors este unul obi?nuit, indexat numeric. Daca argumentul este stabilit în TRUE, atunci localtime() întoarce un tablou asociativ con?inând diferitele elemente ale structurii întoarse în rezultatul apelarii func?iei C localtime. Denumirile cheilor tabloului asociativ sunt urmatoarele:

  • "tm_sec" - secunde, de la 0 pâna la 59
  • "tm_min" - minute, de la 0 pâna la 59
  • "tm_hour" - ore, de la 0 pâna la 23
  • "tm_mday" - ziua lunii, de la 1 pâna la 31
  • "tm_mon" - luna în an, de la 0 (Ian) pâna la 11 (Dec)
  • "tm_year" - numarul de ani începând cu 1900
  • "tm_wday" - ziua din saptamâna, de la 0 (Duminica) pâna la 6 (Sâmbata)
  • "tm_yday" - ziua din an, de la 0 pâna la 365
  • "tm_isdst" - este în vigoare timpul de vara? Pozitiv daca da, 0 daca nu, negativ daca nu se cunoa?te.

Erori/Excep?ii

Fiecare apel al unei func?ii de data/ora va genera o E_NOTICE daca zona orara nu este valida ?i/sau un mesaj E_STRICT sau E_WARNING daca se utilizeaza setarile sistemului sau variabila de mediu TZ. Vede?i de asemenea date_default_timezone_set()

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.

Exemple

Example #1 Exemplu localtime()

<?php
$localtime = localtime();
$localtime_assoc = localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • getdate() - Ob?ine informa?ia despre data/ora

idate
microtime
Func?ii de Data/Timp


Întoarce timpul curent Unix cu microsecunde

localtime
mktime
Func?ii de Data/Timp
PHP Manual

microtime

(PHP 4, PHP 5, PHP 7)

microtime — Întoarce timpul curent Unix cu microsecunde

Descrierea

mixed microtime ([ bool $get_as_float = false ] )

microtime() întoarce timpul curent Unix cu microsecunde. Aceasta func?ie este disponibila numai pe sistemele de operare ce sus?in apelul de sistem gettimeofday().

Parametri

get_as_float

Daca se utilizeaza ?i este stabilita în TRUE, microtime() va întoarce un float în loc de string, dupa cum este descris în sec?iunea de mai jos despre valorile întoarse.

Valorile întoarse

În mod implicit microtime() întoarce un string de forma "msec sec", unde sec este numarul de secunde ce s-au scurs de la epoca Unix (0:00:00 1 Ianuarie, 1970 GMT), ?i msec este numarul de microsecunde ce s-au scurs dupa sec exprimat în secunde.

Daca get_as_float este stabilit în TRUE, atunci microtime() întoarce un float, care reprezinta timpul curent în secunde ce s-au scurs de la epoca Unix cu precizia de microsecunda.

Exemple

Example #1 Masurarea timpului de execu?ie a script-ului cu ajutorul microtime()

<?php
/**
 * O func?ie simpla pentru a copia comportamentul PHP 5
 */
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

$time_start = microtime_float();

// Opre?te execu?ia un pic
usleep(100);

$time_end = microtime_float();
$time = $time_end - $time_start;

echo "Nu am facut nimic timp de $time secunde\n";
?>

Example #2 Masurarea timpului de execu?ie a script-ului în PHP 5

<?php
$time_start = microtime(true);

// Opre?te execu?ia un pic
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Nu am facut nimic timp de $time secunde\n";
?>

Example #3 microtime() ?i REQUEST_TIME_FLOAT (începând cu PHP 5.4.0)

<?php
// ”Adormire” pentru un interval de timp aleator
usleep(mt_rand(100, 10000));

// Începând cu PHP 5.4.0, REQUEST_TIME_FLOAT este disponibil în tabloul superglobal $_SERVER .
// El con?ine timpul startarii interpelarii cu precizie de microsecunde.
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

echo "Nu am facut nimic timp de $time secunde\n";
?>

A se vedea ?i

  • time() - Întoarce timpul curent Unix

localtime
mktime
Func?ii de Data/Timp


Ob?ine timestamp-ul Unix pentru o data ?i ora

microtime
strftime
Func?ii de Data/Timp
PHP Manual

mktime

(PHP 4, PHP 5, PHP 7)

mktime — Ob?ine timestamp-ul Unix pentru o data ?i ora

Descrierea

 int mktime
  ([ int $hour = date("H")
 [, int $minute = date("i")
 [, int $second = date("s")
 [, int $month = date("n")
 [, int $day = date("j")
 [, int $year = date("Y")
 [, int $is_dst = -1
]]]]]]] )

Întoarce timestamp-ul Unix ce corespunde argumentelor furnizate. Acest timestamp este un integer lung con?inând numarul de secunde între Epoca Unix (1 Ianuarie 1970 00:00:00 GMT) ?i timpul specificat.

Argumentele pot fi omise unul dupa altul de la dreapta spre atânga; orice argument omis va fi stabilit la valoarea curenta în corespundere cu data ?i ora locale.

Note

Nota:

Începând cu PHP 5.1, când este apelat fara argumente, mktime() arunca o notificare E_STRICT: utiliza?i func?ia time() în loc.

Parametri

hour

Numarul orei relativ cu începutul zilei determinat de month, day ?i year. Valorile negative se refera la ora înainte de miezul nop?ii a zilei în cauza. Valorile mai mari decât 23 se refera la ora corespunzatoare a zilei (zilelor) urmatoare.

minute

Numarul minutului relativ cu începutul orei determinat de hour. Valorile negative se refera la minutul orei precedente. Valorile mai mari decât 59 se refera la minutul corespunzator a orei (orelor) urmatoare.

second

Numarul de secunde relativ cu începutul minutului determinat de minute. Valorile negative se refera la secunda minutului precedent. Valorile mai mari decât 59 se refera la secunda corespunzatoare ale minutului (minutelor) urmatoare.

month

Numarul lunii relativ cu sfâr?itul anului precedent. Valorile de la 1 pâna la 12 se refera la lunile normale ale anului în cauza. Valorile mai mici decât 1 (inclusiv valorile negative) se refera la lunile anului precedent în ordine inversa, deci 0 este Decembrie, -1 este Noiembrie, etc. Valorile mai mari decât 12 se refera la luna corespunzatoare a anului (anilor) urmator.

day

Numarul zilei relativ cu sfâr?itul lunii precedente. Valorile de la 1 pâna la 28, 29, 30 sau 31 (în dependen?a de luna) se refera la zilele normale ale lunii în cauza. Valorile mai mici decât 1 (inclusiv valorile negative) se refera la zilele lunii precedente, deci 0 este ultima zi a lunii precedente, -1 este penultima zi, etc. Valorile mai mari decât numarul de zile din luna respectiva se refera la ziua corespunzatoare din luna (lunile) urmatoare.

year

Numarul anului. Poate fi format din doua sau din patru cifre. Valorile 0-69 corespund anilor 2000-2069, iar 70-100 corespund 1970-2000. Pe sistemele unde time_t este un întreg pe 32 bi?i cu semn, cum este pe majoritatea sistemelor contemporane, domeniul valid pentru year este între 1901 ?i 2038. Însa înainte de PHP 5.1.0 acest domeniu era limitat între 1970 ?i 2038 pe unele sisteme (de ex. Windows).

is_dst

Acest parametru poate fi stabilit în 1 daca este în efect timpul de vara (daylight savings time (DST)), 0 daca nu, sau -1 (valoarea implicita) daca nu se cunoa?te daca este în efect timpul de vara. Daca nu se cunoa?te, PHP încearca singur sa determine acest lucru. Aceasta poate cauza rezultate nea?teptate (dar nu neaparat incorecte). Unele ore nu sunt valide daca DST este activat pe sistemul unde ruleaza PHP, sau daca parametrul is_dst este stabilit în 1. Daca DST este activat de ex. la 2:00, toate orele între 2:00 ?i 3:00 sunt invalide ?i mktime() întoarce o valoare nedefinita (de obicei negativa). Unele sisteme (de ex. Solaris 8) activeaza DST la miezul nop?ii, de aceea ora 0:30 în ziua când DST este activat este evaluata ca 23:30 a zilei precedente.

Nota:

Începând cu PHP 5.1.0, acest parametru a devenit învechit. În consecin?a acestui fapt trebuie utilizate noile facilita?i de gestiune a fusului orar.

Nota:

Acest parametru a fost eliminat în PHP 7.0.0.

Valorile întoarse

mktime() întoarce timestamp-ul Unix al argumentelor furnizate. Daca argumentele nu sunt valide, func?ia întoarce FALSE (înainte de PHP 5.1 întorcea -1).

Erori/Excep?ii

Fiecare apel al unei func?ii de data/ora va genera o E_NOTICE daca zona orara nu este valida ?i/sau un mesaj E_STRICT sau E_WARNING daca se utilizeaza setarile sistemului sau variabila de mediu TZ. Vede?i de asemenea date_default_timezone_set()

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | Parametrul is_dst a fost eliminat.
5.3.0 | mktime() acum emite o notificare E_DEPRECATED daca este utilizat parametrul is_dst.
5.1.0 | Parametrul is_dst a devenit dezapreciat. Func?ia a fost modificata sa întoarca FALSE în caz de eroare, în loc de -1. Func?ia a fost modificata sa accepte anul, luna ?i ziua cu valorile zero.
5.1.0 | Când este apelata fara argumente, mktime() arunca o notificare E_STRICT. Utiliza?i func?ia time() în loc.
5.1.0 | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.

Exemple

Example #1 Exemplu simplu mktime()

<?php
// Stabile?te fusul orar implicit pentru a fi utilizat. Disponibil începând cu PHP 5.1
date_default_timezone_set('UTC');

// Afi?eaza: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

// Afi?eaza ceva de felul: 2006-04-05T01:02:03+00:00
echo date('c', mktime(1, 2, 3, 4, 5, 2006));
?>

Example #2 Exemple mktime()

mktime() este utila pentru a face opera?ii aritmetice ?i de validare a datelor, deoarece ea va calcula automat valoarea corecta pentru vlorile introduse din afara domeniului. De exemplu, fiecare rând ce urmeaza produce string-ul "Jan-01-1998".

<?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));
?>

Example #3 Ultima zi a lunii

Ultima zi a oricarei luni poate fi exprimata ca ziua "0" a lunii urmatoare, dar nu ziua -1. Ambele exemple ce urmeaza vor produce string-ul "Ultima zi din Februarie 2000 este: 29".

<?php
$lastday = mktime(0, 0, 0, 3, 0, 2000);
echo strftime("Ultima zi din Februarie 2000 este: %d", $lastday);
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo strftime("Ultima zi din Februarie 2000 este: %d", $lastday);
?>

Note

Precautie

Înainte de PHP 5.1.0, timestamp-urile negative nu erau sus?inute în unele sisteme, inclusiv nici într-o versiune cunoscuta Windows. De aceea domeniul valid al anilor era limitat între 1970 ?i 2038.

A se vedea ?i

  • checkdate() - Valideaza o data Gregoriana
  • gmmktime() - Ob?ine momentul de timp Unix pentru o data GMT
  • date() - Formateaza o ora/data
  • time() - Întoarce timpul curent Unix

microtime
strftime
Func?ii de Data/Timp


Formateaza o ora/data locala în conformitate cu setarile locale

mktime
strptime
Func?ii de Data/Timp
PHP Manual

strftime

(PHP 4, PHP 5, PHP 7)

strftime — Formateaza o ora/data locala în conformitate cu setarile locale

Descrierea

string strftime ( string $format [, int $timestamp = time() ] )

Formateaza ora ?i/sau data în conformitate cu setarile locale. Denumirile lunilor ?i a zilelor saptamânii ?i alte string-uri dependente de limba sunt în conformitate cu setarile locale stabilite prin finc?ia setlocale().

Nu toate specificarile de convertire pot fi sus?inute de biblioteca dumneavoastra C, în care caz ele nu vor fi sus?inute de func?ia PHP strftime(). În plus, nu toate platformele sus?in timestamp-uri negative, de aceea domeniul de date poate fi limitat la valori nu mai mici de Epoca Unix. Aceasta înseamna ca %e, %T, %R ?i %D (pot fi mai multe), precum ?i date anterioare la Jan 1, 1970 nu vor func?iona în Windows, unele distibu?ii Linux, ?i alte câteva sisteme de operare. Pentru sisteme Windows o privire de ansamblu a specificatorilor de conversie sus?inu?i poate fi gasita pe acest » website MSDN.

Parametri

format

Urmatoarele caractere sunt recunoscute în cadrul parametrului format
format | Descriere | Exemplu de valori întoarse
Ziua --- ---
%a | Reprezentarea textuala abreviata a zilei saptamânii | De la Sun pâna la Sat
%A | Reprezentarea textuala deplina a zilei saptamânii | De la Sunday pâna la Saturday
%d | Ziua lunii din doua cifre (prefixata cu zero) | De la 01 pâna la 31
%e | Ziua lunii prefixata cu spa?iu în cazul unei singure cifre. Implementarea pentru Windows nu coincide cu descrierea. Gasi?i mai jos informa?ii suplimentare. | De la 1 pâna la 31
%j | Ziua anului, 3 cifre prefixate cu zerouri | De la 001 pâna la 366
%u | Reprezentarea numerica a zilei saptamânii în conformitate cu ISO-8601 | De la 1 (Luni) pâna la 7 (Duminica)
%w | Reprezentarea numerica a zilei saptamânii | De la 0 (Duminica) pâna la 6 (Sâmbata)
Saptamâna --- ---
%U | Numarul saptamânii anului dat. Prima Duminica din an este începutul primei saptamâni | 13 (pentru a 13-a saptamâna deplina a anului)
%V | Numarul saptamânii anului dat în conformitate cu ISO-8601:1988, începând cu prima saptamâna a anului cu cel pu?in 4 zile de lucru, ziua de Luni fiind prima zi a saptamânii | De la 01 pâna la 53 (unde 53 reprezinta o saptamâna suprapusa)
%W | Reprezentarea numerica a saptamânii din an, începând cu prima zi de Luni ca prima saptamâna | 46 (pentru a 46-a saptamâna a anului începând cu Luni)
Luna --- ---
%b | Denumirea abreviata a lunii bazata pe setarile locale | De la Jan pâna la Dec
%B | Denumirea deplina a lunii bazata pe setarile locale | De la January pâna la December
%h | Denumirea abreviata a lunii bazata pe setarile locale (un pseudonim pentru %b) | De la Jan pâna la Dec
%m | Reprezentarea din doua cifre a lunii | De la 01 (Ianuarie) pâna la 12 (Decembrie)
Anul --- ---
%C | Reprezentarea din doua cifre a secolului (anul divizat la 100, trunchiat pâna la un întreg) | 19 pentru secolul 20
%g | Reprezentarea din doua cifre a anului conform standardului ISO-8601:1988 (vezi %V) | Exemplu: 09 pentru 6 Ianuarie, 2009
%G | Versiunea deplina din patru cifre a %g | Exemplu: 2008 pentru 3 Ianuarie 2009
%y | Reprezentarea din doua cifre a anului | Exemplu: 09 pentru 2009, 79 pentru 1979
%Y | Reprezentarea din patru cifre a anului | Exemplu: 2038
Ora --- ---
%H | Reprezentarea din doua cifre a orei în formatul cu 24 de ore | De la 00 pâna la 23
%k | Reprezentarea din doua cifre a orei în formatul cu 24 de ore, cu un spa?iu în fa?a orelor dintr-o singura cifra | De la 0 pâna la 23
%I | Reprezentarea din doua cifre a orei în formatul cu 12 ore | De la 01 pâna la 12
%l (litera minuscula 'L') | Ora în formatul cu 12 ore, cu un spa?iu înaintea orei cu o singura cifra | De la 1 pâna la 12
%M | Reprezentarea din doua cifre a minutei | De la 00 pâna la 59
%p | 'AM' sau 'PM' cu litere majuscule în dependen?a de ora | Exemplu: AM pentru 00:31, PM pentru 22:23
%P | 'am' sau 'pm' cu litere minuscule în dependen?a de ora | Exemplu: am pentru 00:31, pm pentru 22:23
%r | Echivalent cu "%I:%M:%S %p" | Exemplu: 09:34:17 PM pentru 21:34:17
%R | Echivalent cu "%H:%M" | Exemplu: 00:35 pentru 12:35 AM, 16:44 pentru 4:44 PM
%S | Reprezentarea din doua cifre a secundei | De la 00 pâna la 59
%T | Echivalent cu "%H:%M:%S" | Exemplu: 21:34:17 pentru 09:34:17 PM
%X | Reprezentarea preferen?iala a orei în baza setarilor locale, fara data | Exemplu: 03:59:16 sau 15:59:16
%z | Deplasamentul fusului orar. Nu este implementat dupa cum este descris în Windows. Vede?i mai jos pentru informa?ii suplimentare. | Exemplu: -0500 pentru US Eastern Time
%Z | Abrevierea fusului orar. Nu este implementat dupa cum este descris în Windows. Vede?i mai jos pentru informa?ii suplimentare. | Exemplu: EST pentru Eastern Time
Data ?i ora --- ---
%c | Reprezentarea preferen?iala a datei ?i orei bazate pe setarile locale | Exemplu: Tue Feb 5 00:45:10 2009 pentru 5 februarie 2009, ora 12:45:10 AM
%D | Echivalent cu "%m/%d/%y" | Exemplu: 02/05/09 pentru February 5, 2009
%F | Echivalent cu "%Y-%m-%d" (utilizat deseori la bazele de date) | Exemplu: 2009-02-05 pentru February 5, 2009
%s | Momentul de timp dupa Epoca Unix (la fel ca ?i în cazul func?iei time()) | Exemplu: 305815200 pentru September 10, 1979 08:40:00 AM
%x | Reprezentarea preferen?iala a datei în baza setarilor locale, fara ora | Exemplu: 02/05/09 pentru February 5, 2009
Diverse --- ---
%n Trecerea la linie noua ("\n") ---
%t Caracterul Tab ("\t") ---
%% Caracterul "procent" ("%") ---

Lungimea maxima a acestui parametru este de 1023 caractere.

Avertizare

Contrar standardului ISO-9899:1999, Sun Solaris pune în coresponden?a zilei de Duminica numarul 1. Ca rezultat, %u poate sa nu func?ioneze dupa cum este descris în acest manual.

Avertizare

Doar pentru Windows:

Modificatorul %e nu este sus?inut în implementarea Windows a acestei func?ii. Pentru a ob?ine un rezultat analogic, utiliza?i modificatorul %#d în loc. Exemplul de mai jos ilustreaza modalitatea de a scrie o func?ie compatibila cu orice platforma.

Modificatorii %z ?i %Z întorc denumirea fusului orar, în loc de deplasament sau abreviere.

Avertizare

Doar pentru Mac OS X: Modificatorul %P nu este sus?inut în implementarea acestei func?ii pe Mac OS X.

timestamp

Parametrul op?ional timestamp este un integer ?i este un moment de timp Unix ?i are valoarea implicita a orei locale, daca parametrul timestamp nu este indicat. Cu alte cuvinte, valoarea implicita este cea a func?iei time().

Valorile întoarse

Întoarce un string formatat în corespundere cu parametrul format, utilizând timestamp-ul dat sau data ?i ora locala, daca nu este furnizat un timestamp. Denumirile lunilor ?i a zilelor saptamânii ?i alte string-uri dependente de limba sunt în corespundere cu setarile locale stabilite cu setlocale().

Erori/Excep?ii

Fiecare apel al unei func?ii de data/ora va genera o E_NOTICE daca zona orara nu este valida ?i/sau un mesaj E_STRICT sau E_WARNING daca se utilizeaza setarile sistemului sau variabila de mediu TZ. Vede?i de asemenea date_default_timezone_set()

Deoarece valoarea întoarsa depinde de biblioteca C ce sta la baza, unii specificatori de conversie nu sunt sus?inu?i. În Windows, furnizarea specificatorilor de conversie necunoscu?i va rezulta în 5 mesaje E_WARNING ?i va întoarce FALSE. În alte sisteme de operare pute?i sa nu ob?ine?i mesaje E_WARNING iar rezultatul poate sa con?ina specificatorii de conversie neconverti?i.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.

Exemple

Acest exemplu va func?iona daca ave?i setarile locale respective instalate în sistem.

Example #1 Exemple strftime()

<?php
setlocale(LC_TIME, "C");
echo strftime("%A");
setlocale(LC_TIME, "fi_FI");
echo strftime(" in Finnish is %A,");
setlocale(LC_TIME, "fr_FR");
echo strftime(" in French %A and");
setlocale(LC_TIME, "de_DE");
echo strftime(" in German %A.\n");
?>

Example #2 Exemplu al numerelor saptamânilor conform standardului ISO 8601:1988

<?php
/*     December 2002 / January 2003
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     16  17  18  19  20  21  22
52     23  24  25  26  27  28  29
1      30  31   1   2   3   4   5
2       6   7   8   9  10  11  12
3      13  14  15  16  17  18  19   */

// Afi?eaza: 12/28/2002 - %V,%G,%Y = 52,2002,2002
echo "12/28/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/28/2002")) . "\n";

// Afi?eaza: 12/30/2002 - %V,%G,%Y = 1,2003,2002
echo "12/30/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/30/2002")) . "\n";

// Afi?eaza: 1/3/2003 - %V,%G,%Y = 1,2003,2003
echo "1/3/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n";

// Afi?eaza: 1/10/2003 - %V,%G,%Y = 2,2003,2003
echo "1/10/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n";

/*     December 2004 / January 2005
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     13  14  15  16  17  18  19
52     20  21  22  23  24  25  26
53     27  28  29  30  31   1   2
1       3   4   5   6   7   8   9
2      10  11  12  13  14  15  16   */

// Afi?eaza: 12/23/2004 - %V,%G,%Y = 52,2004,2004
echo "12/23/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n";

// Afi?eaza: 12/31/2004 - %V,%G,%Y = 53,2004,2004
echo "12/31/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n";

// Afi?eaza: 1/2/2005 - %V,%G,%Y = 53,2004,2005
echo "1/2/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n";

// Afi?eaza: 1/3/2005 - %V,%G,%Y = 1,2005,2005
echo "1/3/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n";

?>

Example #3 Un exemplu de func?ie compatibila pe mai multe platforme, ce utilizeaza modificatorul %e

<?php

// 1 Ian: rezulta în: '%e%1%' (%%, e, %%, %e, %%)
$format = '%%e%%%e%%';

// Verifica daca se ruleaza pe Windows pentru a gasi
// ?i înlocui în mod corect modificatorul %e
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
    $format = preg_replace('#(?<!%)((?:%%)*)%e#', '\1%#d', $format);
}

echo strftime($format);
?>

Example #4 Afi?eaza toate formatele cunoscute ?i necunoscute.

<?php
// Describe the formats.
$strftimeFormats = array(
    'A' => 'A full textual representation of the day',
    'B' => 'Full month name, based on the locale',
    'C' => 'Two digit representation of the century (year divided by 100, truncated to an integer)',
    'D' => 'Same as "%m/%d/%y"',
    'E' => '',
    'F' => 'Same as "%Y-%m-%d"',
    'G' => 'The full four-digit version of %g',
    'H' => 'Two digit representation of the hour in 24-hour format',
    'I' => 'Two digit representation of the hour in 12-hour format',
    'J' => '',
    'K' => '',
    'L' => '',
    'M' => 'Two digit representation of the minute',
    'N' => '',
    'O' => '',
    'P' => 'lower-case "am" or "pm" based on the given time',
    'Q' => '',
    'R' => 'Same as "%H:%M"',
    'S' => 'Two digit representation of the second',
    'T' => 'Same as "%H:%M:%S"',
    'U' => 'Week number of the given year, starting with the first Sunday as the first week',
    'V' => 'ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week',
    'W' => 'A numeric representation of the week of the year, starting with the first Monday as the first week',
    'X' => 'Preferred time representation based on locale, without the date',
    'Y' => 'Four digit representation for the year',
    'Z' => 'The time zone offset/abbreviation option NOT given by %z (depends on operating system)',
    'a' => 'An abbreviated textual representation of the day',
    'b' => 'Abbreviated month name, based on the locale',
    'c' => 'Preferred date and time stamp based on local',
    'd' => 'Two-digit day of the month (with leading zeros)',
    'e' => 'Day of the month, with a space preceding single digits',
    'f' => '',
    'g' => 'Two digit representation of the year going by ISO-8601:1988 standards (see %V)',
    'h' => 'Abbreviated month name, based on the locale (an alias of %b)',
    'i' => '',
    'j' => 'Day of the year, 3 digits with leading zeros',
    'k' => 'Hour in 24-hour format, with a space preceding single digits',
    'l' => 'Hour in 12-hour format, with a space preceding single digits',
    'm' => 'Two digit representation of the month',
    'n' => 'A newline character ("\n")',
    'o' => '',
    'p' => 'UPPER-CASE "AM" or "PM" based on the given time',
    'q' => '',
    'r' => 'Same as "%I:%M:%S %p"',
    's' => 'Unix Epoch Time timestamp',
    't' => 'A Tab character ("\t")',
    'u' => 'ISO-8601 numeric representation of the day of the week',
    'v' => '',
    'w' => 'Numeric representation of the day of the week',
    'x' => 'Preferred date representation based on locale, without the time',
    'y' => 'Two digit representation of the year',
    'z' => 'Either the time zone offset from UTC or the abbreviation (depends on operating system)',
    '%' => 'A literal percentage character ("%")',
);

// Results.
$strftimeValues = array();

// Evaluate the formats whilst suppressing any errors.
foreach($strftimeFormats as $format => $description){
    if (False !== ($value = @strftime("%{$format}"))){
        $strftimeValues[$format] = $value;
    }
}

// Find the longest value.
$maxValueLength = 2 + max(array_map('strlen', $strftimeValues));

// Report known formats.
foreach($strftimeValues as $format => $value){
    echo "Known format   : '{$format}' = ", str_pad("'{$value}'", $maxValueLength), " ( {$strftimeFormats[$format]} )\n";
}

// Report unknown formats.
foreach(array_diff_key($strftimeFormats, $strftimeValues) as $format => $description){
    echo "Unknown format : '{$format}'   ", str_pad(' ', $maxValueLength), ($description ? " ( {$description} )" : ''), "\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Known format   : 'A' = 'Friday'            ( A full textual representation of the day )
Known format   : 'B' = 'December'          ( Full month name, based on the locale )
Known format   : 'H' = '11'                ( Two digit representation of the hour in 24-hour format )
Known format   : 'I' = '11'                ( Two digit representation of the hour in 12-hour format )
Known format   : 'M' = '24'                ( Two digit representation of the minute )
Known format   : 'S' = '44'                ( Two digit representation of the second )
Known format   : 'U' = '48'                ( Week number of the given year, starting with the first Sunday as the first week )
Known format   : 'W' = '48'                ( A numeric representation of the week of the year, starting with the first Monday as the first week )
Known format   : 'X' = '11:24:44'          ( Preferred time representation based on locale, without the date )
Known format   : 'Y' = '2010'              ( Four digit representation for the year )
Known format   : 'Z' = 'GMT Standard Time' ( The time zone offset/abbreviation option NOT given by %z (depends on operating system) )
Known format   : 'a' = 'Fri'               ( An abbreviated textual representation of the day )
Known format   : 'b' = 'Dec'               ( Abbreviated month name, based on the locale )
Known format   : 'c' = '12/03/10 11:24:44' ( Preferred date and time stamp based on local )
Known format   : 'd' = '03'                ( Two-digit day of the month (with leading zeros) )
Known format   : 'j' = '337'               ( Day of the year, 3 digits with leading zeros )
Known format   : 'm' = '12'                ( Two digit representation of the month )
Known format   : 'p' = 'AM'                ( UPPER-CASE "AM" or "PM" based on the given time )
Known format   : 'w' = '5'                 ( Numeric representation of the day of the week )
Known format   : 'x' = '12/03/10'          ( Preferred date representation based on locale, without the time )
Known format   : 'y' = '10'                ( Two digit representation of the year )
Known format   : 'z' = 'GMT Standard Time' ( Either the time zone offset from UTC or the abbreviation (depends on operating system) )
Known format   : '%' = '%'                 ( A literal percentage character ("%") )
Unknown format : 'C'                       ( Two digit representation of the century (year divided by 100, truncated to an integer) )
Unknown format : 'D'                       ( Same as "%m/%d/%y" )
Unknown format : 'E'
Unknown format : 'F'                       ( Same as "%Y-%m-%d" )
Unknown format : 'G'                       ( The full four-digit version of %g )
Unknown format : 'J'
Unknown format : 'K'
Unknown format : 'L'
Unknown format : 'N'
Unknown format : 'O'
Unknown format : 'P'                       ( lower-case "am" or "pm" based on the given time )
Unknown format : 'Q'
Unknown format : 'R'                       ( Same as "%H:%M" )
Unknown format : 'T'                       ( Same as "%H:%M:%S" )
Unknown format : 'V'                       ( ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week )
Unknown format : 'e'                       ( Day of the month, with a space preceding single digits )
Unknown format : 'f'
Unknown format : 'g'                       ( Two digit representation of the year going by ISO-8601:1988 standards (see %V) )
Unknown format : 'h'                       ( Abbreviated month name, based on the locale (an alias of %b) )
Unknown format : 'i'
Unknown format : 'k'                       ( Hour in 24-hour format, with a space preceding single digits )
Unknown format : 'l'                       ( Hour in 12-hour format, with a space preceding single digits )
Unknown format : 'n'                       ( A newline character ("\n") )
Unknown format : 'o'
Unknown format : 'q'
Unknown format : 'r'                       ( Same as "%I:%M:%S %p" )
Unknown format : 's'                       ( Unix Epoch Time timestamp )
Unknown format : 't'                       ( A Tab character ("\t") )
Unknown format : 'u'                       ( ISO-8601 numeric representation of the day of the week )
Unknown format : 'v'

Note

Nota: %G ?i %V, care se bazeaza pe numerele saptamânilor conform standardului ISO 8601:1988 pot oferi rezultate nea?teptate (dar corecte) daca sistemul de numerotare nu este în?eles în detaliu. Vede?i exemplele %V în aceasta pagina a manualului.

A se vedea ?i

  • » Instrumentul online pentru proiectarea formatelor strftime()
  • setlocale() - Set locale information
  • mktime() - Ob?ine timestamp-ul Unix pentru o data ?i ora
  • strptime() - Parse a time/date generated with strftime
  • gmstrftime() - Formateaza o data/ora GMT/UTC în conformitate cu setarile locale
  • » Specifica?ia Open Group a strftime()

mktime
strptime
Func?ii de Data/Timp


Parse a time/date generated with strftime

strftime
strtotime
Func?ii de Data/Timp
PHP Manual

strptime

(PHP 5 >= 5.1.0, PHP 7)

strptime — Parse a time/date generated with strftime()

Descrierea

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).

Parametri

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.

Valorile întoarse

Returns an array sau FALSE în cazul e?ecului.

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

Exemple

Example #1 strptime() example

<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);

echo "$strf\n";

print_r(strptime($strf, $format));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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] =>
)

Note

Nota: Aceasta func?ie nu este implementata pe platformele Windows.

Nota:

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.

Nota:

"tm_sec" includes any leap seconds (currently upto 2 a year). For more information on leap seconds, see the » Wikipedia article on leap seconds.

Nota:

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.

A se vedea ?i

  • checkdate() - Valideaza o data Gregoriana
  • strftime() - Formateaza o ora/data locala în conformitate cu setarile locale
  • date_parse_from_format() - Get info about given date formatted according to the specified format
  • DateTime::createFromFormat() - Parses a time string according to a specified format

strftime
strtotime
Func?ii de Data/Timp


Transleaza aproape orice descriere textuala în limba engleza a datei ?i orei într-un timestamp Unix

strptime
time
Func?ii de Data/Timp
PHP Manual

strtotime

(PHP 4, PHP 5, PHP 7)

strtotime — Transleaza aproape orice descriere textuala în limba engleza a datei ?i orei într-un timestamp Unix

Descrierea

int strtotime ( string $time [, int $now = time() ] )

Func?ia a?teapta un ?ir de caractere con?inând un format de data engleza ?i încearca sa transforme acest format într-un timestamp Unix (numarul de secunde de la 1 Ianuarie 1970 00:00:00 UTC), în raport cu timestamp-ul dat în parametrul now, sau cu ora curenta daca parametrul now nu este furnizat.

Fiecare parametru al acestei func?ii utilizeaza fusul orar implicit, afara de cazul când fusul orar este specificat în acel parametru. Fi?i aten?i sa nu utiliza?i diferite fusuri orare în fiecare parametru, afara de cazul când anume a?a se inten?ioneaza. Vede?i date_default_timezone_get() pentru diferite metode de a defini fusul orar implicit.

Parametri

time

Un ?ir data/ora. Formatele valide sunt explicate în Formatele datelor ?i orelor.

now

Timestamp-ul care este utilizat ca baza pentru calcularea datelor relative.

Valorile întoarse

Întoarce un timestamp în caz de succes, FALSE în caz contrar. Înainte de PHP 5.1.0, aceasta func?ie întorcea -1 în caz de e?ec.

Erori/Excep?ii

Fiecare apel al unei func?ii de data/ora va genera o E_NOTICE daca zona orara nu este valida ?i/sau un mesaj E_STRICT sau E_WARNING daca se utilizeaza setarile sistemului sau variabila de mediu TZ. Vede?i de asemenea date_default_timezone_set()

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Anterior versiunii PHP 5.3.0, formatele de timp relative transmise prin argumentul time al func?iei strtotime(), cum ar fi this week, previous week, last week ?i next week erau interpretate ca perioada de 7 zile relativ cu data/ora curenta, ?i nu ca o perioada de o saptamâna de la Monday pâna la Sunday.
5.3.0 | Anterior versiunii PHP 5.3.0, 24:00 nu era un format valid ?i strtotime() întorcea FALSE.
5.2.7 | În PHP 5 anterior versiunii 5.2.7, cererea de a ob?ine o anumita zi a saptamânii într-o luna, unde aceasta zi este prima zi a lunii, adauga în mod incorect o saptamâna la valoarea întoarsa. Aceasta a fost corectat în versiunea 5.2.7 ?i cele ulterioare.
5.1.0 | Acum întoarce FALSE în caz de e?ec, în loc de -1.
5.1.0 | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.
5.0.2 | În PHP 5 pâna la versiunea 5.0.2, "now" ?i alte momente de timp relative erau calculate gre?it relativ la miezul nop?ii de astazi. Aceasta difera de alte versiuni, unde el este calculat corect relativ la ora curenta.
5.0.0 | Microsecundele au început sa fie permise, dar sunt ignorate.

Exemple

Example #1 Exemplu 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";
?>

Example #2 Verificarea e?ecului

<?php
$str = 'Nu e bine';

// înainte de PHP 5.1.0 ar fi trebuit de comparat cu -1, în loc de false
if (($timestamp = strtotime($str)) === false) {
    echo "String-ul ($str) nu este corect";
} else {
    echo "$str == " . date('l dS \o\f F Y h:i:s A', $timestamp);
}
?>

Note

Nota:

Daca anul este specificat cu doua cifre, valorile între 00-69 sunt interpretate ca 2000-2069, iar valorile între 70-99 ca 1970-1999. Vede?i notele de mai jos pentru posibilele diferen?e pe sistemele pe 32 de bi?i (datele posibile pot sa se încheie cu 2038-01-19 03:14:07)

Nota:

Domeniul valid al unui timestamp este de obicei de la Fri, 13 Dec 1901 20:45:54 UTC pâna la Tue, 19 Jan 2038 03:14:07 UTC. (Acestea sunt datele ce corespund valorilor minima ?i maxima pentru un întreg pe 32 bi?i cu semn.)

Anterior versiunii PHP 5.1.0, nu toate platformele sus?in timestamp-uri negative, de aceea domeniul datelor poate fi limitat la valorile de dupa Epoca Unix. Aceasta înseamna ca de ex. datele de pâna la 1 Ianuarie 1970 nu vor fi valide în Windows, unele distributive Linux, ?i alte câteva sisteme de operare.

Pentru versiunile PHP pe 64 de bi?i domeniul valid a unui timestamp este practic infinit, deoarece pe 64 de bi?i se pot reprezenta aproximativ 293 milioane de ani în ambele direc?ii.

Nota:

Datele în formatul m/d/y sau d-m-y sunt disambiguate analizând separatorul dintre deferite componente: daca separatorul este slash (/), atunci este utilizat formatul American m/d/y; iar daca separatorul este liniu?a (-) sau punctul (.), atunci este utilizat formatul European d-m-y. Însa daca anul e furnizat în format cu doua cifre ?i separatorul este liniu?a (-), atunci ?irul cu data va fi interpretat ca y-m-d.

Pentru a evita o poten?iala ambiguitate, cel mai bine este de a utiliza date în format ISO 8601 (YYYY-MM-DD) sau DateTime::createFromFormat() atunci când este posibil.

Nota:

Utilizarea acestei func?ii pentru opera?ii matematice nu este recomandabila. Este mai bine de a utiliza DateTime::add() ?i DateTime::sub() în PHP 5.3 ?i ulterior, sau DateTime::modify() în PHP 5.2.

A se vedea ?i

  • Formatele datei ?i orei
  • DateTime::createFromFormat() - Parses a time string according to a specified format
  • checkdate() - Valideaza o data Gregoriana
  • strptime() - Parse a time/date generated with strftime

strptime
time
Func?ii de Data/Timp


Întoarce timpul curent Unix

strtotime
timezone_abbreviations_list
Func?ii de Data/Timp
PHP Manual

time

(PHP 4, PHP 5, PHP 7)

time — Întoarce timpul curent Unix

Descrierea

int time ( void )

Întoarce timpul curent masurat în numarul de secunde de la Epoca Unix (January 1 1970 00:00:00 GMT).

Exemple

Example #1 Exemplu time()

<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
                   // 7 zile; 24 ore; 60 minute; 60 secunde
echo 'Acum:                '. date('Y-m-d') ."\n";
echo 'Saptamâna urmatoare: '. date('Y-m-d', $nextWeek) ."\n";
// sau utilizând strtotime():
echo 'Saptamâna urmatoare: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

Acum:                2005-03-30
Saptamâna urmatoare: 2005-04-06
Saptamâna urmatoare: 2005-04-06

Note

Sfat

Momentul de timp al începutului interpelarii este disponibil în $_SERVER['REQUEST_TIME'] începând cu PHP 5.1.

A se vedea ?i

  • date() - Formateaza o ora/data
  • microtime() - Întoarce timpul curent Unix cu microsecunde

strtotime
timezone_abbreviations_list
Func?ii de Data/Timp


Pseudonim pentru DateTimeZone::listAbbreviations

time
timezone_identifiers_list
Func?ii de Data/Timp
PHP Manual

timezone_abbreviations_list

(PHP 5 >= 5.2.0, PHP 7)

timezone_abbreviations_list — Pseudonim pentru DateTimeZone::listAbbreviations()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTimeZone::listAbbreviations()

time
timezone_identifiers_list
Func?ii de Data/Timp


Pseudonim pentru DateTimeZone::listIdentifiers

timezone_abbreviations_list
timezone_location_get
Func?ii de Data/Timp
PHP Manual

timezone_identifiers_list

(PHP 5 >= 5.2.0, PHP 7)

timezone_identifiers_list — Pseudonim pentru DateTimeZone::listIdentifiers()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTimeZone::listIdentifiers()

timezone_abbreviations_list
timezone_location_get
Func?ii de Data/Timp


Pseudonim pentru DateTimeZone::getLocation

timezone_identifiers_list
timezone_name_from_abbr
Func?ii de Data/Timp
PHP Manual

timezone_location_get

(PHP 5 >= 5.3.0, PHP 7)

timezone_location_get — Pseudonim pentru DateTimeZone::getLocation()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTimeZone::getLocation()

timezone_identifiers_list
timezone_name_from_abbr
Func?ii de Data/Timp


Returns the timezone name from abbreviation

timezone_location_get
timezone_name_get
Func?ii de Data/Timp
PHP Manual

timezone_name_from_abbr

(PHP 5 >= 5.1.3, PHP 7)

timezone_name_from_abbr — Returns the timezone name from abbreviation

Descrierea

string timezone_name_from_abbr ( string $abbr [, int $gmtOffset = -1 [, int $isdst = -1 ]] )

Parametri

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.

Valorile întoarse

Returns time zone name on success sau FALSE în cazul e?ecului.

Exemple

Example #1 A timezone_name_from_abbr() example

<?php
echo timezone_name_from_abbr("CET") . "\n";
echo timezone_name_from_abbr("", 3600, 0) . "\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

Europe/Berlin
Europe/Paris

A se vedea ?i

  • timezone_abbreviations_list() - Pseudonim pentru DateTimeZone::listAbbreviations

timezone_location_get
timezone_name_get
Func?ii de Data/Timp


Pseudonim pentru DateTimeZone::getName

timezone_name_from_abbr
timezone_offset_get
Func?ii de Data/Timp
PHP Manual

timezone_name_get

(PHP 5 >= 5.2.0, PHP 7)

timezone_name_get — Pseudonim pentru DateTimeZone::getName()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTimeZone::getName()

timezone_name_from_abbr
timezone_offset_get
Func?ii de Data/Timp


Pseudonim pentru DateTimeZone::getOffset

timezone_name_get
timezone_open
Func?ii de Data/Timp
PHP Manual

timezone_offset_get

(PHP 5 >= 5.2.0, PHP 7)

timezone_offset_get — Pseudonim pentru DateTimeZone::getOffset()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTimeZone::getOffset()

timezone_name_get
timezone_open
Func?ii de Data/Timp


Pseudonim pentru DateTimeZone::__construct

timezone_offset_get
timezone_transitions_get
Func?ii de Data/Timp
PHP Manual

timezone_open

(PHP 5 >= 5.2.0, PHP 7)

timezone_open — Pseudonim pentru DateTimeZone::__construct()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTimeZone::__construct()

timezone_offset_get
timezone_transitions_get
Func?ii de Data/Timp


Pseudonim pentru DateTimeZone::getTransitions

timezone_open
timezone_version_get
Func?ii de Data/Timp
PHP Manual

timezone_transitions_get

(PHP 5 >= 5.2.0, PHP 7)

timezone_transitions_get — Pseudonim pentru DateTimeZone::getTransitions()

Descrierea

Aceasta func?ie este pseudonim pentru: DateTimeZone::getTransitions()

timezone_open
timezone_version_get
Func?ii de Data/Timp


Gets the version of the timezonedb

timezone_transitions_get
Supported Date and Time Formats
Func?ii de Data/Timp
PHP Manual

timezone_version_get

(PHP 5 >= 5.3.0, PHP 7)

timezone_version_get — Gets the version of the timezonedb

Descrierea

string timezone_version_get ( void )

Returns the current version of the timezonedb.

Valorile întoarse

Returns a string.

Exemple

Example #1 Getting the timezonedb version

<?php
echo timezone_version_get();
?>

Exemplul de mai sus va afi?a ceva similar cu:

2009.7

A se vedea ?i

  • List of Supported Timezones

timezone_transitions_get
Supported Date and Time Formats
Func?ii de Data/Timp


Supported Date and Time Formats

Cuprins

  • 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
Date/Time


Time Formats

This page describes the different time formats that the strtotime(), DateTime and date_create() parser understands.

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", "07", "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

This page describes the different date formats that the strtotime(), DateTime and date_create() parser understands.

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.1978"
Day, month and two digit year, with dots or tabs | dd [.\t] mm "." yy | "30.6.08", "22\t12.78"
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"

Nota:

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".

Nota:

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.

Nota:

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.

Nota:

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).

Note that as of PHP 5.1.0 the day range is restricted to 0-31 as indicated by the regular expression above. Thus "2008-06-32" is not a valid date string, for instance.

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

This page describes the different compound date/time formats that the strtotime(), DateTime and date_create() parser understands.

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] | "001", "012", "180", "350", "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-1][0-9] | "00", "12"
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 ":"? II? | "+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"

Nota:

The "W" in the "ISO year with ISO week" and "ISO year with ISO week and day" formats is case-sensitive, you can only use the upper case "W".

The "T" in the SOAP, XMRPC and WDDX formats is case-sensitive, you can only use the upper case "T".

The "Unix Timestamp" format sets the timezone to UTC.

Date Formats
Relative Formats
Supported Date and Time Formats


Relative Formats

This page describes the different relative date/time formats that the strtotime(), DateTime and date_create() parser understands.

Used Symbols
Description | Format
dayname | 'sunday' | 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat'
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"
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"

Nota:

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.

Nota:

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").

Nota:

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.

Istoricul schimbarilor

Versiune | Descriere
5.6.23, 7.0.8 | Weeks always start on monday. Formerly, sunday would also be considered to start a week.
5.3.3 | "first day" and "last day" changed to behave has "+1 day" and "-1 day", respectively. Previously, the behaviour was as "first day of" and "last day of".

Compound Formats
Lista zonelor orare sus?inute
Supported Date and Time Formats


Lista zonelor orare sus?inute

Cuprins

  • Africa
  • America
  • Antarctica
  • Arctica
  • Asia
  • Atlantica
  • Australia
  • Europa
  • India
  • Pacificul
  • Altele

Aici pute?i gasi lista deplina a zonelor orare sus?inute de PHP, care pot fi utilizate cu de ex. date_default_timezone_set().

Nota: Ultima versiune a bazei de date cu zonele orare poate fi instalata prin » timezonedb al PECL.

Nota: Aceasta lista este bazata pe baza de date a fuselor orare de versiunea 2016.10.

Relative Formats
Africa
Date/Time


Africa

Africa
Africa/Abidjan | Africa/Accra | Africa/Addis_Ababa | Africa/Algiers
Africa/Asmara | 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/Tripoli | Africa/Tunis | Africa/Windhoek
Lista zonelor orare sus?inute
America
Lista zonelor orare sus?inute


America

America
America/Adak | America/Anchorage | America/Anguilla | America/Antigua
America/Araguaina | America/Argentina/Buenos_Aires | America/Argentina/Catamarca | 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/Bahia | America/Bahia_Banderas | America/Barbados | America/Belem
America/Belize | America/Blanc-Sablon | America/Boa_Vista | America/Bogota
America/Boise | America/Cambridge_Bay | America/Campo_Grande | America/Cancun
America/Caracas | America/Cayenne | America/Cayman | America/Chicago
America/Chihuahua | America/Costa_Rica | America/Creston | America/Cuiaba
America/Curacao | America/Danmarkshavn | America/Dawson | America/Dawson_Creek
America/Denver | America/Detroit | America/Dominica | America/Edmonton
America/Eirunepe | America/El_Salvador | America/Fort_Nelson | 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/Inuvik | America/Iqaluit | America/Jamaica | America/Juneau
America/Kentucky/Louisville | America/Kentucky/Monticello | America/Kralendijk | America/La_Paz
America/Lima | America/Los_Angeles | America/Lower_Princes | America/Maceio
America/Managua | America/Manaus | America/Marigot | America/Martinique
America/Matamoros | America/Mazatlan | America/Menominee | America/Merida
America/Metlakatla | America/Mexico_City | America/Miquelon | America/Moncton
America/Monterrey | America/Montevideo | 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_Velho | America/Puerto_Rico
America/Rainy_River | America/Rankin_Inlet | America/Recife | America/Regina
America/Resolute | America/Rio_Branco | America/Santarem | America/Santiago
America/Santo_Domingo | America/Sao_Paulo | America/Scoresbysund | 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/Whitehorse | America/Winnipeg
America/Yakutat | America/Yellowknife |  |
Africa
Antarctica
Lista zonelor orare sus?inute


Antarctica

Antarctica
Antarctica/Casey | Antarctica/Davis | Antarctica/DumontDUrville | Antarctica/Macquarie
Antarctica/Mawson | Antarctica/McMurdo | Antarctica/Palmer | Antarctica/Rothera
Antarctica/Syowa | Antarctica/Troll | Antarctica/Vostok |
America
Arctica
Lista zonelor orare sus?inute


Arctica

Arctica
Arctic/Longyearbyen
Antarctica
Asia
Lista zonelor orare sus?inute


Asia

Asia
Asia/Aden | Asia/Almaty | Asia/Amman | Asia/Anadyr
Asia/Aqtau | Asia/Aqtobe | Asia/Ashgabat | Asia/Atyrau
Asia/Baghdad | Asia/Bahrain | Asia/Baku | Asia/Bangkok
Asia/Barnaul | Asia/Beirut | Asia/Bishkek | Asia/Brunei
Asia/Chita | Asia/Choibalsan | Asia/Colombo | Asia/Damascus
Asia/Dhaka | Asia/Dili | Asia/Dubai | Asia/Dushanbe
Asia/Famagusta | Asia/Gaza | Asia/Hebron | Asia/Ho_Chi_Minh
Asia/Hong_Kong | Asia/Hovd | Asia/Irkutsk | Asia/Jakarta
Asia/Jayapura | Asia/Jerusalem | Asia/Kabul | Asia/Kamchatka
Asia/Karachi | Asia/Kathmandu | Asia/Khandyga | Asia/Kolkata
Asia/Krasnoyarsk | Asia/Kuala_Lumpur | Asia/Kuching | Asia/Kuwait
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/Riyadh
Asia/Sakhalin | Asia/Samarkand | Asia/Seoul | Asia/Shanghai
Asia/Singapore | Asia/Srednekolymsk | Asia/Taipei | Asia/Tashkent
Asia/Tbilisi | Asia/Tehran | Asia/Thimphu | Asia/Tokyo
Asia/Tomsk | Asia/Ulaanbaatar | Asia/Urumqi | Asia/Ust-Nera
Asia/Vientiane | Asia/Vladivostok | Asia/Yakutsk | Asia/Yangon
Asia/Yekaterinburg | Asia/Yerevan |  |
Arctica
Atlantica
Lista zonelor orare sus?inute


Atlantica

Atlantica
Atlantic/Azores | Atlantic/Bermuda | Atlantic/Canary | Atlantic/Cape_Verde
Atlantic/Faroe | Atlantic/Madeira | Atlantic/Reykjavik | Atlantic/South_Georgia
Atlantic/St_Helena | Atlantic/Stanley |  |
Asia
Australia
Lista zonelor orare sus?inute


Australia

Australia
Australia/Adelaide | Australia/Brisbane | Australia/Broken_Hill | Australia/Currie
Australia/Darwin | Australia/Eucla | Australia/Hobart | Australia/Lindeman
Australia/Lord_Howe | Australia/Melbourne | Australia/Perth | Australia/Sydney
Atlantica
Europa
Lista zonelor orare sus?inute


Europa

Europa
Europe/Amsterdam | Europe/Andorra | Europe/Astrakhan | Europe/Athens
Europe/Belgrade | Europe/Berlin | Europe/Bratislava | Europe/Brussels
Europe/Bucharest | Europe/Budapest | Europe/Busingen | 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/Kirov | Europe/Lisbon
Europe/Ljubljana | Europe/London | Europe/Luxembourg | Europe/Madrid
Europe/Malta | Europe/Mariehamn | Europe/Minsk | Europe/Monaco
Europe/Moscow | Europe/Oslo | Europe/Paris | Europe/Podgorica
Europe/Prague | Europe/Riga | Europe/Rome | Europe/Samara
Europe/San_Marino | Europe/Sarajevo | Europe/Saratov | Europe/Simferopol
Europe/Skopje | Europe/Sofia | Europe/Stockholm | Europe/Tallinn
Europe/Tirane | Europe/Ulyanovsk | Europe/Uzhgorod | Europe/Vaduz
Europe/Vatican | Europe/Vienna | Europe/Vilnius | Europe/Volgograd
Europe/Warsaw | Europe/Zagreb | Europe/Zaporozhye | Europe/Zurich
Australia
India
Lista zonelor orare sus?inute


India

India
Indian/Antananarivo | Indian/Chagos | Indian/Christmas | Indian/Cocos
Indian/Comoro | Indian/Kerguelen | Indian/Mahe | Indian/Maldives
Indian/Mauritius | Indian/Mayotte | Indian/Reunion |
Europa
Pacificul
Lista zonelor orare sus?inute


Pacificul

Pacificul
Pacific/Apia | Pacific/Auckland | Pacific/Bougainville | 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/Port_Moresby
Pacific/Rarotonga | Pacific/Saipan | Pacific/Tahiti | Pacific/Tarawa
Pacific/Tongatapu | Pacific/Wake | Pacific/Wallis |
India
Altele
Lista zonelor orare sus?inute


Altele

Avertizare

Nu utiliza?i zonele orare enumerate aici (afara de UTC), ele exista numai din motive de compatibilitate inversa.

Avertizare

Daca nu ?ine?i seama de avertizarea anterioara, va rugam sa atrage?i aten?ia ca baza de date a fuselor orare IANA, care ofera sus?inerea furelor orare în PHP utilizeaza semne în stil POSIX, ceea ce va duce la faptul ca fusele orare Etc/GMT+n ?i Etc/GMT-n vor fi inversate fa?a de modul în care se utilizeaza de obicei.

Spre exemplu, fusul orar de 8 ore înainte de GMT, care e utilizat în China ?i Australia de Vest (printre altele) este de fapt Etc/GMT-8 în aceasta baza de date, ?i nu Etc/GMT+8 dupa cum s-ar fi a?teptat în mod normal.

?i iara?i, este foarte recomandabil sa utiliza?i fusul orar corect pentru loca?ia dumneavoastra, cum ar fi Asia/Shanghai sau Australia/Perth pentru exemplele de mai sus.

Altele
Africa/Asmera | Africa/Timbuktu | America/Argentina/ComodRivadavia | America/Atka
America/Buenos_Aires | America/Catamarca | America/Coral_Harbour | America/Cordoba
America/Ensenada | America/Fort_Wayne | America/Indianapolis | America/Jujuy
America/Knox_IN | America/Louisville | America/Mendoza | America/Montreal
America/Porto_Acre | America/Rosario | America/Santa_Isabel | America/Shiprock
America/Virgin | Antarctica/South_Pole | Asia/Ashkhabad | Asia/Calcutta
Asia/Chongqing | Asia/Chungking | Asia/Dacca | Asia/Harbin
Asia/Istanbul | Asia/Kashgar | Asia/Katmandu | Asia/Macao
Asia/Rangoon | Asia/Saigon | Asia/Tel_Aviv | Asia/Thimbu
Asia/Ujung_Pandang | Asia/Ulan_Bator | Atlantic/Faeroe | Atlantic/Jan_Mayen
Australia/ACT | Australia/Canberra | Australia/LHI | Australia/North
Australia/NSW | Australia/Queensland | Australia/South | Australia/Tasmania
Australia/Victoria | Australia/West | Australia/Yancowinna | 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 | Europe/Belfast | Europe/Nicosia | Europe/Tiraspol
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 | Pacific/Ponape | Pacific/Samoa
Pacific/Truk | Pacific/Yap | 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 |  |  |
Pacificul
HRTime
Lista zonelor orare sus?inute


High resolution timing

  • Introducere
  • Instalarea / configurarea
    • Instalarea
  • Exemple
    • Basic usage
  • HRTime\PerformanceCounter — The HRTime\PerformanceCounter class
    • HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second
    • HRTime\PerformanceCounter::getTicks — Current ticks from the system
    • HRTime\PerformanceCounter::getTicksSince — Ticks elapsed since the given value
  • HRTime\StopWatch — The HRTime\StopWatch class
    • HRTime\StopWatch::getElapsedTicks — Get elapsed ticks for all intervals.
    • HRTime\StopWatch::getElapsedTime — Get elapsed time for all intervals.
    • HRTime\StopWatch::getLastElapsedTicks — Get elapsed ticks for the last interval.
    • HRTime\StopWatch::getLastElapsedTime — Get elapsed time for the last interval.
    • HRTime\StopWatch::isRunning — Whether the measurement is running.
    • HRTime\StopWatch::start — Start time measurement
    • HRTime\StopWatch::stop — Stop time measurement
  • HRTime\Unit — The HRTime\Unit class
Altele
Introducere
Extensii referitoare la data ?i ora


Introducere

The HRTime extension implements a high resolution StopWatch class. It uses the best possible APIs on different platforms which brings resolution up to nanoseconds. It also makes possible to implement a custom stopwatch using low level ticks delivered by the underlaying APIs.

HRTime
Instalarea / configurarea
HRTime


Instalarea / configurarea

Cuprins

  • Instalarea
Introducere
Instalarea
HRTime


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/hrtime.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/hrtime/.

Instalarea / configurarea
Exemple
Instalarea / configurarea


Exemple

Cuprins

  • Basic usage
Instalarea
Basic usage
HRTime


Basic usage

The example illustrates the basic StopWatch class usage

Example #1 Measure several code blocks execution and get the total

<?php

$c = new HRTime\StopWatch;

$c->start();
/* measure this code block execution */
for ($i = 0; $i < 1024*1024; $i++);
$c->stop();
$elapsed0 = $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);

/* measurement is not running here*/
for ($i = 0; $i < 1024*1024; $i++);

$c->start();
/* measure this code block execution */
for ($i = 0; $i < 1024*1024; $i++);
$c->stop();
$elapsed1 = $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);

$elapsed_total = $c->getElapsedTime(HRTime\Unit::NANOSECOND);

?>
Exemple
HRTime\PerformanceCounter
Exemple


The HRTime\PerformanceCounter class

(PECL hrtime >= 0.4.3)

Introducere

Sinopsisul clasei

HRTime\PerformanceCounter {
/* Metode */
public static int getFrequency ( void )
public static int getTicks ( void )
public static int getTicksSince ( integer $start )
}

Cuprins

  • HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second
  • HRTime\PerformanceCounter::getTicks — Current ticks from the system
  • HRTime\PerformanceCounter::getTicksSince — Ticks elapsed since the given value
Basic usage
HRTime\PerformanceCounter::getFrequency
HRTime


Timer frequency in ticks per second

HRTime\PerformanceCounter
HRTime\PerformanceCounter::getTicks
HRTime\PerformanceCounter
PHP Manual

HRTime\PerformanceCounter::getFrequency

(PECL hrtime >= 0.4.3)

HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second

Descrierea

public static int HRTime\PerformanceCounter::getFrequency ( void )

Returns the timer frequency in ticks per second. This value is constant after the system start on almost any operating system.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns integer indicating the timer frequency.

HRTime\PerformanceCounter
HRTime\PerformanceCounter::getTicks
HRTime\PerformanceCounter


Current ticks from the system

HRTime\PerformanceCounter::getFrequency
HRTime\PerformanceCounter::getTicksSince
HRTime\PerformanceCounter
PHP Manual

HRTime\PerformanceCounter::getTicks

(PECL hrtime >= 0.6.0)

HRTime\PerformanceCounter::getTicks — Current ticks from the system

Descrierea

public static int HRTime\PerformanceCounter::getTicks ( void )

Returns the ticks count.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns integer indicating the ticks count.

HRTime\PerformanceCounter::getFrequency
HRTime\PerformanceCounter::getTicksSince
HRTime\PerformanceCounter


Ticks elapsed since the given value

HRTime\PerformanceCounter::getTicks
HRTime\StopWatch
HRTime\PerformanceCounter
PHP Manual

HRTime\PerformanceCounter::getTicksSince

(PECL hrtime >= 0.6.0)

HRTime\PerformanceCounter::getTicksSince — Ticks elapsed since the given value

Descrierea

public static int HRTime\PerformanceCounter::getTicksSince ( integer $start )

Returns the ticks count elapsed since the given start value.

Parametri

start

Starting ticks value.

Valorile întoarse

Returns integer indicating the ticks count.

HRTime\PerformanceCounter::getTicks
HRTime\StopWatch
HRTime\PerformanceCounter


The HRTime\StopWatch class

(PECL hrtime >= 0.4.3)

Introducere

Sinopsisul clasei

HRTime\StopWatch extends HRTime\PerformanceCounter {
/* Metode */
public int getElapsedTicks ( void )
public float getElapsedTime ([ integer $unit ] )
public int getLastElapsedTicks ( void )
public float getLastElapsedTime ([ integer $unit ] )
public bool isRunning ( void )
public void start ( void )
public void stop ( void )
/* Metode mo?tenite */
public static int HRTime\PerformanceCounter::getFrequency ( void )
public static int HRTime\PerformanceCounter::getTicks ( void )
public static int HRTime\PerformanceCounter::getTicksSince ( integer $start )
}

Cuprins

  • HRTime\StopWatch::getElapsedTicks — Get elapsed ticks for all intervals.
  • HRTime\StopWatch::getElapsedTime — Get elapsed time for all intervals.
  • HRTime\StopWatch::getLastElapsedTicks — Get elapsed ticks for the last interval.
  • HRTime\StopWatch::getLastElapsedTime — Get elapsed time for the last interval.
  • HRTime\StopWatch::isRunning — Whether the measurement is running.
  • HRTime\StopWatch::start — Start time measurement
  • HRTime\StopWatch::stop — Stop time measurement
HRTime\PerformanceCounter::getTicksSince
HRTime\StopWatch::getElapsedTicks
HRTime


Get elapsed ticks for all intervals.

HRTime\StopWatch
HRTime\StopWatch::getElapsedTime
HRTime\StopWatch
PHP Manual

HRTime\StopWatch::getElapsedTicks

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getElapsedTicks — Get elapsed ticks for all intervals.

Descrierea

public int HRTime\StopWatch::getElapsedTicks ( void )

Get elapsed ticks for all the previously closed intervals.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns integer indicating elapsed ticks.

HRTime\StopWatch
HRTime\StopWatch::getElapsedTime
HRTime\StopWatch


Get elapsed time for all intervals.

HRTime\StopWatch::getElapsedTicks
HRTime\StopWatch::getLastElapsedTicks
HRTime\StopWatch
PHP Manual

HRTime\StopWatch::getElapsedTime

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getElapsedTime — Get elapsed time for all intervals.

Descrierea

public float HRTime\StopWatch::getElapsedTime ([ integer $unit ] )

Get elapsed time for all the previously closed intervals.

Parametri

unit

Time unit represented by a HRTime\Unit constant. Default is HRTime\Unit::SECOND.

Valorile întoarse

Returns float indicating elapsed time.

HRTime\StopWatch::getElapsedTicks
HRTime\StopWatch::getLastElapsedTicks
HRTime\StopWatch


Get elapsed ticks for the last interval.

HRTime\StopWatch::getElapsedTime
HRTime\StopWatch::getLastElapsedTime
HRTime\StopWatch
PHP Manual

HRTime\StopWatch::getLastElapsedTicks

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getLastElapsedTicks — Get elapsed ticks for the last interval.

Descrierea

public int HRTime\StopWatch::getLastElapsedTicks ( void )

Get elapsed ticks for the previously closed interval.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns integer indicating elapsed ticks.

HRTime\StopWatch::getElapsedTime
HRTime\StopWatch::getLastElapsedTime
HRTime\StopWatch


Get elapsed time for the last interval.

HRTime\StopWatch::getLastElapsedTicks
HRTime\StopWatch::isRunning
HRTime\StopWatch
PHP Manual

HRTime\StopWatch::getLastElapsedTime

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getLastElapsedTime — Get elapsed time for the last interval.

Descrierea

public float HRTime\StopWatch::getLastElapsedTime ([ integer $unit ] )

Get elapsed time for the previously closed interval.

Parametri

unit

Time unit represented by a HRTime\Unit constant. Default is HRTime\Unit::SECOND.

Valorile întoarse

Returns float indicating elapsed time.

HRTime\StopWatch::getLastElapsedTicks
HRTime\StopWatch::isRunning
HRTime\StopWatch


Whether the measurement is running.

HRTime\StopWatch::getLastElapsedTime
HRTime\StopWatch::start
HRTime\StopWatch
PHP Manual

HRTime\StopWatch::isRunning

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::isRunning — Whether the measurement is running.

Descrierea

public bool HRTime\StopWatch::isRunning ( void )

Reveals whether the measurement was started.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns boolean indicating whetehr the measurement is running.

HRTime\StopWatch::getLastElapsedTime
HRTime\StopWatch::start
HRTime\StopWatch


Start time measurement

HRTime\StopWatch::isRunning
HRTime\StopWatch::stop
HRTime\StopWatch
PHP Manual

HRTime\StopWatch::start

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::start — Start time measurement

Descrierea

public void HRTime\StopWatch::start ( void )

Starts the time measurement. It has no effect if the measurement was already started. The measurement will be continued if it was previously stopped.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns void.

HRTime\StopWatch::isRunning
HRTime\StopWatch::stop
HRTime\StopWatch


Stop time measurement

HRTime\StopWatch::start
HRTime\Unit
HRTime\StopWatch
PHP Manual

HRTime\StopWatch::stop

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::stop — Stop time measurement

Descrierea

public void HRTime\StopWatch::stop ( void )

Stop the time measurement for the previously started interval.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns void.

HRTime\StopWatch::start
HRTime\Unit
HRTime\StopWatch


The HRTime\Unit class

(PECL hrtime >= 0.4.3)

Introducere

Sinopsisul clasei

HRTime\Unit {
/* Constants */
const integer SECOND = 0 ;
const integer MILLISECOND = 1 ;
const integer MICROSECOND = 2 ;
const integer NANOSECOND = 3 ;
/* Metode */
}

Constante predefinite

HRTime\Unit::SECOND

HRTime\Unit::MILLISECOND

HRTime\Unit::MICROSECOND

HRTime\Unit::NANOSECOND

HRTime\StopWatch::stop
Extensii referitoare la sistemul de fi?iere
HRTime


Extensii referitoare la sistemul de fi?iere

  • Direct IO
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii IO directe
  • Directorii
    • Instalarea / configurarea
    • Constante predefinite
    • Directory — The Directory class
    • Func?ii de lucru cu directoare
  • Fileinfo — File Information
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Fileinfo
    • finfo — The finfo class
  • Filesystem
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Filesystem Func?ii
  • Inotify
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Inotify
  • Mimetype
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
  • Proctitle
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii proctitle
  • xattr
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii xattr
  • xdiff
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii xdiff
HRTime\Unit
Direct IO
Informa?ii de referin?a despre func?ii


Direct IO

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii IO directe
    • 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
Extensii referitoare la sistemul de fi?iere
Introducere
Extensii referitoare la sistemul de fi?iere


Introducere

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.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.1.0.

This extension is only available on Windows Platforms as of PHP 5.0.0

Direct IO
Instalarea / configurarea
Direct IO


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Direct IO


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/dio.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

One resource type is defined by this extension: a file descriptor returned by dio_open().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)

Tipurile resurselor
Func?ii IO directe
Direct IO


Func?ii IO directe

Cuprins

  • 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
Constante predefinite
dio_close
Direct IO


Closes the file descriptor given by fd

Func?ii IO directe
dio_fcntl
Func?ii IO directe
PHP Manual

dio_close

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5, PHP 7)

dio_close — Closes the file descriptor given by fd

Descrierea

void dio_close ( resource $fd )

The function dio_close() closes the file descriptor fd.

Parametri

fd

The file descriptor returned by dio_open().

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Closing an open file descriptor

<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_close($fd);
?>

A se vedea ?i

  • dio_open() - Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

Func?ii IO directe
dio_fcntl
Func?ii IO directe


Performs a c library fcntl on fd

dio_close
dio_open
Func?ii IO directe
PHP Manual

dio_fcntl

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5, PHP 7)

dio_fcntl — Performs a c library fcntl on fd

Descrierea

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.

Parametri

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 below) 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

  • whence - 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)

Valorile întoarse

Returns the result of the C call.

Exemple

Example #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 successfully set/cleared";
}

dio_close($fd);
?>

Note

Nota: Aceasta func?ie nu este implementata pe platformele Windows.

dio_close
dio_open
Func?ii IO directe


Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

dio_fcntl
dio_read
Func?ii IO directe
PHP Manual

dio_open

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5, PHP 7)

dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

Descrierea

resource dio_open ( string $filename , int $flags [, int $mode = 0 ] )

dio_open() opens a file and returns a new file descriptor for it.

Parametri

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, dio_open() will 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 flags and is ignored otherwise.

The actual permissions assigned to the created file will be affected by the process's umask setting as per usual.

Valorile întoarse

A file descriptor or FALSE on error.

Exemple

Example #1 Opening a file descriptor

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_close($fd);
?>

A se vedea ?i

  • dio_close() - Closes the file descriptor given by fd

dio_fcntl
dio_read
Func?ii IO directe


Reads bytes from a file descriptor

dio_open
dio_seek
Func?ii IO directe
PHP Manual

dio_read

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5, PHP 7)

dio_read — Reads bytes from a file descriptor

Descrierea

string dio_read ( resource $fd [, int $len = 1024 ] )

The function dio_read() reads and returns len bytes from file with descriptor fd.

Parametri

fd

The file descriptor returned by dio_open().

len

The number of bytes to read. If not specified, dio_read() reads 1K sized block.

Valorile întoarse

The bytes read from fd.

A se vedea ?i

  • dio_write() - Writes data to fd with optional truncation at length

dio_open
dio_seek
Func?ii IO directe


Seeks to pos on fd from whence

dio_read
dio_stat
Func?ii IO directe
PHP Manual

dio_seek

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5, PHP 7)

dio_seek — Seeks to pos on fd from whence

Descrierea

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.

Parametri

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.

Valorile întoarse

Exemple

Example #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
Func?ii IO directe


Gets stat information about the file descriptor fd

dio_seek
dio_tcsetattr
Func?ii IO directe
PHP Manual

dio_stat

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5, PHP 7)

dio_stat — Gets stat information about the file descriptor fd

Descrierea

array dio_stat ( resource $fd )

dio_stat() returns information about the given file descriptor.

Parametri

fd

The file descriptor returned by dio_open().

Valorile întoarse

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
Func?ii IO directe


Sets terminal attributes and baud rate for a serial port

dio_stat
dio_truncate
Func?ii IO directe
PHP Manual

dio_tcsetattr

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.5, PHP 7)

dio_tcsetattr — Sets terminal attributes and baud rate for a serial port

Descrierea

bool dio_tcsetattr ( resource $fd , array $options )

dio_tcsetattr() sets the terminal attributes and baud rate of the open fd.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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;
  }
}

?>

Note

Nota: Aceasta func?ie nu este implementata pe platformele Windows.

dio_stat
dio_truncate
Func?ii IO directe


Truncates file descriptor fd to offset bytes

dio_tcsetattr
dio_write
Func?ii IO directe
PHP Manual

dio_truncate

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5, PHP 7)

dio_truncate — Truncates file descriptor fd to offset bytes

Descrierea

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.

Parametri

fd

The file descriptor returned by dio_open().

offset

The offset in bytes.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota: Aceasta func?ie nu este implementata pe platformele Windows.

dio_tcsetattr
dio_write
Func?ii IO directe


Writes data to fd with optional truncation at length

dio_truncate
Directorii
Func?ii IO directe
PHP Manual

dio_write

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5, PHP 7)

dio_write — Writes data to fd with optional truncation at length

Descrierea

int dio_write ( resource $fd , string $data [, int $len = 0 ] )

dio_write() writes up to len bytes from data to file fd.

Parametri

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.

Valorile întoarse

Returns the number of bytes written to fd.

A se vedea ?i

  • dio_read() - Reads bytes from a file descriptor

dio_truncate
Directorii
Func?ii IO directe


Directorii

  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Directory — The Directory class
    • Directory::close — Close directory handle
    • Directory::read — Read entry from directory handle
    • Directory::rewind — Rewind directory handle
  • Func?ii de lucru cu directoare
    • chdir — Change directory
    • chroot — Change the root directory
    • closedir — Close directory handle
    • dir — Return an instance of the Directory class
    • getcwd — Gets the current working directory
    • opendir — Open directory handle
    • readdir — Read entry from directory handle
    • rewinddir — Rewind directory handle
    • scandir — List files and directories inside the specified path
dio_write
Instalarea / configurarea
Extensii referitoare la sistemul de fi?iere


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Directorii
Necesita?i
Directorii


Constante predefinite

DIRECTORY_SEPARATOR (string)
PATH_SEPARATOR (string)
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.
Tipurile resurselor
Directory
Directorii


The Directory class

(PHP 4, PHP 5, PHP 7)

Introducere

Instances of Directory are created by calling the dir() function, not by the new operator.

Sinopsisul clasei

Directory {
/* Proprieta?i */
public string $path ;
public resource $handle ;
/* Metode */
public void close ([ resource $dir_handle ] )
public string read ([ resource $dir_handle ] )
public void rewind ([ resource $dir_handle ] )
}

Proprieta?i

path

The directory that was opened.

handle

Can be used with other directory functions such as readdir(), rewinddir() and closedir().

Cuprins

  • Directory::close — Close directory handle
  • Directory::read — Read entry from directory handle
  • Directory::rewind — Rewind directory handle
Constante predefinite
Directory::close
Directorii


Close directory handle

Directory
Directory::read
Directory
PHP Manual

Directory::close

(PHP 4, PHP 5, PHP 7)

Directory::close — Close directory handle

Descrierea

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

(PHP 4, PHP 5, PHP 7)

Directory::read — Read entry from directory handle

Descrierea

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
Func?ii de lucru cu directoare
Directory
PHP Manual

Directory::rewind

(PHP 4, PHP 5, PHP 7)

Directory::rewind — Rewind directory handle

Descrierea

public void Directory::rewind ([ resource $dir_handle ] )

Same as rewinddir(), only dir_handle defaults to $this.

Directory::read
Func?ii de lucru cu directoare
Directory


Func?ii de lucru cu directoare

A se vedea ?i

Pentru func?ii asemanatoare, cum ar fi dirname(), is_dir(), mkdir() ?i rmdir(), vede?i sec?iunea Sistemul de fi?iere.

Cuprins

  • chdir — Change directory
  • chroot — Change the root directory
  • closedir — Close directory handle
  • dir — Return an instance of the Directory class
  • getcwd — Gets the current working directory
  • opendir — Open directory handle
  • readdir — Read entry from directory handle
  • rewinddir — Rewind directory handle
  • scandir — List files and directories inside the specified path
Directory::rewind
chdir
Directorii


Change directory

Func?ii de lucru cu directoare
chroot
Func?ii de lucru cu directoare
PHP Manual

chdir

(PHP 4, PHP 5, PHP 7)

chdir — Change directory

Descrierea

bool chdir ( string $directory )

Changes PHP's current directory to directory.

Parametri

directory

The new current directory

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws an error of level E_WARNING on failure.

Exemple

Example #1 chdir() example

<?php

// current directory
echo getcwd() . "\n";

chdir('public_html');

// current directory
echo getcwd() . "\n";

?>

Exemplul de mai sus va afi?a ceva similar cu:

/home/vincent
/home/vincent/public_html

Note

Nota: Când este activat modul securizat , PHP verifica daca directorul în care dori?i sa opera?i are acela?i UID (proprietar) ca ?i script-ul care se executa.

A se vedea ?i

  • getcwd() - Gets the current working directory

Func?ii de lucru cu directoare
chroot
Func?ii de lucru cu directoare


Change the root directory

chdir
closedir
Func?ii de lucru cu directoare
PHP Manual

chroot

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

chroot — Change the root directory

Descrierea

bool chroot ( string $directory )

Changes the root directory of the current process to directory, and changes the current working directory to "/".

This function is only available to GNU and BSD systems, and only when using the CLI, CGI or Embed SAPI. Also, this function requires root privileges.

Parametri

directory

The path to change the root directory to.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 chroot() example

<?php
chroot("/path/to/your/chroot/");
echo getcwd();
?>

Exemplul de mai sus va afi?a:

/

Note

Nota: Aceasta func?ie nu este implementata pe platformele Windows.

chdir
closedir
Func?ii de lucru cu directoare


Close directory handle

chroot
dir
Func?ii de lucru cu directoare
PHP Manual

closedir

(PHP 4, PHP 5, PHP 7)

closedir — Close directory handle

Descrierea

void closedir ([ resource $dir_handle ] )

Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().

Parametri

dir_handle

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

Exemple

Example #1 closedir() example

<?php
$dir = "/etc/php5/";

// Open a known directory, read directory into variable and then close
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        $directory = readdir($dh);
        closedir($dh);
    }
}
?>

chroot
dir
Func?ii de lucru cu directoare


Return an instance of the Directory class

closedir
getcwd
Func?ii de lucru cu directoare
PHP Manual

dir

(PHP 4, PHP 5, PHP 7)

dir — Return an instance of the Directory class

Descrierea

Directory dir ( string $directory [, resource $context ] )

A pseudo-object oriented mechanism for reading a directory. The given directory is opened.

Parametri

directory

Directory to open

context

Nota: Sus?inrea contextelor a fost adaugata începând cu PHP 5.0.0. Pentru o descriere a contextelor, referi?i-va la Streams.

Valorile întoarse

Returns an instance of Directory, or NULL with wrong parameters, or FALSE in case of another error.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Handle: Resource id #2
Path: /etc/php5
.
..
apache
cgi
cli

Note

Nota:

The order in which directory entries are returned by the read method is system-dependent.

closedir
getcwd
Func?ii de lucru cu directoare


Gets the current working directory

dir
opendir
Func?ii de lucru cu directoare
PHP Manual

getcwd

(PHP 4, PHP 5, PHP 7)

getcwd — Gets the current working directory

Descrierea

string getcwd ( void )

Gets the current working directory.

Valorile întoarse

Returns the current working directory on success, or FALSE on failure.

On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does. See chmod() for more information on modes and permissions.

Exemple

Example #1 getcwd() example

<?php

// current directory
echo getcwd() . "\n";

chdir('cvs');

// current directory
echo getcwd() . "\n";

?>

Exemplul de mai sus va afi?a ceva similar cu:

/home/didou
/home/didou/cvs

A se vedea ?i

  • chdir() - Change directory
  • chmod() - Changes file mode

dir
opendir
Func?ii de lucru cu directoare


Open directory handle

getcwd
readdir
Func?ii de lucru cu directoare
PHP Manual

opendir

(PHP 4, PHP 5, PHP 7)

opendir — Open directory handle

Descrierea

resource opendir ( string $path [, resource $context ] )

Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

Parametri

path

The directory path that is to be opened

context

For a description of the context parameter, refer to the streams section of the manual.

Valorile întoarse

Returns a directory handle resource on success, or FALSE on failure.

If path is not a valid directory or the directory can not be opened due to permission restrictions or filesystem errors, opendir() returns FALSE and generates a PHP error of level E_WARNING. You can suppress the error output of opendir() by prepending '@' to the front of the function name.

Istoricul schimbarilor

Versiune | Descriere
5.0.0 | path supports the ftp:// URL wrapper.
4.3.0 | path can also be any URL which supports directory listing, however only the file:// URL wrapper supports this in PHP 4

Exemple

Example #1 opendir() example

<?php
$dir = "/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
        }
        closedir($dh);
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir

A se vedea ?i

  • is_dir() - Tells whether the filename is a directory
  • readdir() - Read entry from directory handle
  • dir() - Return an instance of the Directory class

getcwd
readdir
Func?ii de lucru cu directoare


Read entry from directory handle

opendir
rewinddir
Func?ii de lucru cu directoare
PHP Manual

readdir

(PHP 4, PHP 5, PHP 7)

readdir — Read entry from directory handle

Descrierea

string readdir ([ resource $dir_handle ] )

Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.

Parametri

dir_handle

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

Valorile întoarse

Returns the entry name on success sau FALSE în cazul e?ecului.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Exemple

Example #1 List all entries in a directory

Please note the fashion in which readdir()'s return value is checked in the examples 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 (e.g. a directory named "0").

<?php

if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Entries:\n";

    /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
        echo "$entry\n";
    }

    /* This is the WRONG way to loop over the directory. */
    while ($entry = readdir($handle)) {
        echo "$entry\n";
    }

    closedir($handle);
}
?>

Example #2 List all entries in the current directory and strip out . and ..

<?php
if ($handle = opendir('.')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "$entry\n";
        }
    }
    closedir($handle);
}
?>

A se vedea ?i

  • is_dir() - Tells whether the filename is a directory
  • glob() - Find pathnames matching a pattern
  • opendir() - Open directory handle
  • scandir() - List files and directories inside the specified path

opendir
rewinddir
Func?ii de lucru cu directoare


Rewind directory handle

readdir
scandir
Func?ii de lucru cu directoare
PHP Manual

rewinddir

(PHP 4, PHP 5, PHP 7)

rewinddir — Rewind directory handle

Descrierea

void rewinddir ([ resource $dir_handle ] )

Resets the directory stream indicated by dir_handle to the beginning of the directory.

Parametri

dir_handle

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

readdir
scandir
Func?ii de lucru cu directoare


List files and directories inside the specified path

rewinddir
Fileinfo
Func?ii de lucru cu directoare
PHP Manual

scandir

(PHP 5, PHP 7)

scandir — List files and directories inside the specified path

Descrierea

array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )

Returns an array of files and directories from the directory.

Parametri

directory

The directory that will be scanned.

sorting_order

By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is set to SCANDIR_SORT_DESCENDING, then the sort order is alphabetical in descending order. If it is set to SCANDIR_SORT_NONE then the result is unsorted.

context

For a description of the context parameter, refer to the streams section of the manual.

Valorile întoarse

Returns an array of filenames on success, or FALSE on failure. If directory is not a directory, then boolean FALSE is returned, and an error of level E_WARNING is generated.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | sorting_order constants were added. Any nonzero value caused descending order in previous versions. So for all PHP versions, use 0 for ascending order, and 1 for descending order. An option for SCANDIR_SORT_NONE behavior did not exist prior to PHP 5.4.0.

Exemple

Example #1 A simple scandir() example

<?php
$dir    = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Example #2 PHP 4 alternatives to scandir()

<?php
$dir = "/tmp";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}

sort($files);

print_r($files);

rsort($files);

print_r($files);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Note

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

A se vedea ?i

  • opendir() - Open directory handle
  • readdir() - Read entry from directory handle
  • glob() - Find pathnames matching a pattern
  • is_dir() - Tells whether the filename is a directory
  • sort() - Sort an array

rewinddir
Fileinfo
Func?ii de lucru cu directoare


File Information

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Fileinfo
    • 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
  • finfo — The finfo class
    • finfo::buffer — Pseudonim pentru finfo_buffer()
    • finfo::__construct — Pseudonim pentru finfo_open
    • finfo::file — Pseudonim pentru finfo_file()
    • finfo::set_flags — Pseudonim pentru finfo_set_flags()
scandir
Introducere
Extensii referitoare la sistemul de fi?iere


Introducere

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
Instalarea / configurarea
Fileinfo


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Fileinfo


Necesita?i

Before PHP 5.3.0, the magic_open library is needed to build this extension.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie este activata implicit începând cu PHP 5.3.0. Anterior fileinfo a fost o extensie PECL, acuma însa nu mai este men?inuta acolo. Totu?i versiunile anterioare la 5.3+ pot utiliza » extensia PECL învechita.

Pentru a activa aceasta extensie, utilizatorii Windows terbuie sa includa în php.ini calea spre fi?ierul DLL php_fileinfo.dll inclus în pachet.

Biblioteca libmagic este furnizata cu PHP ?i include modificari speciale pentru PHP. Un petic pentru libmagic numit libmagic.patch este sus?inut ?i poate fi gasit în codurile-sursa ale extensiei fileinfo din PHP.

Istoricul reînnoirilor bibliotecii incluse libmagic
Versiune PHP | Versiune libmagic reînnoita | Note
5.3.2 | 5.03 |
5.3.0 | 5.02 |

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

There is one resource used in Fileinfo extension: a magic database descriptor returned by finfo_open().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
Func?ii Fileinfo
Fileinfo


Func?ii Fileinfo

Cuprins

  • 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
Constante predefinite
finfo_buffer
Fileinfo


Return information about a string buffer

Func?ii Fileinfo
finfo_close
Func?ii Fileinfo
PHP Manual

finfo_buffer

finfo::buffer

(PHP 5 >= 5.3.0, PHP 7, PECL fileinfo >= 0.1.0)

finfo_buffer -- finfo::buffer — Return information about a string buffer

Descrierea

Stil procedural

string finfo_buffer ( resource $finfo , string $string = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

Stil obiect-orientat

public 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.

Parametri

finfo

Fileinfo resource returned by finfo_open().

string

Content of a file to be checked.

options

One or disjunction of more Fileinfo constants.

context

Valorile întoarse

Returns a textual description of the string argument, or FALSE if an error occurred.

Exemple

Example #1 A finfo_buffer() example

<?php
$finfo = new finfo(FILEINFO_MIME);
echo $finfo->buffer($_POST["script"]) . "\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

application/x-sh; charset=us-ascii

A se vedea ?i

  • finfo_file() - Pseudonim pentru finfo_file()

Func?ii Fileinfo
finfo_close
Func?ii Fileinfo


Close fileinfo resource

finfo_buffer
finfo_file
Func?ii Fileinfo
PHP Manual

finfo_close

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_close — Close fileinfo resource

Descrierea

bool finfo_close ( resource $finfo )

This function closes the resource opened by finfo_open().

Parametri

finfo

Fileinfo resource returned by finfo_open().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

finfo_buffer
finfo_file
Func?ii Fileinfo


Return information about a file

finfo_close
finfo_open
Func?ii Fileinfo
PHP Manual

finfo_file

finfo::file

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_file -- finfo::file — Return information about a file

Descrierea

Stil procedural

string finfo_file ( resource $finfo , string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

Stil obiect-orientat

public string finfo::file ( string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

This function is used to get information about a file.

Parametri

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 Func?ii de flux.

Valorile întoarse

Returns a textual description of the contents of the file_name argument, or FALSE if an error occurred.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

text/html
image/gif
application/vnd.ms-excel

A se vedea ?i

  • finfo_buffer() - Pseudonim pentru finfo_buffer()

finfo_close
finfo_open
Func?ii Fileinfo


Create a new fileinfo resource

finfo_file
finfo_set_flags
Func?ii Fileinfo
PHP Manual

finfo_open

finfo::__construct

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_open -- finfo::__construct — Create a new fileinfo resource

Descrierea

Stil procedural

resource finfo_open ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )

Stil obiect-orientat (constructor):

public finfo::__construct ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )

This function opens a magic database and returns its resource.

Parametri

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 the environment variable isn't set, then PHP's bundled magic database will be used.

Passing NULL or an empty string will be equivalent to the default value.

Valorile întoarse

(Procedural style only) Returns a magic database resource on success sau FALSE în cazul e?ecului.

Note

Avertizare

The expected magic database format changed in PHP 5.3.11 and 5.4.1. Due to this, the internal magic database was upgraded. This mostly effects code where an external magic database is used: reading an older magic file will now fail. Also, some textual representations of the mime types has changed, for instance for PHP would be "PHP script, ASCII text" instead of "PHP script text" returned.

Nota:

Generally, using the bundled magic database (by leaving magic_file and the MAGIC environment variables unset) is the best course of action unless you specifically need a custom magic database.

Exemple

Example #1 Stil obiect-orientat

<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);

?>

Example #2 Stil procedural

<?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);
?>

Exemplul de mai sus va afi?a:

text/plain; charset=us-ascii

A se vedea ?i

  • finfo_close() - Close fileinfo resource

finfo_file
finfo_set_flags
Func?ii Fileinfo


Set libmagic configuration options

finfo_open
mime_content_type
Func?ii Fileinfo
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

Descrierea

Stil procedural

bool finfo_set_flags ( resource $finfo , int $options )

Stil obiect-orientat

public 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.

Parametri

finfo

Fileinfo resource returned by finfo_open().

options

One or disjunction of more Fileinfo constants.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

finfo_open
mime_content_type
Func?ii Fileinfo


Detect MIME Content-type for a file

finfo_set_flags
finfo
Func?ii Fileinfo
PHP Manual

mime_content_type

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

mime_content_type — Detect MIME Content-type for a file

Descrierea

string mime_content_type ( string $filename )

Returns the MIME content type for a file as determined by using information from the magic.mime file.

Parametri

filename

Path to the tested file.

Valorile întoarse

Returns the content type in MIME format, like text/plain or application/octet-stream.

Exemple

Example #1 mime_content_type() Example

<?php
echo mime_content_type('php.gif') . "\n";
echo mime_content_type('test.php');
?>

Exemplul de mai sus va afi?a:

image/gif
text/plain

A se vedea ?i

  • finfo_file() - Pseudonim pentru finfo_file()
  • finfo_buffer() - Pseudonim pentru finfo_buffer()

finfo_set_flags
finfo
Func?ii Fileinfo


The finfo class

(PHP 5 >= 5.3.0, PHP 7, PECL fileinfo >= 0.1.0)

Introducere

This class provides an object oriented interface into the fileinfo functions.

Sinopsisul clasei

finfo {
public __construct ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )
public string buffer ( string $string = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )
public string file ( string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )
public bool set_flags ( int $options )
}

Cuprins

  • finfo::buffer — Pseudonim pentru finfo_buffer()
  • finfo::__construct — Pseudonim pentru finfo_open
  • finfo::file — Pseudonim pentru finfo_file()
  • finfo::set_flags — Pseudonim pentru finfo_set_flags()
mime_content_type
finfo::buffer
Fileinfo


Pseudonim pentru finfo_buffer()

finfo
finfo::__construct
finfo
PHP Manual

finfo::buffer

(PHP 5 >= 5.3.0, PHP 7, PECL fileinfo >= 0.1.0)

finfo::buffer — Pseudonim pentru finfo_buffer()

Descrierea

public string finfo::buffer ( string $string = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

Aceasta func?ie este pseudonim pentru: finfo_buffer()

finfo
finfo::__construct
finfo


Pseudonim pentru finfo_open

finfo::buffer
finfo::file
finfo
PHP Manual

finfo::__construct

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo::__construct — Pseudonim pentru finfo_open()

Descrierea

public finfo::__construct ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )

Aceasta func?ie este pseudonim pentru: finfo_open()

finfo::buffer
finfo::file
finfo


Pseudonim pentru finfo_file()

finfo::__construct
finfo::set_flags
finfo
PHP Manual

finfo::file

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo::file — Pseudonim pentru finfo_file()

Descrierea

public string finfo::file ( string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

Aceasta func?ie este pseudonim pentru: finfo_file()

finfo::__construct
finfo::set_flags
finfo


Pseudonim pentru finfo_set_flags()

finfo::file
Filesystem
finfo
PHP Manual

finfo::set_flags

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo::set_flags — Pseudonim pentru finfo_set_flags()

Descrierea

public bool finfo::set_flags ( int $options )

Aceasta func?ie este pseudonim pentru: finfo_set_flags()

finfo::file
Filesystem
finfo


Filesystem

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Filesystem Func?ii
    • basename — Returns trailing name component of path
    • chgrp — Changes file group
    • chmod — Changes file mode
    • chown — Changes file owner
    • clearstatcache — Clears file status cache
    • copy — Copies file
    • delete — See unlink or unset
    • dirname — Returns a parent directory's path
    • disk_free_space — Returns available space on filesystem or disk partition
    • disk_total_space — Returns the total size of a filesystem or disk partition
    • diskfreespace — Pseudonim pentru disk_free_space
    • fclose — Closes an open file pointer
    • feof — Tests for end-of-file on a file pointer
    • fflush — Flushes the output to a file
    • fgetc — Gets character from file pointer
    • fgetcsv — Gets line from file pointer and parse for CSV fields
    • fgets — Gets line from file pointer
    • fgetss — Gets line from file pointer and strip HTML tags
    • file_exists — Checks whether a file or directory exists
    • file_get_contents — Reads entire file into a string
    • file_put_contents — Write a string to a file
    • file — Reads entire file into an array
    • fileatime — Gets last access time of file
    • filectime — Gets inode change time of file
    • filegroup — Gets file group
    • fileinode — Gets file inode
    • filemtime — Gets file modification time
    • fileowner — Gets file owner
    • fileperms — Gets file permissions
    • filesize — Gets file size
    • filetype — Gets file type
    • flock — Portable advisory file locking
    • fnmatch — Match filename against a pattern
    • fopen — Opens file or URL
    • fpassthru — Output all remaining data on a file pointer
    • fputcsv — Format line as CSV and write to file pointer
    • fputs — Pseudonim pentru fwrite
    • fread — Binary-safe file read
    • fscanf — Parses input from a file according to a format
    • fseek — Seeks on a file pointer
    • fstat — Gets information about a file using an open file pointer
    • ftell — Returns the current position of the file read/write pointer
    • ftruncate — Truncates a file to a given length
    • fwrite — Binary-safe file write
    • glob — Find pathnames matching a pattern
    • is_dir — Tells whether the filename is a directory
    • is_executable — Tells whether the filename is executable
    • is_file — Tells whether the filename is a regular file
    • is_link — Tells whether the filename is a symbolic link
    • is_readable — Tells whether a file exists and is readable
    • is_uploaded_file — Tells whether the file was uploaded via HTTP POST
    • is_writable — Tells whether the filename is writable
    • is_writeable — Pseudonim pentru is_writable
    • lchgrp — Changes group ownership of symlink
    • lchown — Changes user ownership of symlink
    • link — Create a hard link
    • linkinfo — Gets information about a link
    • lstat — Gives information about a file or symbolic link
    • mkdir — Makes directory
    • move_uploaded_file — Moves an uploaded file to a new location
    • parse_ini_file — Parse a configuration file
    • parse_ini_string — Parse a configuration string
    • pathinfo — Returns information about a file path
    • pclose — Closes process file pointer
    • popen — Opens process file pointer
    • readfile — Outputs a file
    • readlink — Returns the target of a symbolic link
    • 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 — Removes directory
    • set_file_buffer — Pseudonim pentru stream_set_write_buffer
    • stat — Gives information about a file
    • symlink — Creates a symbolic link
    • tempnam — Create file with unique file name
    • tmpfile — Creates a temporary file
    • touch — Sets access and modification time of file
    • umask — Changes the current umask
    • unlink — Deletes a file
finfo::set_flags
Introducere
Extensii referitoare la sistemul de fi?iere


Introducere

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
Instalarea / configurarea
Filesystem


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Filesystem


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Filesystem and Streams Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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_SYSTEM | 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.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Nota:

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.

Avertizare

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 Func?ii GD ?i Image 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.

Nota:

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.

Nota: 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.

Nota: This configuration option was introduced in PHP 4.3.0

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

The file system uses streams as their resource type. Streams are documented in its own reference chapter, Streams.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

SEEK_SET (integer)
SEEK_CUR (integer)
SEEK_END (integer)
LOCK_SH (integer)
LOCK_EX (integer)
LOCK_UN (integer)
LOCK_NB (integer)
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)
Since PHP 5.2.0.
FILE_USE_INCLUDE_PATH (integer)
Search for filename in include_path (since PHP 5).
FILE_NO_DEFAULT_CONTEXT (integer)
FILE_APPEND (integer)
Append content to existing file.
FILE_IGNORE_NEW_LINES (integer)
Strip EOL characters (since PHP 5).
FILE_SKIP_EMPTY_LINES (integer)
Skip empty lines (since PHP 5).
FILE_BINARY (integer)

Binary mode (since PHP 5.2.7).

Nota:

This constant has no effect, and is only available for forward compatibility.

FILE_TEXT (integer)

Text mode (since PHP 5.2.7).

Nota:

This constant has no effect, and is only available for forward compatibility.

INI_SCANNER_NORMAL (integer)
Normal INI scanner mode (since PHP 5.3).
INI_SCANNER_RAW (integer)
Raw INI scanner mode (since PHP 5.3).
INI_SCANNER_TYPED (integer)
Typed INI scanner mode (since PHP 5.6.1).
FNM_NOESCAPE (integer)
Disable backslash escaping.
FNM_PATHNAME (integer)
Slash in string only matches slash in the given pattern.
FNM_PERIOD (integer)
Leading period in string must be exactly matched by period in the given pattern.
FNM_CASEFOLD (integer)
Caseless match. Part of the GNU extension.
Tipurile resurselor
Filesystem Func?ii
Filesystem


Filesystem Func?ii

A se vedea ?i

For related functions, see also the Directory and Program Execution sections.

For a list and explanation of the various URL wrappers that can be used as remote files, see also Supported Protocols and Wrappers.

Cuprins

  • basename — Returns trailing name component of path
  • chgrp — Changes file group
  • chmod — Changes file mode
  • chown — Changes file owner
  • clearstatcache — Clears file status cache
  • copy — Copies file
  • delete — See unlink or unset
  • dirname — Returns a parent directory's path
  • disk_free_space — Returns available space on filesystem or disk partition
  • disk_total_space — Returns the total size of a filesystem or disk partition
  • diskfreespace — Pseudonim pentru disk_free_space
  • fclose — Closes an open file pointer
  • feof — Tests for end-of-file on a file pointer
  • fflush — Flushes the output to a file
  • fgetc — Gets character from file pointer
  • fgetcsv — Gets line from file pointer and parse for CSV fields
  • fgets — Gets line from file pointer
  • fgetss — Gets line from file pointer and strip HTML tags
  • file_exists — Checks whether a file or directory exists
  • file_get_contents — Reads entire file into a string
  • file_put_contents — Write a string to a file
  • file — Reads entire file into an array
  • fileatime — Gets last access time of file
  • filectime — Gets inode change time of file
  • filegroup — Gets file group
  • fileinode — Gets file inode
  • filemtime — Gets file modification time
  • fileowner — Gets file owner
  • fileperms — Gets file permissions
  • filesize — Gets file size
  • filetype — Gets file type
  • flock — Portable advisory file locking
  • fnmatch — Match filename against a pattern
  • fopen — Opens file or URL
  • fpassthru — Output all remaining data on a file pointer
  • fputcsv — Format line as CSV and write to file pointer
  • fputs — Pseudonim pentru fwrite
  • fread — Binary-safe file read
  • fscanf — Parses input from a file according to a format
  • fseek — Seeks on a file pointer
  • fstat — Gets information about a file using an open file pointer
  • ftell — Returns the current position of the file read/write pointer
  • ftruncate — Truncates a file to a given length
  • fwrite — Binary-safe file write
  • glob — Find pathnames matching a pattern
  • is_dir — Tells whether the filename is a directory
  • is_executable — Tells whether the filename is executable
  • is_file — Tells whether the filename is a regular file
  • is_link — Tells whether the filename is a symbolic link
  • is_readable — Tells whether a file exists and is readable
  • is_uploaded_file — Tells whether the file was uploaded via HTTP POST
  • is_writable — Tells whether the filename is writable
  • is_writeable — Pseudonim pentru is_writable
  • lchgrp — Changes group ownership of symlink
  • lchown — Changes user ownership of symlink
  • link — Create a hard link
  • linkinfo — Gets information about a link
  • lstat — Gives information about a file or symbolic link
  • mkdir — Makes directory
  • move_uploaded_file — Moves an uploaded file to a new location
  • parse_ini_file — Parse a configuration file
  • parse_ini_string — Parse a configuration string
  • pathinfo — Returns information about a file path
  • pclose — Closes process file pointer
  • popen — Opens process file pointer
  • readfile — Outputs a file
  • readlink — Returns the target of a symbolic link
  • 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 — Removes directory
  • set_file_buffer — Pseudonim pentru stream_set_write_buffer
  • stat — Gives information about a file
  • symlink — Creates a symbolic link
  • tempnam — Create file with unique file name
  • tmpfile — Creates a temporary file
  • touch — Sets access and modification time of file
  • umask — Changes the current umask
  • unlink — Deletes a file
Constante predefinite
basename
Filesystem


Returns trailing name component of path

Filesystem Func?ii
chgrp
Filesystem Func?ii
PHP Manual

basename

(PHP 4, PHP 5, PHP 7)

basename — Returns trailing name component of path

Descrierea

string basename ( string $path [, string $suffix ] )

Given a string containing the path to a file or directory, this function will return the trailing name component.

Nota:

basename() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "..".

Precautie

basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function.

Parametri

path

A path.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

suffix

If the name component ends in suffix this will also be cut off.

Valorile întoarse

Returns the base name of the given path.

Exemple

Example #1 basename() example

<?php
echo "1) ".basename("/etc/sudoers.d", ".d").PHP_EOL;
echo "2) ".basename("/etc/sudoers.d").PHP_EOL;
echo "3) ".basename("/etc/passwd").PHP_EOL;
echo "4) ".basename("/etc/").PHP_EOL;
echo "5) ".basename(".").PHP_EOL;
echo "6) ".basename("/");
?>

Exemplul de mai sus va afi?a:

1) sudoers
2) sudoers.d
3) passwd
4) etc
5) .
6)

A se vedea ?i

  • dirname() - Returns a parent directory's path
  • pathinfo() - Returns information about a file path

Filesystem Func?ii
chgrp
Filesystem Func?ii


Changes file group

basename
chmod
Filesystem Func?ii
PHP Manual

chgrp

(PHP 4, PHP 5, PHP 7)

chgrp — Changes file group

Descrierea

bool chgrp ( string $filename , mixed $group )

Attempts to change the group of the file filename to group.

Only the superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member.

Parametri

filename

Path to the file.

group

A group name or number.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Changing a file's group

<?php
$filename = 'shared_file.txt';
$format = "%s's Group ID @ %s: %d\n";
printf($format, $filename, date('r'), filegroup($filename));
chgrp($filename, 8);
clearstatcache(); // do not cache filegroup() results
printf($format, $filename, date('r'), filegroup($filename));
?>

Note

Nota: Aceasta func?ie nu va lucra cu fi?iere la distan?a, deoarece fi?ierul care trebuie sa fie examinat trebuie sa fie accesibil prin intermediul sistemului de fi?iere al serverului.

Nota: Când este activat modul securizat, PHP verifica daca fi?ierele ?i directoarele cu care se va opera au acela?i UID (proprietar) ca ?i script-ul care se executa.

A se vedea ?i

  • chown() - Changes file owner
  • chmod() - Changes file mode

basename
chmod
Filesystem Func?ii


Changes file mode

chgrp
chown
Filesystem Func?ii
PHP Manual

chmod

(PHP 4, PHP 5, PHP 7)

chmod — Changes file mode

Descrierea

bool chmod ( string $filename , int $mode )

Attempts to change the mode of the specified file to that given in mode.

Parametri

filename

Path to the file.

mode

Note that mode is not automatically assumed to be an octal value, so to ensure the expected operation, you need to prefix mode with a zero (0). Strings such as "g+w" will not work properly.

<?php
chmod("/somedir/somefile", 755);   // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755);  // octal; correct value of mode
?>

The mode parameter consists of three octal number components specifying access restrictions for the owner, the user group in which the owner is in, and to everybody else in this order. One component can be computed by adding up the needed permissions for that target user base. Number 1 means that you grant execute rights, number 2 means that you make the file writeable, number 4 means that you make the file readable. Add up these numbers to specify needed rights. You can also read more about modes on Unix systems with 'man 1 chmod' and 'man 2 chmod'.

<?php
// Read and write for owner, nothing for everybody else
chmod("/somedir/somefile", 0600);

// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);

// Everything for owner, read and execute for others
chmod("/somedir/somefile", 0755);

// Everything for owner, read and execute for owner's group
chmod("/somedir/somefile", 0750);
?>

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

The current user is the user under which PHP runs. It is probably not the same user you use for normal shell or FTP access. The mode can be changed only by user who owns the file on most systems.

Nota: Aceasta func?ie nu va lucra cu fi?iere la distan?a, deoarece fi?ierul care trebuie sa fie examinat trebuie sa fie accesibil prin intermediul sistemului de fi?iere al serverului.

Nota:

When modul securizat is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits.

A se vedea ?i

  • chown() - Changes file owner
  • chgrp() - Changes file group
  • fileperms() - Gets file permissions
  • stat() - Gives information about a file

chgrp
chown
Filesystem Func?ii


Changes file owner

chmod
clearstatcache
Filesystem Func?ii
PHP Manual

chown

(PHP 4, PHP 5, PHP 7)

chown — Changes file owner

Descrierea

bool chown ( string $filename , mixed $user )

Attempts to change the owner of the file filename to user user. Only the superuser may change the owner of a file.

Parametri

filename

Path to the file.

user

A user name or number.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Simple chown() usage

<?php

// File name and username to use
$file_name= "foo.php";
$path = "/home/sites/php.net/public_html/sandbox/" . $file_name ;
$user_name = "root";

// Set the user
chown($path, $user_name);

// Check the result
$stat = stat($path);
print_r(posix_getpwuid($stat['uid']));

?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [name] => root
    [passwd] => x
    [uid] => 0
    [gid] => 0
    [gecos] => root
    [dir] => /root
    [shell] => /bin/bash
)

Note

Nota: Aceasta func?ie nu va lucra cu fi?iere la distan?a, deoarece fi?ierul care trebuie sa fie examinat trebuie sa fie accesibil prin intermediul sistemului de fi?iere al serverului.

Nota: Când este activat modul securizat, PHP verifica daca fi?ierele ?i directoarele cu care se va opera au acela?i UID (proprietar) ca ?i script-ul care se executa.

A se vedea ?i

  • chmod() - Changes file mode
  • chgrp() - Changes file group

chmod
clearstatcache
Filesystem Func?ii


Clears file status cache

chown
copy
Filesystem Func?ii
PHP Manual

clearstatcache

(PHP 4, PHP 5, PHP 7)

clearstatcache — Clears file status cache

Descrierea

void clearstatcache ([ bool $clear_realpath_cache = false [, string $filename ]] )

When you use stat(), lstat(), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script's operation, you may elect to clear the status cache. In these cases, you can use the clearstatcache() function to clear the information that PHP caches about a file.

You should also note that PHP doesn't cache information about non-existent files. So, if you call file_exists() on a file that doesn't exist, it will return FALSE until you create the file. If you create the file, it will return TRUE even if you then delete the file. However unlink() clears the cache automatically.

Nota:

This function caches information about specific filenames, so you only need to call clearstatcache() if you are performing multiple operations on the same filename and require the information about that particular file to not be cached.

Affected functions include stat(),
lstat(),
file_exists(),
is_writable(),
is_readable(),
is_executable(),
is_file(),
is_dir(),
is_link(),
filectime(),
fileatime(),
filemtime(),
fileinode(),
filegroup(),
fileowner(),
filesize(),
filetype(), and
fileperms().

Parametri

clear_realpath_cache

Whether to clear the realpath cache or not.

filename

Clear the realpath and the stat cache for a specific filename only; only used if clear_realpath_cache is TRUE.

Valorile întoarse

Nu este întoarsa nici o valoare.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Added optional clear_realpath_cache and filename parameters.

Exemple

Example #1 clearstatcache() example

<?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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
Filesystem Func?ii


Copies file

clearstatcache
delete
Filesystem Func?ii
PHP Manual

copy

(PHP 4, PHP 5, PHP 7)

copy — Copies file

Descrierea

bool copy ( string $source , string $dest [, resource $context ] )

Makes a copy of the file source to dest.

If you wish to move a file, use the rename() function.

Parametri

source

Path to the source file.

dest

The destination path. If dest is a URL, the copy operation may fail if the wrapper does not support overwriting of existing files.

Avertizare

If the destination file already exists, it will be overwritten.

context

A valid context resource created with stream_context_create().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.4 | Changed the context parameter to actually have an effect. Previously, any context was ignored.
5.3.0 | Added context support.
4.3.0 | Both source and dest may now be URLs if the "fopen wrappers" have been enabled. See fopen() for more details.

Exemple

Example #1 copy() example

<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';

if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n";
}
?>

A se vedea ?i

  • move_uploaded_file() - Moves an uploaded file to a new location
  • rename() - Renames a file or directory
  • The section of the manual about handling file uploads

clearstatcache
delete
Filesystem Func?ii


See unlink or unset

copy
dirname
Filesystem Func?ii
PHP Manual

delete

delete — See unlink() or unset()

Descrierea

This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place.

A se vedea ?i

  • unlink() - Deletes a file
  • unset() - Elimina o variabila data

copy
dirname
Filesystem Func?ii


Returns a parent directory's path

delete
disk_free_space
Filesystem Func?ii
PHP Manual

dirname

(PHP 4, PHP 5, PHP 7)

dirname — Returns a parent directory's path

Descrierea

string dirname ( string $path [, int $levels = 1 ] )

Given a string containing the path of a file or directory, this function will return the parent directory's path that is levels up from the current directory.

Nota:

dirname() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "..".

Precautie

dirname() is locale aware, so for it to see the correct directory name with multibyte character paths, the matching locale must be set using the setlocale() function.

Parametri

path

A path.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

levels

The number of parent directories to go up.

This must be an integer greater than 0.

Valorile întoarse

Returns the path of a parent directory. If there are no slashes in path, a dot ('.') is returned, indicating the current directory. Otherwise, the returned string is path with any trailing /component removed.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | Added the optional levels parameter.
5.0.0 | dirname() is now binary safe

Exemple

Example #1 dirname() example

<?php
echo dirname("/etc/passwd") . PHP_EOL;
echo dirname("/etc/") . PHP_EOL;
echo dirname(".") . PHP_EOL;
echo dirname("C:\\") . PHP_EOL;
echo dirname("/usr/local/lib", 2);

Exemplul de mai sus va afi?a ceva similar cu:

/etc
/ (or \ on Windows)
.
C:\
/usr

A se vedea ?i

  • basename() - Returns trailing name component of path
  • pathinfo() - Returns information about a file path
  • realpath() - Returns canonicalized absolute pathname

delete
disk_free_space
Filesystem Func?ii


Returns available space on filesystem or disk partition

dirname
disk_total_space
Filesystem Func?ii
PHP Manual

disk_free_space

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

disk_free_space — Returns available space on filesystem or disk partition

Descrierea

float disk_free_space ( string $directory )

Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.

Parametri

directory

A directory of the filesystem or disk partition.

Nota:

Given a file name instead of a directory, the behaviour of the function is unspecified and may differ between operating systems and PHP versions.

Valorile întoarse

Returns the number of available bytes as a float sau FALSE în cazul e?ecului.

Exemple

Example #1 disk_free_space() example

<?php
// $df contains the number of bytes available on "/"
$df = disk_free_space("/");

// On Windows:
$df_c = disk_free_space("C:");
$df_d = disk_free_space("D:");
?>

Note

Nota: Aceasta func?ie nu va lucra cu fi?iere la distan?a, deoarece fi?ierul care trebuie sa fie examinat trebuie sa fie accesibil prin intermediul sistemului de fi?iere al serverului.

A se vedea ?i

  • disk_total_space() - Returns the total size of a filesystem or disk partition

dirname
disk_total_space
Filesystem Func?ii


Returns the total size of a filesystem or disk partition

disk_free_space
diskfreespace
Filesystem Func?ii
PHP Manual

disk_total_space

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

disk_total_space — Returns the total size of a filesystem or disk partition

Descrierea

float disk_total_space ( string $directory )

Given a string containing a directory, this function will return the total number of bytes on the corresponding filesystem or disk partition.

Parametri

directory

A directory of the filesystem or disk partition.

Valorile întoarse

Returns the total number of bytes as a float sau FALSE în cazul e?ecului.

Exemple

Example #1 disk_total_space() example

<?php
// $ds contains the total number of bytes available on "/"
$ds = disk_total_space("/");

// On Windows:
$ds = disk_total_space("C:");
$ds = disk_total_space("D:");
?>

Note

Nota: Aceasta func?ie nu va lucra cu fi?iere la distan?a, deoarece fi?ierul care trebuie sa fie examinat trebuie sa fie accesibil prin intermediul sistemului de fi?iere al serverului.

A se vedea ?i

  • disk_free_space() - Returns available space on filesystem or disk partition

disk_free_space
diskfreespace
Filesystem Func?ii


Pseudonim pentru disk_free_space

disk_total_space
fclose
Filesystem Func?ii
PHP Manual

diskfreespace

(PHP 4, PHP 5, PHP 7)

diskfreespace — Pseudonim pentru disk_free_space()

Descrierea

Aceasta func?ie este pseudonim pentru: disk_free_space().

disk_total_space
fclose
Filesystem Func?ii


Closes an open file pointer

diskfreespace
feof
Filesystem Func?ii
PHP Manual

fclose

(PHP 4, PHP 5, PHP 7)

fclose — Closes an open file pointer

Descrierea

bool fclose ( resource $handle )

The file pointed to by handle is closed.

Parametri

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 A simple fclose() example

<?php

$handle = fopen('somefile.txt', 'r');

fclose($handle);

?>

A se vedea ?i

  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection

diskfreespace
feof
Filesystem Func?ii


Tests for end-of-file on a file pointer

fclose
fflush
Filesystem Func?ii
PHP Manual

feof

(PHP 4, PHP 5, PHP 7)

feof — Tests for end-of-file on a file pointer

Descrierea

bool feof ( resource $handle )

Tests for end-of-file on a file pointer.

Parametri

handle

Indicatorul fi?ierului trebuie sa fie valid ?i trebuie sa indice la un fi?ier deschis cu succes cu ajutorul fopen() sau fsockopen() (?i sa nu fie închis cu fclose()).

Valorile întoarse

Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.

Note

Avertizare

If a connection opened by fsockopen() wasn't closed by the server, feof() will hang. To workaround this, see below example:

Example #1 Handling timeouts with feof()

<?php
function safe_feof($fp, &$start = NULL) {
 $start = microtime(true);

 return feof($fp);
}

/* Assuming $fp is previously opened by fsockopen() */

$start = NULL;
$timeout = ini_get('default_socket_timeout');

while(!safe_feof($fp, $start) && (microtime(true) - $start) < $timeout)
{
 /* Handle */
}
?>

Avertizare

If the passed file pointer is not valid you may get an infinite loop, because feof() fails to return TRUE.

Example #2 feof() example with an invalid file pointer

<?php
// if file can not be read or doesn't exist fopen function returns FALSE
$file = @fopen("no_such_file", "r");

// FALSE from fopen will issue warning and result in infinite loop here
while (!feof($file)) {
}

fclose($file);
?>

fclose
fflush
Filesystem Func?ii


Flushes the output to a file

feof
fgetc
Filesystem Func?ii
PHP Manual

fflush

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

fflush — Flushes the output to a file

Descrierea

bool fflush ( resource $handle )

This function forces a write of all buffered output to the resource pointed to by the file handle.

Parametri

handle

Indicatorul fi?ierului trebuie sa fie valid ?i trebuie sa indice la un fi?ier deschis cu succes cu ajutorul fopen() sau fsockopen() (?i sa nu fie închis cu fclose()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 File write example using fflush()

<?php
$filename = 'bar.txt';

$file = fopen($filename, 'r+');
rewind($file);
fwrite($file, 'Foo');
fflush($file);
ftruncate($file, ftell($file));
fclose($file);
?>

A se vedea ?i

  • clearstatcache() - Clears file status cache
  • fwrite() - Binary-safe file write

feof
fgetc
Filesystem Func?ii


Gets character from file pointer

fflush
fgetcsv
Filesystem Func?ii
PHP Manual

fgetc

(PHP 4, PHP 5, PHP 7)

fgetc — Gets character from file pointer

Descrierea

string fgetc ( resource $handle )

Gets a character from the given file pointer.

Parametri

handle

Indicatorul fi?ierului trebuie sa fie valid ?i trebuie sa indice la un fi?ier deschis cu succes cu ajutorul fopen() sau fsockopen() (?i sa nu fie închis cu fclose()).

Valorile întoarse

Returns a string containing a single character read from the file pointed to by handle. Returns FALSE on EOF.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Exemple

Example #1 A fgetc() example

<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
    echo 'Could not open file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
    echo "$char\n";
}
?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • fread() - Binary-safe file read
  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fsockopen() - Open Internet or Unix domain socket connection
  • fgets() - Gets line from file pointer

fflush
fgetcsv
Filesystem Func?ii


Gets line from file pointer and parse for CSV fields

fgetc
fgets
Filesystem Func?ii
PHP Manual

fgetcsv

(PHP 4, PHP 5, PHP 7)

fgetcsv — Gets line from file pointer and parse for CSV fields

Descrierea

array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\" ]]]] )

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.

Parametri

handle

A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().

length

Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). Otherwise the line is split in chunks of length characters, unless the split would occur inside an enclosure.

Omitting this parameter (or setting it to 0 in PHP 5.1.0 and later) the maximum line length is not limited, which is slightly slower.

delimiter

The optional delimiter parameter sets the field delimiter (one character only).

enclosure

The optional enclosure parameter sets the field enclosure character (one character only).

escape

The optional escape parameter sets the escape character (one character only).

Valorile întoarse

Returns an indexed array containing the fields read.

Nota:

A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.

Nota: Daca PHP nu recunoa?te corect termina?iile liniilor atunci când cite?te fi?iere pe, sau create pe un computer Macintosh, atunci activarea op?iunii de configurare la rulare auto_detect_line_endings ar trebui sa ajute la solu?ionarea problemei.

fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | The escape parameter was added
5.1.0 | The length is now optional. Default is 0, meaning no length limit.
4.3.5 | fgetcsv() is now binary safe

Exemple

Example #1 Read and print the entire contents of a CSV file

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>

Note

Nota:

Locale setting is taken into account by this function. If LANG is e.g. en_US.UTF-8, files in one-byte encoding are read wrong by this function.

A se vedea ?i

  • str_getcsv() - Parse a CSV string into an array
  • explode() - Split a string by string
  • file() - Reads entire file into an array
  • pack() - Pack data into binary string
  • fputcsv() - Format line as CSV and write to file pointer

fgetc
fgets
Filesystem Func?ii


Gets line from file pointer

fgetcsv
fgetss
Filesystem Func?ii
PHP Manual

fgets

(PHP 4, PHP 5, PHP 7)

fgets — Gets line from file pointer

Descrierea

string fgets ( resource $handle [, int $length ] )

Gets a line from file pointer.

Parametri

handle

Indicatorul fi?ierului trebuie sa fie valid ?i trebuie sa indice la un fi?ier deschis cu succes cu ajutorul fopen() sau fsockopen() (?i sa nu fie închis cu fclose()).

length

Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.

Nota:

Until PHP 4.3.0, omitting it would assume 1024 as the line length. If the majority of the lines in the file are all larger than 8KB, it is more resource efficient for your script to specify the maximum line length.

Valorile întoarse

Returns a string of up to length - 1 bytes read from the file pointed to by handle. If there is no more data to read in the file pointer, then FALSE is returned.

If an error occurs, FALSE is returned.

Istoricul schimbarilor

Versiune | Descriere
4.3.0 | fgets() is now binary safe

Exemple

Example #1 Reading a file line by line

<?php
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
?>

Note

Nota: Daca PHP nu recunoa?te corect termina?iile liniilor atunci când cite?te fi?iere pe, sau create pe un computer Macintosh, atunci activarea op?iunii de configurare la rulare auto_detect_line_endings ar trebui sa ajute la solu?ionarea problemei.

Nota:

People used to the 'C' semantics of fgets() should note the difference in how EOF is returned.

A se vedea ?i

  • fgetss() - Gets line from file pointer and strip HTML tags
  • fread() - Binary-safe file read
  • fgetc() - Gets character from file pointer
  • stream_get_line() - Gets line from stream resource up to a given delimiter
  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fsockopen() - Open Internet or Unix domain socket connection
  • stream_set_timeout() - Set timeout period on a stream

fgetcsv
fgetss
Filesystem Func?ii


Gets line from file pointer and strip HTML tags

fgets
file_exists
Filesystem Func?ii
PHP Manual

fgetss

(PHP 4, PHP 5, PHP 7)

fgetss — Gets line from file pointer and strip HTML tags

Descrierea

string fgetss ( resource $handle [, int $length [, string $allowable_tags ]] )

Identical to fgets(), except that fgetss() attempts to strip any NUL bytes, HTML and PHP tags from the text it reads.

Parametri

handle

Indicatorul fi?ierului trebuie sa fie valid ?i trebuie sa indice la un fi?ier deschis cu succes cu ajutorul fopen() sau fsockopen() (?i sa nu fie închis cu fclose()).

length

Length of the data to be retrieved.

allowable_tags

You can use the optional third parameter to specify tags which should not be stripped. See strip_tags() for details regarding allowable_tags.

Valorile întoarse

Returns a string of up to length - 1 bytes read from the file pointed to by handle, with all HTML and PHP code stripped.

If an error occurs, returns FALSE.

Example #1 Reading a PHP file line-by-line

<?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);

$handle = @fopen("sample.php", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgetss($handle, 4096);
        echo $buffer;
    }
    fclose($handle);
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

 Welcome! Today is the  of .

Text outside of the HTML block.

Note

Nota: Daca PHP nu recunoa?te corect termina?iile liniilor atunci când cite?te fi?iere pe, sau create pe un computer Macintosh, atunci activarea op?iunii de configurare la rulare auto_detect_line_endings ar trebui sa ajute la solu?ionarea problemei.

A se vedea ?i

  • fgets() - Gets line from file pointer
  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fsockopen() - Open Internet or Unix domain socket connection
  • strip_tags() - Strip HTML and PHP tags from a string

fgets
file_exists
Filesystem Func?ii


Checks whether a file or directory exists

fgetss
file_get_contents
Filesystem Func?ii
PHP Manual

file_exists

(PHP 4, PHP 5, PHP 7)

file_exists — Checks whether a file or directory exists

Descrierea

bool file_exists ( string $filename )

Checks whether a file or directory exists.

Parametri

filename

Path to the file or directory.

On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.

Valorile întoarse

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

Nota:

This function will return FALSE for symlinks pointing to non-existing files.

Avertizare

This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir.

Nota:

The check is done using the real UID/GID instead of the effective one.

Nota: Deoarece tipul întreg al PHP este cu semn ?i multe platforme utilizeaza întregi de 32 de bi?i, unele func?ii ale sistemului de fi?iere pot întoarce rezultate nea?teptate pentru fi?iere ce depa?esc 2GB.

Exemple

Example #1 Testing whether a file exists

<?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?>

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • is_readable() - Tells whether a file exists and is readable
  • is_writable() - Tells whether the filename is writable
  • is_file() - Tells whether the filename is a regular file
  • file() - Reads entire file into an array

fgetss
file_get_contents
Filesystem Func?ii


Reads entire file into a string

file_exists
file_put_contents
Filesystem Func?ii
PHP Manual

file_get_contents

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

file_get_contents — Reads entire file into a string

Descrierea

string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = 0 [, 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.

Nota:

If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().

Parametri

filename

Name of the file to read.

use_include_path

Nota:

As of PHP 5 the FILE_USE_INCLUDE_PATH constant 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. Negative offsets count from the end of the 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.

Valorile întoarse

The function returns the read data sau FALSE în cazul e?ecului.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Erori/Excep?ii

An E_WARNING level error is generated if filename cannot be found, maxlength is less than zero, or if seeking to the specified offset in the stream fails.

Exemple

Example #1 Get and output the source of the homepage of a website

<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

Example #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);
?>

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(14) "lle Bjori Ro"

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Support for negative offsets has been added.
5.1.0 | Added the offset and maxlen parameters.

Note

Nota: Aceasta func?ie accepta ?i date binare.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

Avertizare

La utilizarea SSL, Microsoft IIS va viola protocolul prin închiderea conexiunii fara a trimite un indicator close_notify. PHP va raporta aceasta ca "SSL: Fatal Protocol Error" (eroare fatala de protocol) când se ajunge la sfâr?itul datelor. Pentru a evita aceasta coborât nivelul error_reporting pentru a nu include avertizari. PHP poate detecta soft-ul de server IIS care produce astfel de gre?eli când deschide?i fluxul utilizând înveli?ul https:// ?i va suprima automat avertizarile. La utilizarea fsockopen() pentru a crea un socket ssl:// programatorul este responsabil sa detecteze ?i sa suprime aceasta avertizare.

A se vedea ?i

  • file() - Reads entire file into an array
  • fgets() - Gets line from file pointer
  • fread() - Binary-safe file read
  • readfile() - Outputs a file
  • file_put_contents() - Write a string to a file
  • stream_get_contents() - Reads remainder of a stream into a string
  • stream_context_create() - Creates a stream context
  • $http_response_header

file_exists
file_put_contents
Filesystem Func?ii


Write a string to a file

file_get_contents
file
Filesystem Func?ii
PHP Manual

file_put_contents

(PHP 5, PHP 7)

file_put_contents — Write a string to a file

Descrierea

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.

Parametri

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. In other words, a flock() call happens between the fopen() call and the fwrite() call. This is not identical to an fopen() call with mode "x".

context

A valid context resource created with stream_context_create().

Valorile întoarse

This function returns the number of bytes that were written to the file, or FALSE on failure.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Exemple

Example #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);
?>

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Added support for LOCK_EX and the ability to pass a stream resource to the data parameter

Note

Nota: Aceasta func?ie accepta ?i date binare.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

A se vedea ?i

  • fopen() - Opens file or URL
  • fwrite() - Binary-safe file write
  • file_get_contents() - Reads entire file into a string
  • stream_context_create() - Creates a stream context

file_get_contents
file
Filesystem Func?ii


Reads entire file into an array

file_put_contents
fileatime
Filesystem Func?ii
PHP Manual

file

(PHP 4, PHP 5, PHP 7)

file — Reads entire file into an array

Descrierea

array file ( string $filename [, int $flags = 0 [, resource $context ]] )

Reads an entire file into an array.

Nota:

You can use file_get_contents() to return the contents of a file as a string.

Parametri

filename

Path to the file.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

flags

The optional parameter flags can be one, or more, of the following constants:

FILE_USE_INCLUDE_PATH
Search for the file in the include_path.
FILE_IGNORE_NEW_LINES
Do not add newline at the end of each array element
FILE_SKIP_EMPTY_LINES
Skip empty lines

context

A context resource created with the stream_context_create() function.

Nota: Sus?inrea contextelor a fost adaugata începând cu PHP 5.0.0. Pentru o descriere a contextelor, referi?i-va la Streams.

Valorile întoarse

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

Nota:

Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.

Nota: Daca PHP nu recunoa?te corect termina?iile liniilor atunci când cite?te fi?iere pe, sau create pe un computer Macintosh, atunci activarea op?iunii de configurare la rulare auto_detect_line_endings ar trebui sa ajute la solu?ionarea problemei.

Erori/Excep?ii

Emits an E_WARNING level error if the file does not exist.

Istoricul schimbarilor

Versiune | Descriere
4.3.0 | file() became binary safe

Exemple

Example #1 file() example

<?php
// Get a file into an array.  In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

// Another example, let's get a web page into a string.  See also file_get_contents().
$html = implode('', file('http://www.example.com/'));

// Using the optional flags parameter since PHP 5
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>

Note

Avertizare

La utilizarea SSL, Microsoft IIS va viola protocolul prin închiderea conexiunii fara a trimite un indicator close_notify. PHP va raporta aceasta ca "SSL: Fatal Protocol Error" (eroare fatala de protocol) când se ajunge la sfâr?itul datelor. Pentru a evita aceasta coborât nivelul error_reporting pentru a nu include avertizari. PHP poate detecta soft-ul de server IIS care produce astfel de gre?eli când deschide?i fluxul utilizând înveli?ul https:// ?i va suprima automat avertizarile. La utilizarea fsockopen() pentru a crea un socket ssl:// programatorul este responsabil sa detecteze ?i sa suprime aceasta avertizare.

A se vedea ?i

  • readfile() - Outputs a file
  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection
  • popen() - Opens process file pointer
  • file_get_contents() - Reads entire file into a string
  • include - include
  • stream_context_create() - Creates a stream context

file_put_contents
fileatime
Filesystem Func?ii


Gets last access time of file

file
filectime
Filesystem Func?ii
PHP Manual

fileatime

(PHP 4, PHP 5, PHP 7)

fileatime — Gets last access time of file

Descrierea

int fileatime ( string $filename )

Gets the last access time of the given file.

Parametri

filename

Path to the file.

Valorile întoarse

Returns the time the file was last accessed, sau FALSE în cazul e?ecului. The time is returned as a Unix timestamp.

Exemple

Example #1 fileatime() example

<?php

// outputs e.g.  somefile.txt was last accessed: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last accessed: " . date("F d Y H:i:s.", fileatime($filename));
}

?>

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota:

The atime of a file is supposed to change whenever the data blocks of a file are being read. This can be costly performance-wise when an application regularly accesses a very large number of files or directories.

Some Unix filesystems can be mounted with atime updates disabled to increase the performance of such applications; USENET news spools are a common example. On such filesystems this function will be useless.

Nota:

Observa?i ca rezolu?ia timpului poate sa difere de la un sistem de fi?iere la altul.

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • filemtime() - Gets file modification time
  • fileinode() - Gets file inode
  • date() - Formateaza o ora/data

file
filectime
Filesystem Func?ii


Gets inode change time of file

fileatime
filegroup
Filesystem Func?ii
PHP Manual

filectime

(PHP 4, PHP 5, PHP 7)

filectime — Gets inode change time of file

Descrierea

int filectime ( string $filename )

Gets the inode change time of a file.

Parametri

filename

Path to the file.

Valorile întoarse

Returns the time the file was last changed, sau FALSE în cazul e?ecului. The time is returned as a Unix timestamp.

Exemple

Example #1 A filectime() example

<?php

// outputs e.g.  somefile.txt was last changed: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last changed: " . date("F d Y H:i:s.", filectime($filename));
}

?>

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota:

Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create "Last Modified" footers on web pages) and fileatime().

Nota:

Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

Nota:

Observa?i ca rezolu?ia timpului poate sa difere de la un sistem de fi?iere la altul.

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • filemtime() - Gets file modification time

fileatime
filegroup
Filesystem Func?ii


Gets file group

filectime
fileinode
Filesystem Func?ii
PHP Manual

filegroup

(PHP 4, PHP 5, PHP 7)

filegroup — Gets file group

Descrierea

int filegroup ( string $filename )

Gets the file group. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name.

Parametri

filename

Path to the file.

Valorile întoarse

Returns the group ID of the file, or FALSE if an error occurs. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name. Upon failure, FALSE is returned.

Exemple

Example #1 Finding the group of a file

<?php
$filename = 'index.php';
print_r(posix_getgrgid(filegroup($filename)));
?>

Erori/Excep?ii

Upon failure, an E_WARNING is emitted.

Note

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • fileowner() - Gets file owner
  • posix_getgrgid() - Return info about a group by group id
  • safe_mode_gid

filectime
fileinode
Filesystem Func?ii


Gets file inode

filegroup
filemtime
Filesystem Func?ii
PHP Manual

fileinode

(PHP 4, PHP 5, PHP 7)

fileinode — Gets file inode

Descrierea

int fileinode ( string $filename )

Gets the file inode.

Parametri

filename

Path to the file.

Valorile întoarse

Returns the inode number of the file, sau FALSE în cazul e?ecului.

Exemple

Example #1 Comparing the inode of a file with the current file

<?php
$filename = 'index.php';
if (getmyinode() == fileinode($filename)) {
    echo 'You are checking the current file.';
}
?>

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • getmyinode() - Gets the inode of the current script
  • stat() - Gives information about a file

filegroup
filemtime
Filesystem Func?ii


Gets file modification time

fileinode
fileowner
Filesystem Func?ii
PHP Manual

filemtime

(PHP 4, PHP 5, PHP 7)

filemtime — Gets file modification time

Descrierea

int filemtime ( string $filename )

This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed.

Parametri

filename

Path to the file.

Valorile întoarse

Returns the time the file was last modified, sau FALSE în cazul e?ecului. The time is returned as a Unix timestamp, which is suitable for the date() function.

Exemple

Example #1 filemtime() example

<?php
// outputs e.g.  somefile.txt was last modified: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota:

Observa?i ca rezolu?ia timpului poate sa difere de la un sistem de fi?iere la altul.

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • filectime() - Gets inode change time of file
  • stat() - Gives information about a file
  • touch() - Sets access and modification time of file
  • getlastmod() - Gets time of last page modification

fileinode
fileowner
Filesystem Func?ii


Gets file owner

filemtime
fileperms
Filesystem Func?ii
PHP Manual

fileowner

(PHP 4, PHP 5, PHP 7)

fileowner — Gets file owner

Descrierea

int fileowner ( string $filename )

Gets the file owner.

Parametri

filename

Path to the file.

Valorile întoarse

Returns the user ID of the owner of the file, sau FALSE în cazul e?ecului. The user ID is returned in numerical format, use posix_getpwuid() to resolve it to a username.

Exemple

Example #1 Finding the owner of a file

<?php
$filename = 'index.php';
print_r(posix_getpwuid(fileowner($filename)));
?>

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • filegroup() - Gets file group
  • stat() - Gives information about a file
  • posix_getpwuid() - Return info about a user by user id

filemtime
fileperms
Filesystem Func?ii


Gets file permissions

fileowner
filesize
Filesystem Func?ii
PHP Manual

fileperms

(PHP 4, PHP 5, PHP 7)

fileperms — Gets file permissions

Descrierea

int fileperms ( string $filename )

Gets permissions for the given file.

Parametri

filename

Path to the file.

Valorile întoarse

Returns the file's permissions as a numeric mode. Lower bits of this mode are the same as the permissions expected by chmod(), however on most platforms the return value will also include information on the type of file given as filename. The examples below demonstrate how to test the return value for specific permissions and file types on POSIX systems, including Linux and Mac OS X.

For local files, the specific return value is that of the st_mode member of the structure returned by the C library's stat() function. Exactly which bits are set can vary from platform to platform, and looking up your specific platform's documentation is recommended if parsing the non-permission bits of the return value is required.

Exemple

Example #1 Display permissions as an octal value

<?php
echo substr(sprintf('%o', fileperms('/tmp')), -4);
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
?>

Exemplul de mai sus va afi?a:

1777
0644

Example #2 Display full permissions

<?php
$perms = fileperms('/etc/passwd');

switch ($perms & 0xF000) {
    case 0xC000: // socket
        $info = 's';
        break;
    case 0xA000: // symbolic link
        $info = 'l';
        break;
    case 0x8000: // regular
        $info = 'r';
        break;
    case 0x6000: // block special
        $info = 'b';
        break;
    case 0x4000: // directory
        $info = 'd';
        break;
    case 0x2000: // character special
        $info = 'c';
        break;
    case 0x1000: // FIFO pipe
        $info = 'p';
        break;
    default: // unknown
        $info = 'u';
}

// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
            (($perms & 0x0800) ? 's' : 'x' ) :
            (($perms & 0x0800) ? 'S' : '-'));

// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
            (($perms & 0x0400) ? 's' : 'x' ) :
            (($perms & 0x0400) ? 'S' : '-'));

// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
            (($perms & 0x0200) ? 't' : 'x' ) :
            (($perms & 0x0200) ? 'T' : '-'));

echo $info;
?>

Exemplul de mai sus va afi?a:

-rw-r--r--

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • chmod() - Changes file mode
  • is_readable() - Tells whether a file exists and is readable
  • stat() - Gives information about a file

fileowner
filesize
Filesystem Func?ii


Gets file size

fileperms
filetype
Filesystem Func?ii
PHP Manual

filesize

(PHP 4, PHP 5, PHP 7)

filesize — Gets file size

Descrierea

int filesize ( string $filename )

Gets the size for the given file.

Parametri

filename

Path to the file.

Valorile întoarse

Returns the size of the file in bytes, or FALSE (and generates an error of level E_WARNING) in case of an error.

Nota: Deoarece tipul întreg al PHP este cu semn ?i multe platforme utilizeaza întregi de 32 de bi?i, unele func?ii ale sistemului de fi?iere pot întoarce rezultate nea?teptate pentru fi?iere ce depa?esc 2GB.

Exemple

Example #1 filesize() example

<?php

// outputs e.g.  somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

?>

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • file_exists() - Checks whether a file or directory exists

fileperms
filetype
Filesystem Func?ii


Gets file type

filesize
flock
Filesystem Func?ii
PHP Manual

filetype

(PHP 4, PHP 5, PHP 7)

filetype — Gets file type

Descrierea

string filetype ( string $filename )

Returns the type of the given file.

Parametri

filename

Path to the file.

Valorile întoarse

Returns the type of the file. Possible values are fifo, char, dir, block, link, file, socket and unknown.

Returns FALSE if an error occurs. filetype() will also produce an E_NOTICE message if the stat call fails or if the file type is unknown.

Exemple

Example #1 filetype() example

<?php

echo filetype('/etc/passwd');  // file
echo filetype('/etc/');        // dir

?>

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • is_dir() - Tells whether the filename is a directory
  • is_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link
  • file_exists() - Checks whether a file or directory exists
  • mime_content_type() - Detect MIME Content-type for a file
  • pathinfo() - Returns information about a file path
  • stat() - Gives information about a file

filesize
flock
Filesystem Func?ii


Portable advisory file locking

filetype
fnmatch
Filesystem Func?ii
PHP Manual

flock

(PHP 4, PHP 5, PHP 7)

flock — Portable advisory file locking

Descrierea

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 with the LOCK_NB option documented below.

Parametri

handle

O resursa de tip indicator în sistemul de fi?iere care este în mod tipic creata utilizând 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.

wouldblock

The optional third argument is set to 1 if the lock would block (EWOULDBLOCK errno condition).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.22, 5.6.6 | Added support for the wouldblock parameter on Windows.
5.3.2 | The automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually.

Exemple

Example #1 flock() example

<?php

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) {  // acquire an exclusive lock
    ftruncate($fp, 0);      // truncate file
    fwrite($fp, "Write something here\n");
    fflush($fp);            // flush output before releasing the lock
    flock($fp, LOCK_UN);    // release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);

?>

Example #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);
?>

Note

Nota:

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.

Nota:

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()).

Nota:

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.

Avertizare

Assigning another value to handle argument in subsequent code will release the lock.

Avertizare

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
Filesystem Func?ii


Match filename against a pattern

flock
fopen
Filesystem Func?ii
PHP Manual

fnmatch

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fnmatch — Match filename against a pattern

Descrierea

bool fnmatch ( string $pattern , string $string [, int $flags = 0 ] )

fnmatch() checks if the passed string would match the given shell wildcard pattern.

Parametri

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.

Valorile întoarse

Returns TRUE if there is a match, FALSE otherwise.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on Windows platforms.

Exemple

Example #1 Checking a color name against a shell wildcard pattern

<?php
if (fnmatch("*gr[ae]y", $color)) {
  echo "some form of gray ...";
}
?>

Note

Avertizare

For now, this function is not available on non-POSIX compliant systems except Windows.

A se vedea ?i

  • 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
Filesystem Func?ii


Opens file or URL

fnmatch
fpassthru
Filesystem Func?ii
PHP Manual

fopen

(PHP 4, PHP 5, PHP 7)

fopen — Opens file or URL

Descrierea

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

fopen() binds a named resource, specified by filename, to a stream.

Parametri

filename

If filename is of the form "scheme://...", it is assumed to be a URL and 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.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled modul securizat or open_basedir further restrictions may apply.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

Nota:

The list of supported protocols can be found in Supported Protocols and Wrappers. Some protocols (also referred to as wrappers) support context and/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini value user_agent used by the http wrapper).

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

<?php
$handle = fopen("c:\\folder\\resource.txt", "r");
?>

mode

The mode parameter specifies the type of access you require to the stream. It may be any of the following:

A list of possible modes for fopen() using mode
mode | Description
'r' | Open for reading only; place the file pointer at the beginning of the file.
'r+' | Open for reading and writing; place the file pointer at the beginning of the file.
'w' | Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' | Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'a' | Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
'a+' | Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.
'x' | Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
'x+' | Create and open for reading and writing; otherwise it has the same behavior as 'x'.
'c' | Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
'c+' | Open the file for reading and writing; otherwise it has the same behavior as 'c'.
'e' | Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.

Nota:

Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use \n as the line ending character, Windows based systems use \r\n as the line ending characters and Macintosh based systems use \r as the line ending character.

If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will "look funny".

Windows offers a text-mode translation flag ('t') which will transparently translate \n to \r\n when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b' or 't' as the last character of the mode parameter.

The default translation mode depends on the SAPI and version of PHP that you are using, so you are encouraged to always specify the appropriate flag for portability reasons. You should use the 't' mode if you are working with plain-text files and you use \n to delimit your line endings in your script, but expect your files to be readable with applications such as notepad. You should use the 'b' in all other cases.

If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.

Nota:

For portability, it is strongly recommended that you always use the 'b' flag when opening files with fopen().

Nota:

Again, for portability, it is also strongly recommended that you re-write code that uses or relies upon the 't' mode so that it uses the correct line endings and 'b' mode instead.

use_include_path

The optional third use_include_path parameter can be set to '1' or TRUE if you want to search for the file in the include_path, too.

context

Nota: Sus?inrea contextelor a fost adaugata începând cu PHP 5.0.0. Pentru o descriere a contextelor, referi?i-va la Streams.

Valorile întoarse

Returns a file pointer resource on success, or FALSE on error.

Erori/Excep?ii

If the open fails, an error of level E_WARNING is generated. You may use @ to suppress this warning.

Istoricul schimbarilor

Versiune | Descriere
7.0.16, 7.1.2 | The 'e' option were added.
5.2.6 | The 'c' and 'c+' options were added
4.3.2 | As of PHP 4.3.2, the default mode is set to binary for all platforms that distinguish between binary and text mode. If you are having problems with your scripts after upgrading, try using the 't' flag as a workaround until you have made your script more portable as mentioned before

Exemple

Example #1 fopen() examples

<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>

Note

Avertizare

La utilizarea SSL, Microsoft IIS va viola protocolul prin închiderea conexiunii fara a trimite un indicator close_notify. PHP va raporta aceasta ca "SSL: Fatal Protocol Error" (eroare fatala de protocol) când se ajunge la sfâr?itul datelor. Pentru a evita aceasta coborât nivelul error_reporting pentru a nu include avertizari. PHP poate detecta soft-ul de server IIS care produce astfel de gre?eli când deschide?i fluxul utilizând înveli?ul https:// ?i va suprima automat avertizarile. La utilizarea fsockopen() pentru a crea un socket ssl:// programatorul este responsabil sa detecteze ?i sa suprime aceasta avertizare.

Nota: Când este activat modul securizat , PHP verifica daca directorul în care dori?i sa opera?i are acela?i UID (proprietar) ca ?i script-ul care se executa.

Nota:

If you are experiencing problems with reading and writing to files and you're using the server module version of PHP, remember to make sure that the files and directories you're using are accessible to the server process.

Nota:

This function may also succeed when filename is a directory. If you are unsure whether filename is a file or a directory, you may need to use the is_dir() function before calling fopen().

A se vedea ?i

  • Supported Protocols and Wrappers
  • fclose() - Closes an open file pointer
  • fgets() - Gets line from file pointer
  • fread() - Binary-safe file read
  • fwrite() - Binary-safe file write
  • fsockopen() - Open Internet or Unix domain socket connection
  • file() - Reads entire file into an array
  • file_exists() - Checks whether a file or directory exists
  • is_readable() - Tells whether a file exists and is readable
  • stream_set_timeout() - Set timeout period on a stream
  • popen() - Opens process file pointer
  • stream_context_create() - Creates a stream context
  • umask() - Changes the current umask
  • SplFileObject

fnmatch
fpassthru
Filesystem Func?ii


Output all remaining data on a file pointer

fopen
fputcsv
Filesystem Func?ii
PHP Manual

fpassthru

(PHP 4, PHP 5, PHP 7)

fpassthru — Output all remaining data on a file pointer

Descrierea

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.

Parametri

handle

Indicatorul fi?ierului trebuie sa fie valid ?i trebuie sa indice la un fi?ier deschis cu succes cu ajutorul fopen() sau fsockopen() (?i sa nu fie închis cu fclose()).

Valorile întoarse

If an error occurs, fpassthru() returns FALSE. Otherwise, fpassthru() returns the number of characters read from handle and passed through to the output.

Exemple

Example #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;

?>

Note

Nota:

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.

A se vedea ?i

  • readfile() - Outputs a file
  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fsockopen() - Open Internet or Unix domain socket connection

fopen
fputcsv
Filesystem Func?ii


Format line as CSV and write to file pointer

fpassthru
fputs
Filesystem Func?ii
PHP Manual

fputcsv

(PHP 5 >= 5.1.0, PHP 7)

fputcsv — Format line as CSV and write to file pointer

Descrierea

int fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape_char = "\" ]]] )

fputcsv() formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file handle.

Parametri

handle

Indicatorul fi?ierului trebuie sa fie valid ?i trebuie sa indice la un fi?ier deschis cu succes cu ajutorul fopen() sau fsockopen() (?i sa nu fie închis cu 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).

escape_char

The optional escape_char parameter sets the escape character (one character only).

Valorile întoarse

Returns the length of the written string sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.4 | The escape_char parameter was added

Exemple

Example #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"""

Note

Nota: Daca PHP nu recunoa?te corect termina?iile liniilor atunci când cite?te fi?iere pe, sau create pe un computer Macintosh, atunci activarea op?iunii de configurare la rulare auto_detect_line_endings ar trebui sa ajute la solu?ionarea problemei.

A se vedea ?i

  • fgetcsv() - Gets line from file pointer and parse for CSV fields

fpassthru
fputs
Filesystem Func?ii


Pseudonim pentru fwrite

fputcsv
fread
Filesystem Func?ii
PHP Manual

fputs

(PHP 4, PHP 5, PHP 7)

fputs — Pseudonim pentru fwrite()

Descrierea

Aceasta func?ie este pseudonim pentru: fwrite().

fputcsv
fread
Filesystem Func?ii


Binary-safe file read

fputs
fscanf
Filesystem Func?ii
PHP Manual

fread

(PHP 4, PHP 5, PHP 7)

fread — Binary-safe file read

Descrierea

string fread ( resource $handle , int $length )

fread() reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met:

  • length bytes have been read
  • EOF (end of file) is reached
  • a packet becomes available or the socket timeout occurs (for network streams)
  • if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size.

Parametri

handle

O resursa de tip indicator în sistemul de fi?iere care este în mod tipic creata utilizând fopen().

length

Up to length number of bytes read.

Valorile întoarse

Returns the read string sau FALSE în cazul e?ecului.

Exemple

Example #1 A simple fread() example

<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Example #2 Binary fread() example

Avertizare

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

<?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Example #3 Remote fread() examples

Avertizare

When reading from anything that is not a regular local file, such as streams returned when reading remote files or from popen() and fsockopen(), reading will stop after a packet is available. This means that you should collect the data together in chunks as shown in the examples below.

<?php
// For PHP 5 and up
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>
<?php
$handle = fopen("http://www.example.com/", "rb");
if (FALSE === $handle) {
    exit("Failed to open stream to URL");
}

$contents = '';

while (!feof($handle)) {
    $contents .= fread($handle, 8192);
}
fclose($handle);
?>

Note

Nota:

If you just want to get the contents of a file into a string, use file_get_contents() as it has much better performance than the code above.

Nota:

Note that fread() reads from the current position of the file pointer. Use ftell() to find the current position of the pointer and rewind() to rewind the pointer position.

A se vedea ?i

  • fwrite() - Binary-safe file write
  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection
  • popen() - Opens process file pointer
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fscanf() - Parses input from a file according to a format
  • file() - Reads entire file into an array
  • fpassthru() - Output all remaining data on a file pointer
  • ftell() - Returns the current position of the file read/write pointer
  • rewind() - Rewind the position of a file pointer
  • unpack() - Unpack data from binary string

fputs
fscanf
Filesystem Func?ii


Parses input from a file according to a format

fread
fseek
Filesystem Func?ii
PHP Manual

fscanf

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

fscanf — Parses input from a file according to a format

Descrierea

mixed fscanf ( resource $handle , string $format [, mixed &$... ] )

The function fscanf() is similar to sscanf(), but it takes its input from a file associated with handle and interprets the input 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 stream. This means that even a tab \t in the format string can match a single space character in the input stream.

Each call to fscanf() reads one line from the file.

Parametri

handle

O resursa de tip indicator în sistemul de fi?iere care este în mod tipic creata utilizând fopen().

format

The specified format as described in the sprintf() documentation.

...

The optional assigned values.

Valorile întoarse

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.

Exemple

Example #1 fscanf() Example

<?php
$handle = fopen("users.txt", "r");
while ($userinfo = fscanf($handle, "%s\t%s\t%s\n")) {
    list ($name, $profession, $countrycode) = $userinfo;
    //... do something with the values
}
fclose($handle);
?>

Example #2 Contents of users.txt

javier  argonaut        pe
hiroshi sculptor        jp
robert  slacker us
luigi   florist it

A se vedea ?i

  • fread() - Binary-safe file read
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • sscanf() - Parses input from a string according to a format
  • printf() - Output a formatted string
  • sprintf() - Return a formatted string

fread
fseek
Filesystem Func?ii


Seeks on a file pointer

fscanf
fstat
Filesystem Func?ii
PHP Manual

fseek

(PHP 4, PHP 5, PHP 7)

fseek — Seeks on a file pointer

Descrierea

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.

Parametri

handle

O resursa de tip indicator în sistemul de fi?iere care este în mod tipic creata utilizând 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.

Valorile întoarse

Upon success, returns 0; otherwise, returns -1.

Exemple

Example #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);

?>

Note

Nota:

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.

Nota:

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.

A se vedea ?i

  • ftell() - Returns the current position of the file read/write pointer
  • rewind() - Rewind the position of a file pointer

fscanf
fstat
Filesystem Func?ii


Gets information about a file using an open file pointer

fseek
ftell
Filesystem Func?ii
PHP Manual

fstat

(PHP 4, PHP 5, PHP 7)

fstat — Gets information about a file using an open file pointer

Descrierea

array fstat ( resource $handle )

Gathers the statistics of the file opened by the file pointer handle. This function is similar to the stat() function except that it operates on an open file pointer instead of a filename.

Parametri

handle

O resursa de tip indicator în sistemul de fi?iere care este în mod tipic creata utilizând fopen().

Valorile întoarse

Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page.

Exemple

Example #1 fstat() example

<?php

// open a file
$fp = fopen("/etc/passwd", "r");

// gather statistics
$fstat = fstat($fp);

// close the file
fclose($fp);

// print only the associative part
print_r(array_slice($fstat, 13));

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

Note

Nota: Aceasta func?ie nu va lucra cu fi?iere la distan?a, deoarece fi?ierul care trebuie sa fie examinat trebuie sa fie accesibil prin intermediul sistemului de fi?iere al serverului.

fseek
ftell
Filesystem Func?ii


Returns the current position of the file read/write pointer

fstat
ftruncate
Filesystem Func?ii
PHP Manual

ftell

(PHP 4, PHP 5, PHP 7)

ftell — Returns the current position of the file read/write pointer

Descrierea

int ftell ( resource $handle )

Returns the position of the file pointer referenced by handle.

Parametri

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or popen(). ftell() gives undefined results for append-only streams (opened with "a" flag).

Valorile întoarse

Returns the position of the file pointer referenced by handle as an integer; i.e., its offset into the file stream.

If an error occurs, returns FALSE.

Nota: Deoarece tipul întreg al PHP este cu semn ?i multe platforme utilizeaza întregi de 32 de bi?i, unele func?ii ale sistemului de fi?iere pot întoarce rezultate nea?teptate pentru fi?iere ce depa?esc 2GB.

Exemple

Example #1 ftell() example

<?php

// opens a file and read some data
$fp = fopen("/etc/passwd", "r");
$data = fgets($fp, 12);

// where are we ?
echo ftell($fp); // 11

fclose($fp);

?>

A se vedea ?i

  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fseek() - Seeks on a file pointer
  • rewind() - Rewind the position of a file pointer

fstat
ftruncate
Filesystem Func?ii


Truncates a file to a given length

ftell
fwrite
Filesystem Func?ii
PHP Manual

ftruncate

(PHP 4, PHP 5, PHP 7)

ftruncate — Truncates a file to a given length

Descrierea

bool ftruncate ( resource $handle , int $size )

Takes the filepointer, handle, and truncates the file to length, size.

Parametri

handle

The file pointer.

Nota:

The handle must be open for writing.

size

The size to truncate to.

Nota:

If size is larger than the file then the file is extended with null bytes.

If size is smaller than the file then the file is truncated to that size.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 File truncation example

<?php
$filename = 'lorem_ipsum.txt';

$handle = fopen($filename, 'r+');
ftruncate($handle, rand(1, filesize($filename)));
rewind($handle);
echo fread($handle, filesize($filename));
fclose($handle);
?>

Note

Nota:

The file pointer is not changed.

A se vedea ?i

  • fopen() - Opens file or URL
  • fseek() - Seeks on a file pointer

ftell
fwrite
Filesystem Func?ii


Binary-safe file write

ftruncate
glob
Filesystem Func?ii
PHP Manual

fwrite

(PHP 4, PHP 5, PHP 7)

fwrite — Binary-safe file write

Descrierea

int fwrite ( resource $handle , string $string [, int $length ] )

fwrite() writes the contents of string to the file stream pointed to by handle.

Parametri

handle

O resursa de tip indicator în sistemul de fi?iere care este în mod tipic creata utilizând fopen().

string

The string that is to be written.

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.

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.

Valorile întoarse

fwrite() returns the number of bytes written, or FALSE on error.

Note

Nota:

Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:

<?php
function fwrite_stream($fp, $string) {
    for ($written = 0; $written < strlen($string); $written += $fwrite) {
        $fwrite = fwrite($fp, substr($string, $written));
        if ($fwrite === false) {
            return $written;
        }
    }
    return $written;
}
?>

Nota:

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

Nota:

If handle was fopen()ed in append mode, fwrite()s are atomic (unless the size of string exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption.

Nota:

If writing twice to the file pointer, then the data will be appended to the end of the file content:

<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);

// the content of 'data.txt' is now 123 and not 23!
?>

Exemple

Example #1 A simple fwrite() example

<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $somecontent will go when we fwrite() it.
    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    // Write $somecontent to our opened file.
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}
?>

A se vedea ?i

  • fread() - Binary-safe file read
  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection
  • popen() - Opens process file pointer
  • file_get_contents() - Reads entire file into a string
  • pack() - Pack data into binary string

ftruncate
glob
Filesystem Func?ii


Find pathnames matching a pattern

fwrite
is_dir
Filesystem Func?ii
PHP Manual

glob

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

glob — Find pathnames matching a pattern

Descrierea

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.

Parametri

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). When this flag is not used, the pathnames are sorted alphabetically
  • 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.

Valorile întoarse

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

Nota:

On some systems it is impossible to distinguish between empty match and an error.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | GLOB_ERR was added

Exemple

Example #1 Convenient way how glob() can replace opendir() and friends.

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

Note

Nota: Aceasta func?ie nu va lucra cu fi?iere la distan?a, deoarece fi?ierul care trebuie sa fie examinat trebuie sa fie accesibil prin intermediul sistemului de fi?iere al serverului.

Nota: This function isn't available on some systems (e.g. old Sun OS).

Nota: The GLOB_BRACE flag is not available on some non GNU systems, like Solaris.

A se vedea ?i

  • opendir() - Open directory handle
  • readdir() - Read entry from directory handle
  • closedir() - Close directory handle
  • fnmatch() - Match filename against a pattern

fwrite
is_dir
Filesystem Func?ii


Tells whether the filename is a directory

glob
is_executable
Filesystem Func?ii
PHP Manual

is_dir

(PHP 4, PHP 5, PHP 7)

is_dir — Tells whether the filename is a directory

Descrierea

bool is_dir ( string $filename )

Tells whether the given filename is a directory.

Parametri

filename

Path to the file. If filename is a relative filename, it will be checked relative to the current working directory. If filename is a symbolic or hard link then the link will be resolved and checked. If you have enabled modul securizat, or open_basedir further restrictions may apply.

Valorile întoarse

Returns TRUE if the filename exists and is a directory, FALSE otherwise.

Exemple

Example #1 is_dir() example

<?php
var_dump(is_dir('a_file.txt'));
var_dump(is_dir('bogus_dir/abc'));

var_dump(is_dir('..')); //one dir up
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(false)
bool(true)

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • chdir() - Change directory
  • dir() - Return an instance of the Directory class
  • opendir() - Open directory handle
  • is_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link

glob
is_executable
Filesystem Func?ii


Tells whether the filename is executable

is_dir
is_file
Filesystem Func?ii
PHP Manual

is_executable

(PHP 4, PHP 5, PHP 7)

is_executable — Tells whether the filename is executable

Descrierea

bool is_executable ( string $filename )

Tells whether the filename is executable.

Parametri

filename

Path to the file.

Valorile întoarse

Returns TRUE if the filename exists and is executable, or FALSE on error.

Exemple

Example #1 is_executable() example

<?php

$file = '/home/vincent/somefile.sh';

if (is_executable($file)) {
    echo $file.' is executable';
} else {
    echo $file.' is not executable';
}

?>

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • is_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link

is_dir
is_file
Filesystem Func?ii


Tells whether the filename is a regular file

is_executable
is_link
Filesystem Func?ii
PHP Manual

is_file

(PHP 4, PHP 5, PHP 7)

is_file — Tells whether the filename is a regular file

Descrierea

bool is_file ( string $filename )

Tells whether the given file is a regular file.

Parametri

filename

Path to the file.

Valorile întoarse

Returns TRUE if the filename exists and is a regular file, FALSE otherwise.

Nota: Deoarece tipul întreg al PHP este cu semn ?i multe platforme utilizeaza întregi de 32 de bi?i, unele func?ii ale sistemului de fi?iere pot întoarce rezultate nea?teptate pentru fi?iere ce depa?esc 2GB.

Exemple

Example #1 is_file() example

<?php
var_dump(is_file('a_file.txt')) . "\n";
var_dump(is_file('/usr/bin/')) . "\n";
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • is_dir() - Tells whether the filename is a directory
  • is_link() - Tells whether the filename is a symbolic link

is_executable
is_link
Filesystem Func?ii


Tells whether the filename is a symbolic link

is_file
is_readable
Filesystem Func?ii
PHP Manual

is_link

(PHP 4, PHP 5, PHP 7)

is_link — Tells whether the filename is a symbolic link

Descrierea

bool is_link ( string $filename )

Tells whether the given file is a symbolic link.

Parametri

filename

Path to the file.

Valorile întoarse

Returns TRUE if the filename exists and is a symbolic link, FALSE otherwise.

Exemple

Example #1 Create and confirm if a file is a symbolic link

<?php
$link = 'uploads';

if (is_link($link)) {
    echo(readlink($link));
} else {
    symlink('uploads.php', $link);
}
?>

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • is_dir() - Tells whether the filename is a directory
  • is_file() - Tells whether the filename is a regular file
  • readlink() - Returns the target of a symbolic link

is_file
is_readable
Filesystem Func?ii


Tells whether a file exists and is readable

is_link
is_uploaded_file
Filesystem Func?ii
PHP Manual

is_readable

(PHP 4, PHP 5, PHP 7)

is_readable — Tells whether a file exists and is readable

Descrierea

bool is_readable ( string $filename )

Tells whether a file exists and is readable.

Parametri

filename

Path to the file.

Valorile întoarse

Returns TRUE if the file or directory specified by filename exists and is readable, FALSE otherwise.

Exemple

Example #1 is_readable() example

<?php
$filename = 'test.txt';
if (is_readable($filename)) {
    echo 'The file is readable';
} else {
    echo 'The file is not readable';
}
?>

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

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.

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

Nota:

The check is done using the real UID/GID instead of the effective one.

This function may return TRUE for directories. Use is_dir() to distinguish file and directory.

A se vedea ?i

  • is_writable() - Tells whether the filename is writable
  • file_exists() - Checks whether a file or directory exists
  • fgets() - Gets line from file pointer

is_link
is_uploaded_file
Filesystem Func?ii


Tells whether the file was uploaded via HTTP POST

is_readable
is_writable
Filesystem Func?ii
PHP Manual

is_uploaded_file

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

is_uploaded_file — Tells whether the file was uploaded via HTTP POST

Descrierea

bool is_uploaded_file ( string $filename )

Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

For proper working, the function is_uploaded_file() needs an argument like $_FILES['userfile']['tmp_name'], - the name of the uploaded file on the client's machine $_FILES['userfile']['name'] does not work.

Parametri

filename

The filename being checked.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 is_uploaded_file() example

<?php

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
   echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
   echo "Displaying contents\n";
   readfile($_FILES['userfile']['tmp_name']);
} else {
   echo "Possible file upload attack: ";
   echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
}

?>

A se vedea ?i

  • move_uploaded_file() - Moves an uploaded file to a new location
  • $_FILES
  • See Handling file uploads for a simple usage example.

is_readable
is_writable
Filesystem Func?ii


Tells whether the filename is writable

is_uploaded_file
is_writeable
Filesystem Func?ii
PHP Manual

is_writable

(PHP 4, PHP 5, PHP 7)

is_writable — Tells whether the filename is writable

Descrierea

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.

Parametri

filename

The filename being checked.

Valorile întoarse

Returns TRUE if the filename exists and is writable.

Exemple

Example #1 is_writable() example

<?php
$filename = 'test.txt';
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';
}
?>

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • is_readable() - Tells whether a file exists and is readable
  • file_exists() - Checks whether a file or directory exists
  • fwrite() - Binary-safe file write

is_uploaded_file
is_writeable
Filesystem Func?ii


Pseudonim pentru is_writable

is_writable
lchgrp
Filesystem Func?ii
PHP Manual

is_writeable

(PHP 4, PHP 5, PHP 7)

is_writeable — Pseudonim pentru is_writable()

Descrierea

Aceasta func?ie este pseudonim pentru: is_writable().

is_writable
lchgrp
Filesystem Func?ii


Changes group ownership of symlink

is_writeable
lchown
Filesystem Func?ii
PHP Manual

lchgrp

(PHP 5 >= 5.1.2, PHP 7)

lchgrp — Changes group ownership of symlink

Descrierea

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.

Parametri

filename

Path to the symlink.

group

The group specified by name or number.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Changing the group of a symbolic link

<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);

lchgrp($link, 8);
?>

Note

Nota: Aceasta func?ie nu va lucra cu fi?iere la distan?a, deoarece fi?ierul care trebuie sa fie examinat trebuie sa fie accesibil prin intermediul sistemului de fi?iere al serverului.

Nota: Când este activat modul securizat, PHP verifica daca fi?ierele ?i directoarele cu care se va opera au acela?i UID (proprietar) ca ?i script-ul care se executa.

Nota: Aceasta func?ie nu este implementata pe platformele Windows.

A se vedea ?i

  • chgrp() - Changes file group
  • lchown() - Changes user ownership of symlink
  • chown() - Changes file owner
  • chmod() - Changes file mode

is_writeable
lchown
Filesystem Func?ii


Changes user ownership of symlink

lchgrp
link
Filesystem Func?ii
PHP Manual

lchown

(PHP 5 >= 5.1.2, PHP 7)

lchown — Changes user ownership of symlink

Descrierea

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.

Parametri

filename

Path to the file.

user

User name or number.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Changing the owner of a symbolic link

<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);

lchown($link, 8);
?>

Note

Nota: Aceasta func?ie nu va lucra cu fi?iere la distan?a, deoarece fi?ierul care trebuie sa fie examinat trebuie sa fie accesibil prin intermediul sistemului de fi?iere al serverului.

Nota: Când este activat modul securizat, PHP verifica daca fi?ierele ?i directoarele cu care se va opera au acela?i UID (proprietar) ca ?i script-ul care se executa.

Nota: Aceasta func?ie nu este implementata pe platformele Windows.

A se vedea ?i

  • chown() - Changes file owner
  • lchgrp() - Changes group ownership of symlink
  • chgrp() - Changes file group
  • chmod() - Changes file mode

lchgrp
link
Filesystem Func?ii


Create a hard link

lchown
linkinfo
Filesystem Func?ii
PHP Manual

link

(PHP 4, PHP 5, PHP 7)

link — Create a hard link

Descrierea

bool link ( string $target , string $link )

link() creates a hard link.

Parametri

target

Target of the link.

link

The link name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Exemple

Example #1 Creating a simple hard link

<?php
$target = 'source.ext'; // This is the file that already exists
$link = 'newfile.ext'; // This the filename that you want to link it to

link($target, $link);
?>

Note

Nota: Aceasta func?ie nu va lucra cu fi?iere la distan?a, deoarece fi?ierul care trebuie sa fie examinat trebuie sa fie accesibil prin intermediul sistemului de fi?iere al serverului.

Nota: For Windows only: This function requires PHP to run in an elevated mode or with the UAC disabled.

A se vedea ?i

  • symlink() - Creates a symbolic link
  • readlink() - Returns the target of a symbolic link
  • linkinfo() - Gets information about a link

lchown
linkinfo
Filesystem Func?ii


Gets information about a link

link
lstat
Filesystem Func?ii
PHP Manual

linkinfo

(PHP 4, PHP 5, PHP 7)

linkinfo — Gets information about a link

Descrierea

int linkinfo ( string $path )

Gets information about a link.

This function is used to verify if a link (pointed to by path) really exists (using the same method as the S_ISLNK macro defined in stat.h).

Parametri

path

Path to the link.

Valorile întoarse

linkinfo() returns the st_dev field of the Unix C stat structure returned by the lstat system call. Returns 0 or FALSE in case of error.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Exemple

Example #1 linkinfo() example

<?php

echo linkinfo('/vmlinuz'); // 835

?>

A se vedea ?i

  • symlink() - Creates a symbolic link
  • link() - Create a hard link
  • readlink() - Returns the target of a symbolic link

link
lstat
Filesystem Func?ii


Gives information about a file or symbolic link

linkinfo
mkdir
Filesystem Func?ii
PHP Manual

lstat

(PHP 4, PHP 5, PHP 7)

lstat — Gives information about a file or symbolic link

Descrierea

array lstat ( string $filename )

Gathers the statistics of the file or symbolic link named by filename.

Parametri

filename

Path to a file or a symbolic link.

Valorile întoarse

See the manual page for stat() for information on the structure of the array that lstat() returns. This function is identical to the stat() function except that if the filename parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link.

Exemple

Example #1 Comparison of stat() and lstat()

<?php
symlink('uploads.php', 'uploads');

// Contrast information for uploads.php and uploads
array_diff(stat('uploads'), lstat('uploads'));
?>

Exemplul de mai sus va afi?a ceva similar cu:

Information that differs between the two files.

Array
(
    [ino] => 97236376
    [mode] => 33188
    [size] => 34
    [atime] => 1223580003
    [mtime] => 1223581848
    [ctime] => 1223581848
    [blocks] => 8
)

Erori/Excep?ii

În cazul e?ecului este emis un E_WARNING.

Note

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • stat() - Gives information about a file

linkinfo
mkdir
Filesystem Func?ii


Makes directory

lstat
move_uploaded_file
Filesystem Func?ii
PHP Manual

mkdir

(PHP 4, PHP 5, PHP 7)

mkdir — Makes directory

Descrierea

bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )

Attempts to create the directory specified by pathname.

Parametri

pathname

The directory path.

mode

The mode is 0777 by default, which means the widest possible access. For more information on modes, read the details on the chmod() page.

Nota:

mode is ignored on Windows.

Note that you probably want to specify the mode as an octal number, which means it should have a leading zero. The mode is also modified by the current umask, which you can change using umask().

recursive

Allows the creation of nested directories specified in the pathname.

context

Nota: Sus?inrea contextelor a fost adaugata începând cu PHP 5.0.0. Pentru o descriere a contextelor, referi?i-va la Streams.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 mkdir() example

<?php
mkdir("/path/to/my/dir", 0700);
?>

Example #2 mkdir() using the recursive parameter

<?php
// Desired folder structure
$structure = './depth1/depth2/depth3/';

// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.

if (!mkdir($structure, 0777, true)) {
    die('Failed to create folders...');
}

// ...
?>

Erori/Excep?ii

Emits an E_WARNING level error if the directory already exists.

Emits an E_WARNING level error if the relevant permissions prevent creating the directory.

Note

Nota: Când este activat modul securizat , PHP verifica daca directorul în care dori?i sa opera?i are acela?i UID (proprietar) ca ?i script-ul care se executa.

A se vedea ?i

  • is_dir() - Tells whether the filename is a directory
  • rmdir() - Removes directory

lstat
move_uploaded_file
Filesystem Func?ii


Moves an uploaded file to a new location

mkdir
parse_ini_file
Filesystem Func?ii
PHP Manual

move_uploaded_file

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

move_uploaded_file — Moves an uploaded file to a new location

Descrierea

bool move_uploaded_file ( string $filename , string $destination )

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

Parametri

filename

The filename of the uploaded file.

destination

The destination of the moved file.

Valorile întoarse

Returns TRUE on success.

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

Exemple

Example #1 Uploading multiple files

<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        // basename() may prevent filesystem traversal attacks;
        // further validation/sanitation of the filename may be appropriate
        $name = basename($_FILES["pictures"]["name"][$key]);
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}
?>

Note

Nota:

move_uploaded_file() is both modul securizat and open_basedir aware. However, restrictions are placed only on the destination path as to allow the moving of uploaded files in which filename may conflict with such restrictions. move_uploaded_file() ensures the safety of this operation by allowing only those files uploaded through PHP to be moved.

Avertizare

If the destination file already exists, it will be overwritten.

A se vedea ?i

  • is_uploaded_file() - Tells whether the file was uploaded via HTTP POST
  • rename() - Renames a file or directory
  • See Handling file uploads for a simple usage example

mkdir
parse_ini_file
Filesystem Func?ii


Parse a configuration file

move_uploaded_file
parse_ini_string
Filesystem Func?ii
PHP Manual

parse_ini_file

(PHP 4, PHP 5, PHP 7)

parse_ini_file — Parse a configuration file

Descrierea

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.

Parametri

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.

Începând cu PHP 5.6.1 poate de asemenea fi specificat ca INI_SCANNER_TYPED. În acest mod tipurile boolean, null ?i integer sunt pastrate, când este posibil. Valorile string "true", "on" ?i "yes" sunt convertite în TRUE. "false", "off", "no" ?i "none" sunt considerate FALSE. "null" este convertit în NULL în modul cu tipuri. De asemenea toate ?irurile numerice sunt convertite în integer, daca acest lucru este posibil.

Valorile întoarse

The settings are returned as an associative array on success, and FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | Hash marks (#) are no longer recognized as comments.
5.6.1 | Added new INI_SCANNER_TYPED mode.
5.3.0 | Added optional scanner_mode parameter. Single quotes may now be used around variable assignments. Hash marks (#) should 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 modul securizat and open_basedir.

Exemple

Example #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"

urls[svn] = "http://svn.php.net"
urls[git] = "http://git.php.net"

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

    [urls] => Array
        (
            [svn] => http://svn.php.net
            [git] => http://git.php.net
        )

)
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
                )

            [urls] => Array
                (
                    [svn] => http://svn.php.net
                    [git] => http://git.php.net
                )

        )

)

Example #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;
?>

Exemplul de mai sus va afi?a ceva similar cu:

(parsed) magic_quotes_gpc = Yes
(loaded) magic_quotes_gpc = Yes

Note

Nota:

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.

Nota:

If a value in the ini file contains any non-alphanumeric characters it needs to be enclosed in double-quotes (").

Nota: 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, off, no and false result in "", and values on, yes and true result in "1", unless INI_SCANNER_TYPED mode is used (as of PHP 5.6.1). Characters ?{}|&~!()^" must not be used anywhere in the key and have a special meaning in the value.

Nota:

Entries without an equal sign are ignored. For example, "foo" is ignored whereas "bar =" is parsed and added with an empty value. For example, MySQL has a "no-auto-rehash" setting in my.cnf that does not take a value, so it is ignored.

A se vedea ?i

  • parse_ini_string() - Parse a configuration string

move_uploaded_file
parse_ini_string
Filesystem Func?ii


Parse a configuration string

parse_ini_file
pathinfo
Filesystem Func?ii
PHP Manual

parse_ini_string

(PHP 5 >= 5.3.0, PHP 7)

parse_ini_string — Parse a configuration string

Descrierea

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.

Parametri

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.

Începând cu PHP 5.6.1 poate de asemenea fi specificat ca INI_SCANNER_TYPED. În acest mod tipurile boolean, null ?i integer sunt pastrate, când este posibil. Valorile string "true", "on" ?i "yes" sunt convertite în TRUE. "false", "off", "no" ?i "none" sunt considerate FALSE. "null" este convertit în NULL în modul cu tipuri. De asemenea toate ?irurile numerice sunt convertite în integer, daca acest lucru este posibil.

Valorile întoarse

The settings are returned as an associative array on success, and FALSE on failure.

Note

Nota: 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, off, no and false result in "", and values on, yes and true result in "1", unless INI_SCANNER_TYPED mode is used. Characters ?{}|&~![()^" must not be used anywhere in the key and have a special meaning in the value.

A se vedea ?i

  • parse_ini_file() - Parse a configuration file

parse_ini_file
pathinfo
Filesystem Func?ii


Returns information about a file path

parse_ini_string
pclose
Filesystem Func?ii
PHP Manual

pathinfo

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pathinfo — Returns information about a file path

Descrierea

mixed pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )

pathinfo() returns information about path: either an associative array or a string, depending on options.

Nota:

For information on retrieving the current path info, read the section on predefined reserved variables.

Precautie

pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function.

Parametri

path

The path to be parsed.

options

If present, specifies a specific element to be returned; one of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME.

If options is not specified, returns all available elements.

Valorile întoarse

If the options parameter is not passed, an associative array containing the following elements is returned: dirname, basename, extension (if any), and filename.

Nota:

If the path has more than one extension, PATHINFO_EXTENSION returns only the last one and PATHINFO_FILENAME only strips the last one. (see first example below).

Nota:

If the path does not have an extension, no extension element will be returned (see second example below).

Nota:

If the basename of the path starts with a dot, the following characters are interpreted as extension, and the filename is empty (see third example below).

If options is present, returns a string containing the requested element.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | The PATHINFO_FILENAME constant was added.

Exemple

Example #1 pathinfo() Example

<?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"; // since PHP 5.2.0
?>

Exemplul de mai sus va afi?a:

/www/htdocs/inc
lib.inc.php
php
lib.inc

Example #2 pathinfo() example showing difference between null and no extension

<?php
$path_parts = pathinfo('/path/emptyextension.');
var_dump($path_parts['extension']);

$path_parts = pathinfo('/path/noextension');
var_dump($path_parts['extension']);
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(0) ""

Notice: Undefined index: extension in test.php on line 6
NULL

Example #3 pathinfo() example for a dot-file

<?php
print_r(pathinfo('/some/path/.test'));
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [dirname] => /some/path
    [basename] => .test
    [extension] => test
    [filename] =>
)

A se vedea ?i

  • dirname() - Returns a parent directory's path
  • basename() - Returns trailing name component of path
  • parse_url() - Parse a URL and return its components
  • realpath() - Returns canonicalized absolute pathname

parse_ini_string
pclose
Filesystem Func?ii


Closes process file pointer

pathinfo
popen
Filesystem Func?ii
PHP Manual

pclose

(PHP 4, PHP 5, PHP 7)

pclose — Closes process file pointer

Descrierea

int pclose ( resource $handle )

Closes a file pointer to a pipe opened by popen().

Parametri

handle

The file pointer must be valid, and must have been returned by a successful call to popen().

Valorile întoarse

Returns the termination status of the process that was run. In case of an error then -1 is returned.

Nota:

If PHP has been compiled with --enable-sigchild, the return value of this function is undefined.

Exemple

Example #1 pclose() example

<?php
$handle = popen('/bin/ls', 'r');
pclose($handle);
?>

Note

Nota: Unix Only:

pclose() is internally implemented using the waitpid(3) system call. To obtain the real exit status code the pcntl_wexitstatus() function should be used.

A se vedea ?i

  • popen() - Opens process file pointer

pathinfo
popen
Filesystem Func?ii


Opens process file pointer

pclose
readfile
Filesystem Func?ii
PHP Manual

popen

(PHP 4, PHP 5, PHP 7)

popen — Opens process file pointer

Descrierea

resource popen ( string $command , string $mode )

Opens a pipe to a process executed by forking the command given by command.

Parametri

command

The command

mode

The mode

Valorile întoarse

Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fwrite(). When the mode is 'r', the returned file pointer equals to the STDOUT of the command, when the mode is 'w', the returned file pointer equals to the STDIN of the command.

If an error occurs, returns FALSE.

Exemple

Example #1 popen() example

<?php
$handle = popen("/bin/ls", "r");
?>

If the command to be executed could not be found, a valid resource is returned. This may seem odd, but makes sense; it allows you to access any error message returned by the shell:

Example #2 popen() example

<?php
error_reporting(E_ALL);

/* Add redirection so we can get stderr. */
$handle = popen('/path/to/executable 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>

Note

Nota:

If you're looking for bi-directional support (two-way), use proc_open().

Nota: Când este activat modul securizat, pute?i executa fi?ierele aflate în safe_mode_exec_dir. Din motive practice, în prezent nu se permite de a avea componente .. în calea catre executabil.

Avertizare

Când este activat modul securizat, linia de comanda este prelucrata cu escapeshellcmd(). De aceea, echo y | echo x devine echo y \| echo x .

A se vedea ?i

  • pclose() - Closes process file pointer
  • fopen() - Opens file or URL
  • proc_open() - Execute a command and open file pointers for input/output

pclose
readfile
Filesystem Func?ii


Outputs a file

popen
readlink
Filesystem Func?ii
PHP Manual

readfile

(PHP 4, PHP 5, PHP 7)

readfile — Outputs a file

Descrierea

int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )

Reads a file and writes it to the output buffer.

Parametri

filename

The filename being read.

use_include_path

You can use the optional second parameter and set it to TRUE, if you want to search for the file in the include_path, too.

context

A context stream resource.

Valorile întoarse

Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile(), an error message is printed.

Exemple

Example #1 Forcing a download using readfile()

<?php
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Open / Save dialogue

Note

Nota:

readfile() will not present any memory issues, even when sending large files, on its own. If you encounter an out of memory error ensure that output buffering is off with ob_get_level().

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

Nota: Sus?inrea contextelor a fost adaugata începând cu PHP 5.0.0. Pentru o descriere a contextelor, referi?i-va la Streams.

A se vedea ?i

  • fpassthru() - Output all remaining data on a file pointer
  • file() - Reads entire file into an array
  • fopen() - Opens file or URL
  • include - include
  • require - require
  • virtual() - Efectueaza o sub-interpelare Apache
  • file_get_contents() - Reads entire file into a string
  • Supported Protocols and Wrappers

popen
readlink
Filesystem Func?ii


Returns the target of a symbolic link

readfile
realpath_cache_get
Filesystem Func?ii
PHP Manual

readlink

(PHP 4, PHP 5, PHP 7)

readlink — Returns the target of a symbolic link

Descrierea

string readlink ( string $path )

readlink() does the same as the readlink C function.

Parametri

path

The symbolic link path.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Valorile întoarse

Returns the contents of the symbolic link path or FALSE on error.

Exemple

Example #1 readlink() example

<?php

// output e.g. /boot/vmlinux-2.4.20-xfs
echo readlink('/vmlinuz');

?>

A se vedea ?i

  • is_link() - Tells whether the filename is a symbolic link
  • symlink() - Creates a symbolic link
  • linkinfo() - Gets information about a link

readfile
realpath_cache_get
Filesystem Func?ii


Get realpath cache entries

readlink
realpath_cache_size
Filesystem Func?ii
PHP Manual

realpath_cache_get

(PHP 5 >= 5.3.2, PHP 7)

realpath_cache_get — Get realpath cache entries

Descrierea

array realpath_cache_get ( void )

Get the contents of the realpath cache.

Valorile întoarse

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.

Exemple

Example #1 realpath_cache_get() example

<?php
var_dump(realpath_cache_get());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)
  }
}

A se vedea ?i

  • realpath_cache_size() - Get realpath cache size

readlink
realpath_cache_size
Filesystem Func?ii


Get realpath cache size

realpath_cache_get
realpath
Filesystem Func?ii
PHP Manual

realpath_cache_size

(PHP 5 >= 5.3.2, PHP 7)

realpath_cache_size — Get realpath cache size

Descrierea

int realpath_cache_size ( void )

Get the amount of memory used by the realpath cache.

Valorile întoarse

Returns how much memory realpath cache is using.

Exemple

Example #1 realpath_cache_size() example

<?php
var_dump(realpath_cache_size());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(412)

A se vedea ?i

  • realpath_cache_get() - Get realpath cache entries
  • The realpath_cache_size configuration option

realpath_cache_get
realpath
Filesystem Func?ii


Returns canonicalized absolute pathname

realpath_cache_size
rename
Filesystem Func?ii
PHP Manual

realpath

(PHP 4, PHP 5, PHP 7)

realpath — Returns canonicalized absolute pathname

Descrierea

string realpath ( string $path )

realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and returns the canonicalized absolute pathname.

Parametri

path

The path being checked.

Nota:

Whilst a path must be supplied, the value can be blank or NULL In these cases, the value is interpreted as the current directory.

Valorile întoarse

Returns the canonicalized absolute pathname on success. The resulting path will have no symbolic link, '/./' or '/../' components. Trailing delimiters, such as \ and /, are also removed.

realpath() returns FALSE on failure, e.g. if the file does not exist.

Nota:

The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return FALSE.

Nota:

For case-insensitive filesystems realpath() may or may not normalize the character case.

Nota: Deoarece tipul întreg al PHP este cu semn ?i multe platforme utilizeaza întregi de 32 de bi?i, unele func?ii ale sistemului de fi?iere pot întoarce rezultate nea?teptate pentru fi?iere ce depa?esc 2GB.

Istoricul schimbarilor

Versiune | Descriere
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.2.1 | Prior to this version, realpath() returned FALSE if path is an empty string or NULL.

Exemple

Example #1 realpath() example

<?php
chdir('/var/www/');
echo realpath('./../../etc/passwd') . PHP_EOL;

echo realpath('/tmp/') . PHP_EOL;
?>

Exemplul de mai sus va afi?a:

/etc/passwd
/tmp

Example #2 realpath() on Windows

On windows realpath() will change unix style paths to windows style.

<?php
echo realpath('/windows/system32');

echo realpath('C:\Program Files\\');
?>

Exemplul de mai sus va afi?a:

C:\WINDOWS\System32
C:\Program Files

A se vedea ?i

  • basename() - Returns trailing name component of path
  • dirname() - Returns a parent directory's path
  • pathinfo() - Returns information about a file path

realpath_cache_size
rename
Filesystem Func?ii


Renames a file or directory

realpath
rewind
Filesystem Func?ii
PHP Manual

rename

(PHP 4, PHP 5, PHP 7)

rename — Renames a file or directory

Descrierea

bool rename ( string $oldname , string $newname [, resource $context ] )

Attempts to rename oldname to newname, moving it between directories if necessary. If newname exists, it will be overwritten.

Parametri

oldname

The old name.

Nota:

The wrapper used in oldname must match the wrapper used in newname.

newname

The new name.

context

Nota: Sus?inrea contextelor a fost adaugata începând cu PHP 5.0.0. Pentru o descriere a contextelor, referi?i-va la Streams.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #1 Example with rename()

<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>

A se vedea ?i

  • copy() - Copies file
  • unlink() - Deletes a file
  • move_uploaded_file() - Moves an uploaded file to a new location

realpath
rewind
Filesystem Func?ii


Rewind the position of a file pointer

rename
rmdir
Filesystem Func?ii
PHP Manual

rewind

(PHP 4, PHP 5, PHP 7)

rewind — Rewind the position of a file pointer

Descrierea

bool rewind ( resource $handle )

Sets the file position indicator for handle to the beginning of the file stream.

Nota:

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.

Parametri

handle

The file pointer must be valid, and must point to a file successfully opened by fopen().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Foolly long sentence.

A se vedea ?i

  • fread() - Binary-safe file read
  • fseek() - Seeks on a file pointer
  • ftell() - Returns the current position of the file read/write pointer
  • fwrite() - Binary-safe file write

rename
rmdir
Filesystem Func?ii


Removes directory

rewind
set_file_buffer
Filesystem Func?ii
PHP Manual

rmdir

(PHP 4, PHP 5, PHP 7)

rmdir — Removes directory

Descrierea

bool rmdir ( string $dirname [, resource $context ] )

Attempts to remove the directory named by dirname. The directory must be empty, and the relevant permissions must permit this. A E_WARNING level error will be generated on failure.

Parametri

dirname

Path to the directory.

context

Nota: Sus?inrea contextelor a fost adaugata începând cu PHP 5.0.0. Pentru o descriere a contextelor, referi?i-va la Streams.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.0.0 | As of PHP 5.0.0 rmdir() can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers for a listing of which wrappers support rmdir().

Exemple

Example #1 rmdir() example

<?php
if (!is_dir('examples')) {
    mkdir('examples');
}

rmdir('examples');
?>

Note

Nota: Când este activat modul securizat , PHP verifica daca directorul în care dori?i sa opera?i are acela?i UID (proprietar) ca ?i script-ul care se executa.

A se vedea ?i

  • is_dir() - Tells whether the filename is a directory
  • mkdir() - Makes directory
  • unlink() - Deletes a file

rewind
set_file_buffer
Filesystem Func?ii


Pseudonim pentru stream_set_write_buffer

rmdir
stat
Filesystem Func?ii
PHP Manual

set_file_buffer

(PHP 4, PHP 5, PHP 7)

set_file_buffer — Pseudonim pentru stream_set_write_buffer()

Descrierea

Aceasta func?ie este pseudonim pentru: stream_set_write_buffer().

rmdir
stat
Filesystem Func?ii


Gives information about a file

set_file_buffer
symlink
Filesystem Func?ii
PHP Manual

stat

(PHP 4, PHP 5, PHP 7)

stat — Gives information about a file

Descrierea

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.

Parametri

filename

Path to the file.

Valorile întoarse

stat() and fstat() result format
Numeric | Associative | 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.

Nota: Deoarece tipul întreg al PHP este cu semn ?i multe platforme utilizeaza întregi de 32 de bi?i, unele func?ii ale sistemului de fi?iere pot întoarce rezultate nea?teptate pentru fi?iere ce depa?esc 2GB.

Erori/Excep?ii

Upon failure, an E_WARNING is emitted.

Exemple

Example #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'];
?>

Example #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...';
    }
}
?>

Note

Nota:

Observa?i ca rezolu?ia timpului poate sa difere de la un sistem de fi?iere la altul.

Nota: Rezultatele acestei func?ii sunt stocate în cache. Accesa?i clearstatcache() pentru mai multe detalii.

Sfat

Începând cu PHP 5.0.0 aceasta func?ie poate fi utilizata de asemenea cu unele înveli?uri URL. Referi?i-va la Supported Protocols and Wrappers pentru a determina care înveli?uri sus?in familia de func?ionalitate stat().

A se vedea ?i

  • lstat() - Gives information about a file or symbolic link
  • fstat() - Gets information about a file using an open file pointer
  • filemtime() - Gets file modification time
  • filegroup() - Gets file group

set_file_buffer
symlink
Filesystem Func?ii


Creates a symbolic link

stat
tempnam
Filesystem Func?ii
PHP Manual

symlink

(PHP 4, PHP 5, PHP 7)

symlink — Creates a symbolic link

Descrierea

bool symlink ( string $target , string $link )

symlink() creates a symbolic link to the existing target with the specified name link.

Parametri

target

Target of the link.

link

The link name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Exemple

Example #1 Create a symbolic link

<?php
$target = 'uploads.php';
$link = 'uploads';
symlink($target, $link);

echo readlink($link);
?>

Note

Nota: Windows users should note that this function will only work if the system you run PHP from is Windows Vista/Windows Server 2008 or newer. Windows versions prior to that do not support symbolic links.

A se vedea ?i

  • link() - Create a hard link
  • readlink() - Returns the target of a symbolic link
  • linkinfo() - Gets information about a link

stat
tempnam
Filesystem Func?ii


Create file with unique file name

symlink
tmpfile
Filesystem Func?ii
PHP Manual

tempnam

(PHP 4, PHP 5, PHP 7)

tempnam — Create file with unique file name

Descrierea

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 or is not writable, tempnam() may generate a file in the system's temporary directory, and return the full path to that file, including its name.

Parametri

dir

The directory where the temporary filename will be created.

prefix

The prefix of the generated temporary filename.

Nota: Windows uses only the first three characters of prefix.

Valorile întoarse

Returns the new temporary filename (with path), or FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #1 tempnam() example

<?php
$tmpfname = tempnam("/tmp", "FOO");

$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

// do here something

unlink($tmpfname);
?>

Note

Nota: 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.

A se vedea ?i

  • tmpfile() - Creates a temporary file
  • sys_get_temp_dir() - Returns directory path used for temporary files
  • unlink() - Deletes a file

symlink
tmpfile
Filesystem Func?ii


Creates a temporary file

tempnam
touch
Filesystem Func?ii
PHP Manual

tmpfile

(PHP 4, PHP 5, PHP 7)

tmpfile — Creates a temporary file

Descrierea

resource tmpfile ( void )

Creates a temporary file with a unique name in read-write (w+) mode and returns a file handle .

The file is automatically removed when closed (for example, by calling fclose(), or when there are no remaining references to the file handle returned by tmpfile()), or when the script ends.

For details, consult your system documentation on the tmpfile(3) function, as well as the stdio.h header file.

Valorile întoarse

Returns a file handle, similar to the one returned by fopen(), for the new file sau FALSE în cazul e?ecului.

Exemple

Example #1 tmpfile() example

<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?>

Exemplul de mai sus va afi?a:

writing to tempfile

A se vedea ?i

  • tempnam() - Create file with unique file name
  • sys_get_temp_dir() - Returns directory path used for temporary files

tempnam
touch
Filesystem Func?ii


Sets access and modification time of file

tmpfile
umask
Filesystem Func?ii
PHP Manual

touch

(PHP 4, PHP 5, PHP 7)

touch — Sets access and modification time of file

Descrierea

bool touch ( string $filename [, int $time = time() [, int $atime ]] )

Attempts to set the access and modification times of the file named in the filename parameter to the value given in time. Note that the access time is always modified, regardless of the number of parameters.

If the file does not exist, it will be created.

Parametri

filename

The name of the file being touched.

time

The touch time. If time is not supplied, the current system time is used.

atime

If present, the access time of the given filename is set to the value of atime. Otherwise, it is set to the value passed to the time parameter. If neither are present, the current system time is used.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | It became possible to change the modification time of a directory under Windows.

Exemple

Example #1 touch() example

<?php
if (touch($filename)) {
    echo $filename . ' modification time has been changed to present time';
} else {
    echo 'Sorry, could not change modification time of ' . $filename;
}
?>

Example #2 touch() using the time parameter

<?php
// This is the touch time, we'll set it to one hour in the past.
$time = time() - 3600;

// Touch the file
if (!touch('some_file.txt', $time)) {
    echo 'Whoops, something went wrong...';
} else {
    echo 'Touched file with success';
}
?>

Note

Nota:

Observa?i ca rezolu?ia timpului poate sa difere de la un sistem de fi?iere la altul.

Avertizare

Prior to PHP 5.3.0 it was not possible to change the modification time of a directory with this function under Windows.

tmpfile
umask
Filesystem Func?ii


Changes the current umask

touch
unlink
Filesystem Func?ii
PHP Manual

umask

(PHP 4, PHP 5, PHP 7)

umask — Changes the current umask

Descrierea

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.

Parametri

mask

The new umask.

Valorile întoarse

umask() without arguments simply returns the current umask otherwise the old umask is returned.

Exemple

Example #1 umask() example

<?php
$old = umask(0);
chmod("/path/some_dir/some_file.txt", 0755);
umask($old);

// Checking
if ($old != umask()) {
    die('An error occurred while changing back the umask');
}
?>

Note

Nota:

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
Filesystem Func?ii


Deletes a file

umask
Inotify
Filesystem Func?ii
PHP Manual

unlink

(PHP 4, PHP 5, PHP 7)

unlink — Deletes a file

Descrierea

bool unlink ( string $filename [, resource $context ] )

Deletes filename. Similar to the Unix C unlink() function. An E_WARNING level error will be generated on failure.

Parametri

filename

Path to the file.

context

Nota: Sus?inrea contextelor a fost adaugata începând cu PHP 5.0.0. Pentru o descriere a contextelor, referi?i-va la Streams.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.0.0 | As of PHP 5.0.0 unlink() can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers for a listing of which wrappers support unlink().

Exemple

Example #1 Basic unlink() usage

<?php
$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Hello world!</h1>');
fclose($fh);

unlink('test.html');
?>

A se vedea ?i

  • rmdir() - Removes directory

umask
Inotify
Filesystem Func?ii


Inotify

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea / configurarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Inotify
    • 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
Introducere
Extensii referitoare la sistemul de fi?iere


Introducere

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
Instalarea / configurarea
Inotify


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea / configurarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Inotify


Necesita?i

This extension requires Linux 2.6.13 or newer, and a recent libC.

Instalarea / configurarea
Instalarea / configurarea
Instalarea / configurarea


Instalarea / configurarea
PHP Manual

Instalarea / configurarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/inotify.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea
PHP Manual


Configura?ia la rulare

Aceasta extensie nu are directive de configurare definite în php.ini.

Instalarea / configurarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

This extension defines a stream resource returned by inotify_init().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.

Nota: The events marked with an asterisk (*) above can occur for files in watched directories.

Tipurile resurselor
Func?ii Inotify
Inotify


Func?ii Inotify

Cuprins

  • 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
Constante predefinite
inotify_add_watch
Inotify


Add a watch to an initialized inotify instance

Func?ii Inotify
inotify_init
Func?ii Inotify
PHP Manual

inotify_add_watch

(PECL inotify >= 0.1.2)

inotify_add_watch — Add a watch to an initialized inotify instance

Descrierea

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.

Parametri

inotify_instance

Resursa întoarsa de inotify_init()

pathname

File or directory to watch

mask

Events to watch for. See Constante predefinite.

Valorile întoarse

The return value is a unique (inotify instance wide) watch descriptor.

A se vedea ?i

  • inotify_init() - Initialize an inotify instance

Func?ii Inotify
inotify_init
Func?ii Inotify


Initialize an inotify instance

inotify_add_watch
inotify_queue_len
Func?ii Inotify
PHP Manual

inotify_init

(PECL inotify >= 0.1.2)

inotify_init — Initialize an inotify instance

Descrierea

resource inotify_init ( void )

Initialize an inotify instance for use with inotify_add_watch()

Valorile întoarse

A stream resource or FALSE on error.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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)
  ),
);

A se vedea ?i

  • 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() - Closes an open file pointer

inotify_add_watch
inotify_queue_len
Func?ii Inotify


Return a number upper than zero if there are pending events

inotify_init
inotify_read
Func?ii Inotify
PHP Manual

inotify_queue_len

(PECL inotify >= 0.1.2)

inotify_queue_len — Return a number upper than zero if there are pending events

Descrierea

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.

Parametri

inotify_instance

Resursa întoarsa de inotify_init()

Valorile întoarse

Returns a number upper than zero if there are pending events.

A se vedea ?i

  • 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
Func?ii Inotify


Read events from an inotify instance

inotify_queue_len
inotify_rm_watch
Func?ii Inotify
PHP Manual

inotify_read

(PECL inotify >= 0.1.2)

inotify_read — Read events from an inotify instance

Descrierea

array inotify_read ( resource $inotify_instance )

Read inotify events from an inotify instance.

Parametri

inotify_instance

Resursa întoarsa de inotify_init()

Valorile întoarse

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)

A se vedea ?i

  • 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
Func?ii Inotify


Remove an existing watch from an inotify instance

inotify_read
Mimetype
Func?ii Inotify
PHP Manual

inotify_rm_watch

(PECL inotify >= 0.1.2)

inotify_rm_watch — Remove an existing watch from an inotify instance

Descrierea

bool inotify_rm_watch ( resource $inotify_instance , int $watch_descriptor )

inotify_rm_watch() removes the watch watch_descriptor from the inotify instance inotify_instance.

Parametri

inotify_instance

Resursa întoarsa de inotify_init()

watch_descriptor

Watch to remove from the instance

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • inotify_init() - Initialize an inotify instance

inotify_read
Mimetype
Func?ii Inotify


Mimetype

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
inotify_rm_watch
Introducere
Extensii referitoare la sistemul de fi?iere


Introducere

Avertizare

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
Instalarea / configurarea
Mimetype


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Mimetype


Instalarea

Avertizare

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.

Nota:

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.

Nota: 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.

Example #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

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Mimetype configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

mime_magic.debug bool

Enable/disable debugging.

mime_magic.magicfile string

The path to the magic.mime file.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Proctitle
Mimetype


Proctitle

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii proctitle
    • setproctitle — Set the process title
    • setthreadtitle — Set the thread title
Constante predefinite
Introducere
Extensii referitoare la sistemul de fi?iere


Introducere

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
Instalarea / configurarea
Proctitle


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Proctitle


Necesita?i

Nothing special.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/proctitle.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii proctitle
Proctitle


Func?ii proctitle

Cuprins

  • setproctitle — Set the process title
  • setthreadtitle — Set the thread title
Constante predefinite
setproctitle
Proctitle


Set the process title

Func?ii proctitle
setthreadtitle
Func?ii proctitle
PHP Manual

setproctitle

(PECL proctitle >= 0.1.0)

setproctitle — Set the process title

Descrierea

void setproctitle ( string $title )

Sets the process title of the current process.

Parametri

title

The title to use as the process title.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 setproctitle() example

Running the example below will change the process title (visible with ps a for example).

<?php
setproctitle("myscript");
?>

Exemplul de mai sus va afi?a ceva similar cu:

$ ps a
  PID TTY      STAT   TIME COMMAND
 1168 pts/3    S      0:00 myscript

A se vedea ?i

  • cli_set_process_title() - Sets the process title
  • pcntl_fork() - Forks the currently running process
  • setthreadtitle() - Set the thread title
Func?ii proctitle
setthreadtitle
Func?ii proctitle


Set the thread title

setproctitle
xattr
Func?ii proctitle
PHP Manual

setthreadtitle

(PECL proctitle >= 0.1.2)

setthreadtitle — Set the thread title

Descrierea

bool setthreadtitle ( string $title )

Sets the thread title.

Parametri

title

The title to use as the thread title.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 setthreadtitle() example

Running the example below will change the thread title (visible with ps c for example).

<?php
setthreadtitle("myscript");
?>

Exemplul de mai sus va afi?a ceva similar cu:

$ ps c
  PID TTY      STAT   TIME COMMAND
 1178 pts/3    S      0:00 myscript

A se vedea ?i

  • pcntl_fork() - Forks the currently running process
  • setproctitle() - Set the process title
setproctitle
xattr
Func?ii proctitle


xattr

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii xattr
    • 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
Introducere
Extensii referitoare la sistemul de fi?iere


Introducere

Extensia xattr permite manipularea cu atributele extinse într-un sistem de fi?iere.

xattr
Instalarea / configurarea
xattr


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
xattr


Necesita?i

To use xattr, you will need libattr installed. It is available at » http://oss.sgi.com/projects/xfs/.

Nota:

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/xattr.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
Func?ii xattr
xattr


Func?ii xattr

Cuprins

  • 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
Constante predefinite
xattr_get
xattr


Get an extended attribute

Func?ii xattr
xattr_list
Func?ii xattr
PHP Manual

xattr_get

(PECL xattr >= 0.9.0)

xattr_get — Get an extended attribute

Descrierea

string xattr_get ( string $filename , string $name [, int $flags = 0 ] )

This function gets the value of an extended attribute of a file.

Atributele extinse au doua spa?ii de nume diferite: spa?iul de nume al utilizatorilor ?i spa?iul de nume root. Spa?iul de nume al utilizatorilor e disponibil tuturor, în timp ce spa?iul de nume root este disponibil numai utilizatorilor cu privilegii de root. xattr opereaza implicit în spa?iul utilizatorilor, dar aceasta poate fi schimbat cu parametrul flags.

Parametri

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.

Valorile întoarse

Returns a string containing the value or FALSE if the attribute doesn't exist.

Exemple

Example #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 ... */

?>

A se vedea ?i

  • xattr_list() - Get a list of extended attributes
  • xattr_set() - Set an extended attribute
  • xattr_remove() - Remove an extended attribute

Func?ii xattr
xattr_list
Func?ii xattr


Get a list of extended attributes

xattr_get
xattr_remove
Func?ii xattr
PHP Manual

xattr_list

(PECL xattr >= 0.9.0)

xattr_list — Get a list of extended attributes

Descrierea

array xattr_list ( string $filename [, int $flags = 0 ] )

This functions gets a list of names of extended attributes of a file.

Atributele extinse au doua spa?ii de nume diferite: spa?iul de nume al utilizatorilor ?i spa?iul de nume root. Spa?iul de nume al utilizatorilor e disponibil tuturor, în timp ce spa?iul de nume root este disponibil numai utilizatorilor cu privilegii de root. xattr opereaza implicit în spa?iul utilizatorilor, dar aceasta poate fi schimbat cu parametrul flags.

Parametri

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.

Valorile întoarse

This function returns an array with names of extended attributes.

Exemple

Example #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);
}

?>

A se vedea ?i

  • xattr_get() - Get an extended attribute

xattr_get
xattr_remove
Func?ii xattr


Remove an extended attribute

xattr_list
xattr_set
Func?ii xattr
PHP Manual

xattr_remove

(PECL xattr >= 0.9.0)

xattr_remove — Remove an extended attribute

Descrierea

bool xattr_remove ( string $filename , string $name [, int $flags = 0 ] )

This function removes an extended attribute of a file.

Atributele extinse au doua spa?ii de nume diferite: spa?iul de nume al utilizatorilor ?i spa?iul de nume root. Spa?iul de nume al utilizatorilor e disponibil tuturor, în timp ce spa?iul de nume root este disponibil numai utilizatorilor cu privilegii de root. xattr opereaza implicit în spa?iul utilizatorilor, dar aceasta poate fi schimbat cu parametrul flags.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
}
?>

A se vedea ?i

  • xattr_list() - Get a list of extended attributes
  • xattr_set() - Set an extended attribute
  • xattr_get() - Get an extended attribute

xattr_list
xattr_set
Func?ii xattr


Set an extended attribute

xattr_remove
xattr_supported
Func?ii xattr
PHP Manual

xattr_set

(PECL xattr >= 0.9.0)

xattr_set — Set an extended attribute

Descrierea

bool xattr_set ( string $filename , string $name , string $value [, int $flags = 0 ] )

This function sets the value of an extended attribute of a file.

Atributele extinse au doua spa?ii de nume diferite: spa?iul de nume al utilizatorilor ?i spa?iul de nume root. Spa?iul de nume al utilizatorilor e disponibil tuturor, în timp ce spa?iul de nume root este disponibil numai utilizatorilor cu privilegii de root. xattr opereaza implicit în spa?iul utilizatorilor, dar aceasta poate fi schimbat cu parametrul flags.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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'));
?>

A se vedea ?i

  • xattr_get() - Get an extended attribute
  • xattr_remove() - Remove an extended attribute

xattr_remove
xattr_supported
Func?ii xattr


Check if filesystem supports extended attributes

xattr_set
xdiff
Func?ii xattr
PHP Manual

xattr_supported

(PECL xattr >= 1.0.0)

xattr_supported — Check if filesystem supports extended attributes

Descrierea

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.

Parametri

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.

Valorile întoarse

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).

Exemple

Example #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 ... */
}

?>

A se vedea ?i

  • xattr_get() - Get an extended attribute
  • xattr_list() - Get a list of extended attributes

xattr_set
xdiff
Func?ii xattr


xdiff

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii xdiff
    • 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
Introducere
Extensii referitoare la sistemul de fi?iere


Introducere

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
Instalarea / configurarea
xdiff


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
xdiff


Necesita?i

To use xdiff, you will need libxdiff installed, available on the libxdiff homepage » http://www.xmailserver.org/xdiff-lib.html.

Nota:

You'll need at least libxdiff 0.7 for these functions to be aware of memory_limit.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/xdiff.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
Func?ii xdiff
xdiff


Func?ii xdiff

Cuprins

  • 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
Constante predefinite
xdiff_file_bdiff_size
xdiff


Read a size of file created by applying a binary diff

Func?ii xdiff
xdiff_file_bdiff
Func?ii xdiff
PHP Manual

xdiff_file_bdiff_size

(PECL xdiff >= 1.5.0)

xdiff_file_bdiff_size — Read a size of file created by applying a binary diff

Descrierea

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.

Parametri

file

The path to the binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

Valorile întoarse

Returns the size of file that would be created.

Exemple

Example #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";
?>

A se vedea ?i

  • 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

Func?ii xdiff
xdiff_file_bdiff
Func?ii xdiff


Make binary diff of two files

xdiff_file_bdiff_size
xdiff_file_bpatch
Func?ii xdiff
PHP Manual

xdiff_file_bdiff

(PECL xdiff >= 1.5.0)

xdiff_file_bdiff — Make binary diff of two files

Descrierea

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().

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');
?>

Note

Nota:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

A se vedea ?i

  • xdiff_file_bpatch() - Patch a file with a binary diff

xdiff_file_bdiff_size
xdiff_file_bpatch
Func?ii xdiff


Patch a file with a binary diff

xdiff_file_bdiff
xdiff_file_diff_binary
Func?ii xdiff
PHP Manual

xdiff_file_bpatch

(PECL xdiff >= 1.5.0)

xdiff_file_bpatch — Patch a file with a binary diff

Descrierea

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.

Parametri

file

The original file.

patch

The binary patch file.

dest

Path of the resulting file.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
}

?>

Note

Nota:

Both files (file and patch) will be loaded into memory so ensure that your memory_limit is set high enough.

A se vedea ?i

  • 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
Func?ii xdiff


Alias of xdiff_file_bdiff

xdiff_file_bpatch
xdiff_file_diff
Func?ii xdiff
PHP Manual

xdiff_file_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_file_diff_binary — Alias of xdiff_file_bdiff

Descrierea

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().

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');
?>

Note

Nota:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

A se vedea ?i

  • 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
Func?ii xdiff


Make unified diff of two files

xdiff_file_diff_binary
xdiff_file_merge3
Func?ii xdiff
PHP Manual

xdiff_file_diff

(PECL xdiff >= 0.2.0)

xdiff_file_diff — Make unified diff of two files

Descrierea

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).

Parametri

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Note

Nota:

This function doesn't work well with binary files. To make diff of binary files use xdiff_file_bdiff()/xdiff_file_rabdiff() function.

A se vedea ?i

  • xdiff_file_patch() - Patch a file with an unified diff

xdiff_file_diff_binary
xdiff_file_merge3
Func?ii xdiff


Merge 3 files into one

xdiff_file_diff
xdiff_file_patch_binary
Func?ii xdiff
PHP Manual

xdiff_file_merge3

(PECL xdiff >= 0.2.0)

xdiff_file_merge3 — Merge 3 files into one

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE if merge was successful, string with rejected chunks if it was not or FALSE if an internal error happened.

Exemple

Example #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;
}
?>

A se vedea ?i

  • xdiff_string_merge3() - Merge 3 strings into one

xdiff_file_diff
xdiff_file_patch_binary
Func?ii xdiff


Alias of xdiff_file_bpatch

xdiff_file_merge3
xdiff_file_patch
Func?ii xdiff
PHP Manual

xdiff_file_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_file_patch_binary — Alias of xdiff_file_bpatch

Descrierea

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().

Parametri

file

The original file.

patch

The binary patch file.

dest

Path of the resulting file.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
}

?>

Note

Nota:

Both files (file and patch) will be loaded into memory so ensure that your memory_limit is set high enough.

A se vedea ?i

  • xdiff_string_patch_binary() - Alias of xdiff_string_bpatch

xdiff_file_merge3
xdiff_file_patch
Func?ii xdiff


Patch a file with an unified diff

xdiff_file_patch_binary
xdiff_file_rabdiff
Func?ii xdiff
PHP Manual

xdiff_file_patch

(PECL xdiff >= 0.2.0)

xdiff_file_patch — Patch a file with an unified diff

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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;
}

?>

Example #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;
}

?>

A se vedea ?i

  • xdiff_file_diff() - Make unified diff of two files

xdiff_file_patch_binary
xdiff_file_rabdiff
Func?ii xdiff


Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

xdiff_file_patch
xdiff_string_bdiff_size
Func?ii xdiff
PHP Manual

xdiff_file_rabdiff

(PECL xdiff >= 1.5.0)

xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');
?>

Note

Nota:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

A se vedea ?i

  • xdiff_file_bpatch() - Patch a file with a binary diff

xdiff_file_patch
xdiff_string_bdiff_size
Func?ii xdiff


Read a size of file created by applying a binary diff

xdiff_file_rabdiff
xdiff_string_bdiff
Func?ii xdiff
PHP Manual

xdiff_string_bdiff_size

(PECL xdiff >= 1.5.0)

xdiff_string_bdiff_size — Read a size of file created by applying a binary diff

Descrierea

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.

Parametri

patch

The binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

Valorile întoarse

Returns the size of file that would be created.

Exemple

Example #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";
?>

A se vedea ?i

  • 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
Func?ii xdiff


Make binary diff of two strings

xdiff_string_bdiff_size
xdiff_string_bpatch
Func?ii xdiff
PHP Manual

xdiff_string_bdiff

(PECL xdiff >= 1.5.0)

xdiff_string_bdiff — Make binary diff of two strings

Descrierea

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().

Parametri

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Valorile întoarse

Returns string with binary diff containing differences between "old" and "new" data or FALSE if an internal error occurred.

A se vedea ?i

  • xdiff_string_bpatch() - Patch a string with a binary diff

xdiff_string_bdiff_size
xdiff_string_bpatch
Func?ii xdiff


Patch a string with a binary diff

xdiff_string_bdiff
xdiff_string_diff_binary
Func?ii xdiff
PHP Manual

xdiff_string_bpatch

(PECL xdiff >= 1.5.0)

xdiff_string_bpatch — Patch a string with a binary diff

Descrierea

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.

Parametri

str

The original binary string.

patch

The binary patch string.

Valorile întoarse

Returns the patched string, or FALSE on error.

A se vedea ?i

  • 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
Func?ii xdiff


Alias of xdiff_string_bdiff

xdiff_string_bpatch
xdiff_string_diff
Func?ii xdiff
PHP Manual

xdiff_string_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_string_diff_binary — Alias of xdiff_string_bdiff

Descrierea

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().

Parametri

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Valorile întoarse

Returns string with result or FALSE if an internal error happened.

A se vedea ?i

  • 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
Func?ii xdiff


Make unified diff of two strings

xdiff_string_diff_binary
xdiff_string_merge3
Func?ii xdiff
PHP Manual

xdiff_string_diff

(PECL xdiff >= 0.2.0)

xdiff_string_diff — Make unified diff of two strings

Descrierea

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).

Parametri

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).

Valorile întoarse

Returns string with resulting diff or FALSE if an internal error happened.

Exemple

Example #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;
}

?>

Note

Nota:

This function doesn't work well with binary strings. To make diff of binary strings use xdiff_string_bdiff()/xdiff_string_rabdiff().

A se vedea ?i

  • xdiff_string_patch() - Patch a string with an unified diff

xdiff_string_diff_binary
xdiff_string_merge3
Func?ii xdiff


Merge 3 strings into one

xdiff_string_diff
xdiff_string_patch_binary
Func?ii xdiff
PHP Manual

xdiff_string_merge3

(PECL xdiff >= 0.2.0)

xdiff_string_merge3 — Merge 3 strings into one

Descrierea

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_data1 and new_data2 are modified versions of an original. An optional error is used to pass any rejected parts during merging process.

Parametri

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.

Valorile întoarse

Returns the merged string, FALSE if an internal error happened, or TRUE if merged string is empty.

A se vedea ?i

  • xdiff_file_merge3() - Merge 3 files into one

xdiff_string_diff
xdiff_string_patch_binary
Func?ii xdiff


Alias of xdiff_string_bpatch

xdiff_string_merge3
xdiff_string_patch
Func?ii xdiff
PHP Manual

xdiff_string_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_string_patch_binary — Alias of xdiff_string_bpatch

Descrierea

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().

Parametri

str

The original binary string.

patch

The binary patch string.

Valorile întoarse

Returns the patched string, or FALSE on error.

A se vedea ?i

  • 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
Func?ii xdiff


Patch a string with an unified diff

xdiff_string_patch_binary
xdiff_string_rabdiff
Func?ii xdiff
PHP Manual

xdiff_string_patch

(PECL xdiff >= 0.2.0)

xdiff_string_patch — Patch a string with an unified diff

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the patched string, or FALSE on error.

Exemple

Example #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;
}

?>

A se vedea ?i

  • xdiff_string_diff() - Make unified diff of two strings

xdiff_string_patch_binary
xdiff_string_rabdiff
Func?ii xdiff


Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

xdiff_string_patch
Sus?inerea limbajului uman ?i a codificarii caracterelor
Func?ii xdiff
PHP Manual

xdiff_string_rabdiff

(PECL xdiff >= 1.5.0)

xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

Descrierea

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.

Parametri

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Valorile întoarse

Returns string with binary diff containing differences between "old" and "new" data or FALSE if an internal error occurred.

A se vedea ?i

  • xdiff_string_bpatch() - Patch a string with a binary diff

xdiff_string_patch
Sus?inerea limbajului uman ?i a codificarii caracterelor
Func?ii xdiff


Sus?inerea limbajului uman ?i a codificarii caracterelor

  • Enchant — Enchant spelling library
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Enchant
  • FriBiDi
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii FriBiDi
  • Gender — Determine gender of firstnames
    • Introducere
    • Instalarea / configurarea
    • Exemple
    • Gender\Gender — The Gender\Gender class
  • Gettext
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Gettext
  • iconv
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii iconv
  • intl — Internationalization Functions
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Collator — The Collator class
    • NumberFormatter — The NumberFormatter class
    • Locale — The Locale class
    • Normalizer — The Normalizer class
    • MessageFormatter — The MessageFormatter class
    • IntlCalendar — The IntlCalendar class
    • IntlTimeZone — The IntlTimeZone class
    • IntlDateFormatter — The IntlDateFormatter class
    • ResourceBundle — The ResourceBundle class
    • Spoofchecker — The Spoofchecker class
    • Transliterator — The Transliterator class
    • IntlBreakIterator — The IntlBreakIterator class
    • IntlRuleBasedBreakIterator — The IntlRuleBasedBreakIterator class
    • IntlCodePointBreakIterator — The IntlCodePointBreakIterator class
    • IntlPartsIterator — The IntlPartsIterator class
    • UConverter — The UConverter class
    • Func?ii Grapheme
    • Func?ii IDN
    • IntlChar
    • IntlException — Exception class for intl errors
    • IntlIterator — The IntlIterator class
    • Func?ii intl
  • Stringuri multioctet
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Summaries of supported encodings
    • Basics of Japanese multi-byte encodings
    • HTTP Input and Output
    • Supported Character Encodings
    • Function Overloading Feature
    • Cerin?e pentru codarea caracterelor în PHP
    • Multibyte String Func?ii
  • Pspell
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Pspell
  • Recode — GNU Recode
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Recode
xdiff_string_rabdiff
Enchant
Informa?ii de referin?a despre func?ii


Enchant spelling library

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii Enchant
    • 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_dict_path — Get the directory path for a given backend
    • 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_dict_path — Set the directory path for a given backend
    • 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
Sus?inerea limbajului uman ?i a codificarii caracterelor
Introducere
Sus?inerea limbajului uman ?i a codificarii caracterelor


Introducere

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."

Enchant 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
Instalarea / configurarea
Enchant


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Enchant


Necesita?i

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/.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

There are two types of resources in this extension. The first one is the broker (backends manager) and the second is for the dictionary.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

ENCHANT_MYSPELL (integer)
Tipul Dictionary pentru MySpell. Utilizat în enchant_broker_get_dict_path() ?i enchant_broker_set_dict_path().
ENCHANT_ISPELL (integer)
Tipul Dictionary pentru Ispell. Utilizat în enchant_broker_get_dict_path() ?i enchant_broker_set_dict_path().

Tipurile resurselor
Exemple
Enchant


Exemple

Example #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);
?>
Constante predefinite
Func?ii Enchant
Enchant


Func?ii Enchant

Cuprins

  • 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_dict_path — Get the directory path for a given backend
  • 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_dict_path — Set the directory path for a given backend
  • 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
Exemple
enchant_broker_describe
Enchant


Enumerates the Enchant providers

Func?ii Enchant
enchant_broker_dict_exists
Func?ii Enchant
PHP Manual

enchant_broker_describe

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0)

enchant_broker_describe — Enumerates the Enchant providers

Descrierea

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().

Parametri

broker

Broker resource

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

)

Func?ii Enchant
enchant_broker_dict_exists
Func?ii Enchant


Whether a dictionary exists or not. Using non-empty tag

enchant_broker_describe
enchant_broker_free_dict
Func?ii Enchant
PHP Manual

enchant_broker_dict_exists

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag

Descrierea

bool enchant_broker_dict_exists ( resource $broker , string $tag )

Tells if a dictionary exists or not, using a non-empty tags

Parametri

broker

Broker resource

tag

non-empty tag in the LOCALE format, ex: us_US, ch_DE, etc.

Valorile întoarse

Returns TRUE when the tag exist or FALSE when not.

Exemple

Example #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";
}
?>

A se vedea ?i

  • enchant_broker_describe() - Enumerates the Enchant providers

enchant_broker_describe
enchant_broker_free_dict
Func?ii Enchant


Free a dictionary resource

enchant_broker_dict_exists
enchant_broker_free
Func?ii Enchant
PHP Manual

enchant_broker_free_dict

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_free_dict — Free a dictionary resource

Descrierea

bool enchant_broker_free_dict ( resource $dict )

Free a dictionary resource.

Parametri

dict

Dictionary resource.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii Enchant


Free the broker resource and its dictionnaries

enchant_broker_free_dict
enchant_broker_get_dict_path
Func?ii Enchant
PHP Manual

enchant_broker_free

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_free — Free the broker resource and its dictionnaries

Descrierea

bool enchant_broker_free ( resource $broker )

Free a broker resource with all its dictionaries.

Parametri

broker

Broker resource

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • enchant_broker_init() - create a new broker object capable of requesting

enchant_broker_free_dict
enchant_broker_get_dict_path
Func?ii Enchant


Get the directory path for a given backend

enchant_broker_free
enchant_broker_get_error
Func?ii Enchant
PHP Manual

enchant_broker_get_dict_path

(PHP 5 >= 5.3.1, PHP 7, PECL enchant >= 1.0.1)

enchant_broker_get_dict_path — Get the directory path for a given backend

Descrierea

bool enchant_broker_get_dict_path ( resource $broker , int $dict_type )

Get the directory path for a given backend.

Parametri

broker

Broker resource.

dict_type

The type of the dictionaries, i.e. ENCHANT_MYSPELL or ENCHANT_ISPELL.

Valorile întoarse

Returns the path of the dictionary directory on success sau FALSE în cazul e?ecului.

A se vedea ?i

  • enchant_broker_set_dict_path() - Set the directory path for a given backend

enchant_broker_free
enchant_broker_get_error
Func?ii Enchant


Returns the last error of the broker

enchant_broker_get_dict_path
enchant_broker_init
Func?ii Enchant
PHP Manual

enchant_broker_get_error

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_get_error — Returns the last error of the broker

Descrierea

string enchant_broker_get_error ( resource $broker )

Returns the last error which occurred in this broker.

Parametri

broker

Broker resource.

Valorile întoarse

Return the msg string if an error was found or FALSE

enchant_broker_get_dict_path
enchant_broker_init
Func?ii Enchant


create a new broker object capable of requesting

enchant_broker_get_error
enchant_broker_list_dicts
Func?ii Enchant
PHP Manual

enchant_broker_init

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_init — create a new broker object capable of requesting

Descrierea

resource enchant_broker_init ( void )

Parametri

Valorile întoarse

Returns a broker resource on success or FALSE.

A se vedea ?i

  • enchant_broker_free() - Free the broker resource and its dictionnaries

enchant_broker_get_error
enchant_broker_list_dicts
Func?ii Enchant


Returns a list of available dictionaries

enchant_broker_init
enchant_broker_request_dict
Func?ii Enchant
PHP Manual

enchant_broker_list_dicts

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 1.0.1)

enchant_broker_list_dicts — Returns a list of available dictionaries

Descrierea

mixed enchant_broker_list_dicts ( resource $broker )

Returns a list of available dictionaries with their details.

Parametri

broker

Broker resource

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 List all available dictionaries for one broker

<?php
$r = enchant_broker_init();
$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

)

A se vedea ?i

  • enchant_broker_describe() - Enumerates the Enchant providers

enchant_broker_init
enchant_broker_request_dict
Func?ii Enchant


create a new dictionary using a tag

enchant_broker_list_dicts
enchant_broker_request_pwl_dict
Func?ii Enchant
PHP Manual

enchant_broker_request_dict

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_request_dict — create a new dictionary using a tag

Descrierea

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", ...)

Parametri

broker

Broker resource

tag

A tag describing the locale, for example en_US, de_DE

Valorile întoarse

Returns a dictionary resource on success sau FALSE în cazul e?ecului.

Exemple

Example #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);
}
?>

A se vedea ?i

  • 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
Func?ii Enchant


creates a dictionary using a PWL file

enchant_broker_request_dict
enchant_broker_set_dict_path
Func?ii Enchant
PHP Manual

enchant_broker_request_pwl_dict

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_request_pwl_dict — creates a dictionary using a PWL file

Descrierea

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.

Parametri

broker

Broker resource

filename

Path to the PWL file. If there is no such file, a new one will be created if possible.

Valorile întoarse

Returns a dictionary resource on success sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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_dict_path
Func?ii Enchant


Set the directory path for a given backend

enchant_broker_request_pwl_dict
enchant_broker_set_ordering
Func?ii Enchant
PHP Manual

enchant_broker_set_dict_path

(PHP 5 >= 5.3.1, PHP 7, PECL enchant >= 1.0.1)

enchant_broker_set_dict_path — Set the directory path for a given backend

Descrierea

bool enchant_broker_set_dict_path ( resource $broker , int $dict_type , string $value )

Set the directory path for a given backend.

Parametri

broker

Broker resource.

dict_type

The type of the dictionaries, i.e. ENCHANT_MYSPELL or ENCHANT_ISPELL.

value

The path of the dictionary directory.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • enchant_broker_get_dict_path() - Get the directory path for a given backend

enchant_broker_request_pwl_dict
enchant_broker_set_ordering
Func?ii Enchant


Declares a preference of dictionaries to use for the language

enchant_broker_set_dict_path
enchant_dict_add_to_personal
Func?ii Enchant
PHP Manual

enchant_broker_set_ordering

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

enchant_broker_set_dict_path
enchant_dict_add_to_personal
Func?ii Enchant


add a word to personal word list

enchant_broker_set_ordering
enchant_dict_add_to_session
Func?ii Enchant
PHP Manual

enchant_dict_add_to_personal

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_add_to_personal — add a word to personal word list

Descrierea

void enchant_dict_add_to_personal ( resource $dict , string $word )

Add a word to personal word list of the given dictionary.

Parametri

dict

Dictionary resource

word

The word to add

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Example #1 Adding a word to a PWL

<?php

$filename = './my_word_list.pwl';
$word = 'Supercalifragilisticexpialidocious';

$broker = enchant_broker_init();
$dict = enchant_broker_request_pwl_dict($broker, $filename);

enchant_dict_add_to_personal($dict, $word);

enchant_broker_free($broker);

?>

A se vedea ?i

  • 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
Func?ii Enchant


add 'word' to this spell-checking session

enchant_dict_add_to_personal
enchant_dict_check
Func?ii Enchant
PHP Manual

enchant_dict_add_to_session

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_add_to_session — add 'word' to this spell-checking session

Descrierea

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.

Parametri

dict

Dictionary resource

word

The word to add

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • enchant_broker_request_dict() - create a new dictionary using a tag

enchant_dict_add_to_personal
enchant_dict_check
Func?ii Enchant


Check whether a word is correctly spelled or not

enchant_dict_add_to_session
enchant_dict_describe
Func?ii Enchant
PHP Manual

enchant_dict_check

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_check — Check whether a word is correctly spelled or not

Descrierea

bool enchant_dict_check ( resource $dict , string $word )

If the word is correctly spelled return TRUE, otherwise return FALSE

Parametri

dict

Dictionary resource

word

The word to check

Valorile întoarse

Returns TRUE if the word is spelled correctly, FALSE if not.

enchant_dict_add_to_session
enchant_dict_describe
Func?ii Enchant


Describes an individual dictionary

enchant_dict_check
enchant_dict_get_error
Func?ii Enchant
PHP Manual

enchant_dict_describe

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_describe — Describes an individual dictionary

Descrierea

mixed enchant_dict_describe ( resource $dict )

Returns the details of the dictionary.

Parametri

dict

Dictionary resource

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [lang] => en_US
    [name] => aspell
    [desc] => Aspell Provider
    [file] => /usr/lib/enchant/libenchant_aspell.so
)

enchant_dict_check
enchant_dict_get_error
Func?ii Enchant


Returns the last error of the current spelling-session

enchant_dict_describe
enchant_dict_is_in_session
Func?ii Enchant
PHP Manual

enchant_dict_get_error

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_get_error — Returns the last error of the current spelling-session

Descrierea

string enchant_dict_get_error ( resource $dict )

Returns the last error of the current spelling-session

Parametri

dict

Dictinaray resource

Valorile întoarse

Returns the error message as string or FALSE if no error occurred.

enchant_dict_describe
enchant_dict_is_in_session
Func?ii Enchant


whether or not 'word' exists in this spelling-session

enchant_dict_get_error
enchant_dict_quick_check
Func?ii Enchant
PHP Manual

enchant_dict_is_in_session

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_is_in_session — whether or not 'word' exists in this spelling-session

Descrierea

bool enchant_dict_is_in_session ( resource $dict , string $word )

Tells whether or not a word already exists in the current session.

Parametri

dict

Dictionary resource

word

The word to lookup

Valorile întoarse

Returns TRUE if the word exists or FALSE

A se vedea ?i

  • enchant_dict_add_to_session() - add 'word' to this spell-checking session

enchant_dict_get_error
enchant_dict_quick_check
Func?ii Enchant


Check the word is correctly spelled and provide suggestions

enchant_dict_is_in_session
enchant_dict_store_replacement
Func?ii Enchant
PHP Manual

enchant_dict_quick_check

(PHP 5 >= 5.3.0, PHP 7, PECL enchant:0.2.0-1.0.1)

enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions

Descrierea

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.

Parametri

dict

Dictionary resource

word

The word to check

suggestions

If the word is not correctly spelled, this variable will contain an array of suggestions.

Valorile întoarse

Returns TRUE if the word is correctly spelled or FALSE

Exemple

Example #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);
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • 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
Func?ii Enchant


Add a correction for a word

enchant_dict_quick_check
enchant_dict_suggest
Func?ii Enchant
PHP Manual

enchant_dict_store_replacement

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_store_replacement — Add a correction for a word

Descrierea

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.

Parametri

dict

Dictionary resource

mis

The work to fix

cor

The correct word

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

enchant_dict_quick_check
enchant_dict_suggest
Func?ii Enchant


Will return a list of values if any of those pre-conditions are not met

enchant_dict_store_replacement
FriBiDi
Func?ii Enchant
PHP Manual

enchant_dict_suggest

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met

Descrierea

array enchant_dict_suggest ( resource $dict , string $word )

Parametri

dict

Dictionary resource

word

Word to use for the suggestions.

Valorile întoarse

Will returns an array of suggestions if the word is bad spelled.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii Enchant


FriBiDi

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii FriBiDi
    • fribidi_log2vis — Convert a logical string to a visual one
enchant_dict_suggest
Introducere
Sus?inerea limbajului uman ?i a codificarii caracterelor


Introducere

FriBiDi este o implementare gratuita a » Algoritmului Unicode Bidirec?ional.

FriBiDi
Instalarea / configurarea
FriBiDi


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
FriBiDi


Necesita?i

You must download and install the » FriBiDi package.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP. Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » 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. O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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
Tipurile resurselor
Func?ii FriBiDi
FriBiDi


Func?ii FriBiDi

Cuprins

  • fribidi_log2vis — Convert a logical string to a visual one
Constante predefinite
fribidi_log2vis
FriBiDi


Convert a logical string to a visual one

Func?ii FriBiDi
Gender
Func?ii FriBiDi
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

Descrierea

string fribidi_log2vis ( string $str , string $direction , int $charset )

Converts a logical string to a visual one.

Parametri

str

The logical string.

direction

One of FRIBIDI_RTL, FRIBIDI_LTR or FRIBIDI_AUTO.

charset

One of the FRIBIDI_CHARSET_XXX constants.

Valorile întoarse

Returns the visual string on success sau FALSE în cazul e?ecului.

Func?ii FriBiDi
Gender
Func?ii FriBiDi


Determine gender of firstnames

  • Introducere
  • Instalarea / configurarea
    • Instalarea
  • Exemple
    • Usage example.
  • Gender\Gender — The Gender\Gender class
    • Gender\Gender::connect — Connect to an external name dictionary.
    • Gender\Gender::__construct — Construct the Gender object.
    • Gender\Gender::country — Get textual country representation
    • Gender\Gender::get — Get gender of a name.
    • Gender\Gender::isNick — Check if the name0 is an alias of the name1.
    • Gender\Gender::similarNames — Get similar names.
fribidi_log2vis
Introducere
Sus?inerea limbajului uman ?i a codificarii caracterelor


Introducere

Gender PHP extension is a port of the gender.c program originally written by Joerg Michael. The main purpose is to find out the gender of firstnames. The current database contains >40000 firstnames from 54 countries.

Gender
Instalarea / configurarea
Gender


Instalarea / configurarea

Cuprins

  • Instalarea
Introducere
Instalarea
Gender


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/gender.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/gender/.

Instalarea / configurarea
Exemple
Instalarea / configurarea


Exemple

Cuprins

  • Usage example.
Instalarea
Usage example.
Gender


Usage example.

Gender class usage example.

Example #1 Usage example.

<?php

namespace Gender;

$gender = new Gender;

$name = "Milene";
$country = Gender::FRANCE;

$result = $gender->get($name, $country);

$data = $gender->country($country);

switch($result) {
    case Gender::IS_FEMALE:
        printf("The name %s is female in %s\n", $name, $data['country']);
    break;

    case Gender::IS_MOSTLY_FEMALE:
        printf("The name %s is mostly female in %s\n", $name, $data['country']);
    break;

    case Gender::IS_MALE:
        printf("The name %s is male in %s\n", $name, $data['country']);
    break;

    case Gender::IS_MOSTLY_MALE:
        printf("The name %s is mostly male in %s\n", $name, $data['country']);
    break;

    case Gender::IS_UNISEX_NAME:
        printf("The name %s is unisex in %s\n", $name, $data['country']);
    break;

    case Gender::IS_A_COUPLE:
        printf("The name %s is both male and female in %s\n", $name, $data['country']);
    break;

    case Gender::NAME_NOT_FOUND:
        printf("The name %s was not found for %s\n", $name, $data['country']);
    break;

    case Gender::ERROR_IN_NAME:
        echo "There is an error in the given name!\n";
    break;

    default:
        echo "An error occurred!\n";
    break;

}
Exemple
Gender\Gender
Exemple


The Gender\Gender class

(PECL gender >= 0.6.0)

Introducere

Sinopsisul clasei

Gender\Gender {
/* Constants */
const integer IS_FEMALE = 70 ;
const integer IS_MOSTLY_FEMALE = 102 ;
const integer IS_MALE = 77 ;
const integer IS_MOSTLY_MALE = 109 ;
const integer IS_UNISEX_NAME = 63 ;
const integer IS_A_COUPLE = 67 ;
const integer NAME_NOT_FOUND = 32 ;
const integer ERROR_IN_NAME = 69 ;
const integer ANY_COUNTRY = 0 ;
const integer BRITAIN = 1 ;
const integer IRELAND = 2 ;
const integer USA = 3 ;
const integer SPAIN = 4 ;
const integer PORTUGAL = 5 ;
const integer ITALY = 6 ;
const integer MALTA = 7 ;
const integer FRANCE = 8 ;
const integer BELGIUM = 9 ;
const integer LUXEMBOURG = 10 ;
const integer NETHERLANDS = 11 ;
const integer GERMANY = 12 ;
const integer EAST_FRISIA = 13 ;
const integer AUSTRIA = 14 ;
const integer SWISS = 15 ;
const integer ICELAND = 16 ;
const integer DENMARK = 17 ;
const integer NORWAY = 18 ;
const integer SWEDEN = 19 ;
const integer FINLAND = 20 ;
const integer ESTONIA = 21 ;
const integer LATVIA = 22 ;
const integer LITHUANIA = 23 ;
const integer POLAND = 24 ;
const integer CZECH_REP = 25 ;
const integer SLOVAKIA = 26 ;
const integer HUNGARY = 27 ;
const integer ROMANIA = 28 ;
const integer BULGARIA = 29 ;
const integer BOSNIA = 30 ;
const integer CROATIA = 31 ;
const integer KOSOVO = 32 ;
const integer MACEDONIA = 33 ;
const integer MONTENEGRO = 34 ;
const integer SERBIA = 35 ;
const integer SLOVENIA = 36 ;
const integer ALBANIA = 37 ;
const integer GREECE = 38 ;
const integer RUSSIA = 39 ;
const integer BELARUS = 40 ;
const integer MOLDOVA = 41 ;
const integer UKRAINE = 42 ;
const integer ARMENIA = 43 ;
const integer AZERBAIJAN = 44 ;
const integer GEORGIA = 45 ;
const integer KAZAKH_UZBEK = 46 ;
const integer TURKEY = 47 ;
const integer ARABIA = 48 ;
const integer ISRAEL = 49 ;
const integer CHINA = 50 ;
const integer INDIA = 51 ;
const integer JAPAN = 52 ;
const integer KOREA = 53 ;
/* Metode */
public boolean connect ( string $dsn )
public __construct ([ string $dsn ] )
public array country ( integer $country )
public integer get ( string $name [, integer $country ] )
public array isNick ( string $name0 , string $name1 [, integer $country ] )
public array similarNames ( string $name [, integer $country ] )
}

Constante predefinite

Gender\Gender::IS_FEMALE

Gender\Gender::IS_MOSTLY_FEMALE

Gender\Gender::IS_MALE

Gender\Gender::IS_MOSTLY_MALE

Gender\Gender::IS_UNISEX_NAME

Gender\Gender::IS_A_COUPLE

Gender\Gender::NAME_NOT_FOUND

Gender\Gender::ERROR_IN_NAME

Gender\Gender::ANY_COUNTRY

Gender\Gender::BRITAIN

Gender\Gender::IRELAND

Gender\Gender::USA

Gender\Gender::SPAIN

Gender\Gender::PORTUGAL

Gender\Gender::ITALY

Gender\Gender::MALTA

Gender\Gender::FRANCE

Gender\Gender::BELGIUM

Gender\Gender::LUXEMBOURG

Gender\Gender::NETHERLANDS

Gender\Gender::GERMANY

Gender\Gender::EAST_FRISIA

Gender\Gender::AUSTRIA

Gender\Gender::SWISS

Gender\Gender::ICELAND

Gender\Gender::DENMARK

Gender\Gender::NORWAY

Gender\Gender::SWEDEN

Gender\Gender::FINLAND

Gender\Gender::ESTONIA

Gender\Gender::LATVIA

Gender\Gender::LITHUANIA

Gender\Gender::POLAND

Gender\Gender::CZECH_REP

Gender\Gender::SLOVAKIA

Gender\Gender::HUNGARY

Gender\Gender::ROMANIA

Gender\Gender::BULGARIA

Gender\Gender::BOSNIA

Gender\Gender::CROATIA

Gender\Gender::KOSOVO

Gender\Gender::MACEDONIA

Gender\Gender::MONTENEGRO

Gender\Gender::SERBIA

Gender\Gender::SLOVENIA

Gender\Gender::ALBANIA

Gender\Gender::GREECE

Gender\Gender::RUSSIA

Gender\Gender::BELARUS

Gender\Gender::MOLDOVA

Gender\Gender::UKRAINE

Gender\Gender::ARMENIA

Gender\Gender::AZERBAIJAN

Gender\Gender::GEORGIA

Gender\Gender::KAZAKH_UZBEK

Gender\Gender::TURKEY

Gender\Gender::ARABIA

Gender\Gender::ISRAEL

Gender\Gender::CHINA

Gender\Gender::INDIA

Gender\Gender::JAPAN

Gender\Gender::KOREA

Cuprins

  • Gender\Gender::connect — Connect to an external name dictionary.
  • Gender\Gender::__construct — Construct the Gender object.
  • Gender\Gender::country — Get textual country representation
  • Gender\Gender::get — Get gender of a name.
  • Gender\Gender::isNick — Check if the name0 is an alias of the name1.
  • Gender\Gender::similarNames — Get similar names.
Usage example.
Gender\Gender::connect
Gender


Connect to an external name dictionary.

Gender\Gender
Gender\Gender::__construct
Gender\Gender
PHP Manual

Gender\Gender::connect

(PECL gender >= 0.6.0)

Gender\Gender::connect — Connect to an external name dictionary.

Descrierea

public boolean Gender\Gender::connect ( string $dsn )

Connect to an external name dictionary. Currently only streams are supported.

Parametri

dsn

DSN to open.

Valorile întoarse

Boolean as success of failure.

Gender\Gender
Gender\Gender::__construct
Gender\Gender


Construct the Gender object.

Gender\Gender::connect
Gender\Gender::country
Gender\Gender
PHP Manual

Gender\Gender::__construct

(PECL gender >= 0.6.0)

Gender\Gender::__construct — Construct the Gender object.

Descrierea

public Gender\Gender::__construct ([ string $dsn ] )

Create a Gender object optionally connecting to an external name dictionary. When no external database was given, compiled in data will be used.

Parametri

dsn

DSN to open.

Valorile întoarse

Gender\Gender::connect
Gender\Gender::country
Gender\Gender


Get textual country representation

Gender\Gender::__construct
Gender\Gender::get
Gender\Gender
PHP Manual

Gender\Gender::country

(PECL gender >= 0.8.0)

Gender\Gender::country — Get textual country representation

Descrierea

public array Gender\Gender::country ( integer $country )

Returns the textual representation of a country from a Gender class constant.

Parametri

country

A country ID specified by a Gender\Gender class constant.

Valorile întoarse

Returns an array with the short and full names of the country on success sau FALSE în cazul e?ecului.

Exemple

Example #1 Using Gender\Gender::country()

$gender = new Gender\Gender;
var_dump($gender->country(Gender\Gender::BRITAIN));

Exemplul de mai sus va afi?a:

array(2) {
  'country_short' =>
  string(2) "UK"
  'country' =>
  string(13) "Great Britain"
}

Gender\Gender::__construct
Gender\Gender::get
Gender\Gender


Get gender of a name.

Gender\Gender::country
Gender\Gender::isNick
Gender\Gender
PHP Manual

Gender\Gender::get

(PECL gender >= 0.6.0)

Gender\Gender::get — Get gender of a name.

Descrierea

public integer Gender\Gender::get ( string $name [, integer $country ] )

Get the gender of the name in a particular country.

Parametri

name

Name to check.

country

Country id identified by Gender class constant.

Valorile întoarse

Returns gender of the name.

Gender\Gender::country
Gender\Gender::isNick
Gender\Gender


Check if the name0 is an alias of the name1.

Gender\Gender::get
Gender\Gender::similarNames
Gender\Gender
PHP Manual

Gender\Gender::isNick

(PECL gender >= 0.9.0)

Gender\Gender::isNick — Check if the name0 is an alias of the name1.

Descrierea

public array Gender\Gender::isNick ( string $name0 , string $name1 [, integer $country ] )

Check whether the name0 is a nick of the name1.

Parametri

name0

Name to check.

name1

Name to check.

country

Country id identified by Gender class constant. If ommited ANY_COUNTRY is used.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Gender\Gender::get
Gender\Gender::similarNames
Gender\Gender


Get similar names.

Gender\Gender::isNick
Gettext
Gender\Gender
PHP Manual

Gender\Gender::similarNames

(PECL gender >= 0.9.0)

Gender\Gender::similarNames — Get similar names.

Descrierea

public array Gender\Gender::similarNames ( string $name [, integer $country ] )

Get similar names for the given name and country.

Parametri

name

Name to check.

country

Country id identified by Gender class constant. If ommited ANY_COUNTRY is used.

Valorile întoarse

Returns an array with the similar names found.

Gender\Gender::isNick
Gettext
Gender\Gender


Gettext

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Gettext
    • 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
Gender\Gender::similarNames
Introducere
Sus?inerea limbajului uman ?i a codificarii caracterelor


Introducere

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
Instalarea / configurarea
Gettext


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Gettext


Necesita?i

To use these functions you must download and install the GNU gettext package from » http://www.gnu.org/software/gettext/gettext.html

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Pentru a include sus?inerea GNU gettext în PHP trebuie sa utiliza?i op?iunea --with-gettext[=DIR] , unde DIR este directorul de instalare al gettext, implicit fiind /usr/local.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii Gettext
Gettext


Func?ii Gettext

Cuprins

  • 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
Constante predefinite
bind_textdomain_codeset
Gettext


Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

Func?ii Gettext
bindtextdomain
Func?ii Gettext
PHP Manual

bind_textdomain_codeset

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

bind_textdomain_codeset — Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

Descrierea

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.

Parametri

domain

The domain

codeset

The code set

Valorile întoarse

A string on success.

Func?ii Gettext
bindtextdomain
Func?ii Gettext


Sets the path for a domain

bind_textdomain_codeset
dcgettext
Func?ii Gettext
PHP Manual

bindtextdomain

(PHP 4, PHP 5, PHP 7)

bindtextdomain — Sets the path for a domain

Descrierea

string bindtextdomain ( string $domain , string $directory )

The bindtextdomain() function sets the path for a domain.

Parametri

domain

The domain

directory

The directory path

Valorile întoarse

The full pathname for the domain currently being set.

Exemple

Example #1 bindtextdomain() example

<?php

$domain = 'myapp';
echo bindtextdomain($domain, '/usr/share/myapp/locale');

?>

Exemplul de mai sus va afi?a:

/usr/share/myapp/locale

bind_textdomain_codeset
dcgettext
Func?ii Gettext


Overrides the domain for a single lookup

bindtextdomain
dcngettext
Func?ii Gettext
PHP Manual

dcgettext

(PHP 4, PHP 5, PHP 7)

dcgettext — Overrides the domain for a single lookup

Descrierea

string dcgettext ( string $domain , string $message , int $category )

This function allows you to override the current domain for a single message lookup.

Parametri

domain

The domain

message

The message

category

The category

Valorile întoarse

A string on success.

A se vedea ?i

  • gettext() - Lookup a message in the current domain

bindtextdomain
dcngettext
Func?ii Gettext


Plural version of dcgettext

dcgettext
dgettext
Func?ii Gettext
PHP Manual

dcngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

dcngettext — Plural version of dcgettext

Descrierea

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.

Parametri

domain

The domain

msgid1

msgid2

n

category

Valorile întoarse

A string on success.

A se vedea ?i

  • ngettext() - Plural version of gettext

dcgettext
dgettext
Func?ii Gettext


Override the current domain

dcngettext
dngettext
Func?ii Gettext
PHP Manual

dgettext

(PHP 4, PHP 5, PHP 7)

dgettext — Override the current domain

Descrierea

string dgettext ( string $domain , string $message )

The dgettext() function allows you to override the current domain for a single message lookup.

Parametri

domain

The domain

message

The message

Valorile întoarse

A string on success.

A se vedea ?i

  • gettext() - Lookup a message in the current domain

dcngettext
dngettext
Func?ii Gettext


Plural version of dgettext

dgettext
gettext
Func?ii Gettext
PHP Manual

dngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

dngettext — Plural version of dgettext

Descrierea

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.

Parametri

domain

The domain

msgid1

msgid2

n

Valorile întoarse

A string on success.

A se vedea ?i

  • ngettext() - Plural version of gettext

dgettext
gettext
Func?ii Gettext


Lookup a message in the current domain

dngettext
ngettext
Func?ii Gettext
PHP Manual

gettext

(PHP 4, PHP 5, PHP 7)

gettext — Lookup a message in the current domain

Descrierea

string gettext ( string $message )

Looks up a message in the current domain.

Parametri

message

The message being translated.

Valorile întoarse

Returns a translated string if one is found in the translation table, or the submitted message if not found.

Exemple

Example #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");
?>

Note

Nota:

You may use the underscore character '_' as an alias to this function.

Nota:

Setting a language isn't enough for some systems and the putenv() should be used to define the current locale.

A se vedea ?i

  • setlocale() - Set locale information

dngettext
ngettext
Func?ii Gettext


Plural version of gettext

gettext
textdomain
Func?ii Gettext
PHP Manual

ngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ngettext — Plural version of gettext

Descrierea

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.

Parametri

msgid1

The singular message ID.

msgid2

The plural message ID.

n

The number (e.g. item count) to determine the translation for the respective grammatical number.

Valorile întoarse

Returns correct plural form of message identified by msgid1 and msgid2 for count n.

Exemple

Example #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
Func?ii Gettext


Sets the default domain

ngettext
iconv
Func?ii Gettext
PHP Manual

textdomain

(PHP 4, PHP 5, PHP 7)

textdomain — Sets the default domain

Descrierea

string textdomain ( string $text_domain = NULL )

This function sets the domain to search within when calls are made to gettext(), usually the named after an application.

Parametri

text_domain

The new message domain, or NULL to get the current setting without changing it

Valorile întoarse

If successful, this function returns the current message domain, after possibly changing it.

ngettext
iconv
Func?ii Gettext


iconv

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii iconv
    • iconv_get_encoding — Retrieve internal configuration variables of iconv extension
    • 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 — Set current setting for character encoding conversion
    • 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 — Convert string to requested character encoding
    • ob_iconv_handler — Convert character encoding as output buffer handler
textdomain
Introducere
Sus?inerea limbajului uman ?i a codificarii caracterelor


Introducere

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
Instalarea / configurarea
iconv


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
iconv


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Iconv Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
iconv.input_encoding | "" | PHP_INI_ALL | Available since PHP 4.0.5. Deprecated in PHP 5.6.0.
iconv.output_encoding | "" | PHP_INI_ALL | Available since PHP 4.0.5. Deprecated in PHP 5.6.0.
iconv.internal_encoding | "" | PHP_INI_ALL | Available since PHP 4.0.5. Deprecated in PHP 5.6.0.

Iata o explica?ie pe scurt a directivelor de configurare.

Avertizare

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
Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.6.0. Utilizarea acestei facilita?i este foarte discurajata.

PHP 5.6 and later users should leave this empty and set default_charset instead.

iconv.output_encoding string
Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.6.0. Utilizarea acestei facilita?i este foarte discurajata.

PHP 5.6 and later users should leave this empty and set default_charset instead.

iconv.internal_encoding string
Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.6.0. Utilizarea acestei facilita?i este foarte discurajata.

PHP 5.6 and later users should leave this empty and set default_charset instead.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

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

Nota:

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()

Tipurile resurselor
Func?ii iconv
iconv


Func?ii iconv

A se vedea ?i

A se vedea func?ii de recodificare GNU.

Cuprins

  • iconv_get_encoding — Retrieve internal configuration variables of iconv extension
  • 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 — Set current setting for character encoding conversion
  • 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 — Convert string to requested character encoding
  • ob_iconv_handler — Convert character encoding as output buffer handler
Constante predefinite
iconv_get_encoding
iconv


Retrieve internal configuration variables of iconv extension

Func?ii iconv
iconv_mime_decode_headers
Func?ii iconv
PHP Manual

iconv_get_encoding

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

iconv_get_encoding — Retrieve internal configuration variables of iconv extension

Descrierea

mixed iconv_get_encoding ([ string $type = "all" ] )

Retrieve internal configuration variables of iconv extension.

Parametri

type

The value of the optional type can be:

  • all
  • input_encoding
  • output_encoding
  • internal_encoding

Valorile întoarse

Returns the current value of the internal configuration variable if successful sau FALSE în cazul e?ecului.

If type is omitted or set to "all", iconv_get_encoding() returns an array that stores all these variables.

Exemple

Example #1 iconv_get_encoding() example

<pre>
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
var_dump(iconv_get_encoding('all'));
?>
</pre>

Exemplul de mai sus va afi?a:

Array
(
    [input_encoding] => ISO-8859-1
    [output_encoding] => ISO-8859-1
    [internal_encoding] => UTF-8
)

A se vedea ?i

  • iconv_set_encoding() - Set current setting for character encoding conversion
  • ob_iconv_handler() - Convert character encoding as output buffer handler

Func?ii iconv
iconv_mime_decode_headers
Func?ii iconv


Decodes multiple MIME header fields at once

iconv_get_encoding
iconv_mime_decode
Func?ii iconv
PHP Manual

iconv_mime_decode_headers

(PHP 5, PHP 7)

iconv_mime_decode_headers — Decodes multiple MIME header fields at once

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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
        )

)

A se vedea ?i

  • 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
Func?ii iconv


Decodes a MIME header field

iconv_mime_decode_headers
iconv_mime_encode
Func?ii iconv
PHP Manual

iconv_mime_decode

(PHP 5, PHP 7)

iconv_mime_decode — Decodes a MIME header field

Descrierea

string iconv_mime_decode ( string $encoded_header [, int $mode = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] )

Decodes a MIME header field.

Parametri

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.

Valorile întoarse

Returns a decoded MIME field on success, or FALSE if an error occurs during the decoding.

Exemple

Example #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");
?>

A se vedea ?i

  • 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
Func?ii iconv


Composes a MIME header field

iconv_mime_decode
iconv_set_encoding
Func?ii iconv
PHP Manual

iconv_mime_encode

(PHP 5, PHP 7)

iconv_mime_encode — Composes a MIME header field

Descrierea

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.

Parametri

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

Valorile întoarse

Returns an encoded MIME field on success, or FALSE if an error occurs during the encoding.

Exemple

Example #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);
?>

A se vedea ?i

  • imap_binary() - Convert an 8bit string to a base64 string
  • mb_encode_mimeheader() - Encode string for MIME header
  • imap_8bit() - Converte?te un string "8bit" într-un string "quoted-printable"
  • quoted_printable_encode() - Convert a 8 bit string to a quoted-printable string

iconv_mime_decode
iconv_set_encoding
Func?ii iconv


Set current setting for character encoding conversion

iconv_mime_encode
iconv_strlen
Func?ii iconv
PHP Manual

iconv_set_encoding

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

iconv_set_encoding — Set current setting for character encoding conversion

Descrierea

bool iconv_set_encoding ( string $type , string $charset )

Changes the value of the internal configuration variable specified by type to charset.

Parametri

type

The value of type can be any one of these:

  • input_encoding
  • output_encoding
  • internal_encoding

charset

The character set.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 iconv_set_encoding() example

<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
?>

A se vedea ?i

  • iconv_get_encoding() - Retrieve internal configuration variables of iconv extension
  • ob_iconv_handler() - Convert character encoding as output buffer handler

iconv_mime_encode
iconv_strlen
Func?ii iconv


Returns the character count of string

iconv_set_encoding
iconv_strpos
Func?ii iconv
PHP Manual

iconv_strlen

(PHP 5, PHP 7)

iconv_strlen — Returns the character count of string

Descrierea

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.

Parametri

str

The string.

charset

If charset parameter is omitted, str is assumed to be encoded in iconv.internal_encoding.

Valorile întoarse

Returns the character count of str, as an integer.

A se vedea ?i

  • grapheme_strlen() - Get string length in grapheme units
  • mb_strlen() - Get string length
  • strlen() - Get string length

iconv_set_encoding
iconv_strpos
Func?ii iconv


Finds position of first occurrence of a needle within a haystack

iconv_strlen
iconv_strrpos
Func?ii iconv
PHP Manual

iconv_strpos

(PHP 5, PHP 7)

iconv_strpos — Finds position of first occurrence of a needle within a haystack

Descrierea

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.

Parametri

haystack

The entire string.

needle

The searched substring.

offset

The optional offset parameter specifies the position from which the search should be performed. If the offset is negative, it is counted from the end of the string.

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.

Valorile întoarse

Returns the numeric position of the first occurrence of needle in haystack.

If needle is not found, iconv_strpos() will return FALSE.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Support for negative offsets has been added.

A se vedea ?i

  • 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
Func?ii iconv


Finds the last occurrence of a needle within a haystack

iconv_strpos
iconv_substr
Func?ii iconv
PHP Manual

iconv_strrpos

(PHP 5, PHP 7)

iconv_strrpos — Finds the last occurrence of a needle within a haystack

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the numeric position of the last occurrence of needle in haystack.

If needle is not found, iconv_strrpos() will return FALSE.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

A se vedea ?i

  • strrpos() - Find the position of the last occurrence of a substring in a string
  • 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
Func?ii iconv


Cut out part of a string

iconv_strrpos
iconv
Func?ii iconv
PHP Manual

iconv_substr

(PHP 5, PHP 7)

iconv_substr — Cut out part of a string

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the portion of str specified by the offset and length parameters.

If str is shorter than offset characters long, FALSE will be returned. If str is exactly offset characters long, an empty string will be returned.

Istoricul schimbarilor

Versiune | Descriere
7.0.11 | If str is equal to offset characters long, an empty string will be returned. Prior to this version, FALSE was returned in this case.

A se vedea ?i

  • substr() - Return part of a string
  • mb_substr() - Get part of string
  • mb_strcut() - Get part of string

iconv_strrpos
iconv
Func?ii iconv


Convert string to requested character encoding

iconv_substr
ob_iconv_handler
Func?ii iconv
PHP Manual

iconv

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

iconv — Convert string to requested character encoding

Descrierea

string iconv ( string $in_charset , string $out_charset , string $str )

Performs a character set conversion on the string str from in_charset to out_charset.

Parametri

in_charset

The input charset.

out_charset

The output charset.

If you append the string //TRANSLIT to out_charset transliteration is activated. This means that when a character can't be represented in the target charset, it can be approximated through one or several similarly looking characters. If you append the string //IGNORE, characters that cannot be represented in the target charset are silently discarded. Otherwise, E_NOTICE is generated and the function will return FALSE.

Precautie

If and how //TRANSLIT works exactly depends on the system's iconv() implementation (cf. ICONV_IMPL). Some implementations are known to ignore //TRANSLIT, so the conversion is likely to fail for characters which are illegal for the out_charset.

str

The string to be converted.

Valorile întoarse

Returns the converted string sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Since this version, the function returns FALSE on illegal characters, unless //IGNORE is specified in output charset. Before, it returned partial output string.

Exemple

Example #1 iconv() example

<?php
$text = "This is the Euro symbol '€'.";

echo 'Original : ', $text, PHP_EOL;
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
echo 'IGNORE   : ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL;
echo 'Plain    : ', iconv("UTF-8", "ISO-8859-1", $text), PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

Original : This is the Euro symbol '€'.
TRANSLIT : This is the Euro symbol 'EUR'.
IGNORE   : This is the Euro symbol ''.
Plain    :
Notice: iconv(): Detected an illegal character in input string in .\iconv-example.php on line 7

iconv_substr
ob_iconv_handler
Func?ii iconv


Convert character encoding as output buffer handler

iconv
intl
Func?ii iconv
PHP Manual

ob_iconv_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

ob_iconv_handler — Convert character encoding as output buffer handler

Descrierea

string ob_iconv_handler ( string $contents , int $status )

Converts the string encoded in internal_encoding to output_encoding.

internal_encoding and output_encoding should be defined in the php.ini file or in iconv_set_encoding().

Parametri

See ob_start() for information about this handler parameters.

Valorile întoarse

See ob_start() for information about this handler return values.

Exemple

Example #1 ob_iconv_handler() example:

<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
ob_start("ob_iconv_handler"); // start output buffering
?>

A se vedea ?i

  • iconv_get_encoding() - Retrieve internal configuration variables of iconv extension
  • iconv_set_encoding() - Set current setting for character encoding conversion
  • output-control functions

iconv
intl
Func?ii iconv


Internationalization Functions

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • 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::canonicalize — Canonicalize the locale string
    • 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
  • IntlCalendar — The IntlCalendar class
    • IntlCalendar::add — Add a (signed) amount of time to a field
    • IntlCalendar::after — Whether this object's time is after that of the passed object
    • IntlCalendar::before — Whether this object's time is before that of the passed object
    • IntlCalendar::clear — Clear a field or all fields
    • IntlCalendar::__construct — Private constructor for disallowing instantiation
    • IntlCalendar::createInstance — Create a new IntlCalendar
    • IntlCalendar::equals — Compare time of two IntlCalendar objects for equality
    • IntlCalendar::fieldDifference — Calculate difference between given time and this object's time
    • IntlCalendar::fromDateTime — Create an IntlCalendar from a DateTime object or string
    • IntlCalendar::get — Get the value for a field
    • IntlCalendar::getActualMaximum — The maximum value for a field, considering the object's current time
    • IntlCalendar::getActualMinimum — The minimum value for a field, considering the object's current time
    • IntlCalendar::getAvailableLocales — Get array of locales for which there is data
    • IntlCalendar::getDayOfWeekType — Tell whether a day is a weekday, weekend or a day that has a transition between the two
    • IntlCalendar::getErrorCode — Get last error code on the object
    • IntlCalendar::getErrorMessage — Get last error message on the object
    • IntlCalendar::getFirstDayOfWeek — Get the first day of the week for the calendar's locale
    • IntlCalendar::getGreatestMinimum — Get the largest local minimum value for a field
    • IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values
    • IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field
    • IntlCalendar::getLocale — Get the locale associated with the object
    • IntlCalendar::getMaximum — Get the global maximum value for a field
    • IntlCalendar::getMinimalDaysInFirstWeek — Get minimal number of days the first week in a year or month can have
    • IntlCalendar::getMinimum — Get the global minimum value for a field
    • IntlCalendar::getNow — Get number representing the current time
    • IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time
    • IntlCalendar::getSkippedWallTimeOption — Get behavior for handling skipped wall time
    • IntlCalendar::getTime — Get time currently represented by the object
    • IntlCalendar::getTimeZone — Get the object's timezone
    • IntlCalendar::getType — Get the calendar type
    • IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends
    • IntlCalendar::inDaylightTime — Whether the object's time is in Daylight Savings Time
    • IntlCalendar::isEquivalentTo — Whether another calendar is equal but for a different time
    • IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode
    • IntlCalendar::isSet — Whether a field is set
    • IntlCalendar::isWeekend — Whether a certain date/time is in the weekend
    • IntlCalendar::roll — Add value to field without carrying into more significant fields
    • IntlCalendar::set — Set a time field or several common fields at once
    • IntlCalendar::setFirstDayOfWeek — Set the day on which the week is deemed to start
    • IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient
    • IntlCalendar::setMinimalDaysInFirstWeek — Set minimal number of days the first week in a year or month can have
    • IntlCalendar::setRepeatedWallTimeOption — Set behavior for handling repeating wall times at negative timezone offset transitions
    • IntlCalendar::setSkippedWallTimeOption — Set behavior for handling skipped wall times at positive timezone offset transitions
    • IntlCalendar::setTime — Set the calendar time in milliseconds since the epoch
    • IntlCalendar::setTimeZone — Set the timezone used by this calendar
    • IntlCalendar::toDateTime — Convert an IntlCalendar into a DateTime object
  • IntlTimeZone — The IntlTimeZone class
    • IntlTimeZone::countEquivalentIDs — Get the number of IDs in the equivalency group that includes the given ID
    • IntlTimeZone::createDefault — Create a new copy of the default timezone for this host
    • IntlTimeZone::createEnumeration — Get an enumeration over time zone IDs associated with the given country or offset
    • IntlTimeZone::createTimeZone — Create a timezone object for the given ID
    • IntlTimeZone::fromDateTimeZone — Create a timezone object from DateTimeZone
    • IntlTimeZone::getCanonicalID — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID
    • IntlTimeZone::getDisplayName — Get a name of this time zone suitable for presentation to the user
    • IntlTimeZone::getDSTSavings — Get the amount of time to be added to local standard time to get local wall clock time
    • IntlTimeZone::getEquivalentID — Get an ID in the equivalency group that includes the given ID
    • IntlTimeZone::getErrorCode — Get last error code on the object
    • IntlTimeZone::getErrorMessage — Get last error message on the object
    • IntlTimeZone::getGMT — Create GMT (UTC) timezone
    • IntlTimeZone::getID — Get timezone ID
    • IntlTimeZone::getOffset — Get the time zone raw and GMT offset for the given moment in time
    • IntlTimeZone::getRawOffset — Get the raw GMT offset (before taking daylight savings time into account
    • IntlTimeZone::getTZDataVersion — Get the timezone data version currently used by ICU
    • IntlTimeZone::hasSameRules — Check if this zone has the same rules and offset as another zone
    • IntlTimeZone::toDateTimeZone — Convert to DateTimeZone object
    • IntlTimeZone::useDaylightTime — Check if this time zone uses daylight savings time
  • IntlDateFormatter — The IntlDateFormatter class
    • IntlDateFormatter::create — Create a date formatter
    • IntlDateFormatter::format — Format the date/time value as a string
    • IntlDateFormatter::formatObject — Formats an object
    • IntlDateFormatter::getCalendar — Get the calendar type 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::getCalendarObject — Get copy of formatter's calendar object
    • IntlDateFormatter::getTimeZone — Get formatter's timezone
    • 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 type used by the formatter
    • 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
    • IntlDateFormatter::setTimeZone — Sets formatter's timezone
  • 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 given strings can be confused
    • 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 — Private constructor to deny instantiation
    • 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
  • IntlBreakIterator — The IntlBreakIterator class
    • IntlBreakIterator::__construct — Private constructor for disallowing instantiation
    • IntlBreakIterator::createCharacterInstance — Create break iterator for boundaries of combining character sequences
    • IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points
    • IntlBreakIterator::createLineInstance — Create break iterator for logically possible line breaks
    • IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks
    • IntlBreakIterator::createTitleInstance — Create break iterator for title-casing breaks
    • IntlBreakIterator::createWordInstance — Create break iterator for word breaks
    • IntlBreakIterator::current — Get index of current position
    • IntlBreakIterator::first — Set position to the first character in the text
    • IntlBreakIterator::following — Advance the iterator to the first boundary following specified offset
    • IntlBreakIterator::getErrorCode — Get last error code on the object
    • IntlBreakIterator::getErrorMessage — Get last error message on the object
    • IntlBreakIterator::getLocale — Get the locale associated with the object
    • IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries
    • IntlBreakIterator::getText — Get the text being scanned
    • IntlBreakIterator::isBoundary — Tell whether an offset is a boundary's offset
    • IntlBreakIterator::last — Set the iterator position to index beyond the last character
    • IntlBreakIterator::next — Advance the iterator the next boundary
    • IntlBreakIterator::preceding — Set the iterator position to the first boundary before an offset
    • IntlBreakIterator::previous — Set the iterator position to the boundary immediately before the current
    • IntlBreakIterator::setText — Set the text being scanned
  • IntlRuleBasedBreakIterator — The IntlRuleBasedBreakIterator class
    • IntlRuleBasedBreakIterator::__construct — Create iterator from ruleset
    • IntlRuleBasedBreakIterator::getBinaryRules — Get the binary form of compiled rules
    • IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object
    • IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position
    • IntlRuleBasedBreakIterator::getRuleStatusVec — Get the status values from the break rules that determined the current break position
  • IntlCodePointBreakIterator — The IntlCodePointBreakIterator class
    • IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator
  • IntlPartsIterator — The IntlPartsIterator class
    • IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator
  • UConverter — The UConverter class
    • UConverter::__construct — Create UConverter object
    • UConverter::convert — Convert string from one charset to another
    • UConverter::fromUCallback — Default "from" callback function
    • UConverter::getAliases — Get the aliases of the given name
    • UConverter::getAvailable — Get the available canonical converter names
    • UConverter::getDestinationEncoding — Get the destination encoding
    • UConverter::getDestinationType — Get the destination converter type
    • UConverter::getErrorCode — Get last error code on the object
    • UConverter::getErrorMessage — Get last error message on the object
    • UConverter::getSourceEncoding — Get the source encoding
    • UConverter::getSourceType — Get the source convertor type
    • UConverter::getStandards — Get standards associated to converter names
    • UConverter::getSubstChars — Get substitution chars
    • UConverter::reasonText — Get string representation of the callback reason
    • UConverter::setDestinationEncoding — Set the destination encoding
    • UConverter::setSourceEncoding — Set the source encoding
    • UConverter::setSubstChars — Set the substitution chars
    • UConverter::toUCallback — Default "to" callback function
    • UConverter::transcode — Convert string from one charset to another
  • Func?ii Grapheme
    • 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
  • Func?ii IDN
    • idn_to_ascii — Convert domain name to IDNA ASCII form.
    • idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode.
  • IntlChar
    • IntlChar::charAge — Get the "age" of the code point
    • IntlChar::charDigitValue — Get the decimal digit value of a decimal digit character
    • IntlChar::charDirection — Get bidirectional category value for a code point
    • IntlChar::charFromName — Find Unicode character by name and return its code point value
    • IntlChar::charMirror — Get the "mirror-image" character for a code point
    • IntlChar::charName — Retrieve the name of a Unicode character
    • IntlChar::charType — Get the general category value for a code point
    • IntlChar::chr — Return Unicode character by code point value
    • IntlChar::digit — Get the decimal digit value of a code point for a given radix
    • IntlChar::enumCharNames — Enumerate all assigned Unicode characters within a range
    • IntlChar::enumCharTypes — Enumerate all code points with their Unicode general categories
    • IntlChar::foldCase — Perform case folding on a code point
    • IntlChar::forDigit — Get character representation for a given digit and radix
    • IntlChar::getBidiPairedBracket — Get the paired bracket character for a code point
    • IntlChar::getBlockCode — Get the Unicode allocation block containing a code point
    • IntlChar::getCombiningClass — Get the combining class of a code point
    • IntlChar::getFC_NFKC_Closure — Get the FC_NFKC_Closure property for a code point
    • IntlChar::getIntPropertyMaxValue — Get the max value for a Unicode property
    • IntlChar::getIntPropertyMinValue — Get the min value for a Unicode property
    • IntlChar::getIntPropertyValue — Get the value for a Unicode property for a code point
    • IntlChar::getNumericValue — Get the numeric value for a Unicode code point
    • IntlChar::getPropertyEnum — Get the property constant value for a given property name
    • IntlChar::getPropertyName — Get the Unicode name for a property
    • IntlChar::getPropertyValueEnum — Get the property value for a given value name
    • IntlChar::getPropertyValueName — Get the Unicode name for a property value
    • IntlChar::getUnicodeVersion — Get the Unicode version
    • IntlChar::hasBinaryProperty — Check a binary Unicode property for a code point
    • IntlChar::isalnum — Check if code point is an alphanumeric character
    • IntlChar::isalpha — Check if code point is a letter character
    • IntlChar::isbase — Check if code point is a base character
    • IntlChar::isblank — Check if code point is a "blank" or "horizontal space" character
    • IntlChar::iscntrl — Check if code point is a control character
    • IntlChar::isdefined — Check whether the code point is defined
    • IntlChar::isdigit — Check if code point is a digit character
    • IntlChar::isgraph — Check if code point is a graphic character
    • IntlChar::isIDIgnorable — Check if code point is an ignorable character
    • IntlChar::isIDPart — Check if code point is permissible in an identifier
    • IntlChar::isIDStart — Check if code point is permissible as the first character in an identifier
    • IntlChar::isISOControl — Check if code point is an ISO control code
    • IntlChar::isJavaIDPart — Check if code point is permissible in a Java identifier
    • IntlChar::isJavaIDStart — Check if code point is permissible as the first character in a Java identifier
    • IntlChar::isJavaSpaceChar — Check if code point is a space character according to Java
    • IntlChar::islower — Check if code point is a lowercase letter
    • IntlChar::isMirrored — Check if code point has the Bidi_Mirrored property
    • IntlChar::isprint — Check if code point is a printable character
    • IntlChar::ispunct — Check if code point is punctuation character
    • IntlChar::isspace — Check if code point is a space character
    • IntlChar::istitle — Check if code point is a titlecase letter
    • IntlChar::isUAlphabetic — Check if code point has the Alphabetic Unicode property
    • IntlChar::isULowercase — Check if code point has the Lowercase Unicode property
    • IntlChar::isupper — Check if code point has the general category "Lu" (uppercase letter)
    • IntlChar::isUUppercase — Check if code point has the Uppercase Unicode property
    • IntlChar::isUWhiteSpace — Check if code point has the White_Space Unicode property
    • IntlChar::isWhitespace — Check if code point is a whitespace character according to ICU
    • IntlChar::isxdigit — Check if code point is a hexadecimal digit
    • IntlChar::ord — Return Unicode code point value of character
    • IntlChar::tolower — Make Unicode character lowercase
    • IntlChar::totitle — Make Unicode character titlecase
    • IntlChar::toupper — Make Unicode character uppercase
  • IntlException — Exception class for intl errors
  • IntlIterator — The IntlIterator class
    • IntlIterator::current — Get the current element
    • IntlIterator::key — Get the current key
    • IntlIterator::next — Move forward to the next element
    • IntlIterator::rewind — Rewind the iterator to the first element
    • IntlIterator::valid — Check if current position is valid
  • Func?ii intl
    • 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
Introducere
Sus?inerea limbajului uman ?i a codificarii caracterelor


Introducere

Internationalization extension (further is referred as Intl) is a wrapper for » ICU library, enabling PHP programmers to perform various locale-aware operations including but not limited to formatting, transliteration, encoding conversion, calendar operations, » UCA-conformant collation, locating text boundaries and working with locale identifiers, timezones and graphemes,

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. It can handle plurals, locale-aware numbers, currencies, conditions and much more.
  • 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.
  • Calendar: provides a class which could be used for locale-aware calendar operations and getting various information such as timezone for locale chosen, first day of week or if it's daylight saving time now.
  • Timezone: provides a wrapper around the » "Olson" database which has information about all the timezones around the world.
  • Date formatter: allows to display date and time according to the localized format or given pattern or set of rules, and to parse strings into date and time.
  • Transliterator: allows getting latin representation of strings in various languages.

Links

  • » Miscellaneous ICU docs

  • » ICU User Guide

  • » Unicode Collation Algorithm

intl
Instalarea / configurarea
intl


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
intl


Necesita?i

To build the extension you need to install the » ICU library, version 4.0.0 or newer is required.

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).

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » 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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Intl Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
intl.default_locale |  | PHP_INI_ALL |
intl.error_level | 0 | PHP_INI_ALL |
intl.use_exceptions | 0 | PHP_INI_ALL | Available since PHP 5.5 and PECL 3.0.0a1

Iata o explica?ie pe scurt a directivelor de configurare.

intl.default_locale string

The locale that will be used in intl functions when none is specified (either by omitting the corresponding argument or by passing NULL). These are ICU locales, not system locales. The built-in ICU locales and their data can be explored at » http://demo.icu-project.org/icu-bin/locexp.

The default value is empty, which forces the usage of ICU's default locale. Once set, the ini setting cannot be reset to this default value. It is not recommended that this default be relied on, as its effective value depends on the server's environment.

intl.error_level integer

The level of the error messages generated when an error occurs in ICU functions. This is a PHP error level, such as E_WARNING. It can be set to 0 in order to inhibit the messages. This does not affect the return values indicating error or the values returned by intl_get_error_code() or by the class specific methods for retrieving error codes and messages. Choosing E_ERROR will terminate the script whenever an error condition is found on intl classes.

The default value is 0.

intl.use_exceptions integer

If set to true, an exception will be raised whenever an error occurs in an intl function. The exception will be of type IntlException. This is possibly in addition to the error message generated due to intl.error_level.

The default value is FALSE.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

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. This constant and using the default has been deprecated as of PHP 7.2.0.
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().

Tipurile resurselor
Exemple
intl


Exemple

Cuprins

  • Basic usage of this extension
Constante predefinite
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.

Nota:

All input strings must be in UTF-8 encoding. All output strings are also in UTF-8.

Example #1 Example of using the procedural API

<?php
$coll  = collator_create('en_US');
$result = collator_compare($coll, "string#1", "string#2");
?>

Example #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);
?>
Exemple
Collator
Exemple


The Collator class

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Introducere

Provides string comparison capability with support for appropriate locale-sensitive sort orderings.

Sinopsisul clasei

Collator {
/* Metode */
public __construct ( string $locale )
public bool asort ( array &$arr [, int $sort_flag ] )
public int compare ( string $str1 , string $str2 )
public static Collator create ( string $locale )
public int getAttribute ( int $attr )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public string getLocale ( int $type )
public string getSortKey ( string $str )
public int getStrength ( void )
public bool setAttribute ( int $attr , int $val )
public bool setStrength ( int $strength )
public bool sortWithSortKeys ( array &$arr )
public bool sort ( array &$arr [, int $sort_flag ] )
}

Constante predefinite

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

Example #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

Example #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

Example #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

Example #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)

Cuprins

  • 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, PHP 7, PECL intl >= 1.0.0)

Collator::asort -- collator_asort — Sort array maintaining index association

Descrierea

Stil obiect-orientat

public bool Collator::asort ( array &$arr [, int $sort_flag ] )

Stil procedural

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().

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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 );
?>

Exemplul de mai sus va afi?a:

array (
  'c' => '7',
  'b' => '50',
  'a' => '100',
)array (
  'a' => '100',
  'b' => '50',
  'c' => '7',
)

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Collator::compare -- collator_compare — Compare two Unicode strings

Descrierea

Stil obiect-orientat

public int Collator::compare ( string $str1 , string $str2 )

Stil procedural

int collator_compare ( Collator $coll , string $str1 , string $str2 )

Compare two Unicode strings according to collation rules.

Parametri

coll

Collator object.

str1

The first string to compare.

str2

The second string to compare.

Valorile întoarse

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.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

s1 is greater than s2

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Collator::__construct — Create a collator

Descrierea

public Collator::__construct ( string $locale )

Creates a new instance of Collator.

Parametri

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's collation rules will be used. If "root" is 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.

Valorile întoarse

Returns Collator instance.

Erori/Excep?ii

Returns an "empty" object on error. You can use intl_get_error_code() and/or intl_get_error_message() to know what happened.

Exemple

Example #1 Collator::__construct() example

<?php
$coll = new Collator( 'en_CA' );
?>

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Collator::create -- collator_create — Create a collator

Descrierea

Stil obiect-orientat

public static Collator Collator::create ( string $locale )

Stil procedural

Collator collator_create ( string $locale )

The strings will be compared using the options already specified.

Parametri

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.

Valorile întoarse

Return new instance of Collator object, or NULL on error.

Exemple

Example #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 );
}
?>

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Collator::getAttribute -- collator_get_attribute — Get collation attribute value

Descrierea

Stil obiect-orientat

public int Collator::getAttribute ( int $attr )

Stil procedural

int collator_get_attribute ( Collator $coll , int $attr )

Get a value of an integer collator attribute.

Parametri

coll

Collator object.

attr

Attribute to get value for.

Valorile întoarse

Attribute value, or boolean FALSE on error.

Exemple

Example #1 collator_get_attribute() example

<?php
$coll = collator_create( 'en_CA' );
$val = collator_get_attribute( $coll, Collator::NUMERIC_COLLATION );
if( $val === false )
{
    // Handle error.
}
?>

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Collator::getErrorCode -- collator_get_error_code — Get collator's last error code

Descrierea

Stil obiect-orientat

public int Collator::getErrorCode ( void )

Stil procedural

int collator_get_error_code ( Collator $coll )

Parametri

coll

Collator object.

Valorile întoarse

Error code returned by the last Collator API function call.

Exemple

Example #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() );
?>

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Collator::getErrorMessage -- collator_get_error_message — Get text for collator's last error code

Descrierea

Stil obiect-orientat

public string Collator::getErrorMessage ( void )

Stil procedural

string collator_get_error_message ( Collator $coll )

Retrieves the message for the last error.

Parametri

coll

Collator object.

Valorile întoarse

Description of an error occurred in the last Collator API function call.

Exemple

Example #1 collator_get_error_message() example

<?php
$coll = collator_create( 'lt' );
if( collator_compare( $coll, 'y', 'k' ) === false ) {
    echo collator_get_error_message( $coll );
}
?>

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Collator::getLocale -- collator_get_locale — Get the locale name of the collator

Descrierea

Stil obiect-orientat

public string Collator::getLocale ( int $type )

Stil procedural

string collator_get_locale ( Collator $coll , int $type )

Get collector locale name.

Parametri

coll

Collator object.

type

You can choose between valid and actual locale ( Locale::VALID_LOCALE and Locale::ACTUAL_LOCALE, respectively).

Valorile întoarse

Real locale name from which the collation data comes. If the collator was instantiated from rules or an error occurred, returns boolean FALSE.

Exemple

Example #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_val, $res_act );
?>

Exemplul de mai sus va afi?a:

Requested locale name: en_US_California
Valid locale name: en_US
Actual locale name: en

A se vedea ?i

  • 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

(PHP 5 >= 5.3.11, PHP 7, PECL intl >= 1.0.3)

Collator::getSortKey -- collator_get_sort_key — Get sorting key for a string

Descrierea

Stil obiect-orientat

public string Collator::getSortKey ( string $str )

Stil procedural

string collator_get_sort_key ( Collator $coll , string $str )

Return collation key for a string.

Parametri

coll

Collator object.

str

The string to produce the key from.

Valorile întoarse

Returns the collation key for the string. Collation keys can be compared directly instead of strings.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Exemple

Example #1 collator_get_sort_key()example

<?php
$s1 = 'Hello';

$coll = collator_create( 'en_US' );
$res  = collator_get_sort_key( $coll, $s1);

echo urlencode($res);
?>

Exemplul de mai sus va afi?a:

71%3F%3FE%01%09%01%8F%08%00

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Collator::getStrength -- collator_get_strength — Get current collation strength

Descrierea

Stil obiect-orientat

public int Collator::getStrength ( void )

Stil procedural

int collator_get_strength ( Collator $coll )

Parametri

coll

Collator object.

Valorile întoarse

Returns current collation strength, or boolean FALSE on error.

Exemple

Example #1 collator_get_strength() example

<?php
$coll     = collator_create( 'en_US' );
$strength = collator_get_strength( $coll );
?>

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Collator::setAttribute -- collator_set_attribute — Set collation attribute

Descrierea

Stil obiect-orientat

public bool Collator::setAttribute ( int $attr , int $val )

Stil procedural

bool collator_set_attribute ( Collator $coll , int $attr , int $val )

Parametri

coll

Collator object.

attr

Attribute.

val

Attribute value.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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.
}
?>

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Collator::setStrength -- collator_set_strength — Set collation strength

Descrierea

Stil obiect-orientat

public bool Collator::setStrength ( int $strength )

Stil procedural

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.

    Nota:

    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.

Parametri

coll

Collator object.

strength

Strength to set.

Possible values are:

  • Collator::PRIMARY

  • Collator::SECONDARY

  • Collator::TERTIARY

  • Collator::QUATERNARY

  • Collator::IDENTICAL

  • Collator::DEFAULT_STRENGTH

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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 );
?>

Exemplul de mai sus va afi?a:

array (
  0 => 'ao',
  1 => 'Ao',
  2 => 'aò',
)
array (
  0 => 'aò',
  1 => 'Ao',
  2 => 'ao',
)

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Collator::sortWithSortKeys -- collator_sort_with_sort_keys — Sort array using specified collator and sort keys

Descrierea

Stil obiect-orientat

public bool Collator::sortWithSortKeys ( array &$arr )

Stil procedural

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.

Parametri

coll

Collator object.

arr

Array of strings to sort

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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 );
?>

Exemplul de mai sus va afi?a:

array (
  0 => 'Kopfe',
  1 => 'Kypper',
  2 => 'Köpfe',
)

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Collator::sort -- collator_sort — Sort array using specified collator

Descrierea

Stil obiect-orientat

public bool Collator::sort ( array &$arr [, int $sort_flag ] )

Stil procedural

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() .

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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 );
?>

Exemplul de mai sus va afi?a:

array (
  0 => 'at',
  1 => 'às',
  2 => 'as',
)array (
  0 => 'as',
  1 => 'às',
  2 => 'at',
)

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Introducere

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.

Sinopsisul clasei

NumberFormatter {
/* Metode */
public __construct ( string $locale , int $style [, string $pattern ] )
public static NumberFormatter create ( string $locale , int $style [, string $pattern ] )
public string formatCurrency ( float $value , string $currency )
public string format ( number $value [, int $type ] )
public int getAttribute ( int $attr )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public string getLocale ([ int $type ] )
public string getPattern ( void )
public string getSymbol ( int $attr )
public string getTextAttribute ( int $attr )
public float parseCurrency ( string $value , string &$currency [, int &$position ] )
public mixed parse ( string $value [, int $type [, int &$position ]] )
public bool setAttribute ( int $attr , int $value )
public bool setPattern ( string $pattern )
public bool setSymbol ( int $attr , string $value )
public bool setTextAttribute ( int $attr , string $value )
}

Constante predefinite

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.

A se vedea ?i

  • » ICU formatting documentation
  • » ICU number formatters
  • » ICU decimal formatters
  • » ICU rule-based number formatters

Cuprins

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::create -- numfmt_create -- NumberFormatter::__construct — Create a number formatter

Descrierea

Stil obiect-orientat (method)

public static NumberFormatter NumberFormatter::create ( string $locale , int $style [, string $pattern ] )

Stil procedural

NumberFormatter numfmt_create ( string $locale , int $style [, string $pattern ] )

Stil obiect-orientat (constructor):

public NumberFormatter::__construct ( string $locale , int $style [, string $pattern ] )

Creates a number formatter.

Parametri

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.

Valorile întoarse

Returns NumberFormatter object or FALSE on error.

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

1.234.567,891
millicentoquarantadue

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::formatCurrency -- numfmt_format_currency — Format a currency value

Descrierea

Stil obiect-orientat

public string NumberFormatter::formatCurrency ( float $value , string $currency )

Stil procedural

string numfmt_format_currency ( NumberFormatter $fmt , float $value , string $currency )

Format the currency value according to the formatter rules.

Parametri

fmt

NumberFormatter object.

value

The numeric currency value.

currency

The 3-letter ISO 4217 currency code indicating the currency to use.

Valorile întoarse

String representing the formatted currency value.

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

1.234.567,89 €
1.234.567,89 RUR
1 234 567,89€
1 234 567,89?.

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::format -- numfmt_format — Format a number

Descrierea

Stil obiect-orientat

public string NumberFormatter::format ( number $value [, int $type ] )

Stil procedural

string numfmt_format ( NumberFormatter $fmt , number $value [, int $type ] )

Format a numeric value according to the formatter rules.

Parametri

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.

Valorile întoarse

Returns the string containing formatted value, or FALSE on error.

Exemple

Example #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");
}
?>

Example #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");
}
?>

Exemplul de mai sus va afi?a:

1.234.567,891

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getAttribute -- numfmt_get_attribute — Get an attribute

Descrierea

Stil obiect-orientat

public int NumberFormatter::getAttribute ( int $attr )

Stil procedural

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.

Parametri

fmt

NumberFormatter object.

attr

Attribute specifier - one of the numeric attribute constants.

Valorile întoarse

Return attribute value on success, or FALSE on error.

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

Digits: 3
1.234.567,891
Digits: 2
1.234.567,89

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getErrorCode -- numfmt_get_error_code — Get formatter's last error code.

Descrierea

Stil obiect-orientat

public int NumberFormatter::getErrorCode ( void )

Stil procedural

int numfmt_get_error_code ( NumberFormatter $fmt )

Get error code from the last function performed by the formatter.

Parametri

fmt

NumberFormatter object.

Valorile întoarse

Returns error code from last formatter call.

Exemple

Example #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");
}
?>

Example #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");
}
?>

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getErrorMessage -- numfmt_get_error_message — Get formatter's last error message.

Descrierea

Stil obiect-orientat

public string NumberFormatter::getErrorMessage ( void )

Stil procedural

string numfmt_get_error_message ( NumberFormatter $fmt )

Get error message from the last function performed by the formatter.

Parametri

fmt

NumberFormatter object.

Valorile întoarse

Returns error message from last formatter call.

Exemple

Example #1 numfmt_get_error_message() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
var_dump(numfmt_get_error_message($fmt));
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
var_dump(numfmt_get_error_message($fmt));
?>

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getLocale -- numfmt_get_locale — Get formatter locale

Descrierea

Stil obiect-orientat

public string NumberFormatter::getLocale ([ int $type ] )

Stil procedural

string numfmt_get_locale ( NumberFormatter $fmt [, int $type ] )

Get formatter locale name.

Parametri

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.

Valorile întoarse

The locale name used to create the formatter.

Exemple

Example #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 );
?>

Exemplul de mai sus va afi?a:

Requested locale name: fr_FR_PARIS
Valid locale name: fr_FR
Actual locale name: fr

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getPattern -- numfmt_get_pattern — Get formatter pattern

Descrierea

Stil obiect-orientat

public string NumberFormatter::getPattern ( void )

Stil procedural

string numfmt_get_pattern ( NumberFormatter $fmt )

Extract pattern used by the formatter.

Parametri

fmt

NumberFormatter object.

Valorile întoarse

Pattern string that is used by the formatter, or FALSE if an error happens.

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

Pattern: #,##0.###
1.234.567,891
Pattern: #0.# kg
1234567,9 kg

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getSymbol -- numfmt_get_symbol — Get a symbol value

Descrierea

Stil obiect-orientat

public string NumberFormatter::getSymbol ( int $attr )

Stil procedural

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.

Parametri

fmt

NumberFormatter object.

attr

Symbol specifier, one of the format symbol constants.

Valorile întoarse

The symbol string or FALSE on error.

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

Sep: .
1.234.567,891
Sep: *
1*234*567,891

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getTextAttribute -- numfmt_get_text_attribute — Get a text attribute

Descrierea

Stil obiect-orientat

public string NumberFormatter::getTextAttribute ( int $attr )

Stil procedural

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.

Parametri

fmt

NumberFormatter object.

attr

Attribute specifier - one of the text attribute constants.

Valorile întoarse

Return attribute value on success, or FALSE on error.

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

Prefix: -
-1.234.567,891
Prefix: MINUS
MINUS1.234.567,891

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::parseCurrency -- numfmt_parse_currency — Parse a currency number

Descrierea

Stil obiect-orientat

public float NumberFormatter::parseCurrency ( string $value , string &$currency [, int &$position ] )

Stil procedural

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.

Parametri

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.

Valorile întoarse

The parsed numeric value or FALSE on error.

Exemple

Example #1 numfmt_parse_currency() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89\xc2\xa0$";
echo "We have ".numfmt_parse_currency($fmt, $num, $curr)." in $curr\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89\xc2\xa0$";
echo "We have ".$fmt->parseCurrency($num, $curr)." in $curr\n";
?>

Exemplul de mai sus va afi?a:

We have 1234567.89 in USD

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::parse -- numfmt_parse — Parse a number

Descrierea

Stil obiect-orientat

public mixed NumberFormatter::parse ( string $value [, int $type [, int &$position ]] )

Stil procedural

mixed numfmt_parse ( NumberFormatter $fmt , string $value [, int $type [, int &$position ]] )

Parse a string into a number using the current formatter rules.

Parametri

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.

Valorile întoarse

The value of the parsed number or FALSE on error.

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

1234567.891
1234567

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::setAttribute -- numfmt_set_attribute — Set an attribute

Descrierea

Stil obiect-orientat

public bool NumberFormatter::setAttribute ( int $attr , int $value )

Stil procedural

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.

Parametri

fmt

NumberFormatter object.

attr

Attribute specifier - one of the numeric attribute constants.

value

The attribute value.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

Digits: 3
1.234.567,891
Digits: 2
1.234.567,89

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::setPattern -- numfmt_set_pattern — Set formatter pattern

Descrierea

Stil obiect-orientat

public bool NumberFormatter::setPattern ( string $pattern )

Stil procedural

bool numfmt_set_pattern ( NumberFormatter $fmt , string $pattern )

Set the pattern used by the formatter. Can not be used on a rule-based formatter.

Parametri

fmt

NumberFormatter object.

pattern

Pattern in syntax described in » ICU DecimalFormat documentation.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

Pattern: #,##0.###
1.234.567,891
Pattern: #0.# kg
1234567,9 kg

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::setSymbol -- numfmt_set_symbol — Set a symbol value

Descrierea

Stil obiect-orientat

public bool NumberFormatter::setSymbol ( int $attr , string $value )

Stil procedural

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.

Parametri

fmt

NumberFormatter object.

attr

Symbol specifier, one of the format symbol constants.

value

Text for the symbol.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

Sep: .
1.234.567,891
Sep: *
1*234*567,891

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::setTextAttribute -- numfmt_set_text_attribute — Set a text attribute

Descrierea

Stil obiect-orientat

public bool NumberFormatter::setTextAttribute ( int $attr , string $value )

Stil procedural

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.

Parametri

fmt

NumberFormatter object.

attr

Attribute specifier - one of the text attribute constants.

value

Text for the attribute value.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

Prefix: -
-1.234.567,891
Prefix: MINUS
MINUS1.234.567,891

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Introducere

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.

Sinopsisul clasei

Locale {
/* Metode */
public static string acceptFromHttp ( string $header )
public static string canonicalize ( string $locale )
public static string composeLocale ( array $subtags )
public static bool filterMatches ( string $langtag , string $locale [, bool $canonicalize = false ] )
public static array getAllVariants ( string $locale )
public static string getDefault ( void )
public static string getDisplayLanguage ( string $locale [, string $in_locale ] )
public static string getDisplayName ( string $locale [, string $in_locale ] )
public static string getDisplayRegion ( string $locale [, string $in_locale ] )
public static string getDisplayScript ( string $locale [, string $in_locale ] )
public static string getDisplayVariant ( string $locale [, string $in_locale ] )
public static array getKeywords ( string $locale )
public static string getPrimaryLanguage ( string $locale )
public static string getRegion ( string $locale )
public static string getScript ( string $locale )
public static string lookup ( array $langtag , string $locale [, bool $canonicalize = false [, string $default ]] )
public static array parseLocale ( string $locale )
public static bool setDefault ( string $locale )
}

Constante predefinite

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

A se vedea ?i

  • » 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

Cuprins

  • Locale::acceptFromHttp — Tries to find out best available locale based on HTTP "Accept-Language" header
  • Locale::canonicalize — Canonicalize the locale string
  • 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::canonicalize
Locale
PHP Manual

Locale::acceptFromHttp

locale_accept_from_http

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Locale::acceptFromHttp -- locale_accept_from_http — Tries to find out best available locale based on HTTP "Accept-Language" header

Descrierea

Stil obiect-orientat

public static string Locale::acceptFromHttp ( string $header )

Stil procedural

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.

Parametri

header

The string containing the "Accept-Language" header according to format in RFC 2616.

Valorile întoarse

The corresponding locale identifier.

Exemple

Example #1 locale_accept_from_http() example

<?php
$locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>

Example #2 OO example

<?php
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>

Exemplul de mai sus va afi?a:

en_US

A se vedea ?i

  • locale_lookup() - Searches the language tag list for the best match to the language

Locale
Locale::canonicalize
Locale


Canonicalize the locale string

Locale::acceptFromHttp
Locale::composeLocale
Locale
PHP Manual

Locale::canonicalize

locale_canonicalize

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Locale::canonicalize -- locale_canonicalize — Canonicalize the locale string

Descrierea

public static string Locale::canonicalize ( string $locale )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

locale

Valorile întoarse

Locale::acceptFromHttp
Locale::composeLocale
Locale


Returns a correctly ordered and delimited locale ID

Locale::canonicalize
Locale::filterMatches
Locale
PHP Manual

Locale::composeLocale

locale_compose

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Locale::composeLocale -- locale_compose — Returns a correctly ordered and delimited locale ID

Descrierea

Stil obiect-orientat

public static string Locale::composeLocale ( array $subtags )

Stil procedural

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.

Parametri

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.

Nota:

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.).

Valorile întoarse

The corresponding locale identifier.

Exemple

Example #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 );
?>

Example #2 OO example

<?php
$arr = array(
    'language'=>'en' ,
    'script'  =>'Hans' ,
    'region'  =>'CN',
    'variant2'=>'rozaj' ,
    'variant1'=>'nedis' ,
    'private1'=>'prv1' ,
    'private2'=>'prv2'
);
echo Locale::composeLocale( $arr );
?>

Exemplul de mai sus va afi?a:

Locale: en_Hans_CN_nedis_rozaj_x_prv1_prv2

A se vedea ?i

  • locale_parse() - Returns a key-value array of locale ID subtag elements.

Locale::canonicalize
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, PHP 7, PECL intl >= 1.0.0)

Locale::filterMatches -- locale_filter_matches — Checks if a language tag filter matches with locale

Descrierea

Stil obiect-orientat

public static bool Locale::filterMatches ( string $langtag , string $locale [, bool $canonicalize = false ] )

Stil procedural

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

Parametri

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.

Valorile întoarse

TRUE if $locale matches $langtag FALSE otherwise.

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

Does not match; Matches

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::getAllVariants -- locale_get_all_variants — Gets the variants for the input locale

Descrierea

Stil obiect-orientat

public static array Locale::getAllVariants ( string $locale )

Stil procedural

array locale_get_all_variants ( string $locale )

Gets the variants for the input locale

Parametri

locale

The locale to extract the variants from

Valorile întoarse

The array containing the list of all variants subtag for the locale or NULL if not present

Exemple

Example #1 locale_get_all_variants() example

<?php
$arr = locale_get_all_variants('sl_IT_NEDIS_ROJAZ_1901');
var_export( $arr );
?>

Example #2 OO example

<?php
 $arr = Locale::getAllVariants('sl_IT_NEDIS_ROJAZ_1901');
 var_export( $arr );
?>

Exemplul de mai sus va afi?a:

array (
    0 => 'NEDIS',
    1 => 'ROJAZ',
    2 => '1901',
)

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::getDefault -- locale_get_default — Gets the default locale value from the INTL global 'default_locale'

Descrierea

Stil obiect-orientat

public static string Locale::getDefault ( void )

Stil procedural

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().

Parametri

Valorile întoarse

The current runtime locale

Exemple

Example #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();
?>

Example #2 OO example

<?php
ini_set('intl.default_locale', 'de-DE');
echo Locale::getDefault();
echo '; ';
Locale::setDefault('fr');
echo Locale::getDefault();
?>

Exemplul de mai sus va afi?a:

de-DE; fr

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::getDisplayLanguage -- locale_get_display_language — Returns an appropriately localized display name for language of the inputlocale

Descrierea

Stil obiect-orientat

public static string Locale::getDisplayLanguage ( string $locale [, string $in_locale ] )

Stil procedural

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.

Parametri

locale

The locale to return a display language for

in_locale

Optional format locale to use to display the language name

Valorile întoarse

display name of the language for the $locale in the format appropriate for $in_locale.

Exemple

Example #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');
?>

Example #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');
?>

Exemplul de mai sus va afi?a:

Slovenian;
slov\xc3\xa8ne;
Slowenisch

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::getDisplayName -- locale_get_display_name — Returns an appropriately localized display name for the input locale

Descrierea

Stil obiect-orientat

public static string Locale::getDisplayName ( string $locale [, string $in_locale ] )

Stil procedural

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.

Parametri

locale

The locale to return a display name for.

in_locale

optional format locale

Valorile întoarse

Display name of the locale in the format appropriate for $in_locale.

Exemple

Example #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');
?>

Example #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');
?>

Exemplul de mai sus va afi?a:

Slovenian (Latin, Italy, Natisone dialect);
slov\xc3\xa8ne (latin, Italie, dialecte de Natisone;
Slowenisch (Lateinisch, Italien, NEDIS)

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::getDisplayRegion -- locale_get_display_region — Returns an appropriately localized display name for region of the input locale

Descrierea

Stil obiect-orientat

public static string Locale::getDisplayRegion ( string $locale [, string $in_locale ] )

Stil procedural

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.

Parametri

locale

The locale to return a display region for.

in_locale

Optional format locale to use to display the region name

Valorile întoarse

display name of the region for the $locale in the format appropriate for $in_locale.

Exemple

Example #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');
?>

Example #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');
?>

Exemplul de mai sus va afi?a:

Italy;
Italie;
Italien

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::getDisplayScript -- locale_get_display_script — Returns an appropriately localized display name for script of the input locale

Descrierea

Stil obiect-orientat

public static string Locale::getDisplayScript ( string $locale [, string $in_locale ] )

Stil procedural

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.

Parametri

locale

The locale to return a display script for

in_locale

Optional format locale to use to display the script name

Valorile întoarse

Display name of the script for the $locale in the format appropriate for $in_locale.

Exemple

Example #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');
?>

Example #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');
?>

Exemplul de mai sus va afi?a:

Latin;
latin;
Lateinisch

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::getDisplayVariant -- locale_get_display_variant — Returns an appropriately localized display name for variants of the input locale

Descrierea

Stil obiect-orientat

public static string Locale::getDisplayVariant ( string $locale [, string $in_locale ] )

Stil procedural

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.

Parametri

locale

The locale to return a display variant for

in_locale

Optional format locale to use to display the variant name

Valorile întoarse

Display name of the variant for the $locale in the format appropriate for $in_locale.

Exemple

Example #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');
?>

Example #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');
?>

Exemplul de mai sus va afi?a:

Natisone dialect;
dialecte de Natisone;
NEDIS

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::getKeywords -- locale_get_keywords — Gets the keywords for the input locale

Descrierea

Stil obiect-orientat

public static array Locale::getKeywords ( string $locale )

Stil procedural

array locale_get_keywords ( string $locale )

Gets the keywords for the input locale.

Parametri

locale

The locale to extract the keywords from

Valorile întoarse

Associative array containing the keyword-value pairs for this locale

Exemple

Example #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";
    }
}
?>

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

collation = PHONEBOOK
currency = EUR

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::getPrimaryLanguage -- locale_get_primary_language — Gets the primary language for the input locale

Descrierea

Stil obiect-orientat

public static string Locale::getPrimaryLanguage ( string $locale )

Stil procedural

string locale_get_primary_language ( string $locale )

Gets the primary language for the input locale

Parametri

locale

The locale to extract the primary language code from

Valorile întoarse

The language code associated with the language or NULL in case of error.

Exemple

Example #1 locale_get_primary_language() example

<?php
echo locale_get_primary_language('zh-Hant');
?>

Example #2 OO example

<?php
echo Locale::getPrimaryLanguage('zh-Hant');
?>

Exemplul de mai sus va afi?a:

zh

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::getRegion -- locale_get_region — Gets the region for the input locale

Descrierea

Stil obiect-orientat

public static string Locale::getRegion ( string $locale )

Stil procedural

string locale_get_region ( string $locale )

Gets the region for the input locale.

Parametri

locale

The locale to extract the region code from

Valorile întoarse

The region subtag for the locale or NULL if not present

Exemple

Example #1 locale_get_region() example

<?php
echo locale_get_region('de-CH-1901');
?>

Example #2 OO example

<?php
echo Locale::getRegion('de-CH-1901');
?>

Exemplul de mai sus va afi?a:

CH

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::getScript -- locale_get_script — Gets the script for the input locale

Descrierea

Stil obiect-orientat

public static string Locale::getScript ( string $locale )

Stil procedural

string locale_get_script ( string $locale )

Gets the script for the input locale.

Parametri

locale

The locale to extract the script code from

Valorile întoarse

The script subtag for the locale or NULL if not present

Exemple

Example #1 locale_get_script() example

<?php
echo locale_get_script('sr-Cyrl');
?>

Example #2 OO example

<?php
echo Locale::getScript('sr-Cyrl');
?>

Exemplul de mai sus va afi?a:

Cyrl

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::lookup -- locale_lookup — Searches the language tag list for the best match to the language

Descrierea

Stil obiect-orientat

public static string Locale::lookup ( array $langtag , string $locale [, bool $canonicalize = false [, string $default ]] )

Stil procedural

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.

Parametri

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.

Valorile întoarse

The closest matching language tag or default value.

Exemple

Example #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', true, 'en_US');
?>

Example #2 OO example

<?php
$arr = array(
    'de-DEVA',
    'de-DE-1996',
    'de',
    'de-De'
);
echo Locale::lookup($arr, 'de-DE-1996-x-prv1-prv2', true, 'en_US');
?>

Exemplul de mai sus va afi?a:

de_de_1996

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::parseLocale -- locale_parse — Returns a key-value array of locale ID subtag elements.

Descrierea

Stil obiect-orientat

public static array Locale::parseLocale ( string $locale )

Stil procedural

array locale_parse ( string $locale )

Returns a key-value array of locale ID subtag elements.

Parametri

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.

Valorile întoarse

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

Exemple

Example #1 locale_parse() example

<?php
$arr = locale_parse('sl-Latn-IT-nedis');
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}
?>

Example #2 OO example

<?php
$arr = Locale::parseLocale('sl-Latn-IT-nedis');
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}
?>

Exemplul de mai sus va afi?a:

language : sl , script : Latn , region : IT , variant0 : NEDIS ,

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Locale::setDefault -- locale_set_default — sets the default runtime locale

Descrierea

Stil obiect-orientat

public static bool Locale::setDefault ( string $locale )

Stil procedural

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.

Parametri

locale

Is a BCP 47 compliant language tag.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 locale_set_default() example

<?php
locale_set_default('de-DE');
echo locale_get_default();
?>

Example #2 OO example

<?php
Locale::setDefault('de-DE');
echo Locale::getDefault();
?>

Exemplul de mai sus va afi?a:

de-DE

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Introducere

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.

Sinopsisul clasei

Normalizer {
/* Metode */
public static bool isNormalized ( string $input [, int $form = Normalizer::FORM_C ] )
public static string normalize ( string $input [, int $form = Normalizer::FORM_C ] )
}

Constante predefinite

The following constants define the normalization form used by the normalizer:

Normalizer::FORM_C (integer)
Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition
Normalizer::FORM_D (integer)
Normalization Form D (NFD) - Canonical Decomposition
Normalizer::FORM_KC (integer)
Normalization Form KC (NFKC) - Compatibility Decomposition, followed by Canonical Composition
Normalizer::FORM_KD (integer)
Normalization Form KD (NFKD) - Compatibility Decomposition
Normalizer::NONE (integer)
No decomposition/composition
Normalizer::OPTION_DEFAULT (integer)
Default normalization options

A se vedea ?i

  • » Unicode Normalization
  • » Unicode Normalization FAQ
  • » ICU User Guide - Normalization
  • » ICU API Reference - Normalization

Cuprins

  • 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, PHP 7, PECL intl >= 1.0.0)

Normalizer::isNormalized -- normalizer_is_normalized — Checks if the provided string is already in the specified normalization form.

Descrierea

Stil obiect-orientat

public static bool Normalizer::isNormalized ( string $input [, int $form = Normalizer::FORM_C ] )

Stil procedural

bool normalizer_is_normalized ( string $input [, int $form = Normalizer::FORM_C ] )

Checks if the provided string is already in the specified normalization form.

Parametri

input

The input string to normalize

form

One of the normalization forms.

Valorile întoarse

TRUE if normalized, FALSE otherwise or if there an error

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

not normalized; normalized

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Normalizer::normalize -- normalizer_normalize — Normalizes the input provided and returns the normalized string

Descrierea

Stil obiect-orientat

public static string Normalizer::normalize ( string $input [, int $form = Normalizer::FORM_C ] )

Stil procedural

string normalizer_normalize ( string $input [, int $form = Normalizer::FORM_C ] )

Normalizes the input provided and returns the normalized string

Parametri

input

The input string to normalize

form

One of the normalization forms.

Valorile întoarse

The normalized string or FALSE if an error occurred.

Exemple

Example #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);
?>

Example #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);
?>

Exemplul de mai sus va afi?a:

%C3%85 %C3%85

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

Introducere

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.

Sinopsisul clasei

MessageFormatter {
/* Metode */
public __construct ( string $locale , string $pattern )
public static MessageFormatter create ( string $locale , string $pattern )
public static string formatMessage ( string $locale , string $pattern , array $args )
public string format ( array $args )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public string getLocale ( void )
public string getPattern ( void )
public static array parseMessage ( string $locale , string $pattern , string $source )
public array parse ( string $value )
public bool setPattern ( string $pattern )
}

A se vedea ?i

  • » ICU formatting documentation
  • » ICU message formatting description
  • » ICU message formatters
  • » ICU choice formatters

Cuprins

  • 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, PHP 7, PECL intl >= 1.0.0)

MessageFormatter::create -- MessageFormatter::__construct -- msgfmt_create — Constructs a new Message Formatter

Descrierea

Stil obiect-orientat (method)

public static MessageFormatter MessageFormatter::create ( string $locale , string $pattern )

Stil obiect-orientat (constructor):

public MessageFormatter::__construct ( string $locale , string $pattern )

Stil procedural

MessageFormatter msgfmt_create ( string $locale , string $pattern )

Constructs a new Message Formatter

Parametri

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.

Valorile întoarse

The formatter object

Exemple

Example #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));
?>

Example #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));
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

MessageFormatter::formatMessage -- msgfmt_format_message — Quick format message

Descrierea

Stil obiect-orientat

public static string MessageFormatter::formatMessage ( string $locale , string $pattern , array $args )

Stil procedural

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.

Parametri

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

Valorile întoarse

The formatted pattern string or FALSE if an error occurred

Exemple

Example #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\n", 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\n", array(4560, 123, 4560/123));
?>

Example #2 OO example

<?php
echo MessageFormatter::formatMessage("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree\n", array(4560, 123, 4560/123));
echo MessageFormatter::formatMessage("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum\n", array(4560, 123, 4560/123));
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

MessageFormatter::format -- msgfmt_format — Format the message

Descrierea

Stil obiect-orientat

public string MessageFormatter::format ( array $args )

Stil procedural

string msgfmt_format ( MessageFormatter $fmt , array $args )

Format the message by substituting the data into the format string according to the locale rules

Parametri

fmt

The message formatter

args

Arguments to insert into the format string

Valorile întoarse

The formatted string, or FALSE if an error occurred

Exemple

Example #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));
?>

Example #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));
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

MessageFormatter::getErrorCode -- msgfmt_get_error_code — Get the error code from last operation

Descrierea

Stil obiect-orientat

public int MessageFormatter::getErrorCode ( void )

Stil procedural

int msgfmt_get_error_code ( MessageFormatter $fmt )

Get the error code from last operation.

Parametri

fmt

The message formatter

Valorile întoarse

The error code, one of UErrorCode values. Initial value is U_ZERO_ERROR.

Exemple

Example #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";
}
?>

Example #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";
}
?>

Exemplul de mai sus va afi?a:

ERROR: msgfmt_format: not enough parameters: U_ILLEGAL_ARGUMENT_ERROR (1)

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

MessageFormatter::getErrorMessage -- msgfmt_get_error_message — Get the error text from the last operation

Descrierea

Stil obiect-orientat

public string MessageFormatter::getErrorMessage ( void )

Stil procedural

string msgfmt_get_error_message ( MessageFormatter $fmt )

Get the error text from the last operation.

Parametri

fmt

The message formatter

Valorile întoarse

Description of the last error.

Exemple

Example #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";
}
?>

Example #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";
}
?>

Exemplul de mai sus va afi?a:

ERROR: msgfmt_format: not enough parameters: U_ILLEGAL_ARGUMENT_ERROR (1)

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

MessageFormatter::getLocale -- msgfmt_get_locale — Get the locale for which the formatter was created.

Descrierea

Stil obiect-orientat

public string MessageFormatter::getLocale ( void )

Stil procedural

string msgfmt_get_locale ( NumberFormatter $formatter )

Get the locale for which the formatter was created.

Parametri

formatter

The formatter resource

Valorile întoarse

The locale name

Exemple

Example #1 msgfmt_get_locale() example

<?php
$fmt = msgfmt_create('en_US', "Number {0,number}");
echo msgfmt_get_locale($fmt);
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter('en_US', "Number {0,number}");
echo $fmt->getLocale();
?>

Exemplul de mai sus va afi?a:

en_US

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

MessageFormatter::getPattern -- msgfmt_get_pattern — Get the pattern used by the formatter

Descrierea

Stil obiect-orientat

public string MessageFormatter::getPattern ( void )

Stil procedural

string msgfmt_get_pattern ( MessageFormatter $fmt )

Get the pattern used by the formatter

Parametri

fmt

The message formatter

Valorile întoarse

The pattern string for this message formatter

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

MessageFormatter::parseMessage -- msgfmt_parse_message — Quick parse input string

Descrierea

Stil obiect-orientat

public static array MessageFormatter::parseMessage ( string $locale , string $pattern , string $source )

Stil procedural

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.

Parametri

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.

Valorile întoarse

An array containing items extracted, or FALSE on error

Exemple

Example #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);
?>

Example #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);
?>

Exemplul de mai sus va afi?a:

array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)
array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

MessageFormatter::parse -- msgfmt_parse — Parse input string according to pattern

Descrierea

Stil obiect-orientat

public array MessageFormatter::parse ( string $value )

Stil procedural

array msgfmt_parse ( MessageFormatter $fmt , string $value )

Parses input string and return any extracted items as an array.

Parametri

fmt

The message formatter

value

The string to parse

Valorile întoarse

An array containing the items extracted, or FALSE on error

Exemple

Example #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);
?>

Example #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);
?>

Exemplul de mai sus va afi?a:

array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)
array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)

A se vedea ?i

  • 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
IntlCalendar
MessageFormatter
PHP Manual

MessageFormatter::setPattern

msgfmt_set_pattern

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

MessageFormatter::setPattern -- msgfmt_set_pattern — Set the pattern used by the formatter

Descrierea

Stil obiect-orientat

public bool MessageFormatter::setPattern ( string $pattern )

Stil procedural

bool msgfmt_set_pattern ( MessageFormatter $fmt , string $pattern )

Set the pattern used by the formatter

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_get_pattern() - Get the pattern used by the formatter

MessageFormatter::parse
IntlCalendar
MessageFormatter


The IntlCalendar class

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

Introducere

Sinopsisul clasei

IntlCalendar {
/* Constants */
const integer FIELD_ERA = 0 ;
const integer FIELD_YEAR = 1 ;
const integer FIELD_MONTH = 2 ;
const integer FIELD_WEEK_OF_YEAR = 3 ;
const integer FIELD_WEEK_OF_MONTH = 4 ;
const integer FIELD_DATE = 5 ;
const integer FIELD_DAY_OF_YEAR = 6 ;
const integer FIELD_DAY_OF_WEEK = 7 ;
const integer FIELD_DAY_OF_WEEK_IN_MONTH = 8 ;
const integer FIELD_AM_PM = 9 ;
const integer FIELD_HOUR = 10 ;
const integer FIELD_HOUR_OF_DAY = 11 ;
const integer FIELD_MINUTE = 12 ;
const integer FIELD_SECOND = 13 ;
const integer FIELD_MILLISECOND = 14 ;
const integer FIELD_ZONE_OFFSET = 15 ;
const integer FIELD_DST_OFFSET = 16 ;
const integer FIELD_YEAR_WOY = 17 ;
const integer FIELD_DOW_LOCAL = 18 ;
const integer FIELD_EXTENDED_YEAR = 19 ;
const integer FIELD_JULIAN_DAY = 20 ;
const integer FIELD_MILLISECONDS_IN_DAY = 21 ;
const integer FIELD_IS_LEAP_MONTH = 22 ;
const integer FIELD_FIELD_COUNT = 23 ;
const integer FIELD_DAY_OF_MONTH = 5 ;
const integer DOW_SUNDAY = 1 ;
const integer DOW_MONDAY = 2 ;
const integer DOW_TUESDAY = 3 ;
const integer DOW_WEDNESDAY = 4 ;
const integer DOW_THURSDAY = 5 ;
const integer DOW_FRIDAY = 6 ;
const integer DOW_SATURDAY = 7 ;
const integer DOW_TYPE_WEEKDAY = 0 ;
const integer DOW_TYPE_WEEKEND = 1 ;
const integer DOW_TYPE_WEEKEND_OFFSET = 2 ;
const integer DOW_TYPE_WEEKEND_CEASE = 3 ;
const integer WALLTIME_FIRST = 1 ;
const integer WALLTIME_LAST = 0 ;
const integer WALLTIME_NEXT_VALID = 2 ;
/* Metode */
public bool add ( int $field , int $amount )
bool intlcal_add ( IntlCalendar $cal , int $field , int $amount )
public bool after ( IntlCalendar $other )
bool intlcal_after ( IntlCalendar $cal , IntlCalendar $other )
public bool before ( IntlCalendar $other )
bool intlcal_before ( IntlCalendar $cal , IntlCalendar $other )
public bool clear ([ int $field = NULL ] )
bool intlcal_clear ( IntlCalendar $cal [, int $field = NULL ] )
private __construct ( void )
public static IntlCalendar createInstance ([ mixed $timeZone = NULL [, string $locale = "" ]] )
IntlCalendar intlcal_create_instance ([ mixed $timeZone = NULL [, string $locale = "" ]] )
public bool equals ( IntlCalendar $other )
bool intlcal_equals ( IntlCalendar $cal , IntlCalendar $other )
public int fieldDifference ( float $when , int $field )
int intlcal_field_difference ( IntlCalendar $cal , float $when , int $field )
public static IntlCalendar fromDateTime ( mixed $dateTime )
IntlCalendar intlcal_from_date_time ( mixed $dateTime )
public int get ( int $field )
int intlcal_get ( IntlCalendar> $cal , int $field )
public int getActualMaximum ( int $field )
int intlcal_get_actual_maximum ( IntlCalendar $cal , int $field )
public int getActualMinimum ( int $field )
int intlcal_get_actual_minimum ( IntlCalendar $cal , int $field )
public static array getAvailableLocales ( void )
array intlcal_get_available_locales ( void )
public int getDayOfWeekType ( int $dayOfWeek )
int intlcal_get_day_of_week_type ( IntlCalendar $cal , int $dayOfWeek )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public int getFirstDayOfWeek ( void )
int intlcal_get_first_day_of_week ( IntlCalendar $cal )
public int getGreatestMinimum ( int $field )
int intlcal_get_greatest_minimum ( IntlCalendar $cal , int $field )
public static Iterator getKeywordValuesForLocale ( string $key , string $locale , boolean $commonlyUsed )
Iterator intlcal_get_keyword_values_for_locale ( string $key , string $locale , boolean $commonlyUsed )
public int getLeastMaximum ( int $field )
int intlcal_get_least_maximum ( IntlCalendar $cal , int $field )
public string getLocale ( int $localeType )
string intlcal_get_locale ( IntlCalendar $cal , int $localeType )
public int getMaximum ( int $field )
int intlcal_get_maximum ( IntlCalendar $cal , int $field )
public int getMinimalDaysInFirstWeek ( void )
int intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal )
public int getMinimum ( int $field )
int intlcal_get_minimum ( IntlCalendar $cal , int $field )
public static float getNow ( void )
float intlcal_get_now ( void )
public int getRepeatedWallTimeOption ( void )
int intlcal_get_repeated_wall_time_option ( IntlCalendar $cal )
public int getSkippedWallTimeOption ( void )
int intlcal_get_skipped_wall_time_option ( IntlCalendar $cal )
public float getTime ( void )
float intlcal_get_time ( IntlCalendar $cal )
public IntlTimeZone getTimeZone ( void )
IntlTimeZone intlcal_get_time_zone ( IntlCalendar $cal )
public string getType ( void )
string intlcal_get_type ( IntlCalendar $cal )
public int getWeekendTransition ( string $dayOfWeek )
int intlcal_get_weekend_transition ( IntlCalendar $cal , string $dayOfWeek )
public bool inDaylightTime ( void )
bool intlcal_in_daylight_time ( IntlCalendar $cal )
public bool isEquivalentTo ( IntlCalendar $other )
bool intlcal_is_equivalent_to ( IntlCalendar $cal , IntlCalendar $other )
public bool isLenient ( void )
bool intlcal_is_lenient ( IntlCalendar $cal )
public bool isSet ( int $field )
bool intlcal_is_set ( IntlCalendar $cal , int $field )
public bool isWeekend ([ float $date = NULL ] )
bool intlcal_is_weekend ( IntlCalendar $cal [, float $date = NULL ] )
public bool roll ( int $field , mixed $amountOrUpOrDown )
bool intlcal_roll ( IntlCalendar $cal , int $field , mixed $amountOrUpOrDown )
public bool set ( int $field , int $value )
public bool set ( int $year , int $month [, int $dayOfMonth = NULL [, int $hour = NULL [, int $minute = NULL [, int $second = NULL ]]]] )
bool intlcal_set ( IntlCalendar $cal , int $field , int $value )
bool intlcal_set ( IntlCalendar $cal , int $year , int $month [, int $dayOfMonth = NULL [, int $hour = NULL [, int $minute = NULL [, int $second = NULL ]]]] )
public bool setFirstDayOfWeek ( int $dayOfWeek )
bool intlcal_set_first_day_of_week ( IntlCalendar $cal , int $dayOfWeek )
public ReturnType setLenient ( string $isLenient )
ReturnType intlcal_set_lenient ( IntlCalendar $cal , string $isLenient )
public bool setMinimalDaysInFirstWeek ( int $minimalDays )
bool intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal , int $minimalDays )
public bool setRepeatedWallTimeOption ( int $wallTimeOption )
bool intlcal_set_repeated_wall_time_option ( IntlCalendar $cal , int $wallTimeOption )
public bool setSkippedWallTimeOption ( int $wallTimeOption )
bool intlcal_set_skipped_wall_time_option ( IntlCalendar $cal , int $wallTimeOption )
public bool setTime ( float $date )
bool intlcal_set_time ( IntlCalendar $cal , float $date )
public bool setTimeZone ( mixed $timeZone )
bool intlcal_set_time_zone ( IntlCalendar $cal , mixed $timeZone )
public DateTime toDateTime ( void )
DateTime intlcal_to_date_time ( IntlCalendar $cal )
}

Constante predefinite

IntlCalendar::FIELD_ERA

Calendar field numerically representing an era, for instance 1 for AD and 0 for BC in the Gregorian/Julian calendars and 235 for the Heisei (??) era in the Japanese calendar. Not all calendars have more than one era.

IntlCalendar::FIELD_YEAR

Calendar field for the year. This is not unique across eras. If the calendar type has more than one era, generally the minimum value for this field will be 1.

IntlCalendar::FIELD_MONTH

Calendar field for the month. The month sequence is zero-based, so Janurary (here used to signify the first month of the calendar; this may be called another name, such as Muharram in the Islamic calendar) is represented by 0, February by 1, …, December by 11 and, for calendars that have it, the 13th or leap month by 12.

IntlCalendar::FIELD_WEEK_OF_YEAR

Calendar field for the number of the week of the year. This depends on which day of the week is deemed to start the week and the minimal number of days in a week.

IntlCalendar::FIELD_WEEK_OF_MONTH

Calendar field for the number of the week of the month. This depends on which day of the week is deemed to start the week and the minimal number of days in a week.

IntlCalendar::FIELD_DATE

Calendar field for the day of the month. The same as IntlCalendar::FIELD_DAY_OF_MONTH, which has a clearer name.

IntlCalendar::FIELD_DAY_OF_YEAR

Calendar field for the day of the year. For the Gregorian calendar, starts with 1 and ends with 365 or 366.

IntlCalendar::FIELD_DAY_OF_WEEK

Calendar field for the day of the week. Its values start with 1 (Sunday, see IntlCalendar::DOW_SUNDAY and subsequent constants) and the last valid value is 7 (Saturday).

IntlCalendar::FIELD_DAY_OF_WEEK_IN_MONTH

Given a day of the week (Sunday, Monday, …), this calendar field assigns an ordinal to such a day of the week in a specific month. Thus, if the value of this field is 1 and the value of the day of the week is 2 (Monday), then the set day of the month is the 1st Monday of the month; the maximum value is 5.

Additionally, the value 0 and negative values are also allowed. The value 0 encompasses the seven days that occur immediately before the first seven days of a month (which therefore have a ‘day of week in month’ with value 1). Negative values starts counting from the end of the month – -1 points to the last occurrence of a day of the week in a month, -2 to the second last, and so on.

Unlike IntlCalendar::FIELD_WEEK_OF_MONTH and IntlCalendar::FIELD_WEEK_OF_YEAR, this value does not depend on IntlCalendar::getFirstDayOfWeek() or on IntlCalendar::getMinimalDaysInFirstWeek(). The first Monday is the first Monday, even if it occurs in a week that belongs to the previous month.

IntlCalendar::FIELD_AM_PM

Calendar field indicating whether a time is before noon (value 0, AM) or after (1). Midnight is AM, noon is PM.

IntlCalendar::FIELD_HOUR

Calendar field for the hour, without specifying whether it's in the morning or in the afternoon. Valid values are 0 to 11.

IntlCalendar::FIELD_HOUR_OF_DAY

Calendar field for the full (24h) hour of the day. Valid values are 0 to 23.

IntlCalendar::FIELD_MINUTE

Calendar field for the minutes component of the time.

IntlCalendar::FIELD_SECOND

Calendar field for the seconds component of the time.

IntlCalendar::FIELD_MILLISECOND

Calendar field the milliseconds component of the time.

IntlCalendar::FIELD_ZONE_OFFSET

Calendar field indicating the raw offset of the timezone, in milliseconds. The raw offset is the timezone offset, excluding any offset due to daylight saving time.

IntlCalendar::FIELD_DST_OFFSET

Calendar field for the daylight saving time offset of the calendar's timezone, in milliseconds, if active for calendar's time.

IntlCalendar::FIELD_YEAR_WOY

Calendar field representing the year for week of year purposes.

IntlCalendar::FIELD_DOW_LOCAL

Calendar field for the localized day of the week. This is a value betwen 1 and 7, 1 being used for the day of the week that matches the value returned by IntlCalendar::getFirstDayOfWeek().

IntlCalendar::FIELD_EXTENDED_YEAR

Calendar field for a year number representation that is continuous across eras. For the Gregorian calendar, the value of this field matches that of IntlCalendar::FIELD_YEAR for AD years; a BC year y is represented by -y + 1.

IntlCalendar::FIELD_JULIAN_DAY

Calendar field for a modified Julian day number. It is different from a conventional Julian day number in that its transitions occur at local zone midnight rather than at noon UTC. It uniquely identifies a date.

IntlCalendar::FIELD_MILLISECONDS_IN_DAY

Calendar field encompassing the information in IntlCalendar::FIELD_HOUR_OF_DAY, IntlCalendar::FIELD_MINUTE, IntlCalendar::FIELD_SECOND and IntlCalendar::FIELD_MILLISECOND. Range is from the 0 to 24 * 3600 * 1000 - 1. It is not the amount of milliseconds ellapsed in the day since on DST transitions it will have discontinuities analog to those of the wall time.

IntlCalendar::FIELD_IS_LEAP_MONTH

Calendar field whose value is 1 for indicating a leap month and 0 otherwise.

IntlCalendar::FIELD_FIELD_COUNT

The total number of fields.

IntlCalendar::FIELD_DAY_OF_MONTH

Alias for IntlCalendar::FIELD_DATE.

IntlCalendar::DOW_SUNDAY

Sunday.

IntlCalendar::DOW_MONDAY

Monday.

IntlCalendar::DOW_TUESDAY

Tuesday.

IntlCalendar::DOW_WEDNESDAY

Wednesday.

IntlCalendar::DOW_THURSDAY

Thursday.

IntlCalendar::DOW_FRIDAY

Friday.

IntlCalendar::DOW_SATURDAY

Saturday.

IntlCalendar::DOW_TYPE_WEEKDAY

Output of IntlCalendar::getDayOfWeekType() indicating a day of week is a weekday.

IntlCalendar::DOW_TYPE_WEEKEND

Output of IntlCalendar::getDayOfWeekType() indicating a day of week belongs to the weekend.

IntlCalendar::DOW_TYPE_WEEKEND_OFFSET

Output of IntlCalendar::getDayOfWeekType() indicating the weekend begins during the given day of week.

IntlCalendar::DOW_TYPE_WEEKEND_CEASE

Output of IntlCalendar::getDayOfWeekType() indicating the weekend ends during the given day of week.

IntlCalendar::WALLTIME_FIRST

Output of IntlCalendar::getSkippedWallTimeOption() indicating that wall times in the skipped range should refer to the same instant as wall times with one hour less and of IntlCalendar::getRepeatedWallTimeOption() indicating the wall times in the repeated range should refer to the instant of the first occurrence of such wall time.

IntlCalendar::WALLTIME_LAST

Output of IntlCalendar::getSkippedWallTimeOption() indicating that wall times in the skipped range should refer to the same instant as wall times with one hour after and of IntlCalendar::getRepeatedWallTimeOption() indicating the wall times in the repeated range should refer to the instant of the second occurrence of such wall time.

IntlCalendar::WALLTIME_NEXT_VALID

Output of IntlCalendar::getSkippedWallTimeOption() indicating that wall times in the skipped range should refer to the instant when the daylight saving time transition occurs (begins).

Cuprins

  • IntlCalendar::add — Add a (signed) amount of time to a field
  • IntlCalendar::after — Whether this object's time is after that of the passed object
  • IntlCalendar::before — Whether this object's time is before that of the passed object
  • IntlCalendar::clear — Clear a field or all fields
  • IntlCalendar::__construct — Private constructor for disallowing instantiation
  • IntlCalendar::createInstance — Create a new IntlCalendar
  • IntlCalendar::equals — Compare time of two IntlCalendar objects for equality
  • IntlCalendar::fieldDifference — Calculate difference between given time and this object's time
  • IntlCalendar::fromDateTime — Create an IntlCalendar from a DateTime object or string
  • IntlCalendar::get — Get the value for a field
  • IntlCalendar::getActualMaximum — The maximum value for a field, considering the object's current time
  • IntlCalendar::getActualMinimum — The minimum value for a field, considering the object's current time
  • IntlCalendar::getAvailableLocales — Get array of locales for which there is data
  • IntlCalendar::getDayOfWeekType — Tell whether a day is a weekday, weekend or a day that has a transition between the two
  • IntlCalendar::getErrorCode — Get last error code on the object
  • IntlCalendar::getErrorMessage — Get last error message on the object
  • IntlCalendar::getFirstDayOfWeek — Get the first day of the week for the calendar's locale
  • IntlCalendar::getGreatestMinimum — Get the largest local minimum value for a field
  • IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values
  • IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field
  • IntlCalendar::getLocale — Get the locale associated with the object
  • IntlCalendar::getMaximum — Get the global maximum value for a field
  • IntlCalendar::getMinimalDaysInFirstWeek — Get minimal number of days the first week in a year or month can have
  • IntlCalendar::getMinimum — Get the global minimum value for a field
  • IntlCalendar::getNow — Get number representing the current time
  • IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time
  • IntlCalendar::getSkippedWallTimeOption — Get behavior for handling skipped wall time
  • IntlCalendar::getTime — Get time currently represented by the object
  • IntlCalendar::getTimeZone — Get the object's timezone
  • IntlCalendar::getType — Get the calendar type
  • IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends
  • IntlCalendar::inDaylightTime — Whether the object's time is in Daylight Savings Time
  • IntlCalendar::isEquivalentTo — Whether another calendar is equal but for a different time
  • IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode
  • IntlCalendar::isSet — Whether a field is set
  • IntlCalendar::isWeekend — Whether a certain date/time is in the weekend
  • IntlCalendar::roll — Add value to field without carrying into more significant fields
  • IntlCalendar::set — Set a time field or several common fields at once
  • IntlCalendar::setFirstDayOfWeek — Set the day on which the week is deemed to start
  • IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient
  • IntlCalendar::setMinimalDaysInFirstWeek — Set minimal number of days the first week in a year or month can have
  • IntlCalendar::setRepeatedWallTimeOption — Set behavior for handling repeating wall times at negative timezone offset transitions
  • IntlCalendar::setSkippedWallTimeOption — Set behavior for handling skipped wall times at positive timezone offset transitions
  • IntlCalendar::setTime — Set the calendar time in milliseconds since the epoch
  • IntlCalendar::setTimeZone — Set the timezone used by this calendar
  • IntlCalendar::toDateTime — Convert an IntlCalendar into a DateTime object
MessageFormatter::setPattern
IntlCalendar::add
intl


Add a (signed) amount of time to a field

IntlCalendar
IntlCalendar::after
IntlCalendar
PHP Manual

IntlCalendar::add

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::add — Add a (signed) amount of time to a field

Descrierea

Stil obiect-orientat

public bool IntlCalendar::add ( int $field , int $amount )

Stil procedural

bool intlcal_add ( IntlCalendar $cal , int $field , int $amount )

Add a signed amount to a field. Adding a positive amount allows advances in time, even if the numeric value of the field decreases (e.g. when working with years in BC dates).

Other fields may need to adjusted – for instance, adding a month to the 31st of January will result in the 28th (or 29th) of February. Contrary to IntlCalendar::roll(), when a value wraps around, more significant fields may change. For instance, adding a day to the 31st of January will result in the 1st of February, not the 1st of Janurary.

Parametri

cal

The IntlCalendar resource.

field

Una din constantele de câmp data/ora ale IntlCalendar. Acestea sunt valori întregi de la 0 pâna la IntlCalendar::FIELD_COUNT.

amount

The signed amount to add to the current field. If the amount is positive, the instant will be moved forward; if it is negative, the instant wil be moved into the past. The unit is implicit to the field type. For instance, hours for IntlCalendar::FIELD_HOUR_OF_DAY.

Valorile întoarse

Returns TRUE on success sau FALSE în cazul e?ecului.

Exemple

Example #1 IntlCalendar::add()

<?php
ini_set('intl.default_locale', 'fr_FR');
ini_set('date.timezone', 'UTC');

$cal = new IntlGregorianCalendar(2012, 0 /* January */, 31);
echo IntlDateFormatter::formatObject($cal), "\n";

$cal->add(IntlCalendar::FIELD_MONTH, 1);
echo IntlDateFormatter::formatObject($cal), "\n";

$cal->add(IntlCalendar::FIELD_DAY_OF_MONTH, 1);
echo IntlDateFormatter::formatObject($cal), "\n";

Exemplul de mai sus va afi?a:

31 janv. 2012 00:00:00
29 févr. 2012 00:00:00
1 mars 2012 00:00:00

IntlCalendar
IntlCalendar::after
IntlCalendar


Whether this object's time is after that of the passed object

IntlCalendar::add
IntlCalendar::before
IntlCalendar
PHP Manual

IntlCalendar::after

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::after — Whether this object's time is after that of the passed object

Descrierea

Stil obiect-orientat

public bool IntlCalendar::after ( IntlCalendar $other )

Stil procedural

bool intlcal_after ( IntlCalendar $cal , IntlCalendar $other )

Returns whether this object's time succeeds the argument's time.

Parametri

cal

The IntlCalendar resource.

other

The calendar whose time will be checked against the primary object's time.

Valorile întoarse

Returns TRUE if this object's current time is after that of the calendar argument's time. Returns FALSE otherwise. Also returns FALSE on failure. You can use exceptions or intl_get_error_code() to detect error conditions.

Exemple

Example #1 IntlCalendar::after()

<?php
$cal1 = IntlCalendar::createInstance();
$cal2 = clone $cal1;

var_dump($cal1->after($cal2), //false
        $cal2->after($cal1)); //false

$cal1->roll(IntlCalendar::FIELD_MILLISECOND, true);

var_dump($cal1->after($cal2), //true
        $cal2->after($cal1)); //false

IntlCalendar::add
IntlCalendar::before
IntlCalendar


Whether this object's time is before that of the passed object

IntlCalendar::after
IntlCalendar::clear
IntlCalendar
PHP Manual

IntlCalendar::before

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::before — Whether this object's time is before that of the passed object

Descrierea

Stil obiect-orientat

public bool IntlCalendar::before ( IntlCalendar $other )

Stil procedural

bool intlcal_before ( IntlCalendar $cal , IntlCalendar $other )

Returns whether this object's time precedes the argument's time.

Parametri

cal

The IntlCalendar resource.

other

The calendar whose time will be checked against the primary object's time.

Valorile întoarse

Returns TRUE if this object's current time is before that of the calendar argument's time. Returns FALSE otherwise. Also returns FALSE on failure. You can use exceptions or intl_get_error_code() to detect error conditions.

IntlCalendar::after
IntlCalendar::clear
IntlCalendar


Clear a field or all fields

IntlCalendar::before
IntlCalendar::__construct
IntlCalendar
PHP Manual

IntlCalendar::clear

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::clear — Clear a field or all fields

Descrierea

Stil obiect-orientat

public bool IntlCalendar::clear ([ int $field = NULL ] )

Stil procedural

bool intlcal_clear ( IntlCalendar $cal [, int $field = NULL ] )

Clears either all of the fields or a specific field. A cleared field is marked as unset, giving it the lowest priority against overlapping fields or even default values when calculating the time. Additionally, its value is set to 0, though given the field's low priority, its value may have been internally set to another value by the time the field has finished been queried.

Parametri

cal

The IntlCalendar resource.

field

Una din constantele de câmp data/ora ale IntlCalendar. Acestea sunt valori întregi de la 0 pâna la IntlCalendar::FIELD_COUNT.

Valorile întoarse

Returns TRUE on success sau FALSE în cazul e?ecului. Failure can only occur is invalid arguments are provided.

Exemple

Example #1 IntlCalendar::clear() examples

<?php
ini_set('intl.default_locale', 'es_ES');
ini_set('date.timezone', 'UTC');

$fields = array(
    'FIELD_ERA'                  => 0,
    'FIELD_YEAR'                 => 1,
    'FIELD_MONTH'                => 2,
    'FIELD_WEEK_OF_YEAR'         => 3,
    'FIELD_WEEK_OF_MONTH'        => 4,
    'FIELD_DATE'                 => 5,
    'FIELD_DAY_OF_YEAR'          => 6,
    'FIELD_DAY_OF_WEEK'          => 7,
    'FIELD_DAY_OF_WEEK_IN_MONTH' => 8,
    'FIELD_AM_PM'                => 9,
    'FIELD_HOUR'                 => 10,
    'FIELD_HOUR_OF_DAY'          => 11,
    'FIELD_MINUTE'               => 12,
    'FIELD_SECOND'               => 13,
    'FIELD_MILLISECOND'          => 14,
    'FIELD_ZONE_OFFSET'          => 15,
    'FIELD_DST_OFFSET'           => 16,
    'FIELD_YEAR_WOY'             => 17,
    'FIELD_DOW_LOCAL'            => 18,
    'FIELD_EXTENDED_YEAR'        => 19,
    'FIELD_JULIAN_DAY'           => 20,
    'FIELD_MILLISECONDS_IN_DAY'  => 21,
    'FIELD_IS_LEAP_MONTH'        => 22,
    'FIELD_FIELD_COUNT'          => 23,
);
function getSetFields(IntlCalendar $cal) {
    global $fields;
    $ret = array();
    foreach ($fields as $name => $value) {
        if ($cal->isSet($value)) {
            $ret[] = $name;
        }
    }
    return $ret;
}

$cal = new IntlGregorianCalendar(2013, 2 /* March */, 15);
echo "After GregorianCalendar creation\n";
print_r(getSetFields($cal));
echo "\n";

echo IntlDateFormatter::formatObject($cal), "\n";
echo "After the formatter requested the extended year\n";
print_r(getSetFields($cal));
echo "\n";

$cal->clear(IntlCalendar::FIELD_YEAR);
echo "After the year has been cleared, the date stays the same\n";
echo IntlDateFormatter::formatObject($cal), "\n";
echo "because FIELD_EXTENDED_YEAR is still set\n";
print_r(getSetFields($cal));
echo "\n";

var_dump($cal->clear(IntlCalendar::FIELD_EXTENDED_YEAR));
echo "After the extended year has been cleared\n";
print_r(getSetFields($cal));
echo IntlDateFormatter::formatObject($cal), "\n";
echo "\n";

echo "After the fields are recalculated,\n"
        . " extended year is set again (to 1970)\n";
print_r(getSetFields($cal));
echo "\n";

$cal->clear();
echo "After calling variant with no arguments\n";
print_r(getSetFields($cal));
echo IntlDateFormatter::formatObject($cal), "\n";

Exemplul de mai sus va afi?a:

After GregorianCalendar creation
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_YEAR
    [2] => FIELD_MONTH
    [3] => FIELD_DATE
)

15/03/2013 00:00:00
After the formatter requested the extended year
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_YEAR
    [2] => FIELD_MONTH
    [3] => FIELD_DATE
    [4] => FIELD_EXTENDED_YEAR
)

After the year has been cleared, the date stays the same
15/03/2013 00:00:00
because FIELD_EXTENDED_YEAR is still set
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_MONTH
    [2] => FIELD_DATE
    [3] => FIELD_EXTENDED_YEAR
)

bool(true)
After the extended year has been cleared
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_MONTH
    [2] => FIELD_DATE
)
15/03/1970 00:00:00

After the fields are recalculated,
 extended year is set again (to 1970)
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_MONTH
    [2] => FIELD_DATE
    [3] => FIELD_EXTENDED_YEAR
)

After calling variant with no arguments
Array
(
)
01/01/1970 00:00:00

IntlCalendar::before
IntlCalendar::__construct
IntlCalendar


Private constructor for disallowing instantiation

IntlCalendar::clear
IntlCalendar::createInstance
IntlCalendar
PHP Manual

IntlCalendar::__construct

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::__construct — Private constructor for disallowing instantiation

Descrierea

private IntlCalendar::__construct ( void )

A private constructor for disallowing instantiation with the new operator.

Call IntlCalendar::createInstance() instead.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

IntlCalendar::clear
IntlCalendar::createInstance
IntlCalendar


Create a new IntlCalendar

IntlCalendar::__construct
IntlCalendar::equals
IntlCalendar
PHP Manual

IntlCalendar::createInstance

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::createInstance — Create a new IntlCalendar

Descrierea

Stil obiect-orientat

public static IntlCalendar IntlCalendar::createInstance ([ mixed $timeZone = NULL [, string $locale = "" ]] )

Stil procedural

IntlCalendar intlcal_create_instance ([ mixed $timeZone = NULL [, string $locale = "" ]] )

Given a timezone and locale, this method creates an IntlCalendar object. This factory method may return a subclass of IntlCalendar.

The calendar created will represent the time instance at which it was created, based on the system time. The fields can all be cleared by calling IntCalendar::clear() with no arguments. See also IntlGregorianCalendar::__construct().

Parametri

timeZone

The timezone to use.

  • NULL, in which case the default timezone will be used, as specified in the ini setting date.timezone or through the function date_default_timezone_set() and as returned by date_default_timezone_get().

  • An IntlTimeZone, which will be used directly.

  • A DateTimeZone. Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICU's database, not PHP's.

  • A string, which should be a valid ICU timezone identifier. See IntlTimeZone::createTimeZoneIDEnumeration(). Raw offsets such as "GMT+08:30" are also accepted.

locale

A locale to use or NULL to use the default locale.

Valorile întoarse

The created IntlCalendar instance or NULL on failure.

Exemple

Example #1 IntlCalendar::createInstance()

<?php
ini_set('intl.default_locale', 'es_ES');
ini_set('date.timezone', 'Europe/Madrid');

$cal = IntlCalendar::createInstance();
echo "No arguments\n";
var_dump(get_class($cal),
        IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL));
echo "\n";

echo "Explicit timezone\n";
$cal = IntlCalendar::createInstance(IntlTimeZone::getGMT());
var_dump(get_class($cal),
        IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL));
echo "\n";

echo "Explicit locale (with calendar)\n";
$cal = IntlCalendar::createInstance(NULL, 'es_ES@calendar=persian');
var_dump(get_class($cal),
        IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL));

Exemplul de mai sus va afi?a:

No arguments
string(21) "IntlGregorianCalendar"
string(68) "martes 18 de junio de 2013 14:11:02 Hora de verano de Europa Central"

Explicit timezone
string(21) "IntlGregorianCalendar"
string(45) "martes 18 de junio de 2013 12:11:02 GMT+00:00"

Explicit locale (with calendar)
string(12) "IntlCalendar"
string(70) "martes 28 de Khordad de 1392 14:11:02 Hora de verano de Europa Central"

A se vedea ?i

  • IntlGregorianCalendar::__construct()

IntlCalendar::__construct
IntlCalendar::equals
IntlCalendar


Compare time of two IntlCalendar objects for equality

IntlCalendar::createInstance
IntlCalendar::fieldDifference
IntlCalendar
PHP Manual

IntlCalendar::equals

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::equals — Compare time of two IntlCalendar objects for equality

Descrierea

Stil obiect-orientat

public bool IntlCalendar::equals ( IntlCalendar $other )

Stil procedural

bool intlcal_equals ( IntlCalendar $cal , IntlCalendar $other )

Returns true if this calendar and the given calendar have the same time. The settings, calendar types and field states do not have to be the same.

Parametri

cal

The IntlCalendar resource.

other

The calendar to compare with the primary object.

Valorile întoarse

Returns TRUE if the current time of both this and the passed in IntlCalendar object are the same, or FALSE otherwise. The value FALSE can also be returned on failure. This can only happen if bad arguments are passed in. In any case, the two cases can be distinguished by calling intl_get_error_code().

Exemple

Example #1 IntlCalendar::equals()

<?php
ini_set('date.timezone', 'UTC');

$cal1 = IntlCalendar::createInstance(NULL, 'es_ES');
$cal2 = clone $cal1;

var_dump($cal1->equals($cal2)); //TRUE

//The locale is not included in the comparison
$cal2 = IntlCalendar::createInstance(NULL, 'pt_PT');
$cal2->setTime($cal1->getTime());
var_dump($cal1->equals($cal2)); //TRUE

//And set fields state is not included as well
$cal2->clear(IntlCalendar::FIELD_YEAR);
var_dump($cal1->isSet(IntlCalendar::FIELD_YEAR) ==
        $cal2->isSet(IntlCalendar::FIELD_YEAR)); //FALSE
var_dump($cal1->equals($cal2)); //TRUE

//Neither is the calendar type
$cal2 = IntlCalendar::createInstance(NULL, 'es_ES@calendar=islamic');
$cal2->setTime($cal1->getTime());
var_dump($cal1->equals($cal2)); //TRUE

//Only the time is
$cal2 = clone $cal1;
$cal2->setTime($cal1->getTime() + 1.);
var_dump($cal1->equals($cal2)); //FALSE

IntlCalendar::createInstance
IntlCalendar::fieldDifference
IntlCalendar


Calculate difference between given time and this object's time

IntlCalendar::equals
IntlCalendar::fromDateTime
IntlCalendar
PHP Manual

IntlCalendar::fieldDifference

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::fieldDifference — Calculate difference between given time and this object's time

Descrierea

Stil obiect-orientat

public int IntlCalendar::fieldDifference ( float $when , int $field )

Stil procedural

int intlcal_field_difference ( IntlCalendar $cal , float $when , int $field )

Return the difference between the given time and the time this object is set to, with respect to the quantity specified the field parameter.

This method is meant to be called successively, first with the most significant field of interest down to the least significant field. To this end, as a side effect, this calendar's value for the field specified is advanced by the amount returned.

Parametri

cal

The IntlCalendar resource.

when

The time against which to compare the quantity represented by the field. For the result to be positive, the time given for this parameter must be ahead of the time of the object the method is being invoked on.

field

The field that represents the quantity being compared.

Una din constantele de câmp data/ora ale IntlCalendar. Acestea sunt valori întregi de la 0 pâna la IntlCalendar::FIELD_COUNT.

Valorile întoarse

Returns a (signed) difference of time in the unit associated with the specified field sau FALSE în cazul e?ecului.

Exemple

Example #1 IntlCalendar::fieldDifference()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'fr_FR');

$cal1 = IntlCalendar::fromDateTime('2012-02-29 09:00:11');
$cal2 = IntlCalendar::fromDateTime('2013-03-01 09:19:29');
$time = $cal2->getTime();

echo "Time before: ", IntlDateFormatter::formatObject($cal1), "\n";

printf(
    "The difference in time is %d year(s), %d month(s), "
  . "%d day(s), %d hour(s) and %d minute(s)\n",
    $cal1->fieldDifference($time, IntlCalendar::FIELD_YEAR),
    $cal1->fieldDifference($time, IntlCalendar::FIELD_MONTH),
    $cal1->fieldDifference($time, IntlCalendar::FIELD_DAY_OF_MONTH),
    $cal1->fieldDifference($time, IntlCalendar::FIELD_HOUR_OF_DAY),
    $cal1->fieldDifference($time, IntlCalendar::FIELD_MINUTE)
);

//now it was advanced to the target time, exception for the seconds,
//for which we did not measure the difference
echo "Time after: ", IntlDateFormatter::formatObject($cal1), "\n";

Exemplul de mai sus va afi?a:

Time before: 29 févr. 2012 09:00:11
The difference in time is 1 year(s), 0 month(s), 1 day(s), 0 hour(s) and 19 minute(s)
Time after: 1 mars 2013 09:19:11

IntlCalendar::equals
IntlCalendar::fromDateTime
IntlCalendar


Create an IntlCalendar from a DateTime object or string

IntlCalendar::fieldDifference
IntlCalendar::get
IntlCalendar
PHP Manual

IntlCalendar::fromDateTime

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a2)

IntlCalendar::fromDateTime — Create an IntlCalendar from a DateTime object or string

Descrierea

Stil obiect-orientat

public static IntlCalendar IntlCalendar::fromDateTime ( mixed $dateTime )

Stil procedural

IntlCalendar intlcal_from_date_time ( mixed $dateTime )

Creates an IntlCalendar object either from a DateTime object or from a string from which a DateTime object can be built.

The new calendar will represent not only the same instant as the given DateTime (subject to precision loss for dates very far into the past or future), but also the same timezone (subject to the caveat that different timezone databases will be used, and therefore the results may differ).

Parametri

dateTime

A DateTime object or a string that can be passed to DateTime::__construct().

Valorile întoarse

The created IntlCalendar object or NULL in case of failure. If a string is passed, any exception that occurs inside the DateTime constructor is propagated.

Exemple

Example #1 IntlCalendar::fromDateTime()

<?php
ini_set('date.timezone', 'Europe/Lisbon');

//same as IntlCalendar::fromDateTime(new DateTime(...))
$cal1 = IntlCalendar::fromDateTime('2013-02-28 00:01:02 Europe/Berlin');

//Note the timezone is Europe/Berlin, not the default Europe/Lisbon
echo IntlDateFormatter::formatObject($cal1, 'yyyy MMMM d HH:mm:ss VVVV', 'de_DE'), "\n";

Exemplul de mai sus va afi?a:

2013 Februar 28 00:01:02 Deutschland Zeit

IntlCalendar::fieldDifference
IntlCalendar::get
IntlCalendar


Get the value for a field

IntlCalendar::fromDateTime
IntlCalendar::getActualMaximum
IntlCalendar
PHP Manual

IntlCalendar::get

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::get — Get the value for a field

Descrierea

Stil obiect-orientat

public int IntlCalendar::get ( int $field )

Stil procedural

int intlcal_get ( IntlCalendar> $cal , int $field )

Gets the value for a specific field.

Parametri

cal

The IntlCalendar resource.

field

Una din constantele de câmp data/ora ale IntlCalendar. Acestea sunt valori întregi de la 0 pâna la IntlCalendar::FIELD_COUNT.

Valorile întoarse

An integer with the value of the time field.

Exemple

Example #1 IntlCalendar::get()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');

$class = new ReflectionClass('IntlCalendar');
$fields = array();
foreach ($class->getConstants() as $name => $val) {
    if (strpos($name, 'FIELD_') !== 0 || $val > 22)
        continue;
    $fields[$val] = $name;
}

$cal = IntlCalendar::createInstance(); // current time
var_dump(IntlDateFormatter::formatObject($cal));
foreach ($fields as $val => $name) {
    echo "$val ($name)", "\n    ", $cal->get($val), "\n";
}

Exemplul de mai sus va afi?a:

string(23) "Jul 1, 2013, 4:44:44 AM"
0 (FIELD_ERA)
    1
1 (FIELD_YEAR)
    2013
2 (FIELD_MONTH)
    6
3 (FIELD_WEEK_OF_YEAR)
    27
4 (FIELD_WEEK_OF_MONTH)
    1
5 (FIELD_DAY_OF_MONTH)
    1
6 (FIELD_DAY_OF_YEAR)
    182
7 (FIELD_DAY_OF_WEEK)
    2
8 (FIELD_DAY_OF_WEEK_IN_MONTH)
    1
9 (FIELD_AM_PM)
    0
10 (FIELD_HOUR)
    4
11 (FIELD_HOUR_OF_DAY)
    4
12 (FIELD_MINUTE)
    44
13 (FIELD_SECOND)
    44
14 (FIELD_MILLISECOND)
    551
15 (FIELD_ZONE_OFFSET)
    0
16 (FIELD_DST_OFFSET)
    3600000
17 (FIELD_YEAR_WOY)
    2013
18 (FIELD_DOW_LOCAL)
    2
19 (FIELD_EXTENDED_YEAR)
    2013
20 (FIELD_JULIAN_DAY)
    2456475
21 (FIELD_MILLISECONDS_IN_DAY)
    17084551
22 (FIELD_IS_LEAP_MONTH)
    0

IntlCalendar::fromDateTime
IntlCalendar::getActualMaximum
IntlCalendar


The maximum value for a field, considering the object's current time

IntlCalendar::get
IntlCalendar::getActualMinimum
IntlCalendar
PHP Manual

IntlCalendar::getActualMaximum

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getActualMaximum — The maximum value for a field, considering the object's current time

Descrierea

Stil obiect-orientat

public int IntlCalendar::getActualMaximum ( int $field )

Stil procedural

int intlcal_get_actual_maximum ( IntlCalendar $cal , int $field )

Returns a field's relative maximum value around the current time. The exact semantics vary by field, but in the general case this is the value that would be obtained if one would set the field value into the smallest relative maximum for the field and would increment it until reaching the global maximum or the field value wraps around, in which the value returned would be the global maximum or the value before the wrapping, respectively.

For instance, in the gregorian calendar, the actual maximum value for the day of month would vary between 28 and 31, depending on the month and year of the current time.

Parametri

cal

The IntlCalendar resource.

field

Una din constantele de câmp data/ora ale IntlCalendar. Acestea sunt valori întregi de la 0 pâna la IntlCalendar::FIELD_COUNT.

Valorile întoarse

An int representing the maximum value in the units associated with the given field sau FALSE în cazul e?ecului.

Exemple

Example #1 IntlCalendar::getActualMaximum()

<?php
ini_set('date.timezone', 'Europe/Lisbon');

$cal = IntlCalendar::fromDateTime('2013-02-15');
var_dump($cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //28

$cal->add(IntlCalendar::FIELD_EXTENDED_YEAR, -1);
var_dump($cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //29

Exemplul de mai sus va afi?a:

int(28)
int(29)

A se vedea ?i

  • IntlCalendar::getMaximum() - Get the global maximum value for a field
  • IntlCalendar::getLeastMaximum() - Get the smallest local maximum for a field
  • IntlCalendar::getActualMinimum() - The minimum value for a field, considering the object's current time

IntlCalendar::get
IntlCalendar::getActualMinimum
IntlCalendar


The minimum value for a field, considering the object's current time

IntlCalendar::getActualMaximum
IntlCalendar::getAvailableLocales
IntlCalendar
PHP Manual

IntlCalendar::getActualMinimum

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getActualMinimum — The minimum value for a field, considering the object's current time

Descrierea

Stil obiect-orientat

public int IntlCalendar::getActualMinimum ( int $field )

Stil procedural

int intlcal_get_actual_minimum ( IntlCalendar $cal , int $field )

Returns a field's relative minimum value around the current time. The exact semantics vary by field, but in the general case this is the value that would be obtained if one would set the field value into the greatest relative minimum for the field and would decrement it until reaching the global minimum or the field value wraps around, in which the value returned would be the global minimum or the value before the wrapping, respectively.

For the Gregorian calendar, this is always the same as IntlCalendar::getMinimum().

Parametri

cal

The IntlCalendar resource.

field

Una din constantele de câmp data/ora ale IntlCalendar. Acestea sunt valori întregi de la 0 pâna la IntlCalendar::FIELD_COUNT.

Valorile întoarse

An int representing the minimum value in the field's unit sau FALSE în cazul e?ecului.

A se vedea ?i

  • IntlCalendar::getMinimum() - Get the global minimum value for a field
  • IntlCalendar::getGreatestMinimum() - Get the largest local minimum value for a field
  • IntlCalendar::getActualMaximum() - The maximum value for a field, considering the object's current time

IntlCalendar::getActualMaximum
IntlCalendar::getAvailableLocales
IntlCalendar


Get array of locales for which there is data

IntlCalendar::getActualMinimum
IntlCalendar::getDayOfWeekType
IntlCalendar
PHP Manual

IntlCalendar::getAvailableLocales

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getAvailableLocales — Get array of locales for which there is data

Descrierea

Stil obiect-orientat

public static array IntlCalendar::getAvailableLocales ( void )

Stil procedural

array intlcal_get_available_locales ( void )

Gives the list of locales for which calendars are installed. As of ICU 51, this is the list of all installed ICU locales.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array of strings, one for which locale.

Exemple

Example #1 IntlCalendar::getAvailableLocales()()

<?php
print_r(IntlCalendar::getAvailableLocales());

Exemplul de mai sus va afi?a:

Array
(
    [0] => af
    [1] => af_NA
    [2] => af_ZA
    [3] => agq
    [4] => agq_CM
    [5] => ak
    [6] => ak_GH
    [7] => am
    [8] => am_ET
    [9] => ar
    [10] => ar_001
    [11] => ar_AE
    [12] => ar_BH
    [13] => ar_DJ
    … output abbreviated …
    [595] => zh_Hant_HK
    [596] => zh_Hant_MO
    [597] => zh_Hant_TW
    [598] => zu
    [599] => zu_ZA
)

IntlCalendar::getActualMinimum
IntlCalendar::getDayOfWeekType
IntlCalendar


Tell whether a day is a weekday, weekend or a day that has a transition between the two

IntlCalendar::getAvailableLocales
IntlCalendar::getErrorCode
IntlCalendar
PHP Manual

IntlCalendar::getDayOfWeekType

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getDayOfWeekType — Tell whether a day is a weekday, weekend or a day that has a transition between the two

Descrierea

Stil obiect-orientat

public int IntlCalendar::getDayOfWeekType ( int $dayOfWeek )

Stil procedural

int intlcal_get_day_of_week_type ( IntlCalendar $cal , int $dayOfWeek )

Returns whether the passed day is a weekday (IntlCalendar::DOW_TYPE_WEEKDAY), a weekend day (IntlCalendar::DOW_TYPE_WEEKEND), a day during which a transition occurs into the weekend (IntlCalendar::DOW_TYPE_WEEKEND_OFFSET) or a day during which the weekend ceases (IntlCalendar::DOW_TYPE_WEEKEND_CEASE).

If the return is either
IntlCalendar::DOW_TYPE_WEEKEND_OFFSET or
IntlCalendar::DOW_TYPE_WEEKEND_CEASE, then
IntlCalendar::getWeekendTransition() can be called to
obtain the time of the transition.

This function requires ICU 4.4 or later.

Parametri

cal

The IntlCalendar resource.

dayOfWeek

One of the constants IntlCalendar::DOW_SUNDAY,
IntlCalendar::DOW_MONDAY, …,
IntlCalendar::DOW_SATURDAY.

Valorile întoarse

Returns one of the constants
IntlCalendar::DOW_TYPE_WEEKDAY,
IntlCalendar::DOW_TYPE_WEEKEND,
IntlCalendar::DOW_TYPE_WEEKEND_OFFSET or
IntlCalendar::DOW_TYPE_WEEKEND_CEASE sau FALSE în cazul e?ecului.

Exemple

Example #1 IntlCalendar::getDayOfWeekType()

<?php

foreach (array('en_US', 'ar_SA') as $locale) {
    echo "Locale: ", Locale::getDisplayName($locale, "en_US"), "\n";

    $cal = IntlCalendar::createInstance('UTC', $locale);

    for ($i = IntlCalendar::DOW_SUNDAY; $i <= IntlCalendar::DOW_SATURDAY; $i++) {
        echo $i, " ", $cal->getDayOfWeekType($i), " ",
                $cal->getDayOfWeekType($i) >= IntlCalendar::DOW_TYPE_WEEKEND_OFFSET
                        ? $cal->getWeekendTransition($i)
                        : '',
                "\n";
    }
    echo "\n";
}

Exemplul de mai sus va afi?a:

Locale: English (United States)
1 3 86400000
2 0
3 0
4 0
5 0
6 0
7 1

Locale: Arabic (Saudi Arabia)
1 0
2 0
3 0
4 0
5 1
6 3 86400000
7 0

IntlCalendar::getAvailableLocales
IntlCalendar::getErrorCode
IntlCalendar


Get last error code on the object

IntlCalendar::getDayOfWeekType
IntlCalendar::getErrorMessage
IntlCalendar
PHP Manual

IntlCalendar::getErrorCode

intlcal_get_error_code

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getErrorCode -- intlcal_get_error_code — Get last error code on the object

Descrierea

Stil obiect-orientat (method):

public int IntlCalendar::getErrorCode ( void )

Stil procedural:

int intlcal_get_error_code ( IntlCalendar $calendar )

Returns the numeric ICU error code for the last call on this object (including cloning) or the IntlCalendar given for the calendar parameter (in the procedural?style version). This may indicate only a warning (negative error code) or no error at all (U_ZERO_ERROR). The actual presence of an error can be tested with intl_is_failure().

Invalid arguments detected on the PHP side (before invoking functions of the ICU library) are not recorded for the purposes of this function.

The last error that occurred in any call to a function of the intl extension, including early argument errors, can be obtained with intl_get_error_code(). This function resets the global error code, but not the object's error code.

Parametri

calendar

The calendar object, on the procedural style interface.

Valorile întoarse

An ICU error code indicating either success, failure or a warning.

Exemple

Example #1 IntlCalendar::getErrorCode() and IntlCalendar::getErrorMessage()

<?php
ini_set("intl.error_level", E_WARNING);
ini_set("intl.default_locale", "nl");

$intlcal = new IntlGregorianCalendar(2012, 1, 29);
var_dump(
    $intlcal->getErrorCode(),
    $intlcal->getErrorMessage()
);
$intlcal->fieldDifference(-1e100, IntlCalendar::FIELD_SECOND);

var_dump(
    $intlcal->getErrorCode(),
    $intlcal->getErrorMessage()
);

Exemplul de mai sus va afi?a:

int(0)
string(12) "U_ZERO_ERROR"

Warning: IntlCalendar::fieldDifference(): intlcal_field_difference: Call to ICU method has failed in /home/glopes/php/ws/example.php on line 10
int(1)
string(81) "intlcal_field_difference: Call to ICU method has failed: U_ILLEGAL_ARGUMENT_ERROR"

A se vedea ?i

  • IntlCalendar::getErrorMessage() - Get last error message on the object
  • 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_code() - Get the last error code
  • intl_get_error_message() - Get description of the last error

IntlCalendar::getDayOfWeekType
IntlCalendar::getErrorMessage
IntlCalendar


Get last error message on the object

IntlCalendar::getErrorCode
IntlCalendar::getFirstDayOfWeek
IntlCalendar
PHP Manual

IntlCalendar::getErrorMessage

intlcal_get_error_message

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getErrorMessage -- intlcal_get_error_message — Get last error message on the object

Descrierea

Stil obiect-orientat (method):

public string IntlCalendar::getErrorMessage ( void )

Stil procedural:

string intlcal_get_error_message ( IntlCalendar $calendar )

Returns the error message (if any) associated with the error reported by IntlCalendar::getErrorCode() or intlcal_get_error_code(). If there is no associated error message, only the string representation of the name of the error constant will be returned. Otherwise, the message also includes a message set on the side of the PHP binding.

Parametri

calendar

The calendar object, on the procedural style interface.

Valorile întoarse

The error message associated with last error that occurred in a function call on this object, or a string indicating the non-existance of an error.

Exemple

Example #1 IntlCalendar::getErrorMessage()

<?php
$cal = IntlCalendar::createInstance('UTC', 'en_US');
var_dump($cal->getErrorMessage());

$cal->getWeekendTransition(IntlCalendar::DOW_WEDNESDAY);
var_dump($cal->getErrorMessage());

Exemplul de mai sus va afi?a:

string(12) "U_ZERO_ERROR"
string(82) "intlcal_get_weekend_transition: Error calling ICU method: U_ILLEGAL_ARGUMENT_ERROR"

IntlCalendar::getErrorCode
IntlCalendar::getFirstDayOfWeek
IntlCalendar


Get the first day of the week for the calendar's locale

IntlCalendar::getErrorMessage
IntlCalendar::getGreatestMinimum
IntlCalendar
PHP Manual

IntlCalendar::getFirstDayOfWeek

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getFirstDayOfWeek — Get the first day of the week for the calendar's locale

Descrierea

Stil obiect-orientat

public int IntlCalendar::getFirstDayOfWeek ( void )

Stil procedural

int intlcal_get_first_day_of_week ( IntlCalendar $cal )

The week day deemed to start a week, either the default value for this locale or the value set with IntlCalendar::setFirstDayOfWeek().

Parametri

cal

The IntlCalendar resource.

Valorile întoarse

One of the constants IntlCalendar::DOW_SUNDAY,
IntlCalendar::DOW_MONDAY, …,
IntlCalendar::DOW_SATURDAY sau FALSE în cazul e?ecului.

Exemple

Example #1 IntlCalendar::getFirstDayOfWeek()

<?php
ini_set('date.timezone', 'UTC');

$cal1 = IntlCalendar::createInstance(NULL, 'es_ES');
var_dump($cal1->getFirstDayOfWeek()); // Monday
$cal1->set(2013, 1 /* February */, 3); // a Sunday
var_dump($cal1->get(IntlCalendar::FIELD_WEEK_OF_YEAR)); // 5

$cal2 = IntlCalendar::createInstance(NULL, 'en_US');
var_dump($cal2->getFirstDayOfWeek()); // Sunday
$cal2->set(2013, 1 /* February */, 3); // a Sunday
var_dump($cal2->get(IntlCalendar::FIELD_WEEK_OF_YEAR)); // 6

Exemplul de mai sus va afi?a:

int(2)
int(5)
int(1)
int(6)

A se vedea ?i

  • IntlCalendar::setFirstDayOfWeek() - Set the day on which the week is deemed to start

IntlCalendar::getErrorMessage
IntlCalendar::getGreatestMinimum
IntlCalendar


Get the largest local minimum value for a field

IntlCalendar::getFirstDayOfWeek
IntlCalendar::getKeywordValuesForLocale
IntlCalendar
PHP Manual

IntlCalendar::getGreatestMinimum

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getGreatestMinimum — Get the largest local minimum value for a field

Descrierea

Stil obiect-orientat

public int IntlCalendar::getGreatestMinimum ( int $field )

Stil procedural

int intlcal_get_greatest_minimum ( IntlCalendar $cal , int $field )

Returns the largest local minimum for a field. This should be a value larger or equal to that returned by IntlCalendar::getActualMinimum(), which is in its turn larger or equal to that returned by IntlCalendar::getMinimum(). All these three functions return the same value for the Gregorian calendar.

Parametri

cal

The IntlCalendar resource.

field

Una din constantele de câmp data/ora ale IntlCalendar. Acestea sunt valori întregi de la 0 pâna la IntlCalendar::FIELD_COUNT.

Valorile întoarse

An int representing a field value, in the field's unit, sau FALSE în cazul e?ecului.

IntlCalendar::getFirstDayOfWeek
IntlCalendar::getKeywordValuesForLocale
IntlCalendar


Get set of locale keyword values

IntlCalendar::getGreatestMinimum
IntlCalendar::getLeastMaximum
IntlCalendar
PHP Manual

IntlCalendar::getKeywordValuesForLocale

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values

Descrierea

Stil obiect-orientat

public static Iterator IntlCalendar::getKeywordValuesForLocale ( string $key , string $locale , boolean $commonlyUsed )

Stil procedural

Iterator intlcal_get_keyword_values_for_locale ( string $key , string $locale , boolean $commonlyUsed )

For a given locale key, get the set of values for that key that would result in a different behavior. For now, only the 'calendar' keyword is supported.

This function requires ICU 4.2 or later.

Parametri

key

The locale keyword for which relevant values are to be queried. Only 'calendar' is supported.

locale

The locale onto which the keyword/value pair are to be appended.

commonlyUsed

Whether to show only the values commonly used for the specified locale.

Valorile întoarse

An iterator that yields strings with the locale keyword values sau FALSE în cazul e?ecului.

Exemple

Example #1 IntlCalendar::getKeyworkValuesForLocale()

<?php
print_r(
        iterator_to_array(
                IntlCalendar::getKeywordValuesForLocale(
                        'calendar', 'fa_IR', true)));
print_r(
        iterator_to_array(
                IntlCalendar::getKeywordValuesForLocale(
                        'calendar', 'fa_IR', false)));

Exemplul de mai sus va afi?a:

Array
(
    [0] => persian
    [1] => gregorian
    [2] => islamic
    [3] => islamic-civil
)
Array
(
    [0] => persian
    [1] => gregorian
    [2] => islamic
    [3] => islamic-civil
    [4] => japanese
    [5] => buddhist
    [6] => roc
    [7] => hebrew
    [8] => chinese
    [9] => indian
    [10] => coptic
    [11] => ethiopic
    [12] => ethiopic-amete-alem
)

IntlCalendar::getGreatestMinimum
IntlCalendar::getLeastMaximum
IntlCalendar


Get the smallest local maximum for a field

IntlCalendar::getKeywordValuesForLocale
IntlCalendar::getLocale
IntlCalendar
PHP Manual

IntlCalendar::getLeastMaximum

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field

Descrierea

Stil obiect-orientat

public int IntlCalendar::getLeastMaximum ( int $field )

Stil procedural

int intlcal_get_least_maximum ( IntlCalendar $cal , int $field )

Returns the smallest local maximumw for a field. This should be a value smaller or equal to that returned by IntlCalendar::getActualMaxmimum(), which is in its turn smaller or equal to that returned by IntlCalendar::getMaximum().

Parametri

cal

The IntlCalendar resource.

field

Una din constantele de câmp data/ora ale IntlCalendar. Acestea sunt valori întregi de la 0 pâna la IntlCalendar::FIELD_COUNT.

Valorile întoarse

An int representing a field value in the field's unit sau FALSE în cazul e?ecului.

Exemple

Example #1 Maxima examples

<?php
ini_set('date.timezone', 'UTC');
ini_set('intl.default_locale', 'it_IT');

$cal = new IntlGregorianCalendar(2013, 3 /* April */, 6);
var_dump(
    $cal->getLeastMaximum(IntlCalendar::FIELD_DAY_OF_MONTH),  // 28
    $cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH), // 30
    $cal->getMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)        // 31
);

Exemplul de mai sus va afi?a:

int(28)
int(30)
int(31)

A se vedea ?i

  • IntlCalendar::getActualMaximum() - The maximum value for a field, considering the object's current time
  • IntlCalendar::getMaximum() - Get the global maximum value for a field
  • IntlCalendar::getGreatestMinimum() - Get the largest local minimum value for a field

IntlCalendar::getKeywordValuesForLocale
IntlCalendar::getLocale
IntlCalendar


Get the locale associated with the object

IntlCalendar::getLeastMaximum
IntlCalendar::getMaximum
IntlCalendar
PHP Manual

IntlCalendar::getLocale

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getLocale — Get the locale associated with the object

Descrierea

Stil obiect-orientat

public string IntlCalendar::getLocale ( int $localeType )

Stil procedural

string intlcal_get_locale ( IntlCalendar $cal , int $localeType )

Returns the locale used by this calendar object.

Parametri

cal

The IntlCalendar resource.

localeType

Whether to fetch the actual locale (the locale from which the calendar data originates, with Locale::ACTUAL_LOCALE) or the valid locale, i.e., the most specific locale supported by ICU relatively to the requested locale – see Locale::VALID_LOCALE. From the most general to the most specific, the locales are ordered in this fashion – actual locale, valid locale, requested locale.

Valorile întoarse

A locale string sau FALSE în cazul e?ecului.

Exemple

Example #1 IntlCalendar::getLocale()

<?php
$cal = IntlCalendar::createInstance(IntlTimeZone::getGMT(), 'en_US_CALIFORNIA');
var_dump(
    $cal->getLocale(Locale::ACTUAL_LOCALE),
    $cal->getLocale(Locale::VALID_LOCALE)
);

Exemplul de mai sus va afi?a:

string(2) "en"
string(5) "en_US"

IntlCalendar::getLeastMaximum
IntlCalendar::getMaximum
IntlCalendar


Get the global maximum value for a field

IntlCalendar::getLocale
IntlCalendar::getMinimalDaysInFirstWeek
IntlCalendar
PHP Manual

IntlCalendar::getMaximum

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getMaximum — Get the global maximum value for a field

Descrierea

Stil obiect-orientat

public int IntlCalendar::getMaximum ( int $field )

Stil procedural

int intlcal_get_maximum ( IntlCalendar $cal , int $field )

Gets the global maximum for a field, in this specific calendar. This value is larger or equal to that returned by IntlCalendar::getActualMaximum(), which is in its turn larger or equal to that returned by IntlCalendar::getLeastMaximum().

Parametri

cal

The IntlCalendar resource.

field

Una din constantele de câmp data/ora ale IntlCalendar. Acestea sunt valori întregi de la 0 pâna la IntlCalendar::FIELD_COUNT.

Valorile întoarse

An int representing a field value in the field's unit sau FALSE în cazul e?ecului.

A se vedea ?i

  • IntlCalendar::getActualMaximum() - The maximum value for a field, considering the object's current time
  • IntlCalendar::getLeastMaximum() - Get the smallest local maximum for a field
  • IntlCalendar::getMinimum() - Get the global minimum value for a field

IntlCalendar::getLocale
IntlCalendar::getMinimalDaysInFirstWeek
IntlCalendar


Get minimal number of days the first week in a year or month can have

IntlCalendar::getMaximum
IntlCalendar::getMinimum
IntlCalendar
PHP Manual

IntlCalendar::getMinimalDaysInFirstWeek

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getMinimalDaysInFirstWeek — Get minimal number of days the first week in a year or month can have

Descrierea

Stil obiect-orientat

public int IntlCalendar::getMinimalDaysInFirstWeek ( void )

Stil procedural

int intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal )

Returns the smallest number of days the first week of a year or month must have in the new year or month. For instance, in the Gregorian calendar, if this value is 1, then the first week of the year will necessarily include January 1st, while if this value is 7, then the week with January 1st will be the first week of the year only if the day of the week for January 1st matches the day of the week returned by IntlCalendar::getFirstDayOfWeek(); otherwise it will be the previous year's last week.

Parametri

cal

The IntlCalendar resource.

Valorile întoarse

An int representing a number of days sau FALSE în cazul e?ecului.

Exemple

Example #1 IntlCalendar::getMinimalDaysInFirstWeek()

<?php
ini_set('date.timezone', 'UTC');
ini_set('intl.default_locale', 'en_US');

$cal = new IntlGregorianCalendar(2013, 0 /* January */, 2);
var_dump(IntlDateFormatter::formatObject($cal, 'cccc')); // Wednesday

var_dump($cal->getMinimalDaysInFirstWeek(), // 1
$cal->getFirstDayofWeek()); // 1 (Sunday)

// Week 1 of 2013
var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y"));

$cal->setMinimalDaysInFirstWeek(4);
// Still Week 1 of 2013 (1st week has 5 days in the new year)
var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y"));

$cal->setMinimalDaysInFirstWeek(6);
// Week 53 of 2012
var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y"));

Exemplul de mai sus va afi?a:

string(9) "Wednesday"
int(1)
int(1)
string(14) "Week 1 of 2013"
string(14) "Week 1 of 2013"
string(15) "Week 53 of 2012"

IntlCalendar::getMaximum
IntlCalendar::getMinimum
IntlCalendar


Get the global minimum value for a field

IntlCalendar::getMinimalDaysInFirstWeek
IntlCalendar::getNow
IntlCalendar
PHP Manual

IntlCalendar::getMinimum

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getMinimum — Get the global minimum value for a field

Descrierea

Stil obiect-orientat

public int IntlCalendar::getMinimum ( int $field )

Stil procedural

int intlcal_get_minimum ( IntlCalendar $cal , int $field )

Gets the global minimum for a field, in this specific calendar. This value is smaller or equal to that returned by IntlCalendar::getActualMinimum(), which is in its turn smaller or equal to that returned by IntlCalendar::getGreatestMinimum(). For the Gregorian calendar, these three functions always return the same value (for each field).

Parametri

cal

The IntlCalendar resource.

field

Una din constantele de câmp data/ora ale IntlCalendar. Acestea sunt valori întregi de la 0 pâna la IntlCalendar::FIELD_COUNT.

Valorile întoarse

An int representing a value for the given field in the field's unit sau FALSE în cazul e?ecului.

IntlCalendar::getMinimalDaysInFirstWeek
IntlCalendar::getNow
IntlCalendar


Get number representing the current time

IntlCalendar::getMinimum
IntlCalendar::getRepeatedWallTimeOption
IntlCalendar
PHP Manual

IntlCalendar::getNow

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getNow — Get number representing the current time

Descrierea

Stil obiect-orientat

public static float IntlCalendar::getNow ( void )

Stil procedural

float intlcal_get_now ( void )

The number of milliseconds that have passed since the reference date. This number is derived from the system time.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A float representing a number of milliseconds since the epoch, not counting leap seconds.

Exemple

Example #1 IntlCalendar::getNow()

<?php
$formatter = IntlDateFormatter::create('es_ES',
        IntlDateFormatter::FULL,
        IntlDateFormatter::FULL,
        'Europe/Madrid');

$val = IntlCalendar::getNow();

var_dump($val);
echo $formatter->format(IntlCalendar::getNow() / 1000.), "\n";

Exemplul de mai sus va afi?a:

float(1371425814666)
lunes, 17 de junio de 2013 01:36:54 Hora de verano de Europa central

IntlCalendar::getMinimum
IntlCalendar::getRepeatedWallTimeOption
IntlCalendar


Get behavior for handling repeating wall time

IntlCalendar::getNow
IntlCalendar::getSkippedWallTimeOption
IntlCalendar
PHP Manual

IntlCalendar::getRepeatedWallTimeOption

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time

Descrierea

Stil obiect-orientat

public int IntlCalendar::getRepeatedWallTimeOption ( void )

Stil procedural

int intlcal_get_repeated_wall_time_option ( IntlCalendar $cal )

Gets the current strategy for dealing with wall times that are repeated whenever the clock is set back during dailight saving time end transitions. The default value is IntlCalendar::WALLTIME_LAST.

This function requires ICU 4.9 or later.

Parametri

cal

The IntlCalendar resource.

Valorile întoarse

One of the constants IntlCalendar::WALLTIME_FIRST or IntlCalendar::WALLTIME_LAST.

Exemple

Example #1 IntlCalendar::getRepeatedWallTimeOption()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');
ini_set('intl.error_level', E_WARNING);

//On October 27th at 0200, the clock goes back 1 hour and from GMT+01 to GMT+00
$cal = new IntlGregorianCalendar(2013, 9 /* October */, 27, 1, 30);

var_dump($cal->getRepeatedWalltimeOption()); // 0 WALLTIME_LAST

$formatter = IntlDateFormatter::create(
    NULL,
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'UTC'
);
var_dump($formatter->format($cal->getTime() / 1000.));

$cal->setRepeatedWalltimeOption(IntlCalendar::WALLTIME_FIRST);
var_dump($cal->getRepeatedWalltimeOption()); // 1 WALLTIME_FIRST
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1);

var_dump($formatter->format($cal->getTime() / 1000.));

Exemplul de mai sus va afi?a:

int(0)
string(42) "Sunday, October 27, 2013 at 1:30:00 AM GMT"
int(1)
string(43) "Sunday, October 27, 2013 at 12:30:00 AM GMT"

A se vedea ?i

  • IntlCalendar::getSkippedWallTimeOption() - Get behavior for handling skipped wall time
  • IntlCalendar::setSkippedWallTimeOption() - Set behavior for handling skipped wall times at positive timezone offset transitions
  • IntlCalendar::setRepeatedWallTimeOption() - Set behavior for handling repeating wall times at negative timezone offset transitions

IntlCalendar::getNow
IntlCalendar::getSkippedWallTimeOption
IntlCalendar


Get behavior for handling skipped wall time

IntlCalendar::getRepeatedWallTimeOption
IntlCalendar::getTime
IntlCalendar
PHP Manual

IntlCalendar::getSkippedWallTimeOption

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getSkippedWallTimeOption — Get behavior for handling skipped wall time

Descrierea

Stil obiect-orientat

public int IntlCalendar::getSkippedWallTimeOption ( void )

Stil procedural

int intlcal_get_skipped_wall_time_option ( IntlCalendar $cal )

Gets the current strategy for dealing with wall times that are skipped whenever the clock is forwarded during dailight saving time start transitions. The default value is IntlCalendar::WALLTIME_LAST.

The calendar must be lenient for this option to have any effect, otherwise attempting to set a non-existing time will cause an error.

This function requires ICU 4.9 or later.

Parametri

cal

The IntlCalendar resource.

Valorile întoarse

One of the constants IntlCalendar::WALLTIME_FIRST,
IntlCalendar::WALLTIME_LAST or
IntlCalendar::WALLTIME_NEXT_VALID.

Exemple

Example #1 IntlCalendar::getSkippedWallTimeOption()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');
ini_set('intl.error_level', E_WARNING);

//On March 31st at 0100, the clock goes forward 1 hour and from GMT+00 to GMT+01
$cal = new IntlGregorianCalendar(2013, 2 /* March */, 31, 1, 30);

var_dump(
    $cal->isLenient(),               // true
    $cal->getSkippedWalltimeOption() // 0 WALLTIME_LAST
);

$formatter = IntlDateFormatter::create(
    NULL,
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'UTC'
);
var_dump($formatter->format($cal->getTime() / 1000));

$cal->setSkippedWallTimeOption(IntlCalendar::WALLTIME_FIRST);
var_dump($cal->getSkippedWalltimeOption()); // 1 WALLTIME_FIRST
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1);

var_dump($formatter->format($cal->getTime() / 1000));

$cal->setSkippedWallTimeOption(IntlCalendar::WALLTIME_NEXT_VALID);
var_dump($cal->getSkippedWalltimeOption()); // 2 WALLTIME_NEXT_VALID
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1);

var_dump($formatter->format($cal->getTime() / 1000));

Exemplul de mai sus va afi?a:

bool(true)
int(0)
string(40) "Sunday, March 31, 2013 at 1:30:00 AM GMT"
int(1)
string(41) "Sunday, March 31, 2013 at 12:30:00 AM GMT"
int(2)
string(40) "Sunday, March 31, 2013 at 1:00:00 AM GMT"

A se vedea ?i

  • IntlCalendar::getRepeatedWallTimeOption() - Get behavior for handling repeating wall time
  • IntlCalendar::setSkippedWallTimeOption() - Set behavior for handling skipped wall times at positive timezone offset transitions
  • IntlCalendar::setRepeatedWallTimeOption() - Set behavior for handling repeating wall times at negative timezone offset transitions

IntlCalendar::getRepeatedWallTimeOption
IntlCalendar::getTime
IntlCalendar


Get time currently represented by the object

IntlCalendar::getSkippedWallTimeOption
IntlCalendar::getTimeZone
IntlCalendar
PHP Manual

IntlCalendar::getTime

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getTime — Get time currently represented by the object

Descrierea

Stil obiect-orientat

public float IntlCalendar::getTime ( void )

Stil procedural

float intlcal_get_time ( IntlCalendar $cal )

Returns the time associated with this object, expressed as the number of milliseconds since the epoch.

Parametri

cal

The IntlCalendar resource.

Valorile întoarse

A float representing the number of milliseconds elapsed since the reference time (1 Jan 1970 00:00:00 UTC).

Exemple

Example #1 IntlCalendar::getTime()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');

$cal = new IntlGregorianCalendar(2013, 4 /* May */, 1, 0, 0, 0);
$time = $cal->getTime();
var_dump($time, $time / 1000 == strtotime('2013-05-01 00:00:00')); //true

Exemplul de mai sus va afi?a:

float(1367362800000)
bool(true)

A se vedea ?i

  • IntlCalendar::getNow() - Get number representing the current time

IntlCalendar::getSkippedWallTimeOption
IntlCalendar::getTimeZone
IntlCalendar


Get the object's timezone

IntlCalendar::getTime
IntlCalendar::getType
IntlCalendar
PHP Manual

IntlCalendar::getTimeZone

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getTimeZone — Get the object's timezone

Descrierea

Stil obiect-orientat

public IntlTimeZone IntlCalendar::getTimeZone ( void )

Stil procedural

IntlTimeZone intlcal_get_time_zone ( IntlCalendar $cal )

Returns the IntlTimeZone object associated with this calendar.

Parametri

cal

The IntlCalendar resource.

Valorile întoarse

An IntlTimeZone object corresponding to the one used internally in this object.

Exemple

Example #1 IntlCalendar::getTimeZone()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');

$cal = IntlCalendar::createInstance();
print_r($cal->getTimeZone());

$cal->setTimeZone('UTC');
print_r($cal->getTimeZone());

$cal = IntlCalendar::fromDateTime('2012-01-01 00:00:00 GMT+03:33');
print_r($cal->getTimeZone());

Exemplul de mai sus va afi?a:

IntlTimeZone Object
(
    [valid] => 1
    [id] => Europe/Lisbon
    [rawOffset] => 0
    [currentOffset] => 3600000
)
IntlTimeZone Object
(
    [valid] => 1
    [id] => UTC
    [rawOffset] => 0
    [currentOffset] => 0
)
IntlTimeZone Object
(
    [valid] => 1
    [id] => GMT+03:33
    [rawOffset] => 12780000
    [currentOffset] => 12780000
)

A se vedea ?i

  • IntlCalendar::setTimeZone() - Set the timezone used by this calendar
  • IntlCalendar::createInstance() - Create a new IntlCalendar
  • IntlGregorianCalendar::__construct()

IntlCalendar::getTime
IntlCalendar::getType
IntlCalendar


Get the calendar type

IntlCalendar::getTimeZone
IntlCalendar::getWeekendTransition
IntlCalendar
PHP Manual

IntlCalendar::getType

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getType — Get the calendar type

Descrierea

Stil obiect-orientat

public string IntlCalendar::getType ( void )

Stil procedural

string intlcal_get_type ( IntlCalendar $cal )

A string describing the type of this calendar. This is one of the valid values for the calendar keyword value 'calendar'.

Parametri

cal

The IntlCalendar resource.

Valorile întoarse

A string representing the calendar type, such as 'gregorian', 'islamic', etc.

Exemple

Example #1 IntlCalendar::getType()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');

$cal = IntlCalendar::createInstance(NULL, '@calendar=ethiopic-amete-alem');
var_dump($cal->getType());

$cal = new IntlGregorianCalendar();
var_dump($cal->getType());

Exemplul de mai sus va afi?a:

string(19) "ethiopic-amete-alem"
string(9) "gregorian"

IntlCalendar::getTimeZone
IntlCalendar::getWeekendTransition
IntlCalendar


Get time of the day at which weekend begins or ends

IntlCalendar::getType
IntlCalendar::inDaylightTime
IntlCalendar
PHP Manual

IntlCalendar::getWeekendTransition

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends

Descrierea

Stil obiect-orientat

public int IntlCalendar::getWeekendTransition ( string $dayOfWeek )

Stil procedural

int intlcal_get_weekend_transition ( IntlCalendar $cal , string $dayOfWeek )

Returns the number of milliseconds after midnight at which the weekend begins or ends.

This is only applicable for days of the week for which
IntlCalendar::getDayOfWeekType() returns either
IntlCalendar::DOW_TYPE_WEEKEND_OFFSET or
IntlCalendar::DOW_TYPE_WEEKEND_CEASE. Calling this
function for other days of the week is an error condition.

This function requires ICU 4.4 or later.

Parametri

cal

The IntlCalendar resource.

dayOfWeek

One of the constants IntlCalendar::DOW_SUNDAY,
IntlCalendar::DOW_MONDAY, …,
IntlCalendar::DOW_SATURDAY.

Valorile întoarse

The number of milliseconds into the day at which the weekend begins or ends sau FALSE în cazul e?ecului.

Exemple

See example on IntlCalendar::getDayOfWeekType().

IntlCalendar::getType
IntlCalendar::inDaylightTime
IntlCalendar


Whether the object's time is in Daylight Savings Time

IntlCalendar::getWeekendTransition
IntlCalendar::isEquivalentTo
IntlCalendar
PHP Manual

IntlCalendar::inDaylightTime

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::inDaylightTime — Whether the object's time is in Daylight Savings Time

Descrierea

Stil obiect-orientat

public bool IntlCalendar::inDaylightTime ( void )

Stil procedural

bool intlcal_in_daylight_time ( IntlCalendar $cal )

Whether, for the instant represented by this object and for this object's timezone, daylight saving time is in place.

Parametri

cal

The IntlCalendar resource.

Valorile întoarse

Returns TRUE if the date is in Daylight Savings Time, FALSE otherwise. The value FALSE may also be returned on failure, for instance after specifying invalid field values on non-lenient mode; use exceptions or query intl_get_error_code() to disambiguate.

Exemple

Example #1 IntlCalendar::inDaylightTime()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');

$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1, 4, 56, 31);
var_dump($cal->inDaylightTime()); // true
$cal->set(IntlCalendar::FIELD_MONTH, 11 /* December */);
var_dump($cal->inDaylightTime()); // false

//DST end transition on 2013-10-27 at 0200 (wall time back 1 hour)
$cal = new IntlGregorianCalendar(2013, 9 /* October */, 27, 1, 30, 0);

var_dump($cal->inDaylightTime()); // false (default WALLTIME_LAST)

$cal->setRepeatedWallTimeOption(IntlCalendar::WALLTIME_FIRST);
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1); // force time recalculation
var_dump($cal->inDaylightTime()); // true

IntlCalendar::getWeekendTransition
IntlCalendar::isEquivalentTo
IntlCalendar


Whether another calendar is equal but for a different time

IntlCalendar::inDaylightTime
IntlCalendar::isLenient
IntlCalendar
PHP Manual

IntlCalendar::isEquivalentTo

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::isEquivalentTo — Whether another calendar is equal but for a different time

Descrierea

Stil obiect-orientat

public bool IntlCalendar::isEquivalentTo ( IntlCalendar $other )

Stil procedural

bool intlcal_is_equivalent_to ( IntlCalendar $cal , IntlCalendar $other )

Returns whether this and the given object are equivalent for all purposes except as to the time they have set. The locales do not have to match, as long as no change in behavior results from such mismatch. This includes the timezone, whether the lenient mode is set, the repeated and skipped wall time settings, the days of the week when the weekend starts and ceases and the times where such transitions occur. It may also include other calendar specific settings, such as the Gregorian/Julian transition instant.

Parametri

cal

The IntlCalendar resource.

other

The other calendar against which the comparison is to be made.

Valorile întoarse

Assuming there are no argument errors, returns TRUE iif the calendars are equivalent except possibly for their set time.

Exemple

Example #1 IntlCalendar::isEquivalentTo()

<?php
$cal1 = IntlCalendar::createInstance('Europe/Lisbon', 'pt_PT');
$cal2 = IntlCalendar::createInstance('Europe/Lisbon', 'es_ES');
$cal2->clear();

var_dump($cal1->isEquivalentTo($cal2)); // true

$cal3 = IntlCalendar::createInstance('Europe/Lisbon', 'en_US');
var_dump($cal1->isEquivalentTo($cal3)); // false
var_dump($cal1->getFirstDayOfWeek(),    // 2 (Monday)
$cal3->getFirstDayOfWeek());            // 1 (Sunday)

Exemplul de mai sus va afi?a:

bool(true)
bool(false)
int(2)
int(1)

A se vedea ?i

  • IntlCalendar::equals() - Compare time of two IntlCalendar objects for equality

IntlCalendar::inDaylightTime
IntlCalendar::isLenient
IntlCalendar


Whether date/time interpretation is in lenient mode

IntlCalendar::isEquivalentTo
IntlCalendar::isSet
IntlCalendar
PHP Manual

IntlCalendar::isLenient

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode

Descrierea

Stil obiect-orientat

public bool IntlCalendar::isLenient ( void )

Stil procedural

bool intlcal_is_lenient ( IntlCalendar $cal )

Returns whether the current date/time interpretations is lenient (the default). If that is case, some out of range values for fields will be accepted instead of raising an error.

Parametri

cal

The IntlCalendar resource.

Valorile întoarse

A bool representing whether the calendar is set to lenient mode.

Exemple

Example #1 IntlCalendar::isLenient()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');
ini_set('intl.use_exceptions', '1');

$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1);
var_dump(IntlDateFormatter::formatObject($cal), // 01/07/2013, 00:00:00
$cal->isLenient()); // true

$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 33);
var_dump(IntlDateFormatter::formatObject($cal)); // 02/08/2013, 00:00:00

$cal->setLenient(false);
var_dump($cal->isLenient()); // false
$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 33);
var_dump(IntlDateFormatter::formatObject($cal)); // error

Exemplul de mai sus va afi?a:

string(20) "01/07/2013, 00:00:00"
bool(true)
string(20) "02/08/2013, 00:00:00"
bool(false)

Fatal error: Uncaught exception 'IntlException' with message 'datefmt_format_object: error obtaining instant from IntlCalendar' in /home/foobar/example.php:16
Stack trace:
#0 /home/foobar/example.php(16): IntlDateFormatter::formatObject(Object(IntlGregorianCalendar))
#1 {main}
  thrown in /home/foobar/example.php on line 16

IntlCalendar::isEquivalentTo
IntlCalendar::isSet
IntlCalendar


Whether a field is set

IntlCalendar::isLenient
IntlCalendar::isWeekend
IntlCalendar
PHP Manual

IntlCalendar::isSet

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::isSet — Whether a field is set

Descrierea

Stil obiect-orientat

public bool IntlCalendar::isSet ( int $field )

Stil procedural

bool intlcal_is_set ( IntlCalendar $cal , int $field )

Returns whether a field is set (as opposed to clear). Set fields take priority over unset fields and their default values when the date/time is being calculated. Fields set later take priority over fields set earlier.

Parametri

cal

The IntlCalendar resource.

field

Una din constantele de câmp data/ora ale IntlCalendar. Acestea sunt valori întregi de la 0 pâna la IntlCalendar::FIELD_COUNT.

Valorile întoarse

Assuming there are no argument errors, returns TRUE iif the field is set.

Exemple

See the example on IntlCalendar::clear().

A se vedea ?i

  • IntlCalendar::clear() - Clear a field or all fields
  • IntlCalendar::set() - Set a time field or several common fields at once

IntlCalendar::isLenient
IntlCalendar::isWeekend
IntlCalendar


Whether a certain date/time is in the weekend

IntlCalendar::isSet
IntlCalendar::roll
IntlCalendar
PHP Manual

IntlCalendar::isWeekend

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::isWeekend — Whether a certain date/time is in the weekend

Descrierea

Stil obiect-orientat

public bool IntlCalendar::isWeekend ([ float $date = NULL ] )

Stil procedural

bool intlcal_is_weekend ( IntlCalendar $cal [, float $date = NULL ] )

Returns whether either the obejct's current time or the provided timestamp occur during a weekend in this object's calendar system.

This function requires ICU 4.4 or later.

Parametri

cal

The IntlCalendar resource.

date

An optional timestamp representing the number of milliseconds since the epoch, excluding leap seconds. If NULL, this object's current time is used instead.

Valorile întoarse

A bool indicating whether the given or this object's time occurs in a weekend.

The value FALSE may also be returned on failure, for instance after giving a date out of bounds on non-lenient mode; use exceptions or query intl_get_error_code() to disambiguate.

Exemple

Example #1 IntlCalendar::isWeekend()

<?php
ini_set('date.timezone', 'Europe/Lisbon');

$cal = new IntlGregorianCalendar(NULL, 'en_US');
$cal->set(2013, 6 /* July */, 7); // a Sunday

var_dump($cal->isWeekend()); // true
var_dump($cal->isWeekend(strtotime('2013-07-01 00:00:00'))); // false, Monday

$cal = new IntlGregorianCalendar(NULL, 'ar_SA');
$cal->set(2013, 6 /* July */, 7); // a Sunday
var_dump($cal->isWeekend()); // false, Sunday not in weekend in this calendar

A se vedea ?i

  • IntlCalendar::getDayOfWeekType() - Tell whether a day is a weekday, weekend or a day that has a transition between the two
  • IntlCalendar::getWeekendTransition() - Get time of the day at which weekend begins or ends

IntlCalendar::isSet
IntlCalendar::roll
IntlCalendar


Add value to field without carrying into more significant fields

IntlCalendar::isWeekend
IntlCalendar::set
IntlCalendar
PHP Manual

IntlCalendar::roll

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::roll — Add value to field without carrying into more significant fields

Descrierea

Stil obiect-orientat

public bool IntlCalendar::roll ( int $field , mixed $amountOrUpOrDown )

Stil procedural

bool intlcal_roll ( IntlCalendar $cal , int $field , mixed $amountOrUpOrDown )

Adds a (signed) amount to a field. The difference with respect to IntlCalendar::add() is that when the field value overflows, it does not carry into more significant fields.

Parametri

cal

The IntlCalendar resource.

field

Una din constantele de câmp data/ora ale IntlCalendar. Acestea sunt valori întregi de la 0 pâna la IntlCalendar::FIELD_COUNT.

amountOrUpOrDown

The (signed) amount to add to the field, TRUE for rolling up (adding 1), or FALSE for rolling down (subtracting 1).

Valorile întoarse

Returns TRUE on success or FALSE on failure.

Exemple

Example #1 IntlCalendar::roll()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');

$cal = new IntlGregorianCalendar(2013, 5 /* June */, 30);

$cal->add(IntlCalendar::FIELD_DAY_OF_MONTH, 1);
var_dump(IntlDateFormatter::formatObject($cal)); // "01/07/2013, 00:00:00"

$cal->set(2013, 5 /* June */, 30);
$cal->roll(IntlCalendar::FIELD_DAY_OF_MONTH, true); // roll up, same as rolling +1
var_dump(IntlDateFormatter::formatObject($cal)); // "01/06/2013, 00:00:00"

Exemplul de mai sus va afi?a:

string(20) "01/07/2013, 00:00:00"
string(20) "01/06/2013, 00:00:00"

A se vedea ?i

  • IntlCalendar::add() - Add a (signed) amount of time to a field
  • IntlCalendar::set() - Set a time field or several common fields at once

IntlCalendar::isWeekend
IntlCalendar::set
IntlCalendar


Set a time field or several common fields at once

IntlCalendar::roll
IntlCalendar::setFirstDayOfWeek
IntlCalendar
PHP Manual

IntlCalendar::set

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::set — Set a time field or several common fields at once

Descrierea

Stil obiect-orientat

public bool IntlCalendar::set ( int $field , int $value )
public bool IntlCalendar::set ( int $year , int $month [, int $dayOfMonth = NULL [, int $hour = NULL [, int $minute = NULL [, int $second = NULL ]]]] )

Stil procedural

bool intlcal_set ( IntlCalendar $cal , int $field , int $value )
bool intlcal_set ( IntlCalendar $cal , int $year , int $month [, int $dayOfMonth = NULL [, int $hour = NULL [, int $minute = NULL [, int $second = NULL ]]]] )

Sets either a specific field to the given value, or sets at once several common fields. The range of values that are accepted depend on whether the calendar is using the lenient mode.

For fields that conflict, the fields that are set later have priority.

This method cannot be called with exactly four arguments.

Parametri

cal

The IntlCalendar resource.

field

Una din constantele de câmp data/ora ale IntlCalendar. Acestea sunt valori întregi de la 0 pâna la IntlCalendar::FIELD_COUNT.

value

The new value of the given field.

year

The new value for IntlCalendar::FIELD_YEAR.

month

The new value for IntlCalendar::FIELD_MONTH.

dayOfMonth

The new value for IntlCalendar::FIELD_DAY_OF_MONTH. The month sequence is zero-based, i.e., January is represented by 0, February by 1, …, December is 11 and Undecember (if the calendar has it) is 12.

hour

The new value for IntlCalendar::FIELD_HOUR_OF_DAY.

minute

The new value for IntlCalendar::FIELD_MINUTE.

second

The new value for IntlCalendar::FIELD_SECOND.

Valorile întoarse

Returns TRUE on success and FALSE on failure.

Exemple

Example #1 IntlCalendar::set()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');

//Calls made later have priority
$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1);
$cal->set(IntlCalendar::FIELD_YEAR, 2012);
$cal->set(IntlCalendar::FIELD_EXTENDED_YEAR, 2011);
var_dump(IntlDateFormatter::formatObject($cal));

$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1);
$cal->set(IntlCalendar::FIELD_YEAR, 2012);
$cal->set(IntlCalendar::FIELD_EXTENDED_YEAR, 2011);
//the time has not been recalculated yet. If we clear the extended year,
//the year set before will be used
$cal->clear(IntlCalendar::FIELD_EXTENDED_YEAR);
var_dump(IntlDateFormatter::formatObject($cal));

Exemplul de mai sus va afi?a:

string(20) "01/07/2011, 00:00:00"
string(20) "01/07/2012, 00:00:00"

A se vedea ?i

  • IntlCalendar::get() - Get the value for a field
  • IntlCalendar::add() - Add a (signed) amount of time to a field
  • IntlCalendar::roll() - Add value to field without carrying into more significant fields

IntlCalendar::roll
IntlCalendar::setFirstDayOfWeek
IntlCalendar


Set the day on which the week is deemed to start

IntlCalendar::set
IntlCalendar::setLenient
IntlCalendar
PHP Manual

IntlCalendar::setFirstDayOfWeek

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::setFirstDayOfWeek — Set the day on which the week is deemed to start

Descrierea

Stil obiect-orientat

public bool IntlCalendar::setFirstDayOfWeek ( int $dayOfWeek )

Stil procedural

bool intlcal_set_first_day_of_week ( IntlCalendar $cal , int $dayOfWeek )

Defines the day of week deemed to start the week. This affects the behavior of fields that depend on the concept of week start and end such as IntlCalendar::FIELD_WEEK_OF_YEAR and IntlCalendar::FIELD_YEAR_WOY.

Parametri

cal

The IntlCalendar resource.

dayOfWeek

One of the constants IntlCalendar::DOW_SUNDAY,
IntlCalendar::DOW_MONDAY, …,
IntlCalendar::DOW_SATURDAY.

Valorile întoarse

Returns TRUE on success. Failure can only happen due to invalid parameters.

Exemple

Example #1 IntlCalendar::setFirstDayOfWeek()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'es_ES');

$cal = IntlCalendar::createInstance();
$cal->set(2013, 5 /* June */, 30); // A Sunday

var_dump($cal->getFirstDayOfWeek()); // 2 (Monday)

echo IntlDateFormatter::formatObject($cal, <<<EOD
'local day of week: 'cc'
week of month    : 'W'
week of year     : 'ww
EOD
), "\n";

$cal->setFirstDayOfWeek(IntlCalendar::DOW_SUNDAY);

echo IntlDateFormatter::formatObject($cal, <<<EOD
'local day of week: 'cc'
week of month    : 'W'
week of year     : 'ww
EOD
), "\n";

Exemplul de mai sus va afi?a:

int(2)
local day of week: 7
week of month    : 4
week of year     : 26
local day of week: 1
week of month    : 5
week of year     : 27

IntlCalendar::set
IntlCalendar::setLenient
IntlCalendar


Set whether date/time interpretation is to be lenient

IntlCalendar::setFirstDayOfWeek
IntlCalendar::setMinimalDaysInFirstWeek
IntlCalendar
PHP Manual

IntlCalendar::setLenient

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient

Descrierea

Stil obiect-orientat

public ReturnType IntlCalendar::setLenient ( string $isLenient )

Stil procedural

ReturnType intlcal_set_lenient ( IntlCalendar $cal , string $isLenient )

Defines whether the calendar is ‘lenient mode’. In such a mode, some of out-of-bounds values for some fields are accepted, the behavior being similar to that of IntlCalendar::add() (i.e., the value wraps around, carrying into more significant fields each time). If the lenient mode is off, then such values will generate an error.

Parametri

cal

The IntlCalendar resource.

isLenient

Use TRUE to activate the lenient mode; FALSE otherwise.

Valorile întoarse

Returns TRUE on success. Failure can only happen due to invalid parameters.

Exemple

See the example in IntlCalendar::isLenient().

IntlCalendar::setFirstDayOfWeek
IntlCalendar::setMinimalDaysInFirstWeek
IntlCalendar


Set minimal number of days the first week in a year or month can have

IntlCalendar::setLenient
IntlCalendar::setRepeatedWallTimeOption
IntlCalendar
PHP Manual

IntlCalendar::setMinimalDaysInFirstWeek

(No version information available, might only be in Git)

IntlCalendar::setMinimalDaysInFirstWeek — Set minimal number of days the first week in a year or month can have

Descrierea

Stil obiect-orientat

public bool IntlCalendar::setMinimalDaysInFirstWeek ( int $minimalDays )

Stil procedural

bool intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal , int $minimalDays )

Sets the smallest number of days the first week of a year or month must have in the new year or month. For instance, in the Gregorian calendar, if this value is 1, then the first week of the year will necessarily include January 1st, while if this value is 7, then the week with January 1st will be the first week of the year only if the day of the week for January 1st matches the day of the week returned by IntlCalendar::getFirstDayOfWeek(); otherwise it will be the previous year's last week.

Parametri

cal

The IntlCalendar resource.

minimalDays

The number of minimal days to set.

Valorile întoarse

TRUE on success, FALSE on failure.

IntlCalendar::setLenient
IntlCalendar::setRepeatedWallTimeOption
IntlCalendar


Set behavior for handling repeating wall times at negative timezone offset transitions

IntlCalendar::setMinimalDaysInFirstWeek
IntlCalendar::setSkippedWallTimeOption
IntlCalendar
PHP Manual

IntlCalendar::setRepeatedWallTimeOption

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::setRepeatedWallTimeOption — Set behavior for handling repeating wall times at negative timezone offset transitions

Descrierea

Stil obiect-orientat

public bool IntlCalendar::setRepeatedWallTimeOption ( int $wallTimeOption )

Stil procedural

bool intlcal_set_repeated_wall_time_option ( IntlCalendar $cal , int $wallTimeOption )

Sets the current strategy for dealing with wall times that are repeated whenever the clock is set back during dailight saving time end transitions. The default value is IntlCalendar::WALLTIME_LAST (take the post-DST instant). The other possible value is IntlCalendar::WALLTIME_FIRST (take the instant that occurs during DST).

This function requires ICU 4.9 or later.

Parametri

cal

The IntlCalendar resource.

wallTimeOption

One of the constants IntlCalendar::WALLTIME_FIRST or IntlCalendar::WALLTIME_LAST.

Valorile întoarse

Returns TRUE on success. Failure can only happen due to invalid parameters.

Exemple

See the example on IntlCalendar::getRepeatedWallTimeOption().

A se vedea ?i

  • intlCalendar::getRepeatedWallTimeOption() - Get behavior for handling repeating wall time
  • intlCalendar::setSkippedWallTimeOption() - Set behavior for handling skipped wall times at positive timezone offset transitions
  • intlCalendar::getSkippedWallTimeOption() - Get behavior for handling skipped wall time

IntlCalendar::setMinimalDaysInFirstWeek
IntlCalendar::setSkippedWallTimeOption
IntlCalendar


Set behavior for handling skipped wall times at positive timezone offset transitions

IntlCalendar::setRepeatedWallTimeOption
IntlCalendar::setTime
IntlCalendar
PHP Manual

IntlCalendar::setSkippedWallTimeOption

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::setSkippedWallTimeOption — Set behavior for handling skipped wall times at positive timezone offset transitions

Descrierea

Stil obiect-orientat

public bool IntlCalendar::setSkippedWallTimeOption ( int $wallTimeOption )

Stil procedural

bool intlcal_set_skipped_wall_time_option ( IntlCalendar $cal , int $wallTimeOption )

Sets the current strategy for dealing with wall times that are skipped whenever the clock is forwarded during dailight saving time start transitions. The default value is IntlCalendar::WALLTIME_LAST (take it as being the same instant as the one when the wall time is one hour more). Alternative values are IntlCalendar::WALLTIME_FIRST (same instant as the one with a wall time of one hour less) and IntlCalendar::WALLTIME_NEXT_VALID (same instant as when DST begins).

This affects only the instant represented by the calendar (as reported by IntlCalendar::getTime()), the field values will not be rewritten accordingly.

The calendar must be lenient for this option to have any effect, otherwise attempting to set a non-existing time will cause an error.

This function requires ICU 4.9 or later.

Parametri

cal

The IntlCalendar resource.

wallTimeOption

One of the constants IntlCalendar::WALLTIME_FIRST,
IntlCalendar::WALLTIME_LAST or
IntlCalendar::WALLTIME_NEXT_VALID.

Valorile întoarse

Returns TRUE on success. Failure can only happen due to invalid parameters.

Exemple

See the example on IntlCalendar::getSkippedWallTimeOption().

A se vedea ?i

  • intlCalendar::getSkippedWallTimeOption() - Get behavior for handling skipped wall time
  • intlCalendar::setRepeatedWallTimeOption() - Set behavior for handling repeating wall times at negative timezone offset transitions
  • intlCalendar::getRepeatedWallTimeOption() - Get behavior for handling repeating wall time

IntlCalendar::setRepeatedWallTimeOption
IntlCalendar::setTime
IntlCalendar


Set the calendar time in milliseconds since the epoch

IntlCalendar::setSkippedWallTimeOption
IntlCalendar::setTimeZone
IntlCalendar
PHP Manual

IntlCalendar::setTime

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::setTime — Set the calendar time in milliseconds since the epoch

Descrierea

Stil obiect-orientat

public bool IntlCalendar::setTime ( float $date )

Stil procedural

bool intlcal_set_time ( IntlCalendar $cal , float $date )

Sets the instant represented by this object. The instant is represented by a float whose value should be an integer number of milliseconds since the epoch (1 Jan 1970 00:00:00.000 UTC), ignoring leap seconds. All the field values will be recalculated accordingly.

Parametri

cal

The IntlCalendar resource.

date

An instant represented by the number of number of milliseconds between such instant and the epoch, ignoring leap seconds.

Valorile întoarse

Returns TRUE on success and FALSE on failure.

Exemple

Example #1 IntlCalendar::setTime()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'fr_FR');

$cal = new IntlGregorianCalendar(2013, 5 /* May */, 1, 12, 0, 0);

echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";

/* In Europe/Lisbon, on 2013-10-27 at 0200, the clock goes back one hour and
   the timezone from UTC+01 to UTC+00 */

$cal->setTime(strtotime('2013-10-27 00:30:00 UTC') * 1000.);

echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";

$cal->setTime(strtotime('2013-10-27 01:30:00 UTC') * 1000.);

echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";

Exemplul de mai sus va afi?a:

samedi 1 juin 2013 12:00:00 heure avancée d’Europe de l’Ouest
dimanche 27 octobre 2013 01:30:00 heure avancée d’Europe de l’Ouest
dimanche 27 octobre 2013 01:30:00 heure normale d’Europe de l’Ouest

IntlCalendar::setSkippedWallTimeOption
IntlCalendar::setTimeZone
IntlCalendar


Set the timezone used by this calendar

IntlCalendar::setTime
IntlCalendar::toDateTime
IntlCalendar
PHP Manual

IntlCalendar::setTimeZone

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::setTimeZone — Set the timezone used by this calendar

Descrierea

Stil obiect-orientat

public bool IntlCalendar::setTimeZone ( mixed $timeZone )

Stil procedural

bool intlcal_set_time_zone ( IntlCalendar $cal , mixed $timeZone )

Defines a new timezone for this calendar. The time represented by the object is preserved to the detriment of the field values.

Parametri

cal

The IntlCalendar resource.

timeZone

The new timezone to be used by this calendar. It can be specified in the following ways:

  • NULL, in which case the default timezone will be used, as specified in the ini setting date.timezone or through the function date_default_timezone_set() and as returned by date_default_timezone_get().

  • An IntlTimeZone, which will be used directly.

  • A DateTimeZone. Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICU's database, not PHP's.

  • A string, which should be a valid ICU timezone identifier. See IntlTimeZone::createTimeZoneIDEnumeration(). Raw offsets such as "GMT+08:30" are also accepted.

Valorile întoarse

Returns TRUE on success and FALSE on failure.

Exemple

Example #1 IntlCalendar::setTimeZone()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'es_ES');

$cal = new IntlGregorianCalendar(2013, 5 /* May */, 1, 12, 0, 0);

echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
echo "(instant {$cal->getTime()})\n";

$cal->setTimeZone(IntlTimeZone::getGMT());
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
echo "(instant {$cal->getTime()})\n";

$cal->setTimeZone('GMT+03:33');
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
echo "(instant {$cal->getTime()})\n";

Exemplul de mai sus va afi?a:

sábado, 1 de junio de 2013 12:00:00 Hora de verano de Europa occidental
(instant 1370084400000)
sábado, 1 de junio de 2013 11:00:00 GMT
(instant 1370084400000)
sábado, 1 de junio de 2013 14:33:00 GMT+03:33
(instant 1370084400000)

IntlCalendar::setTime
IntlCalendar::toDateTime
IntlCalendar


Convert an IntlCalendar into a DateTime object

IntlCalendar::setTimeZone
IntlTimeZone
IntlCalendar
PHP Manual

IntlCalendar::toDateTime

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a2)

IntlCalendar::toDateTime — Convert an IntlCalendar into a DateTime object

Descrierea

Stil obiect-orientat

public DateTime IntlCalendar::toDateTime ( void )

Stil procedural

DateTime intlcal_to_date_time ( IntlCalendar $cal )

Create a DateTime object that represents the same instant (up to second precision, with a rounding error of less than 1 second) and has an analog timezone to this object (the difference being DateTime's timezone will be backed by PHP's timezone while IntlCalendar's timezone is backed by ICU's).

Parametri

cal

The IntlCalendar resource.

Valorile întoarse

A DateTime object with the same timezone as this object (though using PHP's database instead of ICU's) and the same time, except for the smaller precision (second precision instead of millisecond). Returns FALSE on failure.

Exemple

Example #1 IntlCalendar::toDateTime()

<?php
ini_set('date.timezone', 'UTC');
ini_set('intl.default_locale', 'pt_PT');

$cal = IntlCalendar::createInstance('Europe/Lisbon'); //current time

$dt = $cal->toDateTime();
print_r($dt);

Exemplul de mai sus va afi?a:

DateTime Object
(
    [date] => 2013-07-02 00:29:13
    [timezone_type] => 3
    [timezone] => Europe/Lisbon
)

A se vedea ?i

  • IntlCalendar::fromDateTime() - Create an IntlCalendar from a DateTime object or string
  • IntlCalendar::getTime() - Get time currently represented by the object
  • IntlCalendar::createInstance() - Create a new IntlCalendar
  • DateTime:__construct()

IntlCalendar::setTimeZone
IntlTimeZone
IntlCalendar


The IntlTimeZone class

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

Introducere

Sinopsisul clasei

IntlTimeZone {
/* Constants */
const integer DISPLAY_SHORT = 1 ;
const integer DISPLAY_LONG = 2 ;
/* Metode */
public static integer countEquivalentIDs ( string $zoneId )
public static IntlTimeZone createDefault ( void )
public static IntlIterator createEnumeration ([ mixed $countryOrRawOffset ] )
public static IntlTimeZone createTimeZone ( string $zoneId )
public static IntlTimeZone fromDateTimeZone ( DateTimeZone $zoneId )
public static string getCanonicalID ( string $zoneId [, bool &$isSystemID ] )
public string getDisplayName ([ bool $isDaylight [, integer $style [, string $locale ]]] )
public integer getDSTSavings ( void )
public static string getEquivalentID ( string $zoneId , integer $index )
public integer getErrorCode ( void )
public string getErrorMessage ( void )
public static IntlTimeZone getGMT ( void )
public string getID ( void )
public integer getOffset ( float $date , bool $local , integer &$rawOffset , integer &$dstOffset )
public integer getRawOffset ( void )
public static string getTZDataVersion ( void )
public bool hasSameRules ( IntlTimeZone $otherTimeZone )
public DateTimeZone toDateTimeZone ( void )
public bool useDaylightTime ( void )
}

Constante predefinite

IntlTimeZone::DISPLAY_SHORT

IntlTimeZone::DISPLAY_LONG

Cuprins

  • IntlTimeZone::countEquivalentIDs — Get the number of IDs in the equivalency group that includes the given ID
  • IntlTimeZone::createDefault — Create a new copy of the default timezone for this host
  • IntlTimeZone::createEnumeration — Get an enumeration over time zone IDs associated with the given country or offset
  • IntlTimeZone::createTimeZone — Create a timezone object for the given ID
  • IntlTimeZone::fromDateTimeZone — Create a timezone object from DateTimeZone
  • IntlTimeZone::getCanonicalID — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID
  • IntlTimeZone::getDisplayName — Get a name of this time zone suitable for presentation to the user
  • IntlTimeZone::getDSTSavings — Get the amount of time to be added to local standard time to get local wall clock time
  • IntlTimeZone::getEquivalentID — Get an ID in the equivalency group that includes the given ID
  • IntlTimeZone::getErrorCode — Get last error code on the object
  • IntlTimeZone::getErrorMessage — Get last error message on the object
  • IntlTimeZone::getGMT — Create GMT (UTC) timezone
  • IntlTimeZone::getID — Get timezone ID
  • IntlTimeZone::getOffset — Get the time zone raw and GMT offset for the given moment in time
  • IntlTimeZone::getRawOffset — Get the raw GMT offset (before taking daylight savings time into account
  • IntlTimeZone::getTZDataVersion — Get the timezone data version currently used by ICU
  • IntlTimeZone::hasSameRules — Check if this zone has the same rules and offset as another zone
  • IntlTimeZone::toDateTimeZone — Convert to DateTimeZone object
  • IntlTimeZone::useDaylightTime — Check if this time zone uses daylight savings time
IntlCalendar::toDateTime
IntlTimeZone::countEquivalentIDs
intl


Get the number of IDs in the equivalency group that includes the given ID

IntlTimeZone
IntlTimeZone::createDefault
IntlTimeZone
PHP Manual

IntlTimeZone::countEquivalentIDs

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::countEquivalentIDs — Get the number of IDs in the equivalency group that includes the given ID

Descrierea

public static integer IntlTimeZone::countEquivalentIDs ( string $zoneId )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

zoneId

Valorile întoarse

IntlTimeZone
IntlTimeZone::createDefault
IntlTimeZone


Create a new copy of the default timezone for this host

IntlTimeZone::countEquivalentIDs
IntlTimeZone::createEnumeration
IntlTimeZone
PHP Manual

IntlTimeZone::createDefault

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::createDefault — Create a new copy of the default timezone for this host

Descrierea

public static IntlTimeZone IntlTimeZone::createDefault ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlTimeZone::countEquivalentIDs
IntlTimeZone::createEnumeration
IntlTimeZone


Get an enumeration over time zone IDs associated with the given country or offset

IntlTimeZone::createDefault
IntlTimeZone::createTimeZone
IntlTimeZone
PHP Manual

IntlTimeZone::createEnumeration

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::createEnumeration — Get an enumeration over time zone IDs associated with the given country or offset

Descrierea

public static IntlIterator IntlTimeZone::createEnumeration ([ mixed $countryOrRawOffset ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

countryOrRawOffset

Valorile întoarse

IntlTimeZone::createDefault
IntlTimeZone::createTimeZone
IntlTimeZone


Create a timezone object for the given ID

IntlTimeZone::createEnumeration
IntlTimeZone::fromDateTimeZone
IntlTimeZone
PHP Manual

IntlTimeZone::createTimeZone

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::createTimeZone — Create a timezone object for the given ID

Descrierea

public static IntlTimeZone IntlTimeZone::createTimeZone ( string $zoneId )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

zoneId

Valorile întoarse

IntlTimeZone::createEnumeration
IntlTimeZone::fromDateTimeZone
IntlTimeZone


Create a timezone object from DateTimeZone

IntlTimeZone::createTimeZone
IntlTimeZone::getCanonicalID
IntlTimeZone
PHP Manual

IntlTimeZone::fromDateTimeZone

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::fromDateTimeZone — Create a timezone object from DateTimeZone

Descrierea

public static IntlTimeZone IntlTimeZone::fromDateTimeZone ( DateTimeZone $zoneId )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

zoneId

Valorile întoarse

IntlTimeZone::createTimeZone
IntlTimeZone::getCanonicalID
IntlTimeZone


Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID

IntlTimeZone::fromDateTimeZone
IntlTimeZone::getDisplayName
IntlTimeZone
PHP Manual

IntlTimeZone::getCanonicalID

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getCanonicalID — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID

Descrierea

public static string IntlTimeZone::getCanonicalID ( string $zoneId [, bool &$isSystemID ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

zoneId

isSystemID

Valorile întoarse

IntlTimeZone::fromDateTimeZone
IntlTimeZone::getDisplayName
IntlTimeZone


Get a name of this time zone suitable for presentation to the user

IntlTimeZone::getCanonicalID
IntlTimeZone::getDSTSavings
IntlTimeZone
PHP Manual

IntlTimeZone::getDisplayName

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getDisplayName — Get a name of this time zone suitable for presentation to the user

Descrierea

public string IntlTimeZone::getDisplayName ([ bool $isDaylight [, integer $style [, string $locale ]]] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

isDaylight

style

locale

Valorile întoarse

IntlTimeZone::getCanonicalID
IntlTimeZone::getDSTSavings
IntlTimeZone


Get the amount of time to be added to local standard time to get local wall clock time

IntlTimeZone::getDisplayName
IntlTimeZone::getEquivalentID
IntlTimeZone
PHP Manual

IntlTimeZone::getDSTSavings

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getDSTSavings — Get the amount of time to be added to local standard time to get local wall clock time

Descrierea

public integer IntlTimeZone::getDSTSavings ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlTimeZone::getDisplayName
IntlTimeZone::getEquivalentID
IntlTimeZone


Get an ID in the equivalency group that includes the given ID

IntlTimeZone::getDSTSavings
IntlTimeZone::getErrorCode
IntlTimeZone
PHP Manual

IntlTimeZone::getEquivalentID

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getEquivalentID — Get an ID in the equivalency group that includes the given ID

Descrierea

public static string IntlTimeZone::getEquivalentID ( string $zoneId , integer $index )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

zoneId

index

Valorile întoarse

IntlTimeZone::getDSTSavings
IntlTimeZone::getErrorCode
IntlTimeZone


Get last error code on the object

IntlTimeZone::getEquivalentID
IntlTimeZone::getErrorMessage
IntlTimeZone
PHP Manual

IntlTimeZone::getErrorCode

intltz_get_error_code

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getErrorCode -- intltz_get_error_code — Get last error code on the object

Descrierea

Stil obiect-orientat (method):

public integer IntlTimeZone::getErrorCode ( void )

Stil procedural:

integer intltz_get_error_code ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlTimeZone::getEquivalentID
IntlTimeZone::getErrorMessage
IntlTimeZone


Get last error message on the object

IntlTimeZone::getErrorCode
IntlTimeZone::getGMT
IntlTimeZone
PHP Manual

IntlTimeZone::getErrorMessage

intltz_get_error_message

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getErrorMessage -- intltz_get_error_message — Get last error message on the object

Descrierea

Stil obiect-orientat (method):

public string IntlTimeZone::getErrorMessage ( void )

Stil procedural:

string intltz_get_error_message ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlTimeZone::getErrorCode
IntlTimeZone::getGMT
IntlTimeZone


Create GMT (UTC) timezone

IntlTimeZone::getErrorMessage
IntlTimeZone::getID
IntlTimeZone
PHP Manual

IntlTimeZone::getGMT

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getGMT — Create GMT (UTC) timezone

Descrierea

public static IntlTimeZone IntlTimeZone::getGMT ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlTimeZone::getErrorMessage
IntlTimeZone::getID
IntlTimeZone


Get timezone ID

IntlTimeZone::getGMT
IntlTimeZone::getOffset
IntlTimeZone
PHP Manual

IntlTimeZone::getID

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getID — Get timezone ID

Descrierea

public string IntlTimeZone::getID ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlTimeZone::getGMT
IntlTimeZone::getOffset
IntlTimeZone


Get the time zone raw and GMT offset for the given moment in time

IntlTimeZone::getID
IntlTimeZone::getRawOffset
IntlTimeZone
PHP Manual

IntlTimeZone::getOffset

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getOffset — Get the time zone raw and GMT offset for the given moment in time

Descrierea

public integer IntlTimeZone::getOffset ( float $date , bool $local , integer &$rawOffset , integer &$dstOffset )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

date

local

rawOffset

dstOffset

Valorile întoarse

IntlTimeZone::getID
IntlTimeZone::getRawOffset
IntlTimeZone


Get the raw GMT offset (before taking daylight savings time into account

IntlTimeZone::getOffset
IntlTimeZone::getTZDataVersion
IntlTimeZone
PHP Manual

IntlTimeZone::getRawOffset

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getRawOffset — Get the raw GMT offset (before taking daylight savings time into account

Descrierea

public integer IntlTimeZone::getRawOffset ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlTimeZone::getOffset
IntlTimeZone::getTZDataVersion
IntlTimeZone


Get the timezone data version currently used by ICU

IntlTimeZone::getRawOffset
IntlTimeZone::hasSameRules
IntlTimeZone
PHP Manual

IntlTimeZone::getTZDataVersion

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getTZDataVersion — Get the timezone data version currently used by ICU

Descrierea

public static string IntlTimeZone::getTZDataVersion ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlTimeZone::getRawOffset
IntlTimeZone::hasSameRules
IntlTimeZone


Check if this zone has the same rules and offset as another zone

IntlTimeZone::getTZDataVersion
IntlTimeZone::toDateTimeZone
IntlTimeZone
PHP Manual

IntlTimeZone::hasSameRules

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::hasSameRules — Check if this zone has the same rules and offset as another zone

Descrierea

public bool IntlTimeZone::hasSameRules ( IntlTimeZone $otherTimeZone )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

otherTimeZone

Valorile întoarse

IntlTimeZone::getTZDataVersion
IntlTimeZone::toDateTimeZone
IntlTimeZone


Convert to DateTimeZone object

IntlTimeZone::hasSameRules
IntlTimeZone::useDaylightTime
IntlTimeZone
PHP Manual

IntlTimeZone::toDateTimeZone

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::toDateTimeZone — Convert to DateTimeZone object

Descrierea

public DateTimeZone IntlTimeZone::toDateTimeZone ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlTimeZone::hasSameRules
IntlTimeZone::useDaylightTime
IntlTimeZone


Check if this time zone uses daylight savings time

IntlTimeZone::toDateTimeZone
IntlDateFormatter
IntlTimeZone
PHP Manual

IntlTimeZone::useDaylightTime

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::useDaylightTime — Check if this time zone uses daylight savings time

Descrierea

public bool IntlTimeZone::useDaylightTime ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlTimeZone::toDateTimeZone
IntlDateFormatter
IntlTimeZone


The IntlDateFormatter class

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Introducere

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 {
/* Metode */
public __construct ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] )
public static IntlDateFormatter create ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] )
public string format ( mixed $value )
public static string formatObject ( object $object [, mixed $format = NULL [, string $locale = NULL ]] )
int getCalendar ( void )
public int getDateType ( void )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public string getLocale ([ int $which ] )
public string getPattern ( void )
public int getTimeType ( void )
public string getTimeZoneId ( void )
public IntlCalendar getCalendarObject ( void )
public IntlTimeZone getTimeZone ( void )
public bool isLenient ( void )
public array localtime ( string $value [, int &$position ] )
public int parse ( string $value [, int &$position ] )
bool setCalendar ( mixed $which )
public bool setLenient ( bool $lenient )
public bool setPattern ( string $pattern )
public bool setTimeZoneId ( string $zone )
public boolean setTimeZone ( mixed $zone )
}

A se vedea ?i

  • » ICU Date formatter
  • » ICU Date formats

Constante predefinite

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

Cuprins

  • IntlDateFormatter::create — Create a date formatter
  • IntlDateFormatter::format — Format the date/time value as a string
  • IntlDateFormatter::formatObject — Formats an object
  • IntlDateFormatter::getCalendar — Get the calendar type 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::getCalendarObject — Get copy of formatter's calendar object
  • IntlDateFormatter::getTimeZone — Get formatter's timezone
  • 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 type used by the formatter
  • 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
  • IntlDateFormatter::setTimeZone — Sets formatter's timezone
IntlTimeZone::useDaylightTime
IntlDateFormatter::create
intl


Create a date formatter

IntlDateFormatter
IntlDateFormatter::format
IntlDateFormatter
PHP Manual

IntlDateFormatter::create

datefmt_create

IntlDateFormatter::__construct

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::create -- datefmt_create -- IntlDateFormatter::__construct — Create a date formatter

Descrierea

Stil obiect-orientat

public static IntlDateFormatter IntlDateFormatter::create ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] )

Stil obiect-orientat (constructor)

public IntlDateFormatter::__construct ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] )

Stil procedural

IntlDateFormatter datefmt_create ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] )

Create a date formatter.

Parametri

locale

Locale to use when formatting or parsing or NULL to use the value specified in the ini setting intl.default_locale.

datetype

Date type to use (none, short, medium, long, full). This is one of the IntlDateFormatter constants. It can also be NULL, in which case ICU's default date type will be used.

timetype

Time type to use (none, short, medium, long, full). This is one of the IntlDateFormatter constants. It can also be NULL, in which case ICU's default time type will be used.

timezone

Time zone ID. The default (and the one used if NULL is given) is the one returned by date_default_timezone_get() or, if applicable, that of the IntlCalendar object passed for the calendar parameter. This ID must be a valid identifier on ICU's database or an ID representing an explicit offset, such as GMT-05:30.

This can also be an IntlTimeZone or a DateTimeZone object.

calendar

Calendar to use for formatting or parsing. The default value is NULL, which corresponds to IntlDateFormatter::GREGORIAN. This can either be one of the IntlDateFormatter calendar constants or an IntlCalendar. Any IntlCalendar object passed will be clone; it will not be changed by the IntlDateFormatter. This will determine the calendar type used (gregorian, islamic, persian, etc.) and, if NULL is given for the timezone parameter, also the timezone used.

pattern

Optional pattern to use when formatting or parsing. Possible patterns are documented at » http://userguide.icu-project.org/formatparse/datetime.

Valorile întoarse

The created IntlDateFormatter or FALSE in case of failure.

Istoricul schimbarilor

Versiune | Descriere
5.5.0/PECL 3.0.0 | An IntlCalendar object is allowed for calendar. Objects of type IntlTimeZone and DateTimeZone are allowed for timezone. Invalid timezone identifiers (including empty strings) are no longer allowed for timezone. If NULL is given for timezone, the timezone identifier given by date_default_timezone_get() will be used instead of ICU's default.

Exemple

Example #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);
?>

Example #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);
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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::formatObject
IntlDateFormatter
PHP Manual

IntlDateFormatter::format

datefmt_format

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::format -- datefmt_format — Format the date/time value as a string

Descrierea

Stil obiect-orientat

public string IntlDateFormatter::format ( mixed $value )

Stil procedural

string datefmt_format ( IntlDateFormatter $fmt , mixed $value )

Formats the time value as a string.

Parametri

fmt

The date formatter resource.

value

Value to format. This may be a DateTime object, an IntlCalendar object, a numeric type representing a (possibly fractional) number of seconds since epoch or an array in the format output by localtime().

If a DateTime or an IntlCalendar object is passed, its timezone is not considered. The object will be formatted using the formater's configured timezone. If one wants to use the timezone of the object to be formatted, IntlDateFormatter::setTimeZone() must be called before with the object's timezone. Alternatively, the static function IntlDateFormatter::formatObject() may be used instead.

Valorile întoarse

The formatted string or, if an error occurred, FALSE.

Istoricul schimbarilor

Versiune | Descriere
5.5.0/PECL 3.0.0 | Support for providing IntlCalendar objects to the value parameter was added.
5.3.4 | Support for providing DateTime objects to the value parameter was added.

Exemple

Example #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);
?>

Example #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);
?>

Exemplul de mai sus va afi?a:

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

Example #3 With IntlCalendar object

<?php
$tz = reset(iterator_to_array(IntlTimeZone::createEnumeration('FR')));
$formatter = IntlDateFormatter::create(
    'fr_FR',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    $tz,
    IntlDateFormatter::GREGORIAN
);

$cal = IntlCalendar::createInstance($tz, '@calendar=islamic-civil');
$cal->set(IntlCalendar::FIELD_MONTH, 8); //9th month, Ramadan
$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 1); //1st day
$cal->clear(IntlCalendar::FIELD_HOUR_OF_DAY);
$cal->clear(IntlCalendar::FIELD_MINUTE);
$cal->clear(IntlCalendar::FIELD_SECOND);
$cal->clear(IntlCalendar::FIELD_MILLISECOND);

echo "In this islamic year, Ramadan started/will start on:\n\t",
        $formatter->format($cal), "\n";

//It's the formatter's timezone that is used:
$formatter->setTimeZone('Asia/Tokyo');
echo "After changing timezone:\n\t",
        $formatter->format($cal), "\n";

Exemplul de mai sus va afi?a:

In this islamic year, Ramadan started/will start on:
    mardi 9 juillet 2013 19:00:00 heure avancée d’Europe centrale
After changing timezone:
    mercredi 10 juillet 2013 02:00:00 heure normale du Japon

A se vedea ?i

  • 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.
  • datefmt_format_object() - Formats an object

IntlDateFormatter::create
IntlDateFormatter::formatObject
IntlDateFormatter


Formats an object

IntlDateFormatter::format
IntlDateFormatter::getCalendar
IntlDateFormatter
PHP Manual

IntlDateFormatter::formatObject

datefmt_format_object

(PHP 5 >= 5.5.0, PHP 7, PECL intl >= 3.0.0)

IntlDateFormatter::formatObject -- datefmt_format_object — Formats an object

Descrierea

Stil obiect-orientat

public static string IntlDateFormatter::formatObject ( object $object [, mixed $format = NULL [, string $locale = NULL ]] )

Stil procedural

public static string datefmt_format_object ( object $object [, mixed $format = NULL [, string $locale = NULL ]] )

This function allows formatting an IntlCalendar or DateTime object without first explicitly creating a IntlDateFormatter object.

The temporary IntlDateFormatter that will be created will take the timezone from the passed in object. The timezone database bundled with PHP will not be used – ICU's will be used instead. The timezone identifier used in DateTime objects must therefore also exist in ICU's database.

Parametri

object

An object of type IntlCalendar or DateTime. The timezone information in the object will be used.

format

How to format the date/time. This can either be an array with two elements (first the date style, then the time style, these being one of the constants IntlDateFormatter::NONE, IntlDateFormatter::SHORT, IntlDateFormatter::MEDIUM, IntlDateFormatter::LONG, IntlDateFormatter::FULL), a long with the value of one of these constants (in which case it will be used both for the time and the date) or a string with the format described in » the ICU documentation. If NULL, the default style will be used.

locale

The locale to use, or NULL to use the default one.

Valorile întoarse

A string with result sau FALSE în cazul e?ecului.

Exemple

Example #1 IntlDateFormatter::formatObject() examples

<?php
/* default timezone is irrelevant; timezone taken from the object */
ini_set('date.timezone', 'UTC');
/* default locale is taken from this ini setting */
ini_set('intl.default_locale', 'fr_FR');

$cal = IntlCalendar::fromDateTime("2013-06-06 17:05:06 Europe/Dublin");
echo "default:\n\t",
        IntlDateFormatter::formatObject($cal),
        "\n";

echo "long \$format (full):\n\t",
        IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL),
        "\n";

echo "array \$format (none, full):\n\t",
        IntlDateFormatter::formatObject($cal, array(
                IntlDateFormatter::NONE,
                IntlDateFormatter::FULL)),
        "\n";

echo "string \$format (d 'of' MMMM y):\n\t",
        IntlDateFormatter::formatObject($cal, "d 'of' MMMM y", 'en_US'),
        "\n";

echo "with DateTime:\n\t",
        IntlDateFormatter::formatObject(
                new DateTime("2013-09-09 09:09:09 Europe/Madrid"),
                IntlDateFormatter::FULL,
                'es_ES'),
        "\n";

Exemplul de mai sus va afi?a:

default:
    6 juin 2013 17:05:06
long $format (full):
    jeudi 6 juin 2013 17:05:06 heure d’été irlandaise
array $format (none, full):
    17:05:06 heure d’été irlandaise
string $format (d 'of' MMMM y):
    6 of June 2013
with DateTime:
    lunes, 9 de septiembre de 2013 09:09:09 Hora de verano de Europa central

IntlDateFormatter::format
IntlDateFormatter::getCalendar
IntlDateFormatter


Get the calendar type used for the IntlDateFormatter

IntlDateFormatter::formatObject
IntlDateFormatter::getDateType
IntlDateFormatter
PHP Manual

IntlDateFormatter::getCalendar

datefmt_get_calendar

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::getCalendar -- datefmt_get_calendar — Get the calendar type used for the IntlDateFormatter

Descrierea

Stil obiect-orientat

int IntlDateFormatter::getCalendar ( void )

Stil procedural

int datefmt_get_calendar ( IntlDateFormatter $fmt )

Parametri

fmt

The formatter resource

Valorile întoarse

The calendar type being used by the formatter. Either IntlDateFormatter::TRADITIONAL or IntlDateFormatter::GREGORIAN.

Exemple

Example #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);
?>

Example #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();

?>

Exemplul de mai sus va afi?a:

calendar of the formatter is : 1
Now calendar of the formatter is : 0

A se vedea ?i

  • datefmt_get_calendar_object() - Get copy of formatter's calendar object
  • datefmt_set_calendar() - Sets the calendar type used by the formatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::formatObject
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, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::getDateType -- datefmt_get_datetype — Get the datetype used for the IntlDateFormatter

Descrierea

Stil obiect-orientat

public int IntlDateFormatter::getDateType ( void )

Stil procedural

int datefmt_get_datetype ( IntlDateFormatter $fmt )

Returns date type used by the formatter.

Parametri

fmt

The formatter resource.

Valorile întoarse

The current date type value of the formatter.

Exemple

Example #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);

?>

Example #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 ' . $fmt->format(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 ' . $fmt->format(0);

?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::getErrorCode -- datefmt_get_error_code — Get the error code from last operation

Descrierea

Stil obiect-orientat

public int IntlDateFormatter::getErrorCode ( void )

Stil procedural

int datefmt_get_error_code ( IntlDateFormatter $fmt )

Get the error code from last operation. Returns error code from the last number formatting operation.

Parametri

fmt

The formatter resource.

Valorile întoarse

The error code, one of UErrorCode values. Initial value is U_ZERO_ERROR.

Exemple

Example #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) {
    printf(
        "ERROR: %s (%d)\n",
        datefmt_get_error_message($fmt),
        datefmt_get_error_code($fmt)
    );
}
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
$str = $fmt->format();
if (!$str) {
    printf(
        "ERROR: %s (%d)\n",
        $fmt->getErrorMessage(),
        $fmt->getErrorCode()
    );
}
?>

Exemplul de mai sus va afi?a:

ERROR: U_ZERO_ERROR (0)

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::getErrorMessage -- datefmt_get_error_message — Get the error text from the last operation.

Descrierea

Stil obiect-orientat

public string IntlDateFormatter::getErrorMessage ( void )

Stil procedural

string datefmt_get_error_message ( IntlDateFormatter $fmt )

Get the error text from the last operation.

Parametri

fmt

The formatter resource.

Valorile întoarse

Description of the last error.

Exemple

Example #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) {
    prtinf(
        "ERROR: %s (%d)\n",
        datefmt_get_error_message($fmt),
        datefmt_get_error_code($fmt)
    );
}
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
$str = $fmt->format();
if(!$str) {
    prtinf(
        "ERROR: %s (%d)\n",
        $fmt->getErrorMessage(),
        $fmt->getErrorCode()
    );
}

?>

Exemplul de mai sus va afi?a:

ERROR: U_ZERO_ERROR (0)

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::getLocale -- datefmt_get_locale — Get the locale used by formatter

Descrierea

Stil obiect-orientat

public string IntlDateFormatter::getLocale ([ int $which ] )

Stil procedural

string datefmt_get_locale ( IntlDateFormatter $fmt [, int $which ] )

Get locale used by the formatter.

Parametri

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.

Valorile întoarse

the locale of this formatter or 'false' if error

Exemple

Example #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);

?>

Example #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);

?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::getPattern -- datefmt_get_pattern — Get the pattern used for the IntlDateFormatter

Descrierea

Stil obiect-orientat

public string IntlDateFormatter::getPattern ( void )

Stil procedural

string datefmt_get_pattern ( IntlDateFormatter $fmt )

Get pattern used by the formatter.

Parametri

fmt

The formatter resource.

Valorile întoarse

The pattern string being used to format/parse.

Exemple

Example #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);

?>

Example #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 ' . $fmt->format(0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ' . $fmt->getPattern();
echo 'Second Formatted output is ' . $fmt->format(0);
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::getTimeType -- datefmt_get_timetype — Get the timetype used for the IntlDateFormatter

Descrierea

Stil obiect-orientat

public int IntlDateFormatter::getTimeType ( void )

Stil procedural

int datefmt_get_timetype ( IntlDateFormatter $fmt )

Return time type used by the formatter.

Parametri

fmt

The formatter resource.

Valorile întoarse

The current date type value of the formatter.

Exemple

Example #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);

?>

Example #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 ' . $fmt->format(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 ' . $fmt->format(0);

?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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::getCalendarObject
IntlDateFormatter
PHP Manual

IntlDateFormatter::getTimeZoneId

datefmt_get_timezone_id

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::getTimeZoneId -- datefmt_get_timezone_id — Get the timezone-id used for the IntlDateFormatter

Descrierea

Stil obiect-orientat

public string IntlDateFormatter::getTimeZoneId ( void )

Stil procedural

string datefmt_get_timezone_id ( IntlDateFormatter $fmt )

Get the timezone-id used for the IntlDateFormatter.

Parametri

fmt

The formatter resource.

Valorile întoarse

ID string for the time zone used by this formatter.

Exemple

Example #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);

?>

Example #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();

?>

Exemplul de mai sus va afi?a:

timezone_id of the formatter is : America/Los_Angeles
Now timezone_id of the formatter is : CN

A se vedea ?i

  • datefmt_set_timezone_id() - Sets the time zone to use
  • datefmt_create() - Create a date formatter

IntlDateFormatter::getTimeType
IntlDateFormatter::getCalendarObject
IntlDateFormatter


Get copy of formatter's calendar object

IntlDateFormatter::getTimeZoneId
IntlDateFormatter::getTimeZone
IntlDateFormatter
PHP Manual

IntlDateFormatter::getCalendarObject

datefmt_get_calendar_object

(PHP 5 >= 5.5.0, PHP 7, PECL intl >= 3.0.0)

IntlDateFormatter::getCalendarObject -- datefmt_get_calendar_object — Get copy of formatter's calendar object

Descrierea

Stil obiect-orientat

public IntlCalendar IntlDateFormatter::getCalendarObject ( void )

Stil procedural

IntlCalendar datefmt_get_calendar_object ( void )

Obtain a copy of the calendar object used internally by this formatter. This calendar will have a type (as in gregorian, japanese, buddhist, roc, persian, islamic, etc.) and a timezone that match the type and timezone used by the formatter. The date/time of the object is unspecified.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A copy of the internal calendar object used by this formatter.

Exemple

Example #1 IntlDateFormatter::getCalendarObject() example

<?php
$formatter = IntlDateFormatter::create(
    "fr_FR@calendar=islamic",
    NULL,
    NULL,
    "GMT-01:00",
    IntlDateFormatter::TRADITIONAL
);

$cal = $formatter->getCalendarObject();

var_dump(
    $cal->getType(),
    $cal->getTimeZone(),
    $cal->getLocale(Locale::VALID_LOCALE)
);

Exemplul de mai sus va afi?a:

string(7) "islamic"
object(IntlTimeZone)#3 (4) {
  ["valid"]=>
  bool(true)
  ["id"]=>
  string(9) "GMT-01:00"
  ["rawOffset"]=>
  int(-3600000)
  ["currentOffset"]=>
  int(-3600000)
}
string(5) "fr_FR"

A se vedea ?i

  • IntlDateFormatter::getCalendar() - Get the calendar type used for the IntlDateFormatter
  • IntlDateFormatter::setCalendar() - Sets the calendar type used by the formatter
  • IntlCalendar

IntlDateFormatter::getTimeZoneId
IntlDateFormatter::getTimeZone
IntlDateFormatter


Get formatter's timezone

IntlDateFormatter::getCalendarObject
IntlDateFormatter::isLenient
IntlDateFormatter
PHP Manual

IntlDateFormatter::getTimeZone

datefmt_get_timezone

(PHP 5 >= 5.5.0, PHP 7, PECL intl >= 3.0.0)

IntlDateFormatter::getTimeZone -- datefmt_get_timezone — Get formatter's timezone

Descrierea

Stil obiect-orientat

public IntlTimeZone IntlDateFormatter::getTimeZone ( void )

Stil procedural

IntlTimeZone datefmt_get_timezone ( void )

Returns an IntlTimeZone object representing the timezone that will be used by this object to format dates and times. When formatting IntlCalendar and DateTime objects with this IntlDateFormatter, the timezone used will be the one returned by this method, not the one associated with the objects being formatted.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The associated IntlTimeZone object sau FALSE în cazul e?ecului.

Exemple

Example #1 IntlDateFormatter::getTimeZone() examples

<?php

$madrid = IntlDateFormatter::create(NULL, NULL, NULL, 'Europe/Madrid');
$lisbon = IntlDateFormatter::create(NULL, NULL, NULL, 'Europe/Lisbon');

var_dump($madrid->getTimezone());
echo $madrid->getTimezone()->getDisplayName(
        false, IntlTimeZone::DISPLAY_GENERIC_LOCATION, "en_US"), "\n";
echo $lisbon->getTimeZone()->getId(), "\n";
//The id can also be retrieved with ->getTimezoneId()
echo $lisbon->getTimeZoneId(), "\n";

Exemplul de mai sus va afi?a:

object(IntlTimeZone)#4 (4) {
  ["valid"]=>
  bool(true)
  ["id"]=>
  string(13) "Europe/Madrid"
  ["rawOffset"]=>
  int(3600000)
  ["currentOffset"]=>
  int(7200000)
}
Spain Time
Europe/Lisbon
Europe/Lisbon

A se vedea ?i

  • IntlDateFormatter::getTimeZoneId() - Get the timezone-id used for the IntlDateFormatter
  • IntlDateFormatter::setTimeZone() - Sets formatter's timezone
  • IntlTimeZone

IntlDateFormatter::getCalendarObject
IntlDateFormatter::isLenient
IntlDateFormatter


Get the lenient used for the IntlDateFormatter

IntlDateFormatter::getTimeZone
IntlDateFormatter::localtime
IntlDateFormatter
PHP Manual

IntlDateFormatter::isLenient

datefmt_is_lenient

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::isLenient -- datefmt_is_lenient — Get the lenient used for the IntlDateFormatter

Descrierea

Stil obiect-orientat

public bool IntlDateFormatter::isLenient ( void )

Stil procedural

bool datefmt_is_lenient ( IntlDateFormatter $fmt )

Check if the parser is strict or lenient in interpreting inputs that do not match the pattern exactly.

Parametri

fmt

The formatter resource.

Valorile întoarse

TRUE if parser is lenient, FALSE if parser is strict. By default the parser is lenient.

Exemple

Example #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').\nResult is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
    echo "\nError_msg is : " . intl_get_error_message();
    echo "\nError_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 "\nError_msg is : " . intl_get_error_message();
    echo "\nError_code is : " . intl_get_error_code();
}

?>

Example #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').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0){
    echo "\nError_msg is : " . intl_get_error_message();
    echo "\nError_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').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0) {
    echo "\nError_msg is : " . intl_get_error_message();
    echo "\nError_code is : " . intl_get_error_code();
}

?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • datefmt_set_lenient() - Set the leniency of the parser
  • datefmt_create() - Create a date formatter

IntlDateFormatter::getTimeZone
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, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::localtime -- datefmt_localtime — Parse string to a field-based time value

Descrierea

Stil obiect-orientat

public array IntlDateFormatter::localtime ( string $value [, int &$position ] )

Stil procedural

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.

Parametri

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.

Valorile întoarse

Localtime compatible array of integers : contains 24 hour clock value in tm_hour field

Exemple

Example #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 , ";
    }
}

?>

Example #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 , ";
    }
}

?>

Exemplul de mai sus va afi?a:

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 ,

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::parse -- datefmt_parse — Parse string to a timestamp value

Descrierea

Stil obiect-orientat

public int IntlDateFormatter::parse ( string $value [, int &$position ] )

Stil procedural

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.

Parametri

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.

Valorile întoarse

timestamp parsed value, or FALSE if value can't be parsed.

Exemple

Example #1 OO 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
);
?>

Example #2 datefmt_parse() 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');
?

Exemplul de mai sus va afi?a:

First parsed output is 630201600
Second parsed output is 630201600

A se vedea ?i

  • 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 type used by the formatter

IntlDateFormatter::parse
IntlDateFormatter::setLenient
IntlDateFormatter
PHP Manual

IntlDateFormatter::setCalendar

datefmt_set_calendar

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::setCalendar -- datefmt_set_calendar — Sets the calendar type used by the formatter

Descrierea

Stil obiect-orientat

bool IntlDateFormatter::setCalendar ( mixed $which )

Stil procedural

bool datefmt_set_calendar ( IntlDateFormatter $fmt , mixed $which )

Sets the calendar or calendar type used by the formatter.

Parametri

fmt

The formatter resource.

which

This can either be: the calendar type to use (default is IntlDateFormatter::GREGORIAN, which is also used if NULL is specified) or an IntlCalendar object.

Any IntlCalendar object passed in will be cloned; no modifications will be made to the argument object.

The timezone of the formatter will only be kept if an IntlCalendar object is not passed, otherwise the new timezone will be that of the passed object.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.0/PECL 3.0.0 | It became possible to pass an IntlCalendar object.

Exemple

Example #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);
?>

Example #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();
?>

Exemplul de mai sus va afi?a:

calendar of the formatter is : 1
Now calendar of the formatter is : 0

Example #3 Example with IntlCalendar argument

<?php
$time = strtotime("2013-03-03 00:00:00 UTC");
$formatter = IntlDateFormatter::create("en_US", NULL, NULL, "Europe/Amsterdam");

echo "before: ", $formatter->format($time), "\n";

/* note that the calendar's locale is not used! */
$formatter->setCalendar(IntlCalendar::createInstance(
               "America/New_York", "pt_PT@calendar=islamic"));

echo "after:  ", $formatter->format($time), "\n";

Exemplul de mai sus va afi?a:

before: Sunday, March 3, 2013 at 1:00:00 AM Central European Standard Time
after:  Saturday, Rabi? II 20, 1434 at 7:00:00 PM Eastern Standard Time

A se vedea ?i

  • datefmt_get_calendar() - Get the calendar type used for the IntlDateFormatter
  • datefmt_get_calendar_object() - Get copy of formatter's calendar object
  • 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, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::setLenient -- datefmt_set_lenient — Set the leniency of the parser

Descrierea

Stil obiect-orientat

public bool IntlDateFormatter::setLenient ( bool $lenient )

Stil procedural

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.

Parametri

fmt

The formatter resource

lenient

Sets whether the parser is lenient or not, default is TRUE (lenient).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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').\nResult is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
    echo "\nError_msg is : " . intl_get_error_message();
    echo "\nError_code is : " . intl_get_error_code();
}
datefmt_set_lenient($fmt, false);
echo "\nNow lenient of the formatter is : ";
if ($fmt->isLenient()) {
    echo 'TRUE';
} else {
    echo 'FALSE';
}
datefmt_parse($fmt, '35/13/1971');
echo "\nTrying to do parse('35/13/1971').\nResult is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
    echo "\nError_msg is : ".intl_get_error_message();
    echo "\nError_code is : ".intl_get_error_code();
}

?>

Example #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').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0) {
    echo "\nError_msg is : " . intl_get_error_message();
    echo "\nError_code is : " . intl_get_error_code();
}

$fmt->setLenient(FALSE);
echo "\nNow 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').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0) {
    echo "\nError_msg is : " . intl_get_error_message();
    echo "\nError_code is : " . intl_get_error_code();
}

?>

Exemplul de mai sus va afi?a:

lenient of the formatter is : TRUE
Trying to do parse('35/13/1971').
Result is : 66038400
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

A se vedea ?i

  • 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, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::setPattern -- datefmt_set_pattern — Set the pattern used for the IntlDateFormatter

Descrierea

Stil obiect-orientat

public bool IntlDateFormatter::setPattern ( string $pattern )

Stil procedural

bool datefmt_set_pattern ( IntlDateFormatter $fmt , string $pattern )

Set the pattern used for the IntlDateFormatter.

Parametri

fmt

The formatter resource.

pattern

New pattern string to use. Possible patterns are documented at » http://userguide.icu-project.org/formatparse/datetime.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Bad formatstrings are usually the cause of the failure.

Exemple

Example #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);

?>

Example #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 ' . $fmt->format(0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ' . $fmt->getPattern();
echo 'Second Formatted output is ' . $fmt->format(0);

?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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
IntlDateFormatter::setTimeZone
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

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.5.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • IntlDateFormatter::setTimeZone()

Descrierea

Stil obiect-orientat

public bool IntlDateFormatter::setTimeZoneId ( string $zone )

Stil procedural

bool datefmt_set_timezone_id ( IntlDateFormatter $fmt , string $zone )

Sets the time zone to use.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | This function has been removed.
5.5.0 | This function has been deprecated.

Exemple

Example #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);
?>

Example #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();

?>

Exemplul de mai sus va afi?a:

timezone_id of the formatter is : America/Los_Angeles
Now timezone_id of the formatter is : CN

A se vedea ?i

  • datefmt_get_timezone_id() - Get the timezone-id used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::setPattern
IntlDateFormatter::setTimeZone
IntlDateFormatter


Sets formatter's timezone

IntlDateFormatter::setTimeZoneId
ResourceBundle
IntlDateFormatter
PHP Manual

IntlDateFormatter::setTimeZone

datefmt_set_timezone

(PHP 5 >= 5.5.0, PHP 7, PECL intl >= 3.0.0)

IntlDateFormatter::setTimeZone -- datefmt_set_timezone — Sets formatter's timezone

Descrierea

Stil obiect-orientat

public boolean IntlDateFormatter::setTimeZone ( mixed $zone )

Stil procedural

boolean datefmt_set_timezone ( mixed $zone )

Sets the timezone that will be used when formatting dates or times with this object.

Parametri

zone

The timezone to use for this formatter. This can be specified in the following forms:

  • NULL, in which case the default timezone will be used, as specified in the ini setting date.timezone or through the function date_default_timezone_set() and as returned by date_default_timezone_get().

  • An IntlTimeZone, which will be used directly.

  • A DateTimeZone. Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICU's database, not PHP's.

  • A string, which should be a valid ICU timezone identifier. See IntlTimeZone::createTimeZoneIDEnumeration(). Raw offsets such as "GMT+08:30" are also accepted.

Valorile întoarse

Returns TRUE on success and FALSE on failure.

Exemple

Example #1 IntlDateFormatter::setTimeZone() examples

<?php
ini_set('date.timezone', 'Europe/Amsterdam');

$formatter = IntlDateFormatter::create(NULL, NULL, NULL, "UTC");

$formatter->setTimeZone(NULL);
echo "NULL\n    ", $formatter->getTimeZone()->getId(), "\n";

$formatter->setTimeZone(IntlTimeZone::createTimeZone('Europe/Lisbon'));
echo "IntlTimeZone\n    ", $formatter->getTimeZone()->getId(), "\n";

$formatter->setTimeZone(new DateTimeZone('Europe/Paris'));
echo "DateTimeZone\n    ", $formatter->getTimeZone()->getId(), "\n";

$formatter->setTimeZone('Europe/Rome');
echo "String\n    ", $formatter->getTimeZone()->getId(), "\n";

$formatter->setTimeZone('GMT+00:30');
print_r($formatter->getTimeZone());

Exemplul de mai sus va afi?a:

NULL
    Europe/Amsterdam
IntlTimeZone
    Europe/Lisbon
DateTimeZone
    Europe/Paris
String
    Europe/Rome
IntlTimeZone Object
(
    [valid] => 1
    [id] => GMT+00:30
    [rawOffset] => 1800000
    [currentOffset] => 1800000
)

A se vedea ?i

  • IntlDateFormatter::getTimeZone() - Get formatter's timezone

IntlDateFormatter::setTimeZoneId
ResourceBundle
IntlDateFormatter


The ResourceBundle class

(PHP >= 5.3.2, PECL intl >= 2.0.0)

Introducere

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 types: 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.

Sinopsisul clasei

ResourceBundle {
/* Methods */
public __construct ( string $locale , string $bundlename [, bool $fallback ] )
public int count ( void )
public static ResourceBundle create ( string $locale , string $bundlename [, bool $fallback ] )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public mixed get ( string|int $index )
public array getLocales ( string $bundlename )
}

A se vedea ?i

  • » ICU Resource Management
  • » ICU Data

Cuprins

  • 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::setTimeZone
ResourceBundle::count
intl


Get number of elements in the bundle

ResourceBundle
ResourceBundle::create
ResourceBundle
PHP Manual

ResourceBundle::count

resourcebundle_count

(PHP >= 5.3.2, PECL intl >= 2.0.0)

ResourceBundle::count -- resourcebundle_count — Get number of elements in the bundle

Descrierea

Stil obiect-orientat

public int ResourceBundle::count ( void )

Stil procedural

int resourcebundle_count ( ResourceBundle $r )

Get the number of elements in the bundle.

Parametri

r

ResourceBundle object.

Valorile întoarse

Returns number of elements in the bundle.

Exemple

Example #1 resourcebundle_count() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo resourcebundle_count($r);
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r->count();
?>

Exemplul de mai sus va afi?a:

42

A se vedea ?i

  • 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.3.2, PECL intl >= 2.0.0)

ResourceBundle::create -- resourcebundle_create -- ResourceBundle::__construct — Create a resource bundle

Descrierea

Stil obiect-orientat (method)

public static ResourceBundle ResourceBundle::create ( string $locale , string $bundlename [, bool $fallback ] )

Stil procedural

ResourceBundle resourcebundle_create ( string $locale , string $bundlename [, bool $fallback ] )

Stil obiect-orientat (constructor):

public ResourceBundle::__construct ( string $locale , string $bundlename [, bool $fallback ] )

Creates a resource bundle.

Parametri

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.

Valorile întoarse

Returns ResourceBundle object or NULL on error.

Exemple

Example #1 resourcebundle_create() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['teststring'];
?>

Example #2 ResourceBundle::create() example

<?php
$r = ResourceBundle::create( 'es', "/usr/share/data/myapp");
echo $r['teststring'];
?>

Exemplul de mai sus va afi?a:

¡Hola, mundo!

A se vedea ?i

  • 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.3.2, PECL intl >= 2.0.0)

ResourceBundle::getErrorCode -- resourcebundle_get_error_code — Get bundle's last error code.

Descrierea

Stil obiect-orientat

public int ResourceBundle::getErrorCode ( void )

Stil procedural

int resourcebundle_get_error_code ( ResourceBundle $r )

Get error code from the last function performed by the bundle object.

Parametri

r

ResourceBundle object.

Valorile întoarse

Returns error code from last bundle object call.

Exemple

Example #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");
}
?>

Example #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");
}
?>

A se vedea ?i

  • 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.3.2, PECL intl >= 2.0.0)

ResourceBundle::getErrorMessage -- resourcebundle_get_error_message — Get bundle's last error message.

Descrierea

Stil obiect-orientat

public string ResourceBundle::getErrorMessage ( void )

Stil procedural

string resourcebundle_get_error_message ( ResourceBundle $r )

Get error message from the last function performed by the bundle object.

Parametri

r

ResourceBundle object.

Valorile întoarse

Returns error message from last bundle object's call.

Exemple

Example #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));
}
?>

Example #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));
}
?>

A se vedea ?i

  • 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.3.2, PECL intl >= 2.0.0)

ResourceBundle::get -- resourcebundle_get — Get data from the bundle

Descrierea

Stil obiect-orientat

public mixed ResourceBundle::get ( string|int $index )

Stil procedural

mixed resourcebundle_get ( ResourceBundle $r , string|int $index )

Get the data from the bundle by index or string key.

Parametri

r

ResourceBundle object.

index

Data index, must be string or integer.

Valorile întoarse

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.

Exemple

Example #1 resourcebundle_get() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo resourcebundle_get($r, 'somestring');
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r->get('somestring');
?>

Exemplul de mai sus va afi?a:

?Hola, mundo!

A se vedea ?i

  • 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.3.2, PECL intl >= 2.0.0)

ResourceBundle::getLocales -- resourcebundle_locales — Get supported locales

Descrierea

Stil obiect-orientat

public array ResourceBundle::getLocales ( string $bundlename )

Stil procedural

array resourcebundle_locales ( string $bundlename )

Get available locales from ResourceBundle name.

Parametri

bundlename

Path of ResourceBundle for which to get available locales, or empty string for default locales list.

Valorile întoarse

Returns the list of locales supported by the bundle.

Exemple

Example #1 resourcebundle_locales() example

<?php
$bundle = "/user/share/data/myapp";
echo join(PHP_EOL, resourcebundle_locales($bundle));
?>

Exemplul de mai sus va afi?a ceva similar cu:

es
root

Example #2 OO example

<?php
$bundle = "/usr/share/data/myapp";
$r = new ResourceBundle( 'es', $bundle);
echo join("\n", $r->getLocales($bundle));
?>

Exemplul de mai sus va afi?a ceva similar cu:

es
root

A se vedea ?i

  • resourcebundle_get() - Get data from the bundle

ResourceBundle::get
Spoofchecker
ResourceBundle


The Spoofchecker class

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Introducere

This class is provided because Unicode contains large number of characters and incorporates the varied writing systems of the world and their incorrect usage can expose programs or systems to possible security attacks using characters similarity.

Provided methods alllow to check whether an individual string is likely an attempt at confusing the reader (spoof detection), such as "p?yp?l" spelled with Cyrillic '?' characters.

Sinopsisul clasei

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 ;
/* Metode */
public bool areConfusable ( string $str1 , string $str2 [, string &$error ] )
public __construct ( void )
public bool isSuspicious ( string $text [, string &$error ] )
public void setAllowedLocales ( string $locale_list )
public void setChecks ( long $checks )
}

Constante predefinite

Spoofchecker::SINGLE_SCRIPT_CONFUSABLE

Spoofchecker::MIXED_SCRIPT_CONFUSABLE

Spoofchecker::WHOLE_SCRIPT_CONFUSABLE

Spoofchecker::ANY_CASE

Spoofchecker::SINGLE_SCRIPT

Spoofchecker::INVISIBLE

Spoofchecker::CHAR_LIMIT

Cuprins

  • Spoofchecker::areConfusable — Checks if given strings can be confused
  • 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 given strings can be confused

Spoofchecker
Spoofchecker::__construct
Spoofchecker
PHP Manual

Spoofchecker::areConfusable

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Spoofchecker::areConfusable — Checks if given strings can be confused

Descrierea

public bool Spoofchecker::areConfusable ( string $str1 , string $str2 [, string &$error ] )

Checks whether two given strings can easily be mistaken.

Parametri

str1

First string to check.

str2

Second string to check.

error

This variable is set by-reference to string containing an error, if there were any.

Valorile întoarse

Returns TRUE if two given strings can be confused, FALSE otherwise.

Exemple

Example #1 Spoofchecker::areConfusable() example

<?php
$checker = new Spoofchecker();

$checker->areConfusable('google.com', 'goog1e.com'); // true
// Lower l can be confused with digit one

$checker->areConfusable('google.com', 'g00g1e.com'); // false
// Zero (0) cannot be easily confused with "o" letter

Spoofchecker
Spoofchecker::__construct
Spoofchecker


Constructor

Spoofchecker::areConfusable
Spoofchecker::isSuspicious
Spoofchecker
PHP Manual

Spoofchecker::__construct

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Spoofchecker::__construct — Constructor

Descrierea

public Spoofchecker::__construct ( void )

Creates new instance of Spoofchecker.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns Spoofchecker instance.

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, PECL intl >= 2.0.0)

Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters

Descrierea

public bool Spoofchecker::isSuspicious ( string $text [, string &$error ] )

Checks if given string contains any suspicious characters like letters which are almost identical visually, but are Unicode characters from different sets.

Parametri

text

String to test.

error

This variable is set by-reference to string containing an error, if there were any.

Valorile întoarse

Returns TRUE if there are suspicious characters, FALSE otherwise.

Exemple

Example #1 Spoofchecker::isSuspicious() example

<?php
$checker = new Spoofchecker();

$checker->isSuspicious('google.com'); // FALSE: only ASCII characters

$checker->isSuspicious('?aypal.com'); // TRUE
// The first letter is from Cyrylic, not a regular latin "P"

Spoofchecker::__construct
Spoofchecker::setAllowedLocales
Spoofchecker


Locales to use when running checks

Spoofchecker::isSuspicious
Spoofchecker::setChecks
Spoofchecker
PHP Manual

Spoofchecker::setAllowedLocales

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Spoofchecker::setAllowedLocales — Locales to use when running checks

Descrierea

public void Spoofchecker::setAllowedLocales ( string $locale_list )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

locale_list

Valorile întoarse

Spoofchecker::isSuspicious
Spoofchecker::setChecks
Spoofchecker


Set the checks to run

Spoofchecker::setAllowedLocales
Transliterator
Spoofchecker
PHP Manual

Spoofchecker::setChecks

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Spoofchecker::setChecks — Set the checks to run

Descrierea

public void Spoofchecker::setChecks ( long $checks )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

checks

Valorile întoarse

Spoofchecker::setAllowedLocales
Transliterator
Spoofchecker


The Transliterator class

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Introducere

Transliterator provides transliteration of strings.

Sinopsisul clasei

Transliterator {
/* Constante */
const integer FORWARD = 0 ;
const integer REVERSE = 1 ;
/* Proprieta?i */
public $id ;
/* Metode */
__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 ]] )
}

Proprieta?i

id

Constante predefinite

Transliterator::FORWARD

Transliterator::REVERSE

Cuprins

  • Transliterator::__construct — Private constructor to deny instantiation
  • 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


Private constructor to deny instantiation

Transliterator
Transliterator::create
Transliterator
PHP Manual

Transliterator::__construct

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Transliterator::__construct — Private constructor to deny instantiation

Descrierea

Transliterator::__construct ( void )

This method should not be called. Its only purpose is to deny instantiation with the new operator.

Use the factory methods Transliterator::create() or Transliterator::createFromRules() instead.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

This method should not be executed. If it is (e.g. through reflection), then its return value is unspecified.

A se vedea ?i

  • Transliterator::create() - Create a transliterator
  • Transliterator::createFromRules() - Create transliterator from rules

Transliterator
Transliterator::create
Transliterator


Create a transliterator

Transliterator::__construct
Transliterator::createFromRules
Transliterator
PHP Manual

Transliterator::create

transliterator_create

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Transliterator::create -- transliterator_create — Create a transliterator

Descrierea

Stil obiect-orientat

public static Transliterator Transliterator::create ( string $id [, int $direction ] )

Stil procedural

Transliterator transliterator_create ( string $id [, int $direction ] )

Opens a Transliterator by id.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

id

The id.

direction

The direction, defaults to >Transliterator::FORWARD. May also be set to Transliterator::REVERSE.

Valorile întoarse

Returns a Transliterator object on success, or NULL on failure.

A se vedea ?i

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::__construct() - Private constructor to deny instantiation

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, PECL intl >= 2.0.0)

Transliterator::createFromRules -- transliterator_create_from_rules — Create transliterator from rules

Descrierea

Stil obiect-orientat

public static Transliterator Transliterator::createFromRules ( string $rules [, string $direction ] )

Stil procedural

Transliterator transliterator_create_from_rules ( string $id [, int $direction ] )

Creates a Transliterator from rules.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

rules

The rules.

direction

The direction, defaults to >Transliterator::FORWARD. May also be set to Transliterator::REVERSE.

Valorile întoarse

Returns a Transliterator object on success, or NULL on failure.

A se vedea ?i

  • 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, PECL intl >= 2.0.0)

Transliterator::createInverse -- transliterator_create_inverse — Create an inverse transliterator

Descrierea

Stil obiect-orientat

public Transliterator Transliterator::createInverse ( void )

Stil procedural

Transliterator transliterator_create_inverse ( void )

Opens the inverse transliterator.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a Transliterator object on success, or NULL on failure

A se vedea ?i

  • 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, PECL intl >= 2.0.0)

Transliterator::getErrorCode -- transliterator_get_error_code — Get last error code

Descrierea

Stil obiect-orientat

public int Transliterator::getErrorCode ( void )

Stil procedural

int transliterator_get_error_code ( void )

Gets the last error code for this transliterator.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The error code on success, or FALSE if none exists, or on failure.

A se vedea ?i

  • 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, PECL intl >= 2.0.0)

Transliterator::getErrorMessage -- transliterator_get_error_message — Get last error message

Descrierea

Stil obiect-orientat

public string Transliterator::getErrorMessage ( void )

Stil procedural

string transliterator_get_error_message ( void )

Gets the last error message for this transliterator.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The error message on success, or FALSE if none exists, or on failure.

A se vedea ?i

  • 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, PECL intl >= 2.0.0)

Transliterator::listIDs -- transliterator_list_ids — Get transliterator IDs

Descrierea

Stil obiect-orientat

public static array Transliterator::listIDs ( void )

Stil procedural

array transliterator_list_ids ( void )

Returns an array with the registered transliterator IDs.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array of registered transliterator IDs on success, sau FALSE în cazul e?ecului.

A se vedea ?i

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::transliterate() - Transliterate a string

Transliterator::getErrorMessage
Transliterator::transliterate
Transliterator


Transliterate a string

Transliterator::listIDs
IntlBreakIterator
Transliterator
PHP Manual

Transliterator::transliterate

transliterator_transliterate

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Transliterator::transliterate -- transliterator_transliterate — Transliterate a string

Descrierea

Stil obiect-orientat

public string Transliterator::transliterate ( string $subject [, int $start [, int $end ]] )

Stil procedural

transliterator_transliterate ( mixed $transliterator , string $subject [, int $start [, int $end ]] )

Transforms a string or part thereof using an ICU transliterator.

Parametri

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.

Valorile întoarse

The transfomed string on success, sau FALSE în cazul e?ecului.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

????????
1
\uD834\uDD1E
??

A se vedea ?i

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::__construct() - Private constructor to deny instantiation

Transliterator::listIDs
IntlBreakIterator
Transliterator


The IntlBreakIterator class

(No version information available, might only be in Git)

Introducere

A “break iterator” is an ICU object that exposes methods for locating boundaries in text (e.g. word or sentence boundaries). The PHP IntlBreakIterator serves as the base class for all types of ICU break iterators. Where extra functionality is available, the intl extension may expose the ICU break iterator with suitable subclasses, such as IntlRuleBasedBreakIterator or IntlCodePointBreaIterator.

This class implements Traversable. Traversing an IntlBreakIterator yields non-negative integer values representing the successive locations of the text boundaries, expressed as UTF-8 code units (byte) counts, taken from the beggining of the text (which has the location 0). The keys yielded by the iterator simply form the sequence of natural numbers {0, 1, 2, …}.

Sinopsisul clasei

IntlBreakIterator implements Traversable {
/* Constants */
const integer DONE = -1 ;
const integer WORD_NONE = 0 ;
const integer WORD_NONE_LIMIT = 100 ;
const integer WORD_NUMBER = 100 ;
const integer WORD_NUMBER_LIMIT = 200 ;
const integer WORD_LETTER = 200 ;
const integer WORD_LETTER_LIMIT = 300 ;
const integer WORD_KANA = 300 ;
const integer WORD_KANA_LIMIT = 400 ;
const integer WORD_IDEO = 400 ;
const integer WORD_IDEO_LIMIT = 500 ;
const integer LINE_SOFT = 0 ;
const integer LINE_SOFT_LIMIT = 100 ;
const integer LINE_HARD = 100 ;
const integer LINE_HARD_LIMIT = 200 ;
const integer SENTENCE_TERM = 0 ;
const integer SENTENCE_TERM_LIMIT = 100 ;
const integer SENTENCE_SEP = 100 ;
const integer SENTENCE_SEP_LIMIT = 200 ;
/* Metode */
private __construct ( void )
public static ReturnType createCharacterInstance ([ string $"locale" ] )
public static ReturnType createCodePointInstance ( void )
public static ReturnType createLineInstance ([ string $"locale" ] )
public static ReturnType createSentenceInstance ([ string $"locale" ] )
public static ReturnType createTitleInstance ([ string $"locale" ] )
public static ReturnType createWordInstance ([ string $"locale" ] )
public ReturnType current ( void )
public ReturnType first ( void )
public ReturnType following ( string $"offset" )
public ReturnType getErrorCode ( void )
ReturnType intl_get_error_code ( void )
public ReturnType getErrorMessage ( void )
ReturnType intl_get_error_message ( void )
public ReturnType getLocale ( string $"locale_type" )
public ReturnType getPartsIterator ([ string $"key_type" ] )
public ReturnType getText ( void )
public ReturnType isBoundary ( string $"offset" )
public ReturnType last ( void )
public ReturnType next ([ string $"offset" ] )
public ReturnType preceding ( string $"offset" )
public ReturnType previous ( void )
public ReturnType setText ( string $"text" )
}

Constante predefinite

IntlBreakIterator::DONE

IntlBreakIterator::WORD_NONE

IntlBreakIterator::WORD_NONE_LIMIT

IntlBreakIterator::WORD_NUMBER

IntlBreakIterator::WORD_NUMBER_LIMIT

IntlBreakIterator::WORD_LETTER

IntlBreakIterator::WORD_LETTER_LIMIT

IntlBreakIterator::WORD_KANA

IntlBreakIterator::WORD_KANA_LIMIT

IntlBreakIterator::WORD_IDEO

IntlBreakIterator::WORD_IDEO_LIMIT

IntlBreakIterator::LINE_SOFT

IntlBreakIterator::LINE_SOFT_LIMIT

IntlBreakIterator::LINE_HARD

IntlBreakIterator::LINE_HARD_LIMIT

IntlBreakIterator::SENTENCE_TERM

IntlBreakIterator::SENTENCE_TERM_LIMIT

IntlBreakIterator::SENTENCE_SEP

IntlBreakIterator::SENTENCE_SEP_LIMIT

Cuprins

  • IntlBreakIterator::__construct — Private constructor for disallowing instantiation
  • IntlBreakIterator::createCharacterInstance — Create break iterator for boundaries of combining character sequences
  • IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points
  • IntlBreakIterator::createLineInstance — Create break iterator for logically possible line breaks
  • IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks
  • IntlBreakIterator::createTitleInstance — Create break iterator for title-casing breaks
  • IntlBreakIterator::createWordInstance — Create break iterator for word breaks
  • IntlBreakIterator::current — Get index of current position
  • IntlBreakIterator::first — Set position to the first character in the text
  • IntlBreakIterator::following — Advance the iterator to the first boundary following specified offset
  • IntlBreakIterator::getErrorCode — Get last error code on the object
  • IntlBreakIterator::getErrorMessage — Get last error message on the object
  • IntlBreakIterator::getLocale — Get the locale associated with the object
  • IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries
  • IntlBreakIterator::getText — Get the text being scanned
  • IntlBreakIterator::isBoundary — Tell whether an offset is a boundary's offset
  • IntlBreakIterator::last — Set the iterator position to index beyond the last character
  • IntlBreakIterator::next — Advance the iterator the next boundary
  • IntlBreakIterator::preceding — Set the iterator position to the first boundary before an offset
  • IntlBreakIterator::previous — Set the iterator position to the boundary immediately before the current
  • IntlBreakIterator::setText — Set the text being scanned
Transliterator::transliterate
IntlBreakIterator::__construct
intl


Private constructor for disallowing instantiation

IntlBreakIterator
IntlBreakIterator::createCharacterInstance
IntlBreakIterator
PHP Manual

IntlBreakIterator::__construct

(No version information available, might only be in Git)

IntlBreakIterator::__construct — Private constructor for disallowing instantiation

Descrierea

private IntlBreakIterator::__construct ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlBreakIterator
IntlBreakIterator::createCharacterInstance
IntlBreakIterator


Create break iterator for boundaries of combining character sequences

IntlBreakIterator::__construct
IntlBreakIterator::createCodePointInstance
IntlBreakIterator
PHP Manual

IntlBreakIterator::createCharacterInstance

(No version information available, might only be in Git)

IntlBreakIterator::createCharacterInstance — Create break iterator for boundaries of combining character sequences

Descrierea

public static ReturnType IntlBreakIterator::createCharacterInstance ([ string $"locale" ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

"locale"

Valorile întoarse

IntlBreakIterator::__construct
IntlBreakIterator::createCodePointInstance
IntlBreakIterator


Create break iterator for boundaries of code points

IntlBreakIterator::createCharacterInstance
IntlBreakIterator::createLineInstance
IntlBreakIterator
PHP Manual

IntlBreakIterator::createCodePointInstance

(No version information available, might only be in Git)

IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points

Descrierea

public static ReturnType IntlBreakIterator::createCodePointInstance ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlBreakIterator::createCharacterInstance
IntlBreakIterator::createLineInstance
IntlBreakIterator


Create break iterator for logically possible line breaks

IntlBreakIterator::createCodePointInstance
IntlBreakIterator::createSentenceInstance
IntlBreakIterator
PHP Manual

IntlBreakIterator::createLineInstance

(No version information available, might only be in Git)

IntlBreakIterator::createLineInstance — Create break iterator for logically possible line breaks

Descrierea

public static ReturnType IntlBreakIterator::createLineInstance ([ string $"locale" ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

"locale"

Valorile întoarse

IntlBreakIterator::createCodePointInstance
IntlBreakIterator::createSentenceInstance
IntlBreakIterator


Create break iterator for sentence breaks

IntlBreakIterator::createLineInstance
IntlBreakIterator::createTitleInstance
IntlBreakIterator
PHP Manual

IntlBreakIterator::createSentenceInstance

(No version information available, might only be in Git)

IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks

Descrierea

public static ReturnType IntlBreakIterator::createSentenceInstance ([ string $"locale" ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

"locale"

Valorile întoarse

IntlBreakIterator::createLineInstance
IntlBreakIterator::createTitleInstance
IntlBreakIterator


Create break iterator for title-casing breaks

IntlBreakIterator::createSentenceInstance
IntlBreakIterator::createWordInstance
IntlBreakIterator
PHP Manual

IntlBreakIterator::createTitleInstance

(No version information available, might only be in Git)

IntlBreakIterator::createTitleInstance — Create break iterator for title-casing breaks

Descrierea

public static ReturnType IntlBreakIterator::createTitleInstance ([ string $"locale" ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

"locale"

Valorile întoarse

IntlBreakIterator::createSentenceInstance
IntlBreakIterator::createWordInstance
IntlBreakIterator


Create break iterator for word breaks

IntlBreakIterator::createTitleInstance
IntlBreakIterator::current
IntlBreakIterator
PHP Manual

IntlBreakIterator::createWordInstance

(No version information available, might only be in Git)

IntlBreakIterator::createWordInstance — Create break iterator for word breaks

Descrierea

public static ReturnType IntlBreakIterator::createWordInstance ([ string $"locale" ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

"locale"

Valorile întoarse

IntlBreakIterator::createTitleInstance
IntlBreakIterator::current
IntlBreakIterator


Get index of current position

IntlBreakIterator::createWordInstance
IntlBreakIterator::first
IntlBreakIterator
PHP Manual

IntlBreakIterator::current

(No version information available, might only be in Git)

IntlBreakIterator::current — Get index of current position

Descrierea

public ReturnType IntlBreakIterator::current ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlBreakIterator::createWordInstance
IntlBreakIterator::first
IntlBreakIterator


Set position to the first character in the text

IntlBreakIterator::current
IntlBreakIterator::following
IntlBreakIterator
PHP Manual

IntlBreakIterator::first

(No version information available, might only be in Git)

IntlBreakIterator::first — Set position to the first character in the text

Descrierea

public ReturnType IntlBreakIterator::first ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlBreakIterator::current
IntlBreakIterator::following
IntlBreakIterator


Advance the iterator to the first boundary following specified offset

IntlBreakIterator::first
IntlBreakIterator::getErrorCode
IntlBreakIterator
PHP Manual

IntlBreakIterator::following

(No version information available, might only be in Git)

IntlBreakIterator::following — Advance the iterator to the first boundary following specified offset

Descrierea

public ReturnType IntlBreakIterator::following ( string $"offset" )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

"offset"

Valorile întoarse

IntlBreakIterator::first
IntlBreakIterator::getErrorCode
IntlBreakIterator


Get last error code on the object

IntlBreakIterator::following
IntlBreakIterator::getErrorMessage
IntlBreakIterator
PHP Manual

IntlBreakIterator::getErrorCode

intl_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlBreakIterator::getErrorCode -- intl_get_error_code — Get last error code on the object

Descrierea

Stil obiect-orientat (method):

public ReturnType IntlBreakIterator::getErrorCode ( void )

Stil procedural:

ReturnType intl_get_error_code ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlBreakIterator::following
IntlBreakIterator::getErrorMessage
IntlBreakIterator


Get last error message on the object

IntlBreakIterator::getErrorCode
IntlBreakIterator::getLocale
IntlBreakIterator
PHP Manual

IntlBreakIterator::getErrorMessage

intl_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlBreakIterator::getErrorMessage -- intl_get_error_message — Get last error message on the object

Descrierea

Stil obiect-orientat (method):

public ReturnType IntlBreakIterator::getErrorMessage ( void )

Stil procedural:

ReturnType intl_get_error_message ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlBreakIterator::getErrorCode
IntlBreakIterator::getLocale
IntlBreakIterator


Get the locale associated with the object

IntlBreakIterator::getErrorMessage
IntlBreakIterator::getPartsIterator
IntlBreakIterator
PHP Manual

IntlBreakIterator::getLocale

(No version information available, might only be in Git)

IntlBreakIterator::getLocale — Get the locale associated with the object

Descrierea

public ReturnType IntlBreakIterator::getLocale ( string $"locale_type" )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

"locale_type"

Valorile întoarse

IntlBreakIterator::getErrorMessage
IntlBreakIterator::getPartsIterator
IntlBreakIterator


Create iterator for navigating fragments between boundaries

IntlBreakIterator::getLocale
IntlBreakIterator::getText
IntlBreakIterator
PHP Manual

IntlBreakIterator::getPartsIterator

(No version information available, might only be in Git)

IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries

Descrierea

public ReturnType IntlBreakIterator::getPartsIterator ([ string $"key_type" ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

"key_type"

Valorile întoarse

IntlBreakIterator::getLocale
IntlBreakIterator::getText
IntlBreakIterator


Get the text being scanned

IntlBreakIterator::getPartsIterator
IntlBreakIterator::isBoundary
IntlBreakIterator
PHP Manual

IntlBreakIterator::getText

(No version information available, might only be in Git)

IntlBreakIterator::getText — Get the text being scanned

Descrierea

public ReturnType IntlBreakIterator::getText ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlBreakIterator::getPartsIterator
IntlBreakIterator::isBoundary
IntlBreakIterator


Tell whether an offset is a boundary's offset

IntlBreakIterator::getText
IntlBreakIterator::last
IntlBreakIterator
PHP Manual

IntlBreakIterator::isBoundary

(No version information available, might only be in Git)

IntlBreakIterator::isBoundary — Tell whether an offset is a boundary's offset

Descrierea

public ReturnType IntlBreakIterator::isBoundary ( string $"offset" )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

"offset"

Valorile întoarse

IntlBreakIterator::getText
IntlBreakIterator::last
IntlBreakIterator


Set the iterator position to index beyond the last character

IntlBreakIterator::isBoundary
IntlBreakIterator::next
IntlBreakIterator
PHP Manual

IntlBreakIterator::last

(No version information available, might only be in Git)

IntlBreakIterator::last — Set the iterator position to index beyond the last character

Descrierea

public ReturnType IntlBreakIterator::last ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlBreakIterator::isBoundary
IntlBreakIterator::next
IntlBreakIterator


Advance the iterator the next boundary

IntlBreakIterator::last
IntlBreakIterator::preceding
IntlBreakIterator
PHP Manual

IntlBreakIterator::next

(No version information available, might only be in Git)

IntlBreakIterator::next — Advance the iterator the next boundary

Descrierea

public ReturnType IntlBreakIterator::next ([ string $"offset" ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

"offset"

Valorile întoarse

IntlBreakIterator::last
IntlBreakIterator::preceding
IntlBreakIterator


Set the iterator position to the first boundary before an offset

IntlBreakIterator::next
IntlBreakIterator::previous
IntlBreakIterator
PHP Manual

IntlBreakIterator::preceding

(No version information available, might only be in Git)

IntlBreakIterator::preceding — Set the iterator position to the first boundary before an offset

Descrierea

public ReturnType IntlBreakIterator::preceding ( string $"offset" )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

"offset"

Valorile întoarse

IntlBreakIterator::next
IntlBreakIterator::previous
IntlBreakIterator


Set the iterator position to the boundary immediately before the current

IntlBreakIterator::preceding
IntlBreakIterator::setText
IntlBreakIterator
PHP Manual

IntlBreakIterator::previous

(No version information available, might only be in Git)

IntlBreakIterator::previous — Set the iterator position to the boundary immediately before the current

Descrierea

public ReturnType IntlBreakIterator::previous ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlBreakIterator::preceding
IntlBreakIterator::setText
IntlBreakIterator


Set the text being scanned

IntlBreakIterator::previous
IntlRuleBasedBreakIterator
IntlBreakIterator
PHP Manual

IntlBreakIterator::setText

(No version information available, might only be in Git)

IntlBreakIterator::setText — Set the text being scanned

Descrierea

public ReturnType IntlBreakIterator::setText ( string $"text" )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

"text"

Valorile întoarse

IntlBreakIterator::previous
IntlRuleBasedBreakIterator
IntlBreakIterator


The IntlRuleBasedBreakIterator class

(No version information available, might only be in Git)

Introducere

A subclass of IntlBreakIterator that encapsulates ICU break iterators whose behavior is specified using a set of rules. This is the most common kind of break iterators.

These rules are described in the » ICU Boundary Analysis User Guide.

Sinopsisul clasei

IntlRuleBasedBreakIterator extends IntlBreakIterator implements Traversable {
/* Constants */
const integer DONE = -1 ;
const integer WORD_NONE = 0 ;
const integer WORD_NONE_LIMIT = 100 ;
const integer WORD_NUMBER = 100 ;
const integer WORD_NUMBER_LIMIT = 200 ;
const integer WORD_LETTER = 200 ;
const integer WORD_LETTER_LIMIT = 300 ;
const integer WORD_KANA = 300 ;
const integer WORD_KANA_LIMIT = 400 ;
const integer WORD_IDEO = 400 ;
const integer WORD_IDEO_LIMIT = 500 ;
const integer LINE_SOFT = 0 ;
const integer LINE_SOFT_LIMIT = 100 ;
const integer LINE_HARD = 100 ;
const integer LINE_HARD_LIMIT = 200 ;
const integer SENTENCE_TERM = 0 ;
const integer SENTENCE_TERM_LIMIT = 100 ;
const integer SENTENCE_SEP = 100 ;
const integer SENTENCE_SEP_LIMIT = 200 ;
/* Metode */
public __construct ( string $rules [, string $areCompiled ] )
public ReturnType getBinaryRules ( void )
public ReturnType getRules ( void )
public ReturnType getRuleStatus ( void )
public ReturnType getRuleStatusVec ( void )
/* Metode mo?tenite */
private IntlBreakIterator::__construct ( void )
public static ReturnType IntlBreakIterator::createCharacterInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createCodePointInstance ( void )
public static ReturnType IntlBreakIterator::createLineInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createSentenceInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createTitleInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createWordInstance ([ string $"locale" ] )
public ReturnType IntlBreakIterator::current ( void )
public ReturnType IntlBreakIterator::first ( void )
public ReturnType IntlBreakIterator::following ( string $"offset" )
public ReturnType IntlBreakIterator::getErrorCode ( void )
ReturnType intl_get_error_code ( void )
public ReturnType IntlBreakIterator::getErrorMessage ( void )
ReturnType intl_get_error_message ( void )
public ReturnType IntlBreakIterator::getLocale ( string $"locale_type" )
public ReturnType IntlBreakIterator::getPartsIterator ([ string $"key_type" ] )
public ReturnType IntlBreakIterator::getText ( void )
public ReturnType IntlBreakIterator::isBoundary ( string $"offset" )
public ReturnType IntlBreakIterator::last ( void )
public ReturnType IntlBreakIterator::next ([ string $"offset" ] )
public ReturnType IntlBreakIterator::preceding ( string $"offset" )
public ReturnType IntlBreakIterator::previous ( void )
public ReturnType IntlBreakIterator::setText ( string $"text" )
}

Constante predefinite

IntlRuleBasedBreakIterator::DONE

IntlRuleBasedBreakIterator::WORD_NONE

IntlRuleBasedBreakIterator::WORD_NONE_LIMIT

IntlRuleBasedBreakIterator::WORD_NUMBER

IntlRuleBasedBreakIterator::WORD_NUMBER_LIMIT

IntlRuleBasedBreakIterator::WORD_LETTER

IntlRuleBasedBreakIterator::WORD_LETTER_LIMIT

IntlRuleBasedBreakIterator::WORD_KANA

IntlRuleBasedBreakIterator::WORD_KANA_LIMIT

IntlRuleBasedBreakIterator::WORD_IDEO

IntlRuleBasedBreakIterator::WORD_IDEO_LIMIT

IntlRuleBasedBreakIterator::LINE_SOFT

IntlRuleBasedBreakIterator::LINE_SOFT_LIMIT

IntlRuleBasedBreakIterator::LINE_HARD

IntlRuleBasedBreakIterator::LINE_HARD_LIMIT

IntlRuleBasedBreakIterator::SENTENCE_TERM

IntlRuleBasedBreakIterator::SENTENCE_TERM_LIMIT

IntlRuleBasedBreakIterator::SENTENCE_SEP

IntlRuleBasedBreakIterator::SENTENCE_SEP_LIMIT

Cuprins

  • IntlRuleBasedBreakIterator::__construct — Create iterator from ruleset
  • IntlRuleBasedBreakIterator::getBinaryRules — Get the binary form of compiled rules
  • IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object
  • IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position
  • IntlRuleBasedBreakIterator::getRuleStatusVec — Get the status values from the break rules that determined the current break position
IntlBreakIterator::setText
IntlRuleBasedBreakIterator::__construct
intl


Create iterator from ruleset

IntlRuleBasedBreakIterator
IntlRuleBasedBreakIterator::getBinaryRules
IntlRuleBasedBreakIterator
PHP Manual

IntlRuleBasedBreakIterator::__construct

(No version information available, might only be in Git)

IntlRuleBasedBreakIterator::__construct — Create iterator from ruleset

Descrierea

public IntlRuleBasedBreakIterator::__construct ( string $rules [, string $areCompiled ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

"rules"

"areCompiled"

Valorile întoarse

IntlRuleBasedBreakIterator
IntlRuleBasedBreakIterator::getBinaryRules
IntlRuleBasedBreakIterator


Get the binary form of compiled rules

IntlRuleBasedBreakIterator::__construct
IntlRuleBasedBreakIterator::getRules
IntlRuleBasedBreakIterator
PHP Manual

IntlRuleBasedBreakIterator::getBinaryRules

(No version information available, might only be in Git)

IntlRuleBasedBreakIterator::getBinaryRules — Get the binary form of compiled rules

Descrierea

public ReturnType IntlRuleBasedBreakIterator::getBinaryRules ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlRuleBasedBreakIterator::__construct
IntlRuleBasedBreakIterator::getRules
IntlRuleBasedBreakIterator


Get the rule set used to create this object

IntlRuleBasedBreakIterator::getBinaryRules
IntlRuleBasedBreakIterator::getRuleStatus
IntlRuleBasedBreakIterator
PHP Manual

IntlRuleBasedBreakIterator::getRules

(No version information available, might only be in Git)

IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object

Descrierea

public ReturnType IntlRuleBasedBreakIterator::getRules ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlRuleBasedBreakIterator::getBinaryRules
IntlRuleBasedBreakIterator::getRuleStatus
IntlRuleBasedBreakIterator


Get the largest status value from the break rules that determined the current break position

IntlRuleBasedBreakIterator::getRules
IntlRuleBasedBreakIterator::getRuleStatusVec
IntlRuleBasedBreakIterator
PHP Manual

IntlRuleBasedBreakIterator::getRuleStatus

(No version information available, might only be in Git)

IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position

Descrierea

public ReturnType IntlRuleBasedBreakIterator::getRuleStatus ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlRuleBasedBreakIterator::getRules
IntlRuleBasedBreakIterator::getRuleStatusVec
IntlRuleBasedBreakIterator


Get the status values from the break rules that determined the current break position

IntlRuleBasedBreakIterator::getRuleStatus
IntlCodePointBreakIterator
IntlRuleBasedBreakIterator
PHP Manual

IntlRuleBasedBreakIterator::getRuleStatusVec

(No version information available, might only be in Git)

IntlRuleBasedBreakIterator::getRuleStatusVec — Get the status values from the break rules that determined the current break position

Descrierea

public ReturnType IntlRuleBasedBreakIterator::getRuleStatusVec ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlRuleBasedBreakIterator::getRuleStatus
IntlCodePointBreakIterator
IntlRuleBasedBreakIterator


The IntlCodePointBreakIterator class

(No version information available, might only be in Git)

Introducere

This break iterator identifies the boundaries between UTF-8 code points.

Sinopsisul clasei

IntlCodePointBreakIterator extends IntlBreakIterator implements Traversable {
/* Constants */
const integer DONE = -1 ;
const integer WORD_NONE = 0 ;
const integer WORD_NONE_LIMIT = 100 ;
const integer WORD_NUMBER = 100 ;
const integer WORD_NUMBER_LIMIT = 200 ;
const integer WORD_LETTER = 200 ;
const integer WORD_LETTER_LIMIT = 300 ;
const integer WORD_KANA = 300 ;
const integer WORD_KANA_LIMIT = 400 ;
const integer WORD_IDEO = 400 ;
const integer WORD_IDEO_LIMIT = 500 ;
const integer LINE_SOFT = 0 ;
const integer LINE_SOFT_LIMIT = 100 ;
const integer LINE_HARD = 100 ;
const integer LINE_HARD_LIMIT = 200 ;
const integer SENTENCE_TERM = 0 ;
const integer SENTENCE_TERM_LIMIT = 100 ;
const integer SENTENCE_SEP = 100 ;
const integer SENTENCE_SEP_LIMIT = 200 ;
/* Metode */
public ReturnType getLastCodePoint ( void )
/* Metode mo?tenite */
private IntlBreakIterator::__construct ( void )
public static ReturnType IntlBreakIterator::createCharacterInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createCodePointInstance ( void )
public static ReturnType IntlBreakIterator::createLineInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createSentenceInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createTitleInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createWordInstance ([ string $"locale" ] )
public ReturnType IntlBreakIterator::current ( void )
public ReturnType IntlBreakIterator::first ( void )
public ReturnType IntlBreakIterator::following ( string $"offset" )
public ReturnType IntlBreakIterator::getErrorCode ( void )
ReturnType intl_get_error_code ( void )
public ReturnType IntlBreakIterator::getErrorMessage ( void )
ReturnType intl_get_error_message ( void )
public ReturnType IntlBreakIterator::getLocale ( string $"locale_type" )
public ReturnType IntlBreakIterator::getPartsIterator ([ string $"key_type" ] )
public ReturnType IntlBreakIterator::getText ( void )
public ReturnType IntlBreakIterator::isBoundary ( string $"offset" )
public ReturnType IntlBreakIterator::last ( void )
public ReturnType IntlBreakIterator::next ([ string $"offset" ] )
public ReturnType IntlBreakIterator::preceding ( string $"offset" )
public ReturnType IntlBreakIterator::previous ( void )
public ReturnType IntlBreakIterator::setText ( string $"text" )
}

Constante predefinite

IntlCodePointBreakIterator::DONE

IntlCodePointBreakIterator::WORD_NONE

IntlCodePointBreakIterator::WORD_NONE_LIMIT

IntlCodePointBreakIterator::WORD_NUMBER

IntlCodePointBreakIterator::WORD_NUMBER_LIMIT

IntlCodePointBreakIterator::WORD_LETTER

IntlCodePointBreakIterator::WORD_LETTER_LIMIT

IntlCodePointBreakIterator::WORD_KANA

IntlCodePointBreakIterator::WORD_KANA_LIMIT

IntlCodePointBreakIterator::WORD_IDEO

IntlCodePointBreakIterator::WORD_IDEO_LIMIT

IntlCodePointBreakIterator::LINE_SOFT

IntlCodePointBreakIterator::LINE_SOFT_LIMIT

IntlCodePointBreakIterator::LINE_HARD

IntlCodePointBreakIterator::LINE_HARD_LIMIT

IntlCodePointBreakIterator::SENTENCE_TERM

IntlCodePointBreakIterator::SENTENCE_TERM_LIMIT

IntlCodePointBreakIterator::SENTENCE_SEP

IntlCodePointBreakIterator::SENTENCE_SEP_LIMIT

Cuprins

  • IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator
IntlRuleBasedBreakIterator::getRuleStatusVec
IntlCodePointBreakIterator::getLastCodePoint
intl


Get last code point passed over after advancing or receding the iterator

IntlCodePointBreakIterator
IntlPartsIterator
IntlCodePointBreakIterator
PHP Manual

IntlCodePointBreakIterator::getLastCodePoint

(No version information available, might only be in Git)

IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator

Descrierea

public ReturnType IntlCodePointBreakIterator::getLastCodePoint ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlCodePointBreakIterator
IntlPartsIterator
IntlCodePointBreakIterator


The IntlPartsIterator class

(No version information available, might only be in Git)

Introducere

Objects of this class can be obtained from IntlBreakIterator objects. While the break iterators provide a sequence of boundary positions when iterated, IntlPartsIterator objects provide, as a convenience, the text fragments comprehended between two successive boundaries.

The keys may represent the offset of the left boundary, right boundary, or they may just the sequence of non-negative integers. See IntlBreakIterator::getPartsIterator().

Sinopsisul clasei

IntlPartsIterator extends IntlIterator implements Iterator {
/* Constants */
const integer KEY_SEQUENTIAL = 0 ;
const integer KEY_LEFT = 1 ;
const integer KEY_RIGHT = 2 ;
/* Metode */
public ReturnType getBreakIterator ( void )
/* Metode mo?tenite */
public ReturnType IntlIterator::current ( void )
public ReturnType IntlIterator::key ( void )
public ReturnType IntlIterator::next ( void )
public ReturnType IntlIterator::rewind ( void )
public ReturnType IntlIterator::valid ( void )
}

Constante predefinite

IntlPartsIterator::KEY_SEQUENTIAL

IntlPartsIterator::KEY_LEFT

IntlPartsIterator::KEY_RIGHT

Cuprins

  • IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator
IntlCodePointBreakIterator::getLastCodePoint
IntlPartsIterator::getBreakIterator
intl


Get IntlBreakIterator backing this parts iterator

IntlPartsIterator
UConverter
IntlPartsIterator
PHP Manual

IntlPartsIterator::getBreakIterator

(No version information available, might only be in Git)

IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator

Descrierea

public ReturnType IntlPartsIterator::getBreakIterator ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlPartsIterator
UConverter
IntlPartsIterator


The UConverter class

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

Introducere

Sinopsisul clasei

UConverter {
/* Constants */
const integer REASON_UNASSIGNED = 0 ;
const integer REASON_ILLEGAL = 1 ;
const integer REASON_IRREGULAR = 2 ;
const integer REASON_RESET = 3 ;
const integer REASON_CLOSE = 4 ;
const integer REASON_CLONE = 5 ;
const integer UNSUPPORTED_CONVERTER = -1 ;
const integer SBCS = 0 ;
const integer DBCS = 1 ;
const integer MBCS = 2 ;
const integer LATIN_1 = 3 ;
const integer UTF8 = 4 ;
const integer UTF16_BigEndian = 5 ;
const integer UTF16_LittleEndian = 6 ;
const integer UTF32_BigEndian = 7 ;
const integer UTF32_LittleEndian = 8 ;
const integer EBCDIC_STATEFUL = 9 ;
const integer ISO_2022 = 10 ;
const integer LMBCS_1 = 11 ;
const integer LMBCS_2 = 12 ;
const integer LMBCS_3 = 13 ;
const integer LMBCS_4 = 14 ;
const integer LMBCS_5 = 15 ;
const integer LMBCS_6 = 16 ;
const integer LMBCS_8 = 17 ;
const integer LMBCS_11 = 18 ;
const integer LMBCS_16 = 19 ;
const integer LMBCS_17 = 20 ;
const integer LMBCS_18 = 21 ;
const integer LMBCS_19 = 22 ;
const integer LMBCS_LAST = 22 ;
const integer HZ = 23 ;
const integer SCSU = 24 ;
const integer ISCII = 25 ;
const integer US_ASCII = 26 ;
const integer UTF7 = 27 ;
const integer BOCU1 = 28 ;
const integer UTF16 = 29 ;
const integer UTF32 = 30 ;
const integer CESU8 = 31 ;
const integer IMAP_MAILBOX = 32 ;
/* Metode */
public __construct ([ string $destination_encoding [, string $source_encoding ]] )
public string convert ( string $str [, bool $reverse ] )
public mixed fromUCallback ( integer $reason , string $source , string $codePoint , integer &$error )
public static array getAliases ([ string $name ] )
public static array getAvailable ( void )
public string getDestinationEncoding ( void )
public integer getDestinationType ( void )
public integer getErrorCode ( void )
public string getErrorMessage ( void )
public string getSourceEncoding ( void )
public integer getSourceType ( void )
public static array getStandards ( void )
public string getSubstChars ( void )
public static string reasonText ([ integer $reason ] )
public void setDestinationEncoding ( string $encoding )
public void setSourceEncoding ( string $encoding )
public void setSubstChars ( string $chars )
public mixed toUCallback ( integer $reason , string $source , string $codeUnits , integer &$error )
public static string transcode ( string $str , string $toEncoding , string $fromEncoding [, array $options ] )
}

Constante predefinite

UConverter::REASON_UNASSIGNED

UConverter::REASON_ILLEGAL

UConverter::REASON_IRREGULAR

UConverter::REASON_RESET

UConverter::REASON_CLOSE

UConverter::REASON_CLONE

UConverter::UNSUPPORTED_CONVERTER

UConverter::SBCS

UConverter::DBCS

UConverter::MBCS

UConverter::LATIN_1

UConverter::UTF8

UConverter::UTF16_BigEndian

UConverter::UTF16_LittleEndian

UConverter::UTF32_BigEndian

UConverter::UTF32_LittleEndian

UConverter::EBCDIC_STATEFUL

UConverter::ISO_2022

UConverter::LMBCS_1

UConverter::LMBCS_2

UConverter::LMBCS_3

UConverter::LMBCS_4

UConverter::LMBCS_5

UConverter::LMBCS_6

UConverter::LMBCS_8

UConverter::LMBCS_11

UConverter::LMBCS_16

UConverter::LMBCS_17

UConverter::LMBCS_18

UConverter::LMBCS_19

UConverter::LMBCS_LAST

UConverter::HZ

UConverter::SCSU

UConverter::ISCII

UConverter::US_ASCII

UConverter::UTF7

UConverter::BOCU1

UConverter::UTF16

UConverter::UTF32

UConverter::CESU8

UConverter::IMAP_MAILBOX

Cuprins

  • UConverter::__construct — Create UConverter object
  • UConverter::convert — Convert string from one charset to another
  • UConverter::fromUCallback — Default "from" callback function
  • UConverter::getAliases — Get the aliases of the given name
  • UConverter::getAvailable — Get the available canonical converter names
  • UConverter::getDestinationEncoding — Get the destination encoding
  • UConverter::getDestinationType — Get the destination converter type
  • UConverter::getErrorCode — Get last error code on the object
  • UConverter::getErrorMessage — Get last error message on the object
  • UConverter::getSourceEncoding — Get the source encoding
  • UConverter::getSourceType — Get the source convertor type
  • UConverter::getStandards — Get standards associated to converter names
  • UConverter::getSubstChars — Get substitution chars
  • UConverter::reasonText — Get string representation of the callback reason
  • UConverter::setDestinationEncoding — Set the destination encoding
  • UConverter::setSourceEncoding — Set the source encoding
  • UConverter::setSubstChars — Set the substitution chars
  • UConverter::toUCallback — Default "to" callback function
  • UConverter::transcode — Convert string from one charset to another
IntlPartsIterator::getBreakIterator
UConverter::__construct
intl


Create UConverter object

UConverter
UConverter::convert
UConverter
PHP Manual

UConverter::__construct

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::__construct — Create UConverter object

Descrierea

public UConverter::__construct ([ string $destination_encoding [, string $source_encoding ]] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

destination_encoding

source_encoding

Valorile întoarse

UConverter
UConverter::convert
UConverter


Convert string from one charset to another

UConverter::__construct
UConverter::fromUCallback
UConverter
PHP Manual

UConverter::convert

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::convert — Convert string from one charset to another

Descrierea

public string UConverter::convert ( string $str [, bool $reverse ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

str

reverse

Valorile întoarse

UConverter::__construct
UConverter::fromUCallback
UConverter


Default "from" callback function

UConverter::convert
UConverter::getAliases
UConverter
PHP Manual

UConverter::fromUCallback

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::fromUCallback — Default "from" callback function

Descrierea

public mixed UConverter::fromUCallback ( integer $reason , string $source , string $codePoint , integer &$error )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

reason

source

codePoint

error

Valorile întoarse

UConverter::convert
UConverter::getAliases
UConverter


Get the aliases of the given name

UConverter::fromUCallback
UConverter::getAvailable
UConverter
PHP Manual

UConverter::getAliases

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getAliases — Get the aliases of the given name

Descrierea

public static array UConverter::getAliases ([ string $name ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

UConverter::fromUCallback
UConverter::getAvailable
UConverter


Get the available canonical converter names

UConverter::getAliases
UConverter::getDestinationEncoding
UConverter
PHP Manual

UConverter::getAvailable

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getAvailable — Get the available canonical converter names

Descrierea

public static array UConverter::getAvailable ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UConverter::getAliases
UConverter::getDestinationEncoding
UConverter


Get the destination encoding

UConverter::getAvailable
UConverter::getDestinationType
UConverter
PHP Manual

UConverter::getDestinationEncoding

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getDestinationEncoding — Get the destination encoding

Descrierea

public string UConverter::getDestinationEncoding ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UConverter::getAvailable
UConverter::getDestinationType
UConverter


Get the destination converter type

UConverter::getDestinationEncoding
UConverter::getErrorCode
UConverter
PHP Manual

UConverter::getDestinationType

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getDestinationType — Get the destination converter type

Descrierea

public integer UConverter::getDestinationType ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UConverter::getDestinationEncoding
UConverter::getErrorCode
UConverter


Get last error code on the object

UConverter::getDestinationType
UConverter::getErrorMessage
UConverter
PHP Manual

UConverter::getErrorCode

intl_get_error_code

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getErrorCode -- intl_get_error_code — Get last error code on the object

Descrierea

public integer UConverter::getErrorCode ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UConverter::getDestinationType
UConverter::getErrorMessage
UConverter


Get last error message on the object

UConverter::getErrorCode
UConverter::getSourceEncoding
UConverter
PHP Manual

UConverter::getErrorMessage

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getErrorMessage — Get last error message on the object

Descrierea

public string UConverter::getErrorMessage ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UConverter::getErrorCode
UConverter::getSourceEncoding
UConverter


Get the source encoding

UConverter::getErrorMessage
UConverter::getSourceType
UConverter
PHP Manual

UConverter::getSourceEncoding

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getSourceEncoding — Get the source encoding

Descrierea

public string UConverter::getSourceEncoding ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UConverter::getErrorMessage
UConverter::getSourceType
UConverter


Get the source convertor type

UConverter::getSourceEncoding
UConverter::getStandards
UConverter
PHP Manual

UConverter::getSourceType

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getSourceType — Get the source convertor type

Descrierea

public integer UConverter::getSourceType ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UConverter::getSourceEncoding
UConverter::getStandards
UConverter


Get standards associated to converter names

UConverter::getSourceType
UConverter::getSubstChars
UConverter
PHP Manual

UConverter::getStandards

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getStandards — Get standards associated to converter names

Descrierea

public static array UConverter::getStandards ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UConverter::getSourceType
UConverter::getSubstChars
UConverter


Get substitution chars

UConverter::getStandards
UConverter::reasonText
UConverter
PHP Manual

UConverter::getSubstChars

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getSubstChars — Get substitution chars

Descrierea

public string UConverter::getSubstChars ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UConverter::getStandards
UConverter::reasonText
UConverter


Get string representation of the callback reason

UConverter::getSubstChars
UConverter::setDestinationEncoding
UConverter
PHP Manual

UConverter::reasonText

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::reasonText — Get string representation of the callback reason

Descrierea

public static string UConverter::reasonText ([ integer $reason ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

reason

Valorile întoarse

UConverter::getSubstChars
UConverter::setDestinationEncoding
UConverter


Set the destination encoding

UConverter::reasonText
UConverter::setSourceEncoding
UConverter
PHP Manual

UConverter::setDestinationEncoding

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::setDestinationEncoding — Set the destination encoding

Descrierea

public void UConverter::setDestinationEncoding ( string $encoding )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

encoding

Valorile întoarse

UConverter::reasonText
UConverter::setSourceEncoding
UConverter


Set the source encoding

UConverter::setDestinationEncoding
UConverter::setSubstChars
UConverter
PHP Manual

UConverter::setSourceEncoding

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::setSourceEncoding — Set the source encoding

Descrierea

public void UConverter::setSourceEncoding ( string $encoding )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

encoding

Valorile întoarse

UConverter::setDestinationEncoding
UConverter::setSubstChars
UConverter


Set the substitution chars

UConverter::setSourceEncoding
UConverter::toUCallback
UConverter
PHP Manual

UConverter::setSubstChars

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::setSubstChars — Set the substitution chars

Descrierea

public void UConverter::setSubstChars ( string $chars )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

chars

Valorile întoarse

UConverter::setSourceEncoding
UConverter::toUCallback
UConverter


Default "to" callback function

UConverter::setSubstChars
UConverter::transcode
UConverter
PHP Manual

UConverter::toUCallback

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::toUCallback — Default "to" callback function

Descrierea

public mixed UConverter::toUCallback ( integer $reason , string $source , string $codeUnits , integer &$error )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

reason

source

codeUnits

error

Valorile întoarse

UConverter::setSubstChars
UConverter::transcode
UConverter


Convert string from one charset to another

UConverter::toUCallback
Func?ii Grapheme
UConverter
PHP Manual

UConverter::transcode

(PHP 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::transcode — Convert string from one charset to another

Descrierea

public static string UConverter::transcode ( string $str , string $toEncoding , string $fromEncoding [, array $options ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

str

toEncoding

fromEncoding

options

Valorile întoarse

UConverter::toUCallback
Func?ii Grapheme
UConverter


Func?ii Grapheme

Cuprins

  • 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
UConverter::transcode
grapheme_extract
intl


Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

Func?ii Grapheme
grapheme_stripos
Func?ii Grapheme
PHP Manual

grapheme_extract

(PHP 5 >= 5.3.0, PHP 7, 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.

Descrierea

Stil procedural

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.

Parametri

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, or a negative value that counts from the end of $haystack. 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.

Valorile întoarse

A string starting at offset $start and ending on a default grapheme cluster boundary that conforms to the $size and $extract_type specified.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Support for negative starts has been added.

Exemple

Example #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));

?>

Exemplul de mai sus va afi?a:

o%CC%88

A se vedea ?i

  • grapheme_substr() - Return part of a string
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

Func?ii Grapheme
grapheme_stripos
Func?ii Grapheme


Find position (in grapheme units) of first occurrence of a case-insensitive string

grapheme_extract
grapheme_stristr
Func?ii Grapheme
PHP Manual

grapheme_stripos

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string

Descrierea

Stil procedural

int grapheme_stripos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of first occurrence of a case-insensitive string

Parametri

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). If the offset is negative, it is treated relative to the end of the string. The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Valorile întoarse

Returns the position as an integer. If needle is not found, grapheme_stripos() will return boolean FALSE.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Support for negative offsets has been added.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

2

A se vedea ?i

  • 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
Func?ii Grapheme


Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.

grapheme_stripos
grapheme_strlen
Func?ii Grapheme
PHP Manual

grapheme_stristr

(PHP 5 >= 5.3.0, PHP 7, 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.

Descrierea

Stil procedural

string grapheme_stristr ( string $haystack , string $needle [, bool $before_needle = false ] )

Returns part of haystack string starting from and including the first occurrence of case-insensitive needle to the end of haystack.

Parametri

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 (excluding needle).

Valorile întoarse

Returns the portion of $haystack, or FALSE if $needle is not found.

Exemple

Example #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));

?>

Exemplul de mai sus va afi?a:

o%CC%88a%CC%8A

A se vedea ?i

  • 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
Func?ii Grapheme


Get string length in grapheme units

grapheme_stristr
grapheme_strpos
Func?ii Grapheme
PHP Manual

grapheme_strlen

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

grapheme_strlen — Get string length in grapheme units

Descrierea

Stil procedural

int grapheme_strlen ( string $input )

Get string length in grapheme units (not bytes or characters)

Parametri

input

The string being measured for length. It must be a valid UTF-8 string.

Valorile întoarse

The length of the string on success, and 0 if the string is empty.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

6

A se vedea ?i

  • » Unicode Text Segmentation: Grapheme Cluster Boundaries
  • iconv_strlen() - Returns the character count of string
  • mb_strlen() - Get string length
  • strlen() - Get string length

grapheme_stristr
grapheme_strpos
Func?ii Grapheme


Find position (in grapheme units) of first occurrence of a string

grapheme_strlen
grapheme_strripos
Func?ii Grapheme
PHP Manual

grapheme_strpos

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

grapheme_strpos — Find position (in grapheme units) of first occurrence of a string

Descrierea

Stil procedural

int grapheme_strpos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of first occurrence of a string

Parametri

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). If the offset is negative, it is treated relative to the end of the string. The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Valorile întoarse

Returns the position as an integer. If needle is not found, grapheme_strpos() will return boolean FALSE.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Support for negative offsets has been added.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

2

A se vedea ?i

  • 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
Func?ii Grapheme


Find position (in grapheme units) of last occurrence of a case-insensitive string

grapheme_strpos
grapheme_strrpos
Func?ii Grapheme
PHP Manual

grapheme_strripos

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string

Descrierea

Stil procedural

int grapheme_strripos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of last occurrence of a case-insensitive string

Parametri

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.

Valorile întoarse

Returns the position as an integer. If needle is not found, grapheme_strripos() will return boolean FALSE.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

2

A se vedea ?i

  • 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
Func?ii Grapheme


Find position (in grapheme units) of last occurrence of a string

grapheme_strripos
grapheme_strstr
Func?ii Grapheme
PHP Manual

grapheme_strrpos

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string

Descrierea

Stil procedural

int grapheme_strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of last occurrence of a string

Parametri

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.

Valorile întoarse

Returns the position as an integer. If needle is not found, grapheme_strrpos() will return boolean FALSE.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

2

A se vedea ?i

  • 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
Func?ii Grapheme


Returns part of haystack string from the first occurrence of needle to the end of haystack.

grapheme_strrpos
grapheme_substr
Func?ii Grapheme
PHP Manual

grapheme_strstr

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack.

Descrierea

Stil procedural

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 (including the needle).

Parametri

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 (excluding the needle).

Valorile întoarse

Returns the portion of string, or FALSE if needle is not found.

Exemple

Example #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));

?>

Exemplul de mai sus va afi?a:

o%CC%88a%CC%8A

A se vedea ?i

  • 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
Func?ii Grapheme


Return part of a string

grapheme_strstr
Func?ii IDN
Func?ii Grapheme
PHP Manual

grapheme_substr

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

grapheme_substr — Return part of a string

Descrierea

Stil procedural

int grapheme_substr ( string $string , int $start [, int $length ] )

Return part of a string

Parametri

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.

Valorile întoarse

Returns the extracted part of $string.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #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 ));
?>

Exemplul de mai sus va afi?a:

a%CC%8Abco%CC%88

A se vedea ?i

  • 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
Func?ii IDN
Func?ii Grapheme


Func?ii IDN

Cuprins

  • idn_to_ascii — Convert domain name to IDNA ASCII form.
  • idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode.
grapheme_substr
idn_to_ascii
intl


Convert domain name to IDNA ASCII form.

Func?ii IDN
idn_to_utf8
Func?ii IDN
PHP Manual

idn_to_ascii

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.2, PHP 7, PECL idn >= 0.1)

idn_to_ascii — Convert domain name to IDNA ASCII form.

Descrierea

Stil procedural

string idn_to_ascii ( string $domain [, int $options = 0 [, int $variant = INTL_IDNA_VARIANT_2003 [, array &$idna_info ]]] )

This function converts a Unicode domain name to an IDNA ASCII-compatible format.

Parametri

domain

The domain to convert, which 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_*.

Valorile întoarse

The domain name encoded in ASCII-compatible form, sau FALSE în cazul e?ecului

Istoricul schimbarilor

Versiune | Descriere
7.2.0 | INTL_IDNA_VARIANT_2003 has been deprecated; use INTL_IDNA_VARIANT_UTS46 instead.
5.4.0/PECL 2.0.0b1 | Added the parameters variant and idna_info; UTS #46 support.

Exemple

Example #1 idn_to_ascii() example

<?php

echo idn_to_ascii('täst.de');

?>

Exemplul de mai sus va afi?a:

xn--tst-qla.de

A se vedea ?i

  • idn_to_utf8() - Convert domain name from IDNA ASCII to Unicode.

Func?ii IDN
idn_to_utf8
Func?ii IDN


Convert domain name from IDNA ASCII to Unicode.

idn_to_ascii
IntlChar
Func?ii IDN
PHP Manual

idn_to_utf8

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.2, PHP 7, PECL idn >= 0.1)

idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode.

Descrierea

Stil procedural

string idn_to_utf8 ( string $domain [, int $options = 0 [, int $variant = INTL_IDNA_VARIANT_2003 [, array &$idna_info ]]] )

This function converts a Unicode domain name from an IDNA ASCII-compatible format to plain Unicode, encoded in UTF-8.

Parametri

domain

Domain to convert in an 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_*.

Valorile întoarse

The domain name in Unicode, encoded in UTF-8, sau FALSE în cazul e?ecului

Istoricul schimbarilor

Versiune | Descriere
7.2.0 | INTL_IDNA_VARIANT_2003 has been deprecated; use INTL_IDNA_VARIANT_UTS46 instead.
5.4.0/PECL 2.0.0b1 | Added the parameters variant and idna_info; UTS #46 support.

Exemple

Example #1 idn_to_utf8() example

<?php

echo idn_to_utf8('xn--tst-qla.de');

?>

Exemplul de mai sus va afi?a:

täst.de

A se vedea ?i

  • idn_to_ascii() - Convert domain name to IDNA ASCII form.

idn_to_ascii
IntlChar
Func?ii IDN


IntlChar

(PHP 7)

Introducere

IntlChar provides access to a number of utility methods that can be used to access information about Unicode characters.

The methods and constants adhere closely to the names and behavior used by the underlying ICU library.

Sinopsisul clasei

IntlChar {
/* Constants */
const string UNICODE_VERSION = 6.3 ;
const integer CODEPOINT_MIN = 0 ;
const integer CODEPOINT_MAX = 1114111 ;
const float NO_NUMERIC_VALUE = -123456789 ;
const integer PROPERTY_ALPHABETIC = 0 ;
const integer PROPERTY_BINARY_START = 0 ;
const integer PROPERTY_ASCII_HEX_DIGIT = 1 ;
const integer PROPERTY_BIDI_CONTROL = 2 ;
const integer PROPERTY_BIDI_MIRRORED = 3 ;
const integer PROPERTY_DASH = 4 ;
const integer PROPERTY_DEFAULT_IGNORABLE_CODE_POINT = 5 ;
const integer PROPERTY_DEPRECATED = 6 ;
const integer PROPERTY_DIACRITIC = 7 ;
const integer PROPERTY_EXTENDER = 8 ;
const integer PROPERTY_FULL_COMPOSITION_EXCLUSION = 9 ;
const integer PROPERTY_GRAPHEME_BASE = 10 ;
const integer PROPERTY_GRAPHEME_EXTEND = 11 ;
const integer PROPERTY_GRAPHEME_LINK = 12 ;
const integer PROPERTY_HEX_DIGIT = 13 ;
const integer PROPERTY_HYPHEN = 14 ;
const integer PROPERTY_ID_CONTINUE = 15 ;
const integer PROPERTY_ID_START = 16 ;
const integer PROPERTY_IDEOGRAPHIC = 17 ;
const integer PROPERTY_IDS_BINARY_OPERATOR = 18 ;
const integer PROPERTY_IDS_TRINARY_OPERATOR = 19 ;
const integer PROPERTY_JOIN_CONTROL = 20 ;
const integer PROPERTY_LOGICAL_ORDER_EXCEPTION = 21 ;
const integer PROPERTY_LOWERCASE = 22 ;
const integer PROPERTY_MATH = 23 ;
const integer PROPERTY_NONCHARACTER_CODE_POINT = 24 ;
const integer PROPERTY_QUOTATION_MARK = 25 ;
const integer PROPERTY_RADICAL = 26 ;
const integer PROPERTY_SOFT_DOTTED = 27 ;
const integer PROPERTY_TERMINAL_PUNCTUATION = 28 ;
const integer PROPERTY_UNIFIED_IDEOGRAPH = 29 ;
const integer PROPERTY_UPPERCASE = 30 ;
const integer PROPERTY_WHITE_SPACE = 31 ;
const integer PROPERTY_XID_CONTINUE = 32 ;
const integer PROPERTY_XID_START = 33 ;
const integer PROPERTY_CASE_SENSITIVE = 34 ;
const integer PROPERTY_S_TERM = 35 ;
const integer PROPERTY_VARIATION_SELECTOR = 36 ;
const integer PROPERTY_NFD_INERT = 37 ;
const integer PROPERTY_NFKD_INERT = 38 ;
const integer PROPERTY_NFC_INERT = 39 ;
const integer PROPERTY_NFKC_INERT = 40 ;
const integer PROPERTY_SEGMENT_STARTER = 41 ;
const integer PROPERTY_PATTERN_SYNTAX = 42 ;
const integer PROPERTY_PATTERN_WHITE_SPACE = 43 ;
const integer PROPERTY_POSIX_ALNUM = 44 ;
const integer PROPERTY_POSIX_BLANK = 45 ;
const integer PROPERTY_POSIX_GRAPH = 46 ;
const integer PROPERTY_POSIX_PRINT = 47 ;
const integer PROPERTY_POSIX_XDIGIT = 48 ;
const integer PROPERTY_CASED = 49 ;
const integer PROPERTY_CASE_IGNORABLE = 50 ;
const integer PROPERTY_CHANGES_WHEN_LOWERCASED = 51 ;
const integer PROPERTY_CHANGES_WHEN_UPPERCASED = 52 ;
const integer PROPERTY_CHANGES_WHEN_TITLECASED = 53 ;
const integer PROPERTY_CHANGES_WHEN_CASEFOLDED = 54 ;
const integer PROPERTY_CHANGES_WHEN_CASEMAPPED = 55 ;
const integer PROPERTY_CHANGES_WHEN_NFKC_CASEFOLDED = 56 ;
const integer PROPERTY_BINARY_LIMIT = 57 ;
const integer PROPERTY_BIDI_CLASS = 4096 ;
const integer PROPERTY_INT_START = 4096 ;
const integer PROPERTY_BLOCK = 4097 ;
const integer PROPERTY_CANONICAL_COMBINING_CLASS = 4098 ;
const integer PROPERTY_DECOMPOSITION_TYPE = 4099 ;
const integer PROPERTY_EAST_ASIAN_WIDTH = 4100 ;
const integer PROPERTY_GENERAL_CATEGORY = 4101 ;
const integer PROPERTY_JOINING_GROUP = 4102 ;
const integer PROPERTY_JOINING_TYPE = 4103 ;
const integer PROPERTY_LINE_BREAK = 4104 ;
const integer PROPERTY_NUMERIC_TYPE = 4105 ;
const integer PROPERTY_SCRIPT = 4106 ;
const integer PROPERTY_HANGUL_SYLLABLE_TYPE = 4107 ;
const integer PROPERTY_NFD_QUICK_CHECK = 4108 ;
const integer PROPERTY_NFKD_QUICK_CHECK = 4109 ;
const integer PROPERTY_NFC_QUICK_CHECK = 4110 ;
const integer PROPERTY_NFKC_QUICK_CHECK = 4111 ;
const integer PROPERTY_LEAD_CANONICAL_COMBINING_CLASS = 4112 ;
const integer PROPERTY_TRAIL_CANONICAL_COMBINING_CLASS = 4113 ;
const integer PROPERTY_GRAPHEME_CLUSTER_BREAK = 4114 ;
const integer PROPERTY_SENTENCE_BREAK = 4115 ;
const integer PROPERTY_WORD_BREAK = 4116 ;
const integer PROPERTY_BIDI_PAIRED_BRACKET_TYPE = 4117 ;
const integer PROPERTY_INT_LIMIT = 4118 ;
const integer PROPERTY_GENERAL_CATEGORY_MASK = 8192 ;
const integer PROPERTY_MASK_START = 8192 ;
const integer PROPERTY_MASK_LIMIT = 8193 ;
const integer PROPERTY_NUMERIC_VALUE = 12288 ;
const integer PROPERTY_DOUBLE_START = 12288 ;
const integer PROPERTY_DOUBLE_LIMIT = 12289 ;
const integer PROPERTY_AGE = 16384 ;
const integer PROPERTY_STRING_START = 16384 ;
const integer PROPERTY_BIDI_MIRRORING_GLYPH = 16385 ;
const integer PROPERTY_CASE_FOLDING = 16386 ;
const integer PROPERTY_ISO_COMMENT = 16387 ;
const integer PROPERTY_LOWERCASE_MAPPING = 16388 ;
const integer PROPERTY_NAME = 16389 ;
const integer PROPERTY_SIMPLE_CASE_FOLDING = 16390 ;
const integer PROPERTY_SIMPLE_LOWERCASE_MAPPING = 16391 ;
const integer PROPERTY_SIMPLE_TITLECASE_MAPPING = 16392 ;
const integer PROPERTY_SIMPLE_UPPERCASE_MAPPING = 16393 ;
const integer PROPERTY_TITLECASE_MAPPING = 16394 ;
const integer PROPERTY_UNICODE_1_NAME = 16395 ;
const integer PROPERTY_UPPERCASE_MAPPING = 16396 ;
const integer PROPERTY_BIDI_PAIRED_BRACKET = 16397 ;
const integer PROPERTY_STRING_LIMIT = 16398 ;
const integer PROPERTY_SCRIPT_EXTENSIONS = 28672 ;
const integer PROPERTY_OTHER_PROPERTY_START = 28672 ;
const integer PROPERTY_OTHER_PROPERTY_LIMIT = 28673 ;
const integer PROPERTY_INVALID_CODE = -1 ;
const integer CHAR_CATEGORY_UNASSIGNED = 0 ;
const integer CHAR_CATEGORY_GENERAL_OTHER_TYPES = 0 ;
const integer CHAR_CATEGORY_UPPERCASE_LETTER = 1 ;
const integer CHAR_CATEGORY_LOWERCASE_LETTER = 2 ;
const integer CHAR_CATEGORY_TITLECASE_LETTER = 3 ;
const integer CHAR_CATEGORY_MODIFIER_LETTER = 4 ;
const integer CHAR_CATEGORY_OTHER_LETTER = 5 ;
const integer CHAR_CATEGORY_NON_SPACING_MARK = 6 ;
const integer CHAR_CATEGORY_ENCLOSING_MARK = 7 ;
const integer CHAR_CATEGORY_COMBINING_SPACING_MARK = 8 ;
const integer CHAR_CATEGORY_DECIMAL_DIGIT_NUMBER = 9 ;
const integer CHAR_CATEGORY_LETTER_NUMBER = 10 ;
const integer CHAR_CATEGORY_OTHER_NUMBER = 11 ;
const integer CHAR_CATEGORY_SPACE_SEPARATOR = 12 ;
const integer CHAR_CATEGORY_LINE_SEPARATOR = 13 ;
const integer CHAR_CATEGORY_PARAGRAPH_SEPARATOR = 14 ;
const integer CHAR_CATEGORY_CONTROL_CHAR = 15 ;
const integer CHAR_CATEGORY_FORMAT_CHAR = 16 ;
const integer CHAR_CATEGORY_PRIVATE_USE_CHAR = 17 ;
const integer CHAR_CATEGORY_SURROGATE = 18 ;
const integer CHAR_CATEGORY_DASH_PUNCTUATION = 19 ;
const integer CHAR_CATEGORY_START_PUNCTUATION = 20 ;
const integer CHAR_CATEGORY_END_PUNCTUATION = 21 ;
const integer CHAR_CATEGORY_CONNECTOR_PUNCTUATION = 22 ;
const integer CHAR_CATEGORY_OTHER_PUNCTUATION = 23 ;
const integer CHAR_CATEGORY_MATH_SYMBOL = 24 ;
const integer CHAR_CATEGORY_CURRENCY_SYMBOL = 25 ;
const integer CHAR_CATEGORY_MODIFIER_SYMBOL = 26 ;
const integer CHAR_CATEGORY_OTHER_SYMBOL = 27 ;
const integer CHAR_CATEGORY_INITIAL_PUNCTUATION = 28 ;
const integer CHAR_CATEGORY_FINAL_PUNCTUATION = 29 ;
const integer CHAR_CATEGORY_CHAR_CATEGORY_COUNT = 30 ;
const integer CHAR_DIRECTION_LEFT_TO_RIGHT = 0 ;
const integer CHAR_DIRECTION_RIGHT_TO_LEFT = 1 ;
const integer CHAR_DIRECTION_EUROPEAN_NUMBER = 2 ;
const integer CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR = 3 ;
const integer CHAR_DIRECTION_EUROPEAN_NUMBER_TERMINATOR = 4 ;
const integer CHAR_DIRECTION_ARABIC_NUMBER = 5 ;
const integer CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR = 6 ;
const integer CHAR_DIRECTION_BLOCK_SEPARATOR = 7 ;
const integer CHAR_DIRECTION_SEGMENT_SEPARATOR = 8 ;
const integer CHAR_DIRECTION_WHITE_SPACE_NEUTRAL = 9 ;
const integer CHAR_DIRECTION_OTHER_NEUTRAL = 10 ;
const integer CHAR_DIRECTION_LEFT_TO_RIGHT_EMBEDDING = 11 ;
const integer CHAR_DIRECTION_LEFT_TO_RIGHT_OVERRIDE = 12 ;
const integer CHAR_DIRECTION_RIGHT_TO_LEFT_ARABIC = 13 ;
const integer CHAR_DIRECTION_RIGHT_TO_LEFT_EMBEDDING = 14 ;
const integer CHAR_DIRECTION_RIGHT_TO_LEFT_OVERRIDE = 15 ;
const integer CHAR_DIRECTION_POP_DIRECTIONAL_FORMAT = 16 ;
const integer CHAR_DIRECTION_DIR_NON_SPACING_MARK = 17 ;
const integer CHAR_DIRECTION_BOUNDARY_NEUTRAL = 18 ;
const integer CHAR_DIRECTION_FIRST_STRONG_ISOLATE = 19 ;
const integer CHAR_DIRECTION_LEFT_TO_RIGHT_ISOLATE = 20 ;
const integer CHAR_DIRECTION_RIGHT_TO_LEFT_ISOLATE = 21 ;
const integer CHAR_DIRECTION_POP_DIRECTIONAL_ISOLATE = 22 ;
const integer CHAR_DIRECTION_CHAR_DIRECTION_COUNT = 23 ;
const integer BLOCK_CODE_NO_BLOCK = 0 ;
const integer BLOCK_CODE_BASIC_LATIN = 1 ;
const integer BLOCK_CODE_LATIN_1_SUPPLEMENT = 2 ;
const integer BLOCK_CODE_LATIN_EXTENDED_A = 3 ;
const integer BLOCK_CODE_LATIN_EXTENDED_B = 4 ;
const integer BLOCK_CODE_IPA_EXTENSIONS = 5 ;
const integer BLOCK_CODE_SPACING_MODIFIER_LETTERS = 6 ;
const integer BLOCK_CODE_COMBINING_DIACRITICAL_MARKS = 7 ;
const integer BLOCK_CODE_GREEK = 8 ;
const integer BLOCK_CODE_CYRILLIC = 9 ;
const integer BLOCK_CODE_ARMENIAN = 10 ;
const integer BLOCK_CODE_HEBREW = 11 ;
const integer BLOCK_CODE_ARABIC = 12 ;
const integer BLOCK_CODE_SYRIAC = 13 ;
const integer BLOCK_CODE_THAANA = 14 ;
const integer BLOCK_CODE_DEVANAGARI = 15 ;
const integer BLOCK_CODE_BENGALI = 16 ;
const integer BLOCK_CODE_GURMUKHI = 17 ;
const integer BLOCK_CODE_GUJARATI = 18 ;
const integer BLOCK_CODE_ORIYA = 19 ;
const integer BLOCK_CODE_TAMIL = 20 ;
const integer BLOCK_CODE_TELUGU = 21 ;
const integer BLOCK_CODE_KANNADA = 22 ;
const integer BLOCK_CODE_MALAYALAM = 23 ;
const integer BLOCK_CODE_SINHALA = 24 ;
const integer BLOCK_CODE_THAI = 25 ;
const integer BLOCK_CODE_LAO = 26 ;
const integer BLOCK_CODE_TIBETAN = 27 ;
const integer BLOCK_CODE_MYANMAR = 28 ;
const integer BLOCK_CODE_GEORGIAN = 29 ;
const integer BLOCK_CODE_HANGUL_JAMO = 30 ;
const integer BLOCK_CODE_ETHIOPIC = 31 ;
const integer BLOCK_CODE_CHEROKEE = 32 ;
const integer BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS = 33 ;
const integer BLOCK_CODE_OGHAM = 34 ;
const integer BLOCK_CODE_RUNIC = 35 ;
const integer BLOCK_CODE_KHMER = 36 ;
const integer BLOCK_CODE_MONGOLIAN = 37 ;
const integer BLOCK_CODE_LATIN_EXTENDED_ADDITIONAL = 38 ;
const integer BLOCK_CODE_GREEK_EXTENDED = 39 ;
const integer BLOCK_CODE_GENERAL_PUNCTUATION = 40 ;
const integer BLOCK_CODE_SUPERSCRIPTS_AND_SUBSCRIPTS = 41 ;
const integer BLOCK_CODE_CURRENCY_SYMBOLS = 42 ;
const integer BLOCK_CODE_COMBINING_MARKS_FOR_SYMBOLS = 43 ;
const integer BLOCK_CODE_LETTERLIKE_SYMBOLS = 44 ;
const integer BLOCK_CODE_NUMBER_FORMS = 45 ;
const integer BLOCK_CODE_ARROWS = 46 ;
const integer BLOCK_CODE_MATHEMATICAL_OPERATORS = 47 ;
const integer BLOCK_CODE_MISCELLANEOUS_TECHNICAL = 48 ;
const integer BLOCK_CODE_CONTROL_PICTURES = 49 ;
const integer BLOCK_CODE_OPTICAL_CHARACTER_RECOGNITION = 50 ;
const integer BLOCK_CODE_ENCLOSED_ALPHANUMERICS = 51 ;
const integer BLOCK_CODE_BOX_DRAWING = 52 ;
const integer BLOCK_CODE_BLOCK_ELEMENTS = 53 ;
const integer BLOCK_CODE_GEOMETRIC_SHAPES = 54 ;
const integer BLOCK_CODE_MISCELLANEOUS_SYMBOLS = 55 ;
const integer BLOCK_CODE_DINGBATS = 56 ;
const integer BLOCK_CODE_BRAILLE_PATTERNS = 57 ;
const integer BLOCK_CODE_CJK_RADICALS_SUPPLEMENT = 58 ;
const integer BLOCK_CODE_KANGXI_RADICALS = 59 ;
const integer BLOCK_CODE_IDEOGRAPHIC_DESCRIPTION_CHARACTERS = 60 ;
const integer BLOCK_CODE_CJK_SYMBOLS_AND_PUNCTUATION = 61 ;
const integer BLOCK_CODE_HIRAGANA = 62 ;
const integer BLOCK_CODE_KATAKANA = 63 ;
const integer BLOCK_CODE_BOPOMOFO = 64 ;
const integer BLOCK_CODE_HANGUL_COMPATIBILITY_JAMO = 65 ;
const integer BLOCK_CODE_KANBUN = 66 ;
const integer BLOCK_CODE_BOPOMOFO_EXTENDED = 67 ;
const integer BLOCK_CODE_ENCLOSED_CJK_LETTERS_AND_MONTHS = 68 ;
const integer BLOCK_CODE_CJK_COMPATIBILITY = 69 ;
const integer BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A = 70 ;
const integer BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS = 71 ;
const integer BLOCK_CODE_YI_SYLLABLES = 72 ;
const integer BLOCK_CODE_YI_RADICALS = 73 ;
const integer BLOCK_CODE_HANGUL_SYLLABLES = 74 ;
const integer BLOCK_CODE_HIGH_SURROGATES = 75 ;
const integer BLOCK_CODE_HIGH_PRIVATE_USE_SURROGATES = 76 ;
const integer BLOCK_CODE_LOW_SURROGATES = 77 ;
const integer BLOCK_CODE_PRIVATE_USE_AREA = 78 ;
const integer BLOCK_CODE_PRIVATE_USE = 78 ;
const integer BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS = 79 ;
const integer BLOCK_CODE_ALPHABETIC_PRESENTATION_FORMS = 80 ;
const integer BLOCK_CODE_ARABIC_PRESENTATION_FORMS_A = 81 ;
const integer BLOCK_CODE_COMBINING_HALF_MARKS = 82 ;
const integer BLOCK_CODE_CJK_COMPATIBILITY_FORMS = 83 ;
const integer BLOCK_CODE_SMALL_FORM_VARIANTS = 84 ;
const integer BLOCK_CODE_ARABIC_PRESENTATION_FORMS_B = 85 ;
const integer BLOCK_CODE_SPECIALS = 86 ;
const integer BLOCK_CODE_HALFWIDTH_AND_FULLWIDTH_FORMS = 87 ;
const integer BLOCK_CODE_OLD_ITALIC = 88 ;
const integer BLOCK_CODE_GOTHIC = 89 ;
const integer BLOCK_CODE_DESERET = 90 ;
const integer BLOCK_CODE_BYZANTINE_MUSICAL_SYMBOLS = 91 ;
const integer BLOCK_CODE_MUSICAL_SYMBOLS = 92 ;
const integer BLOCK_CODE_MATHEMATICAL_ALPHANUMERIC_SYMBOLS = 93 ;
const integer BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B = 94 ;
const integer BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT = 95 ;
const integer BLOCK_CODE_TAGS = 96 ;
const integer BLOCK_CODE_CYRILLIC_SUPPLEMENT = 97 ;
const integer BLOCK_CODE_CYRILLIC_SUPPLEMENTARY = 97 ;
const integer BLOCK_CODE_TAGALOG = 98 ;
const integer BLOCK_CODE_HANUNOO = 99 ;
const integer BLOCK_CODE_BUHID = 100 ;
const integer BLOCK_CODE_TAGBANWA = 101 ;
const integer BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A = 102 ;
const integer BLOCK_CODE_SUPPLEMENTAL_ARROWS_A = 103 ;
const integer BLOCK_CODE_SUPPLEMENTAL_ARROWS_B = 104 ;
const integer BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B = 105 ;
const integer BLOCK_CODE_SUPPLEMENTAL_MATHEMATICAL_OPERATORS = 106 ;
const integer BLOCK_CODE_KATAKANA_PHONETIC_EXTENSIONS = 107 ;
const integer BLOCK_CODE_VARIATION_SELECTORS = 108 ;
const integer BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_A = 109 ;
const integer BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_B = 110 ;
const integer BLOCK_CODE_LIMBU = 111 ;
const integer BLOCK_CODE_TAI_LE = 112 ;
const integer BLOCK_CODE_KHMER_SYMBOLS = 113 ;
const integer BLOCK_CODE_PHONETIC_EXTENSIONS = 114 ;
const integer BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_ARROWS = 115 ;
const integer BLOCK_CODE_YIJING_HEXAGRAM_SYMBOLS = 116 ;
const integer BLOCK_CODE_LINEAR_B_SYLLABARY = 117 ;
const integer BLOCK_CODE_LINEAR_B_IDEOGRAMS = 118 ;
const integer BLOCK_CODE_AEGEAN_NUMBERS = 119 ;
const integer BLOCK_CODE_UGARITIC = 120 ;
const integer BLOCK_CODE_SHAVIAN = 121 ;
const integer BLOCK_CODE_OSMANYA = 122 ;
const integer BLOCK_CODE_CYPRIOT_SYLLABARY = 123 ;
const integer BLOCK_CODE_TAI_XUAN_JING_SYMBOLS = 124 ;
const integer BLOCK_CODE_VARIATION_SELECTORS_SUPPLEMENT = 125 ;
const integer BLOCK_CODE_ANCIENT_GREEK_MUSICAL_NOTATION = 126 ;
const integer BLOCK_CODE_ANCIENT_GREEK_NUMBERS = 127 ;
const integer BLOCK_CODE_ARABIC_SUPPLEMENT = 128 ;
const integer BLOCK_CODE_BUGINESE = 129 ;
const integer BLOCK_CODE_CJK_STROKES = 130 ;
const integer BLOCK_CODE_COMBINING_DIACRITICAL_MARKS_SUPPLEMENT = 131 ;
const integer BLOCK_CODE_COPTIC = 132 ;
const integer BLOCK_CODE_ETHIOPIC_EXTENDED = 133 ;
const integer BLOCK_CODE_ETHIOPIC_SUPPLEMENT = 134 ;
const integer BLOCK_CODE_GEORGIAN_SUPPLEMENT = 135 ;
const integer BLOCK_CODE_GLAGOLITIC = 136 ;
const integer BLOCK_CODE_KHAROSHTHI = 137 ;
const integer BLOCK_CODE_MODIFIER_TONE_LETTERS = 138 ;
const integer BLOCK_CODE_NEW_TAI_LUE = 139 ;
const integer BLOCK_CODE_OLD_PERSIAN = 140 ;
const integer BLOCK_CODE_PHONETIC_EXTENSIONS_SUPPLEMENT = 141 ;
const integer BLOCK_CODE_SUPPLEMENTAL_PUNCTUATION = 142 ;
const integer BLOCK_CODE_SYLOTI_NAGRI = 143 ;
const integer BLOCK_CODE_TIFINAGH = 144 ;
const integer BLOCK_CODE_VERTICAL_FORMS = 145 ;
const integer BLOCK_CODE_NKO = 146 ;
const integer BLOCK_CODE_BALINESE = 147 ;
const integer BLOCK_CODE_LATIN_EXTENDED_C = 148 ;
const integer BLOCK_CODE_LATIN_EXTENDED_D = 149 ;
const integer BLOCK_CODE_PHAGS_PA = 150 ;
const integer BLOCK_CODE_PHOENICIAN = 151 ;
const integer BLOCK_CODE_CUNEIFORM = 152 ;
const integer BLOCK_CODE_CUNEIFORM_NUMBERS_AND_PUNCTUATION = 153 ;
const integer BLOCK_CODE_COUNTING_ROD_NUMERALS = 154 ;
const integer BLOCK_CODE_SUNDANESE = 155 ;
const integer BLOCK_CODE_LEPCHA = 156 ;
const integer BLOCK_CODE_OL_CHIKI = 157 ;
const integer BLOCK_CODE_CYRILLIC_EXTENDED_A = 158 ;
const integer BLOCK_CODE_VAI = 159 ;
const integer BLOCK_CODE_CYRILLIC_EXTENDED_B = 160 ;
const integer BLOCK_CODE_SAURASHTRA = 161 ;
const integer BLOCK_CODE_KAYAH_LI = 162 ;
const integer BLOCK_CODE_REJANG = 163 ;
const integer BLOCK_CODE_CHAM = 164 ;
const integer BLOCK_CODE_ANCIENT_SYMBOLS = 165 ;
const integer BLOCK_CODE_PHAISTOS_DISC = 166 ;
const integer BLOCK_CODE_LYCIAN = 167 ;
const integer BLOCK_CODE_CARIAN = 168 ;
const integer BLOCK_CODE_LYDIAN = 169 ;
const integer BLOCK_CODE_MAHJONG_TILES = 170 ;
const integer BLOCK_CODE_DOMINO_TILES = 171 ;
const integer BLOCK_CODE_SAMARITAN = 172 ;
const integer BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED = 173 ;
const integer BLOCK_CODE_TAI_THAM = 174 ;
const integer BLOCK_CODE_VEDIC_EXTENSIONS = 175 ;
const integer BLOCK_CODE_LISU = 176 ;
const integer BLOCK_CODE_BAMUM = 177 ;
const integer BLOCK_CODE_COMMON_INDIC_NUMBER_FORMS = 178 ;
const integer BLOCK_CODE_DEVANAGARI_EXTENDED = 179 ;
const integer BLOCK_CODE_HANGUL_JAMO_EXTENDED_A = 180 ;
const integer BLOCK_CODE_JAVANESE = 181 ;
const integer BLOCK_CODE_MYANMAR_EXTENDED_A = 182 ;
const integer BLOCK_CODE_TAI_VIET = 183 ;
const integer BLOCK_CODE_MEETEI_MAYEK = 184 ;
const integer BLOCK_CODE_HANGUL_JAMO_EXTENDED_B = 185 ;
const integer BLOCK_CODE_IMPERIAL_ARAMAIC = 186 ;
const integer BLOCK_CODE_OLD_SOUTH_ARABIAN = 187 ;
const integer BLOCK_CODE_AVESTAN = 188 ;
const integer BLOCK_CODE_INSCRIPTIONAL_PARTHIAN = 189 ;
const integer BLOCK_CODE_INSCRIPTIONAL_PAHLAVI = 190 ;
const integer BLOCK_CODE_OLD_TURKIC = 191 ;
const integer BLOCK_CODE_RUMI_NUMERAL_SYMBOLS = 192 ;
const integer BLOCK_CODE_KAITHI = 193 ;
const integer BLOCK_CODE_EGYPTIAN_HIEROGLYPHS = 194 ;
const integer BLOCK_CODE_ENCLOSED_ALPHANUMERIC_SUPPLEMENT = 195 ;
const integer BLOCK_CODE_ENCLOSED_IDEOGRAPHIC_SUPPLEMENT = 196 ;
const integer BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C = 197 ;
const integer BLOCK_CODE_MANDAIC = 198 ;
const integer BLOCK_CODE_BATAK = 199 ;
const integer BLOCK_CODE_ETHIOPIC_EXTENDED_A = 200 ;
const integer BLOCK_CODE_BRAHMI = 201 ;
const integer BLOCK_CODE_BAMUM_SUPPLEMENT = 202 ;
const integer BLOCK_CODE_KANA_SUPPLEMENT = 203 ;
const integer BLOCK_CODE_PLAYING_CARDS = 204 ;
const integer BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS = 205 ;
const integer BLOCK_CODE_EMOTICONS = 206 ;
const integer BLOCK_CODE_TRANSPORT_AND_MAP_SYMBOLS = 207 ;
const integer BLOCK_CODE_ALCHEMICAL_SYMBOLS = 208 ;
const integer BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D = 209 ;
const integer BLOCK_CODE_ARABIC_EXTENDED_A = 210 ;
const integer BLOCK_CODE_ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS = 211 ;
const integer BLOCK_CODE_CHAKMA = 212 ;
const integer BLOCK_CODE_MEETEI_MAYEK_EXTENSIONS = 213 ;
const integer BLOCK_CODE_MEROITIC_CURSIVE = 214 ;
const integer BLOCK_CODE_MEROITIC_HIEROGLYPHS = 215 ;
const integer BLOCK_CODE_MIAO = 216 ;
const integer BLOCK_CODE_SHARADA = 217 ;
const integer BLOCK_CODE_SORA_SOMPENG = 218 ;
const integer BLOCK_CODE_SUNDANESE_SUPPLEMENT = 219 ;
const integer BLOCK_CODE_TAKRI = 220 ;
const integer BLOCK_CODE_COUNT = 221 ;
const integer BLOCK_CODE_INVALID_CODE = -1 ;
const integer BPT_NONE = 0 ;
const integer BPT_OPEN = 1 ;
const integer BPT_CLOSE = 2 ;
const integer BPT_COUNT = 3 ;
const integer EA_NEUTRAL = 0 ;
const integer EA_AMBIGUOUS = 1 ;
const integer EA_HALFWIDTH = 2 ;
const integer EA_FULLWIDTH = 3 ;
const integer EA_NARROW = 4 ;
const integer EA_WIDE = 5 ;
const integer EA_COUNT = 6 ;
const integer UNICODE_CHAR_NAME = 0 ;
const integer UNICODE_10_CHAR_NAME = 1 ;
const integer EXTENDED_CHAR_NAME = 2 ;
const integer CHAR_NAME_ALIAS = 3 ;
const integer CHAR_NAME_CHOICE_COUNT = 4 ;
const integer SHORT_PROPERTY_NAME = 0 ;
const integer LONG_PROPERTY_NAME = 1 ;
const integer PROPERTY_NAME_CHOICE_COUNT = 2 ;
const integer DT_NONE = 0 ;
const integer DT_CANONICAL = 1 ;
const integer DT_COMPAT = 2 ;
const integer DT_CIRCLE = 3 ;
const integer DT_FINAL = 4 ;
const integer DT_FONT = 5 ;
const integer DT_FRACTION = 6 ;
const integer DT_INITIAL = 7 ;
const integer DT_ISOLATED = 8 ;
const integer DT_MEDIAL = 9 ;
const integer DT_NARROW = 10 ;
const integer DT_NOBREAK = 11 ;
const integer DT_SMALL = 12 ;
const integer DT_SQUARE = 13 ;
const integer DT_SUB = 14 ;
const integer DT_SUPER = 15 ;
const integer DT_VERTICAL = 16 ;
const integer DT_WIDE = 17 ;
const integer DT_COUNT = 18 ;
const integer JT_NON_JOINING = 0 ;
const integer JT_JOIN_CAUSING = 1 ;
const integer JT_DUAL_JOINING = 2 ;
const integer JT_LEFT_JOINING = 3 ;
const integer JT_RIGHT_JOINING = 4 ;
const integer JT_TRANSPARENT = 5 ;
const integer JT_COUNT = 6 ;
const integer JG_NO_JOINING_GROUP = 0 ;
const integer JG_AIN = 1 ;
const integer JG_ALAPH = 2 ;
const integer JG_ALEF = 3 ;
const integer JG_BEH = 4 ;
const integer JG_BETH = 5 ;
const integer JG_DAL = 6 ;
const integer JG_DALATH_RISH = 7 ;
const integer JG_E = 8 ;
const integer JG_FEH = 9 ;
const integer JG_FINAL_SEMKATH = 10 ;
const integer JG_GAF = 11 ;
const integer JG_GAMAL = 12 ;
const integer JG_HAH = 13 ;
const integer JG_TEH_MARBUTA_GOAL = 14 ;
const integer JG_HAMZA_ON_HEH_GOAL = 14 ;
const integer JG_HE = 15 ;
const integer JG_HEH = 16 ;
const integer JG_HEH_GOAL = 17 ;
const integer JG_HETH = 18 ;
const integer JG_KAF = 19 ;
const integer JG_KAPH = 20 ;
const integer JG_KNOTTED_HEH = 21 ;
const integer JG_LAM = 22 ;
const integer JG_LAMADH = 23 ;
const integer JG_MEEM = 24 ;
const integer JG_MIM = 25 ;
const integer JG_NOON = 26 ;
const integer JG_NUN = 27 ;
const integer JG_PE = 28 ;
const integer JG_QAF = 29 ;
const integer JG_QAPH = 30 ;
const integer JG_REH = 31 ;
const integer JG_REVERSED_PE = 32 ;
const integer JG_SAD = 33 ;
const integer JG_SADHE = 34 ;
const integer JG_SEEN = 35 ;
const integer JG_SEMKATH = 36 ;
const integer JG_SHIN = 37 ;
const integer JG_SWASH_KAF = 38 ;
const integer JG_SYRIAC_WAW = 39 ;
const integer JG_TAH = 40 ;
const integer JG_TAW = 41 ;
const integer JG_TEH_MARBUTA = 42 ;
const integer JG_TETH = 43 ;
const integer JG_WAW = 44 ;
const integer JG_YEH = 45 ;
const integer JG_YEH_BARREE = 46 ;
const integer JG_YEH_WITH_TAIL = 47 ;
const integer JG_YUDH = 48 ;
const integer JG_YUDH_HE = 49 ;
const integer JG_ZAIN = 50 ;
const integer JG_FE = 51 ;
const integer JG_KHAPH = 52 ;
const integer JG_ZHAIN = 53 ;
const integer JG_BURUSHASKI_YEH_BARREE = 54 ;
const integer JG_FARSI_YEH = 55 ;
const integer JG_NYA = 56 ;
const integer JG_ROHINGYA_YEH = 57 ;
const integer JG_COUNT = 58 ;
const integer GCB_OTHER = 0 ;
const integer GCB_CONTROL = 1 ;
const integer GCB_CR = 2 ;
const integer GCB_EXTEND = 3 ;
const integer GCB_L = 4 ;
const integer GCB_LF = 5 ;
const integer GCB_LV = 6 ;
const integer GCB_LVT = 7 ;
const integer GCB_T = 8 ;
const integer GCB_V = 9 ;
const integer GCB_SPACING_MARK = 10 ;
const integer GCB_PREPEND = 11 ;
const integer GCB_REGIONAL_INDICATOR = 12 ;
const integer GCB_COUNT = 13 ;
const integer WB_OTHER = 0 ;
const integer WB_ALETTER = 1 ;
const integer WB_FORMAT = 2 ;
const integer WB_KATAKANA = 3 ;
const integer WB_MIDLETTER = 4 ;
const integer WB_MIDNUM = 5 ;
const integer WB_NUMERIC = 6 ;
const integer WB_EXTENDNUMLET = 7 ;
const integer WB_CR = 8 ;
const integer WB_EXTEND = 9 ;
const integer WB_LF = 10 ;
const integer WB_MIDNUMLET = 11 ;
const integer WB_NEWLINE = 12 ;
const integer WB_REGIONAL_INDICATOR = 13 ;
const integer WB_HEBREW_LETTER = 14 ;
const integer WB_SINGLE_QUOTE = 15 ;
const integer WB_DOUBLE_QUOTE = 16 ;
const integer WB_COUNT = 17 ;
const integer SB_OTHER = 0 ;
const integer SB_ATERM = 1 ;
const integer SB_CLOSE = 2 ;
const integer SB_FORMAT = 3 ;
const integer SB_LOWER = 4 ;
const integer SB_NUMERIC = 5 ;
const integer SB_OLETTER = 6 ;
const integer SB_SEP = 7 ;
const integer SB_SP = 8 ;
const integer SB_STERM = 9 ;
const integer SB_UPPER = 10 ;
const integer SB_CR = 11 ;
const integer SB_EXTEND = 12 ;
const integer SB_LF = 13 ;
const integer SB_SCONTINUE = 14 ;
const integer SB_COUNT = 15 ;
const integer LB_UNKNOWN = 0 ;
const integer LB_AMBIGUOUS = 1 ;
const integer LB_ALPHABETIC = 2 ;
const integer LB_BREAK_BOTH = 3 ;
const integer LB_BREAK_AFTER = 4 ;
const integer LB_BREAK_BEFORE = 5 ;
const integer LB_MANDATORY_BREAK = 6 ;
const integer LB_CONTINGENT_BREAK = 7 ;
const integer LB_CLOSE_PUNCTUATION = 8 ;
const integer LB_COMBINING_MARK = 9 ;
const integer LB_CARRIAGE_RETURN = 10 ;
const integer LB_EXCLAMATION = 11 ;
const integer LB_GLUE = 12 ;
const integer LB_HYPHEN = 13 ;
const integer LB_IDEOGRAPHIC = 14 ;
const integer LB_INSEPARABLE = 15 ;
const integer LB_INSEPERABLE = 15 ;
const integer LB_INFIX_NUMERIC = 16 ;
const integer LB_LINE_FEED = 17 ;
const integer LB_NONSTARTER = 18 ;
const integer LB_NUMERIC = 19 ;
const integer LB_OPEN_PUNCTUATION = 20 ;
const integer LB_POSTFIX_NUMERIC = 21 ;
const integer LB_PREFIX_NUMERIC = 22 ;
const integer LB_QUOTATION = 23 ;
const integer LB_COMPLEX_CONTEXT = 24 ;
const integer LB_SURROGATE = 25 ;
const integer LB_SPACE = 26 ;
const integer LB_BREAK_SYMBOLS = 27 ;
const integer LB_ZWSPACE = 28 ;
const integer LB_NEXT_LINE = 29 ;
const integer LB_WORD_JOINER = 30 ;
const integer LB_H2 = 31 ;
const integer LB_H3 = 32 ;
const integer LB_JL = 33 ;
const integer LB_JT = 34 ;
const integer LB_JV = 35 ;
const integer LB_CLOSE_PARENTHESIS = 36 ;
const integer LB_CONDITIONAL_JAPANESE_STARTER = 37 ;
const integer LB_HEBREW_LETTER = 38 ;
const integer LB_REGIONAL_INDICATOR = 39 ;
const integer LB_COUNT = 40 ;
const integer NT_NONE = 0 ;
const integer NT_DECIMAL = 1 ;
const integer NT_DIGIT = 2 ;
const integer NT_NUMERIC = 3 ;
const integer NT_COUNT = 4 ;
const integer HST_NOT_APPLICABLE = 0 ;
const integer HST_LEADING_JAMO = 1 ;
const integer HST_VOWEL_JAMO = 2 ;
const integer HST_TRAILING_JAMO = 3 ;
const integer HST_LV_SYLLABLE = 4 ;
const integer HST_LVT_SYLLABLE = 5 ;
const integer HST_COUNT = 6 ;
/* Metode */
public static array charAge ( mixed $codepoint )
public static int charDigitValue ( mixed $codepoint )
public static int charDirection ( mixed $codepoint )
public static int charFromName ( string $characterName [, int $nameChoice = IntlChar::UNICODE_CHAR_NAME ] )
public static mixed charMirror ( mixed $codepoint )
public static string charName ( mixed $codepoint [, int $nameChoice = IntlChar::UNICODE_CHAR_NAME ] )
public static int charType ( mixed $codepoint )
public static string chr ( mixed $codepoint )
public static int digit ( string $codepoint [, int $radix = 10 ] )
public static void enumCharNames ( mixed $start , mixed $limit , callable $callback [, int $nameChoice = IntlChar::UNICODE_CHAR_NAME ] )
public static void enumCharTypes ( callable $callback )
public static mixed foldCase ( mixed $codepoint [, int $options = IntlChar::FOLD_CASE_DEFAULT ] )
public static int forDigit ( int $digit [, int $radix = 10 ] )
public static mixed getBidiPairedBracket ( mixed $codepoint )
public static int getBlockCode ( mixed $codepoint )
public static int getCombiningClass ( mixed $codepoint )
public static string getFC_NFKC_Closure ( mixed $codepoint )
public static int getIntPropertyMaxValue ( int $property )
public static int getIntPropertyMinValue ( int $property )
public static int getIntPropertyValue ( mixed $codepoint , int $property )
public static float getNumericValue ( mixed $codepoint )
public static int getPropertyEnum ( string $alias )
public static string getPropertyName ( int $property [, int $nameChoice = IntlChar::LONG_PROPERTY_NAME ] )
public static int getPropertyValueEnum ( int $property , string $name )
public static string getPropertyValueName ( int $property , int $value [, int $nameChoice = IntlChar::LONG_PROPERTY_NAME ] )
public static array getUnicodeVersion ( void )
public static bool hasBinaryProperty ( mixed $codepoint , int $property )
public static bool isalnum ( mixed $codepoint )
public static bool isalpha ( mixed $codepoint )
public static bool isbase ( mixed $codepoint )
public static bool isblank ( mixed $codepoint )
public static bool iscntrl ( mixed $codepoint )
public static bool isdefined ( mixed $codepoint )
public static bool isdigit ( mixed $codepoint )
public static bool isgraph ( mixed $codepoint )
public static bool isIDIgnorable ( mixed $codepoint )
public static bool isIDPart ( mixed $codepoint )
public static bool isIDStart ( mixed $codepoint )
public static bool isISOControl ( mixed $codepoint )
public static bool isJavaIDPart ( mixed $codepoint )
public static bool isJavaIDStart ( mixed $codepoint )
public static bool isJavaSpaceChar ( mixed $codepoint )
public static bool islower ( mixed $codepoint )
public static bool isMirrored ( mixed $codepoint )
public static bool isprint ( mixed $codepoint )
public static bool ispunct ( mixed $codepoint )
public static bool isspace ( mixed $codepoint )
public static bool istitle ( mixed $codepoint )
public static bool isUAlphabetic ( mixed $codepoint )
public static bool isULowercase ( mixed $codepoint )
public static bool isupper ( mixed $codepoint )
public static bool isUUppercase ( mixed $codepoint )
public static bool isUWhiteSpace ( mixed $codepoint )
public static bool isWhitespace ( mixed $codepoint )
public static bool isxdigit ( mixed $codepoint )
public static int ord ( mixed $character )
public static mixed tolower ( mixed $codepoint )
public static mixed totitle ( mixed $codepoint )
public static mixed toupper ( mixed $codepoint )
}

Constante predefinite

IntlChar::UNICODE_VERSION

IntlChar::CODEPOINT_MIN

IntlChar::CODEPOINT_MAX

IntlChar::NO_NUMERIC_VALUE

Special value that is returned by IntlChar::getNumericValue() when no numeric value is defined for a code point.

IntlChar::PROPERTY_ALPHABETIC

IntlChar::PROPERTY_BINARY_START

IntlChar::PROPERTY_ASCII_HEX_DIGIT

IntlChar::PROPERTY_BIDI_CONTROL

IntlChar::PROPERTY_BIDI_MIRRORED

IntlChar::PROPERTY_DASH

IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT

IntlChar::PROPERTY_DEPRECATED

IntlChar::PROPERTY_DIACRITIC

IntlChar::PROPERTY_EXTENDER

IntlChar::PROPERTY_FULL_COMPOSITION_EXCLUSION

IntlChar::PROPERTY_GRAPHEME_BASE

IntlChar::PROPERTY_GRAPHEME_EXTEND

IntlChar::PROPERTY_GRAPHEME_LINK

IntlChar::PROPERTY_HEX_DIGIT

IntlChar::PROPERTY_HYPHEN

IntlChar::PROPERTY_ID_CONTINUE

IntlChar::PROPERTY_ID_START

IntlChar::PROPERTY_IDEOGRAPHIC

IntlChar::PROPERTY_IDS_BINARY_OPERATOR

IntlChar::PROPERTY_IDS_TRINARY_OPERATOR

IntlChar::PROPERTY_JOIN_CONTROL

IntlChar::PROPERTY_LOGICAL_ORDER_EXCEPTION

IntlChar::PROPERTY_LOWERCASE

IntlChar::PROPERTY_MATH

IntlChar::PROPERTY_NONCHARACTER_CODE_POINT

IntlChar::PROPERTY_QUOTATION_MARK

IntlChar::PROPERTY_RADICAL

IntlChar::PROPERTY_SOFT_DOTTED

IntlChar::PROPERTY_TERMINAL_PUNCTUATION

IntlChar::PROPERTY_UNIFIED_IDEOGRAPH

IntlChar::PROPERTY_UPPERCASE

IntlChar::PROPERTY_WHITE_SPACE

IntlChar::PROPERTY_XID_CONTINUE

IntlChar::PROPERTY_XID_START

IntlChar::PROPERTY_CASE_SENSITIVE

IntlChar::PROPERTY_S_TERM

IntlChar::PROPERTY_VARIATION_SELECTOR

IntlChar::PROPERTY_NFD_INERT

IntlChar::PROPERTY_NFKD_INERT

IntlChar::PROPERTY_NFC_INERT

IntlChar::PROPERTY_NFKC_INERT

IntlChar::PROPERTY_SEGMENT_STARTER

IntlChar::PROPERTY_PATTERN_SYNTAX

IntlChar::PROPERTY_PATTERN_WHITE_SPACE

IntlChar::PROPERTY_POSIX_ALNUM

IntlChar::PROPERTY_POSIX_BLANK

IntlChar::PROPERTY_POSIX_GRAPH

IntlChar::PROPERTY_POSIX_PRINT

IntlChar::PROPERTY_POSIX_XDIGIT

IntlChar::PROPERTY_CASED

IntlChar::PROPERTY_CASE_IGNORABLE

IntlChar::PROPERTY_CHANGES_WHEN_LOWERCASED

IntlChar::PROPERTY_CHANGES_WHEN_UPPERCASED

IntlChar::PROPERTY_CHANGES_WHEN_TITLECASED

IntlChar::PROPERTY_CHANGES_WHEN_CASEFOLDED

IntlChar::PROPERTY_CHANGES_WHEN_CASEMAPPED

IntlChar::PROPERTY_CHANGES_WHEN_NFKC_CASEFOLDED

IntlChar::PROPERTY_BINARY_LIMIT

IntlChar::PROPERTY_BIDI_CLASS

IntlChar::PROPERTY_INT_START

IntlChar::PROPERTY_BLOCK

IntlChar::PROPERTY_CANONICAL_COMBINING_CLASS

IntlChar::PROPERTY_DECOMPOSITION_TYPE

IntlChar::PROPERTY_EAST_ASIAN_WIDTH

IntlChar::PROPERTY_GENERAL_CATEGORY

IntlChar::PROPERTY_JOINING_GROUP

IntlChar::PROPERTY_JOINING_TYPE

IntlChar::PROPERTY_LINE_BREAK

IntlChar::PROPERTY_NUMERIC_TYPE

IntlChar::PROPERTY_SCRIPT

IntlChar::PROPERTY_HANGUL_SYLLABLE_TYPE

IntlChar::PROPERTY_NFD_QUICK_CHECK

IntlChar::PROPERTY_NFKD_QUICK_CHECK

IntlChar::PROPERTY_NFC_QUICK_CHECK

IntlChar::PROPERTY_NFKC_QUICK_CHECK

IntlChar::PROPERTY_LEAD_CANONICAL_COMBINING_CLASS

IntlChar::PROPERTY_TRAIL_CANONICAL_COMBINING_CLASS

IntlChar::PROPERTY_GRAPHEME_CLUSTER_BREAK

IntlChar::PROPERTY_SENTENCE_BREAK

IntlChar::PROPERTY_WORD_BREAK

IntlChar::PROPERTY_BIDI_PAIRED_BRACKET_TYPE

IntlChar::PROPERTY_INT_LIMIT

IntlChar::PROPERTY_GENERAL_CATEGORY_MASK

IntlChar::PROPERTY_MASK_START

IntlChar::PROPERTY_MASK_LIMIT

IntlChar::PROPERTY_NUMERIC_VALUE

IntlChar::PROPERTY_DOUBLE_START

IntlChar::PROPERTY_DOUBLE_LIMIT

IntlChar::PROPERTY_AGE

IntlChar::PROPERTY_STRING_START

IntlChar::PROPERTY_BIDI_MIRRORING_GLYPH

IntlChar::PROPERTY_CASE_FOLDING

IntlChar::PROPERTY_ISO_COMMENT

IntlChar::PROPERTY_LOWERCASE_MAPPING

IntlChar::PROPERTY_NAME

IntlChar::PROPERTY_SIMPLE_CASE_FOLDING

IntlChar::PROPERTY_SIMPLE_LOWERCASE_MAPPING

IntlChar::PROPERTY_SIMPLE_TITLECASE_MAPPING

IntlChar::PROPERTY_SIMPLE_UPPERCASE_MAPPING

IntlChar::PROPERTY_TITLECASE_MAPPING

IntlChar::PROPERTY_UNICODE_1_NAME

IntlChar::PROPERTY_UPPERCASE_MAPPING

IntlChar::PROPERTY_BIDI_PAIRED_BRACKET

IntlChar::PROPERTY_STRING_LIMIT

IntlChar::PROPERTY_SCRIPT_EXTENSIONS

IntlChar::PROPERTY_OTHER_PROPERTY_START

IntlChar::PROPERTY_OTHER_PROPERTY_LIMIT

IntlChar::PROPERTY_INVALID_CODE

IntlChar::CHAR_CATEGORY_UNASSIGNED

IntlChar::CHAR_CATEGORY_GENERAL_OTHER_TYPES

IntlChar::CHAR_CATEGORY_UPPERCASE_LETTER

IntlChar::CHAR_CATEGORY_LOWERCASE_LETTER

IntlChar::CHAR_CATEGORY_TITLECASE_LETTER

IntlChar::CHAR_CATEGORY_MODIFIER_LETTER

IntlChar::CHAR_CATEGORY_OTHER_LETTER

IntlChar::CHAR_CATEGORY_NON_SPACING_MARK

IntlChar::CHAR_CATEGORY_ENCLOSING_MARK

IntlChar::CHAR_CATEGORY_COMBINING_SPACING_MARK

IntlChar::CHAR_CATEGORY_DECIMAL_DIGIT_NUMBER

IntlChar::CHAR_CATEGORY_LETTER_NUMBER

IntlChar::CHAR_CATEGORY_OTHER_NUMBER

IntlChar::CHAR_CATEGORY_SPACE_SEPARATOR

IntlChar::CHAR_CATEGORY_LINE_SEPARATOR

IntlChar::CHAR_CATEGORY_PARAGRAPH_SEPARATOR

IntlChar::CHAR_CATEGORY_CONTROL_CHAR

IntlChar::CHAR_CATEGORY_FORMAT_CHAR

IntlChar::CHAR_CATEGORY_PRIVATE_USE_CHAR

IntlChar::CHAR_CATEGORY_SURROGATE

IntlChar::CHAR_CATEGORY_DASH_PUNCTUATION

IntlChar::CHAR_CATEGORY_START_PUNCTUATION

IntlChar::CHAR_CATEGORY_END_PUNCTUATION

IntlChar::CHAR_CATEGORY_CONNECTOR_PUNCTUATION

IntlChar::CHAR_CATEGORY_OTHER_PUNCTUATION

IntlChar::CHAR_CATEGORY_MATH_SYMBOL

IntlChar::CHAR_CATEGORY_CURRENCY_SYMBOL

IntlChar::CHAR_CATEGORY_MODIFIER_SYMBOL

IntlChar::CHAR_CATEGORY_OTHER_SYMBOL

IntlChar::CHAR_CATEGORY_INITIAL_PUNCTUATION

IntlChar::CHAR_CATEGORY_FINAL_PUNCTUATION

IntlChar::CHAR_CATEGORY_CHAR_CATEGORY_COUNT

IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT

IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT

IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER

IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR

IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_TERMINATOR

IntlChar::CHAR_DIRECTION_ARABIC_NUMBER

IntlChar::CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR

IntlChar::CHAR_DIRECTION_BLOCK_SEPARATOR

IntlChar::CHAR_DIRECTION_SEGMENT_SEPARATOR

IntlChar::CHAR_DIRECTION_WHITE_SPACE_NEUTRAL

IntlChar::CHAR_DIRECTION_OTHER_NEUTRAL

IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_EMBEDDING

IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_OVERRIDE

IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ARABIC

IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_EMBEDDING

IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_OVERRIDE

IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_FORMAT

IntlChar::CHAR_DIRECTION_DIR_NON_SPACING_MARK

IntlChar::CHAR_DIRECTION_BOUNDARY_NEUTRAL

IntlChar::CHAR_DIRECTION_FIRST_STRONG_ISOLATE

IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_ISOLATE

IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ISOLATE

IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_ISOLATE

IntlChar::CHAR_DIRECTION_CHAR_DIRECTION_COUNT

IntlChar::BLOCK_CODE_NO_BLOCK

IntlChar::BLOCK_CODE_BASIC_LATIN

IntlChar::BLOCK_CODE_LATIN_1_SUPPLEMENT

IntlChar::BLOCK_CODE_LATIN_EXTENDED_A

IntlChar::BLOCK_CODE_LATIN_EXTENDED_B

IntlChar::BLOCK_CODE_IPA_EXTENSIONS

IntlChar::BLOCK_CODE_SPACING_MODIFIER_LETTERS

IntlChar::BLOCK_CODE_COMBINING_DIACRITICAL_MARKS

IntlChar::BLOCK_CODE_GREEK

IntlChar::BLOCK_CODE_CYRILLIC

IntlChar::BLOCK_CODE_ARMENIAN

IntlChar::BLOCK_CODE_HEBREW

IntlChar::BLOCK_CODE_ARABIC

IntlChar::BLOCK_CODE_SYRIAC

IntlChar::BLOCK_CODE_THAANA

IntlChar::BLOCK_CODE_DEVANAGARI

IntlChar::BLOCK_CODE_BENGALI

IntlChar::BLOCK_CODE_GURMUKHI

IntlChar::BLOCK_CODE_GUJARATI

IntlChar::BLOCK_CODE_ORIYA

IntlChar::BLOCK_CODE_TAMIL

IntlChar::BLOCK_CODE_TELUGU

IntlChar::BLOCK_CODE_KANNADA

IntlChar::BLOCK_CODE_MALAYALAM

IntlChar::BLOCK_CODE_SINHALA

IntlChar::BLOCK_CODE_THAI

IntlChar::BLOCK_CODE_LAO

IntlChar::BLOCK_CODE_TIBETAN

IntlChar::BLOCK_CODE_MYANMAR

IntlChar::BLOCK_CODE_GEORGIAN

IntlChar::BLOCK_CODE_HANGUL_JAMO

IntlChar::BLOCK_CODE_ETHIOPIC

IntlChar::BLOCK_CODE_CHEROKEE

IntlChar::BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS

IntlChar::BLOCK_CODE_OGHAM

IntlChar::BLOCK_CODE_RUNIC

IntlChar::BLOCK_CODE_KHMER

IntlChar::BLOCK_CODE_MONGOLIAN

IntlChar::BLOCK_CODE_LATIN_EXTENDED_ADDITIONAL

IntlChar::BLOCK_CODE_GREEK_EXTENDED

IntlChar::BLOCK_CODE_GENERAL_PUNCTUATION

IntlChar::BLOCK_CODE_SUPERSCRIPTS_AND_SUBSCRIPTS

IntlChar::BLOCK_CODE_CURRENCY_SYMBOLS

IntlChar::BLOCK_CODE_COMBINING_MARKS_FOR_SYMBOLS

IntlChar::BLOCK_CODE_LETTERLIKE_SYMBOLS

IntlChar::BLOCK_CODE_NUMBER_FORMS

IntlChar::BLOCK_CODE_ARROWS

IntlChar::BLOCK_CODE_MATHEMATICAL_OPERATORS

IntlChar::BLOCK_CODE_MISCELLANEOUS_TECHNICAL

IntlChar::BLOCK_CODE_CONTROL_PICTURES

IntlChar::BLOCK_CODE_OPTICAL_CHARACTER_RECOGNITION

IntlChar::BLOCK_CODE_ENCLOSED_ALPHANUMERICS

IntlChar::BLOCK_CODE_BOX_DRAWING

IntlChar::BLOCK_CODE_BLOCK_ELEMENTS

IntlChar::BLOCK_CODE_GEOMETRIC_SHAPES

IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS

IntlChar::BLOCK_CODE_DINGBATS

IntlChar::BLOCK_CODE_BRAILLE_PATTERNS

IntlChar::BLOCK_CODE_CJK_RADICALS_SUPPLEMENT

IntlChar::BLOCK_CODE_KANGXI_RADICALS

IntlChar::BLOCK_CODE_IDEOGRAPHIC_DESCRIPTION_CHARACTERS

IntlChar::BLOCK_CODE_CJK_SYMBOLS_AND_PUNCTUATION

IntlChar::BLOCK_CODE_HIRAGANA

IntlChar::BLOCK_CODE_KATAKANA

IntlChar::BLOCK_CODE_BOPOMOFO

IntlChar::BLOCK_CODE_HANGUL_COMPATIBILITY_JAMO

IntlChar::BLOCK_CODE_KANBUN

IntlChar::BLOCK_CODE_BOPOMOFO_EXTENDED

IntlChar::BLOCK_CODE_ENCLOSED_CJK_LETTERS_AND_MONTHS

IntlChar::BLOCK_CODE_CJK_COMPATIBILITY

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS

IntlChar::BLOCK_CODE_YI_SYLLABLES

IntlChar::BLOCK_CODE_YI_RADICALS

IntlChar::BLOCK_CODE_HANGUL_SYLLABLES

IntlChar::BLOCK_CODE_HIGH_SURROGATES

IntlChar::BLOCK_CODE_HIGH_PRIVATE_USE_SURROGATES

IntlChar::BLOCK_CODE_LOW_SURROGATES

IntlChar::BLOCK_CODE_PRIVATE_USE_AREA

IntlChar::BLOCK_CODE_PRIVATE_USE

IntlChar::BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS

IntlChar::BLOCK_CODE_ALPHABETIC_PRESENTATION_FORMS

IntlChar::BLOCK_CODE_ARABIC_PRESENTATION_FORMS_A

IntlChar::BLOCK_CODE_COMBINING_HALF_MARKS

IntlChar::BLOCK_CODE_CJK_COMPATIBILITY_FORMS

IntlChar::BLOCK_CODE_SMALL_FORM_VARIANTS

IntlChar::BLOCK_CODE_ARABIC_PRESENTATION_FORMS_B

IntlChar::BLOCK_CODE_SPECIALS

IntlChar::BLOCK_CODE_HALFWIDTH_AND_FULLWIDTH_FORMS

IntlChar::BLOCK_CODE_OLD_ITALIC

IntlChar::BLOCK_CODE_GOTHIC

IntlChar::BLOCK_CODE_DESERET

IntlChar::BLOCK_CODE_BYZANTINE_MUSICAL_SYMBOLS

IntlChar::BLOCK_CODE_MUSICAL_SYMBOLS

IntlChar::BLOCK_CODE_MATHEMATICAL_ALPHANUMERIC_SYMBOLS

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B

IntlChar::BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT

IntlChar::BLOCK_CODE_TAGS

IntlChar::BLOCK_CODE_CYRILLIC_SUPPLEMENT

IntlChar::BLOCK_CODE_CYRILLIC_SUPPLEMENTARY

IntlChar::BLOCK_CODE_TAGALOG

IntlChar::BLOCK_CODE_HANUNOO

IntlChar::BLOCK_CODE_BUHID

IntlChar::BLOCK_CODE_TAGBANWA

IntlChar::BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A

IntlChar::BLOCK_CODE_SUPPLEMENTAL_ARROWS_A

IntlChar::BLOCK_CODE_SUPPLEMENTAL_ARROWS_B

IntlChar::BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B

IntlChar::BLOCK_CODE_SUPPLEMENTAL_MATHEMATICAL_OPERATORS

IntlChar::BLOCK_CODE_KATAKANA_PHONETIC_EXTENSIONS

IntlChar::BLOCK_CODE_VARIATION_SELECTORS

IntlChar::BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_A

IntlChar::BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_B

IntlChar::BLOCK_CODE_LIMBU

IntlChar::BLOCK_CODE_TAI_LE

IntlChar::BLOCK_CODE_KHMER_SYMBOLS

IntlChar::BLOCK_CODE_PHONETIC_EXTENSIONS

IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_ARROWS

IntlChar::BLOCK_CODE_YIJING_HEXAGRAM_SYMBOLS

IntlChar::BLOCK_CODE_LINEAR_B_SYLLABARY

IntlChar::BLOCK_CODE_LINEAR_B_IDEOGRAMS

IntlChar::BLOCK_CODE_AEGEAN_NUMBERS

IntlChar::BLOCK_CODE_UGARITIC

IntlChar::BLOCK_CODE_SHAVIAN

IntlChar::BLOCK_CODE_OSMANYA

IntlChar::BLOCK_CODE_CYPRIOT_SYLLABARY

IntlChar::BLOCK_CODE_TAI_XUAN_JING_SYMBOLS

IntlChar::BLOCK_CODE_VARIATION_SELECTORS_SUPPLEMENT

IntlChar::BLOCK_CODE_ANCIENT_GREEK_MUSICAL_NOTATION

IntlChar::BLOCK_CODE_ANCIENT_GREEK_NUMBERS

IntlChar::BLOCK_CODE_ARABIC_SUPPLEMENT

IntlChar::BLOCK_CODE_BUGINESE

IntlChar::BLOCK_CODE_CJK_STROKES

IntlChar::BLOCK_CODE_COMBINING_DIACRITICAL_MARKS_SUPPLEMENT

IntlChar::BLOCK_CODE_COPTIC

IntlChar::BLOCK_CODE_ETHIOPIC_EXTENDED

IntlChar::BLOCK_CODE_ETHIOPIC_SUPPLEMENT

IntlChar::BLOCK_CODE_GEORGIAN_SUPPLEMENT

IntlChar::BLOCK_CODE_GLAGOLITIC

IntlChar::BLOCK_CODE_KHAROSHTHI

IntlChar::BLOCK_CODE_MODIFIER_TONE_LETTERS

IntlChar::BLOCK_CODE_NEW_TAI_LUE

IntlChar::BLOCK_CODE_OLD_PERSIAN

IntlChar::BLOCK_CODE_PHONETIC_EXTENSIONS_SUPPLEMENT

IntlChar::BLOCK_CODE_SUPPLEMENTAL_PUNCTUATION

IntlChar::BLOCK_CODE_SYLOTI_NAGRI

IntlChar::BLOCK_CODE_TIFINAGH

IntlChar::BLOCK_CODE_VERTICAL_FORMS

IntlChar::BLOCK_CODE_NKO

IntlChar::BLOCK_CODE_BALINESE

IntlChar::BLOCK_CODE_LATIN_EXTENDED_C

IntlChar::BLOCK_CODE_LATIN_EXTENDED_D

IntlChar::BLOCK_CODE_PHAGS_PA

IntlChar::BLOCK_CODE_PHOENICIAN

IntlChar::BLOCK_CODE_CUNEIFORM

IntlChar::BLOCK_CODE_CUNEIFORM_NUMBERS_AND_PUNCTUATION

IntlChar::BLOCK_CODE_COUNTING_ROD_NUMERALS

IntlChar::BLOCK_CODE_SUNDANESE

IntlChar::BLOCK_CODE_LEPCHA

IntlChar::BLOCK_CODE_OL_CHIKI

IntlChar::BLOCK_CODE_CYRILLIC_EXTENDED_A

IntlChar::BLOCK_CODE_VAI

IntlChar::BLOCK_CODE_CYRILLIC_EXTENDED_B

IntlChar::BLOCK_CODE_SAURASHTRA

IntlChar::BLOCK_CODE_KAYAH_LI

IntlChar::BLOCK_CODE_REJANG

IntlChar::BLOCK_CODE_CHAM

IntlChar::BLOCK_CODE_ANCIENT_SYMBOLS

IntlChar::BLOCK_CODE_PHAISTOS_DISC

IntlChar::BLOCK_CODE_LYCIAN

IntlChar::BLOCK_CODE_CARIAN

IntlChar::BLOCK_CODE_LYDIAN

IntlChar::BLOCK_CODE_MAHJONG_TILES

IntlChar::BLOCK_CODE_DOMINO_TILES

IntlChar::BLOCK_CODE_SAMARITAN

IntlChar::BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED

IntlChar::BLOCK_CODE_TAI_THAM

IntlChar::BLOCK_CODE_VEDIC_EXTENSIONS

IntlChar::BLOCK_CODE_LISU

IntlChar::BLOCK_CODE_BAMUM

IntlChar::BLOCK_CODE_COMMON_INDIC_NUMBER_FORMS

IntlChar::BLOCK_CODE_DEVANAGARI_EXTENDED

IntlChar::BLOCK_CODE_HANGUL_JAMO_EXTENDED_A

IntlChar::BLOCK_CODE_JAVANESE

IntlChar::BLOCK_CODE_MYANMAR_EXTENDED_A

IntlChar::BLOCK_CODE_TAI_VIET

IntlChar::BLOCK_CODE_MEETEI_MAYEK

IntlChar::BLOCK_CODE_HANGUL_JAMO_EXTENDED_B

IntlChar::BLOCK_CODE_IMPERIAL_ARAMAIC

IntlChar::BLOCK_CODE_OLD_SOUTH_ARABIAN

IntlChar::BLOCK_CODE_AVESTAN

IntlChar::BLOCK_CODE_INSCRIPTIONAL_PARTHIAN

IntlChar::BLOCK_CODE_INSCRIPTIONAL_PAHLAVI

IntlChar::BLOCK_CODE_OLD_TURKIC

IntlChar::BLOCK_CODE_RUMI_NUMERAL_SYMBOLS

IntlChar::BLOCK_CODE_KAITHI

IntlChar::BLOCK_CODE_EGYPTIAN_HIEROGLYPHS

IntlChar::BLOCK_CODE_ENCLOSED_ALPHANUMERIC_SUPPLEMENT

IntlChar::BLOCK_CODE_ENCLOSED_IDEOGRAPHIC_SUPPLEMENT

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C

IntlChar::BLOCK_CODE_MANDAIC

IntlChar::BLOCK_CODE_BATAK

IntlChar::BLOCK_CODE_ETHIOPIC_EXTENDED_A

IntlChar::BLOCK_CODE_BRAHMI

IntlChar::BLOCK_CODE_BAMUM_SUPPLEMENT

IntlChar::BLOCK_CODE_KANA_SUPPLEMENT

IntlChar::BLOCK_CODE_PLAYING_CARDS

IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS

IntlChar::BLOCK_CODE_EMOTICONS

IntlChar::BLOCK_CODE_TRANSPORT_AND_MAP_SYMBOLS

IntlChar::BLOCK_CODE_ALCHEMICAL_SYMBOLS

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D

IntlChar::BLOCK_CODE_ARABIC_EXTENDED_A

IntlChar::BLOCK_CODE_ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS

IntlChar::BLOCK_CODE_CHAKMA

IntlChar::BLOCK_CODE_MEETEI_MAYEK_EXTENSIONS

IntlChar::BLOCK_CODE_MEROITIC_CURSIVE

IntlChar::BLOCK_CODE_MEROITIC_HIEROGLYPHS

IntlChar::BLOCK_CODE_MIAO

IntlChar::BLOCK_CODE_SHARADA

IntlChar::BLOCK_CODE_SORA_SOMPENG

IntlChar::BLOCK_CODE_SUNDANESE_SUPPLEMENT

IntlChar::BLOCK_CODE_TAKRI

IntlChar::BLOCK_CODE_COUNT

IntlChar::BLOCK_CODE_INVALID_CODE

IntlChar::BPT_NONE

IntlChar::BPT_OPEN

IntlChar::BPT_CLOSE

IntlChar::BPT_COUNT

IntlChar::EA_NEUTRAL

IntlChar::EA_AMBIGUOUS

IntlChar::EA_HALFWIDTH

IntlChar::EA_FULLWIDTH

IntlChar::EA_NARROW

IntlChar::EA_WIDE

IntlChar::EA_COUNT

IntlChar::UNICODE_CHAR_NAME

IntlChar::UNICODE_10_CHAR_NAME

IntlChar::EXTENDED_CHAR_NAME

IntlChar::CHAR_NAME_ALIAS

IntlChar::CHAR_NAME_CHOICE_COUNT

IntlChar::SHORT_PROPERTY_NAME

IntlChar::LONG_PROPERTY_NAME

IntlChar::PROPERTY_NAME_CHOICE_COUNT

IntlChar::DT_NONE

IntlChar::DT_CANONICAL

IntlChar::DT_COMPAT

IntlChar::DT_CIRCLE

IntlChar::DT_FINAL

IntlChar::DT_FONT

IntlChar::DT_FRACTION

IntlChar::DT_INITIAL

IntlChar::DT_ISOLATED

IntlChar::DT_MEDIAL

IntlChar::DT_NARROW

IntlChar::DT_NOBREAK

IntlChar::DT_SMALL

IntlChar::DT_SQUARE

IntlChar::DT_SUB

IntlChar::DT_SUPER

IntlChar::DT_VERTICAL

IntlChar::DT_WIDE

IntlChar::DT_COUNT

IntlChar::JT_NON_JOINING

IntlChar::JT_JOIN_CAUSING

IntlChar::JT_DUAL_JOINING

IntlChar::JT_LEFT_JOINING

IntlChar::JT_RIGHT_JOINING

IntlChar::JT_TRANSPARENT

IntlChar::JT_COUNT

IntlChar::JG_NO_JOINING_GROUP

IntlChar::JG_AIN

IntlChar::JG_ALAPH

IntlChar::JG_ALEF

IntlChar::JG_BEH

IntlChar::JG_BETH

IntlChar::JG_DAL

IntlChar::JG_DALATH_RISH

IntlChar::JG_E

IntlChar::JG_FEH

IntlChar::JG_FINAL_SEMKATH

IntlChar::JG_GAF

IntlChar::JG_GAMAL

IntlChar::JG_HAH

IntlChar::JG_TEH_MARBUTA_GOAL

IntlChar::JG_HAMZA_ON_HEH_GOAL

IntlChar::JG_HE

IntlChar::JG_HEH

IntlChar::JG_HEH_GOAL

IntlChar::JG_HETH

IntlChar::JG_KAF

IntlChar::JG_KAPH

IntlChar::JG_KNOTTED_HEH

IntlChar::JG_LAM

IntlChar::JG_LAMADH

IntlChar::JG_MEEM

IntlChar::JG_MIM

IntlChar::JG_NOON

IntlChar::JG_NUN

IntlChar::JG_PE

IntlChar::JG_QAF

IntlChar::JG_QAPH

IntlChar::JG_REH

IntlChar::JG_REVERSED_PE

IntlChar::JG_SAD

IntlChar::JG_SADHE

IntlChar::JG_SEEN

IntlChar::JG_SEMKATH

IntlChar::JG_SHIN

IntlChar::JG_SWASH_KAF

IntlChar::JG_SYRIAC_WAW

IntlChar::JG_TAH

IntlChar::JG_TAW

IntlChar::JG_TEH_MARBUTA

IntlChar::JG_TETH

IntlChar::JG_WAW

IntlChar::JG_YEH

IntlChar::JG_YEH_BARREE

IntlChar::JG_YEH_WITH_TAIL

IntlChar::JG_YUDH

IntlChar::JG_YUDH_HE

IntlChar::JG_ZAIN

IntlChar::JG_FE

IntlChar::JG_KHAPH

IntlChar::JG_ZHAIN

IntlChar::JG_BURUSHASKI_YEH_BARREE

IntlChar::JG_FARSI_YEH

IntlChar::JG_NYA

IntlChar::JG_ROHINGYA_YEH

IntlChar::JG_COUNT

IntlChar::GCB_OTHER

IntlChar::GCB_CONTROL

IntlChar::GCB_CR

IntlChar::GCB_EXTEND

IntlChar::GCB_L

IntlChar::GCB_LF

IntlChar::GCB_LV

IntlChar::GCB_LVT

IntlChar::GCB_T

IntlChar::GCB_V

IntlChar::GCB_SPACING_MARK

IntlChar::GCB_PREPEND

IntlChar::GCB_REGIONAL_INDICATOR

IntlChar::GCB_COUNT

IntlChar::WB_OTHER

IntlChar::WB_ALETTER

IntlChar::WB_FORMAT

IntlChar::WB_KATAKANA

IntlChar::WB_MIDLETTER

IntlChar::WB_MIDNUM

IntlChar::WB_NUMERIC

IntlChar::WB_EXTENDNUMLET

IntlChar::WB_CR

IntlChar::WB_EXTEND

IntlChar::WB_LF

IntlChar::WB_MIDNUMLET

IntlChar::WB_NEWLINE

IntlChar::WB_REGIONAL_INDICATOR

IntlChar::WB_HEBREW_LETTER

IntlChar::WB_SINGLE_QUOTE

IntlChar::WB_DOUBLE_QUOTE

IntlChar::WB_COUNT

IntlChar::SB_OTHER

IntlChar::SB_ATERM

IntlChar::SB_CLOSE

IntlChar::SB_FORMAT

IntlChar::SB_LOWER

IntlChar::SB_NUMERIC

IntlChar::SB_OLETTER

IntlChar::SB_SEP

IntlChar::SB_SP

IntlChar::SB_STERM

IntlChar::SB_UPPER

IntlChar::SB_CR

IntlChar::SB_EXTEND

IntlChar::SB_LF

IntlChar::SB_SCONTINUE

IntlChar::SB_COUNT

IntlChar::LB_UNKNOWN

IntlChar::LB_AMBIGUOUS

IntlChar::LB_ALPHABETIC

IntlChar::LB_BREAK_BOTH

IntlChar::LB_BREAK_AFTER

IntlChar::LB_BREAK_BEFORE

IntlChar::LB_MANDATORY_BREAK

IntlChar::LB_CONTINGENT_BREAK

IntlChar::LB_CLOSE_PUNCTUATION

IntlChar::LB_COMBINING_MARK

IntlChar::LB_CARRIAGE_RETURN

IntlChar::LB_EXCLAMATION

IntlChar::LB_GLUE

IntlChar::LB_HYPHEN

IntlChar::LB_IDEOGRAPHIC

IntlChar::LB_INSEPARABLE

IntlChar::LB_INSEPERABLE

IntlChar::LB_INFIX_NUMERIC

IntlChar::LB_LINE_FEED

IntlChar::LB_NONSTARTER

IntlChar::LB_NUMERIC

IntlChar::LB_OPEN_PUNCTUATION

IntlChar::LB_POSTFIX_NUMERIC

IntlChar::LB_PREFIX_NUMERIC

IntlChar::LB_QUOTATION

IntlChar::LB_COMPLEX_CONTEXT

IntlChar::LB_SURROGATE

IntlChar::LB_SPACE

IntlChar::LB_BREAK_SYMBOLS

IntlChar::LB_ZWSPACE

IntlChar::LB_NEXT_LINE

IntlChar::LB_WORD_JOINER

IntlChar::LB_H2

IntlChar::LB_H3

IntlChar::LB_JL

IntlChar::LB_JT

IntlChar::LB_JV

IntlChar::LB_CLOSE_PARENTHESIS

IntlChar::LB_CONDITIONAL_JAPANESE_STARTER

IntlChar::LB_HEBREW_LETTER

IntlChar::LB_REGIONAL_INDICATOR

IntlChar::LB_COUNT

IntlChar::NT_NONE

IntlChar::NT_DECIMAL

IntlChar::NT_DIGIT

IntlChar::NT_NUMERIC

IntlChar::NT_COUNT

IntlChar::HST_NOT_APPLICABLE

IntlChar::HST_LEADING_JAMO

IntlChar::HST_VOWEL_JAMO

IntlChar::HST_TRAILING_JAMO

IntlChar::HST_LV_SYLLABLE

IntlChar::HST_LVT_SYLLABLE

IntlChar::HST_COUNT

IntlChar::FOLD_CASE_DEFAULT

IntlChar::FOLD_CASE_EXCLUDE_SPECIAL_I

Istoricul schimbarilor

Versiune | Descriere
7.0.6 | The IntlChar::NO_NUMERIC_VALUE constant was added.

Cuprins

  • IntlChar::charAge — Get the "age" of the code point
  • IntlChar::charDigitValue — Get the decimal digit value of a decimal digit character
  • IntlChar::charDirection — Get bidirectional category value for a code point
  • IntlChar::charFromName — Find Unicode character by name and return its code point value
  • IntlChar::charMirror — Get the "mirror-image" character for a code point
  • IntlChar::charName — Retrieve the name of a Unicode character
  • IntlChar::charType — Get the general category value for a code point
  • IntlChar::chr — Return Unicode character by code point value
  • IntlChar::digit — Get the decimal digit value of a code point for a given radix
  • IntlChar::enumCharNames — Enumerate all assigned Unicode characters within a range
  • IntlChar::enumCharTypes — Enumerate all code points with their Unicode general categories
  • IntlChar::foldCase — Perform case folding on a code point
  • IntlChar::forDigit — Get character representation for a given digit and radix
  • IntlChar::getBidiPairedBracket — Get the paired bracket character for a code point
  • IntlChar::getBlockCode — Get the Unicode allocation block containing a code point
  • IntlChar::getCombiningClass — Get the combining class of a code point
  • IntlChar::getFC_NFKC_Closure — Get the FC_NFKC_Closure property for a code point
  • IntlChar::getIntPropertyMaxValue — Get the max value for a Unicode property
  • IntlChar::getIntPropertyMinValue — Get the min value for a Unicode property
  • IntlChar::getIntPropertyValue — Get the value for a Unicode property for a code point
  • IntlChar::getNumericValue — Get the numeric value for a Unicode code point
  • IntlChar::getPropertyEnum — Get the property constant value for a given property name
  • IntlChar::getPropertyName — Get the Unicode name for a property
  • IntlChar::getPropertyValueEnum — Get the property value for a given value name
  • IntlChar::getPropertyValueName — Get the Unicode name for a property value
  • IntlChar::getUnicodeVersion — Get the Unicode version
  • IntlChar::hasBinaryProperty — Check a binary Unicode property for a code point
  • IntlChar::isalnum — Check if code point is an alphanumeric character
  • IntlChar::isalpha — Check if code point is a letter character
  • IntlChar::isbase — Check if code point is a base character
  • IntlChar::isblank — Check if code point is a "blank" or "horizontal space" character
  • IntlChar::iscntrl — Check if code point is a control character
  • IntlChar::isdefined — Check whether the code point is defined
  • IntlChar::isdigit — Check if code point is a digit character
  • IntlChar::isgraph — Check if code point is a graphic character
  • IntlChar::isIDIgnorable — Check if code point is an ignorable character
  • IntlChar::isIDPart — Check if code point is permissible in an identifier
  • IntlChar::isIDStart — Check if code point is permissible as the first character in an identifier
  • IntlChar::isISOControl — Check if code point is an ISO control code
  • IntlChar::isJavaIDPart — Check if code point is permissible in a Java identifier
  • IntlChar::isJavaIDStart — Check if code point is permissible as the first character in a Java identifier
  • IntlChar::isJavaSpaceChar — Check if code point is a space character according to Java
  • IntlChar::islower — Check if code point is a lowercase letter
  • IntlChar::isMirrored — Check if code point has the Bidi_Mirrored property
  • IntlChar::isprint — Check if code point is a printable character
  • IntlChar::ispunct — Check if code point is punctuation character
  • IntlChar::isspace — Check if code point is a space character
  • IntlChar::istitle — Check if code point is a titlecase letter
  • IntlChar::isUAlphabetic — Check if code point has the Alphabetic Unicode property
  • IntlChar::isULowercase — Check if code point has the Lowercase Unicode property
  • IntlChar::isupper — Check if code point has the general category "Lu" (uppercase letter)
  • IntlChar::isUUppercase — Check if code point has the Uppercase Unicode property
  • IntlChar::isUWhiteSpace — Check if code point has the White_Space Unicode property
  • IntlChar::isWhitespace — Check if code point is a whitespace character according to ICU
  • IntlChar::isxdigit — Check if code point is a hexadecimal digit
  • IntlChar::ord — Return Unicode code point value of character
  • IntlChar::tolower — Make Unicode character lowercase
  • IntlChar::totitle — Make Unicode character titlecase
  • IntlChar::toupper — Make Unicode character uppercase
idn_to_utf8
IntlChar::charAge
intl


Get the "age" of the code point

IntlChar
IntlChar::charDigitValue
IntlChar
PHP Manual

IntlChar::charAge

(PHP 7)

IntlChar::charAge — Get the "age" of the code point

Descrierea

public static array IntlChar::charAge ( mixed $codepoint )

Gets the "age" of the code point.

The "age" is the Unicode version when the code point was first designated (as a non-character or for Private Use) or assigned a character. This can be useful to avoid emitting code points to receiving processes that do not accept newer characters.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

The Unicode version number, as an array. For example, version 1.3.31.2 would be represented as [1, 3, 31, 2].

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::charage("\u{2603}"));
var_dump(IntlChar::charage("\u{1F576}"));
?>

Exemplul de mai sus va afi?a:

array(4) {
  [0]=>
  int(1)
  [1]=>
  int(1)
  [2]=>
  int(0)
  [3]=>
  int(0)
}
array(4) {
  [0]=>
  int(7)
  [1]=>
  int(0)
  [2]=>
  int(0)
  [3]=>
  int(0)
}

A se vedea ?i

  • IntlChar::getUnicodeVersion() - Get the Unicode version
  • IntlChar::getIntPropertyMinValue() - Get the min value for a Unicode property
  • IntlChar::getIntPropertyValue() - Get the value for a Unicode property for a code point

IntlChar
IntlChar::charDigitValue
IntlChar


Get the decimal digit value of a decimal digit character

IntlChar::charAge
IntlChar::charDirection
IntlChar
PHP Manual

IntlChar::charDigitValue

(PHP 7)

IntlChar::charDigitValue — Get the decimal digit value of a decimal digit character

Descrierea

public static int IntlChar::charDigitValue ( mixed $codepoint )

Returns the decimal digit value of a decimal digit character.

Such characters have the general category "Nd" (decimal digit numbers) and a Numeric_Type of Decimal.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

The decimal digit value of codepoint, or -1 if it is not a decimal digit character.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::charDigitValue("1"));
var_dump(IntlChar::charDigitValue("\u{0662}"));
var_dump(IntlChar::charDigitValue("\u{0E53}"));
?>

Exemplul de mai sus va afi?a:

int(1)
int(2)
int(3)

A se vedea ?i

  • IntlChar::getNumericValue() - Get the numeric value for a Unicode code point

IntlChar::charAge
IntlChar::charDirection
IntlChar


Get bidirectional category value for a code point

IntlChar::charDigitValue
IntlChar::charFromName
IntlChar
PHP Manual

IntlChar::charDirection

(PHP 7)

IntlChar::charDirection — Get bidirectional category value for a code point

Descrierea

public static int IntlChar::charDirection ( mixed $codepoint )

Returns the bidirectional category value for the code point, which is used in the » Unicode bidirectional algorithm (UAX #9).

Nota:

Some unassigned code points have bidi values of R or AL because they are in blocks that are reserved for Right-To-Left scripts.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

The bidirectional category value; one of the following constants:

  • IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT
  • IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT
  • IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER
  • IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR
  • IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_TERMINATOR
  • IntlChar::CHAR_DIRECTION_ARABIC_NUMBER
  • IntlChar::CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR
  • IntlChar::CHAR_DIRECTION_BLOCK_SEPARATOR
  • IntlChar::CHAR_DIRECTION_SEGMENT_SEPARATOR
  • IntlChar::CHAR_DIRECTION_WHITE_SPACE_NEUTRAL
  • IntlChar::CHAR_DIRECTION_OTHER_NEUTRAL
  • IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_EMBEDDING
  • IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_OVERRIDE
  • IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ARABIC
  • IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_EMBEDDING
  • IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_OVERRIDE
  • IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_FORMAT
  • IntlChar::CHAR_DIRECTION_DIR_NON_SPACING_MARK
  • IntlChar::CHAR_DIRECTION_BOUNDARY_NEUTRAL
  • IntlChar::CHAR_DIRECTION_FIRST_STRONG_ISOLATE
  • IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_ISOLATE
  • IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ISOLATE
  • IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_ISOLATE
  • IntlChar::CHAR_DIRECTION_CHAR_DIRECTION_COUNT

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::charDirection("A") === IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT);
var_dump(IntlChar::charDirection("\u{05E9}") === IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT);
var_dump(IntlChar::charDirection("+") === IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR);
var_dump(IntlChar::charDirection(".") === IntlChar::CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR);
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(true)
bool(true)
IntlChar::charDigitValue
IntlChar::charFromName
IntlChar


Find Unicode character by name and return its code point value

IntlChar::charDirection
IntlChar::charMirror
IntlChar
PHP Manual

IntlChar::charFromName

(PHP 7)

IntlChar::charFromName — Find Unicode character by name and return its code point value

Descrierea

public static int IntlChar::charFromName ( string $characterName [, int $nameChoice = IntlChar::UNICODE_CHAR_NAME ] )

Finds a Unicode character by its name and returns its code point value.

The name is matched exactly and completely. If the name does not correspond to a code point, FALSE is returned.

A Unicode 1.0 name is matched only if it differs from the modern name. Unicode names are all uppercase. Extended names are lowercase followed by an uppercase hexadecimal number, and within angle brackets.

Parametri

characterName

Full name of the Unicode character.

nameChoice

Which set of names to use for the lookup. Can be any of these constants:

  • IntlChar::UNICODE_CHAR_NAME (default)
  • IntlChar::UNICODE_10_CHAR_NAME
  • IntlChar::EXTENDED_CHAR_NAME
  • IntlChar::CHAR_NAME_ALIAS
  • IntlChar::CHAR_NAME_CHOICE_COUNT

Valorile întoarse

The Unicode value of the code point with the given name (as an integer), or FALSE if there is no such code point.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::charFromName("LATIN CAPITAL LETTER A"));
var_dump(IntlChar::charFromName("SNOWMAN"));
var_dump(IntlChar::charFromName("RECYCLING SYMBOL FOR TYPE-1 PLASTICS"));
var_dump(IntlChar::charFromName("A RANDOM STRING WHICH DOESN'T CORRESPOND TO ANY UNICODE CHARACTER"));
?>

Exemplul de mai sus va afi?a:

int(65)
int(9731)
int(9843)
bool(false)

A se vedea ?i

  • IntlChar::charName() - Retrieve the name of a Unicode character
  • IntlChar::enumCharNames() - Enumerate all assigned Unicode characters within a range

IntlChar::charDirection
IntlChar::charMirror
IntlChar


Get the "mirror-image" character for a code point

IntlChar::charFromName
IntlChar::charName
IntlChar
PHP Manual

IntlChar::charMirror

(PHP 7)

IntlChar::charMirror — Get the "mirror-image" character for a code point

Descrierea

public static mixed IntlChar::charMirror ( mixed $codepoint )

Maps the specified character to a "mirror-image" character.

For characters with the Bidi_Mirrored property, implementations sometimes need a "poor man's" mapping to another Unicode character (code point) such that the default glyph may serve as the mirror-image of the default glyph of the specified character. This is useful for text conversion to and from codepages with visual order, and for displays without glyph selection capabilities.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns another Unicode code point that may serve as a mirror-image substitute, or codepoint itself if there is no such mapping or codepoint does not have the Bidi_Mirrored property.

Tipul întors va fi integer, doar daca code point nu a fost transmis ca string UTF-8, în care caz va fi întors un string.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::charMirror("A"));
var_dump(IntlChar::charMirror("<"));
var_dump(IntlChar::charMirror("("));
?>

Exemplul de mai sus va afi?a:

string(1) "A"
string(1) ">"
string(2) ")"

A se vedea ?i

  • IntlChar::isMirrored() - Check if code point has the Bidi_Mirrored property
  • IntlChar::PROPERTY_BIDI_MIRRORED

IntlChar::charFromName
IntlChar::charName
IntlChar


Retrieve the name of a Unicode character

IntlChar::charMirror
IntlChar::charType
IntlChar
PHP Manual

IntlChar::charName

(PHP 7)

IntlChar::charName — Retrieve the name of a Unicode character

Descrierea

public static string IntlChar::charName ( mixed $codepoint [, int $nameChoice = IntlChar::UNICODE_CHAR_NAME ] )

Retrieves the name of a Unicode character.

Depending on nameChoice, the resulting character name is the "modern" name or the name that was defined in Unicode version 1.0. The name contains only "invariant" characters like A-Z, 0-9, space, and '-'. Unicode 1.0 names are only retrieved if they are different from the modern names and if ICU contains the data for them.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

nameChoice

Which set of names to use for the lookup. Can be any of these constants:

  • IntlChar::UNICODE_CHAR_NAME (default)
  • IntlChar::UNICODE_10_CHAR_NAME
  • IntlChar::EXTENDED_CHAR_NAME
  • IntlChar::CHAR_NAME_ALIAS
  • IntlChar::CHAR_NAME_CHOICE_COUNT

Valorile întoarse

The corresponding name, or an empty string if there is no name for this character.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::charName("."));
var_dump(IntlChar::charName(".", IntlChar::UNICODE_CHAR_NAME));
var_dump(IntlChar::charName("\u{2603}"));
var_dump(IntlChar::charName("\u{0000}"));
?>

Exemplul de mai sus va afi?a:

string(9) "FULL STOP"
string(9) "FULL STOP"
string(7) "SNOWMAN"
string(0) ""

A se vedea ?i

  • IntlChar::charFromName() - Find Unicode character by name and return its code point value
  • IntlChar::enumCharNames() - Enumerate all assigned Unicode characters within a range

IntlChar::charMirror
IntlChar::charType
IntlChar


Get the general category value for a code point

IntlChar::charName
IntlChar::chr
IntlChar
PHP Manual

IntlChar::charType

(PHP 7)

IntlChar::charType — Get the general category value for a code point

Descrierea

public static int IntlChar::charType ( mixed $codepoint )

Returns the general category value for the code point.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns the general category type, which may be one of the following constants:

  • IntlChar::CHAR_CATEGORY_UNASSIGNED
  • IntlChar::CHAR_CATEGORY_GENERAL_OTHER_TYPES
  • IntlChar::CHAR_CATEGORY_UPPERCASE_LETTER
  • IntlChar::CHAR_CATEGORY_LOWERCASE_LETTER
  • IntlChar::CHAR_CATEGORY_TITLECASE_LETTER
  • IntlChar::CHAR_CATEGORY_MODIFIER_LETTER
  • IntlChar::CHAR_CATEGORY_OTHER_LETTER
  • IntlChar::CHAR_CATEGORY_NON_SPACING_MARK
  • IntlChar::CHAR_CATEGORY_ENCLOSING_MARK
  • IntlChar::CHAR_CATEGORY_COMBINING_SPACING_MARK
  • IntlChar::CHAR_CATEGORY_DECIMAL_DIGIT_NUMBER
  • IntlChar::CHAR_CATEGORY_LETTER_NUMBER
  • IntlChar::CHAR_CATEGORY_OTHER_NUMBER
  • IntlChar::CHAR_CATEGORY_SPACE_SEPARATOR
  • IntlChar::CHAR_CATEGORY_LINE_SEPARATOR
  • IntlChar::CHAR_CATEGORY_PARAGRAPH_SEPARATOR
  • IntlChar::CHAR_CATEGORY_CONTROL_CHAR
  • IntlChar::CHAR_CATEGORY_FORMAT_CHAR
  • IntlChar::CHAR_CATEGORY_PRIVATE_USE_CHAR
  • IntlChar::CHAR_CATEGORY_SURROGATE
  • IntlChar::CHAR_CATEGORY_DASH_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_START_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_END_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_CONNECTOR_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_OTHER_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_MATH_SYMBOL
  • IntlChar::CHAR_CATEGORY_CURRENCY_SYMBOL
  • IntlChar::CHAR_CATEGORY_MODIFIER_SYMBOL
  • IntlChar::CHAR_CATEGORY_OTHER_SYMBOL
  • IntlChar::CHAR_CATEGORY_INITIAL_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_FINAL_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_CHAR_CATEGORY_COUNT

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::charType("A") === IntlChar::CHAR_CATEGORY_UPPERCASE_LETTER);
var_dump(IntlChar::charType(".") === IntlChar::CHAR_CATEGORY_OTHER_PUNCTUATION);
var_dump(IntlChar::charType("\t") === IntlChar::CHAR_CATEGORY_CONTROL_CHAR);
var_dump(IntlChar::charType("\u{2603}") === IntlChar::CHAR_CATEGORY_OTHER_SYMBOL);
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(true)
bool(true)
IntlChar::charName
IntlChar::chr
IntlChar


Return Unicode character by code point value

IntlChar::charType
IntlChar::digit
IntlChar
PHP Manual

IntlChar::chr

(PHP 7)

IntlChar::chr — Return Unicode character by code point value

Descrierea

public static string IntlChar::chr ( mixed $codepoint )

Returns a string containing the character specified by the Unicode code point value.

This function compliments IntlChar::ord().

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

A string containing the single character specified by the Unicode code point value.

Exemple

Example #1 Testarea diferitor code points

<?php
$values = ["A", 63, 123, 9731];
foreach ($values as $value) {
    var_dump(IntlChar::chr($value));
}
?>

Exemplul de mai sus va afi?a:

string(1) "A"
string(1) "A"
string(1) "{"
string(3) "?"

A se vedea ?i

  • IntlChar::ord() - Return Unicode code point value of character
  • chr() - Return a specific character

IntlChar::charType
IntlChar::digit
IntlChar


Get the decimal digit value of a code point for a given radix

IntlChar::chr
IntlChar::enumCharNames
IntlChar
PHP Manual

IntlChar::digit

(PHP 7)

IntlChar::digit — Get the decimal digit value of a code point for a given radix

Descrierea

public static int IntlChar::digit ( string $codepoint [, int $radix = 10 ] )

Returns the decimal digit value of the code point in the specified radix.

If the radix is not in the range 2<=radix<=36 or if the value of codepoint is not a valid digit in the specified radix, FALSE is returned. A character is a valid digit if at least one of the following is true:

  • The character has a decimal digit value. Such characters have the general category "Nd" (decimal digit numbers) and a Numeric_Type of Decimal. In this case the value is the character's decimal digit value.
  • The character is one of the uppercase Latin letters 'A' through 'Z'. In this case the value is c-'A'+10.
  • The character is one of the lowercase Latin letters 'a' through 'z'. In this case the value is ch-'a'+10.
  • Latin letters from both the ASCII range (0061..007A, 0041..005A) as well as from the Fullwidth ASCII range (FF41..FF5A, FF21..FF3A) are recognized.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

radix

The radix (defaults to 10).

Valorile întoarse

Returns the numeric value represented by the character in the specified radix, or FALSE if there is no value or if the value exceeds the radix.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::digit("0"));
var_dump(IntlChar::digit("3"));
var_dump(IntlChar::digit("A"));
var_dump(IntlChar::digit("A", 16));
?>

Exemplul de mai sus va afi?a:

int(0)
int(3)
bool(false)
int(10)

A se vedea ?i

  • IntlChar::forDigit() - Get character representation for a given digit and radix
  • IntlChar::charDigitValue() - Get the decimal digit value of a decimal digit character
  • IntlChar::isdigit() - Check if code point is a digit character
  • IntlChar::PROPERTY_NUMERIC_TYPE

IntlChar::chr
IntlChar::enumCharNames
IntlChar


Enumerate all assigned Unicode characters within a range

IntlChar::digit
IntlChar::enumCharTypes
IntlChar
PHP Manual

IntlChar::enumCharNames

(PHP 7)

IntlChar::enumCharNames — Enumerate all assigned Unicode characters within a range

Descrierea

public static void IntlChar::enumCharNames ( mixed $start , mixed $limit , callable $callback [, int $nameChoice = IntlChar::UNICODE_CHAR_NAME ] )

Enumerate all assigned Unicode characters between the start and limit code points (start inclusive, limit exclusive) and call a function for each, passing the code point value and the character name.

For Unicode 1.0 names, only those are enumerated that differ from the modern names.

Parametri

start

The first code point in the enumeration range.

limit

One more than the last code point in the enumeration range (the first one after the range).

callback

The function that is to be called for each character name. The following three arguments will be passed into it:

  • integer $codepoint - The numeric code point value
  • integer $nameChoice - The same value as the nameChoice parameter below
  • string $name - The name of the character

nameChoice

Selector for which kind of names to enumerate. Can be any of these constants:

  • IntlChar::UNICODE_CHAR_NAME (default)
  • IntlChar::UNICODE_10_CHAR_NAME
  • IntlChar::EXTENDED_CHAR_NAME
  • IntlChar::CHAR_NAME_ALIAS
  • IntlChar::CHAR_NAME_CHOICE_COUNT

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Enumerating over a sample range of code points

<?php
IntlChar::enumCharNames(0x2600, 0x2610, function($codepoint, $nameChoice, $name) {
    printf("U+%04x %s\n", $codepoint, $name);
});
?>

Exemplul de mai sus va afi?a:

U+2600 BLACK SUN WITH RAYS
U+2601 CLOUD
U+2602 UMBRELLA
U+2603 SNOWMAN
U+2604 COMET
U+2605 BLACK STAR
U+2606 WHITE STAR
U+2607 LIGHTNING
U+2608 THUNDERSTORM
U+2609 SUN
U+260a ASCENDING NODE
U+260b DESCENDING NODE
U+260c CONJUNCTION
U+260d OPPOSITION
U+260e BLACK TELEPHONE
U+260f WHITE TELEPHONE

A se vedea ?i

  • IntlChar::charName() - Retrieve the name of a Unicode character
  • IntlChar::charFromName() - Find Unicode character by name and return its code point value

IntlChar::digit
IntlChar::enumCharTypes
IntlChar


Enumerate all code points with their Unicode general categories

IntlChar::enumCharNames
IntlChar::foldCase
IntlChar
PHP Manual

IntlChar::enumCharTypes

(PHP 7)

IntlChar::enumCharTypes — Enumerate all code points with their Unicode general categories

Descrierea

public static void IntlChar::enumCharTypes ( callable $callback )

Enumerates efficiently all code points with their Unicode general categories. This is useful for building data structures, for enumerating all assigned code points, etc.

For each contiguous range of code points with a given general category ("character type"), the callback function is called. Adjacent ranges have different types. The Unicode Standard guarantees that the numeric value of the type is 0..31.

Parametri

callback

The function that is to be called for each contiguous range of code points with the same general category. The following three arguments will be passed into it:

  • integer $start - The starting code point of the range
  • integer $end - The ending code point of the range
  • integer $name - The category type (one of the IntlChar::CHAR_CATEGORY_* constants)

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Enumerating over a sample range of code points

<?php
IntlChar::enumCharTypes(function($start, $end, $type) {
    printf("U+%04x through U+%04x are in category %d\n", $start, $end, $type);
});
?>

Exemplul de mai sus va afi?a:

U+0000 through U+0020 are in category 15
U+0020 through U+0021 are in category 12
U+0021 through U+0024 are in category 23
U+0024 through U+0025 are in category 25
U+0025 through U+0028 are in category 23
U+0028 through U+0029 are in category 20
U+0029 through U+002a are in category 21
U+002a through U+002b are in category 23
U+002b through U+002c are in category 24
U+002c through U+002d are in category 23
U+002d through U+002e are in category 19
U+002e through U+0030 are in category 23
U+0030 through U+003a are in category 9
...
IntlChar::enumCharNames
IntlChar::foldCase
IntlChar


Perform case folding on a code point

IntlChar::enumCharTypes
IntlChar::forDigit
IntlChar
PHP Manual

IntlChar::foldCase

(PHP 7)

IntlChar::foldCase — Perform case folding on a code point

Descrierea

public static mixed IntlChar::foldCase ( mixed $codepoint [, int $options = IntlChar::FOLD_CASE_DEFAULT ] )

The given character is mapped to its case folding equivalent; if the character has no case folding equivalent, the character itself is returned.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

options

Either IntlChar::FOLD_CASE_DEFAULT (default) or IntlChar::FOLD_CASE_EXCLUDE_SPECIAL_I.

Valorile întoarse

Returns the Simple_Case_Folding of the code point, if any; otherwise the code point itself.

IntlChar::enumCharTypes
IntlChar::forDigit
IntlChar


Get character representation for a given digit and radix

IntlChar::foldCase
IntlChar::getBidiPairedBracket
IntlChar
PHP Manual

IntlChar::forDigit

(PHP 7)

IntlChar::forDigit — Get character representation for a given digit and radix

Descrierea

public static int IntlChar::forDigit ( int $digit [, int $radix = 10 ] )

Determines the character representation for a specific digit in the specified radix.

If the value of radix is not a valid radix, or the value of digit is not a valid digit in the specified radix, the null character (U+0000) is returned.

The radix argument is valid if it is greater than or equal to 2 and less than or equal to 36. The digit argument is valid if 0 <= digit < radix.

If the digit is less than 10, then '0' + digit is returned. Otherwise, the value 'a' + digit - 10 is returned.

Parametri

digit

The number to convert to a character.

radix

The radix (defaults to 10).

Valorile întoarse

The character representation (as a string) of the specified digit in the specified radix.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::forDigit(0));
var_dump(IntlChar::forDigit(3));
var_dump(IntlChar::forDigit(3, 10));
var_dump(IntlChar::forDigit(10));
var_dump(IntlChar::forDigit(10, 16));
?>

Exemplul de mai sus va afi?a:

int(48)
int(51)
int(51)
int(0)
int(97)

A se vedea ?i

  • IntlChar::digit() - Get the decimal digit value of a code point for a given radix
  • IntlChar::charDigitValue() - Get the decimal digit value of a decimal digit character
  • IntlChar::isdigit() - Check if code point is a digit character
  • IntlChar::PROPERTY_NUMERIC_TYPE

IntlChar::foldCase
IntlChar::getBidiPairedBracket
IntlChar


Get the paired bracket character for a code point

IntlChar::forDigit
IntlChar::getBlockCode
IntlChar
PHP Manual

IntlChar::getBidiPairedBracket

(PHP 7)

IntlChar::getBidiPairedBracket — Get the paired bracket character for a code point

Descrierea

public static mixed IntlChar::getBidiPairedBracket ( mixed $codepoint )

Maps the specified character to its paired bracket character.

For Bidi_Paired_Bracket_Type!=None, this is the same as IntlChar::charMirror(). Otherwise codepoint itself is returned.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns the paired bracket code point, or codepoint itself if there is no such mapping.

Tipul întors va fi integer, doar daca code point nu a fost transmis ca string UTF-8, în care caz va fi întors un string.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::getBidiPairedBracket(91));
var_dump(IntlChar::getBidiPairedBracket('['));
?>

Exemplul de mai sus va afi?a:

int(93)
string(1) "]"

A se vedea ?i

  • IntlChar::charMirror() - Get the "mirror-image" character for a code point
  • IntlChar::PROPERTY_BIDI_PAIRED_BRACKET
  • IntlChar::PROPERTY_BIDI_PAIRED_BRACKET_TYPE

IntlChar::forDigit
IntlChar::getBlockCode
IntlChar


Get the Unicode allocation block containing a code point

IntlChar::getBidiPairedBracket
IntlChar::getCombiningClass
IntlChar
PHP Manual

IntlChar::getBlockCode

(PHP 7)

IntlChar::getBlockCode — Get the Unicode allocation block containing a code point

Descrierea

public static int IntlChar::getBlockCode ( mixed $codepoint )

Returns the Unicode allocation block that contains the character.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns the block value for codepoint. See the IntlChar::BLOCK_CODE_* constants for possible return values.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::getBlockCode("A") === IntlChar::BLOCK_CODE_BASIC_LATIN);
var_dump(IntlChar::getBlockCode("F") === IntlChar::BLOCK_CODE_GREEK);
var_dump(IntlChar::getBlockCode("\u{2603}") === IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS);
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(true)
IntlChar::getBidiPairedBracket
IntlChar::getCombiningClass
IntlChar


Get the combining class of a code point

IntlChar::getBlockCode
IntlChar::getFC_NFKC_Closure
IntlChar
PHP Manual

IntlChar::getCombiningClass

(PHP 7)

IntlChar::getCombiningClass — Get the combining class of a code point

Descrierea

public static int IntlChar::getCombiningClass ( mixed $codepoint )

Returns the combining class of the code point.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns the combining class of the character.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::getCombiningClass("A"));
var_dump(IntlChar::getCombiningClass("\u{0334}"));
var_dump(IntlChar::getCombiningClass("\u{0358}"));
?>

Exemplul de mai sus va afi?a:

int(0)
int(1)
int(232)
IntlChar::getBlockCode
IntlChar::getFC_NFKC_Closure
IntlChar


Get the FC_NFKC_Closure property for a code point

IntlChar::getCombiningClass
IntlChar::getIntPropertyMaxValue
IntlChar
PHP Manual

IntlChar::getFC_NFKC_Closure

(PHP 7)

IntlChar::getFC_NFKC_Closure — Get the FC_NFKC_Closure property for a code point

Descrierea

public static string IntlChar::getFC_NFKC_Closure ( mixed $codepoint )

Gets the FC_NFKC_Closure property string for a character.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns the FC_NFKC_Closure property string for the codepoint, or an empty string if there is none.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::getFC_NFKC_Closure("\u{2121}"));
var_dump(IntlChar::getFC_NFKC_Closure("\u{1D2D}"));
?>

Exemplul de mai sus va afi?a:

string(3) "tel"
string(2) "æ"
IntlChar::getCombiningClass
IntlChar::getIntPropertyMaxValue
IntlChar


Get the max value for a Unicode property

IntlChar::getFC_NFKC_Closure
IntlChar::getIntPropertyMinValue
IntlChar
PHP Manual

IntlChar::getIntPropertyMaxValue

(PHP 7)

IntlChar::getIntPropertyMaxValue — Get the max value for a Unicode property

Descrierea

public static int IntlChar::getIntPropertyMaxValue ( int $property )

Gets the maximum value for an enumerated/integer/binary Unicode property.

Parametri

property

Proprietatea Unicode spre a fi cautata (a se vedea constantele IntlChar::PROPERTY_*).

Valorile întoarse

The maximum value returned by IntlChar::getIntPropertyValue() for a Unicode property. <=0 if the property selector is out of range.

Exemple

Example #1 Testarea diferitor proprieta?i

<?php
var_dump(IntlChar::getIntPropertyMaxValue(IntlChar::PROPERTY_BIDI_CLASS));
var_dump(IntlChar::getIntPropertyMaxValue(IntlChar::PROPERTY_SCRIPT));
var_dump(IntlChar::getIntPropertyMaxValue(IntlChar::PROPERTY_IDEOGRAPHIC));
var_dump(IntlChar::getIntPropertyMaxValue(999999999)); // Some made-up value
?>

Exemplul de mai sus va afi?a:

int(22)
int(166)
int(1)
int(-1)

A se vedea ?i

  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::getIntPropertyMinValue() - Get the min value for a Unicode property
  • IntlChar::getIntPropertyValue() - Get the value for a Unicode property for a code point
  • IntlChar::getUnicodeVersion() - Get the Unicode version

IntlChar::getFC_NFKC_Closure
IntlChar::getIntPropertyMinValue
IntlChar


Get the min value for a Unicode property

IntlChar::getIntPropertyMaxValue
IntlChar::getIntPropertyValue
IntlChar
PHP Manual

IntlChar::getIntPropertyMinValue

(PHP 7)

IntlChar::getIntPropertyMinValue — Get the min value for a Unicode property

Descrierea

public static int IntlChar::getIntPropertyMinValue ( int $property )

Gets the minimum value for an enumerated/integer/binary Unicode property.

Parametri

property

Proprietatea Unicode spre a fi cautata (a se vedea constantele IntlChar::PROPERTY_*).

Valorile întoarse

The minimum value returned by IntlChar::getIntPropertyValue() for a Unicode property. 0 if the property selector is out of range.

Exemple

Example #1 Testarea diferitor proprieta?i

<?php
var_dump(IntlChar::getIntPropertyMinValue(IntlChar::PROPERTY_BIDI_CLASS));
var_dump(IntlChar::getIntPropertyMinValue(IntlChar::PROPERTY_SCRIPT));
var_dump(IntlChar::getIntPropertyMinValue(IntlChar::PROPERTY_IDEOGRAPHIC));
var_dump(IntlChar::getIntPropertyMinValue(999999999)); // Some made-up value
?>

Exemplul de mai sus va afi?a:

int(0)
int(0)
int(0)
int(0)

A se vedea ?i

  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::getIntPropertyMaxValue() - Get the max value for a Unicode property
  • IntlChar::getIntPropertyValue() - Get the value for a Unicode property for a code point
  • IntlChar::getUnicodeVersion() - Get the Unicode version

IntlChar::getIntPropertyMaxValue
IntlChar::getIntPropertyValue
IntlChar


Get the value for a Unicode property for a code point

IntlChar::getIntPropertyMinValue
IntlChar::getNumericValue
IntlChar
PHP Manual

IntlChar::getIntPropertyValue

(PHP 7)

IntlChar::getIntPropertyValue — Get the value for a Unicode property for a code point

Descrierea

public static int IntlChar::getIntPropertyValue ( mixed $codepoint , int $property )

Gets the property value for an enumerated or integer Unicode property for a code point. Also returns binary and mask property values.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

property

Proprietatea Unicode spre a fi cautata (a se vedea constantele IntlChar::PROPERTY_*).

Valorile întoarse

Returns the numeric value that is directly the property value or, for enumerated properties, corresponds to the numeric value of the enumerated constant of the respective property value enumeration type.

Returns 0 or 1 (for FALSE/TRUE) for binary Unicode properties.

Returns a bit-mask for mask properties.

Returns 0 if property is out of bounds or if the Unicode version does not have data for the property at all, or not for this code point.

Exemple

Example #1 Testarea diferitor proprieta?i

<?php
var_dump(IntlChar::getIntPropertyValue("A", IntlChar::PROPERTY_ALPHABETIC) === 1);
var_dump(IntlChar::getIntPropertyValue("[", IntlChar::PROPERTY_BIDI_MIRRORED) === 1);
var_dump(IntlChar::getIntPropertyValue("F", IntlChar::PROPERTY_BLOCK) === IntlChar::BLOCK_CODE_GREEK);
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(true)

A se vedea ?i

  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::getIntPropertyMinValue() - Get the min value for a Unicode property
  • IntlChar::getIntPropertyMaxValue() - Get the max value for a Unicode property
  • IntlChar::getUnicodeVersion() - Get the Unicode version

IntlChar::getIntPropertyMinValue
IntlChar::getNumericValue
IntlChar


Get the numeric value for a Unicode code point

IntlChar::getIntPropertyValue
IntlChar::getPropertyEnum
IntlChar
PHP Manual

IntlChar::getNumericValue

(PHP 7)

IntlChar::getNumericValue — Get the numeric value for a Unicode code point

Descrierea

public static float IntlChar::getNumericValue ( mixed $codepoint )

Gets the numeric value for a Unicode code point as defined in the Unicode Character Database.

For characters without any numeric values in the Unicode Character Database, this function will return IntlChar::NO_NUMERIC_VALUE.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Numeric value of codepoint, or IntlChar::NO_NUMERIC_VALUE if none is defined. This constant was added in PHP 7.0.6, prior to this version the literal value (float)-123456789 may be used instead.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::getNumericValue("4"));
var_dump(IntlChar::getNumericValue("x"));
var_dump(IntlChar::getNumericValue("\u{216C}"));
?>

Exemplul de mai sus va afi?a:

float(4)
float(-123456789)
float(50)
IntlChar::getIntPropertyValue
IntlChar::getPropertyEnum
IntlChar


Get the property constant value for a given property name

IntlChar::getNumericValue
IntlChar::getPropertyName
IntlChar
PHP Manual

IntlChar::getPropertyEnum

(PHP 7)

IntlChar::getPropertyEnum — Get the property constant value for a given property name

Descrierea

public static int IntlChar::getPropertyEnum ( string $alias )

Returns the property constant value for a given property name, as specified in the Unicode database file PropertyAliases.txt. Short, long, and any other variants are recognized.

In addition, this function maps the synthetic names "gcm" / "General_Category_Mask" to the property IntlChar::PROPERTY_GENERAL_CATEGORY_MASK. These names are not in PropertyAliases.txt.

This function compliments IntlChar::getPropertyName().

Parametri

alias

The property name to be matched. The name is compared using "loose matching" as described in PropertyAliases.txt.

Valorile întoarse

Returns an IntlChar::PROPERTY_ constant value, or IntlChar::PROPERTY_INVALID_CODE if the given name does not match any property.

Exemple

Example #1 Testarea diferitor proprieta?i

<?php
var_dump(IntlChar::getPropertyEnum('Bidi_Class') === IntlChar::PROPERTY_BIDI_CLASS);
var_dump(IntlChar::getPropertyEnum('script') === IntlChar::PROPERTY_SCRIPT);
var_dump(IntlChar::getPropertyEnum('IDEOGRAPHIC') === IntlChar::PROPERTY_IDEOGRAPHIC);
var_dump(IntlChar::getPropertyEnum('Some made-up string') === IntlChar::PROPERTY_INVALID_CODE);
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(true)
bool(true)

A se vedea ?i

  • IntlChar::getPropertyName() - Get the Unicode name for a property

IntlChar::getNumericValue
IntlChar::getPropertyName
IntlChar


Get the Unicode name for a property

IntlChar::getPropertyEnum
IntlChar::getPropertyValueEnum
IntlChar
PHP Manual

IntlChar::getPropertyName

(PHP 7)

IntlChar::getPropertyName — Get the Unicode name for a property

Descrierea

public static string IntlChar::getPropertyName ( int $property [, int $nameChoice = IntlChar::LONG_PROPERTY_NAME ] )

Returns the Unicode name for a given property, as given in the Unicode database file PropertyAliases.txt.

In addition, this function maps the property IntlChar::PROPERTY_GENERAL_CATEGORY_MASK to the synthetic names "gcm" / "General_Category_Mask". These names are not in PropertyAliases.txt.

This function compliments IntlChar::getPropertyEnum().

Parametri

property

Proprietatea Unicode spre a fi cautata (a se vedea constantele IntlChar::PROPERTY_*).

IntlChar::PROPERTY_INVALID_CODE should not be used. Also, if property is out of range, FALSE is returned.

nameChoice

Selector for which name to get. If out of range, FALSE is returned.

All properties have a long name. Most have a short name, but some do not. Unicode allows for additional names; if present these will be returned by adding 1, 2, etc. to IntlChar::LONG_PROPERTY_NAME.

Valorile întoarse

Returns the name, or FALSE if either the property or the nameChoice is out of range.

If a given nameChoice returns FALSE, then all larger values of nameChoice will return FALSE, with one exception: if FALSE is returned for IntlChar::SHORT_PROPERTY_NAME, then IntlChar::LONG_PROPERTY_NAME (and higher) may still return a non-FALSE value.

Exemple

Example #1 Testarea diferitor proprieta?i

<?php
var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS));
var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS, IntlChar::SHORT_PROPERTY_NAME));
var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS, IntlChar::LONG_PROPERTY_NAME));
var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS, IntlChar::LONG_PROPERTY_NAME + 1));
?>

Exemplul de mai sus va afi?a:

string(10) "Bidi_Class"
string(2) "bc"
string(10) "Bidi_Class"
bool(false)

A se vedea ?i

  • IntlChar::getPropertyEnum() - Get the property constant value for a given property name

IntlChar::getPropertyEnum
IntlChar::getPropertyValueEnum
IntlChar


Get the property value for a given value name

IntlChar::getPropertyName
IntlChar::getPropertyValueName
IntlChar
PHP Manual

IntlChar::getPropertyValueEnum

(PHP 7)

IntlChar::getPropertyValueEnum — Get the property value for a given value name

Descrierea

public static int IntlChar::getPropertyValueEnum ( int $property , string $name )

Returns the property value integer for a given value name, as specified in the Unicode database file PropertyValueAliases.txt. Short, long, and any other variants are recognized.

Nota:

Some of the names in PropertyValueAliases.txt will only be recognized with IntlChar::PROPERTY_GENERAL_CATEGORY_MASK, not IntlChar::PROPERTY_GENERAL_CATEGORY. These include:

  • "C" / "Other"
  • "L" / "Letter"
  • "LC" / "Cased_Letter"
  • "M" / "Mark"
  • "N" / "Number"
  • "P" / "Punctuation"
  • "S" / "Symbol"
  • "Z" / "Separator"

Parametri

property

Proprietatea Unicode spre a fi cautata (a se vedea constantele IntlChar::PROPERTY_*).

If out of range, or this method doesn't work with the given value, IntlChar::PROPERTY_INVALID_CODE is returned.

name

The value name to be matched. The name is compared using "loose matching" as described in PropertyValueAliases.txt.

Valorile întoarse

Returns the corresponding value integer, or IntlChar::PROPERTY_INVALID_CODE if the given name does not match any value of the given property, or if the property is invalid.

Exemple

Example #1 Testarea diferitor proprieta?i

<?php
var_dump(IntlChar::getPropertyValueEnum(IntlChar::PROPERTY_BLOCK, 'greek') === IntlChar::BLOCK_CODE_GREEK);
var_dump(IntlChar::getPropertyValueEnum(IntlChar::PROPERTY_BIDI_CLASS, 'RIGHT_TO_LEFT') === IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT);
var_dump(IntlChar::getPropertyValueEnum(IntlChar::PROPERTY_BIDI_CLASS, 'some made-up string') === IntlChar::PROPERTY_INVALID_CODE);
var_dump(IntlChar::getPropertyValueEnum(123456789, 'RIGHT_TO_LEFT') === IntlChar::PROPERTY_INVALID_CODE);
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(true)
bool(true)
IntlChar::getPropertyName
IntlChar::getPropertyValueName
IntlChar


Get the Unicode name for a property value

IntlChar::getPropertyValueEnum
IntlChar::getUnicodeVersion
IntlChar
PHP Manual

IntlChar::getPropertyValueName

(PHP 7)

IntlChar::getPropertyValueName — Get the Unicode name for a property value

Descrierea

public static string IntlChar::getPropertyValueName ( int $property , int $value [, int $nameChoice = IntlChar::LONG_PROPERTY_NAME ] )

Returns the Unicode name for a given property value, as given in the Unicode database file PropertyValueAliases.txt.

Nota:

Some of the names in PropertyValueAliases.txt can only be retrieved using IntlChar::PROPERTY_GENERAL_CATEGORY_MASK, not IntlChar::PROPERTY_GENERAL_CATEGORY. These include:

  • "C" / "Other"
  • "L" / "Letter"
  • "LC" / "Cased_Letter"
  • "M" / "Mark"
  • "N" / "Number"
  • "P" / "Punctuation"
  • "S" / "Symbol"
  • "Z" / "Separator"

Parametri

property

Proprietatea Unicode spre a fi cautata (a se vedea constantele IntlChar::PROPERTY_*).

If out of range, or this method doesn't work with the given value, FALSE is returned.

value

Selector for a value for the given property. If out of range, FALSE is returned.

In general, valid values range from 0 up to some maximum. There are a couple exceptions:

  • IntlChar::PROPERTY_BLOCK values begin at the non-zero value IntlChar::BLOCK_CODE_BASIC_LATIN
  • IntlChar::PROPERTY_CANONICAL_COMBINING_CLASS values are not contiguous and range from 0..240.

nameChoice

Selector for which name to get. If out of range, FALSE is returned.

All values have a long name. Most have a short name, but some do not. Unicode allows for additional names; if present these will be returned by adding 1, 2, etc. to IntlChar::LONG_PROPERTY_NAME.

Valorile întoarse

Returns the name, or FALSE if either the property or the nameChoice is out of range.

If a given nameChoice returns FALSE, then all larger values of nameChoice will return FALSE, with one exception: if FALSE is returned for IntlChar::SHORT_PROPERTY_NAME, then IntlChar::LONG_PROPERTY_NAME (and higher) may still return a non-FALSE value.

Exemple

Example #1 Testarea diferitor proprieta?i

<?php
var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK));
var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK, IntlChar::SHORT_PROPERTY_NAME));
var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK, IntlChar::LONG_PROPERTY_NAME));
var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK, IntlChar::LONG_PROPERTY_NAME + 1));
?>

Exemplul de mai sus va afi?a:

string(16) "Greek_And_Coptic"
string(5) "Greek"
string(16) "Greek_And_Coptic"
bool(false)
IntlChar::getPropertyValueEnum
IntlChar::getUnicodeVersion
IntlChar


Get the Unicode version

IntlChar::getPropertyValueName
IntlChar::hasBinaryProperty
IntlChar
PHP Manual

IntlChar::getUnicodeVersion

(PHP 7)

IntlChar::getUnicodeVersion — Get the Unicode version

Descrierea

public static array IntlChar::getUnicodeVersion ( void )

Gets the Unicode version information.

The version array is filled in with the version information for the Unicode standard that is currently used by ICU. For example, Unicode version 3.1.1 is represented as an array with the values [3, 1, 1, 0].

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array containing the Unicode version number.

Exemple

Example #1 Testarea diferitor proprieta?i

<?php
var_dump(IntlChar::getUnicodeVersion());
?>

Exemplul de mai sus va afi?a:

array(4) {
  [0]=>
  int(7)
  [1]=>
  int(0)
  [2]=>
  int(0)
  [3]=>
  int(0)
}

A se vedea ?i

  • IntlChar::charAge() - Get the "age" of the code point

IntlChar::getPropertyValueName
IntlChar::hasBinaryProperty
IntlChar


Check a binary Unicode property for a code point

IntlChar::getUnicodeVersion
IntlChar::isalnum
IntlChar
PHP Manual

IntlChar::hasBinaryProperty

(PHP 7)

IntlChar::hasBinaryProperty — Check a binary Unicode property for a code point

Descrierea

public static bool IntlChar::hasBinaryProperty ( mixed $codepoint , int $property )

Checks a binary Unicode property for a code point.

Unicode, especially in version 3.2, defines many more properties than the original set in UnicodeData.txt.

The properties APIs are intended to reflect Unicode properties as defined in the Unicode Character Database (UCD) and Unicode Technical Reports (UTR). For details about the properties see » http://www.unicode.org/ucd/. For names of Unicode properties see the UCD file PropertyAliases.txt.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

property

Proprietatea Unicode spre a fi cautata (a se vedea constantele IntlChar::PROPERTY_*).

Valorile întoarse

Returns TRUE or FALSE according to the binary Unicode property value for codepoint. Also FALSE if property is out of bounds or if the Unicode version does not have data for the property at all, or not for this code point.

Exemple

Example #1 Testarea diferitor proprieta?i

<?php
var_dump(IntlChar::hasBinaryProperty("A", IntlChar::PROPERTY_ALPHABETIC));
var_dump(IntlChar::hasBinaryProperty("A", IntlChar::PROPERTY_CASE_SENSITIVE));
var_dump(IntlChar::hasBinaryProperty("A", IntlChar::PROPERTY_BIDI_MIRRORED));
var_dump(IntlChar::hasBinaryProperty("[", IntlChar::PROPERTY_ALPHABETIC));
var_dump(IntlChar::hasBinaryProperty("[", IntlChar::PROPERTY_CASE_SENSITIVE));
var_dump(IntlChar::hasBinaryProperty("[", IntlChar::PROPERTY_BIDI_MIRRORED));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(false)
bool(false)
bool(false)
bool(true)

A se vedea ?i

  • IntlChar::getIntPropertyValue() - Get the value for a Unicode property for a code point
  • IntlChar::getUnicodeVersion() - Get the Unicode version

IntlChar::getUnicodeVersion
IntlChar::isalnum
IntlChar


Check if code point is an alphanumeric character

IntlChar::hasBinaryProperty
IntlChar::isalpha
IntlChar
PHP Manual

IntlChar::isalnum

(PHP 7)

IntlChar::isalnum — Check if code point is an alphanumeric character

Descrierea

public static bool IntlChar::isalnum ( mixed $codepoint )

Determines whether the specified code point is an alphanumeric character (letter or digit). TRUE for characters with general categories "L" (letters) and "Nd" (decimal digit numbers).

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is an alphanumeric character, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isalnum("A"));
var_dump(IntlChar::isalnum("1"));
var_dump(IntlChar::isalnum("\u{2603}"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(false)

A se vedea ?i

  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::isdigit() - Check if code point is a digit character

IntlChar::hasBinaryProperty
IntlChar::isalpha
IntlChar


Check if code point is a letter character

IntlChar::isalnum
IntlChar::isbase
IntlChar
PHP Manual

IntlChar::isalpha

(PHP 7)

IntlChar::isalpha — Check if code point is a letter character

Descrierea

public static bool IntlChar::isalpha ( mixed $codepoint )

Determines whether the specified code point is a letter character. TRUE for general categories "L" (letters).

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is a letter character, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isalpha("A"));
var_dump(IntlChar::isalpha("1"));
var_dump(IntlChar::isalpha("\u{2603}"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)
bool(false)

A se vedea ?i

  • IntlChar::isalnum() - Check if code point is an alphanumeric character
  • IntlChar::isdigit() - Check if code point is a digit character

IntlChar::isalnum
IntlChar::isbase
IntlChar


Check if code point is a base character

IntlChar::isalpha
IntlChar::isblank
IntlChar
PHP Manual

IntlChar::isbase

(PHP 7)

IntlChar::isbase — Check if code point is a base character

Descrierea

public static bool IntlChar::isbase ( mixed $codepoint )

Determines whether the specified code point is a base character. TRUE for general categories "L" (letters), "N" (numbers), "Mc" (spacing combining marks), and "Me" (enclosing marks).

Nota:

This is different from the Unicode definition in chapter 3.5, conformance clause D13, which defines base characters to be all characters (not Cn) that do not graphically combine with preceding characters (M) and that are neither control (Cc) or format (Cf) characters.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is a base character, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isbase("A"));
var_dump(IntlChar::isbase("1"));
var_dump(IntlChar::isbase("\u{2603}"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(false)

A se vedea ?i

  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::isdigit() - Check if code point is a digit character

IntlChar::isalpha
IntlChar::isblank
IntlChar


Check if code point is a "blank" or "horizontal space" character

IntlChar::isbase
IntlChar::iscntrl
IntlChar
PHP Manual

IntlChar::isblank

(PHP 7)

IntlChar::isblank — Check if code point is a "blank" or "horizontal space" character

Descrierea

public static bool IntlChar::isblank ( mixed $codepoint )

Determines whether the specified code point is a "blank" or "horizontal space", a character that visibly separates words on a line.

The following are equivalent definitions:

  • TRUE for Unicode White_Space characters except for "vertical space controls" where "vertical space controls" are the following characters: U+000A (LF) U+000B (VT) U+000C (FF) U+000D (CR) U+0085 (NEL) U+2028 (LS) U+2029 (PS)
  • TRUE for U+0009 (TAB) and characters with general category "Zs" (space separators) except Zero Width Space (ZWSP, U+200B).

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is either a "blank" or "horizontal space" character, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isblank("A"));
var_dump(IntlChar::isblank(" "));
var_dump(IntlChar::isblank("\t"));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
bool(true)

A se vedea ?i

  • IntlChar::isspace() - Check if code point is a space character
  • IntlChar::isJavaSpaceChar() - Check if code point is a space character according to Java
  • IntlChar::isUWhiteSpace() - Check if code point has the White_Space Unicode property
  • IntlChar::isWhitespace() - Check if code point is a whitespace character according to ICU

IntlChar::isbase
IntlChar::iscntrl
IntlChar


Check if code point is a control character

IntlChar::isblank
IntlChar::isdefined
IntlChar
PHP Manual

IntlChar::iscntrl

(PHP 7)

IntlChar::iscntrl — Check if code point is a control character

Descrierea

public static bool IntlChar::iscntrl ( mixed $codepoint )

Determines whether the specified code point is a control character.

A control character is one of the following:

  • ISO 8-bit control character (U+0000..U+001f and U+007f..U+009f)
  • IntlChar::CHAR_CATEGORY_CONTROL_CHAR (Cc)
  • IntlChar::CHAR_CATEGORY_FORMAT_CHAR (Cf)
  • IntlChar::CHAR_CATEGORY_LINE_SEPARATOR (Zl)
  • IntlChar::CHAR_CATEGORY_PARAGRAPH_SEPARATOR (Zp)

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is a control character, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::iscntrl("A"));
var_dump(IntlChar::iscntrl(" "));
var_dump(IntlChar::iscntrl("\n"));
var_dump(IntlChar::iscntrl("\u{200e}"));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(false)
bool(true)
bool(true)

A se vedea ?i

  • IntlChar::isprint() - Check if code point is a printable character
  • IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT

IntlChar::isblank
IntlChar::isdefined
IntlChar


Check whether the code point is defined

IntlChar::iscntrl
IntlChar::isdigit
IntlChar
PHP Manual

IntlChar::isdefined

(PHP 7)

IntlChar::isdefined — Check whether the code point is defined

Descrierea

public static bool IntlChar::isdefined ( mixed $codepoint )

Determines whether the specified code point is "defined", which usually means that it is assigned a character.

TRUE for general categories other than "Cn" (other, not assigned).

Nota:

Note that non-character code points (e.g., U+FDD0) are not "defined" (they are Cn), but surrogate code points are "defined" (Cs).

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is a defined character, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isdefined("A"));
var_dump(IntlChar::isdefined(" "));
var_dump(IntlChar::isdefined("\u{FDD0}"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(false)

A se vedea ?i

  • IntlChar::isdigit() - Check if code point is a digit character
  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::isalnum() - Check if code point is an alphanumeric character
  • IntlChar::isupper() - Check if code point has the general category "Lu" (uppercase letter)
  • IntlChar::islower() - Check if code point is a lowercase letter
  • IntlChar::istitle() - Check if code point is a titlecase letter

IntlChar::iscntrl
IntlChar::isdigit
IntlChar


Check if code point is a digit character

IntlChar::isdefined
IntlChar::isgraph
IntlChar
PHP Manual

IntlChar::isdigit

(PHP 7)

IntlChar::isdigit — Check if code point is a digit character

Descrierea

public static bool IntlChar::isdigit ( mixed $codepoint )

Determines whether the specified code point is a digit character.

TRUE for characters with general category "Nd" (decimal digit numbers). Beginning with Unicode 4, this is the same as testing for the Numeric_Type of Decimal.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is a digit character, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isdigit("A"));
var_dump(IntlChar::isdigit("1"));
var_dump(IntlChar::isdigit("\t"));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
bool(false)

A se vedea ?i

  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::isalnum() - Check if code point is an alphanumeric character
  • IntlChar::isxdigit() - Check if code point is a hexadecimal digit

IntlChar::isdefined
IntlChar::isgraph
IntlChar


Check if code point is a graphic character

IntlChar::isdigit
IntlChar::isIDIgnorable
IntlChar
PHP Manual

IntlChar::isgraph

(PHP 7)

IntlChar::isgraph — Check if code point is a graphic character

Descrierea

public static bool IntlChar::isgraph ( mixed $codepoint )

Determines whether the specified code point is a "graphic" character (printable, excluding spaces).

TRUE for all characters except those with general categories "Cc" (control codes), "Cf" (format controls), "Cs" (surrogates), "Cn" (unassigned), and "Z" (separators).

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is a "graphic" character, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isgraph("A"));
var_dump(IntlChar::isgraph("1"));
var_dump(IntlChar::isgraph("\u{2603}"));
var_dump(IntlChar::isgraph("\n"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(true)
bool(false)
IntlChar::isdigit
IntlChar::isIDIgnorable
IntlChar


Check if code point is an ignorable character

IntlChar::isgraph
IntlChar::isIDPart
IntlChar
PHP Manual

IntlChar::isIDIgnorable

(PHP 7)

IntlChar::isIDIgnorable — Check if code point is an ignorable character

Descrierea

public static bool IntlChar::isIDIgnorable ( mixed $codepoint )

Determines if the specified character should be regarded as an ignorable character in an identifier.

TRUE for characters with general category "Cf" (format controls) as well as non-whitespace ISO controls (U+0000..U+0008, U+000E..U+001B, U+007F..U+009F).

Nota:

Note that Unicode just recommends to ignore Cf (format controls).

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is ignorable in identifiers, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isIDIgnorable("A"));
var_dump(IntlChar::isIDIgnorable(" "));
var_dump(IntlChar::isIDIgnorable("\u{007F}"));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(false)
bool(true)

A se vedea ?i

  • IntlChar::isIDStart() - Check if code point is permissible as the first character in an identifier
  • IntlChar::isIDPart() - Check if code point is permissible in an identifier
  • IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT

IntlChar::isgraph
IntlChar::isIDPart
IntlChar


Check if code point is permissible in an identifier

IntlChar::isIDIgnorable
IntlChar::isIDStart
IntlChar
PHP Manual

IntlChar::isIDPart

(PHP 7)

IntlChar::isIDPart — Check if code point is permissible in an identifier

Descrierea

public static bool IntlChar::isIDPart ( mixed $codepoint )

Determines if the specified character is permissible in an identifier.

TRUE for characters with general categories "L" (letters), "Nl" (letter numbers), "Nd" (decimal digits), "Mc" and "Mn" (combining marks), "Pc" (connecting punctuation), and u_isIDIgnorable(c).

Nota:

This is almost the same as Unicode's ID_Continue (IntlChar::PROPERTY_ID_CONTINUE) except that Unicode recommends to ignore Cf which is less than IntlChar::isIDIgnorable().

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is the code point may occur in an identifier, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isIDPart("A"));
var_dump(IntlChar::isIDPart("$"));
var_dump(IntlChar::isIDPart("\n"));
var_dump(IntlChar::isIDPart("\u{2603}"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)
bool(false)
bool(false)

A se vedea ?i

  • IntlChar::isIDIgnorable() - Check if code point is an ignorable character
  • IntlChar::isIDStart() - Check if code point is permissible as the first character in an identifier
  • IntlChar::PROPERTY_ID_CONTINUE

IntlChar::isIDIgnorable
IntlChar::isIDStart
IntlChar


Check if code point is permissible as the first character in an identifier

IntlChar::isIDPart
IntlChar::isISOControl
IntlChar
PHP Manual

IntlChar::isIDStart

(PHP 7)

IntlChar::isIDStart — Check if code point is permissible as the first character in an identifier

Descrierea

public static bool IntlChar::isIDStart ( mixed $codepoint )

Determines if the specified character is permissible as the first character in an identifier according to Unicode (The Unicode Standard, Version 3.0, chapter 5.16 Identifiers).

TRUE for characters with general categories "L" (letters) and "Nl" (letter numbers).

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint may start an identifier, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isIDStart("A"));
var_dump(IntlChar::isIDStart("$"));
var_dump(IntlChar::isIDStart("\n"));
var_dump(IntlChar::isIDStart("\u{2603}"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)
bool(false)
bool(false)

A se vedea ?i

  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::isIDPart() - Check if code point is permissible in an identifier
  • IntlChar::PROPERTY_ID_START

IntlChar::isIDPart
IntlChar::isISOControl
IntlChar


Check if code point is an ISO control code

IntlChar::isIDStart
IntlChar::isJavaIDPart
IntlChar
PHP Manual

IntlChar::isISOControl

(PHP 7)

IntlChar::isISOControl — Check if code point is an ISO control code

Descrierea

public static bool IntlChar::isISOControl ( mixed $codepoint )

Determines whether the specified code point is an ISO control code.

TRUE for U+0000..U+001f and U+007f..U+009f (general category "Cc").

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is an ISO control code, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isISOControl(" "));
var_dump(IntlChar::isISOControl("\n"));
var_dump(IntlChar::isISOControl("\u{200e}"));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
bool(false)

A se vedea ?i

  • IntlChar::iscntrl() - Check if code point is a control character

IntlChar::isIDStart
IntlChar::isJavaIDPart
IntlChar


Check if code point is permissible in a Java identifier

IntlChar::isISOControl
IntlChar::isJavaIDStart
IntlChar
PHP Manual

IntlChar::isJavaIDPart

(PHP 7)

IntlChar::isJavaIDPart — Check if code point is permissible in a Java identifier

Descrierea

public static bool IntlChar::isJavaIDPart ( mixed $codepoint )

Determines if the specified character is permissible in a Java identifier.

In addition to IntlChar::isIDPart(), TRUE for characters with general category "Sc" (currency symbols).

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint may occur in a Java identifier, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isJavaIDPart("A"));
var_dump(IntlChar::isJavaIDPart("$"));
var_dump(IntlChar::isJavaIDPart("\n"));
var_dump(IntlChar::isJavaIDPart("\u{2603}"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(false)
bool(false)

A se vedea ?i

  • IntlChar::isIDIgnorable() - Check if code point is an ignorable character
  • IntlChar::isIDPart() - Check if code point is permissible in an identifier
  • IntlChar::isJavaIDStart() - Check if code point is permissible as the first character in a Java identifier
  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::isdigit() - Check if code point is a digit character

IntlChar::isISOControl
IntlChar::isJavaIDStart
IntlChar


Check if code point is permissible as the first character in a Java identifier

IntlChar::isJavaIDPart
IntlChar::isJavaSpaceChar
IntlChar
PHP Manual

IntlChar::isJavaIDStart

(PHP 7)

IntlChar::isJavaIDStart — Check if code point is permissible as the first character in a Java identifier

Descrierea

public static bool IntlChar::isJavaIDStart ( mixed $codepoint )

Determines if the specified character is permissible as the start of a Java identifier.

In addition to IntlChar::isIDStart(), TRUE for characters with general categories "Sc" (currency symbols) and "Pc" (connecting punctuation).

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint may start a Java identifier, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isJavaIDStart("A"));
var_dump(IntlChar::isJavaIDStart("$"));
var_dump(IntlChar::isJavaIDStart("\n"));
var_dump(IntlChar::isJavaIDStart("\u{2603}"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(false)
bool(false)

A se vedea ?i

  • IntlChar::isIDStart() - Check if code point is permissible as the first character in an identifier
  • IntlChar::isJavaIDPart() - Check if code point is permissible in a Java identifier
  • IntlChar::isalpha() - Check if code point is a letter character

IntlChar::isJavaIDPart
IntlChar::isJavaSpaceChar
IntlChar


Check if code point is a space character according to Java

IntlChar::isJavaIDStart
IntlChar::islower
IntlChar
PHP Manual

IntlChar::isJavaSpaceChar

(PHP 7)

IntlChar::isJavaSpaceChar — Check if code point is a space character according to Java

Descrierea

public static bool IntlChar::isJavaSpaceChar ( mixed $codepoint )

Determine if the specified code point is a space character according to Java.

TRUE for characters with general categories "Z" (separators), which does not include control codes (e.g., TAB or Line Feed).

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is a space character according to Java, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isJavaSpaceChar("A"));
var_dump(IntlChar::isJavaSpaceChar(" "));
var_dump(IntlChar::isJavaSpaceChar("\n"));
var_dump(IntlChar::isJavaSpaceChar("\t"));
var_dump(IntlChar::isJavaSpaceChar("\u{00A0}"));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
bool(false)
bool(false)
bool(true)

A se vedea ?i

  • IntlChar::isspace() - Check if code point is a space character
  • IntlChar::isWhitespace() - Check if code point is a whitespace character according to ICU
  • IntlChar::isUWhiteSpace() - Check if code point has the White_Space Unicode property

IntlChar::isJavaIDStart
IntlChar::islower
IntlChar


Check if code point is a lowercase letter

IntlChar::isJavaSpaceChar
IntlChar::isMirrored
IntlChar
PHP Manual

IntlChar::islower

(PHP 7)

IntlChar::islower — Check if code point is a lowercase letter

Descrierea

public static bool IntlChar::islower ( mixed $codepoint )

Determines whether the specified code point has the general category "Ll" (lowercase letter).

Nota:

This misses some characters that are also lowercase but have a different general category value. In order to include those, use IntlChar::isULowercase().

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is an Ll lowercase letter, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::islower("A"));
var_dump(IntlChar::islower("a"));
var_dump(IntlChar::islower("F"));
var_dump(IntlChar::islower("f"));
var_dump(IntlChar::islower("1"));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
bool(false)
bool(true)
bool(false)

A se vedea ?i

  • IntlChar::isupper() - Check if code point has the general category "Lu" (uppercase letter)
  • IntlChar::istitle() - Check if code point is a titlecase letter
  • IntlChar::tolower() - Make Unicode character lowercase
  • IntlChar::toupper() - Make Unicode character uppercase
  • IntlChar::PROPERTY_LOWERCASE

IntlChar::isJavaSpaceChar
IntlChar::isMirrored
IntlChar


Check if code point has the Bidi_Mirrored property

IntlChar::islower
IntlChar::isprint
IntlChar
PHP Manual

IntlChar::isMirrored

(PHP 7)

IntlChar::isMirrored — Check if code point has the Bidi_Mirrored property

Descrierea

public static bool IntlChar::isMirrored ( mixed $codepoint )

Determines whether the code point has the Bidi_Mirrored property.

This property is set for characters that are commonly used in Right-To-Left contexts and need to be displayed with a "mirrored" glyph.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint has the Bidi_Mirrored property, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isMirrored("A"));
var_dump(IntlChar::isMirrored("<"));
var_dump(IntlChar::isMirrored("("));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
bool(true)

A se vedea ?i

  • IntlChar::charMirror() - Get the "mirror-image" character for a code point
  • IntlChar::PROPERTY_BIDI_MIRRORED

IntlChar::islower
IntlChar::isprint
IntlChar


Check if code point is a printable character

IntlChar::isMirrored
IntlChar::ispunct
IntlChar
PHP Manual

IntlChar::isprint

(PHP 7)

IntlChar::isprint — Check if code point is a printable character

Descrierea

public static bool IntlChar::isprint ( mixed $codepoint )

Determines whether the specified code point is a printable character.

TRUE for general categories other than "C" (controls).

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is a printable character, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isprint("A"));
var_dump(IntlChar::isprint(" "));
var_dump(IntlChar::isprint("\n"));
var_dump(IntlChar::isprint("\u{200e}"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(false)
bool(false)

A se vedea ?i

  • IntlChar::iscntrl() - Check if code point is a control character
  • IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT

IntlChar::isMirrored
IntlChar::ispunct
IntlChar


Check if code point is punctuation character

IntlChar::isprint
IntlChar::isspace
IntlChar
PHP Manual

IntlChar::ispunct

(PHP 7)

IntlChar::ispunct — Check if code point is punctuation character

Descrierea

public static bool IntlChar::ispunct ( mixed $codepoint )

Determines whether the specified code point is a punctuation character.

TRUE for characters with general categories "P" (punctuation).

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is a punctuation character, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::ispunct("."));
var_dump(IntlChar::ispunct(","));
var_dump(IntlChar::ispunct("\n"));
var_dump(IntlChar::ispunct("$"));

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(false)
bool(false)
IntlChar::isprint
IntlChar::isspace
IntlChar


Check if code point is a space character

IntlChar::ispunct
IntlChar::istitle
IntlChar
PHP Manual

IntlChar::isspace

(PHP 7)

IntlChar::isspace — Check if code point is a space character

Descrierea

public static bool IntlChar::isspace ( mixed $codepoint )

Determines if the specified character is a space character or not.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is a space character, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isspace("A"));
var_dump(IntlChar::isspace(" "));
var_dump(IntlChar::isspace("\n"));
var_dump(IntlChar::isspace("\t"));
var_dump(IntlChar::isspace("\u{00A0}"));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
bool(true)
bool(true)
bool(true)

A se vedea ?i

  • IntlChar::isJavaSpaceChar() - Check if code point is a space character according to Java
  • IntlChar::isWhitespace() - Check if code point is a whitespace character according to ICU
  • IntlChar::isUWhiteSpace() - Check if code point has the White_Space Unicode property

IntlChar::ispunct
IntlChar::istitle
IntlChar


Check if code point is a titlecase letter

IntlChar::isspace
IntlChar::isUAlphabetic
IntlChar
PHP Manual

IntlChar::istitle

(PHP 7)

IntlChar::istitle — Check if code point is a titlecase letter

Descrierea

public static bool IntlChar::istitle ( mixed $codepoint )

Determines whether the specified code point is a titlecase letter.

TRUE for general category "Lt" (titlecase letter).

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is a titlecase letter, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::istitle("A"));
var_dump(IntlChar::istitle("a"));
var_dump(IntlChar::istitle("F"));
var_dump(IntlChar::istitle("f"));
var_dump(IntlChar::istitle("1"));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
bool(false)
bool(true)
bool(false)

A se vedea ?i

  • IntlChar::isupper() - Check if code point has the general category "Lu" (uppercase letter)
  • IntlChar::islower() - Check if code point is a lowercase letter
  • IntlChar::totitle() - Make Unicode character titlecase

IntlChar::isspace
IntlChar::isUAlphabetic
IntlChar


Check if code point has the Alphabetic Unicode property

IntlChar::istitle
IntlChar::isULowercase
IntlChar
PHP Manual

IntlChar::isUAlphabetic

(PHP 7)

IntlChar::isUAlphabetic — Check if code point has the Alphabetic Unicode property

Descrierea

public static bool IntlChar::isUAlphabetic ( mixed $codepoint )

Check if a code point has the Alphabetic Unicode property.

This is the same as IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_ALPHABETIC)

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint has the Alphabetic Unicode property, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isUAlphabetic("A"));
var_dump(IntlChar::isUAlphabetic("1"));
var_dump(IntlChar::isUAlphabetic("\u{2603}"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)
bool(false)

A se vedea ?i

  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::PROPERTY_ALPHABETIC

IntlChar::istitle
IntlChar::isULowercase
IntlChar


Check if code point has the Lowercase Unicode property

IntlChar::isUAlphabetic
IntlChar::isupper
IntlChar
PHP Manual

IntlChar::isULowercase

(PHP 7)

IntlChar::isULowercase — Check if code point has the Lowercase Unicode property

Descrierea

public static bool IntlChar::isULowercase ( mixed $codepoint )

Check if a code point has the Lowercase Unicode property.

This is the same as IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_LOWERCASE)

Nota:

This is different than IntlChar::islower() and will return TRUE for more characters.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint has the Lowercase Unicode property, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isULowercase("A"));
var_dump(IntlChar::isULowercase("a"));
var_dump(IntlChar::isULowercase("F"));
var_dump(IntlChar::isULowercase("f"));
var_dump(IntlChar::isULowercase("1"));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
bool(false)
bool(true)
bool(false)

A se vedea ?i

  • IntlChar::islower() - Check if code point is a lowercase letter
  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::PROPERTY_LOWERCASE

IntlChar::isUAlphabetic
IntlChar::isupper
IntlChar


Check if code point has the general category "Lu" (uppercase letter)

IntlChar::isULowercase
IntlChar::isUUppercase
IntlChar
PHP Manual

IntlChar::isupper

(PHP 7)

IntlChar::isupper — Check if code point has the general category "Lu" (uppercase letter)

Descrierea

public static bool IntlChar::isupper ( mixed $codepoint )

Determines whether the specified code point has the general category "Lu" (uppercase letter).

Nota:

This misses some characters that are also uppercase but have a different general category value. In order to include those, use IntlChar::isUUppercase().

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is an Lu uppercase letter, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isupper("A"));
var_dump(IntlChar::isupper("a"));
var_dump(IntlChar::isupper("F"));
var_dump(IntlChar::isupper("f"));
var_dump(IntlChar::isupper("1"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)
bool(true)
bool(false)
bool(false)

A se vedea ?i

  • IntlChar::islower() - Check if code point is a lowercase letter
  • IntlChar::istitle() - Check if code point is a titlecase letter
  • IntlChar::tolower() - Make Unicode character lowercase
  • IntlChar::toupper() - Make Unicode character uppercase
  • IntlChar::PROPERTY_UPPERCASE

IntlChar::isULowercase
IntlChar::isUUppercase
IntlChar


Check if code point has the Uppercase Unicode property

IntlChar::isupper
IntlChar::isUWhiteSpace
IntlChar
PHP Manual

IntlChar::isUUppercase

(PHP 7)

IntlChar::isUUppercase — Check if code point has the Uppercase Unicode property

Descrierea

public static bool IntlChar::isUUppercase ( mixed $codepoint )

Check if a code point has the Uppercase Unicode property.

This is the same as IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_UPPERCASE)

Nota:

This is different than IntlChar::isupper() and will return TRUE for more characters.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint has the Uppercase Unicode property, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isUUppercase("A"));
var_dump(IntlChar::isUUppercase("a"));
var_dump(IntlChar::isUUppercase("F"));
var_dump(IntlChar::isUUppercase("f"));
var_dump(IntlChar::isUUppercase("1"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)
bool(true)
bool(false)
bool(false)

A se vedea ?i

  • IntlChar::isupper() - Check if code point has the general category "Lu" (uppercase letter)
  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::PROPERTY_UPPERCASE

IntlChar::isupper
IntlChar::isUWhiteSpace
IntlChar


Check if code point has the White_Space Unicode property

IntlChar::isUUppercase
IntlChar::isWhitespace
IntlChar
PHP Manual

IntlChar::isUWhiteSpace

(PHP 7)

IntlChar::isUWhiteSpace — Check if code point has the White_Space Unicode property

Descrierea

public static bool IntlChar::isUWhiteSpace ( mixed $codepoint )

Check if a code point has the White_Space Unicode property.

This is the same as IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_WHITE_SPACE)

Nota:

This is different from both IntlChar::isspace() and IntlChar::isWhitespace().

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint has the White_Space Unicode property, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isUWhiteSpace("A"));
var_dump(IntlChar::isUWhiteSpace(" "));
var_dump(IntlChar::isUWhiteSpace("\n"));
var_dump(IntlChar::isUWhiteSpace("\t"));
var_dump(IntlChar::isUWhiteSpace("\u{00A0}"));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
bool(true)
bool(true)
bool(true)

A se vedea ?i

  • IntlChar::isspace() - Check if code point is a space character
  • IntlChar::isWhitespace() - Check if code point is a whitespace character according to ICU
  • IntlChar::isJavaSpaceChar() - Check if code point is a space character according to Java
  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::PROPERTY_WHITE_SPACE

IntlChar::isUUppercase
IntlChar::isWhitespace
IntlChar


Check if code point is a whitespace character according to ICU

IntlChar::isUWhiteSpace
IntlChar::isxdigit
IntlChar
PHP Manual

IntlChar::isWhitespace

(PHP 7)

IntlChar::isWhitespace — Check if code point is a whitespace character according to ICU

Descrierea

public static bool IntlChar::isWhitespace ( mixed $codepoint )

Determines if the specified code point is a whitespace character according to ICU.

A character is considered to be a ICU whitespace character if and only if it satisfies one of the following criteria:

  • It is a Unicode Separator character (categories "Z" = "Zs" or "Zl" or "Zp"), but is not also a non-breaking space (U+00A0 NBSP or U+2007 Figure Space or U+202F Narrow NBSP).
  • It is U+0009 HORIZONTAL TABULATION.
  • It is U+000A LINE FEED.
  • It is U+000B VERTICAL TABULATION.
  • It is U+000C FORM FEED.
  • It is U+000D CARRIAGE RETURN.
  • It is U+001C FILE SEPARATOR.
  • It is U+001D GROUP SEPARATOR.
  • It is U+001E RECORD SEPARATOR.
  • It is U+001F UNIT SEPARATOR.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is a whitespace character according to ICU, FALSE if not.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::iswhitespace("A"));
var_dump(IntlChar::iswhitespace(" "));
var_dump(IntlChar::iswhitespace("\n"));
var_dump(IntlChar::iswhitespace("\t"));
var_dump(IntlChar::iswhitespace("\u{00A0}"));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
bool(true)
bool(true)
bool(false)

A se vedea ?i

  • IntlChar::isspace() - Check if code point is a space character
  • IntlChar::isJavaSpaceChar() - Check if code point is a space character according to Java
  • IntlChar::isUWhiteSpace() - Check if code point has the White_Space Unicode property

IntlChar::isUWhiteSpace
IntlChar::isxdigit
IntlChar


Check if code point is a hexadecimal digit

IntlChar::isWhitespace
IntlChar::ord
IntlChar
PHP Manual

IntlChar::isxdigit

(PHP 7)

IntlChar::isxdigit — Check if code point is a hexadecimal digit

Descrierea

public static bool IntlChar::isxdigit ( mixed $codepoint )

Determines whether the specified code point is a hexadecimal digit.

TRUE for characters with general category "Nd" (decimal digit numbers) as well as Latin letters a-f and A-F in both ASCII and Fullwidth ASCII. (That is, for letters with code points 0041..0046, 0061..0066, FF21..FF26, FF41..FF46.)

This is equivalent to IntlChar::digit($codepoint, 16) >= 0.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns TRUE if codepoint is a hexadecimal character, FALSE if not.

Note

Nota:

In order to narrow the definition of hexadecimal digits to only ASCII characters use:

<?php
$isASCIIHexadecimal = IntlChar::ord($codepoint) <= 0x7F && IntlChar::isxdigit($codepoint);
?>

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::isxdigit("A"));
var_dump(IntlChar::isxdigit("1"));
var_dump(IntlChar::isxdigit("\u{2603}"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(false)

A se vedea ?i

  • IntlChar::isdigit() - Check if code point is a digit character

IntlChar::isWhitespace
IntlChar::ord
IntlChar


Return Unicode code point value of character

IntlChar::isxdigit
IntlChar::tolower
IntlChar
PHP Manual

IntlChar::ord

(PHP 7)

IntlChar::ord — Return Unicode code point value of character

Descrierea

public static int IntlChar::ord ( mixed $character )

Returns the Unicode code point value of the given character.

This function compliments IntlChar::chr().

Parametri

character

A Unicode character.

Valorile întoarse

Returns the Unicode code point value as an integer.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::ord("A"));
var_dump(IntlChar::ord(" "));
var_dump(IntlChar::ord("\u{2603}"));
?>

Exemplul de mai sus va afi?a:

int(65)
int(32)
int(9731)

A se vedea ?i

  • IntlChar::isalnum() - Check if code point is an alphanumeric character
  • IntlChar::isdigit() - Check if code point is a digit character
  • IntlChar::chr() - Return Unicode character by code point value
  • ord() - Return ASCII value of character

IntlChar::isxdigit
IntlChar::tolower
IntlChar


Make Unicode character lowercase

IntlChar::ord
IntlChar::totitle
IntlChar
PHP Manual

IntlChar::tolower

(PHP 7)

IntlChar::tolower — Make Unicode character lowercase

Descrierea

public static mixed IntlChar::tolower ( mixed $codepoint )

The given character is mapped to its lowercase equivalent. If the character has no lowercase equivalent, the original character itself is returned.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns the Simple_Lowercase_Mapping of the code point, if any; otherwise the code point itself.

Tipul întors va fi integer, doar daca code point nu a fost transmis ca string UTF-8, în care caz va fi întors un string.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::tolower("A"));
var_dump(IntlChar::tolower("a"));
var_dump(IntlChar::tolower("F"));
var_dump(IntlChar::tolower("f"));
var_dump(IntlChar::tolower("1"));
var_dump(IntlChar::tolower(ord("A")));
var_dump(IntlChar::tolower(ord("a")));
?>

Exemplul de mai sus va afi?a:

string(1) "a"
string(1) "a"
string(2) "f"
string(2) "f"
string(1) "1"
int(97)
int(97)

A se vedea ?i

  • IntlChar::totitle() - Make Unicode character titlecase
  • IntlChar::toupper() - Make Unicode character uppercase
  • mb_strtolower() - Make a string lowercase

IntlChar::ord
IntlChar::totitle
IntlChar


Make Unicode character titlecase

IntlChar::tolower
IntlChar::toupper
IntlChar
PHP Manual

IntlChar::totitle

(PHP 7)

IntlChar::totitle — Make Unicode character titlecase

Descrierea

public static mixed IntlChar::totitle ( mixed $codepoint )

The given character is mapped to its titlecase equivalent. If the character has no titlecase equivalent, the original character itself is returned.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns the Simple_Titlecase_Mapping of the code point, if any; otherwise the code point itself.

Tipul întors va fi integer, doar daca code point nu a fost transmis ca string UTF-8, în care caz va fi întors un string.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::totitle("A"));
var_dump(IntlChar::totitle("a"));
var_dump(IntlChar::totitle("F"));
var_dump(IntlChar::totitle("f"));
var_dump(IntlChar::totitle("1"));
var_dump(IntlChar::totitle(ord("A")));
var_dump(IntlChar::totitle(ord("a")));
?>

Exemplul de mai sus va afi?a:

string(1) "A"
string(1) "A"
string(2) "F"
string(2) "F"
string(1) "1"
int(65)
int(65)

A se vedea ?i

  • IntlChar::tolower() - Make Unicode character lowercase
  • IntlChar::toupper() - Make Unicode character uppercase
  • mb_convert_case() - Perform case folding on a string

IntlChar::tolower
IntlChar::toupper
IntlChar


Make Unicode character uppercase

IntlChar::totitle
IntlException
IntlChar
PHP Manual

IntlChar::toupper

(PHP 7)

IntlChar::toupper — Make Unicode character uppercase

Descrierea

public static mixed IntlChar::toupper ( mixed $codepoint )

The given character is mapped to its uppercase equivalent. If the character has no uppercase equivalent, the character itself is returned.

Parametri

codepoint

Valoarea codepoint de tip integer (de ex. 0x2603 pentru U+2603 SNOWMAN) sau caracterul codificat ca string în UTF-8 (de ex. "\u{2603}")

Valorile întoarse

Returns the Simple_Uppercase_Mapping of the code point, if any; otherwise the code point itself.

Tipul întors va fi integer, doar daca code point nu a fost transmis ca string UTF-8, în care caz va fi întors un string.

Exemple

Example #1 Testarea diferitor code points

<?php
var_dump(IntlChar::toupper("A"));
var_dump(IntlChar::toupper("a"));
var_dump(IntlChar::toupper("F"));
var_dump(IntlChar::toupper("f"));
var_dump(IntlChar::toupper("1"));
var_dump(IntlChar::toupper(ord("A")));
var_dump(IntlChar::toupper(ord("a")));
?>

Exemplul de mai sus va afi?a:

string(1) "A"
string(1) "A"
string(2) "F"
string(2) "F"
string(1) "1"
int(65)
int(65)

A se vedea ?i

  • IntlChar::tolower() - Make Unicode character lowercase
  • IntlChar::totitle() - Make Unicode character titlecase
  • mb_strtoupper() - Make a string uppercase

IntlChar::totitle
IntlException
IntlChar


Exception class for intl errors

(PHP 5 > 5.5.0, PHP 7, PECL intl > 3.0.0a1)

Introducere

This class is used for generating exceptions when errors occur inside intl functions. Such exceptions are only generated when intl.use_exceptions is enabled.

Sinopsisul clasei

IntlException extends Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
IntlChar::toupper
IntlIterator
intl


The IntlIterator class

(No version information available, might only be in Git)

Introducere

This class represents iterator objects throughout the intl extension whenever the iterator cannot be identified with any other object provided by the extension. The distinct iterator object used internally by the foreach construct can only be obtained (in the relevant part here) from objects, so objects of this class serve the purpose of providing the hook through which this internal object can be obtained. As a convenience, this class also implements the Iterator interface, allowing the collection of values to be navigated using the methods defined in that interface. Both these methods and the internal iterator objects provided to foreach are backed by the same state (e.g. the position of the iterator and its current value).

Subclasses may provide richer functionality.

Sinopsisul clasei

IntlIterator implements Iterator {
/* Metode */
public ReturnType current ( void )
public ReturnType key ( void )
public ReturnType next ( void )
public ReturnType rewind ( void )
public ReturnType valid ( void )
}

Cuprins

  • IntlIterator::current — Get the current element
  • IntlIterator::key — Get the current key
  • IntlIterator::next — Move forward to the next element
  • IntlIterator::rewind — Rewind the iterator to the first element
  • IntlIterator::valid — Check if current position is valid
IntlException
IntlIterator::current
intl


Get the current element

IntlIterator
IntlIterator::key
IntlIterator
PHP Manual

IntlIterator::current

(No version information available, might only be in Git)

IntlIterator::current — Get the current element

Descrierea

public ReturnType IntlIterator::current ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlIterator
IntlIterator::key
IntlIterator


Get the current key

IntlIterator::current
IntlIterator::next
IntlIterator
PHP Manual

IntlIterator::key

(No version information available, might only be in Git)

IntlIterator::key — Get the current key

Descrierea

public ReturnType IntlIterator::key ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlIterator::current
IntlIterator::next
IntlIterator


Move forward to the next element

IntlIterator::key
IntlIterator::rewind
IntlIterator
PHP Manual

IntlIterator::next

(No version information available, might only be in Git)

IntlIterator::next — Move forward to the next element

Descrierea

public ReturnType IntlIterator::next ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlIterator::key
IntlIterator::rewind
IntlIterator


Rewind the iterator to the first element

IntlIterator::next
IntlIterator::valid
IntlIterator
PHP Manual

IntlIterator::rewind

(No version information available, might only be in Git)

IntlIterator::rewind — Rewind the iterator to the first element

Descrierea

public ReturnType IntlIterator::rewind ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlIterator::next
IntlIterator::valid
IntlIterator


Check if current position is valid

IntlIterator::rewind
Func?ii intl
IntlIterator
PHP Manual

IntlIterator::valid

(No version information available, might only be in Git)

IntlIterator::valid — Check if current position is valid

Descrierea

public ReturnType IntlIterator::valid ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

IntlIterator::rewind
Func?ii intl
IntlIterator


Func?ii intl

Cuprins

  • 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
IntlIterator::valid
intl_error_name
intl


Get symbolic name for a given error code

Func?ii intl
intl_get_error_code
Func?ii intl
PHP Manual

intl_error_name

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

intl_error_name — Get symbolic name for a given error code

Descrierea

string intl_error_name ( int $error_code )

Return ICU error code name.

Parametri

error_code

ICU error code.

Valorile întoarse

The returned string will be the same as the name of the error code constant.

Exemple

Example #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 ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

Symbolic name for -128 is U_USING_FALLBACK_WARNING.

A se vedea ?i

  • 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

Func?ii intl
intl_get_error_code
Func?ii intl


Get the last error code

intl_error_name
intl_get_error_message
Func?ii intl
PHP Manual

intl_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

intl_get_error_code — Get the last error code

Descrierea

int intl_get_error_code ( void )

Useful to handle errors occurred in static methods when there's no object to get error code from.

Valorile întoarse

Error code returned by the last API function call.

Exemple

Example #1 intl_get_error_code() example

<?php
$coll = collator_create( '<bad_param>' );
if( !$coll ) {
    handle_error( intl_get_error_code() );
}
?>

A se vedea ?i

  • 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
Func?ii intl


Get description of the last error

intl_get_error_code
intl_is_failure
Func?ii intl
PHP Manual

intl_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

intl_get_error_message — Get description of the last error

Descrierea

string intl_get_error_message ( void )

Get error message from last internationalization function called.

Valorile întoarse

Description of an error occurred in the last API function call.

Exemple

Example #1 intl_get_error_message() example

<?php
if( Collator::getAvailableLocales() === false ) {
    show_error( intl_get_error_message() );
}
?>

A se vedea ?i

  • 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
Func?ii intl


Check whether the given error code indicates failure

intl_get_error_message
Stringuri multioctet
Func?ii intl
PHP Manual

intl_is_failure

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

intl_is_failure — Check whether the given error code indicates failure

Descrierea

bool intl_is_failure ( int $error_code )

Parametri

error_code

is a value that returned by functions: intl_get_error_code(), collator_get_error_code() .

Valorile întoarse

TRUE if it the code indicates some failure, and FALSE in case of success or a warning.

Exemple

Example #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 );
?>

Exemplul de mai sus va afi?a ceva similar cu:

false
false
true

A se vedea ?i

  • 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
Stringuri multioctet
Func?ii intl


Stringuri multioctet

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Summaries of supported encodings
  • Basics of Japanese multi-byte encodings
  • HTTP Input and Output
  • Supported Character Encodings
  • Function Overloading Feature
  • Cerin?e pentru codarea caracterelor în PHP
  • Multibyte String Func?ii
    • 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_callback — Perform a regular expresssion seach and replace with multibyte support using a callback
    • 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 — Set/Get character encoding for multibyte regex
    • 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
Introducere
Sus?inerea limbajului uman ?i a codificarii caracterelor


Introducere

De?i sunt multe limbi în care orice caracter poate fi reprezentat prin asocierea lui cu o valoare pe 8 bi?i, exista multe alte limbi care au atât de multe caractere pentru comunicarea în scris încât ele nu încap în ceea ce ofera un simplu octet (Un octet este format din 8 bi?i. Fiecare bit poate con?ine valoarea 1 sau 0. Din aceasta cauza, un octet poate reprezenta doar 256 de valori (doi la puterea a opta)). Din aceasta cauza, s-au dezvoltat scheme de codare a caracterelor pe mai mul?i octe?i pentru a lucra cu mai mult de 256 de caractere.

Când manipula?i (trim, split, splice, etc.) stringuri care con?in caractere multioctet, trebuie sa folosi?i func?ii speciale deoarece doi sau mai mul?i octe?i consecutivi pot reprezenta un singur caracter în astfel de scheme de codare. Altfel, daca folosi?i o func?ie care nu ?ine cont de caractere multioctet pe stringuri care con?in astfel de caractere, probabil ca func?ia va e?ua sa detecteze unde începe ?i unde se termina caracterul multioctet ?i ve?i ramâne cu un string care con?ine caractere indescifrabile ?i care ?i-a pierdut în?elesul ini?ial.

mbstring ofera func?ii specifice lucrului cu stringuri care con?in caractere multioctet, func?ii care va ajuta sa lucra?i în PHP cu codarile acestor caractere. În plus, mbstring se ocupa de conversia de caractere între perechi de codari suportate. mbstring este gândit sa se ocupe de codari bazate pe Unicode, cum ar fi UTF-8 ?i UCS-2 dar poate fi folosita ?i cu alte codari de caractere pe un singur octet (enumerate mai jos).

Stringuri multioctet
Instalarea / configurarea
Stringuri multioctet


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Stringuri multioctet


Instalarea

mbstring este o extensie care nu este activata în mod implicit. Trebuie sa o activa?i folosind op?iunea corespunzatoare cu comanda configure. Vede?i sec?iunea Instalare pentru detalii.

Urmatoarele op?iuni de configurare sunt legate de modulul mbstring.

  • --enable-mbstring : Activeaza func?iile mbstring. Aceasta op?iune este necesara pentru a folosi func?iile oferite de mbstring.

    libmbfl e necesar pentru mbstring. libmbfl e distribuit cu mbstring. Daca libmbfl este deja instalat pe sistem cu op?iunea --with-libmbfl[=DIR] pute?i specifica ca dori?i sa utiliza?i libraria instalata.

    De la PHP 4.3.0, extensia mbstring ofera suport îmbunata?it pentru chineza simplificata, chineza tradi?ionala, coreeana ?i rusa la fel ca în japoneza.

    Pentru PHP 4.3.3 sau mai vechi, pentru a activa aceasta îmbunata?ire, trebuie sa specifica?i valoarea parametrului LANG din op?iunea --enable-mbstring=LANG ; --enable-mbstring=cn pentru chineza simplificata, --enable-mbstring=tw pentru chineza tradi?ionala, --enable-mbstring=kr pentru coreeana, --enable-mbstring=ru pentru rusa ?i --enable-mbstring=ja pentru japoneza (implicit). Pentru a activa toate codarile suportate, folosi?i --enable-mbstring=all .

    Nota:

    De la PHP 4.3.4, toate codarile suportate de libmbfl sunt activate prin op?iunea --enable-mbstring .

  • --enable-mbstr-enc-trans : Activeaza conversia de codare a caracterelor introduse prin HTTP folosind motorul de conversie din mbstring. Daca aceasta facilitate este activata, codarea caracterelor introduse prin HTTP poate fi convertita la mbstring.internal_encoding automat.

    Nota:

    De la PHP 4.3.0, op?iunea --enable-mbstr-enc-trans a fost eliminata ?i înlocuita cu setarea mbstring.encoding_translation. Conversia de codare a caracterelor introduse prin HTTP este activata când aceasta setare este On (implicit este Off).

  • --disable-mbregex : Dezactiveaza func?iile pentru expresii regulate care suporta caracterele multioctet.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Op?iuni de configurare pentru mbstring
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
mbstring.language | "neutral" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.; PHP_INI_PERDIR în PHP <= 5.2.6
mbstring.detect_order | NULL | PHP_INI_ALL | Disponibila începând cu PHP 4.0.6.
mbstring.http_input | "pass" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.6. Învechita în PHP 5.6.0.
mbstring.http_output | "pass" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.6. Învechita în PHP 5.6.0.
mbstring.internal_encoding | NULL | PHP_INI_ALL | Disponibila începând cu PHP 4.0.6. Învechita în PHP 5.6.0.
mbstring.script_encoding | NULL | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0. Eliminata în PHP 5.4.0. Folosi?i în loc zend.script_encoding.
mbstring.substitute_character | NULL | PHP_INI_ALL | Disponibila începând cu PHP 4.0.6.
mbstring.func_overload | "0" | PHP_INI_SYSTEM | PHP_INI_PERDIR de la PHP 4.3 pâna la 5.2.6, în caz contrar PHP_INI_SYSTEM. Disponibila începând cu PHP 4.2.0.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR | Disponibila începând cu PHP 4.3.0.
mbstring.strict_detection | "0" | PHP_INI_ALL | Disponibila începând cu PHP 5.1.2.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

mbstring.language string

Setarea implicita a limbii (NLS) folosita de mbstring. Aten?ie, aceasta op?iune define?te automat mbstring.internal_encoding ?i mbstring.internal_encoding a?a ca schimbarile acestor setari din urma trebuie plasate dupa mbstring.language în php.ini

mbstring.encoding_translation boolean

Activeaza filtrul automat de codare a caracterelor care efectueaza detec?ia ?i conversia codarii caracterelor din cea folosita în datele HTTP primite în codarea interna a caracterelor.

mbstring.internal_encoding string
Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.6.0. Utilizarea acestei facilita?i este foarte discurajata.

Define?te codarea interna a caracterelor.

Utilizatorii PHP 5.6, sau ulterior, ar trebui sa lase aceasta setare vida ?i sa seteze în loc default_charset.

mbstring.http_input string
Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.6.0. Utilizarea acestei facilita?i este foarte discurajata.

Define?te codarea implicita a caracterelor introduse prin HTTP.

Utilizatorii PHP 5.6, sau ulterior, ar trebui sa lase aceasta setare vida ?i sa seteze în loc default_charset.

mbstring.http_output string
Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.6.0. Utilizarea acestei facilita?i este foarte discurajata.

Define?te codarea implicita a caracterelor trimise prin HTTP catre client (caracterele trimise vor fi convertite la transmitere din codarea interna în codarea HTTP).

Utilizatorii PHP 5.6, sau ulterior, ar trebui sa lase aceasta setare vida ?i sa seteze în loc default_charset.

mbstring.detect_order string

Define?te ordinea implicita de detec?ie a codarii caracterelor. Vede?i ?i mb_detect_order().

mbstring.substitute_character string

Define?te caracterul de înlocuire pentru caracterele care sunt gasite într-o codare necorespunzatoare.

mbstring.func_overload string

Suprascrie un set de func?ii pentru stringuri pe un singur octet cu echivalentele din mbstring. Vede?i Suprascrierea func?iilor pentru mai multe informa?ii.

Aceasta setare poate fi schimbata doar din fi?ierul php.ini.

mbstring.strict_detection boolean

Activeaza detec?ia stricta a codarii.

Conform » specifica?iilor HTML 4.01, navigatoarelor web le este permis sa codeze un formular completat cu o codare de caractere diferita de cea utilizata de pagina. Vede?i func?ia mb_http_input() pentru a detecta codarile de caractere utilizate de navigatoare.

De?i navigatoarele cele mai utilizate sunt capabile sa intuiasca destul de precis codarea caracterelor dintr-un document HTML, ar fi mai bine sa seta?i parametrul charset din antetul HTTP Content-Type la o valoare corespunzatoare folosind func?ia header() sau setarea ini default_charset.

Example #1 exemple de setari în php.ini

; Stabile?te limba implicita
mbstring.language        = Neutral; Stabile?te limba implicita la Neutral(UTF-8) (implicit)
mbstring.language        = English; Stabile?te limba implicita la English
mbstring.language        = Japanese; Stabile?te limba implicita la Japanese

;; Stabile?te codarea interna implicita
;; Nota: Asigura?i-va ca folosi?i o codare de caractere care func?ioneaza cu PHP
mbstring.internal_encoding    = UTF-8  ; Stabile?te codarea interna la UTF-8

;; Conversia codarii datelor HTTP este activata.
mbstring.encoding_translation = On

;; Stabile?te codarea implicita pentru datele primite prin HTTP
;; Nota: Scripturile nu pot schimba setarea http_input.
mbstring.http_input           = pass    ; Fara conversie
mbstring.http_input           = auto    ; Conversie automata
                                ; „auto” este extins în conformitate cu mbstring.language
mbstring.http_input           = SJIS    ; Stabile?te intrarile HTTP în SJIS
mbstring.http_input           = UTF-8,SJIS,EUC-JP ; Specifica ordinea

;; Stabile?te codarea implicita pentru datele trimise prin HTTP
mbstring.http_output          = pass    ; Fara conversie
mbstring.http_output          = UTF-8   ; Conversia datelor trimise prin HTTP la UTF-8

;; Stabile?te ordinea implicita a detec?iei codarii caracterelor
mbstring.detect_order         = auto    ; Automat
mbstring.detect_order         = ASCII,JIS,UTF-8,SJIS,EUC-JP ; Specifica ordinea

;; Stabile?te caracterul implicit de înlocuire
mbstring.substitute_character = 12307   ; Specifica valoarea Unicode
mbstring.substitute_character = none    ; Nu afi?a caracterul
mbstring.substitute_character = long    ; Exemplu lung: U+3000,JIS+7E7E

Example #2 setari în php.ini pentru utilizatorii EUC-JP

;; Dezactiveaza tamponul de ie?ire
output_buffering      = Off

;; Stabile?te setul de caractere trimis în antetul HTTP
default_charset       = EUC-JP

;; Stabile?te limba implicita la Japanese
mbstring.language = Japanese

;; Conversia codarii datelor HTTP este activata.
mbstring.encoding_translation = On

;; Stabile?te codarea implicita pentru datele primite prin HTTP la auto
mbstring.http_input   = auto

;; Converte?te datele trimise prin HTTP la EUC-JP
mbstring.http_output  = EUC-JP

;; Stabile?te codarea interna la EUC-JP
mbstring.internal_encoding = EUC-JP

;; Nu afi?a caracterele invalide
mbstring.substitute_character = none

Example #3 setari în php.ini pentru utilizatorii SJIS

;; Activeaza tamponul de ie?ire
output_buffering     = On

;; Stabile?te gestionarul de ie?ire la mb_output_handler pentru a activa conversia datelor ie?ite
output_handler       = mb_output_handler

;; Stabile?te setul de caractere folosit în antetele HTTP
default_charset      = Shift_JIS

;; Stabile?te limba implicita la Japanese
mbstring.language = Japanese

;; Stabile?te codarea implicita pentru datele primite prin HTTP la auto
mbstring.http_input  = auto

;; Converte?te la SJIS
mbstring.http_output = SJIS

;; Stabile?te codarea interna la EUC-JP
mbstring.internal_encoding = EUC-JP

;; Nu afi?a caracterele invalide
mbstring.substitute_character = none

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

MB_OVERLOAD_MAIL (integer)
MB_OVERLOAD_STRING (integer)
MB_OVERLOAD_REGEX (integer)
MB_CASE_UPPER (integer)
MB_CASE_LOWER (integer)
MB_CASE_TITLE (integer)
Tipurile resurselor
Summaries of supported encodings
Stringuri multioctet


Summaries of supported encodings

Summaries of supported encodings
Name in the IANA character set registry | Underlying character set | Description | Additional note
ISO-10646-UCS-4 | ISO 10646 | 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. | 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.
ISO-10646-UCS-4 | UCS-4 | See above. | In contrast to UCS-4, strings are always assumed to be in big endian form.
ISO-10646-UCS-4 | UCS-4 | See above. | In contrast to UCS-4, strings are always assumed to be in little endian form.
ISO-10646-UCS-2 | UCS-2 | 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. | 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.
ISO-10646-UCS-2 | UCS-2 | See above. | In contrast to UCS-2, strings are always assumed to be in big endian form.
ISO-10646-UCS-2 | UCS-2 | See above. | In contrast to UCS-2, strings are always assumed to be in little endian form.
UTF-32 | Unicode | 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. | 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.
UTF-32BE | Unicode | See above | In contrast to UTF-32, strings are always assumed to be in big endian form.
UTF-32LE | Unicode | See above | In contrast to UTF-32, strings are always assumed to be in little endian form.
UTF-16 | Unicode | 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. | 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.
UTF-16BE | Unicode | See above. | In contrast to UTF-16, strings are always assumed to be in big endian form.
UTF-16LE | Unicode | See above. | In contrast to UTF-16, strings are always assumed to be in little endian form.
UTF-8 | Unicode / UCS | Unicode Transformation Format of 8-bit unit width. | none
UTF-7 | Unicode | A mail-safe transformation format of Unicode, specified in » RFC2152. | none
(none) | Unicode | A variant of UTF-7 which is specialized for use in the » IMAP protocol. | none
US-ASCII (preferred MIME name) / iso-ir-6 / ANSI_X3.4-1986 / ISO_646.irv:1991 / ASCII / ISO646-US / us / IBM367 / CP367 / csASCII | ASCII / ISO 646 | American Standard Code for Information Interchange is a commonly-used 7-bit encoding. Also standardized as an international standard, ISO 646. | (none)
EUC-JP (preferred MIME name) / Extended_UNIX_Code_Packed_Format_for_Japanese / csEUCPkdFmtJapanese | Compound of US-ASCII / JIS X0201:1997 (hankaku kana part) / JIS X0208:1990 / JIS X0212:1990 | 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. | 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.
Shift_JIS (preferred MIME name) / MS_Kanji / csShift_JIS | Compound of JIS X0201:1997 / JIS X0208:1997 | 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. | For the CP932 codemap, use SJIS-WIN instead.
(none) | Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions | 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. | none
Windows-31J / csWindows31J | Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions | 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. | (none)
ISO-2022-JP (preferred MIME name) / csISO2022JP | US-ASCII / JIS X0201:1976 / JIS X0208:1978 / JIS X0208:1983 | » RFC1468 | (none)
JIS |  |  |
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 |  |  |
ISO-8859-16 |  |  |
byte2be |  |  |
byte2le |  |  |
byte4be |  |  |
byte4le |  |  |
BASE64 |  |  |
HTML-ENTITIES |  |  |
7bit |  |  |
8bit |  |  |
EUC-CN |  |  |
CP936 |  |  |
HZ |  |  |
EUC-TW |  |  |
CP950 |  |  |
BIG-5 |  |  |
EUC-KR |  |  |
UHC (CP949) |  |  |
ISO-2022-KR |  |  |
Windows-1251 (CP1251) |  |  |
Windows-1252 (CP1252) |  |  |
CP866 (IBM866) |  |  |
KOI8-R |  |  |
KOI8-U |  |  |
Constante predefinite
Basics of Japanese multi-byte encodings
Stringuri multioctet


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
Stringuri multioctet


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.

Nota:

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.

    Example #1 Disable HTTP input conversion in php.ini

    ;; Disable HTTP Input conversion
mbstring.http_input = pass
;; Disable HTTP Input conversion
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.

Example #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

Example #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
Stringuri multioctet


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*
  • ISO-8859-16*
  • 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*
  • KOI8-U*
  • ArmSCII-8 (ArmSCII8)

* 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
Stringuri multioctet


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()

Nota:

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
Cerin?e pentru codarea caracterelor în PHP
Stringuri multioctet


Cerin?e pentru codarea caracterelor în PHP

Urmatoarele codari pot fi folosite în siguran?a cu PHP.

  • Orice codare de caractere pe un singur octet,

    • care are mapari compatibile ASCII (compatibile cu standardul ISO646) pentru caracterele de la 00h la 7fh.

  • Orice codare de caractere pe mai mul?i octe?i,

    • care are mapari compatibile ASCII pentru caracterele de la 00h la 7fh.
    • care nu utilizeaza secven?e de de evadare ISO2022.
    • care nu folosesc o valoare de la 00h la 7fh în octe?ii de compunere care reprezinta un singur caracter.

Acestea sunt exemple de codari de caractere care probabil nu merg în PHP.

JIS, SJIS, ISO-2022-JP, BIG-5

De?i s-ar putea ca scripturile PHP scrise în orice codare de mai sus sa nu mearga, în special în cazul în care stringuri codate apar ca identificatori sau literalmente în scripturi, pute?i evita alte probleme cu aceste codari setând conversia codarii caracterelor venite prin HTTP.

Nota:

Nu folosi?i SJIS, BIG5, CP936, CP949 ?i GB18030 pentru codarea interna decât daca sunte?i familiarizat(a) cu parser-ul, scanerul ?i codarea de caractere.

Nota:

Daca va conecta?i la o baza de date cu PHP, este recomandat sa folosi?i acea?i codare de caractere atât pentru baza de date cât ?i pentru codarea interna pentru u?urin?a în utilizare ?i o performan?a mai buna.

Daca folosi?i PostgreSQL, codarea de caractere folosita în baza de date ar putea diferi fa?a de cea folosita în PHP deoarece suporta conversia automata a setului de caractere între backend ?i frontend.

Function Overloading Feature
Multibyte String Func?ii
Stringuri multioctet


Multibyte String Func?ii

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

Cuprins

  • 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_callback — Perform a regular expresssion seach and replace with multibyte support using a callback
  • 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 — Set/Get character encoding for multibyte regex
  • 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
Cerin?e pentru codarea caracterelor în PHP
mb_check_encoding
Stringuri multioctet


Check if the string is valid for the specified encoding

Multibyte String Func?ii
mb_convert_case
Multibyte String Func?ii
PHP Manual

mb_check_encoding

(PHP 4 >= 4.4.3, PHP 5 >= 5.1.3, PHP 7)

mb_check_encoding — Check if the string is valid for the specified encoding

Descrierea

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".

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Multibyte String Func?ii
mb_convert_case
Multibyte String Func?ii


Perform case folding on a string

mb_check_encoding
mb_convert_encoding
Multibyte String Func?ii
PHP Manual

mb_convert_case

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

mb_convert_case — Perform case folding on a string

Descrierea

string mb_convert_case ( string $str , int $mode [, string $encoding = mb_internal_encoding() ] )

Performs case folding on a string, converted in the way specified by mode.

Parametri

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

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

A case folded version of string converted in the way specified by mode.

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/.

Exemple

Example #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
?>

Example #2 mb_convert_case() example with non-Latin UTF-8 text

<?php
$str = "????st? a??p?? ßaf?? ??µ??? ??, d?as?e???e? ?p?? ?????? ?????";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo $str; // Prints ????S?? ?????? ??F?S ?????? G?, ???S??????? ???? ?OT??? ????S
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str; // Prints ????st? ???p?? ?af?s ??µ??? G?, ??as?e???e? ?p?? ?????? ????s
?>

A se vedea ?i

  • mb_strtolower() - Make a string lowercase
  • mb_strtoupper() - Make a string uppercase
  • strtolower() - Make a string lowercase
  • strtoupper() - Make a string uppercase
  • 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 Func?ii


Convert character encoding

mb_convert_case
mb_convert_kana
Multibyte String Func?ii
PHP Manual

mb_convert_encoding

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_convert_encoding — Convert character encoding

Descrierea

string mb_convert_encoding ( string $str , string $to_encoding [, mixed $from_encoding = mb_internal_encoding() ] )

Converts the character encoding of string str to to_encoding from optionally from_encoding.

Parametri

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.

Valorile întoarse

The encoded string.

Exemple

Example #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");
?>

A se vedea ?i

  • mb_detect_order() - Set/Get character encoding detection order

mb_convert_case
mb_convert_kana
Multibyte String Func?ii


Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

mb_convert_encoding
mb_convert_variables
Multibyte String Func?ii
PHP Manual

mb_convert_kana

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

Descrierea

string mb_convert_kana ( string $str [, string $option = "KV" [, string $encoding = mb_internal_encoding() ]] )

Performs a "han-kaku" - "zen-kaku" conversion for string str. This function is only useful for Japanese.

Parametri

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

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

The converted string.

Exemple

Example #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 Func?ii


Convert character code in variable(s)

mb_convert_kana
mb_decode_mimeheader
Multibyte String Func?ii
PHP Manual

mb_convert_variables

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_convert_variables — Convert character code in variable(s)

Descrierea

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.

Parametri

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.

Valorile întoarse

The character encoding before conversion for success, or FALSE for failure.

Exemple

Example #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 Func?ii


Decode string in MIME header field

mb_convert_variables
mb_decode_numericentity
Multibyte String Func?ii
PHP Manual

mb_decode_mimeheader

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_decode_mimeheader — Decode string in MIME header field

Descrierea

string mb_decode_mimeheader ( string $str )

Decodes encoded-word string str in MIME header.

Parametri

str

The string being decoded.

Valorile întoarse

The decoded string in internal character encoding.

A se vedea ?i

  • mb_encode_mimeheader() - Encode string for MIME header

mb_convert_variables
mb_decode_numericentity
Multibyte String Func?ii


Decode HTML numeric string reference to character

mb_decode_mimeheader
mb_detect_encoding
Multibyte String Func?ii
PHP Manual

mb_decode_numericentity

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_decode_numericentity — Decode HTML numeric string reference to character

Descrierea

string mb_decode_numericentity ( string $str , array $convmap [, string $encoding = mb_internal_encoding() ] )

Convert numeric string reference of string str in a specified block to character.

Parametri

str

The string being decoded.

convmap

convmap is an array that specifies the code area to convert.

encoding

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

The converted string.

Exemple

Example #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.
?>

Example #2 convmap example escapes JavaScript string

<?php
function escape_javascript_string($str) {
  $map = [
          1,1,1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,0,0, // 49
          0,0,0,0,0,0,0,0,1,1,
          1,1,1,1,1,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          0,1,1,1,1,1,1,0,0,0, // 99
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,1,1, // 149
          1,1,1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,1,1, // 199
          1,1,1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,1,1,1, // 249
          1,1,1,1,1,1,1, // 255
          ];
  // Char encoding is UTF-8
  $mblen = mb_strlen($str, 'UTF-8');
  $utf32 = bin2hex(mb_convert_encoding($str, 'UTF-32', 'UTF-8'));
  for ($i=0, $encoded=''; $i < $mblen; $i++) {
      $u = substr($utf32, $i*8, 8);
      $v = base_convert($u, 16, 10);
      if ($v < 256 && $map[$v]) {
        $encoded .= '\\x'.substr($u, 6,2);
      } else if ($v == 2028) {
        $encoded .= '\\u2028';
      } else if ($v == 2029) {
        $encoded .= '\\u2029';
      } else {
        $encoded .= mb_convert_encoding(hex2bin($u), 'UTF-8', 'UTF-32');
      }
   }
   return $encoded;
}

// Test data
$convmap = [ 0x0, 0xffff, 0, 0xffff ];
$msg = '';
for ($i=0; $i < 1000; $i++) {
  // chr() cannot generate correct UTF-8 data larger value than 128, use mb_decode_numericentity().
  $msg .= mb_decode_numericentity('&#'.$i.';', $convmap, 'UTF-8');
}

// var_dump($msg);
var_dump(escape_javascript_string($msg));

A se vedea ?i

  • mb_encode_numericentity() - Encode character to HTML numeric string reference

mb_decode_mimeheader
mb_detect_encoding
Multibyte String Func?ii


Detect character encoding

mb_decode_numericentity
mb_detect_order
Multibyte String Func?ii
PHP Manual

mb_detect_encoding

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_detect_encoding — Detect character encoding

Descrierea

string mb_detect_encoding ( string $str [, mixed $encoding_list = mb_detect_order() [, bool $strict = false ]] )

Detects character encoding in string str.

Parametri

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.

Valorile întoarse

The detected character encoding or FALSE if the encoding cannot be detected from the given string.

Exemple

Example #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);
?>

A se vedea ?i

  • mb_detect_order() - Set/Get character encoding detection order

mb_decode_numericentity
mb_detect_order
Multibyte String Func?ii


Set/Get character encoding detection order

mb_detect_encoding
mb_encode_mimeheader
Multibyte String Func?ii
PHP Manual

mb_detect_order

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_detect_order — Set/Get character encoding detection order

Descrierea

mixed mb_detect_order ([ mixed $encoding_list = mb_detect_order() ] )

Sets the automatic character encoding detection order to encoding_list.

Parametri

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.

Valorile întoarse

When setting the encoding detection order, TRUE is returned on success or FALSE on failure.

When getting the encoding detection order, an ordered array of the encodings is returned.

Exemple

Example #1 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());
?>

Example #2 Example showing useless detect orders

; 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

A se vedea ?i

  • 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 Func?ii


Encode string for MIME header

mb_detect_order
mb_encode_numericentity
Multibyte String Func?ii
PHP Manual

mb_encode_mimeheader

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_encode_mimeheader — Encode string for MIME header

Descrierea

string mb_encode_mimeheader ( string $str [, string $charset = determined by mb_language() [, string $transfer_encoding = "B" [, string $linefeed = "\r\n" [, int $indent = 0 ]]]] )

Encodes a given string str by the MIME header encoding scheme.

Parametri

str

The string being encoded. Its encoding should be same as mb_internal_encoding().

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).

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).

Valorile întoarse

A converted version of the string represented in ASCII.

Exemple

Example #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;
?>

Note

Nota:

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.

A se vedea ?i

  • mb_decode_mimeheader() - Decode string in MIME header field

mb_detect_order
mb_encode_numericentity
Multibyte String Func?ii


Encode character to HTML numeric string reference

mb_encode_mimeheader
mb_encoding_aliases
Multibyte String Func?ii
PHP Manual

mb_encode_numericentity

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_encode_numericentity — Encode character to HTML numeric string reference

Descrierea

string mb_encode_numericentity ( string $str , array $convmap [, string $encoding = mb_internal_encoding() [, bool $is_hex = FALSE ]] )

Converts specified character codes in string str from character code to HTML numeric character reference.

Parametri

str

The string being encoded.

convmap

convmap is array specifies code area to convert.

encoding

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

is_hex

Valorile întoarse

The converted string.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added is_hex parameter.

Exemple

Example #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.
?>

Exemple

Example #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");
?>

A se vedea ?i

  • mb_decode_numericentity() - Decode HTML numeric string reference to character

mb_encode_mimeheader
mb_encoding_aliases
Multibyte String Func?ii


Get aliases of a known encoding type

mb_encode_numericentity
mb_ereg_match
Multibyte String Func?ii
PHP Manual

mb_encoding_aliases

(PHP 5 >= 5.3.0, PHP 7)

mb_encoding_aliases — Get aliases of a known encoding type

Descrierea

array mb_encoding_aliases ( string $encoding )

Returns an array of aliases for a known encoding type.

Parametri

encoding

The encoding type being checked, for aliases.

Valorile întoarse

Returns a numerically indexed array of encoding aliases on success, sau FALSE în cazul e?ecului

Erori/Excep?ii

Emits an E_WARNING level error if encoding is unknown.

Exemple

Example #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";

}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • mb_list_encodings() - Returns an array of all supported encodings

mb_encode_numericentity
mb_ereg_match
Multibyte String Func?ii


Regular expression match for multibyte string

mb_encoding_aliases
mb_ereg_replace_callback
Multibyte String Func?ii
PHP Manual

mb_ereg_match

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_match — Regular expression match for multibyte string

Descrierea

bool mb_ereg_match ( string $pattern , string $string [, string $option = "msr" ] )

A regular expression match for a multibyte string

Parametri

pattern

The regular expression pattern.

string

The string being evaluated.

option

Valorile întoarse

Returns TRUE if string matches the regular expression pattern, FALSE if not.

Note

Nota:

Codificarea interna a caracterelor sau codificarea caracterelor specificata de func?ia mb_regex_encoding() va fi utilizata în calitate de codificare a caracterelor pentru aceasta func?ie.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg() - Regular expression match with multibyte support

mb_encoding_aliases
mb_ereg_replace_callback
Multibyte String Func?ii


Perform a regular expresssion seach and replace with multibyte support using a callback

mb_ereg_match
mb_ereg_replace
Multibyte String Func?ii
PHP Manual

mb_ereg_replace_callback

(PHP 5 >= 5.4.1, PHP 7)

mb_ereg_replace_callback — Perform a regular expresssion seach and replace with multibyte support using a callback

Descrierea

string mb_ereg_replace_callback ( string $pattern , callable $callback , string $string [, string $option = "msr" ] )

Scans string for matches to pattern, then replaces the matched text with the output of callback function.

The behavior of this function is almost identical to mb_ereg_replace(), except for the fact that instead of replacement parameter, one should specify a callback.

Parametri

pattern

The regular expression pattern.

Multibyte characters may be used in pattern.

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 mb_ereg_replace_callback() in just one place. In this case you can use an anonymous function to declare the callback within the call to mb_ereg_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.

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. Note that e cannot be used for mb_ereg_replace_callback().

Valorile întoarse

The resultant string on success, or FALSE on error.

Note

Nota:

Codificarea interna a caracterelor sau codificarea caracterelor specificata de func?ia mb_regex_encoding() va fi utilizata în calitate de codificare a caracterelor pentru aceasta func?ie.

Exemple

Example #1 mb_ereg_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 mb_ereg_replace_callback(
            "(\d{2}/\d{2}/)(\d{4})",
            "next_year",
            $text);

?>

Exemplul de mai sus va afi?a:

April fools day is 04/01/2003
Last christmas was 12/24/2002

Example #2 mb_ereg_replace_callback() using anonymous function supported in PHP 5.3.0 or later

<?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";

echo mb_ereg_replace_callback(
            "(\d{2}/\d{2}/)(\d{4})",
            function ($matches) {
               return $matches[1].($matches[2]+1);
            },
            $text);
?>

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_replace() - Replace regular expression with multibyte support
  • Anonymous functions
  • informa?ie despre tipul callback

mb_ereg_match
mb_ereg_replace
Multibyte String Func?ii


Replace regular expression with multibyte support

mb_ereg_replace_callback
mb_ereg_search_getpos
Multibyte String Func?ii
PHP Manual

mb_ereg_replace

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_replace — Replace regular expression with multibyte support

Descrierea

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

Parametri

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.

Valorile întoarse

The resultant string on success, or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | The e modifier has been deprecated.

Note

Nota:

Codificarea interna a caracterelor sau codificarea caracterelor specificata de func?ia mb_regex_encoding() va fi utilizata în calitate de codificare a caracterelor pentru aceasta func?ie.

Avertizare

Niciodata nu utiliza?i modificatorul e când lucra?i cu date introduse ce nu provin din surse de încredere. Nu va avea loc evadarea automata (cum este cazul la preg_replace()). Ignorarea acestui fapt va crea probabil vulnerabilita?i de executare a codului la distan?a în aplica?ia dumneavoastra.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_eregi_replace() - Replace regular expression with multibyte support ignoring case

mb_ereg_replace_callback
mb_ereg_search_getpos
Multibyte String Func?ii


Returns start point for next regular expression match

mb_ereg_replace
mb_ereg_search_getregs
Multibyte String Func?ii
PHP Manual

mb_ereg_search_getpos

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_search_getpos — Returns start point for next regular expression match

Descrierea

int mb_ereg_search_getpos ( void )

Returns the start point for the next regular expression match.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Note

Nota:

Codificarea interna a caracterelor sau codificarea caracterelor specificata de func?ia mb_regex_encoding() va fi utilizata în calitate de codificare a caracterelor pentru aceasta func?ie.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_setpos() - Set start point of next regular expression match

mb_ereg_replace
mb_ereg_search_getregs
Multibyte String Func?ii


Retrieve the result from the last multibyte regular expression match

mb_ereg_search_getpos
mb_ereg_search_init
Multibyte String Func?ii
PHP Manual

mb_ereg_search_getregs

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match

Descrierea

array mb_ereg_search_getregs ( void )

Retrieve the result from the last multibyte regular expression match

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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;

Note

Nota:

Codificarea interna a caracterelor sau codificarea caracterelor specificata de func?ia mb_regex_encoding() va fi utilizata în calitate de codificare a caracterelor pentru aceasta func?ie.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • 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 Func?ii


Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_getregs
mb_ereg_search_pos
Multibyte String Func?ii
PHP Manual

mb_ereg_search_init

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match

Descrierea

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().

Parametri

string

The search string.

pattern

The search pattern.

option

The search option.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

Codificarea interna a caracterelor sau codificarea caracterelor specificata de func?ia mb_regex_encoding() va fi utilizata în calitate de codificare a caracterelor pentru aceasta func?ie.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_regs() - Returns the matched part of a multibyte regular expression

mb_ereg_search_getregs
mb_ereg_search_pos
Multibyte String Func?ii


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 Func?ii
PHP Manual

mb_ereg_search_pos

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

Descrierea

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.

Parametri

pattern

The search pattern.

option

The search option.

Valorile întoarse

An array containing two elements. The first element is the offset, in bytes, where the match begins relative to the start of the search string, and the second element is the length in bytes of the match.

If an error occurs, FALSE is returned.

Note

Nota:

Codificarea interna a caracterelor sau codificarea caracterelor specificata de func?ia mb_regex_encoding() va fi utilizata în calitate de codificare a caracterelor pentru aceasta func?ie.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • 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 Func?ii


Returns the matched part of a multibyte regular expression

mb_ereg_search_pos
mb_ereg_search_setpos
Multibyte String Func?ii
PHP Manual

mb_ereg_search_regs

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_search_regs — Returns the matched part of a multibyte regular expression

Descrierea

array mb_ereg_search_regs ([ string $pattern [, string $option = "ms" ]] )

Returns the matched part of a multibyte regular expression.

Parametri

pattern

The search pattern.

option

The search option.

Valorile întoarse

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.

Note

Nota:

Codificarea interna a caracterelor sau codificarea caracterelor specificata de func?ia mb_regex_encoding() va fi utilizata în calitate de codificare a caracterelor pentru aceasta func?ie.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • 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 Func?ii


Set start point of next regular expression match

mb_ereg_search_regs
mb_ereg_search
Multibyte String Func?ii
PHP Manual

mb_ereg_search_setpos

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_search_setpos — Set start point of next regular expression match

Descrierea

bool mb_ereg_search_setpos ( int $position )

mb_ereg_search_setpos() sets the starting point of a match for mb_ereg_search().

Parametri

position

The position to set. If it is negative, it counts from the end of the string.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Support for negative positions has been added.

Note

Nota:

Codificarea interna a caracterelor sau codificarea caracterelor specificata de func?ia mb_regex_encoding() va fi utilizata în calitate de codificare a caracterelor pentru aceasta func?ie.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_regs
mb_ereg_search
Multibyte String Func?ii


Multibyte regular expression match for predefined multibyte string

mb_ereg_search_setpos
mb_ereg
Multibyte String Func?ii
PHP Manual

mb_ereg_search

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_search — Multibyte regular expression match for predefined multibyte string

Descrierea

bool mb_ereg_search ([ string $pattern [, string $option = "ms" ]] )

Performs a multibyte regular expression match for a predefined multibyte string.

Parametri

pattern

The search pattern.

option

The search option.

Valorile întoarse

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.

Note

Nota:

Codificarea interna a caracterelor sau codificarea caracterelor specificata de func?ia mb_regex_encoding() va fi utilizata în calitate de codificare a caracterelor pentru aceasta func?ie.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_setpos
mb_ereg
Multibyte String Func?ii


Regular expression match with multibyte support

mb_ereg_search
mb_eregi_replace
Multibyte String Func?ii
PHP Manual

mb_ereg

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg — Regular expression match with multibyte support

Descrierea

int mb_ereg ( string $pattern , string $string [, array &$regs ] )

Executes the regular expression match with multibyte support.

Parametri

pattern

The search pattern.

string

The search 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. If no matches are found, regs is set to an empty array.

$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.

Valorile întoarse

Returns the byte 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.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | mb_ereg() will now set regs to an empty array, if nothing matched. Formerly, regs was not modified in that case.

Note

Nota:

Codificarea interna a caracterelor sau codificarea caracterelor specificata de func?ia mb_regex_encoding() va fi utilizata în calitate de codificare a caracterelor pentru aceasta func?ie.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_eregi() - Regular expression match ignoring case with multibyte support

mb_ereg_search
mb_eregi_replace
Multibyte String Func?ii


Replace regular expression with multibyte support ignoring case

mb_ereg
mb_eregi
Multibyte String Func?ii
PHP Manual

mb_eregi_replace

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_eregi_replace — Replace regular expression with multibyte support ignoring case

Descrierea

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.

Parametri

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().

Valorile întoarse

The resultant string or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | The e modifier has been deprecated.

Note

Nota:

Codificarea interna a caracterelor sau codificarea caracterelor specificata de func?ia mb_regex_encoding() va fi utilizata în calitate de codificare a caracterelor pentru aceasta func?ie.

Avertizare

Niciodata nu utiliza?i modificatorul e când lucra?i cu date introduse ce nu provin din surse de încredere. Nu va avea loc evadarea automata (cum este cazul la preg_replace()). Ignorarea acestui fapt va crea probabil vulnerabilita?i de executare a codului la distan?a în aplica?ia dumneavoastra.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_replace() - Replace regular expression with multibyte support

mb_ereg
mb_eregi
Multibyte String Func?ii


Regular expression match ignoring case with multibyte support

mb_eregi_replace
mb_get_info
Multibyte String Func?ii
PHP Manual

mb_eregi

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_eregi — Regular expression match ignoring case with multibyte support

Descrierea

int mb_eregi ( string $pattern , string $string [, array &$regs ] )

Executes the case insensitive regular expression match with multibyte support.

Parametri

pattern

The regular expression pattern.

string

The string being searched.

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. If no matches are found, regs is set to an empty array.

$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.

Valorile întoarse

Returns the byte 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.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | mb_eregi() will now set regs to an empty array, if nothing matched. Formerly, regs was not modified in that case.

Note

Nota:

Codificarea interna a caracterelor sau codificarea caracterelor specificata de func?ia mb_regex_encoding() va fi utilizata în calitate de codificare a caracterelor pentru aceasta func?ie.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg() - Regular expression match with multibyte support

mb_eregi_replace
mb_get_info
Multibyte String Func?ii


Get internal settings of mbstring

mb_eregi
mb_http_input
Multibyte String Func?ii
PHP Manual

mb_get_info

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_get_info — Get internal settings of mbstring

Descrierea

mixed mb_get_info ([ string $type = "all" ] )

mb_get_info() returns the internal setting parameters of mbstring.

Parametri

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.

Valorile întoarse

An array of type information if type is not specified, otherwise a specific type.

Istoricul schimbarilor

Versiune | Descriere
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.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_http_output() - Set/Get HTTP output character encoding

mb_eregi
mb_http_input
Multibyte String Func?ii


Detect HTTP input character encoding

mb_get_info
mb_http_output
Multibyte String Func?ii
PHP Manual

mb_http_input

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_http_input — Detect HTTP input character encoding

Descrierea

mixed mb_http_input ([ string $type = "" ] )

Detects the HTTP input character encoding.

Parametri

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.

Valorile întoarse

The character encoding name, as per the type. If mb_http_input() does not process specified HTTP input, it returns FALSE.

A se vedea ?i

  • 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 Func?ii


Set/Get HTTP output character encoding

mb_http_input
mb_internal_encoding
Multibyte String Func?ii
PHP Manual

mb_http_output

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_http_output — Set/Get HTTP output character encoding

Descrierea

mixed mb_http_output ([ string $encoding = mb_http_output() ] )

Set/Get the HTTP output character encoding. Output after this function is called will be converted from the set internal encoding to encoding.

Parametri

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.

Valorile întoarse

If encoding is omitted, mb_http_output() returns the current HTTP output character encoding. Otherwise, Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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 Func?ii


Set/Get internal character encoding

mb_http_output
mb_language
Multibyte String Func?ii
PHP Manual

mb_internal_encoding

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_internal_encoding — Set/Get internal character encoding

Descrierea

mixed mb_internal_encoding ([ string $encoding = mb_internal_encoding() ] )

Set/Get the internal character encoding

Parametri

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. You should notice that the internal encoding is totally different from the one for multibyte regex.

Valorile întoarse

If encoding is set, then Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. In this case, the character encoding for multibyte regex is NOT changed. If encoding is omitted, then the current character encoding name is returned.

Exemple

Example #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();
?>

A se vedea ?i

  • 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_regex_encoding() - Set/Get character encoding for multibyte regex

mb_http_output
mb_language
Multibyte String Func?ii


Set/Get current language

mb_internal_encoding
mb_list_encodings
Multibyte String Func?ii
PHP Manual

mb_language

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_language — Set/Get current language

Descrierea

mixed mb_language ([ string $language = mb_language() ] )

Set/Get the current language.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • mb_send_mail() - Send encoded mail

mb_internal_encoding
mb_list_encodings
Multibyte String Func?ii


Returns an array of all supported encodings

mb_language
mb_output_handler
Multibyte String Func?ii
PHP Manual

mb_list_encodings

(PHP 5, PHP 7)

mb_list_encodings — Returns an array of all supported encodings

Descrierea

array mb_list_encodings ( void )

Returns an array containing all supported encodings.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a numerically indexed array.

Erori/Excep?ii

This function does not emit any errors.

Exemple

Example #1 mb_list_encodings() example

<?php

print_r(mb_list_encodings());

?>

Exemplul de mai sus va afi?a ceva similar cu:

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 Func?ii


Callback function converts character encoding in output buffer

mb_list_encodings
mb_parse_str
Multibyte String Func?ii
PHP Manual

mb_output_handler

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_output_handler — Callback function converts character encoding in output buffer

Descrierea

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.

Parametri

contents

The contents of the output buffer.

status

The status of the output buffer.

Valorile întoarse

The converted string.

Istoricul schimbarilor

Versiune Descriere
4.1.0

This handler now adds the charset HTTP header when the following conditions are met:

  • Content-Type has not been set, using header().
  • The default MIME type begins with text/.
  • The mbstring.http_input setting is something other than pass.

Exemple

Example #1 mb_output_handler() example

<?php
mb_http_output("UTF-8");
ob_start("mb_output_handler");
?>

Note

Nota:

If you want to output binary data, such as an image, a Content-Type: header must be set using header() before any binary data is sent to the client (e.g. header("Content-Type: image/png")). If Content-Type: header is sent, output character encoding conversion will not be performed.

Note that if 'Content-Type: text/*' is sent, the content body is regarded as text; conversion will take place.

A se vedea ?i

  • ob_start() - Turn on output buffering

mb_list_encodings
mb_parse_str
Multibyte String Func?ii


Parse GET/POST/COOKIE data and set global variable

mb_output_handler
mb_preferred_mime_name
Multibyte String Func?ii
PHP Manual

mb_parse_str

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_parse_str — Parse GET/POST/COOKIE data and set global variable

Descrierea

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.

Parametri

encoded_string

The URL encoded data.

result

An array containing decoded and character encoded converted values.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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 Func?ii


Get MIME charset string

mb_parse_str
mb_regex_encoding
Multibyte String Func?ii
PHP Manual

mb_preferred_mime_name

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_preferred_mime_name — Get MIME charset string

Descrierea

string mb_preferred_mime_name ( string $encoding )

Get a MIME charset string for a specific encoding.

Parametri

encoding

The encoding being checked.

Valorile întoarse

The MIME charset string for character encoding encoding.

Exemple

Example #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 Func?ii


Set/Get character encoding for multibyte regex

mb_preferred_mime_name
mb_regex_set_options
Multibyte String Func?ii
PHP Manual

mb_regex_encoding

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_regex_encoding — Set/Get character encoding for multibyte regex

Descrierea

mixed mb_regex_encoding ([ string $encoding = mb_regex_encoding() ] )

Set/Get character encoding for a multibyte regex.

Parametri

encoding

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

If encoding is set, then Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. In this case, the internal character encoding is NOT changed. If encoding is omitted, then the current character encoding name for a multibyte regex is returned.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Default encoding is changed to UTF-8. It was EUC-JP Previously.

A se vedea ?i

  • 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 Func?ii


Set/Get the default options for mbregex functions

mb_regex_encoding
mb_send_mail
Multibyte String Func?ii
PHP Manual

mb_regex_set_options

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

mb_regex_set_options — Set/Get the default options for mbregex functions

Descrierea

string mb_regex_set_options ([ string $options = mb_regex_set_options() ] )

Sets the default options described by options for multibyte regex functions.

Parametri

options

The options to set. This is 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

Valorile întoarse

The previous options. If options is omitted, it returns the string that describes the current options.

A se vedea ?i

  • 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 Func?ii


Send encoded mail

mb_regex_set_options
mb_split
Multibyte String Func?ii
PHP Manual

mb_send_mail

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_send_mail — Send encoded mail

Descrierea

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.

Parametri

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 (optional)

String to be inserted at the end of the email header.

This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n). Validate parameter not to be injected unwanted headers by attackers.

Nota:

When sending mail, the mail must contain a From header. This can be set with the additional_headers parameter, or a default can be set in php.ini.

Failing to do this will result in an error message similar to Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing. The From header sets also Return-Path under Windows.

Nota:

If messages are not received, try using a LF (\n) only. Some Unix mail transfer agents (most notably » qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.

additional_parameter

additional_parameter is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.

This parameter is escaped by escapeshellcmd() internally to prevent command execution. escapeshellcmd() prevents command execution, but allows to add addtional parameters. For security reason, this parameter should be validated.

Since escapeshellcmd() is applied automatically, some characters that are allowed as email addresses by internet RFCs cannot be used. Programs that are required to use these characters mail() cannot be used.

The user that the webserver runs as should be added as a trusted user to the sendmail configuration to prevent a 'X-Warning' header from being added to the message when the envelope sender (-f) is set using this method. For sendmail users, this file is /etc/mail/trusted-users.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • mail() - Trimite mesaje e-mail
  • mb_encode_mimeheader() - Encode string for MIME header
  • mb_language() - Set/Get current language

mb_regex_set_options
mb_split
Multibyte String Func?ii


Split multibyte string using regular expression

mb_send_mail
mb_strcut
Multibyte String Func?ii
PHP Manual

mb_split

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_split — Split multibyte string using regular expression

Descrierea

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.

Parametri

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.

Valorile întoarse

The result as an array.

Note

Nota:

Codificarea caracterelor specificata de mb_regex_encoding() va fi utilizata implicit în calitate de codificare pentru aceasta func?ie.

A se vedea ?i

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg() - Regular expression match with multibyte support

mb_send_mail
mb_strcut
Multibyte String Func?ii


Get part of string

mb_split
mb_strimwidth
Multibyte String Func?ii
PHP Manual

mb_strcut

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_strcut — Get part of string

Descrierea

string mb_strcut ( string $str , int $start [, int $length = NULL [, string $encoding = mb_internal_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.

Parametri

str

The string being cut.

start

If start is non-negative, the returned string will start at the start'th byte position in str, counting from zero. For instance, in the string 'abcdef', the byte at position 0 is 'a', the byte at position 2 is 'c', and so forth.

If start is negative, the returned string will start at the start'th byte from the end of str.

length

Length in bytes. If omitted or NULL is passed, extract all bytes to the end of the string.

encoding

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

mb_strcut() returns the portion of str specified by the start and length parameters.

Istoricul schimbarilor

Versiune | Descriere
5.4.8 | Passing NULL as length extracts all bytes to the end of the string. Prior to this version NULL was treated the same as 0.

A se vedea ?i

  • mb_substr() - Get part of string
  • mb_internal_encoding() - Set/Get internal character encoding

mb_split
mb_strimwidth
Multibyte String Func?ii


Get truncated string with specified width

mb_strcut
mb_stripos
Multibyte String Func?ii
PHP Manual

mb_strimwidth

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_strimwidth — Get truncated string with specified width

Descrierea

string mb_strimwidth ( string $str , int $start , int $width [, string $trimmarker = "" [, string $encoding = mb_internal_encoding() ]] )

Truncates string str to specified width.

Parametri

str

The string being decoded.

start

The start position offset. Number of characters from the beginning of string (first character is 0), or if start is negative, number of characters from the end of the string.

width

The width of the desired trim. Negative widths count from the end of the string.

trimmarker

A string that is added to the end of string when string is truncated.

encoding

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

The truncated string. If trimmarker is set, trimmarker replaces the last chars to match the width.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Support for negative starts and widths has been added.

Exemple

Example #1 mb_strimwidth() example

<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
// output: "Hello W..."
?>

A se vedea ?i

  • mb_strwidth() - Return width of string
  • mb_internal_encoding() - Set/Get internal character encoding

mb_strcut
mb_stripos
Multibyte String Func?ii


Finds position of first occurrence of a string within another, case insensitive

mb_strimwidth
mb_stristr
Multibyte String Func?ii
PHP Manual

mb_stripos

(PHP 5 >= 5.2.0, PHP 7)

mb_stripos — Finds position of first occurrence of a string within another, case insensitive

Descrierea

int mb_stripos ( string $haystack , string $needle [, int $offset = 0 [, string $encoding = mb_internal_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.

Parametri

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. A negative offset counts from the end of the string.

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Valorile întoarse

Return the numeric position of the first occurrence of needle in the haystack string, or FALSE if needle is not found.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Support for negative offsets has been added.

A se vedea ?i

  • 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 Func?ii


Finds first occurrence of a string within another, case insensitive

mb_stripos
mb_strlen
Multibyte String Func?ii
PHP Manual

mb_stristr

(PHP 5 >= 5.2.0, PHP 7)

mb_stristr — Finds first occurrence of a string within another, case insensitive

Descrierea

string mb_stristr ( string $haystack , string $needle [, bool $before_needle = false [, string $encoding = mb_internal_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.

Parametri

haystack

The string from which to get the first occurrence of needle

needle

The string to find in haystack

before_needle

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 (excluding needle). If set to FALSE, it returns all of haystack from the first occurrence of needle to the end (including needle).

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Valorile întoarse

Returns the portion of haystack, or FALSE if needle is not found.

A se vedea ?i

  • 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 Func?ii


Get string length

mb_stristr
mb_strpos
Multibyte String Func?ii
PHP Manual

mb_strlen

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_strlen — Get string length

Descrierea

mixed mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] )

Gets the length of a string.

Parametri

str

The string being checked for length.

encoding

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

Returns the number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.

Returns FALSE if the given encoding is invalid.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

A se vedea ?i

  • mb_internal_encoding() - Set/Get internal character encoding
  • grapheme_strlen() - Get string length in grapheme units
  • iconv_strlen() - Returns the character count of string
  • strlen() - Get string length

mb_stristr
mb_strpos
Multibyte String Func?ii


Find position of first occurrence of string in a string

mb_strlen
mb_strrchr
Multibyte String Func?ii
PHP Manual

mb_strpos

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_strpos — Find position of first occurrence of string in a string

Descrierea

int mb_strpos ( string $haystack , string $needle [, int $offset = 0 [, string $encoding = mb_internal_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.

Parametri

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. A negative offset counts from the end of the string.

encoding

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

Returns the numeric position of the first occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Support for negative offsets has been added.

A se vedea ?i

  • 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 Func?ii


Finds the last occurrence of a character in a string within another

mb_strpos
mb_strrichr
Multibyte String Func?ii
PHP Manual

mb_strrchr

(PHP 5 >= 5.2.0, PHP 7)

mb_strrchr — Finds the last occurrence of a character in a string within another

Descrierea

string mb_strrchr ( string $haystack , string $needle [, bool $part = false [, string $encoding = mb_internal_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.

Parametri

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.

Valorile întoarse

Returns the portion of haystack. or FALSE if needle is not found.

A se vedea ?i

  • strrchr() - Find the last occurrence of a character in a string
  • 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 Func?ii


Finds the last occurrence of a character in a string within another, case insensitive

mb_strrchr
mb_strripos
Multibyte String Func?ii
PHP Manual

mb_strrichr

(PHP 5 >= 5.2.0, PHP 7)

mb_strrichr — Finds the last occurrence of a character in a string within another, case insensitive

Descrierea

string mb_strrichr ( string $haystack , string $needle [, bool $part = false [, string $encoding = mb_internal_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.

Parametri

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.

Valorile întoarse

Returns the portion of haystack. or FALSE if needle is not found.

A se vedea ?i

  • 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 Func?ii


Finds position of last occurrence of a string within another, case insensitive

mb_strrichr
mb_strrpos
Multibyte String Func?ii
PHP Manual

mb_strripos

(PHP 5 >= 5.2.0, PHP 7)

mb_strripos — Finds position of last occurrence of a string within another, case insensitive

Descrierea

int mb_strripos ( string $haystack , string $needle [, int $offset = 0 [, string $encoding = mb_internal_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.

Parametri

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.

Valorile întoarse

Return the numeric position of the last occurrence of needle in the haystack string, or FALSE if needle is not found.

A se vedea ?i

  • strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
  • strrpos() - Find the position of the last occurrence of a substring in a string
  • mb_strrpos() - Find position of last occurrence of a string in a string

mb_strrichr
mb_strrpos
Multibyte String Func?ii


Find position of last occurrence of a string in a string

mb_strripos
mb_strstr
Multibyte String Func?ii
PHP Manual

mb_strrpos

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_strrpos — Find position of last occurrence of a string in a string

Descrierea

int mb_strrpos ( string $haystack , string $needle [, int $offset = 0 [, string $encoding = mb_internal_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.

Parametri

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

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

Returns the numeric position of the last occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | Added the optional parameter offset.

Note

Nota: 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.

A se vedea ?i

  • mb_strpos() - Find position of first occurrence of string in a string
  • mb_internal_encoding() - Set/Get internal character encoding
  • strrpos() - Find the position of the last occurrence of a substring in a string

mb_strripos
mb_strstr
Multibyte String Func?ii


Finds first occurrence of a string within another

mb_strrpos
mb_strtolower
Multibyte String Func?ii
PHP Manual

mb_strstr

(PHP 5 >= 5.2.0, PHP 7)

mb_strstr — Finds first occurrence of a string within another

Descrierea

string mb_strstr ( string $haystack , string $needle [, bool $before_needle = false [, string $encoding = mb_internal_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.

Parametri

haystack

The string from which to get the first occurrence of needle

needle

The string to find in haystack

before_needle

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 (excluding needle). If set to FALSE, it returns all of haystack from the first occurrence of needle to the end (including needle).

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Valorile întoarse

Returns the portion of haystack, or FALSE if needle is not found.

A se vedea ?i

  • 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 Func?ii


Make a string lowercase

mb_strstr
mb_strtoupper
Multibyte String Func?ii
PHP Manual

mb_strtolower

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

mb_strtolower — Make a string lowercase

Descrierea

string mb_strtolower ( string $str [, string $encoding = mb_internal_encoding() ] )

Returns str with all alphabetic characters converted to lowercase.

Parametri

str

The string being lowercased.

encoding

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

str with all alphabetic characters converted to lowercase.

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 (Ä).

Exemple

Example #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
?>

Example #2 mb_strtolower() example with non-Latin UTF-8 text

<?php
$str = "????st? a??p?? ßaf?? ??µ??? ??, d?as?e???e? ?p?? ?????? ?????";
$str = mb_strtolower($str, 'UTF-8');
echo $str; // Prints t???st? a??p?? ßaf?? ??µ??? ??, d?as?e???e? ?p?? ?????? ?????
?>

A se vedea ?i

  • mb_strtoupper() - Make a string uppercase
  • mb_convert_case() - Perform case folding on a string
  • strtolower() - Make a string lowercase

mb_strstr
mb_strtoupper
Multibyte String Func?ii


Make a string uppercase

mb_strtolower
mb_strwidth
Multibyte String Func?ii
PHP Manual

mb_strtoupper

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

mb_strtoupper — Make a string uppercase

Descrierea

string mb_strtoupper ( string $str [, string $encoding = mb_internal_encoding() ] )

Returns str with all alphabetic characters converted to uppercase.

Parametri

str

The string being uppercased.

encoding

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

str with all alphabetic characters converted to uppercase.

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 (ä).

Exemple

Example #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
?>

Example #2 mb_strtoupper() example with non-Latin UTF-8 text

<?php
$str = "????st? a??p?? ßaf?? ??µ??? ??, d?as?e???e? ?p?? ?????? ?????";
$str = mb_strtoupper($str, 'UTF-8');
echo $str; // Prints ????S?? ?????? ??F?S ?????? G?, ???S??????? ???? ?OT??? ????S
?>

A se vedea ?i

  • mb_strtolower() - Make a string lowercase
  • mb_convert_case() - Perform case folding on a string
  • strtoupper() - Make a string uppercase

mb_strtolower
mb_strwidth
Multibyte String Func?ii


Return width of string

mb_strtoupper
mb_substitute_character
Multibyte String Func?ii
PHP Manual

mb_strwidth

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_strwidth — Return width of string

Descrierea

int mb_strwidth ( string $str [, string $encoding = mb_internal_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

Parametri

str

The string being decoded.

encoding

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

The width of string str.

A se vedea ?i

  • mb_strimwidth() - Get truncated string with specified width
  • mb_internal_encoding() - Set/Get internal character encoding

mb_strtoupper
mb_substitute_character
Multibyte String Func?ii


Set/Get substitution character

mb_strwidth
mb_substr_count
Multibyte String Func?ii
PHP Manual

mb_substitute_character

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_substitute_character — Set/Get substitution character

Descrierea

mixed mb_substitute_character ([ mixed $substrchar = mb_substitute_character() ] )

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().

Parametri

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: ?)

Valorile întoarse

If substchar is set, it returns TRUE for success, otherwise returns FALSE. If substchar is not set, it returns the current setting.

Exemple

Example #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 Func?ii


Count the number of substring occurrences

mb_substitute_character
mb_substr
Multibyte String Func?ii
PHP Manual

mb_substr_count

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

mb_substr_count — Count the number of substring occurrences

Descrierea

int mb_substr_count ( string $haystack , string $needle [, string $encoding = mb_internal_encoding() ] )

Counts the number of times the needle substring occurs in the haystack string.

Parametri

haystack

The string being checked.

needle

The string being found.

encoding

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

The number of times the needle substring occurs in the haystack string.

Exemple

Example #1 mb_substr_count() example

<?php
echo mb_substr_count("This is a test", "is"); // prints out 2
?>

A se vedea ?i

  • 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 Func?ii


Get part of string

mb_substr_count
Pspell
Multibyte String Func?ii
PHP Manual

mb_substr

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_substr — Get part of string

Descrierea

string mb_substr ( string $str , int $start [, int $length = NULL [, string $encoding = mb_internal_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.

Parametri

str

The string to extract the substring from.

start

If start is non-negative, the returned string will start at the start'th position in str, 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 str.

length

Maximum number of characters to use from str. If omitted or NULL is passed, extract all characters to the end of the string.

encoding

Parametrul encoding reprezinta codificarea caracterelor. Daca el este omis, va fi utilizata valoarea interna a codificarii caracterelor.

Valorile întoarse

mb_substr() returns the portion of str specified by the start and length parameters.

Istoricul schimbarilor

Versiune | Descriere
5.4.8 | Passing NULL as length extracts all characters to the end of the string. Prior to this version NULL was treated the same as 0.

A se vedea ?i

  • mb_strcut() - Get part of string
  • mb_internal_encoding() - Set/Get internal character encoding

mb_substr_count
Pspell
Multibyte String Func?ii


Pspell

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Pspell
    • 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
Introducere
Sus?inerea limbajului uman ?i a codificarii caracterelor


Introducere

Aceste func?ii va permit sa verifica?i corectitudinea ortografica a unui cuvânt ?i va ofera sugestii de corectare.

Pspell
Instalarea / configurarea
Pspell


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Pspell


Necesita?i

To compile PHP with pspell support, you need the aspell library, available from » http://aspell.net/.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

If you have the libraries needed add the --with-pspell[=dir] option when compiling PHP.

Nota: Note to Win32 Users

Pentru ca aceasta extensie sa func?ioneze, anumite fi?iere DLL trebuie sa fie accesibile în calea de sistem a Windows din variabila PATH. Pentru informa?ii despre cum poate fi realizat acest lucru, accesa?i FAQ întitulat " Cum sa adaug directorul meu PHP la variabila PATH din Windows" pentru informa?ii despre cum sa realiza?i aceasta. Cu toate ca copierea fi?ierelor DLL din directorul PHP în directorul de sistem al Windows de asemenea func?ioneaza (deoarece directorul de sistem este în mod implicit inclus în variabila PATH), acest lucru nu este recomandabil. Aceasta extensie necesita ca urmatoarele fi?iere sa existe în calea 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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

PSPELL_FAST (integer)
PSPELL_NORMAL (integer)
PSPELL_BAD_SPELLERS (integer)
PSPELL_RUN_TOGETHER (integer)
Tipurile resurselor
Func?ii Pspell
Pspell


Func?ii Pspell

Cuprins

  • 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
Constante predefinite
pspell_add_to_personal
Pspell


Add the word to a personal wordlist

Func?ii Pspell
pspell_add_to_session
Func?ii Pspell
PHP Manual

pspell_add_to_personal

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_add_to_personal — Add the word to a personal wordlist

Descrierea

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().

Parametri

dictionary_link

word

The added word.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Note

Nota:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Func?ii Pspell
pspell_add_to_session
Func?ii Pspell


Add the word to the wordlist in the current session

pspell_add_to_personal
pspell_check
Func?ii Pspell
PHP Manual

pspell_add_to_session

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_add_to_session — Add the word to the wordlist in the current session

Descrierea

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()

Parametri

dictionary_link

word

The added word.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

pspell_add_to_personal
pspell_check
Func?ii Pspell


Check a word

pspell_add_to_session
pspell_clear_session
Func?ii Pspell
PHP Manual

pspell_check

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_check — Check a word

Descrierea

bool pspell_check ( int $dictionary_link , string $word )

pspell_check() checks the spelling of a word.

Parametri

dictionary_link

word

The tested word.

Valorile întoarse

Returns TRUE if the spelling is correct, FALSE if not.

Exemple

Example #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
Func?ii Pspell


Clear the current session

pspell_check
pspell_config_create
Func?ii Pspell
PHP Manual

pspell_clear_session

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_clear_session — Clear the current session

Descrierea

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.

Parametri

dictionary_link

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii Pspell


Create a config used to open a dictionary

pspell_clear_session
pspell_config_data_dir
Func?ii Pspell
PHP Manual

pspell_config_create

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_create — Create a config used to open a dictionary

Descrierea

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/.

Parametri

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.

Valorile întoarse

Retuns a pspell config identifier, or FALSE on error.

Exemple

Example #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
Func?ii Pspell


location of language data files

pspell_config_create
pspell_config_dict_dir
Func?ii Pspell
PHP Manual

pspell_config_data_dir

(PHP 5, PHP 7)

pspell_config_data_dir — location of language data files

Descrierea

bool pspell_config_data_dir ( int $conf , string $directory )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

pspell_config_create
pspell_config_dict_dir
Func?ii Pspell


Location of the main word list

pspell_config_data_dir
pspell_config_ignore
Func?ii Pspell
PHP Manual

pspell_config_dict_dir

(PHP 5, PHP 7)

pspell_config_dict_dir — Location of the main word list

Descrierea

bool pspell_config_dict_dir ( int $conf , string $directory )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

pspell_config_data_dir
pspell_config_ignore
Func?ii Pspell


Ignore words less than N characters long

pspell_config_dict_dir
pspell_config_mode
Func?ii Pspell
PHP Manual

pspell_config_ignore

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_ignore — Ignore words less than N characters long

Descrierea

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.

Parametri

dictionary_link

n

Words less than n characters will be skipped.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii Pspell


Change the mode number of suggestions returned

pspell_config_ignore
pspell_config_personal
Func?ii Pspell
PHP Manual

pspell_config_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_mode — Change the mode number of suggestions returned

Descrierea

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().

Parametri

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)

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii Pspell


Set a file that contains personal wordlist

pspell_config_mode
pspell_config_repl
Func?ii Pspell
PHP Manual

pspell_config_personal

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_personal — Set a file that contains personal wordlist

Descrierea

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().

Parametri

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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");
?>

Note

Nota:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_config_mode
pspell_config_repl
Func?ii Pspell


Set a file that contains replacement pairs

pspell_config_personal
pspell_config_runtogether
Func?ii Pspell
PHP Manual

pspell_config_repl

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_repl — Set a file that contains replacement pairs

Descrierea

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().

Parametri

dictionary_link

file

The file should be writable by whoever PHP runs as (e.g. nobody).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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");
?>

Note

Nota:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_config_personal
pspell_config_runtogether
Func?ii Pspell


Consider run-together words as valid compounds

pspell_config_repl
pspell_config_save_repl
Func?ii Pspell
PHP Manual

pspell_config_runtogether

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_runtogether — Consider run-together words as valid compounds

Descrierea

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().

Parametri

dictionary_link

flag

TRUE if run-together words should be treated as legal compounds, FALSE otherwise.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii Pspell


Determine whether to save a replacement pairs list along with the wordlist

pspell_config_runtogether
pspell_new_config
Func?ii Pspell
PHP Manual

pspell_config_save_repl

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist

Descrierea

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().

Parametri

dictionary_link

flag

TRUE if replacement pairs should be saved, FALSE otherwise.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_config_runtogether
pspell_new_config
Func?ii Pspell


Load a new dictionary with settings based on a given config

pspell_config_save_repl
pspell_new_personal
Func?ii Pspell
PHP Manual

pspell_new_config

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_new_config — Load a new dictionary with settings based on a given config

Descrierea

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().

Parametri

config

The config parameter is the one returned by pspell_config_create() when the config was created.

Valorile întoarse

Returns a dictionary link identifier on success.

Exemple

Example #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
Func?ii Pspell


Load a new dictionary with personal wordlist

pspell_new_config
pspell_new
Func?ii Pspell
PHP Manual

pspell_new_personal

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_new_personal — Load a new dictionary with personal wordlist

Descrierea

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/.

Parametri

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.

Valorile întoarse

Returns the dictionary link identifier for use in other pspell functions.

Exemple

Example #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
Func?ii Pspell


Load a new dictionary

pspell_new_personal
pspell_save_wordlist
Func?ii Pspell
PHP Manual

pspell_new

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_new — Load a new dictionary

Descrierea

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/.

Parametri

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.

Valorile întoarse

Returns the dictionary link identifier on success sau FALSE în cazul e?ecului.

Exemple

Example #1 pspell_new()

<?php
$pspell_link = pspell_new("en", "", "", "",
                           (PSPELL_FAST|PSPELL_RUN_TOGETHER));
?>

pspell_new_personal
pspell_save_wordlist
Func?ii Pspell


Save the personal wordlist to a file

pspell_new
pspell_store_replacement
Func?ii Pspell
PHP Manual

pspell_save_wordlist

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_save_wordlist — Save the personal wordlist to a file

Descrierea

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().

Parametri

dictionary_link

A dictionary link identifier opened with pspell_new_personal().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Note

Nota:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_new
pspell_store_replacement
Func?ii Pspell


Store a replacement pair for a word

pspell_save_wordlist
pspell_suggest
Func?ii Pspell
PHP Manual

pspell_store_replacement

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_store_replacement — Store a replacement pair for a word

Descrierea

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.

Parametri

dictionary_link

A dictionary link identifier, opened with pspell_new_personal()

misspelled

The misspelled word.

correct

The fixed spelling for the misspelled word.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Note

Nota:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_save_wordlist
pspell_suggest
Func?ii Pspell


Suggest spellings of a word

pspell_store_replacement
Recode
Func?ii Pspell
PHP Manual

pspell_suggest

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_suggest — Suggest spellings of a word

Descrierea

array pspell_suggest ( int $dictionary_link , string $word )

pspell_suggest() returns an array of possible spellings for the given word.

Parametri

dictionary_link

word

The tested word.

Valorile întoarse

Returns an array of possible spellings.

Exemple

Example #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
Func?ii Pspell


GNU Recode

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Recode
    • recode_file — Recode from file to file according to recode request
    • recode_string — Recode a string according to a recode request
    • recode — Pseudonim pentru recode_string
pspell_suggest
Introducere
Sus?inerea limbajului uman ?i a codificarii caracterelor


Introducere

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.

Nota: Aceasta extensie nu este disponibila pe platformele Windows.

Recode
Instalarea / configurarea
Recode


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Recode


Necesita?i

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.

Avertizare

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

To be able to use the functions defined in this module you must compile your PHP interpreter using the --with-recode[=DIR] option.

Avertizare

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.

Avertizare

Extensiile IMAP, recode, YAZ ?i Cyrus nu pot fi utilizate împreuna, deoarece ele utilizeaza acelea?i simboluri interne. Nota: Yaz 2.0 ?i ulterior nu manifesta aceasta problema

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii Recode
Recode


Func?ii Recode

Cuprins

  • recode_file — Recode from file to file according to recode request
  • recode_string — Recode a string according to a recode request
  • recode — Pseudonim pentru recode_string
Constante predefinite
recode_file
Recode


Recode from file to file according to recode request

Func?ii Recode
recode_string
Func?ii Recode
PHP Manual

recode_file

(PHP 4, PHP 5, PHP 7)

recode_file — Recode from file to file according to recode request

Descrierea

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.

Parametri

request

The desired recode request type

input

A local file handle resource for the input

output

A local file handle resource for the output

Valorile întoarse

Returns FALSE, if unable to comply, TRUE otherwise.

Exemple

Example #1 Basic recode_file() example

<?php
$input = fopen('input.txt', 'r');
$output = fopen('output.txt', 'w');
recode_file("us..flat", $input, $output);
?>

Note

This function does not currently process file handles referencing remote files (URLs). Both file handles must refer to local files.

A se vedea ?i

  • fopen() - Opens file or URL

Func?ii Recode
recode_string
Func?ii Recode


Recode a string according to a recode request

recode_file
recode
Func?ii Recode
PHP Manual

recode_string

(PHP 4, PHP 5, PHP 7)

recode_string — Recode a string according to a recode request

Descrierea

string recode_string ( string $request , string $string )

Recode the string string according to the recode request request.

Parametri

request

The desired recode request type

string

The string to be recoded

Valorile întoarse

Returns the recoded string or FALSE, if unable to perform the recode request.

Exemple

Example #1 Basic recode_string() example

<?php
echo recode_string("us..flat", "The following character has a diacritical mark: á");
?>

Note

A simple recode request may be "lat1..iso646-de".

A se vedea ?i

  • The GNU Recode documentation of your installation for detailed instructions about recode requests.

recode_file
recode
Func?ii Recode


Pseudonim pentru recode_string

recode_string
Generarea ?i procesarea imaginilor
Func?ii Recode
PHP Manual

recode

(PHP 4, PHP 5, PHP 7)

recode — Pseudonim pentru recode_string()

Descrierea

Aceasta func?ie este pseudonim pentru: recode_string().

recode_string
Generarea ?i procesarea imaginilor
Func?ii Recode


Generarea ?i procesarea imaginilor

  • Cairo
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Cairo
    • 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
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Exif
  • GD — Image Processing and GD
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii GD ?i Image
  • Gmagick
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Gmagick — The Gmagick class
    • GmagickDraw — The GmagickDraw class
    • GmagickPixel — The GmagickPixel class
  • ImageMagick — Image Processing (ImageMagick)
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Imagick — The Imagick class
    • ImagickDraw — The ImagickDraw class
    • ImagickPixel — The ImagickPixel class
    • ImagickPixelIterator — The ImagickPixelIterator class
    • ImagickKernel — The ImagickKernel class
recode
Cairo
Informa?ii de referin?a despre func?ii


Cairo

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii Cairo
    • 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 — Pseudonim pentru CairoMatrix::initScale
    • cairo_matrix_create_translate — Pseudonim pentru 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
Generarea ?i procesarea imaginilor
Introducere
Generarea ?i procesarea imaginilor


Introducere

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
Instalarea / configurarea
Cairo


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Cairo


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/cairo.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)

Tipurile resurselor
Exemple
Cairo


Exemple

Descriere...

Example #1 Exemplu Cairo

<?php

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...
Constante predefinite
Func?ii Cairo
Cairo


Func?ii Cairo

Cuprins

  • 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 — Pseudonim pentru CairoMatrix::initScale
  • cairo_matrix_create_translate — Pseudonim pentru 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
Exemple
cairo_create
Cairo


Returns a new CairoContext object on the requested surface.

Func?ii Cairo
cairo_font_face_get_type
Func?ii Cairo
PHP Manual

cairo_create

(PECL cairo >= 0.1.0)

cairo_create — Returns a new CairoContext object on the requested surface.

Descrierea

CairoContext cairo_create ( CairoSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #1 cairo_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

Func?ii Cairo
cairo_font_face_get_type
Func?ii Cairo


Description

cairo_create
cairo_font_face_status
Func?ii Cairo
PHP Manual

cairo_font_face_get_type

(PECL cairo >= 0.1.0)

cairo_font_face_get_type — Description

Descrierea

int cairo_font_face_get_type ( CairoFontFace $fontface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

fontface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_create
cairo_font_face_status
Func?ii Cairo


Description

cairo_font_face_get_type
cairo_font_options_create
Func?ii Cairo
PHP Manual

cairo_font_face_status

(PECL cairo >= 0.1.0)

cairo_font_face_status — Description

Descrierea

int cairo_font_face_status ( CairoFontFace $fontface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

fontface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_face_get_type
cairo_font_options_create
Func?ii Cairo


Description

cairo_font_face_status
cairo_font_options_equal
Func?ii Cairo
PHP Manual

cairo_font_options_create

(PECL cairo >= 0.1.0)

cairo_font_options_create — Description

Descrierea

CairoFontOptions cairo_font_options_create ( void )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_face_status
cairo_font_options_equal
Func?ii Cairo


Description

cairo_font_options_create
cairo_font_options_get_antialias
Func?ii Cairo
PHP Manual

cairo_font_options_equal

(PECL cairo >= 0.1.0)

cairo_font_options_equal — Description

Descrierea

bool cairo_font_options_equal ( CairoFontOptions $options , CairoFontOptions $other )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

options

Description...

other

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_options_create
cairo_font_options_get_antialias
Func?ii Cairo


Description

cairo_font_options_equal
cairo_font_options_get_hint_metrics
Func?ii Cairo
PHP Manual

cairo_font_options_get_antialias

(PECL cairo >= 0.1.0)

cairo_font_options_get_antialias — Description

Descrierea

int cairo_font_options_get_antialias ( CairoFontOptions $options )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

options

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_options_equal
cairo_font_options_get_hint_metrics
Func?ii Cairo


Description

cairo_font_options_get_antialias
cairo_font_options_get_hint_style
Func?ii Cairo
PHP Manual

cairo_font_options_get_hint_metrics

(PECL cairo >= 0.1.0)

cairo_font_options_get_hint_metrics — Description

Descrierea

int cairo_font_options_get_hint_metrics ( CairoFontOptions $options )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

options

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_options_get_antialias
cairo_font_options_get_hint_style
Func?ii Cairo


Description

cairo_font_options_get_hint_metrics
cairo_font_options_get_subpixel_order
Func?ii Cairo
PHP Manual

cairo_font_options_get_hint_style

(PECL cairo >= 0.1.0)

cairo_font_options_get_hint_style — Description

Descrierea

int cairo_font_options_get_hint_style ( CairoFontOptions $options )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

options

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_options_get_hint_metrics
cairo_font_options_get_subpixel_order
Func?ii Cairo


Description

cairo_font_options_get_hint_style
cairo_font_options_hash
Func?ii Cairo
PHP Manual

cairo_font_options_get_subpixel_order

(PECL cairo >= 0.1.0)

cairo_font_options_get_subpixel_order — Description

Descrierea

int cairo_font_options_get_subpixel_order ( CairoFontOptions $options )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

options

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_options_get_hint_style
cairo_font_options_hash
Func?ii Cairo


Description

cairo_font_options_get_subpixel_order
cairo_font_options_merge
Func?ii Cairo
PHP Manual

cairo_font_options_hash

(PECL cairo >= 0.1.0)

cairo_font_options_hash — Description

Descrierea

int cairo_font_options_hash ( CairoFontOptions $options )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

options

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_options_get_subpixel_order
cairo_font_options_merge
Func?ii Cairo


Description

cairo_font_options_hash
cairo_font_options_set_antialias
Func?ii Cairo
PHP Manual

cairo_font_options_merge

(PECL cairo >= 0.1.0)

cairo_font_options_merge — Description

Descrierea

void cairo_font_options_merge ( CairoFontOptions $options , CairoFontOptions $other )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

options

Description...

other

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_options_hash
cairo_font_options_set_antialias
Func?ii Cairo


Description

cairo_font_options_merge
cairo_font_options_set_hint_metrics
Func?ii Cairo
PHP Manual

cairo_font_options_set_antialias

(PECL cairo >= 0.1.0)

cairo_font_options_set_antialias — Description

Descrierea

void cairo_font_options_set_antialias ( CairoFontOptions $options , int $antialias )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

options

Description...

antialias

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_options_merge
cairo_font_options_set_hint_metrics
Func?ii Cairo


Description

cairo_font_options_set_antialias
cairo_font_options_set_hint_style
Func?ii Cairo
PHP Manual

cairo_font_options_set_hint_metrics

(PECL cairo >= 0.1.0)

cairo_font_options_set_hint_metrics — Description

Descrierea

void cairo_font_options_set_hint_metrics ( CairoFontOptions $options , int $hint_metrics )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

options

Description...

hint_metrics

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_options_set_antialias
cairo_font_options_set_hint_style
Func?ii Cairo


Description

cairo_font_options_set_hint_metrics
cairo_font_options_set_subpixel_order
Func?ii Cairo
PHP Manual

cairo_font_options_set_hint_style

(PECL cairo >= 0.1.0)

cairo_font_options_set_hint_style — Description

Descrierea

void cairo_font_options_set_hint_style ( CairoFontOptions $options , int $hint_style )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

options

Description...

hint_style

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_options_set_hint_metrics
cairo_font_options_set_subpixel_order
Func?ii Cairo


Description

cairo_font_options_set_hint_style
cairo_font_options_status
Func?ii Cairo
PHP Manual

cairo_font_options_set_subpixel_order

(PECL cairo >= 0.1.0)

cairo_font_options_set_subpixel_order — Description

Descrierea

void cairo_font_options_set_subpixel_order ( CairoFontOptions $options , int $subpixel_order )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

options

Description...

subpixel_order

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_options_set_hint_style
cairo_font_options_status
Func?ii Cairo


Description

cairo_font_options_set_subpixel_order
cairo_format_stride_for_width
Func?ii Cairo
PHP Manual

cairo_font_options_status

(PECL cairo >= 0.1.0)

cairo_font_options_status — Description

Descrierea

int cairo_font_options_status ( CairoFontOptions $options )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

options

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_options_set_subpixel_order
cairo_format_stride_for_width
Func?ii Cairo


Description

cairo_font_options_status
cairo_image_surface_create_for_data
Func?ii Cairo
PHP Manual

cairo_format_stride_for_width

(PECL cairo >= 0.1.0)

cairo_format_stride_for_width — Description

Descrierea

int cairo_format_stride_for_width ( int $format , int $width )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

format

Description...

width

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_font_options_status
cairo_image_surface_create_for_data
Func?ii Cairo


Description

cairo_format_stride_for_width
cairo_image_surface_create_from_png
Func?ii Cairo
PHP Manual

cairo_image_surface_create_for_data

(PECL cairo >= 0.1.0)

cairo_image_surface_create_for_data — Description

Descrierea

CairoImageSurface cairo_image_surface_create_for_data ( string $data , int $format , int $width , int $height [, int $stride = -1 ] )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

data

Description...

format

Description...

width

Description...

height

Description...

stride

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_format_stride_for_width
cairo_image_surface_create_from_png
Func?ii Cairo


Description

cairo_image_surface_create_for_data
cairo_image_surface_create
Func?ii Cairo
PHP Manual

cairo_image_surface_create_from_png

(PECL cairo >= 0.1.0)

cairo_image_surface_create_from_png — Description

Descrierea

CairoImageSurface cairo_image_surface_create_from_png ( string $file )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

file

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_image_surface_create_for_data
cairo_image_surface_create
Func?ii Cairo


Description

cairo_image_surface_create_from_png
cairo_image_surface_get_data
Func?ii Cairo
PHP Manual

cairo_image_surface_create

(PECL cairo >= 0.1.0)

cairo_image_surface_create — Description

Descrierea

CairoImageSurface cairo_image_surface_create ( int $format , int $width , int $height )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

format

Description...

width

Description...

height

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_image_surface_create_from_png
cairo_image_surface_get_data
Func?ii Cairo


Description

cairo_image_surface_create
cairo_image_surface_get_format
Func?ii Cairo
PHP Manual

cairo_image_surface_get_data

(PECL cairo >= 0.1.0)

cairo_image_surface_get_data — Description

Descrierea

string cairo_image_surface_get_data ( CairoImageSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_image_surface_create
cairo_image_surface_get_format
Func?ii Cairo


Description

cairo_image_surface_get_data
cairo_image_surface_get_height
Func?ii Cairo
PHP Manual

cairo_image_surface_get_format

(PECL cairo >= 0.1.0)

cairo_image_surface_get_format — Description

Descrierea

int cairo_image_surface_get_format ( CairoImageSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_image_surface_get_data
cairo_image_surface_get_height
Func?ii Cairo


Description

cairo_image_surface_get_format
cairo_image_surface_get_stride
Func?ii Cairo
PHP Manual

cairo_image_surface_get_height

(PECL cairo >= 0.1.0)

cairo_image_surface_get_height — Description

Descrierea

int cairo_image_surface_get_height ( CairoImageSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_image_surface_get_format
cairo_image_surface_get_stride
Func?ii Cairo


Description

cairo_image_surface_get_height
cairo_image_surface_get_width
Func?ii Cairo
PHP Manual

cairo_image_surface_get_stride

(PECL cairo >= 0.1.0)

cairo_image_surface_get_stride — Description

Descrierea

int cairo_image_surface_get_stride ( CairoImageSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_image_surface_get_height
cairo_image_surface_get_width
Func?ii Cairo


Description

cairo_image_surface_get_stride
cairo_matrix_create_scale
Func?ii Cairo
PHP Manual

cairo_image_surface_get_width

(PECL cairo >= 0.1.0)

cairo_image_surface_get_width — Description

Descrierea

int cairo_image_surface_get_width ( CairoImageSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_image_surface_get_stride
cairo_matrix_create_scale
Func?ii Cairo


Pseudonim pentru CairoMatrix::initScale

cairo_image_surface_get_width
cairo_matrix_create_translate
Func?ii Cairo
PHP Manual

cairo_matrix_create_scale

(PECL cairo >= 0.1.0)

cairo_matrix_create_scale — Pseudonim pentru CairoMatrix::initScale()

Descrierea

Aceasta func?ie este pseudonim pentru: CairoMatrix::initScale().

Acest pseudonim al func?iei este învechit ?i exista numai din motivul pastrarii compatibilita?ii cu versiunile anterioare. Utilizarea acestei func?ii nu este recomandata, deoarece ea poate fi eliminata din PHP în viitor.

cairo_image_surface_get_width
cairo_matrix_create_translate
Func?ii Cairo


Pseudonim pentru CairoMatrix::initTranslate

cairo_matrix_create_scale
cairo_matrix_invert
Func?ii Cairo
PHP Manual

cairo_matrix_create_translate

(PECL cairo >= 0.1.0)

cairo_matrix_create_translate — Pseudonim pentru CairoMatrix::initTranslate()

Descrierea

Aceasta func?ie este pseudonim pentru: CairoMatrix::initTranslate().

Acest pseudonim al func?iei este învechit ?i exista numai din motivul pastrarii compatibilita?ii cu versiunile anterioare. Utilizarea acestei func?ii nu este recomandata, deoarece ea poate fi eliminata din PHP în viitor.

cairo_matrix_create_scale
cairo_matrix_invert
Func?ii Cairo


Description

cairo_matrix_create_translate
cairo_matrix_multiply
Func?ii Cairo
PHP Manual

cairo_matrix_invert

(PECL cairo >= 0.1.0)

cairo_matrix_invert — Description

Descrierea

void cairo_matrix_invert ( CairoMatrix $matrix )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

matrix

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_matrix_create_translate
cairo_matrix_multiply
Func?ii Cairo


Description

cairo_matrix_invert
cairo_matrix_rotate
Func?ii Cairo
PHP Manual

cairo_matrix_multiply

(PECL cairo >= 0.1.0)

cairo_matrix_multiply — Description

Descrierea

CairoMatrix cairo_matrix_multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

matrix1

Description...

matrix2

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_matrix_invert
cairo_matrix_rotate
Func?ii Cairo


Description

cairo_matrix_multiply
cairo_matrix_transform_distance
Func?ii Cairo
PHP Manual

cairo_matrix_rotate

(PECL cairo >= 0.1.0)

cairo_matrix_rotate — Description

Descrierea

void cairo_matrix_rotate ( CairoMatrix $matrix , float $radians )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

matrix

Description...

radians

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_matrix_multiply
cairo_matrix_transform_distance
Func?ii Cairo


Description

cairo_matrix_rotate
cairo_matrix_transform_point
Func?ii Cairo
PHP Manual

cairo_matrix_transform_distance

(PECL cairo >= 0.1.0)

cairo_matrix_transform_distance — Description

Descrierea

array cairo_matrix_transform_distance ( CairoMatrix $matrix , float $dx , float $dy )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

matrix

Description...

dx

Description...

dy

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_matrix_rotate
cairo_matrix_transform_point
Func?ii Cairo


Description

cairo_matrix_transform_distance
cairo_matrix_translate
Func?ii Cairo
PHP Manual

cairo_matrix_transform_point

(PECL cairo >= 0.1.0)

cairo_matrix_transform_point — Description

Descrierea

array cairo_matrix_transform_point ( CairoMatrix $matrix , float $dx , float $dy )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

matrix

Description...

dx

Description...

dy

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_matrix_transform_distance
cairo_matrix_translate
Func?ii Cairo


Description

cairo_matrix_transform_point
cairo_pattern_add_color_stop_rgb
Func?ii Cairo
PHP Manual

cairo_matrix_translate

(PECL cairo >= 0.1.0)

cairo_matrix_translate — Description

Descrierea

void cairo_matrix_translate ( CairoMatrix $matrix , float $tx , float $ty )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

matrix

Description...

tx

Description...

ty

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_matrix_transform_point
cairo_pattern_add_color_stop_rgb
Func?ii Cairo


Description

cairo_matrix_translate
cairo_pattern_add_color_stop_rgba
Func?ii Cairo
PHP Manual

cairo_pattern_add_color_stop_rgb

(PECL cairo >= 0.1.0)

cairo_pattern_add_color_stop_rgb — Description

Descrierea

void cairo_pattern_add_color_stop_rgb ( CairoGradientPattern $pattern , float $offset , float $red , float $green , float $blue )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

offset

Description...

red

Description...

green

Description...

blue

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_matrix_translate
cairo_pattern_add_color_stop_rgba
Func?ii Cairo


Description

cairo_pattern_add_color_stop_rgb
cairo_pattern_create_for_surface
Func?ii Cairo
PHP Manual

cairo_pattern_add_color_stop_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_add_color_stop_rgba — Description

Descrierea

void cairo_pattern_add_color_stop_rgba ( CairoGradientPattern $pattern , float $offset , float $red , float $green , float $blue , float $alpha )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

offset

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_add_color_stop_rgb
cairo_pattern_create_for_surface
Func?ii Cairo


Description

cairo_pattern_add_color_stop_rgba
cairo_pattern_create_linear
Func?ii Cairo
PHP Manual

cairo_pattern_create_for_surface

(PECL cairo >= 0.1.0)

cairo_pattern_create_for_surface — Description

Descrierea

CairoPattern cairo_pattern_create_for_surface ( CairoSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_add_color_stop_rgba
cairo_pattern_create_linear
Func?ii Cairo


Description

cairo_pattern_create_for_surface
cairo_pattern_create_radial
Func?ii Cairo
PHP Manual

cairo_pattern_create_linear

(PECL cairo >= 0.1.0)

cairo_pattern_create_linear — Description

Descrierea

CairoPattern cairo_pattern_create_linear ( float $x0 , float $y0 , float $x1 , float $y1 )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x0

Description...

y0

Description...

x1

Description...

y1

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_create_for_surface
cairo_pattern_create_radial
Func?ii Cairo


Description

cairo_pattern_create_linear
cairo_pattern_create_rgb
Func?ii Cairo
PHP Manual

cairo_pattern_create_radial

(PECL cairo >= 0.1.0)

cairo_pattern_create_radial — Description

Descrierea

CairoPattern cairo_pattern_create_radial ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x0

Description...

y0

Description...

r0

Description...

x1

Description...

y1

Description...

r1

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_create_linear
cairo_pattern_create_rgb
Func?ii Cairo


Description

cairo_pattern_create_radial
cairo_pattern_create_rgba
Func?ii Cairo
PHP Manual

cairo_pattern_create_rgb

(PECL cairo >= 0.1.0)

cairo_pattern_create_rgb — Description

Descrierea

CairoPattern cairo_pattern_create_rgb ( float $red , float $green , float $blue )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

red

Description...

green

Description...

blue

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_create_radial
cairo_pattern_create_rgba
Func?ii Cairo


Description

cairo_pattern_create_rgb
cairo_pattern_get_color_stop_count
Func?ii Cairo
PHP Manual

cairo_pattern_create_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_create_rgba — Description

Descrierea

CairoPattern cairo_pattern_create_rgba ( float $red , float $green , float $blue , float $alpha )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

red

Description...

green

Description...

blue

Description...

alpha

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_create_rgb
cairo_pattern_get_color_stop_count
Func?ii Cairo


Description

cairo_pattern_create_rgba
cairo_pattern_get_color_stop_rgba
Func?ii Cairo
PHP Manual

cairo_pattern_get_color_stop_count

(PECL cairo >= 0.1.0)

cairo_pattern_get_color_stop_count — Description

Descrierea

int cairo_pattern_get_color_stop_count ( CairoGradientPattern $pattern )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_create_rgba
cairo_pattern_get_color_stop_rgba
Func?ii Cairo


Description

cairo_pattern_get_color_stop_count
cairo_pattern_get_extend
Func?ii Cairo
PHP Manual

cairo_pattern_get_color_stop_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_get_color_stop_rgba — Description

Descrierea

array cairo_pattern_get_color_stop_rgba ( CairoGradientPattern $pattern , int $index )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

index

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_get_color_stop_count
cairo_pattern_get_extend
Func?ii Cairo


Description

cairo_pattern_get_color_stop_rgba
cairo_pattern_get_filter
Func?ii Cairo
PHP Manual

cairo_pattern_get_extend

(PECL cairo >= 0.1.0)

cairo_pattern_get_extend — Description

Descrierea

int cairo_pattern_get_extend ( string $pattern )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_get_color_stop_rgba
cairo_pattern_get_filter
Func?ii Cairo


Description

cairo_pattern_get_extend
cairo_pattern_get_linear_points
Func?ii Cairo
PHP Manual

cairo_pattern_get_filter

(PECL cairo >= 0.1.0)

cairo_pattern_get_filter — Description

Descrierea

int cairo_pattern_get_filter ( CairoSurfacePattern $pattern )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_get_extend
cairo_pattern_get_linear_points
Func?ii Cairo


Description

cairo_pattern_get_filter
cairo_pattern_get_matrix
Func?ii Cairo
PHP Manual

cairo_pattern_get_linear_points

(PECL cairo >= 0.1.0)

cairo_pattern_get_linear_points — Description

Descrierea

array cairo_pattern_get_linear_points ( CairoLinearGradient $pattern )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_get_filter
cairo_pattern_get_matrix
Func?ii Cairo


Description

cairo_pattern_get_linear_points
cairo_pattern_get_radial_circles
Func?ii Cairo
PHP Manual

cairo_pattern_get_matrix

(PECL cairo >= 0.1.0)

cairo_pattern_get_matrix — Description

Descrierea

CairoMatrix cairo_pattern_get_matrix ( CairoPattern $pattern )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_get_linear_points
cairo_pattern_get_radial_circles
Func?ii Cairo


Description

cairo_pattern_get_matrix
cairo_pattern_get_rgba
Func?ii Cairo
PHP Manual

cairo_pattern_get_radial_circles

(PECL cairo >= 0.1.0)

cairo_pattern_get_radial_circles — Description

Descrierea

array cairo_pattern_get_radial_circles ( CairoRadialGradient $pattern )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_get_matrix
cairo_pattern_get_rgba
Func?ii Cairo


Description

cairo_pattern_get_radial_circles
cairo_pattern_get_surface
Func?ii Cairo
PHP Manual

cairo_pattern_get_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_get_rgba — Description

Descrierea

array cairo_pattern_get_rgba ( CairoSolidPattern $pattern )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_get_radial_circles
cairo_pattern_get_surface
Func?ii Cairo


Description

cairo_pattern_get_rgba
cairo_pattern_get_type
Func?ii Cairo
PHP Manual

cairo_pattern_get_surface

(PECL cairo >= 0.1.0)

cairo_pattern_get_surface — Description

Descrierea

CairoSurface cairo_pattern_get_surface ( CairoSurfacePattern $pattern )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_get_rgba
cairo_pattern_get_type
Func?ii Cairo


Description

cairo_pattern_get_surface
cairo_pattern_set_extend
Func?ii Cairo
PHP Manual

cairo_pattern_get_type

(PECL cairo >= 0.1.0)

cairo_pattern_get_type — Description

Descrierea

int cairo_pattern_get_type ( CairoPattern $pattern )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_get_surface
cairo_pattern_set_extend
Func?ii Cairo


Description

cairo_pattern_get_type
cairo_pattern_set_filter
Func?ii Cairo
PHP Manual

cairo_pattern_set_extend

(PECL cairo >= 0.1.0)

cairo_pattern_set_extend — Description

Descrierea

void cairo_pattern_set_extend ( string $pattern , string $extend )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

extend

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_get_type
cairo_pattern_set_filter
Func?ii Cairo


Description

cairo_pattern_set_extend
cairo_pattern_set_matrix
Func?ii Cairo
PHP Manual

cairo_pattern_set_filter

(PECL cairo >= 0.1.0)

cairo_pattern_set_filter — Description

Descrierea

void cairo_pattern_set_filter ( CairoSurfacePattern $pattern , int $filter )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

filter

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_set_extend
cairo_pattern_set_matrix
Func?ii Cairo


Description

cairo_pattern_set_filter
cairo_pattern_status
Func?ii Cairo
PHP Manual

cairo_pattern_set_matrix

(PECL cairo >= 0.1.0)

cairo_pattern_set_matrix — Description

Descrierea

void cairo_pattern_set_matrix ( CairoPattern $pattern , CairoMatrix $matrix )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

matrix

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_set_filter
cairo_pattern_status
Func?ii Cairo


Description

cairo_pattern_set_matrix
cairo_pdf_surface_create
Func?ii Cairo
PHP Manual

cairo_pattern_status

(PECL cairo >= 0.1.0)

cairo_pattern_status — Description

Descrierea

int cairo_pattern_status ( CairoPattern $pattern )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pattern

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_set_matrix
cairo_pdf_surface_create
Func?ii Cairo


Description

cairo_pattern_status
cairo_pdf_surface_set_size
Func?ii Cairo
PHP Manual

cairo_pdf_surface_create

(PECL cairo >= 0.1.0)

cairo_pdf_surface_create — Description

Descrierea

CairoPdfSurface cairo_pdf_surface_create ( string $file , float $width , float $height )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

file

Description...

width

Description...

height

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pattern_status
cairo_pdf_surface_set_size
Func?ii Cairo


Description

cairo_pdf_surface_create
cairo_ps_get_levels
Func?ii Cairo
PHP Manual

cairo_pdf_surface_set_size

(PECL cairo >= 0.1.0)

cairo_pdf_surface_set_size — Description

Descrierea

void cairo_pdf_surface_set_size ( CairoPdfSurface $surface , float $width , float $height )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

width

Description...

height

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pdf_surface_create
cairo_ps_get_levels
Func?ii Cairo


Description

cairo_pdf_surface_set_size
cairo_ps_level_to_string
Func?ii Cairo
PHP Manual

cairo_ps_get_levels

(PECL cairo >= 0.1.0)

cairo_ps_get_levels — Description

Descrierea

array cairo_ps_get_levels ( void )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_pdf_surface_set_size
cairo_ps_level_to_string
Func?ii Cairo


Description

cairo_ps_get_levels
cairo_ps_surface_create
Func?ii Cairo
PHP Manual

cairo_ps_level_to_string

(PECL cairo >= 0.1.0)

cairo_ps_level_to_string — Description

Descrierea

string cairo_ps_level_to_string ( int $level )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

level

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_ps_get_levels
cairo_ps_surface_create
Func?ii Cairo


Description

cairo_ps_level_to_string
cairo_ps_surface_dsc_begin_page_setup
Func?ii Cairo
PHP Manual

cairo_ps_surface_create

(PECL cairo >= 0.1.0)

cairo_ps_surface_create — Description

Descrierea

CairoPsSurface cairo_ps_surface_create ( string $file , float $width , float $height )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

file

Description...

width

Description...

height

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_ps_level_to_string
cairo_ps_surface_dsc_begin_page_setup
Func?ii Cairo


Description

cairo_ps_surface_create
cairo_ps_surface_dsc_begin_setup
Func?ii Cairo
PHP Manual

cairo_ps_surface_dsc_begin_page_setup

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_begin_page_setup — Description

Descrierea

void cairo_ps_surface_dsc_begin_page_setup ( CairoPsSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_ps_surface_create
cairo_ps_surface_dsc_begin_setup
Func?ii Cairo


Description

cairo_ps_surface_dsc_begin_page_setup
cairo_ps_surface_dsc_comment
Func?ii Cairo
PHP Manual

cairo_ps_surface_dsc_begin_setup

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_begin_setup — Description

Descrierea

void cairo_ps_surface_dsc_begin_setup ( CairoPsSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_ps_surface_dsc_begin_page_setup
cairo_ps_surface_dsc_comment
Func?ii Cairo


Description

cairo_ps_surface_dsc_begin_setup
cairo_ps_surface_get_eps
Func?ii Cairo
PHP Manual

cairo_ps_surface_dsc_comment

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_comment — Description

Descrierea

void cairo_ps_surface_dsc_comment ( CairoPsSurface $surface , string $comment )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

comment

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_ps_surface_dsc_begin_setup
cairo_ps_surface_get_eps
Func?ii Cairo


Description

cairo_ps_surface_dsc_comment
cairo_ps_surface_restrict_to_level
Func?ii Cairo
PHP Manual

cairo_ps_surface_get_eps

(PECL cairo >= 0.1.0)

cairo_ps_surface_get_eps — Description

Descrierea

bool cairo_ps_surface_get_eps ( CairoPsSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_ps_surface_dsc_comment
cairo_ps_surface_restrict_to_level
Func?ii Cairo


Description

cairo_ps_surface_get_eps
cairo_ps_surface_set_eps
Func?ii Cairo
PHP Manual

cairo_ps_surface_restrict_to_level

(PECL cairo >= 0.1.0)

cairo_ps_surface_restrict_to_level — Description

Descrierea

void cairo_ps_surface_restrict_to_level ( CairoPsSurface $surface , int $level )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

level

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_ps_surface_get_eps
cairo_ps_surface_set_eps
Func?ii Cairo


Description

cairo_ps_surface_restrict_to_level
cairo_ps_surface_set_size
Func?ii Cairo
PHP Manual

cairo_ps_surface_set_eps

(PECL cairo >= 0.1.0)

cairo_ps_surface_set_eps — Description

Descrierea

void cairo_ps_surface_set_eps ( CairoPsSurface $surface , bool $level )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

level

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_ps_surface_restrict_to_level
cairo_ps_surface_set_size
Func?ii Cairo


Description

cairo_ps_surface_set_eps
cairo_scaled_font_create
Func?ii Cairo
PHP Manual

cairo_ps_surface_set_size

(PECL cairo >= 0.1.0)

cairo_ps_surface_set_size — Description

Descrierea

void cairo_ps_surface_set_size ( CairoPsSurface $surface , float $width , float $height )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

width

Description...

height

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_ps_surface_set_eps
cairo_scaled_font_create
Func?ii Cairo


Description

cairo_ps_surface_set_size
cairo_scaled_font_extents
Func?ii Cairo
PHP Manual

cairo_scaled_font_create

(PECL cairo >= 0.1.0)

cairo_scaled_font_create — Description

Descrierea

CairoScaledFont cairo_scaled_font_create ( CairoFontFace $fontface , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $fontoptions )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

fontface

Description...

matrix

Description...

ctm

Description...

fontoptions

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_ps_surface_set_size
cairo_scaled_font_extents
Func?ii Cairo


Description

cairo_scaled_font_create
cairo_scaled_font_get_ctm
Func?ii Cairo
PHP Manual

cairo_scaled_font_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_extents — Description

Descrierea

array cairo_scaled_font_extents ( CairoScaledFont $scaledfont )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

scaledfont

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_scaled_font_create
cairo_scaled_font_get_ctm
Func?ii Cairo


Description

cairo_scaled_font_extents
cairo_scaled_font_get_font_face
Func?ii Cairo
PHP Manual

cairo_scaled_font_get_ctm

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_ctm — Description

Descrierea

CairoMatrix cairo_scaled_font_get_ctm ( CairoScaledFont $scaledfont )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

scaledfont

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_scaled_font_extents
cairo_scaled_font_get_font_face
Func?ii Cairo


Description

cairo_scaled_font_get_ctm
cairo_scaled_font_get_font_matrix
Func?ii Cairo
PHP Manual

cairo_scaled_font_get_font_face

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_face — Description

Descrierea

CairoFontFace cairo_scaled_font_get_font_face ( CairoScaledFont $scaledfont )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

scaledfont

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_scaled_font_get_ctm
cairo_scaled_font_get_font_matrix
Func?ii Cairo


Description

cairo_scaled_font_get_font_face
cairo_scaled_font_get_font_options
Func?ii Cairo
PHP Manual

cairo_scaled_font_get_font_matrix

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_matrix — Description

Descrierea

CairoFontOptions cairo_scaled_font_get_font_matrix ( CairoScaledFont $scaledfont )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

scaledfont

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_scaled_font_get_font_face
cairo_scaled_font_get_font_options
Func?ii Cairo


Description

cairo_scaled_font_get_font_matrix
cairo_scaled_font_get_scale_matrix
Func?ii Cairo
PHP Manual

cairo_scaled_font_get_font_options

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_options — Description

Descrierea

CairoFontOptions cairo_scaled_font_get_font_options ( CairoScaledFont $scaledfont )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

scaledfont

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_scaled_font_get_font_matrix
cairo_scaled_font_get_scale_matrix
Func?ii Cairo


Description

cairo_scaled_font_get_font_options
cairo_scaled_font_get_type
Func?ii Cairo
PHP Manual

cairo_scaled_font_get_scale_matrix

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_scale_matrix — Description

Descrierea

CairoMatrix cairo_scaled_font_get_scale_matrix ( CairoScaledFont $scaledfont )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

scaledfont

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_scaled_font_get_font_options
cairo_scaled_font_get_type
Func?ii Cairo


Description

cairo_scaled_font_get_scale_matrix
cairo_scaled_font_glyph_extents
Func?ii Cairo
PHP Manual

cairo_scaled_font_get_type

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_type — Description

Descrierea

int cairo_scaled_font_get_type ( CairoScaledFont $scaledfont )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

scaledfont

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_scaled_font_get_scale_matrix
cairo_scaled_font_glyph_extents
Func?ii Cairo


Description

cairo_scaled_font_get_type
cairo_scaled_font_status
Func?ii Cairo
PHP Manual

cairo_scaled_font_glyph_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_glyph_extents — Description

Descrierea

array cairo_scaled_font_glyph_extents ( CairoScaledFont $scaledfont , array $glyphs )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

scaledfont

Description...

glyphs

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_scaled_font_get_type
cairo_scaled_font_status
Func?ii Cairo


Description

cairo_scaled_font_glyph_extents
cairo_scaled_font_text_extents
Func?ii Cairo
PHP Manual

cairo_scaled_font_status

(PECL cairo >= 0.1.0)

cairo_scaled_font_status — Description

Descrierea

int cairo_scaled_font_status ( CairoScaledFont $scaledfont )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

scaledfont

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_scaled_font_glyph_extents
cairo_scaled_font_text_extents
Func?ii Cairo


Description

cairo_scaled_font_status
cairo_surface_copy_page
Func?ii Cairo
PHP Manual

cairo_scaled_font_text_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_text_extents — Description

Descrierea

array cairo_scaled_font_text_extents ( CairoScaledFont $scaledfont , string $text )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

scaledfont

Description...

text

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_scaled_font_status
cairo_surface_copy_page
Func?ii Cairo


Description

cairo_scaled_font_text_extents
cairo_surface_create_similar
Func?ii Cairo
PHP Manual

cairo_surface_copy_page

(PECL cairo >= 0.1.0)

cairo_surface_copy_page — Description

Descrierea

void cairo_surface_copy_page ( CairoSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_scaled_font_text_extents
cairo_surface_create_similar
Func?ii Cairo


Description

cairo_surface_copy_page
cairo_surface_finish
Func?ii Cairo
PHP Manual

cairo_surface_create_similar

(PECL cairo >= 0.1.0)

cairo_surface_create_similar — Description

Descrierea

CairoSurface cairo_surface_create_similar ( CairoSurface $surface , int $content , float $width , float $height )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

content

Description...

width

Description...

height

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_copy_page
cairo_surface_finish
Func?ii Cairo


Description

cairo_surface_create_similar
cairo_surface_flush
Func?ii Cairo
PHP Manual

cairo_surface_finish

(PECL cairo >= 0.1.0)

cairo_surface_finish — Description

Descrierea

void cairo_surface_finish ( CairoSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_create_similar
cairo_surface_flush
Func?ii Cairo


Description

cairo_surface_finish
cairo_surface_get_content
Func?ii Cairo
PHP Manual

cairo_surface_flush

(PECL cairo >= 0.1.0)

cairo_surface_flush — Description

Descrierea

void cairo_surface_flush ( CairoSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_finish
cairo_surface_get_content
Func?ii Cairo


Description

cairo_surface_flush
cairo_surface_get_device_offset
Func?ii Cairo
PHP Manual

cairo_surface_get_content

(PECL cairo >= 0.1.0)

cairo_surface_get_content — Description

Descrierea

int cairo_surface_get_content ( CairoSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_flush
cairo_surface_get_device_offset
Func?ii Cairo


Description

cairo_surface_get_content
cairo_surface_get_font_options
Func?ii Cairo
PHP Manual

cairo_surface_get_device_offset

(PECL cairo >= 0.1.0)

cairo_surface_get_device_offset — Description

Descrierea

array cairo_surface_get_device_offset ( CairoSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_get_content
cairo_surface_get_font_options
Func?ii Cairo


Description

cairo_surface_get_device_offset
cairo_surface_get_type
Func?ii Cairo
PHP Manual

cairo_surface_get_font_options

(PECL cairo >= 0.1.0)

cairo_surface_get_font_options — Description

Descrierea

CairoFontOptions cairo_surface_get_font_options ( CairoSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_get_device_offset
cairo_surface_get_type
Func?ii Cairo


Description

cairo_surface_get_font_options
cairo_surface_mark_dirty_rectangle
Func?ii Cairo
PHP Manual

cairo_surface_get_type

(PECL cairo >= 0.1.0)

cairo_surface_get_type — Description

Descrierea

int cairo_surface_get_type ( CairoSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_get_font_options
cairo_surface_mark_dirty_rectangle
Func?ii Cairo


Description

cairo_surface_get_type
cairo_surface_mark_dirty
Func?ii Cairo
PHP Manual

cairo_surface_mark_dirty_rectangle

(PECL cairo >= 0.1.0)

cairo_surface_mark_dirty_rectangle — Description

Descrierea

void cairo_surface_mark_dirty_rectangle ( CairoSurface $surface , float $x , float $y , float $width , float $height )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

x

Description...

y

Description...

width

Description...

height

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_get_type
cairo_surface_mark_dirty
Func?ii Cairo


Description

cairo_surface_mark_dirty_rectangle
cairo_surface_set_device_offset
Func?ii Cairo
PHP Manual

cairo_surface_mark_dirty

(PECL cairo >= 0.1.0)

cairo_surface_mark_dirty — Description

Descrierea

void cairo_surface_mark_dirty ( CairoSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_mark_dirty_rectangle
cairo_surface_set_device_offset
Func?ii Cairo


Description

cairo_surface_mark_dirty
cairo_surface_set_fallback_resolution
Func?ii Cairo
PHP Manual

cairo_surface_set_device_offset

(PECL cairo >= 0.1.0)

cairo_surface_set_device_offset — Description

Descrierea

void cairo_surface_set_device_offset ( CairoSurface $surface , float $x , float $y )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

x

Description...

y

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_mark_dirty
cairo_surface_set_fallback_resolution
Func?ii Cairo


Description

cairo_surface_set_device_offset
cairo_surface_show_page
Func?ii Cairo
PHP Manual

cairo_surface_set_fallback_resolution

(PECL cairo >= 0.1.0)

cairo_surface_set_fallback_resolution — Description

Descrierea

void cairo_surface_set_fallback_resolution ( CairoSurface $surface , float $x , float $y )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

x

Description...

y

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_set_device_offset
cairo_surface_show_page
Func?ii Cairo


Description

cairo_surface_set_fallback_resolution
cairo_surface_status
Func?ii Cairo
PHP Manual

cairo_surface_show_page

(PECL cairo >= 0.1.0)

cairo_surface_show_page — Description

Descrierea

void cairo_surface_show_page ( CairoSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_set_fallback_resolution
cairo_surface_status
Func?ii Cairo


Description

cairo_surface_show_page
cairo_surface_write_to_png
Func?ii Cairo
PHP Manual

cairo_surface_status

(PECL cairo >= 0.1.0)

cairo_surface_status — Description

Descrierea

int cairo_surface_status ( CairoSurface $surface )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_show_page
cairo_surface_write_to_png
Func?ii Cairo


Description

cairo_surface_status
cairo_svg_surface_create
Func?ii Cairo
PHP Manual

cairo_surface_write_to_png

(PECL cairo >= 0.1.0)

cairo_surface_write_to_png — Description

Descrierea

void cairo_surface_write_to_png ( CairoSurface $surface , resource $stream )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

stream

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_status
cairo_svg_surface_create
Func?ii Cairo


Description

cairo_surface_write_to_png
cairo_svg_surface_restrict_to_version
Func?ii Cairo
PHP Manual

cairo_svg_surface_create

(PECL cairo >= 0.1.0)

cairo_svg_surface_create — Description

Descrierea

CairoSvgSurface cairo_svg_surface_create ( string $file , float $width , float $height )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

file

Description...

width

Description...

height

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_surface_write_to_png
cairo_svg_surface_restrict_to_version
Func?ii Cairo


Description

cairo_svg_surface_create
cairo_svg_version_to_string
Func?ii Cairo
PHP Manual

cairo_svg_surface_restrict_to_version

(PECL cairo >= 0.1.0)

cairo_svg_surface_restrict_to_version — Description

Descrierea

void cairo_svg_surface_restrict_to_version ( CairoSvgSurface $surface , int $version )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

version

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_svg_surface_create
cairo_svg_version_to_string
Func?ii Cairo


Description

cairo_svg_surface_restrict_to_version
Cairo
Func?ii Cairo
PHP Manual

cairo_svg_version_to_string

(PECL cairo >= 0.1.0)

cairo_svg_version_to_string — Description

Descrierea

string cairo_svg_version_to_string ( int $version )

The function description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

version

Description...

Valorile întoarse

What is returned on success and failure

Erori/Excep?ii

When does this function issue E_* level errors, and/or throw exceptions.

Exemple

Example #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

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • related function name here()

cairo_svg_surface_restrict_to_version
Cairo
Func?ii Cairo


The Cairo class

(PECL cairo >= 0.1.0)

Introducere

Simple class with some static helper methods.

Sinopsisul clasei

Cairo {
/* Metode */
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 )
}

Cuprins

  • 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

Descrierea

Stil obiect-orientat:

public static array Cairo::availableFonts ( void )

Stil procedural:

array cairo_available_fonts ( void )

Returns an array with the available font backends

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A list-type array with all available font backends.

Exemple

Example #1 Stil obiect-orientat

<?php

/* Object Oriented Style */
var_dump(Cairo::availableFonts());

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  [0]=>
  string(5) "WIN32"
  [1]=>
  string(4) "USER"
}

Example #2 Stil procedural

<?php

/* Procedural style */
var_dump(cairo_available_fonts());

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  [0]=>
  string(5) "WIN32"
  [1]=>
  string(4) "USER"
}

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public static array Cairo::availableSurfaces ( void )

Stil procedural:

array cairo_available_surfaces ( void )

Returns an array with the available surface backends

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A list-type array with all available surface backends.

Exemple

Example #1 Stil obiect-orientat

<?php

/* Object Oriented style */
var_dump(Cairo::availableSurfaces());

?>

Exemplul de mai sus va afi?a ceva similar cu:

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"
}

Example #2 Stil procedural

<?php

/* Procedural style */
var_dump(cairo_available_surfaces());

?>

Exemplul de mai sus va afi?a ceva similar cu:

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"
}

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public static string Cairo::statusToString ( int $status )

Stil procedural:

string cairo_status_to_string ( int $status )

Retrieves the current status as a readable string

Parametri

status

A valid status code given by cairo_status() or CairoContext::status()

Valorile întoarse

A string containing the current status of a CairoContext object

Exemple

Example #1 Stil obiect-orientat

<?php
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$context = new CairoContext($surface);

var_dump(Cairo::statusToString($context->status()));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(7) "success"

Example #2 Stil procedural

<?php
$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$context = cairo_create($surface);

var_dump(cairo_status_to_string(cairo_status($context)));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(7) "success"

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public static int Cairo::version ( void )

Stil procedural:

int cairo_version ( void )

Retrieves the current version of the cairo library as an integer value

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Current Cairo library version integer

Exemple

Example #1 Stil obiect-orientat

<?php
var_dump(Cairo::version());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(10808)

Example #2 Stil procedural

<?php
var_dump(cairo_version());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(10808)

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public static string Cairo::versionString ( void )

Stil procedural:

string cairo_version_string ( void )

Retrieves the current cairo library version as a string.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Current Cairo library version string

Exemple

Example #1 Stil obiect-orientat

<?php

var_dump(Cairo::versionString());

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(5) "1.8.8"

Example #2 Stil procedural

<?php

var_dump(cairo_version_string());

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(5) "1.8.8"

A se vedea ?i

  • Cairo::version() - Retrives cairo's library version

Cairo::version
CairoContext
Cairo


The CairoContext class

(PECL cairo >= 0.1.0)

Introducere

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.

Sinopsisul clasei

CairoContext {
/* Metode */
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 )
}

Cuprins

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::appendPath ( CairoPath $path )

Stil procedural:

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

Parametri

context

CairoContext object

path

CairoPath object

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$path = $context->copyPath();

$context->appendPath($path);

?>

Example #2 Stil procedural

<?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);

?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::arc ( float $x , float $y , float $radius , float $angle1 , float $angle2 )

Stil procedural:

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.

Parametri

context

A valid CairoContext object

x

x position

y

y position

radius

Radius of the arc

angle1

start angle

angle2

end angle

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?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');
?>

Example #2 Stil procedural

<?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');
?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::arcNegative ( float $x , float $y , float $radius , float $angle1 , float $angle2 )

Stil procedural:

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.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?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');
?>

Example #2 Stil procedural

<?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');
?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::clip ( void )

Stil procedural:

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().

Parametri

context

A valid CairoContext object

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->clip();

?>

Example #2 Stil procedural

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_clip($context);

?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public array CairoContext::clipExtents ( void )

Stil procedural:

array cairo_clip_extents ( CairoContext $context )

Computes a bounding box in user coordinates covering the area inside the current clip.

Parametri

context

A valid CairoContext object

Valorile întoarse

An array containing the (float)x1, (float)y1, (float)x2, (float)y2, coordinates covering the area inside the current clip

Exemple

Example #1 Stil obiect-orientat

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->clipExtents());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(4) {
  [0]=>
  float(0)
  [1]=>
  float(0)
  [2]=>
  float(50)
  [3]=>
  float(50)
}

Example #2 Stil procedural

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_clip_extents($context));

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(4) {
  [0]=>
  float(0)
  [1]=>
  float(0)
  [2]=>
  float(50)
  [3]=>
  float(50)
}

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::clipPreserve ( void )

Stil procedural:

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().

Parametri

context

A valid CairoContext object

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->clipPreserve();

?>

Example #2 Stil procedural

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_clip_preserve($context);

?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public array CairoContext::clipRectangleList ( void )

Stil procedural:

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

Parametri

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Valorile întoarse

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.)

Exemple

Example #1 Stil obiect-orientat

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->clipRectangleList());

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [0]=>
  array(4) {
    ["x"]=>
    float(0)
    ["y"]=>
    float(0)
    ["width"]=>
    float(50)
    ["height"]=>
    float(50)
  }
}

Example #2 Stil procedural

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_clip_rectangle_list($context));

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [0]=>
  array(4) {
    ["x"]=>
    float(0)
    ["y"]=>
    float(0)
    ["width"]=>
    float(50)
    ["height"]=>
    float(50)
  }
}

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::closePath ( void )

Stil procedural:

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.

Parametri

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->closePath();

?>

Example #2 Stil procedural

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_close_path($context);

?>

A se vedea ?i

  • 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

Descrierea

public CairoContext::__construct ( CairoSurface $surface )

Creates a new CairoContext object to draw

Parametri

surface

A valid CairoSurface like CairoImageSurface or CairoPdfSurface

Valorile întoarse

A CairoContext

Exemple

Example #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);

?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::copyPage ( void )

Stil procedural:

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.

Parametri

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->copyPage();

?>

Example #2 Stil procedural

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_copy_page($context);

?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public CairoPath CairoContext::copyPath ( void )

Stil procedural:

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).

Parametri

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Valorile întoarse

A copy of the current CairoPath in the context

Exemple

Example #1 Stil obiect-orientat

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->copyPath())

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(CairoPath)#3 (0) {
}

Example #2 Stil procedural

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_copy_path($context));

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(CairoPath)#3 (0) {
}

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public CairoPath CairoContext::copyPathFlat ( void )

Stil procedural:

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.

Parametri

context

A CairoContext object

Valorile întoarse

A copy of the current path

Exemple

Example #1 Stil obiect-orientat

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->copyPathFlat());

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(CairoPath)#3 (0) {
}

Example #2 Stil procedural

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_copy_path_flat($context));

?>

Exemplul de mai sus va afi?a ceva similar cu:

object(CairoPath)#3 (0) {
}

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Stil procedural:

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).

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?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');
?>

Example #2 Stil procedural

<?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');
?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public array CairoContext::deviceToUser ( float $x , float $y )

Stil procedural:

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).

Parametri

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

x

x value of the coordinate

y

y value of the coordinate

Valorile întoarse

An array containing the x and y coordinates in the user-space

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public array CairoContext::deviceToUserDistance ( float $x , float $y )

Stil procedural:

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).

Parametri

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

Valorile întoarse

Returns an array with the x and y values of a distance vector in the user-space

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::fill ( void )

Stil procedural:

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.

Parametri

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?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');

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?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');

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public array CairoContext::fillExtents ( void )

Stil procedural:

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.

Parametri

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Valorile întoarse

An array with the coordinates of the afected area

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::fillPreserve ( void )

Stil procedural:

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.

Parametri

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public array CairoContext::fontExtents ( void )

Stil procedural:

array cairo_font_extents ( CairoContext $context )

Gets the font extents for the currently selected font.

Parametri

context

Description...

Valorile întoarse

An array containing the font extents for the current font.

Exemple

Example #1 Stil obiect-orientat

<?php

$sur = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$con = new CairoContext($sur);

var_dump($con->fontExtents());

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(5) {
  ["ascent"]=>
  float(10)
  ["descent"]=>
  float(3)
  ["height"]=>
  float(13.3125)
  ["max_x_advance"]=>
  float(26.65625)
  ["max_y_advance"]=>
  float(0)
}

Example #2 Stil procedural

<?php

$sur = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$con = cairo_create($sur);

var_dump(cairo_font_extents($con));

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(5) {
  ["ascent"]=>
  float(10)
  ["descent"]=>
  float(3)
  ["height"]=>
  float(13.3125)
  ["max_x_advance"]=>
  float(26.65625)
  ["max_y_advance"]=>
  float(0)
}

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public int CairoContext::getAntialias ( void )

Stil procedural:

int cairo_get_antialias ( CairoContext $context )

Returns the current CairoAntialias mode, as set by CairoContext::setAntialias().

Parametri

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Valorile întoarse

The current CairoAntialias mode.

Exemple

Example #1 Stil obiect-orientat

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$context = new CairoContext($surface);

$context->setAntialias(CairoAntialias::MODE_SUBPIXEL);

var_dump($context->getAntialias());

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)

Example #2 Stil procedural

<?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));

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat

public array CairoContext::getCurrentPoint ( void )

Stil procedural

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().

Parametri

context

A valid CairoContext object.

Valorile întoarse

An array containing the x (index 0) and y (index 1) coordinates of the current point.

Exemple

Example #1 Stil obiect-orientat

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->moveTo(10, 10);

var_dump($c->getCurrentPoint());

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  [0]=>
  float(10)
  [1]=>
  float(10)
}

Example #2 Stil procedural

<?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));

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  [0]=>
  float(10)
  [1]=>
  float(10)
}

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public array CairoContext::getDash ( void )

Stil procedural:

array cairo_get_dash ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public int CairoContext::getDashCount ( void )

Stil procedural:

int cairo_get_dash_count ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public int CairoContext::getFillRule ( void )

Stil procedural:

int cairo_get_fill_rule ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::getFontFace ( void )

Stil procedural:

void cairo_get_font_face ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::getFontMatrix ( void )

Stil procedural:

void cairo_get_font_matrix ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::getFontOptions ( void )

Stil procedural:

void cairo_get_font_options ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::getGroupTarget ( void )

Stil procedural:

void cairo_get_group_target ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public int CairoContext::getLineCap ( void )

Stil procedural:

int cairo_get_line_cap ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public int CairoContext::getLineJoin ( void )

Stil procedural:

int cairo_get_line_join ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public float CairoContext::getLineWidth ( void )

Stil procedural:

float cairo_get_line_width ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::getMatrix ( void )

Stil procedural:

void cairo_get_matrix ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public float CairoContext::getMiterLimit ( void )

Stil procedural:

float cairo_get_miter_limit ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public int CairoContext::getOperator ( void )

Stil procedural:

int cairo_get_operator ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::getScaledFont ( void )

Stil procedural:

void cairo_get_scaled_font ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::getSource ( void )

Stil procedural:

void cairo_get_source ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::getTarget ( void )

Stil procedural:

void cairo_get_target ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public float CairoContext::getTolerance ( void )

Stil procedural:

float cairo_get_tolerance ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat

public void CairoContext::glyphPath ( array $glyphs )

Stil procedural

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().

Parametri

context

A CairoContext object

glyphs

Array of glyphs

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

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

Descrierea

Stil obiect-orientat (method):

public bool CairoContext::hasCurrentPoint ( void )

Stil procedural:

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.

Parametri

context

A valid CairoContext object.

Valorile întoarse

Whether a current point is defined

Exemple

Example #1 Stil obiect-orientat

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

var_dump($c->hasCurrentPoint());

$c->moveTo(10, 10);

var_dump($c->hasCurrentPoint());

?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

Example #2 Stil procedural

<?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));

?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::identityMatrix ( void )

Stil procedural:

void cairo_identity_matrix ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public bool CairoContext::inFill ( string $x , string $y )

Stil procedural:

bool cairo_in_fill ( CairoContext $context , string $x , string $y )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

x

Description...

y

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public bool CairoContext::inStroke ( string $x , string $y )

Stil procedural:

bool cairo_in_stroke ( CairoContext $context , string $x , string $y )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

x

Description...

y

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::lineTo ( string $x , string $y )

Stil procedural:

void cairo_line_to ( CairoContext $context , string $x , string $y )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

x

Description...

y

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::mask ( string $pattern )

Stil procedural:

void cairo_mask ( CairoContext $context , CairoPattern $pattern )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

pattern

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::maskSurface ( string $surface [, string $x [, string $y ]] )

Stil procedural:

void cairo_mask_surface ( CairoContext $context , CairoSurface $surface [, string $x [, string $y ]] )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

surface

Description...

x

Description...

y

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::moveTo ( string $x , string $y )

Stil procedural:

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).

Parametri

context

A valid CairoContext object.

x

The x coordinate of the new position.

y

The y coordinate of the new position

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?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');
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?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');
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::newPath ( void )

Stil procedural:

void cairo_new_path ( CairoContext $context )

Clears the current path. After this call there will be no path and no current point.

Parametri

context

A valid CairoContext object.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Stil obiect-orientat

<?php
// [...]
CairoContext::newPath();
?>

Example #2 Stil procedural

<?php
// [...]
cairo_new_path($context);
?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::newSubPath ( void )

Stil procedural:

void cairo_new_sub_path ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::paint ( void )

Stil procedural:

void cairo_paint ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::paintWithAlpha ( string $alpha )

Stil procedural:

void cairo_paint_with_alpha ( CairoContext $context , string $alpha )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

alpha

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public array CairoContext::pathExtents ( void )

Stil procedural:

array cairo_path_extents ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::popGroup ( void )

Stil procedural:

void cairo_pop_group ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::popGroupToSource ( void )

Stil procedural:

void cairo_pop_group_to_source ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::pushGroup ( void )

Stil procedural:

void cairo_push_group ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::pushGroupWithContent ( string $content )

Stil procedural:

void cairo_push_group_with_content ( CairoContext $context , string $content )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

content

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::rectangle ( string $x , string $y , string $width , string $height )

Stil procedural:

void cairo_rectangle ( CairoContext $context , string $x , string $y , string $width , string $height )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

x

Description...

y

Description...

width

Description...

height

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::relCurveTo ( string $x1 , string $y1 , string $x2 , string $y2 , string $x3 , string $y3 )

Stil procedural:

void cairo_rel_curve_to ( CairoContext $context , string $x1 , string $y1 , string $x2 , string $y2 , string $x3 , string $y3 )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

x1

Description...

y1

Description...

x2

Description...

y2

Description...

x3

Description...

y3

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::relLineTo ( string $x , string $y )

Stil procedural:

void cairo_rel_line_to ( CairoContext $context , string $x , string $y )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

x

Description...

y

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::relMoveTo ( string $x , string $y )

Stil procedural:

void cairo_rel_move_to ( CairoContext $context , string $x , string $y )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

x

Description...

y

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::resetClip ( void )

Stil procedural:

void cairo_reset_clip ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::restore ( void )

Stil procedural:

void cairo_restore ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::rotate ( string $angle )

Stil procedural:

void cairo_rotate ( CairoContext $context , string $angle )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

angle

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::save ( void )

Stil procedural:

void cairo_save ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::scale ( string $x , string $y )

Stil procedural:

void cairo_scale ( CairoContext $context , string $x , string $y )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

x

Description...

y

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::selectFontFace ( string $family [, string $slant [, string $weight ]] )

Stil procedural:

void cairo_select_font_face ( CairoContext $context , string $family [, string $slant [, string $weight ]] )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

family

Description...

slant

Description...

weight

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setAntialias ([ string $antialias ] )

Stil procedural:

void cairo_set_antialias ( CairoContext $context [, string $antialias ] )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

antialias

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setDash ( string $dashes [, string $offset ] )

Stil procedural:

void cairo_set_dash ( CairoContext $context , array $dashes [, string $offset ] )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

dashes

Description...

offset

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setFillRule ( string $setting )

Stil procedural:

void cairo_set_fill_rule ( CairoContext $context , string $setting )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

setting

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setFontFace ( CairoFontFace $fontface )

Stil procedural:

void cairo_set_font_face ( CairoContext $context , CairoFontFace $fontface )

Sets the font-face for a given context.

Parametri

context

A CairoContext object to change the font-face for.

fontface

A CairoFontFace object

Valorile întoarse

No value is returned

Exemple

Example #1 Stil obiect-orientat

<?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');
?>

Example #2 Stil procedural

<?php
/* ... */
?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setFontMatrix ( string $matrix )

Stil procedural:

void cairo_set_font_matrix ( CairoContext $context , CairoMatrix $matrix )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

matrix

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setFontOptions ( string $fontoptions )

Stil procedural:

void cairo_set_font_options ( CairoContext $context , CairoFontOptions $fontoptions )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

fontoptions

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setFontSize ( string $size )

Stil procedural:

void cairo_set_font_size ( CairoContext $context , string $size )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

size

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setLineCap ( string $setting )

Stil procedural:

void cairo_set_line_cap ( CairoContext $context , string $setting )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

setting

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setLineJoin ( string $setting )

Stil procedural:

void cairo_set_line_join ( CairoContext $context , string $setting )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

setting

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setLineWidth ( string $width )

Stil procedural:

void cairo_set_line_width ( CairoContext $context , string $width )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

width

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setMatrix ( string $matrix )

Stil procedural:

void cairo_set_matrix ( CairoContext $context , CairoMatrix $matrix )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

matrix

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setMiterLimit ( string $limit )

Stil procedural:

void cairo_set_miter_limit ( CairoContext $context , string $limit )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

limit

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setOperator ( string $setting )

Stil procedural:

void cairo_set_operator ( CairoContext $context , string $setting )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

setting

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setScaledFont ( string $scaledfont )

Stil procedural:

void cairo_set_scaled_font ( CairoContext $context , CairoScaledFont $scaledfont )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

scaledfont

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setSource ( string $pattern )

Stil procedural:

void cairo_set_source ( CairoContext $context , CairoPattern $pattern )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

pattern

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setSourceRGB ( string $red , string $green , string $blue )

Stil procedural:

void cairo_set_source ( CairoContext $context , CairoPattern $pattern )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

pattern

Description...

red

Description...

green

Description...

blue

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setSourceRGBA ( string $red , string $green , string $blue , string $alpha )

Stil procedural:

void cairo_set_source ( CairoContext $context , CairoPattern $pattern )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

pattern

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setSourceSurface ( string $surface [, string $x [, string $y ]] )

Stil procedural:

void cairo_set_source_surface ( CairoContext $context , CairoSurface $surface [, string $x [, string $y ]] )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

surface

Description...

x

Description...

y

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::setTolerance ( string $tolerance )

Stil procedural:

void cairo_set_tolerance ( CairoContext $context , string $tolerance )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

tolerance

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::showPage ( void )

Stil procedural:

void cairo_show_page ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::showText ( string $text )

Stil procedural:

void cairo_show_text ( CairoContext $context , string $text )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

text

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public int CairoContext::status ( void )

Stil procedural:

int cairo_status ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::stroke ( void )

Stil procedural:

void cairo_stroke ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public array CairoContext::strokeExtents ( void )

Stil procedural:

array cairo_stroke_extents ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::strokePreserve ( void )

Stil procedural:

void cairo_stroke_preserve ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public array CairoContext::textExtents ( string $text )

Stil procedural:

array cairo_text_extents ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

text

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat

public void CairoContext::textPath ( string $string )

Stil procedural

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.

Parametri

context

A CairoContext object

text

Description...

string

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::transform ( string $matrix )

Stil procedural:

void cairo_transform ( CairoContext $context , CairoMatrix $matrix )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

matrix

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoContext::translate ( string $x , string $y )

Stil procedural:

void cairo_translate ( CairoContext $context , string $x , string $y )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

x

Description...

y

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public array CairoContext::userToDevice ( string $x , string $y )

Stil procedural:

array cairo_user_to_device ( CairoContext $context , string $x , string $y )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

x

Description...

y

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public array CairoContext::userToDeviceDistance ( string $x , string $y )

Stil procedural:

array cairo_user_to_device_distance ( CairoContext $context , string $x , string $y )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

x

Description...

y

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoContext::userToDevice
CairoException
CairoContext


The CairoException class

(PECL cairo >= 0.1.0)

Introducere

Exception class throwed by Cairo functions and methods

Sinopsisul clasei

CairoException extends Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
CairoContext::userToDeviceDistance
CairoStatus
Cairo


The CairoStatus class

(No version information available, might only be in Git)

Introducere

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.

Sinopsisul clasei

CairoStatus {
/* Constante */
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 ;
}

Constante predefinite

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

(PECL cairo >= 0.1.0)

Introducere

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.

Sinopsisul clasei

CairoSurface {
/* Metode */
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 )
}

Cuprins

  • 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

Descrierea

public CairoSurface::__construct ( void )

CairoSurface is an abstract type and, as such, should not be instantiated in your PHP scripts.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

No return value

Note

Nota:

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.

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoSurface::copyPage ( void )

Stil procedural:

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.

Parametri

context

A CairoContext object

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

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.)

Parametri

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).

Valorile întoarse

A new CairoSurface

Exemple

Example #1 CairoSurface::createSimilar() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoSurface::finish ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoSurface::finish() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoSurface::flush ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoSurface::flush() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoSurface::getContent ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoSurface::getContent() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public array CairoSurface::getDeviceOffset ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoSurface::getDeviceOffset() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoSurface::getFontOptions ( void )

Stil procedural:

void cairo_get_font_options ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoSurface::getType ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoSurface::getType() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoSurface::markDirty ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoSurface::markDirty() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

Description...

y

Description...

width

Description...

height

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoSurface::markDirtyRectangle() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoSurface::setDeviceOffset ( string $x , string $y )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

Description...

y

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoSurface::setDeviceOffset() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoSurface::setFallbackResolution ( string $x , string $y )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

Description...

y

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoSurface::setFallbackResolution() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoSurface::showPage ( void )

Stil procedural:

void cairo_show_page ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public int CairoSurface::status ( void )

Stil procedural:

int cairo_status ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoSurface::writeToPng ( string $file )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

file

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoSurface::writeToPng() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoSurface::status
CairoSvgSurface
CairoSurface


Svg Surface Backend

(PECL cairo >= 0.1.0)

Introducere

Svg specific surface class, uses the SVG (standard vector graphics) surface backend.

Sinopsisul clasei

CairoSvgSurface extends CairoSurface {
/* Metode */
public __construct ( string $file , float $width , float $height )
public static array getVersions ( void )
public void restrictToVersion ( string $version )
public static string versionToString ( int $version )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

public CairoSvgSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

file

Description...

width

Description...

height

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoSvgSurface::__construct() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public static array CairoSvgSurface::getVersions ( void )

Stil procedural:

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().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a numerically indexed array of integer values.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(1)
}
SVG 1.1
SVG 1.2

Example #2 Stil procedural

<?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;
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(1)
}
SVG 1.1
SVG 1.2

A se vedea ?i

  • 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

Descrierea

public void CairoSvgSurface::restrictToVersion ( string $version )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

version

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoSvgSurface::restrictToVersion() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public static string CairoSvgSurface::versionToString ( int $version )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

version

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoSvgSurface::versionToString() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoSvgSurface::restrictToVersion
CairoImageSurface
CairoSvgSurface


The CairoImageSurface class

(PECL cairo >= 0.1.0)

Introducere

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.

Sinopsisul clasei

CairoImageSurface extends CairoSurface {
/* Metode */
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 )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

public CairoImageSurface::__construct ( int $format , int $width , int $height )

Creates a new CairoImageSuface object of type format

Parametri

format

Can be any defined in CairoFormat

width

The width of the image surface

height

The height of the image surface

Valorile întoarse

A new CairoImageSurface

Exemple

Example #1 CairoImageSurface::__construct() example

<?php

// Creates a image with ARGB32 format of 50 width and 50 height
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50,50);

?>

A se vedea ?i

  • 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

Descrierea

public static void CairoImageSurface::createForData ( string $data , int $format , int $width , int $height [, int $stride = -1 ] )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

data

Description...

format

Description...

width

Description...

height

Description...

stride

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoImageSurface::createForData() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public static CairoImageSurface CairoImageSurface::createFromPng ( string $file )

Creates a new CairoImageSurface form a png image file

This method should be called static

Parametri

file

Path to PNG image file

Valorile întoarse

CairoImageSurface object

Exemple

Example #1 CairoImageSurface::createFromPng() example

<?php

$surface = CairoImageSurface::createFromPng('/path/to/image/file.png');

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The image data as string

Exemple

Example #1 CairoImageSurface::getData() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoImageSurface::getFormat ( void )

Retrieves the image format, as one of the CairoFormat defined

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

One of the CairoFormat enums

Exemple

Example #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

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(0)
int(2)

A se vedea ?i

  • 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

Descrierea

public int CairoImageSurface::getHeight ( void )

This methods returns the CairoImageSurface height.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

CairoImageSurface object height

Exemple

Example #1 CairoImageSurface::getHeight() example

<?php
// creates a new image surface
$surface = new CairoImageSurface(CairoFormat::ARGB32, 80, 50);

//gets the height
var_dump($surface->getHeight());

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(50)

A se vedea ?i

  • 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

Descrierea

public int CairoImageSurface::getStride ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoImageSurface::getStride() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoImageSurface::getWidth ( void )

Gets the width of the CairoImageSurface

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the width of the CairoImageSurface object

Exemple

Example #1 CairoImageSurface::getWidth() example

<?php
// creates a new image surface
$surface = new CairoImageSurface(CairoFormat::ARGB32, 80, 50);

//gets the width
var_dump($surface->getWidth());

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(80)

A se vedea ?i

  • CairoImageSurface::getHeight() - Retrieves the height of the CairoImageSurface

CairoImageSurface::getStride
CairoPdfSurface
CairoImageSurface


The CairoPdfSurface class

(PECL cairo >= 0.1.0)

Introducere

Sinopsisul clasei

CairoPdfSurface extends CairoSurface {
/* Metode */
public __construct ( string $file , float $width , float $height )
public void setSize ( string $width , string $height )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

public CairoPdfSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

file

Description...

width

Description...

height

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoPdfSurface::__construct() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoPdfSurface::setSize ( string $width , string $height )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

width

Description...

height

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoPdfSurface::setSize() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoPdfSurface::__construct
CairoPsSurface
CairoPdfSurface


The CairoPsSurface class

(PECL cairo >= 0.1.0)

Introducere

Sinopsisul clasei

CairoPsSurface extends CairoSurface {
/* Metode */
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 )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

public CairoPsSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

file

Description...

width

Description...

height

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoPsSurface::__construct() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoPsSurface::dscBeginPageSetup ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoPsSurface::dscBeginPageSetup() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoPsSurface::dscBeginSetup ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoPsSurface::dscBeginSetup() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoPsSurface::dscComment ( string $comment )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

comment

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoPsSurface::dscComment() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public bool CairoPsSurface::getEps ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoPsSurface::getEps() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public static array CairoPsSurface::getLevels ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoPsSurface::getLevels() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public static string CairoPsSurface::levelToString ( int $level )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

level

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoPsSurface::levelToString() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoPsSurface::restrictToLevel ( string $level )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

level

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoPsSurface::restrictToLevel() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoPsSurface::setEps ( string $level )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

level

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoPsSurface::setEps() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoPsSurface::setSize ( string $width , string $height )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

width

Description...

height

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoPsSurface::setSize() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoPsSurface::setEps
CairoSurfaceType
CairoPsSurface


The CairoSurfaceType class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

CairoSurfaceType {
/* Constante */
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 ;
}

Constante predefinite

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

(PECL cairo >= 0.1.0)

Introducere

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().

Sinopsisul clasei

CairoFontFace {
/* Metode */
public __construct ( void )
public int getType ( void )
public int status ( void )
}

Cuprins

  • 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

Descrierea

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()

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

CairoFontFace

Exemple

Example #1 CairoFontFace::__construct() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A font type that can be any one defined in CairoFontType

Exemple

Example #1 CairoFontFace::getType() example

<?php

// Creates the font face
$fontface = new CairoToyFontFace('sans-serif');

// Get the font face type
var_dump($fontface->getType());

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(0)

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public int CairoFontFace::status ( void )

Stil procedural:

int cairo_font_face_status ( CairoFontFace $fontface )

Checks whether an error has previously occurred for this font face

Parametri

fontface

A valid CairoFontFace object

Valorile întoarse

CAIRO_STATUS_SUCCESS or another error such as CAIRO_STATUS_NO_MEMORY.

Exemple

Example #1 Stil obiect-orientat

<?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

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(0)

Example #2 Stil procedural

<?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

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(0)

A se vedea ?i

  • Classname::Method()

CairoFontFace::getType
CairoFontOptions
CairoFontFace


The CairoFontOptions class

(PECL cairo >= 0.1.0)

Introducere

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.

Sinopsisul clasei

CairoFontOptions {
/* Metode */
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 )
}

Cuprins

  • 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

Descrierea

public CairoFontOptions::__construct ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoFontOptions::__construct() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public bool CairoFontOptions::equal ( string $other )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

other

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoFontOptions::equal() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public int CairoFontOptions::getAntialias ( void )

Stil procedural:

int cairo_get_antialias ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoFontOptions::getHintMetrics ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoFontOptions::getHintMetrics() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoFontOptions::getHintStyle ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoFontOptions::getHintStyle() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoFontOptions::getSubpixelOrder ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoFontOptions::getSubpixelOrder() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoFontOptions::hash ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoFontOptions::hash() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoFontOptions::merge ( string $other )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

other

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoFontOptions::merge() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoFontOptions::setAntialias ( string $antialias )

Stil procedural:

void cairo_set_antialias ( CairoContext $context [, string $antialias ] )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

antialias

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoFontOptions::setHintMetrics ( string $hint_metrics )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

hint_metrics

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoFontOptions::setHintMetrics() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoFontOptions::setHintStyle ( string $hint_style )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

hint_style

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoFontOptions::setHintStyle() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoFontOptions::setSubpixelOrder ( string $subpixel_order )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

subpixel_order

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoFontOptions::setSubpixelOrder() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public int CairoFontOptions::status ( void )

Stil procedural:

int cairo_status ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoFontOptions::setSubpixelOrder
CairoFontSlant
CairoFontOptions


The CairoFontSlant class

(No version information available, might only be in Git)

Introducere

Specifies variants of a font face based on their slant.

Sinopsisul clasei

CairoFontSlant {
/* Constante */
const integer NORMAL = 0 ;
const integer ITALIC = 1 ;
const integer OBLIQUE = 2 ;
}

Constante predefinite

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 Git)

Introducere

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().

Sinopsisul clasei

CairoFontType {
/* Constante */
const integer TOY = 0 ;
const integer FT = 1 ;
const integer WIN32 = 2 ;
const integer QUARTZ = 3 ;
}

Constante predefinite

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 Git)

Introducere

Specifies variants of a font face based on their weight.

Sinopsisul clasei

CairoFontWeight {
/* Constante */
const integer NORMAL = 0 ;
const integer BOLD = 1 ;
}

Constante predefinite

CairoFontWeight::NORMAL

Normal font weight

CairoFontWeight::BOLD

Bold font weight

CairoFontType
CairoScaledFont
Cairo


The CairoScaledFont class

(PECL cairo >= 0.1.0)

Introducere

Sinopsisul clasei

CairoScaledFont {
/* Metode */
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 )
}

Cuprins

  • 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

Descrierea

public CairoScaledFont::__construct ( CairoFontFace $font_face , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $options )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

font_face

Description...

matrix

Description...

ctm

Description...

options

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoScaledFont::__construct() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public array CairoScaledFont::extents ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoScaledFont::extents() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public CairoMatrix CairoScaledFont::getCtm ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoScaledFont::getCtm() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoScaledFont::getFontFace ( void )

Stil procedural:

void cairo_get_font_face ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoScaledFont::getFontMatrix ( void )

Stil procedural:

void cairo_get_font_matrix ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoScaledFont::getFontOptions ( void )

Stil procedural:

void cairo_get_font_options ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoScaledFont::getScaleMatrix ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoScaledFont::getScaleMatrix() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoScaledFont::getType ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoScaledFont::getType() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public array CairoScaledFont::glyphExtents ( string $glyphs )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

glyphs

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoScaledFont::glyphExtents() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public int CairoScaledFont::status ( void )

Stil procedural:

int cairo_status ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public array CairoScaledFont::textExtents ( string $text )

Stil procedural:

array cairo_text_extents ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

text

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoScaledFont::status
CairoToyFontFace
CairoScaledFont


The CairoToyFontFace class

(PECL cairo >= 0.1.0)

Introducere

The CairoToyFontFace class can be used instead of CairoContext::selectFontFace() to create a toy font independently of a context.

Sinopsisul clasei

CairoToyFontFace extends CairoFontFace {
/* Metode mo?tenite */
}
CairoScaledFont::textExtents
CairoPatternType
Cairo


The CairoPatternType class

(No version information available, might only be in Git)

Introducere

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.

Sinopsisul clasei

CairoPatternType {
/* Constante */
const integer SOLID = 0 ;
const integer SURFACE = 1 ;
const integer LINEAR = 2 ;
const integer RADIAL = 3 ;
}

Constante predefinite

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

(PECL cairo >= 0.1.0)

Introducere

CairoPattern is the abstract base class from which all the other pattern classes derive. It cannot be instantiated directly

Sinopsisul clasei

CairoPattern {
/* Metode */
public __construct ( void )
public void getMatrix ( void )
public int getType ( void )
public void setMatrix ( string $matrix )
public int status ( void )
}

Cuprins

  • 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

Descrierea

public CairoPattern::__construct ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoPattern::__construct() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoPattern::getMatrix ( void )

Stil procedural:

void cairo_get_matrix ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoPattern::getType ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoPattern::getType() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoPattern::setMatrix ( string $matrix )

Stil procedural:

void cairo_set_matrix ( CairoContext $context , CairoMatrix $matrix )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

matrix

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public int CairoPattern::status ( void )

Stil procedural:

int cairo_status ( CairoContext $context )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoPattern::setMatrix
CairoGradientPattern
CairoPattern


The CairoGradientPattern class

(PECL cairo >= 0.1.0)

Introducere

CairoGradientPattern is an abstract base class from which other Pattern classes derive. It cannot be instantiated directly.

Sinopsisul clasei

CairoGradientPattern extends CairoPattern {
/* Metode */
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 )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

public void CairoGradientPattern::addColorStopRgb ( string $offset , string $red , string $green , string $blue )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

offset

Description...

red

Description...

green

Description...

blue

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoGradientPattern::addColorStopRgb() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoGradientPattern::addColorStopRgba ( string $offset , string $red , string $green , string $blue , string $alpha )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

offset

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoGradientPattern::addColorStopRgba() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoGradientPattern::getColorStopCount ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoGradientPattern::getColorStopCount() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public array CairoGradientPattern::getColorStopRgba ( string $index )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

index

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoGradientPattern::getColorStopRgba() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoGradientPattern::getExtend ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoGradientPattern::getExtend() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoGradientPattern::setExtend ( int $extend )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

extend

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoGradientPattern::setExtend() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoGradientPattern::getExtend
CairoSolidPattern
CairoGradientPattern


The CairoSolidPattern class

(PECL cairo >= 0.1.0)

Introducere

Sinopsisul clasei

CairoSolidPattern extends CairoPattern {
/* Metode */
public __construct ( float $red , float $green , float $blue [, float $alpha = 0 ] )
public array getRgba ( void )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

public CairoSolidPattern::__construct ( float $red , float $green , float $blue [, float $alpha = 0 ] )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

red

Description...

green

Description...

blue

Description...

alpha

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoSolidPattern::__construct() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public array CairoSolidPattern::getRgba ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoSolidPattern::getRgba() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoSolidPattern::__construct
CairoSurfacePattern
CairoSolidPattern


The CairoSurfacePattern class

(PECL cairo >= 0.1.0)

Introducere

Sinopsisul clasei

CairoSurfacePattern extends CairoPattern {
/* Metode */
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 )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

public CairoSurfacePattern::__construct ( CairoSurface $surface )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

surface

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoSurfacePattern::__construct() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoSurfacePattern::getExtend ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoSurfacePattern::getExtend() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public int CairoSurfacePattern::getFilter ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoSurfacePattern::getFilter() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoSurfacePattern::getSurface ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoSurfacePattern::getSurface() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoSurfacePattern::setExtend ( int $extend )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

extend

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoSurfacePattern::setExtend() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public void CairoSurfacePattern::setFilter ( string $filter )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

filter

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoSurfacePattern::setFilter() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoSurfacePattern::setExtend
CairoLinearGradient
CairoSurfacePattern


The CairoLinearGradient class

(PECL cairo >= 0.1.0)

Introducere

Create a new CairoLinearGradient along the line defined

Sinopsisul clasei

CairoLinearGradient extends CairoGradientPattern {
/* Metode */
public __construct ( float $x0 , float $y0 , float $x1 , float $y1 )
public array getPoints ( void )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

public CairoLinearGradient::__construct ( float $x0 , float $y0 , float $x1 , float $y1 )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x0

Description...

y0

Description...

x1

Description...

y1

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoLinearGradient::__construct() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public array CairoLinearGradient::getPoints ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoLinearGradient::getPoints() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoLinearGradient::__construct
CairoRadialGradient
CairoLinearGradient


The CairoRadialGradient class

(PECL cairo >= 0.1.0)

Introducere

Sinopsisul clasei

CairoRadialGradient extends CairoGradientPattern {
/* Metode */
public __construct ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )
public array getCircles ( void )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

Stil obiect-orientat:

public CairoRadialGradient::__construct ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )

Stil procedural:

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().

Parametri

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.

Valorile întoarse

Description...

Exemple

Example #1 CairoRadialGradient::__construct() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public array CairoRadialGradient::getCircles ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoRadialGradient::getCircles() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoRadialGradient::__construct
CairoAntialias
CairoRadialGradient


The CairoAntialias class

(No version information available, might only be in Git)

Introducere

Enum class that specifies the type of antialiasing to do when rendering text or shapes.

Sinopsisul clasei

CairoAntialias {
/* Constante */
const integer MODE_DEFAULT = 0 ;
const integer MODE_NONE = 1 ;
const integer MODE_GRAY = 2 ;
const integer MODE_SUBPIXEL = 3 ;
}

Constante predefinite

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 Git)

Introducere

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.

Sinopsisul clasei

CairoContent {
/* Constante */
const integer COLOR = 4096 ;
const integer ALPHA = 8192 ;
const integer COLOR_ALPHA = 12288 ;
}

Constante predefinite

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 Git)

Introducere

Sinopsisul clasei

CairoExtend {
/* Constante */
const integer NONE = 0 ;
const integer REPEAT = 1 ;
const integer REFLECT = 2 ;
const integer PAD = 3 ;
}

Constante predefinite

CairoExtend::NONE

Description here...

CairoExtend::REPEAT

Description here...

CairoExtend::REFLECT

Description here...

CairoExtend::PAD

Description here...

CairoContent
CairoFormat
Cairo


The CairoFormat class

(PECL cairo >= 0.1.0)

Introducere

CairoFormat enums are used to identify the memory format of the image data.

Sinopsisul clasei

CairoFormat {
/* Constante */
const integer ARGB32 = 0 ;
const integer RGB24 = 1 ;
const integer A8 = 2 ;
const integer A1 = 3 ;
/* Metode */
public static int strideForWidth ( int $format , int $width )
}

Constante predefinite

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.

Cuprins

  • 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

Descrierea

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.

Parametri

format

The desired CairoFormat to use

width

The width of the image

Valorile întoarse

The appropriate stride to use given the desired format and width, or -1 if either the format is invalid or the width too large.

Exemple

Example #1 CairoFormat::strideForWidth() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoFormat
CairoFillRule
CairoFormat


The CairoFillRule class

(No version information available, might only be in Git)

Introducere

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.

Sinopsisul clasei

CairoFillRule {
/* Constante */
const integer WINDING = 0 ;
const integer EVEN_ODD = 1 ;
}

Constante predefinite

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 Git)

Introducere

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.

Sinopsisul clasei

CairoFilter {
/* Constante */
const integer FAST = 0 ;
const integer GOOD = 1 ;
const integer BEST = 2 ;
const integer NEAREST = 3 ;
const integer BILINEAR = 4 ;
const integer GAUSSIAN = 5 ;
}

Constante predefinite

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 Git)

Introducere

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.

Sinopsisul clasei

CairoHintMetrics {
/* Constante */
const integer METRICS_DEFAULT = 0 ;
const integer METRICS_OFF = 1 ;
const integer METRICS_ON = 2 ;
}

Constante predefinite

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 Git)

Introducere

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.

Sinopsisul clasei

CairoHintStyle {
/* Constante */
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 ;
}

Constante predefinite

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 Git)

Introducere

Specifies how to render the endpoints of the path when stroking.

The default line cap style is CairoLineCap::BUTT.

Sinopsisul clasei

CairoLineCap {
/* Constante */
const integer BUTT = 0 ;
const integer ROUND = 1 ;
const integer SQUARE = 2 ;
}

Constante predefinite

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 Git)

Introducere

Sinopsisul clasei

CairoLineJoin {
/* Constante */
const integer MITER = 0 ;
const integer ROUND = 1 ;
const integer BEVEL = 2 ;
}

Constante predefinite

CairoLineJoin::MITER

Description here...

CairoLineJoin::ROUND

Description here...

CairoLineJoin::BEVEL

Description here...

CairoLineCap
CairoMatrix
Cairo


The CairoMatrix class

(PECL cairo >= 0.1.0)

Introducere

Matrices are used throughout cairo to convert between different coordinate spaces.

Sinopsisul clasei

CairoMatrix {
/* Metode */
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 )
}

Cuprins

  • 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

Descrierea

Stil obiect-orientat (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 ]]]]]] )

Stil procedural:

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;

Parametri

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

Valorile întoarse

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Exemple

Example #1 Stil obiect-orientat

<?php
/* Create a new Matrix */
$matrix = new CairoMatrix(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
?>

Example #2 Stil procedural

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public static void CairoMatrix::initIdentity ( void )

Stil procedural:

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

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Exemple

Example #1 Stil obiect-orientat

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initIdentity();
?>

Example #2 Stil procedural

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_identity();
?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public static void CairoMatrix::initRotate ( float $radians )

Stil procedural:

object cairo_matrix_init_rotate ( float $radians )

Creats a new matrix to a transformation that rotates by radians provided

Parametri

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.

Valorile întoarse

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Exemple

Example #1 Stil obiect-orientat

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initRotate(0.3);
?>

Example #2 Stil procedural

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_rotate(0.3);
?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public static void CairoMatrix::initScale ( float $sx , float $sy )

Stil procedural:

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.

Parametri

sx

scale factor in the X direction

sy

scale factor in the Y direction

Valorile întoarse

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Exemple

Example #1 Stil obiect-orientat

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initScale(1.0, 2.0);
?>

Example #2 Stil procedural

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_scale(1.0, 2.0);
?>

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public static void CairoMatrix::initTranslate ( float $tx , float $ty )

Stil procedural:

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.

Parametri

tx

amount to translate in the X direction

ty

amount to translate in the Y direction

Valorile întoarse

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Exemple

Example #1 Stil obiect-orientat

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initTranslate(1.0, 2.0);
?>

Example #2 Stil procedural

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_translate(1.0, 2.0);
?>

A se vedea ?i

  • 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

Descrierea

public void CairoMatrix::invert ( void )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

Exemple

Example #1 CairoMatrix::invert() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public static CairoMatrix CairoMatrix::multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

matrix1

Description...

matrix2

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoMatrix::multiply() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoMatrix::rotate ( string $sx , string $sy )

Stil procedural:

void cairo_rotate ( CairoContext $context , string $angle )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

angle

Description...

sx

Description...

sy

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoMatrix::scale ( float $sx , float $sy )

Stil procedural:

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.

Parametri

matrix

Procedural only - CairoMatrix instance

sx

scale factor in the X direction

sy

scale factor in the Y direction

Exemple

Example #1 Stil obiect-orientat

<?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);
?>

Example #2 Stil procedural

<?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);
?>

A se vedea ?i

  • 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

Descrierea

public array CairoMatrix::transformDistance ( string $dx , string $dy )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

dx

Description...

dy

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoMatrix::transformDistance() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public array CairoMatrix::transformPoint ( string $dx , string $dy )

The method description goes here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

dx

Description...

dy

Description...

Valorile întoarse

Description...

Exemple

Example #1 CairoMatrix::transformPoint() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (method):

public void CairoMatrix::translate ( string $tx , string $ty )

Stil procedural:

void cairo_translate ( CairoContext $context , string $x , string $y )

Description here.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

context

Description...

x

Description...

y

Description...

tx

Description...

ty

Description...

Valorile întoarse

Description...

Exemple

Example #1 Stil obiect-orientat

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

Example #2 Stil procedural

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

CairoMatrix::transformPoint
CairoOperator
CairoMatrix


The CairoOperator class

(No version information available, might only be in Git)

Introducere

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/.

Sinopsisul clasei

CairoOperator {
/* Constante */
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 ;
}

Constante predefinite

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 Git)

Introducere

Note: CairoPath class cannot be instantiated directly, doing so will result in Fatal Error if used or passed

Sinopsisul clasei

CairoPath {
}
CairoOperator
CairoPsLevel
Cairo


The CairoPsLevel class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

CairoPsLevel {
/* Constante */
const integer LEVEL_2 = 0 ;
const integer LEVEL_3 = 1 ;
}

Constante predefinite

CairoPsLevel::LEVEL_2

Description here...

CairoPsLevel::LEVEL_3

Description here...

CairoPath
CairoSubpixelOrder
Cairo


The CairoSubpixelOrder class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

CairoSubpixelOrder {
/* Constante */
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 ;
}

Constante predefinite

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 Git)

Introducere

Sinopsisul clasei

CairoSvgVersion {
/* Constante */
const integer VERSION_1_1 = 0 ;
const integer VERSION_1_2 = 1 ;
}

Constante predefinite

CairoSvgVersion::VERSION_1_1

Description here...

CairoSvgVersion::VERSION_1_2

Description here...

CairoSubpixelOrder
Exif
Cairo


Exchangeable image information

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii 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 — Pseudonim pentru exif_read_data
CairoSvgVersion
Introducere
Generarea ?i procesarea imaginilor


Introducere

With the exif extension you are able to work with image meta data. For example, you may use exif functions to read meta data of pictures taken from digital cameras by working with information stored in the headers of the JPEG and TIFF images.

Exif
Instalarea / configurarea
Exif


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Exif


Necesita?i

Your PHP must be compiled in with --enable-exif. PHP does not require any additional library for the exif module. Windows users must also have the mbstring extension enabled.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

To enable exif-support configure PHP with --enable-exif

Windows users must enable both the php_mbstring.dll and php_exif.dll DLL's in php.ini. The php_mbstring.dll DLL must be loaded before the php_exif.dll DLL so adjust your php.ini accordingly.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în 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
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

EXIF_USE_MBSTRING (integer)

exif_imagetype() ofera lista câtorva constante încorporate asociate.

Tipurile resurselor
Func?ii Exif
Exif


Func?ii Exif

Cuprins

  • 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 — Pseudonim pentru exif_read_data
Constante predefinite
exif_imagetype
Exif


Determine the type of an image

Func?ii Exif
exif_read_data
Func?ii Exif
PHP Manual

exif_imagetype

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

exif_imagetype — Determine the type of an image

Descrierea

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.

Parametri

filename
The image being checked.

Valorile întoarse

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.

Nota:

exif_imagetype() will emit an E_NOTICE and return FALSE if it is unable to read enough bytes from the file to determine the image type.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Added icon support.

Constante predefinite

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

Exemple

Example #1 exif_imagetype() example

<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
    echo 'The picture is not a gif';
}
?>

A se vedea ?i

  • 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

Func?ii Exif
exif_read_data
Func?ii Exif


Reads the EXIF headers from JPEG or TIFF

exif_imagetype
exif_tagname
Func?ii Exif
PHP Manual

exif_read_data

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

exif_read_data — Reads the EXIF headers from JPEG or TIFF

Descrierea

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).

Nota:

Windows Me/XP can both wipe the Exif headers when connecting to a camera.

Parametri

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.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #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.

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • exif_thumbnail() - Retrieve the embedded thumbnail of a TIFF or JPEG image
  • getimagesize() - Get the size of an image

exif_imagetype
exif_tagname
Func?ii Exif


Get the header name for an index

exif_read_data
exif_thumbnail
Func?ii Exif
PHP Manual

exif_tagname

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

exif_tagname — Get the header name for an index

Descrierea

string exif_tagname ( int $index )

Parametri

index

The Tag ID for which a Tag Name will be looked up.

Valorile întoarse

Returns the header name, or FALSE if index is not a defined EXIF tag id.

Exemple

Example #1 exif_tagname() example

<?php
echo "256: ".exif_tagname(256).PHP_EOL;
echo "257: ".exif_tagname(257).PHP_EOL;
?>

Exemplul de mai sus va afi?a:

256: ImageWidth
257: ImageLength

A se vedea ?i

  • exif_imagetype() - Determine the type of an image
  • » EXIF Specification
  • » EXIF Tags

exif_read_data
exif_thumbnail
Func?ii Exif


Retrieve the embedded thumbnail of a TIFF or JPEG image

exif_tagname
read_exif_data
Func?ii Exif
PHP Manual

exif_thumbnail

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

exif_thumbnail — Retrieve the embedded thumbnail of a TIFF or JPEG image

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the embedded thumbnail, or FALSE if the image contains no thumbnail.

Exemple

Example #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';
}
?>

A se vedea ?i

  • 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
Func?ii Exif


Pseudonim pentru exif_read_data

exif_thumbnail
GD
Func?ii Exif
PHP Manual

read_exif_data

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

read_exif_data — Pseudonim pentru exif_read_data()

Descrierea

Aceasta func?ie este pseudonim pentru: exif_read_data().

exif_thumbnail
GD
Func?ii Exif


Image Processing and GD

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • PNG creation with PHP
    • Adding watermarks to images using alpha channels
    • Using imagecopymerge to create a translucent watermark
  • Func?ii GD ?i Image
    • gd_info — Retrieve information about the currently installed GD library
    • getimagesize — Get the size of an image
    • getimagesizefromstring — Get the size of an image from a string
    • 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 — Afi?eaza imaginea în navigator sau în fi?ier
    • imageaffine — Return an image containing the affine transformed src image, using an optional clipping area
    • imageaffinematrixconcat — Concatenate two affine transformation matrices
    • imageaffinematrixget — Get an affine transformation matrix
    • imagealphablending — Set the blending mode for an image
    • imageantialias — Should antialias functions be used or not
    • imagearc — Draws an arc
    • imagebmp — Output a BMP image to browser or file
    • 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
    • imagecreatefrombmp — Creeaza o imagine noua din fi?ier sau din 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
    • imagecreatefromgd — Create a new image from GD file or URL
    • imagecreatefromgif — Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatefromjpeg — Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatefrompng — Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatefromstring — Create a new image from the image stream in the string
    • imagecreatefromwbmp — Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatefromwebp — Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatefromxbm — Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatefromxpm — Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatetruecolor — Create a new true color image
    • imagecrop — Crop an image to the given rectangle
    • imagecropauto — Crop an image automatically using one of the available modes
    • 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
    • imageflip — Flips an image using a given mode
    • 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
    • imagegetclip — Get the clipping rectangle
    • imagegif — Afi?eaza imaginea în navigator sau în fi?ier
    • imagegrabscreen — Captures the whole screen
    • imagegrabwindow — Captures a window
    • imageinterlace — Enable or disable interlace
    • imageistruecolor — Finds whether an image is a truecolor image
    • imagejpeg — Afi?eaza imaginea în navigator sau în fi?ier
    • imagelayereffect — Set the alpha blending flag to use layering effects
    • imageline — Draw a line
    • imageloadfont — Load a new font
    • imageopenpolygon — Draws an open polygon
    • imagepalettecopy — Copy the palette from one image to another
    • imagepalettetotruecolor — Converts a palette based image to true color
    • 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
    • imageresolution — Get or set the resolution of the image
    • 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
    • imagescale — Scale an image using the given new width and height
    • imagesetbrush — Set the brush image for line drawing
    • imagesetclip — Set the clipping rectangle
    • imagesetinterpolation — Set the interpolation method
    • 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 — Afi?eaza imaginea în navigator sau în fi?ier
    • imagewebp — Output a WebP image to browser or file
    • imagexbm — Output an 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
Introducere
Generarea ?i procesarea imaginilor


Introducere

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 conveniently, 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.

Nota: 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.

Nota: The getimagesize() function does not require the GD extension.

GD supports a varity of formats, below is a list of formats supported by GD and notes to their availability including read/write support.

Formats supported by GD
Format | Read support | Write support | Notes
JPEG | TRUE | TRUE |
PNG | TRUE | TRUE |
GIF | TRUE | TRUE | Available as of GD 2.0.28 and PHP 5.0.1
XBM | TRUE | TRUE |
XPM | TRUE | FALSE | Read support available on Windows as of PHP 5.3.19.
WBMP | TRUE | TRUE |
WebP | TRUE | TRUE | PHP 5.5+
BMP | TRUE | TRUE | Available as of GD 2.1.0 and PHP 7.2.0

Despite most formats being available for both reading and writing in the above table, doesn't mean that PHP was compiled with support for them. To find out which formats that was available to GD during compilation, use the gd_info() function, for more information about compiling support for one or more formats, see the installation chapter.

GD
Instalarea / configurarea
GD


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
GD


Necesita?i

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. GIF support is available as of gd-2.0.28.

Nota: As of PHP 5.0 libgd-2.0.4 or higher is required. As of PHP 5.5 libgd-2.1.0 or higher is required. Alternatively, use the bundled GD library that ships with PHP.

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 newer than gd-2.0.28. Write support is available as of 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 |
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/ | Support for FreeType 1.x has been removed as of PHP 5.3.0.
FreeType 2 | » http://www.freetype.org/ |
T1lib | » ftp://sunsite.unc.edu/pub/Linux/libs/graphics/) | Support for Postscript Type 1 fonts (Removed as of PHP 7.0.0).

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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, 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.

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.
webp | To enable support for webp add --with-vpx-dir=DIR . Available as of PHP 5.5. As of PHP 7.0.0 --with-webp-dir=DIR has to be added, i.e. support for libvpx has been removed in favor of libwebp.

Nota: 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 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] (Removed as of PHP 7.0.0).
Native TrueType string function | To enable support for native TrueType string function add --enable-gd-native-ttf . (Effectless as of PHP 5.5.0; removed as of PHP 7.2.0.)

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Image Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Changelog
gd.jpeg_ignore_warning | "1" | PHP_INI_ALL | Available since PHP 5.1.3.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

gd.jpeg_ignore_warning bool

Ignore warnings created by jpeg2wbmp() and imagecreatefromjpeg()

Changelog for gd.jpeg_ignore_warning
Versiune | Descriere
7.1.0 | The default of gd.jpeg_ignore_warning has been changed from 0 to 1.

See also the exif configuration directives.

Avertizare

Image functions are very memory intensive. Be sure to set memory_limit high enough.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

This extension defines the following resource types:

List of resource types in GD
Name | Description | Notes
gd | Image resource, used by functions like imagecreatefrompng() |
gd font | Font resource returned by imageloadfont() |
gd PS font | PostScript Type 1 font resource, returned by imagepsloadfont() | Removed as of PHP 7.0.0.
gd PS encoding | PostScript Type 1 encoding resource, returned by imagepsencodefont() | Removed as of PHP 7.0.0.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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_BMP (integer)
Used as a return value by imagetypes()
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()

Nota:

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_WEBP (integer)
Used as a return value by imagetypes() Available as of PHP 5.6.25 and PHP 7.0.10, respectively.
IMG_COLOR_TILED (integer)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_COLOR_STYLED (integer)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_COLOR_BRUSHED (integer)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_COLOR_STYLEDBRUSHED (integer)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_COLOR_TRANSPARENT (integer)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_AFFINE_TRANSLATE (integer)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_AFFINE_SCALE (integer)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_AFFINE_ROTATE (integer)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_AFFINE_SHEAR_HORIZONTAL (integer)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_AFFINE_SHEAR_VERTICAL (integer)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_ARC_ROUNDED (integer)
A style constant used by the imagefilledarc() function.

Nota:

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_EFFECT_MULTIPLY (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)
IMAGETYPE_WEBP (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions. (Available as of PHP 7.1.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.
IMG_FLIP_VERTICAL (int)
Used together with imageflip(), available as of PHP 5.5.0.
IMG_FLIP_HORIZONTAL (int)
Used together with imageflip(), available as of PHP 5.5.0.
IMG_FLIP_BOTH (int)
Used together with imageflip(), available as of PHP 5.5.0.
IMG_BELL (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BESSEL (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BILINEAR_FIXED (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BICUBIC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BICUBIC_FIXED (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BLACKMAN (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BOX (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BSPLINE (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_CATMULLROM (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_GAUSSIAN (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_GENERALIZED_CUBIC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_HERMITE (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_HAMMING (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_HANNING (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_MITCHELL (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_POWER (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_QUADRATIC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_SINC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_NEAREST_NEIGHBOUR (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_WEIGHTED4 (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_TRIANGLE (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
Tipurile resurselor
Exemple
GD


Exemple

Cuprins

  • PNG creation with PHP
  • Adding watermarks to images using alpha channels
  • Using imagecopymerge to create a translucent watermark
Constante predefinite
PNG creation with PHP
GD


PNG creation with PHP

Example #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.

Exemple
Adding watermarks to images using alpha channels
Exemple


Adding watermarks to images using alpha channels

Example #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
Exemple


Using imagecopymerge to create a translucent watermark

Adding watermarks to images using alpha channels
Func?ii GD ?i Image
Exemple
PHP Manual

Using imagecopymerge() to create a translucent watermark

Example #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);
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 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. 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
Func?ii GD ?i Image
Exemple


Func?ii GD ?i Image

Cuprins

  • gd_info — Retrieve information about the currently installed GD library
  • getimagesize — Get the size of an image
  • getimagesizefromstring — Get the size of an image from a string
  • 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 — Afi?eaza imaginea în navigator sau în fi?ier
  • imageaffine — Return an image containing the affine transformed src image, using an optional clipping area
  • imageaffinematrixconcat — Concatenate two affine transformation matrices
  • imageaffinematrixget — Get an affine transformation matrix
  • imagealphablending — Set the blending mode for an image
  • imageantialias — Should antialias functions be used or not
  • imagearc — Draws an arc
  • imagebmp — Output a BMP image to browser or file
  • 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
  • imagecreatefrombmp — Creeaza o imagine noua din fi?ier sau din 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
  • imagecreatefromgd — Create a new image from GD file or URL
  • imagecreatefromgif — Creeaza o imagine noua din fi?ier sau din URL
  • imagecreatefromjpeg — Creeaza o imagine noua din fi?ier sau din URL
  • imagecreatefrompng — Creeaza o imagine noua din fi?ier sau din URL
  • imagecreatefromstring — Create a new image from the image stream in the string
  • imagecreatefromwbmp — Creeaza o imagine noua din fi?ier sau din URL
  • imagecreatefromwebp — Creeaza o imagine noua din fi?ier sau din URL
  • imagecreatefromxbm — Creeaza o imagine noua din fi?ier sau din URL
  • imagecreatefromxpm — Creeaza o imagine noua din fi?ier sau din URL
  • imagecreatetruecolor — Create a new true color image
  • imagecrop — Crop an image to the given rectangle
  • imagecropauto — Crop an image automatically using one of the available modes
  • 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
  • imageflip — Flips an image using a given mode
  • 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
  • imagegetclip — Get the clipping rectangle
  • imagegif — Afi?eaza imaginea în navigator sau în fi?ier
  • imagegrabscreen — Captures the whole screen
  • imagegrabwindow — Captures a window
  • imageinterlace — Enable or disable interlace
  • imageistruecolor — Finds whether an image is a truecolor image
  • imagejpeg — Afi?eaza imaginea în navigator sau în fi?ier
  • imagelayereffect — Set the alpha blending flag to use layering effects
  • imageline — Draw a line
  • imageloadfont — Load a new font
  • imageopenpolygon — Draws an open polygon
  • imagepalettecopy — Copy the palette from one image to another
  • imagepalettetotruecolor — Converts a palette based image to true color
  • 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
  • imageresolution — Get or set the resolution of the image
  • 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
  • imagescale — Scale an image using the given new width and height
  • imagesetbrush — Set the brush image for line drawing
  • imagesetclip — Set the clipping rectangle
  • imagesetinterpolation — Set the interpolation method
  • 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 — Afi?eaza imaginea în navigator sau în fi?ier
  • imagewebp — Output a WebP image to browser or file
  • imagexbm — Output an 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

Func?ii GD ?i Image
getimagesize
Func?ii GD ?i Image
PHP Manual

gd_info

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

gd_info — Retrieve information about the currently installed GD library

Descrierea

array gd_info ( void )

Gets information about the version and capabilities of the installed GD library.

Valorile întoarse

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.
WebP Support | boolean value. TRUE if WebP support is included.

Nota:

Previous to PHP 5.3.0, the JPEG Support attribute was named JPG Support.

Exemple

Example #1 Using gd_info()

<?php
var_dump(gd_info());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(10) {
  ["GD Version"]=>
  string(24) "bundled (2.1.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)
  ["WebP Support"]=>
  bool(false)
}

Istoricul schimbarilor

Versiune | Descriere
5.6.12 | WebP Support added.
5.3.0 | JPG Support attribute renamed to JPEG Support.

A se vedea ?i

  • imagepng() - Output a PNG image to either the browser or a file
  • imagejpeg() - Afi?eaza imaginea în navigator sau în fi?ier
  • imagegif() - Afi?eaza imaginea în navigator sau în fi?ier
  • imagewbmp() - Afi?eaza imaginea în navigator sau în fi?ier
  • imagewebp() - Output a WebP image to browser or file
  • imagetypes() - Return the image types supported by this PHP build

Func?ii GD ?i Image
getimagesize
Func?ii GD ?i Image


Get the size of an image

gd_info
getimagesizefromstring
Func?ii GD ?i Image
PHP Manual

getimagesize

(PHP 4, PHP 5, PHP 7)

getimagesize — Get the size of an image

Descrierea

array getimagesize ( string $filename [, array &$imageinfo ] )

The getimagesize() function will determine the size of any supported 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 correspondent HTTP content type.

getimagesize() can also return some more information in imageinfo parameter.

Nota: 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.

Nota: The information about icons are retrieved from the icon with the highest bitrate.

Parametri

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.

Valorile întoarse

Returns an array with up to 7 elements. Not all image types will include the channels and bits elements.

Index 0 and 1 contains respectively the width and the height of the image.

Nota:

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:

Example #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.

Erori/Excep?ii

If accessing the filename image is impossible getimagesize() will generate an error of level E_WARNING. On read error, getimagesize() will generate an error of level E_NOTICE.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Added WebP support.
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 | 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.

Exemple

Example #2 getimagesize() example

<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";
?>

Example #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");

?>

Example #4 getimagesize() returning IPTC

<?php
$size = getimagesize("testimg.jpg", $info);
if (isset($info["APP13"])) {
    $iptc = iptcparse($info["APP13"]);
    var_dump($iptc);
}
?>

Note

Nota:

Aceasta func?ie nu necesita biblioteca de prelucrare a imaginilor GD.

Nota:

This function expects filename to be a valid image file. If a non-image file is supplied, it may be incorrectly detected as an image and the function will return successfully.

Do not use getimagesize() to check that a given file is a valid image. Use a purpose-built solution such as the Fileinfo extension instead.

A se vedea ?i

  • 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
getimagesizefromstring
Func?ii GD ?i Image


Get the size of an image from a string

getimagesize
image_type_to_extension
Func?ii GD ?i Image
PHP Manual

getimagesizefromstring

(PHP 5 >= 5.4.0, PHP 7)

getimagesizefromstring — Get the size of an image from a string

Descrierea

array getimagesizefromstring ( string $imagedata [, array &$imageinfo ] )

Identical to getimagesize() except that getimagesizefromstring() accepts a string instead of a file name as the first parameter.

See the getimagesize() documentation for details on how this function works.

Parametri

imagedata

The image data, as a string.

imageinfo

See getimagesize().

Valorile întoarse

See getimagesize().

Exemple

Example #1 getimagesizefromstring() example

<?php
$img = '/path/to/test.png';

// Open as a file
$size_info1 = getimagesize($img);

// Or open as a string
$data       = file_get_contents($img);
$size_info2 = getimagesizefromstring($data);
?>

A se vedea ?i

  • getimagesize() - Get the size of an image

getimagesize
image_type_to_extension
Func?ii GD ?i Image


Get file extension for image type

getimagesizefromstring
image_type_to_mime_type
Func?ii GD ?i Image
PHP Manual

image_type_to_extension

(PHP 5 >= 5.2.0, PHP 7)

image_type_to_extension — Get file extension for image type

Descrierea

string image_type_to_extension ( int $imagetype [, bool $include_dot = TRUE ] )

Returns the extension for the given IMAGETYPE_XXX constant.

Parametri

imagetype

One of the IMAGETYPE_XXX constant.

include_dot

Whether to prepend a dot to the extension or not. Default to TRUE.

Valorile întoarse

A string with the extension corresponding to the given image type.

Exemple

Example #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);
?>

Note

Nota:

Aceasta func?ie nu necesita biblioteca de prelucrare a imaginilor GD.

getimagesizefromstring
image_type_to_mime_type
Func?ii GD ?i Image


Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

image_type_to_extension
image2wbmp
Func?ii GD ?i Image
PHP Manual

image_type_to_mime_type

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

image_type_to_mime_type — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

Descrierea

string image_type_to_mime_type ( int $imagetype )

The image_type_to_mime_type() function will determine the Mime-Type for an IMAGETYPE constant.

Parametri

imagetype

One of the IMAGETYPE_XXX constants.

Valorile întoarse

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

Exemple

Example #1 image_type_to_mime_type() example

<?php
header("Content-type: " . image_type_to_mime_type(IMAGETYPE_PNG));
?>

Note

Nota:

Aceasta func?ie nu necesita biblioteca de prelucrare a imaginilor GD.

A se vedea ?i

  • 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
Func?ii GD ?i Image


Afi?eaza imaginea în navigator sau în fi?ier

image_type_to_mime_type
imageaffine
Func?ii GD ?i Image
PHP Manual

image2wbmp

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

image2wbmp — Afi?eaza imaginea în navigator sau în fi?ier

Descrierea

bool image2wbmp ( resource $image [, string $filename [, int $threshold ]] )

image2wbmp() outputs or save a WBMP version of the given image.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

filename

Path to the saved file. If not given, the raw image stream will be output directly.

threshold

Threshold value, between 0 and 255 (inclusive).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • imagewbmp() - Afi?eaza imaginea în navigator sau în fi?ier

image_type_to_mime_type
imageaffine
Func?ii GD ?i Image


Return an image containing the affine transformed src image, using an optional clipping area

image2wbmp
imageaffinematrixconcat
Func?ii GD ?i Image
PHP Manual

imageaffine

(PHP 5 >= 5.5.0, PHP 7)

imageaffine — Return an image containing the affine transformed src image, using an optional clipping area

Descrierea

resource imageaffine ( resource $image , array $affine [, array $clip ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

affine

Array with keys 0 to 5.

clip

Array with keys "x", "y", "width" and "height".

Valorile întoarse

Return affined image resource on success sau FALSE în cazul e?ecului.

image2wbmp
imageaffinematrixconcat
Func?ii GD ?i Image


Concatenate two affine transformation matrices

imageaffine
imageaffinematrixget
Func?ii GD ?i Image
PHP Manual

imageaffinematrixconcat

(PHP 5 >= 5.5.0, PHP 7)

imageaffinematrixconcat — Concatenate two affine transformation matrices

Descrierea

array imageaffinematrixconcat ( array $m1 , array $m2 )

Returns the concatenation of two affine transformation matrices, what is useful if multiple transformations should be applied to the same image in one go.

Parametri

m1

An affine transformation matrix (an array with keys 0 to 5 and float values).

m2

An affine transformation matrix (an array with keys 0 to 5 and float values).

Valorile întoarse

An affine transformation matrix (an array with keys 0 to 5 and float values) sau FALSE în cazul e?ecului.

Exemple

Example #1 imageaffinematrixconcat() example

<?php
$m1 = imageaffinematrixget(IMG_AFFINE_TRANSLATE, array('x' = 2, 'y' => 3));
$m2 = imageaffinematrixget(IMG_AFFINE_SCALE, array('x' = 4, 'y' => 5));
$matrix = imageaffinematrixconcat($m1, $m2);
print_r($matrix);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => 4
    [1] => 0
    [2] => 0
    [3] => 5
    [4] => 8
    [5] => 15
)

A se vedea ?i

  • imageaffine() - Return an image containing the affine transformed src image, using an optional clipping area
  • imageaffinematrixget() - Get an affine transformation matrix

imageaffine
imageaffinematrixget
Func?ii GD ?i Image


Get an affine transformation matrix

imageaffinematrixconcat
imagealphablending
Func?ii GD ?i Image
PHP Manual

imageaffinematrixget

(PHP 5 >= 5.5.0, PHP 7)

imageaffinematrixget — Get an affine transformation matrix

Descrierea

array imageaffinematrixget ( int $type , mixed $options )

Returns an affine transformation matrix.

Parametri

type

One of the IMG_AFFINE_* constants.

options

If type is IMG_AFFINE_TRANSLATE or IMG_AFFINE_SCALE, options has to be an array with keys x and y, both having float values.

If type is IMG_AFFINE_ROTATE, IMG_AFFINE_SHEAR_HORIZONTAL or IMG_AFFINE_SHEAR_VERTICAL, options has to be a float specifying the angle.

Valorile întoarse

An affine transformation matrix (an array with keys 0 to 5 and float values) sau FALSE în cazul e?ecului.

Exemple

Example #1 imageaffinematrixget() example

<?php
$matrix = imageaffinematrixget(IMG_AFFINE_TRANSLATE, array('x' = 2, 'y' => 3));
print_r($matrix);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => 1
    [1] => 0
    [2] => 0
    [3] => 1
    [4] => 2
    [5] => 3
)

A se vedea ?i

  • imageaffine() - Return an image containing the affine transformed src image, using an optional clipping area
  • imageaffinematrixconcat() - Concatenate two affine transformation matrices

imageaffinematrixconcat
imagealphablending
Func?ii GD ?i Image


Set the blending mode for an image

imageaffinematrixget
imageantialias
Func?ii GD ?i Image
PHP Manual

imagealphablending

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagealphablending — Set the blending mode for an image

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>
imageaffinematrixget
imageantialias
Func?ii GD ?i Image


Should antialias functions be used or not

imagealphablending
imagearc
Func?ii GD ?i Image
PHP Manual

imageantialias

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

imageantialias — Should antialias functions be used or not

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

enabled

Whether to enable antialiasing or not.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.2.0 | imageantialias() is now generally available. Formerly it was only available if PHP was compiled with the bundled version of the GD library.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : A comparison of two lines, one with anti-aliasing switched on

A se vedea ?i

  • imagecreatetruecolor() - Create a new true color image

imagealphablending
imagearc
Func?ii GD ?i Image


Draws an arc

imageantialias
imagebmp
Func?ii GD ?i Image
PHP Manual

imagearc

(PHP 4, PHP 5, PHP 7)

imagearc — Draws an arc

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Drawing a circle with imagearc()

A se vedea ?i

  • imagefilledarc() - Draw a partial arc and fill it
  • imageellipse() - Draw an ellipse
  • imagefilledellipse() - Draw a filled ellipse

imageantialias
imagebmp
Func?ii GD ?i Image


Output a BMP image to browser or file

imagearc
imagechar
Func?ii GD ?i Image
PHP Manual

imagebmp

(PHP 7 >= 7.2.0)

imagebmp — Output a BMP image to browser or file

Descrierea

bool imagebmp ( resource $image , mixed $to [, bool $compressed = TRUE ] )

Outputs or saves a BMP version of the given image.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

to

Calea unde va fi salvat fi?ierul. Daca nu este stabilita sau este NULL, atunci fluxul imaginii va fi afi?at direct.

compressed

Whether the BMP should be compressed with run-length encoding (RLE), or not.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Saving a BMP 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,  'BMP with PHP', $text_color);

// Save the image
imagebmp($im, 'php.bmp');

// Free up memory
imagedestroy($im);
?>

imagearc
imagechar
Func?ii GD ?i Image


Draw a character horizontally

imagebmp
imagecharup
Func?ii GD ?i Image
PHP Manual

imagechar

(PHP 4, PHP 5, PHP 7)

imagechar — Draw a character horizontally

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

font

Poate fi 1, 2, 3, 4, 5 pentru font-urile încorporate cu codificarea latin2 (unde numerele mai mari corespund font-urilor mai mari) sau orice identificator de font al dumneavoastra, înregistrat cu 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagechar()

A se vedea ?i

  • imagecharup() - Draw a character vertically
  • imageloadfont() - Load a new font

imagebmp
imagecharup
Func?ii GD ?i Image


Draw a character vertically

imagechar
imagecolorallocate
Func?ii GD ?i Image
PHP Manual

imagecharup

(PHP 4, PHP 5, PHP 7)

imagecharup — Draw a character vertically

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

font

Poate fi 1, 2, 3, 4, 5 pentru font-urile încorporate cu codificarea latin2 (unde numerele mai mari corespund font-urilor mai mari) sau orice identificator de font al dumneavoastra, înregistrat cu 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagecharup()

A se vedea ?i

  • imagechar() - Draw a character horizontally
  • imageloadfont() - Load a new font

imagechar
imagecolorallocate
Func?ii GD ?i Image


Allocate a color for an image

imagecharup
imagecolorallocatealpha
Func?ii GD ?i Image
PHP Manual

imagecolorallocate

(PHP 4, PHP 5, PHP 7)

imagecolorallocate — Allocate a color for an image

Descrierea

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.

Nota:

The first call to imagecolorallocate() fills the background color in palette-based images - images created using imagecreate().

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

red

Valoarea componentei ro?ii.

green

Valoarea componentei verzi.

blue

Valoarea componentei albastre.

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Valorile întoarse

A color identifier or FALSE if the allocation failed.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Istoricul schimbarilor

Versiune | Descriere
5.1.3 | Returns FALSE if the allocation failed. Previously -1 was returned.

Exemple

Example #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);

?>

A se vedea ?i

  • imagecolorallocatealpha() - Allocate a color for an image
  • imagecolordeallocate() - De-allocate a color for an image

imagecharup
imagecolorallocatealpha
Func?ii GD ?i Image


Allocate a color for an image

imagecolorallocate
imagecolorat
Func?ii GD ?i Image
PHP Manual

imagecolorallocatealpha

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

imagecolorallocatealpha — Allocate a color for an image

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

red

Valoarea componentei ro?ii.

green

Valoarea componentei verzi.

blue

Valoarea componentei albastre.

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The red, green and blue parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Valorile întoarse

A color identifier or FALSE if the allocation failed.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Istoricul schimbarilor

Versiune | Descriere
5.1.3 | Returns FALSE if the allocation failed. Previously -1 was returned.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Example of using imagecolorallocatealpha()

A se vedea ?i

  • imagecolorallocate() - Allocate a color for an image
  • imagecolordeallocate() - De-allocate a color for an image

imagecolorallocate
imagecolorat
Func?ii GD ?i Image


Get the index of the color of a pixel

imagecolorallocatealpha
imagecolorclosest
Func?ii GD ?i Image
PHP Manual

imagecolorat

(PHP 4, PHP 5, PHP 7)

imagecolorat — Get the index of the color of a pixel

Descrierea

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 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:

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

x

x-coordinate of the point.

y

y-coordinate of the point.

Valorile întoarse

Returns the index of the color.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(119)
int(123)
int(180)

Example #2 Human-readable RGB values using imagecolorsforindex()

<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);

$colors = imagecolorsforindex($im, $rgb);

var_dump($colors);
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(4) {
  ["red"]=>
  int(119)
  ["green"]=>
  int(123)
  ["blue"]=>
  int(180)
  ["alpha"]=>
  int(127)
}

A se vedea ?i

  • imagecolorset() - Set the color for the specified palette index
  • imagecolorsforindex() - Get the colors for an index
  • imagesetpixel() - Set a single pixel

imagecolorallocatealpha
imagecolorclosest
Func?ii GD ?i Image


Get the index of the closest color to the specified color

imagecolorat
imagecolorclosestalpha
Func?ii GD ?i Image
PHP Manual

imagecolorclosest

(PHP 4, PHP 5, PHP 7)

imagecolorclosest — Get the index of the closest color to the specified color

Descrierea

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.

Daca a?i creat imaginea din fi?ier atunci sunt determinate doar culorile utilizate în imagine. Culorile prezente doar în paleta nu sunt determinate.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

red

Valoarea componentei ro?ii.

green

Valoarea componentei verzi.

blue

Valoarea componentei albastre.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Valorile întoarse

Returns the index of the closest color, in the palette of the image, to the specified one

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

#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).

A se vedea ?i

  • 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
Func?ii GD ?i Image


Get the index of the closest color to the specified color + alpha

imagecolorclosest
imagecolorclosesthwb
Func?ii GD ?i Image
PHP Manual

imagecolorclosestalpha

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

red

Valoarea componentei ro?ii.

green

Valoarea componentei verzi.

blue

Valoarea componentei albastre.

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.

Valorile întoarse

Returns the index of the closest color in the palette.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

#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).

A se vedea ?i

  • 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
Func?ii GD ?i Image


Get the index of the color which has the hue, white and blackness

imagecolorclosestalpha
imagecolordeallocate
Func?ii GD ?i Image
PHP Manual

imagecolorclosesthwb

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

red

Valoarea componentei ro?ii.

green

Valoarea componentei verzi.

blue

Valoarea componentei albastre.

Valorile întoarse

Returns an integer with the index of the color which has the hue, white and blackness nearest the given color.

Exemple

Example #1 Example of using imagecolorclosesthwb()

<?php
$im = imagecreatefromgif('php.gif');

echo 'HWB: ' . imagecolorclosesthwb($im, 116, 115, 152);

imagedestroy($im);
?>

Exemplul de mai sus va afi?a ceva similar cu:

HWB: 33

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on Windows

A se vedea ?i

  • imagecolorclosest() - Get the index of the closest color to the specified color

imagecolorclosestalpha
imagecolordeallocate
Func?ii GD ?i Image


De-allocate a color for an image

imagecolorclosesthwb
imagecolorexact
Func?ii GD ?i Image
PHP Manual

imagecolordeallocate

(PHP 4, PHP 5, PHP 7)

imagecolordeallocate — De-allocate a color for an image

Descrierea

bool imagecolordeallocate ( resource $image , int $color )

De-allocates a color previously allocated with imagecolorallocate() or imagecolorallocatealpha().

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

color

The color identifier.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Using imagecolordeallocate()

<?php
$white = imagecolorallocate($im, 255, 255, 255);
imagecolordeallocate($im, $white);
?>

A se vedea ?i

  • imagecolorallocate() - Allocate a color for an image
  • imagecolorallocatealpha() - Allocate a color for an image

imagecolorclosesthwb
imagecolorexact
Func?ii GD ?i Image


Get the index of the specified color

imagecolordeallocate
imagecolorexactalpha
Func?ii GD ?i Image
PHP Manual

imagecolorexact

(PHP 4, PHP 5, PHP 7)

imagecolorexact — Get the index of the specified color

Descrierea

int imagecolorexact ( resource $image , int $red , int $green , int $blue )

Returns the index of the specified color in the palette of the image.

Daca a?i creat imaginea din fi?ier atunci sunt determinate doar culorile utilizate în imagine. Culorile prezente doar în paleta nu sunt determinate.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

red

Valoarea componentei ro?ii.

green

Valoarea componentei verzi.

blue

Valoarea componentei albastre.

Valorile întoarse

Returns the index of the specified color in the palette, or -1 if the color does not exist.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => 16711680
    [1] => 0
    [2] => 16777215
    [3] => 6618932
)

A se vedea ?i

  • imagecolorclosest() - Get the index of the closest color to the specified color

imagecolordeallocate
imagecolorexactalpha
Func?ii GD ?i Image


Get the index of the specified color + alpha

imagecolorexact
imagecolormatch
Func?ii GD ?i Image
PHP Manual

imagecolorexactalpha

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagecolorexactalpha — Get the index of the specified color + alpha

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

red

Valoarea componentei ro?ii.

green

Valoarea componentei verzi.

blue

Valoarea componentei albastre.

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.

Valorile întoarse

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.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => 16711680
    [1] => 2130706432
    [2] => 939524095
    [3] => 342163252
)

A se vedea ?i

  • imagecolorclosestalpha() - Get the index of the closest color to the specified color + alpha

imagecolorexact
imagecolormatch
Func?ii GD ?i Image


Makes the colors of the palette version of an image more closely match the true color version

imagecolorexactalpha
imagecolorresolve
Func?ii GD ?i Image
PHP Manual

imagecolormatch

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version

Descrierea

bool imagecolormatch ( resource $image1 , resource $image2 )

Makes the colors of the palette version of an image more closely match the true color version.

Parametri

image1

A truecolor image link resource.

image2

A palette image link resource pointing to an image that has the same size as image1.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • imagecreatetruecolor() - Create a new true color image

imagecolorexactalpha
imagecolorresolve
Func?ii GD ?i Image


Get the index of the specified color or its closest possible alternative

imagecolormatch
imagecolorresolvealpha
Func?ii GD ?i Image
PHP Manual

imagecolorresolve

(PHP 4, PHP 5, PHP 7)

imagecolorresolve — Get the index of the specified color or its closest possible alternative

Descrierea

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.

Daca a?i creat imaginea din fi?ier atunci sunt determinate doar culorile utilizate în imagine. Culorile prezente doar în paleta nu sunt determinate.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

red

Valoarea componentei ro?ii.

green

Valoarea componentei verzi.

blue

Valoarea componentei albastre.

Valorile întoarse

Returns a color index.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => 89
    [1] => 85
)

A se vedea ?i

  • imagecolorclosest() - Get the index of the closest color to the specified color

imagecolormatch
imagecolorresolvealpha
Func?ii GD ?i Image


Get the index of the specified color + alpha or its closest possible alternative

imagecolorresolve
imagecolorset
Func?ii GD ?i Image
PHP Manual

imagecolorresolvealpha

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

red

Valoarea componentei ro?ii.

green

Valoarea componentei verzi.

blue

Valoarea componentei albastre.

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.

Valorile întoarse

Returns a color index.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => 89
    [1] => 85
)

A se vedea ?i

  • imagecolorclosestalpha() - Get the index of the closest color to the specified color + alpha

imagecolorresolve
imagecolorset
Func?ii GD ?i Image


Set the color for the specified palette index

imagecolorresolvealpha
imagecolorsforindex
Func?ii GD ?i Image
PHP Manual

imagecolorset

(PHP 4, PHP 5, PHP 7)

imagecolorset — Set the color for the specified palette index

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

index

An index in the palette.

red

Valoarea componentei ro?ii.

green

Valoarea componentei verzi.

blue

Valoarea componentei albastre.

alpha

Value of alpha component.

Valorile întoarse

Nu este întoarsa nici o valoare.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | The alpha parameter was added.

Exemple

Example #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);
?>

A se vedea ?i

  • imagecolorat() - Get the index of the color of a pixel

imagecolorresolvealpha
imagecolorsforindex
Func?ii GD ?i Image


Get the colors for an index

imagecolorset
imagecolorstotal
Func?ii GD ?i Image
PHP Manual

imagecolorsforindex

(PHP 4, PHP 5, PHP 7)

imagecolorsforindex — Get the colors for an index

Descrierea

array imagecolorsforindex ( resource $image , int $index )

Gets the color for a specified index.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

index

The color index.

Valorile întoarse

Returns an associative array with red, green, blue and alpha keys that contain the appropriate values for the specified color index.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
   [red] => 226
   [green] => 222
   [blue] => 252
   [alpha] => 0
)

A se vedea ?i

  • imagecolorat() - Get the index of the color of a pixel
  • imagecolorexact() - Get the index of the specified color

imagecolorset
imagecolorstotal
Func?ii GD ?i Image


Find out the number of colors in an image's palette

imagecolorsforindex
imagecolortransparent
Func?ii GD ?i Image
PHP Manual

imagecolorstotal

(PHP 4, PHP 5, PHP 7)

imagecolorstotal — Find out the number of colors in an image's palette

Descrierea

int imagecolorstotal ( resource $image )

Returns the number of colors in an image palette.

Parametri

image

An image resource, returned by one of the image creation functions, such as imagecreatefromgif().

Valorile întoarse

Returns the number of colors in the specified image's palette or 0 for truecolor images.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Total colors in image: 128

A se vedea ?i

  • 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
Func?ii GD ?i Image


Define a color as transparent

imagecolorstotal
imageconvolution
Func?ii GD ?i Image
PHP Manual

imagecolortransparent

(PHP 4, PHP 5, PHP 7)

imagecolortransparent — Define a color as transparent

Descrierea

int imagecolortransparent ( resource $image [, int $color ] )

Sets the transparent color in the given image.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

color

A color identifier created with imagecolorallocate().

Valorile întoarse

The identifier of the new (or current, if none is specified) transparent color is returned. If color is not specified, and the image has no transparent color, the returned identifier will be -1.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagecolortransparent()

Note

Nota:

Transparency is copied only with imagecopymerge() and true color images, not with imagecopy() or pallete images.

Nota:

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
Func?ii GD ?i Image


Apply a 3x3 convolution matrix, using coefficient and offset

imagecolortransparent
imagecopy
Func?ii GD ?i Image
PHP Manual

imageconvolution

(PHP 5 >= 5.1.0, PHP 7)

imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset

Descrierea

bool imageconvolution ( resource $image , array $matrix , float $div , float $offset )

Applies a convolution matrix on the image, using the given coefficient and offset.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

Output of example : Embossing the PHP.net logo

Example #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);
?>

Exemplul de mai sus va afi?a:

Output of example : Gaussian blur

Note

This function requires GD 2.1.0 or higher.

A se vedea ?i

  • imagefilter() - Applies a filter to an image

imagecolortransparent
imagecopy
Func?ii GD ?i Image


Copy part of an image

imageconvolution
imagecopymerge
Func?ii GD ?i Image
PHP Manual

imagecopy

(PHP 4, PHP 5, PHP 7)

imagecopy — Copy part of an image

Descrierea

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.

Parametri

dst_im

Resursa referin?ei imaginii destina?ie.

src_im

Resursa referin?ei imaginii sursa.

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

La?imea sursei.

src_h

Înal?imea sursei.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Cropping the PHP.net logo

imageconvolution
imagecopymerge
Func?ii GD ?i Image


Copy and merge part of an image

imagecopy
imagecopymergegray
Func?ii GD ?i Image
PHP Manual

imagecopymerge

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagecopymerge — Copy and merge part of an image

Descrierea

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.

Parametri

dst_im

Resursa referin?ei imaginii destina?ie.

src_im

Resursa referin?ei imaginii sursa.

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

La?imea sursei.

src_h

Înal?imea sursei.

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, except for ignoring alpha components, while it implements alpha transparency for true colour images.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii GD ?i Image


Copy and merge part of an image with gray scale

imagecopymerge
imagecopyresampled
Func?ii GD ?i Image
PHP Manual

imagecopymergegray

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagecopymergegray — Copy and merge part of an image with gray scale

Descrierea

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.

Parametri

dst_im

Resursa referin?ei imaginii destina?ie.

src_im

Resursa referin?ei imaginii sursa.

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

La?imea sursei.

src_h

Înal?imea sursei.

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, except for ignoring alpha components, while it implements alpha transparency for true colour images.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii GD ?i Image


Copy and resize part of an image with resampling

imagecopymergegray
imagecopyresized
Func?ii GD ?i Image
PHP Manual

imagecopyresampled

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagecopyresampled — Copy and resize part of an image with resampling

Descrierea

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 a 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.

Parametri

dst_image

Resursa referin?ei imaginii destina?ie.

src_image

Resursa referin?ei imaginii sursa.

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

La?imea sursei.

src_h

Înal?imea sursei.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Simple example

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Resampling an image proportionally

Note

Nota:

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().

A se vedea ?i

imagecopyresized() - Copy and resize part of an image

imagecopymergegray
imagecopyresized
Func?ii GD ?i Image


Copy and resize part of an image

imagecopyresampled
imagecreate
Func?ii GD ?i Image
PHP Manual

imagecopyresized

(PHP 4, PHP 5, PHP 7)

imagecopyresized — Copy and resize part of an image

Descrierea

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 a 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.

Parametri

dst_image

Resursa referin?ei imaginii destina?ie.

src_image

Resursa referin?ei imaginii sursa.

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

La?imea sursei.

src_h

Înal?imea sursei.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Resizing an image

The image will be output at half size, though better quality could be obtained using imagecopyresampled().

Note

Nota:

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().

A se vedea ?i

imagecopyresampled() - Copy and resize part of an image with resampling

imagecopyresampled
imagecreate
Func?ii GD ?i Image


Create a new palette based image

imagecopyresized
imagecreatefrombmp
Func?ii GD ?i Image
PHP Manual

imagecreate

(PHP 4, PHP 5, PHP 7)

imagecreate — Create a new palette based image

Descrierea

resource imagecreate ( int $width , int $height )

imagecreate() returns an image identifier representing a blank image of specified size.

In general, we recommend the use of imagecreatetruecolor() instead of imagecreate() so that image processing occurs on the highest quality image possible. If you want to output a palette image, then imagetruecolortopalette() should be called immediately before saving the image with imagepng() or imagegif().

Parametri

width

The image width.

height

The image height.

Valorile întoarse

Întoarce un identificator de resursa de tip imagine în cazul succesului, FALSE în caz de erori.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Creating a new GD image stream and outputting an image.

A se vedea ?i

  • imagedestroy() - Destroy an image
  • imagecreatetruecolor() - Create a new true color image

imagecopyresized
imagecreatefrombmp
Func?ii GD ?i Image


Creeaza o imagine noua din fi?ier sau din URL

imagecreate
imagecreatefromgd2
Func?ii GD ?i Image
PHP Manual

imagecreatefrombmp

(PHP 7 >= 7.2.0)

imagecreatefrombmp — Creeaza o imagine noua din fi?ier sau din URL

Descrierea

resource imagecreatefrombmp ( string $filename )

imagecreatefrombmp() returns an image identifier representing the image obtained from the given filename.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

Parametri

filename

Path to the BMP image.

Valorile întoarse

Întoarce un identificator de resursa de tip imagine în cazul succesului, FALSE în caz de erori.

Exemple

Example #1 Convert an BMP image to a PNG image using imagecreatefrombmp()

<?php
// Load the BMP file
$im = imagecreatefrombmp('./example.bmp');

// Convert it to a PNG file with default settings
imagepng($im, './example.png');
imagedestroy($im);
?>

imagecreate
imagecreatefromgd2
Func?ii GD ?i Image


Create a new image from GD2 file or URL

imagecreatefrombmp
imagecreatefromgd2part
Func?ii GD ?i Image
PHP Manual

imagecreatefromgd2

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imagecreatefromgd2 — Create a new image from GD2 file or URL

Descrierea

resource imagecreatefromgd2 ( string $filename )

Create a new image from GD2 file or URL.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

Parametri

filename

Path to the GD2 image.

Valorile întoarse

Întoarce un identificator de resursa de tip imagine în cazul succesului, FALSE în caz de erori.

Exemple

Example #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);
?>

imagecreatefrombmp
imagecreatefromgd2part
Func?ii GD ?i Image


Create a new image from a given part of GD2 file or URL

imagecreatefromgd2
imagecreatefromgd
Func?ii GD ?i Image
PHP Manual

imagecreatefromgd2part

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL

Descrierea

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.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

Parametri

filename

Path to the GD2 image.

srcX

x-coordinate of source point.

srcY

y-coordinate of source point.

width

La?imea sursei.

height

Înal?imea sursei.

Valorile întoarse

Întoarce un identificator de resursa de tip imagine în cazul succesului, FALSE în caz de erori.

Exemple

Example #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);
?>

imagecreatefromgd2
imagecreatefromgd
Func?ii GD ?i Image


Create a new image from GD file or URL

imagecreatefromgd2part
imagecreatefromgif
Func?ii GD ?i Image
PHP Manual

imagecreatefromgd

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imagecreatefromgd — Create a new image from GD file or URL

Descrierea

resource imagecreatefromgd ( string $filename )

Create a new image from GD file or URL.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

Parametri

filename

Path to the GD file.

Valorile întoarse

Întoarce un identificator de resursa de tip imagine în cazul succesului, FALSE în caz de erori.

Exemple

Example #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);
?>

imagecreatefromgd2part
imagecreatefromgif
Func?ii GD ?i Image


Creeaza o imagine noua din fi?ier sau din URL

imagecreatefromgd
imagecreatefromjpeg
Func?ii GD ?i Image
PHP Manual

imagecreatefromgif

(PHP 4, PHP 5, PHP 7)

imagecreatefromgif — Creeaza o imagine noua din fi?ier sau din URL

Descrierea

resource imagecreatefromgif ( string $filename )

imagecreatefromgif() returns an image identifier representing the image obtained from the given filename.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

Parametri

filename

Path to the GIF image.

Valorile întoarse

Întoarce un identificator de resursa de tip imagine în cazul succesului, FALSE în caz de erori.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Example to handle an error during loading of a GIF

Note

Nota:

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.

Nota:

When reading animated GIF files into memory, only the first frame is returned in the image resource pointer.

imagecreatefromgd
imagecreatefromjpeg
Func?ii GD ?i Image


Creeaza o imagine noua din fi?ier sau din URL

imagecreatefromgif
imagecreatefrompng
Func?ii GD ?i Image
PHP Manual

imagecreatefromjpeg

(PHP 4, PHP 5, PHP 7)

imagecreatefromjpeg — Creeaza o imagine noua din fi?ier sau din URL

Descrierea

resource imagecreatefromjpeg ( string $filename )

imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

Parametri

filename

Path to the JPEG image.

Valorile întoarse

Întoarce un identificator de resursa de tip imagine în cazul succesului, FALSE în caz de erori.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Example to handle an error during loading of a JPEG
imagecreatefromgif
imagecreatefrompng
Func?ii GD ?i Image


Creeaza o imagine noua din fi?ier sau din URL

imagecreatefromjpeg
imagecreatefromstring
Func?ii GD ?i Image
PHP Manual

imagecreatefrompng

(PHP 4, PHP 5, PHP 7)

imagecreatefrompng — Creeaza o imagine noua din fi?ier sau din URL

Descrierea

resource imagecreatefrompng ( string $filename )

imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

Parametri

filename

Path to the PNG image.

Valorile întoarse

Întoarce un identificator de resursa de tip imagine în cazul succesului, FALSE în caz de erori.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

imagecreatefromjpeg
imagecreatefromstring
Func?ii GD ?i Image


Create a new image from the image stream in the string

imagecreatefrompng
imagecreatefromwbmp
Func?ii GD ?i Image
PHP Manual

imagecreatefromstring

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

imagecreatefromstring — Create a new image from the image stream in the string

Descrierea

resource imagecreatefromstring ( string $image )

imagecreatefromstring() returns an image identifier representing the image obtained from the given image. These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, BMP, WBMP, and GD2.

Parametri

image

A string containing the image data.

Valorile întoarse

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.

Erori/Excep?ii

imagecreatefromstring() raises an E_WARNING level error, if the data is not in a recognized format.

Exemple

Example #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.';
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagecreatefromstring()

A se vedea ?i

  • imagecreatefromjpeg() - Creeaza o imagine noua din fi?ier sau din URL
  • imagecreatefrompng() - Creeaza o imagine noua din fi?ier sau din URL
  • imagecreatefromgif() - Creeaza o imagine noua din fi?ier sau din URL
  • imagecreatetruecolor() - Create a new true color image

imagecreatefrompng
imagecreatefromwbmp
Func?ii GD ?i Image


Creeaza o imagine noua din fi?ier sau din URL

imagecreatefromstring
imagecreatefromwebp
Func?ii GD ?i Image
PHP Manual

imagecreatefromwbmp

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagecreatefromwbmp — Creeaza o imagine noua din fi?ier sau din URL

Descrierea

resource imagecreatefromwbmp ( string $filename )

imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

Parametri

filename

Path to the WBMP image.

Valorile întoarse

Întoarce un identificator de resursa de tip imagine în cazul succesului, FALSE în caz de erori.

Exemple

Example #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);
?>
imagecreatefromstring
imagecreatefromwebp
Func?ii GD ?i Image


Creeaza o imagine noua din fi?ier sau din URL

imagecreatefromwbmp
imagecreatefromxbm
Func?ii GD ?i Image
PHP Manual

imagecreatefromwebp

(PHP 5 >= 5.5.0, PHP 7)

imagecreatefromwebp — Creeaza o imagine noua din fi?ier sau din URL

Descrierea

resource imagecreatefromwebp ( string $filename )

imagecreatefromwebp() returns an image identifier representing the image obtained from the given filename.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

Parametri

filename

Path to the WebP image.

Valorile întoarse

Întoarce un identificator de resursa de tip imagine în cazul succesului, FALSE în caz de erori.

Exemple

Example #1 Convert an WebP image to a jpeg image using imagecreatefromwebp()

<?php
// Load the WebP file
$im = imagecreatefromwebp('./example.webp');

// Convert it to a jpeg file with 100% quality
imagejpeg($im, './example.jpeg', 100);
imagedestroy($im);
?>

imagecreatefromwbmp
imagecreatefromxbm
Func?ii GD ?i Image


Creeaza o imagine noua din fi?ier sau din URL

imagecreatefromwebp
imagecreatefromxpm
Func?ii GD ?i Image
PHP Manual

imagecreatefromxbm

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagecreatefromxbm — Creeaza o imagine noua din fi?ier sau din URL

Descrierea

resource imagecreatefromxbm ( string $filename )

imagecreatefromxbm() returns an image identifier representing the image obtained from the given filename.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

Parametri

filename

Path to the XBM image.

Valorile întoarse

Întoarce un identificator de resursa de tip imagine în cazul succesului, FALSE în caz de erori.

Exemple

Example #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);
?>

imagecreatefromwebp
imagecreatefromxpm
Func?ii GD ?i Image


Creeaza o imagine noua din fi?ier sau din URL

imagecreatefromxbm
imagecreatetruecolor
Func?ii GD ?i Image
PHP Manual

imagecreatefromxpm

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagecreatefromxpm — Creeaza o imagine noua din fi?ier sau din URL

Descrierea

resource imagecreatefromxpm ( string $filename )

imagecreatefromxpm() returns an image identifier representing the image obtained from the given filename.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

Parametri

filename

Path to the XPM image.

Valorile întoarse

Întoarce un identificator de resursa de tip imagine în cazul succesului, FALSE în caz de erori.

Istoricul schimbarilor

Versiune | Descriere
5.3.19 | imagecreatefromxpm() is available on Windows.

Exemple

Example #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);
?>

imagecreatefromxbm
imagecreatetruecolor
Func?ii GD ?i Image


Create a new true color image

imagecreatefromxpm
imagecrop
Func?ii GD ?i Image
PHP Manual

imagecreatetruecolor

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagecreatetruecolor — Create a new true color image

Descrierea

resource imagecreatetruecolor ( int $width , int $height )

imagecreatetruecolor() returns an image identifier representing a black image of the specified size.

Parametri

width

Image width.

height

Image height.

Valorile întoarse

Întoarce un identificator de resursa de tip imagine în cazul succesului, FALSE în caz de erori.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Creating a new GD image stream and outputting an image.

A se vedea ?i

  • imagedestroy() - Destroy an image
  • imagecreate() - Create a new palette based image

imagecreatefromxpm
imagecrop
Func?ii GD ?i Image


Crop an image to the given rectangle

imagecreatetruecolor
imagecropauto
Func?ii GD ?i Image
PHP Manual

imagecrop

(PHP 5 >= 5.5.0, PHP 7)

imagecrop — Crop an image to the given rectangle

Descrierea

resource imagecrop ( resource $image , array $rect )

Crops an image to the given rectangular area and returns the resulting image. The given image is not modified.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

rect

The cropping rectangle as array with keys x, y, width and height.

Valorile întoarse

Return cropped image resource on success sau FALSE în cazul e?ecului.

Exemple

Example #1 imagecrop() example

This example shows how to crop an image to a square area.

<?php
$im = imagecreatefrompng('example.png');
$size = min(imagesx($im), imagesy($im));
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size]);
if ($im2 !== FALSE) {
    imagepng($im2, 'example-cropped.png');
}
?>

A se vedea ?i

  • imagecropauto() - Crop an image automatically using one of the available modes
imagecreatetruecolor
imagecropauto
Func?ii GD ?i Image


Crop an image automatically using one of the available modes

imagecrop
imagedashedline
Func?ii GD ?i Image
PHP Manual

imagecropauto

(PHP 5 >= 5.5.0, PHP 7)

imagecropauto — Crop an image automatically using one of the available modes

Descrierea

resource imagecropauto ( resource $image [, int $mode = -1 [, float $threshold = .5 [, int $color = -1 ]]] )

Automatically crops an image according to the given mode.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

mode

One of the following constants:

IMG_CROP_DEFAULT
Attempts to use IMG_CROP_TRANSPARENT and if it fails it falls back to IMG_CROP_SIDES.
IMG_CROP_TRANSPARENT
Crops out a transparent background.
IMG_CROP_BLACK
Crops out a black background.
IMG_CROP_WHITE
Crops out a white background.
IMG_CROP_SIDES
Uses the 4 corners of the image to attempt to detect the background to crop.
IMG_CROP_THRESHOLD
Crops an image using the given threshold and color.
threshold

Specifies the tolerance in percent to be used while comparing the image color and the color to crop. The method used to calculate the color difference is based on the color distance in the RGB(a) cube.

Used only in IMG_CROP_THRESHOLD mode.

color

Either an RGB color value or a palette index.

Used only in IMG_CROP_THRESHOLD mode.

Valorile întoarse

Returns a cropped image resource on success sau FALSE în cazul e?ecului. If no cropping would occur, or the complete image would be cropped, that is treated as failure, i.e. imagecrop() returns FALSE.

Exemple

Example #1 Proper handling of auto-cropping

As noted in the return value section, imagecropauto() returns FALSE when there is either nothing to crop or the whole image would be cropped. In this example we have an image resource $im which should be automatically cropped only if there is something to crop; otherwise we want to proceed with the original image.

<?php
$cropped = imagecropauto($im, IMG_CROP_DEFAULT);
if ($cropped !== false) { // in case a new image resource was returned
    imagedestroy($im);    // we destroy the original image
    $im = $cropped;       // and assign the cropped image to $im
}
?>

A se vedea ?i

  • imagecrop() - Crop an image to the given rectangle
imagecrop
imagedashedline
Func?ii GD ?i Image


Draw a dashed line

imagecropauto
imagedestroy
Func?ii GD ?i Image
PHP Manual

imagedashedline

(PHP 4, PHP 5, PHP 7)

imagedashedline — Draw a dashed line

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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().

Valorile întoarse

Always returns true

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagedashedline()

Example #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);
?>

A se vedea ?i

  • imagesetstyle() - Set the style for line drawing
  • imageline() - Draw a line

imagecropauto
imagedestroy
Func?ii GD ?i Image


Destroy an image

imagedashedline
imageellipse
Func?ii GD ?i Image
PHP Manual

imagedestroy

(PHP 4, PHP 5, PHP 7)

imagedestroy — Destroy an image

Descrierea

bool imagedestroy ( resource $image )

imagedestroy() frees any memory associated with image image.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii GD ?i Image


Draw an ellipse

imagedestroy
imagefill
Func?ii GD ?i Image
PHP Manual

imageellipse

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imageellipse — Draw an ellipse

Descrierea

bool imageellipse ( resource $image , int $cx , int $cy , int $width , int $height , int $color )

Draws an ellipse centered at the specified coordinates.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imageellipse()

Note

Nota:

imageellipse() ignores imagesetthickness().

A se vedea ?i

  • imagefilledellipse() - Draw a filled ellipse
  • imagearc() - Draws an arc

imagedestroy
imagefill
Func?ii GD ?i Image


Flood fill

imageellipse
imagefilledarc
Func?ii GD ?i Image
PHP Manual

imagefill

(PHP 4, PHP 5, PHP 7)

imagefill — Flood fill

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

x

x-coordinate of start point.

y

y-coordinate of start point.

color

The fill color. A color identifier created with imagecolorallocate().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagefill()

A se vedea ?i

  • imagecolorallocate() - Allocate a color for an image

imageellipse
imagefilledarc
Func?ii GD ?i Image


Draw a partial arc and fill it

imagefill
imagefilledellipse
Func?ii GD ?i Image
PHP Manual

imagefilledarc

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagefilledarc — Draw a partial arc and fill it

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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'.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Creating a 3D looking pie

imagefill
imagefilledellipse
Func?ii GD ?i Image


Draw a filled ellipse

imagefilledarc
imagefilledpolygon
Func?ii GD ?i Image
PHP Manual

imagefilledellipse

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagefilledellipse — Draw a filled ellipse

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagefilledellipse()

Note

Nota:

imagefilledellipse() ignores imagesetthickness().

A se vedea ?i

  • imageellipse() - Draw an ellipse
  • imagefilledarc() - Draw a partial arc and fill it

imagefilledarc
imagefilledpolygon
Func?ii GD ?i Image


Draw a filled polygon

imagefilledellipse
imagefilledrectangle
Func?ii GD ?i Image
PHP Manual

imagefilledpolygon

(PHP 4, PHP 5, PHP 7)

imagefilledpolygon — Draw a filled polygon

Descrierea

bool imagefilledpolygon ( resource $image , array $points , int $num_points , int $color )

imagefilledpolygon() creates a filled polygon in the given image.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagefilledpolygon()

A se vedea ?i

  • imagepolygon() - Draws a polygon

imagefilledellipse
imagefilledrectangle
Func?ii GD ?i Image


Draw a filled rectangle

imagefilledpolygon
imagefilltoborder
Func?ii GD ?i Image
PHP Manual

imagefilledrectangle

(PHP 4, PHP 5, PHP 7)

imagefilledrectangle — Draw a filled rectangle

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagefilledrectangle()

imagefilledpolygon
imagefilltoborder
Func?ii GD ?i Image


Flood fill to specific color

imagefilledrectangle
imagefilter
Func?ii GD ?i Image
PHP Manual

imagefilltoborder

(PHP 4, PHP 5, PHP 7)

imagefilltoborder — Flood fill to specific color

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Filling an ellipse with a color

imagefilledrectangle
imagefilter
Func?ii GD ?i Image


Applies a filter to an image

imagefilltoborder
imageflip
Func?ii GD ?i Image
PHP Manual

imagefilter

(PHP 5, PHP 7)

imagefilter — Applies a filter to an image

Descrierea

bool imagefilter ( resource $image , int $filtertype [, int $arg1 [, int $arg2 [, int $arg3 [, int $arg4 ]]]] )

imagefilter() applies the given filter filtertype on the image.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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. The range for the brightness is -255 to 255.
  • 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, green, blue 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: Valoarea componentei ro?ii.
  • IMG_FILTER_SMOOTH: Smoothness level.
  • IMG_FILTER_PIXELATE: Block size in pixels.

arg2

  • IMG_FILTER_COLORIZE: Valoarea componentei verzi.
  • IMG_FILTER_PIXELATE: Whether to use advanced pixelation effect or not (defaults to FALSE).

arg3

  • IMG_FILTER_COLORIZE: Valoarea componentei albastre.

arg4

  • IMG_FILTER_COLORIZE: Alpha channel, A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Pixelation support (IMG_FILTER_PIXELATE) was added.
5.2.5 | Alpha support for IMG_FILTER_COLORIZE was added.

Exemple

Example #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);
?>

Example #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.';
}
?>

Example #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.';
}
?>

Example #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.';
}
?>

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagefilter() pixelate

Note

A se vedea ?i

  • imageconvolution() - Apply a 3x3 convolution matrix, using coefficient and offset

imagefilltoborder
imageflip
Func?ii GD ?i Image


Flips an image using a given mode

imagefilter
imagefontheight
Func?ii GD ?i Image
PHP Manual

imageflip

(PHP 5 >= 5.5.0, PHP 7)

imageflip — Flips an image using a given mode

Descrierea

bool imageflip ( resource $image , int $mode )

Flips the image image using the given mode.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

mode

Flip mode, this can be one of the IMG_FLIP_* constants:

Constant | Meaning
IMG_FLIP_HORIZONTAL | Flips the image horizontally.
IMG_FLIP_VERTICAL | Flips the image vertically.
IMG_FLIP_BOTH | Flips the image both horizontally and vertically.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Flips an image vertically

This example uses the IMG_FLIP_VERTICAL constant.

<?php
// File
$filename = 'phplogo.png';

// Content type
header('Content-type: image/png');

// Load
$im = imagecreatefrompng($filename);

// Flip it vertically
imageflip($im, IMG_FLIP_VERTICAL);

// Output
imagejpeg($im);
imagedestroy($im);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example: Vertically flipped image

Example #2 Flips the image horizontally

This example uses the IMG_FLIP_HORIZONTAL constant.

<?php
// File
$filename = 'phplogo.png';

// Content type
header('Content-type: image/png');

// Load
$im = imagecreatefrompng($filename);

// Flip it horizontally
imageflip($im, IMG_FLIP_HORIZONTAL);

// Output
imagejpeg($im);
imagedestroy($im);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example: Horizontally flipped image

imagefilter
imagefontheight
Func?ii GD ?i Image


Get font height

imageflip
imagefontwidth
Func?ii GD ?i Image
PHP Manual

imagefontheight

(PHP 4, PHP 5, PHP 7)

imagefontheight — Get font height

Descrierea

int imagefontheight ( int $font )

Returns the pixel height of a character in the specified font.

Parametri

font

Poate fi 1, 2, 3, 4, 5 pentru font-urile încorporate cu codificarea latin2 (unde numerele mai mari corespund font-urilor mai mari) sau orice identificator de font al dumneavoastra, înregistrat cu imageloadfont().

Valorile întoarse

Returns the pixel height of the font.

Exemple

Example #1 Using imagefontheight() on built-in fonts

<?php
echo 'Font height: ' . imagefontheight(4);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Font height: 16

Example #2 Using imagefontheight() together with imageloadfont()

<?php
// Load a .gdf font
$font = imageloadfont('anonymous.gdf');

echo 'Font height: ' . imagefontheight($font);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Font height: 43

A se vedea ?i

  • imagefontwidth() - Get font width
  • imageloadfont() - Load a new font

imageflip
imagefontwidth
Func?ii GD ?i Image


Get font width

imagefontheight
imageftbbox
Func?ii GD ?i Image
PHP Manual

imagefontwidth

(PHP 4, PHP 5, PHP 7)

imagefontwidth — Get font width

Descrierea

int imagefontwidth ( int $font )

Returns the pixel width of a character in font.

Parametri

font

Poate fi 1, 2, 3, 4, 5 pentru font-urile încorporate cu codificarea latin2 (unde numerele mai mari corespund font-urilor mai mari) sau orice identificator de font al dumneavoastra, înregistrat cu imageloadfont().

Valorile întoarse

Returns the pixel width of the font.

Exemple

Example #1 Using imagefontwidth() on built-in fonts

<?php
echo 'Font width: ' . imagefontwidth(4);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Font width: 8

Example #2 Using imagefontwidth() together with imageloadfont()

<?php
// Load a .gdf font
$font = imageloadfont('anonymous.gdf');

echo 'Font width: ' . imagefontwidth($font);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Font width: 23

A se vedea ?i

  • imagefontheight() - Get font height
  • imageloadfont() - Load a new font

imagefontheight
imageftbbox
Func?ii GD ?i Image


Give the bounding box of a text using fonts via freetype2

imagefontwidth
imagefttext
Func?ii GD ?i Image
PHP Manual

imageftbbox

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imageftbbox — Give the bounding box of a text using fonts via freetype2

Descrierea

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.

Parametri

size

Dimensiunea font-ului. În dependen?a de versiunea GD, aceasta trebuie specificata în unita?i de pixeli (GD1) sau în unita?i de puncte (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

Valorile întoarse

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.

Exemple

Example #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);
?>

Note

Nota: Aceasta func?ie este disponibila numai daca PHP este compilat cu sus?inerea freetype (--with-freetype-dir=DIR )

A se vedea ?i

  • imagefttext() - Write text to the image using fonts using FreeType 2
  • imagettfbbox() - Give the bounding box of a text using TrueType fonts

imagefontwidth
imagefttext
Func?ii GD ?i Image


Write text to the image using fonts using FreeType 2

imageftbbox
imagegammacorrect
Func?ii GD ?i Image
PHP Manual

imagefttext

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imagefttext — Write text to the image using fonts using FreeType 2

Descrierea

array imagefttext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text [, array $extrainfo ] )

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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

Valorile întoarse

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

Exemple

Example #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);
?>

Note

Nota: Aceasta func?ie este disponibila numai daca PHP este compilat cu sus?inerea freetype (--with-freetype-dir=DIR )

A se vedea ?i

  • imageftbbox() - Give the bounding box of a text using fonts via freetype2
  • imagettftext() - Write text to the image using TrueType fonts

imageftbbox
imagegammacorrect
Func?ii GD ?i Image


Apply a gamma correction to a GD image

imagefttext
imagegd2
Func?ii GD ?i Image
PHP Manual

imagegammacorrect

(PHP 4, PHP 5, PHP 7)

imagegammacorrect — Apply a gamma correction to a GD image

Descrierea

bool imagegammacorrect ( resource $image , float $inputgamma , float $outputgamma )

Applies gamma correction to the given gd image given an input and an output gamma.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

inputgamma

The input gamma.

outputgamma

The output gamma.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii GD ?i Image


Output GD2 image to browser or file

imagegammacorrect
imagegd
Func?ii GD ?i Image
PHP Manual

imagegd2

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imagegd2 — Output GD2 image to browser or file

Descrierea

bool imagegd2 ( resource $image [, mixed $to = NULL [, int $chunk_size = 128 [, int $type = IMG_GD2_RAW ]]] )

Outputs a GD2 image to the given to.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

to

Calea unde va fi salvat fi?ierul. Daca nu este stabilita sau este NULL, atunci fluxul imaginii va fi afi?at direct.

chunk_size

Chunk size.

type

Either IMG_GD2_RAW or IMG_GD2_COMPRESSED. Default is IMG_GD2_RAW.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added support for passing a stream resource to to.

Exemple

Example #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);
?>

Example #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);
?>

Note

Nota:

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.

A se vedea ?i

  • imagegd() - Output GD image to browser or file

imagegammacorrect
imagegd
Func?ii GD ?i Image


Output GD image to browser or file

imagegd2
imagegetclip
Func?ii GD ?i Image
PHP Manual

imagegd

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imagegd — Output GD image to browser or file

Descrierea

bool imagegd ( resource $image [, mixed $to = NULL ] )

Outputs a GD image to the given to.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

to

Calea unde va fi salvat fi?ierul. Daca nu este stabilita sau este NULL, atunci fluxul imaginii va fi afi?at direct.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.2.0 | imagegd() now allows to output truecolor images. Formerly, these have been implicitly converted to palette.
5.4.0 | Added support for passing a stream resource to to.

Exemple

Example #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);
?>

Example #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);
?>

Note

Nota:

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.

A se vedea ?i

  • imagegd2() - Output GD2 image to browser or file

imagegd2
imagegetclip
Func?ii GD ?i Image


Get the clipping rectangle

imagegd
imagegif
Func?ii GD ?i Image
PHP Manual

imagegetclip

(PHP 7.2)

imagegetclip — Get the clipping rectangle

Descrierea

array imagegetclip ( resource $im )

imagegetclip() retrieves the current clipping rectangle, i.e. the area beyond which no pixels will be drawn.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

Valorile întoarse

The function returns an indexed array with the coordinates of the clipping rectangle which has the following entries:

  • x-coordinate of the upper left corner
  • y-coordinate of the upper left corner
  • x-coordinate of the lower right corner
  • y-coordinate of the lower right corner

Exemple

Example #1 imagegetclip() example

Setting and retrieving the clipping rectangle.

<?php
$im = imagecreate(100, 100);
imagesetclip($im, 10,10, 89,89);
print_r(imagegetclip($im));

Exemplul de mai sus va afi?a:

Array
(
    [0] => 10
    [1] => 10
    [2] => 89
    [3] => 89
)

A se vedea ?i

  • imagesetclip() - Set the clipping rectangle
imagegd
imagegif
Func?ii GD ?i Image


Afi?eaza imaginea în navigator sau în fi?ier

imagegetclip
imagegrabscreen
Func?ii GD ?i Image
PHP Manual

imagegif

(PHP 4, PHP 5, PHP 7)

imagegif — Afi?eaza imaginea în navigator sau în fi?ier

Descrierea

bool imagegif ( resource $image [, mixed $to ] )

imagegif() creates the GIF file in to 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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

to

Calea unde va fi salvat fi?ierul. Daca nu este stabilita sau este NULL, atunci fluxul imaginii va fi afi?at direct.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added support for passing a stream resource to to.

Exemple

Example #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);
?>

Example #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!';
?>

Note

Nota:

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);
}
?>

Nota:

You can use the function imagetypes() 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. */
}
?>

A se vedea ?i

  • imagepng() - Output a PNG image to either the browser or a file
  • imagewbmp() - Afi?eaza imaginea în navigator sau în fi?ier
  • imagejpeg() - Afi?eaza imaginea în navigator sau în fi?ier
  • imagetypes() - Return the image types supported by this PHP build

imagegetclip
imagegrabscreen
Func?ii GD ?i Image


Captures the whole screen

imagegif
imagegrabwindow
Func?ii GD ?i Image
PHP Manual

imagegrabscreen

(PHP 5 >= 5.2.2, PHP 7)

imagegrabscreen — Captures the whole screen

Descrierea

resource imagegrabscreen ( void )

Grabs a screenshot of the whole screen.

Valorile întoarse

Returns an image resource identifier on success, FALSE on failure.

Exemple

Example #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);
?>

Note

Nota:

This function is only available on Windows.

A se vedea ?i

  • imagegrabwindow() - Captures a window

imagegif
imagegrabwindow
Func?ii GD ?i Image


Captures a window

imagegrabscreen
imageinterlace
Func?ii GD ?i Image
PHP Manual

imagegrabwindow

(PHP 5 >= 5.2.2, PHP 7)

imagegrabwindow — Captures a window

Descrierea

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)

Parametri

window_handle

The HWND window ID.

client_area

Include the client area of the application window.

Valorile întoarse

Returns an image resource identifier on success, FALSE on failure.

Erori/Excep?ii

E_NOTICE is issued if window_handle is invalid window handle. E_WARNING is issued if the Windows API is too old.

Exemple

Example #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);
?>

Note

Nota:

This function is only available on Windows.

A se vedea ?i

  • imagegrabscreen() - Captures the whole screen

imagegrabscreen
imageinterlace
Func?ii GD ?i Image


Enable or disable interlace

imagegrabwindow
imageistruecolor
Func?ii GD ?i Image
PHP Manual

imageinterlace

(PHP 4, PHP 5, PHP 7)

imageinterlace — Enable or disable interlace

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

interlace

If non-zero, the image will be interlaced, else the interlace bit is turned off.

Valorile întoarse

Returns 1 if the interlace bit is set for the image, 0 otherwise.

Exemple

Example #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
Func?ii GD ?i Image


Finds whether an image is a truecolor image

imageinterlace
imagejpeg
Func?ii GD ?i Image
PHP Manual

imageistruecolor

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

imageistruecolor — Finds whether an image is a truecolor image

Descrierea

bool imageistruecolor ( resource $image )

imageistruecolor() finds whether the image image is a truecolor image.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

Valorile întoarse

Returns TRUE if the image is truecolor, FALSE otherwise.

Exemple

Example #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));

    // Copy over the pixels
    imagecopy($tc, $im, 0, 0, 0, 0, imagesx($im), imagesy($im));
    imagedestroy($im);

    $im = $tc;
    $tc = NULL;

    // OR use imagepalettetotruecolor()
}

// Continue working with image instance
?>

A se vedea ?i

  • imagecreatetruecolor() - Create a new true color image
  • imagepalettetotruecolor() - Converts a palette based image to true color

imageinterlace
imagejpeg
Func?ii GD ?i Image


Afi?eaza imaginea în navigator sau în fi?ier

imageistruecolor
imagelayereffect
Func?ii GD ?i Image
PHP Manual

imagejpeg

(PHP 4, PHP 5, PHP 7)

imagejpeg — Afi?eaza imaginea în navigator sau în fi?ier

Descrierea

bool imagejpeg ( resource $image [, mixed $to [, int $quality ]] )

imagejpeg() creates a JPEG file from the given image.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

to

Calea unde va fi salvat fi?ierul. Daca nu este stabilita sau este NULL, atunci fluxul imaginii va fi afi?at direct.

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Outputting a JPEG image to the browser

<?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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Outputting a JPEG image

Example #2 Saving a JPEG image to a 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 as 'simpletext.jpg'
imagejpeg($im, 'simpletext.jpg');

// Free up memory
imagedestroy($im);
?>

Example #3 Outputting the image at 75% quality to the browser

<?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 to parameter using NULL, then set the quality to 75%
imagejpeg($im, NULL, 75);

// Free up memory
imagedestroy($im);
?>

Note

Nota:

If you want to output Progressive JPEGs, you need to set interlacing on with imageinterlace().

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added support for passing a stream resource to to.
5.4.0 | Disallowed passing an empty string to to to skip this argument.

A se vedea ?i

  • imagepng() - Output a PNG image to either the browser or a file
  • imagegif() - Afi?eaza imaginea în navigator sau în fi?ier
  • imagewbmp() - Afi?eaza imaginea în navigator sau în fi?ier
  • imageinterlace() - Enable or disable interlace
  • imagetypes() - Return the image types supported by this PHP build

imageistruecolor
imagelayereffect
Func?ii GD ?i Image


Set the alpha blending flag to use layering effects

imagejpeg
imageline
Func?ii GD ?i Image
PHP Manual

imagelayereffect

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

imagelayereffect — Set the alpha blending flag to use layering effects

Descrierea

bool imagelayereffect ( resource $image , int $effect )

Set the alpha blending flag to use layering effects.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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.
IMG_EFFECT_MULTIPLY
Overlays with a multiply effect.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.2.0 | Added IMG_EFFECT_MULTIPLY (requires system libgd >= 2.1.1 or the bundled libgd).

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagelayereffect()

Note

Before PHP 5.5.0, this function is only available if PHP is compiled with the bundled version of the GD library.

imagejpeg
imageline
Func?ii GD ?i Image


Draw a line

imagelayereffect
imageloadfont
Func?ii GD ?i Image
PHP Manual

imageline

(PHP 4, PHP 5, PHP 7)

imageline — Draw a line

Descrierea

bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

Draws a line between the two given points.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
}

?>

A se vedea ?i

  • imagecreatetruecolor() - Create a new true color image
  • imagecolorallocate() - Allocate a color for an image

imagelayereffect
imageloadfont
Func?ii GD ?i Image


Load a new font

imageline
imageopenpolygon
Func?ii GD ?i Image
PHP Manual

imageloadfont

(PHP 4, PHP 5, PHP 7)

imageloadfont — Load a new font

Descrierea

int imageloadfont ( string $file )

imageloadfont() loads a user-defined bitmap and returns its identifier.

Parametri

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.

Valorile întoarse

The font identifier which is always bigger than 5 to avoid conflicts with built-in fonts or FALSE on errors.

Exemple

Example #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);
?>

A se vedea ?i

  • imagefontwidth() - Get font width
  • imagefontheight() - Get font height

imageline
imageopenpolygon
Func?ii GD ?i Image


Draws an open polygon

imageloadfont
imagepalettecopy
Func?ii GD ?i Image
PHP Manual

imageopenpolygon

(PHP 7 >= 7.2.0)

imageopenpolygon — Draws an open polygon

Descrierea

bool imageopenpolygon ( resource $image , array $points , int $num_points , int $color )

imageopenpolygon() draws an open polygon on the given image. Contrary to imagepolygon(), no line is drawn between the last and the first point.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 imageopenpolygon() 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
imageopenpolygon($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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imageopenpolygon()

A se vedea ?i

  • imagepolygon() - Draws a polygon

imageloadfont
imagepalettecopy
Func?ii GD ?i Image


Copy the palette from one image to another

imageopenpolygon
imagepalettetotruecolor
Func?ii GD ?i Image
PHP Manual

imagepalettecopy

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagepalettecopy — Copy the palette from one image to another

Descrierea

void imagepalettecopy ( resource $destination , resource $source )

imagepalettecopy() copies the palette from the source image to the destination image.

Parametri

destination

The destination image resource.

source

The source image resource.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);
?>

imageopenpolygon
imagepalettetotruecolor
Func?ii GD ?i Image


Converts a palette based image to true color

imagepalettecopy
imagepng
Func?ii GD ?i Image
PHP Manual

imagepalettetotruecolor

(PHP 5 >= 5.5.0, PHP 7)

imagepalettetotruecolor — Converts a palette based image to true color

Descrierea

bool imagepalettetotruecolor ( resource $src )

Converts a palette based image, created by functions like imagecreate() to a true color image, like imagecreatetruecolor().

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

Valorile întoarse

Returns TRUE if the convertion was complete, or if the source image already is a true color image, otherwise FALSE is returned.

Exemple

Example #1 Converts any image resource to true color

<?php
// Backwards compatiblity
if(!function_exists('imagepalettetotruecolor'))
{
    function imagepalettetotruecolor(&$src)
    {
        if(imageistruecolor($src))
        {
            return(true);
        }

        $dst = imagecreatetruecolor(imagesx($src), imagesy($src));

        imagecopy($dst, $src, 0, 0, 0, 0, imagesx($src), imagesy($src));
        imagedestroy($src);

        $src = $dst;

        return(true);
    }
}

// Helper closure
$typeof = function() use($im)
{
    echo 'typeof($im) = ' . (imageistruecolor($im) ? 'true color' : 'palette'), PHP_EOL;
};

// Create a palette based image
$im = imagecreate(100, 100);
$typeof();

// Convert it to true color
imagepalettetotruecolor($im);
$typeof();

// Free the memory
imagedestroy($im);
?>

Exemplul de mai sus va afi?a:

typeof($im) = palette
typeof($im) = true color

A se vedea ?i

  • imagecreatetruecolor() - Create a new true color image
  • imageistruecolor() - Finds whether an image is a truecolor image

imagepalettecopy
imagepng
Func?ii GD ?i Image


Output a PNG image to either the browser or a file

imagepalettetotruecolor
imagepolygon
Func?ii GD ?i Image
PHP Manual

imagepng

(PHP 4, PHP 5, PHP 7)

imagepng — Output a PNG image to either the browser or a file

Descrierea

bool imagepng ( resource $image [, mixed $to [, int $quality [, int $filters ]]] )

Outputs or saves a PNG image from the given image.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

to

Calea unde va fi salvat fi?ierul. Daca nu este stabilita sau este NULL, atunci fluxul imaginii va fi afi?at direct.

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added support for passing a stream resource to to.
5.1.3 | Added the filters parameter.
5.1.2 | Added the quality parameter.

Exemple

<?php
$im = imagecreatefrompng("test.png");

header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

A se vedea ?i

  • imagegif() - Afi?eaza imaginea în navigator sau în fi?ier
  • imagewbmp() - Afi?eaza imaginea în navigator sau în fi?ier
  • imagejpeg() - Afi?eaza imaginea în navigator sau în fi?ier
  • 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

imagepalettetotruecolor
imagepolygon
Func?ii GD ?i Image


Draws a polygon

imagepng
imagepsbbox
Func?ii GD ?i Image
PHP Manual

imagepolygon

(PHP 4, PHP 5, PHP 7)

imagepolygon — Draws a polygon

Descrierea

bool imagepolygon ( resource $image , array $points , int $num_points , int $color )

imagepolygon() creates a polygon in the given image.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagepolygon()

A se vedea ?i

  • imagefilledpolygon() - Draw a filled polygon
  • imageopenpolygon() - Draws an open polygon
  • imagecreate() - Create a new palette based image
  • imagecreatetruecolor() - Create a new true color image

imagepng
imagepsbbox
Func?ii GD ?i Image


Give the bounding box of a text rectangle using PostScript Type1 fonts

imagepolygon
imagepsencodefont
Func?ii GD ?i Image
PHP Manual

imagepsbbox

(PHP 4, PHP 5)

imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns an array containing the following elements:

0 | left x-coordinate
1 | upper y-coordinate
2 | right x-coordinate
3 | lower y-coordinate

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Note

Nota: Aceasta func?ie e disponibila numai daca PHP este compilat utilizând --with-t1lib[=DIR] .

A se vedea ?i

  • imagepstext() - Draws a text over an image using PostScript Type1 fonts

imagepolygon
imagepsencodefont
Func?ii GD ?i Image


Change the character encoding vector of a font

imagepsbbox
imagepsextendfont
Func?ii GD ?i Image
PHP Manual

imagepsencodefont

(PHP 4, PHP 5)

imagepsencodefont — Change the character encoding vector of a font

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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 a language other 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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Note

Nota: Aceasta func?ie e disponibila numai daca PHP este compilat utilizând --with-t1lib[=DIR] .

imagepsbbox
imagepsextendfont
Func?ii GD ?i Image


Extend or condense a font

imagepsencodefont
imagepsfreefont
Func?ii GD ?i Image
PHP Manual

imagepsextendfont

(PHP 4, PHP 5)

imagepsextendfont — Extend or condense a font

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

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.

Parametri

font_index

A font resource, returned by imagepsloadfont().

extend

Extension value, must be greater than 0.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Note

Nota: Aceasta func?ie e disponibila numai daca PHP este compilat utilizând --with-t1lib[=DIR] .

imagepsencodefont
imagepsfreefont
Func?ii GD ?i Image


Free memory used by a PostScript Type 1 font

imagepsextendfont
imagepsloadfont
Func?ii GD ?i Image
PHP Manual

imagepsfreefont

(PHP 4, PHP 5)

imagepsfreefont — Free memory used by a PostScript Type 1 font

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

bool imagepsfreefont ( resource $font_index )

imagepsfreefont() frees memory used by a PostScript Type 1 font.

Parametri

font_index

A font resource, returned by imagepsloadfont().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Note

Nota: Aceasta func?ie e disponibila numai daca PHP este compilat utilizând --with-t1lib[=DIR] .

A se vedea ?i

  • imagepsloadfont() - Load a PostScript Type 1 font from file

imagepsextendfont
imagepsloadfont
Func?ii GD ?i Image


Load a PostScript Type 1 font from file

imagepsfreefont
imagepsslantfont
Func?ii GD ?i Image
PHP Manual

imagepsloadfont

(PHP 4, PHP 5)

imagepsloadfont — Load a PostScript Type 1 font from file

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

resource imagepsloadfont ( string $filename )

Load a PostScript Type 1 font from the given filename.

Parametri

filename

Path to the Postscript font file.

Valorile întoarse

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.

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Note

Nota: Aceasta func?ie e disponibila numai daca PHP este compilat utilizând --with-t1lib[=DIR] .

A se vedea ?i

  • imagepsfreefont() - Free memory used by a PostScript Type 1 font

imagepsfreefont
imagepsslantfont
Func?ii GD ?i Image


Slant a font

imagepsloadfont
imagepstext
Func?ii GD ?i Image
PHP Manual

imagepsslantfont

(PHP 4, PHP 5)

imagepsslantfont — Slant a font

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Descrierea

bool imagepsslantfont ( resource $font_index , float $slant )

Slant a given font.

Parametri

font_index

A font resource, returned by imagepsloadfont().

slant

Slant level.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Note

Nota: Aceasta func?ie e disponibila numai daca PHP este compilat utilizând --with-t1lib[=DIR] .

imagepsloadfont
imagepstext
Func?ii GD ?i Image


Draws a text over an image using PostScript Type1 fonts

imagepsslantfont
imagerectangle
Func?ii GD ?i Image
PHP Manual

imagepstext

(PHP 4, PHP 5)

imagepstext — Draws a text over an image using PostScript Type1 fonts

Descrierea

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.

Avertizare

Aceasta func?ie a fost ELIMINATA în PHP 7.0.0.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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.

Valorile întoarse

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

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Note

Nota: Aceasta func?ie e disponibila numai daca PHP este compilat utilizând --with-t1lib[=DIR] .

A se vedea ?i

  • imagepsbbox() - Give the bounding box of a text rectangle using PostScript Type1 fonts

imagepsslantfont
imagerectangle
Func?ii GD ?i Image


Draw a rectangle

imagepstext
imageresolution
Func?ii GD ?i Image
PHP Manual

imagerectangle

(PHP 4, PHP 5, PHP 7)

imagerectangle — Draw a rectangle

Descrierea

bool imagerectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

imagerectangle() creates a rectangle starting at the specified coordinates.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Simple imagerectangle() example

imagepstext
imageresolution
Func?ii GD ?i Image


Get or set the resolution of the image

imagerectangle
imagerotate
Func?ii GD ?i Image
PHP Manual

imageresolution

(PHP 7 >= 7.2.0)

imageresolution — Get or set the resolution of the image

Descrierea

mixed imageresolution ( resource $image [, int $res_x [, int $res_y ]] )

imageresolution() allows to set and get the resolution of an image in DPI (dots per inch). If none of the optional parameters is given, the current resolution is returned as indexed array. If only res_x is given, the horizontal and vertical resolution are set to this value. If both optional parameters are given, the horizontal and vertical resolution are set to these values, respectively.

The resolution is only used as meta information when images are read from and written to formats supporting this kind of information (curently PNG and JPEG). It does not affect any drawing operations. The default resolution for new images is 96 DPI.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

res_x

The horizontal resolution in DPI.

res_y

The vertical resolution in DPI.

Valorile întoarse

When used as getter (that is without the optional parameters), it returns TRUE on success, sau FALSE în cazul e?ecului. When used as setter (that is with one or both optional parameters given), it returns an indexed array of the horizontal and vertical resolution on success, sau FALSE în cazul e?ecului.

Exemple

Example #1 Setting and getting the resolution of an image

<?php
$im = imagecreatetruecolor(100, 100);
imageresolution($im, 200);
print_r(imageresolution($im));
imageresolution($im, 300, 72);
print_r(imageresolution($im));
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => 200
    [1] => 200
)
Array
(
    [0] => 300
    [1] => 72
)
imagerectangle
imagerotate
Func?ii GD ?i Image


Rotate an image with a given angle

imageresolution
imagesavealpha
Func?ii GD ?i Image
PHP Manual

imagerotate

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

imagerotate — Rotate an image with a given angle

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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).

Valorile întoarse

Returns an image resource for the rotated image, sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | The ignore_transparent is now silently ignored.
5.5.0 | This function is now affected by the interpolation method set by the imagesetinterpolation() function.
5.1.0 | ignore_transparent was added.

Exemple

Example #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);

// Free the memory
imagedestroy($source);
imagedestroy($rotate);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Rotate an image 180 degrees

Note

Nota:

Aceasta func?ie este afectata de metoda de interpolare stabilita cu ajutorul imagesetinterpolation().

A se vedea ?i

  • imagesetinterpolation() - Set the interpolation method

imageresolution
imagesavealpha
Func?ii GD ?i Image


Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

imagerotate
imagescale
Func?ii GD ?i Image
PHP Manual

imagesavealpha

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

imagesavealpha — Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

saveflag

Whether to save the alpha channel or not. Default to FALSE.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • imagealphablending() - Set the blending mode for an image

imagerotate
imagescale
Func?ii GD ?i Image


Scale an image using the given new width and height

imagesavealpha
imagesetbrush
Func?ii GD ?i Image
PHP Manual

imagescale

(PHP 5 >= 5.5.0, PHP 7)

imagescale — Scale an image using the given new width and height

Descrierea

resource imagescale ( resource $image , int $new_width [, int $new_height = -1 [, int $mode = IMG_BILINEAR_FIXED ]] )

imagescale() scales an image using the given interpolation algorithm.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

new_width

The width to scale the image to.

new_height

The height to scale the image to. If omitted or negative, the aspect ratio will be preserved.

Precautie

You should always provide the height if using PHP 5.5.18 or earlier, or PHP 5.6.2 or earlier, as the aspect ratio calculation was incorrect.

mode

One of IMG_NEAREST_NEIGHBOUR, IMG_BILINEAR_FIXED, IMG_BICUBIC, IMG_BICUBIC_FIXED or anything else (will use two pass).

Nota: IMG_WEIGHTED4 is not yet supported.

Valorile întoarse

Return the scaled image resource on success sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.19/5.6.3 | The calculation of the height if new_height was negative or omitted was fixed; prior to these versions, the aspect ratio was not maintained correctly.

imagesavealpha
imagesetbrush
Func?ii GD ?i Image


Set the brush image for line drawing

imagescale
imagesetclip
Func?ii GD ?i Image
PHP Manual

imagesetbrush

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagesetbrush — Set the brush image for line drawing

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

brush

An image resource.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagesetbrush()

Note

Nota:

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!

imagescale
imagesetclip
Func?ii GD ?i Image


Set the clipping rectangle

imagesetbrush
imagesetinterpolation
Func?ii GD ?i Image
PHP Manual

imagesetclip

(PHP 7.2)

imagesetclip — Set the clipping rectangle

Descrierea

bool imagesetclip ( resource $im , int $x1 , int $y1 , int $x2 , int $y2 )

imagesetclip() sets the current clipping rectangle, i.e. the area beyond which no pixels will be drawn.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

x1

The x-coordinate of the upper left corner.

y1

The y-coordinate of the upper left corner.

x2

The x-coordinate of the lower right corner.

y2

The y-coordinate of the lower right corner.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • imagegetclip() - Get the clipping rectangle
imagesetbrush
imagesetinterpolation
Func?ii GD ?i Image


Set the interpolation method

imagesetclip
imagesetpixel
Func?ii GD ?i Image
PHP Manual

imagesetinterpolation

(PHP 5 >= 5.5.0, PHP 7)

imagesetinterpolation — Set the interpolation method

Descrierea

bool imagesetinterpolation ( resource $image [, int $method = IMG_BILINEAR_FIXED ] )

Sets the interpolation method, setting an interpolation method affects the rendering of various functions in GD, such as the imagerotate() function.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

method

The interpolation method, which can be one of the following:

  • IMG_BELL: Bell filter.
  • IMG_BESSEL: Bessel filter.
  • IMG_BICUBIC: Bicubic interpolation.
  • IMG_BICUBIC_FIXED: Fixed point implementation of the bicubic interpolation.
  • IMG_BILINEAR_FIXED: Fixed point implementation of the bilinear interpolation (default (also on image creation)).
  • IMG_BLACKMAN: Blackman window function.
  • IMG_BOX: Box blur filter.
  • IMG_BSPLINE: Spline interpolation.
  • IMG_CATMULLROM: Cubic Hermite spline interpolation.
  • IMG_GAUSSIAN: Gaussian function.
  • IMG_GENERALIZED_CUBIC: Generalized cubic spline fractal interpolation.
  • IMG_HERMITE: Hermite interpolation.
  • IMG_HAMMING: Hamming filter.
  • IMG_HANNING: Hanning filter.
  • IMG_MITCHELL: Mitchell filter.
  • IMG_POWER: Power interpolation.
  • IMG_QUADRATIC: Inverse quadratic interpolation.
  • IMG_SINC: Sinc function.
  • IMG_NEAREST_NEIGHBOUR: Nearest neighbour interpolation.
  • IMG_WEIGHTED4: Weighting filter.
  • IMG_TRIANGLE: Triangle interpolation.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 imagesetinterpolation() example

<?php
// Load an image
$im = imagecreate(500, 500);

// By default interpolation is IMG_BILINEAR_FIXED, switch
// to use the 'Mitchell' filter:
imagesetinterpolation($im, IMG_MITCHELL);

// Continue to work with $im ...
?>

Note

Changing the interpolation method affects the following functions when rendering:

  • imageaffine()
  • imagerotate()

imagesetclip
imagesetpixel
Func?ii GD ?i Image


Set a single pixel

imagesetinterpolation
imagesetstyle
Func?ii GD ?i Image
PHP Manual

imagesetpixel

(PHP 4, PHP 5, PHP 7)

imagesetpixel — Set a single pixel

Descrierea

bool imagesetpixel ( resource $image , int $x , int $y , int $color )

imagesetpixel() draws a pixel at the specified coordinate.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

x

x-coordinate.

y

y-coordinate.

color

A color identifier created with imagecolorallocate().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagesetpixel()

A se vedea ?i

  • imagecreatetruecolor() - Create a new true color image
  • imagecolorallocate() - Allocate a color for an image
  • imagecolorat() - Get the index of the color of a pixel

imagesetinterpolation
imagesetstyle
Func?ii GD ?i Image


Set the style for line drawing

imagesetpixel
imagesetthickness
Func?ii GD ?i Image
PHP Manual

imagesetstyle

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagesetstyle — Set the style for line drawing

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

style

An array of pixel colors. You can use the IMG_COLOR_TRANSPARENT constant to add a transparent pixel. Note that style must not be an empty array.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Following example script draws a dashed line from upper left to lower right corner of the canvas:

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagesetstyle()

A se vedea ?i

  • imagesetbrush() - Set the brush image for line drawing
  • imageline() - Draw a line

imagesetpixel
imagesetthickness
Func?ii GD ?i Image


Set the thickness for line drawing

imagesetstyle
imagesettile
Func?ii GD ?i Image
PHP Manual

imagesetthickness

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagesetthickness — Set the thickness for line drawing

Descrierea

bool imagesetthickness ( resource $image , int $thickness )

imagesetthickness() sets the thickness of the lines drawn when drawing rectangles, polygons, arcs etc. to thickness pixels.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

thickness

Thickness, in pixels.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagesetthickness()

imagesetstyle
imagesettile
Func?ii GD ?i Image


Set the tile image for filling

imagesetthickness
imagestring
Func?ii GD ?i Image
PHP Manual

imagesettile

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagesettile — Set the tile image for filling

Descrierea

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.

Nota:

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!

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

tile

The image resource to be used as a tile.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagesettile()

imagesetthickness
imagestring
Func?ii GD ?i Image


Draw a string horizontally

imagesettile
imagestringup
Func?ii GD ?i Image
PHP Manual

imagestring

(PHP 4, PHP 5, PHP 7)

imagestring — Draw a string horizontally

Descrierea

bool imagestring ( resource $image , int $font , int $x , int $y , string $string , int $color )

Draws a string at the given coordinates.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

font

Poate fi 1, 2, 3, 4, 5 pentru font-urile încorporate cu codificarea latin2 (unde numerele mai mari corespund font-urilor mai mari) sau orice identificator de font al dumneavoastra, înregistrat cu 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagestring()

A se vedea ?i

  • imageloadfont() - Load a new font
  • imagettftext() - Write text to the image using TrueType fonts

imagesettile
imagestringup
Func?ii GD ?i Image


Draw a string vertically

imagestring
imagesx
Func?ii GD ?i Image
PHP Manual

imagestringup

(PHP 4, PHP 5, PHP 7)

imagestringup — Draw a string vertically

Descrierea

bool imagestringup ( resource $image , int $font , int $x , int $y , string $string , int $color )

Draws a string vertically at the given coordinates.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

font

Poate fi 1, 2, 3, 4, 5 pentru font-urile încorporate cu codificarea latin2 (unde numerele mai mari corespund font-urilor mai mari) sau orice identificator de font al dumneavoastra, înregistrat cu 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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagestringup()

A se vedea ?i

  • imageloadfont() - Load a new font

imagestring
imagesx
Func?ii GD ?i Image


Get image width

imagestringup
imagesy
Func?ii GD ?i Image
PHP Manual

imagesx

(PHP 4, PHP 5, PHP 7)

imagesx — Get image width

Descrierea

int imagesx ( resource $image )

Returns the width of the given image resource.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

Valorile întoarse

Return the width of the image or FALSE on errors.

Exemple

Example #1 Using imagesx()

<?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesx($img); // 300

?>

A se vedea ?i

  • imagecreatetruecolor() - Create a new true color image
  • getimagesize() - Get the size of an image
  • imagesy() - Get image height

imagestringup
imagesy
Func?ii GD ?i Image


Get image height

imagesx
imagetruecolortopalette
Func?ii GD ?i Image
PHP Manual

imagesy

(PHP 4, PHP 5, PHP 7)

imagesy — Get image height

Descrierea

int imagesy ( resource $image )

Returns the height of the given image resource.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

Valorile întoarse

Return the height of the image or FALSE on errors.

Exemple

Example #1 Using imagesy()

<?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesy($img); // 200

?>

A se vedea ?i

  • imagecreatetruecolor() - Create a new true color image
  • getimagesize() - Get the size of an image
  • imagesx() - Get image width

imagesx
imagetruecolortopalette
Func?ii GD ?i Image


Convert a true color image to a palette image

imagesy
imagettfbbox
Func?ii GD ?i Image
PHP Manual

imagetruecolortopalette

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagetruecolortopalette — Convert a true color image to a palette image

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

imagesy
imagettfbbox
Func?ii GD ?i Image


Give the bounding box of a text using TrueType fonts

imagetruecolortopalette
imagettftext
Func?ii GD ?i Image
PHP Manual

imagettfbbox

(PHP 4, PHP 5, PHP 7)

imagettfbbox — Give the bounding box of a text using TrueType fonts

Descrierea

array imagettfbbox ( float $size , float $angle , string $fontfile , string $text )

This function calculates and returns the bounding box in pixels for a TrueType text.

Parametri

size

The font size.

Nota: 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.

Valorile întoarse

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.

Exemple

Example #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);
?>

Note

Nota: Aceasta func?ie este disponibila numai daca PHP este compilat cu sus?inerea freetype (--with-freetype-dir=DIR )

A se vedea ?i

  • imagettftext() - Write text to the image using TrueType fonts
  • imageftbbox() - Give the bounding box of a text using fonts via freetype2

imagetruecolortopalette
imagettftext
Func?ii GD ?i Image


Write text to the image using TrueType fonts

imagettfbbox
imagetypes
Func?ii GD ?i Image
PHP Manual

imagettftext

(PHP 4, PHP 5, PHP 7)

imagettftext — Write text to the image using TrueType fonts

Descrierea

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.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

size

Dimensiunea font-ului. În dependen?a de versiunea GD, aceasta trebuie specificata în unita?i de pixeli (GD1) sau în unita?i de puncte (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.

If a character is used in the string which is not supported by the font, a hollow rectangle will replace the character.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | It is now possible to specify an hexadecimal entity in text.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : imagettftext()

Note

Nota: Aceasta func?ie este disponibila numai daca PHP este compilat cu sus?inerea freetype (--with-freetype-dir=DIR )

A se vedea ?i

  • imagettfbbox() - Give the bounding box of a text using TrueType fonts
  • imagefttext() - Write text to the image using fonts using FreeType 2

imagettfbbox
imagetypes
Func?ii GD ?i Image


Return the image types supported by this PHP build

imagettftext
imagewbmp
Func?ii GD ?i Image
PHP Manual

imagetypes

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

imagetypes — Return the image types supported by this PHP build

Descrierea

int imagetypes ( void )

Returns the image types supported by the current PHP installation.

Valorile întoarse

Returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_BMP | IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM | IMG_WEBP.

Exemple

Example #1 Checking for PNG support

<?php
if (imagetypes() & IMG_PNG) {
    echo "PNG Support is enabled";
}
?>

Istoricul schimbarilor

Versiune | Descriere
7.2.0 | IMG_BMP added.
5.6.25, 7.0.10 | IMG_WEBP added.

A se vedea ?i

  • gd_info() - Retrieve information about the currently installed GD library

imagettftext
imagewbmp
Func?ii GD ?i Image


Afi?eaza imaginea în navigator sau în fi?ier

imagetypes
imagewebp
Func?ii GD ?i Image
PHP Manual

imagewbmp

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagewbmp — Afi?eaza imaginea în navigator sau în fi?ier

Descrierea

bool imagewbmp ( resource $image [, mixed $to [, int $foreground ]] )

imagewbmp() outputs or save a WBMP version of the given image.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

to

Calea unde va fi salvat fi?ierul. Daca nu este stabilita sau este NULL, atunci fluxul imaginii va fi afi?at direct.

foreground

You can set the foreground color with this parameter by setting an identifier obtained from imagecolorallocate(). The default foreground color is black.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added support for passing a stream resource to to.

Exemple

Example #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);
?>

Example #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);
?>

Example #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);
?>

A se vedea ?i

  • image2wbmp() - Afi?eaza imaginea în navigator sau în fi?ier
  • imagepng() - Output a PNG image to either the browser or a file
  • imagegif() - Afi?eaza imaginea în navigator sau în fi?ier
  • imagejpeg() - Afi?eaza imaginea în navigator sau în fi?ier
  • imagetypes() - Return the image types supported by this PHP build

imagetypes
imagewebp
Func?ii GD ?i Image


Output a WebP image to browser or file

imagewbmp
imagexbm
Func?ii GD ?i Image
PHP Manual

imagewebp

(PHP 5 >= 5.5.0, PHP 7)

imagewebp — Output a WebP image to browser or file

Descrierea

bool imagewebp ( resource $image , mixed $to [, int $quality = 80 ] )

Outputs or save an WebP version of the given image.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

to

Calea unde va fi salvat fi?ierul. Daca nu este stabilita sau este NULL, atunci fluxul imaginii va fi afi?at direct.

quality

quality ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added support for passing a stream resource to to.

Exemple

Example #1 Saving an WebP 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,  'WebP with PHP', $text_color);

// Save the image
imagewebp($im, 'php.webp');

// Free up memory
imagedestroy($im);
?>

imagewbmp
imagexbm
Func?ii GD ?i Image


Output an XBM image to browser or file

imagewebp
iptcembed
Func?ii GD ?i Image
PHP Manual

imagexbm

(PHP 5, PHP 7)

imagexbm — Output an XBM image to browser or file

Descrierea

bool imagexbm ( resource $image , string $filename [, int $foreground ] )

Outputs or save an XBM version of the given image.

Nota: imagexbm() doesn't apply any padding, so the image width has to be a multiple of 8. This restriction does no longer apply as of PHP 5.6.24 and 7.0.9, respectively.

Parametri

image

O resursa - imagine, întoarsa de una din func?iile de creare a imaginilor, cum ar fi imagecreatetruecolor().

filename

The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

The filename (without the .xbm extension) is also used for the C identifiers of the XBM, whereby non alphanumeric characters of the current locale are substituted by underscores. If filename is set to NULL, image is used to build the C identifiers.

foreground

You can set the foreground color with this parameter by setting an identifier obtained from imagecolorallocate(). The default foreground color is black. All other colors are treated as background.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Example #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);
?>

Note

imagewebp
iptcembed
Func?ii GD ?i Image


Embeds binary IPTC data into a JPEG image

imagexbm
iptcparse
Func?ii GD ?i Image
PHP Manual

iptcembed

(PHP 4, PHP 5, PHP 7)

iptcembed — Embeds binary IPTC data into a JPEG image

Descrierea

mixed iptcembed ( string $iptcdata , string $jpeg_file_name [, int $spool = 0 ] )

Embeds binary IPTC data into a JPEG image.

Parametri

iptcdata

The data to be written.

jpeg_file_name

Path to the JPEG image.

spool

Spool flag. If the spool flag is less than 2 then the JPEG will be returned as a string. Otherwise the JPEG will be printed to STDOUT.

Valorile întoarse

If spool is less than 2, the JPEG will be returned, sau FALSE în cazul e?ecului. Otherwise returns TRUE on success sau FALSE în cazul e?ecului.

Exemple

Example #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';

// 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);
?>

Note

Nota:

Aceasta func?ie nu necesita biblioteca de prelucrare a imaginilor GD.

imagexbm
iptcparse
Func?ii GD ?i Image


Parse a binary IPTC block into single tags.

iptcembed
jpeg2wbmp
Func?ii GD ?i Image
PHP Manual

iptcparse

(PHP 4, PHP 5, PHP 7)

iptcparse — Parse a binary IPTC block into single tags.

Descrierea

array iptcparse ( string $iptcblock )

Parses an » IPTC block into its single tags.

Parametri

iptcblock

A binary IPTC block.

Valorile întoarse

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.

Exemple

Example #1 iptcparse() used together with getimagesize()

<?php
$size = getimagesize('./test.jpg', $info);
if(isset($info['APP13']))
{
    $iptc = iptcparse($info['APP13']);
    var_dump($iptc);
}
?>

Note

Nota:

Aceasta func?ie nu necesita biblioteca de prelucrare a imaginilor GD.

iptcembed
jpeg2wbmp
Func?ii GD ?i Image


Convert JPEG image file to WBMP image file

iptcparse
png2wbmp
Func?ii GD ?i Image
PHP Manual

jpeg2wbmp

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

jpeg2wbmp — Convert JPEG image file to WBMP image file

Avertizare

jpeg2wbmp() has been deprecated as of PHP 7.2.0, and will be removed as of PHP 8.0.0. Use imagecreatefromjpeg() and imagewbmp() instead.

Descrierea

bool jpeg2wbmp ( string $jpegname , string $wbmpname , int $dest_height , int $dest_width , int $threshold )

Converts a JPEG file into a WBMP file.

Parametri

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • png2wbmp() - Convert PNG image file to WBMP image file

iptcparse
png2wbmp
Func?ii GD ?i Image


Convert PNG image file to WBMP image file

jpeg2wbmp
Gmagick
Func?ii GD ?i Image
PHP Manual

png2wbmp

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

png2wbmp — Convert PNG image file to WBMP image file

Avertizare

png2wbmp() has been deprecated as of PHP 7.2.0, and will be removed as of PHP 8.0.0. Use imagecreatefrompng() and imagewbmp() instead.

Descrierea

bool png2wbmp ( string $pngname , string $wbmpname , int $dest_height , int $dest_width , int $threshold )

Converts a PNG file into a WBMP file.

Parametri

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • jpeg2wbmp() - Convert JPEG image file to WBMP image file

jpeg2wbmp
Gmagick
Func?ii GD ?i Image


Gmagick

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
  • Constante predefinite
  • Exemple
  • 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 — Check 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::setCompressionQuality — Sets the object's default compression quality
    • 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 — Sets 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 — Pseudonim pentru Gmagick::writeimage
    • 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 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
Introducere
Generarea ?i procesarea imaginilor


Introducere

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
Instalarea / configurarea
Gmagick


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
Introducere
Necesita?i
Gmagick


Necesita?i

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 .

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/gmagick.

Nota: The official name of this extension is gmagick.

For Windows, the build of the Gmagick extension is available » here

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Aceasta extensie nu are directive de configurare definite în php.ini.

Instalarea
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
Subtracts 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)
Configura?ia la rulare
Exemple
Gmagick


Exemple

The following shows some common Gmagick image operations.

Example #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');
?>
Constante predefinite
Gmagick
Gmagick


The Gmagick class

(PECL gmagick >= Unknown)

Introducere

Sinopsisul clasei

Gmagick {
/* Metode */
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 Gmagick deconstructimages ( void )
public Gmagick despeckleimage ( void )
public bool 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 GmagickPixel getimagebackgroundcolor ( void )
public array getimageblueprimary ( void )
public GmagickPixel 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 GmagickPixel 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 Gmagick minifyimage ( void )
public Gmagick modulateimage ( float $brightness , float $saturation , float $hue )
public Gmagick motionblurimage ( float $radius , float $sigma , float $angle )
public Gmagick newimage ( int $width , int $height , string $background [, string $format ] )
public bool nextimage ( void )
public Gmagick normalizeimage ([ int $channel ] )
public Gmagick oilpaintimage ( float $radius )
public bool previousimage ( void )
public Gmagick profileimage ( string $name , string $profile )
public Gmagick quantizeimage ( int $numColors , int $colorspace , int $treeDepth , bool $dither , bool $measureError )
public Gmagick 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 Gmagick radialblurimage ( float $angle [, int $channel = Gmagick::CHANNEL_DEFAULT ] )
public Gmagick raiseimage ( int $width , int $height , int $x , int $y , bool $raise )
public Gmagick read ( string $filename )
public Gmagick readimage ( string $filename )
public Gmagick readimageblob ( string $imageContents [, string $filename ] )
public Gmagick readimagefile ( resource $fp [, string $filename ] )
public Gmagick reducenoiseimage ( float $radius )
public Gmagick removeimage ( void )
public string removeimageprofile ( string $name )
public Gmagick resampleimage ( float $xResolution , float $yResolution , int $filter , float $blur )
public Gmagick resizeimage ( int $width , int $height , int $filter , float $blur [, bool $fit = false ] )
public Gmagick 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 )
Gmagick setCompressionQuality ( int $quality = 75 )
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 Gmagick writeimage ( string $filename [, bool $all_frames = false ] )
}

Cuprins

  • 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 — Check 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::setCompressionQuality — Sets the object's default compression quality
  • 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 — Sets 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 — Pseudonim pentru Gmagick::writeimage
  • Gmagick::writeimage — Writes an image to the specified filename
Exemple
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

Descrierea

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.

Parametri

source

The source Gmagick object

Valorile întoarse

The Gmagick object with image added

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::addnoiseimage ( int $NOISE )

Adds random noise to the image.

Parametri

noise_type

The type of the noise. Refer to this list of noise constants.

Valorile întoarse

The Gmagick object with noise added.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::annotateimage ( GmagickDraw $GmagickDraw , float $x , float $y , float $angle , string $text )

Annotates an image with text.

Parametri

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

Valorile întoarse

The Gmagick object with annotation made.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::blurimage ( float $radius , float $sigma [, int $channel ] )

Adds blur filter to image.

Parametri

radius

Blur radius

sigma

Standard deviation

Valorile întoarse

The blurred Gmagick object

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

color

GmagickPixel object or a string containing the border color

width

Border width

height

Border height

Valorile întoarse

The Gmagick object with border defined

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::charcoalimage ( float $radius , float $sigma )

Simulates a charcoal drawing.

Parametri

radius

The radius of the Gaussian, in pixels, not counting the center pixel

sigma

The standard deviation of the Gaussian, in pixels

Valorile întoarse

The Gmagick object with charcoal simulation

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

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

Valorile întoarse

The chopped Gmagick object

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::clear ( void )

Clears all resources associated to Gmagick object

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The cleared Gmagick object

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::commentimage ( string $comment )

Adds a comment to your image.

Parametri

comment

The comment to add

Valorile întoarse

The Gmagick object with comment added.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::compositeimage ( Gmagick $source , int $COMPOSE , int $x , int $y )

Composite one image onto another at the specified offset.

Parametri

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

Valorile întoarse

The Gmagick object with compositions.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick::__construct ([ string $filename ] )

The Gmagick constructor.

Parametri

filename

The path to an image to load or array of paths

Valorile întoarse

Returns a new Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::cropimage ( int $width , int $height , int $x , int $y )

Extracts a region of the image.

Parametri

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

Valorile întoarse

The cropped Gmagick object

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

width

The width of the thumbnail

height

The Height of the thumbnail

Valorile întoarse

The cropped Gmagick object

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::current ( void )

Returns reference to the current gmagick object with image pointer at the correct sequence.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns self on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

displace

The amount to displace the colormap.

Valorile întoarse

Returns self on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::deconstructimages ( void )

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a new Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::despeckleimage ( void )

Reduces the speckle noise in an image while preserving the edges of the original image.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The despeckled Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

Exemple

Example #1 Gmagick::despeckleimage() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • 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

Descrierea

public bool Gmagick::destroy ( void )

Destroys the Gmagick object and frees all resources associated with it

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::drawimage ( GmagickDraw $GmagickDraw )

Renders the GmagickDraw object on the current image

Parametri

GmagickDraw

The drawing operations to render on the image.

Valorile întoarse

The drawn Gmagick object

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

radius

The radius of the operation.

Valorile întoarse

The Gmagick object with edges enhanced.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

radius

The radius of the effect

sigma

The sigma of the effect

Valorile întoarse

The embossed Gmagick object.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::enhanceimage ( void )

Applies a digital filter that improves the quality of a noisy image.

Valorile întoarse

The enhanced Gmagick object.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::equalizeimage ( void )

Equalizes the image histogram.

Valorile întoarse

The equalized Gmagick object.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::flipimage ( void )

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

Valorile întoarse

The flipped Gmagick object.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::flopimage ( void )

Creates a horizontal mirror image by reflecting the pixels around the central y-axis.

Valorile întoarse

The flopped Gmagick object.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

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

Valorile întoarse

The framed Gmagick object.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

gamma

The amount of gamma-correction.

Valorile întoarse

The gamma corrected Gmagick object.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public string Gmagick::getcopyright ( void )

Returns the GraphicsMagick API copyright as a string.

Valorile întoarse

Returns a string containing the copyright notice of GraphicsMagick and Magickwand C API.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public string Gmagick::getfilename ( void )

Returns the filename associated with an image sequence.

Valorile întoarse

Returns a string on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public GmagickPixel Gmagick::getimagebackgroundcolor ( void )

Returns the image background color.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an GmagickPixel set to the background color of the image.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public array Gmagick::getimageblueprimary ( void )

Returns the chromaticity blue primary point for the image.

Parametri

x

The chromaticity blue primary x-point.

y

The chromaticity blue primary y-point.

Valorile întoarse

Array consisting of "x" and "y" coordinates of point.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public GmagickPixel Gmagick::getimagebordercolor ( void )

Returns the image border color.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

GmagickPixel object representing the color of the border

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimagechanneldepth ( int $channel_type )

Gets the depth for a particular image channel.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Depth of image channel

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimagecolors ( void )

Returns the color of the specified colormap index.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The number of colors in image.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimagecolorspace ( void )

Gets the image colorspace.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Colorspace

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimagecompose ( void )

Returns the composite operator associated with the image.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the composite operator associated with the image.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimagedelay ( void )

Gets the image delay

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the composite operator associated with the image.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimagedepth ( void )

Gets the depth of the image.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Image depth

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimagedispose ( void )

Gets the image disposal method

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the dispose method on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public array Gmagick::getimageextrema ( void )

Returns an associative array with the keys "min" and "max". Emite o GmagickException în caz de eroare.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an associative array with the keys "min" and "max".

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public string Gmagick::getimagefilename ( void )

Returns the filename of a particular image in a sequence

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string with the filename of the image

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public string Gmagick::getimageformat ( void )

Returns the format of a particular image in a sequence.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string containing the image format on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public float Gmagick::getimagegamma ( void )

Gets the image gamma

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the image gamma on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public array Gmagick::getimagegreenprimary ( void )

Returns the chromaticity green primary point. Returns an array with the keys "x" and "y".

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array with the keys "x" and "y" on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimageheight ( void )

Returns the image height

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the image height in pixels.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public array Gmagick::getimagehistogram ( void )

Returns the image histogram as an array of GmagickPixel objects. Throw an GmagickException on error.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the image histogram as an array of GmagickPixel objects.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimageindex ( void )

Returns the index of the current active image within the Gmagick object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Index of current active image

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimageinterlacescheme ( void )

Gets the image interlace scheme.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the interlace scheme as an integer on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimageiterations ( void )

Gets the image iterations.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the image iterations as an integer.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

Gmagick::getimageinterlacescheme
Gmagick::getimagematte
Gmagick


Check if the image has a matte channel

Gmagick::getimageiterations
Gmagick::getimagemattecolor
Gmagick
PHP Manual

Gmagick::getimagematte

(PECL gmagick >= Unknown)

Gmagick::getimagematte — Check if the image has a matte channel

Descrierea

public int Gmagick::getimagematte ( void )

Returns TRUE if the image has a matte channel, otherwise FALSE.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the image has a matte channel, otherwise FALSE.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public GmagickPixel Gmagick::getimagemattecolor ( void )

Returns GmagickPixel object on success. Throw an GmagickException on error.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns GmagickPixel object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public string Gmagick::getimageprofile ( string $name )

Returns the named image profile.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string containing the image profile.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public array Gmagick::getimageredprimary ( void )

Returns the chromaticity red primary point as an array with the keys "x" and "y".

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the chromaticity red primary point as an array with the keys "x" and "y".

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimagerenderingintent ( void )

Gets the image rendering intent

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Extracts a region of the image and returns it as a a new wand

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public array Gmagick::getimageresolution ( void )

Returns the resolution as an array.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the resolution as an array.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimagescene ( void )

Gets the image scene.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the image scene.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public string Gmagick::getimagesignature ( void )

Generates an SHA-256 message digest for the image pixel stream.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string containing the SHA-256 hash of the file.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public int Gmagick::getimagetype ( void )

Gets the potential image type.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the potential image type.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimageunits ( void )

Gets the image units of resolution.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public array Gmagick::getimagewhitepoint ( void )

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public int Gmagick::getimagewidth ( void )

Returns the width of the image.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the image width.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public string Gmagick::getpackagename ( void )

Returns the GraphicsMagick package name.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the GraphicsMagick package name as a string.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public array Gmagick::getquantumdepth ( void )

Returns the Gmagick quantum depth as a string.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the Gmagick quantum depth as a string.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public string Gmagick::getreleasedate ( void )

Returns the GraphicsMagick release date as a string.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the GraphicsMagick release date as a string.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public array Gmagick::getsamplingfactors ( void )

Gets the horizontal and vertical sampling factor.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an associative array with the horizontal and vertical sampling factors of the image.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public array Gmagick::getsize ( void )

Returns the size associated with the Gmagick object as an array with the keys "columns" and "rows".

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the size associated with the Gmagick object as an array with the keys "columns" and "rows".

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public array Gmagick::getversion ( void )

Returns the GraphicsMagick API version as a string and as a number.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the GraphicsMagick API version as a string and as a number.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public mixed Gmagick::hasnextimage ( void )

Returns TRUE if the object has more images when traversing the list in the forward direction.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the object has more images when traversing the list in the forward direction, returns FALSE if there are none.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public mixed Gmagick::haspreviousimage ( void )

Returns TRUE if the object has more images when traversing the list in the reverse direction

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the object has more images when traversing the list in the reverse direction, returns FALSE if there are none.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

radius

The radius of the implode

Valorile întoarse

Returns imploded Gmagick object.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public mixed Gmagick::labelimage ( string $label )

Adds a label to an image.

Parametri

label

The label to add

Valorile întoarse

Gmagick with label.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Gmagick object with image levelled.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public mixed Gmagick::magnifyimage ( void )

Conveniently scales an image proportionally to twice its original size.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Magnified Gmagick object.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public Gmagick Gmagick::mapimage ( gmagick $gmagick , bool $dither )

Replaces the colors of an image with the closest color from a reference image.

Parametri

gmagick

The reference image

dither

Set this integer value to something other than zero to dither the mapped image

Valorile întoarse

Gmagick object

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

radius

The radius of the pixel neighborhood.

Valorile întoarse

Gmagick object with median filter applied.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::minifyimage ( void )

A convenient method that scales an image proportionally to one-half its original size

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick 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.

Parametri

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)

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick 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.

Parametri

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.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::newimage ( int $width , int $height , string $background [, string $format ] )

Creates a new image with the specified background color

Parametri

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.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public bool Gmagick::nextimage ( void )

Associates the next image in the image list with an Gmagick object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::normalizeimage ([ int $channel ] )

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available.

Parametri

channel

Identify which channel to normalize

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick 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.

Parametri

radius

The radius of the circular neighborhood.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public bool Gmagick::previousimage ( void )

Associates the previous image in an image list with the Gmagick object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick 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.

Parametri

name

Name of profile to add or remove: ICC, IPTC, or generic profile.

profile

The profile.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick 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.

Parametri

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.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick 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.

Parametri

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.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public array Gmagick::queryfontmetrics ( GmagickDraw $draw , string $text )

MagickQueryFontMetrics() returns an array representing the font metrics.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public array Gmagick::queryfonts ([ string $pattern = "*" ] )

Returns fonts supported by Gmagick.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public array Gmagick::queryformats ([ string $pattern = "*" ] )

Returns formats supported by Gmagick.

Parametri

pattern

Specifies a string containing a pattern.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::radialblurimage ( float $angle [, int $channel = Gmagick::CHANNEL_DEFAULT ] )

Radial blurs an image.

Parametri

angle

The angle of the blur in degrees.

channel

Related channel

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick 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.

Parametri

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.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::read ( string $filename )

Reads image from filename.

Parametri

filename

The image filename.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::readimage ( string $filename )

Reads image from filename.

Parametri

filename

The image filename.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::readimageblob ( string $imageContents [, string $filename ] )

Reads image from a binary string.

Parametri

imageContents

Content of image

filename

The image filename.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::readimagefile ( resource $fp [, string $filename ] )

Reads an image or image sequence from an open file descriptor.

Parametri

fp

The file descriptor.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick 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.

Parametri

radius

The radius of the pixel neighborhood.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::removeimage ( void )

Removes an image from the image list.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public string Gmagick::removeimageprofile ( string $name )

Removes the named image profile and returns it.

Parametri

name

Name of profile to return: ICC, IPTC, or generic profile.

Valorile întoarse

The named profile.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::resampleimage ( float $xResolution , float $yResolution , int $filter , float $blur )

Resample image to desired resolution.

Parametri

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.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::resizeimage ( int $width , int $height , int $filter , float $blur [, bool $fit = false ] )

Scales an image to the desired dimensions with a filter.

Parametri

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.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::rollimage ( int $x , int $y )

Offsets an image as defined by x and y.

Parametri

x

The x offset.

y

The y offset.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

color

The background pixel.

degrees

The number of degrees to rotate the image.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

width

The number of columns in the scaled image.

height

The number of rows in the scaled image.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

Gmagick::rotateimage
Gmagick::separateimagechannel
Gmagick


Separates a channel from the image

Gmagick::scaleimage
Gmagick::setCompressionQuality
Gmagick
PHP Manual

Gmagick::separateimagechannel

(PECL gmagick >= Unknown)

Gmagick::separateimagechannel — Separates a channel from the image

Descrierea

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.

Parametri

channel

Identify which channel to extract: RedChannel, GreenChannel, BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel, BlackChannel.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

Gmagick::scaleimage
Gmagick::setCompressionQuality
Gmagick


Sets the object's default compression quality

Gmagick::separateimagechannel
Gmagick::setfilename
Gmagick
PHP Manual

Gmagick::setCompressionQuality

(No version information available, might only be in Git)

Gmagick::setCompressionQuality — Sets the object's default compression quality

Descrierea

Gmagick Gmagick::setCompressionQuality ( int $quality = 75 )

Sets the object's default compression quality.

Parametri

quality

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

Exemple

Example #1 Gmagick::setCompressionQuality()

<?php
$gm = new Gmagick();
$gm->read("magick:rose");
$gm->setCompressionQuality(2);
?>

Gmagick::separateimagechannel
Gmagick::setfilename
Gmagick


Sets the filename before you read or write the image

Gmagick::setCompressionQuality
Gmagick::setimagebackgroundcolor
Gmagick
PHP Manual

Gmagick::setfilename

(PECL gmagick >= Unknown)

Gmagick::setfilename — Sets the filename before you read or write the image

Descrierea

public Gmagick Gmagick::setfilename ( string $filename )

Sets the filename before you read or write an image file.

Parametri

filename

The image filename.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

Gmagick::setCompressionQuality
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.

Descrierea

public Gmagick Gmagick::setimagebackgroundcolor ( GmagickPixel $color )

Sets the image background color.

Parametri

color

The background pixel wand.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public Gmagick Gmagick::setimageblueprimary ( float $x , float $y )

Sets the image chromaticity blue primary point.

Parametri

x

The blue primary x-point.

y

The blue primary y-point.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public Gmagick Gmagick::setimagebordercolor ( GmagickPixel $color )

Sets the image border color.

Parametri

color

The border pixel wand.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimagechanneldepth ( int $channel , int $depth )

Sets the depth of a particular image channel.

Parametri

channel

Identify which channel to extract: RedChannel, GreenChannel, BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel, BlackChannel.

depth

The image depth in bits.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimagecolorspace ( int $colorspace )

Sets the image colorspace.

Parametri

colorspace

The image colorspace: UndefinedColorspace, RGBColorspace, GRAYColorspace, TransparentColorspace, OHTAColorspace, XYZColorspace, YCbCrColorspace, YCCColorspace, YIQColorspace, YPbPrColorspace, YPbPrColorspace, YUVColorspace, CMYKColorspace, sRGBColorspace, HSLColorspace, or HWBColorspace.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimagecompose ( int $composite )

Sets the image composite operator.

Parametri

composite

The image composite operator.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimagedelay ( int $delay )

Sets the image delay

Parametri

delay

The image delay in 1/100th of a second.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimagedepth ( int $depth )

Sets the image depth

Parametri

depth

The image depth in bits: 8, 16, or 32.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimagedispose ( int $disposeType )

Sets the image disposal method.

Parametri

disposeType

The image disposal type.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimagefilename ( string $filename )

Sets the filename of a particular image in a sequence.

Parametri

filename

The image filename.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimageformat ( string $imageFormat )

Sets the format of a particular image in a sequence.

Parametri

imageFormat

The image format.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimagegamma ( float $gamma )

Sets the image gamma.

Parametri

gamma

The image gamma.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

Gmagick::setimageformat
Gmagick::setimagegreenprimary
Gmagick


Sets the image chromaticity green primary point.

Gmagick::setimagegamma
Gmagick::setimageindex
Gmagick
PHP Manual

Gmagick::setimagegreenprimary

(PECL gmagick >= Unknown)

Gmagick::setimagegreenprimary — Sets the image chromaticity green primary point.

Descrierea

public Gmagick Gmagick::setimagegreenprimary ( float $x , float $y )

Sets the image chromaticity green primary point.

Parametri

x

The chromaticity green primary x-point.

y

The chromaticity green primary y-point.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimageindex ( int $index )

Set the iterator to the position in the image list specified with the index parameter.

Parametri

index

The scene number.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public Gmagick Gmagick::setimageinterlacescheme ( int $interlace )

Sets the interlace scheme of the image.

Parametri

interlace

The image interlace scheme: NoInterlace, LineInterlace, PlaneInterlace, PartitionInterlace.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public Gmagick Gmagick::setimageiterations ( int $iterations )

Sets the image iterations.

Parametri

iterations

The image delay in 1/100th of a second.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

name

Name of profile to add or remove: ICC, IPTC, or generic profile.

profile

The profile.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public Gmagick Gmagick::setimageredprimary ( float $x , float $y )

Sets the image chromaticity red primary point.

Parametri

x

The red primary x-point.

y

The red primary y-point.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimagerenderingintent ( int $rendering_intent )

Sets the image rendering intent.

Parametri

rendering_intent

The image rendering intent: UndefinedIntent, SaturationIntent, PerceptualIntent, AbsoluteIntent, or RelativeIntent.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimageresolution ( float $xResolution , float $yResolution )

Sets the image resolution.

Parametri

xResolution

The image x resolution.

yResolution

The image y resolution.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimagescene ( int $scene )

Sets the image scene.

Parametri

scene

The image scene number.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::setimagetype ( int $imgType )

Sets the image type.

Parametri

imgType

The image type: UndefinedType, BilevelType, GrayscaleType, GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType, TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType, or OptimizeType.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public Gmagick Gmagick::setimageunits ( int $resolution )

Sets the image units of resolution.

Parametri

resolution

The image units of resolution : Undefinedresolution, PixelsPerInchResolution, or PixelsPerCentimeterResolution.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public Gmagick Gmagick::setimagewhitepoint ( float $x , float $y )

Sets the image chromaticity white point.

Parametri

x

The white x-point.

y

The white y-point.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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.

Descrierea

public Gmagick Gmagick::setsamplingfactors ( array $factors )

Sets the image sampling factors.

Parametri

factors

An array of doubles representing the sampling factor for each color component (in RGB order).

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

columns

The width in pixels.

rows

The height in pixels.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

color

The background pixel wand.

xShear

The number of degrees to shear the image.

yShear

The number of degrees to shear the image.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

threshold

Define the extent of the solarization.

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::spreadimage ( float $radius )

Special effects method that randomly displaces each pixel in a block defined by the radius parameter.

Parametri

radius

Choose a random pixel in a neighborhood of this extent.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::stripimage ( void )

Strips an image of all profiles and comments.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

degrees

Define the tightness of the swirling effect.

Valorile întoarse

The Gmagick object on success

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

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.

Parametri

width

Image width

height

Image height

Valorile întoarse

The Gmagick object on success.

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

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

Descrierea

public Gmagick Gmagick::trimimage ( float $fuzz )

Remove edges that are the background color from the image.

Parametri

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.

Valorile întoarse

The Gmagick object

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

Gmagick::thumbnailimage
Gmagick::write
Gmagick


Pseudonim pentru Gmagick::writeimage

Gmagick::trimimage
Gmagick::writeimage
Gmagick
PHP Manual

Gmagick::write

(PECL gmagick >= Unknown)

Gmagick::write — Pseudonim pentru Gmagick::writeimage()

Descrierea

This method is an alias of Gmagick::writeimage().

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

Descrierea

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().

Parametri

filename

The image filename.

Valorile întoarse

The Gmagick object

Erori/Excep?ii

Emite o GmagickException în caz de eroare.

Gmagick::write
GmagickDraw
Gmagick


The GmagickDraw class

(PECL gmagick >= Unknown)

Introducere

Sinopsisul clasei

GmagickDraw {
/* Metode */
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 GmagickPixel getfillcolor ( void )
public float getfillopacity ( void )
public mixed getfont ( void )
public float getfontsize ( void )
public int getfontstyle ( void )
public int getfontweight ( void )
public GmagickPixel getstrokecolor ( void )
public float getstrokeopacity ( void )
public float getstrokewidth ( void )
public int gettextdecoration ( void )
public mixed 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 ( mixed $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 ( mixed $color )
public GmagickDraw setstrokeopacity ( float $stroke_opacity )
public GmagickDraw setstrokewidth ( float $width )
public GmagickDraw settextdecoration ( int $decoration )
public GmagickDraw settextencoding ( string $encoding )
}

Cuprins

  • 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 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

Descrierea

public GmagickDraw GmagickDraw::annotate ( float $x , float $y , string $text )

Draws text on the image.

Parametri

x

x ordinate to left of text

y

y ordinate to text baseline

text

text to draw

Valorile întoarse

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

Descrierea

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.

Parametri

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

Valorile întoarse

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

Descrierea

public GmagickDraw GmagickDraw::bezier ( array $coordinate_array )

Draws a bezier curve through a set of points on the image.

Parametri

coordinate_array

Coordinates array

Valorile întoarse

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

Descrierea

public GmagickDraw GmagickDraw::ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )

Draws an ellipse on the image.

Parametri

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

Valorile întoarse

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

Descrierea

public GmagickPixel GmagickDraw::getfillcolor ( void )

Returns the fill color used for drawing filled objects.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public float GmagickDraw::getfillopacity ( void )

Returns the opacity used when drawing

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public mixed GmagickDraw::getfont ( void )

Returns a string specifying the font used when annotating with text.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public float GmagickDraw::getfontsize ( void )

Returns the font pointsize used when annotating with text.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int GmagickDraw::getfontstyle ( void )

Returns the font style used when annotating with text.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int GmagickDraw::getfontweight ( void )

Returns the font weight used when annotating with text.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public GmagickPixel GmagickDraw::getstrokecolor ( void )

Returns the color used for stroking object outlines.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public float GmagickDraw::getstrokeopacity ( void )

Returns the opacity of stroked object outlines.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public float GmagickDraw::getstrokewidth ( void )

Returns the width of the stroke used to draw object outlines.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int GmagickDraw::gettextdecoration ( void )

Returns the decoration applied when annotating with text.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public mixed GmagickDraw::gettextencoding ( void )

Returns a string which specifies the code set used for text annotations.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

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.

Parametri

sx

starting x ordinate

sy

starting y ordinate

ex

ending x ordinate

ey

ending y ordinate

Valorile întoarse

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

Descrierea

public GmagickDraw GmagickDraw::point ( float $x , float $y )

Draws a point using the current stroke color and stroke thickness at the specified coordinates.

Parametri

x

target x coordinate

y

target y coordinate

Valorile întoarse

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

Descrierea

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.

Parametri

coordinates

coordinate array

Valorile întoarse

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

Descrierea

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.

Parametri

coordinate_array

The array of coordinates

Valorile întoarse

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

Descrierea

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.

Parametri

x1

x ordinate of first coordinate

y1

y ordinate of first coordinate

x2

x ordinate of second coordinate

y2

y ordinate of second coordinate

Valorile întoarse

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

Descrierea

public GmagickDraw GmagickDraw::rotate ( float $degrees )

Applies the specified rotation to the current coordinate space.

Parametri

degrees

degrees of rotation

Valorile întoarse

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

Descrierea

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.

Parametri

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

Valorile întoarse

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

Descrierea

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.

Parametri

x

horizontal scale factor

y

vertical scale factor

Valorile întoarse

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.

Descrierea

public GmagickDraw GmagickDraw::setfillcolor ( mixed $color )

Sets the fill color to be used for drawing filled objects.

Parametri

color

GmagickPixel or string indicating color to use for filling.

Valorile întoarse

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

Descrierea

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.

Parametri

fill_opacity

Fill opacity

Valorile întoarse

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.

Descrierea

public GmagickDraw GmagickDraw::setfont ( string $font )

Sets the fully-specified font to use when annotating with text

Parametri

font

font name

Valorile întoarse

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.

Descrierea

public GmagickDraw GmagickDraw::setfontsize ( float $pointsize )

Sets the font pointsize to use when annotating with text.

Parametri

pointsize

Text pointsize

Valorile întoarse

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

Descrierea

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.

Parametri

style

Font style (NormalStyle, ItalicStyle, ObliqueStyle, AnyStyle)

Valorile întoarse

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

Descrierea

public GmagickDraw GmagickDraw::setfontweight ( int $weight )

Sets the font weight to use when annotating with text.

Parametri

weight

Font weight (valid range 100-900)

Valorile întoarse

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.

Descrierea

public GmagickDraw GmagickDraw::setstrokecolor ( mixed $color )

Sets the color used for stroking object outlines.

Parametri

color

GmagickPixel or string representing the color for the stroke.

Valorile întoarse

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.

Descrierea

public GmagickDraw GmagickDraw::setstrokeopacity ( float $stroke_opacity )

Specifies the opacity of stroked object outlines.

Parametri

stroke_opacity

Stroke opacity. The value 1.0 is opaque.

Valorile întoarse

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.

Descrierea

public GmagickDraw GmagickDraw::setstrokewidth ( float $width )

Sets the width of the stroke used to draw object outlines

Parametri

width

Stroke width

Valorile întoarse

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

Descrierea

public GmagickDraw GmagickDraw::settextdecoration ( int $decoration )

Specifies a decoration to be applied when annotating with text.

Parametri

int

Text decoration. One of NoDecoration, UnderlineDecoration, OverlineDecoration, or LineThroughDecoration

Valorile întoarse

The GmagickDraw object on success

GmagickDraw::setstrokewidth
GmagickDraw::settextencoding
GmagickDraw


Specifies the text code set

GmagickDraw::settextdecoration
GmagickPixel
GmagickDraw
PHP Manual

GmagickDraw::settextencoding

(PECL gmagick >= Unknown)

GmagickDraw::settextencoding — Specifies the text code set

Descrierea

public GmagickDraw GmagickDraw::settextencoding ( string $encoding )

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.

Parametri

encoding

Character string specifying text encoding

Valorile întoarse

The GmagickDraw object on success

GmagickDraw::settextdecoration
GmagickPixel
GmagickDraw


The GmagickPixel class

(PECL gmagick >= Unknown)

Introducere

Sinopsisul clasei

GmagickPixel {
/* Metode */
public __construct ([ string $color ] )
public mixed getcolor ([ bool $as_array = false [, bool $normalize_array = false ]] )
public int getcolorcount ( void )
public float getcolorvalue ( int $color )
public GmagickPixel setcolor ( string $color )
public GmagickPixel setcolorvalue ( int $color , float $value )
}

Cuprins

  • 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

Descrierea

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.

Parametri

color

The optional color string to use as the initial value of this object.

Valorile întoarse

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

Descrierea

public mixed GmagickPixel::getcolor ([ bool $as_array = false [, bool $normalize_array = false ]] )

Returns the color described by the GmagickPixel object, as a string or an array. If the color has an opacity channel set, this is provided as a fourth value in the list.

Parametri

as_array

TRUE to indicate return of array instead of string.

normalize_array

TRUE to normalize the color values.

Valorile întoarse

A string or an array of channel values, each normalized if TRUE is given as normalize_array. 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

Descrierea

public int GmagickPixel::getcolorcount ( void )

Returns the color count associated with this color

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public float GmagickPixel::getcolorvalue ( int $color )

Retrieves the value of the color channel specified, as a floating-point number between 0 and 1.

Parametri

color

The channel to check, specified as one of the Gmagick channel constants.

Valorile întoarse

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

Descrierea

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.).

Parametri

color

The color definition to use in order to initialise the GmagickPixel object.

Valorile întoarse

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

Descrierea

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.

Parametri

color

One of the Gmagick channel color constants.

value

The value to set this channel to, ranging from 0 to 1.

Valorile întoarse

The GmagickPixel object on success.

GmagickPixel::setcolor
ImageMagick
GmagickPixel


Image Processing (ImageMagick)

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • 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::autoLevelImage — Description
    • Imagick::averageImages — Average a set of images
    • Imagick::blackThresholdImage — Forces all pixels below the threshold into black
    • Imagick::blueShiftImage — Description
    • Imagick::blurImage — Adds blur filter to image
    • Imagick::borderImage — Surrounds the image with a border
    • Imagick::brightnessContrastImage — Description
    • Imagick::charcoalImage — Simulates a charcoal drawing
    • Imagick::chopImage — Removes a region of an image and trims
    • Imagick::clampImage — Description
    • Imagick::clear — Clears all resources associated to Imagick object
    • Imagick::clipImage — Clips along the first path from the 8BIM profile
    • Imagick::clipImagePath — Description
    • 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::colorMatrixImage — Description
    • 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::count — Description
    • 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::deleteImageProperty — Description
    • 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::filter — Description
    • 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::forwardFourierTransformImage — Description
    • 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::getImageAttribute — Description
    • 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::getImageMimeType — Description
    • 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::getQuantum — Description
    • Imagick::getQuantumDepth — Gets the quantum depth
    • Imagick::getQuantumRange — Returns the Imagick quantum range
    • Imagick::getRegistry — Description
    • 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::identifyFormat — Description
    • Imagick::identifyImage — Identifies an image and fetches attributes
    • Imagick::implodeImage — Creates a new image as a copy
    • Imagick::importImagePixels — Imports image pixels
    • Imagick::inverseFourierTransformImage — Description
    • 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::listRegistry — Description
    • 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::morphology — Description
    • 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::readimages — Description
    • 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::rotationalBlurImage — Description
    • 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::selectiveBlurImage — Description
    • 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::setImageAttribute — Description
    • Imagick::setImageBackgroundColor — Sets the image background color
    • Imagick::setImageBias — Sets the image bias for any method that convolves an image
    • Imagick::setImageBiasQuantum — Description
    • 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::setProgressMonitor — Description
    • Imagick::setRegistry — Description
    • 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::smushImages — Description
    • 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::statisticImage — Description
    • 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::subImageMatch — Description
    • 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::__toString — Returns the image as a string.
    • Imagick::transformImage — Convenience method for setting crop size and the image geometry
    • Imagick::transformImageColorspace — Transforms an image to a new colorspace.
    • 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::getFontStretch — Description
    • 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::getTextInterlineSpacing — Description
    • ImagickDraw::getTextInterwordSpacing — Description
    • ImagickDraw::getTextKerning — Description
    • 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::resetVectorGraphics — Description
    • 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::setResolution — Description
    • 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 the text code set
    • ImagickDraw::setTextInterlineSpacing — Description
    • ImagickDraw::setTextInterwordSpacing — Description
    • ImagickDraw::setTextKerning — Description
    • 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::getColorQuantum — Description
    • ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
    • ImagickPixel::getColorValueQuantum — Description
    • ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
    • ImagickPixel::getIndex — Description
    • ImagickPixel::isPixelSimilar — Check the distance between this color and another
    • ImagickPixel::isPixelSimilarQuantum — Description
    • ImagickPixel::isSimilar — Check the distance between this color and another
    • ImagickPixel::setColor — Sets the color
    • ImagickPixel::setColorCount — Description
    • ImagickPixel::setColorValue — Sets the normalized value of one of the channels
    • ImagickPixel::setColorValueQuantum — Description
    • ImagickPixel::setHSL — Sets the normalized HSL color
    • ImagickPixel::setIndex — Description
  • 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
  • ImagickKernel — The ImagickKernel class
    • ImagickKernel::addKernel — Description
    • ImagickKernel::addUnityKernel — Description
    • ImagickKernel::fromBuiltIn — Description
    • ImagickKernel::fromMatrix — Description
    • ImagickKernel::getMatrix — Description
    • ImagickKernel::scale — Description
    • ImagickKernel::separate — Description
GmagickPixel::setcolorvalue
Introducere
Generarea ?i procesarea imaginilor


Introducere

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.

ImageMagick Studio LLC is a non-profit organization dedicated to making software imaging solutions freely available.

ImageMagick
Instalarea / configurarea
ImageMagick


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
ImageMagick


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/imagick.

Nota: The official name of this extension is imagick.

Windows users can download prebuilt DLL from the » PECL website.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Imagick configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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
imagick.skip_version_check | FALSE | PHP_INI_SYSTEM | Available since Imagick 3.3.0
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

imagick.skip_version_check boolean

When Imagick is loaded, it checks the version number of ImageMagick that it was compiled against, with the version number that is currently being used and will give a warning if they don't match. This warning can be suppressed by enabling this ini setting.

Using a version of Imagick that was compiled against a different version of ImageMagick than the one being used is not recommended. Although it may appear to work, it can lead to random crashes or other undefined behaviour.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
Subtracts 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)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.0 or higher.
imagick::COMPRESSION_DXT3 (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.0 or higher.
imagick::COMPRESSION_DXT5 (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 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)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 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)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 or higher.
imagick::EVALUATE_LOG (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 or higher.
imagick::EVALUATE_THRESHOLD (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 or higher.
imagick::EVALUATE_THRESHOLDBLACK (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 or higher.
imagick::EVALUATE_THRESHOLDWHITE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 or higher.
imagick::EVALUATE_GAUSSIANNOISE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 or higher.
imagick::EVALUATE_IMPULSENOISE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 or higher.
imagick::EVALUATE_LAPLACIANNOISE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 or higher.
imagick::EVALUATE_MULTIPLICATIVENOISE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 or higher.
imagick::EVALUATE_POISSONNOISE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 or higher.
imagick::EVALUATE_UNIFORMNOISE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 or higher.
imagick::EVALUATE_COSINE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 or higher.
imagick::EVALUATE_SINE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 or higher.
imagick::EVALUATE_ADDMODULUS (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 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)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 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)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_BLACK (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_GRAY (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_WHITE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_HORIZONTALTILE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.3 or higher.
imagick::VIRTUALPIXELMETHOD_VERTICALTILE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 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)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 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)
Set the maximum width * height of an image that can reside in the pixel cache memory.
imagick::RESOURCETYPE_DISK (integer)
Set maximum amount of disk space in bytes permitted for use by the pixel cache.
imagick::RESOURCETYPE_FILE (integer)
Set maximum number of open pixel cache files.
imagick::RESOURCETYPE_MAP (integer)
Set maximum amount of memory map in bytes to allocate for the pixel cache.
imagick::RESOURCETYPE_MEMORY (integer)
Set maximum amount of memory in bytes to allocate for the pixel cache from the heap.
imagick::RESOURCETYPE_THREAD (integer)
Set maximum parallel threads. Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.7.8 or higher.
LAYERMETHOD constants

imagick::LAYERMETHOD_UNDEFINED (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 or higher.
imagick::LAYERMETHOD_COALESCE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 or higher.
imagick::LAYERMETHOD_COMPAREANY (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 or higher.
imagick::LAYERMETHOD_COMPARECLEAR (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 or higher.
imagick::LAYERMETHOD_COMPAREOVERLAY (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 or higher.
imagick::LAYERMETHOD_DISPOSE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZEPLUS (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZEIMAGE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
imagick::LAYERMETHOD_OPTIMIZETRANS (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
imagick::LAYERMETHOD_REMOVEDUPS (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
imagick::LAYERMETHOD_REMOVEZERO (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
imagick::LAYERMETHOD_COMPOSITE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
imagick::LAYERMETHOD_MERGE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.7 or higher.
imagick::LAYERMETHOD_FLATTEN (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.7 or higher.
imagick::LAYERMETHOD_MOSAIC (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.7 or higher.
ORIENTATION constants

imagick::ORIENTATION_UNDEFINED (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
imagick::ORIENTATION_TOPLEFT (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
imagick::ORIENTATION_TOPRIGHT (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
imagick::ORIENTATION_BOTTOMRIGHT (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
imagick::ORIENTATION_BOTTOMLEFT (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
imagick::ORIENTATION_LEFTTOP (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
imagick::ORIENTATION_RIGHTTOP (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
imagick::ORIENTATION_RIGHTBOTTOM (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
imagick::ORIENTATION_LEFTBOTTOM (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.0 or higher.
DISTORTION constants

imagick::DISTORTION_UNDEFINED (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 or higher.
imagick::DISTORTION_AFFINE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 or higher.
imagick::DISTORTION_AFFINEPROJECTION (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 or higher.
imagick::DISTORTION_ARC (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 or higher.
imagick::DISTORTION_BILINEAR (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 or higher.
imagick::DISTORTION_PERSPECTIVE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 or higher.
imagick::DISTORTION_PERSPECTIVEPROJECTION (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 or higher.
imagick::DISTORTION_SCALEROTATETRANSLATE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 or higher.
imagick::DISTORTION_POLYNOMIAL (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::DISTORTION_POLAR (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::DISTORTION_DEPOLAR (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::DISTORTION_BARREL (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::DISTORTION_BARRELINVERSE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::DISTORTION_SHEPARDS (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::DISTORTION_SENTINEL (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
ALPHACHANNEL constants

imagick::ALPHACHANNEL_ACTIVATE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.8 or higher.
imagick::ALPHACHANNEL_DEACTIVATE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.8 or higher.
imagick::ALPHACHANNEL_RESET (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.8 or higher.
imagick::ALPHACHANNEL_SET (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.8 or higher.
imagick::ALPHACHANNEL_UNDEFINED (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::ALPHACHANNEL_COPY (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::ALPHACHANNEL_EXTRACT (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::ALPHACHANNEL_OPAQUE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::ALPHACHANNEL_SHAPE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::ALPHACHANNEL_TRANSPARENT (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
SPARSECOLORMETHOD constants

imagick::SPARSECOLORMETHOD_UNDEFINED (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_BARYCENTRIC (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_BILINEAR (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_POLYNOMIAL (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_SPEPARDS (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_VORONOI (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
FUNCTION constants

imagick::FUNCTION_UNDEFINED (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.9 or higher.
imagick::FUNCTION_POLYNOMIAL (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.9 or higher.
imagick::FUNCTION_SINUSOID (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.9 or higher.
INTERPOLATE constants

imagick::INTERPOLATE_UNDEFINED (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.2 or higher.
imagick::INTERPOLATE_AVERAGE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.2 or higher.
imagick::INTERPOLATE_BICUBIC (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.2 or higher.
imagick::INTERPOLATE_BILINEAR (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.2 or higher.
imagick::INTERPOLATE_FILTER (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.2 or higher.
imagick::INTERPOLATE_INTEGER (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.2 or higher.
imagick::INTERPOLATE_MESH (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.2 or higher.
imagick::INTERPOLATE_NEARESTNEIGHBOR (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.2 or higher.
imagick::INTERPOLATE_SPLINE (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.4 or higher.
DITHERMETHOD constants

imagick::DITHERMETHOD_UNDEFINED (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::DITHERMETHOD_NO (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::DITHERMETHOD_RIEMERSMA (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
imagick::DITHERMETHOD_FLOYDSTEINBERG (integer)
Aceasta constanta este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.6 or higher.
Tipurile resurselor
Exemple
ImageMagick


Exemple

Cuprins

  • Basic usage
Constante predefinite
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:

Example #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:

Example #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.

Example #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;
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Creating a reflection of an image

This example illustrates how to use fill patterns during drawing.

Example #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;
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Filling text with gradient

Working with animated GIF images

Example #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);
?>

Working with ellipse primitive and custom fonts

Example #6 Create a PHP logo

<?php
/* Set width and height in proportion of genuine PHP logo */
$width = 400;
$height = 210;

/* Create an Imagick object with transparent canvas */
$img = new Imagick();
$img->newImage($width, $height, new ImagickPixel('transparent'));

/* New ImagickDraw instance for ellipse draw */
$draw = new ImagickDraw();
/* Set purple fill color for ellipse */
$draw->setFillColor('#777bb4');
/* Set ellipse dimensions */
$draw->ellipse($width / 2, $height / 2, $width / 2, $height / 2, 0, 360);
/* Draw ellipse onto the canvas */
$img->drawImage($draw);

/* Reset fill color from purple to black for text (note: we are reusing ImagickDraw object) */
$draw->setFillColor('black');
/* Set stroke border to white color */
$draw->setStrokeColor('white');
/* Set stroke border thickness */
$draw->setStrokeWidth(2);
/* Set font kerning (negative value means that letters are closer to each other) */
$draw->setTextKerning(-8);
/* Set font and font size used in PHP logo */
$draw->setFont('Handel Gothic.ttf');
$draw->setFontSize(150);
/* Center text horizontally and vertically */
$draw->setGravity(Imagick::GRAVITY_CENTER);

/* Add center "php" with Y offset of -10 to canvas (inside ellipse) */
$img->annotateImage($draw, 0, -10, 0, 'php');
$img->setImageFormat('png');

/* Set appropriate header for PNG and output the image */
header('Content-Type: image/png');
echo $img;
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Creating PHP logo with Imagick

Exemple
Imagick
Exemple


The Imagick class

(PECL imagick 2.0.0)

Sinopsisul clasei

Imagick implements Iterator {
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 )
public void autoLevelImage ([ string $CHANNEL = Imagick::CHANNEL_DEFAULT ] )
Imagick averageImages ( void )
bool blackThresholdImage ( mixed $threshold )
public void blueShiftImage ([ float $factor = 1.5 ] )
bool blurImage ( float $radius , float $sigma [, int $channel ] )
bool borderImage ( mixed $bordercolor , int $width , int $height )
public void brightnessContrastImage ( string $brightness , string $contrast [, string $CHANNEL = Imagick::CHANNEL_DEFAULT ] )
bool charcoalImage ( float $radius , float $sigma )
bool chopImage ( int $width , int $height , int $x , int $y )
public void clampImage ([ string $CHANNEL = Imagick::CHANNEL_DEFAULT ] )
bool clear ( void )
bool clipImage ( void )
public void clipImagePath ( string $pathname , string $inside )
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 )
public void colorMatrixImage ( string $color_matrix = Imagick::CHANNEL_DEFAULT )
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 ] )
public void count ([ string $mode ] )
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 void deleteImageProperty ( string $name )
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 )
public void filter ( ImagickKernel $ImagickKernel [, int $CHANNEL = Imagick::CHANNEL_DEFAULT ] )
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 )
public void forwardFourierTransformimage ( bool $magnitude )
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 )
public string getImageAttribute ( string $key )
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 getImageCompressionQuality ( 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 )
public string getImageMimeType ( void )
int getImageOrientation ( void )
array getImagePage ( void )
ImagickPixel getImagePixelColor ( int $x , int $y )
string getImageProfile ( string $name )
array getImageProfiles ([ string $pattern = "*" [, bool $include_values = true ]] )
array getImageProperties ([ string $pattern = "*" [, bool $include_values = 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 )
public static int getQuantum ( void )
array getQuantumDepth ( void )
array getQuantumRange ( void )
public static string getRegistry ( string $key )
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 )
public string|false identifyFormat ( string $embedText )
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 )
public void inverseFourierTransformImage ( string $complement , string $magnitude )
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 )
public static array listRegistry ( void )
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 )
Imagick 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 )
public void morphology ( int $morphologyMethod , int $iterations , ImagickKernel $ImagickKernel [, string $CHANNEL ] )
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 ] )
public Imagick readImages ( string $filenames )
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 )
public void rotationalBlurImage ( string $angle [, string $CHANNEL = Imagick::CHANNEL_DEFAULT ] )
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 ] )
public void selectiveBlurImage ( float $radius , float $sigma , float $threshold , int $CHANNEL )
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 )
public void setImageAttribute ( string $key , string $value )
bool setImageBackgroundColor ( mixed $background )
bool setImageBias ( float $bias )
public void setImageBiasQuantum ( string $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 )
public void setProgressMonitor ( callable $callback )
public static void setRegistry ( string $key , string $value )
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 )
public Imagick smushImages ( string $stack , string $offset )
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 )
public void statisticImage ( int $type , int $width , int $height [, string $CHANNEL = Imagick::CHANNEL_DEFAULT ] )
Imagick steganoImage ( Imagick $watermark_wand , int $offset )
bool stereoImage ( Imagick $offset_wand )
bool stripImage ( void )
public Imagick subImageMatch ( Imagick $Imagick [, array &$offset [, float &$similarity ]] )
bool swirlImage ( float $degrees )
Imagick 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 )
string __toString ( void )
Imagick transformImage ( string $crop , string $geometry )
bool transformImageColorspace ( int $colorspace )
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 = NULL ] )
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() |  |  |  |

Cuprins

  • 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::autoLevelImage — Description
  • Imagick::averageImages — Average a set of images
  • Imagick::blackThresholdImage — Forces all pixels below the threshold into black
  • Imagick::blueShiftImage — Description
  • Imagick::blurImage — Adds blur filter to image
  • Imagick::borderImage — Surrounds the image with a border
  • Imagick::brightnessContrastImage — Description
  • Imagick::charcoalImage — Simulates a charcoal drawing
  • Imagick::chopImage — Removes a region of an image and trims
  • Imagick::clampImage — Description
  • Imagick::clear — Clears all resources associated to Imagick object
  • Imagick::clipImage — Clips along the first path from the 8BIM profile
  • Imagick::clipImagePath — Description
  • 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::colorMatrixImage — Description
  • 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::count — Description
  • 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::deleteImageProperty — Description
  • 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::filter — Description
  • 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::forwardFourierTransformImage — Description
  • 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::getImageAttribute — Description
  • 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::getImageMimeType — Description
  • 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::getQuantum — Description
  • Imagick::getQuantumDepth — Gets the quantum depth
  • Imagick::getQuantumRange — Returns the Imagick quantum range
  • Imagick::getRegistry — Description
  • 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::identifyFormat — Description
  • Imagick::identifyImage — Identifies an image and fetches attributes
  • Imagick::implodeImage — Creates a new image as a copy
  • Imagick::importImagePixels — Imports image pixels
  • Imagick::inverseFourierTransformImage — Description
  • 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::listRegistry — Description
  • 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::morphology — Description
  • 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::readimages — Description
  • 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::rotationalBlurImage — Description
  • 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::selectiveBlurImage — Description
  • 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::setImageAttribute — Description
  • Imagick::setImageBackgroundColor — Sets the image background color
  • Imagick::setImageBias — Sets the image bias for any method that convolves an image
  • Imagick::setImageBiasQuantum — Description
  • 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::setProgressMonitor — Description
  • Imagick::setRegistry — Description
  • 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::smushImages — Description
  • 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::statisticImage — Description
  • 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::subImageMatch — Description
  • 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::__toString — Returns the image as a string.
  • Imagick::transformImage — Convenience method for setting crop size and the image geometry
  • Imagick::transformImageColorspace — Transforms an image to a new colorspace.
  • 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

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

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

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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;

?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Using Imagick::adaptiveBlurImage()

A se vedea ?i

  • 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

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Nota: Comportamentul parametrului bestfit s-a schimbat în Imagick 3.0.0. Anterior acestei versiuni în cazul dimensiunilor 400x400, o imagine cu dimensiunile 200x150 ar fi ramas neschimbata. În Imagick 3.0.0 ?i versiunile ulterioare imaginea va fi marita la dimensiunile 400x300 deoarece aceasta este "cea mai buna potrivire" pentru dimensiunile date. Daca parametrul bestfit este utilizat, trebuie furnizate atât la?imea, cât ?i înal?imea.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Istoricul schimbarilor

Versiune | Descriere
2.1.0 | Added optional fit parameter.
2.1.0 | This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

Exemple

Example #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;
?>

A se vedea ?i

  • 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

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

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

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #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;
?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

width

Width of the local neighborhood.

height

Height of the local neighborhood.

offset

The mean offset

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::adaptiveThresholdImage()

<?php
function adaptiveThresholdImage($imagePath, $width, $height, $adaptiveOffset) {
    $imagick = new \Imagick(realpath($imagePath));
    $adaptiveOffsetQuantum = intval($adaptiveOffset * \Imagick::getQuantum());
    $imagick->adaptiveThresholdImage($width, $height, $adaptiveOffsetQuantum);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

source

The source Imagick object

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::addNoiseImage ( int $noise_type [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Adds random noise to the image.

Parametri

noise_type

The type of the noise. Refer to this list of noise constants.

channel

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::addNoiseImage()

<?php
function addNoiseImage($noiseType, $imagePath, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->addNoiseImage($noiseType, $channel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::affineTransformImage ( ImagickDraw $matrix )

Transforms an image as dictated by the affine matrix.

Parametri

matrix

The affine matrix

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::affineTransformImage()

<?php
function affineTransformImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $draw = new \ImagickDraw();

    $angle = 40 ;

    $affineRotate = array(
        "sx" => cos($angle), "sy" => cos($angle),
        "rx" => sin($angle), "ry" => -sin($angle),
        "tx" => 0, "ty" => 0,
    );

    $draw->affine($affineRotate);

    $imagick->affineTransformImage($draw);

    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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 Git)

Imagick::animateImages — Animates an image or images

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 sau ulterior.

Parametri

x_server

X server address

Valorile întoarse

Întoarce TRUE în caz de succes.

A se vedea ?i

  • 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

Descrierea

bool Imagick::annotateImage ( ImagickDraw $draw_settings , float $x , float $y , float $angle , string $text )

Annotates an image with text.

Parametri

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

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #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;

?>

A se vedea ?i

  • 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::autoLevelImage
Imagick
PHP Manual

Imagick::appendImages

(PECL imagick 2.0.0)

Imagick::appendImages — Append a set of images

Descrierea

Imagick Imagick::appendImages ( bool $stack = false )

Append a set of images into one larger image.

Parametri

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.

Valorile întoarse

Returns Imagick instance on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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;
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Imagick::appendImages()

Imagick::annotateImage
Imagick::autoLevelImage
Imagick


Description

Imagick::appendImages
Imagick::averageImages
Imagick
PHP Manual

Imagick::autoLevelImage

(No version information available, might only be in Git)

Imagick::autoLevelImage — Description

Descrierea

public void Imagick::autoLevelImage ([ string $CHANNEL = Imagick::CHANNEL_DEFAULT ] )

Adjusts the levels of a particular image channel by scaling the minimum and maximum values to the full quantum range.

Parametri

CHANNEL

Which channel should the auto-levelling should be done on.

Valorile întoarse

Exemple

Example #1 Imagick::autoLevelImage()

<?php
function autoLevelImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->autoLevelImage();
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::appendImages
Imagick::averageImages
Imagick


Average a set of images

Imagick::autoLevelImage
Imagick::blackThresholdImage
Imagick
PHP Manual

Imagick::averageImages

(PECL imagick 2.0.0)

Imagick::averageImages — Average a set of images

Descrierea

Imagick Imagick::averageImages ( void )

Average a set of images.

Valorile întoarse

Returns a new Imagick object on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::autoLevelImage
Imagick::blackThresholdImage
Imagick


Forces all pixels below the threshold into black

Imagick::averageImages
Imagick::blueShiftImage
Imagick
PHP Manual

Imagick::blackThresholdImage

(PECL imagick 2.0.0)

Imagick::blackThresholdImage — Forces all pixels below the threshold into black

Descrierea

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.

Parametri

threshold

The threshold below which everything turns black

Valorile întoarse

Întoarce TRUE în caz de succes.

Istoricul schimbarilor

Versiune | Descriere
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

Exemple

Example #1 Imagick::blackThresholdImage()

<?php
function blackThresholdImage($imagePath, $thresholdColor) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->blackthresholdimage($thresholdColor);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::averageImages
Imagick::blueShiftImage
Imagick


Description

Imagick::blackThresholdImage
Imagick::blurImage
Imagick
PHP Manual

Imagick::blueShiftImage

(No version information available, might only be in Git)

Imagick::blueShiftImage — Description

Descrierea

public void Imagick::blueShiftImage ([ float $factor = 1.5 ] )

Mutes the colors of the image to simulate a scene at nighttime in the moonlight.

Parametri

factor

Valorile întoarse

Exemple

Example #1 Imagick::blueShiftImage()

<?php
function blueShiftImage($imagePath, $blueShift) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->blueShiftImage($blueShift);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::blackThresholdImage
Imagick::blurImage
Imagick


Adds blur filter to image

Imagick::blueShiftImage
Imagick::borderImage
Imagick
PHP Manual

Imagick::blurImage

(PECL imagick 2.0.0)

Imagick::blurImage — Adds blur filter to image

Descrierea

bool Imagick::blurImage ( float $radius , float $sigma [, int $channel ] )

Adds blur filter to image. Optional third parameter to blur a specific channel.

Parametri

radius

Blur radius

sigma

Standard deviation

channel

The Channeltype constant. When not supplied, all channels are blurred.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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;

?>

A se vedea ?i

  • Imagick::adaptiveBlurImage() - Adds adaptive blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

Imagick::blueShiftImage
Imagick::borderImage
Imagick


Surrounds the image with a border

Imagick::blurImage
Imagick::brightnessContrastImage
Imagick
PHP Manual

Imagick::borderImage

(PECL imagick 2.0.0)

Imagick::borderImage — Surrounds the image with a border

Descrierea

bool Imagick::borderImage ( mixed $bordercolor , int $width , int $height )

Surrounds the image with a border of the color defined by the bordercolor ImagickPixel object.

Parametri

bordercolor

ImagickPixel object or a string containing the border color

width

Border width

height

Border height

Valorile întoarse

Întoarce TRUE în caz de succes.

Istoricul schimbarilor

Versiune | Descriere
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Exemple

Example #1 Imagick::borderImage()

<?php
function borderImage($imagePath, $color, $width, $height) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->borderImage($color, $width, $height);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::blurImage
Imagick::brightnessContrastImage
Imagick


Description

Imagick::borderImage
Imagick::charcoalImage
Imagick
PHP Manual

Imagick::brightnessContrastImage

(No version information available, might only be in Git)

Imagick::brightnessContrastImage — Description

Descrierea

public void Imagick::brightnessContrastImage ( string $brightness , string $contrast [, string $CHANNEL = Imagick::CHANNEL_DEFAULT ] )

Change the brightness and/or contrast of an image. It converts the brightness and contrast parameters into slope and intercept and calls a polynomical function to apply to the image.

Parametri

brightness

contrast

CHANNEL

Valorile întoarse

Exemple

Example #1 Imagick::brightnessContrastImage()

<?php
function brightnessContrastImage($imagePath, $brightness, $contrast, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->brightnessContrastImage($brightness, $contrast, $channel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::borderImage
Imagick::charcoalImage
Imagick


Simulates a charcoal drawing

Imagick::brightnessContrastImage
Imagick::chopImage
Imagick
PHP Manual

Imagick::charcoalImage

(PECL imagick 2.0.0)

Imagick::charcoalImage — Simulates a charcoal drawing

Descrierea

bool Imagick::charcoalImage ( float $radius , float $sigma )

Simulates a charcoal drawing.

Parametri

radius

The radius of the Gaussian, in pixels, not counting the center pixel

sigma

The standard deviation of the Gaussian, in pixels

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::charcoalImage()

<?php
function charcoalImage($imagePath, $radius, $sigma) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->charcoalImage($radius, $sigma);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::brightnessContrastImage
Imagick::chopImage
Imagick


Removes a region of an image and trims

Imagick::charcoalImage
Imagick::clampImage
Imagick
PHP Manual

Imagick::chopImage

(PECL imagick 2.0.0)

Imagick::chopImage — Removes a region of an image and trims

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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;

?>

A se vedea ?i

  • Imagick::cropImage() - Extracts a region of the image

Imagick::charcoalImage
Imagick::clampImage
Imagick


Description

Imagick::chopImage
Imagick::clear
Imagick
PHP Manual

Imagick::clampImage

(No version information available, might only be in Git)

Imagick::clampImage — Description

Descrierea

public void Imagick::clampImage ([ string $CHANNEL = Imagick::CHANNEL_DEFAULT ] )

Restricts the color range from 0 to the quantum depth.

Parametri

CHANNEL

Valorile întoarse

Imagick::chopImage
Imagick::clear
Imagick


Clears all resources associated to Imagick object

Imagick::clampImage
Imagick::clipImage
Imagick
PHP Manual

Imagick::clear

(PECL imagick 2.0.0)

Imagick::clear — Clears all resources associated to Imagick object

Descrierea

bool Imagick::clear ( void )

Clears all resources associated to Imagick object

Valorile întoarse

Întoarce TRUE în caz de succes.

Imagick::clampImage
Imagick::clipImage
Imagick


Clips along the first path from the 8BIM profile

Imagick::clear
Imagick::clipImagePath
Imagick
PHP Manual

Imagick::clipImage

(PECL imagick 2.0.0)

Imagick::clipImage — Clips along the first path from the 8BIM profile

Descrierea

bool Imagick::clipImage ( void )

Clips along the first path from the 8BIM profile, if present.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::clear
Imagick::clipImagePath
Imagick


Description

Imagick::clipImage
Imagick::clipPathImage
Imagick
PHP Manual

Imagick::clipImagePath

(No version information available, might only be in Git)

Imagick::clipImagePath — Description

Descrierea

public void Imagick::clipImagePath ( string $pathname , string $inside )

Clips along the named paths from the 8BIM profile, if present. Later operations take effect inside the path. Id may be a number if preceded with #, to work on a numbered path, e.g., "#1" to use the first path.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

pathname

inside

Valorile întoarse

Imagick::clipImage
Imagick::clipPathImage
Imagick


Clips along the named paths from the 8BIM profile

Imagick::clipImagePath
Imagick::clone
Imagick
PHP Manual

Imagick::clipPathImage

(PECL imagick 2.0.0)

Imagick::clipPathImage — Clips along the named paths from the 8BIM profile

Descrierea

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.

Parametri

pathname

The name of the path

inside

If TRUE later operations take effect inside clipping path. Otherwise later operations take effect outside clipping path.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::clipImagePath
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

Descrierea

Imagick Imagick::clone ( void )

Makes an exact copy of the Imagick object.

Avertizare

This function has been DEPRECATED as of imagick 3.1.0 in favour of using the clone keyword.

Exemple

Example #1 Imagick object cloning in different versions of imagick

<?php
// Cloning an Imagick object in imagick 2.x and 3.0:
$newImage = $image->clone();

// Cloning an Imagick object from 3.1.0 on:
$newImage = clone $image;
?>

Valorile întoarse

A copy of the Imagick object is returned.

Istoricul schimbarilor

Versiune | Descriere
3.1.0 | The method was deprecated in favour of the clone keyword.

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

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 sau ulterior.

Parametri

lookup_table

Imagick object containing the color lookup table

channel

The Channeltype constant. When not supplied, default channels are replaced.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #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');
?>

A se vedea ?i

  • 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

Descrierea

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.

Valorile întoarse

Returns a new Imagick object on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Istoricul schimbarilor

Versiune | Descriere
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::colorMatrixImage
Imagick
PHP Manual

Imagick::colorizeImage

(PECL imagick 2.0.0)

Imagick::colorizeImage — Blends the fill color with the image

Descrierea

bool Imagick::colorizeImage ( mixed $colorize , mixed $opacity )

Blends the fill color with each pixel in the image.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #1 Imagick::colorizeImage()

<?php
function colorizeImage($imagePath, $color, $opacity) {
    $imagick = new \Imagick(realpath($imagePath));
    $opacity = $opacity / 255.0;
    $opacityColor = new \ImagickPixel("rgba(0, 0, 0, $opacity)");
    $imagick->colorizeImage($color, $opacityColor);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::colorFloodfillImage
Imagick::colorMatrixImage
Imagick


Description

Imagick::colorizeImage
Imagick::combineImages
Imagick
PHP Manual

Imagick::colorMatrixImage

(No version information available, might only be in Git)

Imagick::colorMatrixImage — Description

Descrierea

public void Imagick::colorMatrixImage ( string $color_matrix = Imagick::CHANNEL_DEFAULT )

Apply color transformation to an image. The method permits saturation changes, hue rotation, luminance to alpha, and various other effects. Although variable-sized transformation matrices can be used, typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA (or RGBA with offsets). The matrix is similar to those used by Adobe Flash except offsets are in column 6 rather than 5 (in support of CMYKA images) and offsets are normalized (divide Flash offset by 255)

Parametri

color_matrix

Valorile întoarse

Exemple

Example #1 Imagick::colorMatrixImage()

<?php
function colorMatrixImage($imagePath, $colorMatrix) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->setImageOpacity(1);

    //A color matrix should look like:
    //    $colorMatrix = [
    //        1.5, 0.0, 0.0, 0.0, 0.0, -0.157,
    //        0.0, 1.0, 0.5, 0.0, 0.0, -0.157,
    //        0.0, 0.0, 1.5, 0.0, 0.0, -0.157,
    //        0.0, 0.0, 0.0, 1.0, 0.0,  0.0,
    //        0.0, 0.0, 0.0, 0.0, 1.0,  0.0,
    //        0.0, 0.0, 0.0, 0.0, 0.0,  1.0
    //    ];

    $background = new \Imagick();
    $background->newPseudoImage($imagick->getImageWidth(), $imagick->getImageHeight(),  "pattern:checkerboard");

    $background->setImageFormat('png');

    $imagick->setImageFormat('png');
    $imagick->colorMatrixImage($colorMatrix);

    $background->compositeImage($imagick, \Imagick::COMPOSITE_ATOP, 0, 0);

    header("Content-Type: image/png");
    echo $background->getImageBlob();
}

?>

Imagick::colorizeImage
Imagick::combineImages
Imagick


Combines one or more images into a single image

Imagick::colorMatrixImage
Imagick::commentImage
Imagick
PHP Manual

Imagick::combineImages

(PECL imagick 2.0.0)

Imagick::combineImages — Combines one or more images into a single image

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::colorMatrixImage
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

Descrierea

bool Imagick::commentImage ( string $comment )

Adds a comment to your image.

Parametri

comment

The comment to add

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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

Descrierea

array Imagick::compareImageChannels ( Imagick $image , int $channelType , int $metricType )

Compares one or more images and returns the difference image.

Parametri

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.

Valorile întoarse

Array consisting of new_wand and distortion.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

method

One of the layer method constants.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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 */
?>

A se vedea ?i

  • 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

Descrierea

array Imagick::compareImages ( Imagick $compare , int $metric )

Returns an array containing a reconstructed image and the difference between images.

Parametri

compare

An image to compare to.

metric

Provide a valid metric type constant. Refer to this list of metric constants.

Valorile întoarse

Returns an array containing a reconstructed image and the difference between images.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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

Descrierea

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. Any extra arguments needed for the compose algorithm should passed to setImageArtifact with 'compose:args' as the first parameter and the data as the second parameter.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Using Imagick::compositeImage():

Composite two images with the 'mathematics' compose method

<?php

// Equivalent to running the command
// convert src1.png src2.png -compose mathematics -define compose:args="1,0,-0.5,0.5" -composite output.png

$src1 = new \Imagick("./src1.png");
$src2 = new \Imagick("./src2.png");

$src1->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
$src1->setImageArtifact('compose:args', "1,0,-0.5,0.5");
$src1->compositeImage($src2, Imagick::COMPOSITE_MATHEMATICS, 0, 0);
$src1->writeImage("./output.png");

?>

A se vedea ?i

  • Imagick::setImageArtifact() - Set image artifact

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

Descrierea

Imagick::__construct ( mixed $files )

Creates an Imagick instance for a specified image or set of images.

Parametri

files

The path to an image to load or an array of paths. Paths can include wildcards for file names, or can be URLs.

Valorile întoarse

Returns a new Imagick object on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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.

Parametri

sharpen

The sharpen value

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::contrastImage()

<?php
function contrastImage($imagePath, $contrastType) {
    $imagick = new \Imagick(realpath($imagePath));
    if ($contrastType != 2) {
        $imagick->contrastImage($contrastType);
    }

    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Imagick::contrastImage
Imagick::convolveImage
Imagick


Applies a custom convolution kernel to the image

Imagick::contrastStretchImage
Imagick::count
Imagick
PHP Manual

Imagick::convolveImage

(PECL imagick 2.0.0)

Imagick::convolveImage — Applies a custom convolution kernel to the image

Descrierea

bool Imagick::convolveImage ( array $kernel [, int $channel = Imagick::CHANNEL_ALL ] )

Applies a custom convolution kernel to the image.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::convolveImage()

<?php
function convolveImage($imagePath, $bias, $kernelMatrix) {
    $imagick = new \Imagick(realpath($imagePath));
    //$edgeFindingKernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1,];
    $imagick->setImageBias($bias * \Imagick::getQuantum());
    $imagick->convolveImage($kernelMatrix);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::contrastStretchImage
Imagick::count
Imagick


Description

Imagick::convolveImage
Imagick::cropImage
Imagick
PHP Manual

Imagick::count

(No version information available, might only be in Git)

Imagick::count — Description

Descrierea

public void Imagick::count ([ string $mode ] )

Returns the number of images.

Parametri

mode

An unused argument. Currently there is a non-particularly well defined feature in PHP where calling count() on a countable object might (or might not) require this method to accept a parameter. This parameter is here to be conformant with the interface of countable, even though the param is not used.

Valorile întoarse

Imagick::convolveImage
Imagick::cropImage
Imagick


Extracts a region of the image

Imagick::count
Imagick::cropThumbnailImage
Imagick
PHP Manual

Imagick::cropImage

(PECL imagick 2.0.0)

Imagick::cropImage — Extracts a region of the image

Descrierea

bool Imagick::cropImage ( int $width , int $height , int $x , int $y )

Extracts a region of the image.

Parametri

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

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::cropImage()

<?php
function cropImage($imagePath, $startX, $startY, $width, $height) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->cropImage($width, $height, $startX, $startY);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::count
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

Descrierea

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.

Parametri

width

The width of the thumbnail

height

The Height of the thumbnail

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

Imagick Imagick::current ( void )

Returns reference to the current imagick object with image pointer at the correct sequence.

Valorile întoarse

Returns self on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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.

Parametri

displace

The amount to displace the colormap.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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 Git)

Imagick::decipherImage — Deciphers an image

Descrierea

bool Imagick::decipherImage ( string $passphrase )

Deciphers image that has been enciphered before. The image must be enciphered using Imagick::encipherImage(). Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.9 sau ulterior.

Parametri

passphrase

The passphrase

Valorile întoarse

Întoarce TRUE în caz de succes.

A se vedea ?i

  • 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

Descrierea

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.

Valorile întoarse

Returns a new Imagick object on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::decipherImage
Imagick::deleteImageArtifact
Imagick


Delete image artifact

Imagick::deconstructImages
Imagick::deleteImageProperty
Imagick
PHP Manual

Imagick::deleteImageArtifact

(No version information available, might only be in Git)

Imagick::deleteImageArtifact — Delete image artifact

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.5.7 sau ulterior.

Parametri

artifact

The name of the artifact to delete

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

A se vedea ?i

  • Imagick::setImageArtifact() - Set image artifact
  • Imagick::getImageArtifact() - Get image artifact

Imagick::deconstructImages
Imagick::deleteImageProperty
Imagick


Description

Imagick::deleteImageArtifact
Imagick::deskewImage
Imagick
PHP Manual

Imagick::deleteImageProperty

(No version information available, might only be in Git)

Imagick::deleteImageProperty — Description

Descrierea

public void Imagick::deleteImageProperty ( string $name )

Deletes an image property.

Parametri

name

The name of the property to delete.

Valorile întoarse

Imagick::deleteImageArtifact
Imagick::deskewImage
Imagick


Removes skew from the image

Imagick::deleteImageProperty
Imagick::despeckleImage
Imagick
PHP Manual

Imagick::deskewImage

(No version information available, might only be in Git)

Imagick::deskewImage — Removes skew from the image

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.5 sau ulterior.

Parametri

threshold

Deskew threshold

Valorile întoarse

Exemple

Example #1 Imagick::deskewImage()

<?php
function deskewImage($threshold) {
    $imagick = new \Imagick(realpath("images/NYTimes-Page1-11-11-1918.jpg"));
    $deskewImagick = clone $imagick;

    //This is the only thing required for deskewing.
    $deskewImagick->deskewImage($threshold);

    //The rest of this example is to make the result obvious - because
    //otherwise the result is not obvious.
    $trim = 9;

    $deskewImagick->cropImage($deskewImagick->getImageWidth() - $trim, $deskewImagick->getImageHeight(), $trim, 0);
    $imagick->cropImage($imagick->getImageWidth() - $trim, $imagick->getImageHeight(), $trim, 0);
    $deskewImagick->resizeimage($deskewImagick->getImageWidth() / 2, $deskewImagick->getImageHeight() / 2, \Imagick::FILTER_LANCZOS, 1);
    $imagick->resizeimage($imagick->getImageWidth() / 2, $imagick->getImageHeight() / 2, \Imagick::FILTER_LANCZOS, 1);
    $newCanvas = new \Imagick();
    $newCanvas->newimage($imagick->getImageWidth() + $deskewImagick->getImageWidth() + 20, $imagick->getImageHeight(), 'red', 'jpg');
    $newCanvas->compositeimage($imagick, \Imagick::COMPOSITE_COPY, 5, 0);
    $newCanvas->compositeimage($deskewImagick, \Imagick::COMPOSITE_COPY, $imagick->getImageWidth() + 10, 0);

    header("Content-Type: image/jpg");
    echo $newCanvas->getImageBlob();
}

?>

Imagick::deleteImageProperty
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

Descrierea

bool Imagick::despeckleImage ( void )

Reduces the speckle noise in an image while preserving the edges of the original image.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::despeckleImage()

<?php
function despeckleImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->despeckleImage();
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::destroy ( void )

Destroys the Imagick object and frees all resources associated with it. This method is deprecated in favour of Imagick::clear.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::displayImage ( string $servername )

This method displays an image on a X server.

Parametri

servername

The X server name

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::displayImages ( string $servername )

Displays an image or image sequence on a X server.

Parametri

servername

The X server name

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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.

Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 sau ulterior.

Parametri

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

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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;
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Using Imagick::distortImage()

A se vedea ?i

  • 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

Descrierea

bool Imagick::drawImage ( ImagickDraw $draw )

Renders the ImagickDraw object on the current image.

Parametri

draw

The drawing operations to render on the image.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

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.

Parametri

radius

The radius of the operation.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::edgeImage()

<?php
function edgeImage($imagePath, $radius) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->edgeImage($radius);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

radius

The radius of the effect

sigma

The sigma of the effect

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::embossImage()

<?php
function embossImage($imagePath, $radius, $sigma) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->embossImage($radius, $sigma);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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 Git)

Imagick::encipherImage — Enciphers an image

Descrierea

bool Imagick::encipherImage ( string $passphrase )

Converts plain pixels to enciphered pixels. The image is not readable until it has been deciphered using Imagick::decipherImage() Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.9 sau ulterior.

Parametri

passphrase

The passphrase

Valorile întoarse

Întoarce TRUE în caz de succes.

A se vedea ?i

  • 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

Descrierea

bool Imagick::enhanceImage ( void )

Applies a digital filter that improves the quality of a noisy image.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::enhanceImage()

<?php
function enhanceImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->enhanceImage();
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::equalizeImage ( void )

Equalizes the image histogram.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::equalizeImage()

<?php
function equalizeImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->equalizeImage();
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

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.

Exemple

Example #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;
?>

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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 Git)

Imagick::exportImagePixels — Exports raw image pixels

Descrierea

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). Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.7 sau ulterior.

Parametri

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

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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)
}

Valorile întoarse

Returns an array containing the pixels values.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::evaluateImage
Imagick::extentImage
Imagick


Set image size

Imagick::exportImagePixels
Imagick::filter
Imagick
PHP Manual

Imagick::extentImage

(No version information available, might only be in Git)

Imagick::extentImage — Set image size

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.1 sau ulterior.

Precautie

Prior to ImageMagick 6.5.7-8 (1623), $x was positive when shifting to the left and negative when shifting to the right, and $y was positive when shifting an image up and negative when shifting an image down. Somewhere betwen ImageMagick 6.3.7 (1591) and ImageMagick 6.5.7-8 (1623), the axes of $x and $y were flipped, so that $x was negative when shifting to the left and positive when shifting to the right, and $y was negative when shifting an image up and positive when shifting an image down. Somewhere between ImageMagick 6.5.7-8 (1623) and ImageMagick 6.6.9-7 (1641), the axes of $x and $y were flipped back to pre-ImageMagick 6.5.7-8 (1623) functionality.

Parametri

width

The new width

height

The new height

x

X position for the new size

y

Y position for the new size

Valorile întoarse

Întoarce TRUE în caz de succes.

A se vedea ?i

  • Imagick::resizeImage() - Scales an image
  • Imagick::thumbnailImage() - Changes the size of an image
  • Imagick::cropImage() - Extracts a region of the image

Imagick::exportImagePixels
Imagick::filter
Imagick


Description

Imagick::extentImage
Imagick::flattenImages
Imagick
PHP Manual

Imagick::filter

(No version information available, might only be in Git)

Imagick::filter — Description

Descrierea

public void Imagick::filter ( ImagickKernel $ImagickKernel [, int $CHANNEL = Imagick::CHANNEL_DEFAULT ] )

Applies a custom convolution kernel to the image.

Parametri

ImagickKernel

An instance of ImagickKernel that represents either a single kernel or a linked series of kernels.

CHANNEL

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Exemple

Example #1 Imagick::filter()

<?php
function filter($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $matrix = [
        [-1, 0, -1],
        [0,  5,  0],
        [-1, 0, -1],
    ];

    $kernel = \ImagickKernel::fromMatrix($matrix);
    $strength = 0.5;
    $kernel->scale($strength, \Imagick::NORMALIZE_KERNEL_VALUE);
    $kernel->addUnityKernel(1 - $strength);

    $imagick->filter($kernel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::extentImage
Imagick::flattenImages
Imagick


Merges a sequence of images

Imagick::filter
Imagick::flipImage
Imagick
PHP Manual

Imagick::flattenImages

(PECL imagick 2.0.0)

Imagick::flattenImages — Merges a sequence of images

Descrierea

Imagick Imagick::flattenImages ( void )

Merges a sequence of images. This is useful for combining Photoshop layers into a single image.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::filter
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

Descrierea

bool Imagick::flipImage ( void )

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::flipImage()

<?php
function flipImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->flipImage();
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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 Git)

Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target

Descrierea

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(). Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.8 sau ulterior.

Parametri

fill

ImagickPixel object or a string containing the fill color

fuzz

Marimea difuziei. Spre exemplu daca stabili?i difuzia la 10, atunci culoarea ro?ie de intensita?ile 100 ?i 102 respectiv sunt interpretate ca aceea?i culoare.

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

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Imagick::floodfillPaintImage()
Output of example : Imagick::floodfillPaintImage()

Imagick::flipImage
Imagick::flopImage
Imagick


Creates a horizontal mirror image

Imagick::floodFillPaintImage
Imagick::forwardFourierTransformImage
Imagick
PHP Manual

Imagick::flopImage

(PECL imagick 2.0.0)

Imagick::flopImage — Creates a horizontal mirror image

Descrierea

bool Imagick::flopImage ( void )

Creates a horizontal mirror image by reflecting the pixels around the central y-axis.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::flopImage()

<?php
function flopImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->flopImage();
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::floodFillPaintImage
Imagick::forwardFourierTransformImage
Imagick


Description

Imagick::flopImage
Imagick::frameImage
Imagick
PHP Manual

Imagick::forwardFourierTransformImage

(No version information available, might only be in Git)

Imagick::forwardFourierTransformImage — Description

Descrierea

public void Imagick::forwardFourierTransformimage ( bool $magnitude )

Implements the discrete Fourier transform (DFT) of the image either as a magnitude / phase or real / imaginary image pair.

Parametri

magnitude

If true, return as magnitude / phase pair otherwise a real / imaginary image pair.

Valorile întoarse

Exemple

Example #1 Imagick::forwardFourierTransformImage()

<?php
//Utility function for forwardTransformImage
function createMask() {
    $draw = new \ImagickDraw();

    $draw->setStrokeOpacity(0);
    $draw->setStrokeColor('rgb(255, 255, 255)');
    $draw->setFillColor('rgb(255, 255, 255)');

    //Draw a circle on the y-axis, with it's centre
    //at x, y that touches the origin
    $draw->circle(250, 250, 220, 250);

    $imagick = new \Imagick();
    $imagick->newImage(512, 512, "black");
    $imagick->drawImage($draw);
    $imagick->gaussianBlurImage(20, 20);
    $imagick->autoLevelImage();

    return $imagick;
}

function forwardFourierTransformImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->resizeimage(512, 512, \Imagick::FILTER_LANCZOS, 1);

    $mask = createMask();
    $imagick->forwardFourierTransformImage(true);

    @$imagick->setimageindex(0);
    $magnitude = $imagick->getimage();

    @$imagick->setimageindex(1);
    $imagickPhase = $imagick->getimage();

    if (true) {
        $imagickPhase->compositeImage($mask, \Imagick::COMPOSITE_MULTIPLY, 0, 0);
    }

    if (false) {
        $output = clone $imagickPhase;
        $output->setimageformat('png');
        header("Content-Type: image/png");
        echo $output->getImageBlob();
    }

    $magnitude->inverseFourierTransformImage($imagickPhase, true);

    $magnitude->setimageformat('png');
    header("Content-Type: image/png");
    echo $magnitude->getImageBlob();
}

?>

Imagick::flopImage
Imagick::frameImage
Imagick


Adds a simulated three-dimensional border

Imagick::forwardFourierTransformImage
Imagick::functionImage
Imagick
PHP Manual

Imagick::frameImage

(PECL imagick 2.0.0)

Imagick::frameImage — Adds a simulated three-dimensional border

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Istoricul schimbarilor

Versiune | Descriere
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Exemple

Example #1 Imagick::frameImage()

<?php
function frameImage($imagePath, $color, $width, $height, $innerBevel, $outerBevel) {
    $imagick = new \Imagick(realpath($imagePath));

    $width = $width + $innerBevel + $outerBevel;
    $height = $height + $innerBevel + $outerBevel;

    $imagick->frameimage(
        $color,
        $width,
        $height,
        $innerBevel,
        $outerBevel
    );
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::forwardFourierTransformImage
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 Git)

Imagick::functionImage — Applies a function on the image

Descrierea

public bool Imagick::functionImage ( int $function , array $arguments [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Applies an arithmetic, relational, or logical expression to a pseudo image.

See also » ImageMagick v6 Examples - Image Transformations — Function, Multi-Argument Evaluate

Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.9 sau ulterior.

Parametri

function

Refer to this list of function constants

arguments

Array of arguments to pass to this function.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Create a sinusoidal gradient

<?php
$imagick = new Imagick();
$imagick->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(3, -90);
$imagick->functionImage(Imagick::FUNCTION_SINUSOID, $arguments);

header("Content-Type: image/png");
$imagick->setImageFormat("png");
echo $imagick->getImageBlob();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of create a sinusoidal gradient

Example #2 Create a gradient from the polynomial (4x^2 - 4x + 1)

<?php
$imagick = new Imagick();
$imagick->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(4, -4, 1);
$imagick->functionImage(Imagick::FUNCTION_POLYNOMIAL, $arguments);

header("Content-Type: image/png");
$imagick->setimageformat("png");
echo $imagick->getImageBlob();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of create a polynomial gradient

Example #3 Create a complex gradient from the polynomial (4x^2 - 4x^2 + 1) modulated by a sinusoidal gradient

<?php
$imagick1 = new Imagick();
$imagick1->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(9, -90);
$imagick1->functionImage(Imagick::FUNCTION_SINUSOID, $arguments);

$imagick2 = new Imagick();
$imagick2->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(0.5, 0);
$imagick2->functionImage(Imagick::FUNCTION_SINUSOID, $arguments);
$imagick1->compositeimage($imagick2, Imagick::COMPOSITE_MULTIPLY, 0, 0);

header("Content-Type: image/png");
$imagick1->setImageFormat("png");
echo $imagick1->getImageBlob();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of create complex gradient

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::fxImage()

<?php
function fxImage() {
    $imagick = new \Imagick();
    $imagick->newPseudoImage(200, 200, "xc:white");

    $fx = 'xx=i-w/2; yy=j-h/2; rr=hypot(xx,yy); (.5-rr/140)*1.2+.5';
    $fxImage = $imagick->fxImage($fx);

    header("Content-Type: image/png");
    $fxImage->setimageformat('png');
    echo $fxImage->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::gammaImage()

<?php
function gammaImage($imagePath, $gamma, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->gammaImage($gamma, $channel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::gaussianBlurImage()

<?php
function gaussianBlurImage($imagePath, $radius, $sigma, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->gaussianBlurImage($radius, $sigma, $channel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

int Imagick::getColorspace ( void )

Gets the global colorspace value. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.5.7 sau ulterior.

Valorile întoarse

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

Descrierea

int Imagick::getCompression ( void )

Gets the object compression type.

Valorile întoarse

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

Descrierea

int Imagick::getCompressionQuality ( void )

Gets the object compression quality.

Valorile întoarse

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

Descrierea

string Imagick::getCopyright ( void )

Returns the ImageMagick API copyright as a string.

Valorile întoarse

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

Descrierea

string Imagick::getFilename ( void )

Returns the filename associated with an image sequence.

Valorile întoarse

Returns a string on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

string Imagick::getFont ( void )

Returns the objects font property. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.7 sau ulterior.

Valorile întoarse

Returns the string containing the font name or FALSE if not font is set.

A se vedea ?i

  • 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

Descrierea

string Imagick::getFormat ( void )

Returns the format of the Imagick object.

Valorile întoarse

Returns the format of the image.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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 Git)

Imagick::getGravity — Gets the gravity

Descrierea

int Imagick::getGravity ( void )

Gets the global gravity property for the Imagick object. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.0 sau ulterior.

Valorile întoarse

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

Descrierea

string Imagick::getHomeURL ( void )

Returns the ImageMagick home URL.

Valorile întoarse

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

Descrierea

Imagick Imagick::getImage ( void )

Returns a new Imagick object with the current image sequence.

Valorile întoarse

Returns a new Imagick object with the current image sequence.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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 Git)

Imagick::getImageAlphaChannel — Gets the image alpha channel

Descrierea

int Imagick::getImageAlphaChannel ( void )

Gets the image alpha channel value. The returned value is one of the alpha channel constants. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.0 sau ulterior.

Valorile întoarse

Returns a constant defining the current alpha channel value. Refer to this list of alpha channel constants.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::getImage
Imagick::getImageArtifact
Imagick


Get image artifact

Imagick::getImageAlphaChannel
Imagick::getImageAttribute
Imagick
PHP Manual

Imagick::getImageArtifact

(No version information available, might only be in Git)

Imagick::getImageArtifact — Get image artifact

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.5.7 sau ulterior.

Parametri

artifact

The name of the artifact

Valorile întoarse

Returns the artifact value on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

A se vedea ?i

  • Imagick::setImageArtifact() - Set image artifact
  • Imagick::deleteImageArtifact() - Delete image artifact

Imagick::getImageAlphaChannel
Imagick::getImageAttribute
Imagick


Description

Imagick::getImageArtifact
Imagick::getImageBackgroundColor
Imagick
PHP Manual

Imagick::getImageAttribute

(No version information available, might only be in Git)

Imagick::getImageAttribute — Description

Descrierea

public string Imagick::getImageAttribute ( string $key )

Returns a named attribute.

Parametri

key

The key of the attribute to get.

Valorile întoarse

Imagick::getImageArtifact
Imagick::getImageBackgroundColor
Imagick


Returns the image background color

Imagick::getImageAttribute
Imagick::getImageBlob
Imagick
PHP Manual

Imagick::getImageBackgroundColor

(PECL imagick 2.0.0)

Imagick::getImageBackgroundColor — Returns the image background color

Descrierea

ImagickPixel Imagick::getImageBackgroundColor ( void )

Returns the image background color.

Valorile întoarse

Returns an ImagickPixel set to the background color of the image.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::getImageAttribute
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

Descrierea

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().

Valorile întoarse

Returns a string containing the image.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

array Imagick::getImageBluePrimary ( void )

Returns the chromaticity blue primary point for the image.

Parametri

x

The chromaticity blue primary x-point.

y

The chromaticity blue primary y-point.

Valorile întoarse

Array consisting of "x" and "y" coordinates of point.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

ImagickPixel Imagick::getImageBorderColor ( void )

Returns the image border color.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageChannelDepth ( int $channel )

Gets the depth for a particular image channel.

Parametri

channel

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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 Git)

Imagick::getImageChannelDistortions — Gets channel distortions

Descrierea

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 Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 sau ulterior.

Parametri

reference

Imagick object containing the reference image

metric

Refer to this list of metric type constants.

channel

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Returns a double describing the channel distortion.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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".

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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 Git)

Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose

Descrierea

public array Imagick::getImageChannelKurtosis ([ int $channel = Imagick::CHANNEL_DEFAULT ] )

Get the kurtosis and skewness of a specific channel. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.9 sau ulterior.

Parametri

channel

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Returns an array with kurtosis and skewness members.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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".

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

array Imagick::getImageChannelRange ( int $channel )

Gets the range for one or more image channels. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.0 sau ulterior.

Parametri

channel

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Returns an array containing minima and maxima values of the channel(s).

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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:

Valorile întoarse

Întoarce TRUE în caz de succes.

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 Git)

Imagick::getImageClipMask — Gets image clip mask

Descrierea

Imagick Imagick::getImageClipMask ( void )

Returns the image clip mask. The clip mask is an Imagick object containing the clip mask. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 sau ulterior.

Valorile întoarse

Returns an Imagick object containing the clip mask.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

ImagickPixel Imagick::getImageColormapColor ( int $index )

Returns the color of the specified colormap index.

Parametri

index

The offset into the image colormap.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageColors ( void )

Gets the number of unique colors in the image.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

int Imagick::getImageColorspace ( void )

Gets the image colorspace.

Valorile întoarse

Returns an integer which can be compared against COLORSPACE constants.

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

Descrierea

int Imagick::getImageCompose ( void )

Returns the composite operator associated with the image.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

int Imagick::getImageCompression ( void )

Gets the current image's compression type.

Valorile întoarse

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

Descrierea

int Imagick::getImageCompressionQuality ( void )

Gets the current image's compression quality

Valorile întoarse

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

Descrierea

int Imagick::getImageDelay ( void )

Gets the image delay.

Valorile întoarse

Returns the image delay.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageDepth ( void )

Gets the image depth.

Valorile întoarse

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

Descrierea

int Imagick::getImageDispose ( void )

Gets the image disposal method.

Valorile întoarse

Returns the dispose method on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

float Imagick::getImageDistortion ( MagickWand $reference , int $metric )

Compares an image to a reconstructed image and returns the specified distortion metric.

Parametri

reference

Imagick object to compare to.

metric

One of the metric type constants.

Valorile întoarse

Returns the distortion metric used on the image (or the best guess thereof).

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

array Imagick::getImageExtrema ( void )

Gets the extrema for the image. Returns an associative array with the keys "min" and "max".

Valorile întoarse

Returns an associative array with the keys "min" and "max".

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

string Imagick::getImageFilename ( void )

Returns the filename of a particular image in a sequence.

Valorile întoarse

Returns a string with the filename of the image.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

string Imagick::getImageFormat ( void )

Returns the format of a particular image in a sequence.

Valorile întoarse

Returns a string containing the image format on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

float Imagick::getImageGamma ( void )

Gets the image gamma.

Valorile întoarse

Returns the image gamma on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

array Imagick::getImageGeometry ( void )

Returns the width and height as an associative array.

Valorile întoarse

Returns an array with the width/height of the image.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::getImageGeometry()

<?php
function getImageGeometry($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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 Git)

Imagick::getImageGravity — Gets the image gravity

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 sau ulterior.

Valorile întoarse

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

Descrierea

array Imagick::getImageGreenPrimary ( void )

Returns the chromaticity green primary point. Returns an array with the keys "x" and "y".

Valorile întoarse

Returns an array with the keys "x" and "y" on success, throws an ImagickException on failure.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageHeight ( void )

Returns the image height.

Valorile întoarse

Returns the image height in pixels.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

array Imagick::getImageHistogram ( void )

Returns the image histogram as an array of ImagickPixel objects.

Valorile întoarse

Returns the image histogram as an array of ImagickPixel objects.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Generates Imagick::getImageHistogram()

<?php
function getColorStatistics($histogramElements, $colorChannel) {
    $colorStatistics = [];

    foreach ($histogramElements as $histogramElement) {
        $color = $histogramElement->getColorValue($colorChannel);
        $color = intval($color * 255);
        $count = $histogramElement->getColorCount();

        if (array_key_exists($color, $colorStatistics)) {
            $colorStatistics[$color] += $count;
        }
        else {
            $colorStatistics[$color] = $count;
        }
    }

    ksort($colorStatistics);

    return $colorStatistics;
}

function getImageHistogram($imagePath) {

    $backgroundColor = 'black';

    $draw = new \ImagickDraw();
    $draw->setStrokeWidth(0); //make the lines be as thin as possible

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    $histogramWidth = 256;
    $histogramHeight = 100; // the height for each RGB segment

    $imagick = new \Imagick(realpath($imagePath));
    //Resize the image to be small, otherwise PHP tends to run out of memory
    //This might lead to bad results for images that are pathologically 'pixelly'
    $imagick->adaptiveResizeImage(200, 200, true);
    $histogramElements = $imagick->getImageHistogram();

    $histogram = new \Imagick();
    $histogram->newpseudoimage($histogramWidth, $histogramHeight * 3, 'xc:black');
    $histogram->setImageFormat('png');

    $getMax = function ($carry, $item)  {
        if ($item > $carry) {
            return $item;
        }
        return $carry;
    };

    $colorValues = [
        'red' => getColorStatistics($histogramElements, \Imagick::COLOR_RED),
        'lime' => getColorStatistics($histogramElements, \Imagick::COLOR_GREEN),
        'blue' => getColorStatistics($histogramElements, \Imagick::COLOR_BLUE),
    ];

    $max = array_reduce($colorValues['red'] , $getMax, 0);
    $max = array_reduce($colorValues['lime'] , $getMax, $max);
    $max = array_reduce($colorValues['blue'] , $getMax, $max);

    $scale =  $histogramHeight / $max;

    $count = 0;
    foreach ($colorValues as $color => $values) {
        $draw->setstrokecolor($color);

        $offset = ($count + 1) * $histogramHeight;

        foreach ($values as $index => $value) {
            $draw->line($index, $offset, $index, $offset - ($value * $scale));
        }
        $count++;
    }

    $histogram->drawImage($draw);

    header( "Content-Type: image/png" );
    echo $histogram;
}

?>

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

Descrierea

int Imagick::getImageIndex ( void )

Returns the index of the current active image within the Imagick object. This method has been deprecated. See Imagick::getIteratorIndex().

Valorile întoarse

Returns an integer containing the index of the image in the stack.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageInterlaceScheme ( void )

Gets the image interlace scheme.

Valorile întoarse

Returns the interlace scheme as an integer on success. Emite un ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageInterpolateMethod ( void )

Returns the interpolation method for the specified image. The method is one of the Imagick::INTERPOLATE_* constants.

Valorile întoarse

Returns the interpolate method on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageIterations ( void )

Gets the image iterations.

Valorile întoarse

Returns the image iterations as an integer.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageLength ( void )

Returns the image length in bytes

Valorile întoarse

Returns an int containing the current image size.

Exemple

Example #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

Descrierea

string Imagick::getImageMagickLicense ( void )

Returns a string containing the ImageMagick license

Valorile întoarse

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

Descrierea

bool Imagick::getImageMatte ( void )

Returns TRUE if the image has a matte channel otherwise false. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Imagick::getImageMagickLicense
Imagick::getImageMatteColor
Imagick


Returns the image matte color

Imagick::getImageMatte
Imagick::getImageMimeType
Imagick
PHP Manual

Imagick::getImageMatteColor

(PECL imagick 2.0.0)

Imagick::getImageMatteColor — Returns the image matte color

Descrierea

ImagickPixel Imagick::getImageMatteColor ( void )

Returns the image matte color.

Valorile întoarse

Returns ImagickPixel object on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::getImageMatte
Imagick::getImageMimeType
Imagick


Description

Imagick::getImageMatteColor
Imagick::getImageOrientation
Imagick
PHP Manual

Imagick::getImageMimeType

(No version information available, might only be in Git)

Imagick::getImageMimeType — Description

Descrierea

public string Imagick::getImageMimeType ( void )

Returns the image mime-type.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Imagick::getImageMatteColor
Imagick::getImageOrientation
Imagick


Gets the image orientation

Imagick::getImageMimeType
Imagick::getImagePage
Imagick
PHP Manual

Imagick::getImageOrientation

(PECL imagick 2.0.0)

Imagick::getImageOrientation — Gets the image orientation

Descrierea

int Imagick::getImageOrientation ( void )

Gets the image orientation. The return value is one of the orientation constants.

Valorile întoarse

Returns an int on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::getImageMimeType
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

Descrierea

array Imagick::getImagePage ( void )

Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y".

Valorile întoarse

Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y".

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

ImagickPixel Imagick::getImagePixelColor ( int $x , int $y )

Returns the color of the specified pixel.

Parametri

x

The x-coordinate of the pixel

y

The y-coordinate of the pixel

Valorile întoarse

Returns an ImagickPixel instance for the color at the coordinates given.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

string Imagick::getImageProfile ( string $name )

Returns the named image profile.

Parametri

name

The name of the profile to return.

Valorile întoarse

Returns a string containing the image profile.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

array Imagick::getImageProfiles ([ string $pattern = "*" [, bool $include_values = true ]] )

Returns all associated profiles that match the pattern. If FALSE is passed as second parameter only the profile names are returned. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 sau ulterior.

Parametri

pattern

The pattern for profile names.

include_values

Whether to return only profile names. If FALSE then only profile names will be returned.

Valorile întoarse

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

Descrierea

array Imagick::getImageProperties ([ string $pattern = "*" [, bool $include_values = true ]] )

Returns all associated properties that match the pattern. If FALSE is passed as second parameter only the property names are returned. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 sau ulterior.

Parametri

pattern

The pattern for property names.

include_values

Whether to return only property names. If FALSE then only property names will be returned.

Valorile întoarse

Returns an array containing the image properties or property names.

Exemple

Example #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

Descrierea

string Imagick::getImageProperty ( string $name )

Returns the named image property. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.2 sau ulterior.

Parametri

name

name of the property (for example Exif:DateTime)

Exemple

Example #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');
?>

A se vedea ?i

  • Imagick::setImageProperty() - Sets an image property

Valorile întoarse

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

Descrierea

array Imagick::getImageRedPrimary ( void )

Returns the chromaticity red primary point as an array with the keys "x" and "y".

Valorile întoarse

Returns the chromaticity red primary point as an array with the keys "x" and "y". Emite un ImagickException în caz de eroare.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Extracts a region of the image and returns it as a new wand.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageRenderingIntent ( void )

Gets the image rendering intent.

Valorile întoarse

Returns the image rendering intent.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

array Imagick::getImageResolution ( void )

Gets the image X and Y resolution.

Valorile întoarse

Returns the resolution as an array.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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().

Valorile întoarse

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

Descrierea

int Imagick::getImageScene ( void )

Gets the image scene.

Valorile întoarse

Returns the image scene.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

string Imagick::getImageSignature ( void )

Generates an SHA-256 message digest for the image pixel stream.

Valorile întoarse

Returns a string containing the SHA-256 hash of the file.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageSize ( void )

Returns the image length in bytes. Deprecated in favour of Imagick::getImageLength()

Valorile întoarse

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

Descrierea

int Imagick::getImageTicksPerSecond ( void )

Gets the image ticks-per-second.

Valorile întoarse

Returns the image ticks-per-second.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

float Imagick::getImageTotalInkDensity ( void )

Gets the image total ink density.

Valorile întoarse

Returns the image total ink density of the image. Emite un ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageType ( void )

Gets the potential image type.

Valorile întoarse

Returns the potential image type.

  • imagick::IMGTYPE_UNDEFINED
  • imagick::IMGTYPE_BILEVEL
  • imagick::IMGTYPE_GRAYSCALE
  • imagick::IMGTYPE_GRAYSCALEMATTE
  • imagick::IMGTYPE_PALETTE
  • imagick::IMGTYPE_PALETTEMATTE
  • imagick::IMGTYPE_TRUECOLOR
  • imagick::IMGTYPE_TRUECOLORMATTE
  • imagick::IMGTYPE_COLORSEPARATION
  • imagick::IMGTYPE_COLORSEPARATIONMATTE
  • imagick::IMGTYPE_OPTIMIZE

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageUnits ( void )

Gets the image units of resolution.

Valorile întoarse

Returns the image units of resolution.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageVirtualPixelMethod ( void )

Returns the virtual pixel method for the specified image.

Valorile întoarse

Returns the virtual pixel method on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

array Imagick::getImageWhitePoint ( void )

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Valorile întoarse

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getImageWidth ( void )

Returns the image width.

Valorile întoarse

Returns the image width.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getInterlaceScheme ( void )

Gets the object interlace scheme.

Valorile întoarse

Gets the wand interlace scheme.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getIteratorIndex ( void )

Returns the index of the current active image within the Imagick object. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Valorile întoarse

Returns an integer containing the index of the image in the stack.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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();
?>

A se vedea ?i

  • 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

Descrierea

int Imagick::getNumberImages ( void )

Returns the number of images associated with Imagick object.

Valorile întoarse

Returns the number of images associated with Imagick object.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

string Imagick::getOption ( string $key )

Returns a value associated within the object for the specified key.

Parametri

key

The name of the option

Valorile întoarse

Returns a value associated with a wand and the specified key.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

string Imagick::getPackageName ( void )

Returns the ImageMagick package name.

Valorile întoarse

Returns the ImageMagick package name as a string.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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".

Valorile întoarse

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

Descrierea

ImagickPixelIterator Imagick::getPixelIterator ( void )

Returns a MagickPixelIterator.

Valorile întoarse

Returns an ImagickPixelIterator on success.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::getPixelIterator()

<?php
function getPixelIterator($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imageIterator = $imagick->getPixelIterator();

    foreach ($imageIterator as $row => $pixels) { /* Loop through pixel rows */
        foreach ($pixels as $column => $pixel) { /* Loop through the pixels in the row (columns) */
            /** @var $pixel \ImagickPixel */
            if ($column % 2) {
                $pixel->setColor("rgba(0, 0, 0, 0)"); /* Paint every second pixel black*/
            }
        }
        $imageIterator->syncIterator(); /* Sync the iterator, this is important to do on each iteration */
    }

    header("Content-Type: image/jpg");
    echo $imagick;
}

?>

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

Descrierea

ImagickPixelIterator Imagick::getPixelRegionIterator ( int $x , int $y , int $columns , int $rows )

Get an ImagickPixelIterator for an image section.

Parametri

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.

Valorile întoarse

Returns an ImagickPixelIterator for an image section.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::getPixelRegionIterator() example

Iterate over the pixels in the top left of the image, changing them to be black.

<?php
$im = new Imagick(realpath("./testImage.png"));
$areaIterator = $im->getPixelRegionIterator(0, 0, 10, 10);

foreach ($areaIterator as $rowIterator) {
    foreach ($rowIterator as $pixel) {
        // Paint every pixel black
        $pixel->setColor("rgba(0, 0, 0, 0)");
    }
    $areaIterator->syncIterator();
}
$im->writeImage("./output.png");
?>

Imagick::getPixelIterator
Imagick::getPointSize
Imagick


Gets point size

Imagick::getPixelRegionIterator
Imagick::getQuantum
Imagick
PHP Manual

Imagick::getPointSize

(No version information available, might only be in Git)

Imagick::getPointSize — Gets point size

Descrierea

float Imagick::getPointSize ( void )

Returns the objects point size property. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.7 sau ulterior.

Valorile întoarse

Returns a float containing the point size.

A se vedea ?i

  • Imagick::setPointSize() - Sets point size

Imagick::getPixelRegionIterator
Imagick::getQuantum
Imagick


Description

Imagick::getPointSize
Imagick::getQuantumDepth
Imagick
PHP Manual

Imagick::getQuantum

(No version information available, might only be in Git)

Imagick::getQuantum — Description

Descrierea

public static int Imagick::getQuantum ( void )

Returns the ImageMagick quantum range as an integer.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Imagick::getPointSize
Imagick::getQuantumDepth
Imagick


Gets the quantum depth

Imagick::getQuantum
Imagick::getQuantumRange
Imagick
PHP Manual

Imagick::getQuantumDepth

(PECL imagick 2.0.0)

Imagick::getQuantumDepth — Gets the quantum depth

Descrierea

array Imagick::getQuantumDepth ( void )

Returns the Imagick quantum depth as a string.

Valorile întoarse

Returns the Imagick quantum depth as a string.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::getQuantum
Imagick::getQuantumRange
Imagick


Returns the Imagick quantum range

Imagick::getQuantumDepth
Imagick::getRegistry
Imagick
PHP Manual

Imagick::getQuantumRange

(PECL imagick 2.0.0)

Imagick::getQuantumRange — Returns the Imagick quantum range

Descrierea

array Imagick::getQuantumRange ( void )

Returns the quantum range for the Imagick instance.

Valorile întoarse

Returns an associative array containing the quantum range as an integer ("quantumRangeLong") and as a string ("quantumRangeString").

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::getQuantumDepth
Imagick::getRegistry
Imagick


Description

Imagick::getQuantumRange
Imagick::getReleaseDate
Imagick
PHP Manual

Imagick::getRegistry

(No version information available, might only be in Git)

Imagick::getRegistry — Description

Descrierea

public static string Imagick::getRegistry ( string $key )

Get the StringRegistry entry for the named key or false if not set.

Parametri

key

The entry to get.

Valorile întoarse

Imagick::getQuantumRange
Imagick::getReleaseDate
Imagick


Returns the ImageMagick release date

Imagick::getRegistry
Imagick::getResource
Imagick
PHP Manual

Imagick::getReleaseDate

(PECL imagick 2.0.0)

Imagick::getReleaseDate — Returns the ImageMagick release date

Descrierea

string Imagick::getReleaseDate ( void )

Returns the ImageMagick release date as a string.

Valorile întoarse

Returns the ImageMagick release date as a string.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::getRegistry
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

Descrierea

int Imagick::getResource ( int $type )

Returns the specified resource's memory usage in megabytes.

Parametri

type

Refer to the list of resourcetype constants.

Valorile întoarse

Returns the specified resource's memory usage in megabytes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

int Imagick::getResourceLimit ( int $type )

Returns the specified resource limit.

Parametri

type

Refer to the list of resourcetype constants.

Valorile întoarse

Returns the specified resource limit in megabytes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

array Imagick::getSamplingFactors ( void )

Gets the horizontal and vertical sampling factor.

Valorile întoarse

Returns an associative array with the horizontal and vertical sampling factors of the image.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

array Imagick::getSize ( void )

Returns the size associated with the Imagick object as an array with the keys "columns" and "rows".

Valorile întoarse

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

Descrierea

int Imagick::getSizeOffset ( void )

Returns the size offset associated with the Imagick object. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Valorile întoarse

Returns the size offset associated with the Imagick object.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

array Imagick::getVersion ( void )

Returns the ImageMagick API version as a string and as a number.

Valorile întoarse

Returns the ImageMagick API version as a string and as a number.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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 Git)

Imagick::haldClutImage — Replaces colors in the image

Descrierea

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.

Parametri

clut

Imagick object containing the Hald lookup image.

channel

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::haldClutImage()

<?php
function haldClutImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagickPalette = new \Imagick(realpath("images/hald/hald_8.png"));
    $imagickPalette->sepiatoneImage(55);
    $imagick->haldClutImage($imagickPalette);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::hasNextImage ( void )

Returns TRUE if the object has more images when traversing the list in the forward direction.

Valorile întoarse

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::identifyFormat
Imagick
PHP Manual

Imagick::hasPreviousImage

(PECL imagick 2.0.0)

Imagick::hasPreviousImage — Checks if the object has a previous image

Descrierea

bool Imagick::hasPreviousImage ( void )

Returns TRUE if the object has more images when traversing the list in the reverse direction

Valorile întoarse

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::identifyFormat
Imagick


Description

Imagick::hasPreviousImage
Imagick::identifyImage
Imagick
PHP Manual

Imagick::identifyFormat

(No version information available, might only be in Git)

Imagick::identifyFormat — Description

Descrierea

public string|false Imagick::identifyFormat ( string $embedText )

Replaces any embedded formatting characters with the appropriate image property and returns the interpreted text. See http://www.imagemagick.org/script/escape.php for escape sequences.

Parametri

embedText

A string containing formatting sequences e.g. "Trim box: %@ number of unique colors: %k".

Valorile întoarse

Exemple

Example #1 Imagick::identifyFormat()

<?php
        $output = "Output of 'Trim box: %@ number of unique colors: %k' is: <br/>";
        $imagick = new \Imagick(realpath("./images/artifact/mask.png"));
        $output .= $imagick->identifyFormat("Trim box: %@ number of unique colors: %k");

?>

Imagick::hasPreviousImage
Imagick::identifyImage
Imagick


Identifies an image and fetches attributes

Imagick::identifyFormat
Imagick::implodeImage
Imagick
PHP Manual

Imagick::identifyImage

(PECL imagick 2.0.0)

Imagick::identifyImage — Identifies an image and fetches attributes

Descrierea

array Imagick::identifyImage ([ bool $appendRawOutput = false ] )

Identifies an image and returns the attributes. Attributes include the image width, height, size, and others.

Parametri

appendRawOutput

Valorile întoarse

Identifies an image and returns the attributes. Attributes include the image width, height, size, and others.

Example #1 Example Result Format

Array
(
    [imageName] => /some/path/image.jpg
    [format] => JPEG (Joint Photographic Experts Group JFIF format)
    [geometry] => Array
        (
            [width] => 90
            [height] => 90
        )

    [type] => TrueColor
    [colorSpace] => RGB
    [resolution] => Array
        (
            [x] => 300
            [y] => 300
        )

    [units] => PixelsPerInch
    [fileSize] => 1.88672kb
    [compression] => JPEG
    [signature] => 9a6dc8f604f97d0d691c0286176ddf992e188f0bebba98494b2146ee2d7118da
)

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::identifyFormat
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

Descrierea

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.

Parametri

radius

The radius of the implode

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::implodeImage()

<?php
function implodeImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->implodeImage(0.0001);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();

}

?>

Imagick::identifyImage
Imagick::importImagePixels
Imagick


Imports image pixels

Imagick::implodeImage
Imagick::inverseFourierTransformImage
Imagick
PHP Manual

Imagick::importImagePixels

(No version information available, might only be in Git)

Imagick::importImagePixels — Imports image pixels

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.5 sau ulterior.

Parametri

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

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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;

?>

Exemplul de mai sus va afi?a ceva similar cu:

Output of example : Imagick::importImagePixels()

Imagick::implodeImage
Imagick::inverseFourierTransformImage
Imagick


Description

Imagick::importImagePixels
Imagick::labelImage
Imagick
PHP Manual

Imagick::inverseFourierTransformImage

(No version information available, might only be in Git)

Imagick::inverseFourierTransformImage — Description

Descrierea

public void Imagick::inverseFourierTransformImage ( string $complement , string $magnitude )

Implements the inverse discrete Fourier transform (DFT) of the image either as a magnitude / phase or real / imaginary image pair.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

complement

The second image to combine with this one to form either the magnitude / phase or real / imaginary image pair.

magnitude

If true, combine as magnitude / phase pair otherwise a real / imaginary image pair.

Valorile întoarse

Imagick::importImagePixels
Imagick::labelImage
Imagick


Adds a label to an image

Imagick::inverseFourierTransformImage
Imagick::levelImage
Imagick
PHP Manual

Imagick::labelImage

(PECL imagick 2.0.0)

Imagick::labelImage — Adds a label to an image

Descrierea

bool Imagick::labelImage ( string $label )

Adds a label to an image.

Parametri

label

The label to add

Valorile întoarse

Întoarce TRUE în caz de succes.

Imagick::inverseFourierTransformImage
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::levelImage()

<?php
function levelImage($blackPoint, $gamma, $whitePoint) {
    $imagick = new \Imagick();
    $imagick->newPseudoimage(500, 500, 'gradient:black-white');

    $imagick->setFormat('png');
    $quantum = $imagick->getQuantum();
    $imagick->levelImage($blackPoint / 100 , $gamma, $quantum * $whitePoint / 100);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::linearStretchImage ( float $blackPoint , float $whitePoint )

Stretches with saturation the image intensity.

Parametri

blackPoint

The image black point

whitePoint

The image white point

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::linearStretchImage()

<?php
function linearStretchImage($imagePath, $blackThreshold, $whiteThreshold) {
    $imagick = new \Imagick(realpath($imagePath));
    $pixels = $imagick->getImageWidth() * $imagick->getImageHeight();
    $imagick->linearStretchImage($blackThreshold * $pixels, $whiteThreshold * $pixels);

    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::levelImage
Imagick::liquidRescaleImage
Imagick


Animates an image or images

Imagick::linearStretchImage
Imagick::listRegistry
Imagick
PHP Manual

Imagick::liquidRescaleImage

(No version information available, might only be in Git)

Imagick::liquidRescaleImage — Animates an image or images

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.9 sau ulterior.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

A se vedea ?i

  • Imagick::resizeImage() - Scales an image

Imagick::linearStretchImage
Imagick::listRegistry
Imagick


Description

Imagick::liquidRescaleImage
Imagick::magnifyImage
Imagick
PHP Manual

Imagick::listRegistry

(No version information available, might only be in Git)

Imagick::listRegistry — Description

Descrierea

public static array Imagick::listRegistry ( void )

List all the registry settings. Returns an array of all the key/value pairs in the registry

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array containing the key/values from the registry.

Imagick::liquidRescaleImage
Imagick::magnifyImage
Imagick


Scales an image proportionally 2x

Imagick::listRegistry
Imagick::mapImage
Imagick
PHP Manual

Imagick::magnifyImage

(PECL imagick 2.0.0)

Imagick::magnifyImage — Scales an image proportionally 2x

Descrierea

bool Imagick::magnifyImage ( void )

Is a convenience method that scales an image proportionally to twice its original size.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::magnifyImage()

<?php
function magnifyImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->magnifyImage();
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::listRegistry
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.

Descrierea

bool Imagick::mapImage ( Imagick $map , bool $dither )

Parametri

map

dither

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Istoricul schimbarilor

Versiune | Descriere
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

Descrierea

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.

Parametri

radius

The radius of the pixel neighborhood.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::medianFilterImage()

<?php
function medianFilterImage($radius, $imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    @$imagick->medianFilterImage($radius);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

Imagick 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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.7 sau ulterior.

Parametri

layer_method

One of the Imagick::LAYERMETHOD_* constants

Valorile întoarse

Returns an Imagick object containing the merged image.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

A se vedea ?i

  • Imagick::flattenImages() - Merges a sequence of images

Exemple

Example #1 Imagick::mergeImageLayers()

<?php
function mergeImageLayers($layerMethodType, $imagePath1, $imagePath2) {

    $imagick = new \Imagick(realpath($imagePath));

    $imagick2 = new \Imagick(realpath($imagePath2));
    $imagick->addImage($imagick2);
    $imagick->setImageFormat('png');

    $result = $imagick->mergeImageLayers($layerMethodType);
    header("Content-Type: image/png");
    echo $result->getImageBlob();
}

?>

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

Descrierea

bool Imagick::minifyImage ( void )

Is a convenience method that scales an image proportionally to one-half its original size

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

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.

Parametri

brightness

saturation

hue

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::modulateImage()

<?php
function modulateImage($imagePath, $hue, $brightness, $saturation) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->modulateImage($brightness, $saturation, $hue);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Imagick::modulateImage
Imagick::morphImages
Imagick


Method morphs a set of images

Imagick::montageImage
Imagick::morphology
Imagick
PHP Manual

Imagick::morphImages

(PECL imagick 2.0.0)

Imagick::morphImages — Method morphs a set of images

Descrierea

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.

Parametri

number_frames

The number of in-between images to generate.

Valorile întoarse

This method returns a new Imagick object on success. Emite un ImagickException în caz de eroare.

Imagick::montageImage
Imagick::morphology
Imagick


Description

Imagick::morphImages
Imagick::mosaicImages
Imagick
PHP Manual

Imagick::morphology

(No version information available, might only be in Git)

Imagick::morphology — Description

Descrierea

public void Imagick::morphology ( int $morphologyMethod , int $iterations , ImagickKernel $ImagickKernel [, string $CHANNEL ] )

Applies a user supplied kernel to the image according to the given morphology method.

Parametri

morphologyMethod

Which morphology method to use one of the \Imagick::MORPHOLOGY_* constants.

iterations

The number of iteration to apply the morphology function. A value of -1 means loop until no change found. How this is applied may depend on the morphology method. Typically this is a value of 1.

ImagickKernel

CHANNEL

Valorile întoarse

Exemple

Example #1 Convolve Imagick::morphology()

<?php
        $imagick = $this->getCharacter();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_GAUSSIAN, "5,1");
        $imagick->morphology(\Imagick::MORPHOLOGY_CONVOLVE, 2, $kernel);
        header("Content-Type: image/png");
        echo $imagick->getImageBlob();

?>

Example #2 Correlate Imagick::morphology()

<?php

        // Top-left pixel must be black
        // Bottom right pixel must be white
        // We don't care about the rest.

        $imagick = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromMatrix(self::$correlateMatrix, [2, 2]);
        $imagick->morphology(\Imagick::MORPHOLOGY_CORRELATE, 1, $kernel);
        header("Content-Type: image/png");
        echo $imagick->getImageBlob();

?>

Example #3 Erode Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
        $canvas->morphology(\Imagick::MORPHOLOGY_ERODE, 2, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #4 Erode Intensity Imagick::morphology()

<?php
        $canvas = $this->getCharacter();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "1");
        $canvas->morphology(\Imagick::MORPHOLOGY_ERODE_INTENSITY, 2, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #5 Dilate Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
        $canvas->morphology(\Imagick::MORPHOLOGY_DILATE, 4, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #6 Dilate intensity Imagick::morphology()

<?php
        $canvas = $this->getCharacter();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "1");
        $canvas->morphology(\Imagick::MORPHOLOGY_DILATE_INTENSITY, 4, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #7 Distance with Chebyshev kernel Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_CHEBYSHEV, "3");
        $canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);
        $canvas->autoLevelImage();
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #8 Distance with Manhattan kernel Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_MANHATTAN, "5");
        $canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);
        $canvas->autoLevelImage();
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #9 Distance with ocatagonal kernel Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGONAL, "5");
        $canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);
        $canvas->autoLevelImage();
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #10 Distance with Euclidean kernel Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_EUCLIDEAN, "4");
        $canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);
        $canvas->autoLevelImage();
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #11 Edge Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
        $canvas->morphology(\Imagick::MORPHOLOGY_EDGE, 1, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #12 Open Imagick::morphology()

<?php
        // As a result you will see that 'Open' smoothed the outline, by rounding off any sharp points, and remove any parts that is smaller than the shape used. It will also disconnect or 'open' any thin bridges.
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");
        $canvas->morphology(\Imagick::MORPHOLOGY_OPEN, 1, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #13 Open intensity Imagick::morphology()

<?php
        // As a result you will see that 'Open' smoothed the outline, by rounding off any sharp points, and remove any parts that is smaller than the shape used. It will also disconnect or 'open' any thin bridges.

        $canvas = $this->getCharacter();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");
        $canvas->morphology(\Imagick::MORPHOLOGY_OPEN_INTENSITY, 1, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #14 Close Imagick::morphology()

<?php
        //The basic use of the 'Close' method is to reduce or remove any 'holes' or 'gaps' about the size of the kernel 'Structure Element'. That is 'close' parts of the background that are about that size.
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");
        $canvas->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #15 Close Intensity Imagick::morphology()

<?php
        //The basic use of the 'Close' method is to reduce or remove any 'holes' or 'gaps' about the size of the kernel 'Structure Element'. That is 'close' parts of the background that are about that size.
        $canvas = $this->getCharacter();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");
        $canvas->morphology(\Imagick::MORPHOLOGY_CLOSE_INTENSITY, 1, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #16 Smooth Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
        $canvas->morphology(\Imagick::MORPHOLOGY_SMOOTH, 1, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #17 Edge in Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
        $canvas->morphology(\Imagick::MORPHOLOGY_EDGE_IN, 1, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #18 Edge out Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
        $canvas->morphology(\Imagick::MORPHOLOGY_EDGE_OUT, 1, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #19 The 'TopHat' method, or more specifically 'White Top Hat', returns the pixels that were removed by a Opening of the shape, that is the pixels that were removed to round off the points, and the connecting bridged between shapes. Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "5");
        $canvas->morphology(\Imagick::MORPHOLOGY_TOP_HAT, 1, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #20 The 'BottomHat' method, also known as 'Black TopHat' is the pixels that a Closing of the shape adds to the image. That is the the pixels that were used to fill in the 'holes', 'gaps', and 'bridges'. Imagick::morphology()

<?php

        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "5");
        $canvas->morphology(\Imagick::MORPHOLOGY_BOTTOM_HAT, 1, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #21 Hit and Miss Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        //This finds all the pixels with 3 pixels of the right edge
        $matrix = [[1, false, false, 0]];
        $kernel = \ImagickKernel::fromMatrix(
            $matrix,
            [0, 0]
        );
        $canvas->morphology(\Imagick::MORPHOLOGY_HIT_AND_MISS, 1, $kernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #22 Thinning Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $leftEdgeKernel = \ImagickKernel::fromMatrix([[0, 1]], [1, 0]);
        $rightEdgeKernel = \ImagickKernel::fromMatrix([[1, 0]], [0, 0]);
        $leftEdgeKernel->addKernel($rightEdgeKernel);

        $canvas->morphology(\Imagick::MORPHOLOGY_THINNING, 3, $leftEdgeKernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #23 Thicken Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $leftEdgeKernel = \ImagickKernel::fromMatrix([[0, 1]], [1, 0]);
        $rightEdgeKernel = \ImagickKernel::fromMatrix([[1, 0]], [0, 0]);
        $leftEdgeKernel->addKernel($rightEdgeKernel);

        $canvas->morphology(\Imagick::MORPHOLOGY_THICKEN, 3, $leftEdgeKernel);
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #24 Thick to generate a convex hull Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $diamondKernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DIAMOND, "1");
        $convexKernel =  \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_CONVEX_HULL, "");

        // The thicken morphology doesn't handle small gaps. We close them
        // with the close morphology.
        $canvas->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $diamondKernel);
        $canvas->morphology(\Imagick::MORPHOLOGY_THICKEN, -1, $convexKernel);
        $canvas->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $diamondKernel);

        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #25 Iterative morphology Imagick::morphology()

<?php
        $canvas = $this->getCharacterOutline();
        $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "2");
        $canvas->morphology(\Imagick::MORPHOLOGY_ITERATIVE, 3, $kernel);
        $canvas->autoLevelImage();
        header("Content-Type: image/png");
        echo $canvas->getImageBlob();

?>

Example #26 Helper functon to get an image silhouette Imagick::morphology()

<?php
    private function getCharacterOutline() {

        $imagick = new \Imagick(realpath("./images/character.png"));
        $character = new \Imagick();
        $character->newPseudoImage(
            $imagick->getImageWidth(),
            $imagick->getImageHeight(),
            "canvas:white"
        );
        $canvas = new \Imagick();
        $canvas->newPseudoImage(
            $imagick->getImageWidth(),
            $imagick->getImageHeight(),
            "canvas:black"
        );

        $character->compositeimage(
            $imagick,
            \Imagick::COMPOSITE_COPYOPACITY,
            0, 0
        );
        $canvas->compositeimage(
            $character,
            \Imagick::COMPOSITE_ATOP,
            0, 0
        );
        $canvas->setFormat('png');

        return $canvas;
    }

?>

Imagick::morphImages
Imagick::mosaicImages
Imagick


Forms a mosaic from images

Imagick::morphology
Imagick::motionBlurImage
Imagick
PHP Manual

Imagick::mosaicImages

(PECL imagick 2.0.0)

Imagick::mosaicImages — Forms a mosaic from images

Descrierea

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Imagick::morphology
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::motionBlurImage()

<?php
function motionBlurImage($imagePath, $radius, $sigma, $angle, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->motionBlurImage($radius, $sigma, $angle, $channel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::negateImage()

<?php
function negateImage($imagePath, $grayOnly, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->negateImage($grayOnly, $channel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::newImage ( int $cols , int $rows , mixed $background [, string $format ] )

Creates a new image and associates ImagickPixel value as background color

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Istoricul schimbarilor

Versiune | Descriere
2.1.0 | Now allows a string representing the color as the third parameter. Previous versions allow only an ImagickPixel object.

Exemple

Example #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

Descrierea

bool Imagick::newPseudoImage ( int $columns , int $rows , string $pseudoString )

Creates a new image using ImageMagick pseudo-formats.

Parametri

columns

columns in the new image

rows

rows in the new image

pseudoString

string containing pseudo image definition.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::newPseudoImage()

<?php
function newPseudoImage($canvasType) {
    $imagick = new \Imagick();
    $imagick->newPseudoImage(300, 300, $canvasType);
    $imagick->setImageFormat("png");
    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

//newPseudoImage('gradient:red-rgba(64, 255, 255, 0.5)');
//newPseudoImage("radial-gradient:red-blue");
newPseudoImage("plasma:fractal");

?>

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

Descrierea

bool Imagick::nextImage ( void )

Associates the next image in the image list with an Imagick object.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::normalizeImage()

<?php
function normalizeImage($imagePath, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $original = clone $imagick;
    $original->cropimage($original->getImageWidth() / 2, $original->getImageHeight(), 0, 0);
    $imagick->normalizeImage($channel);
    $imagick->compositeimage($original, \Imagick::COMPOSITE_ATOP, 0, 0);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

radius

The radius of the circular neighborhood.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::oilPaintImage()

<?php
function oilPaintImage($imagePath, $radius) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->oilPaintImage($radius);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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 Git)

Imagick::opaquePaintImage — Changes the color value of any pixel that matches target

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.8 sau ulterior.

Parametri

target

ImagickPixel object or a string containing the color to change

fill

The replacement color

fuzz

Marimea difuziei. Spre exemplu daca stabili?i difuzia la 10, atunci culoarea ro?ie de intensita?ile 100 ?i 102 respectiv sunt interpretate ca aceea?i culoare.

invert

If TRUE paints any pixel that does not match the target color.

channel

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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);
?>

A se vedea ?i

  • 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

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.1 sau ulterior.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::orderedPosterizeImage()

<?php
function orderedPosterizeImage($imagePath, $orderedPosterizeType) {
    $imagick = new \Imagick(realpath($imagePath));

    $imagick->orderedPosterizeImage($orderedPosterizeType);
    $imagick->setImageFormat('png');

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

//orderedPosterizeImage($imagePath, 'o4x4,3,3');
//orderedPosterizeImage($imagePath, 'o8x8,6,6');
orderedPosterizeImage($imagePath, 'h8x8a');

?>

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

Descrierea

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.

Parametri

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

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Istoricul schimbarilor

Versiune | Descriere
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

Descrierea

bool Imagick::paintTransparentImage ( mixed $target , float $alpha , float $fuzz )

Changes any pixel that matches color with the color defined by fill.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Istoricul schimbarilor

Versiune | Descriere
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

Descrierea

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.

Parametri

filename

The filename to read the information from.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

image

A string containing the image.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #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();
?>

A se vedea ?i

  • 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

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

filehandle

An open filehandle to the image.

fileName

Optional filename for this image.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #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);
?>

A se vedea ?i

  • 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

Descrierea

bool Imagick::polaroidImage ( ImagickDraw $properties , float $angle )

Simulates a Polaroid picture. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.2 sau ulterior.

Parametri

properties

The polaroid properties

angle

The polaroid angle

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #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

Descrierea

bool Imagick::posterizeImage ( int $levels , bool $dither )

Reduces the image to a limited number of color level.

Parametri

levels

dither

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::posterizeImage()

<?php
function posterizeImage($imagePath, $posterizeType, $numberLevels) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->posterizeImage($numberLevels, $posterizeType);
    $imagick->setImageFormat('png');
    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

posterizeImage($imagePath, \Imagick::DITHERMETHOD_RIEMERSMA, 8);

?>

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

Descrierea

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.

Parametri

preview

Preview type. See Preview type constants

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::previousImage ( void )

Assocates the previous image in an image list with the Imagick object.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

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.

Parametri

name

profile

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::quantizeImage ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )

Parametri

numberColors

colorspace

treedepth

dither

measureError

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::quantizeImage()

<?php
function quantizeImage($imagePath, $numberColors, $colorSpace, $treeDepth, $dither) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->quantizeImage($numberColors, $colorSpace, $treeDepth, $dither, false);
    $imagick->setImageFormat('png');
    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::quantizeImages ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )

Parametri

numberColors

colorspace

treedepth

dither

measureError

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

array Imagick::queryFontMetrics ( ImagickDraw $properties , string $text [, bool $multiline ] )

Returns a multi-dimensional array representing the font metrics.

Parametri

properties

ImagickDraw object containing font properties

text

The text

multiline

Multiline parameter. If left empty it is autodetected

Valorile întoarse

Returns a multi-dimensional array representing the font metrics.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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

Descrierea

array Imagick::queryFonts ([ string $pattern = "*" ] )

Returns the configured fonts.

Parametri

pattern

The query pattern

Valorile întoarse

Returns an array containing the configured fonts.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::queryFonts()

<?php
        $output = '';
        $output .= "Fonts that match 'Helvetica*' are:<br/>";

        $fontList = \Imagick::queryFonts("Helvetica*");

        foreach ($fontList as $fontName) {
            $output .= '<li>'. $fontName."</li>";
        }

        return $output;

?>

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

Descrierea

array Imagick::queryFormats ([ string $pattern = "*" ] )

Returns formats supported by Imagick.

Parametri

pattern

Valorile întoarse

Returns an array containing the formats supported by Imagick.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::queryFormats()

<?php
    function render() {
        $output = "";
        $input = \Imagick::queryformats();
        $columns = 6;

        $output .= "<table border='2'>";

        for ($i=0; $i < count($input); $i += $columns) {
            $output .= "<tr>";
            for ($c=0; $c<$columns; $c++) {
                $output .= "<td>";
                if (($i + $c) <  count($input)) {
                    $output .= $input[$i + $c];
                }
                $output .= "</td>";
            }
            $output .= "</tr>";
        }

        $output .= "</table>";

        return $output;
    }

?>

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

Descrierea

bool Imagick::radialBlurImage ( float $angle [, int $channel = Imagick::CHANNEL_ALL ] )

Radial blurs an image.

Parametri

angle

channel

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::radialBlurImage()

<?php
function radialBlurImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    //Blur 3 times with different radii
    $imagick->radialBlurImage(3);
    $imagick->radialBlurImage(5);
    $imagick->radialBlurImage(7);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

width

height

x

y

raise

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::raiseImage()

<?php
function raiseImage($imagePath, $width, $height, $x, $y, $raise) {
    $imagick = new \Imagick(realpath($imagePath));

    //x and y do nothing?
    $imagick->raiseImage($width, $height, $x, $y, $raise);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::randomThresholdImage()

<?php
function randomThresholdimage($imagePath, $lowThreshold, $highThreshold, $channel) {
    $imagick = new \Imagick(realpath($imagePath));

    $imagick->randomThresholdimage(
        $lowThreshold * \Imagick::getQuantum(),
        $highThreshold * \Imagick::getQuantum(),
        $channel
    );
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::readImage ( string $filename )

Reads image from filename

Parametri

filename

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::readImageBlob ( string $image [, string $filename ] )

Reads image from a binary string

Parametri

image

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::readImageBlob()

<?php
function readImageBlob() {
    $base64 = "iVBORw0KGgoAAAANSUhEUgAAAM0AAAD
 NCAMAAAAsYgRbAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5c
 cllPAAAABJQTFRF3NSmzMewPxIG//ncJEJsldTou1jHgAAAARBJREFUeNrs2EEK
 gCAQBVDLuv+V20dENbMY831wKz4Y/VHb/5RGQ0NDQ0NDQ0NDQ0NDQ0NDQ
 0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0PzMWtyaGhoaGhoaGhoaGhoaGhoxtb0QGho
 aGhoaGhoaGhoaGhoaMbRLEvv50VTQ9OTQ5OpyZ01GpM2g0bfmDQaL7S+ofFC6x
 v3ZpxJiywakzbvd9r3RWPS9I2+MWk0+kbf0Hih9Y17U0nTHibrDDQ0NDQ0NDQ0
 NDQ0NDQ0NTXbRSL/AK72o6GhoaGhoRlL8951vwsNDQ0NDQ1NDc0WyHtDTEhD
 Q0NDQ0NTS5MdGhoaGhoaGhoaGhoaGhoaGhoaGhoaGposzSHAAErMwwQ2HwRQ
 AAAAAElFTkSuQmCC";

    $imageBlob = base64_decode($base64);

    $imagick = new Imagick();
    $imagick->readImageBlob($imageBlob);

    header("Content-Type: image/png");
    echo $imagick;
}

?>

Imagick::readImage
Imagick::readImageFile
Imagick


Reads image from open filehandle

Imagick::readImageBlob
Imagick::readimages
Imagick
PHP Manual

Imagick::readImageFile

(PECL imagick 2.0.0)

Imagick::readImageFile — Reads image from open filehandle

Descrierea

bool Imagick::readImageFile ( resource $filehandle [, string $fileName = null ] )

Reads image from open filehandle

Parametri

filehandle

fileName

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::readImageBlob
Imagick::readimages
Imagick


Description

Imagick::readImageFile
Imagick::recolorImage
Imagick
PHP Manual

Imagick::readimages

(No version information available, might only be in Git)

Imagick::readimages — Description

Descrierea

public Imagick Imagick::readImages ( string $filenames )

Reads image from an array of filenames. All the images are held in a single Imagick object.

Parametri

filenames

Valorile întoarse

The Imagick object that contains all the images.

Imagick::readImageFile
Imagick::recolorImage
Imagick


Recolors image

Imagick::readimages
Imagick::reduceNoiseImage
Imagick
PHP Manual

Imagick::recolorImage

(No version information available, might only be in Git)

Imagick::recolorImage — Recolors image

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 sau ulterior.

Parametri

matrix

The matrix containing the color values

Valorile întoarse

Întoarce TRUE în caz de succes.

A se vedea ?i

  • Imagick::displayImage() - Displays an image

Exemple

Example #1 Imagick::recolorImage()

<?php
function recolorImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $remapColor = [ 1, 0, 0,
        0, 0, 1,
        0, 1, 0,];

//$remapColor = [
//    1.438, -0.122, -0.016,  0, 0, -0.03,
//    -0.062,  1.378, -0.016,  0, 0,  0.05,
//    -0.062, -0.122, 1.483,   0, 0, -0.02,
//];

    @$imagick->recolorImage($remapColor);

    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::readimages
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

Descrierea

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.

Parametri

radius

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::reduceNoiseImage()

<?php
function reduceNoiseImage($imagePath, $reduceNoise) {
    $imagick = new \Imagick(realpath($imagePath));
    @$imagick->reduceNoiseImage($reduceNoise);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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 Git)

Imagick::remapImage — Remaps image colors

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.5 sau ulterior.

Parametri

replacement

An Imagick object containing the replacement colors

DITHER

Refer to this list of dither method constants

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::removeImage ( void )

Removes an image from the image list.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

string Imagick::removeImageProfile ( string $name )

Removes the named image profile and returns it.

Parametri

name

Valorile întoarse

Returns a string containing the profile of the image.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::render ( void )

Renders all preceding drawing commands.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::resampleImage ( float $x_resolution , float $y_resolution , int $filter , float $blur )

Resample image to desired resolution.

Parametri

x_resolution

y_resolution

filter

blur

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::resampleImage()

<?php
function resampleImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));

    $imagick->resampleImage(200, 200, \Imagick::FILTER_LANCZOS, 1);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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 Git)

Imagick::resetImagePage — Reset image page

Descrierea

bool Imagick::resetImagePage ( string $page )

The page definition as a string. The string is in format WxH+x+y. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 sau ulterior.

Parametri

page

The page definition. For example 7168x5147+0+0

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] )

Scales an image to the desired dimensions with a filter.

Nota: Comportamentul parametrului bestfit s-a schimbat în Imagick 3.0.0. Anterior acestei versiuni în cazul dimensiunilor 400x400, o imagine cu dimensiunile 200x150 ar fi ramas neschimbata. În Imagick 3.0.0 ?i versiunile ulterioare imaginea va fi marita la dimensiunile 400x300 deoarece aceasta este "cea mai buna potrivire" pentru dimensiunile date. Daca parametrul bestfit este utilizat, trebuie furnizate atât la?imea, cât ?i înal?imea.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Istoricul schimbarilor

Versiune | Descriere
2.1.0 | Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

Exemple

Example #1 Imagick::resizeImage()

<?php
function resizeImage($imagePath, $width, $height, $filterType, $blur, $bestFit, $cropZoom) {
    //The blur factor where &gt; 1 is blurry, &lt; 1 is sharp.
    $imagick = new \Imagick(realpath($imagePath));

    $imagick->resizeImage($width, $height, $filterType, $blur, $bestFit);

    $cropWidth = $imagick->getImageWidth();
    $cropHeight = $imagick->getImageHeight();

    if ($cropZoom) {
        $newWidth = $cropWidth / 2;
        $newHeight = $cropHeight / 2;

        $imagick->cropimage(
            $newWidth,
            $newHeight,
            ($cropWidth - $newWidth) / 2,
            ($cropHeight - $newHeight) / 2
        );

        $imagick->scaleimage(
            $imagick->getImageWidth() * 4,
            $imagick->getImageHeight() * 4
        );
    }

    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::rollImage ( int $x , int $y )

Offsets an image as defined by x and y.

Parametri

x

The X offset.

y

The Y offset.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::rollImage()

<?php
function rollImage($imagePath, $rollX, $rollY) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->rollimage($rollX, $rollY);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::resizeImage
Imagick::rotateImage
Imagick


Rotates an image

Imagick::rollImage
Imagick::rotationalBlurImage
Imagick
PHP Manual

Imagick::rotateImage

(PECL imagick 2.0.0)

Imagick::rotateImage — Rotates an image

Descrierea

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.

Parametri

background

The background color

degrees

Rotation angle, in degrees. The rotation angle is interpreted as the number of degrees to rotate the image clockwise.

Valorile întoarse

Întoarce TRUE în caz de succes.

Istoricul schimbarilor

Versiune | Descriere
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Exemple

Example #1 Imagick::rotateImage()

<?php
function rotateImage($imagePath, $angle, $color) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->rotateimage($color, $angle);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::rollImage
Imagick::rotationalBlurImage
Imagick


Description

Imagick::rotateImage
Imagick::roundCorners
Imagick
PHP Manual

Imagick::rotationalBlurImage

(No version information available, might only be in Git)

Imagick::rotationalBlurImage — Description

Descrierea

public void Imagick::rotationalBlurImage ( string $angle [, string $CHANNEL = Imagick::CHANNEL_DEFAULT ] )

Rotational blurs an image.

Parametri

angle

The angle to apply the blur over.

CHANNEL

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Exemple

Example #1 Imagick::rotationalBlurImage()

<?php
function rotationalBlurImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->rotationalBlurImage(3);
    $imagick->rotationalBlurImage(5);
    $imagick->rotationalBlurImage(7);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::rotateImage
Imagick::roundCorners
Imagick


Rounds image corners

Imagick::rotationalBlurImage
Imagick::sampleImage
Imagick
PHP Manual

Imagick::roundCorners

(PECL imagick 2.0.0)

Imagick::roundCorners — Rounds image corners

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

x_rounding

x rounding

y_rounding

y rounding

stroke_width

stroke width

displace

image displace

size_correction

size correction

Exemple

Example #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");
?>

Valorile întoarse

Întoarce TRUE în caz de succes.

Imagick::rotationalBlurImage
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

Descrierea

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.

Parametri

columns

rows

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

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.

Nota: Comportamentul parametrului bestfit s-a schimbat în Imagick 3.0.0. Anterior acestei versiuni în cazul dimensiunilor 400x400, o imagine cu dimensiunile 200x150 ar fi ramas neschimbata. În Imagick 3.0.0 ?i versiunile ulterioare imaginea va fi marita la dimensiunile 400x300 deoarece aceasta este "cea mai buna potrivire" pentru dimensiunile date. Daca parametrul bestfit este utilizat, trebuie furnizate atât la?imea, cât ?i înal?imea.

Parametri

cols

rows

bestfit

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Istoricul schimbarilor

Versiune | Descriere
2.1.0 | Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

Exemple

Example #1 Imagick::scaleImage()

<?php
function scaleImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->scaleImage(150, 150, true);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::sampleImage
Imagick::segmentImage
Imagick


Segments an image

Imagick::scaleImage
Imagick::selectiveBlurImage
Imagick
PHP Manual

Imagick::segmentImage

(No version information available, might only be in Git)

Imagick::segmentImage — Segments an image

Descrierea

public bool Imagick::segmentImage ( int $COLORSPACE , float $cluster_threshold , float $smooth_threshold [, bool $verbose = false ] )

Analyses the image and identifies units that are similar. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.5 sau ulterior.

Parametri

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.

Valorile întoarse

Exemple

Example #1 Imagick::segmentImage()

<?php
function segmentImage($imagePath, $colorSpace, $clusterThreshold, $smoothThreshold) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->segmentImage($colorSpace, $clusterThreshold, $smoothThreshold);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

segmentImage($imagePath, \Imagick::COLORSPACE_RGB, 5, 5);

?>

Imagick::scaleImage
Imagick::selectiveBlurImage
Imagick


Description

Imagick::segmentImage
Imagick::separateImageChannel
Imagick
PHP Manual

Imagick::selectiveBlurImage

(No version information available, might only be in Git)

Imagick::selectiveBlurImage — Description

Descrierea

public void Imagick::selectiveBlurImage ( float $radius , float $sigma , float $threshold , int $CHANNEL )

Selectively blur an image within a contrast threshold. It is similar to the unsharpen mask that sharpens everything with contrast above a certain threshold.

Parametri

radius

sigma

threshold

CHANNEL

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Exemple

Example #1 Imagick::selectiveBlurImage()

<?php
function selectiveBlurImage($imagePath, $radius, $sigma, $threshold, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->selectiveBlurImage($radius, $sigma, $threshold, $channel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::segmentImage
Imagick::separateImageChannel
Imagick


Separates a channel from the image

Imagick::selectiveBlurImage
Imagick::sepiaToneImage
Imagick
PHP Manual

Imagick::separateImageChannel

(PECL imagick 2.0.0)

Imagick::separateImageChannel — Separates a channel from the image

Descrierea

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.

Parametri

channel

Which 'channel' to return. For colorspaces other than RGB, you can still use the CHANNEL_RED, CHANNEL_GREEN, CHANNEL_BLUE constants to indicate the 1st, 2nd and 3rd channels.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::separateImageChannel()

<?php
function separateImageChannel($imagePath, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->separateimagechannel($channel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

separateImageChannel($imagePath, \Imagick::CHANNEL_GREEN);

?>

Imagick::selectiveBlurImage
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

Descrierea

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.

Parametri

threshold

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::sepiaToneImage()

<?php
function sepiaToneImage($imagePath, $sepia) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->sepiaToneImage($sepia);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::setBackgroundColor ( mixed $background )

Sets the object's default background color.

Parametri

background

Valorile întoarse

Întoarce TRUE în caz de succes.

Istoricul schimbarilor

Versiune | Descriere
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 Git)

Imagick::setColorspace — Set colorspace

Descrierea

bool Imagick::setColorspace ( int $COLORSPACE )

Sets the global colorspace value for the object. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.5.7 sau ulterior.

Parametri

COLORSPACE

One of the COLORSPACE constants

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setCompression ( int $compression )

Sets the object's default compression type

Parametri

compression

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::setCompressionQuality ( int $quality )

Sets the object's default compression quality.

Precautie

This method only works for new images e.g. those created through Imagick::newPseudoImage. For existing images you should use Imagick::setImageCompressionQuality().

Parametri

quality

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::setCompressionQuality()

<?php
function setCompressionQuality($imagePath, $quality) {

    $backgroundImagick = new \Imagick(realpath($imagePath));
    $imagick = new \Imagick();
    $imagick->setCompressionQuality($quality);
    $imagick->newPseudoImage(
        $backgroundImagick->getImageWidth(),
        $backgroundImagick->getImageHeight(),
        'canvas:white'
    );

    $imagick->compositeImage(
        $backgroundImagick,
        \Imagick::COMPOSITE_ATOP,
        0,
        0
    );

    $imagick->setFormat("jpg");
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::setFilename ( string $filename )

Sets the filename before you read or write an image file.

Parametri

filename

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::setFirstIterator ( void )

Sets the Imagick iterator to the first image.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

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 configuration 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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.7 sau ulterior.

Parametri

font

Font name or a filename

Valorile întoarse

Întoarce TRUE în caz de succes.

A se vedea ?i

  • Imagick::getFont() - Gets font
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text
  • ImagickDraw::getFont() - Returns the font

Exemple

Example #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

Descrierea

bool Imagick::setFormat ( string $format )

Sets the format of the Imagick object.

Parametri

format

Valorile întoarse

Întoarce TRUE în caz de succes.

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 Git)

Imagick::setGravity — Sets the gravity

Descrierea

bool Imagick::setGravity ( int $gravity )

Sets the global gravity property for the Imagick object. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.0 sau ulterior.

Parametri

gravity

The gravity property. Refer to the list of gravity constants.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool Imagick::setImage ( Imagick $replace )

Replaces the current image sequence with the image from replace object.

Parametri

replace

The replace Imagick object

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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 Git)

Imagick::setImageAlphaChannel — Sets image alpha channel

Descrierea

bool Imagick::setImageAlphaChannel ( int $mode )

Activate or deactivate image alpha channel. The mode is one of the Imagick::ALPHACHANNEL_* constants. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.8 sau ulterior.

Parametri

mode

One of the Imagick::ALPHACHANNEL_* constants

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

A se vedea ?i

  • Imagick::setImageMatte() - Sets the image matte channel
  • Imagick Alpha Channel Constants

Imagick::setImage
Imagick::setImageArtifact
Imagick


Set image artifact

Imagick::setImageAlphaChannel
Imagick::setImageAttribute
Imagick
PHP Manual

Imagick::setImageArtifact

(No version information available, might only be in Git)

Imagick::setImageArtifact — Set image artifact

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.5.7 sau ulterior.

Parametri

artifact

The name of the artifact

value

The value of the artifact

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

A se vedea ?i

  • Imagick::getImageArtifact() - Get image artifact
  • Imagick::deleteImageArtifact() - Delete image artifact

Exemple

Example #1 Imagick::setImageArtifact()

<?php
function setImageArtifact() {

    $src1 = new \Imagick(realpath("./images/artifact/source1.png"));
    $src2 = new \Imagick(realpath("./images/artifact/source2.png"));

    $src2->setImageVirtualPixelMethod(\Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
    $src2->setImageArtifact('compose:args', "1,0,-0.5,0.5");
    $src1->compositeImage($src2, Imagick::COMPOSITE_MATHEMATICS, 0, 0);

    $src1->setImageFormat('png');
    header("Content-Type: image/png");
    echo $src1->getImagesBlob();
}

?>

Imagick::setImageAlphaChannel
Imagick::setImageAttribute
Imagick


Description

Imagick::setImageArtifact
Imagick::setImageBackgroundColor
Imagick
PHP Manual

Imagick::setImageAttribute

(No version information available, might only be in Git)

Imagick::setImageAttribute — Description

Descrierea

public void Imagick::setImageAttribute ( string $key , string $value )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

key

value

Valorile întoarse

Imagick::setImageArtifact
Imagick::setImageBackgroundColor
Imagick


Sets the image background color

Imagick::setImageAttribute
Imagick::setImageBias
Imagick
PHP Manual

Imagick::setImageBackgroundColor

(PECL imagick 2.0.0)

Imagick::setImageBackgroundColor — Sets the image background color

Descrierea

bool Imagick::setImageBackgroundColor ( mixed $background )

Sets the image background color.

Parametri

background

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Istoricul schimbarilor

Versiune | Descriere
2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object.

Imagick::setImageAttribute
Imagick::setImageBias
Imagick


Sets the image bias for any method that convolves an image

Imagick::setImageBackgroundColor
Imagick::setImageBiasQuantum
Imagick
PHP Manual

Imagick::setImageBias

(PECL imagick 2.0.0)

Imagick::setImageBias — Sets the image bias for any method that convolves an image

Descrierea

bool Imagick::setImageBias ( float $bias )

Sets the image bias for any method that convolves an image (e.g. Imagick::ConvolveImage()).

Parametri

bias

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::setImageBias()

<?php
//requires ImageMagick version 6.9.0-1 to have an effect on convolveImage
function setImageBias($bias) {
    $imagick = new \Imagick(realpath("images/stack.jpg"));

    $xKernel = array(
        -0.70, 0, 0.70,
        -0.70, 0, 0.70,
        -0.70, 0, 0.70
    );

    $imagick->setImageBias($bias * \Imagick::getQuantum());
    $imagick->convolveImage($xKernel, \Imagick::CHANNEL_ALL);

    $imagick->setImageFormat('png');

    header('Content-type: image/png');
    echo $imagick->getImageBlob();
}

?>

Imagick::setImageBackgroundColor
Imagick::setImageBiasQuantum
Imagick


Description

Imagick::setImageBias
Imagick::setImageBluePrimary
Imagick
PHP Manual

Imagick::setImageBiasQuantum

(No version information available, might only be in Git)

Imagick::setImageBiasQuantum — Description

Descrierea

public void Imagick::setImageBiasQuantum ( string $bias )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

bias

Valorile întoarse

Imagick::setImageBias
Imagick::setImageBluePrimary
Imagick


Sets the image chromaticity blue primary point

Imagick::setImageBiasQuantum
Imagick::setImageBorderColor
Imagick
PHP Manual

Imagick::setImageBluePrimary

(PECL imagick 2.0.0)

Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point

Descrierea

bool Imagick::setImageBluePrimary ( float $x , float $y )

Sets the image chromaticity blue primary point.

Parametri

x

y

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::setImageBiasQuantum
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

Descrierea

bool Imagick::setImageBorderColor ( mixed $border )

Sets the image border color.

Parametri

border

The border color

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Istoricul schimbarilor

Versiune | Descriere
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

Descrierea

bool Imagick::setImageChannelDepth ( int $channel , int $depth )

Sets the depth of a particular image channel.

Parametri

channel

depth

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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 Git)

Imagick::setImageClipMask — Sets image clip mask

Descrierea

bool Imagick::setImageClipMask ( Imagick $clip_mask )

Sets image clip mask from another Imagick object. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 sau ulterior.

Parametri

clip_mask

The Imagick object containing the clip mask

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::setImageClipMask()

<?php
function setImageClipMask($imagePath) {
    $imagick = new \Imagick();
    $imagick->readImage(realpath($imagePath));

    $width = $imagick->getImageWidth();
    $height = $imagick->getImageHeight();

    $clipMask = new \Imagick();
    $clipMask->newPseudoImage(
        $width,
        $height,
        "canvas:transparent"
    );

    $draw = new \ImagickDraw();
    $draw->setFillColor('white');
    $draw->circle(
        $width / 2,
        $height / 2,
        ($width / 2) + ($width / 4),
        $height / 2
    );
    $clipMask->drawImage($draw);
    $imagick->setImageClipMask($clipMask);

    $imagick->negateImage(false);
    $imagick->setFormat("png");

    header("Content-Type: image/png");
    echo $imagick->getImagesBlob();

}

?>

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

Descrierea

bool Imagick::setImageColormapColor ( int $index , ImagickPixel $color )

Sets the color of the specified colormap index.

Parametri

index

color

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setImageColorspace ( int $colorspace )

Sets the image colorspace. This method should be used when creating new images. To change the colorspace of an existing image, you should use Imagick::transformImageColorspace().

Parametri

colorspace

One of the COLORSPACE constants

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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.

Parametri

compose

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setImageCompression ( int $compression )

Parametri

compression

One of the COMPRESSION constants

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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 Git)

Imagick::setImageCompressionQuality — Sets the image compression quality

Descrierea

bool Imagick::setImageCompressionQuality ( int $quality )

Sets the image compression quality.

Parametri

quality

The image compression quality as an integer

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::setImageCompressionQuality()

<?php
function setImageCompressionQuality($imagePath, $quality) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->setImageCompressionQuality($quality);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::setImageDelay ( int $delay )

Sets the image delay. For an animated image this is the amount of time that this frame of the image should be displayed for, before displaying the next frame.

The delay can be set individually for each frame in an image.

Parametri

delay

The amount of time expressed in 'ticks' that the image should be displayed for. For animated GIFs there are 100 ticks per second, so a value of 20 would be 20/100 of a second aka 1/5th of a second.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Modify animated Gif with Imagick::setImageDelay()

<?php

// Modify an animated Gif so that it's frames are played at a variable speed,
// varying between being shown for 50ms down to 0ms, which will cause the frame
// to be skipped in most browsers.
$imagick = new Imagick(realpath("Test.gif"));
$imagick = $imagick->coalesceImages();

$frameCount = 0;

foreach ($imagick as $frame) {
    $imagick->setImageDelay((($frameCount % 11) * 5));
    $frameCount++;
}

$imagick = $imagick->deconstructImages();

$imagick->writeImages("/path/to/save/output.gif", true);

?>

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

Descrierea

bool Imagick::setImageDepth ( int $depth )

Sets the image depth.

Parametri

depth

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setImageDispose ( int $dispose )

Sets the image disposal method.

Parametri

dispose

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setImageExtent ( int $columns , int $rows )

Sets the image size (i.e. columns & rows).

Parametri

columns

rows

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setImageFilename ( string $filename )

Sets the filename of a particular image in a sequence.

Parametri

filename

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setImageFormat ( string $format )

Sets the format of a particular image in a sequence.

Parametri

format

String presentation of the image format. Format support depends on the ImageMagick installation.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::setImageGamma ( float $gamma )

Sets the image gamma.

Parametri

gamma

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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 Git)

Imagick::setImageGravity — Sets the image gravity

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.4 sau ulterior.

Parametri

gravity

The gravity property. Refer to the list of gravity constants.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool Imagick::setImageGreenPrimary ( float $x , float $y )

Sets the image chromaticity green primary point.

Parametri

x

y

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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().

Parametri

index

The position to set the iterator to

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setImageInterlaceScheme ( int $interlace_scheme )

Sets the image compression.

Parametri

interlace_scheme

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setImageInterpolateMethod ( int $method )

Sets the image interpolate pixel method.

Parametri

method

The method is one of the Imagick::INTERPOLATE_* constants

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::setImageIterations ( int $iterations )

Sets the number of iterations an animated image is repeated.

Parametri

iterations

The number of iterations the image should loop over. Set to '0' to loop continuously.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Basic Imagick::setImageIterations() usage

<?php

$imagick = new Imagick(realpath("Test.gif"));

$imagick = $imagick->coalesceImages();
$imagick->setImageIterations(1);
$imagick = $imagick->deconstructImages();

$imagick->writeImages('/path/to/save/OnceOnly.gif', true);

?>

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

Descrierea

bool Imagick::setImageMatte ( bool $matte )

Sets the image matte channel. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

matte

True activates the matte channel and false disables it.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::setImageMatteColor ( mixed $matte )

Sets the image matte color.

Parametri

matte

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Istoricul schimbarilor

Versiune | Descriere
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

Descrierea

bool Imagick::setImageOpacity ( float $opacity )

Sets the image to the specified opacity level. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.1 sau ulterior. This method operates on all channels, which means that for example opacity value of 0.5 will set all transparent areas to partially opaque. To add transparency to areas that are not already transparent use Imagick::evaluateImage()

Parametri

opacity

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #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

Descrierea

bool Imagick::setImageOrientation ( int $orientation )

Sets the image orientation.

Parametri

orientation

One of the orientation constants

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::setImageOrientation()

<?php
//Doesn't appear to do anything
function setImageOrientation($imagePath, $orientationType) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->setImageOrientation($orientationType);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::setImagePage ( int $width , int $height , int $x , int $y )

Sets the page geometry of the image.

Parametri

width

height

x

y

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

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.

Parametri

name

profile

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setImageProperty ( string $name , string $value )

Sets a named property to the image. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.2 sau ulterior.

Parametri

name

value

Exemple

Example #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');
?>

A se vedea ?i

  • Imagick::getImageProperty() - Returns the named image property

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::setImageRedPrimary ( float $x , float $y )

Sets the image chromaticity red primary point.

Parametri

x

y

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setImageRenderingIntent ( int $rendering_intent )

Sets the image rendering intent.

Parametri

rendering_intent

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setImageResolution ( float $x_resolution , float $y_resolution )

Sets the image resolution.

Parametri

x_resolution

y_resolution

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::setImageResolution()

<?php
function setImageResolution($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->setImageResolution(50, 50);

    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::setImageScene ( int $scene )

Sets the image scene.

Parametri

scene

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setImageTicksPerSecond ( int $ticks_per_second )

Adjust the amount of time that a frame of an animated image is displayed for.

Nota:

For animated GIFs, this function does not change the number of 'image ticks' per second, which is always defined as 100. Instead it adjusts the amount of time that the frame is displayed for to simulate the change in 'ticks per second'.

For example, for an animated GIF where each frame is displayed for 20 ticks (1/5 of a second) when this method is called on each frame of that image with an argument of 50 the frames are adjusted to be displayed for 40 ticks (2/5 of a second) and the animation will play at half the original speed.

Parametri

ticks_per_second

The duration for which an image should be displayed expressed in ticks per second.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Modify animated Gif with Imagick::setImageTicksPerSecond()

<?php

// Modify an animated gif so the first half of the gif is played at half the
// speed it currently is, and the second half to be played at double the speed
// it currently is

$imagick = new Imagick(realpath("Test.gif"));
$imagick = $imagick->coalesceImages();

$totalFrames = $imagick->getNumberImages();

$frameCount = 0;

foreach ($imagick as $frame) {
    $imagick->setImageTicksPerSecond(50);

    if ($frameCount < ($totalFrames / 2)) {
        // Modify the frame to be displayed for twice as long as it currently is
        $imagick->setImageTicksPerSecond(50);
    } else {
        // Modify the frame to be displayed for half as long as it currently is
        $imagick->setImageTicksPerSecond(200);
    }

    $frameCount++;
}

$imagick = $imagick->deconstructImages();

$imagick->writeImages("/path/to/save/output.gif", true);

?>

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

Descrierea

bool Imagick::setImageType ( int $image_type )

Sets the image type.

Parametri

image_type

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::setImageUnits ( int $units )

Sets the image units of resolution.

Parametri

units

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::setImageVirtualPixelMethod ( int $method )

Sets the image virtual pixel method.

Parametri

method

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::setImageWhitePoint ( float $x , float $y )

Sets the image chromaticity white point.

Parametri

x

y

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

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

Descrierea

bool Imagick::setInterlaceScheme ( int $interlace_scheme )

Sets the image compression.

Parametri

interlace_scheme

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::setIteratorIndex ( int $index )

Set the iterator to the position in the image list specified with the index parameter. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

index

The position to set the iterator to

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #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();
?>

A se vedea ?i

  • 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

Descrierea

bool Imagick::setLastIterator ( void )

Sets the Imagick iterator to the last image.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::setOption ( string $key , string $value )

Associates one or more options with the wand.

Parametri

key

value

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Attempt to reach '$extent' sizeImagick::setOption()

<?php
    function renderJPG($extent) {
        $imagePath = $this->control->getImagePath();
        $imagick = new \Imagick(realpath($imagePath));
        $imagick->setImageFormat('jpg');
        $imagick->setOption('jpeg:extent', $extent);
        header("Content-Type: image/jpg");
        echo $imagick->getImageBlob();
    }

?>

Example #2 Imagick::setOption()

<?php
    function renderPNG($imagePath, $format) {

        $imagick = new \Imagick(realpath($imagePath));
        $imagick->setImageFormat('png');
        $imagick->setOption('png:format', $format);
        header("Content-Type: image/png");
        echo $imagick->getImageBlob();
    }

    //Save as 64bit PNG.
    renderPNG($imagePath, 'png64');

?>

Example #3 Imagick::setOption()

<?php
    function renderCustomBitDepthPNG() {
        $imagePath = $this->control->getImagePath();
        $imagick = new \Imagick(realpath($imagePath));
        $imagick->setImageFormat('png');

        $imagick->setOption('png:bit-depth', '16');
        $imagick->setOption('png:color-type', 6);
        header("Content-Type: image/png");
        $crash = true;
        if ($crash) {
            echo $imagick->getImageBlob();
        }
        else {
            $tempFilename = tempnam('./', 'imagick');
            $imagick->writeimage(realpath($tempFilename));
            echo file_get_contents($tempFilename);
        }
    }

?>

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

Descrierea

bool Imagick::setPage ( int $width , int $height , int $x , int $y )

Sets the page geometry of the Imagick object.

Parametri

width

height

x

y

Valorile întoarse

Întoarce TRUE în caz de succes.

Imagick::setOption
Imagick::setPointSize
Imagick


Sets point size

Imagick::setPage
Imagick::setProgressMonitor
Imagick
PHP Manual

Imagick::setPointSize

(PECL imagick 2.1.0)

Imagick::setPointSize — Sets point size

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.7 sau ulterior.

Parametri

point_size

Point size

Valorile întoarse

Întoarce TRUE în caz de succes.

A se vedea ?i

  • Imagick::getPointSize() - Gets point size

Exemple

Example #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::setProgressMonitor
Imagick


Description

Imagick::setPointSize
Imagick::setRegistry
Imagick
PHP Manual

Imagick::setProgressMonitor

(No version information available, might only be in Git)

Imagick::setProgressMonitor — Description

Descrierea

public void Imagick::setProgressMonitor ( callable $callback )

Set a callback that will be called during the processing of the Imagick image.

Parametri

callback

The progress function to call. It should return true if image processing should continue, or false if it should be cancelled. The offset parameter indicates the progress and the span parameter indicates the total amount of work needed to be done.

bool callback ( mixed $offset , mixed $span )
Precautie

The values passed to the callback function are not consistent. In particular the span parameter can increase during image processing. Because of this calculating the percentage complete of an image operation is not trivial.

Valorile întoarse

Exemple

Example #1 Imagick::setProgressMonitor()

<?php
        $abortReason = null;

        try {
            $imagick = new \Imagick(realpath($this->control->getImagePath()));
            $startTime = time();

            $callback = function ($offset, $span)  use ($startTime, &$abortReason) {
                if (((100 * $offset) / $span)  > 20) {
                    $abortReason = "Processing reached 20%";
                    return false;
                }

                $nowTime = time();

                if ($nowTime - $startTime > 5) {
                    $abortReason = "Image processing took more than 5 seconds";
                    return false;
                }
                if (($offset % 5) == 0) {
                    echo "Progress: $offset / $span <br/>";
                }
                return true;
            };

            $imagick->setProgressMonitor($callback);

            $imagick->waveImage(2, 15);

            echo "Data len is: ".strlen($imagick->getImageBlob());
        }
        catch(\ImagickException $e) {
            if ($abortReason != null) {
                echo "Image processing was aborted: ".$abortReason."<br/>";
            }
            else {
                echo "ImagickException caught: ".$e->getMessage()." Exception type is ".get_class($e);
            }
        }

?>

Imagick::setPointSize
Imagick::setRegistry
Imagick


Description

Imagick::setProgressMonitor
Imagick::setResolution
Imagick
PHP Manual

Imagick::setRegistry

(No version information available, might only be in Git)

Imagick::setRegistry — Description

Descrierea

public static void Imagick::setRegistry ( string $key , string $value )

Sets the ImageMagick registry entry named key to value. This is most useful for setting "temporary-path" which controls where ImageMagick creates temporary images e.g. while processing PDFs.

Parametri

key

value

Valorile întoarse

Imagick::setProgressMonitor
Imagick::setResolution
Imagick


Sets the image resolution

Imagick::setRegistry
Imagick::setResourceLimit
Imagick
PHP Manual

Imagick::setResolution

(PECL imagick 2.0.0)

Imagick::setResolution — Sets the image resolution

Descrierea

bool Imagick::setResolution ( float $x_resolution , float $y_resolution )

Sets the image resolution.

Parametri

x_resolution

The horizontal resolution.

y_resolution

The vertical resolution.

Valorile întoarse

Întoarce TRUE în caz de succes.

Note

Imagick::setResolution() must be called before loading or creating an image.

A se vedea ?i

  • Imagick::setImageResolution() - Sets the image resolution
  • Imagick::getImageResolution() - Gets the image X and Y resolution
Imagick::setRegistry
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

Descrierea

bool Imagick::setResourceLimit ( int $type , int $limit )

This method is used to modify the resource limits of the underlying ImageMagick library.

Parametri

type

Refer to the list of resourcetype constants.

limit

The resource limit. The unit depends on the type of the resource being limited.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::setSamplingFactors ( array $factors )

Sets the image sampling factors.

Parametri

factors

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::setSamplingFactors()

<?php
function setSamplingFactors($imagePath) {

    $imagePath = "../imagick/images/FineDetail.png";
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->setImageFormat('jpg');
    $imagick->setSamplingFactors(array('2x2', '1x1', '1x1'));

    $compressed = $imagick->getImageBlob();

    $reopen = new \Imagick();
    $reopen->readImageBlob($compressed);

    $reopen->resizeImage(
        $reopen->getImageWidth() * 4,
        $reopen->getImageHeight() * 4,
        \Imagick::FILTER_POINT,
        1
    );

    header("Content-Type: image/jpg");
    echo $reopen->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

columns

rows

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

columns

The width in pixels.

rows

The height in pixels.

offset

The image offset.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::setType ( int $image_type )

Sets the image type attribute.

Parametri

image_type

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

gray

A value other than zero shades the intensity of each pixel.

azimuth

Defines the light source direction.

elevation

Defines the light source direction.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Throws ImagickException on failure.

Exemple

Example #1 Imagick::shadeImage()

<?php
function shadeImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->shadeImage(true, 45, 20);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::shadowImage ( float $opacity , float $sigma , int $x , int $y )

Simulates an image shadow.

Parametri

opacity

sigma

x

y

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::shadowImage()

<?php
function shadowImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->shadowImage(0.4, 10, 50, 5);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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 Imagick::sharpenImage() selects a suitable radius for you.

Parametri

radius

sigma

channel

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::sharpenImage()

<?php
function sharpenImage($imagePath, $radius, $sigma, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->sharpenimage($radius, $sigma, $channel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

columns

rows

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::shaveImage()

<?php
function shaveImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->shaveImage(100, 50);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce TRUE în caz de succes.

Istoricul schimbarilor

Versiune | Descriere
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Exemple

Example #1 Imagick::shearImage()

<?php
function shearImage($imagePath, $color, $shearX, $shearY) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->shearimage($color, $shearX, $shearY);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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.

See also » ImageMagick v6 Examples - Image Transformations — Sigmoidal Non-linearity Contrast

Parametri

sharpen

If true increase the contrast, if false decrease the contrast.

alpha

The amount of contrast to apply. 1 is very little, 5 is a significant amount, 20 is extreme.

beta

Where the midpoint of the gradient will be. This value should be in the range 0 to 1 - mutliplied by the quantum value for ImageMagick.

channel

Which color channels the contrast will be applied to.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Create a gradient image using Imagick::sigmoidalContrastImage() suitable for blending two images together smoothly, with the blending defined by $contrast and $the midpoint

<?php

function generateBlendImage($width, $height, $contrast = 10, $midpoint = 0.5) {
    $imagick = new Imagick();
    $imagick->newPseudoImage($width, $height, 'gradient:black-white');
    $quanta = $imagick->getQuantumRange();
    $imagick->sigmoidalContrastImage(true, $contrast, $midpoint * $quanta["quantumRangeLong"]);

    return $imagick;
}

?>

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::shearImage
Imagick::sketchImage
Imagick


Simulates a pencil sketch

Imagick::sigmoidalContrastImage
Imagick::smushImages
Imagick
PHP Manual

Imagick::sketchImage

(PECL imagick 2.0.0)

Imagick::sketchImage — Simulates a pencil sketch

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::sketchImage()

<?php
function sketchImage($imagePath, $radius, $sigma, $angle) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->sketchimage($radius, $sigma, $angle);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::sigmoidalContrastImage
Imagick::smushImages
Imagick


Description

Imagick::sketchImage
Imagick::solarizeImage
Imagick
PHP Manual

Imagick::smushImages

(No version information available, might only be in Git)

Imagick::smushImages — Description

Descrierea

public Imagick Imagick::smushImages ( string $stack , string $offset )

Takes all images from the current image pointer to the end of the image list and smushs them to each other top-to-bottom if the stack parameter is true, otherwise left-to-right.

Parametri

stack

offset

Valorile întoarse

The new smushed image.

Exemple

Example #1 Imagick::smushImages()

<?php
function smushImages($imagePath, $imagePath2) {

    $imagick = new \Imagick(realpath($imagePath));
    $imagick2 = new \Imagick(realpath($imagePath2));

    $imagick->addimage($imagick2);
    $smushed = $imagick->smushImages(false, 50);
    $smushed->setImageFormat('jpg');
    header("Content-Type: image/jpg");
    echo $smushed->getImageBlob();
}

?>

Imagick::sketchImage
Imagick::solarizeImage
Imagick


Applies a solarizing effect to the image

Imagick::smushImages
Imagick::sparseColorImage
Imagick
PHP Manual

Imagick::solarizeImage

(PECL imagick 2.0.0)

Imagick::solarizeImage — Applies a solarizing effect to the image

Descrierea

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.

Parametri

threshold

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::solarizeImage()

<?php
function solarizeImage($imagePath, $solarizeThreshold) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->solarizeImage($solarizeThreshold * \Imagick::getQuantum());
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::smushImages
Imagick::sparseColorImage
Imagick


Interpolates colors

Imagick::solarizeImage
Imagick::spliceImage
Imagick
PHP Manual

Imagick::sparseColorImage

(No version information available, might only be in Git)

Imagick::sparseColorImage — Interpolates colors

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.4.5 sau ulterior.

Parametri

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

Înscrie?i orice constanta a canalului care este valida pentru modul de canal. Pentru a aplica opera?ia asupra mai multor canale, combina?i constante de canal utilizând operatori binari. Valoarea implicita este Imagick::CHANNEL_DEFAULT. Iata lista de referin?a a constantelor de canal

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage()

<?php
    function renderImageBarycentric2() {
        $points = [
            [0.30, 0.10, 'red'],
            [0.10, 0.80, 'blue'],
            [0.70, 0.60, 'lime'],
            [0.80, 0.20, 'yellow'],
        ];
        $imagick = createGradientImage(
            400, 400,
            $points,
            \Imagick::SPARSECOLORMETHOD_BARYCENTRIC
        );
        header("Content-Type: image/png");
        echo $imagick->getImageBlob();
    }

?>

Example #2 SPARSECOLORMETHOD_BILINEAR Imagick::sparseColorImage()

<?php
    function renderImageBilinear() {
        $points = [[0.30, 0.10, 'red'], [0.10, 0.80, 'blue'], [0.70, 0.60, 'lime'], [0.80, 0.20, 'yellow'],];
        $imagick = createGradientImage(500, 500, $points, \Imagick::SPARSECOLORMETHOD_BILINEAR);
        header("Content-Type: image/png");
        echo $imagick->getImageBlob();
    }

?>

Example #3 SPARSECOLORMETHOD_SPEPARDS Imagick::sparseColorImage()

<?php
    function renderImageShepards() {
        $points = [
            [0.30, 0.10, 'red'],
            [0.10, 0.80, 'blue'],
            [0.70, 0.60, 'lime'],
            [0.80, 0.20, 'yellow'],
        ];
        $imagick = createGradientImage(600, 600, $points, \Imagick::SPARSECOLORMETHOD_SPEPARDS);
        header("Content-Type: image/png");
        echo $imagick->getImageBlob();
    }

?>

Example #4 SPARSECOLORMETHOD_VORONOI Imagick::sparseColorImage()

<?php
    function renderImageVoronoi() {
        $points = [
            [0.30, 0.10, 'red'],
            [0.10, 0.80, 'blue'],
            [0.70, 0.60, 'lime'],
            [0.80, 0.20, 'yellow'],
        ];
        $imagick = createGradientImage(500, 500, $points, \Imagick::SPARSECOLORMETHOD_VORONOI);
        header("Content-Type: image/png");
        echo $imagick->getImageBlob();
    }

?>

Example #5 SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage()

<?php
    function renderImageBarycentric() {
        $points = [
            [0, 0, 'skyblue'],
            [-1, 1, 'skyblue'],
            [1, 1, 'black'],
        ];
        $imagick = createGradientImage(600, 200, $points, \Imagick::SPARSECOLORMETHOD_BARYCENTRIC);
        header("Content-Type: image/png");
        echo $imagick->getImageBlob();
    }

?>

Example #6 createGradientImage is used by other examples. Imagick::sparseColorImage()

<?php
function createGradientImage($width, $height, $colorPoints, $sparseMethod, $absolute = false) {

    $imagick = new \Imagick();
    $imagick->newImage($width, $height, "white");
    $imagick->setImageFormat("png");

    $barycentricPoints = array();

    foreach ($colorPoints as $colorPoint) {

        if ($absolute == true) {
            $barycentricPoints[] = $colorPoint[0];
            $barycentricPoints[] = $colorPoint[1];
        }
        else {
            $barycentricPoints[] = $colorPoint[0] * $width;
            $barycentricPoints[] = $colorPoint[1] * $height;
        }

        if (is_string($colorPoint[2])) {
            $imagickPixel = new \ImagickPixel($colorPoint[2]);
        }
        else if ($colorPoint[2] instanceof \ImagickPixel) {
            $imagickPixel = $colorPoint[2];
        }
        else{
            $errorMessage = sprintf(
                "Value %s is neither a string nor an ImagickPixel class. Cannot use as a color.",
                $colorPoint[2]
            );

            throw new \InvalidArgumentException(
                $errorMessage
            );
        }

        $red = $imagickPixel->getColorValue(\Imagick::COLOR_RED);
        $green = $imagickPixel->getColorValue(\Imagick::COLOR_GREEN);
        $blue = $imagickPixel->getColorValue(\Imagick::COLOR_BLUE);
        $alpha = $imagickPixel->getColorValue(\Imagick::COLOR_ALPHA);

        $barycentricPoints[] = $red;
        $barycentricPoints[] = $green;
        $barycentricPoints[] = $blue;
        $barycentricPoints[] = $alpha;
    }

    $imagick->sparseColorImage($sparseMethod, $barycentricPoints);

    return $imagick;
}

?>

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

Descrierea

bool Imagick::spliceImage ( int $width , int $height , int $x , int $y )

Splices a solid color into the image.

Parametri

width

height

x

y

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::spliceImage()

<?php
function spliceImage($imagePath, $startX, $startY, $width, $height) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->spliceImage($width, $height, $startX, $startY);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::sparseColorImage
Imagick::spreadImage
Imagick


Randomly displaces each pixel in a block

Imagick::spliceImage
Imagick::statisticImage
Imagick
PHP Manual

Imagick::spreadImage

(PECL imagick 2.0.0)

Imagick::spreadImage — Randomly displaces each pixel in a block

Descrierea

bool Imagick::spreadImage ( float $radius )

Special effects method that randomly displaces each pixel in a block defined by the radius parameter.

Parametri

radius

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::spreadImage()

<?php
function spreadImage($imagePath, $radius) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->spreadImage($radius);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::spliceImage
Imagick::statisticImage
Imagick


Description

Imagick::spreadImage
Imagick::steganoImage
Imagick
PHP Manual

Imagick::statisticImage

(No version information available, might only be in Git)

Imagick::statisticImage — Description

Descrierea

public void Imagick::statisticImage ( int $type , int $width , int $height [, string $CHANNEL = Imagick::CHANNEL_DEFAULT ] )

Replace each pixel with corresponding statistic from the neighborhood of the specified width and height.

Parametri

type

width

height

CHANNEL

Valorile întoarse

Exemple

Example #1 Imagick::statisticImage()

<?php
function statisticImage($imagePath, $statisticType, $width, $height, $channel) {
    $imagick = new \Imagick(realpath($imagePath));

    $imagick->statisticImage(
        $statisticType,
        $width,
        $height,
        $channel
    );

    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

statisticImage($imagePath, \Imagick::STATISTIC_MEDIAN, 5, 5, \Imagick::CHANNEL_DEFAULT);

?>

Imagick::spreadImage
Imagick::steganoImage
Imagick


Hides a digital watermark within the image

Imagick::statisticImage
Imagick::stereoImage
Imagick
PHP Manual

Imagick::steganoImage

(PECL imagick 2.0.0)

Imagick::steganoImage — Hides a digital watermark within the image

Descrierea

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.

Parametri

watermark_wand

offset

Valorile întoarse

Întoarce TRUE în caz de succes.

Imagick::statisticImage
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

Descrierea

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.

Parametri

offset_wand

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::steganoImage
Imagick::stripImage
Imagick


Strips an image of all profiles and comments

Imagick::stereoImage
Imagick::subImageMatch
Imagick
PHP Manual

Imagick::stripImage

(PECL imagick 2.0.0)

Imagick::stripImage — Strips an image of all profiles and comments

Descrierea

bool Imagick::stripImage ( void )

Strips an image of all profiles and comments.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Imagick::stereoImage
Imagick::subImageMatch
Imagick


Description

Imagick::stripImage
Imagick::swirlImage
Imagick
PHP Manual

Imagick::subImageMatch

(No version information available, might only be in Git)

Imagick::subImageMatch — Description

Descrierea

public Imagick Imagick::subImageMatch ( Imagick $Imagick [, array &$offset [, float &$similarity ]] )

Searches for a subimage in the current image and returns a similarity image such that an exact match location is completely white and if none of the pixels match, black, otherwise some gray level in-between. You can also pass in the optional parameters bestMatch and similarity. After calling the function similarity will be set to the 'score' of the similarity between the subimage and the matching position in the larger image, bestMatch will contain an associative array with elements x, y, width, height that describe the matching region.

Parametri

Imagick

offset

similarity

A new image that displays the amount of similarity at each pixel.

Valorile întoarse

Exemple

Example #1 Imagick::subImageMatch()

<?php
function subImageMatch($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick2 = clone $imagick;
    $imagick2->cropimage(40, 40, 250, 110);
    $imagick2->vignetteimage(0, 1, 3, 3);

    $similarity = null;
    $bestMatch = null;
    $comparison = $imagick->subImageMatch($imagick2, $bestMatch, $similarity);

    $comparison->setImageFormat('png');
    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

Imagick::stripImage
Imagick::swirlImage
Imagick


Swirls the pixels about the center of the image

Imagick::subImageMatch
Imagick::textureImage
Imagick
PHP Manual

Imagick::swirlImage

(PECL imagick 2.0.0)

Imagick::swirlImage — Swirls the pixels about the center of the image

Descrierea

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.

Parametri

degrees

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::swirlImage()

<?php
function swirlImage($imagePath, $swirl) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->swirlImage($swirl);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::subImageMatch
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

Descrierea

Imagick Imagick::textureImage ( Imagick $texture_wand )

Repeatedly tiles the texture image across and down the image canvas.

Parametri

texture_wand

Imagick object to use as texture image

Valorile întoarse

Returns a new Imagick object that has the repeated texture applied.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::textureImage()

<?php
function textureImage($imagePath) {
    $image = new \Imagick();
    $image->newImage(640, 480, new \ImagickPixel('pink'));
    $image->setImageFormat("jpg");
    $texture = new \Imagick(realpath($imagePath));
    $texture->scaleimage($image->getimagewidth() / 4, $image->getimageheight() / 4);
    $image = $image->textureImage($texture);
    header("Content-Type: image/jpg");
    echo $image;
}

?>

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

Descrierea

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.

Parametri

threshold

channel

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::thresholdImage()

<?php
function thresholdimage($imagePath, $threshold, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->thresholdimage($threshold * \Imagick::getQuantum(), $channel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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 they match or are smaller than the parameter given for the side.

Nota: Comportamentul parametrului bestfit s-a schimbat în Imagick 3.0.0. Anterior acestei versiuni în cazul dimensiunilor 400x400, o imagine cu dimensiunile 200x150 ar fi ramas neschimbata. În Imagick 3.0.0 ?i versiunile ulterioare imaginea va fi marita la dimensiunile 400x300 deoarece aceasta este "cea mai buna potrivire" pentru dimensiunile date. Daca parametrul bestfit este utilizat, trebuie furnizate atât la?imea, cât ?i înal?imea.

Parametri

columns

Image width

rows

Image height

bestfit

Whether to force maximum values

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::thumbnailImage()

<?php
function thumbnailImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->setbackgroundcolor('rgb(64, 64, 64)');
    $imagick->thumbnailImage(100, 100, true, true);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::thresholdImage
Imagick::tintImage
Imagick


Applies a color vector to each pixel in the image

Imagick::thumbnailImage
Imagick::__toString
Imagick
PHP Manual

Imagick::tintImage

(PECL imagick 2.0.0)

Imagick::tintImage — Applies a color vector to each pixel in the image

Descrierea

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)))).

Parametri

tint

opacity

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #1 Imagick::tintImage()

<?php
function tintImage($r, $g, $b, $a) {
    $a = $a / 100;

    $imagick = new \Imagick();
    $imagick->newPseudoImage(400, 400, 'gradient:black-white');

    $tint = new \ImagickPixel("rgb($r, $g, $b)");
    $opacity = new \ImagickPixel("rgb(128, 128, 128, $a)");
    $imagick->tintImage($tint, $opacity);
    $imagick->setImageFormat('png');
    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

Imagick::thumbnailImage
Imagick::__toString
Imagick


Returns the image as a string.

Imagick::tintImage
Imagick::transformImage
Imagick
PHP Manual

Imagick::__toString

(No version information available, might only be in Git)

Imagick::__toString — Returns the image as a string.

Descrierea

string Imagick::__toString ( void )

Returns the current image as string. This will only return a single image; it should not be used for Imagick objects that contain multiple images e.g. an animated GIF or PDF with multiple pages.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the string content on success or an empty string on failure.

A se vedea ?i

  • Imagick::getImageBlob() - Returns the image sequence as a blob
  • Imagick::getImagesBlob() - Returns all image sequences as a blob
Imagick::tintImage
Imagick::transformImage
Imagick


Convenience method for setting crop size and the image geometry

Imagick::__toString
Imagick::transformImageColorspace
Imagick
PHP Manual

Imagick::transformImage

(PECL imagick 2.0.0)

Imagick::transformImage — Convenience method for setting crop size and the image geometry

Descrierea

Imagick Imagick::transformImage ( string $crop , string $geometry )

A convenience method for setting crop size and the image geometry from strings. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

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.

Valorile întoarse

Returns an Imagick object containing the transformed image.

Exemple

Example #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');
?>

A se vedea ?i

  • Imagick::cropImage() - Extracts a region of the image
  • Imagick::resizeImage() - Scales an image
  • Imagick::thumbnailImage() - Changes the size of an image

Imagick::__toString
Imagick::transformImageColorspace
Imagick


Transforms an image to a new colorspace.

Imagick::transformImage
Imagick::transparentPaintImage
Imagick
PHP Manual

Imagick::transformImageColorspace

(No version information available, might only be in Git)

Imagick::transformImageColorspace — Transforms an image to a new colorspace.

Descrierea

bool Imagick::transformImageColorspace ( int $colorspace )

Transforms an image to a new colorspace.

Parametri

colorspace

The colorspace the image should be transformed to, one of the COLORSPACE constants e.g. Imagick::COLORSPACE_CMYK.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Imagick::transformImageColorspace() example

Transforms an image to a new colorspace, and then extracts a single channel so that the individual channel values can be viewed.

<?php
function transformImageColorspace($imagePath, $colorSpace, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->transformimagecolorspace($colorSpace);
    //channel should be one of the channel constants e.g. \Imagick::CHANNEL_BLUE
    $imagick->separateImageChannel($channel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}
?>

A se vedea ?i

  • Imagick::setColorSpace() - Set colorspace

Exemple

Example #2 Imagick::transformImageColorspace()

<?php
function transformImageColorspace($imagePath, $colorSpace, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->transformimagecolorspace($colorSpace);
    $imagick->separateImageChannel($channel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

Imagick::transformImage
Imagick::transparentPaintImage
Imagick


Paints pixels transparent

Imagick::transformImageColorspace
Imagick::transposeImage
Imagick
PHP Manual

Imagick::transparentPaintImage

(No version information available, might only be in Git)

Imagick::transparentPaintImage — Paints pixels transparent

Descrierea

bool Imagick::transparentPaintImage ( mixed $target , float $alpha , float $fuzz , bool $invert )

Paints pixels matching the target color transparent. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.8 sau ulterior.

Parametri

target

The target color to paint

alpha

Nivelul transparen?ei: 1.0 este deplin opac iar 0.0 este deplin transparent.

fuzz

Marimea difuziei. Spre exemplu daca stabili?i difuzia la 10, atunci culoarea ro?ie de intensita?ile 100 ?i 102 respectiv sunt interpretate ca aceea?i culoare.

invert

If TRUE paints any pixel that does not match the target color.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::transparentPaintImage()

<?php
function transparentPaintImage($color, $alpha, $fuzz) {
    $imagick = new \Imagick(realpath("images/BlueScreen.jpg"));

    //Need to be in a format that supports transparency
    $imagick->setimageformat('png');

    $imagick->transparentPaintImage(
        $color, $alpha, $fuzz * \Imagick::getQuantum(), false
    );

    //Not required, but helps tidy up left over pixels
    $imagick->despeckleimage();

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

Imagick::transformImageColorspace
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

Descrierea

bool Imagick::transposeImage ( void )

Creates a vertical mirror image by reflecting the pixels around the central x-axis while rotating them 90-degrees. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Valorile întoarse

Întoarce TRUE în caz de succes.

A se vedea ?i

  • Imagick::transverseImage() - Creates a horizontal mirror image

Exemple

Example #1 Imagick::transposeImage()

<?php
function transposeImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->transposeImage();
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::transverseImage ( void )

Creates a horizontal mirror image by reflecting the pixels around the central y-axis while rotating them 270-degrees. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Valorile întoarse

Întoarce TRUE în caz de succes.

A se vedea ?i

  • Imagick::transposeImage() - Creates a vertical mirror image

Exemple

Example #1 Imagick::transverseImage()

<?php
function transverseImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->transverseImage();
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::trimImage ( float $fuzz )

Remove edges that are the background color from the image. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #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;
?>

A se vedea ?i

  • 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

Descrierea

bool Imagick::uniqueImageColors ( void )

Discards all but one of any pixel color. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Imagick::uniqueImageColors()

<?php
function uniqueImageColors($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    //Reduce the image to 256 colours nicely.
    $imagick->quantizeImage(256, \Imagick::COLORSPACE_YIQ, 0, false, false);
    $imagick->uniqueImageColors();
    $imagick->scaleimage($imagick->getImageWidth(), $imagick->getImageHeight() * 20);
    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

radius

sigma

amount

threshold

channel

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

Exemple

Example #1 Imagick::unsharpMaskImage()

<?php
function unsharpMaskImage($imagePath, $radius, $sigma, $amount, $unsharpThreshold) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->unsharpMaskImage($radius, $sigma, $amount, $unsharpThreshold);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::valid ( void )

Checks if the current item is valid.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::vignetteImage ( float $blackPoint , float $whitePoint , int $x , int $y )

Softens the edges of the image in vignette style. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

blackPoint

The black point.

whitePoint

The white point

x

X offset of the ellipse

y

Y offset of the ellipse

Valorile întoarse

Întoarce TRUE în caz de succes.

A se vedea ?i

  • Imagick::waveImage() - Applies wave filter to the image
  • Imagick::swirlImage() - Swirls the pixels about the center of the image

Exemple

Example #1 Imagick::vignetteImage()

<?php
function vignetteImage($imagePath, $blackPoint, $whitePoint, $x, $y) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->vignetteImage($blackPoint, $whitePoint, $x, $y);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::waveImage ( float $amplitude , float $length )

Applies a wave filter to the image. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.2.9 sau ulterior.

Parametri

amplitude

The amplitude of the wave.

length

The length of the wave.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excep?ii

Emite ImagickException în caz de eroare.

A se vedea ?i

  • 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

Exemple

Example #1 WaveImage can be quite slow Imagick::waveImage()

<?php
function waveImage($imagePath, $amplitude, $length) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->waveImage($amplitude, $length);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

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.

Parametri

threshold

Valorile întoarse

Întoarce TRUE în caz de succes.

Istoricul schimbarilor

Versiune | Descriere
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

Exemple

Example #1 Imagick::whiteThresholdImage()

<?php
function whiteThresholdImage($imagePath, $color) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->whiteThresholdImage($color);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool Imagick::writeImage ([ string $filename = NULL ] )

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().

Parametri

filename

Filename where to write the image. The extension of the filename defines the type of the file. Format can be forced regardless of file extension using format: prefix, for example "jpg:test.png".

Valorile întoarse

Întoarce TRUE în caz de succes.

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 Git)

Imagick::writeImageFile — Writes an image to a filehandle

Descrierea

bool Imagick::writeImageFile ( resource $filehandle )

Writes the image sequence to an open filehandle. The handle must be opened with for example fopen. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 sau ulterior.

Parametri

filehandle

Filehandle where to write the image

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool Imagick::writeImages ( string $filename , bool $adjoin )

Writes an image or image sequence.

Parametri

filename

adjoin

Valorile întoarse

Întoarce TRUE în caz de succes.

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 Git)

Imagick::writeImagesFile — Writes frames to a filehandle

Descrierea

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. Aceasta metoda este disponibila daca Imagick a fost compilat cu ImageMagick de versiunea 6.3.6 sau ulterior.

Parametri

filehandle

Filehandle where to write the images

Valorile întoarse

Întoarce TRUE în caz de succes.

Imagick::writeImages
ImagickDraw
Imagick


The ImagickDraw class

(PECL imagick 2.0.0)

Sinopsisul clasei

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 )
public int getFontStretch ( 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 )
public float getTextInterlineSpacing ( void )
public float getTextInterwordSpacing ( void )
public float getTextKerning ( 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 )
public void resetVectorGraphics ( 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 )
public void setResolution ( string $x_resolution , string $y_resolution )
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 )
public void setTextInterlineSpacing ( float $spacing )
public void setTextInterwordSpacing ( float $spacing )
public void setTextKerning ( float $kerning )
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 )
}

Cuprins

  • 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::getFontStretch — Description
  • 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::getTextInterlineSpacing — Description
  • ImagickDraw::getTextInterwordSpacing — Description
  • ImagickDraw::getTextKerning — Description
  • 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::resetVectorGraphics — Description
  • 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::setResolution — Description
  • 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 the text code set
  • ImagickDraw::setTextInterlineSpacing — Description
  • ImagickDraw::setTextInterwordSpacing — Description
  • ImagickDraw::setTextKerning — Description
  • 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

Descrierea

bool ImagickDraw::affine ( array $affine )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Adjusts the current affine transformation matrix with the specified affine transformation matrix.

Parametri

affine

Affine matrix parameters

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::affine()

<?php
function affine($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeWidth(1);
    $draw->setStrokeOpacity(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(2);

    $PI = 3.141592653589794;
    $angle = 60 * $PI / 360;

    //Scale the drawing co-ordinates.
    $affineScale = array("sx" => 1.75, "sy" => 1.75, "rx" => 0, "ry" => 0, "tx" => 0, "ty" => 0);

    //Shear the drawing co-ordinates.
    $affineShear = array("sx" => 1, "sy" => 1, "rx" => sin($angle), "ry" => -sin($angle), "tx" => 0, "ty" => 0);

    //Rotate the drawing co-ordinates. The shear affine matrix
    //produces incorrectly scaled drawings.
    $affineRotate = array("sx" => cos($angle), "sy" => cos($angle), "rx" => sin($angle), "ry" => -sin($angle), "tx" => 0, "ty" => 0,);

    //Translate (offset) the drawing
    $affineTranslate = array("sx" => 1, "sy" => 1, "rx" => 0, "ry" => 0, "tx" => 30, "ty" => 30);

    //The identiy affine matrix
    $affineIdentity = array("sx" => 1, "sy" => 1, "rx" => 0, "ry" => 0, "tx" => 0, "ty" => 0);

    $examples = [$affineScale, $affineShear, $affineRotate, $affineTranslate, $affineIdentity,];

    $count = 0;

    foreach ($examples as $example) {
        $draw->push();
        $draw->translate(($count % 2) * 250, intval($count / 2) * 250);
        $draw->translate(100, 100);
        $draw->affine($example);
        $draw->rectangle(-50, -50, 50, 50);
        $draw->pop();
        $count++;
    }

    //Create an image object which the draw commands can be rendered into
    $image = new \Imagick();
    $image->newImage(500, 750, $backgroundColor);
    $image->setImageFormat("png");

    //Render the draw commands in the ImagickDraw object
    //into the image.
    $image->drawImage($draw);

    //Send the image to the browser
    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::annotation ( float $x , float $y , string $text )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws text on the image.

Parametri

x

The x coordinate where text is drawn

y

The y coordinate where text is drawn

text

The text to draw on the image

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws an arc falling within a specified bounding rectangle on the image.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::arc()

<?php
function arc($strokeColor, $fillColor, $backgroundColor, $startX, $startY, $endX, $endY, $startAngle, $endAngle) {

    //Create a ImagickDraw object to draw into.
    $draw = new \ImagickDraw();
    $draw->setStrokeWidth(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(2);

    $draw->arc($startX, $startY, $endX, $endY, $startAngle, $endAngle);

    //Create an image object which the draw commands can be rendered into
    $image = new \Imagick();
    $image->newImage(IMAGE_WIDTH, IMAGE_HEIGHT, $backgroundColor);
    $image->setImageFormat("png");

    //Render the draw commands in the ImagickDraw object
    //into the image.
    $image->drawImage($draw);

    //Send the image to the browser
    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::bezier ( array $coordinates )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws a bezier curve through a set of points on the image.

Parametri

coordinates

Multidimensional array like array( array( 'x' => 1, 'y' => 2 ), array( 'x' => 3, 'y' => 4 ) )

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::bezier()

<?php
function bezier($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $strokeColor = new \ImagickPixel($strokeColor);
    $fillColor = new \ImagickPixel($fillColor);

    $draw->setStrokeOpacity(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(2);

    $smoothPointsSet = [
        [
            ['x' => 10.0 * 5, 'y' => 10.0 * 5],
            ['x' => 30.0 * 5, 'y' => 90.0 * 5],
            ['x' => 25.0 * 5, 'y' => 10.0 * 5],
            ['x' => 50.0 * 5, 'y' => 50.0 * 5],
        ],
        [
            ['x' => 50.0 * 5, 'y' => 50.0 * 5],
            ['x' => 75.0 * 5, 'y' => 90.0 * 5],
            ['x' => 70.0 * 5, 'y' => 10.0 * 5],
            ['x' => 90.0 * 5, 'y' => 40.0 * 5],
        ],
    ];

    foreach ($smoothPointsSet as $points) {
        $draw->bezier($points);
    }

    $disjointPoints = [
        [
            ['x' => 10 * 5, 'y' => 10 * 5],
            ['x' => 30 * 5, 'y' => 90 * 5],
            ['x' => 25 * 5, 'y' => 10 * 5],
            ['x' => 50 * 5, 'y' => 50 * 5],
        ],
        [
            ['x' => 50 * 5, 'y' => 50 * 5],
            ['x' => 80 * 5, 'y' => 50 * 5],
            ['x' => 70 * 5, 'y' => 10 * 5],
            ['x' => 90 * 5, 'y' => 40 * 5],
         ]
    ];
    $draw->translate(0, 200);

    foreach ($disjointPoints as $points) {
        $draw->bezier($points);
    }

    //Create an image object which the draw commands can be rendered into
    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    //Render the draw commands in the ImagickDraw object
    //into the image.
    $imagick->drawImage($draw);

    //Send the image to the browser
    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::circle ( float $ox , float $oy , float $px , float $py )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws a circle on the image.

Parametri

ox

origin x coordinate

oy

origin y coordinate

px

perimeter x coordinate

py

perimeter y coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::circle()

<?php
function circle($strokeColor, $fillColor, $backgroundColor, $originX, $originY, $endX, $endY) {

    //Create a ImagickDraw object to draw into.
    $draw = new \ImagickDraw();

    $strokeColor = new \ImagickPixel($strokeColor);
    $fillColor = new \ImagickPixel($fillColor);

    $draw->setStrokeOpacity(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(2);
    $draw->setFontSize(72);

    $draw->circle($originX, $originY, $endX, $endY);

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::clear ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Clears the ImagickDraw object of any accumulated commands, and resets the settings it contains to their defaults.

Valorile întoarse

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

Descrierea

ImagickDraw ImagickDraw::clone ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Makes an exact copy of the specified ImagickDraw object.

Valorile întoarse

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

Descrierea

bool ImagickDraw::color ( float $x , float $y , int $paintMethod )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws color on image using the current fill color, starting at specified position, and using specified paint method.

Parametri

x

x coordinate of the paint

y

y coordinate of the paint

paintMethod

one of the PAINT_ constants

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::comment ( string $comment )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Adds a comment to a vector output stream.

Parametri

comment

The comment string to add to vector output stream

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::composite ( int $compose , float $x , float $y , float $width , float $height , Imagick $compositeWand )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Composites an image onto the current image, using the specified composition operator, specified position, and at the specified size.

Parametri

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

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 ImagickDraw::composite()

<?php
function composite($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setFillOpacity(1);
    $draw->setStrokeWidth(2);
    $draw->setFontSize(72);
    $draw->setStrokeOpacity(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setStrokeWidth(2);
    $draw->setFont("../fonts/CANDY.TTF");
    $draw->setFontSize(140);
    $draw->rectangle(0, 0, 1000, 300);
    $draw->setFillColor('white');
    $draw->setfillopacity(1);
    $draw->annotation(50, 180, "Lorem Ipsum!");

    //Create an image object which the draw commands can be rendered into
    $imagick = new \Imagick();
    $imagick->newImage(1000, 302, $backgroundColor);
    $imagick->setImageFormat("png");

    //Render the draw commands in the ImagickDraw object
    //into the image.
    $imagick->drawImage($draw);

    //Send the image to the browser
    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

ImagickDraw::__construct ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

The ImagickDraw constructor

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::destroy ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Frees all resources associated with the ImagickDraw object.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws an ellipse on the image.

Parametri

ox

oy

rx

ry

start

end

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::ellipse()

<?php
function ellipse($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(2);
    $draw->setFontSize(72);

    $draw->ellipse(125, 70, 100, 50, 0, 360);
    $draw->ellipse(350, 70, 100, 50, 0, 315);

    $draw->push();
    $draw->translate(125, 250);
    $draw->rotate(30);
    $draw->ellipse(0, 0, 100, 50, 0, 360);
    $draw->pop();

    $draw->push();
    $draw->translate(350, 250);
    $draw->rotate(30);
    $draw->ellipse(0, 0, 100, 50, 0, 315);
    $draw->pop();

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

string ImagickDraw::getClipPath ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Obtains the current clipping path ID.

Valorile întoarse

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

Descrierea

int ImagickDraw::getClipRule ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the current polygon fill rule to be used by the clipping path.

Valorile întoarse

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

Descrierea

int ImagickDraw::getClipUnits ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the interpretation of clip path units.

Valorile întoarse

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

Descrierea

ImagickPixel ImagickDraw::getFillColor ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the fill color used for drawing filled objects.

Valorile întoarse

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

Descrierea

float ImagickDraw::getFillOpacity ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the opacity used when drawing using the fill color or fill texture. Fully opaque is 1.0.

Valorile întoarse

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

Descrierea

int ImagickDraw::getFillRule ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the fill rule used while drawing polygons.

Valorile întoarse

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

Descrierea

string ImagickDraw::getFont ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns a string specifying the font used when annotating with text.

Valorile întoarse

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

Descrierea

string ImagickDraw::getFontFamily ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the font family to use when annotating with text.

Valorile întoarse

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::getFontStretch
ImagickDraw
PHP Manual

ImagickDraw::getFontSize

(PECL imagick 2.0.0)

ImagickDraw::getFontSize — Returns the font pointsize

Descrierea

float ImagickDraw::getFontSize ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the font pointsize used when annotating with text.

Valorile întoarse

Returns the font size associated with the current ImagickDraw object.

ImagickDraw::getFontFamily
ImagickDraw::getFontStretch
ImagickDraw


Description

ImagickDraw::getFontSize
ImagickDraw::getFontStyle
ImagickDraw
PHP Manual

ImagickDraw::getFontStretch

(No version information available, might only be in Git)

ImagickDraw::getFontStretch — Description

Descrierea

public int ImagickDraw::getFontStretch ( void )

Gets the font stretch to use when annotating with text. Returns a StretchType.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ImagickDraw::getFontSize
ImagickDraw::getFontStyle
ImagickDraw


Returns the font style

ImagickDraw::getFontStretch
ImagickDraw::getFontWeight
ImagickDraw
PHP Manual

ImagickDraw::getFontStyle

(PECL imagick 2.0.0)

ImagickDraw::getFontStyle — Returns the font style

Descrierea

int ImagickDraw::getFontStyle ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the font style used when annotating with text.

Valorile întoarse

Returns the font style constant (STYLE_) associated with the ImagickDraw object or 0 if no style is set.

ImagickDraw::getFontStretch
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

Descrierea

int ImagickDraw::getFontWeight ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the font weight used when annotating with text.

Valorile întoarse

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

Descrierea

int ImagickDraw::getGravity ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the text placement gravity used when annotating with text.

Valorile întoarse

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

Descrierea

bool ImagickDraw::getStrokeAntialias ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Valorile întoarse

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

Descrierea

ImagickPixel ImagickDraw::getStrokeColor ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the color used for stroking object outlines.

Parametri

stroke_color

Valorile întoarse

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

Descrierea

array ImagickDraw::getStrokeDashArray ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns an array representing the pattern of dashes and gaps used to stroke paths.

Valorile întoarse

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

Descrierea

float ImagickDraw::getStrokeDashOffset ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the offset into the dash pattern to start the dash.

Valorile întoarse

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

Descrierea

int ImagickDraw::getStrokeLineCap ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the shape to be used at the end of open subpaths when they are stroked.

Valorile întoarse

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

Descrierea

int ImagickDraw::getStrokeLineJoin ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the shape to be used at the corners of paths (or other vector shapes) when they are stroked.

Valorile întoarse

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

Descrierea

int ImagickDraw::getStrokeMiterLimit ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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'.

Valorile întoarse

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

Descrierea

float ImagickDraw::getStrokeOpacity ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the opacity of stroked object outlines.

Valorile întoarse

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

Descrierea

float ImagickDraw::getStrokeWidth ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the width of the stroke used to draw object outlines.

Valorile întoarse

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

Descrierea

int ImagickDraw::getTextAlignment ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the alignment applied when annotating with text.

Valorile întoarse

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

Descrierea

bool ImagickDraw::getTextAntialias ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the current text antialias setting, which determines whether text is antialiased. Text is antialiased by default.

Valorile întoarse

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

Descrierea

int ImagickDraw::getTextDecoration ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the decoration applied when annotating with text.

Valorile întoarse

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::getTextInterlineSpacing
ImagickDraw
PHP Manual

ImagickDraw::getTextEncoding

(PECL imagick 2.0.0)

ImagickDraw::getTextEncoding — Returns the code set used for text annotations

Descrierea

string ImagickDraw::getTextEncoding ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns a string which specifies the code set used for text annotations.

Valorile întoarse

Returns a string specifying the code set or false if text encoding is not set.

ImagickDraw::getTextDecoration
ImagickDraw::getTextInterlineSpacing
ImagickDraw


Description

ImagickDraw::getTextEncoding
ImagickDraw::getTextInterwordSpacing
ImagickDraw
PHP Manual

ImagickDraw::getTextInterlineSpacing

(No version information available, might only be in Git)

ImagickDraw::getTextInterlineSpacing — Description

Descrierea

public float ImagickDraw::getTextInterlineSpacing ( void )

Gets the text interword spacing.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ImagickDraw::getTextEncoding
ImagickDraw::getTextInterwordSpacing
ImagickDraw


Description

ImagickDraw::getTextInterlineSpacing
ImagickDraw::getTextKerning
ImagickDraw
PHP Manual

ImagickDraw::getTextInterwordSpacing

(No version information available, might only be in Git)

ImagickDraw::getTextInterwordSpacing — Description

Descrierea

public float ImagickDraw::getTextInterwordSpacing ( void )

Gets the text interword spacing.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ImagickDraw::getTextInterlineSpacing
ImagickDraw::getTextKerning
ImagickDraw


Description

ImagickDraw::getTextInterwordSpacing
ImagickDraw::getTextUnderColor
ImagickDraw
PHP Manual

ImagickDraw::getTextKerning

(No version information available, might only be in Git)

ImagickDraw::getTextKerning — Description

Descrierea

public float ImagickDraw::getTextKerning ( void )

Gets the text kerning.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ImagickDraw::getTextInterwordSpacing
ImagickDraw::getTextUnderColor
ImagickDraw


Returns the text under color

ImagickDraw::getTextKerning
ImagickDraw::getVectorGraphics
ImagickDraw
PHP Manual

ImagickDraw::getTextUnderColor

(PECL imagick 2.0.0)

ImagickDraw::getTextUnderColor — Returns the text under color

Descrierea

ImagickPixel ImagickDraw::getTextUnderColor ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the color of a background rectangle to place under text annotations.

Valorile întoarse

Returns an ImagickPixel object describing the color.

ImagickDraw::getTextKerning
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

Descrierea

string ImagickDraw::getVectorGraphics ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns a string which specifies the vector graphics generated by any graphics calls made since the ImagickDraw object was instantiated.

Valorile întoarse

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

Descrierea

bool ImagickDraw::line ( float $sx , float $sy , float $ex , float $ey )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws a line on the image using the current stroke color, stroke opacity, and stroke width.

Parametri

sx

starting x coordinate

sy

starting y coordinate

ex

ending x coordinate

ey

ending y coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::line()

<?php
function line($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(2);
    $draw->setFontSize(72);

    $draw->line(125, 70, 100, 50);
    $draw->line(350, 170, 100, 150);

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::matte ( float $x , float $y , int $paintMethod )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Paints on the image's opacity channel in order to set effected pixels to transparent, to influence the opacity of pixels.

Parametri

x

x coordinate of the matte

y

y coordinate of the matte

paintMethod

PAINT_ constant

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ImagickDraw::matte()

<?php
function matte($strokeColor, $fillColor, $backgroundColor, $paintType) {
    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(2);
    $draw->setFontSize(72);

    $draw->matte(120, 120, $paintType);
    $draw->rectangle(100, 100, 300, 200);

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::pathClose ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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).

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathCurveToAbsolute ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathCurveToQuadraticBezierAbsolute ( float $x1 , float $y1 , float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::pathCurveToQuadraticBezierAbsolute()

<?php
function pathCurveToQuadraticBezierAbsolute($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeOpacity(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(2);
    $draw->setFontSize(72);

    $draw->pathStart();
    $draw->pathMoveToAbsolute(50,250);

    // This specifies a quadratic bezier curve with the current position as the start
    // point, the control point is the first two params, and the end point is the last two params.
    $draw->pathCurveToQuadraticBezierAbsolute(
        150,50,
        250,250
    );

    // This specifies a quadratic bezier curve with the current position as the start
    // point, the control point is mirrored from the previous curves control point
    // and the end point is defined by the x, y values.
    $draw->pathCurveToQuadraticBezierSmoothAbsolute(
        450,250
    );

    // This specifies a quadratic bezier curve with the current position as the start
    // point, the control point is mirrored from the previous curves control point
    // and the end point is defined relative from the current position by the x, y values.
    $draw->pathCurveToQuadraticBezierSmoothRelative(
        200,-100
    );

    $draw->pathFinish();

    $imagick = new \Imagick();
    $imagick->newImage(700, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();

}

?>

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

Descrierea

bool ImagickDraw::pathCurveToQuadraticBezierRelative ( float $x1 , float $y1 , float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

x1

starting x coordinate

y1

starting y coordinate

x

ending x coordinate

y

ending y coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute ( float $x , float $y )

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.

This function cannot be used to continue a cubic Bezier curve smoothly. It can only continue from a quadratic curve smoothly.

Parametri

x

ending x coordinate

y

ending y coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute()

<?php
$draw = new \ImagickDraw();

$draw->setStrokeOpacity(1);
$draw->setStrokeColor("black");
$draw->setFillColor("blue");

$draw->setStrokeWidth(2);
$draw->setFontSize(72);

$draw->pathStart();
$draw->pathMoveToAbsolute(50,250);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is the first two params, and the end point is the last two params.
$draw->pathCurveToQuadraticBezierAbsolute(
    150,50,
    250,250
);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothAbsolute(
    450,250
);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined relative from the current position by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothRelative(
    200,-100
);

$draw->pathFinish();

$imagick = new \Imagick();
$imagick->newImage(700, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
?>

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

Descrierea

bool ImagickDraw::pathCurveToQuadraticBezierSmoothRelative ( float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

This function cannot be used to continue a cubic Bezier curve smoothly. It can only continue from a quadratic curve smoothly.

Parametri

x

ending x coordinate

y

ending y coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::pathCurveToQuadraticBezierSmoothRelative()

<?php
$draw = new \ImagickDraw();

$draw->setStrokeOpacity(1);
$draw->setStrokeColor("black");
$draw->setFillColor("blue");

$draw->setStrokeWidth(2);
$draw->setFontSize(72);

$draw->pathStart();
$draw->pathMoveToAbsolute(50,250);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is the first two params, and the end point is the last two params.
$draw->pathCurveToQuadraticBezierAbsolute(
    150,50,
    250,250
);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothAbsolute(
    450,250
);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined relative from the current position by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothRelative(
    200,-100
);

$draw->pathFinish();

$imagick = new \Imagick();
$imagick->newImage(700, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
?>

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

Descrierea

bool ImagickDraw::pathCurveToRelative ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathCurveToSmoothAbsolute ( float $x2 , float $y2 , float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathCurveToSmoothRelative ( float $x2 , float $y2 , float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathEllipticArcAbsolute ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathEllipticArcRelative ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathFinish ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Terminates the current path.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathLineToAbsolute ( float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws a line path from the current point to the given coordinate using absolute coordinates. The coordinate then becomes the new current point.

Parametri

x

starting x coordinate

y

ending x coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathLineToHorizontalAbsolute ( float $x )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

x

x coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathLineToHorizontalRelative ( float $x )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

x

x coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathLineToRelative ( float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws a line path from the current point to the given coordinate using relative coordinates. The coordinate then becomes the new current point.

Parametri

x

starting x coordinate

y

starting y coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathLineToVerticalAbsolute ( float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

y

y coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathLineToVerticalRelative ( float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

y

y coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathMoveToAbsolute ( float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Starts a new sub-path at the given coordinate using absolute coordinates. The current point then becomes the specified coordinate.

Parametri

x

x coordinate of the starting point

y

y coordinate of the starting point

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathMoveToRelative ( float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Starts a new sub-path at the given coordinate using relative coordinates. The current point then becomes the specified coordinate.

Parametri

x

target x coordinate

y

target y coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pathStart ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::pathStart()

<?php
function pathStart($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeOpacity(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(2);
    $draw->setFontSize(72);

    $draw->pathStart();
    $draw->pathMoveToAbsolute(50, 50);
    $draw->pathLineToAbsolute(100, 50);
    $draw->pathLineToRelative(0, 50);
    $draw->pathLineToHorizontalRelative(-50);
    $draw->pathFinish();

    $draw->pathStart();
    $draw->pathMoveToAbsolute(50, 50);
    $draw->pathMoveToRelative(300, 0);
    $draw->pathLineToRelative(50, 0);
    $draw->pathLineToVerticalRelative(50);
    $draw->pathLineToHorizontalAbsolute(350);
    $draw->pathclose();
    $draw->pathFinish();

    $draw->pathStart();
    $draw->pathMoveToAbsolute(50, 300);
    $draw->pathCurveToAbsolute(50, 300, 100, 200, 300, 300);
    $draw->pathLineToVerticalAbsolute(350);
    $draw->pathFinish();

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::point ( float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws a point using the current stroke color and stroke thickness at the specified coordinates.

Parametri

x

point's x coordinate

y

point's y coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::point()

<?php
function point($fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setFillColor($fillColor);

    for ($x = 0; $x < 10000; $x++) {
        $draw->point(rand(0, 500), rand(0, 500));
    }

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::polygon ( array $coordinates )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws a polygon using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parametri

coordinates

multidimensional array like array( array( 'x' => 3, 'y' => 4 ), array( 'x' => 2, 'y' => 6 ) );

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 ImagickDraw::polygon()

<?php
function polygon($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeOpacity(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setStrokeWidth(4);

    $draw->setFillColor($fillColor);

    $points = [
        ['x' => 40 * 5, 'y' => 10 * 5],
        ['x' => 20 * 5, 'y' => 20 * 5],
        ['x' => 70 * 5, 'y' => 50 * 5],
        ['x' => 60 * 5, 'y' => 15 * 5],
    ];

    $draw->polygon($points);

    $image = new \Imagick();
    $image->newImage(500, 300, $backgroundColor);
    $image->setImageFormat("png");
    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::polyline ( array $coordinates )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws a polyline using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parametri

coordinates

array of x and y coordinates: array( array( 'x' => 4, 'y' => 6 ), array( 'x' => 8, 'y' => 10 ) )

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 ImagickDraw::polyline()

<?php
function polyline($strokeColor, $fillColor, $backgroundColor) {
    $draw = new \ImagickDraw();

    $draw->setStrokeOpacity(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(5);

    $points = [
        ['x' => 40 * 5, 'y' => 10 * 5],
        ['x' => 20 * 5, 'y' => 20 * 5],
        ['x' => 70 * 5, 'y' => 50 * 5],
        ['x' => 60 * 5, 'y' => 15 * 5]
    ];

    $draw->polyline($points);

    $image = new \Imagick();
    $image->newImage(500, 300, $backgroundColor);
    $image->setImageFormat("png");
    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::pop ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Valorile întoarse

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

Descrierea

bool ImagickDraw::popClipPath ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Terminates a clip path definition.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::popDefs ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Terminates a definition list.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::popDefs()

<?php
function popDefs($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setstrokeOpacity(1);
    $draw->setStrokeWidth(2);
    $draw->setFontSize(72);
    $draw->pushDefs();
    $draw->setStrokeColor('white');
    $draw->rectangle(50, 50, 200, 200);
    $draw->popDefs();

    $draw->rectangle(300, 50, 450, 200);

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::popPattern ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Terminates a pattern definition.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

bool ImagickDraw::push ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ImagickDraw::push()

<?php
function push($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor) {

    $draw = new \ImagickDraw();
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillModifiedColor);
    $draw->setStrokeWidth(2);
    $draw->setFontSize(72);
    $draw->push();
    $draw->translate(50, 50);
    $draw->rectangle(200, 200, 300, 300);
    $draw->pop();
    $draw->setFillColor($fillColor);
    $draw->rectangle(200, 200, 300, 300);

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::pushClipPath ( string $clip_mask_id )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Starts a clip path definition which is comprised of any number of drawing commands and terminated by a ImagickDraw::popClipPath() command.

Parametri

clip_mask_id

Clip mask Id

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pushDefs ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

bool ImagickDraw::pushPattern ( string $pattern_id , float $x , float $y , float $width , float $height )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ImagickDraw::pushPattern()

<?php
function pushPattern($strokeColor, $fillColor, $backgroundColor) {
    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(1);
    $draw->setStrokeOpacity(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(1);

    $draw->pushPattern("MyFirstPattern", 0, 0, 50, 50);
    for ($x = 0; $x < 50; $x += 10) {
        for ($y = 0; $y < 50; $y += 5) {
            $positionX = $x + (($y / 5) % 5);
            $draw->rectangle($positionX, $y, $positionX + 5, $y + 5);
        }
    }
    $draw->popPattern();

    $draw->setFillOpacity(0);
    $draw->rectangle(100, 100, 400, 400);
    $draw->setFillOpacity(1);

    $draw->setFillOpacity(1);

    $draw->push();
    $draw->setFillPatternURL('#MyFirstPattern');
    $draw->setFillColor('yellow');
    $draw->rectangle(100, 100, 400, 400);
    $draw->pop();

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::rectangle ( float $x1 , float $y1 , float $x2 , float $y2 )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws a rectangle given two coordinates and using the current stroke, stroke width, and fill settings.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::rectangle()

<?php
function rectangle($strokeColor, $fillColor, $backgroundColor) {
    $draw = new \ImagickDraw();
    $strokeColor = new \ImagickPixel($strokeColor);
    $fillColor = new \ImagickPixel($fillColor);

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeOpacity(1);
    $draw->setStrokeWidth(2);

    $draw->rectangle(200, 200, 300, 300);
    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

ImagickDraw::pushPattern
ImagickDraw::render
ImagickDraw


Renders all preceding drawing commands onto the image

ImagickDraw::rectangle
ImagickDraw::resetVectorGraphics
ImagickDraw
PHP Manual

ImagickDraw::render

(PECL imagick 2.0.0)

ImagickDraw::render — Renders all preceding drawing commands onto the image

Descrierea

bool ImagickDraw::render ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Renders all preceding drawing commands onto the image.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ImagickDraw::rectangle
ImagickDraw::resetVectorGraphics
ImagickDraw


Description

ImagickDraw::render
ImagickDraw::rotate
ImagickDraw
PHP Manual

ImagickDraw::resetVectorGraphics

(No version information available, might only be in Git)

ImagickDraw::resetVectorGraphics — Description

Descrierea

public void ImagickDraw::resetVectorGraphics ( void )

Resets the vector graphics.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ImagickDraw::render
ImagickDraw::rotate
ImagickDraw


Applies the specified rotation to the current coordinate space

ImagickDraw::resetVectorGraphics
ImagickDraw::roundRectangle
ImagickDraw
PHP Manual

ImagickDraw::rotate

(PECL imagick 2.0.0)

ImagickDraw::rotate — Applies the specified rotation to the current coordinate space

Descrierea

bool ImagickDraw::rotate ( float $degrees )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Applies the specified rotation to the current coordinate space.

Parametri

degrees

degrees to rotate

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::rotate()

<?php
function rotate($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor) {
    $draw = new \ImagickDraw();
    $draw->setStrokeColor($strokeColor);
    $draw->setStrokeOpacity(1);
    $draw->setFillColor($fillColor);
    $draw->rectangle(200, 200, 300, 300);
    $draw->setFillColor($fillModifiedColor);
    $draw->rotate(15);
    $draw->rectangle(200, 200, 300, 300);

    $image = new \Imagick();
    $image->newImage(500, 500, $backgroundColor);
    $image->setImageFormat("png");
    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

ImagickDraw::resetVectorGraphics
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

Descrierea

bool ImagickDraw::roundRectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Draws a rounded rectangle given two coordinates, x & y corner radiuses and using the current stroke, stroke width, and fill settings.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::roundRectangle()

<?php
function roundRectangle($strokeColor, $fillColor, $backgroundColor, $startX, $startY, $endX, $endY, $roundX, $roundY) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeOpacity(1);
    $draw->setStrokeWidth(2);

    $draw->roundRectangle($startX, $startY, $endX, $endY, $roundX, $roundY);

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::scale ( float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Adjusts the scaling factor to apply in the horizontal and vertical directions to the current coordinate space.

Parametri

x

horizontal factor

y

vertical factor

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::scale()

<?php
function scale($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor) {

    $draw = new \ImagickDraw();
    $draw->setStrokeColor($strokeColor);
    $draw->setStrokeWidth(4);
    $draw->setFillColor($fillColor);
    $draw->rectangle(200, 200, 300, 300);
    $draw->setFillColor($fillModifiedColor);
    $draw->scale(1.4, 1.4);
    $draw->rectangle(200, 200, 300, 300);

    $image = new \Imagick();
    $image->newImage(500, 500, $backgroundColor);
    $image->setImageFormat("png");
    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setClipPath ( string $clip_mask )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

clip_mask

the clipping path name

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setClipPath()

<?php
function setClipPath($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeOpacity(1);
    $draw->setStrokeWidth(2);

    $clipPathName = 'testClipPath';

    $draw->pushClipPath($clipPathName);
    $draw->rectangle(0, 0, 250, 250);
    $draw->popClipPath();
    $draw->setClipPath($clipPathName);
    $draw->rectangle(100, 100, 400, 400);

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setClipRule ( int $fill_rule )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Set the polygon fill rule to be used by the clipping path.

Parametri

fill_rule

FILLRULE_ constant

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setClipRule()

<?php
function setClipRule($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeOpacity(1);
    $draw->setStrokeWidth(2);
    //\Imagick::FILLRULE_EVENODD
    //\Imagick::FILLRULE_NONZERO

    $clipPathName = 'testClipPath';
    $draw->pushClipPath($clipPathName);
    $draw->setClipRule(\Imagick::FILLRULE_EVENODD);
    $draw->rectangle(0, 0, 300, 500);
    $draw->rectangle(200, 0, 500, 500);
    $draw->popClipPath();
    $draw->setClipPath($clipPathName);
    $draw->rectangle(200, 200, 300, 300);

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setClipUnits ( int $clip_units )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the interpretation of clip path units.

Parametri

clip_units

the number of clip units

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setClipUnits()

<?php
function setClipUnits($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeOpacity(1);
    $draw->setStrokeWidth(2);
    $clipPathName = 'testClipPath';
    $draw->setClipUnits(\Imagick::RESOLUTION_PIXELSPERINCH);
    $draw->pushClipPath($clipPathName);
    $draw->rectangle(0, 0, 250, 250);
    $draw->popClipPath();
    $draw->setClipPath($clipPathName);

    //RESOLUTION_PIXELSPERINCH
    //RESOLUTION_PIXELSPERCENTIMETER

    $draw->rectangle(200, 200, 300, 300);
    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setFillAlpha ( float $opacity )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the opacity to use when drawing using the fill color or fill texture. Fully opaque is 1.0.

Parametri

opacity

fill alpha

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setFillAlpha()

<?php
function setFillAlpha($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeOpacity(1);
    $draw->setStrokeWidth(2);
    $draw->rectangle(100, 200, 200, 300);
    @$draw->setFillAlpha(0.4);
    $draw->rectangle(300, 200, 400, 300);

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setFillColor ( ImagickPixel $fill_pixel )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the fill color to be used for drawing filled objects.

Parametri

fill_pixel

ImagickPixel to use to set the color

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setFillColor()

<?php
function setFillColor($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeOpacity(1);
    $draw->setStrokeWidth(1.5);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->rectangle(50, 50, 150, 150);

    $draw->setFillColor("rgb(200, 32, 32)");
    $draw->rectangle(200, 50, 300, 150);

    $image = new \Imagick();
    $image->newImage(500, 500, $backgroundColor);
    $image->setImageFormat("png");

    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setFillOpacity ( float $fillOpacity )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the opacity to use when drawing using the fill color or fill texture. Fully opaque is 1.0.

Parametri

fillOpacity

the fill opacity

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setFillOpacity()

<?php
function setFillOpacity($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeOpacity(1);
    $draw->setStrokeWidth(2);

    $draw->rectangle(100, 200, 200, 300);

    $draw->setFillOpacity(0.4);
    $draw->rectangle(300, 200, 400, 300);

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setFillPatternURL ( string $fill_url )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

fill_url

URL to use to obtain fill pattern.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

bool ImagickDraw::setFillRule ( int $fill_rule )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the fill rule to use while drawing polygons.

Parametri

fill_rule

FILLRULE_ constant

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setFillRule()

<?php
function setFillRule($fillColor, $strokeColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeWidth(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $fillRules = [\Imagick::FILLRULE_NONZERO, \Imagick::FILLRULE_EVENODD];

    $points = 11;
    $size = 150;

    $draw->translate(175, 160);

    for ($x = 0; $x < 2; $x++) {
        $draw->setFillRule($fillRules[$x]);
        $draw->pathStart();
        for ($n = 0; $n < $points * 2; $n++) {

            if ($n >= $points) {
                $angle = fmod($n * 360 * 4 / $points, 360) * pi() / 180;
            }
            else {
                $angle = fmod($n * 360 * 3 / $points, 360) * pi() / 180;
            }

            $positionX = $size * sin($angle);
            $positionY = $size * cos($angle);

            if ($n == 0) {
                $draw->pathMoveToAbsolute($positionX, $positionY);
            }
            else {
                $draw->pathLineToAbsolute($positionX, $positionY);
            }
        }

        $draw->pathClose();
        $draw->pathFinish();

        $draw->translate(325, 0);
    }

    $image = new \Imagick();
    $image->newImage(700, 320, $backgroundColor);
    $image->setImageFormat("png");
    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setFont ( string $font_name )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the fully-specified font to use when annotating with text.

Parametri

font_name

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 ImagickDraw::setFont()

<?php
function setFont($fillColor, $strokeColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(2);
    $draw->setFontSize(36);

    $draw->setFont("../fonts/Arial.ttf");
    $draw->annotation(50, 50, "Lorem Ipsum!");

    $draw->setFont("../fonts/Consolas.ttf");
    $draw->annotation(50, 100, "Lorem Ipsum!");

    $draw->setFont("../fonts/CANDY.TTF");
    $draw->annotation(50, 150, "Lorem Ipsum!");

    $draw->setFont("../fonts/Inconsolata-dz.otf");
    $draw->annotation(50, 200, "Lorem Ipsum!");

    $imagick = new \Imagick();
    $imagick->newImage(500, 300, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setFontFamily ( string $font_family )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the font family to use when annotating with text.

Parametri

font_family

the font family

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 ImagickDraw::setFontFamily()

<?php
function setFontFamily($fillColor, $strokeColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $strokeColor = new \ImagickPixel($strokeColor);
    $fillColor = new \ImagickPixel($fillColor);

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(2);

    $draw->setFontSize(48);

    $draw->setFontFamily("Times");
    $draw->annotation(50, 50, "Lorem Ipsum!");

    $draw->setFontFamily("AvantGarde");
    $draw->annotation(50, 100, "Lorem Ipsum!");

    $draw->setFontFamily("NewCenturySchlbk");
    $draw->annotation(50, 150, "Lorem Ipsum!");

    $draw->setFontFamily("Palatino");
    $draw->annotation(50, 200, "Lorem Ipsum!");

    $imagick = new \Imagick();
    $imagick->newImage(450, 250, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setFontSize ( float $pointsize )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the font pointsize to use when annotating with text.

Parametri

pointsize

the point size

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setFontSize()

<?php
function setFontSize($fillColor, $strokeColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeOpacity(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(2);
    $draw->setFont("../fonts/Arial.ttf");

    $sizes = [24, 36, 48, 60, 72];

    foreach ($sizes as $size) {
        $draw->setFontSize($size);
        $draw->annotation(50, ($size * $size / 16), "Lorem Ipsum!");
    }

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setFontStretch ( int $fontStretch )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the font stretch to use when annotating with text. The AnyStretch enumeration acts as a wild-card "don't care" option.

Parametri

fontStretch

STRETCH_ constant

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setFontStretch()

<?php
function setFontStretch($fillColor, $strokeColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(2);
    $draw->setFontSize(36);

    $fontStretchTypes = [
        \Imagick::STRETCH_ULTRACONDENSED,
        \Imagick::STRETCH_CONDENSED,
        \Imagick::STRETCH_SEMICONDENSED,
        \Imagick::STRETCH_SEMIEXPANDED,
        \Imagick::STRETCH_EXPANDED,
        \Imagick::STRETCH_EXTRAEXPANDED,
        \Imagick::STRETCH_ULTRAEXPANDED,
        \Imagick::STRETCH_ANY
    ];

    $offset = 0;
    foreach ($fontStretchTypes as $fontStretch) {
        $draw->setFontStretch($fontStretch);
        $draw->annotation(50, 75 + $offset, "Lorem Ipsum!");
        $offset += 50;
    }

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setFontStyle ( int $style )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the font style to use when annotating with text. The AnyStyle enumeration acts as a wild-card "don't care" option.

Parametri

style

STYLETYPE_ constant

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setFontStyle()

<?php
function setFontStyle($fillColor, $strokeColor, $backgroundColor) {
    $draw = new \ImagickDraw();
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(1);
    $draw->setFontSize(36);
    $draw->setFontStyle(\Imagick::STYLE_NORMAL);
    $draw->annotation(50, 50, "Lorem Ipsum!");

    $draw->setFontStyle(\Imagick::STYLE_ITALIC);
    $draw->annotation(50, 100, "Lorem Ipsum!");

    $draw->setFontStyle(\Imagick::STYLE_OBLIQUE);
    $draw->annotation(50, 150, "Lorem Ipsum!");

    $imagick = new \Imagick();
    $imagick->newImage(350, 300, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setFontWeight ( int $font_weight )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the font weight to use when annotating with text.

Parametri

font_weight

Valorile întoarse

Exemple

Example #1 ImagickDraw::setFontWeight()

<?php
function setFontWeight($fillColor, $strokeColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(1);

    $draw->setFontSize(36);

    $draw->setFontWeight(100);
    $draw->annotation(50, 50, "Lorem Ipsum!");

    $draw->setFontWeight(200);
    $draw->annotation(50, 100, "Lorem Ipsum!");

    $draw->setFontWeight(400);
    $draw->annotation(50, 150, "Lorem Ipsum!");

    $draw->setFontWeight(800);
    $draw->annotation(50, 200, "Lorem Ipsum!");

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

ImagickDraw::setFontStyle
ImagickDraw::setGravity
ImagickDraw


Sets the text placement gravity

ImagickDraw::setFontWeight
ImagickDraw::setResolution
ImagickDraw
PHP Manual

ImagickDraw::setGravity

(PECL imagick 2.0.0)

ImagickDraw::setGravity — Sets the text placement gravity

Descrierea

bool ImagickDraw::setGravity ( int $gravity )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the text placement gravity to use when annotating with text.

Parametri

gravity

GRAVITY_ constant

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setGravity()

<?php
function setGravity($fillColor, $strokeColor, $backgroundColor) {

    $draw = new \ImagickDraw();
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(1);
    $draw->setFontSize(24);

    $gravitySettings = array(
        \Imagick::GRAVITY_NORTHWEST => 'NorthWest',
        \Imagick::GRAVITY_NORTH => 'North',
        \Imagick::GRAVITY_NORTHEAST => 'NorthEast',
        \Imagick::GRAVITY_WEST => 'West',
        \Imagick::GRAVITY_CENTER => 'Centre',
        \Imagick::GRAVITY_SOUTHWEST => 'SouthWest',
        \Imagick::GRAVITY_SOUTH => 'South',
        \Imagick::GRAVITY_SOUTHEAST => 'SouthEast',
        \Imagick::GRAVITY_EAST => 'East'
    );

    $draw->setFont("../fonts/Arial.ttf");

    foreach ($gravitySettings as $type => $description) {
        $draw->setGravity($type);
        $draw->annotation(50, 50, '"' . $description . '"');
    }

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

ImagickDraw::setFontWeight
ImagickDraw::setResolution
ImagickDraw


Description

ImagickDraw::setGravity
ImagickDraw::setStrokeAlpha
ImagickDraw
PHP Manual

ImagickDraw::setResolution

(No version information available, might only be in Git)

ImagickDraw::setResolution — Description

Descrierea

public void ImagickDraw::setResolution ( string $x_resolution , string $y_resolution )

Sets the resolution.

Parametri

x_resolution

y_resolution

Valorile întoarse

ImagickDraw::setGravity
ImagickDraw::setStrokeAlpha
ImagickDraw


Specifies the opacity of stroked object outlines

ImagickDraw::setResolution
ImagickDraw::setStrokeAntialias
ImagickDraw
PHP Manual

ImagickDraw::setStrokeAlpha

(PECL imagick 2.0.0)

ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines

Descrierea

bool ImagickDraw::setStrokeAlpha ( float $opacity )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Specifies the opacity of stroked object outlines.

Parametri

opacity

opacity

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setStrokeAlpha()

<?php
function setStrokeAlpha($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(4);
    $draw->line(100, 100, 400, 145);
    $draw->rectangle(100, 200, 225, 350);
    $draw->setStrokeOpacity(0.1);
    $draw->line(100, 120, 400, 165);
    $draw->rectangle(275, 200, 400, 350);

    $image = new \Imagick();
    $image->newImage(500, 400, $backgroundColor);
    $image->setImageFormat("png");

    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

ImagickDraw::setResolution
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

Descrierea

bool ImagickDraw::setStrokeAntialias ( bool $stroke_antialias )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

stroke_antialias

the antialias setting

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setStrokeAntialias()

<?php
function setStrokeAntialias($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(1);
    $draw->setStrokeAntialias(false);
    $draw->line(100, 100, 400, 105);

    $draw->line(100, 140, 400, 185);

    $draw->setStrokeAntialias(true);
    $draw->line(100, 110, 400, 115);
    $draw->line(100, 150, 400, 195);

    $image = new \Imagick();
    $image->newImage(500, 250, $backgroundColor);
    $image->setImageFormat("png");

    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setStrokeColor ( ImagickPixel $stroke_pixel )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the color used for stroking object outlines.

Parametri

stroke_pixel

the stroke color

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setStrokeColor()

<?php
function setStrokeColor($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(5);

    $draw->line(100, 100, 400, 145);
    $draw->rectangle(100, 200, 225, 350);

    $draw->setStrokeOpacity(0.1);
    $draw->line(100, 120, 400, 165);
    $draw->rectangle(275, 200, 400, 350);

    $image = new \Imagick();
    $image->newImage(500, 400, $backgroundColor);
    $image->setImageFormat("png");

    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setStrokeDashArray ( array $dashArray )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

dashArray

array of floats

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 ImagickDraw::setStrokeDashArray()

<?php
function setStrokeDashArray($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(4);

    $draw->setStrokeDashArray([10, 10]);
    $draw->rectangle(100, 50, 225, 175);

    $draw->setStrokeDashArray([20, 5, 20, 5, 5, 5,]);
    $draw->rectangle(275, 50, 400, 175);

    $draw->setStrokeDashArray([20, 5, 20, 5, 5]);
    $draw->rectangle(100, 200, 225, 350);

    $draw->setStrokeDashArray([1, 1, 1, 1, 2, 2, 3, 3, 5, 5, 8, 8, 13, 13, 21, 21, 34, 34, 55, 55, 89, 89, 144, 144, 233, 233, 377, 377, 610, 610, 987, 987, 1597, 1597, 2584, 2584, 4181, 4181,]);

    $draw->rectangle(275, 200, 400, 350);

    $image = new \Imagick();
    $image->newImage(500, 400, $backgroundColor);
    $image->setImageFormat("png");
    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setStrokeDashOffset ( float $dash_offset )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Specifies the offset into the dash pattern to start the dash.

Parametri

dash_offset

dash offset

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setStrokeDashOffset()

<?php
function setStrokeDashOffset($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(4);
    $draw->setStrokeDashArray([20, 20]);
    $draw->setStrokeDashOffset(0);
    $draw->rectangle(100, 50, 225, 175);

    //Start the dash effect halfway through the solid portion
    $draw->setStrokeDashOffset(10);
    $draw->rectangle(275, 50, 400, 175);

    //Start the dash effect on the space portion
    $draw->setStrokeDashOffset(20);
    $draw->rectangle(100, 200, 225, 350);
    $draw->setStrokeDashOffset(5);
    $draw->rectangle(275, 200, 400, 350);

    $image = new \Imagick();
    $image->newImage(500, 400, $backgroundColor);
    $image->setImageFormat("png");
    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setStrokeLineCap ( int $linecap )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Specifies the shape to be used at the end of open subpaths when they are stroked.

Parametri

linecap

LINECAP_ constant

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setStrokeLineCap()

<?php
function setStrokeLineCap($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(25);

    $lineTypes = [\Imagick::LINECAP_BUTT, \Imagick::LINECAP_ROUND, \Imagick::LINECAP_SQUARE,];

    $offset = 0;

    foreach ($lineTypes as $lineType) {
        $draw->setStrokeLineCap($lineType);
        $draw->line(50 + $offset, 50, 50 + $offset, 250);
        $offset += 50;
    }

    $imagick = new \Imagick();
    $imagick->newImage(300, 300, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setStrokeLineJoin ( int $linejoin )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Specifies the shape to be used at the corners of paths (or other vector shapes) when they are stroked.

Parametri

linejoin

LINEJOIN_ constant

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setStrokeLineJoin()

<?php
function setStrokeLineJoin($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();
    $draw->setStrokeWidth(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);

    $draw->setStrokeWidth(20);

    $offset = 220;

    $lineJoinStyle = [
        \Imagick::LINEJOIN_MITER,
        \Imagick::LINEJOIN_ROUND,
        \Imagick::LINEJOIN_BEVEL,
        ];

    for ($x = 0; $x < count($lineJoinStyle); $x++) {
        $draw->setStrokeLineJoin($lineJoinStyle[$x]);
        $points = [
            ['x' => 40 * 5, 'y' => 10 * 5 + $x * $offset],
            ['x' => 20 * 5, 'y' => 20 * 5 + $x * $offset],
            ['x' => 70 * 5, 'y' => 50 * 5 + $x * $offset],
            ['x' => 40 * 5, 'y' => 10 * 5 + $x * $offset],
        ];

        $draw->polyline($points);
    }

    $image = new \Imagick();
    $image->newImage(500, 700, $backgroundColor);
    $image->setImageFormat("png");

    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setStrokeMiterLimit ( int $miterlimit )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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'.

Parametri

miterlimit

the miter limit

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setStrokeMiterLimit()

<?php
function setStrokeMiterLimit($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setStrokeOpacity(0.6);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(10);

    $yOffset = 100;

    $draw->setStrokeLineJoin(\Imagick::LINEJOIN_MITER);

    for ($y = 0; $y < 3; $y++) {

        $draw->setStrokeMiterLimit(40 * $y);

        $points = [
            ['x' => 22 * 3, 'y' => 15 * 4 + $y * $yOffset],
            ['x' => 20 * 3, 'y' => 20 * 4 + $y * $yOffset],
            ['x' => 70 * 5, 'y' => 45 * 4 + $y * $yOffset],
        ];

        $draw->polygon($points);
    }

    $image = new \Imagick();
    $image->newImage(500, 500, $backgroundColor);
    $image->setImageFormat("png");
    $image->drawImage($draw);

    $image->setImageType(\Imagick::IMGTYPE_PALETTE);
    $image->setImageCompressionQuality(100);
    $image->stripImage();

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setStrokeOpacity ( float $stroke_opacity )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Specifies the opacity of stroked object outlines.

Parametri

stroke_opacity

stroke opacity. 1.0 is fully opaque

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setStrokeOpacity()

<?php
function setStrokeOpacity($strokeColor, $fillColor, $backgroundColor) {
    $draw = new \ImagickDraw();

    $draw->setStrokeWidth(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(10);
    $draw->setStrokeOpacity(1);
    $draw->line(100, 80, 400, 125);
    $draw->rectangle(25, 200, 150, 350);
    $draw->setStrokeOpacity(0.5);
    $draw->line(100, 100, 400, 145);
    $draw->rectangle(200, 200, 325, 350);
    $draw->setStrokeOpacity(0.2);
    $draw->line(100, 120, 400, 165);
    $draw->rectangle(375, 200, 500, 350);

    $image = new \Imagick();
    $image->newImage(550, 400, $backgroundColor);
    $image->setImageFormat("png");
    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setStrokePatternURL ( string $stroke_url )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the pattern used for stroking object outlines.

Parametri

stroke_url

stroke URL

Valorile întoarse

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

Descrierea

bool ImagickDraw::setStrokeWidth ( float $stroke_width )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the width of the stroke used to draw object outlines.

Parametri

stroke_width

stroke width

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setStrokeWidth()

<?php
function setStrokeWidth($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeWidth(1);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->line(100, 100, 400, 145);
    $draw->rectangle(100, 200, 225, 350);
    $draw->setStrokeWidth(5);
    $draw->line(100, 120, 400, 165);
    $draw->rectangle(275, 200, 400, 350);

    $image = new \Imagick();
    $image->newImage(500, 400, $backgroundColor);
    $image->setImageFormat("png");
    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setTextAlignment ( int $alignment )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Specifies a text alignment to be applied when annotating with text.

Parametri

alignment

ALIGN_ constant

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setTextAlignment()

<?php
function setTextAlignment($strokeColor, $fillColor, $backgroundColor) {
    $draw = new \ImagickDraw();
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(1);
    $draw->setFontSize(36);

    $draw->setTextAlignment(\Imagick::ALIGN_LEFT);
    $draw->annotation(250, 75, "Lorem Ipsum!");
    $draw->setTextAlignment(\Imagick::ALIGN_CENTER);
    $draw->annotation(250, 150, "Lorem Ipsum!");
    $draw->setTextAlignment(\Imagick::ALIGN_RIGHT);
    $draw->annotation(250, 225, "Lorem Ipsum!");
    $draw->line(250, 0, 250, 500);

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setTextAntialias ( bool $antiAlias )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Controls whether text is antialiased. Text is antialiased by default.

Parametri

antiAlias

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setTextAntialias()

<?php
function setTextAntialias($fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();
    $draw->setStrokeColor('none');
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(1);
    $draw->setFontSize(32);
    $draw->setTextAntialias(false);
    $draw->annotation(5, 30, "Lorem Ipsum!");
    $draw->setTextAntialias(true);
    $draw->annotation(5, 65, "Lorem Ipsum!");

    $imagick = new \Imagick();
    $imagick->newImage(220, 80, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    //Scale the image so that people can see the aliasing.
    $imagick->scaleImage(220 * 6, 80 * 6);
    $imagick->cropImage(640, 480, 0, 0);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setTextDecoration ( int $decoration )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Specifies a decoration to be applied when annotating with text.

Parametri

decoration

DECORATION_ constant

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setTextDecoration()

<?php
function setTextDecoration($strokeColor, $fillColor, $backgroundColor, $textDecoration) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(2);
    $draw->setFontSize(72);
    $draw->setTextDecoration($textDecoration);
    $draw->annotation(50, 75, "Lorem Ipsum!");

    $imagick = new \Imagick();
    $imagick->newImage(500, 200, $backgroundColor);
    $imagick->setImageFormat("png");
    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

ImagickDraw::setTextAntialias
ImagickDraw::setTextEncoding
ImagickDraw


Specifies the text code set

ImagickDraw::setTextDecoration
ImagickDraw::setTextInterlineSpacing
ImagickDraw
PHP Manual

ImagickDraw::setTextEncoding

(PECL imagick 2.0.0)

ImagickDraw::setTextEncoding — Specifies the text code set

Descrierea

bool ImagickDraw::setTextEncoding ( string $encoding )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

encoding

the encoding name

Valorile întoarse

Nu este întoarsa nici o valoare.

ImagickDraw::setTextDecoration
ImagickDraw::setTextInterlineSpacing
ImagickDraw


Description

ImagickDraw::setTextEncoding
ImagickDraw::setTextInterwordSpacing
ImagickDraw
PHP Manual

ImagickDraw::setTextInterlineSpacing

(No version information available, might only be in Git)

ImagickDraw::setTextInterlineSpacing — Description

Descrierea

public void ImagickDraw::setTextInterlineSpacing ( float $spacing )

Sets the text interline spacing.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

spacing

Valorile întoarse

ImagickDraw::setTextEncoding
ImagickDraw::setTextInterwordSpacing
ImagickDraw


Description

ImagickDraw::setTextInterlineSpacing
ImagickDraw::setTextKerning
ImagickDraw
PHP Manual

ImagickDraw::setTextInterwordSpacing

(No version information available, might only be in Git)

ImagickDraw::setTextInterwordSpacing — Description

Descrierea

public void ImagickDraw::setTextInterwordSpacing ( float $spacing )

Sets the text interword spacing.

Parametri

spacing

Valorile întoarse

ImagickDraw::setTextInterlineSpacing
ImagickDraw::setTextKerning
ImagickDraw


Description

ImagickDraw::setTextInterwordSpacing
ImagickDraw::setTextUnderColor
ImagickDraw
PHP Manual

ImagickDraw::setTextKerning

(No version information available, might only be in Git)

ImagickDraw::setTextKerning — Description

Descrierea

public void ImagickDraw::setTextKerning ( float $kerning )

Sets the text kerning

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

kerning

Valorile întoarse

ImagickDraw::setTextInterwordSpacing
ImagickDraw::setTextUnderColor
ImagickDraw


Specifies the color of a background rectangle

ImagickDraw::setTextKerning
ImagickDraw::setVectorGraphics
ImagickDraw
PHP Manual

ImagickDraw::setTextUnderColor

(PECL imagick 2.0.0)

ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle

Descrierea

bool ImagickDraw::setTextUnderColor ( ImagickPixel $under_color )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Specifies the color of a background rectangle to place under text annotations.

Parametri

under_color

the under color

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setTextUnderColor()

<?php
function setTextUnderColor($strokeColor, $fillColor, $backgroundColor, $textUnderColor) {
    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(2);
    $draw->setFontSize(72);
    $draw->annotation(50, 75, "Lorem Ipsum!");
    $draw->setTextUnderColor($textUnderColor);
    $draw->annotation(50, 175, "Lorem Ipsum!");

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

ImagickDraw::setTextKerning
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

Descrierea

bool ImagickDraw::setVectorGraphics ( string $xml )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

xml

xml containing the vector graphics

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ImagickDraw::setVectorGraphics()

<?php
function setVectorGraphics() {
    //Setup a draw object with some drawing in it.
    $draw = new \ImagickDraw();
    $draw->setFillColor("red");
    $draw->circle(20, 20, 50, 50);
    $draw->setFillColor("blue");
    $draw->circle(50, 70, 50, 50);
    $draw->rectangle(50, 120, 80, 150);

    //Get the drawing as a string
    $SVG = $draw->getVectorGraphics();

    //$svg is a string, and could be saved anywhere a string can be saved

    //Use the saved drawing to generate a new draw object
    $draw2 = new \ImagickDraw();
    //Apparently the SVG text is missing the root element.
    $draw2->setVectorGraphics("<root>".$SVG."</root>");

    $imagick = new \Imagick();
    $imagick->newImage(200, 200, 'white');
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw2);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::setViewbox ( int $x1 , int $y1 , int $x2 , int $y2 )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Parametri

x1

left x coordinate

y1

left y coordinate

x2

right x coordinate

y2

right y coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::setViewBox()

<?php
function setViewBox($strokeColor, $fillColor, $backgroundColor) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->setStrokeWidth(2);
    $draw->setFontSize(72);

    /*

    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.

     */

    $draw->circle(250, 250, 250, 0);
    $draw->setviewbox(0, 0, 200, 200);
    $draw->circle(125, 250, 250, 250);
    $draw->translate(250, 125);
    $draw->circle(0, 0, 125, 0);

    $imagick = new \Imagick();
    $imagick->newImage(500, 500, $backgroundColor);
    $imagick->setImageFormat("png");

    $imagick->drawImage($draw);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::skewX ( float $degrees )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Skews the current coordinate system in the horizontal direction.

Parametri

degrees

degrees to skew

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::skewX()

<?php
function skewX($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor,
               $startX, $startY, $endX, $endY, $skew) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setStrokeWidth(2);
    $draw->setFillColor($fillColor);
    $draw->rectangle($startX, $startY, $endX, $endY);
    $draw->setFillColor($fillModifiedColor);
    $draw->skewX($skew);
    $draw->rectangle($startX, $startY, $endX, $endY);

    $image = new \Imagick();
    $image->newImage(500, 500, $backgroundColor);
    $image->setImageFormat("png");

    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::skewY ( float $degrees )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Skews the current coordinate system in the vertical direction.

Parametri

degrees

degrees to skew

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::skewY()

<?php
function skewY($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor,
               $startX, $startY, $endX, $endY, $skew) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setStrokeWidth(2);
    $draw->setFillColor($fillColor);
    $draw->rectangle($startX, $startY, $endX, $endY);
    $draw->setFillColor($fillModifiedColor);
    $draw->skewY($skew);
    $draw->rectangle($startX, $startY, $endX, $endY);

    $image = new \Imagick();
    $image->newImage(500, 500, $backgroundColor);
    $image->setImageFormat("png");
    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickDraw::translate ( float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Applies a translation to the current coordinate system which moves the coordinate system origin to the specified coordinate.

Parametri

x

horizontal translation

y

vertical translation

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ImagickDraw::translate()

<?php
function translate($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor,
                   $startX, $startY, $endX, $endY, $translateX, $translateY) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->rectangle($startX, $startY, $endX, $endY);

    $draw->setFillColor($fillModifiedColor);
    $draw->translate($translateX, $translateY);
    $draw->rectangle($startX, $startY, $endX, $endY);

    $image = new \Imagick();
    $image->newImage(500, 500, $backgroundColor);
    $image->setImageFormat("png");

    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

ImagickDraw::skewY
ImagickPixel
ImagickDraw


The ImagickPixel class

(PECL imagick 2.0.0)

Sinopsisul clasei

ImagickPixel {
bool clear ( void )
__construct ([ string $color ] )
bool destroy ( void )
array getColor ([ bool $normalized = false ] )
string getColorAsString ( void )
int getColorCount ( void )
public mixed getColorQuantum ( void )
float getColorValue ( int $color )
public mixed getColorValueQuantum ( void )
array getHSL ( void )
public int getIndex ( void )
bool isPixelSimilar ( ImagickPixel $color , float $fuzz )
public bool isPixelSimilarQuantum ( string $color [, string $fuzz ] )
bool isSimilar ( ImagickPixel $color , float $fuzz )
bool setColor ( string $color )
public void setcolorcount ( string $colorCount )
bool setColorValue ( int $color , float $value )
public void setColorValueQuantum ( int $color , mixed $value )
bool setHSL ( float $hue , float $saturation , float $luminosity )
public void setIndex ( int $index )
}

Cuprins

  • 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::getColorQuantum — Description
  • ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
  • ImagickPixel::getColorValueQuantum — Description
  • ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
  • ImagickPixel::getIndex — Description
  • ImagickPixel::isPixelSimilar — Check the distance between this color and another
  • ImagickPixel::isPixelSimilarQuantum — Description
  • ImagickPixel::isSimilar — Check the distance between this color and another
  • ImagickPixel::setColor — Sets the color
  • ImagickPixel::setColorCount — Description
  • ImagickPixel::setColorValue — Sets the normalized value of one of the channels
  • ImagickPixel::setColorValueQuantum — Description
  • ImagickPixel::setHSL — Sets the normalized HSL color
  • ImagickPixel::setIndex — Description
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

Descrierea

bool ImagickPixel::clear ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Clears the ImagickPixel object, leaving it in a fresh state. This also unsets any color associated with the object.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

ImagickPixel::__construct ([ string $color ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Constructs an ImagickPixel object. If a color is specified, the object is constructed and then initialised with that color before being returned.

Parametri

color

The optional color string to use as the initial value of this object.

Valorile întoarse

Returns an ImagickPixel object on success, throwing ImagickPixelException on failure.

Exemple

Example #1 ImagickPixel::construct()

<?php
function construct() {

    $columns = 4;

    $exampleColors = array(
        "rgba(100%, 0%, 0%, 0.5)",
        "hsb(33.3333%, 100%,  75%)", // medium green
        "hsl(120, 255,   191.25)", //medium green
        "graya(50%, 0.5)", //  semi-transparent mid gray
        "LightCoral", "none", //"cmyk(0.9, 0.48, 0.83, 0.50)",
        "#f00", //  #rgb
        "#ff0000", //  #rrggbb
        "#ff0000ff", //  #rrggbbaa
        "#ffff00000000", //  #rrrrggggbbbb
        "#ffff00000000ffff", //  #rrrrggggbbbbaaaa
        "rgb(255, 0, 0)", //  an integer in the range 0—255 for each component
        "rgb(100.0%, 0.0%, 0.0%)", //  a float in the range 0—100% for each component
        "rgb(255, 0, 0)", //  range 0 - 255
        "rgba(255, 0, 0, 1.0)", //  the same, with an explicit alpha value
        "rgb(100%, 0%, 0%)", //  range 0.0% - 100.0%
        "rgba(100%, 0%, 0%, 1.0)", //  the same, with an explicit alpha value
    );

    $draw = new \ImagickDraw();
    $count = 0;
    $black = new \ImagickPixel('rgb(0, 0, 0)');

    foreach ($exampleColors as $exampleColor) {
        $color = new \ImagickPixel($exampleColor);

        $draw->setstrokewidth(1.0);
        $draw->setStrokeColor($black);
        $draw->setFillColor($color);
        $offsetX = ($count % $columns) * 50 + 5;
        $offsetY = intval($count / $columns) * 50 + 5;
        $draw->rectangle(0 + $offsetX, 0 + $offsetY, 40 + $offsetX, 40 + $offsetY);
        $count++;
    }

    $image = new \Imagick();
    $image->newImage(350, 350, "blue");
    $image->setImageFormat("png");
    $image->drawImage($draw);
    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

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

Descrierea

bool ImagickPixel::destroy ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

array ImagickPixel::getColor ([ bool $normalized = false ] )

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.

Parametri

normalized

Normalize the color values

Valorile întoarse

An array of channel values, each normalized if TRUE is given as param. Throws ImagickPixelException on error.

Exemple

Example #1 Basic Imagick::getColor() usage

<?php

//Create an ImagickPixel with the predefined color 'brown'
$color = new ImagickPixel('brown');

//Set the color to have an alpha of 25%
$color->setColorValue(Imagick::COLOR_ALPHA, 64 / 256.0);

$colorInfo = $color->getColor();

echo "Standard values".PHP_EOL;
print_r($colorInfo);

$colorInfo = $color->getColor(true);

echo "Normalized values:".PHP_EOL;
print_r($colorInfo);

?>

Exemplul de mai sus va afi?a:

Standard values
Array
(
    [r] => 165
    [g] => 42
    [b] => 42
    [a] => 0
)
Normalized values:
Array
(
    [r] => 0.64705882352941
    [g] => 0.16470588235294
    [b] => 0.16470588235294
    [a] => 0.25000381475547
)

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

Descrierea

string ImagickPixel::getColorAsString ( void )

Returns the color of the ImagickPixel object as a string.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the color of the ImagickPixel object as a string.

Exemple

Example #1 Basic Imagick::getColorAsString() usage

<?php

//Create an ImagickPixel with the predefined color 'brown'
$color = new ImagickPixel('brown');

$color->setColorValue(Imagick::COLOR_ALPHA, 64 / 256.0);

$colorInfo = $color->getColorAsString();

print_r($colorInfo);
?>

Exemplul de mai sus va afi?a:

rgb(165,42,42)

Note

Nota: Alpha not returned

This function does not return the alpha value of the color in the string.

ImagickPixel::getColor
ImagickPixel::getColorCount
ImagickPixel


Returns the color count associated with this color

ImagickPixel::getColorAsString
ImagickPixel::getColorQuantum
ImagickPixel
PHP Manual

ImagickPixel::getColorCount

(PECL imagick 2.0.0)

ImagickPixel::getColorCount — Returns the color count associated with this color

Descrierea

int ImagickPixel::getColorCount ( void )

Returns the color count associated with this color.

The color count is the number of pixels in the image that have the same color as this ImagickPixel.

ImagickPixel::getColorCount appears to only work for ImagickPixel objects created through Imagick::getImageHistogram()

Valorile întoarse

Returns the color count as an integer on success, throws ImagickPixelException on failure.

Exemple

Example #1 ImagickPixel getColorCount()

<?php
    $imagick = new \Imagick();
    $imagick->newPseudoImage(640, 480, "magick:logo");
    $histogramElements = $imagick->getImageHistogram();
    $lastColor = array_pop($histogramElements);
    echo "Last pixel color count is: ".$lastColor->getColorCount();
?>

The output for this will be similar to:

Last pixel color count is: 256244

ImagickPixel::getColorAsString
ImagickPixel::getColorQuantum
ImagickPixel


Description

ImagickPixel::getColorCount
ImagickPixel::getColorValue
ImagickPixel
PHP Manual

ImagickPixel::getColorQuantum

(No version information available, might only be in Git)

ImagickPixel::getColorQuantum — Description

Descrierea

public mixed ImagickPixel::getColorQuantum ( void )

Returns the color of the pixel in an array as Quantum values. If ImageMagick was compiled as HDRI these will be floats, otherwise they will be integers.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The quantum value of the color element. Float if ImageMagick was compiled with HDRI, otherwise an int.

ImagickPixel::getColorCount
ImagickPixel::getColorValue
ImagickPixel


Gets the normalized value of the provided color channel

ImagickPixel::getColorQuantum
ImagickPixel::getColorValueQuantum
ImagickPixel
PHP Manual

ImagickPixel::getColorValue

(PECL imagick 2.0.0)

ImagickPixel::getColorValue — Gets the normalized value of the provided color channel

Descrierea

float ImagickPixel::getColorValue ( int $color )

Retrieves the value of the color channel specified, as a floating-point number between 0 and 1.

Parametri

color

The color to get the value of, specified as one of the Imagick color constants. This can be one of the RGB colors, CMYK colors, alpha and opacity e.g (Imagick::COLOR_BLUE, Imagick::COLOR_MAGENTA).

Valorile întoarse

The value of the channel, as a normalized floating-point number, throwing ImagickPixelException on error.

Exemple

Example #1 Basic Imagick::getColorValue() usage

<?php

$color = new ImagickPixel('rgba(90%, 20%, 20%, 0.75)');

echo "Alpha value is ".$color->getColorValue(Imagick::COLOR_ALPHA).PHP_EOL;
echo "".PHP_EOL;
echo "Red value is ".$color->getColorValue(Imagick::COLOR_RED).PHP_EOL;
echo "Green value is ".$color->getColorValue(Imagick::COLOR_GREEN).PHP_EOL;
echo "Blue value is ".$color->getColorValue(Imagick::COLOR_BLUE).PHP_EOL;
echo "".PHP_EOL;
echo "Cyan value is ".$color->getColorValue(Imagick::COLOR_CYAN).PHP_EOL;
echo "Magenta value is ".$color->getColorValue(Imagick::COLOR_MAGENTA).PHP_EOL;
echo "Yellow value is ".$color->getColorValue(Imagick::COLOR_YELLOW).PHP_EOL;
echo "Black value is ".$color->getColorValue(Imagick::COLOR_BLACK).PHP_EOL;

?>

Exemplul de mai sus va afi?a:

Alpha value is 0.74999618524453

Red value is 0.90000762951095
Green value is 0.2
Blue value is 0.2

Cyan value is 0.90000762951095
Magenta value is 0.2
Yellow value is 0.2
Black value is 0

ImagickPixel::getColorQuantum
ImagickPixel::getColorValueQuantum
ImagickPixel


Description

ImagickPixel::getColorValue
ImagickPixel::getHSL
ImagickPixel
PHP Manual

ImagickPixel::getColorValueQuantum

(No version information available, might only be in Git)

ImagickPixel::getColorValueQuantum — Description

Descrierea

public mixed ImagickPixel::getColorValueQuantum ( void )

Gets the quantum value of a color in the ImagickPixel. Return value is a float if ImageMagick was compiled with HDRI, otherwise an integer.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The quantum value of the color element. Float if ImageMagick was compiled with HDRI, otherwise an int.

Exemple

Example #1 ImagickPixel::getColorValueQuantum()

<?php
        $color = new \ImagickPixel('rgb(128, 5, 255)');
        $colorRed = $color->getColorValueQuantum(\Imagick::COLOR_RED);
        $colorGreen = $color->getColorValueQuantum(\Imagick::COLOR_GREEN);
        $colorBlue = $color->getColorValueQuantum(\Imagick::COLOR_BLUE);
        $colorAlpha = $color->getColorValueQuantum(\Imagick::COLOR_ALPHA);

        printf(
            "Red: %s Green: %s  Blue %s Alpha: %s",
            $colorRed,
            $colorGreen,
            $colorBlue,
            $colorAlpha
        );

?>

ImagickPixel::getColorValue
ImagickPixel::getHSL
ImagickPixel


Returns the normalized HSL color of the ImagickPixel object

ImagickPixel::getColorValueQuantum
ImagickPixel::getIndex
ImagickPixel
PHP Manual

ImagickPixel::getHSL

(PECL imagick 2.0.0)

ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object

Descrierea

array ImagickPixel::getHSL ( void )

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.

Valorile întoarse

Returns the HSL value in an array with the keys "hue", "saturation", and "luminosity". Throws ImagickPixelException on failure.

Exemple

Example #1 Basic Imagick::getHSL() example

<?php

$color = new ImagickPixel('rgb(90%, 10%, 10%)');

$colorInfo = $color->getHSL();

print_r($colorInfo);

?>

Exemplul de mai sus va afi?a:

Array
(
    [hue] => 0
    [saturation] => 0.80001220740379
    [luminosity] => 0.50000762951095
)

Note

Nota:

Available with ImageMagick library version 6.2.9 and higher.

ImagickPixel::getColorValueQuantum
ImagickPixel::getIndex
ImagickPixel


Description

ImagickPixel::getHSL
ImagickPixel::isPixelSimilar
ImagickPixel
PHP Manual

ImagickPixel::getIndex

(No version information available, might only be in Git)

ImagickPixel::getIndex — Description

Descrierea

public int ImagickPixel::getIndex ( void )

Gets the colormap index of the pixel wand.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ImagickPixel::getHSL
ImagickPixel::isPixelSimilar
ImagickPixel


Check the distance between this color and another

ImagickPixel::getIndex
ImagickPixel::isPixelSimilarQuantum
ImagickPixel
PHP Manual

ImagickPixel::isPixelSimilar

(No version information available, might only be in Git)

ImagickPixel::isPixelSimilar — Check the distance between this color and another

Descrierea

bool ImagickPixel::isPixelSimilar ( ImagickPixel $color , float $fuzz )

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. This method replaces ImagickPixel::isSimilar() and correctly normalises the fuzz value to ImageMagick QuantumRange.

Parametri

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).

Valorile întoarse

Întoarce TRUE în caz de succes.

ImagickPixel::getIndex
ImagickPixel::isPixelSimilarQuantum
ImagickPixel


Description

ImagickPixel::isPixelSimilar
ImagickPixel::isSimilar
ImagickPixel
PHP Manual

ImagickPixel::isPixelSimilarQuantum

(No version information available, might only be in Git)

ImagickPixel::isPixelSimilarQuantum — Description

Descrierea

public bool ImagickPixel::isPixelSimilarQuantum ( string $color [, string $fuzz ] )

Returns true if the distance between two colors is less than the specified distance. The fuzz value should be in the range 0-QuantumRange. The maximum value represents the longest possible distance in the colorspace. e.g. from RGB(0, 0, 0) to RGB(255, 255, 255) for the RGB colorspace

Parametri

color

fuzz

Valorile întoarse

ImagickPixel::isPixelSimilar
ImagickPixel::isSimilar
ImagickPixel


Check the distance between this color and another

ImagickPixel::isPixelSimilarQuantum
ImagickPixel::setColor
ImagickPixel
PHP Manual

ImagickPixel::isSimilar

(PECL imagick 2.0.0)

ImagickPixel::isSimilar — Check the distance between this color and another

Descrierea

bool ImagickPixel::isSimilar ( ImagickPixel $color , float $fuzz )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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. Deprecated in favour of ImagickPixel::isPixelSimilar().

Parametri

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).

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 ImagickPixel::isSimilar()

<?php
        // The tests below are written with the maximum distance expressed as 255
        // so we need to scale them by the square root of 3 - the diagonal length
        // of a unit cube.
        $root3 = 1.732050807568877;

        $tests = array(
            ['rgb(245, 0, 0)',      'rgb(255, 0, 0)',   9 / $root3,         false,],
            ['rgb(245, 0, 0)',      'rgb(255, 0, 0)',  10 / $root3,         true,],
            ['rgb(0, 0, 0)',        'rgb(7, 7, 0)',     9 / $root3,         false,],
            ['rgb(0, 0, 0)',        'rgb(7, 7, 0)',    10 / $root3,         true,],
            ['rgba(0, 0, 0, 1)',    'rgba(7, 7, 0, 1)', 9 / $root3,         false,],
            ['rgba(0, 0, 0, 1)',    'rgba(7, 7, 0, 1)',    10 / $root3,     true,],
            ['rgb(128, 128, 128)',  'rgb(128, 128, 120)',   7 / $root3,     false,],
            ['rgb(128, 128, 128)',  'rgb(128, 128, 120)',   8 / $root3,     true,],
            ['rgb(0, 0, 0)',        'rgb(255, 255, 255)',   254.9,          false,],
            ['rgb(0, 0, 0)',        'rgb(255, 255, 255)',   255,            true,],
            ['rgb(255, 0, 0)',      'rgb(0, 255, 255)',     254.9,          false,],
            ['rgb(255, 0, 0)',      'rgb(0, 255, 255)',     255,            true,],
            ['black',               'rgba(0, 0, 0)',        0.0,            true],
            ['black',               'rgba(10, 0, 0, 1.0)',  10.0 / $root3,  true],);

        $output = "<table width='100%' class='infoTable'><thead>
                <tr>
                <th>
                Color 1
                </th>
                <th>
                Color 2
                </th>
                <th>
                    Test distance * 255
                </th>
                <th>
                    Is within distance
                </th>
                </tr>
        </thead>";

        $output .= "<tbody>";

        foreach ($tests as $testInfo) {
            $color1 = $testInfo[0];
            $color2 = $testInfo[1];
            $distance = $testInfo[2];
            $expectation = $testInfo[3];
            $testDistance = ($distance / 255.0);

            $color1Pixel = new \ImagickPixel($color1);
            $color2Pixel = new \ImagickPixel($color2);

            $isSimilar = $color1Pixel->isPixelSimilar($color2Pixel, $testDistance);

            if ($isSimilar !== $expectation) {
                echo "Test distance failed. Color [$color1] compared to color [$color2] is not within distance $testDistance FAILED.".NL;
            }

            $layout = "<tr>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td style='text-align: center;'>%s</td>
            </tr>";

            $output .= sprintf(
                $layout,
                $color1,
                $color2,
                $distance,
                $isSimilar ? 'yes' : 'no'
            );
        }

        $output .= "</tbody></table>";

        return $output;

?>

ImagickPixel::isPixelSimilarQuantum
ImagickPixel::setColor
ImagickPixel


Sets the color

ImagickPixel::isSimilar
ImagickPixel::setColorCount
ImagickPixel
PHP Manual

ImagickPixel::setColor

(PECL imagick 2.0.0)

ImagickPixel::setColor — Sets the color

Descrierea

bool ImagickPixel::setColor ( string $color )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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.).

Parametri

color

The color definition to use in order to initialise the ImagickPixel object.

Valorile întoarse

Returns TRUE if the specified color was set, FALSE otherwise.

Exemple

Example #1 ImagickPixel::setColor()

<?php
function setColor() {
    $draw = new \ImagickDraw();

    $strokeColor = new \ImagickPixel('green');
    $fillColor = new \ImagickPixel();
    $fillColor->setColor('rgba(100%, 75%, 0%, 1.0)');

    $draw->setstrokewidth(3.0);
    $draw->setStrokeColor($strokeColor);
    $draw->setFillColor($fillColor);
    $draw->rectangle(200, 200, 300, 300);

    $image = new \Imagick();
    $image->newImage(500, 500, "SteelBlue2");
    $image->setImageFormat("png");

    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

ImagickPixel::isSimilar
ImagickPixel::setColorCount
ImagickPixel


Description

ImagickPixel::setColor
ImagickPixel::setColorValue
ImagickPixel
PHP Manual

ImagickPixel::setColorCount

(No version information available, might only be in Git)

ImagickPixel::setColorCount — Description

Descrierea

public void ImagickPixel::setcolorcount ( string $colorCount )

Sets the color count associated with this color.

Parametri

colorCount

Valorile întoarse

ImagickPixel::setColor
ImagickPixel::setColorValue
ImagickPixel


Sets the normalized value of one of the channels

ImagickPixel::setColorCount
ImagickPixel::setColorValueQuantum
ImagickPixel
PHP Manual

ImagickPixel::setColorValue

(PECL imagick 2.0.0)

ImagickPixel::setColorValue — Sets the normalized value of one of the channels

Descrierea

bool ImagickPixel::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 an ImagickPixel object.

Parametri

color

One of the Imagick color constants e.g. \Imagick::COLOR_GREEN or \Imagick::COLOR_ALPHA.

value

The value to set this channel to, ranging from 0 to 1.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Basic Imagick::setColorValue() usage

<?php

$color  = new \ImagickPixel('firebrick');

$color->setColorValue(Imagick::COLOR_ALPHA, 0.5);

print_r($color->getcolor(true));
?>

Exemplul de mai sus va afi?a:

Array
(
    [r] => 0.69803921568627
    [g] => 0.13333333333333
    [b] => 0.13333333333333
    [a] => 0.50000762951095
)

ImagickPixel::setColorCount
ImagickPixel::setColorValueQuantum
ImagickPixel


Description

ImagickPixel::setColorValue
ImagickPixel::setHSL
ImagickPixel
PHP Manual

ImagickPixel::setColorValueQuantum

(No version information available, might only be in Git)

ImagickPixel::setColorValueQuantum — Description

Descrierea

public void ImagickPixel::setColorValueQuantum ( int $color , mixed $value )

Sets the quantum value of a color element of the ImagickPixel.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

color

Which color element to set e.g. \Imagick::COLOR_GREEN.

value

The quantum value to set the color element to. This should be a float if ImageMagick was compiled with HDRI otherwise an int in the range 0 to Imagick::getQuantum().

Valorile întoarse

Exemple

Example #1 ImagickPixel::setColorValueQuantum()

<?php
function setColorValueQuantum() {
    $image = new \Imagick();

    $quantumRange = $image->getQuantumRange();

    $draw = new \ImagickDraw();
    $color = new \ImagickPixel('blue');
    $color->setcolorValueQuantum(\Imagick::COLOR_RED, 128 * $quantumRange['quantumRangeLong'] / 256);

    $draw->setstrokewidth(1.0);
    $draw->setStrokeColor($color);
    $draw->setFillColor($color);
    $draw->rectangle(200, 200, 300, 300);

    $image->newImage(500, 500, "SteelBlue2");
    $image->setImageFormat("png");

    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>

ImagickPixel::setColorValue
ImagickPixel::setHSL
ImagickPixel


Sets the normalized HSL color

ImagickPixel::setColorValueQuantum
ImagickPixel::setIndex
ImagickPixel
PHP Manual

ImagickPixel::setHSL

(PECL imagick 2.0.0)

ImagickPixel::setHSL — Sets the normalized HSL color

Descrierea

bool ImagickPixel::setHSL ( float $hue , float $saturation , float $luminosity )

Sets the color described by the ImagickPixel object using normalized values for hue, saturation and luminosity.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 Use ImagickPixel::setHSL() to modify a color

<?php

//Create an almost pure red color
$color = new ImagickPixel('rgb(90%, 10%, 10%)');

//Get it's HSL values
$colorInfo = $color->getHSL();

//Rotate the hue by 180 degrees
$newHue = $colorInfo['hue'] + 0.5;
if ($newHue > 1) {
    $newHue = $newHue - 1;
}

//Set the ImagickPixel to the new color
$colorInfo = $color->setHSL($newHue, $colorInfo['saturation'], $colorInfo['luminosity']);

//Check that the new color is blue/green
$colorInfo = $color->getcolor();
print_r($colorInfo);

?>

Exemplul de mai sus va afi?a:

Array
(
    [r] => 26
    [g] => 230
    [b] => 230
    [a] => 255
)

Note

Nota:

Available with ImageMagick library version 6.2.9 and higher.

ImagickPixel::setColorValueQuantum
ImagickPixel::setIndex
ImagickPixel


Description

ImagickPixel::setHSL
ImagickPixelIterator
ImagickPixel
PHP Manual

ImagickPixel::setIndex

(No version information available, might only be in Git)

ImagickPixel::setIndex — Description

Descrierea

public void ImagickPixel::setIndex ( int $index )

Sets the colormap index of the pixel wand.

Parametri

index

Valorile întoarse

ImagickPixel::setHSL
ImagickPixelIterator
ImagickPixel


The ImagickPixelIterator class

(PECL imagick 2.0.0)

Sinopsisul clasei

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 )
}

Cuprins

  • 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::setIndex
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

Descrierea

bool ImagickPixelIterator::clear ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Clear resources associated with a PixelIterator.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 ImagickPixelIterator::clear()

<?php
function clear($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));

    $imageIterator = $imagick->getPixelRegionIterator(100, 100, 250, 200);

    /* Loop through pixel rows */
    foreach ($imageIterator as $pixels) {
        /** @var $pixel \ImagickPixel */
        /* Loop through the pixels in the row (columns) */
        foreach ($pixels as $column => $pixel) {
            if ($column % 2) {
                /* Paint every second pixel black*/
                $pixel->setColor("rgba(0, 0, 0, 0)");
            }
        }
        /* Sync the iterator, this is important to do on each iteration */
        $imageIterator->syncIterator();
    }

    $imageIterator->clear();

    header("Content-Type: image/jpg");
    echo $imagick;
}

?>

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

Descrierea

ImagickPixelIterator::__construct ( Imagick $wand )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

The ImagickPixelIterator constructor

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 ImagickPixelIterator::construct()

<?php
function construct($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imageIterator = new \ImagickPixelIterator($imagick);

    /* Loop through pixel rows */
    foreach ($imageIterator as $pixels) {
        /* Loop through the pixels in the row (columns) */
        foreach ($pixels as $column => $pixel) {
            /** @var $pixel \ImagickPixel */
            if ($column % 2) {
                /* Paint every second pixel black*/
                $pixel->setColor("rgba(0, 0, 0, 0)");
            }
        }
        /* Sync the iterator, this is important to do on each iteration */
        $imageIterator->syncIterator();
    }

    header("Content-Type: image/jpg");
    echo $imagick;
}

?>

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

Descrierea

bool ImagickPixelIterator::destroy ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Deallocates resources associated with a PixelIterator.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

array ImagickPixelIterator::getCurrentIteratorRow ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the current row as an array of ImagickPixel objects from the pixel iterator.

Valorile întoarse

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

Descrierea

int ImagickPixelIterator::getIteratorRow ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the current pixel iterator row.

Valorile întoarse

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

Descrierea

array ImagickPixelIterator::getNextIteratorRow ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the next row as an array of pixel wands from the pixel iterator.

Valorile întoarse

Returns the next row as an array of ImagickPixel objects, throwing ImagickPixelIteratorException on error.

Exemple

Example #1 ImagickPixelIterator::getNextIteratorRow()

<?php
function getNextIteratorRow($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imageIterator = $imagick->getPixelIterator();

    $count = 0;
    while ($pixels = $imageIterator->getNextIteratorRow()) {
        if (($count % 3) == 0) {
            /* Loop through the pixels in the row (columns) */
            foreach ($pixels as $column => $pixel) {
                /** @var $pixel \ImagickPixel */
                if ($column % 2) {
                    /* Paint every second pixel black*/
                    $pixel->setColor("rgba(0, 0, 0, 0)");
                }
            }
            /* Sync the iterator, this is important to do on each iteration */
            $imageIterator->syncIterator();
        }

        $count += 1;
    }

    header("Content-Type: image/jpg");
    echo $imagick;
}

?>

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

Descrierea

array ImagickPixelIterator::getPreviousIteratorRow ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the previous row as an array of pixel wands from the pixel iterator.

Valorile întoarse

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

Descrierea

bool ImagickPixelIterator::newPixelIterator ( Imagick $wand )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns a new pixel iterator.

Valorile întoarse

Întoarce TRUE în caz de succes. 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

Descrierea

bool ImagickPixelIterator::newPixelRegionIterator ( Imagick $wand , int $x , int $y , int $columns , int $rows )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns a new pixel iterator.

Parametri

wand

x

y

columns

rows

Valorile întoarse

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

Descrierea

bool ImagickPixelIterator::resetIterator ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Resets the pixel iterator. Use it in conjunction with ImagickPixelIterator::getNextIteratorRow() to iterate over all the pixels in a pixel container.

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 ImagickPixelIterator::resetIterator()

<?php
function resetIterator($imagePath) {

    $imagick = new \Imagick(realpath($imagePath));

    $imageIterator = $imagick->getPixelIterator();

    /* Loop trough pixel rows */
    foreach ($imageIterator as $pixels) {
        /* Loop through the pixels in the row (columns) */
        foreach ($pixels as $column => $pixel) {
            /** @var $pixel \ImagickPixel */
            if ($column % 2) {

                /* Make every second pixel 25% red*/
                $pixel->setColorValue(\Imagick::COLOR_RED, 64);
            }
        }
        /* Sync the iterator, this is important to do on each iteration */
        $imageIterator->syncIterator();
    }

    $imageIterator->resetiterator();

    /* Loop trough pixel rows */
    foreach ($imageIterator as $pixels) {
        /* Loop through the pixels in the row (columns) */
        foreach ($pixels as $column => $pixel) {
            /** @var $pixel \ImagickPixel */
            if ($column % 3) {
                $pixel->setColorValue(\Imagick::COLOR_BLUE, 64); /* Make every second pixel a little blue*/
                //$pixel->setColor("rgba(0, 0, 128, 0)"); /* Paint every second pixel black*/
            }
        }
        $imageIterator->syncIterator(); /* Sync the iterator, this is important to do on each iteration */
    }

    $imageIterator->clear();

    header("Content-Type: image/jpg");
    echo $imagick;
}

?>

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

Descrierea

bool ImagickPixelIterator::setIteratorFirstRow ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the pixel iterator to the first pixel row.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool ImagickPixelIterator::setIteratorLastRow ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Sets the pixel iterator to the last pixel row.

Valorile întoarse

Întoarce TRUE în caz de succes.

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

Descrierea

bool ImagickPixelIterator::setIteratorRow ( int $row )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Set the pixel iterator row.

Parametri

row

Valorile întoarse

Întoarce TRUE în caz de succes.

Exemple

Example #1 ImagickPixelIterator::setIteratorRow()

<?php
function setIteratorRow($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imageIterator = $imagick->getPixelRegionIterator(200, 100, 200, 200);

    for ($x = 0; $x < 20; $x++) {
        $imageIterator->setIteratorRow($x * 5);
        $pixels = $imageIterator->getCurrentIteratorRow();
        /* Loop through the pixels in the row (columns) */
        foreach ($pixels as $pixel) {
            /** @var $pixel \ImagickPixel */
            /* Paint every second pixel black*/
            $pixel->setColor("rgba(0, 0, 0, 0)");
        }

        /* Sync the iterator, this is important to do on each iteration */
        $imageIterator->syncIterator();
    }

    header("Content-Type: image/jpg");
    echo $imagick;
}

?>

ImagickPixelIterator::setIteratorLastRow
ImagickPixelIterator::syncIterator
ImagickPixelIterator


Syncs the pixel iterator

ImagickPixelIterator::setIteratorRow
ImagickKernel
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::syncIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::syncIterator — Syncs the pixel iterator

Descrierea

bool ImagickPixelIterator::syncIterator ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Syncs the pixel iterator.

Valorile întoarse

Întoarce TRUE în caz de succes.

ImagickPixelIterator::setIteratorRow
ImagickKernel
ImagickPixelIterator


The ImagickKernel class

(PECL imagick >= 3.3.0)

Introducere

Sinopsisul clasei

ImagickKernel {
/* Metode */
public void addKernel ( ImagickKernel $ImagickKernel )
public void addUnityKernel ( void )
public static ImagickKernel fromBuiltin ( string $kernelType , string $kernelString )
public static ImagickKernel fromMatrix ( array $matrix [, array $origin ] )
public array getMatrix ( void )
public void scale ( void )
public array separate ( void )
}

Cuprins

  • ImagickKernel::addKernel — Description
  • ImagickKernel::addUnityKernel — Description
  • ImagickKernel::fromBuiltIn — Description
  • ImagickKernel::fromMatrix — Description
  • ImagickKernel::getMatrix — Description
  • ImagickKernel::scale — Description
  • ImagickKernel::separate — Description
ImagickPixelIterator::syncIterator
ImagickKernel::addKernel
ImageMagick


Description

ImagickKernel
ImagickKernel::addUnityKernel
ImagickKernel
PHP Manual

ImagickKernel::addKernel

(PECL imagick >= 3.3.0)

ImagickKernel::addKernel — Description

Descrierea

public void ImagickKernel::addKernel ( ImagickKernel $ImagickKernel )

Attach another kernel to this kernel to allow them to both be applied in a single morphology or filter function. Returns the new combined kernel.

Parametri

ImagickKernel

Valorile întoarse

Exemple

Example #1 ImagickKernel::addKernel()

<?php
function addKernel($imagePath) {
    $matrix1 = [
        [-1, -1, -1],
        [ 0,  0,  0],
        [ 1,  1,  1],
    ];

    $matrix2 = [
        [-1,  0,  1],
        [-1,  0,  1],
        [-1,  0,  1],
    ];

    $kernel1 = ImagickKernel::fromMatrix($matrix1);
    $kernel2 = ImagickKernel::fromMatrix($matrix2);
    $kernel1->addKernel($kernel2);

    $imagick = new \Imagick(realpath($imagePath));
    $imagick->filter($kernel1);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();

}

?>

ImagickKernel
ImagickKernel::addUnityKernel
ImagickKernel


Description

ImagickKernel::addKernel
ImagickKernel::fromBuiltIn
ImagickKernel
PHP Manual

ImagickKernel::addUnityKernel

(PECL imagick >= 3.3.0)

ImagickKernel::addUnityKernel — Description

Descrierea

public void ImagickKernel::addUnityKernel ( void )

Adds a given amount of the 'Unity' Convolution Kernel to the given pre-scaled and normalized Kernel. This in effect adds that amount of the original image into the resulting convolution kernel. The resulting effect is to convert the defined kernels into blended soft-blurs, unsharp kernels or into sharpening kernels.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #1 ImagickKernel::addUnityKernel()

<?php

    function renderKernelTable($matrix) {
        $output = "<table class='infoTable'>";

        foreach ($matrix as $row) {
            $output .= "<tr>";
            foreach ($row as $cell) {
                $output .= "<td style='text-align:left'>";
                if ($cell === false) {
                    $output .= "false";
                }
                else {
                    $output .= round($cell, 3);
                }
                $output .= "</td>";
            }
            $output .= "</tr>";
        }

        $output .= "</table>";

        return $output;
    }

    $matrix = [
        [-1, 0, -1],
        [ 0, 4,  0],
        [-1, 0, -1],
    ];

    $kernel = \ImagickKernel::fromMatrix($matrix);
    $kernel->scale(1, \Imagick::NORMALIZE_KERNEL_VALUE);
    $output = "Before adding unity kernel: <br/>";
    $output .= renderKernelTable($kernel->getMatrix());
    $kernel->addUnityKernel(0.5);
    $output .= "After adding unity kernel: <br/>";
    $output .= renderKernelTable($kernel->getMatrix());

    $kernel->scale(1, \Imagick::NORMALIZE_KERNEL_VALUE);
    $output .= "After renormalizing kernel: <br/>";
    $output .= renderKernelTable($kernel->getMatrix());

    echo $output;

?>

Example #2 ImagickKernel::addUnityKernel()

<?php
function addUnityKernel($imagePath) {

    $matrix = [
        [-1, 0, -1],
        [ 0, 4,  0],
        [-1, 0, -1],
    ];

    $kernel = ImagickKernel::fromMatrix($matrix);

    $kernel->scale(4, \Imagick::NORMALIZE_KERNEL_VALUE);
    $kernel->addUnityKernel(0.5);

    $imagick = new \Imagick(realpath($imagePath));
    $imagick->filter($kernel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();

}

?>

ImagickKernel::addKernel
ImagickKernel::fromBuiltIn
ImagickKernel


Description

ImagickKernel::addUnityKernel
ImagickKernel::fromMatrix
ImagickKernel
PHP Manual

ImagickKernel::fromBuiltIn

(PECL imagick >= 3.3.0)

ImagickKernel::fromBuiltIn — Description

Descrierea

public static ImagickKernel ImagickKernel::fromBuiltin ( string $kernelType , string $kernelString )

Create a kernel from a builtin in kernel. See http://www.imagemagick.org/Usage/morphology/#kernel for examples. Currently the 'rotation' symbols are not supported. Example: $diamondKernel = ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DIAMOND, "2");

Parametri

kerneltype

The type of kernel to build e.g. \Imagick::KERNEL_DIAMOND

kernelString

A string that describes the parameters e.g. "4,2.5"

Valorile întoarse

Exemple

Example #1 ImagickKernel::fromBuiltin()

<?php

function renderKernel(ImagickKernel $imagickKernel) {
    $matrix = $imagickKernel->getMatrix();

    $imageMargin = 20;

    $tileSize = 20;
    $tileSpace = 4;
    $shadowSigma = 4;
    $shadowDropX = 20;
    $shadowDropY = 0;

    $radius = ($tileSize / 2) * 0.9;

    $rows = count($matrix);
    $columns = count($matrix[0]);

    $imagickDraw = new \ImagickDraw();

    $imagickDraw->setFillColor('#afafaf');
    $imagickDraw->setStrokeColor('none');

    $imagickDraw->translate($imageMargin, $imageMargin);
    $imagickDraw->push();

    ksort($matrix);

    foreach ($matrix as $row) {
        ksort($row);
        $imagickDraw->push();
        foreach ($row as $cell) {
            if ($cell !== false) {
                $color = intval(255 * $cell);
                $colorString = sprintf("rgb(%f, %f, %f)", $color, $color, $color);
                $imagickDraw->setFillColor($colorString);
                $imagickDraw->rectangle(0, 0, $tileSize, $tileSize);
            }
            $imagickDraw->translate(($tileSize + $tileSpace), 0);
        }
        $imagickDraw->pop();
        $imagickDraw->translate(0, ($tileSize + $tileSpace));
    }

    $imagickDraw->pop();

    $width = ($columns * $tileSize) + (($columns - 1) * $tileSpace);
    $height = ($rows * $tileSize) + (($rows - 1) * $tileSpace);

    $imagickDraw->push();
    $imagickDraw->translate($width/2 , $height/2);
    $imagickDraw->setFillColor('rgba(0, 0, 0, 0)');
    $imagickDraw->setStrokeColor('white');
    $imagickDraw->circle(0, 0, $radius - 1, 0);
    $imagickDraw->setStrokeColor('black');
    $imagickDraw->circle(0, 0, $radius, 0);
    $imagickDraw->pop();

    $canvasWidth = $width + (2 * $imageMargin);
    $canvasHeight = $height + (2 * $imageMargin);

    $kernel = new \Imagick();
    $kernel->newPseudoImage(
        $canvasWidth,
        $canvasHeight,
        'canvas:none'
    );

    $kernel->setImageFormat('png');
    $kernel->drawImage($imagickDraw);

    /* create drop shadow on it's own layer */
    $canvas = $kernel->clone();
    $canvas->setImageBackgroundColor(new \ImagickPixel('rgb(0, 0, 0)'));
    $canvas->shadowImage(100, $shadowSigma, $shadowDropX, $shadowDropY);

    $canvas->setImagePage($canvasWidth, $canvasHeight, -5, -5);
    $canvas->cropImage($canvasWidth, $canvasHeight, 0, 0);

    /* composite original text_layer onto shadow_layer */
    $canvas->compositeImage($kernel, \Imagick::COMPOSITE_OVER, 0, 0);
    $canvas->setImageFormat('png');

    return $canvas;
}

function createFromBuiltin($kernelType, $kernelFirstTerm, $kernelSecondTerm, $kernelThirdTerm) {
    $string = '';

    if ($kernelFirstTerm != false && strlen(trim($kernelFirstTerm)) != 0) {
        $string .= $kernelFirstTerm;

        if ($kernelSecondTerm != false && strlen(trim($kernelSecondTerm)) != 0) {
            $string .= ','.$kernelSecondTerm;
            if ($kernelThirdTerm != false && strlen(trim($kernelThirdTerm)) != 0) {
                $string .= ','.$kernelThirdTerm;
            }
        }
    }

    $kernel = ImagickKernel::fromBuiltIn(
        $kernelType,
        $string
    );

    return $kernel;
}

function fromBuiltin($kernelType, $kernelFirstTerm, $kernelSecondTerm, $kernelThirdTerm) {
    $diamondKernel = createFromBuiltin($kernelType, $kernelFirstTerm, $kernelSecondTerm, $kernelThirdTerm);
    $imagick = renderKernel($diamondKernel);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

fromBuiltin(\Imagick::KERNEL_DIAMOND, 2, false, false);

?>

ImagickKernel::addUnityKernel
ImagickKernel::fromMatrix
ImagickKernel


Description

ImagickKernel::fromBuiltIn
ImagickKernel::getMatrix
ImagickKernel
PHP Manual

ImagickKernel::fromMatrix

(PECL imagick >= 3.3.0)

ImagickKernel::fromMatrix — Description

Descrierea

public static ImagickKernel ImagickKernel::fromMatrix ( array $matrix [, array $origin ] )

Create a kernel from an 2d matrix of values. Each value should either be a float (if the element should be used) or 'false' if the element should be skipped. For matrices that are odd sizes in both dimensions the the origin pixel will default to the centre of the kernel. For all other kernel sizes the origin pixel must be specified.

Parametri

array

A matrix (i.e. 2d array) of values that define the kernel. Each element should be either a float value, or FALSE if that element shouldn't be used by the kernel.

array

Which element of the kernel should be used as the origin pixel. e.g. For a 3x3 matrix specifying the origin as [2, 2] would specify that the bottom right element should be the origin pixel.

Valorile întoarse

The generated ImagickKernel.

Exemple

Example #1 ImagickKernel::fromMatrix()

<?php

function renderKernel(ImagickKernel $imagickKernel) {
    $matrix = $imagickKernel->getMatrix();

    $imageMargin = 20;

    $tileSize = 20;
    $tileSpace = 4;
    $shadowSigma = 4;
    $shadowDropX = 20;
    $shadowDropY = 0;

    $radius = ($tileSize / 2) * 0.9;

    $rows = count($matrix);
    $columns = count($matrix[0]);

    $imagickDraw = new \ImagickDraw();

    $imagickDraw->setFillColor('#afafaf');
    $imagickDraw->setStrokeColor('none');

    $imagickDraw->translate($imageMargin, $imageMargin);
    $imagickDraw->push();

    ksort($matrix);

    foreach ($matrix as $row) {
        ksort($row);
        $imagickDraw->push();
        foreach ($row as $cell) {
            if ($cell !== false) {
                $color = intval(255 * $cell);
                $colorString = sprintf("rgb(%f, %f, %f)", $color, $color, $color);
                $imagickDraw->setFillColor($colorString);
                $imagickDraw->rectangle(0, 0, $tileSize, $tileSize);
            }
            $imagickDraw->translate(($tileSize + $tileSpace), 0);
        }
        $imagickDraw->pop();
        $imagickDraw->translate(0, ($tileSize + $tileSpace));
    }

    $imagickDraw->pop();

    $width = ($columns * $tileSize) + (($columns - 1) * $tileSpace);
    $height = ($rows * $tileSize) + (($rows - 1) * $tileSpace);

    $imagickDraw->push();
    $imagickDraw->translate($width/2 , $height/2);
    $imagickDraw->setFillColor('rgba(0, 0, 0, 0)');
    $imagickDraw->setStrokeColor('white');
    $imagickDraw->circle(0, 0, $radius - 1, 0);
    $imagickDraw->setStrokeColor('black');
    $imagickDraw->circle(0, 0, $radius, 0);
    $imagickDraw->pop();

    $canvasWidth = $width + (2 * $imageMargin);
    $canvasHeight = $height + (2 * $imageMargin);

    $kernel = new \Imagick();
    $kernel->newPseudoImage(
        $canvasWidth,
        $canvasHeight,
        'canvas:none'
    );

    $kernel->setImageFormat('png');
    $kernel->drawImage($imagickDraw);

    /* create drop shadow on it's own layer */
    $canvas = $kernel->clone();
    $canvas->setImageBackgroundColor(new \ImagickPixel('rgb(0, 0, 0)'));
    $canvas->shadowImage(100, $shadowSigma, $shadowDropX, $shadowDropY);

    $canvas->setImagePage($canvasWidth, $canvasHeight, -5, -5);
    $canvas->cropImage($canvasWidth, $canvasHeight, 0, 0);

    /* composite original text_layer onto shadow_layer */
    $canvas->compositeImage($kernel, \Imagick::COMPOSITE_OVER, 0, 0);
    $canvas->setImageFormat('png');

    return $canvas;
}

function createFromMatrix() {
    $matrix = [
        [0.5, 0, 0.2],
        [0, 1, 0],
        [0.9, 0, false],
    ];

    $kernel = \ImagickKernel::fromMatrix($matrix);

    return $kernel;
}

function fromMatrix() {
    $kernel = createFromMatrix();
    $imagick = renderKernel($kernel);

    header("Content-Type: image/png");
    echo $imagick->getImageBlob();
}

?>

ImagickKernel::fromBuiltIn
ImagickKernel::getMatrix
ImagickKernel


Description

ImagickKernel::fromMatrix
ImagickKernel::scale
ImagickKernel
PHP Manual

ImagickKernel::getMatrix

(PECL imagick >= 3.3.0)

ImagickKernel::getMatrix — Description

Descrierea

public array ImagickKernel::getMatrix ( void )

Get the 2d matrix of values used in this kernel. The elements are either float for elements that are used or 'false' if the element should be skipped.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A matrix (2d array) of the values that represent the kernel.

Exemple

Example #1 ImagickKernel::getMatrix()

<?php

function renderKernelTable($matrix) {
    $output = "<table class='infoTable'>";

    foreach ($matrix as $row) {
        $output .= "<tr>";
        foreach ($row as $cell) {
            $output .= "<td style='text-align:left'>";
            if ($cell === false) {
                $output .= "false";
            }
            else {
                $output .= round($cell, 3);
            }
            $output .= "</td>";
        }
        $output .= "</tr>";
    }

    $output .= "</table>";

    return $output;
}

    $output = "The built-in kernel name 'ring' with parameters of '2,3.5':<br/>";
    $kernel = \ImagickKernel::fromBuiltIn(
        \Imagick::KERNEL_RING,
        "2,3.5"
    );
    $matrix = $kernel->getMatrix();
    $output .= renderKernelTable($matrix);

    echo $output;

?>

ImagickKernel::fromMatrix
ImagickKernel::scale
ImagickKernel


Description

ImagickKernel::getMatrix
ImagickKernel::separate
ImagickKernel
PHP Manual

ImagickKernel::scale

(PECL imagick >= 3.3.0)

ImagickKernel::scale — Description

Descrierea

public void ImagickKernel::scale ( void )

ScaleKernelInfo() scales the given kernel list by the given amount, with or without normalization of the sum of the kernel values (as per given flags). The exact behaviour of this function depends on the normalization type being used please see http://www.imagemagick.org/api/morphology.php#ScaleKernelInfo for details. Flag should be one of Imagick::NORMALIZE_KERNEL_VALUE, Imagick::NORMALIZE_KERNEL_CORRELATE, Imagick::NORMALIZE_KERNEL_PERCENT or not set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #1 ImagickKernel::scale()

<?php

    function renderKernelTable($matrix) {
        $output = "<table class='infoTable'>";

        foreach ($matrix as $row) {
            $output .= "<tr>";
            foreach ($row as $cell) {
                $output .= "<td style='text-align:left'>";
                if ($cell === false) {
                    $output .= "false";
                }
                else {
                    $output .= round($cell, 3);
                }
                $output .= "</td>";
            }
            $output .= "</tr>";
        }

        $output .= "</table>";

        return $output;
    }

    $output = "";

    $matrix = [
        [-1, 0, -1],
        [ 0, 4,  0],
        [-1, 0, -1],
    ];

    $kernel = \ImagickKernel::fromMatrix($matrix);
    $kernelClone = clone $kernel;

    $output .= "Start kernel<br/>";
    $output .= renderKernelTable($kernel->getMatrix());

    $output .= "Scaling with NORMALIZE_KERNEL_VALUE. The  <br/>";
    $kernel->scale(2, \Imagick::NORMALIZE_KERNEL_VALUE);
    $output .= renderKernelTable($kernel->getMatrix());

    $kernel = clone $kernelClone;
    $output .= "Scaling by percent<br/>";
    $kernel->scale(2, \Imagick::NORMALIZE_KERNEL_PERCENT);
    $output .= renderKernelTable($kernel->getMatrix());

    $matrix2 = [
        [-1, -1, 1],
        [ -1, false,  1],
        [1, 1, 1],
    ];

    $kernel = \ImagickKernel::fromMatrix($matrix2);
    $output .= "Scaling by correlate<br/>";
    $kernel->scale(1, \Imagick::NORMALIZE_KERNEL_CORRELATE);
    $output .= renderKernelTable($kernel->getMatrix());

    return $output;
?>

ImagickKernel::getMatrix
ImagickKernel::separate
ImagickKernel


Description

ImagickKernel::scale
Extensii referitoare la po?ta electronica
ImagickKernel
PHP Manual

ImagickKernel::separate

(PECL imagick >= 3.3.0)

ImagickKernel::separate — Description

Descrierea

public array ImagickKernel::separate ( void )

Separates a linked set of kernels and returns an array of ImagickKernels.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #1 ImagickKernel::separate()

<?php

    function renderKernelTable($matrix) {

        $output = "<table class='infoTable'>";
        foreach ($matrix as $row) {
            $output .= "<tr>";
            foreach ($row as $cell) {
                $output .= "<td style='text-align:left'>";
                if ($cell === false) {
                    $output .= "false";
                }
                else {
                    $output .= round($cell, 3);
                }
                $output .= "</td>";
            }
            $output .= "</tr>";
        }

        $output .= "</table>";

        return $output;
    }

    $matrix = [
        [-1, 0, -1],
        [ 0, 4,  0],
        [-1, 0, -1],
    ];

    $kernel = \ImagickKernel::fromMatrix($matrix);
    $kernel->scale(4, \Imagick::NORMALIZE_KERNEL_VALUE);
    $diamondKernel = \ImagickKernel::fromBuiltIn(
        \Imagick::KERNEL_DIAMOND,
        "2"
    );

    $kernel->addKernel($diamondKernel);

    $kernelList = $kernel->separate();

    $output = '';
    $count = 0;
    foreach ($kernelList as $kernel) {
        $output .= "<br/>Kernel $count<br/>";
        $output .= renderKernelTable($kernel->getMatrix());
        $count++;
    }

    return $output;

?>

ImagickKernel::scale
Extensii referitoare la po?ta electronica
ImagickKernel


Extensii referitoare la po?ta electronica

  • Cyrus — Administrarea Cyrus IMAP
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Cyrus
  • IMAP — IMAP, POP3 ?i NNTP
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii IMAP
  • Po?ta
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii de po?ta
  • Mailparse
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii de prelucrare a po?tei
  • vpopmail
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii vpopmail
ImagickKernel::separate
Cyrus
Informa?ii de referin?a despre func?ii


Administrarea Cyrus IMAP

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Cyrus
    • 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 ...
Extensii referitoare la po?ta electronica
Introducere
Extensii referitoare la po?ta electronica


Introducere

Nota: Aceasta extensie nu este disponibila pe platformele Windows.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.0.0.

Cyrus
Instalarea / configurarea
Cyrus


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Cyrus


Instalarea

Pentru a activa sus?inerea Cyrus IMAP ?i a utiliza aceste func?ii este necesar de a compila PHP cu op?iunea --with-cyrus .

Avertizare

Extensiile IMAP, recode, YAZ ?i Cyrus nu pot fi utilizate împreuna, deoarece ele utilizeaza acelea?i simboluri interne. Nota: Yaz 2.0 ?i ulterior nu manifesta aceasta problema

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

This extension defines a Cyrus IMAP connection identifier returned by cyrus_connect().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

CYRUS_CONN_NONSYNCLITERAL (integer)
CYRUS_CONN_INITIALRESPONSE (integer)
CYRUS_CALLBACK_NUMBERED (integer)
CYRUS_CALLBACK_NOLITERAL (integer)
Tipurile resurselor
Func?ii Cyrus
Cyrus


Func?ii Cyrus

Cuprins

  • 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 ...
Constante predefinite
cyrus_authenticate
Cyrus


Authenticate against a Cyrus IMAP server

Func?ii Cyrus
cyrus_bind
Func?ii Cyrus
PHP Manual

cyrus_authenticate

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_authenticate — Authenticate against a Cyrus IMAP server

Descrierea

void cyrus_authenticate ( resource $connection [, string $mechlist [, string $service [, string $user [, int $minssf [, int $maxssf [, string $authname [, string $password ]]]]]]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

Func?ii Cyrus
cyrus_bind
Func?ii Cyrus


Bind callbacks to a Cyrus IMAP connection

cyrus_authenticate
cyrus_close
Func?ii Cyrus
PHP Manual

cyrus_bind

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_bind — Bind callbacks to a Cyrus IMAP connection

Descrierea

bool cyrus_bind ( resource $connection , array $callbacks )

Binds callbacks to a Cyrus IMAP connection.

Parametri

connection

The connection handle.

callbacks

An array of callbacks.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

cyrus_authenticate
cyrus_close
Func?ii Cyrus


Close connection to a Cyrus IMAP server

cyrus_bind
cyrus_connect
Func?ii Cyrus
PHP Manual

cyrus_close

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_close — Close connection to a Cyrus IMAP server

Descrierea

bool cyrus_close ( resource $connection )

Closes the connection to a Cyrus IMAP server.

Parametri

connection

The connection handle.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

cyrus_bind
cyrus_connect
Func?ii Cyrus


Connect to a Cyrus IMAP server

cyrus_close
cyrus_query
Func?ii Cyrus
PHP Manual

cyrus_connect

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_connect — Connect to a Cyrus IMAP server

Descrierea

resource cyrus_connect ([ string $host [, string $port [, int $flags ]]] )

Connects to a Cyrus IMAP server.

Parametri

host

The Cyrus IMAP host name.

port

The port number.

flags

Valorile întoarse

Returns a connection handler on success sau FALSE în cazul e?ecului.

cyrus_close
cyrus_query
Func?ii Cyrus


Send a query to a Cyrus IMAP server

cyrus_connect
cyrus_unbind
Func?ii Cyrus
PHP Manual

cyrus_query

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_query — Send a query to a Cyrus IMAP server

Descrierea

array cyrus_query ( resource $connection , string $query )

Sends a query to a Cyrus IMAP server.

Parametri

connection

The connection handle.

query

The query string.

Valorile întoarse

Returns an associative array with the following keys: text, msgno, and keyword.

cyrus_connect
cyrus_unbind
Func?ii Cyrus


Unbind ...

cyrus_query
IMAP
Func?ii Cyrus
PHP Manual

cyrus_unbind

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_unbind — Unbind ...

Descrierea

bool cyrus_unbind ( resource $connection , string $trigger_name )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

connection

The connection handle.

trigger_name

The trigger name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

cyrus_query
IMAP
Func?ii Cyrus


IMAP, POP3 ?i NNTP

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii IMAP
    • imap_8bit — Converte?te un string "8bit" într-un string "quoted-printable"
    • imap_alerts — Întoarce toate mesajele de alerta IMAP care au avut loc
    • 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 — Pseudonim pentru 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 occurred
    • 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 — Pseudonim pentru 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 — Pseudonim pentru 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 — Pseudonim pentru imap_list
    • imap_listscan — Returns the list of mailboxes that matches the given text
    • imap_listsubscribed — Pseudonim pentru 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 — Pseudonim pentru 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 — Pseudonim pentru imap_listscan
    • imap_scanmailbox — Pseudonim pentru 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 given 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
Introducere
Extensii referitoare la po?ta electronica


Introducere

Aceste func?ii va permit sa opera?i cu protocolul IMAP, precum ?i cu metodele de accesare a cutiilor po?tale locale ?i prin NNTP, POP3.

Va aten?ionam însa ca unele func?ii IMAP nu vor func?iona corect cu protocolul POP.

IMAP
Instalarea / configurarea
IMAP


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
IMAP


Necesita?i

Aceasta extensie necesita instalarea bibliotecii c-client. Ob?ine?i ultima versiune de la » ftp://ftp.cac.washington.edu/imap/ ?i compila?i-o.

Este important sa nu copia?i fi?ierele-sursa IMAP direct în directorul de includeri de sistem, deoarece pot aparea conflicte. În loc, crea?i un nou director în interiorul directorului de includeri de sistem, cum ar fi de exemplu /usr/local/imap-2000b/ (amplasarea ?i denumirea depind de setarile dumneavoastra ?i de versiunea IMAP), ?i în interiorul acestui nou director crea?i directoare suplimentare denumite lib/ ?i include/. Din directorul c-client din arborele cu sursele IMAP copia?i toate fi?ierele *.h în include/ ?i toate fi?ierele *.c în lib/. Suplimentar, când a?i compilat IMAP, a fost creat un fi?ier cu denumirea c-client.a. De asemenea pune?i-l în directorul lib/, dar redenumi?i-l în libc-client.a.

Nota:

Pentru a asambla biblioteca c-client cu sus?inerea SSL ?i/sau Kerberos citi?i documenta?ia furnizata cu pachetul.

Nota: În Mandrake Linux, biblioteca IMAP (libc-client.a) este compilata fara sus?inerea Kerberos. O versiune separata cu SSL (client-PHP4.a) este instalata. Biblioteca trebuie sa fie recompilata pentru a adauga sus?inerea Kerberos.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Pentru ca aceste func?ii sa lucreze, trebuie sa compila?i PHP cu op?iunea --with-imap[=DIR] , unde DIR este prefixul caii unde a fost instalat c-client. Cu exemplul de mai sus, ve?i folosi --with-imap=/usr/local/imap-2000b . Aceasta loca?ie depinde de locul unde a?i creat acest director, conform descrierii anterioare. Utilizatorii Windows pot include biblioteca DLL php_imap.dll în php.ini.

IMAP nu este sus?inut pe sisteme mai vechi de Windows 2000. Aceasta se datoreaza faptului ca el utilizeaza func?ii de criptare pentru a permite conexiuni SSL la serverele de po?ta.

Nota: În dependen?a de configurarea c-client, posibil va trebui sa adauga?i --with-imap-ssl=/path/to/openssl/ ?i/sau --with-kerberos=/path/to/kerberos la linia de configurare PHP.

Avertizare

Extensiile IMAP, recode, YAZ ?i Cyrus nu pot fi utilizate împreuna, deoarece ele utilizeaza acelea?i simboluri interne. Nota: Yaz 2.0 ?i ulterior nu manifesta aceasta problema

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

NIL (integer)
OP_DEBUG (integer)
OP_READONLY (integer)
Deschide cutia po?tala numai pentru citire
OP_ANONYMOUS (integer)
Nu utiliza sau reînnoi .newsrcpentru nouta?i (numai NNTP)
OP_SHORTCACHE (integer)
OP_SILENT (integer)
OP_PROTOTYPE (integer)
OP_HALFOPEN (integer)
Pentru nume IMAP ?i NNTP deschide o conexiune, dar nu deschide o cutie po?tala.
OP_EXPUNGE (integer)
OP_SECURE (integer)
CL_EXPUNGE (integer)
?terge silen?ios cutia po?tala înainte de a o închide la apelul imap_close()
FT_UID (integer)
Parametrul este un UID
FT_PEEK (integer)
Nu stabili fanionul \Seen daca nu este de acum stabilit
FT_NOT (integer)
FT_INTERNAL (integer)
?irul întors este în format intern, nu va fi transformat canonic în CRLF.
FT_PREFETCHTEXT (integer)
ST_UID (integer)
Argumentul secven?ei con?ine UID-uri în loc de numere de secven?a
ST_SILENT (integer)
ST_SET (integer)
CP_UID (integer)
numerele de secven?a con?in UID-uri
CP_MOVE (integer)
Elimina mesajul din cutia po?tala curenta dupa copierea cu imap_mail_copy()
SE_UID (integer)
Întoarce UID-uri în loc de numere de secven?a
SE_FREE (integer)
SE_NOPREFETCH (integer)
Nu încarca anticipat mesajele cautate
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)
Aceasta cutie po?tala nu are "descenden?i" (nu sunt cutii po?tale mai jos de aceasta).
LATT_NOSELECT (integer)
Acesta este doar un container, nu o cutie po?tala - nu îl pute?i deschide.
LATT_MARKED (integer)
Aceassta cutie po?tala este marcata. Utilizat numai de UW-IMAPD.
LATT_UNMARKED (integer)
Aceassta cutie po?tala nu este marcata. Utilizat numai de UW-IMAPD.
SORTDATE (integer)
Criteriul de sortare pentru imap_sort(): data mesajului
SORTARRIVAL (integer)
Criteriul de sortare pentru imap_sort(): data sosirii
SORTFROM (integer)
Criteriul de sortare pentru imap_sort(): cutia po?tala din prima adresa a expeditorului
SORTSUBJECT (integer)
Criteriul de sortare pentru imap_sort(): subiectul mesajului
SORTTO (integer)
Criteriul de sortare pentru imap_sort(): cutia po?tala în prima adresa a destinatarului
SORTCC (integer)
Criteriul de sortare pentru imap_sort(): cutia po?tala din prima adresa cc
SORTSIZE (integer)
Criteriul de sortare pentru imap_sort(): dimensiunea mesajului în octe?i
TYPETEXT (integer)
Tipul primar al corpului: text neformatat
TYPEMULTIPART (integer)
Tipul primar al corpului: parte multipla
TYPEMESSAGE (integer)
Tipul primar al corpului: masaj încapsulat
TYPEAPPLICATION (integer)
Tipul primar al corpului: date ale aplica?iei
TYPEAUDIO (integer)
Tipul primar al corpului: audio
TYPEIMAGE (integer)
Tipul primar al corpului: imagine statica
TYPEVIDEO (integer)
Tipul primar al corpului: video
TYPEMODEL (integer)
Tipul primar al corpului: model
TYPEOTHER (integer)
Tipul primar al corpului: necunoscut
ENC7BIT (integer)
Codificarea corpului: date semantice SNMP pe 7 bi?i
ENC8BIT (integer)
Codificarea corpului: date semantice SNMP pe 8 bi?i
ENCBINARY (integer)
Codificarea corpului: date binare pe 8 bi?i
ENCBASE64 (integer)
Codificarea corpului: date codificate în base-64
ENCQUOTEDPRINTABLE (integer)
Codificarea corpului: date ce pot fi citite de om pe 8bi?i afi?ate în 7 bi?i
ENCOTHER (integer)
Codificarea corpului: necunoscuta
IMAP_OPENTIMEOUT (integer)
IMAP_READTIMEOUT (integer)
IMAP_WRITETIMEOUT (integer)
IMAP_CLOSETIMEOUT (integer)
LATT_REFERRAL (integer)
LATT_HASCHILDREN (integer)
LATT_HASNOCHILDREN (integer)
IMAP_GC_ELT (integer)
Colectorul gunoiului, cura?a elementele de cache ale mesajului.
IMAP_GC_ENV (integer)
Colectorul gunoiului, cura?a plicurile ?i corpurile.
IMAP_GC_TEXTS (integer)
Colectorul gunoiului, cura?a textele.
Tipurile resurselor
Func?ii IMAP
IMAP


Func?ii IMAP

A se vedea ?i

Acest document nu poate cuprinde toate amanuntele subiectelor atinse de func?iile date. Informa?ii suplimentare sunt oferite de documenta?ia codului-sursa al bibliotecii c-client (docs/internal.txt) ?i de utmatoarele documente RFC:

  • » 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).
O privire generala de detaliu este disponibila în car?ile » Programming Internet Email de David Wood ?i » Managing IMAP de Dianna Mullet & Kevin Mullet.

Cuprins

  • imap_8bit — Converte?te un string "8bit" într-un string "quoted-printable"
  • imap_alerts — Întoarce toate mesajele de alerta IMAP care au avut loc
  • 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 — Pseudonim pentru 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 occurred
  • 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 — Pseudonim pentru 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 — Pseudonim pentru 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 — Pseudonim pentru imap_list
  • imap_listscan — Returns the list of mailboxes that matches the given text
  • imap_listsubscribed — Pseudonim pentru 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 — Pseudonim pentru 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 — Pseudonim pentru imap_listscan
  • imap_scanmailbox — Pseudonim pentru 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 given 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
Constante predefinite
imap_8bit
IMAP


Converte?te un string "8bit" într-un string "quoted-printable"

Func?ii IMAP
imap_alerts
Func?ii IMAP
PHP Manual

imap_8bit

(PHP 4, PHP 5, PHP 7)

imap_8bit — Converte?te un string "8bit" într-un string "quoted-printable"

Descrierea

string imap_8bit ( string $string )

Converte?te un string "8bit" într-un string "quoted-printable" (în conformitate cu » RFC2045, section 6.7).

Parametri

string

String-ul "8bit" de convertit

Valorile întoarse

Întoarce un string "quoted-printable".

A se vedea ?i

  • imap_qprint() - Convert a quoted-printable string to an 8 bit string

Func?ii IMAP
imap_alerts
Func?ii IMAP


Întoarce toate mesajele de alerta IMAP care au avut loc

imap_8bit
imap_append
Func?ii IMAP
PHP Manual

imap_alerts

(PHP 4, PHP 5, PHP 7)

imap_alerts — Întoarce toate mesajele de alerta IMAP care au avut loc

Descrierea

array imap_alerts ( void )

Întoarce toate mesajele de alerta IMAP generate dupa ultimul apel al func?iei imap_alerts(), sau începutul paginii.

Când imap_alerts() este apelata, stiva alertelor este mai apoi cura?ita. Specifica?ia IMAP stabile?te ca aceste mesaje sa fie transmise utilizatorului.

Valorile întoarse

Întoarce un tablou cu toate mesajele de alerta IMAP generate sau FALSE daca nu este disponibil nici un mesaj de alerta.

A se vedea ?i

  • imap_errors() - Returns all of the IMAP errors that have occurred

imap_8bit
imap_append
Func?ii IMAP


Append a string message to a specified mailbox

imap_alerts
imap_base64
Func?ii IMAP
PHP Manual

imap_append

(PHP 4, PHP 5, PHP 7)

imap_append — Append a string message to a specified mailbox

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.2 | Added INTERNALDATE support to imap_append.

Exemple

Example #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
Func?ii IMAP


Decode BASE64 encoded text

imap_append
imap_binary
Func?ii IMAP
PHP Manual

imap_base64

(PHP 4, PHP 5, PHP 7)

imap_base64 — Decode BASE64 encoded text

Descrierea

string imap_base64 ( string $text )

Decodes the given BASE-64 encoded text.

Parametri

text

The encoded text

Valorile întoarse

Returns the decoded message as a string.

A se vedea ?i

  • imap_binary() - Convert an 8bit string to a base64 string
  • base64_encode() - Encodes data with MIME base64
  • base64_decode() - Decodes data encoded with MIME base64
  • » RFC2045, Section 6.8

imap_append
imap_binary
Func?ii IMAP


Convert an 8bit string to a base64 string

imap_base64
imap_body
Func?ii IMAP
PHP Manual

imap_binary

(PHP 4, PHP 5, PHP 7)

imap_binary — Convert an 8bit string to a base64 string

Descrierea

string imap_binary ( string $string )

Convert an 8bit string to a base64 string according to » RFC2045, Section 6.8.

Parametri

string

The 8bit string

Valorile întoarse

Returns a base64 encoded string.

A se vedea ?i

  • imap_base64() - Decode BASE64 encoded text

imap_base64
imap_body
Func?ii IMAP


Read the message body

imap_binary
imap_bodystruct
Func?ii IMAP
PHP Manual

imap_body

(PHP 4, PHP 5, PHP 7)

imap_body — Read the message body

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de 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.

Valorile întoarse

Returns the body of the specified message, as a string.

imap_binary
imap_bodystruct
Func?ii IMAP


Read the structure of a specified body section of a specific message

imap_body
imap_check
Func?ii IMAP
PHP Manual

imap_bodystruct

(PHP 4, PHP 5, PHP 7)

imap_bodystruct — Read the structure of a specified body section of a specific message

Descrierea

object imap_bodystruct ( resource $imap_stream , int $msg_number , string $section )

Read the structure of a specified body section of a specific message.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

msg_number

The message number

section

The body section to read

Valorile întoarse

Returns the information in an object, for a detailed description of the object structure and properties see imap_fetchstructure().

A se vedea ?i

  • imap_fetchstructure() - Read the structure of a particular message

imap_body
imap_check
Func?ii IMAP


Check current mailbox

imap_bodystruct
imap_clearflag_full
Func?ii IMAP
PHP Manual

imap_check

(PHP 4, PHP 5, PHP 7)

imap_check — Check current mailbox

Descrierea

object imap_check ( resource $imap_stream )

Checks information about the current mailbox.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

Valorile întoarse

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.

Exemple

Example #1 imap_check() example

<?php

$imap_obj = imap_check($imap_stream);
var_dump($imap_obj);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
Func?ii IMAP


Clears flags on messages

imap_check
imap_close
Func?ii IMAP
PHP Manual

imap_clearflag_full

(PHP 4, PHP 5, PHP 7)

imap_clearflag_full — Clears flags on messages

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de 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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • imap_setflag_full() - Sets flags on messages

imap_check
imap_close
Func?ii IMAP


Close an IMAP stream

imap_clearflag_full
imap_create
Func?ii IMAP
PHP Manual

imap_close

(PHP 4, PHP 5, PHP 7)

imap_close — Close an IMAP stream

Descrierea

bool imap_close ( resource $imap_stream [, int $flag = 0 ] )

Closes the imap stream.

Parametri

imap_stream

Un flux IMAP întors de 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()

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • imap_open() - Open an IMAP stream to a mailbox

imap_clearflag_full
imap_create
Func?ii IMAP


Pseudonim pentru imap_createmailbox

imap_close
imap_createmailbox
Func?ii IMAP
PHP Manual

imap_create

(PHP 4, PHP 5, PHP 7)

imap_create — Pseudonim pentru imap_createmailbox()

Descrierea

Aceasta func?ie este pseudonim pentru: imap_createmailbox().

imap_close
imap_createmailbox
Func?ii IMAP


Create a new mailbox

imap_create
imap_delete
Func?ii IMAP
PHP Manual

imap_createmailbox

(PHP 4, PHP 5, PHP 7)

imap_createmailbox — Create a new mailbox

Descrierea

bool imap_createmailbox ( resource $imap_stream , string $mailbox )

Creates a new mailbox specified by mailbox.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

mailbox

The mailbox name, see imap_open() for more information. Names containing international characters should be encoded by imap_utf7_encode()

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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 finally 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);
?>

A se vedea ?i

  • imap_renamemailbox() - Rename an old mailbox to new mailbox
  • imap_deletemailbox() - Delete a mailbox

imap_create
imap_delete
Func?ii IMAP


Mark a message for deletion from current mailbox

imap_createmailbox
imap_deletemailbox
Func?ii IMAP
PHP Manual

imap_delete

(PHP 4, PHP 5, PHP 7)

imap_delete — Mark a message for deletion from current mailbox

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de 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.

Valorile întoarse

Returns TRUE.

Exemple

Example #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);
?>

Note

Nota:

IMAP mailboxes may not have their message flags saved between connections, so imap_expunge() should be called during the same connection in order to guarantee that messages marked for deletion will actually be purged.

A se vedea ?i

  • 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
Func?ii IMAP


Delete a mailbox

imap_delete
imap_errors
Func?ii IMAP
PHP Manual

imap_deletemailbox

(PHP 4, PHP 5, PHP 7)

imap_deletemailbox — Delete a mailbox

Descrierea

bool imap_deletemailbox ( resource $imap_stream , string $mailbox )

Deletes the specified mailbox.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

mailbox

The mailbox name, see imap_open() for more information

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii IMAP


Returns all of the IMAP errors that have occurred

imap_deletemailbox
imap_expunge
Func?ii IMAP
PHP Manual

imap_errors

(PHP 4, PHP 5, PHP 7)

imap_errors — Returns all of the IMAP errors that have occurred

Descrierea

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.

Valorile întoarse

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.

A se vedea ?i

  • imap_last_error() - Gets the last IMAP error that occurred during this page request
  • imap_alerts() - Întoarce toate mesajele de alerta IMAP care au avut loc

imap_deletemailbox
imap_expunge
Func?ii IMAP


Delete all messages marked for deletion

imap_errors
imap_fetch_overview
Func?ii IMAP
PHP Manual

imap_expunge

(PHP 4, PHP 5, PHP 7)

imap_expunge — Delete all messages marked for deletion

Descrierea

bool imap_expunge ( resource $imap_stream )

Deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().

Parametri

imap_stream

Un flux IMAP întors de imap_open().

Valorile întoarse

Returns TRUE.

imap_errors
imap_fetch_overview
Func?ii IMAP


Read an overview of the information in the headers of the given message

imap_expunge
imap_fetchbody
Func?ii IMAP
PHP Manual

imap_fetch_overview

(PHP 4, PHP 5, PHP 7)

imap_fetch_overview — Read an overview of the information in the headers of the given message

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de 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.

Valorile întoarse

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
  • update - the UNIX timestamp of the arrival date

Istoricul schimbarilor

Versiune | Descriere
5.3.3 | Add the update property.

Exemple

Example #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);
?>

A se vedea ?i

  • imap_fetchheader() - Returns header for a message

imap_expunge
imap_fetchbody
Func?ii IMAP


Fetch a particular section of the body of the message

imap_fetch_overview
imap_fetchheader
Func?ii IMAP
PHP Manual

imap_fetchbody

(PHP 4, PHP 5, PHP 7)

imap_fetchbody — Fetch a particular section of the body of the message

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de 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.

Valorile întoarse

Returns a particular section of the body of the specified messages as a text string.

A se vedea ?i

  • imap_savebody() - Save a specific body section to a file
  • imap_fetchstructure() - Read the structure of a particular message

imap_fetch_overview
imap_fetchheader
Func?ii IMAP


Returns header for a message

imap_fetchbody
imap_fetchmime
Func?ii IMAP
PHP Manual

imap_fetchheader

(PHP 4, PHP 5, PHP 7)

imap_fetchheader — Returns header for a message

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de 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)

Valorile întoarse

Returns the header of the specified message as a text string.

A se vedea ?i

  • imap_fetch_overview() - Read an overview of the information in the headers of the given message

imap_fetchbody
imap_fetchmime
Func?ii IMAP


Fetch MIME headers for a particular section of the message

imap_fetchheader
imap_fetchstructure
Func?ii IMAP
PHP Manual

imap_fetchmime

(PHP 5 >= 5.3.6, PHP 7)

imap_fetchmime — Fetch MIME headers for a particular section of the message

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de 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.

Valorile întoarse

Returns the MIME headers of a particular section of the body of the specified messages as a text string.

A se vedea ?i

  • 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
Func?ii IMAP


Read the structure of a particular message

imap_fetchmime
imap_fetchtext
Func?ii IMAP
PHP Manual

imap_fetchstructure

(PHP 4, PHP 5, PHP 7)

imap_fetchstructure — Read the structure of a particular message

Descrierea

object imap_fetchstructure ( resource $imap_stream , int $msg_number [, int $options = 0 ] )

Fetches all the structured information for a given message.

Parametri

imap_stream

Un flux IMAP întors de 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.

Valorile întoarse

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 (value may vary with used library, use of constants is recommended)
Value | Type | Constant
0 | text | TYPETEXT
1 | multipart | TYPEMULTIPART
2 | message | TYPEMESSAGE
3 | application | TYPEAPPLICATION
4 | audio | TYPEAUDIO
5 | image | TYPEIMAGE
6 | video | TYPEVIDEO
7 | model | TYPEMODEL
8 | other | TYPEOTHER

Transfer encodings (value may vary with used library, use of constants is recommended)
Value | Type | Constant
0 | 7bit | ENC7BIT
1 | 8bit | ENC8BIT
2 | Binary | ENCBINARY
3 | Base64 | ENCBASE64
4 | Quoted-Printable | ENCQUOTEDPRINTABLE
5 | other | ENCOTHER

A se vedea ?i

  • 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
Func?ii IMAP


Pseudonim pentru imap_body

imap_fetchstructure
imap_gc
Func?ii IMAP
PHP Manual

imap_fetchtext

(PHP 4, PHP 5, PHP 7)

imap_fetchtext — Pseudonim pentru imap_body()

Descrierea

Aceasta func?ie este pseudonim pentru: imap_body().

imap_fetchstructure
imap_gc
Func?ii IMAP


Clears IMAP cache

imap_fetchtext
imap_get_quota
Func?ii IMAP
PHP Manual

imap_gc

(PHP 5 >= 5.3.0, PHP 7)

imap_gc — Clears IMAP cache

Descrierea

bool imap_gc ( resource $imap_stream , int $caches )

Purges the cache of entries of a specific type.

Parametri

imap_stream

Un flux IMAP întors de 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 (envelope and bodies), IMAP_GC_TEXTS (texts).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii IMAP


Retrieve the quota level settings, and usage statics per mailbox

imap_gc
imap_get_quotaroot
Func?ii IMAP
PHP Manual

imap_get_quota

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de 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.

Valorile întoarse

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.

Exemple

Example #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);
?>

Example #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);
?>

Note

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.

A se vedea ?i

  • 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
Func?ii IMAP


Retrieve the quota settings per user

imap_get_quota
imap_getacl
Func?ii IMAP
PHP Manual

imap_get_quotaroot

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

imap_get_quotaroot — Retrieve the quota settings per user

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

quota_root

quota_root should normally be in the form of which mailbox (i.e. INBOX).

Valorile întoarse

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.

Exemple

Example #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['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota['MESSAGE'];
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE limit level is: " .  $message['limit'];

   /* ...  */

}

imap_close($mbox);
?>

Note

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.

A se vedea ?i

  • 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
Func?ii IMAP


Gets the ACL for a given mailbox

imap_get_quotaroot
imap_getmailboxes
Func?ii IMAP
PHP Manual

imap_getacl

(PHP 5, PHP 7)

imap_getacl — Gets the ACL for a given mailbox

Descrierea

array imap_getacl ( resource $imap_stream , string $mailbox )

Gets the ACL for a given mailbox.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

mailbox

The mailbox name, see imap_open() for more information

Valorile întoarse

Returns an associative array of "folder" => "acl" pairs.

Exemple

Example #1 imap_getacl() example

<?php

print_r(imap_getacl($conn_id, 'user.joecool'));

?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [asubfolder] => lrswipcda
    [anothersubfolder] => lrswipcda
)

Note

This function is currently only available to users of the c-client2000 or greater library.

A se vedea ?i

  • imap_setacl() - Sets the ACL for a given mailbox

imap_get_quotaroot
imap_getmailboxes
Func?ii IMAP


Read the list of mailboxes, returning detailed information on each one

imap_getacl
imap_getsubscribed
Func?ii IMAP
PHP Manual

imap_getmailboxes

(PHP 4, PHP 5, PHP 7)

imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one

Descrierea

array imap_getmailboxes ( resource $imap_stream , string $ref , string $pattern )

Gets information on the mailboxes.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifica pozi?ia în ierarhia cutiilor po?tale de unde va începe cautarea.

Sunt doua caractere speciale pe care pute?i sa le transmite?i în cadrul pattern: '*' ?i '%'. '*' înseamna a returna toate cutiile po?tale. Daca transmite?i pattern ca '*', ve?i ob?ine o lista a întregii ierarhii a cutiilor po?tale. '%' înseamna a întoarce doar nivelul curent. '%' în calitate de pattern va întoarce doar cutiile po?tale de la nivelul superior; '~/mail/%' pe UW_IMAPD va întoarce toate cutiile po?tale în directorul ~/mail, dar nici una din submapele acstui director.

Valorile întoarse

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 not 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.

Exemple

Example #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);
?>

A se vedea ?i

  • imap_getsubscribed() - List all the subscribed mailboxes

imap_getacl
imap_getsubscribed
Func?ii IMAP


List all the subscribed mailboxes

imap_getmailboxes
imap_header
Func?ii IMAP
PHP Manual

imap_getsubscribed

(PHP 4, PHP 5, PHP 7)

imap_getsubscribed — List all the subscribed mailboxes

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifica pozi?ia în ierarhia cutiilor po?tale de unde va începe cautarea.

Sunt doua caractere speciale pe care pute?i sa le transmite?i în cadrul pattern: '*' ?i '%'. '*' înseamna a returna toate cutiile po?tale. Daca transmite?i pattern ca '*', ve?i ob?ine o lista a întregii ierarhii a cutiilor po?tale. '%' înseamna a întoarce doar nivelul curent. '%' în calitate de pattern va întoarce doar cutiile po?tale de la nivelul superior; '~/mail/%' pe UW_IMAPD va întoarce toate cutiile po?tale în directorul ~/mail, dar nici una din submapele acstui director.

Valorile întoarse

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
Func?ii IMAP


Pseudonim pentru imap_headerinfo

imap_getsubscribed
imap_headerinfo
Func?ii IMAP
PHP Manual

imap_header

(PHP 4, PHP 5, PHP 7)

imap_header — Pseudonim pentru imap_headerinfo()

Descrierea

Aceasta func?ie este pseudonim pentru: imap_headerinfo().

imap_getsubscribed
imap_headerinfo
Func?ii IMAP


Read the header of the message

imap_header
imap_headers
Func?ii IMAP
PHP Manual

imap_headerinfo

(PHP 4, PHP 5, PHP 7)

imap_headerinfo — Read the header of the message

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de 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

Valorile întoarse

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 as 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

A se vedea ?i

  • imap_fetch_overview() - Read an overview of the information in the headers of the given message

imap_header
imap_headers
Func?ii IMAP


Returns headers for all messages in a mailbox

imap_headerinfo
imap_last_error
Func?ii IMAP
PHP Manual

imap_headers

(PHP 4, PHP 5, PHP 7)

imap_headers — Returns headers for all messages in a mailbox

Descrierea

array imap_headers ( resource $imap_stream )

Returns headers for all messages in a mailbox.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

Valorile întoarse

Returns an array of string formatted with header info. One element per mail message.

imap_headerinfo
imap_last_error
Func?ii IMAP


Gets the last IMAP error that occurred during this page request

imap_headers
imap_list
Func?ii IMAP
PHP Manual

imap_last_error

(PHP 4, PHP 5, PHP 7)

imap_last_error — Gets the last IMAP error that occurred during this page request

Descrierea

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.

Valorile întoarse

Returns the full text of the last IMAP error message that occurred on the current page. Returns FALSE if no error messages are available.

A se vedea ?i

  • imap_errors() - Returns all of the IMAP errors that have occurred

imap_headers
imap_list
Func?ii IMAP


Read the list of mailboxes

imap_last_error
imap_listmailbox
Func?ii IMAP
PHP Manual

imap_list

(PHP 4, PHP 5, PHP 7)

imap_list — Read the list of mailboxes

Descrierea

array imap_list ( resource $imap_stream , string $ref , string $pattern )

Read the list of mailboxes.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

ref

ref should normally be just the server specification as described in imap_open().

pattern

Specifica pozi?ia în ierarhia cutiilor po?tale de unde va începe cautarea.

Sunt doua caractere speciale pe care pute?i sa le transmite?i în cadrul pattern: '*' ?i '%'. '*' înseamna a returna toate cutiile po?tale. Daca transmite?i pattern ca '*', ve?i ob?ine o lista a întregii ierarhii a cutiilor po?tale. '%' înseamna a întoarce doar nivelul curent. '%' în calitate de pattern va întoarce doar cutiile po?tale de la nivelul superior; '~/mail/%' pe UW_IMAPD va întoarce toate cutiile po?tale în directorul ~/mail, dar nici una din submapele acstui director.

Valorile întoarse

Returns an array containing the names of the mailboxes.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii IMAP


Pseudonim pentru imap_list

imap_list
imap_listscan
Func?ii IMAP
PHP Manual

imap_listmailbox

(PHP 4, PHP 5, PHP 7)

imap_listmailbox — Pseudonim pentru imap_list()

Descrierea

Aceasta func?ie este pseudonim pentru: imap_list().

imap_list
imap_listscan
Func?ii IMAP


Returns the list of mailboxes that matches the given text

imap_listmailbox
imap_listsubscribed
Func?ii IMAP
PHP Manual

imap_listscan

(PHP 4, PHP 5, PHP 7)

imap_listscan — Returns the list of mailboxes that matches the given text

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifica pozi?ia în ierarhia cutiilor po?tale de unde va începe cautarea.

Sunt doua caractere speciale pe care pute?i sa le transmite?i în cadrul pattern: '*' ?i '%'. '*' înseamna a returna toate cutiile po?tale. Daca transmite?i pattern ca '*', ve?i ob?ine o lista a întregii ierarhii a cutiilor po?tale. '%' înseamna a întoarce doar nivelul curent. '%' în calitate de pattern va întoarce doar cutiile po?tale de la nivelul superior; '~/mail/%' pe UW_IMAPD va întoarce toate cutiile po?tale în directorul ~/mail, dar nici una din submapele acstui director.

content

The searched string

Valorile întoarse

Returns an array containing the names of the mailboxes that have content in the text of the mailbox.

A se vedea ?i

  • imap_listmailbox() - Pseudonim pentru imap_list
  • imap_search() - This function returns an array of messages matching the given search criteria

imap_listmailbox
imap_listsubscribed
Func?ii IMAP


Pseudonim pentru imap_lsub

imap_listscan
imap_lsub
Func?ii IMAP
PHP Manual

imap_listsubscribed

(PHP 4, PHP 5, PHP 7)

imap_listsubscribed — Pseudonim pentru imap_lsub()

Descrierea

Aceasta func?ie este pseudonim pentru: imap_lsub().

imap_listscan
imap_lsub
Func?ii IMAP


List all the subscribed mailboxes

imap_listsubscribed
imap_mail_compose
Func?ii IMAP
PHP Manual

imap_lsub

(PHP 4, PHP 5, PHP 7)

imap_lsub — List all the subscribed mailboxes

Descrierea

array imap_lsub ( resource $imap_stream , string $ref , string $pattern )

Gets an array of all the mailboxes that you have subscribed.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifica pozi?ia în ierarhia cutiilor po?tale de unde va începe cautarea.

Sunt doua caractere speciale pe care pute?i sa le transmite?i în cadrul pattern: '*' ?i '%'. '*' înseamna a returna toate cutiile po?tale. Daca transmite?i pattern ca '*', ve?i ob?ine o lista a întregii ierarhii a cutiilor po?tale. '%' înseamna a întoarce doar nivelul curent. '%' în calitate de pattern va întoarce doar cutiile po?tale de la nivelul superior; '~/mail/%' pe UW_IMAPD va întoarce toate cutiile po?tale în directorul ~/mail, dar nici una din submapele acstui director.

Valorile întoarse

Returns an array of all the subscribed mailboxes.

A se vedea ?i

  • 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
Func?ii IMAP


Create a MIME message based on given envelope and body sections

imap_lsub
imap_mail_copy
Func?ii IMAP
PHP Manual

imap_mail_compose

(PHP 4, PHP 5, PHP 7)

imap_mail_compose — Create a MIME message based on given envelope and body sections

Descrierea

string imap_mail_compose ( array $envelope , array $body )

Create a MIME message based on the given envelope and body sections.

Parametri

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".

Valorile întoarse

Returns the MIME message.

Exemple

Example #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
Func?ii IMAP


Copy specified messages to a mailbox

imap_mail_compose
imap_mail_move
Func?ii IMAP
PHP Manual

imap_mail_copy

(PHP 4, PHP 5, PHP 7)

imap_mail_copy — Copy specified messages to a mailbox

Descrierea

bool imap_mail_copy ( resource $imap_stream , string $msglist , string $mailbox [, int $options = 0 ] )

Copies mail messages specified by msglist to specified mailbox.

Parametri

imap_stream

Un flux IMAP întors de 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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • imap_mail_move() - Move specified messages to a mailbox

imap_mail_compose
imap_mail_move
Func?ii IMAP


Move specified messages to a mailbox

imap_mail_copy
imap_mail
Func?ii IMAP
PHP Manual

imap_mail_move

(PHP 4, PHP 5, PHP 7)

imap_mail_move — Move specified messages to a mailbox

Descrierea

bool imap_mail_move ( resource $imap_stream , string $msglist , string $mailbox [, int $options = 0 ] )

Moves mail messages specified by msglist to the specified mailbox.

Parametri

imap_stream

Un flux IMAP întors de 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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

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.

A se vedea ?i

  • imap_mail_copy() - Copy specified messages to a mailbox

imap_mail_copy
imap_mail
Func?ii IMAP


Send an email message

imap_mail_move
imap_mailboxmsginfo
Func?ii IMAP
PHP Manual

imap_mail

(PHP 4, PHP 5, PHP 7)

imap_mail — Send an email message

Descrierea

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.

Parametri

to

The receiver

subject

The mail subject

message

The mail body, see imap_mail_compose()

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • mail() - Trimite mesaje e-mail
  • imap_mail_compose() - Create a MIME message based on given envelope and body sections

imap_mail_move
imap_mailboxmsginfo
Func?ii IMAP


Get information about the current mailbox

imap_mail
imap_mime_header_decode
Func?ii IMAP
PHP Manual

imap_mailboxmsginfo

(PHP 4, PHP 5, PHP 7)

imap_mailboxmsginfo — Get information about the current mailbox

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

Valorile întoarse

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.

Exemple

Example #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_mailboxmsginfo() failed: " . imap_last_error() . "<br />\n";
}

imap_close($mbox);

?>

imap_mail
imap_mime_header_decode
Func?ii IMAP


Decode MIME header elements

imap_mailboxmsginfo
imap_msgno
Func?ii IMAP
PHP Manual

imap_mime_header_decode

(PHP 4, PHP 5, PHP 7)

imap_mime_header_decode — Decode MIME header elements

Descrierea

array imap_mime_header_decode ( string $text )

Decodes MIME message header extensions that are non ASCII text (see » RFC2047).

Parametri

text

The MIME text

Valorile întoarse

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.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • imap_utf8() - Converts MIME-encoded text to UTF-8

imap_mailboxmsginfo
imap_msgno
Func?ii IMAP


Gets the message sequence number for the given UID

imap_mime_header_decode
imap_num_msg
Func?ii IMAP
PHP Manual

imap_msgno

(PHP 4, PHP 5, PHP 7)

imap_msgno — Gets the message sequence number for the given UID

Descrierea

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().

Parametri

imap_stream

Un flux IMAP întors de imap_open().

uid

The message UID

Valorile întoarse

Returns the message sequence number for the given uid.

A se vedea ?i

  • imap_uid() - This function returns the UID for the given message sequence number

imap_mime_header_decode
imap_num_msg
Func?ii IMAP


Gets the number of messages in the current mailbox

imap_msgno
imap_num_recent
Func?ii IMAP
PHP Manual

imap_num_msg

(PHP 4, PHP 5, PHP 7)

imap_num_msg — Gets the number of messages in the current mailbox

Descrierea

int imap_num_msg ( resource $imap_stream )

Gets the number of messages in the current mailbox.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

Valorile întoarse

Return the number of messages in the current mailbox, as an integer, or FALSE on error.

A se vedea ?i

  • 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
Func?ii IMAP


Gets the number of recent messages in current mailbox

imap_num_msg
imap_open
Func?ii IMAP
PHP Manual

imap_num_recent

(PHP 4, PHP 5, PHP 7)

imap_num_recent — Gets the number of recent messages in current mailbox

Descrierea

int imap_num_recent ( resource $imap_stream )

Gets the number of recent messages in the current mailbox.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

Valorile întoarse

Returns the number of recent messages in the current mailbox, as an integer.

A se vedea ?i

  • 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
Func?ii IMAP


Open an IMAP stream to a mailbox

imap_num_recent
imap_ping
Func?ii IMAP
PHP Manual

imap_open

(PHP 4, PHP 5, PHP 7)

imap_open — Open an IMAP stream to a mailbox

Descrierea

resource imap_open ( string $mailbox , string $username , string $password [, int $options = 0 [, 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.

Parametri

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

Valorile întoarse

Returns an IMAP stream on success or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
5.3.2 | params added
5.2.0 | n_retries added

Exemple

Example #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.
?>

Example #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);
?>

A se vedea ?i

  • imap_close() - Close an IMAP stream

imap_num_recent
imap_ping
Func?ii IMAP


Check if the IMAP stream is still active

imap_open
imap_qprint
Func?ii IMAP
PHP Manual

imap_ping

(PHP 4, PHP 5, PHP 7)

imap_ping — Check if the IMAP stream is still active

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

Valorile întoarse

Returns TRUE if the stream is still alive, FALSE otherwise.

Exemple

Example #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
Func?ii IMAP


Convert a quoted-printable string to an 8 bit string

imap_ping
imap_rename
Func?ii IMAP
PHP Manual

imap_qprint

(PHP 4, PHP 5, PHP 7)

imap_qprint — Convert a quoted-printable string to an 8 bit string

Descrierea

string imap_qprint ( string $string )

Convert a quoted-printable string to an 8 bit string according to » RFC2045, section 6.7.

Parametri

string

A quoted-printable string

Valorile întoarse

Returns an 8 bits string.

A se vedea ?i

  • imap_8bit() - Converte?te un string "8bit" într-un string "quoted-printable"

imap_ping
imap_rename
Func?ii IMAP


Pseudonim pentru imap_renamemailbox

imap_qprint
imap_renamemailbox
Func?ii IMAP
PHP Manual

imap_rename

(PHP 4, PHP 5, PHP 7)

imap_rename — Pseudonim pentru imap_renamemailbox()

Descrierea

Aceasta func?ie este pseudonim pentru: imap_renamemailbox().

imap_qprint
imap_renamemailbox
Func?ii IMAP


Rename an old mailbox to new mailbox

imap_rename
imap_reopen
Func?ii IMAP
PHP Manual

imap_renamemailbox

(PHP 4, PHP 5, PHP 7)

imap_renamemailbox — Rename an old mailbox to new mailbox

Descrierea

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).

Parametri

imap_stream

Un flux IMAP întors de 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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • imap_createmailbox() - Create a new mailbox
  • imap_deletemailbox() - Delete a mailbox

imap_rename
imap_reopen
Func?ii IMAP


Reopen IMAP stream to new mailbox

imap_renamemailbox
imap_rfc822_parse_adrlist
Func?ii IMAP
PHP Manual

imap_reopen

(PHP 4, PHP 5, PHP 7)

imap_reopen — Reopen IMAP stream to new mailbox

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de 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

Valorile întoarse

Returns TRUE if the stream is reopened, FALSE otherwise.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | n_retries added

Exemple

Example #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
Func?ii IMAP


Parses an address string

imap_reopen
imap_rfc822_parse_headers
Func?ii IMAP
PHP Manual

imap_rfc822_parse_adrlist

(PHP 4, PHP 5, PHP 7)

imap_rfc822_parse_adrlist — Parses an address string

Descrierea

array imap_rfc822_parse_adrlist ( string $address , string $default_host )

Parses the address string as defined in » RFC2822 and for each address.

Parametri

address

A string containing addresses

default_host

The default host name

Valorile întoarse

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

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

# 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     :

A se vedea ?i

  • imap_rfc822_parse_headers() - Parse mail headers from a string

imap_reopen
imap_rfc822_parse_headers
Func?ii IMAP


Parse mail headers from a string

imap_rfc822_parse_adrlist
imap_rfc822_write_address
Func?ii IMAP
PHP Manual

imap_rfc822_parse_headers

(PHP 4, PHP 5, PHP 7)

imap_rfc822_parse_headers — Parse mail headers from a string

Descrierea

object imap_rfc822_parse_headers ( string $headers [, string $defaulthost = "UNKNOWN" ] )

Gets an object of various header elements, similar to imap_header().

Parametri

headers

The parsed headers data

defaulthost

The default host name

Valorile întoarse

Returns an object similar to the one returned by imap_header(), except for the flags and other properties that come from the IMAP server.

A se vedea ?i

  • imap_rfc822_parse_adrlist() - Parses an address string

imap_rfc822_parse_adrlist
imap_rfc822_write_address
Func?ii IMAP


Returns a properly formatted email address given the mailbox, host, and personal info

imap_rfc822_parse_headers
imap_savebody
Func?ii IMAP
PHP Manual

imap_rfc822_write_address

(PHP 4, PHP 5, PHP 7)

imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info

Descrierea

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.

Parametri

mailbox

The mailbox name, see imap_open() for more information

host

The email host part

personal

The name of the account owner

Valorile întoarse

Returns a string properly formatted email address as defined in » RFC2822.

Exemple

Example #1 imap_rfc822_write_address() example

<?php
echo imap_rfc822_write_address("hartmut", "example.com", "Hartmut Holzgraefe");
?>

Exemplul de mai sus va afi?a:

Hartmut Holzgraefe <hartmut@example.com>

imap_rfc822_parse_headers
imap_savebody
Func?ii IMAP


Save a specific body section to a file

imap_rfc822_write_address
imap_scan
Func?ii IMAP
PHP Manual

imap_savebody

(PHP 5 >= 5.1.3, PHP 7)

imap_savebody — Save a specific body section to a file

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • imap_fetchbody() - Fetch a particular section of the body of the message

imap_rfc822_write_address
imap_scan
Func?ii IMAP


Pseudonim pentru imap_listscan

imap_savebody
imap_scanmailbox
Func?ii IMAP
PHP Manual

imap_scan

(PHP 4, PHP 5, PHP 7)

imap_scan — Pseudonim pentru imap_listscan()

Descrierea

Aceasta func?ie este pseudonim pentru: imap_listscan().

imap_savebody
imap_scanmailbox
Func?ii IMAP


Pseudonim pentru imap_listscan

imap_scan
imap_search
Func?ii IMAP
PHP Manual

imap_scanmailbox

(PHP 4, PHP 5, PHP 7)

imap_scanmailbox — Pseudonim pentru imap_listscan()

Descrierea

Aceasta func?ie este pseudonim pentru: imap_listscan().

imap_scan
imap_search
Func?ii IMAP


This function returns an array of messages matching the given search criteria

imap_scanmailbox
imap_set_quota
Func?ii IMAP
PHP Manual

imap_search

(PHP 4, PHP 5, PHP 7)

imap_search — This function returns an array of messages matching the given search criteria

Descrierea

array imap_search ( resource $imap_stream , string $criteria [, int $options = SE_FREE [, string $charset = NULL ]] )

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).

Parametri

imap_stream

Un flux IMAP întors de 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

MIME character set to use when searching strings.

Valorile întoarse

Returns an array of message numbers or UIDs.

Return FALSE if it does not understand the search criteria or no messages have been found.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • imap_listscan() - Returns the list of mailboxes that matches the given text

imap_scanmailbox
imap_set_quota
Func?ii IMAP


Sets a quota for a given mailbox

imap_search
imap_setacl
Func?ii IMAP
PHP Manual

imap_set_quota

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

imap_set_quota — Sets a quota for a given mailbox

Descrierea

bool imap_set_quota ( resource $imap_stream , string $quota_root , int $quota_limit )

Sets an upper limit quota on a per mailbox basis.

Parametri

imap_stream

Un flux IMAP întors de 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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Note

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.

A se vedea ?i

  • 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
Func?ii IMAP


Sets the ACL for a given mailbox

imap_set_quota
imap_setflag_full
Func?ii IMAP
PHP Manual

imap_setacl

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imap_setacl — Sets the ACL for a given mailbox

Descrierea

bool imap_setacl ( resource $imap_stream , string $mailbox , string $id , string $rights )

Sets the ACL for a giving mailbox.

Parametri

imap_stream

Un flux IMAP întors de 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

This function is currently only available to users of the c-client2000 or greater library.

A se vedea ?i

  • imap_getacl() - Gets the ACL for a given mailbox

imap_set_quota
imap_setflag_full
Func?ii IMAP


Sets flags on messages

imap_setacl
imap_sort
Func?ii IMAP
PHP Manual

imap_setflag_full

(PHP 4, PHP 5, PHP 7)

imap_setflag_full — Sets flags on messages

Descrierea

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.

Parametri

imap_stream

Un flux IMAP întors de 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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • imap_clearflag_full() - Clears flags on messages

imap_setacl
imap_sort
Func?ii IMAP


Gets and sort messages

imap_setflag_full
imap_status
Func?ii IMAP
PHP Manual

imap_sort

(PHP 4, PHP 5, PHP 7)

imap_sort — Gets and sort messages

Descrierea

array imap_sort ( resource $imap_stream , int $criteria , int $reverse [, int $options = 0 [, string $search_criteria = NULL [, string $charset = NULL ]]] )

Gets and sorts message numbers by the given parameters.

Parametri

imap_stream

Un flux IMAP întors de 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

IMAP2-format search criteria string. For details see imap_search().

charset

MIME character set to use when sorting strings.

Valorile întoarse

Returns an array of message numbers sorted by the given parameters.

imap_setflag_full
imap_status
Func?ii IMAP


Returns status information on a mailbox

imap_sort
imap_subscribe
Func?ii IMAP
PHP Manual

imap_status

(PHP 4, PHP 5, PHP 7)

imap_status — Returns status information on a mailbox

Descrierea

object imap_status ( resource $imap_stream , string $mailbox , int $options )

Gets status information about the given mailbox.

Parametri

imap_stream

Un flux IMAP întors de 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

Valorile întoarse

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.

Exemple

Example #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
Func?ii IMAP


Subscribe to a mailbox

imap_status
imap_thread
Func?ii IMAP
PHP Manual

imap_subscribe

(PHP 4, PHP 5, PHP 7)

imap_subscribe — Subscribe to a mailbox

Descrierea

bool imap_subscribe ( resource $imap_stream , string $mailbox )

Subscribe to a new mailbox.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

mailbox

The mailbox name, see imap_open() for more information

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • imap_unsubscribe() - Unsubscribe from a mailbox

imap_status
imap_thread
Func?ii IMAP


Returns a tree of threaded message

imap_subscribe
imap_timeout
Func?ii IMAP
PHP Manual

imap_thread

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imap_thread — Returns a tree of threaded message

Descrierea

array imap_thread ( resource $imap_stream [, int $options = SE_FREE ] )

Gets a tree of a threaded message.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

options

Valorile întoarse

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"]

Exemple

Example #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
Func?ii IMAP


Set or fetch imap timeout

imap_thread
imap_uid
Func?ii IMAP
PHP Manual

imap_timeout

(PHP 4 >= 4.3.3, PHP 5, PHP 7)

imap_timeout — Set or fetch imap timeout

Descrierea

mixed imap_timeout ( int $timeout_type [, int $timeout = -1 ] )

Sets or fetches the imap timeout.

Parametri

timeout_type

One of the following: IMAP_OPENTIMEOUT, IMAP_READTIMEOUT, IMAP_WRITETIMEOUT, or IMAP_CLOSETIMEOUT.

timeout

The timeout, in seconds.

Valorile întoarse

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.

Exemple

Example #1 imap_timeout() example

<?php

echo "The current read timeout is " . imap_timeout(IMAP_READTIMEOUT) . "\n";

?>

imap_thread
imap_uid
Func?ii IMAP


This function returns the UID for the given message sequence number

imap_timeout
imap_undelete
Func?ii IMAP
PHP Manual

imap_uid

(PHP 4, PHP 5, PHP 7)

imap_uid — This function returns the UID for the given message sequence number

Descrierea

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().

Parametri

imap_stream

Un flux IMAP întors de imap_open().

msg_number

The message number.

Valorile întoarse

The UID of the given message.

Note

Nota:

This function is not supported by POP3 mailboxes.

A se vedea ?i

  • imap_msgno() - Gets the message sequence number for the given UID

imap_timeout
imap_undelete
Func?ii IMAP


Unmark the message which is marked deleted

imap_uid
imap_unsubscribe
Func?ii IMAP
PHP Manual

imap_undelete

(PHP 4, PHP 5, PHP 7)

imap_undelete — Unmark the message which is marked deleted

Descrierea

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().

Parametri

imap_stream

Un flux IMAP întors de imap_open().

msg_number

The message number

flags

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • imap_delete() - Mark a message for deletion from current mailbox
  • imap_mail_move() - Move specified messages to a mailbox

imap_uid
imap_unsubscribe
Func?ii IMAP


Unsubscribe from a mailbox

imap_undelete
imap_utf7_decode
Func?ii IMAP
PHP Manual

imap_unsubscribe

(PHP 4, PHP 5, PHP 7)

imap_unsubscribe — Unsubscribe from a mailbox

Descrierea

bool imap_unsubscribe ( resource $imap_stream , string $mailbox )

Unsubscribe from the specified mailbox.

Parametri

imap_stream

Un flux IMAP întors de imap_open().

mailbox

The mailbox name, see imap_open() for more information

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • imap_subscribe() - Subscribe to a mailbox

imap_undelete
imap_utf7_decode
Func?ii IMAP


Decodes a modified UTF-7 encoded string

imap_unsubscribe
imap_utf7_encode
Func?ii IMAP
PHP Manual

imap_utf7_decode

(PHP 4, PHP 5, PHP 7)

imap_utf7_decode — Decodes a modified UTF-7 encoded string

Descrierea

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.

Parametri

text

A modified UTF-7 encoding string, as defined in » RFC 2060, section 5.1.3 (original UTF-7 was defined in » RFC1642).

Valorile întoarse

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.

A se vedea ?i

  • imap_utf7_encode() - Converts ISO-8859-1 string to modified UTF-7 text

imap_unsubscribe
imap_utf7_encode
Func?ii IMAP


Converts ISO-8859-1 string to modified UTF-7 text

imap_utf7_decode
imap_utf8
Func?ii IMAP
PHP Manual

imap_utf7_encode

(PHP 4, PHP 5, PHP 7)

imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text

Descrierea

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.

Parametri

data

An ISO-8859-1 string.

Valorile întoarse

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).

A se vedea ?i

  • imap_utf7_decode() - Decodes a modified UTF-7 encoded string

imap_utf7_decode
imap_utf8
Func?ii IMAP


Converts MIME-encoded text to UTF-8

imap_utf7_encode
Po?ta
Func?ii IMAP
PHP Manual

imap_utf8

(PHP 4, PHP 5, PHP 7)

imap_utf8 — Converts MIME-encoded text to UTF-8

Descrierea

string imap_utf8 ( string $mime_encoded_text )

Converts the given mime_encoded_text to UTF-8.

Parametri

mime_encoded_text

A MIME encoded string. MIME encoding method and the UTF-8 specification are described in » RFC2047 and » RFC2044 respectively.

Valorile întoarse

Returns an UTF-8 encoded string.

A se vedea ?i

  • imap_mime_header_decode() - Decode MIME header elements

imap_utf7_encode
Po?ta
Func?ii IMAP


Po?ta

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii de po?ta
    • ezmlm_hash — Calculeaza valoarea hash necesara EZMLM
    • mail — Trimite mesaje e-mail
imap_utf8
Introducere
Extensii referitoare la po?ta electronica


Introducere

Func?ia mail() va permite sa trimite?i mesaje e-mail.

Po?ta
Instalarea / configurarea
Po?ta


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Po?ta


Necesita?i

Pentru ca func?iile po?tale sa fie disponibile, PHP trebuie sa aiba acces la binarul sendmail din sistem la momentul compilarii. Daca utiliza?i un alt program po?tal, cum ar fi qmail sau postfix, asigura?i-va ca utiliza?i înveli?ul sendmail corespunzator cu care sunt furnizate. PHP mai întâi va cauta sendmail în caile din PATH, ?i dupa aceasta în urmatoarele locuri: /usr/bin:/usr/sbin:/usr/etc:/etc:/usr/ucblib:/usr/lib. Este foarte recomandabil sa ave?i sendmail disponibil în una din caile din PATH. De asemenea, utilizatorul ce a compilat PHP trebuie sa aiba permisiunea de a accesa binarul sendmail.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Op?iuni de configurare a po?tei
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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. (PHP_INI_SYSTEM|PHP_INI_PERDIR)
mail.force_extra_parameters | NULL | PHP_INI_PERDIR | Disponibil începând cu PHP 5.0.0. (PHP_INI_SYSTEM|PHP_INI_PERDIR)
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 |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

mail.add_x_header bool

Adauga X-PHP-Originating-Script ce va include UID al scriptului, urmat de denumirea fi?ierului.

mail.log string

Calea catre un fi?ier-jurnal care va duce eviden?a tuturor apelurilor mail(). Înregistrarile în jurnal includ calea deplina a script-ului, numarul liniei, adresa To ?i antetele.

mail.force_extra_parameters string

For?eaza adaugarea parametrilor specifica?i spre a fi transmi?i ca parametri suplimentari pentru binarul sendmail. Ace?ti parametri întotdeauna vor înlocui valoarea parametrului al 5-lea din func?ia mail(), chiar ?i în modul sigur.

SMTP string

Se utilizeaza numai în Windows: denumirea sau adresa IP a serverului SMTP pe care PHP trebuie sa-l utilizeze pentru trimiterea po?tei cu func?ia mail().

smtp_port int

Se utilizeaza numai în Windows: numarul portului pentru conectare la serverul specificat în op?iunea SMTP la trimiterea po?tei cu func?ia mail(); implicit este 25. Disponibil numai începând cu PHP 4.3.0.

sendmail_from string

Indica adresa ce trebuie înscrisa în câmpul "From:" în po?ta trimisa din PHP sub Windows. Aceasta directiva de asemenea stabile?te antetul "Return-Path:".

sendmail_path string

Indica locul unde programul sendmail poate fi gasit, de obicei /usr/sbin/sendmail sau /usr/lib/sendmail. configure încearca sa gasesca independent programul ?i sa stabileasca implicit aceasta loca?ie, dar daca e?ueaza, pute?i sa o stabili?i aici.

Sistemele ce nu utilizeaza sendmail ar trebui sa stabileasca aceasta directiva catre înveli?ul/înlocuitorul sendmail pe care îl ofera sistemul lor, daca exista. Spre exemplu, utilizatorii » Qmail în mod mormal pot sa stabileasca valoarea în /var/qmail/bin/sendmail sau /var/qmail/bin/qmail-inject.

qmail-inject nu necesita nici o op?iune pentru a prelucra corect po?ta.

Aceasta directiva func?ioneaza de asemenea ?i în Windows. Daca ea este stabilita, atunci smtp, smtp_port ?i sendmail_from sunt ignorate ?i comanda specificata este executata.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii de po?ta
Po?ta


Func?ii de po?ta

Cuprins

  • ezmlm_hash — Calculeaza valoarea hash necesara EZMLM
  • mail — Trimite mesaje e-mail
Constante predefinite
ezmlm_hash
Po?ta


Calculeaza valoarea hash necesara EZMLM

Func?ii de po?ta
mail
Func?ii de po?ta
PHP Manual

ezmlm_hash

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

ezmlm_hash — Calculeaza valoarea hash necesara EZMLM

Descrierea

int ezmlm_hash ( string $addr )

ezmlm_hash() calculeaza valoarea hash necesara pentru men?inerea listelor po?tale EZMLM într-o baza de date MySQL.

Parametri

addr

Adresa email asupra careia se aplica func?ia hash.

Valorile întoarse

Valoarea hash a addr.

Exemple

Example #1 Calcularea hash-ului ?i înscrierea în lista a unui utilizator

<?php

$user = "joecool@example.com";
$hash = ezmlm_hash($user);
$query = sprintf("INSERT INTO sample VALUES (%s, '%s')", $hash, $user);
$db->query($query); // using PHPLIB db interface

?>

Func?ii de po?ta
mail
Func?ii de po?ta


Trimite mesaje e-mail

ezmlm_hash
Mailparse
Func?ii de po?ta
PHP Manual

mail

(PHP 4, PHP 5, PHP 7)

mail — Trimite mesaje e-mail

Descrierea

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

Trimite un mesaj e-mail.

Parametri

to

Destinatarul sau destinatarii mesajului.

Formatul acestui string trebuie sa respecte » RFC 2822. Unele exemple:

  • user@example.com
  • user@example.com, anotheruser@example.com
  • User <user@example.com>
  • User <user@example.com>, Another User <anotheruser@example.com>

subject

Subiectul mesajului spre a fi trimis.

Precautie

Subiectul trebuie sa satisfaca cerin?elor » RFC 2047.

message

Mesajul spre a fi trimis.

Fiecare rând trebuie sa fie încheiat cu CRLF (\r\n). Lungimea rândurilor nu trebuie sa depa?easca 70 de caractere.

Precautie

(Numai pentru Windows) Când PHP conlucreaza direct cu un server SMTP, daca este întâlnit un punct la începutul unui rând, el este eliminat. Pentru a depa?i aceste situa?ii, dubla?i punctul de la începutul rândului.

<?php
$text = str_replace("\n.", "\n..", $text);
?>

additional_headers (op?ional)

Un string spre a fi inserat la sfâr?itul antetelor mesajului.

Acesta este utilizat de obicei pentru a adauga antete suplimentare (From, Cc, ?i Bcc). Antetele suplimentare multiple trebuie separate cu CRLF (\r\n). Daca pentru a stabili acest antet se folosesc date externe, ele trebuie filtrate, astfel încât sa nu fie posibila inserarea antetelor nedorite.

Nota:

additional_headers nu are o protec?ie împotriva injectarii antetelor de email. De aceea utilizatorii trebuie sa se asigure ca antetele specificate sunt în siguran?a ?i ca con?in doar antete. De ex. niciodata nu începe?i corpul mesajului inserând mai multe linii noi.

Nota:

La trimiterea mesajului, acesta trebuie sa con?ina antetul From. Acesta poate fi stabilit cu ajutorul parametrului additional_headers, sau poate fi stabilita o valoare implicita în php.ini.

În caz ca nu se respecta aceasta condi?ie, se va produce un mesaj de eroare similar cu acesta: Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing (Avertizare: mail(): "sendmail_from" nu este stabilit în php.ini sau antetul "From:" lipse?te). Antetul From stabile?te de asemenea Return-Path în Windows.

Nota:

Daca mesajele nu sunt primite, încerca?i sa utiliza?i numai LF (\n). Unii agen?i de transfer a mesajelor în Unix (în special » qmail) înlocuiesc LF cu CRLF în mod automat (ceea ce duce la dublarea CR daca este utilizat CRLF). Utiliza?i acest procedeu numai în caz excep?ional, deoarece acesta nu se conformaeza cu » RFC 2822.

additional_parameters (op?ional)

Parametrul additional_parameters poate fi utilizat pentru a transmite fanioane suplimentare programului configurat pentru a transmite po?ta, definit de op?iunea de configurare sendmail_path. Spre exemplu, acesta poate fi utilizat pentru a stabili adresa expeditorului de pe plic când se utilizeaza sendmail cu op?iunea -f.

Acest parametru este filtrat cu escapeshellcmd() în mod automat pentru a preveni execu?ia comenzilor. escapeshellcmd() previne execu?ia comenzilor, dar permite adaugarea parametrilor suplimentari. Din punct de vedere al securita?ii este recomandabil ca utilizatorul sa filtreze ?i sa verifice acest parametru pentru a evita adaugarea parametrilor nedori?i la comanda pentru înveli?.

Deoarece escapeshellcmd() este aaplicata în mod automat, unele caractere care sunt permise în adrese email de standardele RFC, nu pot fi utilizate. Func?ia mail() nu poate permite asemenea caractere, de aceea în programele în care este necesara utilizarea acestor caractere, se recomanda utilizarea metodelor alternative de transmitere a email-urilor (de ex. utilizarea unui framework sau a unei biblioteci).

Utilizatorul cu care ruleaza serveul web trebuie adaugat în calitate de utilizator de încredere în configura?ia sendmail pentru a preveni adaugarea unui antet 'X-Warning' la mesaj atunci când expeditorul de pe plic (-f) este stabilit prin aceasta metoda. Pentru utilizatorii sendmail acest fi?ier este /etc/mail/trusted-users.

Valorile întoarse

Întoarce TRUE daca mesajul a fost acceptat cu succes pentru trimitere, FALSE în caz contrar.

Este important sa ?ti?i ca cu toate ca mesajul a fost acceptat spre trimitere, aceasta NU înseamna ca mesajul într-adevar va ajunge la destina?ie.

Istoricul schimbarilor

Versiune | Descriere
4.2.3 | Parametrul additional_parameters este dezactivat în safe_mode ?i func?ia mail() va emite un mesaj de avertizare ?i va întoarce FALSE atunci când este utilizat.

Exemple

Example #1 Trimiterea mesajelor.

Utilizarea mail() pentru a transmite un mesaj simplu:

<?php
// Mesajul
$message = "Line 1\r\nLine 2\r\nLine 3";

// În caz ca vre-un rând depa?e?te 70 de caractere, trebuie sa utilizam
// wordwrap()
$message = wordwrap($message, 70, "\r\n");

// Trimiterea
mail('caffeinated@example.com', 'My Subject', $message);
?>

Example #2 Trimiterea unui mesaj cu antete suplimentare.

Adaugarea antetelor de baza, transmi?ându-i MUA adresele From ?i Reply-To:

<?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>

Example #3 Trimiterea unui mesaj cu un parametru suplimentar în linia de comanda.

Parametrul additional_parameters poate fi utilizat pentru a transmite un parametru suplimentar programului configurat pentru a fi utilizat la trimiterea po?tei cu ajutorul sendmail_path.

<?php
mail('nobody@example.com', 'the subject', 'the message', null,
   '-fwebmaster@example.com');
?>

Example #4 Transmiterea unui mesaj HTML

Este posibil de a trimite mesaje HTML cu mail().

<?php
// Destinatari multipli
$to  = 'aidan@example.com' . ', '; // observa?i virgula
$to .= 'wez@example.com';

// Subiectul
$subject = 'Birthday Reminders for August';

// Mesajul
$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>
';

// Pentru a trimite mesaje HTML, trebuie stabilit antetul Content-type
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Antete suplimentare
$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";

// Trimiterea mesajului
mail($to, $subject, $message, $headers);
?>

Nota:

Daca se inten?ioneaza trimiterea mesajelor HTML, sau a altor mesaje complexe, este recomandata utilizarea pachetului PEAR » PEAR::Mail_Mime.

Note

Nota:

Implementarea func?iei mail() în Windows difera în multe aspecte de cea din Unix. În primul rând ea nu utilizeaza un binar local pentru a compune mesajele, dar opereaza direct asupra socket-urilor, ceea ce înseamna ca este necesar ca un MTA sa asculte pe un socket de re?ea (care poate fi pe serverul local sau pe unul îndepartat).

În al doilea rând, antetele personalizate, cum ar fi From:, Cc:, Bcc: ?i Date: nu sunt interpretate de catre MTA în primul rând, dar sunt procesate de PHP.

Prin urmare, parametrul to nu trebuie sa fie o adresa de forma "Ceva <cineva@exemplu.com>". Comanda mail poate sa nu prelucreze aceasta în mod corect în timp ce conlucreaza cu MTA.

Nota:

Face de men?ionat ca func?ia mail() nu este potrivita pentru volume mari de masaje trimise consecutiv. Aceasta func?ie deschide ?i închide socket-ul SMTP pentru fiecare mesaj, ceea ce nu este foarte eficient.

Pentru transmiterea volumelor mari de mesaje considera?i pachetele » PEAR::Mail ?i » PEAR::Mail_Queue.

Nota:

Urmatoarele RFC-uri pot fi de folos: » RFC 1896, » RFC 2045, » RFC 2046, » RFC 2047, » RFC 2048, » RFC 2049 ?i » RFC 2822.

A se vedea ?i

  • imap_mail() - Send an email message
  • » PEAR::Mail
  • » PEAR::Mail_Mime

ezmlm_hash
Mailparse
Func?ii de po?ta


Mailparse

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii de prelucrare a po?tei
    • 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
Introducere
Extensii referitoare la po?ta electronica


Introducere

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.

Nota:

Mailparse requires the mbstring extension, and mbstring must be loaded before mailparse.

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 4.2.0.

Mailparse
Instalarea / configurarea
Mailparse


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Mailparse


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP. Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » 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. O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

It is necessary that the mbstring extension is loaded before mailparse.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

MAILPARSE_EXTRACT_OUTPUT (integer)
MAILPARSE_EXTRACT_STREAM (integer)
MAILPARSE_EXTRACT_RETURN (integer)
Tipurile resurselor
Func?ii de prelucrare a po?tei
Mailparse


Func?ii de prelucrare a po?tei

Cuprins

  • 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
Constante predefinite
mailparse_determine_best_xfer_encoding
Mailparse


Gets the best way of encoding

Func?ii de prelucrare a po?tei
mailparse_msg_create
Func?ii de prelucrare a po?tei
PHP Manual

mailparse_determine_best_xfer_encoding

(PECL mailparse >= 0.9.0)

mailparse_determine_best_xfer_encoding — Gets the best way of encoding

Descrierea

string mailparse_determine_best_xfer_encoding ( resource $fp )

Figures out the best way of encoding the content read from the given file pointer.

Parametri

fp

A valid file pointer, which must be seek-able.

Valorile întoarse

Returns one of the character encodings supported by the mbstring module.

Exemple

Example #1 mailparse_determine_best_xfer_encoding() example

<?php

$fp = fopen('somemail.eml', 'r');
echo 'Best encoding: ' . mailparse_determine_best_xfer_encoding($fp);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Best encoding: 7bit

Func?ii de prelucrare a po?tei
mailparse_msg_create
Func?ii de prelucrare a po?tei


Create a mime mail resource

mailparse_determine_best_xfer_encoding
mailparse_msg_extract_part_file
Func?ii de prelucrare a po?tei
PHP Manual

mailparse_msg_create

(PECL mailparse >= 0.9.0)

mailparse_msg_create — Create a mime mail resource

Descrierea

resource mailparse_msg_create ( void )

Create a MIME mail resource.

Valorile întoarse

Returns a handle that can be used to parse a message.

A se vedea ?i

  • mailparse_msg_free() - Frees a MIME resource
  • mailparse_msg_parse_file() - Parses a file

mailparse_determine_best_xfer_encoding
mailparse_msg_extract_part_file
Func?ii de prelucrare a po?tei


Extracts/decodes a message section

mailparse_msg_create
mailparse_msg_extract_part
Func?ii de prelucrare a po?tei
PHP Manual

mailparse_msg_extract_part_file

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_part_file — Extracts/decodes a message section

Descrierea

string mailparse_msg_extract_part_file ( resource $mimemail , mixed $filename [, callable $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.

Parametri

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".

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii de prelucrare a po?tei


Extracts/decodes a message section

mailparse_msg_extract_part_file
mailparse_msg_extract_whole_part_file
Func?ii de prelucrare a po?tei
PHP Manual

mailparse_msg_extract_part

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_part — Extracts/decodes a message section

Descrierea

void mailparse_msg_extract_part ( resource $mimemail , string $msgbody [, callable $callbackfunc ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

mimemail

A valid MIME resource.

msgbody

callbackfunc

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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
Func?ii de prelucrare a po?tei


Extracts a message section including headers without decoding the transfer encoding

mailparse_msg_extract_part
mailparse_msg_free
Func?ii de prelucrare a po?tei
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

Descrierea

string mailparse_msg_extract_whole_part_file ( resource $mimemail , string $filename [, callable $callbackfunc ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

mimemail

A valid MIME resource.

filename

callbackfunc

Valorile întoarse

A se vedea ?i

  • 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
Func?ii de prelucrare a po?tei


Frees a MIME resource

mailparse_msg_extract_whole_part_file
mailparse_msg_get_part_data
Func?ii de prelucrare a po?tei
PHP Manual

mailparse_msg_free

(PECL mailparse >= 0.9.0)

mailparse_msg_free — Frees a MIME resource

Descrierea

bool mailparse_msg_free ( resource $mimemail )

Frees a MIME resource.

Parametri

mimemail

A valid MIME resource allocated by mailparse_msg_create() or mailparse_msg_parse_file().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii de prelucrare a po?tei


Returns an associative array of info about the message

mailparse_msg_free
mailparse_msg_get_part
Func?ii de prelucrare a po?tei
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

Descrierea

array mailparse_msg_get_part_data ( resource $mimemail )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

mimemail

A valid MIME resource.

mailparse_msg_free
mailparse_msg_get_part
Func?ii de prelucrare a po?tei


Returns a handle on a given section in a mimemessage

mailparse_msg_get_part_data
mailparse_msg_get_structure
Func?ii de prelucrare a po?tei
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

Descrierea

resource mailparse_msg_get_part ( resource $mimemail , string $mimesection )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

mimemail

A valid MIME resource.

mimesection

mailparse_msg_get_part_data
mailparse_msg_get_structure
Func?ii de prelucrare a po?tei


Returns an array of mime section names in the supplied message

mailparse_msg_get_part
mailparse_msg_parse_file
Func?ii de prelucrare a po?tei
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

Descrierea

array mailparse_msg_get_structure ( resource $mimemail )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

mimemail

A valid MIME resource.

mailparse_msg_get_part
mailparse_msg_parse_file
Func?ii de prelucrare a po?tei


Parses a file

mailparse_msg_get_structure
mailparse_msg_parse
Func?ii de prelucrare a po?tei
PHP Manual

mailparse_msg_parse_file

(PECL mailparse >= 0.9.0)

mailparse_msg_parse_file — Parses a file

Descrierea

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.

Parametri

filename

Path to the file holding the message. The file is opened and streamed through the parser.

Valorile întoarse

Returns a MIME resource representing the structure, or FALSE on error.

A se vedea ?i

  • mailparse_msg_free() - Frees a MIME resource
  • mailparse_msg_create() - Create a mime mail resource

mailparse_msg_get_structure
mailparse_msg_parse
Func?ii de prelucrare a po?tei


Incrementally parse data into buffer

mailparse_msg_parse_file
mailparse_rfc822_parse_addresses
Func?ii de prelucrare a po?tei
PHP Manual

mailparse_msg_parse

(PECL mailparse >= 0.9.0)

mailparse_msg_parse — Incrementally parse data into buffer

Descrierea

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.

Parametri

mimemail

A valid MIME resource.

data

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

mailparse_msg_parse_file
mailparse_rfc822_parse_addresses
Func?ii de prelucrare a po?tei


Parse RFC 822 compliant addresses

mailparse_msg_parse
mailparse_stream_encode
Func?ii de prelucrare a po?tei
PHP Manual

mailparse_rfc822_parse_addresses

(PECL mailparse >= 0.9.0)

mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses

Descrierea

array mailparse_rfc822_parse_addresses ( string $addresses )

Parses a » RFC 822 compliant recipient list, such as that found in the To: header.

Parametri

addresses

A string containing addresses, like in: Wez Furlong <wez@example.com>, doe@example.com

Nota:

This string must not include the header name.

Valorile întoarse

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.

Exemple

Example #1 mailparse_rfc822_parse_addresses() example

<?php

$to = 'Wez Furlong <wez@example.com>, doe@example.com';
var_dump(mailparse_rfc822_parse_addresses($to));

?>

Exemplul de mai sus va afi?a:

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
Func?ii de prelucrare a po?tei


Streams data from source file pointer, apply encoding and write to destfp

mailparse_rfc822_parse_addresses
mailparse_uudecode_all
Func?ii de prelucrare a po?tei
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

hello, this is some text=3Dhello.

mailparse_rfc822_parse_addresses
mailparse_uudecode_all
Func?ii de prelucrare a po?tei


Scans the data from fp and extract each embedded uuencoded file

mailparse_stream_encode
vpopmail
Func?ii de prelucrare a po?tei
PHP Manual

mailparse_uudecode_all

(PECL mailparse >= 0.9.0)

mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file

Descrierea

array mailparse_uudecode_all ( resource $fp )

Scans the data from the given file pointer and extract each embedded uuencoded file into a temporary file.

Parametri

fp

A valid file pointer.

Valorile întoarse

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.

Exemple

Example #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"]);

?>

Exemplul de mai sus va afi?a:

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
Func?ii de prelucrare a po?tei


vpopmail

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii vpopmail
    • vpopmail_add_alias_domain_ex — Add alias to an existing virtual domain
    • vpopmail_add_alias_domain — Add an alias for a virtual domain
    • vpopmail_add_domain_ex — Add a new virtual domain
    • vpopmail_add_domain — Add a new virtual domain
    • vpopmail_add_user — Add a new user to the specified virtual domain
    • vpopmail_alias_add — Insert a virtual alias
    • vpopmail_alias_del_domain — Deletes all virtual aliases of a domain
    • vpopmail_alias_del — Deletes all virtual aliases of a user
    • vpopmail_alias_get_all — Get all lines of an alias for a domain
    • vpopmail_alias_get — Get all lines of an alias for a domain
    • vpopmail_auth_user — Attempt to validate a username/domain/password
    • vpopmail_del_domain_ex — Delete a virtual domain
    • vpopmail_del_domain — Delete a virtual domain
    • vpopmail_del_user — Delete a user from a virtual domain
    • vpopmail_error — Ob?ine mesajul textual pentru ultima eroare vpopmail
    • vpopmail_passwd — Change a virtual user's password
    • vpopmail_set_user_quota — Sets a virtual user's quota
mailparse_uudecode_all
Introducere
Extensii referitoare la po?ta electronica


Introducere

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

This extension has been moved from PHP as of PHP 4.3.0 and now vpopmail lives in » PECL.

vpopmail
Instalarea / configurarea
vpopmail


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
vpopmail


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/vpopmail.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii vpopmail
vpopmail


Func?ii vpopmail

Cuprins

  • vpopmail_add_alias_domain_ex — Add alias to an existing virtual domain
  • vpopmail_add_alias_domain — Add an alias for a virtual domain
  • vpopmail_add_domain_ex — Add a new virtual domain
  • vpopmail_add_domain — Add a new virtual domain
  • vpopmail_add_user — Add a new user to the specified virtual domain
  • vpopmail_alias_add — Insert a virtual alias
  • vpopmail_alias_del_domain — Deletes all virtual aliases of a domain
  • vpopmail_alias_del — Deletes all virtual aliases of a user
  • vpopmail_alias_get_all — Get all lines of an alias for a domain
  • vpopmail_alias_get — Get all lines of an alias for a domain
  • vpopmail_auth_user — Attempt to validate a username/domain/password
  • vpopmail_del_domain_ex — Delete a virtual domain
  • vpopmail_del_domain — Delete a virtual domain
  • vpopmail_del_user — Delete a user from a virtual domain
  • vpopmail_error — Ob?ine mesajul textual pentru ultima eroare vpopmail
  • vpopmail_passwd — Change a virtual user's password
  • vpopmail_set_user_quota — Sets a virtual user's quota
Constante predefinite
vpopmail_add_alias_domain_ex
vpopmail


Add alias to an existing virtual domain

Func?ii vpopmail
vpopmail_add_alias_domain
Func?ii vpopmail
PHP Manual

vpopmail_add_alias_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_alias_domain_ex — Add alias to an existing virtual domain

Descrierea

bool vpopmail_add_alias_domain_ex ( string $olddomain , string $newdomain )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Func?ii vpopmail
vpopmail_add_alias_domain
Func?ii vpopmail


Add an alias for a virtual domain

vpopmail_add_alias_domain_ex
vpopmail_add_domain_ex
Func?ii vpopmail
PHP Manual

vpopmail_add_alias_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_alias_domain — Add an alias for a virtual domain

Descrierea

bool vpopmail_add_alias_domain ( string $domain , string $aliasdomain )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_add_alias_domain_ex
vpopmail_add_domain_ex
Func?ii vpopmail


Add a new virtual domain

vpopmail_add_alias_domain
vpopmail_add_domain
Func?ii vpopmail
PHP Manual

vpopmail_add_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_domain_ex — Add a new virtual domain

Descrierea

bool vpopmail_add_domain_ex ( string $domain , string $passwd [, string $quota [, string $bounce [, bool $apop ]]] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_add_alias_domain
vpopmail_add_domain
Func?ii vpopmail


Add a new virtual domain

vpopmail_add_domain_ex
vpopmail_add_user
Func?ii vpopmail
PHP Manual

vpopmail_add_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_domain — Add a new virtual domain

Descrierea

bool vpopmail_add_domain ( string $domain , string $dir , int $uid , int $gid )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_add_domain_ex
vpopmail_add_user
Func?ii vpopmail


Add a new user to the specified virtual domain

vpopmail_add_domain
vpopmail_alias_add
Func?ii vpopmail
PHP Manual

vpopmail_add_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_user — Add a new user to the specified virtual domain

Descrierea

bool vpopmail_add_user ( string $user , string $domain , string $password [, string $gecos [, bool $apop ]] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_add_domain
vpopmail_alias_add
Func?ii vpopmail


Insert a virtual alias

vpopmail_add_user
vpopmail_alias_del_domain
Func?ii vpopmail
PHP Manual

vpopmail_alias_add

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_add — Insert a virtual alias

Descrierea

bool vpopmail_alias_add ( string $user , string $domain , string $alias )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_add_user
vpopmail_alias_del_domain
Func?ii vpopmail


Deletes all virtual aliases of a domain

vpopmail_alias_add
vpopmail_alias_del
Func?ii vpopmail
PHP Manual

vpopmail_alias_del_domain

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_del_domain — Deletes all virtual aliases of a domain

Descrierea

bool vpopmail_alias_del_domain ( string $domain )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_alias_add
vpopmail_alias_del
Func?ii vpopmail


Deletes all virtual aliases of a user

vpopmail_alias_del_domain
vpopmail_alias_get_all
Func?ii vpopmail
PHP Manual

vpopmail_alias_del

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_del — Deletes all virtual aliases of a user

Descrierea

bool vpopmail_alias_del ( string $user , string $domain )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_alias_del_domain
vpopmail_alias_get_all
Func?ii vpopmail


Get all lines of an alias for a domain

vpopmail_alias_del
vpopmail_alias_get
Func?ii vpopmail
PHP Manual

vpopmail_alias_get_all

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_get_all — Get all lines of an alias for a domain

Descrierea

array vpopmail_alias_get_all ( string $domain )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_alias_del
vpopmail_alias_get
Func?ii vpopmail


Get all lines of an alias for a domain

vpopmail_alias_get_all
vpopmail_auth_user
Func?ii vpopmail
PHP Manual

vpopmail_alias_get

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_get — Get all lines of an alias for a domain

Descrierea

array vpopmail_alias_get ( string $alias , string $domain )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_alias_get_all
vpopmail_auth_user
Func?ii vpopmail


Attempt to validate a username/domain/password

vpopmail_alias_get
vpopmail_del_domain_ex
Func?ii vpopmail
PHP Manual

vpopmail_auth_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_auth_user — Attempt to validate a username/domain/password

Descrierea

bool vpopmail_auth_user ( string $user , string $domain , string $password [, string $apop ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_alias_get
vpopmail_del_domain_ex
Func?ii vpopmail


Delete a virtual domain

vpopmail_auth_user
vpopmail_del_domain
Func?ii vpopmail
PHP Manual

vpopmail_del_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_del_domain_ex — Delete a virtual domain

Descrierea

bool vpopmail_del_domain_ex ( string $domain )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_auth_user
vpopmail_del_domain
Func?ii vpopmail


Delete a virtual domain

vpopmail_del_domain_ex
vpopmail_del_user
Func?ii vpopmail
PHP Manual

vpopmail_del_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_del_domain — Delete a virtual domain

Descrierea

bool vpopmail_del_domain ( string $domain )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_del_domain_ex
vpopmail_del_user
Func?ii vpopmail


Delete a user from a virtual domain

vpopmail_del_domain
vpopmail_error
Func?ii vpopmail
PHP Manual

vpopmail_del_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_del_user — Delete a user from a virtual domain

Descrierea

bool vpopmail_del_user ( string $user , string $domain )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_del_domain
vpopmail_error
Func?ii vpopmail


Ob?ine mesajul textual pentru ultima eroare vpopmail

vpopmail_del_user
vpopmail_passwd
Func?ii vpopmail
PHP Manual

vpopmail_error

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_error — Ob?ine mesajul textual pentru ultima eroare vpopmail

Descrierea

string vpopmail_error ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_del_user
vpopmail_passwd
Func?ii vpopmail


Change a virtual user's password

vpopmail_error
vpopmail_set_user_quota
Func?ii vpopmail
PHP Manual

vpopmail_passwd

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_passwd — Change a virtual user's password

Descrierea

bool vpopmail_passwd ( string $user , string $domain , string $password [, bool $apop ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_error
vpopmail_set_user_quota
Func?ii vpopmail


Sets a virtual user's quota

vpopmail_passwd
Extensii matematice
Func?ii vpopmail
PHP Manual

vpopmail_set_user_quota

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_set_user_quota — Sets a virtual user's quota

Descrierea

bool vpopmail_set_user_quota ( string $user , string $domain , string $quota )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

vpopmail_passwd
Extensii matematice
Func?ii vpopmail


Extensii matematice

  • BC Math — BCMath Arbitrary Precision Mathematics
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii matematice BC
  • GMP — GNU Multiple Precision
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii GMP
    • GMP — The GMP class
  • Lapack
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Lapack — The Lapack class
    • LapackException — The LapackException class
  • Math — Mathematical Functions
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii matematice
  • Statistics
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii statistice
  • Trader — Technical Analysis for Traders
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii trader
vpopmail_set_user_quota
BC Math
Informa?ii de referin?a despre func?ii


BCMath Arbitrary Precision Mathematics

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii matematice BC
    • bcadd — Add two arbitrary precision numbers
    • bccomp — Compare two arbitrary precision numbers
    • bcdiv — Divide two arbitrary precision numbers
    • bcmod — Get modulus of an arbitrary precision number
    • bcmul — Multiply two arbitrary precision numbers
    • bcpow — Raise an arbitrary precision number to another
    • bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
    • bcscale — Set default scale parameter for all bc math functions
    • bcsqrt — Get the square root of an arbitrary precision number
    • bcsub — Subtract one arbitrary precision number from another
Extensii matematice
Introducere
Extensii matematice


Introducere

For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision up to 2147483647-1 (or 0x7FFFFFFF-1) decimals, represented as strings.

BC Math
Instalarea / configurarea
BC Math


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
BC Math


Necesita?i

Since PHP 4.0.4, libbcmath is bundled with PHP. You don't need any external libraries for this extension.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceste func?ii sunt disponibile doar daca PHP a fost configurat cu op?iunea --enable-bcmath .

Versiunea PHP pentru Windows sus?ine implicit aceasta extensie. Nu este nevoie sa încarca?i extensii suplimentare pentru a putea utiliza aceste func?ii.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

BC math configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
bcmath.scale | "0" | PHP_INI_ALL |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

bcmath.scale integer

Number of decimal digits for all bcmath functions. See also bcscale().

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii matematice BC
BC Math


Func?ii matematice BC

Cuprins

  • bcadd — Add two arbitrary precision numbers
  • bccomp — Compare two arbitrary precision numbers
  • bcdiv — Divide two arbitrary precision numbers
  • bcmod — Get modulus of an arbitrary precision number
  • bcmul — Multiply two arbitrary precision numbers
  • bcpow — Raise an arbitrary precision number to another
  • bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
  • bcscale — Set default scale parameter for all bc math functions
  • bcsqrt — Get the square root of an arbitrary precision number
  • bcsub — Subtract one arbitrary precision number from another
Constante predefinite
bcadd
BC Math


Add two arbitrary precision numbers

Func?ii matematice BC
bccomp
Func?ii matematice BC
PHP Manual

bcadd

(PHP 4, PHP 5, PHP 7)

bcadd — Add two arbitrary precision numbers

Descrierea

string bcadd ( string $left_operand , string $right_operand [, int $scale = 0 ] )

Sums left_operand and right_operand.

Parametri

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

Acest parametru op?ional este utilizat pentru a stabili numarul cifrelor dupa virgula din rezultat. Daca este omis, valoarea implicita va fi cea stabilita global cu func?ia bcscale(), sau va fi 0 daca nu a fost stabilita cu ajutorul acestei func?ii.

Valorile întoarse

The sum of the two operands, as a string.

Exemple

Example #1 bcadd() example

<?php

$a = '1.234';
$b = '5';

echo bcadd($a, $b);     // 6
echo bcadd($a, $b, 4);  // 6.2340

?>

A se vedea ?i

  • bcsub() - Subtract one arbitrary precision number from another

Func?ii matematice BC
bccomp
Func?ii matematice BC


Compare two arbitrary precision numbers

bcadd
bcdiv
Func?ii matematice BC
PHP Manual

bccomp

(PHP 4, PHP 5, PHP 7)

bccomp — Compare two arbitrary precision numbers

Descrierea

int bccomp ( string $left_operand , string $right_operand [, int $scale = 0 ] )

Compares the left_operand to the right_operand and returns the result as an integer.

Parametri

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

The optional scale parameter is used to set the number of digits after the decimal place which will be used in the comparison.

Valorile întoarse

Returns 0 if the two operands are equal, 1 if the left_operand is larger than the right_operand, -1 otherwise.

Exemple

Example #1 bccomp() example

<?php

echo bccomp('1', '2') . "\n";   // -1
echo bccomp('1.00001', '1', 3); // 0
echo bccomp('1.00001', '1', 5); // 1

?>
bcadd
bcdiv
Func?ii matematice BC


Divide two arbitrary precision numbers

bccomp
bcmod
Func?ii matematice BC
PHP Manual

bcdiv

(PHP 4, PHP 5, PHP 7)

bcdiv — Divide two arbitrary precision numbers

Descrierea

string bcdiv ( string $left_operand , string $right_operand [, int $scale = 0 ] )

Divides the left_operand by the right_operand.

Parametri

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

Acest parametru op?ional este utilizat pentru a stabili numarul cifrelor dupa virgula din rezultat. Daca este omis, valoarea implicita va fi cea stabilita global cu func?ia bcscale(), sau va fi 0 daca nu a fost stabilita cu ajutorul acestei func?ii.

Valorile întoarse

Returns the result of the division as a string, or NULL if right_operand is 0.

Exemple

Example #1 bcdiv() example

<?php

echo bcdiv('105', '6.55957', 3);  // 16.007

?>

A se vedea ?i

  • bcmul() - Multiply two arbitrary precision numbers

bccomp
bcmod
Func?ii matematice BC


Get modulus of an arbitrary precision number

bcdiv
bcmul
Func?ii matematice BC
PHP Manual

bcmod

(PHP 4, PHP 5, PHP 7)

bcmod — Get modulus of an arbitrary precision number

Descrierea

string bcmod ( string $left_operand , string $modulus )

Get the modulus of the left_operand using modulus.

Parametri

left_operand

The left operand, as a string.

modulus

The modulus, as a string.

Valorile întoarse

Returns the modulus as a string, or NULL if modulus is 0.

Exemple

Example #1 bcmod() example

<?php
echo bcmod('4', '2'); // 0
echo bcmod('2', '4'); // 2
?>

A se vedea ?i

  • bcdiv() - Divide two arbitrary precision numbers

bcdiv
bcmul
Func?ii matematice BC


Multiply two arbitrary precision numbers

bcmod
bcpow
Func?ii matematice BC
PHP Manual

bcmul

(PHP 4, PHP 5, PHP 7)

bcmul — Multiply two arbitrary precision numbers

Descrierea

string bcmul ( string $left_operand , string $right_operand [, int $scale = 0 ] )

Multiply the left_operand by the right_operand.

Parametri

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

Acest parametru op?ional este utilizat pentru a stabili numarul cifrelor dupa virgula din rezultat. Daca este omis, valoarea implicita va fi cea stabilita global cu func?ia bcscale(), sau va fi 0 daca nu a fost stabilita cu ajutorul acestei func?ii.

Valorile întoarse

Returns the result as a string.

Exemple

Example #1 bcmul() example

<?php
echo bcmul('1.34747474747', '35', 3); // 47.161
echo bcmul('2', '4'); // 8
?>

A se vedea ?i

  • bcdiv() - Divide two arbitrary precision numbers

bcmod
bcpow
Func?ii matematice BC


Raise an arbitrary precision number to another

bcmul
bcpowmod
Func?ii matematice BC
PHP Manual

bcpow

(PHP 4, PHP 5, PHP 7)

bcpow — Raise an arbitrary precision number to another

Descrierea

string bcpow ( string $left_operand , string $right_operand [, int $scale = 0 ] )

Raise left_operand to the power right_operand.

Parametri

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

Acest parametru op?ional este utilizat pentru a stabili numarul cifrelor dupa virgula din rezultat. Daca este omis, valoarea implicita va fi cea stabilita global cu func?ia bcscale(), sau va fi 0 daca nu a fost stabilita cu ajutorul acestei func?ii.

Valorile întoarse

Returns the result as a string.

Exemple

Example #1 bcpow() example

<?php

echo bcpow('4.2', '3', 2); // 74.08

?>

Note

Nota:

bcpow() may return a result with fewer digits after the decimal point than the scale parameter would indicate. This only occurs when the result doesn't require all of the precision allowed by the scale. For example:

Example #2 bcpow() scale example

<?php
echo bcpow('5', '2', 2);     // prints "25", not "25.00"
?>

A se vedea ?i

  • bcpowmod() - Raise an arbitrary precision number to another, reduced by a specified modulus
  • bcsqrt() - Get the square root of an arbitrary precision number

bcmul
bcpowmod
Func?ii matematice BC


Raise an arbitrary precision number to another, reduced by a specified modulus

bcpow
bcscale
Func?ii matematice BC
PHP Manual

bcpowmod

(PHP 5, PHP 7)

bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus

Descrierea

string bcpowmod ( string $left_operand , string $right_operand , string $modulus [, int $scale = 0 ] )

Use the fast-exponentiation method to raise left_operand to the power right_operand with respect to the modulus modulus.

Parametri

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

modulus

The modulus, as a string.

scale

Acest parametru op?ional este utilizat pentru a stabili numarul cifrelor dupa virgula din rezultat. Daca este omis, valoarea implicita va fi cea stabilita global cu func?ia bcscale(), sau va fi 0 daca nu a fost stabilita cu ajutorul acestei func?ii.

Valorile întoarse

Returns the result as a string, or NULL if modulus is 0.

Note

Nota:

Because this method uses the modulus operation, numbers which are not positive integers may give unexpected results.

Exemple

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.

?>

A se vedea ?i

  • bcpow() - Raise an arbitrary precision number to another
  • bcmod() - Get modulus of an arbitrary precision number

bcpow
bcscale
Func?ii matematice BC


Set default scale parameter for all bc math functions

bcpowmod
bcsqrt
Func?ii matematice BC
PHP Manual

bcscale

(PHP 4, PHP 5, PHP 7)

bcscale — Set default scale parameter for all bc math functions

Descrierea

bool bcscale ( int $scale )

Sets the default scale parameter for all subsequent calls to bc math functions that do not explicitly specify a scale parameter.

Parametri

scale

The scale factor.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 bcscale() example

<?php

// default scale : 3
bcscale(3);
echo bcdiv('105', '6.55957'); // 16.007

// this is the same without bcscale()
echo bcdiv('105', '6.55957', 3); // 16.007

?>

bcpowmod
bcsqrt
Func?ii matematice BC


Get the square root of an arbitrary precision number

bcscale
bcsub
Func?ii matematice BC
PHP Manual

bcsqrt

(PHP 4, PHP 5, PHP 7)

bcsqrt — Get the square root of an arbitrary precision number

Descrierea

string bcsqrt ( string $operand [, int $scale = 0 ] )

Return the square root of the operand.

Parametri

operand

The operand, as a string.

scale

Acest parametru op?ional este utilizat pentru a stabili numarul cifrelor dupa virgula din rezultat. Daca este omis, valoarea implicita va fi cea stabilita global cu func?ia bcscale(), sau va fi 0 daca nu a fost stabilita cu ajutorul acestei func?ii.

Valorile întoarse

Returns the square root as a string, or NULL if operand is negative.

Exemple

Example #1 bcsqrt() example

<?php

echo bcsqrt('2', 3); // 1.414

?>

A se vedea ?i

  • bcpow() - Raise an arbitrary precision number to another

bcscale
bcsub
Func?ii matematice BC


Subtract one arbitrary precision number from another

bcsqrt
GMP
Func?ii matematice BC
PHP Manual

bcsub

(PHP 4, PHP 5, PHP 7)

bcsub — Subtract one arbitrary precision number from another

Descrierea

string bcsub ( string $left_operand , string $right_operand [, int $scale = 0 ] )

Subtracts the right_operand from the left_operand.

Parametri

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

Acest parametru op?ional este utilizat pentru a stabili numarul cifrelor dupa virgula din rezultat. Daca este omis, valoarea implicita va fi cea stabilita global cu func?ia bcscale(), sau va fi 0 daca nu a fost stabilita cu ajutorul acestei func?ii.

Valorile întoarse

The result of the subtraction, as a string.

Exemple

Example #1 bcsub() example

<?php

$a = '1.234';
$b = '5';

echo bcsub($a, $b);     // -3
echo bcsub($a, $b, 4);  // -3.7660

?>

A se vedea ?i

  • bcadd() - Add two arbitrary precision numbers

bcsqrt
GMP
Func?ii matematice BC


GNU Multiple Precision

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii GMP
    • 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 — Pseudonim pentru gmp_div_q
    • gmp_divexact — Exact division of numbers
    • gmp_export — Export to a binary string
    • gmp_fact — Factorial
    • gmp_gcd — Calculate GCD
    • gmp_gcdext — Calculate GCD and multipliers
    • gmp_hamdist — Hamming distance
    • gmp_import — Import from a binary string
    • 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_bits — Random number
    • gmp_random_range — Random number
    • gmp_random_seed — Sets the RNG seed
    • gmp_random — Random number
    • gmp_root — Take the integer part of nth root
    • gmp_rootrem — Take the integer part and remainder of nth root
    • 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
  • GMP — The GMP class
bcsub
Introducere
Extensii matematice


Introducere

These functions allow for arbitrary-length integers to be worked with using the GNU MP library.

Nota:

Most GMP functions accept GMP number arguments. These are shown in this documentation as GMP objects. However, note that PHP 5.5 and earlier represented GMP numbers as resources. Most of these functions will also accept numeric and string arguments, so long as it is possible to convert the latter to a number. Also, if there is a more performant function that can operate on the arguments (integers only), then it will be used instead (this is done transparently). See also the gmp_init() function.

Nota:

From PHP 5.6 onwards, the arithmetic, bitwise, and comparison operators may be used with the GMP objects returned from gmp_init() and other GMP functions.

Avertizare

Large integers must be specified as strings - otherwise, PHP will coerce them to floats, resulting in a loss of precision.

Nota: This extension is available on Windows platforms since PHP 5.1.0.

GMP
Instalarea / configurarea
GMP


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
GMP


Necesita?i

The GMP library can be downloaded from » http://gmplib.org/#DOWNLOAD. This site also has the GMP manual available.

At least GMP version 2 is required, with some functions requiring a more recent version of the GMP library.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Pentru a avea disponibile aceste func?ii este nevoie de a compila PHP cu sus?inerea GMP utilizând op?iunea --with-gmp .

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

Prior to PHP 5.6, most GMP functions operate on or return GMP number resources. PHP 5.6 onwards uses GMP objects in place of GMP number resources.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

GMP_ROUND_ZERO (integer)
GMP_ROUND_PLUSINF (integer)
GMP_ROUND_MINUSINF (integer)
GMP_MSW_FIRST (integer)
GMP_LSW_FIRST (integer)
GMP_LITTLE_ENDIAN (integer)
GMP_BIG_ENDIAN (integer)
GMP_NATIVE_ENDIAN (integer)
GMP_VERSION (string)
The GMP library version
Tipurile resurselor
Exemple
GMP


Exemple

Example #1 Exemplu de func?ie factoriala utilizând 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";
?>

Acest exemplu va calcula factorialul 1000 (un numar destul de mare) foarte repede.

Constante predefinite
Func?ii GMP
GMP


Func?ii GMP

A se vedea ?i

Mai multe func?ii matematice pot fi gasite în sec?iunea Extensii matematice.

Cuprins

  • 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 — Pseudonim pentru gmp_div_q
  • gmp_divexact — Exact division of numbers
  • gmp_export — Export to a binary string
  • gmp_fact — Factorial
  • gmp_gcd — Calculate GCD
  • gmp_gcdext — Calculate GCD and multipliers
  • gmp_hamdist — Hamming distance
  • gmp_import — Import from a binary string
  • 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_bits — Random number
  • gmp_random_range — Random number
  • gmp_random_seed — Sets the RNG seed
  • gmp_random — Random number
  • gmp_root — Take the integer part of nth root
  • gmp_rootrem — Take the integer part and remainder of nth root
  • 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
Exemple
gmp_abs
GMP


Absolute value

Func?ii GMP
gmp_add
Func?ii GMP
PHP Manual

gmp_abs

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_abs — Absolute value

Descrierea

GMP gmp_abs ( GMP $a )

Get the absolute value of a number.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Returns the absolute value of a, as a GMP number.

Exemple

Example #1 gmp_abs() example

<?php
$abs1 = gmp_abs("274982683358");
$abs2 = gmp_abs("-274982683358");

echo gmp_strval($abs1) . "\n";
echo gmp_strval($abs2) . "\n";
?>

Exemplul de mai sus va afi?a:

274982683358
274982683358

Func?ii GMP
gmp_add
Func?ii GMP


Add numbers

gmp_abs
gmp_and
Func?ii GMP
PHP Manual

gmp_add

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_add — Add numbers

Descrierea

GMP gmp_add ( GMP $a , GMP $b )

Add two numbers.

Parametri

a

The first summand (augent).

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

b

The second summand (addend).

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

A GMP number representing the sum of the arguments.

Exemple

Example #1 gmp_add() example

<?php
$sum = gmp_add("123456789012345", "76543210987655");
echo gmp_strval($sum) . "\n";
?>

Exemplul de mai sus va afi?a:

200000000000000

gmp_abs
gmp_and
Func?ii GMP


Bitwise AND

gmp_add
gmp_clrbit
Func?ii GMP
PHP Manual

gmp_and

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_and — Bitwise AND

Descrierea

GMP gmp_and ( GMP $a , GMP $b )

Calculates bitwise AND of two GMP numbers.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

b

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

A GMP number representing the bitwise AND comparison.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

4
0
gmp_add
gmp_clrbit
Func?ii GMP


Clear bit

gmp_and
gmp_cmp
Func?ii GMP
PHP Manual

gmp_clrbit

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_clrbit — Clear bit

Descrierea

void gmp_clrbit ( GMP $a , int $index )

Clears (sets to 0) bit index in a. The index starts at 0.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

index

The index of the bit to clear. Index 0 represents the least significant bit.

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

254

Note

Nota:

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.

A se vedea ?i

  • gmp_setbit() - Set bit
  • gmp_testbit() - Tests if a bit is set

gmp_and
gmp_cmp
Func?ii GMP


Compare numbers

gmp_clrbit
gmp_com
Func?ii GMP
PHP Manual

gmp_cmp

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_cmp — Compare numbers

Descrierea

int gmp_cmp ( GMP $a , GMP $b )

Compares two numbers.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

b

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Returns a positive value if a > b, zero if a = b and a negative value if a < b.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

1 -1 0
gmp_clrbit
gmp_com
Func?ii GMP


Calculates one's complement

gmp_cmp
gmp_div_q
Func?ii GMP
PHP Manual

gmp_com

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_com — Calculates one's complement

Descrierea

GMP gmp_com ( GMP $a )

Returns the one's complement of a.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Returns the one's complement of a, as a GMP number.

Exemple

Example #1 gmp_com() example

<?php
$com = gmp_com("1234");
echo gmp_strval($com) . "\n";
?>

Exemplul de mai sus va afi?a:

-1235
gmp_cmp
gmp_div_q
Func?ii GMP


Divide numbers

gmp_com
gmp_div_qr
Func?ii GMP
PHP Manual

gmp_div_q

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_div_q — Divide numbers

Descrierea

GMP gmp_div_q ( GMP $a , GMP $b [, int $round = GMP_ROUND_ZERO ] )

Divides a by b and returns the integer result.

Parametri

a

The number being divided.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

b

The number that a is being divided by.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

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.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

20
0
1
0
-1

Note

Nota:

This function can also be called as gmp_div().

A se vedea ?i

  • gmp_div_r() - Remainder of the division of numbers
  • gmp_div_qr() - Divide numbers and get quotient and remainder

gmp_com
gmp_div_qr
Func?ii GMP


Divide numbers and get quotient and remainder

gmp_div_q
gmp_div_r
Func?ii GMP
PHP Manual

gmp_div_qr

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_div_qr — Divide numbers and get quotient and remainder

Descrierea

array gmp_div_qr ( GMP $n , GMP $d [, int $round = GMP_ROUND_ZERO ] )

The function divides n by d.

Parametri

n

The number being divided.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

d

The number that n is being divided by.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

round

See the gmp_div_q() function for description of the round argument.

Valorile întoarse

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).

Exemple

Example #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]));
?>

A se vedea ?i

  • gmp_div_q() - Divide numbers
  • gmp_div_r() - Remainder of the division of numbers

gmp_div_q
gmp_div_r
Func?ii GMP


Remainder of the division of numbers

gmp_div_qr
gmp_div
Func?ii GMP
PHP Manual

gmp_div_r

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_div_r — Remainder of the division of numbers

Descrierea

GMP gmp_div_r ( GMP $n , GMP $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.

Parametri

n

The number being divided.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

d

The number that n is being divided by.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

round

See the gmp_div_q() function for description of the round argument.

Valorile întoarse

The remainder, as a GMP number.

Exemple

Example #1 gmp_div_r() example

<?php
$div = gmp_div_r("105", "20");
echo gmp_strval($div) . "\n";
?>

Exemplul de mai sus va afi?a:

5

A se vedea ?i

  • gmp_div_q() - Divide numbers
  • gmp_div_qr() - Divide numbers and get quotient and remainder

gmp_div_qr
gmp_div
Func?ii GMP


Pseudonim pentru gmp_div_q

gmp_div_r
gmp_divexact
Func?ii GMP
PHP Manual

gmp_div

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_div — Pseudonim pentru gmp_div_q()

Descrierea

Aceasta func?ie este pseudonim pentru: gmp_div_q().

gmp_div_r
gmp_divexact
Func?ii GMP


Exact division of numbers

gmp_div
gmp_export
Func?ii GMP
PHP Manual

gmp_divexact

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_divexact — Exact division of numbers

Descrierea

GMP gmp_divexact ( GMP $n , GMP $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.

Parametri

n

The number being divided.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

d

The number that a is being divided by.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

5
2863311534

gmp_div
gmp_export
Func?ii GMP


Export to a binary string

gmp_divexact
gmp_fact
Func?ii GMP
PHP Manual

gmp_export

(PHP 5 >= 5.6.1, PHP 7)

gmp_export — Export to a binary string

Descrierea

string gmp_export ( GMP $gmpnumber , integer $word_size , integer $options )

Export a GMP number to a binary string

Parametri

gmpnumber

The GMP number being exported

word_size

Default value is 1. The number of bytes in each chunk of binary data. This is mainly used in conjunction with the options parameter.

options

Default value is GMP_MSW_FIRST | GMP_NATIVE_ENDIAN.

Valorile întoarse

Returns a string sau FALSE în cazul e?ecului.

Exemple

Example #1 gmp_export() example

<?php
$number = gmp_init(16705);
echo gmp_export($number) . "\n";
?>

Exemplul de mai sus va afi?a:

AA

gmp_divexact
gmp_fact
Func?ii GMP


Factorial

gmp_export
gmp_gcd
Func?ii GMP
PHP Manual

gmp_fact

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_fact — Factorial

Descrierea

GMP gmp_fact ( mixed $a )

Calculates factorial (a!) of a.

Parametri

a

The factorial number.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

120
30414093201713378043612608166064768844377641568960512000000000000

gmp_export
gmp_gcd
Func?ii GMP


Calculate GCD

gmp_fact
gmp_gcdext
Func?ii GMP
PHP Manual

gmp_gcd

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_gcd — Calculate GCD

Descrierea

GMP gmp_gcd ( GMP $a , GMP $b )

Calculate greatest common divisor of a and b. The result is always positive even if either of, or both, input operands are negative.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

b

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

A positive GMP number that divides into both a and b.

Exemple

Example #1 gmp_gcd() example

<?php
$gcd = gmp_gcd("12", "21");
echo gmp_strval($gcd) . "\n";
?>

Exemplul de mai sus va afi?a:

3

gmp_fact
gmp_gcdext
Func?ii GMP


Calculate GCD and multipliers

gmp_gcd
gmp_hamdist
Func?ii GMP
PHP Manual

gmp_gcdext

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_gcdext — Calculate GCD and multipliers

Descrierea

array gmp_gcdext ( GMP $a , GMP $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

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

b

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

An array of GMP numbers.

Exemple

Example #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
Func?ii GMP


Hamming distance

gmp_gcdext
gmp_import
Func?ii GMP
PHP Manual

gmp_hamdist

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_hamdist — Hamming distance

Descrierea

int gmp_hamdist ( GMP $a , GMP $b )

Returns the hamming distance between a and b. Both operands should be non-negative.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

It should be positive.

b

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

It should be positive.

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Exemple

Example #1 gmp_hamdist() example

<?php
$ham1 = gmp_init("1001010011", 2);
$ham2 = gmp_init("1011111100", 2);
echo gmp_hamdist($ham1, $ham2) . "\n";

/* hamdist is equivalent to: */
echo gmp_popcount(gmp_xor($ham1, $ham2)) . "\n";
?>

Exemplul de mai sus va afi?a:

6
6

A se vedea ?i

  • gmp_popcount() - Population count
  • gmp_xor() - Bitwise XOR

gmp_gcdext
gmp_import
Func?ii GMP


Import from a binary string

gmp_hamdist
gmp_init
Func?ii GMP
PHP Manual

gmp_import

(PHP 5 >= 5.6.1, PHP 7)

gmp_import — Import from a binary string

Descrierea

GMP gmp_import ( string $data , integer $word_size , integer $options )

Import a GMP number from a binary string

Parametri

data

The binary string being imported

word_size

Default value is 1. The number of bytes in each chunk of binary data. This is mainly used in conjunction with the options parameter.

options

Default value is GMP_MSW_FIRST | GMP_NATIVE_ENDIAN.

Valorile întoarse

Returns a GMP number sau FALSE în cazul e?ecului.

Exemple

Example #1 gmp_import() example

<?php
$number = gmp_import("\0");
echo gmp_strval($number) . "\n";

$number = gmp_import("\0\1\2");
echo gmp_strval($number) . "\n";
?>

Exemplul de mai sus va afi?a:

0
258

gmp_hamdist
gmp_init
Func?ii GMP


Create GMP number

gmp_import
gmp_intval
Func?ii GMP
PHP Manual

gmp_init

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_init — Create GMP number

Descrierea

GMP gmp_init ( mixed $number [, int $base = 0 ] )

Creates a GMP number from an integer or string.

Parametri

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.

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Istoricul schimbarilor

Versiune | Descriere
5.3.2 | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.

Note

Nota:

To use the extended base introduced in PHP 5.3.2, then PHP must be compiled against GMP 4.2.0 or greater.

Exemple

Example #1 Creating GMP number

<?php
$a = gmp_init(123456);
$b = gmp_init("0xFFFFDEBACDFEDF7200");
?>

Note

Nota:

It is not necessary to call this function in order to use integers or strings in place of GMP numbers in GMP functions (such as with 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_import
gmp_intval
Func?ii GMP


Convert GMP number to integer

gmp_init
gmp_invert
Func?ii GMP
PHP Manual

gmp_intval

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_intval — Convert GMP number to integer

Descrierea

int gmp_intval ( GMP $gmpnumber )

This function converts GMP number into native PHP integers.

Parametri

gmpnumber

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

The integer value of gmpnumber.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

2147483647
2147483647
2147483648

Note

Avertizare

This function returns a useful result only if the number actually fits the PHP integer (i.e., signed long type). To simply print the GMP number, use gmp_strval().

gmp_init
gmp_invert
Func?ii GMP


Inverse by modulo

gmp_intval
gmp_jacobi
Func?ii GMP
PHP Manual

gmp_invert

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_invert — Inverse by modulo

Descrierea

GMP gmp_invert ( GMP $a , GMP $b )

Computes the inverse of a modulo b.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

b

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

A GMP number on success or FALSE if an inverse does not exist.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

9

gmp_intval
gmp_jacobi
Func?ii GMP


Jacobi symbol

gmp_invert
gmp_legendre
Func?ii GMP
PHP Manual

gmp_jacobi

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_jacobi — Jacobi symbol

Descrierea

int gmp_jacobi ( GMP $a , GMP $p )

Computes » Jacobi symbol of a and p. p should be odd and must be positive.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

p

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Should be odd and must be positive.

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Exemple

Example #1 gmp_jacobi() example

<?php
echo gmp_jacobi("1", "3") . "\n";
echo gmp_jacobi("2", "3") . "\n";
?>

Exemplul de mai sus va afi?a:

1
0

gmp_invert
gmp_legendre
Func?ii GMP


Legendre symbol

gmp_jacobi
gmp_mod
Func?ii GMP
PHP Manual

gmp_legendre

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_legendre — Legendre symbol

Descrierea

int gmp_legendre ( GMP $a , GMP $p )

Compute the » Legendre symbol of a and p. p should be odd and must be positive.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

p

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Should be odd and must be positive.

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Exemple

Example #1 gmp_legendre() example

<?php
echo gmp_legendre("1", "3") . "\n";
echo gmp_legendre("2", "3") . "\n";
?>

Exemplul de mai sus va afi?a:

1
0

gmp_jacobi
gmp_mod
Func?ii GMP


Modulo operation

gmp_legendre
gmp_mul
Func?ii GMP
PHP Manual

gmp_mod

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_mod — Modulo operation

Descrierea

GMP gmp_mod ( GMP $n , GMP $d )

Calculates n modulo d. The result is always non-negative, the sign of d is ignored.

Parametri

n

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

d

The modulo that is being evaluated.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Exemple

Example #1 gmp_mod() example

<?php
$mod = gmp_mod("8", "3");
echo gmp_strval($mod) . "\n";
?>

Exemplul de mai sus va afi?a:

2

gmp_legendre
gmp_mul
Func?ii GMP


Multiply numbers

gmp_mod
gmp_neg
Func?ii GMP
PHP Manual

gmp_mul

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_mul — Multiply numbers

Descrierea

GMP gmp_mul ( GMP $a , GMP $b )

Multiplies a by b and returns the result.

Parametri

a

A number that will be multiplied by b.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

b

A number that will be multiplied by a.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Exemple

Example #1 gmp_mul() example

<?php
$mul = gmp_mul("12345678", "2000");
echo gmp_strval($mul) . "\n";
?>

Exemplul de mai sus va afi?a:

24691356000

gmp_mod
gmp_neg
Func?ii GMP


Negate number

gmp_mul
gmp_nextprime
Func?ii GMP
PHP Manual

gmp_neg

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_neg — Negate number

Descrierea

GMP gmp_neg ( GMP $a )

Returns the negative value of a number.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Returns -a, as a GMP number.

Exemple

Example #1 gmp_neg() example

<?php
$neg1 = gmp_neg("1");
echo gmp_strval($neg1) . "\n";
$neg2 = gmp_neg("-1");
echo gmp_strval($neg2) . "\n";
?>

Exemplul de mai sus va afi?a:

-1
1

gmp_mul
gmp_nextprime
Func?ii GMP


Find next prime number

gmp_neg
gmp_or
Func?ii GMP
PHP Manual

gmp_nextprime

(PHP 5 >= 5.2.0, PHP 7)

gmp_nextprime — Find next prime number

Descrierea

GMP gmp_nextprime ( int $a )

Find next prime number

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Return the next prime number greater than a, as a GMP number.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

11
-997

Note

Nota:

This function uses a probabilistic algorithm to identify primes and chances to get a composite number are extremely small.

gmp_neg
gmp_or
Func?ii GMP


Bitwise OR

gmp_nextprime
gmp_perfect_square
Func?ii GMP
PHP Manual

gmp_or

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_or — Bitwise OR

Descrierea

GMP gmp_or ( GMP $a , GMP $b )

Calculates bitwise inclusive OR of two GMP numbers.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

b

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

fffffff6
fffffff2

gmp_nextprime
gmp_perfect_square
Func?ii GMP


Perfect square check

gmp_or
gmp_popcount
Func?ii GMP
PHP Manual

gmp_perfect_square

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_perfect_square — Perfect square check

Descrierea

bool gmp_perfect_square ( GMP $a )

Check if a number is a perfect square.

Parametri

a

The number being checked as a perfect square.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Returns TRUE if a is a perfect square, FALSE otherwise.

Exemple

Example #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"));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)
bool(true)

A se vedea ?i

  • gmp_sqrt() - Calculate square root
  • gmp_sqrtrem() - Square root with remainder

gmp_or
gmp_popcount
Func?ii GMP


Population count

gmp_perfect_square
gmp_pow
Func?ii GMP
PHP Manual

gmp_popcount

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_popcount — Population count

Descrierea

int gmp_popcount ( GMP $a )

Get the population count.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

The population count of a, as an integer.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

3
7

gmp_perfect_square
gmp_pow
Func?ii GMP


Raise number into power

gmp_popcount
gmp_powm
Func?ii GMP
PHP Manual

gmp_pow

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_pow — Raise number into power

Descrierea

GMP gmp_pow ( GMP $base , int $exp )

Raise base into power exp.

Parametri

base

The base number.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

exp

The positive power to raise the base.

Valorile întoarse

The new (raised) number, as a GMP number. The case of 0^0 yields 1.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

2147483648
1

gmp_popcount
gmp_powm
Func?ii GMP


Raise number into power with modulo

gmp_pow
gmp_prob_prime
Func?ii GMP
PHP Manual

gmp_powm

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_powm — Raise number into power with modulo

Descrierea

GMP gmp_powm ( GMP $base , GMP $exp , GMP $mod )

Calculate (base raised into power exp) modulo mod. If exp is negative, result is undefined.

Parametri

base

The base number.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

exp

The positive power to raise the base.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

mod

The modulo.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

The new (raised) number, as a GMP number.

Exemple

Example #1 gmp_powm() example

<?php
$pow1 = gmp_powm("2", "31", "2147483649");
echo gmp_strval($pow1) . "\n";
?>

Exemplul de mai sus va afi?a:

2147483648

gmp_pow
gmp_prob_prime
Func?ii GMP


Check if number is "probably prime"

gmp_powm
gmp_random_bits
Func?ii GMP
PHP Manual

gmp_prob_prime

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_prob_prime — Check if number is "probably prime"

Descrierea

int gmp_prob_prime ( GMP $a [, int $reps = 10 ] )

The function uses Miller-Rabin's probabilistic test to check if a number is a prime.

Parametri

a

The number being checked as a prime.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

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.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

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.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

0
1
2

gmp_powm
gmp_random_bits
Func?ii GMP


Random number

gmp_prob_prime
gmp_random_range
Func?ii GMP
PHP Manual

gmp_random_bits

(PHP 5 >= 5.6.3, PHP 7)

gmp_random_bits — Random number

Descrierea

GMP gmp_random_bits ( integer $bits )

Generate a random number. The number will be between 0 and (2 ** bits) - 1.

bits must greater than 0, and the maximum value is restricted by available memory.

Parametri

bits

The number of bits.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

A random GMP number.

Exemple

Example #1 gmp_random_bits() example

<?php
$rand1 = gmp_random_bits(3); // random number from 0 to 7
$rand2 = gmp_random_bits(5); // random number from 0 to 31

echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>

Exemplul de mai sus va afi?a:

3
15

gmp_prob_prime
gmp_random_range
Func?ii GMP


Random number

gmp_random_bits
gmp_random_seed
Func?ii GMP
PHP Manual

gmp_random_range

(PHP 5 >= 5.6.3, PHP 7)

gmp_random_range — Random number

Descrierea

GMP gmp_random_range ( GMP $min , GMP $max )

Generate a random number. The number will be between min and max.

min and max can both be negative but min must always be less than max.

Parametri

min

A GMP number representing the lower bound for the random number

max

A GMP number representing the upper bound for the random number

Valorile întoarse

A random GMP number.

Exemple

Example #1 gmp_random_range() example

<?php
$rand1 = gmp_random_range(0, 100);    // random number between 0 and 100
$rand2 = gmp_random_range(-100, -10); // random number between -100 and -10

echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>

Exemplul de mai sus va afi?a:

42
-67

gmp_random_bits
gmp_random_seed
Func?ii GMP


Sets the RNG seed

gmp_random_range
gmp_random
Func?ii GMP
PHP Manual

gmp_random_seed

(PHP 7)

gmp_random_seed — Sets the RNG seed

Descrierea

mixed gmp_random_seed ( mixed $seed )

Parametri

seed

The seed to be set for the gmp_random(), gmp_random_bits(), and gmp_random_range() functions.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Returns NULL on success.

Erori/Excep?ii

Issues an E_WARNING and returns FALSE if seed is not valid.

Exemple

Example #1 gmp_random_seed() example

<?php
// set the seed
gmp_random_seed(100);

var_dump(gmp_strval(gmp_random(1)));

// set the seed to something else
gmp_random_seed(gmp_init(-100));

var_dump(gmp_strval(gmp_random_bits(10)));

// set the seed to something invalid
var_dump(gmp_random_seed('not a number'));

Exemplul de mai sus va afi?a:

string(20) "15370156633245019617"
string(3) "683"

Warning: gmp_random_seed(): Unable to convert variable to GMP - string is not an integer in %s on line %d
bool(false)

A se vedea ?i

  • gmp_init() - Create GMP number
  • gmp_random() - Random number
  • gmp_random_bits() - Random number
  • gmp_random_range() - Random number
gmp_random_range
gmp_random
Func?ii GMP


Random number

gmp_random_seed
gmp_root
Func?ii GMP
PHP Manual

gmp_random

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_random — Random number

Descrierea

GMP 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.

Parametri

limiter

The limiter.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

A random GMP number.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

1915834968
8642564075890328087

gmp_random_seed
gmp_root
Func?ii GMP


Take the integer part of nth root

gmp_random
gmp_rootrem
Func?ii GMP
PHP Manual

gmp_root

(PHP 5 >= 5.6.0, PHP 7)

gmp_root — Take the integer part of nth root

Descrierea

GMP gmp_root ( GMP $a , int $nth )

Takes the nth root of a and returns the integer component of the result.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

nth

The positive root to take of a.

Valorile întoarse

The integer component of the resultant root, as a GMP number.

gmp_random
gmp_rootrem
Func?ii GMP


Take the integer part and remainder of nth root

gmp_root
gmp_scan0
Func?ii GMP
PHP Manual

gmp_rootrem

(PHP 5 >= 5.6.0, PHP 7)

gmp_rootrem — Take the integer part and remainder of nth root

Descrierea

array gmp_rootrem ( GMP $a , int $nth )

Takes the nth root of a and returns the integer component and remainder of the result.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

nth

The positive root to take of a.

Valorile întoarse

A two element array, where the first element is the integer component of the root, and the second element is the remainder, both represented as GMP numbers.

gmp_root
gmp_scan0
Func?ii GMP


Scan for 0

gmp_rootrem
gmp_scan1
Func?ii GMP
PHP Manual

gmp_scan0

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_scan0 — Scan for 0

Descrierea

int gmp_scan0 ( GMP $a , int $start )

Scans a, starting with bit start, towards more significant bits, until the first clear bit is found.

Parametri

a

The number to scan.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

start

The starting bit.

Valorile întoarse

Returns the index of the found bit, as an integer. The index starts from 0.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

3
7

gmp_rootrem
gmp_scan1
Func?ii GMP


Scan for 1

gmp_scan0
gmp_setbit
Func?ii GMP
PHP Manual

gmp_scan1

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_scan1 — Scan for 1

Descrierea

int gmp_scan1 ( GMP $a , int $start )

Scans a, starting with bit start, towards more significant bits, until the first set bit is found.

Parametri

a

The number to scan.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

start

The starting bit.

Valorile întoarse

Returns the index of the found bit, as an integer. If no set bit is found, -1 is returned.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

3
9

gmp_scan0
gmp_setbit
Func?ii GMP


Set bit

gmp_scan1
gmp_sign
Func?ii GMP
PHP Manual

gmp_setbit

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_setbit — Set bit

Descrierea

void gmp_setbit ( GMP &$a , int $index [, bool $bit_on = true ] )

Sets bit index in a.

Parametri

a

The value to modify.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

index

The index of the bit to set. Index 0 represents the least significant bit.

bit_on

True to set the bit (set it to 1/on); false to clear the bit (set it to 0/off).

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Exemple

Example #1 gmp_setbit() example - 0 index

<?php
$a = gmp_init("2"); //
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
gmp_setbit($a, 0); // 0b10 now becomes 0b11
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
?>

Exemplul de mai sus va afi?a:

2 -> 0b10
3 -> 0b11

Example #2 gmp_setbit() example - 1 index

<?php
$a = gmp_init("0xfd");
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
gmp_setbit($a, 1); // index starts at 0
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
?>

Exemplul de mai sus va afi?a:

253 -> 0b11111101
255 -> 0b11111111

Example #3 gmp_setbit() example - clearing a bit

<?php
$a = gmp_init("0xff");
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
gmp_setbit($a, 0, false); // clear bit at index 0
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
?>

Exemplul de mai sus va afi?a:

255 -> 0b11111111
254 -> 0b11111110

Note

Nota:

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.

A se vedea ?i

  • gmp_clrbit() - Clear bit
  • gmp_testbit() - Tests if a bit is set

gmp_scan1
gmp_sign
Func?ii GMP


Sign of number

gmp_setbit
gmp_sqrt
Func?ii GMP
PHP Manual

gmp_sign

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_sign — Sign of number

Descrierea

int gmp_sign ( GMP $a )

Checks the sign of a number.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Returns 1 if a is positive, -1 if a is negative, and 0 if a is zero.

Exemple

Example #1 gmp_sign() example

<?php
// positive
echo gmp_sign("500") . "\n";

// negative
echo gmp_sign("-500") . "\n";

// zero
echo gmp_sign("0") . "\n";
?>

Exemplul de mai sus va afi?a:

1
-1
0

A se vedea ?i

  • gmp_abs() - Absolute value
  • abs() - Absolute value

gmp_setbit
gmp_sqrt
Func?ii GMP


Calculate square root

gmp_sign
gmp_sqrtrem
Func?ii GMP
PHP Manual

gmp_sqrt

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_sqrt — Calculate square root

Descrierea

GMP gmp_sqrt ( GMP $a )

Calculates square root of a.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

The integer portion of the square root, as a GMP number.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

3
2
1234567890

gmp_sign
gmp_sqrtrem
Func?ii GMP


Square root with remainder

gmp_sqrt
gmp_strval
Func?ii GMP
PHP Manual

gmp_sqrtrem

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_sqrtrem — Square root with remainder

Descrierea

array gmp_sqrtrem ( GMP $a )

Calculate the square root of a number, with remainder.

Parametri

a

The number being square rooted.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

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).

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

3, 0
2, 3
1024, 0

gmp_sqrt
gmp_strval
Func?ii GMP


Convert GMP number to string

gmp_sqrtrem
gmp_sub
Func?ii GMP
PHP Manual

gmp_strval

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_strval — Convert GMP number to string

Descrierea

string gmp_strval ( GMP $gmpnumber [, int $base = 10 ] )

Convert GMP number to string representation in base base. The default base is 10.

Parametri

gmpnumber

The GMP number that will be converted to a string.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

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.

Valorile întoarse

The number, as a string.

Istoricul schimbarilor

Versiune | Descriere
5.3.2 | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.

Note

Nota:

To use the extended base introduced in PHP 5.3.2, then PHP must be compiled against GMP 4.2.0 or greater.

Exemple

Example #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
Func?ii GMP


Subtract numbers

gmp_strval
gmp_testbit
Func?ii GMP
PHP Manual

gmp_sub

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_sub — Subtract numbers

Descrierea

GMP gmp_sub ( GMP $a , GMP $b )

Subtracts b from a and returns the result.

Parametri

a

The number being subtracted from.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

b

The number subtracted from a.

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Exemple

Example #1 gmp_sub() example

<?php
$sub = gmp_sub("281474976710656", "4294967296"); // 2^48 - 2^32
echo gmp_strval($sub) . "\n";
?>

Exemplul de mai sus va afi?a:

281470681743360

gmp_strval
gmp_testbit
Func?ii GMP


Tests if a bit is set

gmp_sub
gmp_xor
Func?ii GMP
PHP Manual

gmp_testbit

(PHP 5 >= 5.3.0, PHP 7)

gmp_testbit — Tests if a bit is set

Descrierea

bool gmp_testbit ( GMP $a , int $index )

Tests if the specified bit is set.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

index

The bit to test

Valorile întoarse

Returns TRUE if the bit is set in resource $a, otherwise FALSE.

Erori/Excep?ii

An E_WARNING level error is issued when index is less than zero, and FALSE is returned.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

A se vedea ?i

  • gmp_setbit() - Set bit
  • gmp_clrbit() - Clear bit

gmp_sub
gmp_xor
Func?ii GMP


Bitwise XOR

gmp_testbit
GMP
Func?ii GMP
PHP Manual

gmp_xor

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_xor — Bitwise XOR

Descrierea

GMP gmp_xor ( GMP $a , GMP $b )

Calculates bitwise exclusive OR (XOR) of two GMP numbers.

Parametri

a

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

b

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, un obiect GMP în PHP 5.6 ?i ultrior, su un ?ir de caractere numeric atunci când acesta poate fi convertit într-un numar.

Valorile întoarse

Un numar GMP sub forma de resource în PHP 5.5 ?i anterior, sau obiect GMP în PHP 5.6 ?i ulterior.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

1011110111000100

gmp_testbit
GMP
Func?ii GMP


The GMP class

(PHP 5 >= 5.6.0, PHP 7)

Introducere

A GMP number. These objects support overloaded arithmetic, bitwise and comparison operators.

Nota:

No object oriented interface is provided to manipulate GMP objects. Please use the procedural GMP API.

GMP implements Serializable {
}
gmp_xor
Lapack
GMP


Lapack

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Lapack — The Lapack class
    • Lapack::eigenValues — This function returns the eigenvalues for a given square matrix
    • Lapack::identity — Return an identity matrix
    • Lapack::leastSquaresByFactorisation — Calculate the linear least squares solution of a matrix using QR factorisation
    • Lapack::leastSquaresBySVD — Solve the linear least squares problem, using SVD
    • Lapack::pseudoInverse — Calculate the inverse of a matrix
    • Lapack::singularValues — Calculated the singular values of a matrix
    • Lapack::solveLinearEquation — Solve a system of linear equations
  • LapackException — The LapackException class
GMP
Introducere
Extensii matematice


Introducere

LAPACK is written in Fortran 90 and provides routines for solving systems of simultaneous linear equations, least-squares solutions of linear systems of equations, eigenvalue problems, and singular value problems. This extension wraps the LAPACKE C bindings to allow access to several processes exposed by the library. Most functions work with arrays of arrays, representing rectangular matrices in row major order - so a two by two matrix [1 2; 3 4] would be array(array(1, 2), array(3, 4))

Lapack
Instalarea / configurarea
Lapack


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Lapack


Necesita?i

Lapack requires the LAPACK and LAPACKE libraries.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Most distribution LAPACK packages do not include lapacke, so the easiest method is to build from source:

  svn co https://icl.cs.utk.edu/svn/lapack-dev/lapack/trunk lapack
  cd lapack
  mkdir build
  cd build
  cmake -D BUILD_SHARED_LIBS=ON -D LAPACKE=ON ../
  make
  sudo make install
Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Lapack
Lapack


The Lapack class

(PECL lapack >= 0.1.0)

Introducere

LAPACK is written in Fortran 90 and provides routines for solving systems of simultaneous linear equations, least-squares solutions of linear systems of equations, eigenvalue problems, and singular value problems. This extension wraps the LAPACKE C bindings to allow access to several processes exposed by the library. Most functions work with arrays of arrays, representing rectangular matrices in row major order - so a two by two matrix [1 2; 3 4] would be array(array(1, 2), array(3, 4)).

All of the functions are called statically, for example $eig = Lapack::eigenvalues($a);

Sinopsisul clasei

Lapack {
/* Metode */
public static array eigenValues ( array $a [, array $left [, array $right ]] )
public static array identity ( int $n )
public static array leastSquaresByFactorisation ( array $a , array $b )
public static array leastSquaresBySVD ( array $a , array $b )
public static array pseudoInverse ( array $a )
public static array singularValues ( array $a )
public static array solveLinearEquation ( array $a , array $b )
}

Cuprins

  • Lapack::eigenValues — This function returns the eigenvalues for a given square matrix
  • Lapack::identity — Return an identity matrix
  • Lapack::leastSquaresByFactorisation — Calculate the linear least squares solution of a matrix using QR factorisation
  • Lapack::leastSquaresBySVD — Solve the linear least squares problem, using SVD
  • Lapack::pseudoInverse — Calculate the inverse of a matrix
  • Lapack::singularValues — Calculated the singular values of a matrix
  • Lapack::solveLinearEquation — Solve a system of linear equations
Constante predefinite
Lapack::eigenValues
Lapack


This function returns the eigenvalues for a given square matrix

Lapack
Lapack::identity
Lapack
PHP Manual

Lapack::eigenValues

(PECL lapack >= 0.1.0)

Lapack::eigenValues — This function returns the eigenvalues for a given square matrix

Descrierea

public static array Lapack::eigenValues ( array $a [, array $left [, array $right ]] )

Calculate the eigenvalues for a square matrix, and optionally calculate the left and right eigenvectors.

Parametri

a

The matrix to calculate the eigenvalues for.

left

Optional parameter - if an array is passed here, it will be filled with the left eigenvectors

right

Optional parameter - if an array is passed here, it will be filled with the right eigenvectors

Valorile întoarse

Returns an array of arrays representing the eigenvalues for the array.

Exemple

Example #1 Using Lapack::eigenValues():

<?php

 $a = array(
     array(-1.01,   0.86,  -4.60,  3.31,  -4.81  ),
     array( 3.98,   0.53,  -7.04,  5.29,   3.55  ),
     array( 3.30,   8.26,  -3.89,  8.20,  -1.51  ),
     array( 4.43,   4.96,  -7.66, -7.33,   6.18  ),
     array( 7.31,  -6.43,  -6.16,  2.47,   5.58  ),
 );

 $result = Lapack::eigenValues($a);

 ?>

Lapack
Lapack::identity
Lapack


Return an identity matrix

Lapack::eigenValues
Lapack::leastSquaresByFactorisation
Lapack
PHP Manual

Lapack::identity

(PECL lapack >= 0.1.0)

Lapack::identity — Return an identity matrix

Descrierea

public static array Lapack::identity ( int $n )

Return a size n identity matrix

Parametri

n

The height and width of the identity matrix.

Valorile întoarse

Will return a an array of n arrays, each containing n entries. The diagonals of the matrix will be 1s, the other positions 0.

Lapack::eigenValues
Lapack::leastSquaresByFactorisation
Lapack


Calculate the linear least squares solution of a matrix using QR factorisation

Lapack::identity
Lapack::leastSquaresBySVD
Lapack
PHP Manual

Lapack::leastSquaresByFactorisation

(PECL lapack >= 0.1.0)

Lapack::leastSquaresByFactorisation — Calculate the linear least squares solution of a matrix using QR factorisation

Descrierea

public static array Lapack::leastSquaresByFactorisation ( array $a , array $b )

Solve the linear least squares problem, find min x in || B - Ax || Returns an array representing x. Expects arrays of arrays, and will return an array of arrays in the dimension B num cols x A num cols. Uses QR or LQ factorisation on matrix A.

Parametri

a

Matrix A

b

Matrix B

Valorile întoarse

Array of the solution matrix

Exemple

Example #1 Using Lapack::leastSquaresByFactorisation():

<?php

 $a = array(
     array( 1.44,  -7.84,  -4.39,   4.53),
     array(-9.96,  -0.28,  -3.24,   3.83),
     array(-7.55,   3.24,   6.27,  -6.64),
     array( 8.34,   8.09,   5.28,   2.06),
     array( 7.08,   2.52,   0.74,  -2.47),
     array(-5.45,  -5.70,  -1.19,   4.70),
 );

 $b = array(
     array( 8.58,   9.35),
     array( 8.26,  -4.43),
     array( 8.48,  -0.70),
     array(-5.28,  -0.26),
     array( 5.72,  -7.36),
     array( 8.93,  -2.52),
 );

 $result = Lapack::leastSquaresByFactorisation($a, $b);
 ?>

Lapack::identity
Lapack::leastSquaresBySVD
Lapack


Solve the linear least squares problem, using SVD

Lapack::leastSquaresByFactorisation
Lapack::pseudoInverse
Lapack
PHP Manual

Lapack::leastSquaresBySVD

(PECL lapack >= 0.1.0)

Lapack::leastSquaresBySVD — Solve the linear least squares problem, using SVD

Descrierea

public static array Lapack::leastSquaresBySVD ( array $a , array $b )

Solve the linear least squares problem, find min x in || B - Ax || Returns an array representing x. Expects arrays of arrays, and will return an array of arrays in the dimension B num cols x A num cols. Uses SVD with a divide and conquer algorithm.

Parametri

a

Matrix A

b

Matrix B

Valorile întoarse

Returns the solution as an array of arrays.

Exemple

Example #1 Using Lapack::leastSquaresBySVD():

<?php

  $a = array(
      array( 1.44,  -7.84,  -4.39,   4.53),
      array(-9.96,  -0.28,  -3.24,   3.83),
      array(-7.55,   3.24,   6.27,  -6.64),
      array( 8.34,   8.09,   5.28,   2.06),
      array( 7.08,   2.52,   0.74,  -2.47),
      array(-5.45,  -5.70,  -1.19,   4.70),
  );

  $b = array(
      array( 8.58,   9.35),
      array( 8.26,  -4.43),
      array( 8.48,  -0.70),
      array(-5.28,  -0.26),
      array( 5.72,  -7.36),
      array( 8.93,  -2.52),
  );

  $result = Lapack::leastSquaresBySVD($a, $b);

  ?>

Lapack::leastSquaresByFactorisation
Lapack::pseudoInverse
Lapack


Calculate the inverse of a matrix

Lapack::leastSquaresBySVD
Lapack::singularValues
Lapack
PHP Manual

Lapack::pseudoInverse

(PECL lapack >= 0.1.0)

Lapack::pseudoInverse — Calculate the inverse of a matrix

Descrierea

public static array Lapack::pseudoInverse ( array $a )

Find the pseudoinverse of a matrix A.

Parametri

a

Matrix to invert

Valorile întoarse

Inverted matrix (array of arrays).

Exemple

Example #1 Using Lapack::pseudoInverse():

<?php

   $a = array(
       array( 8, 1, 6 ),
       array( 3, 5, 7 ),
       array( 4, 9, 2 ),
   );

   $result = Lapack::pseudoInverse($a);

   ?>

Lapack::leastSquaresBySVD
Lapack::singularValues
Lapack


Calculated the singular values of a matrix

Lapack::pseudoInverse
Lapack::solveLinearEquation
Lapack
PHP Manual

Lapack::singularValues

(PECL lapack >= 0.1.0)

Lapack::singularValues — Calculated the singular values of a matrix

Descrierea

public static array Lapack::singularValues ( array $a )

Calculate the singular values of the matrix A.

Parametri

a

The matrix to calculate the singular values for

Valorile întoarse

The singular values

Exemple

Example #1 Using Lapack::singularValues():

<?php

    $a = array(
        array( 7.52,  -1.10,  -7.95,  1.08  ),
        array(-0.76,   0.62,   9.34, -7.10  ),
        array( 5.13,   6.62,  -5.66,  0.87  ),
        array(-4.75,   8.52,   5.75,  5.30  ),
        array( 1.33,   4.91,  -5.49, -3.52  ),
        array(-2.40,  -6.77,   2.34,  3.95  ),
    );

    $result = Lapack::singularValues($a);

    ?>

Lapack::pseudoInverse
Lapack::solveLinearEquation
Lapack


Solve a system of linear equations

Lapack::singularValues
LapackException
Lapack
PHP Manual

Lapack::solveLinearEquation

(PECL lapack >= 0.1.0)

Lapack::solveLinearEquation — Solve a system of linear equations

Descrierea

public static array Lapack::solveLinearEquation ( array $a , array $b )

This function computes the solution to the system of linear equations with a square matrix A and multiple right-hand sides B. Solves A * X = B for multiple B.

Parametri

a

Square matrix of linear equations

b

Right hand side to be solved for

Valorile întoarse

Matrix X

Exemple

Example #1 Using Lapack::singularValues():

<?php

    $a = array(
        array( 6.80,  -6.05,  -0.45,   8.32,  -9.67   ),
        array(-2.11,  -3.30,   2.58,   2.71,  -5.14   ),
        array( 5.66,   5.36,  -2.70,   4.35,  -7.26   ),
        array( 5.97,  -4.44,   0.27,  -7.17,   6.08   ),
        array( 8.23,   1.08,   9.04,   2.14,  -6.87   ),
    );

    $b = array(
       array(  4.02,  -1.56,   9.81   ),
       array(  6.19,   4.00,  -4.09   ),
       array( -8.22,  -8.67,  -4.57   ),
       array( -7.57,   1.75,  -8.61   ),
       array( -3.03,   2.86,   8.99   ),
    );

    $result = Lapack::solveLinearEquation($a, $b);

    ?>

Lapack::singularValues
LapackException
Lapack


The LapackException class

(PECL lapack >= 0.1.0)

Introducere

Exception thrown when an error is caught in the LAPACK functions

Sinopsisul clasei

lapackexception extends Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
Lapack::solveLinearEquation
Math
Lapack


Mathematical Functions

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii matematice
    • abs — Absolute value
    • acos — Arc cosine
    • acosh — Inverse hyperbolic cosine
    • asin — Arc sine
    • asinh — Inverse hyperbolic sine
    • atan2 — Arc tangent of two variables
    • atan — Arc tangent
    • atanh — Inverse hyperbolic tangent
    • base_convert — Convert a number between arbitrary bases
    • bindec — Binary to decimal
    • ceil — Round fractions up
    • cos — Cosine
    • cosh — Hyperbolic cosine
    • decbin — Decimal to binary
    • dechex — Decimal to hexadecimal
    • decoct — Decimal to octal
    • deg2rad — Converts the number in degrees to the radian equivalent
    • exp — Calculates the exponent of e
    • expm1 — Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
    • floor — Round fractions down
    • fmod — Returns the floating point remainder (modulo) of the division of the arguments
    • getrandmax — Show largest possible random value
    • hexdec — Hexadecimal to decimal
    • hypot — Calculate the length of the hypotenuse of a right-angle triangle
    • intdiv — Integer division
    • is_finite — Finds whether a value is a legal finite number
    • is_infinite — Finds whether a value is infinite
    • is_nan — Finds whether a value is not a number
    • lcg_value — Combined linear congruential generator
    • log10 — Base-10 logarithm
    • log1p — Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
    • log — Natural logarithm
    • max — Find highest value
    • min — Find lowest value
    • mt_getrandmax — Show largest possible random value
    • mt_rand — Generate a random value via the Mersenne Twister Random Number Generator
    • mt_srand — Seeds the Mersenne Twister Random Number Generator
    • octdec — Octal to decimal
    • pi — Get value of pi
    • pow — Exponential expression
    • rad2deg — Converts the radian number to the equivalent number in degrees
    • rand — Generate a random integer
    • round — Rounds a float
    • sin — Sine
    • sinh — Hyperbolic sine
    • sqrt — Square root
    • srand — Seed the random number generator
    • tan — Tangent
    • tanh — Hyperbolic tangent
LapackException
Introducere
Extensii matematice


Introducere

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
Instalarea / configurarea
Math


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Math


Constante predefinite

Constantele de mai jos sunt întotdeauna disponibile ca parte componenta a nucleului PHP.

Math constants
Constant | Value | Description | Availability
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 | Euler constant | PHP 5.2.0
PHP_ROUND_HALF_UP | 1 | Round halves up | PHP 5.3.0
PHP_ROUND_HALF_DOWN | 2 | Round halves down | PHP 5.3.0
PHP_ROUND_HALF_EVEN | 3 | Round halves to even numbers | PHP 5.3.0
PHP_ROUND_HALF_ODD | 4 | Round halves to odd numbers | PHP 5.3.0
NAN | NAN (as a float) | Not A Number |
INF | INF (as a float) | The infinite |

All constants without a labeled PHP version above are available starting with PHP 5.0.0.

Tipurile resurselor
Func?ii matematice
Math


Func?ii matematice

Cuprins

  • abs — Absolute value
  • acos — Arc cosine
  • acosh — Inverse hyperbolic cosine
  • asin — Arc sine
  • asinh — Inverse hyperbolic sine
  • atan2 — Arc tangent of two variables
  • atan — Arc tangent
  • atanh — Inverse hyperbolic tangent
  • base_convert — Convert a number between arbitrary bases
  • bindec — Binary to decimal
  • ceil — Round fractions up
  • cos — Cosine
  • cosh — Hyperbolic cosine
  • decbin — Decimal to binary
  • dechex — Decimal to hexadecimal
  • decoct — Decimal to octal
  • deg2rad — Converts the number in degrees to the radian equivalent
  • exp — Calculates the exponent of e
  • expm1 — Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
  • floor — Round fractions down
  • fmod — Returns the floating point remainder (modulo) of the division of the arguments
  • getrandmax — Show largest possible random value
  • hexdec — Hexadecimal to decimal
  • hypot — Calculate the length of the hypotenuse of a right-angle triangle
  • intdiv — Integer division
  • is_finite — Finds whether a value is a legal finite number
  • is_infinite — Finds whether a value is infinite
  • is_nan — Finds whether a value is not a number
  • lcg_value — Combined linear congruential generator
  • log10 — Base-10 logarithm
  • log1p — Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
  • log — Natural logarithm
  • max — Find highest value
  • min — Find lowest value
  • mt_getrandmax — Show largest possible random value
  • mt_rand — Generate a random value via the Mersenne Twister Random Number Generator
  • mt_srand — Seeds the Mersenne Twister Random Number Generator
  • octdec — Octal to decimal
  • pi — Get value of pi
  • pow — Exponential expression
  • rad2deg — Converts the radian number to the equivalent number in degrees
  • rand — Generate a random integer
  • round — Rounds a float
  • sin — Sine
  • sinh — Hyperbolic sine
  • sqrt — Square root
  • srand — Seed the random number generator
  • tan — Tangent
  • tanh — Hyperbolic tangent
Constante predefinite
abs
Math


Absolute value

Func?ii matematice
acos
Func?ii matematice
PHP Manual

abs

(PHP 4, PHP 5, PHP 7)

abs — Absolute value

Descrierea

number abs ( mixed $number )

Returns the absolute value of number.

Parametri

number

The numeric value to process

Valorile întoarse

The absolute value of number. If the argument number is of type float, the return type is also float, otherwise it is integer (as float usually has a bigger value range than integer).

Exemple

Example #1 abs() example

<?php
echo abs(-4.2); // 4.2 (double/float)
echo abs(5);    // 5 (integer)
echo abs(-5);   // 5 (integer)
?>

A se vedea ?i

  • gmp_abs() - Absolute value
  • gmp_sign() - Sign of number

Func?ii matematice
acos
Func?ii matematice


Arc cosine

abs
acosh
Func?ii matematice
PHP Manual

acos

(PHP 4, PHP 5, PHP 7)

acos — Arc cosine

Descrierea

float acos ( float $arg )

Returns the arc cosine of arg in radians. acos() is the complementary function of cos(), which means that a==cos(acos(a)) for every value of a that is within acos()' range.

Parametri

arg

The argument to process

Valorile întoarse

The arc cosine of arg in radians.

A se vedea ?i

  • cos() - Cosine
  • acosh() - Inverse hyperbolic cosine
  • asin() - Arc sine
  • atan() - Arc tangent

abs
acosh
Func?ii matematice


Inverse hyperbolic cosine

acos
asin
Func?ii matematice
PHP Manual

acosh

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

acosh — Inverse hyperbolic cosine

Descrierea

float acosh ( float $arg )

Returns the inverse hyperbolic cosine of arg, i.e. the value whose hyperbolic cosine is arg.

Parametri

arg

The value to process

Valorile întoarse

The inverse hyperbolic cosine of arg

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on all platforms

A se vedea ?i

  • cosh() - Hyperbolic cosine
  • acos() - Arc cosine
  • asinh() - Inverse hyperbolic sine
  • atanh() - Inverse hyperbolic tangent

acos
asin
Func?ii matematice


Arc sine

acosh
asinh
Func?ii matematice
PHP Manual

asin

(PHP 4, PHP 5, PHP 7)

asin — Arc sine

Descrierea

float asin ( float $arg )

Returns the arc sine of arg in radians. asin() is the complementary function of sin(), which means that a==sin(asin(a)) for every value of a that is within asin()'s range.

Parametri

arg

The argument to process

Valorile întoarse

The arc sine of arg in radians

A se vedea ?i

  • sin() - Sine
  • asinh() - Inverse hyperbolic sine
  • acos() - Arc cosine
  • atan() - Arc tangent

acosh
asinh
Func?ii matematice


Inverse hyperbolic sine

asin
atan2
Func?ii matematice
PHP Manual

asinh

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

asinh — Inverse hyperbolic sine

Descrierea

float asinh ( float $arg )

Returns the inverse hyperbolic sine of arg, i.e. the value whose hyperbolic sine is arg.

Parametri

arg

The argument to process

Valorile întoarse

The inverse hyperbolic sine of arg

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on all platforms

A se vedea ?i

  • sinh() - Hyperbolic sine
  • asin() - Arc sine
  • acosh() - Inverse hyperbolic cosine
  • atanh() - Inverse hyperbolic tangent

asin
atan2
Func?ii matematice


Arc tangent of two variables

asinh
atan
Func?ii matematice
PHP Manual

atan2

(PHP 4, PHP 5, PHP 7)

atan2 — Arc tangent of two variables

Descrierea

float atan2 ( float $y , float $x )

This function calculates the arc tangent of the two variables x and y. It is similar to calculating the arc tangent of y / x, except that the signs of both arguments are used to determine the quadrant of the result.

The function returns the result in radians, which is between -PI and PI (inclusive).

Parametri

y

Dividend parameter

x

Divisor parameter

Valorile întoarse

The arc tangent of y/x in radians.

A se vedea ?i

  • atan() - Arc tangent

asinh
atan
Func?ii matematice


Arc tangent

atan2
atanh
Func?ii matematice
PHP Manual

atan

(PHP 4, PHP 5, PHP 7)

atan — Arc tangent

Descrierea

float atan ( float $arg )

Returns the arc tangent of arg in radians. atan() is the complementary function of tan(), which means that a==tan(atan(a)) for every value of a that is within atan()'s range.

Parametri

arg

The argument to process

Valorile întoarse

The arc tangent of arg in radians.

A se vedea ?i

  • tan() - Tangent
  • atanh() - Inverse hyperbolic tangent
  • asin() - Arc sine
  • acos() - Arc cosine

atan2
atanh
Func?ii matematice


Inverse hyperbolic tangent

atan
base_convert
Func?ii matematice
PHP Manual

atanh

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

atanh — Inverse hyperbolic tangent

Descrierea

float atanh ( float $arg )

Returns the inverse hyperbolic tangent of arg, i.e. the value whose hyperbolic tangent is arg.

Parametri

arg

The argument to process

Valorile întoarse

Inverse hyperbolic tangent of arg

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on all platforms

A se vedea ?i

  • tanh() - Hyperbolic tangent
  • atan() - Arc tangent
  • asinh() - Inverse hyperbolic sine
  • acosh() - Inverse hyperbolic cosine

atan
base_convert
Func?ii matematice


Convert a number between arbitrary bases

atanh
bindec
Func?ii matematice
PHP Manual

base_convert

(PHP 4, PHP 5, PHP 7)

base_convert — Convert a number between arbitrary bases

Descrierea

string base_convert ( string $number , int $frombase , int $tobase )

Returns a string containing number represented in base tobase. The base in which number is given is specified in frombase. Both frombase and tobase have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35. The case of the letters doesn't matter, i.e. number is interpreted case-insensitively.

Avertizare

base_convert() may lose precision on large numbers due to properties related to the internal "double" or "float" type used. Please see the Floating point numbers section in the manual for more specific information and limitations.

Parametri

number

The number to convert. Any invalid characters in number are silently ignored.

frombase

The base number is in

tobase

The base to convert number to

Valorile întoarse

number converted to base tobase

Exemple

Example #1 base_convert() example

<?php
$hexadecimal = 'a37334';
echo base_convert($hexadecimal, 16, 2);
?>

Exemplul de mai sus va afi?a:

101000110111001100110100

A se vedea ?i

  • intval() - Ob?ine valoarea întreaga a unei variabile

atanh
bindec
Func?ii matematice


Binary to decimal

base_convert
ceil
Func?ii matematice
PHP Manual

bindec

(PHP 4, PHP 5, PHP 7)

bindec — Binary to decimal

Descrierea

number bindec ( string $binary_string )

Returns the decimal equivalent of the binary number represented by the binary_string argument.

bindec() converts a binary number to an integer or, if needed for size reasons, float.

bindec() interprets all binary_string values as unsigned integers. This is because bindec() sees the most significant bit as another order of magnitude rather than as the sign bit.

Parametri

binary_string

The binary string to convert

Avertizare

The parameter must be a string. Using other data types will produce unexpected results.

Valorile întoarse

The decimal value of binary_string

Exemple

Example #1 bindec() example

<?php
echo bindec('110011') . "\n";
echo bindec('000110011') . "\n";

echo bindec('111');
?>

Exemplul de mai sus va afi?a:

51
51
7

Example #2 bindec() interprets input as unsigned integers

<?php
/*
 * The lesson from this example is in the output
 * rather than the PHP code itself.
 */

$magnitude_lower = pow(2, (PHP_INT_SIZE * 8) - 2);
p($magnitude_lower - 1);
p($magnitude_lower, 'See the rollover?  Watch it next time around...');

p(PHP_INT_MAX, 'PHP_INT_MAX');
p(~PHP_INT_MAX, 'interpreted to be one more than PHP_INT_MAX');

if (PHP_INT_SIZE == 4) {
    $note = 'interpreted to be the largest unsigned integer';
} else {
    $note = 'interpreted to be the largest unsigned integer
              (18446744073709551615) but skewed by float precision';
}
p(-1, $note);

function p($input, $note = '') {
    echo "input:        $input\n";

    $format = '%0' . (PHP_INT_SIZE * 8) . 'b';
    $bin = sprintf($format, $input);
    echo "binary:       $bin\n";

    ini_set('precision', 20);  // For readability on 64 bit boxes.
    $dec = bindec($bin);
    echo 'bindec():     ' . $dec . "\n";

    if ($note) {
        echo "NOTE:         $note\n";
    }

    echo "\n";
}
?>

Exemplul de mai sus va afi?a pe ma?ini pe 32 de bi?i:

input:        1073741823
binary:       00111111111111111111111111111111
bindec():     1073741823

input:        1073741824
binary:       01000000000000000000000000000000
bindec():     1073741824
NOTE:         See the rollover?  Watch it next time around...

input:        2147483647
binary:       01111111111111111111111111111111
bindec():     2147483647
NOTE:         PHP_INT_MAX

input:        -2147483648
binary:       10000000000000000000000000000000
bindec():     2147483648
NOTE:         interpreted to be one more than PHP_INT_MAX

input:        -1
binary:       11111111111111111111111111111111
bindec():     4294967295
NOTE:         interpreted to be the largest unsigned integer

Exemplul de mai sus va afi?a pe ma?ini pe 64 de bi?i:

input:        4611686018427387903
binary:       0011111111111111111111111111111111111111111111111111111111111111
bindec():     4611686018427387903

input:        4611686018427387904
binary:       0100000000000000000000000000000000000000000000000000000000000000
bindec():     4611686018427387904
NOTE:         See the rollover?  Watch it next time around...

input:        9223372036854775807
binary:       0111111111111111111111111111111111111111111111111111111111111111
bindec():     9223372036854775807
NOTE:         PHP_INT_MAX

input:        -9223372036854775808
binary:       1000000000000000000000000000000000000000000000000000000000000000
bindec():     9223372036854775808
NOTE:         interpreted to be one more than PHP_INT_MAX

input:        -1
binary:       1111111111111111111111111111111111111111111111111111111111111111
bindec():     18446744073709551616
NOTE:         interpreted to be the largest unsigned integer
              (18446744073709551615) but skewed by float precision

Note

Nota:

The function can convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.

A se vedea ?i

  • decbin() - Decimal to binary
  • octdec() - Octal to decimal
  • hexdec() - Hexadecimal to decimal
  • base_convert() - Convert a number between arbitrary bases

base_convert
ceil
Func?ii matematice


Round fractions up

bindec
cos
Func?ii matematice
PHP Manual

ceil

(PHP 4, PHP 5, PHP 7)

ceil — Round fractions up

Descrierea

float ceil ( float $value )

Returns the next highest integer value by rounding up value if necessary.

Parametri

value

The value to round

Valorile întoarse

value rounded up to the next highest integer. The return value of ceil() is still of type float as the value range of float is usually bigger than that of integer.

Exemple

Example #1 ceil() example

<?php
echo ceil(4.3);    // 5
echo ceil(9.999);  // 10
echo ceil(-3.14);  // -3
?>

A se vedea ?i

  • floor() - Round fractions down
  • round() - Rounds a float

bindec
cos
Func?ii matematice


Cosine

ceil
cosh
Func?ii matematice
PHP Manual

cos

(PHP 4, PHP 5, PHP 7)

cos — Cosine

Descrierea

float cos ( float $arg )

cos() returns the cosine of the arg parameter. The arg parameter is in radians.

Parametri

arg

An angle in radians

Valorile întoarse

The cosine of arg

Exemple

Example #1 cos() example

<?php

echo cos(M_PI); // -1

?>

A se vedea ?i

  • acos() - Arc cosine
  • sin() - Sine
  • tan() - Tangent
  • deg2rad() - Converts the number in degrees to the radian equivalent

ceil
cosh
Func?ii matematice


Hyperbolic cosine

cos
decbin
Func?ii matematice
PHP Manual

cosh

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

cosh — Hyperbolic cosine

Descrierea

float cosh ( float $arg )

Returns the hyperbolic cosine of arg, defined as (exp(arg) + exp(-arg))/2.

Parametri

arg

The argument to process

Valorile întoarse

The hyperbolic cosine of arg

A se vedea ?i

  • cos() - Cosine
  • acosh() - Inverse hyperbolic cosine
  • sinh() - Hyperbolic sine
  • cosh()

cos
decbin
Func?ii matematice


Decimal to binary

cosh
dechex
Func?ii matematice
PHP Manual

decbin

(PHP 4, PHP 5, PHP 7)

decbin — Decimal to binary

Descrierea

string decbin ( int $number )

Returns a string containing a binary representation of the given number argument.

Parametri

number

Decimal value to convert

Range of inputs on 32-bit machines
positive number | negative number | return value
0 | 0
1 | 1
2 | 10
... normal progression ...
2147483646 | 1111111111111111111111111111110
2147483647 (largest signed integer) | 1111111111111111111111111111111 (31 1's)
2147483648 | -2147483648 | 10000000000000000000000000000000
... normal progression ...
4294967294 | -2 | 11111111111111111111111111111110
4294967295 (largest unsigned integer) | -1 | 11111111111111111111111111111111 (32 1's)
Range of inputs on 64-bit machines
positive number | negative number | return value
0 | 0
1 | 1
2 | 10
... normal progression ...
9223372036854775806 | 111111111111111111111111111111111111111111111111111111111111110
9223372036854775807 (largest signed integer) | 111111111111111111111111111111111111111111111111111111111111111 (63 1's)
-9223372036854775808 | 1000000000000000000000000000000000000000000000000000000000000000
... normal progression ...
-2 | 1111111111111111111111111111111111111111111111111111111111111110
-1 | 1111111111111111111111111111111111111111111111111111111111111111 (64 1's)

Valorile întoarse

Binary string representation of number

Exemple

Example #1 decbin() example

<?php
echo decbin(12) . "\n";
echo decbin(26);
?>

Exemplul de mai sus va afi?a:

1100
11010

A se vedea ?i

  • bindec() - Binary to decimal
  • decoct() - Decimal to octal
  • dechex() - Decimal to hexadecimal
  • base_convert() - Convert a number between arbitrary bases
  • printf() - Output a formatted string, using %b, %032b or %064b as the format
  • sprintf(), using %b, %032b or %064b as the format

cosh
dechex
Func?ii matematice


Decimal to hexadecimal

decbin
decoct
Func?ii matematice
PHP Manual

dechex

(PHP 4, PHP 5, PHP 7)

dechex — Decimal to hexadecimal

Descrierea

string dechex ( int $number )

Returns a string containing a hexadecimal representation of the given unsigned number argument.

The largest number that can be converted is PHP_INT_MAX * 2 + 1 (or -1): on 32-bit platforms, this will be 4294967295 in decimal, which results in dechex() returning ffffffff.

Parametri

number

The decimal value to convert.

As PHP's integer type is signed, but dechex() deals with unsigned integers, negative integers will be treated as though they were unsigned.

Valorile întoarse

Hexadecimal string representation of number.

Exemple

Example #1 dechex() example

<?php
echo dechex(10) . "\n";
echo dechex(47);
?>

Exemplul de mai sus va afi?a:

a
2f

Example #2 dechex() example with large integers

<?php
// The output below assumes a 32-bit platform.
// Note that the output is the same for all values.
echo dechex(-1)."\n";
echo dechex(PHP_INT_MAX * 2 + 1)."\n";
echo dechex(pow(2, 32) - 1)."\n";
?>

Exemplul de mai sus va afi?a:

ffffffff
ffffffff
ffffffff

A se vedea ?i

  • hexdec() - Hexadecimal to decimal
  • decbin() - Decimal to binary
  • decoct() - Decimal to octal
  • base_convert() - Convert a number between arbitrary bases

decbin
decoct
Func?ii matematice


Decimal to octal

dechex
deg2rad
Func?ii matematice
PHP Manual

decoct

(PHP 4, PHP 5, PHP 7)

decoct — Decimal to octal

Descrierea

string decoct ( int $number )

Returns a string containing an octal representation of the given number argument. The largest number that can be converted depends on the platform in use. For 32-bit platforms this is usually 4294967295 in decimal resulting in 37777777777. For 64-bit platforms this is usually 9223372036854775807 in decimal resulting in 777777777777777777777.

Parametri

number

Decimal value to convert

Valorile întoarse

Octal string representation of number

Exemple

Example #1 decoct() example

<?php
echo decoct(15) . "\n";
echo decoct(264);
?>

Exemplul de mai sus va afi?a:

17
410

A se vedea ?i

  • octdec() - Octal to decimal
  • decbin() - Decimal to binary
  • dechex() - Decimal to hexadecimal
  • base_convert() - Convert a number between arbitrary bases

dechex
deg2rad
Func?ii matematice


Converts the number in degrees to the radian equivalent

decoct
exp
Func?ii matematice
PHP Manual

deg2rad

(PHP 4, PHP 5, PHP 7)

deg2rad — Converts the number in degrees to the radian equivalent

Descrierea

float deg2rad ( float $number )

This function converts number from degrees to the radian equivalent.

Parametri

number

Angular value in degrees

Valorile întoarse

The radian equivalent of number

Exemple

Example #1 deg2rad() example

<?php

echo deg2rad(45); // 0.785398163397
var_dump(deg2rad(45) === M_PI_4); // bool(true)

?>

A se vedea ?i

  • rad2deg() - Converts the radian number to the equivalent number in degrees

decoct
exp
Func?ii matematice


Calculates the exponent of e

deg2rad
expm1
Func?ii matematice
PHP Manual

exp

(PHP 4, PHP 5, PHP 7)

exp — Calculates the exponent of e

Descrierea

float exp ( float $arg )

Returns e raised to the power of arg.

Nota:

'e' is the base of the natural system of logarithms, or approximately 2.718282.

Parametri

arg

The argument to process

Valorile întoarse

'e' raised to the power of arg

Exemple

Example #1 exp() example

<?php
echo exp(12) . "\n";
echo exp(5.7);
?>

Exemplul de mai sus va afi?a:

1.6275E+005
298.87

A se vedea ?i

  • log() - Natural logarithm
  • pow() - Exponential expression

deg2rad
expm1
Func?ii matematice


Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero

exp
floor
Func?ii matematice
PHP Manual

expm1

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

expm1 — Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero

Descrierea

float expm1 ( float $arg )

expm1() returns the equivalent to 'exp(arg) - 1' computed in a way that is accurate even if the value of arg is near zero, a case where 'exp (arg) - 1' would be inaccurate due to subtraction of two numbers that are nearly equal.

Parametri

arg

The argument to process

Valorile întoarse

'e' to the power of arg minus one

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on all platforms

A se vedea ?i

  • log1p() - Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
  • exp() - Calculates the exponent of e

exp
floor
Func?ii matematice


Round fractions down

expm1
fmod
Func?ii matematice
PHP Manual

floor

(PHP 4, PHP 5, PHP 7)

floor — Round fractions down

Descrierea

mixed floor ( float $value )

Returns the next lowest integer value (as float) by rounding down value if necessary.

Parametri

value

The numeric value to round

Valorile întoarse

value rounded to the next lowest integer. The return value of floor() is still of type float because the value range of float is usually bigger than that of integer. This function returns FALSE in case of an error (e.g. passing an array).

Exemple

Example #1 floor() example

<?php
echo floor(4.3);   // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
?>

A se vedea ?i

  • ceil() - Round fractions up
  • round() - Rounds a float

expm1
fmod
Func?ii matematice


Returns the floating point remainder (modulo) of the division of the arguments

floor
getrandmax
Func?ii matematice
PHP Manual

fmod

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fmod — Returns the floating point remainder (modulo) of the division of the arguments

Descrierea

float fmod ( float $x , float $y )

Returns the floating point remainder of dividing the dividend (x) by the divisor (y). The remainder (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.

Parametri

x

The dividend

y

The divisor

Valorile întoarse

The floating point remainder of x/y

Exemple

Example #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
?>

A se vedea ?i

  • / - Floating-point division
  • % - Integer modulus
  • intdiv() - Integer division

floor
getrandmax
Func?ii matematice


Show largest possible random value

fmod
hexdec
Func?ii matematice
PHP Manual

getrandmax

(PHP 4, PHP 5, PHP 7)

getrandmax — Show largest possible random value

Descrierea

int getrandmax ( void )

Returns the maximum value that can be returned by a call to rand().

Valorile întoarse

The largest possible random value returned by rand()

A se vedea ?i

  • rand() - Generate a random integer
  • srand() - Seed the random number generator
  • mt_getrandmax() - Show largest possible random value

fmod
hexdec
Func?ii matematice


Hexadecimal to decimal

getrandmax
hypot
Func?ii matematice
PHP Manual

hexdec

(PHP 4, PHP 5, PHP 7)

hexdec — Hexadecimal to decimal

Descrierea

number hexdec ( string $hex_string )

Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument. hexdec() converts a hexadecimal string to a decimal number.

hexdec() will ignore any non-hexadecimal characters it encounters.

Parametri

hex_string

The hexadecimal string to convert

Valorile întoarse

The decimal representation of hex_string

Exemple

Example #1 hexdec() example

<?php
var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// both print "int(238)"

var_dump(hexdec("that")); // print "int(10)"
var_dump(hexdec("a0")); // print "int(160)"
?>

Note

Nota:

The function can convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.

A se vedea ?i

  • dechex() - Decimal to hexadecimal
  • bindec() - Binary to decimal
  • octdec() - Octal to decimal
  • base_convert() - Convert a number between arbitrary bases

getrandmax
hypot
Func?ii matematice


Calculate the length of the hypotenuse of a right-angle triangle

hexdec
intdiv
Func?ii matematice
PHP Manual

hypot

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

hypot — Calculate the length of the hypotenuse of a right-angle triangle

Descrierea

float hypot ( float $x , float $y )

hypot() returns the length of the hypotenuse of a right-angle triangle with sides of length x and y, or the distance of the point (x, y) from the origin. This is equivalent to sqrt(x*x + y*y).

Parametri

x

Length of first side

y

Length of second side

Valorile întoarse

Calculated length of the hypotenuse

hexdec
intdiv
Func?ii matematice


Integer division

hypot
is_finite
Func?ii matematice
PHP Manual

intdiv

(PHP 7)

intdiv — Integer division

Descrierea

int intdiv ( int $dividend , int $divisor )

Returns the integer quotient of the division of dividend by divisor.

Parametri

dividend

Number to be divided.

divisor

Number which divides the dividend.

Valorile întoarse

The integer quotient of the division of dividend by divisor.

Erori/Excep?ii

If divisor is 0, a DivisionByZeroError exception is thrown. If the dividend is PHP_INT_MIN and the divisor is -1, then an ArithmeticError exception is thrown.

Exemple

Example #1 intdiv() example

<?php
var_dump(intdiv(3, 2));
var_dump(intdiv(-3, 2));
var_dump(intdiv(3, -2));
var_dump(intdiv(-3, -2));
var_dump(intdiv(PHP_INT_MAX, PHP_INT_MAX));
var_dump(intdiv(PHP_INT_MIN, PHP_INT_MIN));
var_dump(intdiv(PHP_INT_MIN, -1));
var_dump(intdiv(1, 0));
?>
int(1)
int(-1)
int(-1)
int(1)
int(1)
int(1)

Fatal error: Uncaught ArithmeticError: Division of PHP_INT_MIN by -1 is not an integer in %s on line 8
Fatal error: Uncaught DivisionByZeroError: Division by zero in %s on line 9

A se vedea ?i

  • / - Floating-point division
  • % - Integer modulus
  • fmod() - Floating-point modulo

hypot
is_finite
Func?ii matematice


Finds whether a value is a legal finite number

intdiv
is_infinite
Func?ii matematice
PHP Manual

is_finite

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

is_finite — Finds whether a value is a legal finite number

Descrierea

bool is_finite ( float $val )

Checks whether val is a legal finite on this platform.

Parametri

val

The value to check

Valorile întoarse

TRUE if val is a legal finite number within the allowed range for a PHP float on this platform, else FALSE.

A se vedea ?i

  • is_infinite() - Finds whether a value is infinite
  • is_nan() - Finds whether a value is not a number

intdiv
is_infinite
Func?ii matematice


Finds whether a value is infinite

is_finite
is_nan
Func?ii matematice
PHP Manual

is_infinite

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

is_infinite — Finds whether a value is infinite

Descrierea

bool is_infinite ( float $val )

Returns TRUE if val is infinite (positive or negative), like the result of log(0) or any value too big to fit into a float on this platform.

Parametri

val

The value to check

Valorile întoarse

TRUE if val is infinite, else FALSE.

A se vedea ?i

  • is_finite() - Finds whether a value is a legal finite number
  • is_nan() - Finds whether a value is not a number

is_finite
is_nan
Func?ii matematice


Finds whether a value is not a number

is_infinite
lcg_value
Func?ii matematice
PHP Manual

is_nan

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

is_nan — Finds whether a value is not a number

Descrierea

bool is_nan ( float $val )

Checks whether val is 'not a number', like the result of acos(1.01).

Parametri

val

The value to check

Valorile întoarse

Returns TRUE if val is 'not a number', else FALSE.

Exemple

Example #1 is_nan() example

<?php
// Invalid calculation, will return a
// NaN value
$nan = acos(8);

var_dump($nan, is_nan($nan));
?>

Exemplul de mai sus va afi?a:

float(NAN)
bool(true)

A se vedea ?i

  • is_finite() - Finds whether a value is a legal finite number
  • is_infinite() - Finds whether a value is infinite

is_infinite
lcg_value
Func?ii matematice


Combined linear congruential generator

is_nan
log10
Func?ii matematice
PHP Manual

lcg_value

(PHP 4, PHP 5, PHP 7)

lcg_value — Combined linear congruential generator

Descrierea

float lcg_value ( void )

lcg_value() returns a pseudo random number in the range of (0, 1). The function combines two CGs with periods of 2^31 - 85 and 2^31 - 249. The period of this function is equal to the product of both primes.

Precautie

Aceasta func?ie nu genereaza valori securizate din punct de vedere criptografic ?i deci nu trebuie utilizata pentru scopuri criptografice. Daca ave?i nevoie de o valoare securizata din punct de vedere criptografic considera?i utilizarea random_int(), random_bytes() sau openssl_random_pseudo_bytes() în schimb.

Valorile întoarse

A pseudo random float value in the range of (0, 1)

A se vedea ?i

  • rand() - Generate a random integer
  • mt_rand() - Generate a random value via the Mersenne Twister Random Number Generator

is_nan
log10
Func?ii matematice


Base-10 logarithm

lcg_value
log1p
Func?ii matematice
PHP Manual

log10

(PHP 4, PHP 5, PHP 7)

log10 — Base-10 logarithm

Descrierea

float log10 ( float $arg )

Returns the base-10 logarithm of arg.

Parametri

arg

The argument to process

Valorile întoarse

The base-10 logarithm of arg

A se vedea ?i

  • log() - Natural logarithm

lcg_value
log1p
Func?ii matematice


Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero

log10
log
Func?ii matematice
PHP Manual

log1p

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

log1p — Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero

Descrierea

float log1p ( float $number )

log1p() returns log(1 + number) computed in a way that is accurate even when the value of number is close to zero. log() might only return log(1) in this case due to lack of precision.

Parametri

number

The argument to process

Valorile întoarse

log(1 + number)

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on all platforms

A se vedea ?i

  • expm1() - Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
  • log() - Natural logarithm
  • log10() - Base-10 logarithm

log10
log
Func?ii matematice


Natural logarithm

log1p
max
Func?ii matematice
PHP Manual

log

(PHP 4, PHP 5, PHP 7)

log — Natural logarithm

Descrierea

float log ( float $arg [, float $base = M_E ] )

If the optional base parameter is specified, log() returns logbase arg, otherwise log() returns the natural logarithm of arg.

Parametri

arg

The value to calculate the logarithm for

base

The optional logarithmic base to use (defaults to 'e' and so to the natural logarithm).

Valorile întoarse

The logarithm of arg to base, if given, or the natural logarithm.

A se vedea ?i

  • log10() - Base-10 logarithm
  • exp() - Calculates the exponent of e
  • pow() - Exponential expression

log1p
max
Func?ii matematice


Find highest value

log
min
Func?ii matematice
PHP Manual

max

(PHP 4, PHP 5, PHP 7)

max — Find highest value

Descrierea

mixed max ( array $values )
mixed max ( mixed $value1 , mixed $value2 [, mixed $... ] )

If the first and only parameter is an array, max() returns the highest value in that array. If at least two parameters are provided, max() returns the biggest of these values.

Nota:

Values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an integer as though it were 0, but multiple non-numeric string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied.

Precautie

Be careful when passing arguments with mixed types values because max() can produce unpredictable results.

Parametri

values

An array containing the values.

value1

Any comparable value.

value2

Any comparable value.

...

Any comparable value.

Valorile întoarse

max() returns the parameter value considered "highest" according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and 'abc') the first provided to the function will be returned.

If an empty array is passed, then FALSE will be returned and an E_WARNING error will be emitted.

Exemple

Example #1 Example uses of max()

<?php
echo max(2, 3, 1, 6, 7);  // 7
echo max(array(2, 4, 5)); // 5

// The string 'hello' when compared to an int is treated as 0
// Since the two values are equal, the order they are provided determines the result
echo max(0, 'hello');     // 0
echo max('hello', 0);     // hello

// Here we are comparing -1 < 0, so 'hello' is the highest value
echo max('hello', -1);    // hello

// With multiple arrays of different lengths, max returns the longest
$val = max(array(2, 2, 2), array(1, 1, 1, 1)); // array(1, 1, 1, 1)

// Multiple arrays of the same length are compared from left to right
// so in our example: 2 == 2, but 5 > 4
$val = max(array(2, 4, 8), array(2, 5, 1)); // array(2, 5, 1)

// If both an array and non-array are given, the array will be returned
// as comparisons treat arrays as greater than any other value
$val = max('string', array(2, 5, 7), 42);   // array(2, 5, 7)

// If one argument is NULL or a boolean, it will be compared against
// other values using the rule FALSE < TRUE regardless of the other types involved
// In the below example, -10 is treated as TRUE in the comparison
$val = max(-10, FALSE); // -10

// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE
$val = max(0, TRUE); // TRUE
?>

A se vedea ?i

  • min() - Find lowest value
  • count() - Count all elements in an array, or something in an object

log
min
Func?ii matematice


Find lowest value

max
mt_getrandmax
Func?ii matematice
PHP Manual

min

(PHP 4, PHP 5, PHP 7)

min — Find lowest value

Descrierea

mixed min ( array $values )
mixed min ( mixed $value1 , mixed $value2 [, mixed $... ] )

If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values.

Nota:

Values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an integer as though it were 0, but multiple non-numeric string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied.

Precautie

Be careful when passing arguments with mixed types values because min() can produce unpredictable results.

Parametri

values

An array containing the values.

value1

Any comparable value.

value2

Any comparable value.

...

Any comparable value.

Valorile întoarse

min() returns the parameter value considered "lowest" according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and 'abc') the first provided to the function will be returned.

If an empty array is passed, then FALSE will be returned and an E_WARNING error will be emitted.

Exemple

Example #1 Example uses of min()

<?php
echo min(2, 3, 1, 6, 7);  // 1
echo min(array(2, 4, 5)); // 2

// The string 'hello' when compared to an int is treated as 0
// Since the two values are equal, the order they are provided determines the result
echo min(0, 'hello');     // 0
echo min('hello', 0);     // hello

// Here we are comparing -1 < 0, so -1 is the lowest value
echo min('hello', -1);    // -1

// With multiple arrays of different lengths, min returns the shortest
$val = min(array(2, 2, 2), array(1, 1, 1, 1)); // array(2, 2, 2)

// Multiple arrays of the same length are compared from left to right
// so in our example: 2 == 2, but 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)

// If both an array and non-array are given, the array is never returned
// as comparisons treat arrays as greater than any other value
$val = min('string', array(2, 5, 7), 42);   // string

// If one argument is NULL or a boolean, it will be compared against
// other values using the rules FALSE < TRUE and NULL == FALSE regardless of the
// other types involved
// In the below examples, both -10 and 10 are treated as TRUE in the comparison
$val = min(-10, FALSE, 10); // FALSE
$val = min(-10, NULL, 10);  // NULL

// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE
$val = min(0, TRUE); // 0
?>

A se vedea ?i

  • max() - Find highest value
  • count() - Count all elements in an array, or something in an object

max
mt_getrandmax
Func?ii matematice


Show largest possible random value

min
mt_rand
Func?ii matematice
PHP Manual

mt_getrandmax

(PHP 4, PHP 5, PHP 7)

mt_getrandmax — Show largest possible random value

Descrierea

int mt_getrandmax ( void )

Returns the maximum value that can be returned by a call to mt_rand().

Valorile întoarse

Returns the maximum random value returned by a call to mt_rand() without arguments, which is the maximum value that can be used for its max parameter without the result being scaled up (and therefore less random).

Exemple

Example #1 Calculate a random floating-point number

<?php
function randomFloat($min = 0, $max = 1) {
    return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}

var_dump(randomFloat());
var_dump(randomFloat(2, 20));
?>

Exemplul de mai sus va afi?a ceva similar cu:

float(0.91601131712832)
float(16.511210331931)

A se vedea ?i

  • mt_rand() - Generate a random value via the Mersenne Twister Random Number Generator
  • mt_srand() - Seeds the Mersenne Twister Random Number Generator
  • getrandmax() - Show largest possible random value

min
mt_rand
Func?ii matematice


Generate a random value via the Mersenne Twister Random Number Generator

mt_getrandmax
mt_srand
Func?ii matematice
PHP Manual

mt_rand

(PHP 4, PHP 5, PHP 7)

mt_rand — Generate a random value via the Mersenne Twister Random Number Generator

Descrierea

int mt_rand ( void )
int mt_rand ( int $min , int $max )
Precautie

Aceasta func?ie nu genereaza valori securizate din punct de vedere criptografic ?i deci nu trebuie utilizata pentru scopuri criptografice. Daca ave?i nevoie de o valoare securizata din punct de vedere criptografic considera?i utilizarea random_int(), random_bytes() sau openssl_random_pseudo_bytes() în schimb.

Many random number generators of older libcs have dubious or unknown characteristics and are slow. The mt_rand() function is a drop-in replacement for the older rand(). It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

If called without the optional min, max arguments mt_rand() returns a pseudo-random value between 0 and mt_getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use mt_rand(5, 15).

Parametri

min

Optional lowest value to be returned (default: 0)

max

Optional highest value to be returned (default: mt_getrandmax())

Valorile întoarse

A random integer value between min (or 0) and max (or mt_getrandmax(), inclusive), or FALSE if max is less than min.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | rand() has been made an alias of mt_rand().
7.1.0 | mt_rand()has been updated to use the fixed, correct, version of the Mersenne Twister algorithm. To fall back to the old behaviour, use mt_srand() with MT_RAND_PHP as the second paramter.
5.3.4 | Issues an E_WARNING and returns FALSE if max < min.

Exemple

Example #1 mt_rand() example

<?php
echo mt_rand() . "\n";
echo mt_rand() . "\n";

echo mt_rand(5, 15);
?>

Exemplul de mai sus va afi?a ceva similar cu:

1604716014
1478613278
6

Note

Avertizare

min max range must be within the range mt_getrandmax(). i.e. (max - min) <= mt_getrandmax() Otherwise, mt_rand() may return poor random numbers than it should be.

A se vedea ?i

  • mt_srand() - Seeds the Mersenne Twister Random Number Generator
  • mt_getrandmax() - Show largest possible random value
  • random_int() - Generates cryptographically secure pseudo-random integers
  • random_bytes() - Generates cryptographically secure pseudo-random bytes
  • openssl_random_pseudo_bytes() - Generate a pseudo-random string of bytes
  • rand() - Generate a random integer

mt_getrandmax
mt_srand
Func?ii matematice


Seeds the Mersenne Twister Random Number Generator

mt_rand
octdec
Func?ii matematice
PHP Manual

mt_srand

(PHP 4, PHP 5, PHP 7)

mt_srand — Seeds the Mersenne Twister Random Number Generator

Descrierea

void mt_srand ([ int $seed [, int $mode = MT_RAND_MT19937 ]] )

Seeds the random number generator with seed or with a random value if no seed is given.

Nota: Nu este nevoie de a însamân?a generatorul de numere aleatoare cu ajutorul srand() sau mt_srand(), deoarece aceasta se efectueaza în mod automat.

Parametri

seed

An arbitrary integer seed value.

mode

Use one of the following constants to specify the implementation of the algorithm to use.

Constant | Descriere
MT_RAND_MT19937 | Uses the fixed, correct, Mersenne Twister implementation, available as of PHP 7.1.0.
MT_RAND_PHP | Uses an incorrect Mersenne Twister implementation which was used as the default up till PHP 7.1.0. This mode is available for backward compatibility.

Valorile întoarse

Nu este întoarsa nici o valoare.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | srand() has been made an alias of mt_srand().
7.1.0 | mt_rand()has been updated to use the fixed, correct, version of the Mersenne Twister algorithm. To fall back to the old behaviour, use mt_srand() with MT_RAND_PHP as the second paramter.
5.2.1 | The Mersenne Twister implementation in PHP now uses a new seeding algorithm by Richard Wagner. Identical seeds no longer produce the same sequence of values they did in previous versions. This behavior is not expected to change again, but it is considered unsafe to rely upon it nonetheless.

Exemple

Example #1 mt_srand() example

<?php
// seed with microseconds
function make_seed()
{
  list($usec, $sec) = explode(' ', microtime());
  return $sec + $usec * 1000000;
}
mt_srand(make_seed());
$randval = mt_rand();
?>

A se vedea ?i

  • mt_rand() - Generate a random value via the Mersenne Twister Random Number Generator
  • mt_getrandmax() - Show largest possible random value
  • srand() - Seed the random number generator

mt_rand
octdec
Func?ii matematice


Octal to decimal

mt_srand
pi
Func?ii matematice
PHP Manual

octdec

(PHP 4, PHP 5, PHP 7)

octdec — Octal to decimal

Descrierea

number octdec ( string $octal_string )

Returns the decimal equivalent of the octal number represented by the octal_string argument.

Parametri

octal_string

The octal string to convert

Valorile întoarse

The decimal representation of octal_string

Exemple

Example #1 octdec() example

<?php
echo octdec('77') . "\n";
echo octdec(decoct(45));
?>

Exemplul de mai sus va afi?a:

63
45

Note

Nota:

The function can convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.

A se vedea ?i

  • decoct() - Decimal to octal
  • bindec() - Binary to decimal
  • hexdec() - Hexadecimal to decimal
  • base_convert() - Convert a number between arbitrary bases

mt_srand
pi
Func?ii matematice


Get value of pi

octdec
pow
Func?ii matematice
PHP Manual

pi

(PHP 4, PHP 5, PHP 7)

pi — Get value of pi

Descrierea

float pi ( void )

Returns an approximation of pi. The returned float has a precision based on the precision directive in php.ini, which defaults to 14. Also, you can use the M_PI constant which yields identical results to pi().

Valorile întoarse

The value of pi as float.

Exemple

Example #1 pi() example

<?php
echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898
?>

octdec
pow
Func?ii matematice


Exponential expression

pi
rad2deg
Func?ii matematice
PHP Manual

pow

(PHP 4, PHP 5, PHP 7)

pow — Exponential expression

Descrierea

number pow ( number $base , number $exp )

Returns base raised to the power of exp.

Nota:

In PHP 5.6 onwards, you may prefer to use the ** operator.

Parametri

base

The base to use

exp

The exponent

Valorile întoarse

base raised to the power of exp. If both arguments are non-negative integers and the result can be represented as an integer, the result will be returned with integer type, otherwise it will be returned as a float.

Exemple

Example #1 Some examples of pow()

<?php

var_dump(pow(2, 8)); // int(256)
echo pow(-1, 20); // 1
echo pow(0, 0); // 1
echo pow(10, -1); // 0.1

echo pow(-1, 5.5); // PHP >=5.2.2: NAN
echo pow(-1, 5.5); // PHP <5.2.2: -NAN
?>

Note

Nota:

This function will convert all input to a number, even non-scalar values, which could lead to weird results.

A se vedea ?i

  • exp() - Calculates the exponent of e
  • sqrt() - Square root
  • bcpow() - Raise an arbitrary precision number to another
  • gmp_pow() - Raise number into power

pi
rad2deg
Func?ii matematice


Converts the radian number to the equivalent number in degrees

pow
rand
Func?ii matematice
PHP Manual

rad2deg

(PHP 4, PHP 5, PHP 7)

rad2deg — Converts the radian number to the equivalent number in degrees

Descrierea

float rad2deg ( float $number )

This function converts number from radian to degrees.

Parametri

number

A radian value

Valorile întoarse

The equivalent of number in degrees

Exemple

Example #1 rad2deg() example

<?php

echo rad2deg(M_PI_4); // 45

?>

A se vedea ?i

  • deg2rad() - Converts the number in degrees to the radian equivalent

pow
rand
Func?ii matematice


Generate a random integer

rad2deg
round
Func?ii matematice
PHP Manual

rand

(PHP 4, PHP 5, PHP 7)

rand — Generate a random integer

Descrierea

int rand ( void )
int rand ( int $min , int $max )

If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15).

Precautie

Aceasta func?ie nu genereaza valori securizate din punct de vedere criptografic ?i deci nu trebuie utilizata pentru scopuri criptografice. Daca ave?i nevoie de o valoare securizata din punct de vedere criptografic considera?i utilizarea random_int(), random_bytes() sau openssl_random_pseudo_bytes() în schimb.

Nota: On some platforms (such as Windows), getrandmax() is only 32767. If you require a range larger than 32767, specifying min and max will allow you to create a range larger than this, or consider using mt_rand() instead.

Nota: As of PHP 7.1.0, rand() has been made an alias of mt_rand().

Parametri

min

The lowest value to return (default: 0)

max

The highest value to return (default: getrandmax())

Valorile întoarse

A pseudo random value between min (or 0) and max (or getrandmax(), inclusive).

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | rand() has been made an alias of mt_rand().

Exemple

Example #1 rand() example

<?php
echo rand() . "\n";
echo rand() . "\n";

echo rand(5, 15);
?>

Exemplul de mai sus va afi?a ceva similar cu:

7771
22264
11

Note

Avertizare

min max range must be within the range getrandmax(). i.e. (max - min) <= getrandmax() Otherwise, rand() may return poor-quality random numbers.

A se vedea ?i

  • srand() - Seed the random number generator
  • getrandmax() - Show largest possible random value
  • mt_rand() - Generate a random value via the Mersenne Twister Random Number Generator
  • random_int() - Generates cryptographically secure pseudo-random integers
  • random_bytes() - Generates cryptographically secure pseudo-random bytes
  • openssl_random_pseudo_bytes() - Generate a pseudo-random string of bytes

rad2deg
round
Func?ii matematice


Rounds a float

rand
sin
Func?ii matematice
PHP Manual

round

(PHP 4, PHP 5, PHP 7)

round — Rounds a float

Descrierea

float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )

Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

Nota: PHP doesn't handle strings like "12,300.2" correctly by default. See converting from strings.

Parametri

val

The value to round

precision

The optional number of decimal digits to round to.

mode

Use one of the following constants to specify the mode in which rounding occurs.

Constant | Descriere
PHP_ROUND_HALF_UP | Round val up to precision decimal places away from zero, when it is half way there. Making 1.5 into 2 and -1.5 into -2.
PHP_ROUND_HALF_DOWN | Round val down to precision decimal places towards zero, when it is half way there. Making 1.5 into 1 and -1.5 into -1.
PHP_ROUND_HALF_EVEN | Round val to precision decimal places towards the next even value.
PHP_ROUND_HALF_ODD | Round val to precision decimal places towards the next odd value.

Valorile întoarse

The rounded value

Exemple

Example #1 round() examples

<?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
?>

Example #2 mode examples

<?php
echo round(9.5, 0, PHP_ROUND_HALF_UP);   // 10
echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
echo round(9.5, 0, PHP_ROUND_HALF_ODD);  // 9

echo round(8.5, 0, PHP_ROUND_HALF_UP);   // 9
echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_ODD);  // 9
?>

Example #3 mode with precision examples

<?php
/* Using PHP_ROUND_HALF_UP with 1 decimal digit precision */
echo round( 1.55, 1, PHP_ROUND_HALF_UP);   //  1.6
echo round( 1.54, 1, PHP_ROUND_HALF_UP);   //  1.5
echo round(-1.55, 1, PHP_ROUND_HALF_UP);   // -1.6
echo round(-1.54, 1, PHP_ROUND_HALF_UP);   // -1.5

/* Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision */
echo round( 1.55, 1, PHP_ROUND_HALF_DOWN); //  1.5
echo round( 1.54, 1, PHP_ROUND_HALF_DOWN); //  1.5
echo round(-1.55, 1, PHP_ROUND_HALF_DOWN); // -1.5
echo round(-1.54, 1, PHP_ROUND_HALF_DOWN); // -1.5

/* Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision */
echo round( 1.55, 1, PHP_ROUND_HALF_EVEN); //  1.6
echo round( 1.54, 1, PHP_ROUND_HALF_EVEN); //  1.5
echo round(-1.55, 1, PHP_ROUND_HALF_EVEN); // -1.6
echo round(-1.54, 1, PHP_ROUND_HALF_EVEN); // -1.5

/* Using PHP_ROUND_HALF_ODD with 1 decimal digit precision */
echo round( 1.55, 1, PHP_ROUND_HALF_ODD);  //  1.5
echo round( 1.54, 1, PHP_ROUND_HALF_ODD);  //  1.5
echo round(-1.55, 1, PHP_ROUND_HALF_ODD);  // -1.5
echo round(-1.54, 1, PHP_ROUND_HALF_ODD);  // -1.5
?>

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | The mode parameter was introduced.
5.2.7 | The inner workings of round() was changed to conform to the C99 standard.

A se vedea ?i

  • ceil() - Round fractions up
  • floor() - Round fractions down
  • number_format() - Format a number with grouped thousands

rand
sin
Func?ii matematice


Sine

round
sinh
Func?ii matematice
PHP Manual

sin

(PHP 4, PHP 5, PHP 7)

sin — Sine

Descrierea

float sin ( float $arg )

sin() returns the sine of the arg parameter. The arg parameter is in radians.

Parametri

arg

A value in radians

Valorile întoarse

The sine of arg

Exemple

Example #1 sin() example

<?php

// Precision depends on your precision directive
echo sin(deg2rad(60));  //  0.866025403 ...
echo sin(60);           // -0.304810621 ...

?>

A se vedea ?i

  • asin() - Arc sine
  • sinh() - Hyperbolic sine
  • cos() - Cosine
  • tan() - Tangent
  • deg2rad() - Converts the number in degrees to the radian equivalent

round
sinh
Func?ii matematice


Hyperbolic sine

sin
sqrt
Func?ii matematice
PHP Manual

sinh

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

sinh — Hyperbolic sine

Descrierea

float sinh ( float $arg )

Returns the hyperbolic sine of arg, defined as (exp(arg) - exp(-arg))/2.

Parametri

arg

The argument to process

Valorile întoarse

The hyperbolic sine of arg

A se vedea ?i

  • sin() - Sine
  • asinh() - Inverse hyperbolic sine
  • cosh() - Hyperbolic cosine
  • tanh() - Hyperbolic tangent

sin
sqrt
Func?ii matematice


Square root

sinh
srand
Func?ii matematice
PHP Manual

sqrt

(PHP 4, PHP 5, PHP 7)

sqrt — Square root

Descrierea

float sqrt ( float $arg )

Returns the square root of arg.

Parametri

arg

The argument to process

Valorile întoarse

The square root of arg or the special value NAN for negative numbers.

Exemple

Example #1 sqrt() example

<?php
// Precision depends on your precision directive
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...
?>

A se vedea ?i

  • pow() - Exponential expression

sinh
srand
Func?ii matematice


Seed the random number generator

sqrt
tan
Func?ii matematice
PHP Manual

srand

(PHP 4, PHP 5, PHP 7)

srand — Seed the random number generator

Descrierea

void srand ([ int $seed ] )

Seeds the random number generator with seed or with a random value if no seed is given.

Nota: Nu este nevoie de a însamân?a generatorul de numere aleatoare cu ajutorul srand() sau mt_srand(), deoarece aceasta se efectueaza în mod automat.

Nota: As of PHP 7.1.0, srand() has been made an alias of mt_srand().

Parametri

seed

An arbitrary integer seed value.

Valorile întoarse

Nu este întoarsa nici o valoare.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | srand() has been made an alias of mt_srand().

Exemple

Example #1 srand() example

<?php
// seed with microseconds
function make_seed()
{
  list($usec, $sec) = explode(' ', microtime());
  return $sec + $usec * 1000000;
}
srand(make_seed());
$randval = rand();
?>

A se vedea ?i

  • rand() - Generate a random integer
  • getrandmax() - Show largest possible random value
  • mt_srand() - Seeds the Mersenne Twister Random Number Generator

sqrt
tan
Func?ii matematice


Tangent

srand
tanh
Func?ii matematice
PHP Manual

tan

(PHP 4, PHP 5, PHP 7)

tan — Tangent

Descrierea

float tan ( float $arg )

tan() returns the tangent of the arg parameter. The arg parameter is in radians.

Parametri

arg

The argument to process in radians

Valorile întoarse

The tangent of arg

Exemple

Example #1 tan() example

<?php

echo tan(M_PI_4); // 1

?>

A se vedea ?i

  • atan() - Arc tangent
  • atan2() - Arc tangent of two variables
  • sin() - Sine
  • cos() - Cosine
  • tanh() - Hyperbolic tangent
  • deg2rad() - Converts the number in degrees to the radian equivalent

srand
tanh
Func?ii matematice


Hyperbolic tangent

tan
Statistics
Func?ii matematice
PHP Manual

tanh

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

tanh — Hyperbolic tangent

Descrierea

float tanh ( float $arg )

Returns the hyperbolic tangent of arg, defined as sinh(arg)/cosh(arg).

Parametri

arg

The argument to process

Valorile întoarse

The hyperbolic tangent of arg

A se vedea ?i

  • tan() - Tangent
  • atanh() - Inverse hyperbolic tangent
  • sinh() - Hyperbolic sine
  • cosh() - Hyperbolic cosine

tan
Statistics
Func?ii matematice


Statistics

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii statistice
    • 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 — Descrierea
    • 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 — Descrierea
    • 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 — Descrierea
    • 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
Introducere
Extensii matematice


Introducere

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
Instalarea / configurarea
Statistics


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Statistics


Necesita?i

No external libraries are needed. The extension comes bundled with the libraries used.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/stats.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii statistice
Statistics


Func?ii statistice

Cuprins

  • 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 — Descrierea
  • 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 — Descrierea
  • 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 — Descrierea
  • 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
Constante predefinite
stats_absolute_deviation
Statistics


Returns the absolute deviation of an array of values

Func?ii statistice
stats_cdf_beta
Func?ii statistice
PHP Manual

stats_absolute_deviation

(PECL stats >= 1.0.0)

stats_absolute_deviation — Returns the absolute deviation of an array of values

Descrierea

float stats_absolute_deviation ( array $a )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

a

Valorile întoarse

Func?ii statistice
stats_cdf_beta
Func?ii statistice


CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.

stats_absolute_deviation
stats_cdf_binomial
Func?ii statistice
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.

Descrierea

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.

Parametri

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

Valorile întoarse

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
Func?ii statistice


Calculates any one parameter of the binomial distribution given values for the others.

stats_cdf_beta
stats_cdf_cauchy
Func?ii statistice
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.

Descrierea

float stats_cdf_binomial ( float $par1 , float $par2 , float $par3 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

par3

which

Valorile întoarse

stats_cdf_beta
stats_cdf_cauchy
Func?ii statistice


Not documented

stats_cdf_binomial
stats_cdf_chisquare
Func?ii statistice
PHP Manual

stats_cdf_cauchy

(PECL stats >= 1.0.0)

stats_cdf_cauchy — Not documented

Descrierea

float stats_cdf_cauchy ( float $par1 , float $par2 , float $par3 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

par3

which

Valorile întoarse

stats_cdf_binomial
stats_cdf_chisquare
Func?ii statistice


Calculates any one parameter of the chi-square distribution given values for the others.

stats_cdf_cauchy
stats_cdf_exponential
Func?ii statistice
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.

Descrierea

float stats_cdf_chisquare ( float $par1 , float $par2 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

which

Valorile întoarse

stats_cdf_cauchy
stats_cdf_exponential
Func?ii statistice


Not documented

stats_cdf_chisquare
stats_cdf_f
Func?ii statistice
PHP Manual

stats_cdf_exponential

(PECL stats >= 1.0.0)

stats_cdf_exponential — Not documented

Descrierea

float stats_cdf_exponential ( float $par1 , float $par2 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

which

Valorile întoarse

stats_cdf_chisquare
stats_cdf_f
Func?ii statistice


Calculates any one parameter of the F distribution given values for the others.

stats_cdf_exponential
stats_cdf_gamma
Func?ii statistice
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.

Descrierea

float stats_cdf_f ( float $par1 , float $par2 , float $par3 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

par3

which

Valorile întoarse

stats_cdf_exponential
stats_cdf_gamma
Func?ii statistice


Calculates any one parameter of the gamma distribution given values for the others.

stats_cdf_f
stats_cdf_laplace
Func?ii statistice
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.

Descrierea

float stats_cdf_gamma ( float $par1 , float $par2 , float $par3 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

par3

which

Valorile întoarse

stats_cdf_f
stats_cdf_laplace
Func?ii statistice


Not documented

stats_cdf_gamma
stats_cdf_logistic
Func?ii statistice
PHP Manual

stats_cdf_laplace

(PECL stats >= 1.0.0)

stats_cdf_laplace — Not documented

Descrierea

float stats_cdf_laplace ( float $par1 , float $par2 , float $par3 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

par3

which

Valorile întoarse

stats_cdf_gamma
stats_cdf_logistic
Func?ii statistice


Not documented

stats_cdf_laplace
stats_cdf_negative_binomial
Func?ii statistice
PHP Manual

stats_cdf_logistic

(PECL stats >= 1.0.0)

stats_cdf_logistic — Not documented

Descrierea

float stats_cdf_logistic ( float $par1 , float $par2 , float $par3 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

par3

which

Valorile întoarse

stats_cdf_laplace
stats_cdf_negative_binomial
Func?ii statistice


Calculates any one parameter of the negative binomial distribution given values for the others.

stats_cdf_logistic
stats_cdf_noncentral_chisquare
Func?ii statistice
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.

Descrierea

float stats_cdf_negative_binomial ( float $par1 , float $par2 , float $par3 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

par3

which

Valorile întoarse

stats_cdf_logistic
stats_cdf_noncentral_chisquare
Func?ii statistice


Calculates any one parameter of the non-central chi-square distribution given values for the others.

stats_cdf_negative_binomial
stats_cdf_noncentral_f
Func?ii statistice
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.

Descrierea

float stats_cdf_noncentral_chisquare ( float $par1 , float $par2 , float $par3 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

par3

which

Valorile întoarse

stats_cdf_negative_binomial
stats_cdf_noncentral_f
Func?ii statistice


Calculates any one parameter of the Non-central F distribution given values for the others.

stats_cdf_noncentral_chisquare
stats_cdf_poisson
Func?ii statistice
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.

Descrierea

float stats_cdf_noncentral_f ( float $par1 , float $par2 , float $par3 , float $par4 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

par3

par4

which

Valorile întoarse

stats_cdf_noncentral_chisquare
stats_cdf_poisson
Func?ii statistice


Calculates any one parameter of the Poisson distribution given values for the others.

stats_cdf_noncentral_f
stats_cdf_t
Func?ii statistice
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.

Descrierea

float stats_cdf_poisson ( float $par1 , float $par2 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

which

Valorile întoarse

stats_cdf_noncentral_f
stats_cdf_t
Func?ii statistice


Calculates any one parameter of the T distribution given values for the others.

stats_cdf_poisson
stats_cdf_uniform
Func?ii statistice
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.

Descrierea

float stats_cdf_t ( float $par1 , float $par2 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

which

Valorile întoarse

stats_cdf_poisson
stats_cdf_uniform
Func?ii statistice


Not documented

stats_cdf_t
stats_cdf_weibull
Func?ii statistice
PHP Manual

stats_cdf_uniform

(PECL stats >= 1.0.0)

stats_cdf_uniform — Not documented

Descrierea

float stats_cdf_uniform ( float $par1 , float $par2 , float $par3 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

par3

which

Valorile întoarse

stats_cdf_t
stats_cdf_weibull
Func?ii statistice


Not documented

stats_cdf_uniform
stats_covariance
Func?ii statistice
PHP Manual

stats_cdf_weibull

(PECL stats >= 1.0.0)

stats_cdf_weibull — Not documented

Descrierea

float stats_cdf_weibull ( float $par1 , float $par2 , float $par3 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

par3

which

Valorile întoarse

stats_cdf_uniform
stats_covariance
Func?ii statistice


Computes the covariance of two data sets

stats_cdf_weibull
stats_den_uniform
Func?ii statistice
PHP Manual

stats_covariance

(PECL stats >= 1.0.0)

stats_covariance — Computes the covariance of two data sets

Descrierea

float stats_covariance ( array $a , array $b )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

a

b

Valorile întoarse

stats_cdf_weibull
stats_den_uniform
Func?ii statistice


Not documented

stats_covariance
stats_dens_beta
Func?ii statistice
PHP Manual

stats_den_uniform

(PECL stats >= 1.0.0)

stats_den_uniform — Not documented

Descrierea

float stats_den_uniform ( float $x , float $a , float $b )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

a

b

Valorile întoarse

stats_covariance
stats_dens_beta
Func?ii statistice


Not documented

stats_den_uniform
stats_dens_cauchy
Func?ii statistice
PHP Manual

stats_dens_beta

(PECL stats >= 1.0.0)

stats_dens_beta — Not documented

Descrierea

float stats_dens_beta ( float $x , float $a , float $b )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

a

b

Valorile întoarse

stats_den_uniform
stats_dens_cauchy
Func?ii statistice


Not documented

stats_dens_beta
stats_dens_chisquare
Func?ii statistice
PHP Manual

stats_dens_cauchy

(PECL stats >= 1.0.0)

stats_dens_cauchy — Not documented

Descrierea

float stats_dens_cauchy ( float $x , float $ave , float $stdev )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

ave

stdev

Valorile întoarse

stats_dens_beta
stats_dens_chisquare
Func?ii statistice


Not documented

stats_dens_cauchy
stats_dens_exponential
Func?ii statistice
PHP Manual

stats_dens_chisquare

(PECL stats >= 1.0.0)

stats_dens_chisquare — Not documented

Descrierea

float stats_dens_chisquare ( float $x , float $dfr )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

dfr

Valorile întoarse

stats_dens_cauchy
stats_dens_exponential
Func?ii statistice


Not documented

stats_dens_chisquare
stats_dens_f
Func?ii statistice
PHP Manual

stats_dens_exponential

(PECL stats >= 1.0.0)

stats_dens_exponential — Not documented

Descrierea

float stats_dens_exponential ( float $x , float $scale )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

scale

Valorile întoarse

stats_dens_chisquare
stats_dens_f
Func?ii statistice


stats_dens_exponential
stats_dens_gamma
Func?ii statistice
PHP Manual

stats_dens_f

(PECL stats >= 1.0.0)

stats_dens_f —

Descrierea

float stats_dens_f ( float $x , float $dfr1 , float $dfr2 )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

dfr1

dfr2

Valorile întoarse

stats_dens_exponential
stats_dens_gamma
Func?ii statistice


Not documented

stats_dens_f
stats_dens_laplace
Func?ii statistice
PHP Manual

stats_dens_gamma

(PECL stats >= 1.0.0)

stats_dens_gamma — Not documented

Descrierea

float stats_dens_gamma ( float $x , float $shape , float $scale )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

shape

scale

Valorile întoarse

stats_dens_f
stats_dens_laplace
Func?ii statistice


Not documented

stats_dens_gamma
stats_dens_logistic
Func?ii statistice
PHP Manual

stats_dens_laplace

(PECL stats >= 1.0.0)

stats_dens_laplace — Not documented

Descrierea

float stats_dens_laplace ( float $x , float $ave , float $stdev )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

ave

stdev

Valorile întoarse

stats_dens_gamma
stats_dens_logistic
Func?ii statistice


Not documented

stats_dens_laplace
stats_dens_negative_binomial
Func?ii statistice
PHP Manual

stats_dens_logistic

(PECL stats >= 1.0.0)

stats_dens_logistic — Not documented

Descrierea

float stats_dens_logistic ( float $x , float $ave , float $stdev )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

ave

stdev

Valorile întoarse

stats_dens_laplace
stats_dens_negative_binomial
Func?ii statistice


Not documented

stats_dens_logistic
stats_dens_normal
Func?ii statistice
PHP Manual

stats_dens_negative_binomial

(PECL stats >= 1.0.0)

stats_dens_negative_binomial — Not documented

Descrierea

float stats_dens_negative_binomial ( float $x , float $n , float $pi )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

n

pi

Valorile întoarse

stats_dens_logistic
stats_dens_normal
Func?ii statistice


Not documented

stats_dens_negative_binomial
stats_dens_pmf_binomial
Func?ii statistice
PHP Manual

stats_dens_normal

(PECL stats >= 1.0.0)

stats_dens_normal — Not documented

Descrierea

float stats_dens_normal ( float $x , float $ave , float $stdev )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

ave

stdev

Valorile întoarse

stats_dens_negative_binomial
stats_dens_pmf_binomial
Func?ii statistice


Not documented

stats_dens_normal
stats_dens_pmf_hypergeometric
Func?ii statistice
PHP Manual

stats_dens_pmf_binomial

(PECL stats >= 1.0.0)

stats_dens_pmf_binomial — Not documented

Descrierea

float stats_dens_pmf_binomial ( float $x , float $n , float $pi )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

n

pi

Valorile întoarse

stats_dens_normal
stats_dens_pmf_hypergeometric
Func?ii statistice


stats_dens_pmf_binomial
stats_dens_pmf_poisson
Func?ii statistice
PHP Manual

stats_dens_pmf_hypergeometric

(PECL stats >= 1.0.0)

stats_dens_pmf_hypergeometric —

Descrierea

float stats_dens_pmf_hypergeometric ( float $n1 , float $n2 , float $N1 , float $N2 )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

n1

n2

N1

N2

Valorile întoarse

stats_dens_pmf_binomial
stats_dens_pmf_poisson
Func?ii statistice


Not documented

stats_dens_pmf_hypergeometric
stats_dens_t
Func?ii statistice
PHP Manual

stats_dens_pmf_poisson

(PECL stats >= 1.0.0)

stats_dens_pmf_poisson — Not documented

Descrierea

float stats_dens_pmf_poisson ( float $x , float $lb )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

lb

Valorile întoarse

stats_dens_pmf_hypergeometric
stats_dens_t
Func?ii statistice


Not documented

stats_dens_pmf_poisson
stats_dens_weibull
Func?ii statistice
PHP Manual

stats_dens_t

(PECL stats >= 1.0.0)

stats_dens_t — Not documented

Descrierea

float stats_dens_t ( float $x , float $dfr )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

dfr

Valorile întoarse

stats_dens_pmf_poisson
stats_dens_weibull
Func?ii statistice


Not documented

stats_dens_t
stats_harmonic_mean
Func?ii statistice
PHP Manual

stats_dens_weibull

(PECL stats >= 1.0.0)

stats_dens_weibull — Not documented

Descrierea

float stats_dens_weibull ( float $x , float $a , float $b )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

a

b

Valorile întoarse

stats_dens_t
stats_harmonic_mean
Func?ii statistice


Returns the harmonic mean of an array of values

stats_dens_weibull
stats_kurtosis
Func?ii statistice
PHP Manual

stats_harmonic_mean

(PECL stats >= 1.0.0)

stats_harmonic_mean — Returns the harmonic mean of an array of values

Descrierea

number stats_harmonic_mean ( array $a )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

a

Valorile întoarse

stats_dens_weibull
stats_kurtosis
Func?ii statistice


Computes the kurtosis of the data in the array

stats_harmonic_mean
stats_rand_gen_beta
Func?ii statistice
PHP Manual

stats_kurtosis

(PECL stats >= 1.0.0)

stats_kurtosis — Computes the kurtosis of the data in the array

Descrierea

float stats_kurtosis ( array $a )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

a

Valorile întoarse

stats_harmonic_mean
stats_rand_gen_beta
Func?ii statistice


Generates beta random deviate

stats_kurtosis
stats_rand_gen_chisquare
Func?ii statistice
PHP Manual

stats_rand_gen_beta

(PECL stats >= 1.0.0)

stats_rand_gen_beta — Generates beta random deviate

Descrierea

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.

Parametri

a

b

Valorile întoarse

stats_kurtosis
stats_rand_gen_chisquare
Func?ii statistice


Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.

stats_rand_gen_beta
stats_rand_gen_exponential
Func?ii statistice
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.

Descrierea

float stats_rand_gen_chisquare ( float $df )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

df

Valorile întoarse

stats_rand_gen_beta
stats_rand_gen_exponential
Func?ii statistice


Generates a single random deviate from an exponential distribution with mean "av"

stats_rand_gen_chisquare
stats_rand_gen_f
Func?ii statistice
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"

Descrierea

float stats_rand_gen_exponential ( float $av )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

av

Valorile întoarse

stats_rand_gen_chisquare
stats_rand_gen_f
Func?ii statistice


Generates a random deviate

stats_rand_gen_exponential
stats_rand_gen_funiform
Func?ii statistice
PHP Manual

stats_rand_gen_f

(PECL stats >= 1.0.0)

stats_rand_gen_f — Generates a random deviate

Descrierea

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.

Parametri

dfn

dfd

Valorile întoarse

stats_rand_gen_exponential
stats_rand_gen_funiform
Func?ii statistice


Generates uniform float between low (exclusive) and high (exclusive)

stats_rand_gen_f
stats_rand_gen_gamma
Func?ii statistice
PHP Manual

stats_rand_gen_funiform

(PECL stats >= 1.0.0)

stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)

Descrierea

float stats_rand_gen_funiform ( float $low , float $high )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

low

high

Valorile întoarse

stats_rand_gen_f
stats_rand_gen_gamma
Func?ii statistice


Generates random deviates from a gamma distribution

stats_rand_gen_funiform
stats_rand_gen_ibinomial_negative
Func?ii statistice
PHP Manual

stats_rand_gen_gamma

(PECL stats >= 1.0.0)

stats_rand_gen_gamma — Generates random deviates from a gamma distribution

Descrierea

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).

Parametri

a

location parameter of Gamma distribution (a > 0).

r

shape parameter of Gamma distribution (r > 0).

Valorile întoarse

stats_rand_gen_funiform
stats_rand_gen_ibinomial_negative
Func?ii statistice


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
Func?ii statistice
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)).

Descrierea

int stats_rand_gen_ibinomial_negative ( int $n , float $p )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

n

p

Valorile întoarse

stats_rand_gen_gamma
stats_rand_gen_ibinomial
Func?ii statistice


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
Func?ii statistice
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

Descrierea

int stats_rand_gen_ibinomial ( int $n , float $pp )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

n

pp

Valorile întoarse

stats_rand_gen_ibinomial_negative
stats_rand_gen_int
Func?ii statistice


Generates random integer between 1 and 2147483562

stats_rand_gen_ibinomial
stats_rand_gen_ipoisson
Func?ii statistice
PHP Manual

stats_rand_gen_int

(PECL stats >= 1.0.0)

stats_rand_gen_int — Generates random integer between 1 and 2147483562

Descrierea

int stats_rand_gen_int ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Valorile întoarse

stats_rand_gen_ibinomial
stats_rand_gen_ipoisson
Func?ii statistice


Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).

stats_rand_gen_int
stats_rand_gen_iuniform
Func?ii statistice
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).

Descrierea

int stats_rand_gen_ipoisson ( float $mu )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

mu

Valorile întoarse

stats_rand_gen_int
stats_rand_gen_iuniform
Func?ii statistice


Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

stats_rand_gen_ipoisson
stats_rand_gen_noncenral_chisquare
Func?ii statistice
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)

Descrierea

int stats_rand_gen_iuniform ( int $low , int $high )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

low

high

Valorile întoarse

stats_rand_gen_ipoisson
stats_rand_gen_noncenral_chisquare
Func?ii statistice


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
Func?ii statistice
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

Descrierea

float stats_rand_gen_noncenral_chisquare ( float $df , float $xnonc )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

df

xnonc

Valorile întoarse

stats_rand_gen_iuniform
stats_rand_gen_noncentral_f
Func?ii statistice


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
Func?ii statistice
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.

Descrierea

float stats_rand_gen_noncentral_f ( float $dfn , float $dfd , float $xnonc )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

dfn

dfd

xnonc

Valorile întoarse

stats_rand_gen_noncenral_chisquare
stats_rand_gen_noncentral_t
Func?ii statistice


Generates a single random deviate from a noncentral T distribution

stats_rand_gen_noncentral_f
stats_rand_gen_normal
Func?ii statistice
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

Descrierea

float stats_rand_gen_noncentral_t ( float $df , float $xnonc )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

df

xnonc

Valorile întoarse

stats_rand_gen_noncentral_f
stats_rand_gen_normal
Func?ii statistice


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
Func?ii statistice
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.

Descrierea

float stats_rand_gen_normal ( float $av , float $sd )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

av

sd

Valorile întoarse

stats_rand_gen_noncentral_t
stats_rand_gen_t
Func?ii statistice


Generates a single random deviate from a T distribution

stats_rand_gen_normal
stats_rand_get_seeds
Func?ii statistice
PHP Manual

stats_rand_gen_t

(PECL stats >= 1.0.0)

stats_rand_gen_t — Generates a single random deviate from a T distribution

Descrierea

float stats_rand_gen_t ( float $df )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

df

Valorile întoarse

stats_rand_gen_normal
stats_rand_get_seeds
Func?ii statistice


Not documented

stats_rand_gen_t
stats_rand_phrase_to_seeds
Func?ii statistice
PHP Manual

stats_rand_get_seeds

(PECL stats >= 1.0.0)

stats_rand_get_seeds — Not documented

Descrierea

array stats_rand_get_seeds ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Valorile întoarse

stats_rand_gen_t
stats_rand_phrase_to_seeds
Func?ii statistice


generate two seeds for the RGN random number generator

stats_rand_get_seeds
stats_rand_ranf
Func?ii statistice
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

Descrierea

array stats_rand_phrase_to_seeds ( string $phrase )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

phrase

Valorile întoarse

stats_rand_get_seeds
stats_rand_ranf
Func?ii statistice


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
Func?ii statistice
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

Descrierea

float stats_rand_ranf ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Valorile întoarse

stats_rand_phrase_to_seeds
stats_rand_setall
Func?ii statistice


Not documented

stats_rand_ranf
stats_skew
Func?ii statistice
PHP Manual

stats_rand_setall

(PECL stats >= 1.0.0)

stats_rand_setall — Not documented

Descrierea

void stats_rand_setall ( int $iseed1 , int $iseed2 )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

iseed1

iseed2

Valorile întoarse

stats_rand_ranf
stats_skew
Func?ii statistice


Computes the skewness of the data in the array

stats_rand_setall
stats_standard_deviation
Func?ii statistice
PHP Manual

stats_skew

(PECL stats >= 1.0.0)

stats_skew — Computes the skewness of the data in the array

Descrierea

float stats_skew ( array $a )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

a

Valorile întoarse

stats_rand_setall
stats_standard_deviation
Func?ii statistice


Returns the standard deviation

stats_skew
stats_stat_binomial_coef
Func?ii statistice
PHP Manual

stats_standard_deviation

(PECL stats >= 1.0.0)

stats_standard_deviation — Returns the standard deviation

Descrierea

float stats_standard_deviation ( array $a [, bool $sample = false ] )

Parametri

a

The array of data to find the standard deviation for. Note that all values of the array will be cast to float.

sample

Indicates if a represents a sample of the population; defaults to FALSE.

Valorile întoarse

Returns the standard deviation on success; FALSE on failure.

Erori/Excep?ii

Raises an E_WARNING when there are fewer than 2 values in a.

stats_skew
stats_stat_binomial_coef
Func?ii statistice


Not documented

stats_standard_deviation
stats_stat_correlation
Func?ii statistice
PHP Manual

stats_stat_binomial_coef

(PECL stats >= 1.0.0)

stats_stat_binomial_coef — Not documented

Descrierea

float stats_stat_binomial_coef ( int $x , int $n )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

x

n

Valorile întoarse

stats_standard_deviation
stats_stat_correlation
Func?ii statistice


Not documented

stats_stat_binomial_coef
stats_stat_gennch
Func?ii statistice
PHP Manual

stats_stat_correlation

(PECL stats >= 1.0.0)

stats_stat_correlation — Not documented

Descrierea

float stats_stat_correlation ( array $arr1 , array $arr2 )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

arr1

arr2

Valorile întoarse

stats_stat_binomial_coef
stats_stat_gennch
Func?ii statistice


Not documented

stats_stat_correlation
stats_stat_independent_t
Func?ii statistice
PHP Manual

stats_stat_gennch

(PECL stats >= 1.0.0)

stats_stat_gennch — Not documented

Descrierea

float stats_stat_gennch ( int $n )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

n

Valorile întoarse

stats_stat_correlation
stats_stat_independent_t
Func?ii statistice


Not documented

stats_stat_gennch
stats_stat_innerproduct
Func?ii statistice
PHP Manual

stats_stat_independent_t

(PECL stats >= 1.0.0)

stats_stat_independent_t — Not documented

Descrierea

float stats_stat_independent_t ( array $arr1 , array $arr2 )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

arr1

arr2

Valorile întoarse

stats_stat_gennch
stats_stat_innerproduct
Func?ii statistice


stats_stat_independent_t
stats_stat_noncentral_t
Func?ii statistice
PHP Manual

stats_stat_innerproduct

(PECL stats >= 1.0.0)

stats_stat_innerproduct —

Descrierea

float stats_stat_innerproduct ( array $arr1 , array $arr2 )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

arr1

arr2

Valorile întoarse

stats_stat_independent_t
stats_stat_noncentral_t
Func?ii statistice


Calculates any one parameter of the noncentral t distribution give values for the others.

stats_stat_innerproduct
stats_stat_paired_t
Func?ii statistice
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.

Descrierea

float stats_stat_noncentral_t ( float $par1 , float $par2 , float $par3 , int $which )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

par1

par2

par3

which

Valorile întoarse

stats_stat_innerproduct
stats_stat_paired_t
Func?ii statistice


Not documented

stats_stat_noncentral_t
stats_stat_percentile
Func?ii statistice
PHP Manual

stats_stat_paired_t

(PECL stats >= 1.0.0)

stats_stat_paired_t — Not documented

Descrierea

float stats_stat_paired_t ( array $arr1 , array $arr2 )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

arr1

arr2

Valorile întoarse

stats_stat_noncentral_t
stats_stat_percentile
Func?ii statistice


Not documented

stats_stat_paired_t
stats_stat_powersum
Func?ii statistice
PHP Manual

stats_stat_percentile

(PECL stats >= 1.0.0)

stats_stat_percentile — Not documented

Descrierea

float stats_stat_percentile ( float $df , float $xnonc )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

df

xnonc

Valorile întoarse

stats_stat_paired_t
stats_stat_powersum
Func?ii statistice


Not documented

stats_stat_percentile
stats_variance
Func?ii statistice
PHP Manual

stats_stat_powersum

(PECL stats >= 1.0.0)

stats_stat_powersum — Not documented

Descrierea

float stats_stat_powersum ( array $arr , float $power )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

arr

power

Valorile întoarse

stats_stat_percentile
stats_variance
Func?ii statistice


Returns the population variance

stats_stat_powersum
Trader
Func?ii statistice
PHP Manual

stats_variance

(PECL stats >= 1.0.0)

stats_variance — Returns the population variance

Descrierea

float stats_variance ( array $a [, bool $sample = false ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

a

sample

Valorile întoarse

stats_stat_powersum
Trader
Func?ii statistice


Technical Analysis for Traders

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
  • Constante predefinite
  • Func?ii trader
    • trader_acos — Vector Trigonometric ACos
    • trader_ad — Chaikin A/D Line
    • trader_add — Vector Arithmetic Add
    • trader_adosc — Chaikin A/D Oscillator
    • trader_adx — Average Directional Movement Index
    • trader_adxr — Average Directional Movement Index Rating
    • trader_apo — Absolute Price Oscillator
    • trader_aroon — Aroon
    • trader_aroonosc — Aroon Oscillator
    • trader_asin — Vector Trigonometric ASin
    • trader_atan — Vector Trigonometric ATan
    • trader_atr — Average True Range
    • trader_avgprice — Average Price
    • trader_bbands — Bollinger Bands
    • trader_beta — Beta
    • trader_bop — Balance Of Power
    • trader_cci — Commodity Channel Index
    • trader_cdl2crows — Two Crows
    • trader_cdl3blackcrows — Three Black Crows
    • trader_cdl3inside — Three Inside Up/Down
    • trader_cdl3linestrike — Three-Line Strike
    • trader_cdl3outside — Three Outside Up/Down
    • trader_cdl3starsinsouth — Three Stars In The South
    • trader_cdl3whitesoldiers — Three Advancing White Soldiers
    • trader_cdlabandonedbaby — Abandoned Baby
    • trader_cdladvanceblock — Advance Block
    • trader_cdlbelthold — Belt-hold
    • trader_cdlbreakaway — Breakaway
    • trader_cdlclosingmarubozu — Closing Marubozu
    • trader_cdlconcealbabyswall — Concealing Baby Swallow
    • trader_cdlcounterattack — Counterattack
    • trader_cdldarkcloudcover — Dark Cloud Cover
    • trader_cdldoji — Doji
    • trader_cdldojistar — Doji Star
    • trader_cdldragonflydoji — Dragonfly Doji
    • trader_cdlengulfing — Engulfing Pattern
    • trader_cdleveningdojistar — Evening Doji Star
    • trader_cdleveningstar — Evening Star
    • trader_cdlgapsidesidewhite — Up/Down-gap side-by-side white lines
    • trader_cdlgravestonedoji — Gravestone Doji
    • trader_cdlhammer — Hammer
    • trader_cdlhangingman — Hanging Man
    • trader_cdlharami — Harami Pattern
    • trader_cdlharamicross — Harami Cross Pattern
    • trader_cdlhighwave — High-Wave Candle
    • trader_cdlhikkake — Hikkake Pattern
    • trader_cdlhikkakemod — Modified Hikkake Pattern
    • trader_cdlhomingpigeon — Homing Pigeon
    • trader_cdlidentical3crows — Identical Three Crows
    • trader_cdlinneck — In-Neck Pattern
    • trader_cdlinvertedhammer — Inverted Hammer
    • trader_cdlkicking — Kicking
    • trader_cdlkickingbylength — Kicking - bull/bear determined by the longer marubozu
    • trader_cdlladderbottom — Ladder Bottom
    • trader_cdllongleggeddoji — Long Legged Doji
    • trader_cdllongline — Long Line Candle
    • trader_cdlmarubozu — Marubozu
    • trader_cdlmatchinglow — Matching Low
    • trader_cdlmathold — Mat Hold
    • trader_cdlmorningdojistar — Morning Doji Star
    • trader_cdlmorningstar — Morning Star
    • trader_cdlonneck — On-Neck Pattern
    • trader_cdlpiercing — Piercing Pattern
    • trader_cdlrickshawman — Rickshaw Man
    • trader_cdlrisefall3methods — Rising/Falling Three Methods
    • trader_cdlseparatinglines — Separating Lines
    • trader_cdlshootingstar — Shooting Star
    • trader_cdlshortline — Short Line Candle
    • trader_cdlspinningtop — Spinning Top
    • trader_cdlstalledpattern — Stalled Pattern
    • trader_cdlsticksandwich — Stick Sandwich
    • trader_cdltakuri — Takuri (Dragonfly Doji with very long lower shadow)
    • trader_cdltasukigap — Tasuki Gap
    • trader_cdlthrusting — Thrusting Pattern
    • trader_cdltristar — Tristar Pattern
    • trader_cdlunique3river — Unique 3 River
    • trader_cdlupsidegap2crows — Upside Gap Two Crows
    • trader_cdlxsidegap3methods — Upside/Downside Gap Three Methods
    • trader_ceil — Vector Ceil
    • trader_cmo — Chande Momentum Oscillator
    • trader_correl — Pearson's Correlation Coefficient (r)
    • trader_cos — Vector Trigonometric Cos
    • trader_cosh — Vector Trigonometric Cosh
    • trader_dema — Double Exponential Moving Average
    • trader_div — Vector Arithmetic Div
    • trader_dx — Directional Movement Index
    • trader_ema — Exponential Moving Average
    • trader_errno — Get error code
    • trader_exp — Vector Arithmetic Exp
    • trader_floor — Vector Floor
    • trader_get_compat — Get compatibility mode
    • trader_get_unstable_period — Get unstable period
    • trader_ht_dcperiod — Hilbert Transform - Dominant Cycle Period
    • trader_ht_dcphase — Hilbert Transform - Dominant Cycle Phase
    • trader_ht_phasor — Hilbert Transform - Phasor Components
    • trader_ht_sine — Hilbert Transform - SineWave
    • trader_ht_trendline — Hilbert Transform - Instantaneous Trendline
    • trader_ht_trendmode — Hilbert Transform - Trend vs Cycle Mode
    • trader_kama — Kaufman Adaptive Moving Average
    • trader_linearreg_angle — Linear Regression Angle
    • trader_linearreg_intercept — Linear Regression Intercept
    • trader_linearreg_slope — Linear Regression Slope
    • trader_linearreg — Linear Regression
    • trader_ln — Vector Log Natural
    • trader_log10 — Vector Log10
    • trader_ma — Moving average
    • trader_macd — Moving Average Convergence/Divergence
    • trader_macdext — MACD with controllable MA type
    • trader_macdfix — Moving Average Convergence/Divergence Fix 12/26
    • trader_mama — MESA Adaptive Moving Average
    • trader_mavp — Moving average with variable period
    • trader_max — Highest value over a specified period
    • trader_maxindex — Index of highest value over a specified period
    • trader_medprice — Median Price
    • trader_mfi — Money Flow Index
    • trader_midpoint — MidPoint over period
    • trader_midprice — Midpoint Price over period
    • trader_min — Lowest value over a specified period
    • trader_minindex — Index of lowest value over a specified period
    • trader_minmax — Lowest and highest values over a specified period
    • trader_minmaxindex — Indexes of lowest and highest values over a specified period
    • trader_minus_di — Minus Directional Indicator
    • trader_minus_dm — Minus Directional Movement
    • trader_mom — Momentum
    • trader_mult — Vector Arithmetic Mult
    • trader_natr — Normalized Average True Range
    • trader_obv — On Balance Volume
    • trader_plus_di — Plus Directional Indicator
    • trader_plus_dm — Plus Directional Movement
    • trader_ppo — Percentage Price Oscillator
    • trader_roc — Rate of change : ((price/prevPrice)-1)*100
    • trader_rocp — Rate of change Percentage: (price-prevPrice)/prevPrice
    • trader_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100
    • trader_rocr — Rate of change ratio: (price/prevPrice)
    • trader_rsi — Relative Strength Index
    • trader_sar — Parabolic SAR
    • trader_sarext — Parabolic SAR - Extended
    • trader_set_compat — Set compatibility mode
    • trader_set_unstable_period — Set unstable period
    • trader_sin — Vector Trigonometric Sin
    • trader_sinh — Vector Trigonometric Sinh
    • trader_sma — Simple Moving Average
    • trader_sqrt — Vector Square Root
    • trader_stddev — Standard Deviation
    • trader_stoch — Stochastic
    • trader_stochf — Stochastic Fast
    • trader_stochrsi — Stochastic Relative Strength Index
    • trader_sub — Vector Arithmetic Subtraction
    • trader_sum — Summation
    • trader_t3 — Triple Exponential Moving Average (T3)
    • trader_tan — Vector Trigonometric Tan
    • trader_tanh — Vector Trigonometric Tanh
    • trader_tema — Triple Exponential Moving Average
    • trader_trange — True Range
    • trader_trima — Triangular Moving Average
    • trader_trix — 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
    • trader_tsf — Time Series Forecast
    • trader_typprice — Typical Price
    • trader_ultosc — Ultimate Oscillator
    • trader_var — Variance
    • trader_wclprice — Weighted Close Price
    • trader_willr — Williams' %R
    • trader_wma — Weighted Moving Average
stats_variance
Introducere
Extensii matematice


Introducere

The trader extension is a free open source stock library based on TA-Lib. It's dedicated to trading software developers requiring to perform technical analysis of financial market data. Alongside many indicators like ADX, MACD, RSI, Stochastic, TRIX the candlestick pattern recognition and several vector arithmetic and algebraic functions are present.

Calculations can be done in two modes - TA-Lib and Metastock. Changing it using trader_set_compat() will affect the way some trader functions work.

Some trader functions provide different results depending of the "starting point" of the data being involved. This is often referred as a function having memories. An example of such function is the Exponential Moving Average. It is possible to control the unstable period (the amount of data to strip off) using trader_set_unstable_period() function.

Extended documentation about indicators, formulas and implementations in other programming languages can be found under » tadoc.org.

Trader
Instalarea / configurarea
Trader


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
Introducere
Necesita?i
Trader


Necesita?i

The trader extension is based on » TA-Lib. TA-Lib is fully integrated into the extension, therefore no external libraries are needed.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/trader.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/trader/.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Trader Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
trader.real_precision | 3 | PHP_INI_ALL | Since trader 0.2.1
trader.real_round_mode | HALF_DOWN | PHP_INI_ALL | Since trader 0.3.0

Iata o explica?ie pe scurt a directivelor de configurare.

trader.real_precision integer

All the values in the returned arrays will be rounded to this precision. However the calculations inside TA-Lib happen with unrounded values.

trader.real_round_mode string

Controls the trader real rounding policy. Valid values are HALF_UP, HALF_DOWN, HALF_EVEN and HALF_ODD. The behaviour is identical to the round() function used with the mode argument.

Instalarea
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

TRADER_MA_TYPE_SMA (integer)
TRADER_MA_TYPE_EMA (integer)
TRADER_MA_TYPE_WMA (integer)
TRADER_MA_TYPE_DEMA (integer)
TRADER_MA_TYPE_TEMA (integer)
TRADER_MA_TYPE_TRIMA (integer)
TRADER_MA_TYPE_KAMA (integer)
TRADER_MA_TYPE_MAMA (integer)
TRADER_MA_TYPE_T3 (integer)
TRADER_REAL_MIN (double)
TRADER_REAL_MAX (double)
TRADER_FUNC_UNST_ADX (integer)
TRADER_FUNC_UNST_ADXR (integer)
TRADER_FUNC_UNST_ATR (integer)
TRADER_FUNC_UNST_CMO (integer)
TRADER_FUNC_UNST_DX (integer)
TRADER_FUNC_UNST_EMA (integer)
TRADER_FUNC_UNST_HT_DCPERIOD (integer)
TRADER_FUNC_UNST_HT_DCPHASE (integer)
TRADER_FUNC_UNST_HT_PHASOR (integer)
TRADER_FUNC_UNST_HT_SINE (integer)
TRADER_FUNC_UNST_HT_TRENDLINE (integer)
TRADER_FUNC_UNST_HT_TRENDMODE (integer)
TRADER_FUNC_UNST_KAMA (integer)
TRADER_FUNC_UNST_MAMA (integer)
TRADER_FUNC_UNST_MFI (integer)
TRADER_FUNC_UNST_MINUS_DI (integer)
TRADER_FUNC_UNST_MINUS_DM (integer)
TRADER_FUNC_UNST_NATR (integer)
TRADER_FUNC_UNST_PLUS_DI (integer)
TRADER_FUNC_UNST_PLUS_DM (integer)
TRADER_FUNC_UNST_RSI (integer)
TRADER_FUNC_UNST_STOCHRSI (integer)
TRADER_FUNC_UNST_T3 (integer)
TRADER_FUNC_UNST_ALL (integer)
TRADER_FUNC_UNST_NONE (integer)
TRADER_COMPATIBILITY_DEFAULT (integer)
TRADER_COMPATIBILITY_METASTOCK (integer)
TRADER_ERR_SUCCESS (integer)
TRADER_ERR_LIB_NOT_INITIALIZE (integer)
TRADER_ERR_BAD_PARAM (integer)
TRADER_ERR_ALLOC_ERR (integer)
TRADER_ERR_GROUP_NOT_FOUND (integer)
TRADER_ERR_FUNC_NOT_FOUND (integer)
TRADER_ERR_INVALID_HANDLE (integer)
TRADER_ERR_INVALID_PARAM_HOLDER (integer)
TRADER_ERR_INVALID_PARAM_HOLDER_TYPE (integer)
TRADER_ERR_INVALID_PARAM_FUNCTION (integer)
TRADER_ERR_INPUT_NOT_ALL_INITIALIZE (integer)
TRADER_ERR_OUTPUT_NOT_ALL_INITIALIZE (integer)
TRADER_ERR_OUT_OF_RANGE_START_INDEX (integer)
TRADER_ERR_OUT_OF_RANGE_END_INDEX (integer)
TRADER_ERR_INVALID_LIST_TYPE (integer)
TRADER_ERR_BAD_OBJECT (integer)
TRADER_ERR_NOT_SUPPORTED (integer)
TRADER_ERR_INTERNAL_ERROR (integer)
TRADER_ERR_UNKNOWN_ERROR (integer)

Configura?ia la rulare
Func?ii trader
Trader


Func?ii trader

Cuprins

  • trader_acos — Vector Trigonometric ACos
  • trader_ad — Chaikin A/D Line
  • trader_add — Vector Arithmetic Add
  • trader_adosc — Chaikin A/D Oscillator
  • trader_adx — Average Directional Movement Index
  • trader_adxr — Average Directional Movement Index Rating
  • trader_apo — Absolute Price Oscillator
  • trader_aroon — Aroon
  • trader_aroonosc — Aroon Oscillator
  • trader_asin — Vector Trigonometric ASin
  • trader_atan — Vector Trigonometric ATan
  • trader_atr — Average True Range
  • trader_avgprice — Average Price
  • trader_bbands — Bollinger Bands
  • trader_beta — Beta
  • trader_bop — Balance Of Power
  • trader_cci — Commodity Channel Index
  • trader_cdl2crows — Two Crows
  • trader_cdl3blackcrows — Three Black Crows
  • trader_cdl3inside — Three Inside Up/Down
  • trader_cdl3linestrike — Three-Line Strike
  • trader_cdl3outside — Three Outside Up/Down
  • trader_cdl3starsinsouth — Three Stars In The South
  • trader_cdl3whitesoldiers — Three Advancing White Soldiers
  • trader_cdlabandonedbaby — Abandoned Baby
  • trader_cdladvanceblock — Advance Block
  • trader_cdlbelthold — Belt-hold
  • trader_cdlbreakaway — Breakaway
  • trader_cdlclosingmarubozu — Closing Marubozu
  • trader_cdlconcealbabyswall — Concealing Baby Swallow
  • trader_cdlcounterattack — Counterattack
  • trader_cdldarkcloudcover — Dark Cloud Cover
  • trader_cdldoji — Doji
  • trader_cdldojistar — Doji Star
  • trader_cdldragonflydoji — Dragonfly Doji
  • trader_cdlengulfing — Engulfing Pattern
  • trader_cdleveningdojistar — Evening Doji Star
  • trader_cdleveningstar — Evening Star
  • trader_cdlgapsidesidewhite — Up/Down-gap side-by-side white lines
  • trader_cdlgravestonedoji — Gravestone Doji
  • trader_cdlhammer — Hammer
  • trader_cdlhangingman — Hanging Man
  • trader_cdlharami — Harami Pattern
  • trader_cdlharamicross — Harami Cross Pattern
  • trader_cdlhighwave — High-Wave Candle
  • trader_cdlhikkake — Hikkake Pattern
  • trader_cdlhikkakemod — Modified Hikkake Pattern
  • trader_cdlhomingpigeon — Homing Pigeon
  • trader_cdlidentical3crows — Identical Three Crows
  • trader_cdlinneck — In-Neck Pattern
  • trader_cdlinvertedhammer — Inverted Hammer
  • trader_cdlkicking — Kicking
  • trader_cdlkickingbylength — Kicking - bull/bear determined by the longer marubozu
  • trader_cdlladderbottom — Ladder Bottom
  • trader_cdllongleggeddoji — Long Legged Doji
  • trader_cdllongline — Long Line Candle
  • trader_cdlmarubozu — Marubozu
  • trader_cdlmatchinglow — Matching Low
  • trader_cdlmathold — Mat Hold
  • trader_cdlmorningdojistar — Morning Doji Star
  • trader_cdlmorningstar — Morning Star
  • trader_cdlonneck — On-Neck Pattern
  • trader_cdlpiercing — Piercing Pattern
  • trader_cdlrickshawman — Rickshaw Man
  • trader_cdlrisefall3methods — Rising/Falling Three Methods
  • trader_cdlseparatinglines — Separating Lines
  • trader_cdlshootingstar — Shooting Star
  • trader_cdlshortline — Short Line Candle
  • trader_cdlspinningtop — Spinning Top
  • trader_cdlstalledpattern — Stalled Pattern
  • trader_cdlsticksandwich — Stick Sandwich
  • trader_cdltakuri — Takuri (Dragonfly Doji with very long lower shadow)
  • trader_cdltasukigap — Tasuki Gap
  • trader_cdlthrusting — Thrusting Pattern
  • trader_cdltristar — Tristar Pattern
  • trader_cdlunique3river — Unique 3 River
  • trader_cdlupsidegap2crows — Upside Gap Two Crows
  • trader_cdlxsidegap3methods — Upside/Downside Gap Three Methods
  • trader_ceil — Vector Ceil
  • trader_cmo — Chande Momentum Oscillator
  • trader_correl — Pearson's Correlation Coefficient (r)
  • trader_cos — Vector Trigonometric Cos
  • trader_cosh — Vector Trigonometric Cosh
  • trader_dema — Double Exponential Moving Average
  • trader_div — Vector Arithmetic Div
  • trader_dx — Directional Movement Index
  • trader_ema — Exponential Moving Average
  • trader_errno — Get error code
  • trader_exp — Vector Arithmetic Exp
  • trader_floor — Vector Floor
  • trader_get_compat — Get compatibility mode
  • trader_get_unstable_period — Get unstable period
  • trader_ht_dcperiod — Hilbert Transform - Dominant Cycle Period
  • trader_ht_dcphase — Hilbert Transform - Dominant Cycle Phase
  • trader_ht_phasor — Hilbert Transform - Phasor Components
  • trader_ht_sine — Hilbert Transform - SineWave
  • trader_ht_trendline — Hilbert Transform - Instantaneous Trendline
  • trader_ht_trendmode — Hilbert Transform - Trend vs Cycle Mode
  • trader_kama — Kaufman Adaptive Moving Average
  • trader_linearreg_angle — Linear Regression Angle
  • trader_linearreg_intercept — Linear Regression Intercept
  • trader_linearreg_slope — Linear Regression Slope
  • trader_linearreg — Linear Regression
  • trader_ln — Vector Log Natural
  • trader_log10 — Vector Log10
  • trader_ma — Moving average
  • trader_macd — Moving Average Convergence/Divergence
  • trader_macdext — MACD with controllable MA type
  • trader_macdfix — Moving Average Convergence/Divergence Fix 12/26
  • trader_mama — MESA Adaptive Moving Average
  • trader_mavp — Moving average with variable period
  • trader_max — Highest value over a specified period
  • trader_maxindex — Index of highest value over a specified period
  • trader_medprice — Median Price
  • trader_mfi — Money Flow Index
  • trader_midpoint — MidPoint over period
  • trader_midprice — Midpoint Price over period
  • trader_min — Lowest value over a specified period
  • trader_minindex — Index of lowest value over a specified period
  • trader_minmax — Lowest and highest values over a specified period
  • trader_minmaxindex — Indexes of lowest and highest values over a specified period
  • trader_minus_di — Minus Directional Indicator
  • trader_minus_dm — Minus Directional Movement
  • trader_mom — Momentum
  • trader_mult — Vector Arithmetic Mult
  • trader_natr — Normalized Average True Range
  • trader_obv — On Balance Volume
  • trader_plus_di — Plus Directional Indicator
  • trader_plus_dm — Plus Directional Movement
  • trader_ppo — Percentage Price Oscillator
  • trader_roc — Rate of change : ((price/prevPrice)-1)*100
  • trader_rocp — Rate of change Percentage: (price-prevPrice)/prevPrice
  • trader_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100
  • trader_rocr — Rate of change ratio: (price/prevPrice)
  • trader_rsi — Relative Strength Index
  • trader_sar — Parabolic SAR
  • trader_sarext — Parabolic SAR - Extended
  • trader_set_compat — Set compatibility mode
  • trader_set_unstable_period — Set unstable period
  • trader_sin — Vector Trigonometric Sin
  • trader_sinh — Vector Trigonometric Sinh
  • trader_sma — Simple Moving Average
  • trader_sqrt — Vector Square Root
  • trader_stddev — Standard Deviation
  • trader_stoch — Stochastic
  • trader_stochf — Stochastic Fast
  • trader_stochrsi — Stochastic Relative Strength Index
  • trader_sub — Vector Arithmetic Subtraction
  • trader_sum — Summation
  • trader_t3 — Triple Exponential Moving Average (T3)
  • trader_tan — Vector Trigonometric Tan
  • trader_tanh — Vector Trigonometric Tanh
  • trader_tema — Triple Exponential Moving Average
  • trader_trange — True Range
  • trader_trima — Triangular Moving Average
  • trader_trix — 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
  • trader_tsf — Time Series Forecast
  • trader_typprice — Typical Price
  • trader_ultosc — Ultimate Oscillator
  • trader_var — Variance
  • trader_wclprice — Weighted Close Price
  • trader_willr — Williams' %R
  • trader_wma — Weighted Moving Average
Constante predefinite
trader_acos
Trader


Vector Trigonometric ACos

Func?ii trader
trader_ad
Func?ii trader
PHP Manual

trader_acos

(PECL trader >= 0.2.0)

trader_acos — Vector Trigonometric ACos

Descrierea

array trader_acos ( array $real )

Calculates the arc cosine for each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

Func?ii trader
trader_ad
Func?ii trader


Chaikin A/D Line

trader_acos
trader_add
Func?ii trader
PHP Manual

trader_ad

(PECL trader >= 0.2.0)

trader_ad — Chaikin A/D Line

Descrierea

array trader_ad ( array $high , array $low , array $close , array $volume )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

volume

Volumul tranzac?ionat, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_acos
trader_add
Func?ii trader


Vector Arithmetic Add

trader_ad
trader_adosc
Func?ii trader
PHP Manual

trader_add

(PECL trader >= 0.2.0)

trader_add — Vector Arithmetic Add

Descrierea

array trader_add ( array $real0 , array $real1 )

Calculates the vector addition of real0 to real1 and returns the resulting vector.

Parametri

real0

Un tablou cu valori reale.

real1

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_ad
trader_adosc
Func?ii trader


Chaikin A/D Oscillator

trader_add
trader_adx
Func?ii trader
PHP Manual

trader_adosc

(PECL trader >= 0.2.0)

trader_adosc — Chaikin A/D Oscillator

Descrierea

array trader_adosc ( array $high , array $low , array $close , array $volume [, integer $fastPeriod [, integer $slowPeriod ]] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

volume

Volumul tranzac?ionat, un tablou cu valori reale.

fastPeriod

Numarul perioadei pentru MA rapida. Domeniul valorilor admisibile este de la 2 pâna la 100000.

slowPeriod

Numarul perioadei pentru MA lenta. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_add
trader_adx
Func?ii trader


Average Directional Movement Index

trader_adosc
trader_adxr
Func?ii trader
PHP Manual

trader_adx

(PECL trader >= 0.2.0)

trader_adx — Average Directional Movement Index

Descrierea

array trader_adx ( array $high , array $low , array $close [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_adosc
trader_adxr
Func?ii trader


Average Directional Movement Index Rating

trader_adx
trader_apo
Func?ii trader
PHP Manual

trader_adxr

(PECL trader >= 0.2.0)

trader_adxr — Average Directional Movement Index Rating

Descrierea

array trader_adxr ( array $high , array $low , array $close [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_adx
trader_apo
Func?ii trader


Absolute Price Oscillator

trader_adxr
trader_aroon
Func?ii trader
PHP Manual

trader_apo

(PECL trader >= 0.2.0)

trader_apo — Absolute Price Oscillator

Descrierea

array trader_apo ( array $real [, integer $fastPeriod [, integer $slowPeriod [, integer $mAType ]]] )

Parametri

real

Un tablou cu valori reale.

fastPeriod

Numarul perioadei pentru MA rapida. Domeniul valorilor admisibile este de la 2 pâna la 100000.

slowPeriod

Numarul perioadei pentru MA lenta. Domeniul valorilor admisibile este de la 2 pâna la 100000.

mAType

Tipul Mediei Mobile. Trebuie utilizate constantele din seria TRADER_MA_TYPE_*.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_adxr
trader_aroon
Func?ii trader


Aroon

trader_apo
trader_aroonosc
Func?ii trader
PHP Manual

trader_aroon

(PECL trader >= 0.2.0)

trader_aroon — Aroon

Descrierea

array trader_aroon ( array $high , array $low [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_apo
trader_aroonosc
Func?ii trader


Aroon Oscillator

trader_aroon
trader_asin
Func?ii trader
PHP Manual

trader_aroonosc

(PECL trader >= 0.2.0)

trader_aroonosc — Aroon Oscillator

Descrierea

array trader_aroonosc ( array $high , array $low [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_aroon
trader_asin
Func?ii trader


Vector Trigonometric ASin

trader_aroonosc
trader_atan
Func?ii trader
PHP Manual

trader_asin

(PECL trader >= 0.2.0)

trader_asin — Vector Trigonometric ASin

Descrierea

array trader_asin ( array $real )

Calculates the arc sine for each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_aroonosc
trader_atan
Func?ii trader


Vector Trigonometric ATan

trader_asin
trader_atr
Func?ii trader
PHP Manual

trader_atan

(PECL trader >= 0.2.0)

trader_atan — Vector Trigonometric ATan

Descrierea

array trader_atan ( array $real )

Calculates the arc tangent for each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_asin
trader_atr
Func?ii trader


Average True Range

trader_atan
trader_avgprice
Func?ii trader
PHP Manual

trader_atr

(PECL trader >= 0.2.0)

trader_atr — Average True Range

Descrierea

array trader_atr ( array $high , array $low , array $close [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_atan
trader_avgprice
Func?ii trader


Average Price

trader_atr
trader_bbands
Func?ii trader
PHP Manual

trader_avgprice

(PECL trader >= 0.2.0)

trader_avgprice — Average Price

Descrierea

array trader_avgprice ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_atr
trader_bbands
Func?ii trader


Bollinger Bands

trader_avgprice
trader_beta
Func?ii trader
PHP Manual

trader_bbands

(PECL trader >= 0.2.0)

trader_bbands — Bollinger Bands

Descrierea

array trader_bbands ( array $real [, integer $timePeriod [, float $nbDevUp [, float $nbDevDn [, integer $mAType ]]]] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

nbDevUp

Multiplificatorul devia?iei pentru banda superioara. Domeniul valorilor admisibile este de la TRADER_REAL_MIN pâna la TRADER_REAL_MAX.

nbDevDn

Multiplificatorul devia?iei pentru banda inferioara. Domeniul valorilor admisibile este de la TRADER_REAL_MIN pâna la TRADER_REAL_MAX.

mAType

Tipul Mediei Mobile. Trebuie utilizate constantele din seria TRADER_MA_TYPE_*.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_avgprice
trader_beta
Func?ii trader


Beta

trader_bbands
trader_bop
Func?ii trader
PHP Manual

trader_beta

(PECL trader >= 0.2.0)

trader_beta — Beta

Descrierea

array trader_beta ( array $real0 , array $real1 [, integer $timePeriod ] )

Parametri

real0

Un tablou cu valori reale.

real1

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_bbands
trader_bop
Func?ii trader


Balance Of Power

trader_beta
trader_cci
Func?ii trader
PHP Manual

trader_bop

(PECL trader >= 0.2.0)

trader_bop — Balance Of Power

Descrierea

array trader_bop ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_beta
trader_cci
Func?ii trader


Commodity Channel Index

trader_bop
trader_cdl2crows
Func?ii trader
PHP Manual

trader_cci

(PECL trader >= 0.2.0)

trader_cci — Commodity Channel Index

Descrierea

array trader_cci ( array $high , array $low , array $close [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_bop
trader_cdl2crows
Func?ii trader


Two Crows

trader_cci
trader_cdl3blackcrows
Func?ii trader
PHP Manual

trader_cdl2crows

(PECL trader >= 0.2.0)

trader_cdl2crows — Two Crows

Descrierea

array trader_cdl2crows ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cci
trader_cdl3blackcrows
Func?ii trader


Three Black Crows

trader_cdl2crows
trader_cdl3inside
Func?ii trader
PHP Manual

trader_cdl3blackcrows

(PECL trader >= 0.2.0)

trader_cdl3blackcrows — Three Black Crows

Descrierea

array trader_cdl3blackcrows ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdl2crows
trader_cdl3inside
Func?ii trader


Three Inside Up/Down

trader_cdl3blackcrows
trader_cdl3linestrike
Func?ii trader
PHP Manual

trader_cdl3inside

(PECL trader >= 0.2.0)

trader_cdl3inside — Three Inside Up/Down

Descrierea

array trader_cdl3inside ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdl3blackcrows
trader_cdl3linestrike
Func?ii trader


Three-Line Strike

trader_cdl3inside
trader_cdl3outside
Func?ii trader
PHP Manual

trader_cdl3linestrike

(PECL trader >= 0.2.0)

trader_cdl3linestrike — Three-Line Strike

Descrierea

array trader_cdl3linestrike ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdl3inside
trader_cdl3outside
Func?ii trader


Three Outside Up/Down

trader_cdl3linestrike
trader_cdl3starsinsouth
Func?ii trader
PHP Manual

trader_cdl3outside

(PECL trader >= 0.2.0)

trader_cdl3outside — Three Outside Up/Down

Descrierea

array trader_cdl3outside ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdl3linestrike
trader_cdl3starsinsouth
Func?ii trader


Three Stars In The South

trader_cdl3outside
trader_cdl3whitesoldiers
Func?ii trader
PHP Manual

trader_cdl3starsinsouth

(PECL trader >= 0.2.0)

trader_cdl3starsinsouth — Three Stars In The South

Descrierea

array trader_cdl3starsinsouth ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdl3outside
trader_cdl3whitesoldiers
Func?ii trader


Three Advancing White Soldiers

trader_cdl3starsinsouth
trader_cdlabandonedbaby
Func?ii trader
PHP Manual

trader_cdl3whitesoldiers

(PECL trader >= 0.2.0)

trader_cdl3whitesoldiers — Three Advancing White Soldiers

Descrierea

array trader_cdl3whitesoldiers ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdl3starsinsouth
trader_cdlabandonedbaby
Func?ii trader


Abandoned Baby

trader_cdl3whitesoldiers
trader_cdladvanceblock
Func?ii trader
PHP Manual

trader_cdlabandonedbaby

(PECL trader >= 0.2.0)

trader_cdlabandonedbaby — Abandoned Baby

Descrierea

array trader_cdlabandonedbaby ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

penetration

Procentul penetrarii unei lumânari în alta lumânare.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdl3whitesoldiers
trader_cdladvanceblock
Func?ii trader


Advance Block

trader_cdlabandonedbaby
trader_cdlbelthold
Func?ii trader
PHP Manual

trader_cdladvanceblock

(PECL trader >= 0.2.0)

trader_cdladvanceblock — Advance Block

Descrierea

array trader_cdladvanceblock ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlabandonedbaby
trader_cdlbelthold
Func?ii trader


Belt-hold

trader_cdladvanceblock
trader_cdlbreakaway
Func?ii trader
PHP Manual

trader_cdlbelthold

(PECL trader >= 0.2.0)

trader_cdlbelthold — Belt-hold

Descrierea

array trader_cdlbelthold ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdladvanceblock
trader_cdlbreakaway
Func?ii trader


Breakaway

trader_cdlbelthold
trader_cdlclosingmarubozu
Func?ii trader
PHP Manual

trader_cdlbreakaway

(PECL trader >= 0.2.0)

trader_cdlbreakaway — Breakaway

Descrierea

array trader_cdlbreakaway ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlbelthold
trader_cdlclosingmarubozu
Func?ii trader


Closing Marubozu

trader_cdlbreakaway
trader_cdlconcealbabyswall
Func?ii trader
PHP Manual

trader_cdlclosingmarubozu

(PECL trader >= 0.2.0)

trader_cdlclosingmarubozu — Closing Marubozu

Descrierea

array trader_cdlclosingmarubozu ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlbreakaway
trader_cdlconcealbabyswall
Func?ii trader


Concealing Baby Swallow

trader_cdlclosingmarubozu
trader_cdlcounterattack
Func?ii trader
PHP Manual

trader_cdlconcealbabyswall

(PECL trader >= 0.2.0)

trader_cdlconcealbabyswall — Concealing Baby Swallow

Descrierea

array trader_cdlconcealbabyswall ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlclosingmarubozu
trader_cdlcounterattack
Func?ii trader


Counterattack

trader_cdlconcealbabyswall
trader_cdldarkcloudcover
Func?ii trader
PHP Manual

trader_cdlcounterattack

(PECL trader >= 0.2.0)

trader_cdlcounterattack — Counterattack

Descrierea

array trader_cdlcounterattack ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlconcealbabyswall
trader_cdldarkcloudcover
Func?ii trader


Dark Cloud Cover

trader_cdlcounterattack
trader_cdldoji
Func?ii trader
PHP Manual

trader_cdldarkcloudcover

(PECL trader >= 0.2.0)

trader_cdldarkcloudcover — Dark Cloud Cover

Descrierea

array trader_cdldarkcloudcover ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

penetration

Procentul penetrarii unei lumânari în alta lumânare.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlcounterattack
trader_cdldoji
Func?ii trader


Doji

trader_cdldarkcloudcover
trader_cdldojistar
Func?ii trader
PHP Manual

trader_cdldoji

(PECL trader >= 0.2.0)

trader_cdldoji — Doji

Descrierea

array trader_cdldoji ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdldarkcloudcover
trader_cdldojistar
Func?ii trader


Doji Star

trader_cdldoji
trader_cdldragonflydoji
Func?ii trader
PHP Manual

trader_cdldojistar

(PECL trader >= 0.2.0)

trader_cdldojistar — Doji Star

Descrierea

array trader_cdldojistar ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdldoji
trader_cdldragonflydoji
Func?ii trader


Dragonfly Doji

trader_cdldojistar
trader_cdlengulfing
Func?ii trader
PHP Manual

trader_cdldragonflydoji

(PECL trader >= 0.2.0)

trader_cdldragonflydoji — Dragonfly Doji

Descrierea

array trader_cdldragonflydoji ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdldojistar
trader_cdlengulfing
Func?ii trader


Engulfing Pattern

trader_cdldragonflydoji
trader_cdleveningdojistar
Func?ii trader
PHP Manual

trader_cdlengulfing

(PECL trader >= 0.2.0)

trader_cdlengulfing — Engulfing Pattern

Descrierea

array trader_cdlengulfing ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdldragonflydoji
trader_cdleveningdojistar
Func?ii trader


Evening Doji Star

trader_cdlengulfing
trader_cdleveningstar
Func?ii trader
PHP Manual

trader_cdleveningdojistar

(PECL trader >= 0.2.0)

trader_cdleveningdojistar — Evening Doji Star

Descrierea

array trader_cdleveningdojistar ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

penetration

Procentul penetrarii unei lumânari în alta lumânare.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlengulfing
trader_cdleveningstar
Func?ii trader


Evening Star

trader_cdleveningdojistar
trader_cdlgapsidesidewhite
Func?ii trader
PHP Manual

trader_cdleveningstar

(PECL trader >= 0.2.0)

trader_cdleveningstar — Evening Star

Descrierea

array trader_cdleveningstar ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

penetration

Procentul penetrarii unei lumânari în alta lumânare.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdleveningdojistar
trader_cdlgapsidesidewhite
Func?ii trader


Up/Down-gap side-by-side white lines

trader_cdleveningstar
trader_cdlgravestonedoji
Func?ii trader
PHP Manual

trader_cdlgapsidesidewhite

(PECL trader >= 0.2.0)

trader_cdlgapsidesidewhite — Up/Down-gap side-by-side white lines

Descrierea

array trader_cdlgapsidesidewhite ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdleveningstar
trader_cdlgravestonedoji
Func?ii trader


Gravestone Doji

trader_cdlgapsidesidewhite
trader_cdlhammer
Func?ii trader
PHP Manual

trader_cdlgravestonedoji

(PECL trader >= 0.2.0)

trader_cdlgravestonedoji — Gravestone Doji

Descrierea

array trader_cdlgravestonedoji ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlgapsidesidewhite
trader_cdlhammer
Func?ii trader


Hammer

trader_cdlgravestonedoji
trader_cdlhangingman
Func?ii trader
PHP Manual

trader_cdlhammer

(PECL trader >= 0.2.0)

trader_cdlhammer — Hammer

Descrierea

array trader_cdlhammer ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlgravestonedoji
trader_cdlhangingman
Func?ii trader


Hanging Man

trader_cdlhammer
trader_cdlharami
Func?ii trader
PHP Manual

trader_cdlhangingman

(PECL trader >= 0.2.0)

trader_cdlhangingman — Hanging Man

Descrierea

array trader_cdlhangingman ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlhammer
trader_cdlharami
Func?ii trader


Harami Pattern

trader_cdlhangingman
trader_cdlharamicross
Func?ii trader
PHP Manual

trader_cdlharami

(PECL trader >= 0.2.0)

trader_cdlharami — Harami Pattern

Descrierea

array trader_cdlharami ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlhangingman
trader_cdlharamicross
Func?ii trader


Harami Cross Pattern

trader_cdlharami
trader_cdlhighwave
Func?ii trader
PHP Manual

trader_cdlharamicross

(PECL trader >= 0.2.0)

trader_cdlharamicross — Harami Cross Pattern

Descrierea

array trader_cdlharamicross ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlharami
trader_cdlhighwave
Func?ii trader


High-Wave Candle

trader_cdlharamicross
trader_cdlhikkake
Func?ii trader
PHP Manual

trader_cdlhighwave

(PECL trader >= 0.2.0)

trader_cdlhighwave — High-Wave Candle

Descrierea

array trader_cdlhighwave ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlharamicross
trader_cdlhikkake
Func?ii trader


Hikkake Pattern

trader_cdlhighwave
trader_cdlhikkakemod
Func?ii trader
PHP Manual

trader_cdlhikkake

(PECL trader >= 0.2.0)

trader_cdlhikkake — Hikkake Pattern

Descrierea

array trader_cdlhikkake ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlhighwave
trader_cdlhikkakemod
Func?ii trader


Modified Hikkake Pattern

trader_cdlhikkake
trader_cdlhomingpigeon
Func?ii trader
PHP Manual

trader_cdlhikkakemod

(PECL trader >= 0.2.0)

trader_cdlhikkakemod — Modified Hikkake Pattern

Descrierea

array trader_cdlhikkakemod ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlhikkake
trader_cdlhomingpigeon
Func?ii trader


Homing Pigeon

trader_cdlhikkakemod
trader_cdlidentical3crows
Func?ii trader
PHP Manual

trader_cdlhomingpigeon

(PECL trader >= 0.2.0)

trader_cdlhomingpigeon — Homing Pigeon

Descrierea

array trader_cdlhomingpigeon ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlhikkakemod
trader_cdlidentical3crows
Func?ii trader


Identical Three Crows

trader_cdlhomingpigeon
trader_cdlinneck
Func?ii trader
PHP Manual

trader_cdlidentical3crows

(PECL trader >= 0.2.0)

trader_cdlidentical3crows — Identical Three Crows

Descrierea

array trader_cdlidentical3crows ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlhomingpigeon
trader_cdlinneck
Func?ii trader


In-Neck Pattern

trader_cdlidentical3crows
trader_cdlinvertedhammer
Func?ii trader
PHP Manual

trader_cdlinneck

(PECL trader >= 0.2.0)

trader_cdlinneck — In-Neck Pattern

Descrierea

array trader_cdlinneck ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlidentical3crows
trader_cdlinvertedhammer
Func?ii trader


Inverted Hammer

trader_cdlinneck
trader_cdlkicking
Func?ii trader
PHP Manual

trader_cdlinvertedhammer

(PECL trader >= 0.2.0)

trader_cdlinvertedhammer — Inverted Hammer

Descrierea

array trader_cdlinvertedhammer ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlinneck
trader_cdlkicking
Func?ii trader


Kicking

trader_cdlinvertedhammer
trader_cdlkickingbylength
Func?ii trader
PHP Manual

trader_cdlkicking

(PECL trader >= 0.2.0)

trader_cdlkicking — Kicking

Descrierea

array trader_cdlkicking ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlinvertedhammer
trader_cdlkickingbylength
Func?ii trader


Kicking - bull/bear determined by the longer marubozu

trader_cdlkicking
trader_cdlladderbottom
Func?ii trader
PHP Manual

trader_cdlkickingbylength

(PECL trader >= 0.2.0)

trader_cdlkickingbylength — Kicking - bull/bear determined by the longer marubozu

Descrierea

array trader_cdlkickingbylength ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlkicking
trader_cdlladderbottom
Func?ii trader


Ladder Bottom

trader_cdlkickingbylength
trader_cdllongleggeddoji
Func?ii trader
PHP Manual

trader_cdlladderbottom

(PECL trader >= 0.2.0)

trader_cdlladderbottom — Ladder Bottom

Descrierea

array trader_cdlladderbottom ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlkickingbylength
trader_cdllongleggeddoji
Func?ii trader


Long Legged Doji

trader_cdlladderbottom
trader_cdllongline
Func?ii trader
PHP Manual

trader_cdllongleggeddoji

(PECL trader >= 0.2.0)

trader_cdllongleggeddoji — Long Legged Doji

Descrierea

array trader_cdllongleggeddoji ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlladderbottom
trader_cdllongline
Func?ii trader


Long Line Candle

trader_cdllongleggeddoji
trader_cdlmarubozu
Func?ii trader
PHP Manual

trader_cdllongline

(PECL trader >= 0.2.0)

trader_cdllongline — Long Line Candle

Descrierea

array trader_cdllongline ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdllongleggeddoji
trader_cdlmarubozu
Func?ii trader


Marubozu

trader_cdllongline
trader_cdlmatchinglow
Func?ii trader
PHP Manual

trader_cdlmarubozu

(PECL trader >= 0.2.0)

trader_cdlmarubozu — Marubozu

Descrierea

array trader_cdlmarubozu ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdllongline
trader_cdlmatchinglow
Func?ii trader


Matching Low

trader_cdlmarubozu
trader_cdlmathold
Func?ii trader
PHP Manual

trader_cdlmatchinglow

(PECL trader >= 0.2.0)

trader_cdlmatchinglow — Matching Low

Descrierea

array trader_cdlmatchinglow ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlmarubozu
trader_cdlmathold
Func?ii trader


Mat Hold

trader_cdlmatchinglow
trader_cdlmorningdojistar
Func?ii trader
PHP Manual

trader_cdlmathold

(PECL trader >= 0.2.0)

trader_cdlmathold — Mat Hold

Descrierea

array trader_cdlmathold ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

penetration

Procentul penetrarii unei lumânari în alta lumânare.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlmatchinglow
trader_cdlmorningdojistar
Func?ii trader


Morning Doji Star

trader_cdlmathold
trader_cdlmorningstar
Func?ii trader
PHP Manual

trader_cdlmorningdojistar

(PECL trader >= 0.2.0)

trader_cdlmorningdojistar — Morning Doji Star

Descrierea

array trader_cdlmorningdojistar ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

penetration

Procentul penetrarii unei lumânari în alta lumânare.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlmathold
trader_cdlmorningstar
Func?ii trader


Morning Star

trader_cdlmorningdojistar
trader_cdlonneck
Func?ii trader
PHP Manual

trader_cdlmorningstar

(PECL trader >= 0.2.0)

trader_cdlmorningstar — Morning Star

Descrierea

array trader_cdlmorningstar ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

penetration

Procentul penetrarii unei lumânari în alta lumânare.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlmorningdojistar
trader_cdlonneck
Func?ii trader


On-Neck Pattern

trader_cdlmorningstar
trader_cdlpiercing
Func?ii trader
PHP Manual

trader_cdlonneck

(PECL trader >= 0.2.0)

trader_cdlonneck — On-Neck Pattern

Descrierea

array trader_cdlonneck ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlmorningstar
trader_cdlpiercing
Func?ii trader


Piercing Pattern

trader_cdlonneck
trader_cdlrickshawman
Func?ii trader
PHP Manual

trader_cdlpiercing

(PECL trader >= 0.2.0)

trader_cdlpiercing — Piercing Pattern

Descrierea

array trader_cdlpiercing ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlonneck
trader_cdlrickshawman
Func?ii trader


Rickshaw Man

trader_cdlpiercing
trader_cdlrisefall3methods
Func?ii trader
PHP Manual

trader_cdlrickshawman

(PECL trader >= 0.2.0)

trader_cdlrickshawman — Rickshaw Man

Descrierea

array trader_cdlrickshawman ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlpiercing
trader_cdlrisefall3methods
Func?ii trader


Rising/Falling Three Methods

trader_cdlrickshawman
trader_cdlseparatinglines
Func?ii trader
PHP Manual

trader_cdlrisefall3methods

(PECL trader >= 0.2.0)

trader_cdlrisefall3methods — Rising/Falling Three Methods

Descrierea

array trader_cdlrisefall3methods ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlrickshawman
trader_cdlseparatinglines
Func?ii trader


Separating Lines

trader_cdlrisefall3methods
trader_cdlshootingstar
Func?ii trader
PHP Manual

trader_cdlseparatinglines

(PECL trader >= 0.2.0)

trader_cdlseparatinglines — Separating Lines

Descrierea

array trader_cdlseparatinglines ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlrisefall3methods
trader_cdlshootingstar
Func?ii trader


Shooting Star

trader_cdlseparatinglines
trader_cdlshortline
Func?ii trader
PHP Manual

trader_cdlshootingstar

(PECL trader >= 0.2.0)

trader_cdlshootingstar — Shooting Star

Descrierea

array trader_cdlshootingstar ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlseparatinglines
trader_cdlshortline
Func?ii trader


Short Line Candle

trader_cdlshootingstar
trader_cdlspinningtop
Func?ii trader
PHP Manual

trader_cdlshortline

(PECL trader >= 0.2.0)

trader_cdlshortline — Short Line Candle

Descrierea

array trader_cdlshortline ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlshootingstar
trader_cdlspinningtop
Func?ii trader


Spinning Top

trader_cdlshortline
trader_cdlstalledpattern
Func?ii trader
PHP Manual

trader_cdlspinningtop

(PECL trader >= 0.2.0)

trader_cdlspinningtop — Spinning Top

Descrierea

array trader_cdlspinningtop ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlshortline
trader_cdlstalledpattern
Func?ii trader


Stalled Pattern

trader_cdlspinningtop
trader_cdlsticksandwich
Func?ii trader
PHP Manual

trader_cdlstalledpattern

(PECL trader >= 0.2.0)

trader_cdlstalledpattern — Stalled Pattern

Descrierea

array trader_cdlstalledpattern ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlspinningtop
trader_cdlsticksandwich
Func?ii trader


Stick Sandwich

trader_cdlstalledpattern
trader_cdltakuri
Func?ii trader
PHP Manual

trader_cdlsticksandwich

(PECL trader >= 0.2.0)

trader_cdlsticksandwich — Stick Sandwich

Descrierea

array trader_cdlsticksandwich ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlstalledpattern
trader_cdltakuri
Func?ii trader


Takuri (Dragonfly Doji with very long lower shadow)

trader_cdlsticksandwich
trader_cdltasukigap
Func?ii trader
PHP Manual

trader_cdltakuri

(PECL trader >= 0.2.0)

trader_cdltakuri — Takuri (Dragonfly Doji with very long lower shadow)

Descrierea

array trader_cdltakuri ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlsticksandwich
trader_cdltasukigap
Func?ii trader


Tasuki Gap

trader_cdltakuri
trader_cdlthrusting
Func?ii trader
PHP Manual

trader_cdltasukigap

(PECL trader >= 0.2.0)

trader_cdltasukigap — Tasuki Gap

Descrierea

array trader_cdltasukigap ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdltakuri
trader_cdlthrusting
Func?ii trader


Thrusting Pattern

trader_cdltasukigap
trader_cdltristar
Func?ii trader
PHP Manual

trader_cdlthrusting

(PECL trader >= 0.2.0)

trader_cdlthrusting — Thrusting Pattern

Descrierea

array trader_cdlthrusting ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdltasukigap
trader_cdltristar
Func?ii trader


Tristar Pattern

trader_cdlthrusting
trader_cdlunique3river
Func?ii trader
PHP Manual

trader_cdltristar

(PECL trader >= 0.2.0)

trader_cdltristar — Tristar Pattern

Descrierea

array trader_cdltristar ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlthrusting
trader_cdlunique3river
Func?ii trader


Unique 3 River

trader_cdltristar
trader_cdlupsidegap2crows
Func?ii trader
PHP Manual

trader_cdlunique3river

(PECL trader >= 0.2.0)

trader_cdlunique3river — Unique 3 River

Descrierea

array trader_cdlunique3river ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdltristar
trader_cdlupsidegap2crows
Func?ii trader


Upside Gap Two Crows

trader_cdlunique3river
trader_cdlxsidegap3methods
Func?ii trader
PHP Manual

trader_cdlupsidegap2crows

(PECL trader >= 0.2.0)

trader_cdlupsidegap2crows — Upside Gap Two Crows

Descrierea

array trader_cdlupsidegap2crows ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlunique3river
trader_cdlxsidegap3methods
Func?ii trader


Upside/Downside Gap Three Methods

trader_cdlupsidegap2crows
trader_ceil
Func?ii trader
PHP Manual

trader_cdlxsidegap3methods

(PECL trader >= 0.2.0)

trader_cdlxsidegap3methods — Upside/Downside Gap Three Methods

Descrierea

array trader_cdlxsidegap3methods ( array $open , array $high , array $low , array $close )

Parametri

open

Pre?ul de deschidere, un tablou cu valori reale.

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlupsidegap2crows
trader_ceil
Func?ii trader


Vector Ceil

trader_cdlxsidegap3methods
trader_cmo
Func?ii trader
PHP Manual

trader_ceil

(PECL trader >= 0.2.0)

trader_ceil — Vector Ceil

Descrierea

array trader_ceil ( array $real )

Calculates the next higest integer for each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cdlxsidegap3methods
trader_cmo
Func?ii trader


Chande Momentum Oscillator

trader_ceil
trader_correl
Func?ii trader
PHP Manual

trader_cmo

(PECL trader >= 0.2.0)

trader_cmo — Chande Momentum Oscillator

Descrierea

array trader_cmo ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_ceil
trader_correl
Func?ii trader


Pearson's Correlation Coefficient (r)

trader_cmo
trader_cos
Func?ii trader
PHP Manual

trader_correl

(PECL trader >= 0.2.0)

trader_correl — Pearson's Correlation Coefficient (r)

Descrierea

array trader_correl ( array $real0 , array $real1 [, integer $timePeriod ] )

Parametri

real0

Un tablou cu valori reale.

real1

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cmo
trader_cos
Func?ii trader


Vector Trigonometric Cos

trader_correl
trader_cosh
Func?ii trader
PHP Manual

trader_cos

(PECL trader >= 0.2.0)

trader_cos — Vector Trigonometric Cos

Descrierea

array trader_cos ( array $real )

Calculates the cosine for each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_correl
trader_cosh
Func?ii trader


Vector Trigonometric Cosh

trader_cos
trader_dema
Func?ii trader
PHP Manual

trader_cosh

(PECL trader >= 0.2.0)

trader_cosh — Vector Trigonometric Cosh

Descrierea

array trader_cosh ( array $real )

Calculates the hyperbolic cosine for each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cos
trader_dema
Func?ii trader


Double Exponential Moving Average

trader_cosh
trader_div
Func?ii trader
PHP Manual

trader_dema

(PECL trader >= 0.2.0)

trader_dema — Double Exponential Moving Average

Descrierea

array trader_dema ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_cosh
trader_div
Func?ii trader


Vector Arithmetic Div

trader_dema
trader_dx
Func?ii trader
PHP Manual

trader_div

(PECL trader >= 0.2.0)

trader_div — Vector Arithmetic Div

Descrierea

array trader_div ( array $real0 , array $real1 )

Divides each value from real0 by the corresponding value from real1 and returns the resulting array.

Parametri

real0

Un tablou cu valori reale.

real1

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_dema
trader_dx
Func?ii trader


Directional Movement Index

trader_div
trader_ema
Func?ii trader
PHP Manual

trader_dx

(PECL trader >= 0.2.0)

trader_dx — Directional Movement Index

Descrierea

array trader_dx ( array $high , array $low , array $close [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_div
trader_ema
Func?ii trader


Exponential Moving Average

trader_dx
trader_errno
Func?ii trader
PHP Manual

trader_ema

(PECL trader >= 0.2.0)

trader_ema — Exponential Moving Average

Descrierea

array trader_ema ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_dx
trader_errno
Func?ii trader


Get error code

trader_ema
trader_exp
Func?ii trader
PHP Manual

trader_errno

(PECL trader >= 0.3.0)

trader_errno — Get error code

Descrierea

integer trader_errno ( void )

Get error code of the last operation.

Valorile întoarse

Returns the error code identified by one of the TRADER_ERR_* constants.

trader_ema
trader_exp
Func?ii trader


Vector Arithmetic Exp

trader_errno
trader_floor
Func?ii trader
PHP Manual

trader_exp

(PECL trader >= 0.2.0)

trader_exp — Vector Arithmetic Exp

Descrierea

array trader_exp ( array $real )

Calculates e raised to the power of each value in real. Returns an array with the calculated data.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_errno
trader_floor
Func?ii trader


Vector Floor

trader_exp
trader_get_compat
Func?ii trader
PHP Manual

trader_floor

(PECL trader >= 0.2.0)

trader_floor — Vector Floor

Descrierea

array trader_floor ( array $real )

Calculates the next lowest integer for each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_exp
trader_get_compat
Func?ii trader


Get compatibility mode

trader_floor
trader_get_unstable_period
Func?ii trader
PHP Manual

trader_get_compat

(PECL trader >= 0.2.2)

trader_get_compat — Get compatibility mode

Descrierea

integer trader_get_compat ( void )

Get compatibility mode which affects the way calculations are done by all the extension functions.

Valorile întoarse

Returns the compatibility mode id which can be identified by TRADER_COMPATIBILITY_* series of constants.

trader_floor
trader_get_unstable_period
Func?ii trader


Get unstable period

trader_get_compat
trader_ht_dcperiod
Func?ii trader
PHP Manual

trader_get_unstable_period

(PECL trader >= 0.2.2)

trader_get_unstable_period — Get unstable period

Descrierea

integer trader_get_unstable_period ( integer $functionId )

Get unstable period factor for a particular function.

Parametri

functionId

Function ID the factor to be read for. TRADER_FUNC_UNST_* series of constants should be used.

Valorile întoarse

Returns the unstable period factor for the corresponding function.

trader_get_compat
trader_ht_dcperiod
Func?ii trader


Hilbert Transform - Dominant Cycle Period

trader_get_unstable_period
trader_ht_dcphase
Func?ii trader
PHP Manual

trader_ht_dcperiod

(PECL trader >= 0.2.0)

trader_ht_dcperiod — Hilbert Transform - Dominant Cycle Period

Descrierea

array trader_ht_dcperiod ( array $real )

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_get_unstable_period
trader_ht_dcphase
Func?ii trader


Hilbert Transform - Dominant Cycle Phase

trader_ht_dcperiod
trader_ht_phasor
Func?ii trader
PHP Manual

trader_ht_dcphase

(PECL trader >= 0.2.0)

trader_ht_dcphase — Hilbert Transform - Dominant Cycle Phase

Descrierea

array trader_ht_dcphase ( array $real )

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_ht_dcperiod
trader_ht_phasor
Func?ii trader


Hilbert Transform - Phasor Components

trader_ht_dcphase
trader_ht_sine
Func?ii trader
PHP Manual

trader_ht_phasor

(PECL trader >= 0.2.0)

trader_ht_phasor — Hilbert Transform - Phasor Components

Descrierea

array trader_ht_phasor ( array $real )

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_ht_dcphase
trader_ht_sine
Func?ii trader


Hilbert Transform - SineWave

trader_ht_phasor
trader_ht_trendline
Func?ii trader
PHP Manual

trader_ht_sine

(PECL trader >= 0.2.0)

trader_ht_sine — Hilbert Transform - SineWave

Descrierea

array trader_ht_sine ( array $real )

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_ht_phasor
trader_ht_trendline
Func?ii trader


Hilbert Transform - Instantaneous Trendline

trader_ht_sine
trader_ht_trendmode
Func?ii trader
PHP Manual

trader_ht_trendline

(PECL trader >= 0.2.0)

trader_ht_trendline — Hilbert Transform - Instantaneous Trendline

Descrierea

array trader_ht_trendline ( array $real )

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_ht_sine
trader_ht_trendmode
Func?ii trader


Hilbert Transform - Trend vs Cycle Mode

trader_ht_trendline
trader_kama
Func?ii trader
PHP Manual

trader_ht_trendmode

(PECL trader >= 0.2.0)

trader_ht_trendmode — Hilbert Transform - Trend vs Cycle Mode

Descrierea

array trader_ht_trendmode ( array $real )

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_ht_trendline
trader_kama
Func?ii trader


Kaufman Adaptive Moving Average

trader_ht_trendmode
trader_linearreg_angle
Func?ii trader
PHP Manual

trader_kama

(PECL trader >= 0.2.0)

trader_kama — Kaufman Adaptive Moving Average

Descrierea

array trader_kama ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_ht_trendmode
trader_linearreg_angle
Func?ii trader


Linear Regression Angle

trader_kama
trader_linearreg_intercept
Func?ii trader
PHP Manual

trader_linearreg_angle

(PECL trader >= 0.2.0)

trader_linearreg_angle — Linear Regression Angle

Descrierea

array trader_linearreg_angle ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_kama
trader_linearreg_intercept
Func?ii trader


Linear Regression Intercept

trader_linearreg_angle
trader_linearreg_slope
Func?ii trader
PHP Manual

trader_linearreg_intercept

(PECL trader >= 0.2.0)

trader_linearreg_intercept — Linear Regression Intercept

Descrierea

array trader_linearreg_intercept ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_linearreg_angle
trader_linearreg_slope
Func?ii trader


Linear Regression Slope

trader_linearreg_intercept
trader_linearreg
Func?ii trader
PHP Manual

trader_linearreg_slope

(PECL trader >= 0.2.0)

trader_linearreg_slope — Linear Regression Slope

Descrierea

array trader_linearreg_slope ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_linearreg_intercept
trader_linearreg
Func?ii trader


Linear Regression

trader_linearreg_slope
trader_ln
Func?ii trader
PHP Manual

trader_linearreg

(PECL trader >= 0.2.0)

trader_linearreg — Linear Regression

Descrierea

array trader_linearreg ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_linearreg_slope
trader_ln
Func?ii trader


Vector Log Natural

trader_linearreg
trader_log10
Func?ii trader
PHP Manual

trader_ln

(PECL trader >= 0.2.0)

trader_ln — Vector Log Natural

Descrierea

array trader_ln ( array $real )

Calculates the natural logarithm for each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_linearreg
trader_log10
Func?ii trader


Vector Log10

trader_ln
trader_ma
Func?ii trader
PHP Manual

trader_log10

(PECL trader >= 0.2.0)

trader_log10 — Vector Log10

Descrierea

array trader_log10 ( array $real )

Calculates the base-10 logarithm for each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_ln
trader_ma
Func?ii trader


Moving average

trader_log10
trader_macd
Func?ii trader
PHP Manual

trader_ma

(PECL trader >= 0.2.0)

trader_ma — Moving average

Descrierea

array trader_ma ( array $real [, integer $timePeriod [, integer $mAType ]] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

mAType

Tipul Mediei Mobile. Trebuie utilizate constantele din seria TRADER_MA_TYPE_*.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_log10
trader_macd
Func?ii trader


Moving Average Convergence/Divergence

trader_ma
trader_macdext
Func?ii trader
PHP Manual

trader_macd

(PECL trader >= 0.2.0)

trader_macd — Moving Average Convergence/Divergence

Descrierea

array trader_macd ( array $real [, integer $fastPeriod [, integer $slowPeriod [, integer $signalPeriod ]]] )

Parametri

real

Un tablou cu valori reale.

fastPeriod

Numarul perioadei pentru MA rapida. Domeniul valorilor admisibile este de la 2 pâna la 100000.

slowPeriod

Numarul perioadei pentru MA lenta. Domeniul valorilor admisibile este de la 2 pâna la 100000.

signalPeriod

Netezirea pentru linia de semnalizare (nb al perioadei). Domeniul valorilor admisibile este de la 1 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_ma
trader_macdext
Func?ii trader


MACD with controllable MA type

trader_macd
trader_macdfix
Func?ii trader
PHP Manual

trader_macdext

(PECL trader >= 0.2.0)

trader_macdext — MACD with controllable MA type

Descrierea

array trader_macdext ( array $real [, integer $fastPeriod [, integer $fastMAType [, integer $slowPeriod [, integer $slowMAType [, integer $signalPeriod [, integer $signalMAType ]]]]]] )

Parametri

real

Un tablou cu valori reale.

fastPeriod

Numarul perioadei pentru MA rapida. Domeniul valorilor admisibile este de la 2 pâna la 100000.

fastMAType

Tipul Mediei Mobile pentru MA rapida. Trebuie utilizate constantele din seria TRADER_MA_TYPE_*.

slowPeriod

Numarul perioadei pentru MA lenta. Domeniul valorilor admisibile este de la 2 pâna la 100000.

slowMAType

Tipul Mediei Mobile pentru MA lenta. Trebuie utilizate constantele din seria TRADER_MA_TYPE_*.

signalPeriod

Netezirea pentru linia de semnalizare (nb al perioadei). Domeniul valorilor admisibile este de la 1 pâna la 100000.

signalMAType

Tipul Mediei Mobile pentru linia de semnalizare. Trebuie utilizate constantele din seria TRADER_MA_TYPE_*.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_macd
trader_macdfix
Func?ii trader


Moving Average Convergence/Divergence Fix 12/26

trader_macdext
trader_mama
Func?ii trader
PHP Manual

trader_macdfix

(PECL trader >= 0.2.0)

trader_macdfix — Moving Average Convergence/Divergence Fix 12/26

Descrierea

array trader_macdfix ( array $real [, integer $signalPeriod ] )

Parametri

real

Un tablou cu valori reale.

signalPeriod

Netezirea pentru linia de semnalizare (nb al perioadei). Domeniul valorilor admisibile este de la 1 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_macdext
trader_mama
Func?ii trader


MESA Adaptive Moving Average

trader_macdfix
trader_mavp
Func?ii trader
PHP Manual

trader_mama

(PECL trader >= 0.2.0)

trader_mama — MESA Adaptive Moving Average

Descrierea

array trader_mama ( array $real [, float $fastLimit [, float $slowLimit ]] )

Parametri

real

Un tablou cu valori reale.

fastLimit

Limita superioara în algoritmul adaptiv. Domeniul valorilor admisibile este de la 0.01 pâna la 0.99.

slowLimit

Limita inferioara în algoritmul adaptiv. Domeniul valorilor admisibile este de la 0.01 pâna la 0.99.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_macdfix
trader_mavp
Func?ii trader


Moving average with variable period

trader_mama
trader_max
Func?ii trader
PHP Manual

trader_mavp

(PECL trader >= 0.2.0)

trader_mavp — Moving average with variable period

Descrierea

array trader_mavp ( array $real , array $periods [, integer $minPeriod [, integer $maxPeriod [, integer $mAType ]]] )

Parametri

real

Un tablou cu valori reale.

periods

Un tablou cu valori reale.

minPeriod

Valoarea mai mica decât minimul va fi schimbata în perioada Minima. Domeniul valorilor admisibile este de la 2 pâna la 100000.

maxPeriod

Valoarea mai mare decât minimul va fi schimbata în perioada Maxima. Domeniul valorilor admisibile este de la 2 pâna la 100000.

mAType

Tipul Mediei Mobile. Trebuie utilizate constantele din seria TRADER_MA_TYPE_*.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_mama
trader_max
Func?ii trader


Highest value over a specified period

trader_mavp
trader_maxindex
Func?ii trader
PHP Manual

trader_max

(PECL trader >= 0.2.0)

trader_max — Highest value over a specified period

Descrierea

array trader_max ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_mavp
trader_maxindex
Func?ii trader


Index of highest value over a specified period

trader_max
trader_medprice
Func?ii trader
PHP Manual

trader_maxindex

(PECL trader >= 0.2.0)

trader_maxindex — Index of highest value over a specified period

Descrierea

array trader_maxindex ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_max
trader_medprice
Func?ii trader


Median Price

trader_maxindex
trader_mfi
Func?ii trader
PHP Manual

trader_medprice

(PECL trader >= 0.2.0)

trader_medprice — Median Price

Descrierea

array trader_medprice ( array $high , array $low )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_maxindex
trader_mfi
Func?ii trader


Money Flow Index

trader_medprice
trader_midpoint
Func?ii trader
PHP Manual

trader_mfi

(PECL trader >= 0.2.0)

trader_mfi — Money Flow Index

Descrierea

array trader_mfi ( array $high , array $low , array $close , array $volume [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

volume

Volumul tranzac?ionat, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_medprice
trader_midpoint
Func?ii trader


MidPoint over period

trader_mfi
trader_midprice
Func?ii trader
PHP Manual

trader_midpoint

(PECL trader >= 0.2.0)

trader_midpoint — MidPoint over period

Descrierea

array trader_midpoint ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_mfi
trader_midprice
Func?ii trader


Midpoint Price over period

trader_midpoint
trader_min
Func?ii trader
PHP Manual

trader_midprice

(PECL trader >= 0.2.0)

trader_midprice — Midpoint Price over period

Descrierea

array trader_midprice ( array $high , array $low [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_midpoint
trader_min
Func?ii trader


Lowest value over a specified period

trader_midprice
trader_minindex
Func?ii trader
PHP Manual

trader_min

(PECL trader >= 0.2.0)

trader_min — Lowest value over a specified period

Descrierea

array trader_min ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_midprice
trader_minindex
Func?ii trader


Index of lowest value over a specified period

trader_min
trader_minmax
Func?ii trader
PHP Manual

trader_minindex

(PECL trader >= 0.2.0)

trader_minindex — Index of lowest value over a specified period

Descrierea

array trader_minindex ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_min
trader_minmax
Func?ii trader


Lowest and highest values over a specified period

trader_minindex
trader_minmaxindex
Func?ii trader
PHP Manual

trader_minmax

(PECL trader >= 0.2.0)

trader_minmax — Lowest and highest values over a specified period

Descrierea

array trader_minmax ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_minindex
trader_minmaxindex
Func?ii trader


Indexes of lowest and highest values over a specified period

trader_minmax
trader_minus_di
Func?ii trader
PHP Manual

trader_minmaxindex

(PECL trader >= 0.2.0)

trader_minmaxindex — Indexes of lowest and highest values over a specified period

Descrierea

array trader_minmaxindex ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_minmax
trader_minus_di
Func?ii trader


Minus Directional Indicator

trader_minmaxindex
trader_minus_dm
Func?ii trader
PHP Manual

trader_minus_di

(PECL trader >= 0.2.0)

trader_minus_di — Minus Directional Indicator

Descrierea

array trader_minus_di ( array $high , array $low , array $close [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_minmaxindex
trader_minus_dm
Func?ii trader


Minus Directional Movement

trader_minus_di
trader_mom
Func?ii trader
PHP Manual

trader_minus_dm

(PECL trader >= 0.2.0)

trader_minus_dm — Minus Directional Movement

Descrierea

array trader_minus_dm ( array $high , array $low [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_minus_di
trader_mom
Func?ii trader


Momentum

trader_minus_dm
trader_mult
Func?ii trader
PHP Manual

trader_mom

(PECL trader >= 0.2.0)

trader_mom — Momentum

Descrierea

array trader_mom ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_minus_dm
trader_mult
Func?ii trader


Vector Arithmetic Mult

trader_mom
trader_natr
Func?ii trader
PHP Manual

trader_mult

(PECL trader >= 0.2.0)

trader_mult — Vector Arithmetic Mult

Descrierea

array trader_mult ( array $real0 , array $real1 )

Calculates the vector dot product of real0 with real1 and returns the resulting vector.

Parametri

real0

Un tablou cu valori reale.

real1

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_mom
trader_natr
Func?ii trader


Normalized Average True Range

trader_mult
trader_obv
Func?ii trader
PHP Manual

trader_natr

(PECL trader >= 0.2.0)

trader_natr — Normalized Average True Range

Descrierea

array trader_natr ( array $high , array $low , array $close [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_mult
trader_obv
Func?ii trader


On Balance Volume

trader_natr
trader_plus_di
Func?ii trader
PHP Manual

trader_obv

(PECL trader >= 0.2.0)

trader_obv — On Balance Volume

Descrierea

array trader_obv ( array $real , array $volume )

Parametri

real

Un tablou cu valori reale.

volume

Volumul tranzac?ionat, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_natr
trader_plus_di
Func?ii trader


Plus Directional Indicator

trader_obv
trader_plus_dm
Func?ii trader
PHP Manual

trader_plus_di

(PECL trader >= 0.2.0)

trader_plus_di — Plus Directional Indicator

Descrierea

array trader_plus_di ( array $high , array $low , array $close [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_obv
trader_plus_dm
Func?ii trader


Plus Directional Movement

trader_plus_di
trader_ppo
Func?ii trader
PHP Manual

trader_plus_dm

(PECL trader >= 0.2.0)

trader_plus_dm — Plus Directional Movement

Descrierea

array trader_plus_dm ( array $high , array $low [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_plus_di
trader_ppo
Func?ii trader


Percentage Price Oscillator

trader_plus_dm
trader_roc
Func?ii trader
PHP Manual

trader_ppo

(PECL trader >= 0.2.0)

trader_ppo — Percentage Price Oscillator

Descrierea

array trader_ppo ( array $real [, integer $fastPeriod [, integer $slowPeriod [, integer $mAType ]]] )

Parametri

real

Un tablou cu valori reale.

fastPeriod

Numarul perioadei pentru MA rapida. Domeniul valorilor admisibile este de la 2 pâna la 100000.

slowPeriod

Numarul perioadei pentru MA lenta. Domeniul valorilor admisibile este de la 2 pâna la 100000.

mAType

Tipul Mediei Mobile. Trebuie utilizate constantele din seria TRADER_MA_TYPE_*.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_plus_dm
trader_roc
Func?ii trader


Rate of change : ((price/prevPrice)-1)*100

trader_ppo
trader_rocp
Func?ii trader
PHP Manual

trader_roc

(PECL trader >= 0.2.0)

trader_roc — Rate of change : ((price/prevPrice)-1)*100

Descrierea

array trader_roc ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_ppo
trader_rocp
Func?ii trader


Rate of change Percentage: (price-prevPrice)/prevPrice

trader_roc
trader_rocr100
Func?ii trader
PHP Manual

trader_rocp

(PECL trader >= 0.2.0)

trader_rocp — Rate of change Percentage: (price-prevPrice)/prevPrice

Descrierea

array trader_rocp ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_roc
trader_rocr100
Func?ii trader


Rate of change ratio 100 scale: (price/prevPrice)*100

trader_rocp
trader_rocr
Func?ii trader
PHP Manual

trader_rocr100

(PECL trader >= 0.2.0)

trader_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100

Descrierea

array trader_rocr100 ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_rocp
trader_rocr
Func?ii trader


Rate of change ratio: (price/prevPrice)

trader_rocr100
trader_rsi
Func?ii trader
PHP Manual

trader_rocr

(PECL trader >= 0.2.0)

trader_rocr — Rate of change ratio: (price/prevPrice)

Descrierea

array trader_rocr ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_rocr100
trader_rsi
Func?ii trader


Relative Strength Index

trader_rocr
trader_sar
Func?ii trader
PHP Manual

trader_rsi

(PECL trader >= 0.2.0)

trader_rsi — Relative Strength Index

Descrierea

array trader_rsi ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_rocr
trader_sar
Func?ii trader


Parabolic SAR

trader_rsi
trader_sarext
Func?ii trader
PHP Manual

trader_sar

(PECL trader >= 0.2.0)

trader_sar — Parabolic SAR

Descrierea

array trader_sar ( array $high , array $low [, float $acceleration [, float $maximum ]] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

acceleration

Acceleration Factor used up to the Maximum value. Valid range from 0 to TRADER_REAL_MAX.

maximum

Acceleration Factor Maximum value. Valid range from 0 to TRADER_REAL_MAX.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_rsi
trader_sarext
Func?ii trader


Parabolic SAR - Extended

trader_sar
trader_set_compat
Func?ii trader
PHP Manual

trader_sarext

(PECL trader >= 0.2.0)

trader_sarext — Parabolic SAR - Extended

Descrierea

array trader_sarext ( array $high , array $low [, float $startValue [, float $offsetOnReverse [, float $accelerationInitLong [, float $accelerationLong [, float $accelerationMaxLong [, float $accelerationInitShort [, float $accelerationShort [, float $accelerationMaxShort ]]]]]]]] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

startValue

Start value and direction. 0 for Auto, >0 for Long, <0 for Short. Valid range from TRADER_REAL_MIN to TRADER_REAL_MAX.

offsetOnReverse

Percent offset added/removed to initial stop on short/long reversal. Valid range from 0 to TRADER_REAL_MAX.

accelerationInitLong

Acceleration Factor initial value for the Long direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationLong

Acceleration Factor for the Long direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationMaxLong

Acceleration Factor maximum value for the Long direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationInitShort

Acceleration Factor initial value for the Short direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationShort

Acceleration Factor for the Short direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationMaxShort

Acceleration Factor maximum value for the Short direction. Valid range from 0 to TRADER_REAL_MAX.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_sar
trader_set_compat
Func?ii trader


Set compatibility mode

trader_sarext
trader_set_unstable_period
Func?ii trader
PHP Manual

trader_set_compat

(PECL trader >= 0.2.2)

trader_set_compat — Set compatibility mode

Descrierea

void trader_set_compat ( integer $compatId )

Set compatibility mode which will affect the way calculations are done by all the extension functions.

Parametri

compatId

Compatibility Id. TRADER_COMPATIBILITY_* series of constants should be used.

Valorile întoarse

Nu este întoarsa nici o valoare.

trader_sarext
trader_set_unstable_period
Func?ii trader


Set unstable period

trader_set_compat
trader_sin
Func?ii trader
PHP Manual

trader_set_unstable_period

(PECL trader >= 0.2.2)

trader_set_unstable_period — Set unstable period

Descrierea

void trader_set_unstable_period ( integer $functionId , integer $timePeriod )

Influences unstable period factor for functions, which are sensible to it. More information about unstable periods can be found on the » TA-Lib API documentation page.

Parametri

functionId

Function ID the factor should be set for. TRADER_FUNC_UNST_* constant series can be used to affect the corresponding function.

timePeriod

Unstable period value.

Valorile întoarse

Nu este întoarsa nici o valoare.

trader_set_compat
trader_sin
Func?ii trader


Vector Trigonometric Sin

trader_set_unstable_period
trader_sinh
Func?ii trader
PHP Manual

trader_sin

(PECL trader >= 0.2.0)

trader_sin — Vector Trigonometric Sin

Descrierea

array trader_sin ( array $real )

Calculates the sine for each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_set_unstable_period
trader_sinh
Func?ii trader


Vector Trigonometric Sinh

trader_sin
trader_sma
Func?ii trader
PHP Manual

trader_sinh

(PECL trader >= 0.2.0)

trader_sinh — Vector Trigonometric Sinh

Descrierea

array trader_sinh ( array $real )

Calculates the hyperbolic sine for each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_sin
trader_sma
Func?ii trader


Simple Moving Average

trader_sinh
trader_sqrt
Func?ii trader
PHP Manual

trader_sma

(PECL trader >= 0.2.0)

trader_sma — Simple Moving Average

Descrierea

array trader_sma ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_sinh
trader_sqrt
Func?ii trader


Vector Square Root

trader_sma
trader_stddev
Func?ii trader
PHP Manual

trader_sqrt

(PECL trader >= 0.2.0)

trader_sqrt — Vector Square Root

Descrierea

array trader_sqrt ( array $real )

Calculates the square root of each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_sma
trader_stddev
Func?ii trader


Standard Deviation

trader_sqrt
trader_stoch
Func?ii trader
PHP Manual

trader_stddev

(PECL trader >= 0.2.0)

trader_stddev — Standard Deviation

Descrierea

array trader_stddev ( array $real [, integer $timePeriod [, float $nbDev ]] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

nbDev

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_sqrt
trader_stoch
Func?ii trader


Stochastic

trader_stddev
trader_stochf
Func?ii trader
PHP Manual

trader_stoch

(PECL trader >= 0.2.0)

trader_stoch — Stochastic

Descrierea

array trader_stoch ( array $high , array $low , array $close [, integer $fastK_Period [, integer $slowK_Period [, integer $slowK_MAType [, integer $slowD_Period [, integer $slowD_MAType ]]]]] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

fastK_Period

Perioada de timp pentru constituirea liniei Fast-K. Domeniul valorilor admisibile este de la 1 pâna la 100000.

slowK_Period

Netezirea pentru constituirea liniei Slow-K. Domeniul valorilor admisibile este de la 1 pâna la 100000, de obicei este stabilit la 3.

slowK_MAType

Tipul Mediei Mobile pentru Slow-K. Trebuie utilizate constantele din seria TRADER_MA_TYPE_*.

slowD_Period

Netezirea pentru constituirea liniei Slow-D. Domeniul valorilor admisibile este de la 1 pâna la 100000.

slowD_MAType

Tipul Mediei Mobile pentru Slow-D. Trebuie utilizate constantele din seria TRADER_MA_TYPE_*.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_stddev
trader_stochf
Func?ii trader


Stochastic Fast

trader_stoch
trader_stochrsi
Func?ii trader
PHP Manual

trader_stochf

(PECL trader >= 0.2.0)

trader_stochf — Stochastic Fast

Descrierea

array trader_stochf ( array $high , array $low , array $close [, integer $fastK_Period [, integer $fastD_Period [, integer $fastD_MAType ]]] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

fastK_Period

Perioada de timp pentru constituirea liniei Fast-K. Domeniul valorilor admisibile este de la 1 pâna la 100000.

fastD_Period

Netezirea pentru constituirea liniei Fast-D. Domeniul valorilor admisibile este de la 1 pâna la 100000, de obicei este stabilit la 3.

fastD_MAType

Tipul Mediei Mobile pentru Fast-D. Trebuie utilizate constantele din seria TRADER_MA_TYPE_*.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_stoch
trader_stochrsi
Func?ii trader


Stochastic Relative Strength Index

trader_stochf
trader_sub
Func?ii trader
PHP Manual

trader_stochrsi

(PECL trader >= 0.2.0)

trader_stochrsi — Stochastic Relative Strength Index

Descrierea

array trader_stochrsi ( array $real [, integer $timePeriod [, integer $fastK_Period [, integer $fastD_Period [, integer $fastD_MAType ]]]] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

fastK_Period

Perioada de timp pentru constituirea liniei Fast-K. Domeniul valorilor admisibile este de la 1 pâna la 100000.

fastD_Period

Netezirea pentru constituirea liniei Fast-D. Domeniul valorilor admisibile este de la 1 pâna la 100000, de obicei este stabilit la 3.

fastD_MAType

Tipul Mediei Mobile pentru Fast-D. Trebuie utilizate constantele din seria TRADER_MA_TYPE_*.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_stochf
trader_sub
Func?ii trader


Vector Arithmetic Subtraction

trader_stochrsi
trader_sum
Func?ii trader
PHP Manual

trader_sub

(PECL trader >= 0.2.0)

trader_sub — Vector Arithmetic Subtraction

Descrierea

array trader_sub ( array $real0 , array $real1 )

Calculates the vector subtraction of real1 from real0 and returns the resulting vector.

Parametri

real0

Un tablou cu valori reale.

real1

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_stochrsi
trader_sum
Func?ii trader


Summation

trader_sub
trader_t3
Func?ii trader
PHP Manual

trader_sum

(PECL trader >= 0.2.0)

trader_sum — Summation

Descrierea

array trader_sum ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_sub
trader_t3
Func?ii trader


Triple Exponential Moving Average (T3)

trader_sum
trader_tan
Func?ii trader
PHP Manual

trader_t3

(PECL trader >= 0.2.0)

trader_t3 — Triple Exponential Moving Average (T3)

Descrierea

array trader_t3 ( array $real [, integer $timePeriod [, float $vFactor ]] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

vFactor

Factorul de volum. Domeniul valorilor admisibile este de la 1 la 0.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_sum
trader_tan
Func?ii trader


Vector Trigonometric Tan

trader_t3
trader_tanh
Func?ii trader
PHP Manual

trader_tan

(PECL trader >= 0.2.0)

trader_tan — Vector Trigonometric Tan

Descrierea

array trader_tan ( array $real )

Calculates the tangent for each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_t3
trader_tanh
Func?ii trader


Vector Trigonometric Tanh

trader_tan
trader_tema
Func?ii trader
PHP Manual

trader_tanh

(PECL trader >= 0.2.0)

trader_tanh — Vector Trigonometric Tanh

Descrierea

array trader_tanh ( array $real )

Calculates the hyperbolic tangent for each value in real and returns the resulting array.

Parametri

real

Un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_tan
trader_tema
Func?ii trader


Triple Exponential Moving Average

trader_tanh
trader_trange
Func?ii trader
PHP Manual

trader_tema

(PECL trader >= 0.2.0)

trader_tema — Triple Exponential Moving Average

Descrierea

array trader_tema ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_tanh
trader_trange
Func?ii trader


True Range

trader_tema
trader_trima
Func?ii trader
PHP Manual

trader_trange

(PECL trader >= 0.2.0)

trader_trange — True Range

Descrierea

array trader_trange ( array $high , array $low , array $close )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_tema
trader_trima
Func?ii trader


Triangular Moving Average

trader_trange
trader_trix
Func?ii trader
PHP Manual

trader_trima

(PECL trader >= 0.2.0)

trader_trima — Triangular Moving Average

Descrierea

array trader_trima ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_trange
trader_trix
Func?ii trader


1-day Rate-Of-Change (ROC) of a Triple Smooth EMA

trader_trima
trader_tsf
Func?ii trader
PHP Manual

trader_trix

(PECL trader >= 0.2.0)

trader_trix — 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA

Descrierea

array trader_trix ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_trima
trader_tsf
Func?ii trader


Time Series Forecast

trader_trix
trader_typprice
Func?ii trader
PHP Manual

trader_tsf

(PECL trader >= 0.2.0)

trader_tsf — Time Series Forecast

Descrierea

array trader_tsf ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_trix
trader_typprice
Func?ii trader


Typical Price

trader_tsf
trader_ultosc
Func?ii trader
PHP Manual

trader_typprice

(PECL trader >= 0.2.0)

trader_typprice — Typical Price

Descrierea

array trader_typprice ( array $high , array $low , array $close )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_tsf
trader_ultosc
Func?ii trader


Ultimate Oscillator

trader_typprice
trader_var
Func?ii trader
PHP Manual

trader_ultosc

(PECL trader >= 0.2.0)

trader_ultosc — Ultimate Oscillator

Descrierea

array trader_ultosc ( array $high , array $low , array $close [, integer $timePeriod1 [, integer $timePeriod2 [, integer $timePeriod3 ]]] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

timePeriod1

Number of bars for 1st period. Valid range from 1 to 100000.

timePeriod2

Number of bars for 2nd period. Valid range from 1 to 100000.

timePeriod3

Number of bars for 3rd period. Valid range from 1 to 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_typprice
trader_var
Func?ii trader


Variance

trader_ultosc
trader_wclprice
Func?ii trader
PHP Manual

trader_var

(PECL trader >= 0.2.0)

trader_var — Variance

Descrierea

array trader_var ( array $real [, integer $timePeriod [, float $nbDev ]] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

nbDev

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_ultosc
trader_wclprice
Func?ii trader


Weighted Close Price

trader_var
trader_willr
Func?ii trader
PHP Manual

trader_wclprice

(PECL trader >= 0.2.0)

trader_wclprice — Weighted Close Price

Descrierea

array trader_wclprice ( array $high , array $low , array $close )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_var
trader_willr
Func?ii trader


Williams' %R

trader_wclprice
trader_wma
Func?ii trader
PHP Manual

trader_willr

(PECL trader >= 0.2.0)

trader_willr — Williams' %R

Descrierea

array trader_willr ( array $high , array $low , array $close [, integer $timePeriod ] )

Parametri

high

Pre?ul înalt, un tablou cu valori reale.

low

Pre?ul jos, un tablou cu valori reale.

close

Pre?ul de închidere, un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_wclprice
trader_wma
Func?ii trader


Weighted Moving Average

trader_willr
Ie?iri MIME non-textuale
Func?ii trader
PHP Manual

trader_wma

(PECL trader >= 0.2.0)

trader_wma — Weighted Moving Average

Descrierea

array trader_wma ( array $real [, integer $timePeriod ] )

Parametri

real

Un tablou cu valori reale.

timePeriod

Numarul perioadei. Domeniul valorilor admisibile este de la 2 pâna la 100000.

Valorile întoarse

Returns an array with calculated data or false on failure.

trader_willr
Ie?iri MIME non-textuale
Func?ii trader


Ie?iri MIME non-textuale

  • FDF — Forms Data Format
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii FDF
  • GnuPG — GNU Privacy Guard
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • GnuPG Func?ii
  • haru — Haru PDF
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • 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)
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Ming
    • 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
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • PDF Func?ii
  • PS — PostScript document creation
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii PS
  • RPM Reader — RPM Header Reading
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii ale cititorului RPM
trader_wma
FDF
Informa?ii de referin?a despre func?ii


Forms Data Format

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii FDF
    • 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
Ie?iri MIME non-textuale
Introducere
Ie?iri MIME non-textuale


Introducere

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
Instalarea / configurarea
FDF


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
FDF


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie este considerata ne-între?inuta ?i moarta. Oricum însa codul-sursa al acestei extensii este înca disponibil în PECL SVN aici: » http://svn.php.net/viewvc/pecl/fdf.

This extension is no longer bundled with PHP as of PHP 5.3.0.

Nota: 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 .

Nota: Note to Win32 Users

Pentru ca aceasta extensie sa func?ioneze, anumite fi?iere DLL trebuie sa fie accesibile în calea de sistem a Windows din variabila PATH. Pentru informa?ii despre cum poate fi realizat acest lucru, accesa?i FAQ întitulat " Cum sa adaug directorul meu PHP la variabila PATH din Windows" pentru informa?ii despre cum sa realiza?i aceasta. Cu toate ca copierea fi?ierelor DLL din directorul PHP în directorul de sistem al Windows de asemenea func?ioneaza (deoarece directorul de sistem este în mod implicit inclus în variabila PATH), acest lucru nu este recomandabil. Aceasta extensie necesita ca urmatoarele fi?iere sa existe în calea PATH : fdftk.dll

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

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().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
Tipurile resurselor
Exemple
FDF


Exemple

The following examples shows just the evaluation of form data.

Example #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);
?>

Constante predefinite
Func?ii FDF
FDF


Func?ii FDF

Cuprins

  • 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
Exemple
fdf_add_doc_javascript
FDF


Adds javascript code to the FDF document

Func?ii FDF
fdf_add_template
Func?ii FDF
PHP Manual

fdf_add_doc_javascript

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_add_doc_javascript — Adds javascript code to the FDF document

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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

Func?ii FDF
fdf_add_template
Func?ii FDF


Adds a template into the FDF document

fdf_add_doc_javascript
fdf_close
Func?ii FDF
PHP Manual

fdf_add_template

(PHP 4, PHP 5, PHP 7)

fdf_add_template — Adds a template into the FDF document

Descrierea

bool fdf_add_template ( resource $fdf_document , int $newpage , string $filename , string $template , int $rename )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

fdf_add_doc_javascript
fdf_close
Func?ii FDF


Close an FDF document

fdf_add_template
fdf_create
Func?ii FDF
PHP Manual

fdf_close

(PHP 4, PHP 5, PHP 7)

fdf_close — Close an FDF document

Descrierea

void fdf_close ( resource $fdf_document )

Closes the FDF document.

Parametri

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • fdf_open() - Open a FDF document

fdf_add_template
fdf_create
Func?ii FDF


Create a new FDF document

fdf_close
fdf_enum_values
Func?ii FDF
PHP Manual

fdf_create

(PHP 4, PHP 5, PHP 7)

fdf_create — Create a new FDF document

Descrierea

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.

Valorile întoarse

Returns a FDF document handle, or FALSE on error.

Exemple

Example #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");
?>

A se vedea ?i

  • fdf_close() - Close an FDF document
  • fdf_save() - Save a FDF document
  • fdf_open() - Open a FDF document

fdf_close
fdf_enum_values
Func?ii FDF


Call a user defined function for each document value

fdf_create
fdf_errno
Func?ii FDF
PHP Manual

fdf_enum_values

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_enum_values — Call a user defined function for each document value

Descrierea

bool fdf_enum_values ( resource $fdf_document , callable $function [, mixed $userdata ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

fdf_create
fdf_errno
Func?ii FDF


Return error code for last fdf operation

fdf_enum_values
fdf_error
Func?ii FDF
PHP Manual

fdf_errno

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_errno — Return error code for last fdf operation

Descrierea

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().

Valorile întoarse

Returns the error code as an integer, or zero if there was no errors.

A se vedea ?i

  • fdf_error() - Return error description for FDF error code

fdf_enum_values
fdf_error
Func?ii FDF


Return error description for FDF error code

fdf_errno
fdf_get_ap
Func?ii FDF
PHP Manual

fdf_error

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_error — Return error description for FDF error code

Descrierea

string fdf_error ([ int $error_code = -1 ] )

Gets a textual description for the FDF error code given in error_code.

Parametri

error_code

An error code obtained with fdf_errno(). If not provided, this function uses the internal error code set by the last operation.

Valorile întoarse

Returns the error message as a string, or the string no error if nothing went wrong.

A se vedea ?i

  • fdf_errno() - Return error code for last fdf operation

fdf_errno
fdf_get_ap
Func?ii FDF


Get the appearance of a field

fdf_error
fdf_get_attachment
Func?ii FDF
PHP Manual

fdf_get_ap

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_get_ap — Get the appearance of a field

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

fdf_error
fdf_get_attachment
Func?ii FDF


Extracts uploaded file embedded in the FDF

fdf_get_ap
fdf_get_encoding
Func?ii FDF
PHP Manual

fdf_get_attachment

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_get_attachment — Extracts uploaded file embedded in the FDF

Descrierea

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.

Parametri

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.

Nota:

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.

Valorile întoarse

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

Exemple

Example #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
Func?ii FDF


Get the value of the /Encoding key

fdf_get_attachment
fdf_get_file
Func?ii FDF
PHP Manual

fdf_get_encoding

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_get_encoding — Get the value of the /Encoding key

Descrierea

string fdf_get_encoding ( resource $fdf_document )

Gets the value of the /Encoding key.

Parametri

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Valorile întoarse

Returns the encoding as a string. An empty string is returned if the default PDFDocEncoding/Unicode scheme is used.

A se vedea ?i

  • fdf_set_encoding() - Sets FDF character encoding

fdf_get_attachment
fdf_get_file
Func?ii FDF


Get the value of the /F key

fdf_get_encoding
fdf_get_flags
Func?ii FDF
PHP Manual

fdf_get_file

(PHP 4, PHP 5, PHP 7)

fdf_get_file — Get the value of the /F key

Descrierea

string fdf_get_file ( resource $fdf_document )

Gets the value of the /F key.

Parametri

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Valorile întoarse

Returns the key value, as a string.

A se vedea ?i

  • fdf_set_file() - Set PDF document to display FDF data in

fdf_get_encoding
fdf_get_flags
Func?ii FDF


Gets the flags of a field

fdf_get_file
fdf_get_opt
Func?ii FDF
PHP Manual

fdf_get_flags

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_get_flags — Gets the flags of a field

Descrierea

int fdf_get_flags ( resource $fdf_document , string $fieldname , int $whichflags )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

fdf_get_file
fdf_get_opt
Func?ii FDF


Gets a value from the opt array of a field

fdf_get_flags
fdf_get_status
Func?ii FDF
PHP Manual

fdf_get_opt

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_get_opt — Gets a value from the opt array of a field

Descrierea

mixed fdf_get_opt ( resource $fdf_document , string $fieldname [, int $element = -1 ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

fdf_get_flags
fdf_get_status
Func?ii FDF


Get the value of the /STATUS key

fdf_get_opt
fdf_get_value
Func?ii FDF
PHP Manual

fdf_get_status

(PHP 4, PHP 5, PHP 7)

fdf_get_status — Get the value of the /STATUS key

Descrierea

string fdf_get_status ( resource $fdf_document )

Gets the value of the /STATUS key.

Parametri

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Valorile întoarse

Returns the key value, as a string.

A se vedea ?i

  • fdf_set_status() - Set the value of the /STATUS key

fdf_get_opt
fdf_get_value
Func?ii FDF


Get the value of a field

fdf_get_status
fdf_get_version
Func?ii FDF
PHP Manual

fdf_get_value

(PHP 4, PHP 5, PHP 7)

fdf_get_value — Get the value of a field

Descrierea

mixed fdf_get_value ( resource $fdf_document , string $fieldname [, int $which = -1 ] )

Gets the value for the requested field.

Parametri

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.

Valorile întoarse

Returns the field value.

Istoricul schimbarilor

Versiune | Descriere
4.3.0 | Support for arrays and the which parameter were added.

A se vedea ?i

  • fdf_set_value() - Set the value of a field

fdf_get_status
fdf_get_version
Func?ii FDF


Gets version number for FDF API or file

fdf_get_value
fdf_header
Func?ii FDF
PHP Manual

fdf_get_version

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_get_version — Gets version number for FDF API or file

Descrierea

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.

Parametri

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Valorile întoarse

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.

A se vedea ?i

  • fdf_set_version() - Sets version number for a FDF file

fdf_get_value
fdf_header
Func?ii FDF


Sets FDF-specific output headers

fdf_get_version
fdf_next_field_name
Func?ii FDF
PHP Manual

fdf_header

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_header — Sets FDF-specific output headers

Descrierea

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

fdf_get_version
fdf_next_field_name
Func?ii FDF


Get the next field name

fdf_header
fdf_open_string
Func?ii FDF
PHP Manual

fdf_next_field_name

(PHP 4, PHP 5, PHP 7)

fdf_next_field_name — Get the next field name

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the field name as a string.

Exemple

Example #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";
}
?>

A se vedea ?i

  • fdf_get_value() - Get the value of a field

fdf_header
fdf_open_string
Func?ii FDF


Read a FDF document from a string

fdf_next_field_name
fdf_open
Func?ii FDF
PHP Manual

fdf_open_string

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_open_string — Read a FDF document from a string

Descrierea

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.

Parametri

fdf_data

The data as returned from a PDF form or created using fdf_create() and fdf_save_string().

Valorile întoarse

Returns a FDF document handle, or FALSE on error.

Exemple

Example #1 Accessing the form data

<?php
$fdf = fdf_open_string($HTTP_FDF_DATA);
/* ... */
fdf_close($fdf);
?>

A se vedea ?i

  • 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
Func?ii FDF


Open a FDF document

fdf_open_string
fdf_remove_item
Func?ii FDF
PHP Manual

fdf_open

(PHP 4, PHP 5, PHP 7)

fdf_open — Open a FDF document

Descrierea

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.

Parametri

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().

Valorile întoarse

Returns a FDF document handle, or FALSE on error.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii FDF


Sets target frame for form

fdf_open
fdf_save_string
Func?ii FDF
PHP Manual

fdf_remove_item

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_remove_item — Sets target frame for form

Descrierea

bool fdf_remove_item ( resource $fdf_document , string $fieldname , int $item )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

fdf_open
fdf_save_string
Func?ii FDF


Returns the FDF document as a string

fdf_remove_item
fdf_save
Func?ii FDF
PHP Manual

fdf_save_string

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_save_string — Returns the FDF document as a string

Descrierea

string fdf_save_string ( resource $fdf_document )

Returns the FDF document as a string.

Parametri

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Valorile întoarse

Returns the document as a string, or FALSE on error.

Exemple

Example #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;
?>

Exemplul de mai sus va afi?a:

%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

A se vedea ?i

  • 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
Func?ii FDF


Save a FDF document

fdf_save_string
fdf_set_ap
Func?ii FDF
PHP Manual

fdf_save

(PHP 4, PHP 5, PHP 7)

fdf_save — Save a FDF document

Descrierea

bool fdf_save ( resource $fdf_document [, string $filename ] )

Saves a FDF document.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii FDF


Set the appearance of a field

fdf_save
fdf_set_encoding
Func?ii FDF
PHP Manual

fdf_set_ap

(PHP 4, PHP 5, PHP 7)

fdf_set_ap — Set the appearance of a field

Descrierea

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).

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

fdf_save
fdf_set_encoding
Func?ii FDF


Sets FDF character encoding

fdf_set_ap
fdf_set_file
Func?ii FDF
PHP Manual

fdf_set_encoding

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

fdf_set_encoding — Sets FDF character encoding

Descrierea

bool fdf_set_encoding ( resource $fdf_document , string $encoding )

Sets the character encoding for the FDF document.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

fdf_set_ap
fdf_set_file
Func?ii FDF


Set PDF document to display FDF data in

fdf_set_encoding
fdf_set_flags
Func?ii FDF
PHP Manual

fdf_set_file

(PHP 4, PHP 5, PHP 7)

fdf_set_file — Set PDF document to display FDF data in

Descrierea

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.

Parametri

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().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii FDF


Sets a flag of a field

fdf_set_file
fdf_set_javascript_action
Func?ii FDF
PHP Manual

fdf_set_flags

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

fdf_set_flags — Sets a flag of a field

Descrierea

bool fdf_set_flags ( resource $fdf_document , string $fieldname , int $whichFlags , int $newFlags )

Sets certain flags of the given field.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fdf_set_opt() - Sets an option of a field

fdf_set_file
fdf_set_javascript_action
Func?ii FDF


Sets an javascript action of a field

fdf_set_flags
fdf_set_on_import_javascript
Func?ii FDF
PHP Manual

fdf_set_javascript_action

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

fdf_set_javascript_action — Sets an javascript action of a field

Descrierea

bool fdf_set_javascript_action ( resource $fdf_document , string $fieldname , int $trigger , string $script )

Sets a javascript action for the given field.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fdf_set_submit_form_action() - Sets a submit form action of a field

fdf_set_flags
fdf_set_on_import_javascript
Func?ii FDF


Adds javascript code to be executed when Acrobat opens the FDF

fdf_set_javascript_action
fdf_set_opt
Func?ii FDF
PHP Manual

fdf_set_on_import_javascript

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF

Descrierea

bool fdf_set_on_import_javascript ( resource $fdf_document , string $script , bool $before_data_import )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • 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
Func?ii FDF


Sets an option of a field

fdf_set_on_import_javascript
fdf_set_status
Func?ii FDF
PHP Manual

fdf_set_opt

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

fdf_set_opt — Sets an option of a field

Descrierea

bool fdf_set_opt ( resource $fdf_document , string $fieldname , int $element , string $str1 , string $str2 )

Sets options of the given field.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fdf_set_flags() - Sets a flag of a field

fdf_set_on_import_javascript
fdf_set_status
Func?ii FDF


Set the value of the /STATUS key

fdf_set_opt
fdf_set_submit_form_action
Func?ii FDF
PHP Manual

fdf_set_status

(PHP 4, PHP 5, PHP 7)

fdf_set_status — Set the value of the /STATUS key

Descrierea

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.

Parametri

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

status

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fdf_get_status() - Get the value of the /STATUS key

fdf_set_opt
fdf_set_submit_form_action
Func?ii FDF


Sets a submit form action of a field

fdf_set_status
fdf_set_target_frame
Func?ii FDF
PHP Manual

fdf_set_submit_form_action

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

fdf_set_submit_form_action — Sets a submit form action of a field

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fdf_set_javascript_action() - Sets an javascript action of a field

fdf_set_status
fdf_set_target_frame
Func?ii FDF


Set target frame for form display

fdf_set_submit_form_action
fdf_set_value
Func?ii FDF
PHP Manual

fdf_set_target_frame

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_set_target_frame — Set target frame for form display

Descrierea

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.

Parametri

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

frame_name

The frame name, as a string.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fdf_save_file()

fdf_set_submit_form_action
fdf_set_value
Func?ii FDF


Set the value of a field

fdf_set_target_frame
fdf_set_version
Func?ii FDF
PHP Manual

fdf_set_value

(PHP 4, PHP 5, PHP 7)

fdf_set_value — Set the value of a field

Descrierea

bool fdf_set_value ( resource $fdf_document , string $fieldname , mixed $value [, int $isName ] )

Sets the value for the given field.

Parametri

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

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
4.3.0 | Support for arrays in the value parameter was added.

A se vedea ?i

  • fdf_get_value() - Get the value of a field
  • fdf_remove_item() - Sets target frame for form

fdf_set_target_frame
fdf_set_version
Func?ii FDF


Sets version number for a FDF file

fdf_set_value
GnuPG
Func?ii FDF
PHP Manual

fdf_set_version

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_set_version — Sets version number for a FDF file

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fdf_get_version() - Gets version number for FDF API or file

fdf_set_value
GnuPG
Func?ii FDF


GNU Privacy Guard

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Clearsign text
  • GnuPG Func?ii
    • 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
Introducere
Ie?iri MIME non-textuale


Introducere

This module allows you to interact with » gnupg.

GnuPG
Instalarea / configurarea
GnuPG


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
GnuPG


Necesita?i

This extension requires the » gpgme library

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/gnupg.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

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)
Tipurile resurselor
Exemple
GnuPG


Exemple

Cuprins

  • Clearsign text
Constante predefinite
Clearsign text
GnuPG


Clearsign text

This example will clearsign a given text.

Example #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;
?>

Example #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;
?>

Example #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";
}
?>
Exemple
GnuPG Func?ii
Exemple


GnuPG Func?ii

Note

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.

Nota:

As alternative to the explicitly documented functions using resources, you can also use an object-oriented style using gnupg objects.

Cuprins

  • 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 Func?ii
gnupg_addencryptkey
GnuPG Func?ii
PHP Manual

gnupg_adddecryptkey

(PECL gnupg >= 0.5)

gnupg_adddecryptkey — Add a key for decryption

Descrierea

bool gnupg_adddecryptkey ( resource $identifier , string $fingerprint , string $passphrase )

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

fingerprint

Cheia amprentei.

passphrase

The pass phrase.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Procedural gnupg_adddecryptkey() example

<?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

Example #2 OO gnupg_adddecryptkey() example

<?php
$gpg = new gnupg();
$gpg -> adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

GnuPG Func?ii
gnupg_addencryptkey
GnuPG Func?ii


Add a key for encryption

gnupg_adddecryptkey
gnupg_addsignkey
GnuPG Func?ii
PHP Manual

gnupg_addencryptkey

(PECL gnupg >= 0.5)

gnupg_addencryptkey — Add a key for encryption

Descrierea

bool gnupg_addencryptkey ( resource $identifier , string $fingerprint )

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

fingerprint

Cheia amprentei.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Procedural gnupg_addencryptkey() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
?>

Example #2 OO gnupg_addencryptkey() example

<?php
$gpg = new gnupg();
$gpg -> addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
?>

gnupg_adddecryptkey
gnupg_addsignkey
GnuPG Func?ii


Add a key for signing

gnupg_addencryptkey
gnupg_cleardecryptkeys
GnuPG Func?ii
PHP Manual

gnupg_addsignkey

(PECL gnupg >= 0.5)

gnupg_addsignkey — Add a key for signing

Descrierea

bool gnupg_addsignkey ( resource $identifier , string $fingerprint [, string $passphrase ] )

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

fingerprint

Cheia amprentei.

passphrase

The pass phrase.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Procedural gnupg_addsignkey() example

<?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

Example #2 OO gnupg_addsignkey() example

<?php
$gpg = new gnupg();
$gpg -> addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

gnupg_addencryptkey
gnupg_cleardecryptkeys
GnuPG Func?ii


Removes all keys which were set for decryption before

gnupg_addsignkey
gnupg_clearencryptkeys
GnuPG Func?ii
PHP Manual

gnupg_cleardecryptkeys

(PECL gnupg >= 0.5)

gnupg_cleardecryptkeys — Removes all keys which were set for decryption before

Descrierea

bool gnupg_cleardecryptkeys ( resource $identifier )

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Procedural gnupg_cleardecryptkeys() example

<?php
$res = gnupg_init();
gnupg_cleardecryptkeys($res);
?>

Example #2 OO gnupg_cleardecryptkeys() example

<?php
$gpg = new gnupg();
$gpg -> cleardecryptkeys();
?>

gnupg_addsignkey
gnupg_clearencryptkeys
GnuPG Func?ii


Removes all keys which were set for encryption before

gnupg_cleardecryptkeys
gnupg_clearsignkeys
GnuPG Func?ii
PHP Manual

gnupg_clearencryptkeys

(PECL gnupg >= 0.5)

gnupg_clearencryptkeys — Removes all keys which were set for encryption before

Descrierea

bool gnupg_clearencryptkeys ( resource $identifier )

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Procedural gnupg_clearencryptkeys() example

<?php
$res = gnupg_init();
gnupg_clearencryptkeys($res);
?>

Example #2 OO gnupg_clearencryptkeys() example

<?php
$gpg = new gnupg();
$gpg -> clearencryptkeys();
?>

gnupg_cleardecryptkeys
gnupg_clearsignkeys
GnuPG Func?ii


Removes all keys which were set for signing before

gnupg_clearencryptkeys
gnupg_decrypt
GnuPG Func?ii
PHP Manual

gnupg_clearsignkeys

(PECL gnupg >= 0.5)

gnupg_clearsignkeys — Removes all keys which were set for signing before

Descrierea

bool gnupg_clearsignkeys ( resource $identifier )

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Procedural gnupg_clearsignkeys() example

<?php
$res = gnupg_init();
gnupg_clearsignkeys($res);
?>

Example #2 OO gnupg_clearsignkeys() example

<?php
$gpg = new gnupg();
$gpg -> clearsignkeys();
?>

gnupg_clearencryptkeys
gnupg_decrypt
GnuPG Func?ii


Decrypts a given text

gnupg_clearsignkeys
gnupg_decryptverify
GnuPG Func?ii
PHP Manual

gnupg_decrypt

(PECL gnupg >= 0.1)

gnupg_decrypt — Decrypts a given text

Descrierea

string gnupg_decrypt ( resource $identifier , string $text )

Decrypts the given text with the keys, which were set with gnupg_adddecryptkey before.

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

text

The text being decrypted.

Valorile întoarse

On success, this function returns the decrypted text. On failure, this function returns FALSE.

Exemple

Example #1 Procedural gnupg_decrypt() example

<?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = gnupg_decrypt($res,$encrypted_text);
echo $plain;
?>

Example #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 Func?ii


Decrypts and verifies a given text

gnupg_decrypt
gnupg_encrypt
GnuPG Func?ii
PHP Manual

gnupg_decryptverify

(PECL gnupg >= 0.2)

gnupg_decryptverify — Decrypts and verifies a given text

Descrierea

array gnupg_decryptverify ( resource $identifier , string $text , string &$plaintext )

Decrypts and verifies a given text and returns information about the signature.

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

text

The text being decrypted.

plaintext

The parameter plaintext gets filled with the decrypted text.

Valorile întoarse

On success, this function returns information about the signature and fills the plaintext parameter with the decrypted text. On failure, this function returns FALSE.

Exemple

Example #1 Procedural gnupg_decryptverify() example

<?php
$plaintext = "";
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$info = gnupg_decryptverify($res,$text,$plaintext);
print_r($info);
?>

Example #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 Func?ii


Encrypts a given text

gnupg_decryptverify
gnupg_encryptsign
GnuPG Func?ii
PHP Manual

gnupg_encrypt

(PECL gnupg >= 0.1)

gnupg_encrypt — Encrypts a given text

Descrierea

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.

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

plaintext

The text being encrypted.

Valorile întoarse

On success, this function returns the encrypted text. On failure, this function returns FALSE.

Exemple

Example #1 Procedural gnupg_encrypt() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
$enc = gnupg_encrypt($res, "just a test");
echo $enc;
?>

Example #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 Func?ii


Encrypts and signs a given text

gnupg_encrypt
gnupg_export
GnuPG Func?ii
PHP Manual

gnupg_encryptsign

(PECL gnupg >= 0.2)

gnupg_encryptsign — Encrypts and signs a given text

Descrierea

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.

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

plaintext

The text being encrypted.

Valorile întoarse

On success, this function returns the encrypted and signed text. On failure, this function returns FALSE.

Exemple

Example #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;
?>

Example #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 Func?ii


Exports a key

gnupg_encryptsign
gnupg_geterror
GnuPG Func?ii
PHP Manual

gnupg_export

(PECL gnupg >= 0.1)

gnupg_export — Exports a key

Descrierea

string gnupg_export ( resource $identifier , string $fingerprint )

Exports the key fingerprint.

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

fingerprint

Cheia amprentei.

Valorile întoarse

On success, this function returns the keydata. On failure, this function returns FALSE.

Exemple

Example #1 Procedural gnupg_export() example

<?php
$res = gnupg_init();
$export = gnupg_export($res,"8660281B6051D071D94B5B230549F9DC851566DC");
echo $export;
?>

Example #2 OO gnupg_export() example

<?php
$gpg = new gnupg();
$export = $gpg -> export("8660281B6051D071D94B5B230549F9DC851566DC");
?>

gnupg_encryptsign
gnupg_geterror
GnuPG Func?ii


Returns the errortext, if a function fails

gnupg_export
gnupg_getprotocol
GnuPG Func?ii
PHP Manual

gnupg_geterror

(PECL gnupg >= 0.1)

gnupg_geterror — Returns the errortext, if a function fails

Descrierea

string gnupg_geterror ( resource $identifier )

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

Valorile întoarse

Returns an errortext, if an error has occurred, otherwise FALSE.

Exemple

Example #1 Procedural gnupg_geterror() example

<?php
$res = gnupg_init();
echo gnupg_geterror($res);
?>

Example #2 OO gnupg_geterror() example

<?php
$gpg = new gnupg();
echo $gpg -> geterror();
?>

gnupg_export
gnupg_getprotocol
GnuPG Func?ii


Returns the currently active protocol for all operations

gnupg_geterror
gnupg_import
GnuPG Func?ii
PHP Manual

gnupg_getprotocol

(PECL gnupg >= 0.1)

gnupg_getprotocol — Returns the currently active protocol for all operations

Descrierea

int gnupg_getprotocol ( resource $identifier )

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

Valorile întoarse

Returns the currently active protocol, which can be one of GNUPG_PROTOCOL_OpenPGP or GNUPG_PROTOCOL_CMS.

Exemple

Example #1 Procedural gnupg_getprotocol() example

<?php
$res = gnupg_init();
echo gnupg_getprotocol($res);
?>

Example #2 OO gnupg_getprotocol() example

<?php
$gpg = new gnupg();
echo $gpg -> getprotocol();
?>

gnupg_geterror
gnupg_import
GnuPG Func?ii


Imports a key

gnupg_getprotocol
gnupg_init
GnuPG Func?ii
PHP Manual

gnupg_import

(PECL gnupg >= 0.3)

gnupg_import — Imports a key

Descrierea

array gnupg_import ( resource $identifier , string $keydata )

Imports the key keydata and returns an array with information about the importprocess.

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

keydata

The data key that is being imported.

Valorile întoarse

On success, this function returns and info-array about the importprocess. On failure, this function returns FALSE.

Exemple

Example #1 Procedural gnupg_import() example

<?php
$res = gnupg_init();
$info = gnupg_import($res,$keydata);
print_r($info);
?>

Example #2 OO gnupg_import() example

<?php
$gpg = new gnupg();
$info = $gpg -> import($keydata);
print_r($info);
?>

gnupg_getprotocol
gnupg_init
GnuPG Func?ii


Initialize a connection

gnupg_import
gnupg_keyinfo
GnuPG Func?ii
PHP Manual

gnupg_init

(PECL gnupg >= 0.4)

gnupg_init — Initialize a connection

Descrierea

resource gnupg_init ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A GnuPG resource connection used by other GnuPG functions.

Exemple

Example #1 Procedural gnupg_init() example

<?php
$res = gnupg_init();
?>

Example #2 OO gnupg initializer example

<?php
$gpg = new gnupg();
?>

gnupg_import
gnupg_keyinfo
GnuPG Func?ii


Returns an array with information about all keys that matches the given pattern

gnupg_init
gnupg_setarmor
GnuPG Func?ii
PHP Manual

gnupg_keyinfo

(PECL gnupg >= 0.1)

gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern

Descrierea

array gnupg_keyinfo ( resource $identifier , string $pattern )

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

pattern

The pattern being checked against the keys.

Valorile întoarse

Returns an array with information about all keys that matches the given pattern or FALSE, if an error has occurred.

Exemple

Example #1 Procedural gnupg_keyinfo() example

<?php
$res = gnupg_init();
$info = gnupg_keyinfo($res, 'test');
print_r($info);
?>

Example #2 OO gnupg_keyinfo() example

<?php
$gpg = new gnupg();
$info = $gpg -> keyinfo("test");
print_r($info);
?>

gnupg_init
gnupg_setarmor
GnuPG Func?ii


Toggle armored output

gnupg_keyinfo
gnupg_seterrormode
GnuPG Func?ii
PHP Manual

gnupg_setarmor

(PECL gnupg >= 0.1)

gnupg_setarmor — Toggle armored output

Descrierea

bool gnupg_setarmor ( resource $identifier , int $armor )

Toggle the armored output.

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

armor

Pass a non-zero integer-value to this function to enable armored-output (default). Pass 0 to disable armored output.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Procedural gnupg_setarmor() example

<?php
$res = gnupg_init();
gnupg_setarmor($res,1); // enable armored output;
gnupg_setarmor($res,0); // disable armored output;
?>

Example #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 Func?ii


Sets the mode for error_reporting

gnupg_setarmor
gnupg_setsignmode
GnuPG Func?ii
PHP Manual

gnupg_seterrormode

(PECL gnupg >= 0.6)

gnupg_seterrormode — Sets the mode for error_reporting

Descrierea

void gnupg_seterrormode ( resource $identifier , int $errormode )

Sets the mode for error_reporting.

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau 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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Procedural gnupg_seterrormode() example

<?php
$res = gnupg_init();
gnupg_seterrormode($res,GNUPG_ERROR_WARNING); // raise a PHP-Warning in case of an error
?>

Example #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 Func?ii


Sets the mode for signing

gnupg_seterrormode
gnupg_sign
GnuPG Func?ii
PHP Manual

gnupg_setsignmode

(PECL gnupg >= 0.1)

gnupg_setsignmode — Sets the mode for signing

Descrierea

bool gnupg_setsignmode ( resource $identifier , int $signmode )

Sets the mode for signing.

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Procedural gnupg_setsignmode() example

<?php
$res = gnupg_init();
gnupg_setsignmode($res,GNUPG_SIG_MODE_DETACH); // produce a detached signature
?>

Example #2 OO gnupg_setsignmode() example

<?php
$gpg = new gnupg();
$gpg -> setsignmode(gnupg::SIG_MODE_DETACH); // produce a detached signature
?>

gnupg_seterrormode
gnupg_sign
GnuPG Func?ii


Signs a given text

gnupg_setsignmode
gnupg_verify
GnuPG Func?ii
PHP Manual

gnupg_sign

(PECL gnupg >= 0.1)

gnupg_sign — Signs a given text

Descrierea

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.

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau gnupg.

plaintext

The plain text being signed.

Valorile întoarse

On success, this function returns the signed text or the signature. On failure, this function returns FALSE.

Exemple

Example #1 Procedural gnupg_sign() example

<?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = gnupg_sign($res, "just a test");
echo $signed;
?>

Example #2 OO gnupg_sign() example

<?php
$gpg = new gnupg();
$gpg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = $gpg->sign("just a test");
echo $signed;
?>

gnupg_setsignmode
gnupg_verify
GnuPG Func?ii


Verifies a signed text

gnupg_sign
haru
GnuPG Func?ii
PHP Manual

gnupg_verify

(PECL gnupg >= 0.1)

gnupg_verify — Verifies a signed text

Descrierea

array gnupg_verify ( resource $identifier , string $signed_text , string $signature [, string &$plaintext ] )

Verifies the given signed_text and returns information about the signature.

Parametri

identifier

Identificatorul gnupg, ob?inut în rezultatul apelarii gnupg_init() sau 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.

Valorile întoarse

On success, this function returns information about the signature. On failure, this function returns FALSE.

Exemple

Example #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);
?>

Example #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 Func?ii


Haru PDF

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • 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 byte length of characters which can be included on one line of 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
Introducere
Ie?iri MIME non-textuale


Introducere

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.

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

haru
Instalarea / configurarea
haru


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
haru


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/haru.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
haru


Exemple

Cuprins

  • Basic PECL/haru example
Constante predefinite
Basic PECL/haru example
haru


Basic PECL/haru example

Example #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.

Exemple
Builtin Fonts And Encodings
Exemple


Builtin Fonts And Encodings

Cuprins

  • 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

(PECL haru >= 0.0.1)

Introducere

Haru PDF Exception Class.

Sinopsisul clasei

HaruException extends Exception {
/* Inherits */
final public string Exception::getMessage ( void )
final public Throwable 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

(PECL haru >= 0.0.1)

Introducere

Haru PDF Document Class.

Sinopsisul clasei

HaruDoc {
/* Metode */
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 )
}

Constante predefinite

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 |

Cuprins

  • 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

Descrierea

object HaruDoc::addPage ( void )

Adds a new page to the document.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a new HaruPage instance.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::addPageLabel ( int $first_page , int $style , int $first_num [, string $prefix = "" ] )

Set the numbering style for the specified range of pages.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

HaruDoc::__construct ( void )

Constructs new HaruDoc instance.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

object HaruDoc::createOutline ( string $title [, object $parent_outline [, object $encoder ]] )

Create a HaruOutline instance.

Parametri

title

The caption of new outline object.

parent_outline

A valid HaruOutline instance or NULL.

encoder

A valid HaruEncoder instance or NULL.

Valorile întoarse

Returns a new HaruOutline instance.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

object HaruDoc::getCurrentEncoder ( void )

Get the HaruEncoder currently used in the document.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns HaruEncoder currently used in the document or FALSE if encoder is not set.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

object HaruDoc::getCurrentPage ( void )

Get current page of the document.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns HaruPage instance on success or FALSE if there is no current page at the moment.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

object HaruDoc::getEncoder ( string $encoding )

Get the HaruEncoder instance for the specified encoding.

Parametri

encoding

The encoding name. See Builtin Encodings for the list of allowed values.

Valorile întoarse

Returns a HaruEncoder instance for the specified encoding.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

object HaruDoc::getFont ( string $fontname [, string $encoding ] )

Get a HaruFont instance.

Parametri

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.

Valorile întoarse

Returns a HaruFont instance with the specified fontname and encoding.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

string HaruDoc::getInfoAttr ( int $type )

Get the current value of the specified document attribute.

Parametri

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

Valorile întoarse

Returns the string value of the specified document attribute.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

int HaruDoc::getPageLayout ( void )

Get the current page layout. See HaruDoc::setPageLayout() for the list of possible values.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

int HaruDoc::getPageMode ( void )

Get the current page mode. See HaruDoc::setPageMode() for the list of possible values.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the page mode currently set in the document. See HaruDoc::setPageMode() for the list of possible values.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

int HaruDoc::getStreamSize ( void )

Get the size of the temporary stream.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

object HaruDoc::insertPage ( object $page )

Creates a new page and inserts just before the specified page.

Parametri

page

A valid HaruPage instance.

Valorile întoarse

Returns a new HaruPage instance.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

object HaruDoc::loadJPEG ( string $filename )

Loads the specified JPEG image.

Parametri

filename

A valid JPEG image file.

Valorile întoarse

Returns a new HaruImage instance.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a HaruImage instance.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

object HaruDoc::loadRaw ( string $filename , int $width , int $height , int $color_space )

Loads a RAW image.

Parametri

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

Valorile întoarse

Returns a HaruImage instance.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

string HaruDoc::loadTTC ( string $fontfile , int $index [, bool $embed = false ] )

Loads the TrueType font with the specified index from a TrueType collection file.

Parametri

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.

Valorile întoarse

Returns the name of the loaded font on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

string HaruDoc::loadTTF ( string $fontfile [, bool $embed = false ] )

Loads the given TTF file and (optionally) embed its data into the document.

Parametri

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.

Valorile întoarse

Returns the name of the loaded font on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

string HaruDoc::loadType1 ( string $afmfile [, string $pfmfile ] )

Loads Type1 font from the given file and registers it in the PDF document.

Parametri

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.

Valorile întoarse

Returns the name of the loaded font on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::output ( void )

Writes the document data into standard output.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

string HaruDoc::readFromStream ( int $bytes )

Read data from the temporary stream.

Parametri

bytes

The bytes parameter specifies how many bytes to read, though the stream may contain less bytes than requested.

Valorile întoarse

Returns data from the temporary stream.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

bool HaruDoc::resetStream ( void )

Rewinds the temporary stream of the document.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::save ( string $file )

Saves the document into the specified file.

Parametri

file

The file to save the document to.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::saveToStream ( void )

Saves the document data into a temporary stream.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruDoc::setCurrentEncoder ( string $encoding )

Defines the encoder currently used in the document.

Parametri

encoding

The name of the encoding to use. See Builtin Encodings for the list of allowed values.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

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.

Parametri

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).

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::setInfoAttr ( int $type , string $info )

Defines an info attribute. Uses the current encoding of the document.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::setOpenAction ( object $destination )

Defines which page should be shown when the document is opened.

Parametri

destination

A valid HaruDestination instance.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruDoc::setPageLayout ( int $layout )

Defines how pages should be displayed.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::setPageMode ( int $mode )

Defines how the document should be displayed.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

page_per_pages

The numbers of pages that a pages object can contain.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::setPermission ( int $permission )

Defines permissions for the document.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::useCNSEncodings ( void )

Enables Chinese simplified encodings.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::useCNSFonts ( void )

Enables builtin Chinese simplified fonts.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::useCNTEncodings ( void )

Enables Chinese traditional encodings.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::useCNTFonts ( void )

Enables builtin Chinese traditional fonts.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::useJPEncodings ( void )

Enables Japanese encodings.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::useJPFonts ( void )

Enables builtin Japanese fonts.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::useKREncodings ( void )

Enables Korean encodings.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruDoc::useKRFonts ( void )

Enables builtin Korean fonts.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • HaruDoc::useKREncodings() - Enable Korean encodings

HaruDoc::useKREncodings
HaruPage
HaruDoc


The HaruPage class

(PECL haru >= 0.0.1)

Introducere

Haru PDF Page Class.

Sinopsisul clasei

HaruPage {
/* Metode */
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 ] )
}

Constante predefinite

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 |

Cuprins

  • 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 byte length of characters which can be included on one line of 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

Descrierea

bool HaruPage::arc ( float $x , float $y , float $ray , float $ang1 , float $ang2 )

Appends an arc to the current path.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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)

Descrierea

bool HaruPage::beginText ( void )

Begins new text object and sets the current text position to (0,0).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::circle ( float $x , float $y , float $ray )

Appends a circle to the current path.

Parametri

x

Horizontal coordinate of the center point.

y

Vertical coordinate of the center point.

ray

The ray of the circle.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::closePath ( void )

Appends a straight line from the current point to the start point of the path.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

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.

Parametri

a

b

c

d

x

y

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

object HaruPage::createDestination ( void )

Create a new HaruDestination instance.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a new HaruDestination instance.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

object HaruPage::createLinkAnnotation ( array $rectangle , object $destination )

Creates a new HaruAnnotation instance.

Parametri

rectangle

An array with 4 coordinates of the clickable area.

destination

Valid HaruDestination instance.

Valorile întoarse

Returns a new HaruAnnotation instance.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

object HaruPage::createTextAnnotation ( array $rectangle , string $text [, object $encoder ] )

Creates a new HaruAnnotation instance.

Parametri

rectangle

An array with 4 coordinates of the annotation area.

text

The text to be displayed.

encoder

Optional HaruEncoder instance.

Valorile întoarse

Returns a new HaruAnnotation instance.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

object HaruPage::createURLAnnotation ( array $rectangle , string $url )

Creates a new HaruAnnotation instance.

Parametri

rectangle

An array with 4 coordinates of the clickable area.

url

The URL to open.

Valorile întoarse

Returns a new HaruAnnotation instance.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

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).

Parametri

x2

A Bezier curve control point.

y2

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

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).

Parametri

x1

A Bezier curve control point.

y1

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

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).

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::drawImage ( object $image , float $x , float $y , float $width , float $height )

Show image at the page.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::ellipse ( float $x , float $y , float $xray , float $yray )

Appends an ellipse to the current path.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::endPath ( void )

Ends current path object without performing filling and painting operations.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::endText ( void )

Finalizes current text object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::eofill ( void )

Fills current path using even-odd rule.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::eoFillStroke ([ bool $close_path = false ] )

Fills current path using even-odd rule, then paints the path.

Parametri

close_path

Optional parameter. When set to TRUE, the function closes the current path. Default to FALSE.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::fill ( void )

Fills current path using nonzero winding number rule.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::fillStroke ([ bool $close_path = false ] )

Fills current path using nonzero winding number rule, then paints the path.

Parametri

close_path

Optional parameter. When set to TRUE, the function closes the current path. Default to FALSE.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

float HaruPage::getCharSpace ( void )

Get the current value of character spacing.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current value of character spacing.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

array HaruPage::getCMYKFill ( void )

Returns the current filling color.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current filling color as an array with 4 elements ("c", "m", "y" and "k").

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

array HaruPage::getCMYKStroke ( void )

Get the current stroking color.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current stroking color as an array with 4 elements ("c", "m", "y" and "k").

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

object HaruPage::getCurrentFont ( void )

Get the currently used font.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the currently used font as an instance of HaruFont.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

float HaruPage::getCurrentFontSize ( void )

Get the current font size.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current font size.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

array HaruPage::getCurrentPos ( void )

Get the current position for path painting.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current position for path painting as an array of with two elements - "x" and "y".

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

array HaruPage::getCurrentTextPos ( void )

Get the current position for text printing.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current position for text printing as an array with 2 elements - "x" and "y".

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

array HaruPage::getDash ( void )

Get the current dash pattern. See HaruPage::setDash() for more information on dash patterns.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current dash pattern as an array of two elements - "pattern" and "phase" or FALSE if dash pattern was not set.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

int HaruPage::getFillingColorSpace ( void )

Get the current filling color space.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

float HaruPage::getFlatness ( void )

Get the flatness of the page.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the flatness of the page.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

int HaruPage::getGMode ( void )

Get the current graphics mode.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

float HaruPage::getGrayFill ( void )

Get the current filling color.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current filling color.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

float HaruPage::getGrayStroke ( void )

Get the current stroking color.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current stroking color.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

float HaruPage::getHeight ( void )

Get the height of the page.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the height of the page.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

float HaruPage::getHorizontalScaling ( void )

Get the current value of the horizontal scaling.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current value of horizontal scaling.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

int HaruPage::getLineCap ( void )

Get the current line cap style.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

int HaruPage::getLineJoin ( void )

Get the current line join style.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current line join style. The result value is one of the following:

  • HaruPage::MITER_JOIN
  • HaruPage::ROUND_JOIN
  • HaruPage::BEVEL_JOIN

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

float HaruPage::getLineWidth ( void )

Get the current line width.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current line width.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

float HaruPage::getMiterLimit ( void )

Get the value of the miter limit.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the value of the miter limit.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

array HaruPage::getRGBFill ( void )

Get the current filling color.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current filling color as an array with 3 elements: "r", "g" and "b".

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

array HaruPage::getRGBStroke ( void )

Get the current stroking color.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current stroking color.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

int HaruPage::getStrokingColorSpace ( void )

Get the current stroking color space.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current stroking color space. The list of return values is the same as for HaruPage::getFillingColorSpace()

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

float HaruPage::getTextLeading ( void )

Get the current value of line spacing.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current value of line spacing.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

array HaruPage::getTextMatrix ( void )

Get the current text transformation matrix of the page.

Valorile întoarse

Returns the current text transformation matrix of the page as an array of 6 elements: "a", "b", "c", "d", "x" and "y".

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

int HaruPage::getTextRenderingMode ( void )

Get the current text rendering mode.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

float HaruPage::getTextRise ( void )

Get the current value of text rising.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current value of text rising.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

float HaruPage::getTextWidth ( string $text )

Get the width of the text using current fontsize, character spacing and word spacing

Parametri

text

The text to measure.

Valorile întoarse

Returns the width of the text using current fontsize, character spacing and word spacing.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • HaruPage::measureText() - Calculate the byte length of characters which can be included on one line of 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

Descrierea

array HaruPage::getTransMatrix ( void )

Get the current transformation matrix of the page.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current transformation matrix of the page as an array of 6 elements: "a", "b", "c", "d", "x" and "y".

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

float HaruPage::getWidth ( void )

Get the width of the page.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the width of the page.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

float HaruPage::getWordSpace ( void )

Get the current value of word spacing.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current value of word spacing.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::lineTo ( float $x , float $y )

Draws a line from the current point to the specified point.

Parametri

x

y

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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 byte length of characters which can be included on one line of the specified width

HaruPage::lineTo
HaruPage::moveTextPos
HaruPage
PHP Manual

HaruPage::measureText

(PECL haru >= 0.0.1)

HaruPage::measureText — Calculate the byte length of characters which can be included on one line of the specified width

Descrierea

int HaruPage::measureText ( string $text , float $width [, bool $wordwrap = false ] )

Get the byte length of characters which can be included on one line of the specified width.

Parametri

text

The text to measure.

width

The width of the line.

wordwrap

When this parameter is set to TRUE the function "emulates" word wrapping by stopping after the last full word (delimited by whitespace) that can fit on the line.

Valorile întoarse

Returns the byte length of characters which can be included within the specified width. For single-byte encodings, this is equal to the number of characters. For multi-byte encodings, this is not necessarily the case.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

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).

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::moveTo ( float $x , float $y )

Defines starting point for new drawing path.

Parametri

x

A new starting point coordinate.

y

A new starting point coordinate.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::moveToNextLine ( void )

Moves text position to the start of the next line.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::rectangle ( float $x , float $y , float $width , float $height )

Appends a rectangle to the current drawing path.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::setCharSpace ( float $char_space )

Defines character spacing for the page.

Parametri

char_space

The new character spacing for the page.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setCMYKFill ( float $c , float $m , float $y , float $k )

Defines filling color for the page.

Parametri

c

m

y

k

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setCMYKStroke ( float $c , float $m , float $y , float $k )

Defines stroking color for the page.

Parametri

c

m

y

k

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setDash ( array $pattern , int $phase )

Defines the dash pattern for the page.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setFlatness ( float $flatness )

Defines flatness for the page.

Parametri

flatness

The defined flatness for the page.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setFontAndSize ( object $font , float $size )

Defines current font and its size for the page.

Parametri

font

A valid HaruFont instance.

size

The size of the font.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setGrayFill ( float $value )

Defines filling color for the page.

Parametri

value

The value of gray level between 0 and 1.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setGrayStroke ( float $value )

Defines stroking color for the page.

Parametri

value

The value of gray level between 0 and 1.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setHeight ( float $height )

Defines height of the page.

Parametri

height

The defined height for the page.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setHorizontalScaling ( float $scaling )

Set the horizontal scaling for the page.

Parametri

scaling

The horizontal scaling for text showing on the page. The initial value is 100.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setLineCap ( int $cap )

Defines the shape to be used at the ends of lines.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setLineJoin ( int $join )

Defines line join style for the page.

Parametri

join

Must be one of the following values:

  • HaruPage::MITER_JOIN
  • HaruPage::ROUND_JOIN
  • HaruPage::BEVEL_JOIN

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setLineWidth ( float $width )

Defines line width for the page.

Parametri

width

The defined line width for the page.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setMiterLimit ( float $limit )

Set the current value of the miter limit of the page.

Parametri

limit

Defines the current value of the miter limit of the page.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setRGBFill ( float $r , float $g , float $b )

Defines filling color for the page. All values must be between 0 and 1.

Parametri

r

g

b

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setRGBStroke ( float $r , float $g , float $b )

Defines stroking color for the page. All values must be between 0 and 1.

Parametri

r

g

b

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setRotate ( int $angle )

Defines rotation angle of the page.

Parametri

angle

Must be a multiple of 90 degrees.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::setSize ( int $size , int $direction )

Changes size and direction of the page to a predefined format.

Parametri

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

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setSlideShow ( int $type , float $disp_time , float $trans_time )

Defines transition style for the page.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::setTextLeading ( float $text_leading )

Set the text leading (line spacing) for the page.

Parametri

text_leading

Defines line spacing for the page.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setTextMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )

Defines the text transformation matrix of the page.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setTextRenderingMode ( int $mode )

Defines text rendering mode for the page.

Parametri

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

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setTextRise ( float $rise )

Set the current value of text rising.

Parametri

rise

Defines the current value of text rising.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setWidth ( float $width )

Set the width of the page.

Parametri

width

Defines width of the page.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::setWordSpace ( float $word_space )

Set the word spacing for the page.

Parametri

word_space

Defines word spacing for the page.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::showText ( string $text )

Prints out the text at the current position of the page.

Parametri

text

The text to show.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

text

The text to show.

word_space

The word spacing.

char_space

The character spacing.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

bool HaruPage::stroke ([ bool $close_path = false ] )

Paints the current path.

Parametri

close_path

Closes the current path if set to TRUE.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruPage::textOut ( float $x , float $y , string $text )

Prints the text on the specified position.

Parametri

x

y

text

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

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

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

A se vedea ?i

  • 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

(PECL haru >= 0.0.1)

Introducere

Haru PDF Font Class.

Sinopsisul clasei

HaruFont {
/* Metode */
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 ] )
}

Cuprins

  • 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

Descrierea

int HaruFont::getAscent ( void )

Get the vertical ascent of the font.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the vertical ascent of the font.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

int HaruFont::getCapHeight ( void )

Get the distance from the baseline of uppercase letters.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the distance from the baseline of uppercase letters.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

int HaruFont::getDescent ( void )

Get the vertical descent of the font.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Return the vertical descent of the font.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

string HaruFont::getEncodingName ( void )

Get the name of the font encoding.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the name of the font encoding.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

string HaruFont::getFontName ( void )

Get the name of the font.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the name of the font.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

array HaruFont::getTextWidth ( string $text )

Get the total width of the text, number of characters, number of words and number of spaces.

Parametri

text

The text to measure.

Valorile întoarse

Returns the total width of the text, number of characters, number of words and number of spaces in the given text.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

int HaruFont::getUnicodeWidth ( int $character )

Get the width of the character in the font.

Parametri

character

The code of the character.

Valorile întoarse

Returns the width of the character in the font.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

int HaruFont::getXHeight ( void )

Gets the distance from the baseline of lowercase letters.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the distance from the baseline of lowercase letters.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the number of characters which can be included within the specified width.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

HaruFont::getXHeight
HaruImage
HaruFont


The HaruImage class

(PECL haru >= 0.0.1)

Introducere

Haru PDF Image Class.

Sinopsisul clasei

HaruImage {
/* Metode */
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 )
}

Cuprins

  • 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

Descrierea

int HaruImage::getBitsPerComponent ( void )

Gets the number of bits used to describe each color component of the image.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the number of bits used to describe each color component of the image.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

string HaruImage::getColorSpace ( void )

Get the name of the color space.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the name of the color space of the image. The name is one of the following values:

  • "DeviceGray"
  • "DeviceRGB"
  • "DeviceCMYK"
  • "Indexed"

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

int HaruImage::getHeight ( void )

Get the height of the image.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the height of the image.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

array HaruImage::getSize ( void )

Get the size of the image.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array with two elements: width and height, which contain appropriate dimensions of the image.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

int HaruImage::getWidth ( void )

Get the width of the image.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the width of the image.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruImage::setMaskImage ( object $mask_image )

Sets the image used as image-mask. It must be 1bit gray-scale color image.

Parametri

mask_image

A valid HaruImage instance.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

HaruImage::setColorMask
HaruEncoder
HaruImage


The HaruEncoder class

(PECL haru >= 0.0.1)

Introducere

Haru PDF Encoder Class.

Sinopsisul clasei

HaruEncoder {
/* Metode */
int getByteType ( string $text , int $index )
int getType ( void )
int getUnicode ( int $character )
int getWritingMode ( void )
}

Constante predefinite

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 |

Cuprins

  • 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

Descrierea

int HaruEncoder::getByteType ( string $text , int $index )

Get the type of the byte in the text.

Parametri

text

The text.

index

The position in the text.

Valorile întoarse

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.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

int HaruEncoder::getType ( void )

Get the type of the encoder.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

int HaruEncoder::getUnicode ( int $character )

Converts the specified character to unicode.

Parametri

character

The character code to convert.

Valorile întoarse

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

int HaruEncoder::getWritingMode ( void )

Get the writing mode of the encoder.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

HaruEncoder::getUnicode
HaruOutline
HaruEncoder


The HaruOutline class

(PECL haru >= 0.0.1)

Introducere

Haru PDF Outline Class.

Sinopsisul clasei

HaruOutline {
/* Metode */
bool setDestination ( object $destination )
bool setOpened ( bool $opened )
}

Cuprins

  • 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

Descrierea

bool HaruOutline::setDestination ( object $destination )

Sets a destination object which becomes a target to jump to when the outline is clicked.

Parametri

destination

A valid HaruDestination instance.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruOutline::setOpened ( bool $opened )

Defines whether this node is opened or not when the outline is displayed for the first time.

Parametri

opened

TRUE means open, FALSE - closed.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

HaruOutline::setDestination
HaruAnnotation
HaruOutline


The HaruAnnotation class

(PECL haru >= 0.0.1)

Introducere

Haru PDF Annotation Class.

Sinopsisul clasei

HaruAnnotation {
/* Metode */
bool setBorderStyle ( float $width , int $dash_on , int $dash_off )
bool setHighlightMode ( int $mode )
bool setIcon ( int $icon )
bool setOpened ( bool $opened )
}

Constante predefinite

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 |

Cuprins

  • 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

Descrierea

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.

Parametri

width

The width of the border line.

dash_on

The dash style.

dash_off

The dash style.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruAnnotation::setHighlightMode ( int $mode )

Defines the appearance of the annotation when clicked. This function may be used with link annotations only.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruAnnotation::setIcon ( int $icon )

Defines the style of the annotation icon. This function may be used with text annotations only.

Parametri

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

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruAnnotation::setOpened ( bool $opened )

Defines whether the annotation is initially displayed open. This function may be used with text annotations only.

Parametri

opened

TRUE means the annotation is initially displayed open, FALSE - means it's closed.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

HaruAnnotation::setIcon
HaruDestination
HaruAnnotation


The HaruDestination class

(PECL haru >= 0.0.1)

Introducere

Haru PDF Destination Class.

Sinopsisul clasei

HaruDestination {
/* Metode */
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 )
}

Cuprins

  • 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

Descrierea

bool HaruDestination::setFit ( void )

Defines the appearance of the page to fit the window.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruDestination::setFitB ( void )

Defines the appearance of the page to fit the bounding box of the page within the window.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

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.

Parametri

top

The top coordinates of the page.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

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.

Parametri

left

The left coordinates of the page.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

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.

Parametri

top

The top position of the page.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruDestination::setFitR ( float $left , float $bottom , float $right , float $top )

Defines the appearance of the page to fit the rectangle by the parameters.

Parametri

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.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruDestination::setFitV ( float $left )

Defines the appearance of the page to fit the window height.

Parametri

left

The left position of the page.

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

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

Descrierea

bool HaruDestination::setXYZ ( float $left , float $top , float $zoom )

Defines the appearance of the page using three parameters: left, top and zoom.

Parametri

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%).

Valorile întoarse

Returns TRUE on success.

Erori/Excep?ii

Emite un HaruException în caz de eroare.

HaruDestination::setFitV
Ming
HaruDestination


Ming (flash)

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • SWFAction Examples
    • SWFSPrite basic examples
  • Func?ii Ming
    • 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 — Descrierea
    • SWFDisplayItem::getX — Descrierea
    • SWFDisplayItem::getXScale — Descrierea
    • SWFDisplayItem::getXSkew — Descrierea
    • SWFDisplayItem::getY — Descrierea
    • SWFDisplayItem::getYScale — Descrierea
    • SWFDisplayItem::getYSkew — Descrierea
    • 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 — Descrierea
    • SWFMovie::addFont — Descrierea
    • SWFMovie::__construct — Creates a new movie object, representing an SWF version 4 movie
    • SWFMovie::importChar — Descrierea
    • SWFMovie::importFont — Descrierea
    • 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 — Descrierea
    • 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 — Descrierea
    • SWFMovie::stopSound — Descrierea
    • SWFMovie::streamMP3 — Streams a MP3 file
    • SWFMovie::writeExports — Descrierea
  • 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 — Descrierea
    • SWFSoundInstance::loopInPoint — Descrierea
    • SWFSoundInstance::loopOutPoint — Descrierea
    • SWFSoundInstance::noMultiple — Descrierea
  • SWFSprite — The SWFSprite class
    • SWFSprite::add — Adds an object to a sprite
    • SWFSprite::__construct — Creeaza un videoclip (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 — Descrierea
    • SWFSprite::stopSound — Descrierea
  • 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
Introducere
Ie?iri MIME non-textuale


Introducere

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/.

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.3.0.

Ming
Instalarea / configurarea
Ming


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Ming


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/ming.

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.3.0

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
Tipurile resurselor
Exemple
Ming


Exemple

Cuprins

  • SWFAction Examples
  • SWFSPrite basic examples
Constante predefinite
SWFAction Examples
Ming


SWFAction Examples

This simple example will move the red square across the window.

Example #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.

Example #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...

Example #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();
?>

Exemple
SWFSPrite basic examples
Exemple


SWFSPrite basic examples

This simple example will spin gracefully a big red square.

Example #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
Func?ii Ming
Exemple


Func?ii Ming

Cuprins

  • 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)

Func?ii Ming
ming_setcubicthreshold
Func?ii Ming
PHP Manual

ming_keypress

(PHP 5 <= 5.3.0, PECL ming SVN)

ming_keypress — Returns the action flag for keyPress(char)

Descrierea

int ming_keypress ( string $char )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Func?ii Ming
ming_setcubicthreshold
Func?ii Ming


Set cubic threshold

ming_keypress
ming_setscale
Func?ii Ming
PHP Manual

ming_setcubicthreshold

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PECL ming SVN)

ming_setcubicthreshold — Set cubic threshold

Descrierea

void ming_setcubicthreshold ( int $threshold )

Sets the threshold error for drawing cubic beziers.

Parametri

threshold

The Threshold. Lower is more accurate, hence larger file size.

Valorile întoarse

Nu este întoarsa nici o valoare.

ming_keypress
ming_setscale
Func?ii Ming


Set the global scaling factor.

ming_setcubicthreshold
ming_setswfcompression
Func?ii Ming
PHP Manual

ming_setscale

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PECL ming SVN)

ming_setscale — Set the global scaling factor.

Descrierea

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.

Parametri

scale

The scale to be set.

Valorile întoarse

Nu este întoarsa nici o valoare.

ming_setcubicthreshold
ming_setswfcompression
Func?ii Ming


Sets the SWF output compression

ming_setscale
ming_useconstants
Func?ii Ming
PHP Manual

ming_setswfcompression

(PHP 5.2.1-5.3.0, PHP 7, PECL ming SVN)

ming_setswfcompression — Sets the SWF output compression

Descrierea

void ming_setswfcompression ( int $level )

Sets the SWF output compression level.

Parametri

level

The new compression level. Should be a value between 1 and 9 inclusive.

Valorile întoarse

Nu este întoarsa nici o valoare.

ming_setscale
ming_useconstants
Func?ii Ming


Use constant pool

ming_setswfcompression
ming_useswfversion
Func?ii Ming
PHP Manual

ming_useconstants

(PHP 5 <= 5.3.0, PECL ming SVN)

ming_useconstants — Use constant pool

Descrierea

void ming_useconstants ( int $use )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

ming_setswfcompression
ming_useswfversion
Func?ii Ming


Sets the SWF version

ming_useconstants
SWFAction
Func?ii Ming
PHP Manual

ming_useswfversion

(PHP 4 >= 4.2.0, PHP 5 <= 5.3.0, PECL ming SVN)

ming_useswfversion — Sets the SWF version

Descrierea

void ming_useswfversion ( int $version )

Sets the SWF version to be used in the movie. This affect the bahaviour of Action Script.

Parametri

version

SWF version to use.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ming_useswfversion() example

<?php

$movie = new SWFMovie();
ming_useswfversion(4); // Flash 4

?>

ming_useconstants
SWFAction
Func?ii Ming


The SWFAction class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

SWFAction.

Sinopsisul clasei

SWFAction {
/* Metode */
__construct ( string $script )
}

Descrierea

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.

Cuprins

  • 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

Descrierea

SWFAction::__construct ( string $script )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Creates a new SWFAction and compiles the given script in it.

Parametri

script

An ActionScript snippet to associate with the SWFAction. See SWFAction for more details.

SWFAction
SWFBitmap
SWFAction


The SWFBitmap class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

SWFBitmap.

Sinopsisul clasei

SWFBitmap {
/* Metode */
__construct ( mixed $file [, mixed $alphafile ] )
float getHeight ( void )
float getWidth ( void )
}

Cuprins

  • 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

Descrierea

SWFBitmap::__construct ( mixed $file [, mixed $alphafile ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Creates the new SWFBitmap object from the given file.

Parametri

For both parameters you can provide a file pointer returned by fopen() or the image data, as a binary string.

file

Nota:

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.

Exemple

Example #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();
?>

Example #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 5 <= 5.3.0, PECL ming SVN)

SWFBitmap::getHeight — Returns the bitmap's height

Descrierea

float SWFBitmap::getHeight ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Returns the bitmap's height.

Valorile întoarse

Returns the bitmap height in pixels.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFBitmap::getWidth — Returns the bitmap's width

Descrierea

float SWFBitmap::getWidth ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Returns the bitmap's width.

Valorile întoarse

Returns the bitmap width in pixels.

A se vedea ?i

  • SWFBitmap::getHeight() - Returns the bitmap's height

SWFBitmap::getHeight
SWFButton
SWFBitmap


The SWFButton class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

SWFButton.

Sinopsisul clasei

SWFButton {
/* Metode */
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 )
}

Cuprins

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFButton::addAction — Adds an action

Descrierea

void SWFButton::addAction ( SWFAction $action , int $flags )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Adds the given action to the button for the given conditions.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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

Descrierea

SWFSoundInstance SWFButton::addASound ( SWFSound $sound , int $flags )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

SWFButton::addAction
SWFButton::addShape
SWFButton


Adds a shape to a button

SWFButton::addASound
SWFButton::__construct
SWFButton
PHP Manual

SWFButton::addShape

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::addShape — Adds a shape to a button

Descrierea

void SWFButton::addShape ( SWFShape $shape , int $flags )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Adds the given shape to the button.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

SWFButton::__construct ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Creates a new Button.

Exemple

This simple example will show your usual interactions with buttons : rollover, rollon, mouseup, mousedown, noaction.

Example #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.

Example #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 5 <= 5.3.0, PECL ming SVN)

SWFButton::setAction — Sets the action

Descrierea

void SWFButton::setAction ( SWFAction $action )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Sets the action to be performed when the button is clicked.

This is a shortcut for SWFButton::addAction() called with the SWFBUTTON_MOUSEUP flag.

Parametri

action

An SWFAction, returned by SWFAction::__construct().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFButton::setDown — Alias for addShape(shape, SWFBUTTON_DOWN)

Descrierea

void SWFButton::setDown ( SWFShape $shape )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swfbutton::setdown() alias for addShape(shape, SWFBUTTON_DOWN).

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFButton::setHit — Alias for addShape(shape, SWFBUTTON_HIT)

Descrierea

void SWFButton::setHit ( SWFShape $shape )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swfbutton::sethit() alias for addShape(shape, SWFBUTTON_HIT).

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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

Descrierea

void SWFButton::setMenu ( int $flag )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

flag

This parameter can be used for a slight different behavior of buttons. You can set it to 0 (off) or 1 (on).

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFButton::setHit
SWFButton::setOver
SWFButton


Alias for addShape(shape, SWFBUTTON_OVER)

SWFButton::setMenu
SWFButton::setUp
SWFButton
PHP Manual

SWFButton::setOver

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::setOver — Alias for addShape(shape, SWFBUTTON_OVER)

Descrierea

void SWFButton::setOver ( SWFShape $shape )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swfbutton::setover() alias for addShape(shape, SWFBUTTON_OVER).

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFButton::setUp — Alias for addShape(shape, SWFBUTTON_UP)

Descrierea

void SWFButton::setUp ( SWFShape $shape )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swfbutton::setup() alias for addShape(shape, SWFBUTTON_UP).

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction

SWFButton::setOver
SWFDisplayItem
SWFButton


The SWFDisplayItem class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

SWFDisplayItem.

Sinopsisul clasei

SWFDisplayItem {
/* Metode */
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 )
}

Cuprins

  • 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 — Descrierea
  • SWFDisplayItem::getX — Descrierea
  • SWFDisplayItem::getXScale — Descrierea
  • SWFDisplayItem::getXSkew — Descrierea
  • SWFDisplayItem::getY — Descrierea
  • SWFDisplayItem::getYScale — Descrierea
  • SWFDisplayItem::getYSkew — Descrierea
  • 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 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::addAction — Adds this SWFAction to the given SWFSprite instance

Descrierea

void SWFDisplayItem::addAction ( SWFAction $action , int $flags )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

action

An SWFAction, returned by SWFAction::__construct().

flags

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::addColor — Adds the given color to this item's color transform

Descrierea

void SWFDisplayItem::addColor ( int $red , int $green , int $blue [, int $a ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

void SWFDisplayItem::endMask ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFDisplayItem::addColor
SWFDisplayItem::getRot
SWFDisplayItem


SWFDisplayItem::endMask
SWFDisplayItem::getX
SWFDisplayItem
PHP Manual

SWFDisplayItem::getRot

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getRot —

Descrierea

float SWFDisplayItem::getRot ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

SWFDisplayItem::endMask
SWFDisplayItem::getX
SWFDisplayItem


SWFDisplayItem::getRot
SWFDisplayItem::getXScale
SWFDisplayItem
PHP Manual

SWFDisplayItem::getX

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getX —

Descrierea

float SWFDisplayItem::getX ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • SWFDisplayItem::getY() - Descrierea

SWFDisplayItem::getRot
SWFDisplayItem::getXScale
SWFDisplayItem


SWFDisplayItem::getX
SWFDisplayItem::getXSkew
SWFDisplayItem
PHP Manual

SWFDisplayItem::getXScale

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getXScale —

Descrierea

float SWFDisplayItem::getXScale ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • SWFDisplayItem::getYScale() - Descrierea

SWFDisplayItem::getX
SWFDisplayItem::getXSkew
SWFDisplayItem


SWFDisplayItem::getXScale
SWFDisplayItem::getY
SWFDisplayItem
PHP Manual

SWFDisplayItem::getXSkew

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getXSkew —

Descrierea

float SWFDisplayItem::getXSkew ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • SWFDisplayItem::getYSkew() - Descrierea

SWFDisplayItem::getXScale
SWFDisplayItem::getY
SWFDisplayItem


SWFDisplayItem::getXSkew
SWFDisplayItem::getYScale
SWFDisplayItem
PHP Manual

SWFDisplayItem::getY

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getY —

Descrierea

float SWFDisplayItem::getY ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • SWFDisplayItem::getX() - Descrierea

SWFDisplayItem::getXSkew
SWFDisplayItem::getYScale
SWFDisplayItem


SWFDisplayItem::getY
SWFDisplayItem::getYSkew
SWFDisplayItem
PHP Manual

SWFDisplayItem::getYScale

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getYScale —

Descrierea

float SWFDisplayItem::getYScale ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • SWFDisplayItem::getXScale() - Descrierea

SWFDisplayItem::getY
SWFDisplayItem::getYSkew
SWFDisplayItem


SWFDisplayItem::getYScale
SWFDisplayItem::move
SWFDisplayItem
PHP Manual

SWFDisplayItem::getYSkew

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getYSkew —

Descrierea

float SWFDisplayItem::getYSkew ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • SWFDisplayItem::getXSkew() - Descrierea

SWFDisplayItem::getYScale
SWFDisplayItem::move
SWFDisplayItem


Moves object in relative coordinates

SWFDisplayItem::getYSkew
SWFDisplayItem::moveTo
SWFDisplayItem
PHP Manual

SWFDisplayItem::move

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::move — Moves object in relative coordinates

Descrierea

void SWFDisplayItem::move ( float $dx , float $dy )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::moveTo — Moves object in global coordinates

Descrierea

void SWFDisplayItem::moveTo ( float $x , float $y )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::multColor — Multiplies the item's color transform

Descrierea

void SWFDisplayItem::multColor ( float $red , float $green , float $blue [, float $a ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

This simple example will modify your picture's atmosphere to Halloween (use a landscape or bright picture).

Example #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

Descrierea

void SWFDisplayItem::remove ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::rotate — Rotates in relative coordinates

Descrierea

void SWFDisplayItem::rotate ( float $angle )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::rotateTo — Rotates the object in global coordinates

Descrierea

void SWFDisplayItem::rotateTo ( float $angle )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

This example bring three rotating string from the background to the foreground. Pretty nice.

Example #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();
?>

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::scale — Scales the object in relative coordinates

Descrierea

void SWFDisplayItem::scale ( float $dx , float $dy )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::scaleTo — Scales the object in global coordinates

Descrierea

void SWFDisplayItem::scaleTo ( float $x [, float $y ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::setDepth — Sets z-order

Descrierea

void SWFDisplayItem::setDepth ( int $depth )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

void SWFDisplayItem::setMaskLevel ( int $level )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFDisplayItem::setDepth
SWFDisplayItem::setMatrix
SWFDisplayItem


Sets the item's transform matrix

SWFDisplayItem::setMaskLevel
SWFDisplayItem::setName
SWFDisplayItem
PHP Manual

SWFDisplayItem::setMatrix

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::setMatrix — Sets the item's transform matrix

Descrierea

void SWFDisplayItem::setMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFDisplayItem::setMaskLevel
SWFDisplayItem::setName
SWFDisplayItem


Sets the object's name

SWFDisplayItem::setMatrix
SWFDisplayItem::setRatio
SWFDisplayItem
PHP Manual

SWFDisplayItem::setName

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::setName — Sets the object's name

Descrierea

void SWFDisplayItem::setName ( string $name )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFDisplayItem::setMatrix
SWFDisplayItem::setRatio
SWFDisplayItem


Sets the object's ratio

SWFDisplayItem::setName
SWFDisplayItem::skewX
SWFDisplayItem
PHP Manual

SWFDisplayItem::setRatio

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::setRatio — Sets the object's ratio

Descrierea

void SWFDisplayItem::setRatio ( float $ratio )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

This simple example will morph nicely three concentric circles.

Example #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 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::skewX — Sets the X-skew

Descrierea

void SWFDisplayItem::skewX ( float $ddegrees )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::skewXTo — Sets the X-skew

Descrierea

void SWFDisplayItem::skewXTo ( float $degrees )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::skewY — Sets the Y-skew

Descrierea

void SWFDisplayItem::skewY ( float $ddegrees )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::skewYTo — Sets the Y-skew

Descrierea

void SWFDisplayItem::skewYTo ( float $degrees )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

The SWFFill object allows you to transform (scale, skew, rotate) bitmap and gradient fills.

swffill objects are created by the SWFShape::addFill() method.

Sinopsisul clasei

SWFFill {
/* Metode */
void moveTo ( float $x , float $y )
void rotateTo ( float $angle )
void scaleTo ( float $x [, float $y ] )
void skewXTo ( float $x )
void skewYTo ( float $y )
}

Cuprins

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFFill::moveTo — Moves fill origin

Descrierea

void SWFFill::moveTo ( float $x , float $y )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Moves the fill origin to the given global coordinates.

Parametri

x

X-coordinate

y

Y-coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFFill
SWFFill::rotateTo
SWFFill


Sets fill's rotation

SWFFill::moveTo
SWFFill::scaleTo
SWFFill
PHP Manual

SWFFill::rotateTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFill::rotateTo — Sets fill's rotation

Descrierea

void SWFFill::rotateTo ( float $angle )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Sets the fill rotation to the given angle.

Parametri

angle

The rotation angle, in degrees.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFFill::moveTo
SWFFill::scaleTo
SWFFill


Sets fill's scale

SWFFill::rotateTo
SWFFill::skewXTo
SWFFill
PHP Manual

SWFFill::scaleTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFill::scaleTo — Sets fill's scale

Descrierea

void SWFFill::scaleTo ( float $x [, float $y ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Sets the fill scale to the given coordinates.

Parametri

x

X-coordinate

y

Y-coordinate

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFFill::rotateTo
SWFFill::skewXTo
SWFFill


Sets fill x-skew

SWFFill::scaleTo
SWFFill::skewYTo
SWFFill
PHP Manual

SWFFill::skewXTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFill::skewXTo — Sets fill x-skew

Descrierea

void SWFFill::skewXTo ( float $x )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Sets the fill x-skew to x.

Parametri

x

When x is 1.0, it is a 45-degree forward slant. More is more forward, less is more backward.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • SWFFill::skewYTo() - Sets fill y-skew

SWFFill::scaleTo
SWFFill::skewYTo
SWFFill


Sets fill y-skew

SWFFill::skewXTo
SWFFont
SWFFill
PHP Manual

SWFFill::skewYTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFill::skewYTo — Sets fill y-skew

Descrierea

void SWFFill::skewYTo ( float $y )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Sets the fill y-skew to y.

Parametri

y

When y is 1.0, it is a 45-degree upward slant. More is more upward, less is more downward.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • SWFFill::skewXTo() - Sets fill x-skew

SWFFill::skewXTo
SWFFont
SWFFill


The SWFFont class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

The SWFFont object represent a reference to the font definition, for us with SWFText::setFont() and SWFTextField::setFont().

Sinopsisul clasei

SWFFont {
/* Metode */
__construct ( string $filename )
float getAscent ( void )
float getDescent ( void )
float getLeading ( void )
string getShape ( int $code )
float getUTF8Width ( string $string )
float getWidth ( string $string )
}

Cuprins

  • 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

Descrierea

SWFFont::__construct ( string $filename )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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 5 <= 5.3.0, PECL ming SVN)

SWFFont::getAscent — Returns the ascent of the font, or 0 if not available

Descrierea

float SWFFont::getAscent ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFFont::getDescent — Returns the descent of the font, or 0 if not available

Descrierea

float SWFFont::getDescent ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFFont::getLeading — Returns the leading of the font, or 0 if not available

Descrierea

float SWFFont::getLeading ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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

Descrierea

string SWFFont::getShape ( int $code )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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

Descrierea

float SWFFont::getUTF8Width ( string $string )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFFont::getWidth — Returns the string's width

Descrierea

float SWFFont::getWidth ( string $string )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

A se vedea ?i

  • SWFFont::getUTF8Width() - Calculates the width of the given string in this font at full height

SWFFont::getUTF8Width
SWFFontChar
SWFFont


The SWFFontChar class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

SWFFontChar.

Sinopsisul clasei

SWFFontChar {
/* Metode */
void addChars ( string $char )
void addUTF8Chars ( string $char )
}

Cuprins

  • 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

Descrierea

void SWFFontChar::addChars ( string $char )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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

Descrierea

void SWFFontChar::addUTF8Chars ( string $char )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • SWFFontChar::addChars() - Adds characters to a font for exporting font

SWFFontChar::addChars
SWFGradient
SWFFontChar


The SWFGradient class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

SWFGradient.

Sinopsisul clasei

SWFGradient {
/* Metode */
void addEntry ( float $ratio , int $red , int $green , int $blue [, int $alpha = 255 ] )
__construct ( void )
}

Cuprins

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFGradient::addEntry — Adds an entry to the gradient list

Descrierea

void SWFGradient::addEntry ( float $ratio , int $red , int $green , int $blue [, int $alpha = 255 ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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).

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

SWFGradient::__construct ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Example #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

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

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.)

Sinopsisul clasei

SWFMorph {
/* Metode */
__construct ( void )
SWFShape getShape1 ( void )
SWFShape getShape2 ( void )
}

Cuprins

  • 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

Descrierea

SWFMorph::__construct ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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!

Exemple

This simple example will morph a big red square into a smaller blue black-bordered square.

Example #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 5 <= 5.3.0, PECL ming SVN)

SWFMorph::getShape1 — Gets a handle to the starting shape

Descrierea

SWFShape SWFMorph::getShape1 ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Gets the morph's starting shape.

Valorile întoarse

Returns a SWFShape object.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFMorph::getShape2 — Gets a handle to the ending shape

Descrierea

SWFShape SWFMorph::getShape2 ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Gets the morph's ending shape.

Valorile întoarse

Returns a SWFShape object.

A se vedea ?i

  • SWFMorph::getShape1() - Gets a handle to the starting shape

SWFMorph::getShape1
SWFMovie
SWFMorph


The SWFMovie class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

SWFMovie is a movie object representing an SWF movie.

Sinopsisul clasei

SWFMovie {
/* Metode */
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 )
}

Cuprins

  • SWFMovie::add — Adds any type of data to a movie
  • SWFMovie::addExport — Descrierea
  • SWFMovie::addFont — Descrierea
  • SWFMovie::__construct — Creates a new movie object, representing an SWF version 4 movie
  • SWFMovie::importChar — Descrierea
  • SWFMovie::importFont — Descrierea
  • 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 — Descrierea
  • 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 — Descrierea
  • SWFMovie::stopSound — Descrierea
  • SWFMovie::streamMP3 — Streams a MP3 file
  • SWFMovie::writeExports — Descrierea
SWFMorph::getShape2
SWFMovie::add
Ming


Adds any type of data to a movie

SWFMovie
SWFMovie::addExport
SWFMovie
PHP Manual

SWFMovie::add

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::add — Adds any type of data to a movie

Descrierea

mixed SWFMovie::add ( object $instance )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Adds an SWF object instance to the current movie.

Parametri

instance

Any type of object instance, like SWFShape, SWFText, SWFFont.

Valorile întoarse

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.

A se vedea ?i

  • 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 —

Descrierea

void SWFMovie::addExport ( SWFCharacter $char , string $name )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFMovie::add
SWFMovie::addFont
SWFMovie


SWFMovie::addExport
SWFMovie::__construct
SWFMovie
PHP Manual

SWFMovie::addFont

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::addFont —

Descrierea

mixed SWFMovie::addFont ( SWFFont $font )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

SWFMovie::__construct ([ int $version ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Creates a new movie object, representing an SWF movie.

Parametri

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 —

Descrierea

SWFSprite SWFMovie::importChar ( string $libswf , string $name )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • SWFMovie::importFont() - Descrierea

SWFMovie::__construct
SWFMovie::importFont
SWFMovie


SWFMovie::importChar
SWFMovie::labelFrame
SWFMovie
PHP Manual

SWFMovie::importFont

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::importFont —

Descrierea

SWFFontChar SWFMovie::importFont ( string $libswf , string $name )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • SWFMovie::importChar() - Descrierea

SWFMovie::importChar
SWFMovie::labelFrame
SWFMovie


Labels a frame

SWFMovie::importFont
SWFMovie::nextFrame
SWFMovie
PHP Manual

SWFMovie::labelFrame

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::labelFrame — Labels a frame

Descrierea

void SWFMovie::labelFrame ( string $label )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFMovie::importFont
SWFMovie::nextFrame
SWFMovie


Moves to the next frame of the animation

SWFMovie::labelFrame
SWFMovie::output
SWFMovie
PHP Manual

SWFMovie::nextFrame

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::nextFrame — Moves to the next frame of the animation

Descrierea

void SWFMovie::nextFrame ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Moves to the next frame of the animation.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFMovie::labelFrame
SWFMovie::output
SWFMovie


Dumps your lovingly prepared movie out

SWFMovie::nextFrame
SWFMovie::remove
SWFMovie
PHP Manual

SWFMovie::output

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::output — Dumps your lovingly prepared movie out

Descrierea

int SWFMovie::output ([ int $compression ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

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).

Valorile întoarse

Return the number of bytes written or FALSE on error.

Exemple

Example #1 Displaying your $movie in a browser

<?php
header('Content-type: application/x-shockwave-flash');
$movie->output();
?>

A se vedea ?i

  • SWFMovie::save() - Saves the SWF movie in a file
  • SWFMovie::saveToFile() - Descrierea

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, PHP 7, PECL ming SVN)

SWFMovie::remove — Removes the object instance from the display list

Descrierea

void SWFMovie::remove ( object $instance )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Removes the given object instance from the display list.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFMovie::save — Saves the SWF movie in a file

Descrierea

int SWFMovie::save ( string $filename [, int $compression = -1 ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Saves the SWF movie to the specified filename.

Parametri

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).

Valorile întoarse

Return the number of bytes written or FALSE on error.

A se vedea ?i

  • SWFMovie::output() - Dumps your lovingly prepared movie out
  • SWFMovie::saveToFile() - Descrierea

SWFMovie::remove
SWFMovie::saveToFile
SWFMovie


SWFMovie::save
SWFMovie::setbackground
SWFMovie
PHP Manual

SWFMovie::saveToFile

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::saveToFile —

Descrierea

int SWFMovie::saveToFile ( resource $x [, int $compression = -1 ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

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).

Valorile întoarse

Return the number of bytes written or FALSE on error.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFMovie::setbackground — Sets the background color

Descrierea

void SWFMovie::setbackground ( int $red , int $green , int $blue )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFMovie::saveToFile
SWFMovie::setDimension
SWFMovie


Sets the movie's width and height

SWFMovie::setbackground
SWFMovie::setFrames
SWFMovie
PHP Manual

SWFMovie::setDimension

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::setDimension — Sets the movie's width and height

Descrierea

void SWFMovie::setDimension ( float $width , float $height )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Sets the movie's dimension to the specified width and height.

Parametri

width

The movie width.

height

The movie height.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFMovie::setbackground
SWFMovie::setFrames
SWFMovie


Sets the total number of frames in the animation

SWFMovie::setDimension
SWFMovie::setRate
SWFMovie
PHP Manual

SWFMovie::setFrames

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::setFrames — Sets the total number of frames in the animation

Descrierea

void SWFMovie::setFrames ( int $number )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Sets the total number of frames in the animation to the given number.

Parametri

number

The number of frames.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFMovie::setDimension
SWFMovie::setRate
SWFMovie


Sets the animation's frame rate

SWFMovie::setFrames
SWFMovie::startSound
SWFMovie
PHP Manual

SWFMovie::setRate

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::setRate — Sets the animation's frame rate

Descrierea

void SWFMovie::setRate ( float $rate )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

rate

The frame rate, in frame per seconds.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFMovie::setFrames
SWFMovie::startSound
SWFMovie


SWFMovie::setRate
SWFMovie::stopSound
SWFMovie
PHP Manual

SWFMovie::startSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::startSound —

Descrierea

SWFSoundInstance SWFMovie::startSound ( SWFSound $sound )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • SWFMovie::stopSound() - Descrierea

SWFMovie::setRate
SWFMovie::stopSound
SWFMovie


SWFMovie::startSound
SWFMovie::streamMP3
SWFMovie
PHP Manual

SWFMovie::stopSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::stopSound —

Descrierea

void SWFMovie::stopSound ( SWFSound $sound )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • SWFMovie::startSound() - Descrierea

SWFMovie::startSound
SWFMovie::streamMP3
SWFMovie


Streams a MP3 file

SWFMovie::stopSound
SWFMovie::writeExports
SWFMovie
PHP Manual

SWFMovie::streamMP3

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::streamMP3 — Streams a MP3 file

Descrierea

int SWFMovie::streamMP3 ( mixed $mp3file [, float $skip = 0 ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

mp3file

Can be a file pointer returned by fopen() or the MP3 data, as a binary string.

skip

Number of seconds to skip.

Valorile întoarse

Return number of frames.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | skip added

Exemple

Example #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 —

Descrierea

void SWFMovie::writeExports ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFMovie::streamMP3
SWFPrebuiltClip
SWFMovie


The SWFPrebuiltClip class

(PHP 5.0.5-5.3.0, PHP 7, PECL ming SVN)

Introducere

SWFPrebuiltClip.

Sinopsisul clasei

SWFPrebuiltClip {
/* Metode */
__construct ( mixed $file )
}

Cuprins

  • 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, PHP 7, PECL ming SVN)

SWFPrebuiltClip::__construct — Returns a SWFPrebuiltClip object

Descrierea

SWFPrebuiltClip::__construct ( mixed $file )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

SWFPrebuiltClip
SWFShape
SWFPrebuiltClip


The SWFShape class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

SWFShape.

Sinopsisul clasei

SWFShape {
/* Metode */
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 )
}

Cuprins

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFShape::addFill — Adds a solid fill to the shape

Descrierea

SWFFill SWFShape::addFill ( int $red , int $green , int $blue [, int $alpha = 255 ] )
SWFFill addFill ( SWFBitmap $bitmap [, int $flags ] )
SWFFill addFill ( SWFGradient $gradient [, int $flags ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Exemple

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..

Example #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();
?>

A se vedea ?i

  • 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

Descrierea

SWFShape::__construct ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Created a new SWFShape object.

Exemple

This simple example will draw a big red elliptic quadrant.

Example #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 5 <= 5.3.0, PECL ming SVN)

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

Descrierea

void SWFShape::drawArc ( float $r , float $startAngle , float $endAngle )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawCircle — Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

Descrierea

void SWFShape::drawCircle ( float $r )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

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 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawCubic — Draws a cubic bezier curve using the current position and the three given points as control points

Descrierea

int SWFShape::drawCubic ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • 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

Descrierea

int SWFShape::drawCubicTo ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawCurve — Draws a curve (relative)

Descrierea

int SWFShape::drawCurve ( float $controldx , float $controldy , float $anchordx , float $anchordy [, float $targetdx ], float $targetdy )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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).

A se vedea ?i

  • SWFShape::drawCurve()

SWFShape::drawCubicTo
SWFShape::drawCurveTo
SWFShape


Draws a curve

SWFShape::drawCurve
SWFShape::drawGlyph
SWFShape
PHP Manual

SWFShape::drawCurveTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawCurveTo — Draws a curve

Descrierea

int SWFShape::drawCurveTo ( float $controlx , float $controly , float $anchorx , float $anchory [, float $targetx ], float $targety )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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).

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawGlyph — Draws the first character in the given string into the shape using the glyph definition from the given font

Descrierea

void SWFShape::drawGlyph ( SWFFont $font , string $character [, int $size ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFShape::drawCurveTo
SWFShape::drawLine
SWFShape


Draws a line (relative)

SWFShape::drawGlyph
SWFShape::drawLineTo
SWFShape
PHP Manual

SWFShape::drawLine

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawLine — Draws a line (relative)

Descrierea

void SWFShape::drawLine ( float $dx , float $dy )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swfshape::drawline() draws a line (using the current line style set by swfshape::setline()) from the current pen position to displacement (dx,dy).

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • SWFShape::drawLineTo() - Draws a line

SWFShape::drawGlyph
SWFShape::drawLineTo
SWFShape


Draws a line

SWFShape::drawLine
SWFShape::movePen
SWFShape
PHP Manual

SWFShape::drawLineTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawLineTo — Draws a line

Descrierea

void SWFShape::drawLineTo ( float $x , float $y )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFShape::movePen — Moves the shape's pen (relative)

Descrierea

void SWFShape::movePen ( float $dx , float $dy )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFShape::movePenTo — Moves the shape's pen

Descrierea

void SWFShape::movePenTo ( float $x , float $y )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swfshape::setrightfill() move the shape's pen to (x,y) in the shape's coordinate space.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFShape::setLeftFill — Sets left rasterizing color

Descrierea

void SWFShape::setLeftFill ( SWFGradient $fill )
void setLeftFill ( int $red , int $green , int $blue [, int $a ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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]));.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFShape::setLine — Sets the shape's line style

Descrierea

void SWFShape::setLine ( SWFShape $shape )
void setLine ( int $width , int $red , int $green , int $blue [, int $a ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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).

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

This simple example will draw a big "!#%*@", in funny colors and gracious style.

Example #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();
?>

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFShape::setLeftFill
SWFShape::setRightFill
SWFShape


Sets right rasterizing color

SWFShape::setLine
SWFSound
SWFShape
PHP Manual

SWFShape::setRightFill

(No version information available, might only be in Git)

SWFShape::setRightFill — Sets right rasterizing color

Descrierea

void SWFShape::setRightFill ( SWFGradient $fill )
void setRightFill ( int $red , int $green , int $blue [, int $a ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Shortcut for $swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • SWFShape::setLeftFill() - Sets left rasterizing color

SWFShape::setLine
SWFSound
SWFShape


The SWFSound class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

SWFSound.

Sinopsisul clasei

SWFSound {
/* Metode */
__construct ( string $filename [, int $flags = 0 ] )
}

Cuprins

  • 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

Descrierea

SWFSound::__construct ( string $filename [, int $flags = 0 ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

SWFSound
SWFSoundInstance
SWFSound


The SWFSoundInstance class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

SWFSoundInstance objects are returned by the SWFSprite::startSound() and SWFMovie::startSound() methods.

Sinopsisul clasei

SWFSoundInstance {
/* Metode */
void loopCount ( int $point )
void loopInPoint ( int $point )
void loopOutPoint ( int $point )
void noMultiple ( void )
}

Cuprins

  • SWFSoundInstance::loopCount — Descrierea
  • SWFSoundInstance::loopInPoint — Descrierea
  • SWFSoundInstance::loopOutPoint — Descrierea
  • SWFSoundInstance::noMultiple — Descrierea
SWFSound::__construct
SWFSoundInstance::loopCount
Ming


SWFSoundInstance
SWFSoundInstance::loopInPoint
SWFSoundInstance
PHP Manual

SWFSoundInstance::loopCount

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance::loopCount —

Descrierea

void SWFSoundInstance::loopCount ( int $point )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

point

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • SWFSoundInstance::loopOutPoint() - Descrierea

SWFSoundInstance
SWFSoundInstance::loopInPoint
SWFSoundInstance


SWFSoundInstance::loopCount
SWFSoundInstance::loopOutPoint
SWFSoundInstance
PHP Manual

SWFSoundInstance::loopInPoint

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance::loopInPoint —

Descrierea

void SWFSoundInstance::loopInPoint ( int $point )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

point

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • SWFSoundInstance::loopOutPoint() - Descrierea

SWFSoundInstance::loopCount
SWFSoundInstance::loopOutPoint
SWFSoundInstance


SWFSoundInstance::loopInPoint
SWFSoundInstance::noMultiple
SWFSoundInstance
PHP Manual

SWFSoundInstance::loopOutPoint

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance::loopOutPoint —

Descrierea

void SWFSoundInstance::loopOutPoint ( int $point )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

point

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • SWFSoundInstance::loopInPoint() - Descrierea

SWFSoundInstance::loopInPoint
SWFSoundInstance::noMultiple
SWFSoundInstance


SWFSoundInstance::loopOutPoint
SWFSprite
SWFSoundInstance
PHP Manual

SWFSoundInstance::noMultiple

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance::noMultiple —

Descrierea

void SWFSoundInstance::noMultiple ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFSoundInstance::loopOutPoint
SWFSprite
SWFSoundInstance


The SWFSprite class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

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.

Sinopsisul clasei

SWFSprite {
/* Metode */
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 )
}

Cuprins

  • SWFSprite::add — Adds an object to a sprite
  • SWFSprite::__construct — Creeaza un videoclip (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 — Descrierea
  • SWFSprite::stopSound — Descrierea
SWFSoundInstance::noMultiple
SWFSprite::add
Ming


Adds an object to a sprite

SWFSprite
SWFSprite::__construct
SWFSprite
PHP Manual

SWFSprite::add

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::add — Adds an object to a sprite

Descrierea

void SWFSprite::add ( object $object )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFSprite
SWFSprite::__construct
SWFSprite


Creeaza un videoclip (sprite)

SWFSprite::add
SWFSprite::labelFrame
SWFSprite
PHP Manual

SWFSprite::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::__construct — Creeaza un videoclip (sprite)

Descrierea

SWFSprite::__construct ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Creeaza un nou obiect SWFSprite.

SWFSprite::add
SWFSprite::labelFrame
SWFSprite


Labels frame

SWFSprite::__construct
SWFSprite::nextFrame
SWFSprite
PHP Manual

SWFSprite::labelFrame

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::labelFrame — Labels frame

Descrierea

void SWFSprite::labelFrame ( string $label )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFSprite::__construct
SWFSprite::nextFrame
SWFSprite


Moves to the next frame of the animation

SWFSprite::labelFrame
SWFSprite::remove
SWFSprite
PHP Manual

SWFSprite::nextFrame

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::nextFrame — Moves to the next frame of the animation

Descrierea

void SWFSprite::nextFrame ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swfsprite::setframes() moves to the next frame of the animation.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFSprite::labelFrame
SWFSprite::remove
SWFSprite


Removes an object to a sprite

SWFSprite::nextFrame
SWFSprite::setFrames
SWFSprite
PHP Manual

SWFSprite::remove

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::remove — Removes an object to a sprite

Descrierea

void SWFSprite::remove ( object $object )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swfsprite::remove() remove a swfshape(), a
swfbutton(), a swftext(),
a swfaction() or a swfsprite() object
from the sprite.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFSprite::nextFrame
SWFSprite::setFrames
SWFSprite


Sets the total number of frames in the animation

SWFSprite::remove
SWFSprite::startSound
SWFSprite
PHP Manual

SWFSprite::setFrames

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::setFrames — Sets the total number of frames in the animation

Descrierea

void SWFSprite::setFrames ( int $number )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swfsprite::setframes() sets the total number of frames in the animation to numberofframes.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFSprite::remove
SWFSprite::startSound
SWFSprite


SWFSprite::setFrames
SWFSprite::stopSound
SWFSprite
PHP Manual

SWFSprite::startSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::startSound —

Descrierea

SWFSoundInstance SWFSprite::startSound ( SWFSound $sount )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • SWFSprite::stopSound() - Descrierea

SWFSprite::setFrames
SWFSprite::stopSound
SWFSprite


SWFSprite::startSound
SWFText
SWFSprite
PHP Manual

SWFSprite::stopSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::stopSound —

Descrierea

void SWFSprite::stopSound ( SWFSound $sount )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • SWFSprite::startSound() - Descrierea

SWFSprite::startSound
SWFText
SWFSprite


The SWFText class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

SWFText.

Sinopsisul clasei

SWFText {
/* Metode */
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 )
}

Cuprins

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFText::addString — Draws a string

Descrierea

void SWFText::addString ( string $string )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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

Descrierea

void SWFText::addUTF8String ( string $text )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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

Descrierea

SWFText::__construct ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Creates a new SWFText object, fresh for manipulating.

Exemple

This simple example will draw a big yellow "PHP generates Flash with Ming" text, on white background.

Example #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 5 <= 5.3.0, PECL ming SVN)

SWFText::getAscent — Returns the ascent of the current font at its current size, or 0 if not available

Descrierea

float SWFText::getAscent ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFText::getDescent — Returns the descent of the current font at its current size, or 0 if not available

Descrierea

float SWFText::getDescent ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFText::getLeading — Returns the leading of the current font at its current size, or 0 if not available

Descrierea

float SWFText::getLeading ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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

Descrierea

float SWFText::getUTF8Width ( string $string )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFText::getWidth — Computes string's width

Descrierea

float SWFText::getWidth ( string $string )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Returns the rendered width of the string at the text object's current font, scale, and spacing settings.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFText::moveTo — Moves the pen

Descrierea

void SWFText::moveTo ( float $x , float $y )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFText::getWidth
SWFText::setColor
SWFText


Sets the current text color

SWFText::moveTo
SWFText::setFont
SWFText
PHP Manual

SWFText::setColor

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::setColor — Sets the current text color

Descrierea

void SWFText::setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Changes the current text color.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFText::moveTo
SWFText::setFont
SWFText


Sets the current font

SWFText::setColor
SWFText::setHeight
SWFText
PHP Manual

SWFText::setFont

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::setFont — Sets the current font

Descrierea

void SWFText::setFont ( SWFFont $font )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swftext::setfont() sets the current font to font.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFText::setColor
SWFText::setHeight
SWFText


Sets the current font height

SWFText::setFont
SWFText::setSpacing
SWFText
PHP Manual

SWFText::setHeight

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::setHeight — Sets the current font height

Descrierea

void SWFText::setHeight ( float $height )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swftext::setheight() sets the current font height to height. Default is 240.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFText::setFont
SWFText::setSpacing
SWFText


Sets the current font spacing

SWFText::setHeight
SWFTextField
SWFText
PHP Manual

SWFText::setSpacing

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::setSpacing — Sets the current font spacing

Descrierea

void SWFText::setSpacing ( float $spacing )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFText::setHeight
SWFTextField
SWFText


The SWFTextField class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introducere

SWFTextField.

Sinopsisul clasei

SWFTextField {
/* Metode */
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 )
}

Cuprins

  • 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

Descrierea

void SWFTextField::addChars ( string $chars )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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 5 <= 5.3.0, PECL ming SVN)

SWFTextField::addString — Concatenates the given string to the text field

Descrierea

void SWFTextField::addString ( string $string )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swftextfield::setname() concatenates the string string to the text field.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFTextField::addChars
SWFTextField::align
SWFTextField


Sets the text field alignment

SWFTextField::addString
SWFTextField::__construct
SWFTextField
PHP Manual

SWFTextField::align

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::align — Sets the text field alignment

Descrierea

void SWFTextField::align ( int $alignement )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

SWFTextField::__construct ([ int $flags ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setBounds — Sets the text field width and height

Descrierea

void SWFTextField::setBounds ( float $width , float $height )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFTextField::__construct
SWFTextField::setColor
SWFTextField


Sets the color of the text field

SWFTextField::setBounds
SWFTextField::setFont
SWFTextField
PHP Manual

SWFTextField::setColor

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setColor — Sets the color of the text field

Descrierea

void SWFTextField::setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swftextfield::setcolor() sets the color of the text field. Default is fully opaque black. Color is represented using RGB system.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFTextField::setBounds
SWFTextField::setFont
SWFTextField


Sets the text field font

SWFTextField::setColor
SWFTextField::setHeight
SWFTextField
PHP Manual

SWFTextField::setFont

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setFont — Sets the text field font

Descrierea

void SWFTextField::setFont ( SWFFont $font )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swftextfield::setfont() sets the text field font to the [browser-defined?] font font.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFTextField::setColor
SWFTextField::setHeight
SWFTextField


Sets the font height of this text field font

SWFTextField::setFont
SWFTextField::setIndentation
SWFTextField
PHP Manual

SWFTextField::setHeight

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setHeight — Sets the font height of this text field font

Descrierea

void SWFTextField::setHeight ( float $height )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swftextfield::setheight() sets the font height of this text field font to the given height height. Default is 240.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFTextField::setFont
SWFTextField::setIndentation
SWFTextField


Sets the indentation of the first line

SWFTextField::setHeight
SWFTextField::setLeftMargin
SWFTextField
PHP Manual

SWFTextField::setIndentation

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setIndentation — Sets the indentation of the first line

Descrierea

void SWFTextField::setIndentation ( float $width )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swftextfield::setindentation() sets the indentation of the first line in the text field, to width.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFTextField::setHeight
SWFTextField::setLeftMargin
SWFTextField


Sets the left margin width of the text field

SWFTextField::setIndentation
SWFTextField::setLineSpacing
SWFTextField
PHP Manual

SWFTextField::setLeftMargin

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setLeftMargin — Sets the left margin width of the text field

Descrierea

void SWFTextField::setLeftMargin ( float $width )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swftextfield::setleftmargin() sets the left margin width of the text field to width. Default is 0.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFTextField::setIndentation
SWFTextField::setLineSpacing
SWFTextField


Sets the line spacing of the text field

SWFTextField::setLeftMargin
SWFTextField::setMargins
SWFTextField
PHP Manual

SWFTextField::setLineSpacing

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setLineSpacing — Sets the line spacing of the text field

Descrierea

void SWFTextField::setLineSpacing ( float $height )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swftextfield::setlinespacing() sets the line spacing of the text field to the height of height. Default is 40.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFTextField::setLeftMargin
SWFTextField::setMargins
SWFTextField


Sets the margins width of the text field

SWFTextField::setLineSpacing
SWFTextField::setName
SWFTextField
PHP Manual

SWFTextField::setMargins

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setMargins — Sets the margins width of the text field

Descrierea

void SWFTextField::setMargins ( float $left , float $right )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swftextfield::setmargins() set both margins at once, for the man on the go.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFTextField::setLineSpacing
SWFTextField::setName
SWFTextField


Sets the variable name

SWFTextField::setMargins
SWFTextField::setPadding
SWFTextField
PHP Manual

SWFTextField::setName

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setName — Sets the variable name

Descrierea

void SWFTextField::setName ( string $name )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swftextfield::setname() sets the variable name of this text field to name, for form posting and action scripting purposes.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

void SWFTextField::setPadding ( float $padding )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFTextField::setName
SWFTextField::setRightMargin
SWFTextField


Sets the right margin width of the text field

SWFTextField::setPadding
SWFVideoStream
SWFTextField
PHP Manual

SWFTextField::setRightMargin

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setRightMargin — Sets the right margin width of the text field

Descrierea

void SWFTextField::setRightMargin ( float $width )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

swftextfield::setrightmargin() sets the right margin width of the text field to width. Default is 0.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFTextField::setPadding
SWFVideoStream
SWFTextField


The SWFVideoStream class

(PHP 5.0.5-5.3.0, PHP 7, PECL ming SVN)

Introducere

SWFVideoStream.

Sinopsisul clasei

SWFVideoStream {
/* Metode */
__construct ([ string $file ] )
int getNumFrames ( void )
void setDimension ( int $x , int $y )
}

Cuprins

  • 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, PHP 7, PECL ming SVN)

SWFVideoStream::__construct — Returns a SWFVideoStream object

Descrierea

SWFVideoStream::__construct ([ string $file ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

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, PHP 7, PECL ming SVN)

SWFVideoStream::getNumFrames — Returns the number of frames in the video

Descrierea

int SWFVideoStream::getNumFrames ( void )

This function returns the number of video-frames of a SWFVideoStream.

Valorile întoarse

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, PHP 7, PECL ming SVN)

SWFVideoStream::setDimension — Sets video dimension

Descrierea

void SWFVideoStream::setDimension ( int $x , int $y )

Sets the width and height for streamed videos.

Parametri

x

Width in pixels.

y

Height in pixels.

Valorile întoarse

Nu este întoarsa nici o valoare.

SWFVideoStream::getNumFrames
PDF
SWFVideoStream


PDF

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic Usage Examples
  • PDF Func?ii
    • PDF_activate_item — Activeaza un element de structura sau un alt element de con?inut
    • PDF_add_annotation — Adauga o adnotare [învechit]
    • PDF_add_bookmark — Adauga un semn de carte pentru pagina curenta [învechit]
    • PDF_add_launchlink — Adauga o adnotare de lansare pentru pagina curenta [învechit]
    • PDF_add_locallink — Adauga o adnotare de referin?a pentru pagina curenta [învechit]
    • PDF_add_nameddest — Creeaza o destina?ie cu denumire
    • PDF_add_note — Stabile?te o adnotare pentru pagina curenta [învechit]
    • PDF_add_outline — Adauga un semn de carte pentru pagina curenta [învechit]
    • PDF_add_pdflink — Adauga o adnotare-referin?a catre fi?ier pentru pagina curenta [învechit]
    • PDF_add_table_cell — Adauga o celula catre un tabel nou sau existent
    • PDF_add_textflow — Creaza un Textflow sau adauga text catre un Textflow existent
    • PDF_add_thumbnail — Adauga o miniatura pentru pagina curenta
    • PDF_add_weblink — Adauga o referin?a web pentru pagina curenta [învechit]
    • PDF_arc — Deseneaza un segment de arc de circumferin?a contra sensului acelor de ceasornic
    • PDF_arcn — Deseneaza un segment de arc de circumferin?a în sensul acelor de ceasornic
    • PDF_attach_file — Adauga un fi?ier ata?at la pagina curenta [învechit]
    • PDF_begin_document — Creeaza un fi?ier PDF nou
    • PDF_begin_font — Începe o defini?ie de font de Tip 3
    • PDF_begin_glyph — Începe o defini?ie de simbol pentru un font de Tip 3
    • PDF_begin_item — Deschide un element de structura sau un alt element de con?inut
    • PDF_begin_layer — Începe un strat
    • PDF_begin_page_ext — Începe o pagina noua
    • PDF_begin_page — Începe o pagina noua [învechit]
    • PDF_begin_pattern — Începe defini?ia unui tipar
    • PDF_begin_template_ext — Începe defini?ia unui tipar
    • PDF_begin_template — Începe defini?ia unui tipar [învechit]
    • PDF_circle — Deseneaza un cerc
    • PDF_clip — Taie conform caii curente
    • PDF_close_image — Închide o imagine
    • PDF_close_pdi_page — Închide handle-ul paginii
    • PDF_close_pdi — Închide documentul PDF de intrare [învechit]
    • PDF_close — Închite resursa PDF [învechit]
    • PDF_closepath_fill_stroke — Închide, umple ?i traseaza calea curenta
    • PDF_closepath_stroke — Închide ?i traseaza calea
    • PDF_closepath — Închide calea curenta
    • PDF_concat — Concateneaza o matrice la MCT
    • PDF_continue_text — Afi?eaza textul în linia urmatoare
    • PDF_create_3dview — Creeaza o imagine 3D
    • PDF_create_action — Creeaza ac?iuni pentru obiecte sau evenimente
    • PDF_create_annotation — Creeaza o adnotare dreptunghiulara
    • PDF_create_bookmark — Creeaza un semn de carte
    • PDF_create_field — Creeaza un câmp în formular
    • PDF_create_fieldgroup — Creeaza un grup de câmpuri de formular
    • PDF_create_gstate — Creeaza un obiect de stare grafica
    • PDF_create_pvf — Creeaza un fi?ier virtual PDFlib
    • PDF_create_textflow — Creeaza un obiect textflow
    • PDF_curveto — Deseneaza o curba Bezier
    • PDF_define_layer — Creeaza o defini?ie a stratului
    • PDF_delete_pvf — Elimina un fi?ier virtual PDFlib
    • PDF_delete_table — Elimina un obiect-tabel
    • PDF_delete_textflow — Elimina un obiect textflow
    • PDF_delete — Elimina un obiect PDFlib
    • PDF_encoding_set_char — Adauga denumirea unui simbol ?i/sau valoarea Unicode
    • PDF_end_document — Închide un fi?ier PDF
    • PDF_end_font — Încheie o defini?ie de font te Tip 3
    • PDF_end_glyph — Încheie o defini?ie a simbolului pentru un font de Tip 3
    • PDF_end_item — Închide un element de structura sau un alt element de con?inut
    • PDF_end_layer — Dezactiveaza toate straturile active
    • PDF_end_page_ext — Încheie o pagina
    • PDF_end_page — Încheie o pagina
    • PDF_end_pattern — Încheie un tipar
    • PDF_end_template — Încheie un ?ablon
    • PDF_endpath — Încheie calea curenta
    • PDF_fill_imageblock — Umple un bloc de imagine cu date variabile
    • PDF_fill_pdfblock — Umple un bloc PDF cu date variabile
    • PDF_fill_stroke — Umple ?i traseaza o cale
    • PDF_fill_textblock — Umple un bloc de text cu date variabile
    • PDF_fill — Umple calea curenta
    • PDF_findfont — Pregate?te un font pentru utilizarea sa ulterioara [învechit]
    • PDF_fit_image — Plaseaza o imagine sau un ?ablon
    • PDF_fit_pdi_page — Plaseaza o pagina PDF importata
    • PDF_fit_table — Plaseaza un tabel pe pagina
    • PDF_fit_textflow — Formateaza un textflow într-o zona dreptunghiulara
    • PDF_fit_textline — Plaseaza o singura linie de text
    • PDF_get_apiname — Ob?ine denumirea func?iei API care a e?uat
    • PDF_get_buffer — Ob?ine zona-tampon de ie?ire a PDF
    • PDF_get_errmsg — Ob?ine textul erorii
    • PDF_get_errnum — Ob?ine numarul erorii
    • PDF_get_font — Ob?ine fontul [învechit]
    • PDF_get_fontname — Ob?ine denumirea fontului [învechit]
    • PDF_get_fontsize — Manipularea fontului [învechit]
    • PDF_get_image_height — Ob?ine înal?imea imaginii [învechit]
    • PDF_get_image_width — Ob?ine la?imea imaginii [învechit]
    • PDF_get_majorversion — Ob?ine numarul major al versiunii [învechit]
    • PDF_get_minorversion — Ob?ine numarul minor al versiunii [învechit]
    • PDF_get_parameter — Ob?ine un parametru string
    • PDF_get_pdi_parameter — Ob?ine un parametru string al PDI [învechit]
    • PDF_get_pdi_value — Ob?ine un parametru numeric PDI [învechit]
    • PDF_get_value — Ob?ine un parametru numeric
    • PDF_info_font — Transmite o interpelare a informa?iilor detaliate despre un font încarcat
    • PDF_info_matchbox — Transmite o interpelare despre informa?ia matchbox
    • PDF_info_table — Ob?ine informa?ii despre tabel
    • PDF_info_textflow — Interpeleaza starea textflow
    • PDF_info_textline — Efectueaza formatarea unei linii de text ?i interpeleaza metricile
    • PDF_initgraphics — Restabile?te starea grafica
    • PDF_lineto — Deseneaza o linie
    • PDF_load_3ddata — Încarca un model 3D
    • PDF_load_font — Cauta ?i pregate?te un font
    • PDF_load_iccprofile — Cauta ?i pregate?te un profil ICC
    • PDF_load_image — Deschide un fi?ier cu imagine
    • PDF_makespotcolor — Creeaza o culoare a punctului
    • PDF_moveto — Stabile?te punctul curent
    • PDF_new — Creeaza un obiect PDFlib
    • PDF_open_ccitt — Deschide o imagine bruta CCITT [învechit]
    • PDF_open_file — Creeaza un fi?ier PDF [învechit]
    • PDF_open_gif — Deschide o imagine GIF [învechit]
    • PDF_open_image_file — Cite?te o imagine dintr-un fi?ier [învechit]
    • PDF_open_image — Utilizeaza datele imaginii [învechit]
    • PDF_open_jpeg — Deschide o imagine JPEG [învechit]
    • PDF_open_memory_image — Deschide o imagine creata cu func?iile de imagini ale PHP [nu este sus?inut]
    • PDF_open_pdi_document — Prepare a pdi document
    • PDF_open_pdi_page — Pregate?te o pagina
    • PDF_open_pdi — Deschide un fi?ier PDF [învechit]
    • PDF_open_tiff — Deschide o imagine TIFF [învechit]
    • PDF_pcos_get_number — Ob?ine valoarea unei cai pCOS, de tip numeric sau boolean
    • PDF_pcos_get_stream — Ob?ine con?inutul unei cai pCOS, de tip stream, fstream sau string
    • PDF_pcos_get_string — Ob?ine valoarea unei cai pCOS, de tip name, string sau boolean
    • PDF_place_image — Plaseaza o imagine pe pagina [învechit]
    • PDF_place_pdi_page — Plaseaza o pagina PDF [învechit]
    • PDF_process_pdi — Proceseaza un document PDF importat
    • PDF_rect — Deseneaza un dreptunghi
    • PDF_restore — Restabile?te starea grafica
    • PDF_resume_page — Continua o pagina
    • PDF_rotate — Rote?te sistemul de coordonate
    • PDF_save — Salveaza starea grafica
    • PDF_scale — Modifica scara sistemului de coordonate
    • PDF_set_border_color — Stabile?te culoarea bordurii adnotarilor [învechit]
    • PDF_set_border_dash — Stabile?te stilul liniei bordurii adnotarilor [învechit]
    • PDF_set_border_style — Stabile?te stilul bordurii adnotarilor [învechit]
    • PDF_set_char_spacing — Stabile?te spa?ierea dintre caractere [învechit]
    • PDF_set_duration — Stabile?te durata dintre pagini [învechit]
    • PDF_set_gstate — Activeaza obiectul starii grafice
    • PDF_set_horiz_scaling — Stabile?te marimea scarii textului pe orizontala [învechit]
    • PDF_set_info_author — Completeaza câmpul documentului cu informa?ia despre autor [învechit]
    • PDF_set_info_creator — Completeaza câmpul documentului cu informa?ia despre creator [învechit]
    • PDF_set_info_keywords — Completeaza câmpul documentului cu cuvintele-cheie [învechit]
    • PDF_set_info_subject — Completeaza câmpul documentului cu subiectul [învechit]
    • PDF_set_info_title — Completeaza câmpul documentului cu titlul [învechit]
    • PDF_set_info — Completeaza un câmp informa?ional al documentului
    • PDF_set_layer_dependency — Define?te rela?iile dintre straturi
    • PDF_set_leading — Stabile?te distan?a dintre liniile de text [învechit]
    • PDF_set_parameter — Stabile?te un parametru string
    • PDF_set_text_matrix — Stabile?te matricea textului [învechit]
    • PDF_set_text_pos — Stabile?te pozi?ia textului
    • PDF_set_text_rendering — Determina redarea textului [învechit]
    • PDF_set_text_rise — Stabile?te înal?area textului [învechit]
    • PDF_set_value — Stabile?te un parametru numeric
    • PDF_set_word_spacing — Stabile?te spa?ierea dintre cuvinte [învechit]
    • PDF_setcolor — Stabile?te culorile de umplere ?i de trasare
    • PDF_setdash — Stabile?te un tipar al liniei obi?nuit
    • PDF_setdashpattern — Stabile?te tiparul liniei
    • PDF_setflat — Stabile?te platitudinea
    • PDF_setfont — Stabile?te fontul
    • PDF_setgray_fill — Stabile?te culoarea de umplere în sur [învechit]
    • PDF_setgray_stroke — Stabile?te culoarea de trasare în sur [învechit]
    • PDF_setgray — Stabile?te culoarea în sur [învechit]
    • PDF_setlinecap — Stabile?te parametrul capului de linie
    • PDF_setlinejoin — Stabile?te parametrul linejoin
    • PDF_setlinewidth — Stabile?te grosimea liniei
    • PDF_setmatrix — Stabile?te matricea curenta de transformare
    • PDF_setmiterlimit — Stabile?te limita mitrei
    • PDF_setpolydash — Stabile?te un tipar al liniei complicat [învechit]
    • PDF_setrgbcolor_fill — Stabile?te valorile rgb ale culorii de umplere [învechit]
    • PDF_setrgbcolor_stroke — Stabile?te valorile rgb ale culorii de trasare [învechit]
    • PDF_setrgbcolor — Stabile?te valorile rgb ale culorilor de umplere ?i de trasare [învechit]
    • PDF_shading_pattern — Define?te tiparul de umbrire
    • PDF_shading — Define?te amestecarea
    • PDF_shfill — Umple o regiune cu umbrire
    • PDF_show_boxed — Afi?eaza un text într-o caseta [învechit]
    • PDF_show_xy — Afi?eaza un text la pozi?ia data
    • PDF_show — Afi?eaza un text în pozi?ia curenta
    • PDF_skew — Deformeaza oblic sistemul de coordonate
    • PDF_stringwidth — Întoarce la?imea textului
    • PDF_stroke — Traseaza o cale
    • PDF_suspend_page — Suspendeaza o pagina
    • PDF_translate — Stabile?te originea sistemului de coordonate
    • PDF_utf16_to_utf8 — Converte?te un string din UTF-16 în UTF-8
    • PDF_utf32_to_utf16 — Converte?te un string din UTF-32 în UTF-16
    • PDF_utf8_to_utf16 — Converte?te un string din UTF-8 în UTF-16
SWFVideoStream::setDimension
Introducere
Ie?iri MIME non-textuale


Introducere

The PDF functions in PHP can create PDF files using the PDFlib library from PDFlib GmbH (» www.pdflib.com). A restricted version called PDFlib Lite 7 is available for free, but it is no longer maintained since 2010. PDFlib integration for PHP is still actively maintained by PDFlib GmbH. It is mainly targeted at the commercial PDFlib versions, but can also be used for the old PDFlib Lite.

If you want to use PDFlib we urge you start with the examples which are included in all PDFlib packages, and refer to the extensive manuals in PDF format which are also included. At a minimum you should take a look at the hello.php sample to learn basic setup for PDFlib usage.

Nota:

If you're interested in alternative free PDF generators that do not utilize external PDF libraries, see this related FAQ.

PDF
Instalarea / configurarea
PDF


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
PDF


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP. Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/pdflib.

Pentru ca aceste func?ii sa lucreze în PHP < 4.3.9, trebuie sa compila?i PHP cu op?iunea --with-pdflib[=DIR] . DIR este directorul de baza de instalare al PDFlib, valoarea implicita este /usr/local.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

PDF_new() creates a new PDFlib object required by most PDF functions.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
PDF


Exemple

Cuprins

  • Basic Usage Examples
Constante predefinite
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)".

Example #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)".

Example #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;
?>

Exemple
PDF Func?ii
Exemple


PDF Func?ii

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.

Cuprins

  • PDF_activate_item — Activeaza un element de structura sau un alt element de con?inut
  • PDF_add_annotation — Adauga o adnotare [învechit]
  • PDF_add_bookmark — Adauga un semn de carte pentru pagina curenta [învechit]
  • PDF_add_launchlink — Adauga o adnotare de lansare pentru pagina curenta [învechit]
  • PDF_add_locallink — Adauga o adnotare de referin?a pentru pagina curenta [învechit]
  • PDF_add_nameddest — Creeaza o destina?ie cu denumire
  • PDF_add_note — Stabile?te o adnotare pentru pagina curenta [învechit]
  • PDF_add_outline — Adauga un semn de carte pentru pagina curenta [învechit]
  • PDF_add_pdflink — Adauga o adnotare-referin?a catre fi?ier pentru pagina curenta [învechit]
  • PDF_add_table_cell — Adauga o celula catre un tabel nou sau existent
  • PDF_add_textflow — Creaza un Textflow sau adauga text catre un Textflow existent
  • PDF_add_thumbnail — Adauga o miniatura pentru pagina curenta
  • PDF_add_weblink — Adauga o referin?a web pentru pagina curenta [învechit]
  • PDF_arc — Deseneaza un segment de arc de circumferin?a contra sensului acelor de ceasornic
  • PDF_arcn — Deseneaza un segment de arc de circumferin?a în sensul acelor de ceasornic
  • PDF_attach_file — Adauga un fi?ier ata?at la pagina curenta [învechit]
  • PDF_begin_document — Creeaza un fi?ier PDF nou
  • PDF_begin_font — Începe o defini?ie de font de Tip 3
  • PDF_begin_glyph — Începe o defini?ie de simbol pentru un font de Tip 3
  • PDF_begin_item — Deschide un element de structura sau un alt element de con?inut
  • PDF_begin_layer — Începe un strat
  • PDF_begin_page_ext — Începe o pagina noua
  • PDF_begin_page — Începe o pagina noua [învechit]
  • PDF_begin_pattern — Începe defini?ia unui tipar
  • PDF_begin_template_ext — Începe defini?ia unui tipar
  • PDF_begin_template — Începe defini?ia unui tipar [învechit]
  • PDF_circle — Deseneaza un cerc
  • PDF_clip — Taie conform caii curente
  • PDF_close_image — Închide o imagine
  • PDF_close_pdi_page — Închide handle-ul paginii
  • PDF_close_pdi — Închide documentul PDF de intrare [învechit]
  • PDF_close — Închite resursa PDF [învechit]
  • PDF_closepath_fill_stroke — Închide, umple ?i traseaza calea curenta
  • PDF_closepath_stroke — Închide ?i traseaza calea
  • PDF_closepath — Închide calea curenta
  • PDF_concat — Concateneaza o matrice la MCT
  • PDF_continue_text — Afi?eaza textul în linia urmatoare
  • PDF_create_3dview — Creeaza o imagine 3D
  • PDF_create_action — Creeaza ac?iuni pentru obiecte sau evenimente
  • PDF_create_annotation — Creeaza o adnotare dreptunghiulara
  • PDF_create_bookmark — Creeaza un semn de carte
  • PDF_create_field — Creeaza un câmp în formular
  • PDF_create_fieldgroup — Creeaza un grup de câmpuri de formular
  • PDF_create_gstate — Creeaza un obiect de stare grafica
  • PDF_create_pvf — Creeaza un fi?ier virtual PDFlib
  • PDF_create_textflow — Creeaza un obiect textflow
  • PDF_curveto — Deseneaza o curba Bezier
  • PDF_define_layer — Creeaza o defini?ie a stratului
  • PDF_delete_pvf — Elimina un fi?ier virtual PDFlib
  • PDF_delete_table — Elimina un obiect-tabel
  • PDF_delete_textflow — Elimina un obiect textflow
  • PDF_delete — Elimina un obiect PDFlib
  • PDF_encoding_set_char — Adauga denumirea unui simbol ?i/sau valoarea Unicode
  • PDF_end_document — Închide un fi?ier PDF
  • PDF_end_font — Încheie o defini?ie de font te Tip 3
  • PDF_end_glyph — Încheie o defini?ie a simbolului pentru un font de Tip 3
  • PDF_end_item — Închide un element de structura sau un alt element de con?inut
  • PDF_end_layer — Dezactiveaza toate straturile active
  • PDF_end_page_ext — Încheie o pagina
  • PDF_end_page — Încheie o pagina
  • PDF_end_pattern — Încheie un tipar
  • PDF_end_template — Încheie un ?ablon
  • PDF_endpath — Încheie calea curenta
  • PDF_fill_imageblock — Umple un bloc de imagine cu date variabile
  • PDF_fill_pdfblock — Umple un bloc PDF cu date variabile
  • PDF_fill_stroke — Umple ?i traseaza o cale
  • PDF_fill_textblock — Umple un bloc de text cu date variabile
  • PDF_fill — Umple calea curenta
  • PDF_findfont — Pregate?te un font pentru utilizarea sa ulterioara [învechit]
  • PDF_fit_image — Plaseaza o imagine sau un ?ablon
  • PDF_fit_pdi_page — Plaseaza o pagina PDF importata
  • PDF_fit_table — Plaseaza un tabel pe pagina
  • PDF_fit_textflow — Formateaza un textflow într-o zona dreptunghiulara
  • PDF_fit_textline — Plaseaza o singura linie de text
  • PDF_get_apiname — Ob?ine denumirea func?iei API care a e?uat
  • PDF_get_buffer — Ob?ine zona-tampon de ie?ire a PDF
  • PDF_get_errmsg — Ob?ine textul erorii
  • PDF_get_errnum — Ob?ine numarul erorii
  • PDF_get_font — Ob?ine fontul [învechit]
  • PDF_get_fontname — Ob?ine denumirea fontului [învechit]
  • PDF_get_fontsize — Manipularea fontului [învechit]
  • PDF_get_image_height — Ob?ine înal?imea imaginii [învechit]
  • PDF_get_image_width — Ob?ine la?imea imaginii [învechit]
  • PDF_get_majorversion — Ob?ine numarul major al versiunii [învechit]
  • PDF_get_minorversion — Ob?ine numarul minor al versiunii [învechit]
  • PDF_get_parameter — Ob?ine un parametru string
  • PDF_get_pdi_parameter — Ob?ine un parametru string al PDI [învechit]
  • PDF_get_pdi_value — Ob?ine un parametru numeric PDI [învechit]
  • PDF_get_value — Ob?ine un parametru numeric
  • PDF_info_font — Transmite o interpelare a informa?iilor detaliate despre un font încarcat
  • PDF_info_matchbox — Transmite o interpelare despre informa?ia matchbox
  • PDF_info_table — Ob?ine informa?ii despre tabel
  • PDF_info_textflow — Interpeleaza starea textflow
  • PDF_info_textline — Efectueaza formatarea unei linii de text ?i interpeleaza metricile
  • PDF_initgraphics — Restabile?te starea grafica
  • PDF_lineto — Deseneaza o linie
  • PDF_load_3ddata — Încarca un model 3D
  • PDF_load_font — Cauta ?i pregate?te un font
  • PDF_load_iccprofile — Cauta ?i pregate?te un profil ICC
  • PDF_load_image — Deschide un fi?ier cu imagine
  • PDF_makespotcolor — Creeaza o culoare a punctului
  • PDF_moveto — Stabile?te punctul curent
  • PDF_new — Creeaza un obiect PDFlib
  • PDF_open_ccitt — Deschide o imagine bruta CCITT [învechit]
  • PDF_open_file — Creeaza un fi?ier PDF [învechit]
  • PDF_open_gif — Deschide o imagine GIF [învechit]
  • PDF_open_image_file — Cite?te o imagine dintr-un fi?ier [învechit]
  • PDF_open_image — Utilizeaza datele imaginii [învechit]
  • PDF_open_jpeg — Deschide o imagine JPEG [învechit]
  • PDF_open_memory_image — Deschide o imagine creata cu func?iile de imagini ale PHP [nu este sus?inut]
  • PDF_open_pdi_document — Prepare a pdi document
  • PDF_open_pdi_page — Pregate?te o pagina
  • PDF_open_pdi — Deschide un fi?ier PDF [învechit]
  • PDF_open_tiff — Deschide o imagine TIFF [învechit]
  • PDF_pcos_get_number — Ob?ine valoarea unei cai pCOS, de tip numeric sau boolean
  • PDF_pcos_get_stream — Ob?ine con?inutul unei cai pCOS, de tip stream, fstream sau string
  • PDF_pcos_get_string — Ob?ine valoarea unei cai pCOS, de tip name, string sau boolean
  • PDF_place_image — Plaseaza o imagine pe pagina [învechit]
  • PDF_place_pdi_page — Plaseaza o pagina PDF [învechit]
  • PDF_process_pdi — Proceseaza un document PDF importat
  • PDF_rect — Deseneaza un dreptunghi
  • PDF_restore — Restabile?te starea grafica
  • PDF_resume_page — Continua o pagina
  • PDF_rotate — Rote?te sistemul de coordonate
  • PDF_save — Salveaza starea grafica
  • PDF_scale — Modifica scara sistemului de coordonate
  • PDF_set_border_color — Stabile?te culoarea bordurii adnotarilor [învechit]
  • PDF_set_border_dash — Stabile?te stilul liniei bordurii adnotarilor [învechit]
  • PDF_set_border_style — Stabile?te stilul bordurii adnotarilor [învechit]
  • PDF_set_char_spacing — Stabile?te spa?ierea dintre caractere [învechit]
  • PDF_set_duration — Stabile?te durata dintre pagini [învechit]
  • PDF_set_gstate — Activeaza obiectul starii grafice
  • PDF_set_horiz_scaling — Stabile?te marimea scarii textului pe orizontala [învechit]
  • PDF_set_info_author — Completeaza câmpul documentului cu informa?ia despre autor [învechit]
  • PDF_set_info_creator — Completeaza câmpul documentului cu informa?ia despre creator [învechit]
  • PDF_set_info_keywords — Completeaza câmpul documentului cu cuvintele-cheie [învechit]
  • PDF_set_info_subject — Completeaza câmpul documentului cu subiectul [învechit]
  • PDF_set_info_title — Completeaza câmpul documentului cu titlul [învechit]
  • PDF_set_info — Completeaza un câmp informa?ional al documentului
  • PDF_set_layer_dependency — Define?te rela?iile dintre straturi
  • PDF_set_leading — Stabile?te distan?a dintre liniile de text [învechit]
  • PDF_set_parameter — Stabile?te un parametru string
  • PDF_set_text_matrix — Stabile?te matricea textului [învechit]
  • PDF_set_text_pos — Stabile?te pozi?ia textului
  • PDF_set_text_rendering — Determina redarea textului [învechit]
  • PDF_set_text_rise — Stabile?te înal?area textului [învechit]
  • PDF_set_value — Stabile?te un parametru numeric
  • PDF_set_word_spacing — Stabile?te spa?ierea dintre cuvinte [învechit]
  • PDF_setcolor — Stabile?te culorile de umplere ?i de trasare
  • PDF_setdash — Stabile?te un tipar al liniei obi?nuit
  • PDF_setdashpattern — Stabile?te tiparul liniei
  • PDF_setflat — Stabile?te platitudinea
  • PDF_setfont — Stabile?te fontul
  • PDF_setgray_fill — Stabile?te culoarea de umplere în sur [învechit]
  • PDF_setgray_stroke — Stabile?te culoarea de trasare în sur [învechit]
  • PDF_setgray — Stabile?te culoarea în sur [învechit]
  • PDF_setlinecap — Stabile?te parametrul capului de linie
  • PDF_setlinejoin — Stabile?te parametrul linejoin
  • PDF_setlinewidth — Stabile?te grosimea liniei
  • PDF_setmatrix — Stabile?te matricea curenta de transformare
  • PDF_setmiterlimit — Stabile?te limita mitrei
  • PDF_setpolydash — Stabile?te un tipar al liniei complicat [învechit]
  • PDF_setrgbcolor_fill — Stabile?te valorile rgb ale culorii de umplere [învechit]
  • PDF_setrgbcolor_stroke — Stabile?te valorile rgb ale culorii de trasare [învechit]
  • PDF_setrgbcolor — Stabile?te valorile rgb ale culorilor de umplere ?i de trasare [învechit]
  • PDF_shading_pattern — Define?te tiparul de umbrire
  • PDF_shading — Define?te amestecarea
  • PDF_shfill — Umple o regiune cu umbrire
  • PDF_show_boxed — Afi?eaza un text într-o caseta [învechit]
  • PDF_show_xy — Afi?eaza un text la pozi?ia data
  • PDF_show — Afi?eaza un text în pozi?ia curenta
  • PDF_skew — Deformeaza oblic sistemul de coordonate
  • PDF_stringwidth — Întoarce la?imea textului
  • PDF_stroke — Traseaza o cale
  • PDF_suspend_page — Suspendeaza o pagina
  • PDF_translate — Stabile?te originea sistemului de coordonate
  • PDF_utf16_to_utf8 — Converte?te un string din UTF-16 în UTF-8
  • PDF_utf32_to_utf16 — Converte?te un string din UTF-32 în UTF-16
  • PDF_utf8_to_utf16 — Converte?te un string din UTF-8 în UTF-16
Basic Usage Examples
PDF_activate_item
PDF


Activeaza un element de structura sau un alt element de con?inut

PDF Func?ii
PDF_add_annotation
PDF Func?ii
PHP Manual

PDF_activate_item

(PECL pdflib >= 2.0.0)

PDF_activate_item — Activeaza un element de structura sau un alt element de con?inut

Descrierea

bool PDF_activate_item ( resource $pdfdoc , int $id )

Activeaza un element de structura sau un alt element de con?inut creat anterior. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF Func?ii
PDF_add_annotation
PDF Func?ii


Adauga o adnotare [învechit]

PDF_activate_item
PDF_add_bookmark
PDF Func?ii
PHP Manual

PDF_add_annotation

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_annotation — Adauga o adnotare [învechit]

Descrierea

Aceasta func?ie este învechita, utiliza?i PDF_create_annotation() cu parametrul type=Text în loc.

PDF_activate_item
PDF_add_bookmark
PDF Func?ii


Adauga un semn de carte pentru pagina curenta [învechit]

PDF_add_annotation
PDF_add_launchlink
PDF Func?ii
PHP Manual

PDF_add_bookmark

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_add_bookmark — Adauga un semn de carte pentru pagina curenta [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i PDF_create_bookmark() în loc.

PDF_add_annotation
PDF_add_launchlink
PDF Func?ii


Adauga o adnotare de lansare pentru pagina curenta [învechit]

PDF_add_bookmark
PDF_add_locallink
PDF Func?ii
PHP Manual

PDF_add_launchlink

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_launchlink — Adauga o adnotare de lansare pentru pagina curenta [învechit]

Descrierea

bool PDF_add_launchlink ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $filename )

Adauga o referin?a catre o resursa web.

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i
PDF_create_action() cu
type=Launch ?i
PDF_create_annotation() cu
type=Link în loc.

PDF_add_bookmark
PDF_add_locallink
PDF Func?ii


Adauga o adnotare de referin?a pentru pagina curenta [învechit]

PDF_add_launchlink
PDF_add_nameddest
PDF Func?ii
PHP Manual

PDF_add_locallink

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_locallink — Adauga o adnotare de referin?a pentru pagina curenta [învechit]

Descrierea

bool PDF_add_locallink ( resource $pdfdoc , float $lowerleftx , float $lowerlefty , float $upperrightx , float $upperrighty , int $page , string $dest )

Adauga o adnotare de referin?a spre o ?inta din fi?ierul PDF curent. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i
PDF_create_action() cu type=GoTo
?i PDF_create_annotation() cu
type=Link în loc.

PDF_add_launchlink
PDF_add_nameddest
PDF Func?ii


Creeaza o destina?ie cu denumire

PDF_add_locallink
PDF_add_note
PDF Func?ii
PHP Manual

PDF_add_nameddest

(PECL pdflib >= 2.0.0)

PDF_add_nameddest — Creeaza o destina?ie cu denumire

Descrierea

bool PDF_add_nameddest ( resource $pdfdoc , string $name , string $optlist )

Creeaza o destina?ie cu denumire pe o pagina arbitrara în documentul curent. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_add_locallink
PDF_add_note
PDF Func?ii


Stabile?te o adnotare pentru pagina curenta [învechit]

PDF_add_nameddest
PDF_add_outline
PDF Func?ii
PHP Manual

PDF_add_note

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_note — Stabile?te o adnotare pentru pagina curenta [învechit]

Descrierea

bool PDF_add_note ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $contents , string $title , string $icon , int $open )

Stabile?te o adnotare pentru pagina curenta. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i PDF_create_annotation() cu type=Text în loc.

PDF_add_nameddest
PDF_add_outline
PDF Func?ii


Adauga un semn de carte pentru pagina curenta [învechit]

PDF_add_note
PDF_add_pdflink
PDF Func?ii
PHP Manual

PDF_add_outline

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_outline — Adauga un semn de carte pentru pagina curenta [învechit]

Descrierea

Aceasta func?ie este învechita, utiliza?i PDF_create_bookmark() în loc.

PDF_add_note
PDF_add_pdflink
PDF Func?ii


Adauga o adnotare-referin?a catre fi?ier pentru pagina curenta [învechit]

PDF_add_outline
PDF_add_table_cell
PDF Func?ii
PHP Manual

PDF_add_pdflink

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_pdflink — Adauga o adnotare-referin?a catre fi?ier pentru pagina curenta [învechit]

Descrierea

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 )

Adauga o adnotare-referin?a catre un fi?ier pentru o ?inta PDF. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i
PDF_create_action() cu
type=GoToR ?i
PDF_create_annotation() cu
type=Link în loc.

PDF_add_outline
PDF_add_table_cell
PDF Func?ii


Adauga o celula catre un tabel nou sau existent

PDF_add_pdflink
PDF_add_textflow
PDF Func?ii
PHP Manual

PDF_add_table_cell

(PECL pdflib >= 2.1.0)

PDF_add_table_cell — Adauga o celula catre un tabel nou sau existent

Descrierea

int PDF_add_table_cell ( resource $pdfdoc , int $table , int $column , int $row , string $text , string $optlist )

Adauga o celula catre un tabel nou sau existent.

PDF_add_pdflink
PDF_add_textflow
PDF Func?ii


Creaza un Textflow sau adauga text catre un Textflow existent

PDF_add_table_cell
PDF_add_thumbnail
PDF Func?ii
PHP Manual

PDF_add_textflow

(PECL pdflib >= 2.1.0)

PDF_add_textflow — Creaza un Textflow sau adauga text catre un Textflow existent

Descrierea

int PDF_add_textflow ( resource $pdfdoc , int $textflow , string $text , string $optlist )

Creeaza un obiect Textflow sau adauga text ?i op?iuni explicite catre un Textflow existent.

PDF_add_table_cell
PDF_add_thumbnail
PDF Func?ii


Adauga o miniatura pentru pagina curenta

PDF_add_textflow
PDF_add_weblink
PDF Func?ii
PHP Manual

PDF_add_thumbnail

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_thumbnail — Adauga o miniatura pentru pagina curenta

Descrierea

bool PDF_add_thumbnail ( resource $pdfdoc , int $image )

Adauga o imagine existenta în calitate de miniatura pentru pagina curenta. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_add_textflow
PDF_add_weblink
PDF Func?ii


Adauga o referin?a web pentru pagina curenta [învechit]

PDF_add_thumbnail
PDF_arc
PDF Func?ii
PHP Manual

PDF_add_weblink

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_weblink — Adauga o referin?a web pentru pagina curenta [învechit]

Descrierea

bool PDF_add_weblink ( resource $pdfdoc , float $lowerleftx , float $lowerlefty , float $upperrightx , float $upperrighty , string $url )

Adauga o adnotare-referin?a web catre o resursa url. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i
PDF_create_action() cu type=URI
?i PDF_create_annotation() cu
type=Link în loc.

PDF_add_thumbnail
PDF_arc
PDF Func?ii


Deseneaza un segment de arc de circumferin?a contra sensului acelor de ceasornic

PDF_add_weblink
PDF_arcn
PDF Func?ii
PHP Manual

PDF_arc

(PHP 4, PECL pdflib >= 1.0.0)

PDF_arc — Deseneaza un segment de arc de circumferin?a contra sensului acelor de ceasornic

Descrierea

bool PDF_arc ( resource $p , float $x , float $y , float $r , float $alpha , float $beta )

Adauga un arc de circumferin?a contra sensului acelor de ceasornic.

PDF_add_weblink
PDF_arcn
PDF Func?ii


Deseneaza un segment de arc de circumferin?a în sensul acelor de ceasornic

PDF_arc
PDF_attach_file
PDF Func?ii
PHP Manual

PDF_arcn

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_arcn — Deseneaza un segment de arc de circumferin?a în sensul acelor de ceasornic

Descrierea

bool PDF_arcn ( resource $p , float $x , float $y , float $r , float $alpha , float $beta )

Cu excep?ia direc?iei de desenare, aceasta func?ie se comporta exact ca PDF_arc().

PDF_arc
PDF_attach_file
PDF Func?ii


Adauga un fi?ier ata?at la pagina curenta [învechit]

PDF_arcn
PDF_begin_document
PDF Func?ii
PHP Manual

PDF_attach_file

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_attach_file — Adauga un fi?ier ata?at la pagina curenta [învechit]

Descrierea

bool PDF_attach_file ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $filename , string $description , string $author , string $mimetype , string $icon )

Adauga o adnotare cu fi?ier ata?at. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i PDF_create_annotation() cu type=FileAttachment în loc.

PDF_arcn
PDF_begin_document
PDF Func?ii


Creeaza un fi?ier PDF nou

PDF_attach_file
PDF_begin_font
PDF Func?ii
PHP Manual

PDF_begin_document

(PECL pdflib >= 2.0.0)

PDF_begin_document — Creeaza un fi?ier PDF nou

Descrierea

int PDF_begin_document ( resource $pdfdoc , string $filename , string $optlist )

Creeaza un nou fi?ier PDF supus diferitor op?iuni.

PDF_attach_file
PDF_begin_font
PDF Func?ii


Începe o defini?ie de font de Tip 3

PDF_begin_document
PDF_begin_glyph
PDF Func?ii
PHP Manual

PDF_begin_font

(PECL pdflib >= 2.0.0)

PDF_begin_font — Începe o defini?ie de font de Tip 3

Descrierea

bool PDF_begin_font ( resource $pdfdoc , string $filename , float $a , float $b , float $c , float $d , float $e , float $f , string $optlist )

Începe o defini?ie de font de Tip 3.

PDF_begin_document
PDF_begin_glyph
PDF Func?ii


Începe o defini?ie de simbol pentru un font de Tip 3

PDF_begin_font
PDF_begin_item
PDF Func?ii
PHP Manual

PDF_begin_glyph

(PECL pdflib >= 2.0.0)

PDF_begin_glyph — Începe o defini?ie de simbol pentru un font de Tip 3

Descrierea

bool PDF_begin_glyph ( resource $pdfdoc , string $glyphname , float $wx , float $llx , float $lly , float $urx , float $ury )

Începe o defini?ie de simbol pentru un font de Tip 3.

PDF_begin_font
PDF_begin_item
PDF Func?ii


Deschide un element de structura sau un alt element de con?inut

PDF_begin_glyph
PDF_begin_layer
PDF Func?ii
PHP Manual

PDF_begin_item

(PECL pdflib >= 2.0.0)

PDF_begin_item — Deschide un element de structura sau un alt element de con?inut

Descrierea

int PDF_begin_item ( resource $pdfdoc , string $tag , string $optlist )

Deschide un element de structura sau un alt element de con?inut cu atributele furnizate ca op?iuni.

PDF_begin_glyph
PDF_begin_layer
PDF Func?ii


Începe un strat

PDF_begin_item
PDF_begin_page_ext
PDF Func?ii
PHP Manual

PDF_begin_layer

(PECL pdflib >= 2.0.0)

PDF_begin_layer — Începe un strat

Descrierea

bool PDF_begin_layer ( resource $pdfdoc , int $layer )

Începe un strat pentru ie?iri ulterioare pe pagina. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie necesita PDF 1.5.

PDF_begin_item
PDF_begin_page_ext
PDF Func?ii


Începe o pagina noua

PDF_begin_layer
PDF_begin_page
PDF Func?ii
PHP Manual

PDF_begin_page_ext

(PECL pdflib >= 2.0.0)

PDF_begin_page_ext — Începe o pagina noua

Descrierea

bool PDF_begin_page_ext ( resource $pdfdoc , float $width , float $height , string $optlist )

Adauga o pagina noua la document specificând diverse op?iuni. Parametrii width ?i height sunt dimensiunile paginii noi în puncte. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Dimensiunile cele mai des întâlnite ale paginilor în puncte
denumire | dimensiune
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 Func?ii


Începe o pagina noua [învechit]

PDF_begin_page_ext
PDF_begin_pattern
PDF Func?ii
PHP Manual

PDF_begin_page

(PHP 4, PECL pdflib >= 1.0.0)

PDF_begin_page — Începe o pagina noua [învechit]

Descrierea

bool PDF_begin_page ( resource $pdfdoc , float $width , float $height )

Adauga o pagina noua la document. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i PDF_begin_page_ext() în loc.

PDF_begin_page_ext
PDF_begin_pattern
PDF Func?ii


Începe defini?ia unui tipar

PDF_begin_page
PDF_begin_template_ext
PDF Func?ii
PHP Manual

PDF_begin_pattern

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_begin_pattern — Începe defini?ia unui tipar

Descrierea

int PDF_begin_pattern ( resource $pdfdoc , float $width , float $height , float $xstep , float $ystep , int $painttype )

Începe defini?ia unui tipar nou.

PDF_begin_page
PDF_begin_template_ext
PDF Func?ii


Începe defini?ia unui tipar

PDF_begin_pattern
PDF_begin_template
PDF Func?ii
PHP Manual

PDF_begin_template_ext

(PECL pdflib >= 2.1.0)

PDF_begin_template_ext — Începe defini?ia unui tipar

Descrierea

int PDF_begin_template_ext ( resource $pdfdoc , float $width , float $height , string $optlist )

Începe defini?ia unui tipar nou.

PDF_begin_pattern
PDF_begin_template
PDF Func?ii


Începe defini?ia unui tipar [învechit]

PDF_begin_template_ext
PDF_circle
PDF Func?ii
PHP Manual

PDF_begin_template

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_begin_template — Începe defini?ia unui tipar [învechit]

Descrierea

int PDF_begin_template ( resource $pdfdoc , float $width , float $height )

Începe defini?ia unui tipar nou.

Aceasta func?ie este învechita începând cu PDFlib versiunea 7, utiliza?i PDF_begin_template_ext() în loc.

PDF_begin_template_ext
PDF_circle
PDF Func?ii


Deseneaza un cerc

PDF_begin_template
PDF_clip
PDF Func?ii
PHP Manual

PDF_circle

(PHP 4, PECL pdflib >= 1.0.0)

PDF_circle — Deseneaza un cerc

Descrierea

bool PDF_circle ( resource $pdfdoc , float $x , float $y , float $r )

Adauga un cerc. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_begin_template
PDF_clip
PDF Func?ii


Taie conform caii curente

PDF_circle
PDF_close_image
PDF Func?ii
PHP Manual

PDF_clip

(PHP 4, PECL pdflib >= 1.0.0)

PDF_clip — Taie conform caii curente

Descrierea

bool PDF_clip ( resource $p )

Utilizeaza calea curenta în calitate de cale de taiere ?i încheie calea. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_circle
PDF_close_image
PDF Func?ii


Închide o imagine

PDF_clip
PDF_close_pdi_page
PDF Func?ii
PHP Manual

PDF_close_image

(PHP 4, PECL pdflib >= 1.0.0)

PDF_close_image — Închide o imagine

Descrierea

bool PDF_close_image ( resource $p , int $image )

Închide image ob?inut cu ajutorul func?iei PDF_open_image().

PDF_clip
PDF_close_pdi_page
PDF Func?ii


Închide handle-ul paginii

PDF_close_image
PDF_close_pdi
PDF Func?ii
PHP Manual

PDF_close_pdi_page

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_close_pdi_page — Închide handle-ul paginii

Descrierea

bool PDF_close_pdi_page ( resource $p , int $page )

Închide handle-ul paginii ?i elibereaza toate resursele legate de pagina. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_close_image
PDF_close_pdi
PDF Func?ii


Închide documentul PDF de intrare [învechit]

PDF_close_pdi_page
PDF_close
PDF Func?ii
PHP Manual

PDF_close_pdi

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_close_pdi — Închide documentul PDF de intrare [învechit]

Descrierea

bool PDF_close_pdi ( resource $p , int $doc )

Închide toate handle-urile deschise ale paginii ?i închide documentul PDF de intrare. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 7, utiliza?i PDF_close_pdi_document() în loc.

PDF_close_pdi_page
PDF_close
PDF Func?ii


Închite resursa PDF [învechit]

PDF_close_pdi
PDF_closepath_fill_stroke
PDF Func?ii
PHP Manual

PDF_close

(PHP 4, PECL pdflib >= 1.0.0)

PDF_close — Închite resursa PDF [învechit]

Descrierea

bool PDF_close ( resource $p )

Închide fi?ierul PDF generat ?i elibereaza toate resursele legate de document. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i PDF_end_document() în loc.

PDF_close_pdi
PDF_closepath_fill_stroke
PDF Func?ii


Închide, umple ?i traseaza calea curenta

PDF_close
PDF_closepath_stroke
PDF Func?ii
PHP Manual

PDF_closepath_fill_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_closepath_fill_stroke — Închide, umple ?i traseaza calea curenta

Descrierea

bool PDF_closepath_fill_stroke ( resource $p )

Închide calea, o umple ?i o traseaza. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_close
PDF_closepath_stroke
PDF Func?ii


Închide ?i traseaza calea

PDF_closepath_fill_stroke
PDF_closepath
PDF Func?ii
PHP Manual

PDF_closepath_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_closepath_stroke — Închide ?i traseaza calea

Descrierea

bool PDF_closepath_stroke ( resource $p )

Închide calea ?i o traseaza. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_closepath_fill_stroke
PDF_closepath
PDF Func?ii


Închide calea curenta

PDF_closepath_stroke
PDF_concat
PDF Func?ii
PHP Manual

PDF_closepath

(PHP 4, PECL pdflib >= 1.0.0)

PDF_closepath — Închide calea curenta

Descrierea

bool PDF_closepath ( resource $p )

Închide calea curenta. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_closepath_stroke
PDF_concat
PDF Func?ii


Concateneaza o matrice la MCT

PDF_closepath
PDF_continue_text
PDF Func?ii
PHP Manual

PDF_concat

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_concat — Concateneaza o matrice la MCT

Descrierea

bool PDF_concat ( resource $p , float $a , float $b , float $c , float $d , float $e , float $f )

Concateneaza o matrice la matricea curenta de transformare (MCT). Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_closepath
PDF_continue_text
PDF Func?ii


Afi?eaza textul în linia urmatoare

PDF_concat
PDF_create_3dview
PDF Func?ii
PHP Manual

PDF_continue_text

(PHP 4, PECL pdflib >= 1.0.0)

PDF_continue_text — Afi?eaza textul în linia urmatoare

Descrierea

bool PDF_continue_text ( resource $p , string $text )

Afi?eaza text în linia urmatoare. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_concat
PDF_create_3dview
PDF Func?ii


Creeaza o imagine 3D

PDF_continue_text
PDF_create_action
PDF Func?ii
PHP Manual

PDF_create_3dview

(PECL pdflib >= 2.1.0)

PDF_create_3dview — Creeaza o imagine 3D

Descrierea

int PDF_create_3dview ( resource $pdfdoc , string $username , string $optlist )

Creeaza o imagine 3D.

Aceasta func?ie necesita PDF 1.6.

PDF_continue_text
PDF_create_action
PDF Func?ii


Creeaza ac?iuni pentru obiecte sau evenimente

PDF_create_3dview
PDF_create_annotation
PDF Func?ii
PHP Manual

PDF_create_action

(PECL pdflib >= 2.0.0)

PDF_create_action — Creeaza ac?iuni pentru obiecte sau evenimente

Descrierea

int PDF_create_action ( resource $pdfdoc , string $type , string $optlist )

Creeaza o ac?iune care poate fi aplicata diverselor obiecte ?i evenimente.

PDF_create_3dview
PDF_create_annotation
PDF Func?ii


Creeaza o adnotare dreptunghiulara

PDF_create_action
PDF_create_bookmark
PDF Func?ii
PHP Manual

PDF_create_annotation

(PECL pdflib >= 2.0.0)

PDF_create_annotation — Creeaza o adnotare dreptunghiulara

Descrierea

bool PDF_create_annotation ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $type , string $optlist )

Creeaza o adnotare dreptunghiulara pe pagina curenta.

PDF_create_action
PDF_create_bookmark
PDF Func?ii


Creeaza un semn de carte

PDF_create_annotation
PDF_create_field
PDF Func?ii
PHP Manual

PDF_create_bookmark

(PECL pdflib >= 2.0.0)

PDF_create_bookmark — Creeaza un semn de carte

Descrierea

int PDF_create_bookmark ( resource $pdfdoc , string $text , string $optlist )

Creeaza un semn de carte supus diverselor op?iuni.

PDF_create_annotation
PDF_create_field
PDF Func?ii


Creeaza un câmp în formular

PDF_create_bookmark
PDF_create_fieldgroup
PDF Func?ii
PHP Manual

PDF_create_field

(PECL pdflib >= 2.0.0)

PDF_create_field — Creeaza un câmp în formular

Descrierea

bool PDF_create_field ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $name , string $type , string $optlist )

Creeaza un câmp de formular pe pagina curenta, supus diferitor op?iuni.

PDF_create_bookmark
PDF_create_fieldgroup
PDF Func?ii


Creeaza un grup de câmpuri de formular

PDF_create_field
PDF_create_gstate
PDF Func?ii
PHP Manual

PDF_create_fieldgroup

(PECL pdflib >= 2.0.0)

PDF_create_fieldgroup — Creeaza un grup de câmpuri de formular

Descrierea

bool PDF_create_fieldgroup ( resource $pdfdoc , string $name , string $optlist )

Creeaza un grup de câmpuri de formular supus diverselor op?iuni.

PDF_create_field
PDF_create_gstate
PDF Func?ii


Creeaza un obiect de stare grafica

PDF_create_fieldgroup
PDF_create_pvf
PDF Func?ii
PHP Manual

PDF_create_gstate

(PECL pdflib >= 2.0.0)

PDF_create_gstate — Creeaza un obiect de stare grafica

Descrierea

int PDF_create_gstate ( resource $pdfdoc , string $optlist )

Creeaza un obiect de stare grafica, supus diverselor op?iuni.

PDF_create_fieldgroup
PDF_create_pvf
PDF Func?ii


Creeaza un fi?ier virtual PDFlib

PDF_create_gstate
PDF_create_textflow
PDF Func?ii
PHP Manual

PDF_create_pvf

(PECL pdflib >= 2.0.0)

PDF_create_pvf — Creeaza un fi?ier virtual PDFlib

Descrierea

bool PDF_create_pvf ( resource $pdfdoc , string $filename , string $data , string $optlist )

Creeaza un fi?ier virtual, cu nume, numai pentru citire din datele furnizate din memorie.

PDF_create_gstate
PDF_create_textflow
PDF Func?ii


Creeaza un obiect textflow

PDF_create_pvf
PDF_curveto
PDF Func?ii
PHP Manual

PDF_create_textflow

(PECL pdflib >= 2.0.0)

PDF_create_textflow — Creeaza un obiect textflow

Descrierea

int PDF_create_textflow ( resource $pdfdoc , string $text , string $optlist )

Preproceseaza textul pentru formatare ulterioara ?i creeaza un obiect textflow.

PDF_create_pvf
PDF_curveto
PDF Func?ii


Deseneaza o curba Bezier

PDF_create_textflow
PDF_define_layer
PDF Func?ii
PHP Manual

PDF_curveto

(PHP 4, PECL pdflib >= 1.0.0)

PDF_curveto — Deseneaza o curba Bezier

Descrierea

bool PDF_curveto ( resource $p , float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Deseneaza o curba Bezier din punctul curent, utilizând alte 3 puncte de control. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_create_textflow
PDF_define_layer
PDF Func?ii


Creeaza o defini?ie a stratului

PDF_curveto
PDF_delete_pvf
PDF Func?ii
PHP Manual

PDF_define_layer

(PECL pdflib >= 2.0.0)

PDF_define_layer — Creeaza o defini?ie a stratului

Descrierea

int PDF_define_layer ( resource $pdfdoc , string $name , string $optlist )

Creeaza o noua defini?ie a stratului.

Aceasta func?ie necesita PDF 1.5.

PDF_curveto
PDF_delete_pvf
PDF Func?ii


Elimina un fi?ier virtual PDFlib

PDF_define_layer
PDF_delete_table
PDF Func?ii
PHP Manual

PDF_delete_pvf

(PECL pdflib >= 2.0.0)

PDF_delete_pvf — Elimina un fi?ier virtual PDFlib

Descrierea

int PDF_delete_pvf ( resource $pdfdoc , string $filename )

Elimina un fi?ier virtual denumit ?i elibereaza structurile sale de date (dar nu ?i con?inutul).

PDF_define_layer
PDF_delete_table
PDF Func?ii


Elimina un obiect-tabel

PDF_delete_pvf
PDF_delete_textflow
PDF Func?ii
PHP Manual

PDF_delete_table

(PECL pdflib >= 2.1.0)

PDF_delete_table — Elimina un obiect-tabel

Descrierea

bool PDF_delete_table ( resource $pdfdoc , int $table , string $optlist )

Elimina un tabel ?i toate structurile de date asociate acestuia.

PDF_delete_pvf
PDF_delete_textflow
PDF Func?ii


Elimina un obiect textflow

PDF_delete_table
PDF_delete
PDF Func?ii
PHP Manual

PDF_delete_textflow

(PECL pdflib >= 2.0.0)

PDF_delete_textflow — Elimina un obiect textflow

Descrierea

bool PDF_delete_textflow ( resource $pdfdoc , int $textflow )

Elimina un textflow ?i structurile de date asociate acestuia.

PDF_delete_table
PDF_delete
PDF Func?ii


Elimina un obiect PDFlib

PDF_delete_textflow
PDF_encoding_set_char
PDF Func?ii
PHP Manual

PDF_delete

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_delete — Elimina un obiect PDFlib

Descrierea

bool PDF_delete ( resource $pdfdoc )

Elimina un obiect PDFlib ?i elibereaza toate resursele interne. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_delete_textflow
PDF_encoding_set_char
PDF Func?ii


Adauga denumirea unui simbol ?i/sau valoarea Unicode

PDF_delete
PDF_end_document
PDF Func?ii
PHP Manual

PDF_encoding_set_char

(PECL pdflib >= 2.0.0)

PDF_encoding_set_char — Adauga denumirea unui simbol ?i/sau valoarea Unicode

Descrierea

bool PDF_encoding_set_char ( resource $pdfdoc , string $encoding , int $slot , string $glyphname , int $uv )

Adauga denumirea unui simbol ?i/sau valoarea Unicode la o codificare personalizata.

PDF_delete
PDF_end_document
PDF Func?ii


Închide un fi?ier PDF

PDF_encoding_set_char
PDF_end_font
PDF Func?ii
PHP Manual

PDF_end_document

(PECL pdflib >= 2.0.0)

PDF_end_document — Închide un fi?ier PDF

Descrierea

bool PDF_end_document ( resource $pdfdoc , string $optlist )

Închide fi?ierul PDF generat ?i aplica diverse op?iuni.

PDF_encoding_set_char
PDF_end_font
PDF Func?ii


Încheie o defini?ie de font te Tip 3

PDF_end_document
PDF_end_glyph
PDF Func?ii
PHP Manual

PDF_end_font

(PECL pdflib >= 2.0.0)

PDF_end_font — Încheie o defini?ie de font te Tip 3

Descrierea

bool PDF_end_font ( resource $pdfdoc )

Încheie o defini?ie de font te Tip 3.

PDF_end_document
PDF_end_glyph
PDF Func?ii


Încheie o defini?ie a simbolului pentru un font de Tip 3

PDF_end_font
PDF_end_item
PDF Func?ii
PHP Manual

PDF_end_glyph

(PECL pdflib >= 2.0.0)

PDF_end_glyph — Încheie o defini?ie a simbolului pentru un font de Tip 3

Descrierea

bool PDF_end_glyph ( resource $pdfdoc )

Încheie o defini?ie a simbolului pentru un font de Tip 3.

PDF_end_font
PDF_end_item
PDF Func?ii


Închide un element de structura sau un alt element de con?inut

PDF_end_glyph
PDF_end_layer
PDF Func?ii
PHP Manual

PDF_end_item

(PECL pdflib >= 2.0.0)

PDF_end_item — Închide un element de structura sau un alt element de con?inut

Descrierea

bool PDF_end_item ( resource $pdfdoc , int $id )

Închide un element de structura sau un alt element de con?inut.

PDF_end_glyph
PDF_end_layer
PDF Func?ii


Dezactiveaza toate straturile active

PDF_end_item
PDF_end_page_ext
PDF Func?ii
PHP Manual

PDF_end_layer

(PECL pdflib >= 2.0.0)

PDF_end_layer — Dezactiveaza toate straturile active

Descrierea

bool PDF_end_layer ( resource $pdfdoc )

Dezactiveaza toate straturile active. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie necesita PDF 1.5.

PDF_end_item
PDF_end_page_ext
PDF Func?ii


Încheie o pagina

PDF_end_layer
PDF_end_page
PDF Func?ii
PHP Manual

PDF_end_page_ext

(PECL pdflib >= 2.0.0)

PDF_end_page_ext — Încheie o pagina

Descrierea

bool PDF_end_page_ext ( resource $pdfdoc , string $optlist )

Încheie o pagina ?i aplica diverse op?iuni. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_end_layer
PDF_end_page
PDF Func?ii


Încheie o pagina

PDF_end_page_ext
PDF_end_pattern
PDF Func?ii
PHP Manual

PDF_end_page

(PHP 4, PECL pdflib >= 1.0.0)

PDF_end_page — Încheie o pagina

Descrierea

bool PDF_end_page ( resource $p )

Încheie o pagina. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_end_page_ext
PDF_end_pattern
PDF Func?ii


Încheie un tipar

PDF_end_page
PDF_end_template
PDF Func?ii
PHP Manual

PDF_end_pattern

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_end_pattern — Încheie un tipar

Descrierea

bool PDF_end_pattern ( resource $p )

Încheie defini?ia unui tipar. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_end_page
PDF_end_template
PDF Func?ii


Încheie un ?ablon

PDF_end_pattern
PDF_endpath
PDF Func?ii
PHP Manual

PDF_end_template

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_end_template — Încheie un ?ablon

Descrierea

bool PDF_end_template ( resource $p )

Încheie defini?ia unui ?ablon. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_end_pattern
PDF_endpath
PDF Func?ii


Încheie calea curenta

PDF_end_template
PDF_fill_imageblock
PDF Func?ii
PHP Manual

PDF_endpath

(PHP 4, PECL pdflib >= 1.0.0)

PDF_endpath — Încheie calea curenta

Descrierea

bool PDF_endpath ( resource $p )

Încheie calea curenta fara a o umple sau a o trasa.

PDF_end_template
PDF_fill_imageblock
PDF Func?ii


Umple un bloc de imagine cu date variabile

PDF_endpath
PDF_fill_pdfblock
PDF Func?ii
PHP Manual

PDF_fill_imageblock

(PECL pdflib >= 2.0.0)

PDF_fill_imageblock — Umple un bloc de imagine cu date variabile

Descrierea

int PDF_fill_imageblock ( resource $pdfdoc , int $page , string $blockname , int $image , string $optlist )

Umple un bloc de imagine cu date variabile conform proprieta?ilor acestora.

Aceasta func?ie este disponibila doar în PDFlib Personalization Server (PPS).

PDF_endpath
PDF_fill_pdfblock
PDF Func?ii


Umple un bloc PDF cu date variabile

PDF_fill_imageblock
PDF_fill_stroke
PDF Func?ii
PHP Manual

PDF_fill_pdfblock

(PECL pdflib >= 2.0.0)

PDF_fill_pdfblock — Umple un bloc PDF cu date variabile

Descrierea

int PDF_fill_pdfblock ( resource $pdfdoc , int $page , string $blockname , int $contents , string $optlist )

Umple un bloc PDF cu date variabile conform proprieta?ilor acestora.

Aceasta func?ie este disponibila doar în PDFlib Personalization Server (PPS).

PDF_fill_imageblock
PDF_fill_stroke
PDF Func?ii


Umple ?i traseaza o cale

PDF_fill_pdfblock
PDF_fill_textblock
PDF Func?ii
PHP Manual

PDF_fill_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_fill_stroke — Umple ?i traseaza o cale

Descrierea

bool PDF_fill_stroke ( resource $p )

Umple ?i traseaza calea curenta cu culoarea curenta a umpluturii ?i a trasarii. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_fill_pdfblock
PDF_fill_textblock
PDF Func?ii


Umple un bloc de text cu date variabile

PDF_fill_stroke
PDF_fill
PDF Func?ii
PHP Manual

PDF_fill_textblock

(PECL pdflib >= 2.0.0)

PDF_fill_textblock — Umple un bloc de text cu date variabile

Descrierea

int PDF_fill_textblock ( resource $pdfdoc , int $page , string $blockname , string $text , string $optlist )

Umple un bloc de text cu date variabile conform proprieta?ilor acestora.

Aceasta func?ie este disponibila doar în PDFlib Personalization Server (PPS).

PDF_fill_stroke
PDF_fill
PDF Func?ii


Umple calea curenta

PDF_fill_textblock
PDF_findfont
PDF Func?ii
PHP Manual

PDF_fill

(PHP 4, PECL pdflib >= 1.0.0)

PDF_fill — Umple calea curenta

Descrierea

bool PDF_fill ( resource $p )

Umple interiorul caii curente cu culoarea curenta de umplere. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_fill_textblock
PDF_findfont
PDF Func?ii


Pregate?te un font pentru utilizarea sa ulterioara [învechit]

PDF_fill
PDF_fit_image
PDF Func?ii
PHP Manual

PDF_findfont

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_findfont — Pregate?te un font pentru utilizarea sa ulterioara [învechit]

Descrierea

int PDF_findfont ( resource $p , string $fontname , string $encoding , int $embed )

Cauta un font ?i îl pregate?te pentru utilizare ulterioara cu PDF_setfont(). Metricile vor fi încarcate ?i daca embed este nonzero, font-ul va fi verificat, dar nu va fi utilizat. encoding poate fi builtin, macroman, winansi, host, o denumire de codificare definita de utilizator sau denumirea unui CMap. Parametrul embed este op?ional înainte de PHP 4.3.5 sau cu PDFlib mai mic de 5.

Aceasta func?ie este învechita începând cu PDFlib versiunea 5, utiliza?i PDF_load_font() în loc.

PDF_fill
PDF_fit_image
PDF Func?ii


Plaseaza o imagine sau un ?ablon

PDF_findfont
PDF_fit_pdi_page
PDF Func?ii
PHP Manual

PDF_fit_image

(PECL pdflib >= 2.0.0)

PDF_fit_image — Plaseaza o imagine sau un ?ablon

Descrierea

bool PDF_fit_image ( resource $pdfdoc , int $image , float $x , float $y , string $optlist )

Plaseaza o imagine sau un ?ablon pe pagina, supus diferitor op?iuni. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_findfont
PDF_fit_pdi_page
PDF Func?ii


Plaseaza o pagina PDF importata

PDF_fit_image
PDF_fit_table
PDF Func?ii
PHP Manual

PDF_fit_pdi_page

(PECL pdflib >= 2.0.0)

PDF_fit_pdi_page — Plaseaza o pagina PDF importata

Descrierea

bool PDF_fit_pdi_page ( resource $pdfdoc , int $page , float $x , float $y , string $optlist )

Plaseaza o pagina PDF importata în pagina aleasa, supusa diferitor op?iuni. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_fit_image
PDF_fit_table
PDF Func?ii


Plaseaza un tabel pe pagina

PDF_fit_pdi_page
PDF_fit_textflow
PDF Func?ii
PHP Manual

PDF_fit_table

(PECL pdflib >= 2.1.0)

PDF_fit_table — Plaseaza un tabel pe pagina

Descrierea

string PDF_fit_table ( resource $pdfdoc , int $table , float $llx , float $lly , float $urx , float $ury , string $optlist )

Plaseaza un tabel pe pagina, deplin sau par?ial.

PDF_fit_pdi_page
PDF_fit_textflow
PDF Func?ii


Formateaza un textflow într-o zona dreptunghiulara

PDF_fit_table
PDF_fit_textline
PDF Func?ii
PHP Manual

PDF_fit_textflow

(PECL pdflib >= 2.0.0)

PDF_fit_textflow — Formateaza un textflow într-o zona dreptunghiulara

Descrierea

string PDF_fit_textflow ( resource $pdfdoc , int $textflow , float $llx , float $lly , float $urx , float $ury , string $optlist )

Formateaza urmatoarea por?iune a unui textflow într-o regiune dreptunghiulara.

PDF_fit_table
PDF_fit_textline
PDF Func?ii


Plaseaza o singura linie de text

PDF_fit_textflow
PDF_get_apiname
PDF Func?ii
PHP Manual

PDF_fit_textline

(PECL pdflib >= 2.0.0)

PDF_fit_textline — Plaseaza o singura linie de text

Descrierea

bool PDF_fit_textline ( resource $pdfdoc , string $text , float $x , float $y , string $optlist )

Plaseaza o singura linie de text pe pagina, supusa diferitor op?iuni. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_fit_textflow
PDF_get_apiname
PDF Func?ii


Ob?ine denumirea func?iei API care a e?uat

PDF_fit_textline
PDF_get_buffer
PDF Func?ii
PHP Manual

PDF_get_apiname

(PECL pdflib >= 2.0.0)

PDF_get_apiname — Ob?ine denumirea func?iei API care a e?uat

Descrierea

string PDF_get_apiname ( resource $pdfdoc )

Ob?ine denumirea func?iei API care a emis ultima excep?ie sau a e?uat.

PDF_fit_textline
PDF_get_buffer
PDF Func?ii


Ob?ine zona-tampon de ie?ire a PDF

PDF_get_apiname
PDF_get_errmsg
PDF Func?ii
PHP Manual

PDF_get_buffer

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_buffer — Ob?ine zona-tampon de ie?ire a PDF

Descrierea

string PDF_get_buffer ( resource $p )

Intercepteaza zona-tampon ce con?ine datele PDF generate.

PDF_get_apiname
PDF_get_errmsg
PDF Func?ii


Ob?ine textul erorii

PDF_get_buffer
PDF_get_errnum
PDF Func?ii
PHP Manual

PDF_get_errmsg

(PECL pdflib >= 2.0.0)

PDF_get_errmsg — Ob?ine textul erorii

Descrierea

string PDF_get_errmsg ( resource $pdfdoc )

Ob?ine textul ultimei excep?ii emise sau motivul e?ecului unui apel de func?ie.

PDF_get_buffer
PDF_get_errnum
PDF Func?ii


Ob?ine numarul erorii

PDF_get_errmsg
PDF_get_font
PDF Func?ii
PHP Manual

PDF_get_errnum

(PECL pdflib >= 2.0.0)

PDF_get_errnum — Ob?ine numarul erorii

Descrierea

int PDF_get_errnum ( resource $pdfdoc )

Ob?ine numarul ultimei excep?ii emise sau motivul e?ecului unui apel de func?ie.

PDF_get_errmsg
PDF_get_font
PDF Func?ii


Ob?ine fontul [învechit]

PDF_get_errnum
PDF_get_fontname
PDF Func?ii
PHP Manual

PDF_get_font

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_font — Ob?ine fontul [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_get_value() cu parametrul font în loc.

PDF_get_errnum
PDF_get_fontname
PDF Func?ii


Ob?ine denumirea fontului [învechit]

PDF_get_font
PDF_get_fontsize
PDF Func?ii
PHP Manual

PDF_get_fontname

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_fontname — Ob?ine denumirea fontului [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_get_parameter() cu parametrul fontname în loc.

PDF_get_font
PDF_get_fontsize
PDF Func?ii


Manipularea fontului [învechit]

PDF_get_fontname
PDF_get_image_height
PDF Func?ii
PHP Manual

PDF_get_fontsize

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_fontsize — Manipularea fontului [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_get_value() cu parametrul fontsize în loc.

PDF_get_fontname
PDF_get_image_height
PDF Func?ii


Ob?ine înal?imea imaginii [învechit]

PDF_get_fontsize
PDF_get_image_width
PDF Func?ii
PHP Manual

PDF_get_image_height

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_image_height — Ob?ine înal?imea imaginii [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_get_value() cu parametrul imageheight în loc.

PDF_get_fontsize
PDF_get_image_width
PDF Func?ii


Ob?ine la?imea imaginii [învechit]

PDF_get_image_height
PDF_get_majorversion
PDF Func?ii
PHP Manual

PDF_get_image_width

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_image_width — Ob?ine la?imea imaginii [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_get_value() cu parametrul imagewidth în loc.

PDF_get_image_height
PDF_get_majorversion
PDF Func?ii


Ob?ine numarul major al versiunii [învechit]

PDF_get_image_width
PDF_get_minorversion
PDF Func?ii
PHP Manual

PDF_get_majorversion

(PHP 4 >= 4.2.0, PECL pdflib >= 1.0.0)

PDF_get_majorversion — Ob?ine numarul major al versiunii [învechit]

Descrierea

int PDF_get_majorversion ( void )

Aceasta func?ie este învechita începând cu PDFlib versiunea 5, utiliza?i PDF_get_value() cu parametrul major în loc.

PDF_get_image_width
PDF_get_minorversion
PDF Func?ii


Ob?ine numarul minor al versiunii [învechit]

PDF_get_majorversion
PDF_get_parameter
PDF Func?ii
PHP Manual

PDF_get_minorversion

(PHP 4 >= 4.2.0, PECL pdflib >= 1.0.0)

PDF_get_minorversion — Ob?ine numarul minor al versiunii [învechit]

Descrierea

int PDF_get_minorversion ( void )

Întoarce numarul minor al versiunii PDFlib.

Aceasta func?ie este învechita începând cu PDFlib versiunea 5, utiliza?i PDF_get_value() cu parametrul minor în loc.

PDF_get_majorversion
PDF_get_parameter
PDF Func?ii


Ob?ine un parametru string

PDF_get_minorversion
PDF_get_pdi_parameter
PDF Func?ii
PHP Manual

PDF_get_parameter

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_get_parameter — Ob?ine un parametru string

Descrierea

string PDF_get_parameter ( resource $p , string $key , float $modifier )

Ob?ine con?inutul unui parametru de tip string al PDFlib.

PDF_get_minorversion
PDF_get_pdi_parameter
PDF Func?ii


Ob?ine un parametru string al PDI [învechit]

PDF_get_parameter
PDF_get_pdi_value
PDF Func?ii
PHP Manual

PDF_get_pdi_parameter

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_pdi_parameter — Ob?ine un parametru string al PDI [învechit]

Descrierea

string PDF_get_pdi_parameter ( resource $p , string $key , int $doc , int $page , int $reserved )

Ob?ine con?inutul unui parametru de tip string dintr-un document PDI.

Aceasta func?ie este învechita începând cu PDFlib versiunea 7, utiliza?i PDF_pcos_get_string() în loc.

PDF_get_parameter
PDF_get_pdi_value
PDF Func?ii


Ob?ine un parametru numeric PDI [învechit]

PDF_get_pdi_parameter
PDF_get_value
PDF Func?ii
PHP Manual

PDF_get_pdi_value

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_pdi_value — Ob?ine un parametru numeric PDI [învechit]

Descrierea

float PDF_get_pdi_value ( resource $p , string $key , int $doc , int $page , int $reserved )

Ob?ine con?inutul unui parametru de tip numeric al unui document PDI.

Aceasta func?ie este învechita începând cu PDFlib versiunea 7, utiliza?i PDF_pcos_get_number() în loc.

PDF_get_pdi_parameter
PDF_get_value
PDF Func?ii


Ob?ine un parametru numeric

PDF_get_pdi_value
PDF_info_font
PDF Func?ii
PHP Manual

PDF_get_value

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_get_value — Ob?ine un parametru numeric

Descrierea

float PDF_get_value ( resource $p , string $key , float $modifier )

Ob?ine valoarea unui parametru de tip numeric al PDFlib.

PDF_get_pdi_value
PDF_info_font
PDF Func?ii


Transmite o interpelare a informa?iilor detaliate despre un font încarcat

PDF_get_value
PDF_info_matchbox
PDF Func?ii
PHP Manual

PDF_info_font

(PECL pdflib >= 2.1.0)

PDF_info_font — Transmite o interpelare a informa?iilor detaliate despre un font încarcat

Descrierea

float PDF_info_font ( resource $pdfdoc , int $font , string $keyword , string $optlist )

Transmite o interpelare a informa?iilor detaliate despre un font încarcat.

PDF_get_value
PDF_info_matchbox
PDF Func?ii


Transmite o interpelare despre informa?ia matchbox

PDF_info_font
PDF_info_table
PDF Func?ii
PHP Manual

PDF_info_matchbox

(PECL pdflib >= 2.1.0)

PDF_info_matchbox — Transmite o interpelare despre informa?ia matchbox

Descrierea

float PDF_info_matchbox ( resource $pdfdoc , string $boxname , int $num , string $keyword )

Interpeleaza informa?ii despre un matchbox de pe pagina curenta.

PDF_info_font
PDF_info_table
PDF Func?ii


Ob?ine informa?ii despre tabel

PDF_info_matchbox
PDF_info_textflow
PDF Func?ii
PHP Manual

PDF_info_table

(PECL pdflib >= 2.1.0)

PDF_info_table — Ob?ine informa?ii despre tabel

Descrierea

float PDF_info_table ( resource $pdfdoc , int $table , string $keyword )

Ob?ine informa?ii despre cea mai recent plasata instan?a a unui tabel.

PDF_info_matchbox
PDF_info_textflow
PDF Func?ii


Interpeleaza starea textflow

PDF_info_table
PDF_info_textline
PDF Func?ii
PHP Manual

PDF_info_textflow

(PECL pdflib >= 2.0.0)

PDF_info_textflow — Interpeleaza starea textflow

Descrierea

float PDF_info_textflow ( resource $pdfdoc , int $textflow , string $keyword )

Interpeleaza starea curenta a unui textflow.

PDF_info_table
PDF_info_textline
PDF Func?ii


Efectueaza formatarea unei linii de text ?i interpeleaza metricile

PDF_info_textflow
PDF_initgraphics
PDF Func?ii
PHP Manual

PDF_info_textline

(PECL pdflib >= 2.1.0)

PDF_info_textline — Efectueaza formatarea unei linii de text ?i interpeleaza metricile

Descrierea

float PDF_info_textline ( resource $pdfdoc , string $text , string $keyword , string $optlist )

Efectueaza formatarea unei linii de text ?i interpeleaza metricile rezultante.

PDF_info_textflow
PDF_initgraphics
PDF Func?ii


Restabile?te starea grafica

PDF_info_textline
PDF_lineto
PDF Func?ii
PHP Manual

PDF_initgraphics

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_initgraphics — Restabile?te starea grafica

Descrierea

bool PDF_initgraphics ( resource $p )

Restabile?te to?i parametrii de stare a culorilor ?i a graficii la valorile implicite. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_info_textline
PDF_lineto
PDF Func?ii


Deseneaza o linie

PDF_initgraphics
PDF_load_3ddata
PDF Func?ii
PHP Manual

PDF_lineto

(PHP 4, PECL pdflib >= 1.0.0)

PDF_lineto — Deseneaza o linie

Descrierea

bool PDF_lineto ( resource $p , float $x , float $y )

Deseneaza o linie din punctul curent spre un alt punct. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_initgraphics
PDF_load_3ddata
PDF Func?ii


Încarca un model 3D

PDF_lineto
PDF_load_font
PDF Func?ii
PHP Manual

PDF_load_3ddata

(PECL pdflib >= 2.1.0)

PDF_load_3ddata — Încarca un model 3D

Descrierea

int PDF_load_3ddata ( resource $pdfdoc , string $filename , string $optlist )

Încarca un model 3D dintr-un fi?ier de pe disc sau virtual.

Aceasta func?ie necesita PDF 1.6.

PDF_lineto
PDF_load_font
PDF Func?ii


Cauta ?i pregate?te un font

PDF_load_3ddata
PDF_load_iccprofile
PDF Func?ii
PHP Manual

PDF_load_font

(PECL pdflib >= 2.0.0)

PDF_load_font — Cauta ?i pregate?te un font

Descrierea

int PDF_load_font ( resource $pdfdoc , string $fontname , string $encoding , string $optlist )

Cauta un font ?i îl pregate?te pentru utilizarea ulterioara.

PDF_load_3ddata
PDF_load_iccprofile
PDF Func?ii


Cauta ?i pregate?te un profil ICC

PDF_load_font
PDF_load_image
PDF Func?ii
PHP Manual

PDF_load_iccprofile

(PECL pdflib >= 2.0.0)

PDF_load_iccprofile — Cauta ?i pregate?te un profil ICC

Descrierea

int PDF_load_iccprofile ( resource $pdfdoc , string $profilename , string $optlist )

Cauta un profil ICC ?i îl pregate?te pentru utilizarea ulterioara.

PDF_load_font
PDF_load_image
PDF Func?ii


Deschide un fi?ier cu imagine

PDF_load_iccprofile
PDF_makespotcolor
PDF Func?ii
PHP Manual

PDF_load_image

(PECL pdflib >= 2.0.0)

PDF_load_image — Deschide un fi?ier cu imagine

Descrierea

int PDF_load_image ( resource $pdfdoc , string $imagetype , string $filename , string $optlist )

Deschide un fi?ier-imagine de pe disc sau virtual, supus diferitor op?iuni.

PDF_load_iccprofile
PDF_makespotcolor
PDF Func?ii


Creeaza o culoare a punctului

PDF_load_image
PDF_moveto
PDF Func?ii
PHP Manual

PDF_makespotcolor

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_makespotcolor — Creeaza o culoare a punctului

Descrierea

int PDF_makespotcolor ( resource $p , string $spotname )

Gase?te un nume încorporat al culorii punctului sau creeaza o culoare denumita a punctului pe baza culorii curente de ha?urare. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_load_image
PDF_moveto
PDF Func?ii


Stabile?te punctul curent

PDF_makespotcolor
PDF_new
PDF Func?ii
PHP Manual

PDF_moveto

(PHP 4, PECL pdflib >= 1.0.0)

PDF_moveto — Stabile?te punctul curent

Descrierea

bool PDF_moveto ( resource $p , float $x , float $y )

Stabile?te punctul curent pentru afi?area grafica. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_makespotcolor
PDF_new
PDF Func?ii


Creeaza un obiect PDFlib

PDF_moveto
PDF_open_ccitt
PDF Func?ii
PHP Manual

PDF_new

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_new — Creeaza un obiect PDFlib

Descrierea

resource PDF_new ( void )

Creeaza un obiect nou PDFlib cu parametri implici?i.

PDF_moveto
PDF_open_ccitt
PDF Func?ii


Deschide o imagine bruta CCITT [învechit]

PDF_new
PDF_open_file
PDF Func?ii
PHP Manual

PDF_open_ccitt

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_ccitt — Deschide o imagine bruta CCITT [învechit]

Descrierea

int PDF_open_ccitt ( resource $pdfdoc , string $filename , int $width , int $height , int $BitReverse , int $k , int $Blackls1 )

Deschide o imagine bruta CCITT.

Aceasta func?ie este învechita începând cu PDFlib versiunea 5, utiliza?i PDF_load_image() în loc.

PDF_new
PDF_open_file
PDF Func?ii


Creeaza un fi?ier PDF [învechit]

PDF_open_ccitt
PDF_open_gif
PDF Func?ii
PHP Manual

PDF_open_file

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_file — Creeaza un fi?ier PDF [învechit]

Descrierea

bool PDF_open_file ( resource $p , string $filename )

Creeaza un fi?ier nou PDF utilizând numele fi?ierului furnizat. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i PDF_begin_document() în loc.

PDF_open_ccitt
PDF_open_gif
PDF Func?ii


Deschide o imagine GIF [învechit]

PDF_open_file
PDF_open_image_file
PDF Func?ii
PHP Manual

PDF_open_gif

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_gif — Deschide o imagine GIF [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_load_image() în loc.

PDF_open_file
PDF_open_image_file
PDF Func?ii


Cite?te o imagine dintr-un fi?ier [învechit]

PDF_open_gif
PDF_open_image
PDF Func?ii
PHP Manual

PDF_open_image_file

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_image_file — Cite?te o imagine dintr-un fi?ier [învechit]

Descrierea

int PDF_open_image_file ( resource $p , string $imagetype , string $filename , string $stringparam , int $intparam )

Deschide un fi?ier cu imagine.

Aceasta func?ie este învechita începând cu PDFlib versiunea 5, utiliza?i PDF_load_image() cu op?iunile colorize, ignoremask, invert, mask, masked ?i page în loc.

PDF_open_gif
PDF_open_image
PDF Func?ii


Utilizeaza datele imaginii [învechit]

PDF_open_image_file
PDF_open_jpeg
PDF Func?ii
PHP Manual

PDF_open_image

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_image — Utilizeaza datele imaginii [învechit]

Descrierea

int PDF_open_image ( resource $p , string $imagetype , string $source , string $data , int $length , int $width , int $height , int $components , int $bpc , string $params )

Utilizeaza datele imaginii din diferite surse de date.

Aceasta func?ie este învechita începând cu PDFlib versiunea 5, utiliza?i fi?iere virtuale ?i PDF_load_image() în loc.

PDF_open_image_file
PDF_open_jpeg
PDF Func?ii


Deschide o imagine JPEG [învechit]

PDF_open_image
PDF_open_memory_image
PDF Func?ii
PHP Manual

PDF_open_jpeg

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_jpeg — Deschide o imagine JPEG [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_load_image() în loc.

PDF_open_image
PDF_open_memory_image
PDF Func?ii


Deschide o imagine creata cu func?iile de imagini ale PHP [nu este sus?inut]

PDF_open_jpeg
PDF_open_pdi_document
PDF Func?ii
PHP Manual

PDF_open_memory_image

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_memory_image — Deschide o imagine creata cu func?iile de imagini ale PHP [nu este sus?inut]

Descrierea

int PDF_open_memory_image ( resource $p , resource $image )

Aceasta func?ie nu este sus?inuta de PDFlib GmbH.

PDF_open_jpeg
PDF_open_pdi_document
PDF Func?ii


Prepare a pdi document

PDF_open_memory_image
PDF_open_pdi_page
PDF Func?ii
PHP Manual

PDF_open_pdi_document

(PECL pdflib >= 2.1.0)

PDF_open_pdi_document — Prepare a pdi document

Descrierea

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 Func?ii


Pregate?te o pagina

PDF_open_pdi_document
PDF_open_pdi
PDF Func?ii
PHP Manual

PDF_open_pdi_page

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_pdi_page — Pregate?te o pagina

Descrierea

int PDF_open_pdi_page ( resource $p , int $doc , int $pagenumber , string $optlist )

Pregate?te o pagina pentru utilizare ulterioara cu PDF_fit_pdi_page().

PDF_open_pdi_document
PDF_open_pdi
PDF Func?ii


Deschide un fi?ier PDF [învechit]

PDF_open_pdi_page
PDF_open_tiff
PDF Func?ii
PHP Manual

PDF_open_pdi

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_pdi — Deschide un fi?ier PDF [învechit]

Descrierea

int PDF_open_pdi ( resource $pdfdoc , string $filename , string $optlist , int $len )

Deschide un document PDF dintr-un fi?ier de disc sau virtual ?i îl pregate?te pentru utilizare ulterioara.

Aceasta func?ie este învechita începând cu PDFlib versiunea 7, utiliza?i PDF_open_pdi_document() în loc.

PDF_open_pdi_page
PDF_open_tiff
PDF Func?ii


Deschide o imagine TIFF [învechit]

PDF_open_pdi
PDF_pcos_get_number
PDF Func?ii
PHP Manual

PDF_open_tiff

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_tiff — Deschide o imagine TIFF [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_load_image() în loc.

PDF_open_pdi
PDF_pcos_get_number
PDF Func?ii


Ob?ine valoarea unei cai pCOS, de tip numeric sau boolean

PDF_open_tiff
PDF_pcos_get_stream
PDF Func?ii
PHP Manual

PDF_pcos_get_number

(PECL pdflib >= 2.1.0)

PDF_pcos_get_number — Ob?ine valoarea unei cai pCOS, de tip numeric sau boolean

Descrierea

float PDF_pcos_get_number ( resource $p , int $doc , string $path )

Ob?ine valoarea unei cai pCOS, de tip numeric sau boolean.

PDF_open_tiff
PDF_pcos_get_stream
PDF Func?ii


Ob?ine con?inutul unei cai pCOS, de tip stream, fstream sau string

PDF_pcos_get_number
PDF_pcos_get_string
PDF Func?ii
PHP Manual

PDF_pcos_get_stream

(PECL pdflib >= 2.1.0)

PDF_pcos_get_stream — Ob?ine con?inutul unei cai pCOS, de tip stream, fstream sau string

Descrierea

string PDF_pcos_get_stream ( resource $p , int $doc , string $optlist , string $path )

Ob?ine con?inutul unei cai pCOS, de tip stream, fstream sau string.

PDF_pcos_get_number
PDF_pcos_get_string
PDF Func?ii


Ob?ine valoarea unei cai pCOS, de tip name, string sau boolean

PDF_pcos_get_stream
PDF_place_image
PDF Func?ii
PHP Manual

PDF_pcos_get_string

(PECL pdflib >= 2.1.0)

PDF_pcos_get_string — Ob?ine valoarea unei cai pCOS, de tip name, string sau boolean

Descrierea

string PDF_pcos_get_string ( resource $p , int $doc , string $path )

Ob?ine valoarea unei cai pCOS, de tip name, string sau boolean.

PDF_pcos_get_stream
PDF_place_image
PDF Func?ii


Plaseaza o imagine pe pagina [învechit]

PDF_pcos_get_string
PDF_place_pdi_page
PDF Func?ii
PHP Manual

PDF_place_image

(PHP 4, PECL pdflib >= 1.0.0)

PDF_place_image — Plaseaza o imagine pe pagina [învechit]

Descrierea

bool PDF_place_image ( resource $pdfdoc , int $image , float $x , float $y , float $scale )

Plaseaza o imagine ?i îi modifica scara. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 5, utiliza?i PDF_fit_image() în loc.

PDF_pcos_get_string
PDF_place_pdi_page
PDF Func?ii


Plaseaza o pagina PDF [învechit]

PDF_place_image
PDF_process_pdi
PDF Func?ii
PHP Manual

PDF_place_pdi_page

(PHP 4 >= 4.0.6, PECL pdflib >= 1.0.0)

PDF_place_pdi_page — Plaseaza o pagina PDF [învechit]

Descrierea

bool PDF_place_pdi_page ( resource $pdfdoc , int $page , float $x , float $y , float $sx , float $sy )

Plaseaza o pagina PDF ?i îi modifica scara. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 5, utiliza?i PDF_fit_pdi_page() în loc.

PDF_place_image
PDF_process_pdi
PDF Func?ii


Proceseaza un document PDF importat

PDF_place_pdi_page
PDF_rect
PDF Func?ii
PHP Manual

PDF_process_pdi

(PECL pdflib >= 2.0.0)

PDF_process_pdi — Proceseaza un document PDF importat

Descrierea

int PDF_process_pdi ( resource $pdfdoc , int $doc , int $page , string $optlist )

Proceseaza anumite elemente ale unui document PDF importat.

PDF_place_pdi_page
PDF_rect
PDF Func?ii


Deseneaza un dreptunghi

PDF_process_pdi
PDF_restore
PDF Func?ii
PHP Manual

PDF_rect

(PHP 4, PECL pdflib >= 1.0.0)

PDF_rect — Deseneaza un dreptunghi

Descrierea

bool PDF_rect ( resource $p , float $x , float $y , float $width , float $height )

Deseneaza un dreptunghi. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_process_pdi
PDF_restore
PDF Func?ii


Restabile?te starea grafica

PDF_rect
PDF_resume_page
PDF Func?ii
PHP Manual

PDF_restore

(PHP 4, PECL pdflib >= 1.0.0)

PDF_restore — Restabile?te starea grafica

Descrierea

bool PDF_restore ( resource $p )

Restabile?te cea mai recent salvata stare grafica. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_rect
PDF_resume_page
PDF Func?ii


Continua o pagina

PDF_restore
PDF_rotate
PDF Func?ii
PHP Manual

PDF_resume_page

(PECL pdflib >= 2.0.0)

PDF_resume_page — Continua o pagina

Descrierea

bool PDF_resume_page ( resource $pdfdoc , string $optlist )

Continua o pagina pentru a-i adauga mai mult con?inut.

PDF_restore
PDF_rotate
PDF Func?ii


Rote?te sistemul de coordonate

PDF_resume_page
PDF_save
PDF Func?ii
PHP Manual

PDF_rotate

(PHP 4, PECL pdflib >= 1.0.0)

PDF_rotate — Rote?te sistemul de coordonate

Descrierea

bool PDF_rotate ( resource $p , float $phi )

Rote?te sistemul de coordonate. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_resume_page
PDF_save
PDF Func?ii


Salveaza starea grafica

PDF_rotate
PDF_scale
PDF Func?ii
PHP Manual

PDF_save

(PHP 4, PECL pdflib >= 1.0.0)

PDF_save — Salveaza starea grafica

Descrierea

bool PDF_save ( resource $p )

Salveaza starea grafica curenta. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_rotate
PDF_scale
PDF Func?ii


Modifica scara sistemului de coordonate

PDF_save
PDF_set_border_color
PDF Func?ii
PHP Manual

PDF_scale

(PHP 4, PECL pdflib >= 1.0.0)

PDF_scale — Modifica scara sistemului de coordonate

Descrierea

bool PDF_scale ( resource $p , float $sx , float $sy )

Modifica scara sistemului de coordonate. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_save
PDF_set_border_color
PDF Func?ii


Stabile?te culoarea bordurii adnotarilor [învechit]

PDF_scale
PDF_set_border_dash
PDF Func?ii
PHP Manual

PDF_set_border_color

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_border_color — Stabile?te culoarea bordurii adnotarilor [învechit]

Descrierea

bool PDF_set_border_color ( resource $p , float $red , float $green , float $blue )

Stabile?te culoarea bordurii pentru diferite tipuri de adnotari. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i op?iunea annotcolor în PDF_create_annotation() în loc.

PDF_scale
PDF_set_border_dash
PDF Func?ii


Stabile?te stilul liniei bordurii adnotarilor [învechit]

PDF_set_border_color
PDF_set_border_style
PDF Func?ii
PHP Manual

PDF_set_border_dash

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_set_border_dash — Stabile?te stilul liniei bordurii adnotarilor [învechit]

Descrierea

bool PDF_set_border_dash ( resource $pdfdoc , float $black , float $white )

Stabile?te stilul liniei bordurii diferitor tipuri de adnotari. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i op?iunea dasharray în PDF_create_annotation() în loc.

PDF_set_border_color
PDF_set_border_style
PDF Func?ii


Stabile?te stilul bordurii adnotarilor [învechit]

PDF_set_border_dash
PDF_set_char_spacing
PDF Func?ii
PHP Manual

PDF_set_border_style

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_border_style — Stabile?te stilul bordurii adnotarilor [învechit]

Descrierea

bool PDF_set_border_style ( resource $pdfdoc , string $style , float $width )

Stabile?te stilul bordurii diferitor tipuri de adnotari. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i op?iunile borderstyle ?i linewidth în PDF_create_annotation() în loc.

PDF_set_border_dash
PDF_set_char_spacing
PDF Func?ii


Stabile?te spa?ierea dintre caractere [învechit]

PDF_set_border_style
PDF_set_duration
PDF Func?ii
PHP Manual

PDF_set_char_spacing

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_char_spacing — Stabile?te spa?ierea dintre caractere [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_set_value() cu parametrul charspacing în loc.

PDF_set_border_style
PDF_set_duration
PDF Func?ii


Stabile?te durata dintre pagini [învechit]

PDF_set_char_spacing
PDF_set_gstate
PDF Func?ii
PHP Manual

PDF_set_duration

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_duration — Stabile?te durata dintre pagini [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i op?iunea duration în PDF_begin_page_ext() sau PDF_end_page_ext() în loc.

PDF_set_char_spacing
PDF_set_gstate
PDF Func?ii


Activeaza obiectul starii grafice

PDF_set_duration
PDF_set_horiz_scaling
PDF Func?ii
PHP Manual

PDF_set_gstate

(PECL pdflib >= 2.0.0)

PDF_set_gstate — Activeaza obiectul starii grafice

Descrierea

bool PDF_set_gstate ( resource $pdfdoc , int $gstate )

Activeaza obiectul starii grafice.

PDF_set_duration
PDF_set_horiz_scaling
PDF Func?ii


Stabile?te marimea scarii textului pe orizontala [învechit]

PDF_set_gstate
PDF_set_info_author
PDF Func?ii
PHP Manual

PDF_set_horiz_scaling

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_horiz_scaling — Stabile?te marimea scarii textului pe orizontala [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_set_value() cu parametrul horizscaling în loc.

PDF_set_gstate
PDF_set_info_author
PDF Func?ii


Completeaza câmpul documentului cu informa?ia despre autor [învechit]

PDF_set_horiz_scaling
PDF_set_info_creator
PDF Func?ii
PHP Manual

PDF_set_info_author

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_author — Completeaza câmpul documentului cu informa?ia despre autor [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_set_info() în loc.

PDF_set_horiz_scaling
PDF_set_info_creator
PDF Func?ii


Completeaza câmpul documentului cu informa?ia despre creator [învechit]

PDF_set_info_author
PDF_set_info_keywords
PDF Func?ii
PHP Manual

PDF_set_info_creator

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_creator — Completeaza câmpul documentului cu informa?ia despre creator [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_set_info() în loc.

PDF_set_info_author
PDF_set_info_keywords
PDF Func?ii


Completeaza câmpul documentului cu cuvintele-cheie [învechit]

PDF_set_info_creator
PDF_set_info_subject
PDF Func?ii
PHP Manual

PDF_set_info_keywords

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_keywords — Completeaza câmpul documentului cu cuvintele-cheie [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_set_info() în loc.

PDF_set_info_creator
PDF_set_info_subject
PDF Func?ii


Completeaza câmpul documentului cu subiectul [învechit]

PDF_set_info_keywords
PDF_set_info_title
PDF Func?ii
PHP Manual

PDF_set_info_subject

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_subject — Completeaza câmpul documentului cu subiectul [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_set_info() în loc.

PDF_set_info_keywords
PDF_set_info_title
PDF Func?ii


Completeaza câmpul documentului cu titlul [învechit]

PDF_set_info_subject
PDF_set_info
PDF Func?ii
PHP Manual

PDF_set_info_title

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_title — Completeaza câmpul documentului cu titlul [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_set_info() în loc.

PDF_set_info_subject
PDF_set_info
PDF Func?ii


Completeaza un câmp informa?ional al documentului

PDF_set_info_title
PDF_set_layer_dependency
PDF Func?ii
PHP Manual

PDF_set_info

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_set_info — Completeaza un câmp informa?ional al documentului

Descrierea

bool PDF_set_info ( resource $p , string $key , string $value )

Completeaza câmpul informa?ional key al documentului cu valoarea value. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_set_info_title
PDF_set_layer_dependency
PDF Func?ii


Define?te rela?iile dintre straturi

PDF_set_info
PDF_set_leading
PDF Func?ii
PHP Manual

PDF_set_layer_dependency

(PECL pdflib >= 2.0.0)

PDF_set_layer_dependency — Define?te rela?iile dintre straturi

Descrierea

bool PDF_set_layer_dependency ( resource $pdfdoc , string $type , string $optlist )

Define?te rela?iile ierarhice ?i de grup dintre straturi. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie necesita PDF 1.5.

PDF_set_info
PDF_set_leading
PDF Func?ii


Stabile?te distan?a dintre liniile de text [învechit]

PDF_set_layer_dependency
PDF_set_parameter
PDF Func?ii
PHP Manual

PDF_set_leading

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_leading — Stabile?te distan?a dintre liniile de text [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_set_value() cu parametrul leading în loc.

PDF_set_layer_dependency
PDF_set_parameter
PDF Func?ii


Stabile?te un parametru string

PDF_set_leading
PDF_set_text_matrix
PDF Func?ii
PHP Manual

PDF_set_parameter

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_parameter — Stabile?te un parametru string

Descrierea

bool PDF_set_parameter ( resource $p , string $key , string $value )

Stabile?te un careva parametru de tip string al PDFlib. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_set_leading
PDF_set_text_matrix
PDF Func?ii


Stabile?te matricea textului [învechit]

PDF_set_parameter
PDF_set_text_pos
PDF Func?ii
PHP Manual

PDF_set_text_matrix

(PHP 4 <= 4.0.4)

PDF_set_text_matrix — Stabile?te matricea textului [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_scale(), PDF_translate(), PDF_rotate() sau PDF_skew() în loc.

PDF_set_parameter
PDF_set_text_pos
PDF Func?ii


Stabile?te pozi?ia textului

PDF_set_text_matrix
PDF_set_text_rendering
PDF Func?ii
PHP Manual

PDF_set_text_pos

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_text_pos — Stabile?te pozi?ia textului

Descrierea

bool PDF_set_text_pos ( resource $p , float $x , float $y )

Stabile?te pozi?ia pentru afi?area textului pe pagina. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_set_text_matrix
PDF_set_text_rendering
PDF Func?ii


Determina redarea textului [învechit]

PDF_set_text_pos
PDF_set_text_rise
PDF Func?ii
PHP Manual

PDF_set_text_rendering

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_text_rendering — Determina redarea textului [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_set_value() cu parametrul textrendering în loc.

PDF_set_text_pos
PDF_set_text_rise
PDF Func?ii


Stabile?te înal?area textului [învechit]

PDF_set_text_rendering
PDF_set_value
PDF Func?ii
PHP Manual

PDF_set_text_rise

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_text_rise — Stabile?te înal?area textului [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_set_value() cu parametrul textrise în loc.

PDF_set_text_rendering
PDF_set_value
PDF Func?ii


Stabile?te un parametru numeric

PDF_set_text_rise
PDF_set_word_spacing
PDF Func?ii
PHP Manual

PDF_set_value

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_set_value — Stabile?te un parametru numeric

Descrierea

bool PDF_set_value ( resource $p , string $key , float $value )

Stabile?te valoarea unui parametru PDFlib de tip numeric. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_set_text_rise
PDF_set_word_spacing
PDF Func?ii


Stabile?te spa?ierea dintre cuvinte [învechit]

PDF_set_value
PDF_setcolor
PDF Func?ii
PHP Manual

PDF_set_word_spacing

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_word_spacing — Stabile?te spa?ierea dintre cuvinte [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 3, utiliza?i PDF_set_value() cu parametrul wordspacing în loc.

PDF_set_value
PDF_setcolor
PDF Func?ii


Stabile?te culorile de umplere ?i de trasare

PDF_set_word_spacing
PDF_setdash
PDF Func?ii
PHP Manual

PDF_setcolor

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setcolor — Stabile?te culorile de umplere ?i de trasare

Descrierea

bool PDF_setcolor ( resource $p , string $fstype , string $colorspace , float $c1 , float $c2 , float $c3 , float $c4 )

Stabile?te spa?iul curent de culori ?i culoarea. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_set_word_spacing
PDF_setdash
PDF Func?ii


Stabile?te un tipar al liniei obi?nuit

PDF_setcolor
PDF_setdashpattern
PDF Func?ii
PHP Manual

PDF_setdash

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setdash — Stabile?te un tipar al liniei obi?nuit

Descrierea

bool PDF_setdash ( resource $pdfdoc , float $b , float $w )

Stabile?te tiparul curent al liniei în b unita?i negre ?i w unita?i albe. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_setcolor
PDF_setdashpattern
PDF Func?ii


Stabile?te tiparul liniei

PDF_setdash
PDF_setflat
PDF Func?ii
PHP Manual

PDF_setdashpattern

(PECL pdflib >= 2.0.0)

PDF_setdashpattern — Stabile?te tiparul liniei

Descrierea

bool PDF_setdashpattern ( resource $pdfdoc , string $optlist )

Stabile?te tiparul liniei definit de o lista de op?iuni. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_setdash
PDF_setflat
PDF Func?ii


Stabile?te platitudinea

PDF_setdashpattern
PDF_setfont
PDF Func?ii
PHP Manual

PDF_setflat

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setflat — Stabile?te platitudinea

Descrierea

bool PDF_setflat ( resource $pdfdoc , float $flatness )

Stabile?te parametrul platitudinii. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_setdashpattern
PDF_setfont
PDF Func?ii


Stabile?te fontul

PDF_setflat
PDF_setgray_fill
PDF Func?ii
PHP Manual

PDF_setfont

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setfont — Stabile?te fontul

Descrierea

bool PDF_setfont ( resource $pdfdoc , int $font , float $fontsize )

Stabile?te fontul curent la marimea fontsize, utilizând un handle font întors de PDF_load_font(). Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_setflat
PDF_setgray_fill
PDF Func?ii


Stabile?te culoarea de umplere în sur [învechit]

PDF_setfont
PDF_setgray_stroke
PDF Func?ii
PHP Manual

PDF_setgray_fill

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setgray_fill — Stabile?te culoarea de umplere în sur [învechit]

Descrierea

bool PDF_setgray_fill ( resource $p , float $g )

Stabile?te culoarea de umplere la o valoare a surului între 0 ?i 1 inclusiv. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 4, utiliza?i PDF_setcolor() în loc.

PDF_setfont
PDF_setgray_stroke
PDF Func?ii


Stabile?te culoarea de trasare în sur [învechit]

PDF_setgray_fill
PDF_setgray
PDF Func?ii
PHP Manual

PDF_setgray_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setgray_stroke — Stabile?te culoarea de trasare în sur [învechit]

Descrierea

bool PDF_setgray_stroke ( resource $p , float $g )

Stabile?te culoarea curenta de trasare la o valoare a surului între 0 ?i 1 inclusiv. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 4, utiliza?i PDF_setcolor() în loc.

PDF_setgray_fill
PDF_setgray
PDF Func?ii


Stabile?te culoarea în sur [învechit]

PDF_setgray_stroke
PDF_setlinecap
PDF Func?ii
PHP Manual

PDF_setgray

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setgray — Stabile?te culoarea în sur [învechit]

Descrierea

bool PDF_setgray ( resource $p , float $g )

Stabile?te culorile de umplere ?i trasare într-o nuan?a a surului cuprinsa între 0 ?i 1 inclusiv. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 4, utiliza?i PDF_setcolor() în loc.

PDF_setgray_stroke
PDF_setlinecap
PDF Func?ii


Stabile?te parametrul capului de linie

PDF_setgray
PDF_setlinejoin
PDF Func?ii
PHP Manual

PDF_setlinecap

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setlinecap — Stabile?te parametrul capului de linie

Descrierea

bool PDF_setlinecap ( resource $p , int $linecap )

Stabile?te parametrul linecap pentru a controla forma de la capatul unei cai în ce prive?te trasarea.

PDF_setgray
PDF_setlinejoin
PDF Func?ii


Stabile?te parametrul linejoin

PDF_setlinecap
PDF_setlinewidth
PDF Func?ii
PHP Manual

PDF_setlinejoin

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setlinejoin — Stabile?te parametrul linejoin

Descrierea

bool PDF_setlinejoin ( resource $p , int $value )

Stabile?te parametrul linejoin pentru a specifica forma de la unghiurile cailor ce se traseaza. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_setlinecap
PDF_setlinewidth
PDF Func?ii


Stabile?te grosimea liniei

PDF_setlinejoin
PDF_setmatrix
PDF Func?ii
PHP Manual

PDF_setlinewidth

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setlinewidth — Stabile?te grosimea liniei

Descrierea

bool PDF_setlinewidth ( resource $p , float $width )

Stabile?te grosimea curenta a liniei. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_setlinejoin
PDF_setmatrix
PDF Func?ii


Stabile?te matricea curenta de transformare

PDF_setlinewidth
PDF_setmiterlimit
PDF Func?ii
PHP Manual

PDF_setmatrix

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setmatrix — Stabile?te matricea curenta de transformare

Descrierea

bool PDF_setmatrix ( resource $p , float $a , float $b , float $c , float $d , float $e , float $f )

Stabile?te matricea curenta de transformare în mod explicit. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_setlinewidth
PDF_setmiterlimit
PDF Func?ii


Stabile?te limita mitrei

PDF_setmatrix
PDF_setpolydash
PDF Func?ii
PHP Manual

PDF_setmiterlimit

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setmiterlimit — Stabile?te limita mitrei

Descrierea

bool PDF_setmiterlimit ( resource $pdfdoc , float $miter )

Stabile?te limita mitrei. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_setmatrix
PDF_setpolydash
PDF Func?ii


Stabile?te un tipar al liniei complicat [învechit]

PDF_setmiterlimit
PDF_setrgbcolor_fill
PDF Func?ii
PHP Manual

PDF_setpolydash

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setpolydash — Stabile?te un tipar al liniei complicat [învechit]

Descrierea

Aceasta func?ie este învechita începând cu PDFlib versiunea 5, utiliza?i PDF_setdashpattern() în loc.

PDF_setmiterlimit
PDF_setrgbcolor_fill
PDF Func?ii


Stabile?te valorile rgb ale culorii de umplere [învechit]

PDF_setpolydash
PDF_setrgbcolor_stroke
PDF Func?ii
PHP Manual

PDF_setrgbcolor_fill

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setrgbcolor_fill — Stabile?te valorile rgb ale culorii de umplere [învechit]

Descrierea

bool PDF_setrgbcolor_fill ( resource $p , float $red , float $green , float $blue )

Stabile?te culoarea curenta de umplere la valorile RGB furnizate. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 4, utiliza?i PDF_setcolor() în loc.

PDF_setpolydash
PDF_setrgbcolor_stroke
PDF Func?ii


Stabile?te valorile rgb ale culorii de trasare [învechit]

PDF_setrgbcolor_fill
PDF_setrgbcolor
PDF Func?ii
PHP Manual

PDF_setrgbcolor_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setrgbcolor_stroke — Stabile?te valorile rgb ale culorii de trasare [învechit]

Descrierea

bool PDF_setrgbcolor_stroke ( resource $p , float $red , float $green , float $blue )

Stabile?te culoarea curenta de trasare la valorile RGB furnizate. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 4, utiliza?i PDF_setcolor() în loc.

PDF_setrgbcolor_fill
PDF_setrgbcolor
PDF Func?ii


Stabile?te valorile rgb ale culorilor de umplere ?i de trasare [învechit]

PDF_setrgbcolor_stroke
PDF_shading_pattern
PDF Func?ii
PHP Manual

PDF_setrgbcolor

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setrgbcolor — Stabile?te valorile rgb ale culorilor de umplere ?i de trasare [învechit]

Descrierea

bool PDF_setrgbcolor ( resource $p , float $red , float $green , float $blue )

Stabile?te culorile curente de umplere ?i de trasare la valorile RGB furnizate. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Aceasta func?ie este învechita începând cu PDFlib versiunea 4, utiliza?i PDF_setcolor() în loc.

PDF_setrgbcolor_stroke
PDF_shading_pattern
PDF Func?ii


Define?te tiparul de umbrire

PDF_setrgbcolor
PDF_shading
PDF Func?ii
PHP Manual

PDF_shading_pattern

(PECL pdflib >= 2.0.0)

PDF_shading_pattern — Define?te tiparul de umbrire

Descrierea

int PDF_shading_pattern ( resource $pdfdoc , int $shading , string $optlist )

Define?te un tipar de umbrire utilizând un obiect de umbrire.

Aceasta func?ie necesita PDF 1.4 sau ulterior.

PDF_setrgbcolor
PDF_shading
PDF Func?ii


Define?te amestecarea

PDF_shading_pattern
PDF_shfill
PDF Func?ii
PHP Manual

PDF_shading

(PECL pdflib >= 2.0.0)

PDF_shading — Define?te amestecarea

Descrierea

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 )

Define?te un amestec dintre culoarea curenta de umplere ?i o alta culoare.

Aceasta func?ie necesita PDF 1.4 sau ulterior.

PDF_shading_pattern
PDF_shfill
PDF Func?ii


Umple o regiune cu umbrire

PDF_shading
PDF_show_boxed
PDF Func?ii
PHP Manual

PDF_shfill

(PECL pdflib >= 2.0.0)

PDF_shfill — Umple o regiune cu umbrire

Descrierea

bool PDF_shfill ( resource $pdfdoc , int $shading )

Umple o regiune cu o umbrire bazându-se pe un obiect de umbrire.

Aceasta func?ie necesita PDF 1.4 sau ulterior.

PDF_shading
PDF_show_boxed
PDF Func?ii


Afi?eaza un text într-o caseta [învechit]

PDF_shfill
PDF_show_xy
PDF Func?ii
PHP Manual

PDF_show_boxed

(PHP 4, PECL pdflib >= 1.0.0)

PDF_show_boxed — Afi?eaza un text într-o caseta [învechit]

Descrierea

int PDF_show_boxed ( resource $p , string $text , float $left , float $top , float $width , float $height , string $mode , string $feature )

Aceasta func?ie este învechita începând cu PDFlib versiunea 6, utiliza?i în loc PDF_fit_textline() pentru o singura linie, sau func?iile PDF_*_textflow() pentru formatarea pe mai multe linii.

PDF_shfill
PDF_show_xy
PDF Func?ii


Afi?eaza un text la pozi?ia data

PDF_show_boxed
PDF_show
PDF Func?ii
PHP Manual

PDF_show_xy

(PHP 4, PECL pdflib >= 1.0.0)

PDF_show_xy — Afi?eaza un text la pozi?ia data

Descrierea

bool PDF_show_xy ( resource $p , string $text , float $x , float $y )

Afi?eaza text în fontul curent. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_show_boxed
PDF_show
PDF Func?ii


Afi?eaza un text în pozi?ia curenta

PDF_show_xy
PDF_skew
PDF Func?ii
PHP Manual

PDF_show

(PHP 4, PECL pdflib >= 1.0.0)

PDF_show — Afi?eaza un text în pozi?ia curenta

Descrierea

bool PDF_show ( resource $pdfdoc , string $text )

Afi?eaza text cu fontul ?i dimensiunea curenta în pozi?ia curenta. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_show_xy
PDF_skew
PDF Func?ii


Deformeaza oblic sistemul de coordonate

PDF_show
PDF_stringwidth
PDF Func?ii
PHP Manual

PDF_skew

(PHP 4, PECL pdflib >= 1.0.0)

PDF_skew — Deformeaza oblic sistemul de coordonate

Descrierea

bool PDF_skew ( resource $p , float $alpha , float $beta )

Deformeaza oblic sistemul de coordonate în direc?ia x ?i y la alpha ?i beta grade respectiv. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_show
PDF_stringwidth
PDF Func?ii


Întoarce la?imea textului

PDF_skew
PDF_stroke
PDF Func?ii
PHP Manual

PDF_stringwidth

(PHP 4, PECL pdflib >= 1.0.0)

PDF_stringwidth — Întoarce la?imea textului

Descrierea

float PDF_stringwidth ( resource $p , string $text , int $font , float $fontsize )

Întoarce la?imea textului text într-un font arbitrar.

PDF_skew
PDF_stroke
PDF Func?ii


Traseaza o cale

PDF_stringwidth
PDF_suspend_page
PDF Func?ii
PHP Manual

PDF_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_stroke — Traseaza o cale

Descrierea

bool PDF_stroke ( resource $p )

Traseaza calea cu culoarea ?i grosimea liniei curente ?i o cura?a. Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

PDF_stringwidth
PDF_suspend_page
PDF Func?ii


Suspendeaza o pagina

PDF_stroke
PDF_translate
PDF Func?ii
PHP Manual

PDF_suspend_page

(PECL pdflib >= 2.0.0)

PDF_suspend_page — Suspendeaza o pagina

Descrierea

bool PDF_suspend_page ( resource $pdfdoc , string $optlist )

Suspendeaza pagina curenta pentru ca ea sa poata fi reluata ulterior cu PDF_resume_page().

PDF_stroke
PDF_translate
PDF Func?ii


Stabile?te originea sistemului de coordonate

PDF_suspend_page
PDF_utf16_to_utf8
PDF Func?ii
PHP Manual

PDF_translate

(PHP 4, PECL pdflib >= 1.0.0)

PDF_translate — Stabile?te originea sistemului de coordonate

Descrierea

bool PDF_translate ( resource $p , float $tx , float $ty )

Transleaza originea sistemului de coordonate.

PDF_suspend_page
PDF_utf16_to_utf8
PDF Func?ii


Converte?te un string din UTF-16 în UTF-8

PDF_translate
PDF_utf32_to_utf16
PDF Func?ii
PHP Manual

PDF_utf16_to_utf8

(PECL pdflib >= 2.0.3)

PDF_utf16_to_utf8 — Converte?te un string din UTF-16 în UTF-8

Descrierea

string PDF_utf16_to_utf8 ( resource $pdfdoc , string $utf16string )

Converte?te un string din formatul UTF-16 în UTF-8.

PDF_translate
PDF_utf32_to_utf16
PDF Func?ii


Converte?te un string din UTF-32 în UTF-16

PDF_utf16_to_utf8
PDF_utf8_to_utf16
PDF Func?ii
PHP Manual

PDF_utf32_to_utf16

(PECL pdflib >= Unknown future)

PDF_utf32_to_utf16 — Converte?te un string din UTF-32 în UTF-16

Descrierea

string PDF_utf32_to_utf16 ( resource $pdfdoc , string $utf32string , string $ordering )

Converte?te un string din formatul UTF-32 în UTF-16.

PDF_utf16_to_utf8
PDF_utf8_to_utf16
PDF Func?ii


Converte?te un string din UTF-8 în UTF-16

PDF_utf32_to_utf16
PS
PDF Func?ii
PHP Manual

PDF_utf8_to_utf16

(PECL pdflib >= 2.0.3)

PDF_utf8_to_utf16 — Converte?te un string din UTF-8 în UTF-16

Descrierea

string PDF_utf8_to_utf16 ( resource $pdfdoc , string $utf8string , string $ordering )

Converte?te un string din formatul UTF-8 în UTF-16.

PDF_utf32_to_utf16
PS
PDF Func?ii


PostScript document creation

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii PS
    • 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
Introducere
Ie?iri MIME non-textuale


Introducere

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
Instalarea / configurarea
PS


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
PS


Necesita?i

You need at least pslib >= 0.1.12. The ps library (pslib) is available at » http://pslib.sourceforge.net/.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/ps.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

This extension defines a PostScript document resource returned by ps_new().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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 |

Tipurile resurselor
Func?ii PS
PS


Func?ii PS

Informa?ii de contact

Daca ave?i comentarii, corectari de bug-uri, îmbunata?iri pentru aceasta extensie, sau pentru biblioteca pslib, va rog sa-mi scrie?i un mesaj la adresa » steinm@php.net. Orice ajutor e binevenit.

Cuprins

  • 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
Constante predefinite
ps_add_bookmark
PS


Add bookmark to current page

Func?ii PS
ps_add_launchlink
Func?ii PS
PHP Manual

ps_add_bookmark

(PECL ps >= 1.1.0)

ps_add_bookmark — Add bookmark to current page

Descrierea

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.

Nota nu va fi vizibla daca documentul este tiparit sau vizualizat, dar va apare daca documentul este convertit în pdf fie de Acrobat Distiller™ sau de Ghostview.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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

Func?ii PS
ps_add_launchlink
Func?ii PS


Adds link which launches file

ps_add_bookmark
ps_add_locallink
Func?ii PS
PHP Manual

ps_add_launchlink

(PECL ps >= 1.1.0)

ps_add_launchlink — Adds link which launches file

Descrierea

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.

Nota nu va fi vizibla daca documentul este tiparit sau vizualizat, dar va apare daca documentul este convertit în pdf fie de Acrobat Distiller™ sau de Ghostview.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii PS


Adds link to a page in the same document

ps_add_launchlink
ps_add_note
Func?ii PS
PHP Manual

ps_add_locallink

(PECL ps >= 1.1.0)

ps_add_locallink — Adds link to a page in the same document

Descrierea

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.

Nota nu va fi vizibla daca documentul este tiparit sau vizualizat, dar va apare daca documentul este convertit în pdf fie de Acrobat Distiller™ sau de Ghostview.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii PS


Adds note to current page

ps_add_locallink
ps_add_pdflink
Func?ii PS
PHP Manual

ps_add_note

(PECL ps >= 1.1.0)

ps_add_note — Adds note to current page

Descrierea

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.

Nota nu va fi vizibla daca documentul este tiparit sau vizualizat, dar va apare daca documentul este convertit în pdf fie de Acrobat Distiller™ sau de Ghostview.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii PS


Adds link to a page in a second pdf document

ps_add_note
ps_add_weblink
Func?ii PS
PHP Manual

ps_add_pdflink

(PECL ps >= 1.1.0)

ps_add_pdflink — Adds link to a page in a second pdf document

Descrierea

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.

Nota nu va fi vizibla daca documentul este tiparit sau vizualizat, dar va apare daca documentul este convertit în pdf fie de Acrobat Distiller™ sau de Ghostview.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii PS


Adds link to a web location

ps_add_pdflink
ps_arc
Func?ii PS
PHP Manual

ps_add_weblink

(PECL ps >= 1.1.0)

ps_add_weblink — Adds link to a web location

Descrierea

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.

Nota nu va fi vizibla daca documentul este tiparit sau vizualizat, dar va apare daca documentul este convertit în pdf fie de Acrobat Distiller™ sau de Ghostview.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii PS


Draws an arc counterclockwise

ps_add_weblink
ps_arcn
Func?ii PS
PHP Manual

ps_arc

(PECL ps >= 1.1.0)

ps_arc — Draws an arc counterclockwise

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_arcn() - Draws an arc clockwise

ps_add_weblink
ps_arcn
Func?ii PS


Draws an arc clockwise

ps_arc
ps_begin_page
Func?ii PS
PHP Manual

ps_arcn

(PECL ps >= 1.1.0)

ps_arcn — Draws an arc clockwise

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_arc() - Draws an arc counterclockwise

ps_arc
ps_begin_page
Func?ii PS


Start a new page

ps_arcn
ps_begin_pattern
Func?ii PS
PHP Manual

ps_begin_page

(PECL ps >= 1.1.0)

ps_begin_page — Start a new page

Descrierea

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.

Nota:

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_end_page() - End a page
  • ps_findfont() - Loads a font
  • ps_set_info() - Sets information fields of document

ps_arcn
ps_begin_pattern
Func?ii PS


Start a new pattern

ps_begin_page
ps_begin_template
Func?ii PS
PHP Manual

ps_begin_pattern

(PECL ps >= 1.2.0)

ps_begin_pattern — Start a new pattern

Descrierea

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.

Parametri

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.

Valorile întoarse

The identifier of the pattern sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii PS


Start a new template

ps_begin_pattern
ps_circle
Func?ii PS
PHP Manual

ps_begin_template

(PECL ps >= 1.2.0)

ps_begin_template — Start a new template

Descrierea

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().

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • ps_end_template() - End a template

ps_begin_pattern
ps_circle
Func?ii PS


Draws a circle

ps_begin_template
ps_clip
Func?ii PS
PHP Manual

ps_circle

(PECL ps >= 1.1.0)

ps_circle — Draws a circle

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_arc() - Draws an arc counterclockwise
  • ps_arcn() - Draws an arc clockwise

ps_begin_template
ps_clip
Func?ii PS


Clips drawing to current path

ps_circle
ps_close_image
Func?ii PS
PHP Manual

ps_clip

(PECL ps >= 1.1.0)

ps_clip — Clips drawing to current path

Descrierea

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.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_closepath() - Closes path

ps_circle
ps_close_image
Func?ii PS


Closes image and frees memory

ps_clip
ps_close
Func?ii PS
PHP Manual

ps_close_image

(PECL ps >= 1.1.0)

ps_close_image — Closes image and frees memory

Descrierea

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.

Parametri

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().

Valorile întoarse

Returns NULL on success sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_open_image() - Reads an image for later placement
  • ps_open_image_file() - Opens image from file

ps_clip
ps_close
Func?ii PS


Closes a PostScript document

ps_close_image
ps_closepath_stroke
Func?ii PS
PHP Manual

ps_close

(PECL ps >= 1.1.0)

ps_close — Closes a PostScript document

Descrierea

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.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_open_file() - Opens a file for output
  • ps_delete() - Deletes all resources of a PostScript document

ps_close_image
ps_closepath_stroke
Func?ii PS


Closes and strokes path

ps_close
ps_closepath
Func?ii PS
PHP Manual

ps_closepath_stroke

(PECL ps >= 1.1.0)

ps_closepath_stroke — Closes and strokes path

Descrierea

bool ps_closepath_stroke ( resource $psdoc )

Connects the last point with first point of a path and draws the resulting closed line.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_closepath() - Closes path

ps_close
ps_closepath
Func?ii PS


Closes path

ps_closepath_stroke
ps_continue_text
Func?ii PS
PHP Manual

ps_closepath

(PECL ps >= 1.1.0)

ps_closepath — Closes path

Descrierea

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..

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_clip() - Clips drawing to current path
  • ps_closepath_stroke() - Closes and strokes path

ps_closepath_stroke
ps_continue_text
Func?ii PS


Continue text in next line

ps_closepath
ps_curveto
Func?ii PS
PHP Manual

ps_continue_text

(PECL ps >= 1.1.0)

ps_continue_text — Continue text in next line

Descrierea

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()

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to output.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_show() - Output text
  • ps_show_xy() - Output text at given position
  • ps_show_boxed() - Output text in a box

ps_closepath
ps_curveto
Func?ii PS


Draws a curve

ps_continue_text
ps_delete
Func?ii PS
PHP Manual

ps_curveto

(PECL ps >= 1.1.0)

ps_curveto — Draws a curve

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_lineto() - Draws a line

ps_continue_text
ps_delete
Func?ii PS


Deletes all resources of a PostScript document

ps_curveto
ps_end_page
Func?ii PS
PHP Manual

ps_delete

(PECL ps >= 1.1.0)

ps_delete — Deletes all resources of a PostScript document

Descrierea

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.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_close() - Closes a PostScript document

ps_curveto
ps_end_page
Func?ii PS


End a page

ps_delete
ps_end_pattern
Func?ii PS
PHP Manual

ps_end_page

(PECL ps >= 1.1.0)

ps_end_page — End a page

Descrierea

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..

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_begin_page() - Start a new page

ps_delete
ps_end_pattern
Func?ii PS


End a pattern

ps_end_page
ps_end_template
Func?ii PS
PHP Manual

ps_end_pattern

(PECL ps >= 1.2.0)

ps_end_pattern — End a pattern

Descrierea

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.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_begin_pattern() - Start a new pattern

ps_end_page
ps_end_template
Func?ii PS


End a template

ps_end_pattern
ps_fill_stroke
Func?ii PS
PHP Manual

ps_end_template

(PECL ps >= 1.2.0)

ps_end_template — End a template

Descrierea

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.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_begin_template() - Start a new template

ps_end_pattern
ps_fill_stroke
Func?ii PS


Fills and strokes the current path

ps_end_template
ps_fill
Func?ii PS
PHP Manual

ps_fill_stroke

(PECL ps >= 1.1.0)

ps_fill_stroke — Fills and strokes the current path

Descrierea

bool ps_fill_stroke ( resource $psdoc )

Fills and draws the path constructed with previously called drawing functions like ps_lineto().

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_fill() - Fills the current path
  • ps_stroke() - Draws the current path

ps_end_template
ps_fill
Func?ii PS


Fills the current path

ps_fill_stroke
ps_findfont
Func?ii PS
PHP Manual

ps_fill

(PECL ps >= 1.1.0)

ps_fill — Fills the current path

Descrierea

bool ps_fill ( resource $psdoc )

Fills the path constructed with previously called drawing functions like ps_lineto().

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_fill_stroke() - Fills and strokes the current path
  • ps_stroke() - Draws the current path

ps_fill_stroke
ps_findfont
Func?ii PS


Loads a font

ps_fill
ps_get_buffer
Func?ii PS
PHP Manual

ps_findfont

(PECL ps >= 1.1.0)

ps_findfont — Loads a font

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the identifier of the font or zero in case of an error. The identifier is a positive number.

A se vedea ?i

  • ps_begin_page() - Start a new page
  • ps_setfont() - Sets font to use for following output

ps_fill
ps_get_buffer
Func?ii PS


Fetches the full buffer containig the generated PS data

ps_findfont
ps_get_parameter
Func?ii PS
PHP Manual

ps_get_buffer

(PECL ps >= 1.1.0)

ps_get_buffer — Fetches the full buffer containig the generated PS data

Descrierea

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.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

A se vedea ?i

  • ps_open_file() - Opens a file for output

ps_findfont
ps_get_parameter
Func?ii PS


Gets certain parameters

ps_get_buffer
ps_get_value
Func?ii PS
PHP Manual

ps_get_parameter

(PECL ps >= 1.1.0)

ps_get_parameter — Gets certain parameters

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the value of the parameter sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_set_parameter() - Sets certain parameters

ps_get_buffer
ps_get_value
Func?ii PS


Gets certain values

ps_get_parameter
ps_hyphenate
Func?ii PS
PHP Manual

ps_get_value

(PECL ps >= 1.1.0)

ps_get_value — Gets certain values

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the value of the parameter or FALSE.

A se vedea ?i

  • ps_set_value() - Sets certain values

ps_get_parameter
ps_hyphenate
Func?ii PS


Hyphenates a word

ps_get_value
ps_include_file
Func?ii PS
PHP Manual

ps_hyphenate

(PECL ps >= 1.1.1)

ps_hyphenate — Hyphenates a word

Descrierea

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.

Parametri

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.

Valorile întoarse

An array of integers indicating the position of possible breaks in the text sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

Ko-ordi-na-ten-sys-tem

A se vedea ?i

  • ps_show_boxed() - Output text in a box
  • locale(1)

ps_get_value
ps_include_file
Func?ii PS


Reads an external file with raw PostScript code

ps_hyphenate
ps_lineto
Func?ii PS
PHP Manual

ps_include_file

(PECL ps >= 1.3.4)

ps_include_file — Reads an external file with raw PostScript code

Descrierea

bool ps_include_file ( resource $psdoc , string $file )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

file

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ps_hyphenate
ps_lineto
Func?ii PS


Draws a line

ps_include_file
ps_makespotcolor
Func?ii PS
PHP Manual

ps_lineto

(PECL ps >= 1.1.0)

ps_lineto — Draws a line

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • ps_moveto() - Sets current point

ps_include_file
ps_makespotcolor
Func?ii PS


Create spot color

ps_lineto
ps_moveto
Func?ii PS
PHP Manual

ps_makespotcolor

(PECL ps >= 1.1.0)

ps_makespotcolor — Create spot color

Descrierea

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.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

Name of the spot color, e.g. Pantone 5565.

Valorile întoarse

The id of the new spot color or 0 in case of an error.

Exemple

Example #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.

A se vedea ?i

  • ps_setcolor() - Sets current color

ps_lineto
ps_moveto
Func?ii PS


Sets current point

ps_makespotcolor
ps_new
Func?ii PS
PHP Manual

ps_moveto

(PECL ps >= 1.1.0)

ps_moveto — Sets current point

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_lineto() - Draws a line

ps_makespotcolor
ps_new
Func?ii PS


Creates a new PostScript document object

ps_moveto
ps_open_file
Func?ii PS
PHP Manual

ps_new

(PECL ps >= 1.1.0)

ps_new — Creates a new PostScript document object

Descrierea

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.

Valorile întoarse

Resource of PostScript document sau FALSE în cazul e?ecului. The return value is passed to all other functions as the first argument.

A se vedea ?i

  • ps_delete() - Deletes all resources of a PostScript document

ps_moveto
ps_open_file
Func?ii PS


Opens a file for output

ps_new
ps_open_image_file
Func?ii PS
PHP Manual

ps_open_file

(PECL ps >= 1.1.0)

ps_open_file — Opens a file for output

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_close() - Closes a PostScript document

ps_new
ps_open_image_file
Func?ii PS


Opens image from file

ps_open_file
ps_open_image
Func?ii PS
PHP Manual

ps_open_image_file

(PECL ps >= 1.1.0)

ps_open_image_file — Opens image from file

Descrierea

int ps_open_image_file ( resource $psdoc , string $type , string $filename [, string $stringparam [, int $intparam = 0 ]] )

Loads an image for later use.

Parametri

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.

Valorile întoarse

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

A se vedea ?i

  • 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
Func?ii PS


Reads an image for later placement

ps_open_image_file
ps_open_memory_image
Func?ii PS
PHP Manual

ps_open_image

(PECL ps >= 1.1.0)

ps_open_image — Reads an image for later placement

Descrierea

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.

Parametri

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

Valorile întoarse

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

A se vedea ?i

  • 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
Func?ii PS


Takes an GD image and returns an image for placement in a PS document

ps_open_image
ps_place_image
Func?ii PS
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

Descrierea

int ps_open_memory_image ( resource $psdoc , int $gd )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

gd

ps_open_image
ps_place_image
Func?ii PS


Places image on the page

ps_open_memory_image
ps_rect
Func?ii PS
PHP Manual

ps_place_image

(PECL ps >= 1.1.0)

ps_place_image — Places image on the page

Descrierea

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().

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_open_image() - Reads an image for later placement
  • ps_open_image_file() - Opens image from file

ps_open_memory_image
ps_rect
Func?ii PS


Draws a rectangle

ps_place_image
ps_restore
Func?ii PS
PHP Manual

ps_rect

(PECL ps >= 1.1.0)

ps_rect — Draws a rectangle

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_arc() - Draws an arc counterclockwise
  • ps_cirle()
  • ps_lineto() - Draws a line

ps_place_image
ps_restore
Func?ii PS


Restore previously save context

ps_rect
ps_rotate
Func?ii PS
PHP Manual

ps_restore

(PECL ps >= 1.1.0)

ps_restore — Restore previously save context

Descrierea

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().

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_save() - Save current context

ps_rect
ps_rotate
Func?ii PS


Sets rotation factor

ps_restore
ps_save
Func?ii PS
PHP Manual

ps_rotate

(PECL ps >= 1.1.0)

ps_rotate — Sets rotation factor

Descrierea

bool ps_rotate ( resource $psdoc , float $rot )

Sets the rotation of the coordinate system.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

rot

Angle of rotation in degree.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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().

A se vedea ?i

  • ps_scale() - Sets scaling factor
  • ps_translate() - Sets translation

ps_restore
ps_save
Func?ii PS


Save current context

ps_rotate
ps_scale
Func?ii PS
PHP Manual

ps_save

(PECL ps >= 1.1.0)

ps_save — Save current context

Descrierea

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().

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_restore() - Restore previously save context

ps_rotate
ps_scale
Func?ii PS


Sets scaling factor

ps_save
ps_set_border_color
Func?ii PS
PHP Manual

ps_scale

(PECL ps >= 1.1.0)

ps_scale — Sets scaling factor

Descrierea

bool ps_scale ( resource $psdoc , float $x , float $y )

Sets horizontal and vertical scaling of the coordinate system.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

Scaling factor in horizontal direction.

y

Scaling factor in vertical direction.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_rotate() - Sets rotation factor
  • ps_translate() - Sets translation

ps_save
ps_set_border_color
Func?ii PS


Sets color of border for annotations

ps_scale
ps_set_border_dash
Func?ii PS
PHP Manual

ps_set_border_color

(PECL ps >= 1.1.0)

ps_set_border_color — Sets color of border for annotations

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii PS


Sets length of dashes for border of annotations

ps_set_border_color
ps_set_border_style
Func?ii PS
PHP Manual

ps_set_border_dash

(PECL ps >= 1.1.0)

ps_set_border_dash — Sets length of dashes for border of annotations

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii PS


Sets border style of annotations

ps_set_border_dash
ps_set_info
Func?ii PS
PHP Manual

ps_set_border_style

(PECL ps >= 1.1.0)

ps_set_border_style — Sets border style of annotations

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii PS


Sets information fields of document

ps_set_border_style
ps_set_parameter
Func?ii PS
PHP Manual

ps_set_info

(PECL ps >= 1.1.0)

ps_set_info — Sets information fields of document

Descrierea

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().

Parametri

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.

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_findfont() - Loads a font
  • ps_begin_page() - Start a new page

ps_set_border_style
ps_set_parameter
Func?ii PS


Sets certain parameters

ps_set_info
ps_set_text_pos
Func?ii PS
PHP Manual

ps_set_parameter

(PECL ps >= 1.1.0)

ps_set_parameter — Sets certain parameters

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_get_parameters()
  • ps_set_value() - Sets certain values

ps_set_info
ps_set_text_pos
Func?ii PS


Sets position for text output

ps_set_parameter
ps_set_value
Func?ii PS
PHP Manual

ps_set_text_pos

(PECL ps >= 1.1.0)

ps_set_text_pos — Sets position for text output

Descrierea

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().

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • ps_set_value() - Sets certain values
  • ps_show() - Output text

ps_set_parameter
ps_set_value
Func?ii PS


Sets certain values

ps_set_text_pos
ps_setcolor
Func?ii PS
PHP Manual

ps_set_value

(PECL ps >= 1.1.0)

ps_set_value — Sets certain values

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_get_value() - Gets certain values
  • ps_set_parameter() - Sets certain parameters

ps_set_text_pos
ps_setcolor
Func?ii PS


Sets current color

ps_set_value
ps_setdash
Func?ii PS
PHP Manual

ps_setcolor

(PECL ps >= 1.1.0)

ps_setcolor — Sets current color

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ps_set_value
ps_setdash
Func?ii PS


Sets appearance of a dashed line

ps_setcolor
ps_setflat
Func?ii PS
PHP Manual

ps_setdash

(PECL ps >= 1.1.0)

ps_setdash — Sets appearance of a dashed line

Descrierea

bool ps_setdash ( resource $psdoc , float $on , float $off )

Sets the length of the black and white portions of a dashed line.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_setpolydash() - Sets appearance of a dashed line

ps_setcolor
ps_setflat
Func?ii PS


Sets flatness

ps_setdash
ps_setfont
Func?ii PS
PHP Manual

ps_setflat

(PECL ps >= 1.1.0)

ps_setflat — Sets flatness

Descrierea

bool ps_setflat ( resource $psdoc , float $value )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

value

The value must be between 0.2 and 1.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ps_setdash
ps_setfont
Func?ii PS


Sets font to use for following output

ps_setflat
ps_setgray
Func?ii PS
PHP Manual

ps_setfont

(PECL ps >= 1.1.0)

ps_setfont — Sets font to use for following output

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_findfont() - Loads a font
  • ps_set_text_pos() - Sets position for text output for an example.

ps_setflat
ps_setgray
Func?ii PS


Sets gray value

ps_setfont
ps_setlinecap
Func?ii PS
PHP Manual

ps_setgray

(PECL ps >= 1.1.0)

ps_setgray — Sets gray value

Descrierea

bool ps_setgray ( resource $psdoc , float $gray )

Sets the gray value for all following drawing operations.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

gray

The value must be between 0 (white) and 1 (black).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_setcolor() - Sets current color

ps_setfont
ps_setlinecap
Func?ii PS


Sets appearance of line ends

ps_setgray
ps_setlinejoin
Func?ii PS
PHP Manual

ps_setlinecap

(PECL ps >= 1.1.0)

ps_setlinecap — Sets appearance of line ends

Descrierea

bool ps_setlinecap ( resource $psdoc , int $type )

Sets how line ends look like.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii PS


Sets how contected lines are joined

ps_setlinecap
ps_setlinewidth
Func?ii PS
PHP Manual

ps_setlinejoin

(PECL ps >= 1.1.0)

ps_setlinejoin — Sets how contected lines are joined

Descrierea

bool ps_setlinejoin ( resource $psdoc , int $type )

Sets how lines are joined.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_setlinecap() - Sets appearance of line ends
  • ps_setlinewidth() - Sets width of a line
  • ps_setmiterlimit() - Sets the miter limit

ps_setlinecap
ps_setlinewidth
Func?ii PS


Sets width of a line

ps_setlinejoin
ps_setmiterlimit
Func?ii PS
PHP Manual

ps_setlinewidth

(PECL ps >= 1.1.0)

ps_setlinewidth — Sets width of a line

Descrierea

bool ps_setlinewidth ( resource $psdoc , float $width )

Sets the line width for all following drawing operations.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of lines in points.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii PS


Sets the miter limit

ps_setlinewidth
ps_setoverprintmode
Func?ii PS
PHP Manual

ps_setmiterlimit

(PECL ps >= 1.1.0)

ps_setmiterlimit — Sets the miter limit

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii PS


Sets overprint mode

ps_setmiterlimit
ps_setpolydash
Func?ii PS
PHP Manual

ps_setoverprintmode

(PECL ps >= 1.3.0)

ps_setoverprintmode — Sets overprint mode

Descrierea

bool ps_setoverprintmode ( resource $psdoc , int $mode )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

mode

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ps_setmiterlimit
ps_setpolydash
Func?ii PS


Sets appearance of a dashed line

ps_setoverprintmode
ps_shading_pattern
Func?ii PS
PHP Manual

ps_setpolydash

(PECL ps >= 1.1.0)

ps_setpolydash — Sets appearance of a dashed line

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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.

A se vedea ?i

  • ps_setdash() - Sets appearance of a dashed line

ps_setoverprintmode
ps_shading_pattern
Func?ii PS


Creates a pattern based on a shading

ps_setpolydash
ps_shading
Func?ii PS
PHP Manual

ps_shading_pattern

(PECL ps >= 1.3.0)

ps_shading_pattern — Creates a pattern based on a shading

Descrierea

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.

Parametri

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.

Valorile întoarse

The identifier of the pattern sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_shading() - Creates a shading for later use
  • ps_shfill() - Fills an area with a shading

ps_setpolydash
ps_shading
Func?ii PS


Creates a shading for later use

ps_shading_pattern
ps_shfill
Func?ii PS
PHP Manual

ps_shading

(PECL ps >= 1.3.0)

ps_shading — Creates a shading for later use

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the identifier of the pattern sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_shading_pattern() - Creates a pattern based on a shading
  • ps_shfill() - Fills an area with a shading

ps_shading_pattern
ps_shfill
Func?ii PS


Fills an area with a shading

ps_shading
ps_show_boxed
Func?ii PS
PHP Manual

ps_shfill

(PECL ps >= 1.3.0)

ps_shfill — Fills an area with a shading

Descrierea

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.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

shadingid

The identifier of a shading previously created with ps_shading().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_shading() - Creates a shading for later use
  • ps_shading_pattern() - Creates a pattern based on a shading

ps_shading
ps_show_boxed
Func?ii PS


Output text in a box

ps_shfill
ps_show_xy2
Func?ii PS
PHP Manual

ps_show_boxed

(PECL ps >= 1.1.0)

ps_show_boxed — Output text in a box

Descrierea

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.

Parametri

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.

Valorile întoarse

Number of characters that could not be written.

A se vedea ?i

  • ps_continue_text() - Continue text in next line

ps_shfill
ps_show_xy2
Func?ii PS


Output text at position

ps_show_boxed
ps_show_xy
Func?ii PS
PHP Manual

ps_show_xy2

(PECL ps >= 1.1.0)

ps_show_xy2 — Output text at position

Descrierea

bool ps_show_xy2 ( resource $psdoc , string $text , int $len , float $xcoor , float $ycoor )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ps_show_boxed
ps_show_xy
Func?ii PS


Output text at given position

ps_show_xy2
ps_show2
Func?ii PS
PHP Manual

ps_show_xy

(PECL ps >= 1.1.0)

ps_show_xy — Output text at given position

Descrierea

bool ps_show_xy ( resource $psdoc , string $text , float $x , float $y )

Output a text at the given text position.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_continue_text() - Continue text in next line
  • ps_show() - Output text

ps_show_xy2
ps_show2
Func?ii PS


Output a text at current position

ps_show_xy
ps_show
Func?ii PS
PHP Manual

ps_show2

(PECL ps >= 1.1.0)

ps_show2 — Output a text at current position

Descrierea

bool ps_show2 ( resource $psdoc , string $text , int $len )

Output text at the current position. Do not print more than len characters.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output.

len

The maximum number of characters to print.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ps_show_xy
ps_show
Func?ii PS


Output text

ps_show2
ps_string_geometry
Func?ii PS
PHP Manual

ps_show

(PECL ps >= 1.1.0)

ps_show — Output text

Descrierea

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.

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii PS


Gets geometry of a string

ps_show
ps_stringwidth
Func?ii PS
PHP Manual

ps_string_geometry

(PECL ps >= 1.2.0)

ps_string_geometry — Gets geometry of a string

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • ps_continue_text() - Continue text in next line
  • ps_stringwidth() - Gets width of a string

ps_show
ps_stringwidth
Func?ii PS


Gets width of a string

ps_string_geometry
ps_stroke
Func?ii PS
PHP Manual

ps_stringwidth

(PECL ps >= 1.1.0)

ps_stringwidth — Gets width of a string

Descrierea

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.

Parametri

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.

Valorile întoarse

Width of a string in points.

A se vedea ?i

  • ps_string_geometry() - Gets geometry of a string

ps_string_geometry
ps_stroke
Func?ii PS


Draws the current path

ps_stringwidth
ps_symbol_name
Func?ii PS
PHP Manual

ps_stroke

(PECL ps >= 1.1.0)

ps_stroke — Draws the current path

Descrierea

bool ps_stroke ( resource $psdoc )

Draws the path constructed with previously called drawing functions like ps_lineto().

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii PS


Gets name of a glyph

ps_stroke
ps_symbol_width
Func?ii PS
PHP Manual

ps_symbol_name

(PECL ps >= 1.2.0)

ps_symbol_name — Gets name of a glyph

Descrierea

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.

Parametri

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.

Valorile întoarse

The name of a glyph in the given font.

A se vedea ?i

  • ps_symbol() - Output a glyph
  • ps_symbol_width() - Gets width of a glyph

ps_stroke
ps_symbol_width
Func?ii PS


Gets width of a glyph

ps_symbol_name
ps_symbol
Func?ii PS
PHP Manual

ps_symbol_width

(PECL ps >= 1.2.0)

ps_symbol_width — Gets width of a glyph

Descrierea

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.

Parametri

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.

Valorile întoarse

The width of a glyph in points.

A se vedea ?i

  • ps_symbol() - Output a glyph
  • ps_symbol_name() - Gets name of a glyph

ps_symbol_name
ps_symbol
Func?ii PS


Output a glyph

ps_symbol_width
ps_translate
Func?ii PS
PHP Manual

ps_symbol

(PECL ps >= 1.2.0)

ps_symbol — Output a glyph

Descrierea

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().

Parametri

psdoc

Resource identifier of the postscript file as returned by ps_new().

ord

The position of the glyph in the font encoding vector.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ps_symbol_name() - Gets name of a glyph
  • ps_symbol_width() - Gets width of a glyph

ps_symbol_width
ps_translate
Func?ii PS


Sets translation

ps_symbol
RPM Reader
Func?ii PS
PHP Manual

ps_translate

(PECL ps >= 1.1.0)

ps_translate — Sets translation

Descrierea

bool ps_translate ( resource $psdoc , float $x , float $y )

Sets a new initial point of the coordinate system.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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.

A se vedea ?i

  • ps_scale() - Sets scaling factor
  • ps_rotate() - Sets rotation factor

ps_symbol
RPM Reader
Func?ii PS


RPM Header Reading

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic usage
  • Func?ii ale cititorului RPM
    • 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
Introducere
Ie?iri MIME non-textuale


Introducere

This module allows you to read the meta information stored in the headers of a » RedHat Package Manager (» RPM) file.

RPM Reader
Instalarea / configurarea
RPM Reader


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
RPM Reader


Necesita?i

The RPMReader extension requires PHP 5.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/rpmreader.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

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.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.

Tipurile resurselor
Exemple
RPM Reader


Exemple

Cuprins

  • Basic usage
Constante predefinite
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.

Example #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);

?>
Exemple
Func?ii ale cititorului RPM
Exemple


Func?ii ale cititorului RPM

Cuprins

  • 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

Func?ii ale cititorului RPM
rpm_get_tag
Func?ii ale cititorului RPM
PHP Manual

rpm_close

(PECL rpmreader >= 0.1.0)

rpm_close — Closes an RPM file

Descrierea

bool rpm_close ( resource $rpmr )

rpm_close() will close an RPM file pointer.

Parametri

rpmr

A file pointer resource successfully opened by rpm_open().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 rpm_close() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?>

A se vedea ?i

  • rpm_open() - Opens an RPM file

Func?ii ale cititorului RPM
rpm_get_tag
Func?ii ale cititorului RPM


Retrieves a header tag from an RPM file

rpm_close
rpm_is_valid
Func?ii ale cititorului RPM
PHP Manual

rpm_get_tag

(PECL rpmreader >= 0.1.0)

rpm_get_tag — Retrieves a header tag from an RPM file

Descrierea

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.

Parametri

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.

Valorile întoarse

The return value can be of various types depending on the tagnum supplied to the function.

Exemple

Example #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);

?>

A se vedea ?i

  • rpm_open() - Opens an RPM file
  • rpm_close() - Closes an RPM file

rpm_close
rpm_is_valid
Func?ii ale cititorului RPM


Tests a filename for validity as an RPM file

rpm_get_tag
rpm_open
Func?ii ale cititorului RPM
PHP Manual

rpm_is_valid

(PECL rpmreader >= 0.1.0)

rpm_is_valid — Tests a filename for validity as an RPM file

Descrierea

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.

Parametri

filename

The filename of the RPM file you wish to check for validity.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii ale cititorului RPM


Opens an RPM file

rpm_is_valid
rpm_version
Func?ii ale cititorului RPM
PHP Manual

rpm_open

(PECL rpmreader >= 0.1.0)

rpm_open — Opens an RPM file

Descrierea

resource rpm_open ( string $filename )

rpm_open() will open an RPM file and will determine if the file is a valid RPM file.

Parametri

filename

The filename of the RPM file you wish to open.

Valorile întoarse

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.

Exemple

Example #1 rpm_open() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?>

A se vedea ?i

  • rpm_close() - Closes an RPM file

rpm_is_valid
rpm_version
Func?ii ale cititorului RPM


Returns a string representing the current version of the rpmreader extension

rpm_open
Extensii de control al proceselor
Func?ii ale cititorului RPM
PHP Manual

rpm_version

(PECL rpmreader >= 0.3.0)

rpm_version — Returns a string representing the current version of the rpmreader extension

Descrierea

string rpm_version ( void )

rpm_version() will return the current version of the rpmreader extension.

Valorile întoarse

rpm_version() will return a string representing the rpmreader version currently loaded in PHP.

Exemple

Example #1 rpm_version() example

<?php

$rpmr_ver = rpm_version();

echo "$rpmr_ver<br />\n";

?>

rpm_open
Extensii de control al proceselor
Func?ii ale cititorului RPM


Extensii de control al proceselor

  • Eio
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii eio
  • Ev
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Watchers
    • Watcher callbacks
    • Periodic watcher operation modes
    • Ev — The Ev class
    • EvCheck — The EvCheck class
    • EvChild — The EvChild class
    • EvEmbed — The EvEmbed class
    • EvFork — The EvFork class
    • EvIdle — The EvIdle class
    • EvIo — The EvIo class
    • EvLoop — The EvLoop class
    • EvPeriodic — The EvPeriodic class
    • EvPrepare — The EvPrepare class
    • EvSignal — The EvSignal class
    • EvStat — The EvStat class
    • EvTimer — The EvTimer class
    • EvWatcher — The EvWatcher class
  • Expect
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Expect
  • Libevent
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Libevent
  • PCNTL — Process Control
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii PCNTL
  • POSIX
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii POSIX
  • Program execution — System program execution
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Program execution Func?ii
  • pthreads
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Threaded — The Threaded class
    • Thread — The Thread class
    • Worker — The Worker class
    • Collectable — The Collectable interface
    • Modifiers — Method Modifiers
    • Pool — The Pool class
    • Mutex — The Mutex class
    • Cond — The Cond class
  • Semaphore — Semaphore, Shared Memory and IPC
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii de lucru cu Semafoare
  • Shared Memory
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii de lucru cu memoria partajata
  • Sync
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • SyncMutex — The SyncMutex class
    • SyncSemaphore — The SyncSemaphore class
    • SyncEvent — The SyncEvent class
    • SyncReaderWriter — The SyncReaderWriter class
    • SyncSharedMemory — The SyncSharedMemory class
rpm_version
Eio
Informa?ii de referin?a despre func?ii


Eio

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii eio
    • 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_get_last_error — Returns string describing the last error associated with a request resource
    • 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 — Creates a request group.
    • eio_init — (Re-)initialize Eio
    • 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_seek — Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence
    • 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
Extensii de control al proceselor
Introducere
Extensii de control al proceselor


Introducere

This extension provides asyncronous POSIX I/O by means of » libeio C library written by Marc Lehmann.

Nota: Aceasta extensie nu este disponibila pe platformele Windows.

Avertizare

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.

Example #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():

Example #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:

Example #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:

Example #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
Instalarea / configurarea
Eio


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Eio


Necesita?i

This extension has » libeio library embedded. So you do NOT need to install libeio separately.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/eio.

Pentru informa?ii despre instalarea manuala va rugam sa citi?i fi?ierul INSTALL inclus în pachet.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

There are two resource types in this extension: request and request group.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Request priority constants:

EIO_PRI_MIN (integer)
Request minimal prioriry
EIO_PRI_DEFAULT (integer)
Request default prioriry
EIO_PRI_MAX (integer)
Request maximal prioriry

eio_seek() whence argument:

EIO_SEEK_SET (integer)
The offset is set to specified number of bytes(offset).
EIO_SEEK_CUR (integer)
The offset is set to its current location plus offset bytes.
EIO_SEEK_END (integer)
The offset is set to the size of the file plus offset bytes.

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)

Nota:

EIO_S_I* constants have the same meaning as their S_I* POSIX counterparts.

Nota:

EIO_SYNC_FILE_* constants have the same meaning as their SYNC_FILE_** counterparts.

Nota:

EIO_O_* constants have the same meaning as their O_* POSIX counterparts.

Tipurile resurselor
Exemple
Eio


Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

resource(4) of type (EIO Request Descriptor)
my_nop 2

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

eio_chmod_ok

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

resource(6) of type (EIO Group Descriptor)
bool(true)
string(4) "some"
bool(true)

Example #5 Using eio with libevent extension

<?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 */
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)
int(0)
string(8) "nop data"
int(0)
string(10) "mkdir data"

Example #6 Using eio with event extension

<?php
$base = new EventBase();

// Retrieve eio polling stream.
// Note, this variable should be alive as long as the event loop is running.
$eio_stream = eio_get_event_stream();

// Bind eio polling stream to the event loop.
$poll_event = new Event($base, $eio_stream, Event::READ, function () {
  if (eio_nreqs()) {
    eio_poll();
  }
});
$poll_event->add();

// Add eio jobs
eio_nop(EIO_PRI_DEFAULT, function () {
  echo "eio_nop\n";
});

// Add events
$timer = Event::timer($base, function () {
  echo "2 seconds elapsed\n";
});
$timer->add(2);

// Dispatch events.
$base->dispatch();
?>

Exemplul de mai sus va afi?a ceva similar cu:

eio_nop
2 seconds elapsed

Constante predefinite
Func?ii eio
Eio


Func?ii eio

Cuprins

  • 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_get_last_error — Returns string describing the last error associated with a request resource
  • 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 — Creates a request group.
  • eio_init — (Re-)initialize Eio
  • 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_seek — Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence
  • 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
Exemple
eio_busy
Eio


Artificially increase load. Could be useful in tests, benchmarking.

Func?ii eio
eio_cancel
Func?ii eio
PHP Manual

eio_busy

(PECL eio >= 0.0.1dev)

eio_busy — Artificially increase load. Could be useful in tests, benchmarking.

Descrierea

resource eio_busy ( int $delay [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_busy() artificially increases load taking delay seconds to execute. May be used for debugging, or benchmarking.

Parametri

delay

Delay in seconds

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

This callback is called when all the group requests are done.

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_busy() returns request resource on success or FALSE on error.

A se vedea ?i

  • eio_nop
Func?ii eio
eio_cancel
Func?ii eio


Cancels a request

eio_busy
eio_chmod
Func?ii eio
PHP Manual

eio_cancel

(PECL eio >= 0.0.1dev)

eio_cancel — Cancels a request

Descrierea

void eio_cancel ( resource $req )

eio_cancel() cancels a request specified by req

Parametri

req

The request resource

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

resource(4) of type (EIO Request Descriptor)
my_nop 2

A se vedea ?i

  • eio_grp_cancel
eio_busy
eio_chmod
Func?ii eio


Change file/direcrory permissions.

eio_cancel
eio_chown
Func?ii eio
PHP Manual

eio_chmod

(PECL eio >= 0.0.1dev)

eio_chmod — Change file/direcrory permissions.

Descrierea

resource eio_chmod ( string $path , int $mode [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_chmod() changes file, or direcrory permissions. The new permissions are specified by mode.

Parametri

path

Path to the target file or directory

Avertizare

Evita?i caile relative

mode

The new permissions. E.g. 0644.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_chmod() returns request resource on success or FALSE on error.

A se vedea ?i

  • eio_chown
eio_cancel
eio_chown
Func?ii eio


Change file/direcrory permissions.

eio_chmod
eio_close
Func?ii eio
PHP Manual

eio_chown

(PECL eio >= 0.0.1dev)

eio_chown — Change file/direcrory permissions.

Descrierea

resource eio_chown ( string $path , int $uid [, int $gid = -1 [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]]] )

Changes file, or directory permissions.

Parametri

path

Path to file or directory.

Avertizare

Evita?i caile relative

uid

User ID. Is ignored when equal to -1.

gid

Group ID. Is ignored when equal to -1.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_chown() returns request resource on success or FALSE on error.

A se vedea ?i

  • eio_chmod
eio_chmod
eio_close
Func?ii eio


Close file

eio_chown
eio_custom
Func?ii eio
PHP Manual

eio_close

(PECL eio >= 0.0.1dev)

eio_close — Close file

Descrierea

resource eio_close ( mixed $fd [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_close() closes file specified by fd.

Parametri

fd

Stream, Socket resource, or numeric file descriptor

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_close() returns request resource on success or FALSE on error.

A se vedea ?i

  • eio_open
eio_chown
eio_custom
Func?ii eio


Execute custom request like any other eio_* call.

eio_close
eio_dup2
Func?ii eio
PHP Manual

eio_custom

(PECL eio >= 0.0.1dev)

eio_custom — Execute custom request like any other eio_* call.

Descrierea

resource eio_custom ( callable $execute , int $pri , callable $callback [, mixed $data = NULL ] )

eio_custom() executes custom function specified by execute processing it just like any other eio_* call.

Parametri

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

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_custom() returns request resource on success or FALSE on error.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
Func?ii eio


Duplicate a file descriptor

eio_custom
eio_event_loop
Func?ii eio
PHP Manual

eio_dup2

(PECL eio >= 0.0.1dev)

eio_dup2 — Duplicate a file descriptor

Descrierea

resource eio_dup2 ( mixed $fd , mixed $fd2 [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_dup2() duplicates file descriptor.

Parametri

fd

Source stream, Socket resource, or numeric file descriptor

fd2

Target stream, Socket resource, or numeric file descriptor

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_dup2() returns request resource on success or FALSE on error.

eio_custom
eio_event_loop
Func?ii eio


Polls libeio until all requests proceeded

eio_dup2
eio_fallocate
Func?ii eio
PHP Manual

eio_event_loop

(PECL eio >= 0.0.1dev)

eio_event_loop — Polls libeio until all requests proceeded

Descrierea

bool eio_event_loop ( void )

eio_event_loop() polls libeio until all requests proceeded.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

eio_event_loop() returns TRUE on success or FALSE on error.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

eio_chmod_ok

A se vedea ?i

  • eio_poll
eio_dup2
eio_fallocate
Func?ii eio


Allows the caller to directly manipulate the allocated disk space for a file

eio_event_loop
eio_fchmod
Func?ii eio
PHP Manual

eio_fallocate

(PECL eio >= 0.0.1dev)

eio_fallocate — Allows the caller to directly manipulate the allocated disk space for a file

Descrierea

resource eio_fallocate ( mixed $fd , int $mode , int $offset , int $length [, int $pri = EIO_PRI_DEFAULT [, callable $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.

Nota: File should be opened for writing

EIO_O_CREAT should be logically OR'd with EIO_O_WRONLY, or EIO_O_RDWR

Parametri

fd

Stream, Socket resource, or numeric 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

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_fallocate() returns request resource on success or FALSE on error.

eio_event_loop
eio_fchmod
Func?ii eio


Change file permissions.

eio_fallocate
eio_fchown
Func?ii eio
PHP Manual

eio_fchmod

(PECL eio >= 0.0.1dev)

eio_fchmod — Change file permissions.

Descrierea

resource eio_fchmod ( mixed $fd , int $mode [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_fchmod() changes permissions for the file specified by fd file descriptor.

Parametri

fd

Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open().

mode

The new permissions. E.g. 0644.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_fchmod() returns request resource on success or FALSE on error.

A se vedea ?i

  • eio_fchown
eio_fallocate
eio_fchown
Func?ii eio


Change file ownership

eio_fchmod
eio_fdatasync
Func?ii eio
PHP Manual

eio_fchown

(PECL eio >= 0.0.1dev)

eio_fchown — Change file ownership

Descrierea

resource eio_fchown ( mixed $fd , int $uid [, int $gid = -1 [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]]] )

eio_fchown() changes ownership of the file specified by fd file descriptor.

Parametri

fd

Stream, Socket resource, or numeric file descriptor.

uid

User ID. Is ignored when equal to -1.

gid

Group ID. Is ignored when equal to -1.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

A se vedea ?i

  • eio_fchmod
eio_fchmod
eio_fdatasync
Func?ii eio


Synchronize a file's in-core state with storage device.

eio_fchown
eio_fstat
Func?ii eio
PHP Manual

eio_fdatasync

(PECL eio >= 0.0.1dev)

eio_fdatasync — Synchronize a file's in-core state with storage device.

Descrierea

resource eio_fdatasync ( mixed $fd [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_fdatasync() synchronizes a file's in-core state with storage device.

Parametri

fd

Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open().

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_fdatasync() returns request resource on success or FALSE on error.

eio_fchown
eio_fstat
Func?ii eio


Get file status

eio_fdatasync
eio_fstatvfs
Func?ii eio
PHP Manual

eio_fstat

(PECL eio >= 0.0.1dev)

eio_fstat — Get file status

Descrierea

resource eio_fstat ( mixed $fd , int $pri , callable $callback [, mixed $data ] )

eio_fstat() returns file status information in result argument of callback

Parametri

fd

Stream, Socket resource, or numeric file descriptor.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_busy() returns request resource on success or FALSE on error.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)
}

A se vedea ?i

  • eio_lstat
  • eio_stat
eio_fdatasync
eio_fstatvfs
Func?ii eio


Get file system statistics

eio_fstat
eio_fsync
Func?ii eio
PHP Manual

eio_fstatvfs

(PECL eio >= 0.0.1dev)

eio_fstatvfs — Get file system statistics

Descrierea

resource eio_fstatvfs ( mixed $fd , int $pri , callable $callback [, mixed $data ] )

eio_fstatvfs() returns file system statistics in result of callback.

Parametri

fd

A file descriptor of a file within the mounted file system.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_fstatvfs() returns request resource on success or FALSE on error.

A se vedea ?i

  • eio_statvfs
eio_fstat
eio_fsync
Func?ii eio


Synchronize a file's in-core state with storage device

eio_fstatvfs
eio_ftruncate
Func?ii eio
PHP Manual

eio_fsync

(PECL eio >= 0.0.1dev)

eio_fsync — Synchronize a file's in-core state with storage device

Descrierea

resource eio_fsync ( mixed $fd [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

Synchronize a file's in-core state with storage device

Parametri

fd

Stream, Socket resource, or numeric file descriptor.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_fsync() returns request resource on success or FALSE on error.

A se vedea ?i

  • eio_sync
eio_fstatvfs
eio_ftruncate
Func?ii eio


Truncate a file

eio_fsync
eio_futime
Func?ii eio
PHP Manual

eio_ftruncate

(PECL eio >= 0.0.1dev)

eio_ftruncate — Truncate a file

Descrierea

resource eio_ftruncate ( mixed $fd [, int $offset = 0 [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]]] )

eio_ftruncate() causes a regular file referenced by fd file descriptor to be truncated to precisely length bytes.

Parametri

fd

Stream, Socket resource, or numeric file descriptor.

offset

Offset from beginning of the file

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_ftruncate() returns request resource on success or FALSE on error.

A se vedea ?i

  • eio_truncate
eio_fsync
eio_futime
Func?ii eio


Change file last access and modification times

eio_ftruncate
eio_get_event_stream
Func?ii eio
PHP Manual

eio_futime

(PECL eio >= 0.0.1dev)

eio_futime — Change file last access and modification times

Descrierea

resource eio_futime ( mixed $fd , float $atime , float $mtime [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_futime() changes file last access and modification times.

Parametri

fd

Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open()

atime

Access time

mtime

Modification time

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_futime() returns request resource on success or FALSE on error.

A se vedea ?i

  • eio_utime
eio_ftruncate
eio_get_event_stream
Func?ii eio


Get stream representing a variable used in internal communications with libeio.

eio_futime
eio_get_last_error
Func?ii eio
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.

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

eio_get_event_stream() returns stream on success; otherwise, NULL

Exemple

Example #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 */
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)
int(0)
string(8) "nop data"
int(0)
string(10) "mkdir data"
eio_futime
eio_get_last_error
Func?ii eio


Returns string describing the last error associated with a request resource

eio_get_event_stream
eio_grp_add
Func?ii eio
PHP Manual

eio_get_last_error

(PECL eio >= 1.0.0)

eio_get_last_error — Returns string describing the last error associated with a request resource

Descrierea

string eio_get_last_error ( resource $req )

eio_get_last_error() returns string describing the last error associated with req.

Parametri

req

The request resource

Valorile întoarse

eio_get_last_error() returns string describing the last error associated with the request resource specified by req.

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

eio_get_event_stream
eio_grp_add
Func?ii eio


Adds a request to the request group.

eio_get_last_error
eio_grp_cancel
Func?ii eio
PHP Manual

eio_grp_add

(PECL eio >= 0.0.1dev)

eio_grp_add — Adds a request to the request group.

Descrierea

void eio_grp_add ( resource $grp , resource $req )

eio_grp_add() adds a request to the request group.

Parametri

grp

The request group resource returned by eio_grp()

req

The request resource

Valorile întoarse

eio_grp_add() doesn't return a value.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

resource(6) of type (EIO Group Descriptor)
bool(true)
string(4) "some"
bool(true)

A se vedea ?i

  • eio_grp
  • eio_grp_cancel
  • eio_grp_limit
eio_get_last_error
eio_grp_cancel
Func?ii eio


Cancels a request group

eio_grp_add
eio_grp_limit
Func?ii eio
PHP Manual

eio_grp_cancel

(PECL eio >= 0.0.1dev)

eio_grp_cancel — Cancels a request group

Descrierea

void eio_grp_cancel ( resource $grp )

eio_grp_cancel() cancels a group request specified by grp request group resource.

Parametri

grp

The request group resource returned by eio_grp().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • eio_grp
  • eio_grp_add
eio_grp_add
eio_grp_limit
Func?ii eio


Set group limit

eio_grp_cancel
eio_grp
Func?ii eio
PHP Manual

eio_grp_limit

(PECL eio >= 0.0.1dev)

eio_grp_limit — Set group limit

Descrierea

void eio_grp_limit ( resource $grp , int $limit )

Limit number of requests in the request group.

Parametri

grp

The request group resource.

limit

Number of requests in the group.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • eio_grp_add
eio_grp_cancel
eio_grp
Func?ii eio


Creates a request group.

eio_grp_limit
eio_init
Func?ii eio
PHP Manual

eio_grp

(PECL eio >= 0.0.1dev)

eio_grp — Creates a request group.

Descrierea

resource eio_grp ( callable $callback [, string $data = NULL ] )

eio_grp() creates a request group.

Parametri

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_grp() returns request group resource on success or FALSE on error.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(4) "some"

A se vedea ?i

  • eio_grp_cancel
  • eio_grp_add
eio_grp_limit
eio_init
Func?ii eio


(Re-)initialize Eio

eio_grp
eio_link
Func?ii eio
PHP Manual

eio_init

(PECL eio = 1.0.0)

eio_init — (Re-)initialize Eio

Descrierea

void eio_init ( void )

eio_init() (re-)initializes Eio. It allocates memory for internal structures of libeio and Eio itself. You may call eio_init() before using Eio functions. Otherwise it will be called internally first time you invoke an Eio function in a process.

Avertizare

Aceasta facilitate învechita cu siguran?a va fi eliminata în viitor. Since Eio 1.1.0 eio_init() is deprecated. In Eio 1.0.0 because of » libeio's restrictions you must call eio_init() in child process, if you fork one by any means. You have to avoid using Eio in parent process, if you use it in childs.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

eio_grp
eio_link
Func?ii eio


Create a hardlink for file

eio_init
eio_lstat
Func?ii eio
PHP Manual

eio_link

(PECL eio >= 0.0.1dev)

eio_link — Create a hardlink for file

Descrierea

resource eio_link ( string $path , string $new_path [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_link() creates a hardlink new_path for a file specified by path.

Parametri

path

Source file path.

new_path

Target file path.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(true)
string(%d) "%ssymlink.dat"

A se vedea ?i

  • eio_symlink
eio_init
eio_lstat
Func?ii eio


Get file status

eio_link
eio_mkdir
Func?ii eio
PHP Manual

eio_lstat

(PECL eio >= 0.0.1dev)

eio_lstat — Get file status

Descrierea

resource eio_lstat ( string $path , int $pri , callable $callback [, mixed $data = NULL ] )

eio_lstat() returns file status information in result argument of callback

Parametri

path

The file path

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_lstat() returns request resource on success or FALSE on error.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)
}

A se vedea ?i

  • eio_stat
  • eio_fstat
eio_link
eio_mkdir
Func?ii eio


Create directory

eio_lstat
eio_mknod
Func?ii eio
PHP Manual

eio_mkdir

(PECL eio >= 0.0.1dev)

eio_mkdir — Create directory

Descrierea

resource eio_mkdir ( string $path , int $mode [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_mkdir() creates directory with specified access mode.

Parametri

path

Path for the new directory.

mode

Access mode, e.g. 0755

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_mkdir() returns request resource on success or FALSE on error.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

eio_mkdir_ok

A se vedea ?i

  • eio_rmdir
eio_lstat
eio_mknod
Func?ii eio


Create a special or ordinary file.

eio_mkdir
eio_nop
Func?ii eio
PHP Manual

eio_mknod

(PECL eio >= 0.0.1dev)

eio_mknod — Create a special or ordinary file.

Descrierea

resource eio_mknod ( string $path , int $mode , int $dev [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_mknod() creates ordinary or special(often) file.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

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

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_mknod() returns request resource on success or FALSE on error.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • eio_open
eio_mkdir
eio_nop
Func?ii eio


Does nothing, except go through the whole request cycle.

eio_mknod
eio_npending
Func?ii eio
PHP Manual

eio_nop

(PECL eio >= 0.0.1dev)

eio_nop — Does nothing, except go through the whole request cycle.

Descrierea

resource eio_nop ([ int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_nop() does nothing, except go through the whole request cycle. Could be useful in debugging.

Parametri

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_nop() returns request resource on success or FALSE on error.

A se vedea ?i

  • eio_busy
eio_mknod
eio_npending
Func?ii eio


Returns number of finished, but unhandled requests

eio_nop
eio_nready
Func?ii eio
PHP Manual

eio_npending

(PECL eio >= 0.0.1dev)

eio_npending — Returns number of finished, but unhandled requests

Descrierea

int eio_npending ( void )

eio_npending() returns number of finished, but unhandled requests

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

eio_npending() returns number of finished, but unhandled requests.

A se vedea ?i

  • eio_nreqs
  • eio_nready
  • eio_nthreads
eio_nop
eio_nready
Func?ii eio


Returns number of not-yet handled requests

eio_npending
eio_nreqs
Func?ii eio
PHP Manual

eio_nready

(PECL eio >= 0.0.1dev)

eio_nready — Returns number of not-yet handled requests

Descrierea

int eio_nready ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

eio_nready() returns number of not-yet handled requests

A se vedea ?i

  • eio_nreqs
  • eio_nready
  • eio_nthreads
eio_npending
eio_nreqs
Func?ii eio


Returns number of requests to be processed

eio_nready
eio_nthreads
Func?ii eio
PHP Manual

eio_nreqs

(PECL eio >= 0.0.1dev)

eio_nreqs — Returns number of requests to be processed

Descrierea

int eio_nreqs ( void )

eio_nreqs() could be called in a custom loop calling eio_poll().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

eio_nreqs() returns number of requests to be processed.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "1"
int(0)
string(1) "3"
int(0)
string(1) "2"
int(0)

A se vedea ?i

  • eio_poll
  • eio_nready
eio_nready
eio_nthreads
Func?ii eio


Returns number of threads currently in use

eio_nreqs
eio_open
Func?ii eio
PHP Manual

eio_nthreads

(PECL eio >= 0.0.1dev)

eio_nthreads — Returns number of threads currently in use

Descrierea

int eio_nthreads ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

eio_nthreads() returns number of threads currently in use.

A se vedea ?i

  • eio_npending
  • eio_nready
  • eio_nreqs
eio_nreqs
eio_open
Func?ii eio


Opens a file

eio_nthreads
eio_poll
Func?ii eio
PHP Manual

eio_open

(PECL eio >= 0.0.1dev)

eio_open — Opens a file

Descrierea

resource eio_open ( string $path , int $flags , int $mode , int $pri , callable $callback [, mixed $data = NULL ] )

eio_open() opens file specified by path in access mode mode with

Parametri

path

Path of the file to be opened.

Avertizare

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

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_open() returns file descriptor in result argument of callback on success; otherwise, result is equal to -1.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(true)

A se vedea ?i

  • eio_mknod
eio_nthreads
eio_poll
Func?ii eio


Can be to be called whenever there are pending requests that need finishing.

eio_open
eio_read
Func?ii eio
PHP Manual

eio_poll

(PECL eio >= 0.0.1dev)

eio_poll — Can be to be called whenever there are pending requests that need finishing.

Descrierea

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.

Nota:

Applicable only when implementing userspace event loop.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

If any request invocation returns a non-zero value, returns that value. Otherwise, it returns 0.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "1"
int(0)
string(1) "3"
int(0)
string(1) "2"
int(0)

A se vedea ?i

  • eio_nreqs
eio_open
eio_read
Func?ii eio


Read from a file descriptor at given offset.

eio_poll
eio_readahead
Func?ii eio
PHP Manual

eio_read

(PECL eio >= 0.0.1dev)

eio_read — Read from a file descriptor at given offset.

Descrierea

resource eio_read ( mixed $fd , int $length , int $offset , int $pri , callable $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.

Parametri

fd

Stream, Socket resource, or numeric file descriptor

length

Maximum number of bytes to read.

offset

Offset within the file.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_read() stores read bytes in result argument of callback function.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(5) "34567"

A se vedea ?i

  • eio_open
  • eio_write
  • eio_close
  • eio_event_loop
eio_poll
eio_readahead
Func?ii eio


Perform file readahead into page cache

eio_read
eio_readdir
Func?ii eio
PHP Manual

eio_readahead

(PECL eio >= 0.0.1dev)

eio_readahead — Perform file readahead into page cache

Descrierea

resource eio_readahead ( mixed $fd , int $offset , int $length [, int $pri = EIO_PRI_DEFAULT [, callable $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.

Parametri

fd

Stream, Socket resource, or numeric file descriptor

offset

Starting point from which data is to be read.

length

Number of bytes to be read.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_readahead() returns request resource on success or FALSE on error.

eio_read
eio_readdir
Func?ii eio


Reads through a whole directory

eio_readahead
eio_readlink
Func?ii eio
PHP Manual

eio_readdir

(PECL eio >= 0.0.1dev)

eio_readdir — Reads through a whole directory

Descrierea

resource eio_readdir ( string $path , int $flags , int $pri , callable $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.

Parametri

path

Directory path.

flags

Combination of EIO_READDIR_* constants.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

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

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
Func?ii eio


Read value of a symbolic link.

eio_readdir
eio_realpath
Func?ii eio
PHP Manual

eio_readlink

(PECL eio >= 0.0.1dev)

eio_readlink — Read value of a symbolic link.

Descrierea

resource eio_readlink ( string $path , int $pri , callable $callback [, string $data = NULL ] )

Parametri

path

Source symbolic link path

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_readlink() returns request resource on success or FALSE on error.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(true)
string(16) "/tmp/symlink.dat"

A se vedea ?i

  • eio_symlink
eio_readdir
eio_realpath
Func?ii eio


Get the canonicalized absolute pathname.

eio_readlink
eio_rename
Func?ii eio
PHP Manual

eio_realpath

(PECL eio >= 0.0.1dev)

eio_realpath — Get the canonicalized absolute pathname.

Descrierea

resource eio_realpath ( string $path , int $pri , callable $callback [, string $data = NULL ] )

eio_realpath() returns the canonicalized absolute pathname in result argument of callback function.

Parametri

path

Short pathname

pri

callback

data

Valorile întoarse

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(12) "/home/ruslan"
string(5) "/home"
eio_readlink
eio_rename
Func?ii eio


Change the name or location of a file.

eio_realpath
eio_rmdir
Func?ii eio
PHP Manual

eio_rename

(PECL eio >= 0.0.1dev)

eio_rename — Change the name or location of a file.

Descrierea

resource eio_rename ( string $path , string $new_path [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_rename() renames or moves a file to new location.

Parametri

path

Source path

new_path

Target path

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_rename() returns request resource on success or FALSE on error.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

eio_rename_ok
eio_realpath
eio_rmdir
Func?ii eio


Remove a directory

eio_rename
eio_seek
Func?ii eio
PHP Manual

eio_rmdir

(PECL eio >= 0.0.1dev)

eio_rmdir — Remove a directory

Descrierea

resource eio_rmdir ( string $path [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_rmdir() removes a directory.

Parametri

path

Directory path

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_rmdir() returns request resource on success or FALSE on error.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

eio_rmdir_ok

A se vedea ?i

  • eio_mkdir
eio_rename
eio_seek
Func?ii eio


Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence

eio_rmdir
eio_sendfile
Func?ii eio
PHP Manual

eio_seek

(PECL eio >= 0.5.0b)

eio_seek — Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence

Descrierea

resource eio_seek ( mixed $fd , int $offset , int $whence [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_seek() repositions the offset of the open file associated with stream, Socket resource, or file descriptor specified by fd to the argument offset according to the directive whence as follows:

  • EIO_SEEK_SET - Set position equal to offset bytes.
  • EIO_SEEK_CUR - Set position to current location plus offset.
  • EIO_SEEK_END - Set position to end-of-file plus offset.

Parametri

fd

Stream, Socket resource, or numeric file descriptor

offset

Starting point from which data is to be read.

length

Number of bytes to be read.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_seek() returns request resource on success or FALSE on error.

eio_rmdir
eio_sendfile
Func?ii eio


Transfer data between file descriptors

eio_seek
eio_set_max_idle
Func?ii eio
PHP Manual

eio_sendfile

(PECL eio >= 0.0.1dev)

eio_sendfile — Transfer data between file descriptors

Descrierea

resource eio_sendfile ( mixed $out_fd , mixed $in_fd , int $offset , int $length [, int $pri [, callable $callback [, string $data ]]] )

eio_sendfile() copies data between one file descriptor and another. See SENDFILE(2) man page for details.

Parametri

out_fd

Output stream, Socket resource, or file descriptor. Should be opened for writing.

in_fd

Input stream, Socket resource, or file descriptor. Should be opened for reading.

offset

Offset within the source file.

length

Number of bytes to copy.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_sendfile() returns request resource on success or FALSE on error.

eio_seek
eio_set_max_idle
Func?ii eio


Set maximum number of idle threads.

eio_sendfile
eio_set_max_parallel
Func?ii eio
PHP Manual

eio_set_max_idle

(PECL eio >= 0.0.1dev)

eio_set_max_idle — Set maximum number of idle threads.

Descrierea

void eio_set_max_idle ( int $nthreads )

Parametri

nthreads

Number of idle threads.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • eio_set_min_parallel
  • eio_set_max_parallel
eio_sendfile
eio_set_max_parallel
Func?ii eio


Set maximum parallel threads

eio_set_max_idle
eio_set_max_poll_reqs
Func?ii eio
PHP Manual

eio_set_max_parallel

(PECL eio >= 0.0.1dev)

eio_set_max_parallel — Set maximum parallel threads

Descrierea

void eio_set_max_parallel ( int $nthreads )

Parametri

nthreads

Number of parallel threads

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • eio_set_min_parallel
eio_set_max_idle
eio_set_max_poll_reqs
Func?ii eio


Set maximum number of requests processed in a poll.

eio_set_max_parallel
eio_set_max_poll_time
Func?ii eio
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.

Descrierea

void eio_set_max_poll_reqs ( int $nreqs )

Parametri

nreqs

Number of requests

Valorile întoarse

Nu este întoarsa nici o valoare.

eio_set_max_parallel
eio_set_max_poll_time
Func?ii eio


Set maximum poll time

eio_set_max_poll_reqs
eio_set_min_parallel
Func?ii eio
PHP Manual

eio_set_max_poll_time

(PECL eio >= 0.0.1dev)

eio_set_max_poll_time — Set maximum poll time

Descrierea

void eio_set_max_poll_time ( float $nseconds )

Polling stops, if poll took longer than nseconds seconds.

Parametri

nseconds

Number of seconds

Valorile întoarse

Nu este întoarsa nici o valoare.

eio_set_max_poll_reqs
eio_set_min_parallel
Func?ii eio


Set minimum parallel thread number

eio_set_max_poll_time
eio_stat
Func?ii eio
PHP Manual

eio_set_min_parallel

(PECL eio >= 0.0.1dev)

eio_set_min_parallel — Set minimum parallel thread number

Descrierea

void eio_set_min_parallel ( string $nthreads )

Parametri

nthreads

Number of parallel threads.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • eio_set_max_parallel
eio_set_max_poll_time
eio_stat
Func?ii eio


Get file status

eio_set_min_parallel
eio_statvfs
Func?ii eio
PHP Manual

eio_stat

(PECL eio >= 0.0.1dev)

eio_stat — Get file status

Descrierea

resource eio_stat ( string $path , int $pri , callable $callback [, mixed $data = NULL ] )

eio_stat() returns file status information in result argument of callback

Parametri

path

The file path

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_stat() returns request resource on success or FALSE on error. On success assigns result argument of callback to an array.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)
}

A se vedea ?i

  • eio_lstat
  • eio_fstat
eio_set_min_parallel
eio_statvfs
Func?ii eio


Get file system statistics

eio_stat
eio_symlink
Func?ii eio
PHP Manual

eio_statvfs

(PECL eio >= 0.0.1dev)

eio_statvfs — Get file system statistics

Descrierea

resource eio_statvfs ( string $path , int $pri , callable $callback [, mixed $data ] )

eio_statvfs() returns file system statistics information in result argument of callback

Parametri

path

Pathname of any file within the mounted file system

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_statvfs() returns request resource on success or FALSE on error. On success assigns result argument of callback to an array.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
Func?ii eio


Create a symbolic link

eio_statvfs
eio_sync_file_range
Func?ii eio
PHP Manual

eio_symlink

(PECL eio >= 0.0.1dev)

eio_symlink — Create a symbolic link

Descrierea

resource eio_symlink ( string $path , string $new_path [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_symlink() creates a symbolic link new_path to path.

Parametri

path

Source path

new_path

Target path

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_symlink() returns request resource on success or FALSE on error.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
string(16) "/tmp/symlink.dat"

A se vedea ?i

  • eio_link
eio_statvfs
eio_sync_file_range
Func?ii eio


Sync a file segment with disk

eio_symlink
eio_sync
Func?ii eio
PHP Manual

eio_sync_file_range

(PECL eio >= 0.0.1dev)

eio_sync_file_range — Sync a file segment with disk

Descrierea

resource eio_sync_file_range ( mixed $fd , int $offset , int $nbytes , int $flags [, int $pri = EIO_PRI_DEFAULT [, callable $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.

Parametri

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

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_sync_file_range() returns request resource on success or FALSE on error.

eio_symlink
eio_sync
Func?ii eio


Commit buffer cache to disk

eio_sync_file_range
eio_syncfs
Func?ii eio
PHP Manual

eio_sync

(PECL eio >= 0.0.1dev)

eio_sync — Commit buffer cache to disk

Descrierea

resource eio_sync ([ int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

eio_sync() returns request resource on success or FALSE on error.

eio_sync_file_range
eio_syncfs
Func?ii eio


Calls Linux' syncfs syscall, if available

eio_sync
eio_truncate
Func?ii eio
PHP Manual

eio_syncfs

(PECL eio >= 0.0.1dev)

eio_syncfs — Calls Linux' syncfs syscall, if available

Descrierea

resource eio_syncfs ( mixed $fd [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

Parametri

fd

File descriptor

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_syncfs() returns request resource on success or FALSE on error.

eio_sync
eio_truncate
Func?ii eio


Truncate a file

eio_syncfs
eio_unlink
Func?ii eio
PHP Manual

eio_truncate

(PECL eio >= 0.0.1dev)

eio_truncate — Truncate a file

Descrierea

resource eio_truncate ( string $path [, int $offset = 0 [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]]] )

eio_truncate() causes the regular file named by path to be truncated to a size of precisely length bytes

Parametri

path

File path

offset

Offset from beginning of the file.

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_busy() returns request resource on success or FALSE on error.

A se vedea ?i

  • eio_ftruncate
eio_syncfs
eio_unlink
Func?ii eio


Delete a name and possibly the file it refers to

eio_truncate
eio_utime
Func?ii eio
PHP Manual

eio_unlink

(PECL eio >= 0.0.1dev)

eio_unlink — Delete a name and possibly the file it refers to

Descrierea

resource eio_unlink ( string $path [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_unlink() deletes a name from the file system.

Parametri

path

Path to file

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_unlink() returns request resource on success or FALSE on error.

eio_truncate
eio_utime
Func?ii eio


Change file last access and modification times.

eio_unlink
eio_write
Func?ii eio
PHP Manual

eio_utime

(PECL eio >= 0.0.1dev)

eio_utime — Change file last access and modification times.

Descrierea

resource eio_utime ( string $path , float $atime , float $mtime [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

Parametri

path

Path to the file.

atime

Access time

mtime

Modification time

pri

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_utime() returns request resource on success or FALSE on error.

A se vedea ?i

  • eio_futime
eio_unlink
eio_write
Func?ii eio


Write to file

eio_utime
Ev
Func?ii eio
PHP Manual

eio_write

(PECL eio >= 0.0.1dev)

eio_write — Write to file

Descrierea

resource eio_write ( mixed $fd , string $str [, int $length = 0 [, int $offset = 0 [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]]]] )

eio_write() writes up to length bytes from str at offset offset from the beginning of the file.

Parametri

fd

Stream, Socket resource, or numeric 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

Prioritatea cererii: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX sau NULL. Daca este transmis NULL, pri este stabilit intern la valoarea EIO_PRI_DEFAULT.

callback

Func?ia callback este apelata atunci când o interpelare este încheiata. Ea trebuie sa corespunda urmatorului prototip:

void callback(mixed $data, int $result[, resource $req]);
data

sunt ni?te date personalizate transmise în cerere.

result

con?ine rezultatul specific cererii; în esen?a, valoarea întoarsa de apelul de sistem corespunzator.

req

este o resursa a cererii op?ionala ce poate fi utilizata cu func?ii precum eio_get_last_error()

data

Arbitrary variable passed to callback.

Valorile întoarse

eio_write() returns request resource on success or FALSE on error.

A se vedea ?i

  • eio_open
eio_utime
Ev
Func?ii eio


Ev

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Watchers
  • Watcher callbacks
  • Periodic watcher operation modes
  • Ev — The Ev class
    • Ev::backend — Returns an integer describing the backend used by libev.
    • Ev::depth — Returns recursion depth
    • Ev::embeddableBackends — Returns the set of backends that are embeddable in other event loops.
    • Ev::feedSignal — Feed a signal event info Ev
    • Ev::feedSignalEvent — Feed signal event into the default loop
    • Ev::iteration — Return the number of times the default event loop has polled for new events.
    • Ev::now — Returns the time when the last iteration of the default event loop has started.
    • Ev::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.
    • Ev::recommendedBackends — Returns a bit mask of recommended backends for current platform.
    • Ev::resume — Resume previously suspended default event loop
    • Ev::run — Begin checking for events and calling callbacks for the default loop
    • Ev::sleep — Block the process for the given number of seconds.
    • Ev::stop — Stops the default event loop
    • Ev::supportedBackends — Returns the set of backends supported by current libev configuration.
    • Ev::suspend — Suspend the default event loop
    • Ev::time — Returns the current time in fractional seconds since the epoch.
    • Ev::verify — Performs internal consistency checks(for debugging)
  • EvCheck — The EvCheck class
    • EvCheck::__construct — Constructs the EvCheck watcher object
    • EvCheck::createStopped — Create instance of a stopped EvCheck watcher
  • EvChild — The EvChild class
    • EvChild::__construct — Constructs the EvChild watcher object
    • EvChild::createStopped — Create instance of a stopped EvCheck watcher
    • EvChild::set — Configures the watcher
  • EvEmbed — The EvEmbed class
    • EvEmbed::__construct — Constructs the EvEmbed object
    • EvEmbed::createStopped — Create stopped EvEmbed watcher object
    • EvEmbed::set — Configures the watcher
    • EvEmbed::sweep — Make a single, non-blocking sweep over the embedded loop.
  • EvFork — The EvFork class
    • EvFork::__construct — Constructs the EvFork watcher object
    • EvFork::createStopped — Creates a stopped instance of EvFork watcher class
  • EvIdle — The EvIdle class
    • EvIdle::__construct — Constructs the EvIdle watcher object
    • EvIdle::createStopped — Creates instance of a stopped EvIdle watcher object
  • EvIo — The EvIo class
    • EvIo::__construct — Constructs EvIo watcher object
    • EvIo::createStopped — Create stopped EvIo watcher object
    • EvIo::set — Configures the watcher
  • EvLoop — The EvLoop class
    • EvLoop::backend — Returns an integer describing the backend used by libev.
    • EvLoop::check — Creates EvCheck object associated with the current event loop instance
    • EvLoop::child — Creates EvChild object associated with the current event loop
    • EvLoop::__construct — Constructs the event loop object
    • EvLoop::defaultLoop — Returns or creates the default event loop.
    • EvLoop::embed — Creates an instance of EvEmbed watcher associated with the current EvLoop object.
    • EvLoop::fork — Creates EvFork watcher object associated with the current event loop instance
    • EvLoop::idle — Creates EvIdle watcher object associated with the current event loop instance
    • EvLoop::invokePending — Invoke all pending watchers while resetting their pending state
    • EvLoop::io — Create EvIo watcher object associated with the current event loop instance
    • EvLoop::loopFork — Must be called after a fork
    • EvLoop::now — Returns the current "event loop time"
    • EvLoop::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress.
    • EvLoop::periodic — Creates EvPeriodic watcher object associated with the current event loop instance
    • EvLoop::prepare — Creates EvPrepare watcher object associated with the current event loop instance
    • EvLoop::resume — Resume previously suspended default event loop
    • EvLoop::run — Begin checking for events and calling callbacks for the loop
    • EvLoop::signal — Creates EvSignal watcher object associated with the current event loop instance
    • EvLoop::stat — Creates EvStat watcher object associated with the current event loop instance
    • EvLoop::stop — Stops the event loop
    • EvLoop::suspend — Suspend the loop
    • EvLoop::timer — Creates EvTimer watcher object associated with the current event loop instance
    • EvLoop::verify — Performs internal consistency checks(for debugging)
  • EvPeriodic — The EvPeriodic class
    • EvPeriodic::again — Simply stops and restarts the periodic watcher again.
    • EvPeriodic::at — Returns the absolute time that this watcher is supposed to trigger next
    • EvPeriodic::__construct — Constructs EvPeriodic watcher object
    • EvPeriodic::createStopped — Create a stopped EvPeriodic watcher
    • EvPeriodic::set — Configures the watcher
  • EvPrepare — The EvPrepare class
    • EvPrepare::__construct — Constructs EvPrepare watcher object
    • EvPrepare::createStopped — Creates a stopped instance of EvPrepare watcher
  • EvSignal — The EvSignal class
    • EvSignal::__construct — Constructs EvPeriodic watcher object
    • EvSignal::createStopped — Create stopped EvSignal watcher object
    • EvSignal::set — Configures the watcher
  • EvStat — The EvStat class
    • EvStat::attr — Returns the values most recently detected by Ev
    • EvStat::__construct — Constructs EvStat watcher object
    • EvStat::createStopped — Create a stopped EvStat watcher object
    • EvStat::prev — Returns the previous set of values returned by EvStat::attr
    • EvStat::set — Configures the watcher
    • EvStat::stat — Initiates the stat call
  • EvTimer — The EvTimer class
    • EvTimer::again — Restarts the timer watcher
    • EvTimer::__construct — Constructs an EvTimer watcher object
    • EvTimer::createStopped — Creates EvTimer stopped watcher object
    • EvTimer::set — Configures the watcher
  • EvWatcher — The EvWatcher class
    • EvWatcher::clear — Clear watcher pending status
    • EvWatcher::__construct — Abstract constructor of a watcher object
    • EvWatcher::feed — Feeds the given revents set into the event loop
    • EvWatcher::getLoop — Returns the loop responsible for the watcher
    • EvWatcher::invoke — Invokes the watcher callback with the given received events bit mask
    • EvWatcher::keepalive — Configures whether to keep the loop from returning
    • EvWatcher::setCallback — Sets new callback for the watcher
    • EvWatcher::start — Starts the watcher
    • EvWatcher::stop — Stops the watcher
eio_write
Introducere
Extensii de control al proceselor


Introducere

This extension provides inteface to » libev library - a high performance full-featured event loop written in C.

Nota: Aceasta extensie nu este disponibila pe platformele Windows.

Libev is an event loop: one registers interest in certain events (such as a file descriptor being readable or a timeout occurring), and it will manage these event sources and provide the program with events.

To do this, it must take more or less complete control over the process (or thread) by executing the event loop handler, and will then communicate events via a callback mechanism.

You register interest in certain events by registering so-called event watchers, and then hand it over to libev by starting the watcher.

For details refer to the » documentation of libev

Ev
Instalarea / configurarea
Ev


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Ev


Necesita?i

libev library is embedded into this extension. You don't need to install it separately.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/ev .

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Majoritatea constantelor au fost mutate în clasa singleton Ev.

Tipurile resurselor
Exemple
Ev


Exemple

Example #1 Simple timers

<?php
// Create and start timer firing after 2 seconds
$w1 = new EvTimer(2, 0, function () {
    echo "2 seconds elapsed\n";
});

// Create and launch timer firing after 2 seconds repeating each second
// until we manually stop it
$w2 = new EvTimer(2, 1, function ($w) {
    echo "is called every second, is launched after 2 seconds\n";
    echo "iteration = ", Ev::iteration(), PHP_EOL;

    // Stop the watcher after 5 iterations
    Ev::iteration() == 5 and $w->stop();
    // Stop the watcher if further calls cause more than 10 iterations
    Ev::iteration() >= 10 and $w->stop();
});

// Create stopped timer. It will be inactive until we start it ourselves
$w_stopped = EvTimer::createStopped(10, 5, function($w) {
    echo "Callback of a timer created as stopped\n";

    // Stop the watcher after 2 iterations
    Ev::iteration() >= 2 and $w->stop();
});

// Loop until Ev::stop() is called or all of watchers stop
Ev::run();

// Start and look if it works
$w_stopped->start();
echo "Run single iteration\n";
Ev::run(Ev::RUN_ONCE);

echo "Restart the second watcher and try to handle the same events, but don't block\n";
$w2->again();
Ev::run(Ev::RUN_NOWAIT);

$w = new EvTimer(10, 0, function() {});
echo "Running a blocking loop\n";
Ev::run();
echo "END\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

2 seconds elapsed
is called every second, is launched after 2 seconds
iteration = 1
is called every second, is launched after 2 seconds
iteration = 2
is called every second, is launched after 2 seconds
iteration = 3
is called every second, is launched after 2 seconds
iteration = 4
is called every second, is launched after 2 seconds
iteration = 5
Run single iteration
Callback of a timer created as stopped
Restart the second watcher and try to handle the same events, but don't block
Running a blocking loop
is called every second, is launched after 2 seconds
iteration = 8
is called every second, is launched after 2 seconds
iteration = 9
is called every second, is launched after 2 seconds
iteration = 10
END

Example #2 Periodic timer. Tick each 10.5 seconds

<?php
$w = new EvPeriodic(0., 10.5, NULL, function ($w, $revents) {
    echo time(), PHP_EOL;
});

Ev::run();
?>

Example #3 Periodic timer. Use reschedule callback

<?php
// Tick each 10.5 seconds

function reschedule_cb ($watcher, $now) {
    return $now + (10.5. - fmod($now, 10.5));
}

$w = new EvPeriodic(0., 0., "reschedule_cb", function ($w, $revents) {
    echo time(), PHP_EOL;
});

Ev::run();
?>

Example #4 Periodic timer. Tick every 10.5 seconds starting at now

<?php
// Tick every 10.5 seconds starting at now
$w = new EvPeriodic(fmod(Ev::now(), 10.5), 10.5, NULL, function ($w, $revents) {
    echo time(), PHP_EOL;
});

Ev::run();
?>

Example #5 Wait until STDIN is readable

<?php
// Wait until STDIN is readable
$w = new EvIo(STDIN, Ev::READ, function ($watcher, $revents) {
    echo "STDIN is readable\n";
});

Ev::run(Ev::RUN_ONCE);
?>

Example #6 Use some async I/O to access a socket

<?php
/* Use some async I/O to access a socket */

// `sockets' extension still logs warnings
// for EINPROGRESS, EAGAIN/EWOULDBLOCK etc.
error_reporting(E_ERROR);

$e_nonblocking = array (/*EAGAIN or EWOULDBLOCK*/11, /*EINPROGRESS*/115);

// Get the port for the WWW service
$service_port = getservbyname('www', 'tcp');

// Get the IP address for the target host
$address = gethostbyname('google.co.uk');

// 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";
}

// Set O_NONBLOCK flag
socket_set_nonblock($socket);

// Abort on timeout
$timeout_watcher = new EvTimer(10.0, 0., function () use ($socket) {
    socket_close($socket);
    Ev::stop(Ev::BREAK_ALL);
});

// Make HEAD request when the socket is writable
$write_watcher = new EvIo($socket, Ev::WRITE, function ($w)
    use ($socket, $timeout_watcher, $e_nonblocking)
{
    // Stop timeout watcher
    $timeout_watcher->stop();
    // Stop write watcher
    $w->stop();

    $in = "HEAD / HTTP/1.1\r\n";
    $in .= "Host: google.co.uk\r\n";
    $in .= "Connection: Close\r\n\r\n";

    if (!socket_write($socket, $in, strlen($in))) {
        trigger_error("Failed writing $in to socket", E_USER_ERROR);
    }

    $read_watcher = new EvIo($socket, Ev::READ, function ($w, $re)
        use ($socket, $e_nonblocking)
    {
        // Socket is readable. recv() 20 bytes using non-blocking mode
        $ret = socket_recv($socket, $out, 20, MSG_DONTWAIT);

        if ($ret) {
            echo $out;
        } elseif ($ret === 0) {
            // All read
            $w->stop();
            socket_close($socket);
            return;
        }

        // Caught EINPROGRESS, EAGAIN, or EWOULDBLOCK
        if (in_array(socket_last_error(), $e_nonblocking)) {
            return;
        }

        $w->stop();
        socket_close($socket);
    });

    Ev::run();
});

$result = socket_connect($socket, $address, $service_port);

Ev::run();
?>

Exemplul de mai sus va afi?a ceva similar cu:

HTTP/1.1 301 Moved Permanently
Location: http://www.google.co.uk/
Content-Type: text/html; CHARSET=Windows-1252
Date: Sun, 23 Dec 2012 16:08:27 GMT
Expires: Tue, 22 Jan 2013 16:08:27 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Connection: close

Example #7 Embedding one loop into another

<?php
/*
* Try to get an embeddable event loop and embed it into the default event loop.
* If it is impossible, use the default
* loop. The default loop is stored in $loop_hi, while the embeddable loop is
* stored in $loop_lo(which is $loop_hi in the case no embeddable loop can be
* used).
*
* Sample translated to PHP
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop_hi = EvLoop::defaultLoop();
$loop_lo = NULL;
$embed   = NULL;

/*
* See if there is a chance of getting one that works
* (flags' value of 0 means autodetection)
*/
$loop_lo = Ev::embeddableBackends() & Ev::recommendedBackends()
    ? new EvLoop(Ev::embeddableBackends() & Ev::recommendedBackends())
    : 0;

if ($loop_lo) {
    $embed = new EvEmbed($loop_lo, function () {});
} else {
    $loop_lo = $loop_hi;
}
?>

Example #8 Embedding loop created with kqueue backend into the default loop

<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop        = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed       = NULL;

if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
    if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
        $embed = new EvEmbed($loop);
    }
}

if (!$socket_loop) {
    $socket_loop = $loop;
}

// Now use $socket_loop for all sockets, and $loop for anything else
?>

Example #9 Handle SIGTERM signal

<?php
$w = new EvSignal(SIGTERM, function ($watcher) {
    echo "SIGTERM received\n";
    $watcher->stop();
});

Ev::run();
?>

Example #10 Monitor changes of /var/log/messages

<?php
// Use 10 second update interval.
$w = new EvStat("/var/log/messages", 8, function ($w) {
    echo "/var/log/messages changed\n";

    $attr = $w->attr();

    if ($attr['nlink']) {
        printf("Current size: %ld\n", $attr['size']);
        printf("Current atime: %ld\n", $attr['atime']);
        printf("Current mtime: %ld\n", $attr['mtime']);
    } else {
        fprintf(STDERR, "`messages` file is not there!");
        $w->stop();
    }
});

Ev::run();
?>

Example #11 Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay

<?php
$timer = EvTimer::createStopped(0., 1.02, function ($w) {
    $w->stop();

    $stat = $w->data;

    // 1 second after the most recent change of the file
    printf("Current size: %ld\n", $stat->attr()['size']);
});

$stat = new EvStat("/var/log/messages", 0., function () use ($timer) {
    // Reset timer watcher
    $timer->again();
});

$timer->data = $stat;

Ev::run();
?>

Example #12 Process status changes

<?php
$pid = pcntl_fork();

if ($pid == -1) {
    fprintf(STDERR, "pcntl_fork failed\n");
} elseif ($pid) {
    $w = new EvChild($pid, FALSE, function ($w, $revents) {
        $w->stop();

        printf("Process %d exited with status %d\n", $w->rpid, $w->rstatus);
    });

    Ev::run();

    // Protect against Zombies
    pcntl_wait($status);
} else {
    //Forked child
    exit(2);
}
?>
Constante predefinite
Watchers
Ev


Watchers

A watcher is an object that gets created to record interest in some event. For instance, the following code waits for STDIN to become readable:

<?php
// Wait until STDIN is readable
$w = new EvIo(STDIN, Ev::READ, function ($watcher, $revents) {
 echo "STDIN is readable\n";
});
Ev::run(Ev::RUN_ONCE);
?>

All the watcher constructors automatically start the watchers. createStopped methods create stopped watchers(e.g. EvIo::createStopped() )

Note that a watcher will automatically be stopped when the watcher object is destroyed. Therefore, the watcher objects returned by the constructors or factory methods should be kept.

Note also that all methods changing some watcher property( set , priority etc.) automatically stop and start it again if it is active, which means pending events get lost.

See also: Watcher callbacks .

Exemple
Watcher callbacks
Ev


Watcher callbacks

All watchers can be active(waiting for events) or inactive(paused). Only active watchers will have their callbacks invoked. All callbacks will be called with at least two arguments: watcher - the watcher, and revents a bitmask of received events.

Watcher callbacks are passed to the watcher contructors(the classes derived from EvWatcher - EvCheck::__construct() , EvChild::__construct() etc.). A watcher callback should match the following prototype:

void callback ([ object $watcher = NULL [, int $revents = NULL ]] )

watcher

The watcher instance(of a class extending EvWatcher ).

revents

Watcher received events .

Each watcher type has its associated bit in revents , so one can use the same callback for multiple watchers. The event mask is named after the type, i.e. EvChild (or EvLoop::child() ) sets EV::CHILD , EvPrepare (or EvLoop::prepare() ) sets Ev::PREPARE , EvPeriodic (or EvLoop::periodic() ) sets Ev::PERIODIC and so on, with the exception of I/O events (which can set both Ev::READ and Ev::WRITE bits).

Watchers
Periodic watcher operation modes
Ev


Periodic watcher operation modes

EvPeriodic watcher works in different modes depending on the offset , interval and reschedule_cb parameters.

  1. Absolute timer . In this mode interval = 0 , reschedule_cb = NULL. This time simply fires at the wallclock time offset and doesn't repeat. It will not adjust when a time jump occurs, that is, if it is to be run at January 1st 2014 then it will run when the system time reaches or surpasses this time.

  2. Repeating interval timer . In this mode interval > 0 , reschedule_cb = NULL; the watcher will always be scheduled to timeout at the next offset + N * interval time(for some integer N ) and then repeat, regardless of any time jumps.

    This can be used to create timers that do not drift with respect to system time:

    <?php
    $hourly     = EvPeriodic(0, 3600, NULL, function () {
      echo     "once per hour\n";
    };
    ?>
    That doesn't mean there will always be 3600 seconds in between triggers, but only that the callback will be called when the system time shows a full hour( UTC ).

    EvPeriodic will try to run the callback in this mode at the next possible time where time = offset ( mod interval ), regardless of any time jumps.

  3. Manual reschedule mode . In this mode reschedule_cb is a callable .

    interval and offset are both being ignored. Instead, each time the periodic watcher gets scheduled, the reschedule callback ( reschedule_cb ) will be called with the watcher as first, and the current time as second argument.

    This callback must not stop or destroy this or any other periodic watchers, ever, and must not call any event loop functions or methods. To stop it return 1e30 and stop it afterwards. An EvPrepare watcher may be used for this task.

    It must return the next time to trigger, based on the passed time value (that is, the lowest time value larger than or equal to the second argument). It will usually be called just before the callback will be triggered, but might be called at other times, too.

    Example #1 Using reschedule callback

    <?php
    // Tick each 10.5 seconds

    function reschedule_cb ($watcher, $now) {
       return     $now + (10.5. - fmod($now, 10.5));
    }

    $w = new EvPeriodic(0., 0., "reschedule_cb", function ($w, $revents) {
       echo     time(), PHP_EOL;
    });

    Ev::run();
    ?>
Watcher callbacks
Ev
Ev


The Ev class

(PECL ev >= 0.2.0)

Introducere

Ev is a static class providing access to the default loop and to some common operations.

Sinopsisul clasei

final Ev {
/* Constants */
const integer FLAG_AUTO = 0 ;
const integer FLAG_NOENV = 16777216 ;
const integer FLAG_FORKCHECK = 33554432 ;
const integer FLAG_NOINOTIFY = 1048576 ;
const integer FLAG_SIGNALFD = 2097152 ;
const integer FLAG_NOSIGMASK = 4194304 ;
const integer RUN_NOWAIT = 1 ;
const integer RUN_ONCE = 2 ;
const integer BREAK_CANCEL = 0 ;
const integer BREAK_ONE = 1 ;
const integer BREAK_ALL = 2 ;
const integer MINPRI = -2 ;
const integer MAXPRI = 2 ;
const integer READ = 1 ;
const integer WRITE = 2 ;
const integer TIMER = 256 ;
const integer PERIODIC = 512 ;
const integer SIGNAL = 1024 ;
const integer CHILD = 2048 ;
const integer STAT = 4096 ;
const integer IDLE = 8192 ;
const integer PREPARE = 16384 ;
const integer CHECK = 32768 ;
const integer EMBED = 65536 ;
const integer CUSTOM = 16777216 ;
const integer ERROR = 2147483648 ;
const integer BACKEND_SELECT = 1 ;
const integer BACKEND_POLL = 2 ;
const integer BACKEND_EPOLL = 4 ;
const integer BACKEND_KQUEUE = 8 ;
const integer BACKEND_DEVPOLL = 16 ;
const integer BACKEND_PORT = 32 ;
const integer BACKEND_ALL = 63 ;
const integer BACKEND_MASK = 65535 ;
/* Metode */
final public static int backend ( void )
final public static int depth ( void )
final public static void embeddableBackends ( void )
final public static void feedSignal ( int $signum )
final public static void feedSignalEvent ( int $signum )
final public static int iteration ( void )
final public static double now ( void )
final public static void nowUpdate ( void )
final public static void recommendedBackends ( void )
final public static void resume ( void )
final public static void run ([ int $flags ] )
final public static void sleep ( double $seconds )
final public static void stop ([ int $how ] )
final public static void supportedBackends ( void )
final public static void suspend ( void )
final public static double time ( void )
final public static void verify ( void )
}

Constante predefinite

Flags passed to create a loop:

Ev::FLAG_AUTO

The default flags value

Ev::FLAG_NOENV

If this flag used(or the program runs setuid or setgid), libev won't look at the environment variable LIBEV_FLAGS . Otherwise(by default), LIBEV_FLAGS will override the flags completely if it is found. Useful for performance tests and searching for bugs.

Ev::FLAG_FORKCHECK

Makes libev check for a fork in each iteration, instead of calling EvLoop::fork() manually. This works by calling getpid() on every iteration of the loop, and thus this might slow down the event loop with lots of loop iterations, but usually is not noticeable. This flag setting cannot be overridden or specified in the LIBEV_FLAGS environment variable.

Ev::FLAG_NOINOTIFY

When this flag is specified, libev won't attempt to use the inotify API for its » ev_stat watchers. The flag can be useful to conserve inotify file descriptors, as otherwise each loop using ev_stat watchers consumes one inotify handle.

Ev::FLAG_SIGNALFD

When this flag is specified, libev will attempt to use the signalfd API for its » ev_signal (and » ev_child ) watchers. This API delivers signals synchronously, which makes it both faster and might make it possible to get the queued signal data. It can also simplify signal handling with threads, as long as signals are properly blocked in threads. Signalfd will not be used by default.

Ev::FLAG_NOSIGMASK

When this flag is specified, libev will avoid to modify the signal mask. Specifically, this means having to make sure signals are unblocked before receiving them.

This behaviour is useful for custom signal handling, or handling signals only in specific threads.

Flags passed to Ev::run() , or EvLoop::run()

Ev::RUN_NOWAIT

Means that event loop will look for new events, will handle those events and any already outstanding ones, but will not wait and block the process in case there are no events and will return after one iteration of the loop. This is sometimes useful to poll and handle new events while doing lengthy calculations, to keep the program responsive.

Ev::RUN_ONCE

Means that event loop will look for new events (waiting if necessary) and will handle those and any already outstanding ones. It will block the process until at least one new event arrives (which could be an event internal to libev itself, so there is no guarantee that a user-registered callback will be called), and will return after one iteration of the loop.

Flags passed to Ev::stop() , or EvLoop::stop()

Ev::BREAK_CANCEL

Cancel the break operation.

Ev::BREAK_ONE

Makes the innermost Ev::run() (or EvLoop::run() ) call return.

Ev::BREAK_ALL

Makes all nested Ev::run() (or EvLoop::run() ) calls return.

Watcher priorities:

Ev::MINPRI

Minimum allowed watcher priority.

Ev::MAXPRI

Maximum allowed watcher priority.

Bit masks of (received) events:

Ev::READ

The file descriptor in the EvIo watcher has become readable.

Ev::WRITE

The file descriptor in the EvIo watcher has become writable.

Ev::TIMER

EvTimer watcher has been timed out.

Ev::PERIODIC

EvPeriodic watcher has been timed out.

Ev::SIGNAL

A signal specified in EvSignal::__construct() has been received.

Ev::CHILD

The pid specified in EvChild::__construct() has received a status change.

Ev::STAT

The path specified in EvStat watcher changed its attributes.

Ev::IDLE

EvIdle watcher works when there is nothing to do with other watchers.

Ev::PREPARE

All EvPrepare watchers are invoked just before Ev::run() starts. Thus, EvPrepare watchers are the last watchers invoked before the event loop sleeps or polls for new events.

Ev::CHECK

All EvCheck watchers are queued just after Ev::run() has gathered the new events, but before it queues any callbacks for any received events. Thus, EvCheck watchers will be invoked before any other watchers of the same or lower priority within an event loop iteration.

Ev::EMBED

The embedded event loop specified in the EvEmbed watcher needs attention.

Ev::CUSTOM

Not ever sent(or otherwise used) by libev itself, but can be freely used by libev users to signal watchers (e.g. via EvWatcher::feed() ).

Ev::ERROR

An unspecified error has occurred, the watcher has been stopped. This might happen because the watcher could not be properly started because libev ran out of memory, a file descriptor was found to be closed or any other problem. Libev considers these application bugs. See also » ANATOMY OF A WATCHER

Backend flags:

Ev::BACKEND_SELECT

select(2) backend

Ev::BACKEND_POLL

poll(2) backend

Ev::BACKEND_EPOLL

Linux-specific epoll(7) backend for both pre- and post-2.6.9 kernels

Ev::BACKEND_KQUEUE

kqueue backend used on most BSD systems. EvEmbed watcher could be used to embed one loop(with kqueue backend) into another. For instance, one can try to create an event loop with kqueue backend and use it for sockets only.

Ev::BACKEND_DEVPOLL

Solaris 8 backend. This is not implemented yet.

Ev::BACKEND_PORT

Solaris 10 event port mechanism with a good scaling.

Ev::BACKEND_ALL

Try all backends(even currupted ones). It's not recommended to use it explicitly. Bitwise operators should be applied here(e.g. Ev::BACKEND_ALL & ~ Ev::BACKEND_KQUEUE ) Use Ev::recommendedBackends() , or don't specify any backends at all.

Ev::BACKEND_MASK

Not a backend, but a mask to select all backend bits from flags value to mask out any backends(e.g. when modifying the LIBEV_FLAGS environment variable).

Nota:

For the default loop during module initialization phase Ev registers » ev_loop_fork call by means of pthread_atfork (if available).

Nota:

There are methods providing access to the default event loop in Ev class(e.g. Ev::iteration() , Ev::depth() etc.) For custom loops (created with EvLoop::__construct() ) these values may be accessed via corresponding properties and methods of the EvLoop class.

The instance of the default event loop itself can be fetched by means of EvLoop::defaultLoop() method.

Cuprins

  • Ev::backend — Returns an integer describing the backend used by libev.
  • Ev::depth — Returns recursion depth
  • Ev::embeddableBackends — Returns the set of backends that are embeddable in other event loops.
  • Ev::feedSignal — Feed a signal event info Ev
  • Ev::feedSignalEvent — Feed signal event into the default loop
  • Ev::iteration — Return the number of times the default event loop has polled for new events.
  • Ev::now — Returns the time when the last iteration of the default event loop has started.
  • Ev::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.
  • Ev::recommendedBackends — Returns a bit mask of recommended backends for current platform.
  • Ev::resume — Resume previously suspended default event loop
  • Ev::run — Begin checking for events and calling callbacks for the default loop
  • Ev::sleep — Block the process for the given number of seconds.
  • Ev::stop — Stops the default event loop
  • Ev::supportedBackends — Returns the set of backends supported by current libev configuration.
  • Ev::suspend — Suspend the default event loop
  • Ev::time — Returns the current time in fractional seconds since the epoch.
  • Ev::verify — Performs internal consistency checks(for debugging)
Periodic watcher operation modes
Ev::backend
Ev


Returns an integer describing the backend used by libev.

Ev
Ev::depth
Ev
PHP Manual

Ev::backend

(PECL ev >= 0.2.0)

Ev::backend — Returns an integer describing the backend used by libev.

Descrierea

final public static int Ev::backend ( void )

Returns an integer describing the backend used by libev . See Backend flags

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an integer(bit mask) describing the backend used by libev .

A se vedea ?i

  • EvEmbed
  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops.
  • Ev::recommendedBackends() - Returns a bit mask of recommended backends for current platform.
  • Ev::supportedBackends() - Returns the set of backends supported by current libev configuration.
  • Backend flags
Ev
Ev::depth
Ev


Returns recursion depth

Ev::backend
Ev::embeddableBackends
Ev
PHP Manual

Ev::depth

(PECL ev >= 0.2.0)

Ev::depth — Returns recursion depth

Descrierea

final public static int Ev::depth ( void )

The number of times Ev::run() was entered minus the number of times Ev::run() was exited normally, in other words, the recursion depth. Outside Ev::run() , this number is 0 . In a callback, this number is 1 , unless Ev::run() was invoked recursively (or from another thread), in which case it is higher.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ev_depth() returns recursion depth of the default loop.

A se vedea ?i

  • Ev::iteration() - Return the number of times the default event loop has polled for new events.
Ev::backend
Ev::embeddableBackends
Ev


Returns the set of backends that are embeddable in other event loops.

Ev::depth
Ev::feedSignal
Ev
PHP Manual

Ev::embeddableBackends

(PECL ev >= 0.2.0)

Ev::embeddableBackends — Returns the set of backends that are embeddable in other event loops.

Descrierea

final public static void Ev::embeddableBackends ( void )

Returns the set of backends that are embeddable in other event loops.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a bit mask which can containing backend flags combined using bitwise OR operator.

Exemple

Example #1 Embedding loop created with kqueue backend into the default loop

<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop        = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed       = NULL;

if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
 if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
  $embed = new EvEmbed($loop);
 }
}

if (!$socket_loop) {
 $socket_loop = $loop;
}

// Now use $socket_loop for all sockets, and $loop for anything else
?>

A se vedea ?i

  • EvEmbed
  • Ev::recommendedBackends() - Returns a bit mask of recommended backends for current platform.
  • Ev::supportedBackends() - Returns the set of backends supported by current libev configuration.
  • Backend flags
  • Examples
Ev::depth
Ev::feedSignal
Ev


Feed a signal event info Ev

Ev::embeddableBackends
Ev::feedSignalEvent
Ev
PHP Manual

Ev::feedSignal

(PECL ev >= 0.2.0)

Ev::feedSignal — Feed a signal event info Ev

Descrierea

final public static void Ev::feedSignal ( int $signum )

Simulates a signal receive. It is safe to call this function at any time, from any context, including signal handlers or random threads. Its main use is to customise signal handling in the process.

Unlike Ev::feedSignalEvent() , this works regardless of which loop has registered the signal.

Parametri

signum

Signal number. See signal(7) man page for detals. You can use constants exported by pcntl extension.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Ev::feedSignalEvent() - Feed signal event into the default loop
Ev::embeddableBackends
Ev::feedSignalEvent
Ev


Feed signal event into the default loop

Ev::feedSignal
Ev::iteration
Ev
PHP Manual

Ev::feedSignalEvent

(No version information available, might only be in Git)

Ev::feedSignalEvent — Feed signal event into the default loop

Descrierea

final public static void Ev::feedSignalEvent ( int $signum )

Feed signal event into the default loop. Ev will react to this call as if the signal specified by signal had occurred.

Parametri

signum

Signal number. See signal(7) man page for detals. See also constants exported by pcntl extension.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Ev::feedSignal() - Feed a signal event info Ev
Ev::feedSignal
Ev::iteration
Ev


Return the number of times the default event loop has polled for new events.

Ev::feedSignalEvent
Ev::now
Ev
PHP Manual

Ev::iteration

(PECL ev >= 0.2.0)

Ev::iteration — Return the number of times the default event loop has polled for new events.

Descrierea

final public static int Ev::iteration ( void )

Return the number of times the event loop has polled for new events. Sometimes useful as a generation counter.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns number of polls of the default event loop.

A se vedea ?i

  • Ev::depth() - Returns recursion depth
Ev::feedSignalEvent
Ev::now
Ev


Returns the time when the last iteration of the default event loop has started.

Ev::iteration
Ev::nowUpdate
Ev
PHP Manual

Ev::now

(PECL ev >= 0.2.0)

Ev::now — Returns the time when the last iteration of the default event loop has started.

Descrierea

final public static double Ev::now ( void )

Returns the time when the last iteration of the default event loop has started. This is the time that timers( EvTimer and EvPeriodic ) are based on, and referring to it is usually faster then calling Ev::time() .

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns number of seconds(fractional) representing the time when the last iteration of the default event loop has started.

A se vedea ?i

  • Ev::nowUpdate() - Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.
Ev::iteration
Ev::nowUpdate
Ev


Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.

Ev::now
Ev::recommendedBackends
Ev
PHP Manual

Ev::nowUpdate

(PECL ev >= 0.2.0)

Ev::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.

Descrierea

final public static void Ev::nowUpdate ( void )

Establishes the current time by querying the kernel, updating the time returned by Ev::now() in the progress. This is a costly operation and is usually done automatically within Ev::run() .

This method is rarely useful, but when some event callback runs for a very long time without entering the event loop, updating libev 's consideration of the current time is a good idea.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Ev::now() - Returns the time when the last iteration of the default event loop has started.
Ev::now
Ev::recommendedBackends
Ev


Returns a bit mask of recommended backends for current platform.

Ev::nowUpdate
Ev::resume
Ev
PHP Manual

Ev::recommendedBackends

(PECL ev >= 0.2.0)

Ev::recommendedBackends — Returns a bit mask of recommended backends for current platform.

Descrierea

final public static void Ev::recommendedBackends ( void )

Returns the set of all backends compiled into this binary of libev and also recommended for this platform, meaning it will work for most file descriptor types. This set is often smaller than the one returned by ev_supported_backends() , as for example kqueue is broken on most BSD systems and will not be auto-detected unless it is requested explicitly. This is the set of backends that libev will probe no backends specified explicitly.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a bit mask which can containing backend flags combined using bitwise OR operator.

Exemple

Example #1 Embedding one loop into another

<?php
/*
* Try to get an embeddable event loop and embed it into the default event loop.
* If it is impossible, use the default
* loop. The default loop is stored in $loop_hi, while the embeddable loop is
* stored in $loop_lo(which is $loop_hi in the case no embeddable loop can be
* used).
*
* Sample translated to PHP
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop_hi = EvLoop::defaultLoop();
$loop_lo = NULL;
$embed   = NULL;

/*
* See if there is a chance of getting one that works
* (flags' value of 0 means autodetection)
*/
$loop_lo = Ev::embeddableBackends() & Ev::recommendedBackends()
 ? new EvLoop(Ev::embeddableBackends() & Ev::recommendedBackends())
 : 0;

if ($loop_lo) {
 $embed = new EvEmbed($loop_lo, function () {});
} else {
 $loop_lo = $loop_hi;
}
?>

A se vedea ?i

  • EvEmbed
  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops.
  • Ev::supportedBackends() - Returns the set of backends supported by current libev configuration.
  • Backend flags
  • Examples
Ev::nowUpdate
Ev::resume
Ev


Resume previously suspended default event loop

Ev::recommendedBackends
Ev::run
Ev
PHP Manual

Ev::resume

(PECL ev >= 0.2.0)

Ev::resume — Resume previously suspended default event loop

Descrierea

final public static void Ev::resume ( void )

Ev::suspend() and Ev::resume() methods suspend and resume a loop correspondingly.

All timer watchers will be delayed by the time spend between suspend and resume , and all periodic watchers will be rescheduled(that is, they will lose any events that would have occurred while suspended).

After calling Ev::suspend() it is not allowed to call any function on the given loop other than Ev::resume() . Also it is not allowed to call Ev::resume() without a previous call to Ev::suspend() .

Calling suspend / resume has the side effect of updating the event loop time(see Ev::nowUpdate() ).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Ev::suspend() - Suspend the default event loop
Ev::recommendedBackends
Ev::run
Ev


Begin checking for events and calling callbacks for the default loop

Ev::resume
Ev::sleep
Ev
PHP Manual

Ev::run

(PECL ev >= 0.2.0)

Ev::run — Begin checking for events and calling callbacks for the default loop

Descrierea

final public static void Ev::run ([ int $flags ] )

Begin checking for events and calling callbacks for the default loop . Returns when a callback calls Ev::stop() method, or the flags are nonzero(in which case the return value is true) or when there are no active watchers which reference the loop( EvWatcher::keepalive() is TRUE), in which case the return value will be FALSE. The return value can generally be interpreted as if TRUE, there is more work left to do .

Parametri

flags

Optional parameter flags can be one of the following:

List for possible values of flags
flags | Description
0 | The default behavior described above
Ev::RUN_ONCE | Block at most one(wait, but don't loop)
Ev::RUN_NOWAIT | Don't block at all(fetch/handle events, but don't wait)

See the run flag constants .

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Ev::stop() - Stops the default event loop
  • EvLoop::run() - Begin checking for events and calling callbacks for the loop
Ev::resume
Ev::sleep
Ev


Block the process for the given number of seconds.

Ev::run
Ev::stop
Ev
PHP Manual

Ev::sleep

(PECL ev >= 0.2.0)

Ev::sleep — Block the process for the given number of seconds.

Descrierea

final public static void Ev::sleep ( double $seconds )

Block the process for the given number of seconds.

Parametri

seconds

Fractional number of seconds

Valorile întoarse

Nu este întoarsa nici o valoare.

Ev::run
Ev::stop
Ev


Stops the default event loop

Ev::sleep
Ev::supportedBackends
Ev
PHP Manual

Ev::stop

(PECL ev >= 0.2.0)

Ev::stop — Stops the default event loop

Descrierea

final public static void Ev::stop ([ int $how ] )

Stops the default event loop

Parametri

how

One of Ev::BREAK_* constants .

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Ev::run() - Begin checking for events and calling callbacks for the default loop
Ev::sleep
Ev::supportedBackends
Ev


Returns the set of backends supported by current libev configuration.

Ev::stop
Ev::suspend
Ev
PHP Manual

Ev::supportedBackends

(PECL ev >= 0.2.0)

Ev::supportedBackends — Returns the set of backends supported by current libev configuration.

Descrierea

final public static void Ev::supportedBackends ( void )

Returns the set of backends supported by current libev configuration.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a bit mask which can containing backend flags combined using bitwise OR operator.

Exemple

Example #1 Embedding loop created with kqueue backend into the default loop

<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop        = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed       = NULL;

if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
 if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
  $embed = new EvEmbed($loop);
 }
}

if (!$socket_loop) {
 $socket_loop = $loop;
}

// Now use $socket_loop for all sockets, and $loop for anything else
?>

A se vedea ?i

  • EvEmbed
  • Ev::recommendedBackends() - Returns a bit mask of recommended backends for current platform.
  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops.
  • Backend flags
  • Examples
Ev::stop
Ev::suspend
Ev


Suspend the default event loop

Ev::supportedBackends
Ev::time
Ev
PHP Manual

Ev::suspend

(PECL ev >= 0.2.0)

Ev::suspend — Suspend the default event loop

Descrierea

final public static void Ev::suspend ( void )

Ev::suspend() and Ev::resume() methods suspend and resume the default loop correspondingly.

All timer watchers will be delayed by the time spend between suspend and resume , and all periodic watchers will be rescheduled(that is, they will lose any events that would have occurred while suspended).

After calling Ev::suspend() it is not allowed to call any function on the given loop other than Ev::resume() . Also it is not allowed to call Ev::resume() without a previous call to Ev::suspend() .

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Ev::resume() - Resume previously suspended default event loop
Ev::supportedBackends
Ev::time
Ev


Returns the current time in fractional seconds since the epoch.

Ev::suspend
Ev::verify
Ev
PHP Manual

Ev::time

(PECL ev >= 0.2.0)

Ev::time — Returns the current time in fractional seconds since the epoch.

Descrierea

final public static double Ev::time ( void )

Returns the current time in fractional seconds since the epoch. Consider using Ev::now()

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current time in fractional seconds since the epoch.

A se vedea ?i

  • Ev::now() - Returns the time when the last iteration of the default event loop has started.
Ev::suspend
Ev::verify
Ev


Performs internal consistency checks(for debugging)

Ev::time
EvCheck
Ev
PHP Manual

Ev::verify

(PECL ev >= 0.2.0)

Ev::verify — Performs internal consistency checks(for debugging)

Descrierea

final public static void Ev::verify ( void )

Performs internal consistency checks(for debugging libev ) and abort the program if any data structures were found to be corrupted.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Ev::time
EvCheck
Ev


The EvCheck class

(PECL ev >= 0.2.0)

Introducere

EvPrepare and EvCheck watchers are usually used in pairs. EvPrepare watchers get invoked before the process blocks, EvCheck afterwards.

It is not allowed to call EvLoop::run() or similar methods or functions that enter the current event loop from either EvPrepare or EvCheck watchers. Other loops than the current one are fine, however. The rationale behind this is that one don't need to check for recursion in those watchers, i.e. the sequence will always be: EvPrepare -> blocking -> EvCheck , so having a watcher of each kind they will always be called in pairs bracketing the blocking call.

The main purpose is to integrate other event mechanisms into libev and their use is somewhat advanced. They could be used, for example, to track variable changes, implement custom watchers, integrate net-snmp or a coroutine library and lots more. They are also occasionally useful to cache some data and want to flush it before blocking.

It is recommended to give EvCheck watchers highest( Ev::MAXPRI ) priority, to ensure that they are being run before any other watchers after the poll (this doesn’t matter for EvPrepare watchers).

Also, EvCheck watchers should not activate/feed events. While libev fully supports this, they might get executed before other EvCheck watchers did their job.

Sinopsisul clasei

EvCheck extends EvWatcher {
/* Proprieta?i mo?tenite */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Metode */
public __construct ( callable $callback [, mixed $data [, int $priority ]] )
final public static object createStopped ( string $callback [, string $data [, string $priority ]] )
/* Metode mo?tenite */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Cuprins

  • EvCheck::__construct — Constructs the EvCheck watcher object
  • EvCheck::createStopped — Create instance of a stopped EvCheck watcher
Ev::verify
EvCheck::__construct
Ev


Constructs the EvCheck watcher object

EvCheck
EvCheck::createStopped
EvCheck
PHP Manual

EvCheck::__construct

(PECL ev >= 0.2.0)

EvCheck::__construct — Constructs the EvCheck watcher object

Descrierea

public EvCheck::__construct ( callable $callback [, mixed $data [, int $priority ]] )

Constructs the EvCheck watcher object.

Parametri

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvCheck object on success.

A se vedea ?i

  • EvPrepare
  • EvLoop::check() - Creates EvCheck object associated with the current event loop instance
EvCheck
EvCheck::createStopped
EvCheck


Create instance of a stopped EvCheck watcher

EvCheck::__construct
EvChild
EvCheck
PHP Manual

EvCheck::createStopped

(PECL ev >= 0.2.0)

EvCheck::createStopped — Create instance of a stopped EvCheck watcher

Descrierea

final public static object EvCheck::createStopped ( string $callback [, string $data [, string $priority ]] )

Create instance of a stopped EvCheck watcher

Parametri

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvCheck object on success.

A se vedea ?i

  • EvPrepare
EvCheck::__construct
EvChild
EvCheck


The EvChild class

(PECL ev >= 0.2.0)

Introducere

EvChild watchers trigger when the process receives a SIGCHLD in response to some child status changes (most typically when a child dies or exits). It is permissible to install an EvChild watcher after the child has been forked(which implies it might have already exited), as long as the event loop isn't entered(or is continued from a watcher), i.e. forking and then immediately registering a watcher for the child is fine, but forking and registering a watcher a few event loop iterations later or in the next callback invocation is not.

It is allowed to register EvChild watchers in the default loop only.

Sinopsisul clasei

EvChild extends EvWatcher {
/* Proprieta?i */
public $pid ;
public $rpid ;
public $rstatus ;
/* Proprieta?i mo?tenite */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Metode */
public __construct ( int $pid , bool $trace , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static object createStopped ( int $pid , bool $trace , callable $callback [, mixed $data [, int $priority ]] )
public void set ( int $pid , bool $trace )
/* Metode mo?tenite */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Proprieta?i

pid

Readonly . The process ID this watcher watches out for, or 0 , meaning any process ID.

rpid

Readonly .The process ID that detected a status change.

rstatus

Readonly . The process exit status caused by rpid .

Cuprins

  • EvChild::__construct — Constructs the EvChild watcher object
  • EvChild::createStopped — Create instance of a stopped EvCheck watcher
  • EvChild::set — Configures the watcher
EvCheck::createStopped
EvChild::__construct
Ev


Constructs the EvChild watcher object

EvChild
EvChild::createStopped
EvChild
PHP Manual

EvChild::__construct

(PECL ev >= 0.2.0)

EvChild::__construct — Constructs the EvChild watcher object

Descrierea

public EvChild::__construct ( int $pid , bool $trace , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs the EvChild watcher object.

Call the callback when a status change for process ID pid (or any PID if pid is 0 ) has been received(a status change happens when the process terminates or is killed, or, when trace is TRUE, additionally when it is stopped or continued). In other words, when the process receives a SIGCHLD , Ev will fetch the outstanding exit/wait status for all changed/zombie children and call the callback.

It is valid to install a child watcher after an EvChild has exited but before the event loop has started its next iteration. For example, first one calls fork , then the new child process might exit, and only then an EvChild watcher is installed in the parent for the new PID .

You can access both exit/tracing status and pid by using the rstatus and rpid properties of the watcher object.

The number of PID watchers per PID is unlimited. All of them will be called.

The EvChild::createStopped() method doesn't start(activate) the newly created watcher.

Parametri

pid

Wait for status changes of process PID(or any process if PID is specified as 0 ).

trace

If FALSE, only activate the watcher when the process terminates. Otherwise(TRUE) additionally activate the watcher when the process is stopped or continued.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvChild object on success.

A se vedea ?i

  • EvLoop::child() - Creates EvChild object associated with the current event loop
EvChild
EvChild::createStopped
EvChild


Create instance of a stopped EvCheck watcher

EvChild::__construct
EvChild::set
EvChild
PHP Manual

EvChild::createStopped

(PECL ev >= 0.2.0)

EvChild::createStopped — Create instance of a stopped EvCheck watcher

Descrierea

final public static object EvChild::createStopped ( int $pid , bool $trace , callable $callback [, mixed $data [, int $priority ]] )

The same as EvChild::__construct() , but doesn't start the watcher automatically.

Parametri

pid

The same as for EvChild::__construct()

trace

The same as for EvChild::__construct()

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

A se vedea ?i

  • EvChild::__construct() - Constructs the EvChild watcher object
  • EvLoop::child() - Creates EvChild object associated with the current event loop
EvChild::__construct
EvChild::set
EvChild


Configures the watcher

EvChild::createStopped
EvEmbed
EvChild
PHP Manual

EvChild::set

(PECL ev >= 0.2.0)

EvChild::set — Configures the watcher

Descrierea

public void EvChild::set ( int $pid , bool $trace )

Parametri

pid

The same as for EvChild::__construct()

trace

The same as for EvChild::__construct()

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EvChild::__construct() - Constructs the EvChild watcher object
EvChild::createStopped
EvEmbed
EvChild


The EvEmbed class

(PECL ev >= 0.2.0)

Introducere

Used to embed one event loop into another.

Sinopsisul clasei

EvEmbed extends EvWatcher {
/* Proprieta?i */
public $embed ;
/* Metode */
public __construct ( object $other [, callable $callback [, mixed $data [, int $priority ]]] )
final public static void createStopped ( object $other [, callable $callback [, mixed $data [, int $priority ]]] )
public void set ( object $other )
public void sweep ( void )
/* Metode mo?tenite */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Proprieta?i

is_active

data

is_pending

priority

embed

Cuprins

  • EvEmbed::__construct — Constructs the EvEmbed object
  • EvEmbed::createStopped — Create stopped EvEmbed watcher object
  • EvEmbed::set — Configures the watcher
  • EvEmbed::sweep — Make a single, non-blocking sweep over the embedded loop.
EvChild::set
EvEmbed::__construct
Ev


Constructs the EvEmbed object

EvEmbed
EvEmbed::createStopped
EvEmbed
PHP Manual

EvEmbed::__construct

(PECL ev >= 0.2.0)

EvEmbed::__construct — Constructs the EvEmbed object

Descrierea

public EvEmbed::__construct ( object $other [, callable $callback [, mixed $data [, int $priority ]]] )

This is a rather advanced watcher type that lets to embed one event loop into another(currently only IO events are supported in the embedded loop, other types of watchers might be handled in a delayed or incorrect fashion and must not be used).

See » the libev documentation for details.

This watcher is most useful on BSD systems without working kqueue to still be able to handle a large number of sockets. See example below.

Parametri

other

Instance of EvLoop . The loop to embed, this loop must be embeddable(see Ev::embeddableBackends() ).

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvEmbed object on success.

Exemple

Example #1 Embedding loop created with kqueue backend into the default loop

<?php
/*
 * Check if kqueue is available but not recommended and create a kqueue backend
 * for use with sockets (which usually work with any kqueue implementation).
 * Store the kqueue/socket-only event loop in loop_socket. (One might optionally
 * use EVFLAG_NOENV, too)
 *
 * Example borrowed from
 * http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
 */
$loop        = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed       = NULL;

if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
    if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
        $embed = new EvEmbed($loop);
    }
}

if (!$socket_loop) {
    $socket_loop = $loop;
}

// Now use $socket_loop for all sockets, and $loop for anything else
?>

A se vedea ?i

  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops.
EvEmbed
EvEmbed::createStopped
EvEmbed


Create stopped EvEmbed watcher object

EvEmbed::__construct
EvEmbed::set
EvEmbed
PHP Manual

EvEmbed::createStopped

(PECL ev >= 0.2.0)

EvEmbed::createStopped — Create stopped EvEmbed watcher object

Descrierea

final public static void EvEmbed::createStopped ( object $other [, callable $callback [, mixed $data [, int $priority ]]] )

The same as EvEmbed::__construct() , but doesn't start the watcher automatically.

Parametri

other

The same as for EvEmbed::__construct()

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns stopped EvEmbed object on success.

A se vedea ?i

  • EvEmbed::__construct() - Constructs the EvEmbed object
  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops.
EvEmbed::__construct
EvEmbed::set
EvEmbed


Configures the watcher

EvEmbed::createStopped
EvEmbed::sweep
EvEmbed
PHP Manual

EvEmbed::set

(PECL ev >= 0.2.0)

EvEmbed::set — Configures the watcher

Descrierea

public void EvEmbed::set ( object $other )

Configures the watcher to use other event loop object.

Parametri

other

The same as for EvEmbed::__construct()

Valorile întoarse

Nu este întoarsa nici o valoare.

EvEmbed::createStopped
EvEmbed::sweep
EvEmbed


Make a single, non-blocking sweep over the embedded loop.

EvEmbed::set
EvFork
EvEmbed
PHP Manual

EvEmbed::sweep

(PECL ev >= 0.2.0)

EvEmbed::sweep — Make a single, non-blocking sweep over the embedded loop.

Descrierea

public void EvEmbed::sweep ( void )

Make a single, non-blocking sweep over the embedded loop. Works similarly to the following, but in the most appropriate way for embedded loops:

<?php
$other->start(Ev::RUN_NOWAIT);
?>

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EvWatcher::start() - Starts the watcher
EvEmbed::set
EvFork
EvEmbed


The EvFork class

(PECL ev >= 0.2.0)

Introducere

Fork watchers are called when a fork() was detected (usually because whoever signalled libev about it by calling EvLoop::fork() ). The invocation is done before the event loop blocks next and before EvCheck watchers are being called, and only in the child after the fork. Note, that if whoever calling EvLoop::fork() calls it in the wrong process, the fork handlers will be invoked, too.

Sinopsisul clasei

EvFork extends EvWatcher {
/* Proprieta?i mo?tenite */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Metode */
public __construct ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static object createStopped ( string $callback [, string $data [, string $priority ]] )
/* Metode mo?tenite */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Cuprins

  • EvFork::__construct — Constructs the EvFork watcher object
  • EvFork::createStopped — Creates a stopped instance of EvFork watcher class
EvEmbed::sweep
EvFork::__construct
Ev


Constructs the EvFork watcher object

EvFork
EvFork::createStopped
EvFork
PHP Manual

EvFork::__construct

(PECL ev >= 0.2.0)

EvFork::__construct — Constructs the EvFork watcher object

Descrierea

public EvFork::__construct ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs the EvFork watcher object and starts the watcher automatically.

Parametri

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvFork object on success.

A se vedea ?i

  • EvLoop::fork() - Creates EvFork watcher object associated with the current event loop instance
  • EvCheck
EvFork
EvFork::createStopped
EvFork


Creates a stopped instance of EvFork watcher class

EvFork::__construct
EvIdle
EvFork
PHP Manual

EvFork::createStopped

(PECL ev >= 0.2.0)

EvFork::createStopped — Creates a stopped instance of EvFork watcher class

Descrierea

final public static object EvFork::createStopped ( string $callback [, string $data [, string $priority ]] )

The same as EvFork::__construct() , but doesn't start the watcher automatically.

Parametri

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvFork(stopped) object on success.

A se vedea ?i

  • EvFork::__construct() - Constructs the EvFork watcher object
EvFork::__construct
EvIdle
EvFork


The EvIdle class

(PECL ev >= 0.2.0)

Introducere

EvIdle watchers trigger events when no other events of the same or higher priority are pending ( EvPrepare , EvCheck and other EvIdle watchers do not count as receiving events ).

Thus, as long as the process is busy handling sockets or timeouts(or even signals) of the same or higher priority it will not be triggered. But when the process is in idle(or only lower-priority watchers are pending), the EvIdle watchers are being called once per event loop iteration - until stopped, that is, or the process receives more events and becomes busy again with higher priority stuff.

Apart from keeping the process non-blocking(which is a useful on its own sometimes), EvIdle watchers are a good place to do "pseudo-background processing" , or delay processing stuff to after the event loop has handled all outstanding events.

The most noticeable effect is that as long as any idle watchers are active, the process will not block when waiting for new events.

Sinopsisul clasei

EvIdle extends EvWatcher {
/* Proprieta?i mo?tenite */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Metode */
public __construct ( callable $callback [, mixed $data [, int $priority ]] )
final public static object createStopped ( string $callback [, mixed $data [, int $priority ]] )
/* Metode mo?tenite */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Cuprins

  • EvIdle::__construct — Constructs the EvIdle watcher object
  • EvIdle::createStopped — Creates instance of a stopped EvIdle watcher object
EvFork::createStopped
EvIdle::__construct
Ev


Constructs the EvIdle watcher object

EvIdle
EvIdle::createStopped
EvIdle
PHP Manual

EvIdle::__construct

(PECL ev >= 0.2.0)

EvIdle::__construct — Constructs the EvIdle watcher object

Descrierea

public EvIdle::__construct ( callable $callback [, mixed $data [, int $priority ]] )

Constructs the EvIdle watcher object and starts the watcher automatically.

Parametri

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvIdle object on success.

A se vedea ?i

  • EvIdle::createStopped() - Creates instance of a stopped EvIdle watcher object
  • EvLoop::idle() - Creates EvIdle watcher object associated with the current event loop instance
EvIdle
EvIdle::createStopped
EvIdle


Creates instance of a stopped EvIdle watcher object

EvIdle::__construct
EvIo
EvIdle
PHP Manual

EvIdle::createStopped

(PECL ev >= 0.2.0)

EvIdle::createStopped — Creates instance of a stopped EvIdle watcher object

Descrierea

final public static object EvIdle::createStopped ( string $callback [, mixed $data [, int $priority ]] )

The same as EvIdle::__construct() , but doesn't start the watcher automatically.

Parametri

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvIdle object on success.

A se vedea ?i

  • EvIdle::__construct() - Constructs the EvIdle watcher object
  • EvLoop::idle() - Creates EvIdle watcher object associated with the current event loop instance
EvIdle::__construct
EvIo
EvIdle


The EvIo class

(PECL ev >= 0.2.0)

Introducere

EvIo watchers check whether a file descriptor(or socket, or a stream castable to numeric file descriptor) is readable or writable in each iteration of the event loop, or, more precisely, when reading would not block the process and writing would at least be able to write some data. This behaviour is called level-triggering because events are kept receiving as long as the condition persists. To stop receiving events just stop the watcher.

The number of read and/or write event watchers per fd is unlimited. Setting all file descriptors to non-blocking mode is also usually a good idea(but not required).

Another thing to watch out for is that it is quite easy to receive false readiness notifications, i.e. the callback might be called with Ev::READ but a subsequent read() will actually block because there is no data. It is very easy to get into this situation. Thus it is best to always use non-blocking I/O: An extra read() returning EAGAIN (or similar) is far preferable to a program hanging until some data arrives.

If for some reason it is impossible to run the fd in non-blocking mode, then separately re-test whether a file descriptor is really ready. Some people additionally use SIGALRM and an interval timer, just to be sure thry won't block infinitely.

Always consider using non-blocking mode.

Sinopsisul clasei

EvIo extends EvWatcher {
/* Proprieta?i */
public $fd ;
public $events ;
/* Proprieta?i mo?tenite */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Metode */
public __construct ( mixed $fd , int $events , callable $callback [, mixed $data [, int $priority ]] )
final public static EvIo createStopped ( mixed $fd , int $events , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void set ( mixed $fd , int $events )
/* Metode mo?tenite */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Proprieta?i

fd

events

Cuprins

  • EvIo::__construct — Constructs EvIo watcher object
  • EvIo::createStopped — Create stopped EvIo watcher object
  • EvIo::set — Configures the watcher
EvIdle::createStopped
EvIo::__construct
Ev


Constructs EvIo watcher object

EvIo
EvIo::createStopped
EvIo
PHP Manual

EvIo::__construct

(PECL ev >= 0.2.0)

EvIo::__construct — Constructs EvIo watcher object

Descrierea

public EvIo::__construct ( mixed $fd , int $events , callable $callback [, mixed $data [, int $priority ]] )

Constructs EvIo watcher object and starts the watcher automatically.

Parametri

fd

Can be a stream opened with fopen() or similar functions, numeric file descriptor, or socket.

events

Ev::READ and/or Ev::WRITE . See the bit masks .

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvIo object on success.

A se vedea ?i

  • EvIo::createStopped() - Create stopped EvIo watcher object
  • EvLoop::io() - Create EvIo watcher object associated with the current event loop instance
EvIo
EvIo::createStopped
EvIo


Create stopped EvIo watcher object

EvIo::__construct
EvIo::set
EvIo
PHP Manual

EvIo::createStopped

(PECL ev >= 0.2.0)

EvIo::createStopped — Create stopped EvIo watcher object

Descrierea

final public static EvIo EvIo::createStopped ( mixed $fd , int $events , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

The same as EvIo::__construct() , but doesn't start the watcher automatically.

Parametri

fd

The same as for EvIo::__construct()

events

The same as for EvIo::__construct()

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvIo object on success.

A se vedea ?i

  • EvIo::__construct() - Constructs EvIo watcher object
  • EvLoop::io() - Create EvIo watcher object associated with the current event loop instance
EvIo::__construct
EvIo::set
EvIo


Configures the watcher

EvIo::createStopped
EvLoop
EvIo
PHP Manual

EvIo::set

(PECL ev >= 0.2.0)

EvIo::set — Configures the watcher

Descrierea

public void EvIo::set ( mixed $fd , int $events )

Configures the EvIo watcher

Parametri

fd

The same as for EvIo::__construct()

events

The same as for EvIo::__construct()

Valorile întoarse

Nu este întoarsa nici o valoare.

EvIo::createStopped
EvLoop
EvIo


The EvLoop class

(PECL ev >= 0.2.0)

Introducere

Represents an event loop that is always distinct from the default loop . Unlike the default loop , it cannot handle EvChild watchers.

Having threads we have to create a loop per thread, and use the default loop in the parent thread.

The default event loop is initialized automatically by Ev . It is accessible via methods of the Ev class, or via EvLoop::defaultLoop() method.

Sinopsisul clasei

final EvLoop {
/* Proprieta?i */
public $data ;
public $backend ;
public $is_default_loop ;
public $iteration ;
public $pending ;
public $io_interval ;
public $timeout_interval ;
public $depth ;
/* Metode */
public int backend ( void )
final public EvCheck check ( string $callback [, string $data [, string $priority ]] )
final public EvChild child ( string $pid , string $trace , string $callback [, string $data [, string $priority ]] )
public __construct ([ int $flags [, mixed $data = NULL [, double $io_interval = 0.0 [, double $timeout_interval = 0.0 ]]]] )
public static EvLoop defaultLoop ([ int $flags = Ev::FLAG_AUTO [, mixed $data = NULL [, double $io_interval = 0. [, double $timeout_interval = 0. ]]]] )
final public EvEmbed embed ( string $other [, string $callback [, string $data [, string $priority ]]] )
final public EvFork fork ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public EvIdle idle ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void invokePending ( void )
final public EvIo io ( mixed $fd , int $events , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void loopFork ( void )
public double now ( void )
public void nowUpdate ( void )
final public EvPeriodic periodic ( double $offset , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public EvPrepare prepare ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void resume ( void )
public void run ([ int $flags = 0 ] )
final public EvSignal signal ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public EvStat stat ( string $path , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void stop ([ int $how ] )
public void suspend ( void )
final public EvTimer timer ( double $after , double $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void verify ( void )
}

Proprieta?i

data

Custom data attached to loop

backend

Readonly . The backend flags indicating the event backend in use.

is_default_loop

Readonly . TRUE if it is the default event loop.

iteration

The current iteration count of the loop. See Ev::iteration()

pending

The number of pending watchers. 0 indicates that there are no watchers pending.

io_interval

Higher io_interval allows libev to spend more time collecting EvIo events, so more events can be handled per iteration, at the cost of increasing latency. Timeouts (both EvPeriodic and EvTimer ) will not be affected. Setting this to a non-zero value will introduce an additional sleep() call into most loop iterations. The sleep time ensures that libev will not poll for EvIo events more often than once per this interval, on average. Many programs can usually benefit by setting the io_interval to a value near 0.1 , which is often enough for interactive servers(not for games). It usually doesn't make much sense to set it to a lower value than 0.01 , as this approaches the timing granularity of most systems.

See also » FUNCTIONS CONTROLLING EVENT LOOPS .

timeout_interval

Higher timeout_interval allows libev to spend more time collecting timeouts, at the expense of increased latency/jitter/inexactness(the watcher callback will be called later). EvIo watchers will not be affected. Setting this to a non-null value will not introduce any overhead in libev . See also » FUNCTIONS CONTROLLING EVENT LOOPS .

depth

The recursion depth. See Ev::depth() .

Cuprins

  • EvLoop::backend — Returns an integer describing the backend used by libev.
  • EvLoop::check — Creates EvCheck object associated with the current event loop instance
  • EvLoop::child — Creates EvChild object associated with the current event loop
  • EvLoop::__construct — Constructs the event loop object
  • EvLoop::defaultLoop — Returns or creates the default event loop.
  • EvLoop::embed — Creates an instance of EvEmbed watcher associated with the current EvLoop object.
  • EvLoop::fork — Creates EvFork watcher object associated with the current event loop instance
  • EvLoop::idle — Creates EvIdle watcher object associated with the current event loop instance
  • EvLoop::invokePending — Invoke all pending watchers while resetting their pending state
  • EvLoop::io — Create EvIo watcher object associated with the current event loop instance
  • EvLoop::loopFork — Must be called after a fork
  • EvLoop::now — Returns the current "event loop time"
  • EvLoop::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress.
  • EvLoop::periodic — Creates EvPeriodic watcher object associated with the current event loop instance
  • EvLoop::prepare — Creates EvPrepare watcher object associated with the current event loop instance
  • EvLoop::resume — Resume previously suspended default event loop
  • EvLoop::run — Begin checking for events and calling callbacks for the loop
  • EvLoop::signal — Creates EvSignal watcher object associated with the current event loop instance
  • EvLoop::stat — Creates EvStat watcher object associated with the current event loop instance
  • EvLoop::stop — Stops the event loop
  • EvLoop::suspend — Suspend the loop
  • EvLoop::timer — Creates EvTimer watcher object associated with the current event loop instance
  • EvLoop::verify — Performs internal consistency checks(for debugging)
EvIo::set
EvLoop::backend
Ev


Returns an integer describing the backend used by libev.

EvLoop
EvLoop::check
EvLoop
PHP Manual

EvLoop::backend

(PECL ev >= 0.2.0)

EvLoop::backend — Returns an integer describing the backend used by libev.

Descrierea

public int EvLoop::backend ( void )

The same as Ev::backend() , but for the loop instance.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an integer describing the backend used by libev. See Ev::backend() .

A se vedea ?i

  • Ev::backend() - Returns an integer describing the backend used by libev.
EvLoop
EvLoop::check
EvLoop


Creates EvCheck object associated with the current event loop instance

EvLoop::backend
EvLoop::child
EvLoop
PHP Manual

EvLoop::check

(PECL ev >= 0.2.0)

EvLoop::check — Creates EvCheck object associated with the current event loop instance

Descrierea

final public EvCheck EvLoop::check ( string $callback [, string $data [, string $priority ]] )

Creates EvCheck object associated with the current event loop instance.

Parametri

All parameters have the same meaning as for EvCheck::__construct()

Valorile întoarse

Returns EvCheck object on success.

A se vedea ?i

  • EvCheck::__construct() - Constructs the EvCheck watcher object
EvLoop::backend
EvLoop::child
EvLoop


Creates EvChild object associated with the current event loop

EvLoop::check
EvLoop::__construct
EvLoop
PHP Manual

EvLoop::child

(PECL ev >= 0.2.0)

EvLoop::child — Creates EvChild object associated with the current event loop

Descrierea

final public EvChild EvLoop::child ( string $pid , string $trace , string $callback [, string $data [, string $priority ]] )

Creates EvChild object associated with the current event loop.

Parametri

All parameters have the same meaning as for EvChild::__construct()

Valorile întoarse

Returns EvChild object on success.

A se vedea ?i

  • EvChild::__construct() - Constructs the EvChild watcher object
EvLoop::check
EvLoop::__construct
EvLoop


Constructs the event loop object

EvLoop::child
EvLoop::defaultLoop
EvLoop
PHP Manual

EvLoop::__construct

(PECL ev >= 0.2.0)

EvLoop::__construct — Constructs the event loop object

Descrierea

public EvLoop::__construct ([ int $flags [, mixed $data = NULL [, double $io_interval = 0.0 [, double $timeout_interval = 0.0 ]]]] )

Constructs the event loop object.

Parametri

flags

One of the event loop flags

data

Custom data associated with the loop.

io_interval

See io_interval

timeout_interval

See timeout_interval

Valorile întoarse

Returns new EvLoop object.

A se vedea ?i

  • EvLoop::defaultLoop() - Returns or creates the default event loop.
EvLoop::child
EvLoop::defaultLoop
EvLoop


Returns or creates the default event loop.

EvLoop::__construct
EvLoop::embed
EvLoop
PHP Manual

EvLoop::defaultLoop

(PECL ev >= 0.2.0)

EvLoop::defaultLoop — Returns or creates the default event loop.

Descrierea

public static EvLoop EvLoop::defaultLoop ([ int $flags = Ev::FLAG_AUTO [, mixed $data = NULL [, double $io_interval = 0. [, double $timeout_interval = 0. ]]]] )

If the default event loop is not created, EvLoop::defaultLoop() creates it with the specified parameters. Otherwise, it just returns the object representing previously created instance ignoring all the parameters.

Parametri

flags

One of the event loop flags

data

Custom data to associate with the loop.

io_collect_interval

See io_interval

timeout_collect_interval

See timeout_interval

Valorile întoarse

Returns EvLoop object on success.

A se vedea ?i

  • EvLoop::__construct() - Constructs the event loop object
EvLoop::__construct
EvLoop::embed
EvLoop


Creates an instance of EvEmbed watcher associated with the current EvLoop object.

EvLoop::defaultLoop
EvLoop::fork
EvLoop
PHP Manual

EvLoop::embed

(PECL ev >= 0.2.0)

EvLoop::embed — Creates an instance of EvEmbed watcher associated with the current EvLoop object.

Descrierea

final public EvEmbed EvLoop::embed ( string $other [, string $callback [, string $data [, string $priority ]]] )

Creates an instance of EvEmbed watcher associated with the current EvLoop object.

Parametri

All parameters have the same meaning as for EvEmbed::__construct() .

Valorile întoarse

Returns EvEmbed object on success.

A se vedea ?i

  • EvEmbed::__construct() - Constructs the EvEmbed object
EvLoop::defaultLoop
EvLoop::fork
EvLoop


Creates EvFork watcher object associated with the current event loop instance

EvLoop::embed
EvLoop::idle
EvLoop
PHP Manual

EvLoop::fork

(PECL ev >= 0.2.0)

EvLoop::fork — Creates EvFork watcher object associated with the current event loop instance

Descrierea

final public EvFork EvLoop::fork ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvFork watcher object associated with the current event loop instance

Parametri

All parameters have the same meaning as for EvFork::__construct()

Valorile întoarse

Returns EvFork object on success.

A se vedea ?i

  • EvFork::__construct() - Constructs the EvFork watcher object
EvLoop::embed
EvLoop::idle
EvLoop


Creates EvIdle watcher object associated with the current event loop instance

EvLoop::fork
EvLoop::invokePending
EvLoop
PHP Manual

EvLoop::idle

(PECL ev >= 0.2.0)

EvLoop::idle — Creates EvIdle watcher object associated with the current event loop instance

Descrierea

final public EvIdle EvLoop::idle ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvIdle watcher object associated with the current event loop instance

Parametri

All the parameters have the same meaning as for EvIdle::__construct()

Valorile întoarse

Returns EvIdle object on success.

A se vedea ?i

  • EvIdle::__construct() - Constructs the EvIdle watcher object
EvLoop::fork
EvLoop::invokePending
EvLoop


Invoke all pending watchers while resetting their pending state

EvLoop::idle
EvLoop::io
EvLoop
PHP Manual

EvLoop::invokePending

(PECL ev >= 0.2.0)

EvLoop::invokePending — Invoke all pending watchers while resetting their pending state

Descrierea

public void EvLoop::invokePending ( void )

Invoke all pending watchers while resetting their pending state.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

EvLoop::idle
EvLoop::io
EvLoop


Create EvIo watcher object associated with the current event loop instance

EvLoop::invokePending
EvLoop::loopFork
EvLoop
PHP Manual

EvLoop::io

(PECL ev >= 0.2.0)

EvLoop::io — Create EvIo watcher object associated with the current event loop instance

Descrierea

final public EvIo EvLoop::io ( mixed $fd , int $events , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Create EvIo watcher object associated with the current event loop instance.

Parametri

All parameters have the same meaning as for EvIo::__construct()

Valorile întoarse

Returns EvIo object on success.

A se vedea ?i

  • EvIo::__construct() - Constructs EvIo watcher object
EvLoop::invokePending
EvLoop::loopFork
EvLoop


Must be called after a fork

EvLoop::io
EvLoop::now
EvLoop
PHP Manual

EvLoop::loopFork

(PECL ev >= 0.2.0)

EvLoop::loopFork — Must be called after a fork

Descrierea

public void EvLoop::loopFork ( void )

Must be called after a fork in the child, before entering or continuing the event loop. An alternative is to use Ev::FLAG_FORKCHECK which calls this function automatically, at some performance loss (refer to the » libev documentation ).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

EvLoop::io
EvLoop::now
EvLoop


Returns the current "event loop time"

EvLoop::loopFork
EvLoop::nowUpdate
EvLoop
PHP Manual

EvLoop::now

(PECL ev >= 0.2.0)

EvLoop::now — Returns the current "event loop time"

Descrierea

public double EvLoop::now ( void )

Returns the current "event loop time", which is the time the event loop received events and started processing them. This timestamp does not change as long as callbacks are being processed, and this is also the base time used for relative timers. You can treat it as the timestamp of the event occurring(or more correctly, libev finding out about it).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns time of the event loop in (fractional) seconds.

A se vedea ?i

  • Ev::now() - Returns the time when the last iteration of the default event loop has started.
EvLoop::loopFork
EvLoop::nowUpdate
EvLoop


Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress.

EvLoop::now
EvLoop::periodic
EvLoop
PHP Manual

EvLoop::nowUpdate

(PECL ev >= 0.2.0)

EvLoop::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress.

Descrierea

public void EvLoop::nowUpdate ( void )

Establishes the current time by querying the kernel, updating the time returned by EvLoop::now() in the progress. This is a costly operation and is usually done automatically within EvLoop::run() .

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EvLoop::now() - Returns the current "event loop time"
  • Ev::nowUpdate() - Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.
EvLoop::now
EvLoop::periodic
EvLoop


Creates EvPeriodic watcher object associated with the current event loop instance

EvLoop::nowUpdate
EvLoop::prepare
EvLoop
PHP Manual

EvLoop::periodic

(PECL ev >= 0.2.0)

EvLoop::periodic — Creates EvPeriodic watcher object associated with the current event loop instance

Descrierea

final public EvPeriodic EvLoop::periodic ( double $offset , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvPeriodic watcher object associated with the current event loop instance

Parametri

All parameters have the same maening as for EvPeriodic::__construct()

Valorile întoarse

Returns EvPeriodic object on success.

A se vedea ?i

  • EvPeriodic::__construct() - Constructs EvPeriodic watcher object
EvLoop::nowUpdate
EvLoop::prepare
EvLoop


Creates EvPrepare watcher object associated with the current event loop instance

EvLoop::periodic
EvLoop::resume
EvLoop
PHP Manual

EvLoop::prepare

(PECL ev >= 0.2.0)

EvLoop::prepare — Creates EvPrepare watcher object associated with the current event loop instance

Descrierea

final public EvPrepare EvLoop::prepare ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvPrepare watcher object associated with the current event loop instance

Parametri

All parameters have the same maening as for EvPrepare()

Valorile întoarse

Returns EvPrepare object on success

A se vedea ?i

  • EvPrepare::__construct() - Constructs EvPrepare watcher object
EvLoop::periodic
EvLoop::resume
EvLoop


Resume previously suspended default event loop

EvLoop::prepare
EvLoop::run
EvLoop
PHP Manual

EvLoop::resume

(PECL ev >= 0.2.0)

EvLoop::resume — Resume previously suspended default event loop

Descrierea

public void EvLoop::resume ( void )

EvLoop::suspend() and EvLoop::resume() methods suspend and resume a loop correspondingly.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EvLoop::suspend() - Suspend the loop
  • Ev::resume() - Resume previously suspended default event loop
EvLoop::prepare
EvLoop::run
EvLoop


Begin checking for events and calling callbacks for the loop

EvLoop::resume
EvLoop::signal
EvLoop
PHP Manual

EvLoop::run

(PECL ev >= 0.2.0)

EvLoop::run — Begin checking for events and calling callbacks for the loop

Descrierea

public void EvLoop::run ([ int $flags = 0 ] )

Begin checking for events and calling callbacks for the current event loop. Returns when a callback calls Ev::stop() method, or the flags are nonzero(in which case the return value is true) or when there are no active watchers which reference the loop( EvWatcher::keepalive() is TRUE), in which case the return value will be FALSE. The return value can generally be interpreted as if TRUE, there is more work left to do .

Parametri

flags

Optional parameter flags can be one of the following:

List for possible values of flags
flags | Description
0 | The default behavior described above
Ev::RUN_ONCE | Block at most one(wait, but don't loop)
Ev::RUN_NOWAIT | Don't block at all(fetch/handle events, but don't wait)

See the run flag constants .

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EvLoop::stop() - Stops the event loop
  • Ev::run() - Begin checking for events and calling callbacks for the default loop
EvLoop::resume
EvLoop::signal
EvLoop


Creates EvSignal watcher object associated with the current event loop instance

EvLoop::run
EvLoop::stat
EvLoop
PHP Manual

EvLoop::signal

(PECL ev >= 0.2.0)

EvLoop::signal — Creates EvSignal watcher object associated with the current event loop instance

Descrierea

final public EvSignal EvLoop::signal ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvSignal watcher object associated with the current event loop instance

Parametri

All parameters have the same meaning as for EvSignal::__construct()

Valorile întoarse

Returns EvSignal object on success

A se vedea ?i

  • EvSignal::__construct() - Constructs EvPeriodic watcher object
EvLoop::run
EvLoop::stat
EvLoop


Creates EvStat watcher object associated with the current event loop instance

EvLoop::signal
EvLoop::stop
EvLoop
PHP Manual

EvLoop::stat

(PECL ev >= 0.2.0)

EvLoop::stat — Creates EvStat watcher object associated with the current event loop instance

Descrierea

final public EvStat EvLoop::stat ( string $path , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvStat watcher object associated with the current event loop instance

Parametri

All parameters have the same meaning as for EvSignal::__construct()

Valorile întoarse

Returns EvStat object on success

A se vedea ?i

  • EvSignal::__construct() - Constructs EvPeriodic watcher object
EvLoop::signal
EvLoop::stop
EvLoop


Stops the event loop

EvLoop::stat
EvLoop::suspend
EvLoop
PHP Manual

EvLoop::stop

(PECL ev >= 0.2.0)

EvLoop::stop — Stops the event loop

Descrierea

public void EvLoop::stop ([ int $how ] )

Stops the event loop

Parametri

how

One of Ev::BREAK_* constants .

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EvLoop::run() - Begin checking for events and calling callbacks for the loop
  • Ev::stop() - Stops the default event loop
EvLoop::stat
EvLoop::suspend
EvLoop


Suspend the loop

EvLoop::stop
EvLoop::timer
EvLoop
PHP Manual

EvLoop::suspend

(PECL ev >= 0.2.0)

EvLoop::suspend — Suspend the loop

Descrierea

public void EvLoop::suspend ( void )

EvLoop::suspend() and EvLoop::resume() methods suspend and resume a loop correspondingly.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EvLoop::resume() - Resume previously suspended default event loop
  • Ev::suspend() - Suspend the default event loop
EvLoop::stop
EvLoop::timer
EvLoop


Creates EvTimer watcher object associated with the current event loop instance

EvLoop::suspend
EvLoop::verify
EvLoop
PHP Manual

EvLoop::timer

(PECL ev >= 0.2.0)

EvLoop::timer — Creates EvTimer watcher object associated with the current event loop instance

Descrierea

final public EvTimer EvLoop::timer ( double $after , double $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvTimer watcher object associated with the current event loop instance

Parametri

All parameters have the same meaning as for EvTimer::__construct()

Valorile întoarse

Returns EvTimer object on success

A se vedea ?i

  • EvTimer::__construct() - Constructs an EvTimer watcher object
EvLoop::suspend
EvLoop::verify
EvLoop


Performs internal consistency checks(for debugging)

EvLoop::timer
EvPeriodic
EvLoop
PHP Manual

EvLoop::verify

(PECL ev >= 0.2.0)

EvLoop::verify — Performs internal consistency checks(for debugging)

Descrierea

public void EvLoop::verify ( void )

Performs internal consistency checks(for debugging libev ) and abort the program if any data structures were found to be corrupted.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Ev::verify() - Performs internal consistency checks(for debugging)
EvLoop::timer
EvPeriodic
EvLoop


The EvPeriodic class

(PECL ev >= 0.2.0)

Introducere

Periodic watchers are also timers of a kind, but they are very versatile.

Unlike EvTimer , EvPeriodic watchers are not based on real time(or relative time, the physical time that passes) but on wall clock time(absolute time, calendar or clock). The difference is that wall clock time can run faster or slower than real time, and time jumps are not uncommon(e.g. when adjusting it).

EvPeriodic watcher can be configured to trigger after some specific point in time. For example, if an EvPeriodic watcher is configured to trigger "in 10 seconds" (e.g. EvLoop::now() + 10.0 , i.e. an absolute time, not a delay), and the system clock is reset to January of the previous year , then it will take a year or more to trigger the event (unlike an EvTimer , which would still trigger roughly 10 seconds after starting it as it uses a relative timeout).

As with timers, the callback is guaranteed to be invoked only when the point in time where it is supposed to trigger has passed. If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones with later time-out values (but this is no longer true when a callback calls EvLoop::run() recursively).

Sinopsisul clasei

EvPeriodic extends EvWatcher {
/* Proprieta?i */
public $offset ;
public $interval ;
/* Proprieta?i mo?tenite */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Metode */
public void again ( void )
public double at ( void )
public __construct ( double $offset , string $interval , callable $reschedule_cb , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static EvPeriodic createStopped ( double $offset , double $interval , callable $reschedule_cb , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void set ( double $offset , double $interval )
/* Metode mo?tenite */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Proprieta?i

offset

When repeating, this contains the offset value, otherwise this is the absolute point in time(the offset value passed to EvPeriodic::set() , although libev might modify this value for better numerical stability).

interval

The current interval value. Can be modified any time, but changes only take effect when the periodic timer fires or EvPeriodic::again() is being called.

Cuprins

  • EvPeriodic::again — Simply stops and restarts the periodic watcher again.
  • EvPeriodic::at — Returns the absolute time that this watcher is supposed to trigger next
  • EvPeriodic::__construct — Constructs EvPeriodic watcher object
  • EvPeriodic::createStopped — Create a stopped EvPeriodic watcher
  • EvPeriodic::set — Configures the watcher
EvLoop::verify
EvPeriodic::again
Ev


Simply stops and restarts the periodic watcher again.

EvPeriodic
EvPeriodic::at
EvPeriodic
PHP Manual

EvPeriodic::again

(PECL ev >= 0.2.0)

EvPeriodic::again — Simply stops and restarts the periodic watcher again.

Descrierea

public void EvPeriodic::again ( void )

Simply stops and restarts the periodic watcher again. This is only useful when attributes are changed.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EvTimer::again() - Restarts the timer watcher
EvPeriodic
EvPeriodic::at
EvPeriodic


Returns the absolute time that this watcher is supposed to trigger next

EvPeriodic::again
EvPeriodic::__construct
EvPeriodic
PHP Manual

EvPeriodic::at

(PECL ev >= 0.2.0)

EvPeriodic::at — Returns the absolute time that this watcher is supposed to trigger next

Descrierea

public double EvPeriodic::at ( void )

When the watcher is active, returns the absolute time that this watcher is supposed to trigger next. This is not the same as the offset argument to EvPeriodic::set() or EvPeriodic::__construct() , but indeed works even in interval mode.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the absolute time this watcher is supposed to trigger next in seconds.

EvPeriodic::again
EvPeriodic::__construct
EvPeriodic


Constructs EvPeriodic watcher object

EvPeriodic::at
EvPeriodic::createStopped
EvPeriodic
PHP Manual

EvPeriodic::__construct

(PECL ev >= 0.2.0)

EvPeriodic::__construct — Constructs EvPeriodic watcher object

Descrierea

public EvPeriodic::__construct ( double $offset , string $interval , callable $reschedule_cb , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs EvPeriodic watcher object and starts it automatically. EvPeriodic::createStopped() method creates stopped periodic watcher.

Parametri

offset

See Periodic watcher operation modes

interval

See Periodic watcher operation modes

reschedule_cb

Reschedule callback. You can pass NULL. See Periodic watcher operation modes

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvPeriodic object on success.

Exemple

Example #1 Periodic timer. Use reschedule callback

<?php
// Tick each 10.5 seconds

function reschedule_cb ($watcher, $now) {
 return $now + (10.5. - fmod($now, 10.5));
}

$w = new EvPeriodic(0., 0., "reschedule_cb", function ($w, $revents) {
 echo time(), PHP_EOL;
});
Ev::run();
?>

Example #2 Periodic timer. Tick every 10.5 seconds starting at now

<?php
// Tick every 10.5 seconds starting at now
$w = new EvPeriodic(fmod(Ev::now(), 10.5), 10.5, NULL, function ($w, $revents) {
 echo time(), PHP_EOL;
});
Ev::run();
?>

Example #3 Hourly watcher

<?php
$hourly = EvPeriodic(0, 3600, NULL, function () {
 echo "once per hour\n";
});
?>

A se vedea ?i

  • Periodic watcher operation modes
  • EvTimer
  • EvPeriodic::createStopped() - Create a stopped EvPeriodic watcher
EvPeriodic::at
EvPeriodic::createStopped
EvPeriodic


Create a stopped EvPeriodic watcher

EvPeriodic::__construct
EvPeriodic::set
EvPeriodic
PHP Manual

EvPeriodic::createStopped

(PECL ev >= 0.2.0)

EvPeriodic::createStopped — Create a stopped EvPeriodic watcher

Descrierea

final public static EvPeriodic EvPeriodic::createStopped ( double $offset , double $interval , callable $reschedule_cb , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Create EvPeriodic object. Unlike EvPeriodic::__construct() this method doesn't start the watcher automatically.

Parametri

offset

See Periodic watcher operation modes

interval

See Periodic watcher operation modes

reschedule_cb

Reschedule callback. You can pass NULL. See Periodic watcher operation modes

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvPeriodic watcher object on success.

A se vedea ?i

  • EvPeriodic::__construct() - Constructs EvPeriodic watcher object
  • EvTimer::createStopped() - Creates EvTimer stopped watcher object
EvPeriodic::__construct
EvPeriodic::set
EvPeriodic


Configures the watcher

EvPeriodic::createStopped
EvPrepare
EvPeriodic
PHP Manual

EvPeriodic::set

(PECL ev >= 0.2.0)

EvPeriodic::set — Configures the watcher

Descrierea

public void EvPeriodic::set ( double $offset , double $interval )

(Re-)Configures EvPeriodic watcher

Parametri

offset

The same meaning as for EvPeriodic::__construct() . See Periodic watcher operation modes

interval

The same meaning as for EvPeriodic::__construct() . See Periodic watcher operation modes

Valorile întoarse

Nu este întoarsa nici o valoare.

EvPeriodic::createStopped
EvPrepare
EvPeriodic


The EvPrepare class

(PECL ev >= 0.2.0)

Introducere

EvPrepare and EvCheck watchers are usually used in pairs. EvPrepare watchers get invoked before the process blocks, EvCheck afterwards.

It is not allowed to call EvLoop::run() or similar methods or functions that enter the current event loop from either EvPrepare or EvCheck watchers. Other loops than the current one are fine, however. The rationale behind this is that one don't need to check for recursion in those watchers, i.e. the sequence will always be: EvPrepare -> blocking -> EvCheck , so having a watcher of each kind they will always be called in pairs bracketing the blocking call.

The main purpose is to integrate other event mechanisms into libev and their use is somewhat advanced. They could be used, for example, to track variable changes, implement custom watchers, integrate net-snmp or a coroutine library and lots more. They are also occasionally useful to cache some data and want to flush it before blocking.

It is recommended to give EvCheck watchers highest( Ev::MAXPRI ) priority, to ensure that they are being run before any other watchers after the poll (this doesn’t matter for EvPrepare watchers).

Also, EvCheck watchers should not activate/feed events. While libev fully supports this, they might get executed before other EvCheck watchers did their job.

Sinopsisul clasei

EvPrepare extends EvWatcher {
/* Proprieta?i mo?tenite */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Metode */
public __construct ( string $callback [, string $data [, string $priority ]] )
final public static EvPrepare createStopped ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
/* Metode mo?tenite */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Cuprins

  • EvPrepare::__construct — Constructs EvPrepare watcher object
  • EvPrepare::createStopped — Creates a stopped instance of EvPrepare watcher
EvPeriodic::set
EvPrepare::__construct
Ev


Constructs EvPrepare watcher object

EvPrepare
EvPrepare::createStopped
EvPrepare
PHP Manual

EvPrepare::__construct

(PECL ev >= 0.2.0)

EvPrepare::__construct — Constructs EvPrepare watcher object

Descrierea

public EvPrepare::__construct ( string $callback [, string $data [, string $priority ]] )

Constructs EvPrepare watcher object. And starts the watcher automatically. If need a stopped watcher consider using EvPrepare::createStopped()

Parametri

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvPrepare object on success.

A se vedea ?i

  • EvCheck
EvPrepare
EvPrepare::createStopped
EvPrepare


Creates a stopped instance of EvPrepare watcher

EvPrepare::__construct
EvSignal
EvPrepare
PHP Manual

EvPrepare::createStopped

(PECL ev >= 0.2.0)

EvPrepare::createStopped — Creates a stopped instance of EvPrepare watcher

Descrierea

final public static EvPrepare EvPrepare::createStopped ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates a stopped instance of EvPrepare watcher. Unlike EvPrepare::__construct() , this method doesn' start the watcher automatically.

Parametri

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Return EvPrepare object on success.

A se vedea ?i

  • EvPrepare::__construct() - Constructs EvPrepare watcher object
  • EvWatcher::start() - Starts the watcher
EvPrepare::__construct
EvSignal
EvPrepare


The EvSignal class

(PECL ev >= 0.2.0)

Introducere

EvSignal watchers will trigger an event when the process receives a specific signal one or more times. Even though signals are very asynchronous, libev will try its best to deliver signals synchronously, i.e. as part of the normal event processing, like any other event.

There is no limit for the number of watchers for the same signal, but only within the same loop, i.e. one can watch for SIGINT in the default loop and for SIGIO in another loop, but it is not allowed to watch for SIGINT in both the default loop and another loop at the same time. At the moment, SIGCHLD is permanently tied to the default loop.

If possible and supported, libev will install its handlers with SA_RESTART (or equivalent) behaviour enabled, so system calls should not be unduly interrupted. In case of a problem with system calls getting interrupted by signals, all the signals can be blocked in an EvCheck watcher and unblocked in a EvPrepare watcher.

Sinopsisul clasei

EvSignal extends EvWatcher {
/* Proprieta?i */
public $signum ;
/* Proprieta?i mo?tenite */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Metode */
public __construct ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static EvSignal createStopped ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void set ( int $signum )
/* Metode mo?tenite */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Proprieta?i

signum

Signal number. See the constants exported by pcntl extension. See also signal(7) man page.

Cuprins

  • EvSignal::__construct — Constructs EvPeriodic watcher object
  • EvSignal::createStopped — Create stopped EvSignal watcher object
  • EvSignal::set — Configures the watcher
EvPrepare::createStopped
EvSignal::__construct
Ev


Constructs EvPeriodic watcher object

EvSignal
EvSignal::createStopped
EvSignal
PHP Manual

EvSignal::__construct

(PECL ev >= 0.2.0)

EvSignal::__construct — Constructs EvPeriodic watcher object

Descrierea

public EvSignal::__construct ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs EvPeriodic watcher object and starts it automatically. For a stopped periodic watcher consider using EvSignal::createStopped() method.

Parametri

signum

Signal number. See constants exported by pcntl extension. See also signal(7) man page.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvSignal object on success.

Exemple

Example #1 Handle SIGTERM signal

<?php
$w = new EvSignal(SIGTERM, function ($watcher) {
    echo "SIGTERM received\n";
    $watcher->stop();
});

Ev::run();
?>

A se vedea ?i

  • EvSignal::createStopped() - Create stopped EvSignal watcher object
EvSignal
EvSignal::createStopped
EvSignal


Create stopped EvSignal watcher object

EvSignal::__construct
EvSignal::set
EvSignal
PHP Manual

EvSignal::createStopped

(PECL ev >= 0.2.0)

EvSignal::createStopped — Create stopped EvSignal watcher object

Descrierea

final public static EvSignal EvSignal::createStopped ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Create stopped EvSignal watcher object. Unlike EvSignal::__construct() , this method does't start the watcher automatically.

Parametri

signum

Signal number. See constants exported by pcntl extension. See also signal(7) man page.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvSignal object on success.

A se vedea ?i

  • EvWatcher::start() - Starts the watcher
  • EvSignal::__construct() - Constructs EvPeriodic watcher object
EvSignal::__construct
EvSignal::set
EvSignal


Configures the watcher

EvSignal::createStopped
EvStat
EvSignal
PHP Manual

EvSignal::set

(PECL ev >= 0.2.0)

EvSignal::set — Configures the watcher

Descrierea

public void EvSignal::set ( int $signum )

Configures the watcher.

Parametri

signum

Signal number. The same as for EvSignal::__construct()

Valorile întoarse

Nu este întoarsa nici o valoare.

EvSignal::createStopped
EvStat
EvSignal


The EvStat class

(PECL ev >= 0.2.0)

Introducere

EvStat monitors a file system path for attribute changes. It calls stat() on that path in regular intervals(or when the OS signals it changed) and sees if it changed compared to the last time, invoking the callback if it did.

The path does not need to exist: changing from "path exists" to "path does not exist" is a status change like any other. The condition "path does not exist" is signified by the 'nlink' item being 0(returned by EvStat::attr() method).

The path must not end in a slash or contain special components such as '.' or .. . The path should be absolute: if it is relative and the working directory changes, then the behaviour is undefined.

Since there is no portable change notification interface available, the portable implementation simply calls stat() regularly on the path to see if it changed somehow. For this case a recommended polling interval can be specified. If one specifies a polling interval of 0.0 (highly recommended) then a suitable, unspecified default value will be used(which could be expected to be around 5 seconds, although this might change dynamically). libev will also impose a minimum interval which is currently around 0.1 , but that’s usually overkill.

This watcher type is not meant for massive numbers of EvStat watchers, as even with OS-supported change notifications, this can be resource-intensive.

Sinopsisul clasei

EvStat extends EvWatcher {
/* Proprieta?i */
public $path ;
public $interval ;
/* Proprieta?i mo?tenite */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Metode */
public array attr ( void )
public __construct ( string $path , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static void createStopped ( string $path , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void prev ( void )
public void set ( string $path , double $interval )
public bool stat ( void )
/* Metode mo?tenite */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Proprieta?i

interval

Readonly . Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

path

Readonly . The path to wait for status changes on.

Cuprins

  • EvStat::attr — Returns the values most recently detected by Ev
  • EvStat::__construct — Constructs EvStat watcher object
  • EvStat::createStopped — Create a stopped EvStat watcher object
  • EvStat::prev — Returns the previous set of values returned by EvStat::attr
  • EvStat::set — Configures the watcher
  • EvStat::stat — Initiates the stat call
EvSignal::set
EvStat::attr
Ev


Returns the values most recently detected by Ev

EvStat
EvStat::__construct
EvStat
PHP Manual

EvStat::attr

(PECL ev >= 0.2.0)

EvStat::attr — Returns the values most recently detected by Ev

Descrierea

public array EvStat::attr ( void )

Returns array of the values most recently detected by Ev

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns array with the values most recently detect by Ev(without actual stat 'ing):

List for item keys of the array returned by EvStat::attr()
Key | Description
'dev' | ID of device containing file
'ino' | inode number
'mode' | protection
'nlink' | number of hard links
'uid' | user ID of owner
'size' | total size, in bytes
'gid' | group ID of owner
'rdev' | device ID (if special file)
'blksize' | blocksize for file system I/O
'blocks' | number of 512B blocks allocated
'atime' | time of last access
'ctime' | time of last status change
'mtime' | time of last modification

See stat(2) man page for details.

Exemple

Example #1 Monitor changes of /var/log/messages

<?php
// Use 10 second update interval.
$w = new EvStat("/var/log/messages", 8, function ($w) {
    echo "/var/log/messages changed\n";

    $attr = $w->attr();

    if ($attr['nlink']) {
        printf("Current size: %ld\n", $attr['size']);
        printf("Current atime: %ld\n", $attr['atime']);
        printf("Current mtime: %ld\n", $attr['mtime']);
    } else {
        fprintf(STDERR, "`messages` file is not there!");
        $w->stop();
    }
});

Ev::run();
?>

A se vedea ?i

  • EvStat::prev() - Returns the previous set of values returned by EvStat::attr
  • EvStat::stat() - Initiates the stat call
EvStat
EvStat::__construct
EvStat


Constructs EvStat watcher object

EvStat::attr
EvStat::createStopped
EvStat
PHP Manual

EvStat::__construct

(PECL ev >= 0.2.0)

EvStat::__construct — Constructs EvStat watcher object

Descrierea

public EvStat::__construct ( string $path , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs EvStat watcher object and starts the watcher automatically.

Parametri

path

The path to wait for status changes on.

interval

Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvStat watcher object on succes.

Exemple

Example #1 Monitor changes of /var/log/messages

<?php
// Use 10 second update interval.
$w = new EvStat("/var/log/messages", 8, function ($w) {
 echo "/var/log/messages changed\n";

 $attr = $w->attr();

 if ($attr['nlink']) {
  printf("Current size: %ld\n", $attr['size']);
  printf("Current atime: %ld\n", $attr['atime']);
  printf("Current mtime: %ld\n", $attr['mtime']);
 } else {
  fprintf(STDERR, "`messages` file is not there!");
  $w->stop();
 }
});

Ev::run();
?>
EvStat::attr
EvStat::createStopped
EvStat


Create a stopped EvStat watcher object

EvStat::__construct
EvStat::prev
EvStat
PHP Manual

EvStat::createStopped

(PECL ev >= 0.2.0)

EvStat::createStopped — Create a stopped EvStat watcher object

Descrierea

final public static void EvStat::createStopped ( string $path , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvStat watcher object, but doesn't start it automatically(unlike EvStat::__construct() ).

Parametri

path

The path to wait for status changes on.

interval

Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns a stopped EvStat watcher object on success.

A se vedea ?i

  • EvStat::__construct() - Constructs EvStat watcher object
  • EvWatcher::start() - Starts the watcher
EvStat::__construct
EvStat::prev
EvStat


Returns the previous set of values returned by EvStat::attr

EvStat::createStopped
EvStat::set
EvStat
PHP Manual

EvStat::prev

(PECL ev >= 0.2.0)

EvStat::prev — Returns the previous set of values returned by EvStat::attr

Descrierea

public void EvStat::prev ( void )

Just like EvStat::attr() , but returns the previous set of values.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array with the same structure as the array returned by EvStat::attr() . The array contains previously detected values.

A se vedea ?i

  • EvStat::attr() - Returns the values most recently detected by Ev
  • EvStat::stat() - Initiates the stat call
EvStat::createStopped
EvStat::set
EvStat


Configures the watcher

EvStat::prev
EvStat::stat
EvStat
PHP Manual

EvStat::set

(PECL ev >= 0.2.0)

EvStat::set — Configures the watcher

Descrierea

public void EvStat::set ( string $path , double $interval )

Configures the watcher.

Parametri

path

The path to wait for status changes on.

interval

Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

Valorile întoarse

Nu este întoarsa nici o valoare.

EvStat::prev
EvStat::stat
EvStat


Initiates the stat call

EvStat::set
EvTimer
EvStat
PHP Manual

EvStat::stat

(PECL ev >= 0.2.0)

EvStat::stat — Initiates the stat call

Descrierea

public bool EvStat::stat ( void )

Initiates the stat call(updates internal cache). It stats(using lstat ) the path specified in the watcher and sets to the values found.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if path exists. Otherwise FALSE.

A se vedea ?i

  • EvStat::attr() - Returns the values most recently detected by Ev
  • EvStat::prev() - Returns the previous set of values returned by EvStat::attr
EvStat::set
EvTimer
EvStat


The EvTimer class

(PECL ev >= 0.2.0)

Introducere

EvTimer watchers are simple relative timers that generate an event after a given time, and optionally repeating in regular intervals after that.

The timers are based on real time, that is, if one registers an event that times out after an hour and resets the system clock to January last year , it will still time out after(roughly) one hour. "Roughly" because detecting time jumps is hard, and some inaccuracies are unavoidable.

The callback is guaranteed to be invoked only after its timeout has passed (not at, so on systems with very low-resolution clocks this might introduce a small delay). If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones of the same priority with later time-out values (but this is no longer true when a callback calls EvLoop::run() recursively).

The timer itself will do a best-effort at avoiding drift, that is, if a timer is configured to trigger every 10 seconds, then it will normally trigger at exactly 10 second intervals. If, however, the script cannot keep up with the timer because it takes longer than those 10 seconds to do) the timer will not fire more than once per event loop iteration.

Sinopsisul clasei

EvTimer extends EvWatcher {
/* Proprieta?i */
public $repeat ;
public $remaining ;
/* Proprieta?i mo?tenite */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Metode */
public void again ( void )
public __construct ( double $after , double $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static EvTimer createStopped ( double $after , double $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void set ( double $after , double $repeat )
/* Metode mo?tenite */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Proprieta?i

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

remaining

Returns the remaining time until a timer fires. If the timer is active, then this time is relative to the current event loop time, otherwise it's the timeout value currently configured.

That is, after instanciating an EvTimer with an after value of 5.0 and repeat value of 7.0 , remaining returns 5.0 . When the timer is started and one second passes, remaining will return 4.0 . When the timer expires and is restarted, it will return roughly 7.0 (likely slightly less as callback invocation takes some time too), and so on.

Cuprins

  • EvTimer::again — Restarts the timer watcher
  • EvTimer::__construct — Constructs an EvTimer watcher object
  • EvTimer::createStopped — Creates EvTimer stopped watcher object
  • EvTimer::set — Configures the watcher
EvStat::stat
EvTimer::again
Ev


Restarts the timer watcher

EvTimer
EvTimer::__construct
EvTimer
PHP Manual

EvTimer::again

(PECL ev >= 0.2.0)

EvTimer::again — Restarts the timer watcher

Descrierea

public void EvTimer::again ( void )

This will act as if the timer timed out and restart it again if it is repeating. The exact semantics are:

  1. if the timer is pending, its pending status is cleared.

  2. if the timer is started but non-repeating, stop it (as if it timed out).

  3. if the timer is repeating, either start it if necessary (with the repeat value), or reset the running timer to the repeat value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EvWatcher::stop() - Stops the watcher
EvTimer
EvTimer::__construct
EvTimer


Constructs an EvTimer watcher object

EvTimer::again
EvTimer::createStopped
EvTimer
PHP Manual

EvTimer::__construct

(PECL ev >= 0.2.0)

EvTimer::__construct — Constructs an EvTimer watcher object

Descrierea

public EvTimer::__construct ( double $after , double $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs an EvTimer watcher object.

Parametri

after

Configures the timer to trigger after after seconds.

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvTimer object on success.

Exemple

Example #1 Simple timers

<?php
// Create and start timer firing after 2 seconds
$w1 = new EvTimer(2, 0, function () {
    echo "2 seconds elapsed\n";
});

// Create and launch timer firing after 2 seconds repeating each second
// until we manually stop it
$w2 = new EvTimer(2, 1, function ($w) {
    echo "is called every second, is launched after 2 seconds\n";
    echo "iteration = ", Ev::iteration(), PHP_EOL;

    // Stop the watcher after 5 iterations
    Ev::iteration() == 5 and $w->stop();
    // Stop the watcher if further calls cause more than 10 iterations
    Ev::iteration() >= 10 and $w->stop();
});

// Create stopped timer. It will be inactive until we start it ourselves
$w_stopped = EvTimer::createStopped(10, 5, function($w) {
    echo "Callback of a timer created as stopped\n";

    // Stop the watcher after 2 iterations
    Ev::iteration() >= 2 and $w->stop();
});

// Loop until Ev::stop() is called or all of watchers stop
Ev::run();

// Start and look if it works
$w_stopped->start();
echo "Run single iteration\n";
Ev::run(Ev::RUN_ONCE);

echo "Restart the second watcher and try to handle the same events, but don't block\n";
$w2->again();
Ev::run(Ev::RUN_NOWAIT);

$w = new EvTimer(10, 0, function() {});
echo "Running a blocking loop\n";
Ev::run();
echo "END\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

2 seconds elapsed
is called every second, is launched after 2 seconds
iteration = 1
is called every second, is launched after 2 seconds
iteration = 2
is called every second, is launched after 2 seconds
iteration = 3
is called every second, is launched after 2 seconds
iteration = 4
is called every second, is launched after 2 seconds
iteration = 5
Run single iteration
Callback of a timer created as stopped
Restart the second watcher and try to handle the same events, but don't block
Running a blocking loop
is called every second, is launched after 2 seconds
iteration = 8
is called every second, is launched after 2 seconds
iteration = 9
is called every second, is launched after 2 seconds
iteration = 10
END

A se vedea ?i

  • EvTimer::createStopped() - Creates EvTimer stopped watcher object
  • EvPeriodic
  • » ev_timer - relative and optionally repeating timeouts
  • » Be smart about timeouts
EvTimer::again
EvTimer::createStopped
EvTimer


Creates EvTimer stopped watcher object

EvTimer::__construct
EvTimer::set
EvTimer
PHP Manual

EvTimer::createStopped

(PECL ev >= 0.2.0)

EvTimer::createStopped — Creates EvTimer stopped watcher object

Descrierea

final public static EvTimer EvTimer::createStopped ( double $after , double $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvTimer stopped watcher object. Unlike EvTimer::__construct() , this method doesn't start the watcher automatically.

Parametri

after

Configures the timer to trigger after after seconds.

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Valorile întoarse

Returns EvTimer watcher object on success.

Exemple

Example #1 Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay

<?php
$timer = EvTimer::createStopped(0., 1.02, function ($w) {
    $w->stop();

    $stat = $w->data;

    // 1 second after the most recent change of the file
    printf("Current size: %ld\n", $stat->attr()['size']);
});

$stat = new EvStat("/var/log/messages", 0., function () use ($timer) {
    // Reset timer watcher
    $timer->again();
});

$timer->data = $stat;

Ev::run();
?>

A se vedea ?i

  • EvTimer::__construct() - Constructs an EvTimer watcher object
  • EvPeriodic
EvTimer::__construct
EvTimer::set
EvTimer


Configures the watcher

EvTimer::createStopped
EvWatcher
EvTimer
PHP Manual

EvTimer::set

(PECL ev >= 0.2.0)

EvTimer::set — Configures the watcher

Descrierea

public void EvTimer::set ( double $after , double $repeat )

Configures the watcher

Parametri

after

Configures the timer to trigger after after seconds.

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

Valorile întoarse

Nu este întoarsa nici o valoare.

EvTimer::createStopped
EvWatcher
EvTimer


The EvWatcher class

(PECL ev >= 0.2.0)

Introducere

EvWatcher is a base class for all watchers( EvCheck , EvChild etc.). Since EvWatcher 's constructor is abstract , one can't(and don't need to) create EvWatcher objects directly.

Sinopsisul clasei

abstract EvWatcher {
/* Proprieta?i */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Metode */
public int clear ( void )
abstract public __construct ( void )
public void feed ( int $revents )
public EvLoop getLoop ( void )
public void invoke ( int $revents )
public bool keepalive ([ bool $value ] )
public void setCallback ( callable $callback )
public void start ( void )
public void stop ( void )
}

Proprieta?i

is_active

Readonly . TRUE if the watcher is active. FALSE otherwise.

data

User custom data associated with the watcher

is_pending

Readonly .TRUE if the watcher is pending, i.e. it has outstanding events, but its callback has not yet been invoked. FALSE otherwise. As long, as a watcher is pending(but not active), one must not change its priority.

priority

Integer between Ev::MINPRI and Ev::MAXPRI . Pending watchers with higher priority will be invoked before watchers with lower priority, but priority will not keep watchers from being executed(except for EvIdle watchers). EvIdle watchers provide functionality to suppress invocation when higher priority events are pending.

Cuprins

  • EvWatcher::clear — Clear watcher pending status
  • EvWatcher::__construct — Abstract constructor of a watcher object
  • EvWatcher::feed — Feeds the given revents set into the event loop
  • EvWatcher::getLoop — Returns the loop responsible for the watcher
  • EvWatcher::invoke — Invokes the watcher callback with the given received events bit mask
  • EvWatcher::keepalive — Configures whether to keep the loop from returning
  • EvWatcher::setCallback — Sets new callback for the watcher
  • EvWatcher::start — Starts the watcher
  • EvWatcher::stop — Stops the watcher
EvTimer::set
EvWatcher::clear
Ev


Clear watcher pending status

EvWatcher
EvWatcher::__construct
EvWatcher
PHP Manual

EvWatcher::clear

(PECL ev >= 0.2.0)

EvWatcher::clear — Clear watcher pending status

Descrierea

public int EvWatcher::clear ( void )

If the watcher is pending, this method clears its pending status and returns its revents bitset(as if its callback was invoked). If the watcher isn't pending it does nothing and returns 0 .

Sometimes it can be useful to "poll" a watcher instead of waiting for its callback to be invoked, which can be accomplished with this function.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

In case if the watcher is pending, returns revents bitset as if the watcher callback had been invoked. Otherwise returns 0 .

EvWatcher
EvWatcher::__construct
EvWatcher


Abstract constructor of a watcher object

EvWatcher::clear
EvWatcher::feed
EvWatcher
PHP Manual

EvWatcher::__construct

(PECL ev >= 0.2.0)

EvWatcher::__construct — Abstract constructor of a watcher object

Descrierea

abstract public EvWatcher::__construct ( void )

EvWatcher::__construct() is an abstract constructor of a watcher object implemented in the derived classes.

EvWatcher::clear
EvWatcher::feed
EvWatcher


Feeds the given revents set into the event loop

EvWatcher::__construct
EvWatcher::getLoop
EvWatcher
PHP Manual

EvWatcher::feed

(PECL ev >= 0.2.0)

EvWatcher::feed — Feeds the given revents set into the event loop

Descrierea

public void EvWatcher::feed ( int $revents )

Feeds the given revents set into the event loop, as if the specified event had happened for the watcher.

Parametri

revents

Bit mask of watcher received events .

Valorile întoarse

Nu este întoarsa nici o valoare.

EvWatcher::__construct
EvWatcher::getLoop
EvWatcher


Returns the loop responsible for the watcher

EvWatcher::feed
EvWatcher::invoke
EvWatcher
PHP Manual

EvWatcher::getLoop

(PECL ev >= 0.2.0)

EvWatcher::getLoop — Returns the loop responsible for the watcher

Descrierea

public EvLoop EvWatcher::getLoop ( void )

Returns the loop responsible for the watcher

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns EvLoop event loop object responsible for the watcher.

EvWatcher::feed
EvWatcher::invoke
EvWatcher


Invokes the watcher callback with the given received events bit mask

EvWatcher::getLoop
EvWatcher::keepalive
EvWatcher
PHP Manual

EvWatcher::invoke

(PECL ev >= 0.2.0)

EvWatcher::invoke — Invokes the watcher callback with the given received events bit mask

Descrierea

public void EvWatcher::invoke ( int $revents )

Invokes the watcher callback with the given received events bit mask.

Parametri

revents

Bit mask of watcher received events .

Valorile întoarse

Nu este întoarsa nici o valoare.

EvWatcher::getLoop
EvWatcher::keepalive
EvWatcher


Configures whether to keep the loop from returning

EvWatcher::invoke
EvWatcher::setCallback
EvWatcher
PHP Manual

EvWatcher::keepalive

(PECL ev >= 0.2.0)

EvWatcher::keepalive — Configures whether to keep the loop from returning

Descrierea

public bool EvWatcher::keepalive ([ bool $value ] )

Configures whether to keep the loop from returning. With keepalive value set to FALSE the watcher won't keep Ev::run() / EvLoop::run() from returning even though the watcher is active.

Watchers have keepalive value TRUE by default.

Clearing keepalive status is useful when returning from Ev::run() / EvLoop::run() just because of the watcher is undesirable. It could be a long running UDP socket watcher or so.

Parametri

value

With keepalive value set to FALSE the watcher won't keep Ev::run() / EvLoop::run() from returning even though the watcher is active.

Valorile întoarse

Returns the previous state.

Exemple

Example #1 Register an I/O watcher for some UDP socket but do not keep the event loop from running just because of that watcher.

<?php
$udp_socket = ...
$udp_watcher = new EvIo($udp_socket, Ev::READ, function () { /* ... */ });
$udp_watcher->keepalive(FALSE);
?>
EvWatcher::invoke
EvWatcher::setCallback
EvWatcher


Sets new callback for the watcher

EvWatcher::keepalive
EvWatcher::start
EvWatcher
PHP Manual

EvWatcher::setCallback

(PECL ev >= 0.2.0)

EvWatcher::setCallback — Sets new callback for the watcher

Descrierea

public void EvWatcher::setCallback ( callable $callback )

Sets new callback for the watcher

Parametri

callback

See Watcher callbacks .

Valorile întoarse

Nu este întoarsa nici o valoare.

EvWatcher::keepalive
EvWatcher::start
EvWatcher


Starts the watcher

EvWatcher::setCallback
EvWatcher::stop
EvWatcher
PHP Manual

EvWatcher::start

(PECL ev >= 0.2.0)

EvWatcher::start — Starts the watcher

Descrierea

public void EvWatcher::start ( void )

Marks the watcher as active. Note that only active watchers will receive events.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EvWatcher::stop() - Stops the watcher
EvWatcher::setCallback
EvWatcher::stop
EvWatcher


Stops the watcher

EvWatcher::start
Expect
EvWatcher
PHP Manual

EvWatcher::stop

(PECL ev >= 0.2.0)

EvWatcher::stop — Stops the watcher

Descrierea

public void EvWatcher::stop ( void )

Marks the watcher as inactive. Note that only active watchers will receive events.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EvWatcher::start() - Starts the watcher
EvWatcher::start
Expect
EvWatcher


Expect

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Expect Usage Examples
  • Func?ii Expect
    • 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
EvWatcher::stop
Introducere
Extensii de control al proceselor


Introducere

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
Instalarea / configurarea
Expect


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Expect


Necesita?i

This module uses the functions of the » expect library. You need libexpect version >= 5.43.0.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP. Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/expect.

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. O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

In order to configure expect extension, there are configuration options in the configuration file php.ini.

Expect Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Changelog
expect.timeout | "10" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.logfile | "" | PHP_INI_ALL |
expect.match_max | "" | PHP_INI_ALL |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Nota:

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.

Nota:

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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

expect_popen() returns an open PTY stream used by expect_expectl().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
Exemple
Expect


Exemple

Cuprins

  • Expect Usage Examples
Constante predefinite
Expect Usage Examples
Expect


Expect Usage Examples

Example #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.

Example #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);
?>
Exemple
Func?ii Expect
Exemple


Func?ii Expect

Cuprins

  • 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

Func?ii Expect
expect_popen
Func?ii Expect
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

Descrierea

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).

Parametri

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

Valorile întoarse

Returns value associated with the pattern that was matched.

On failure this function returns: EXP_EOF, EXP_TIMEOUT or EXP_FULLBUFFER

Istoricul schimbarilor

Versiune | Descriere
0.2.1 | Prior to version 0.2.1, in match parameter a match string was returned, not an array of match substrings.

Exemple

Example #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);
?>

A se vedea ?i

  • expect_popen() - Execute command via Bourne shell, and open the PTY stream to the process

Func?ii Expect
expect_popen
Func?ii Expect


Execute command via Bourne shell, and open the PTY stream to the process

expect_expectl
Libevent
Func?ii Expect
PHP Manual

expect_popen

(PECL expect >= 0.1.0)

expect_popen — Execute command via Bourne shell, and open the PTY stream to the process

Descrierea

resource expect_popen ( string $command )

Execute command via Bourne shell, and open the PTY stream to the process.

Parametri

command

Command to execute.

Valorile întoarse

Returns an open PTY stream to the processes stdio, stdout, and stderr.

On failure this function returns FALSE.

Exemple

Example #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);
?>

A se vedea ?i

  • popen() - Opens process file pointer

expect_expectl
Libevent
Func?ii Expect


Libevent

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii Libevent
    • 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_reinit — Reinitialize the event base after a fork
    • 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_priority_set — Assign a priority to an event.
    • event_set — Prepare an event
    • event_timer_add — Pseudonim pentru event_add
    • event_timer_del — Pseudonim pentru event_del
    • event_timer_new — Pseudonim pentru event_new
    • event_timer_set — Prepare a timer event
expect_popen
Introducere
Extensii de control al proceselor


Introducere

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://libevent.org/.

Libevent
Instalarea / configurarea
Libevent


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Libevent


Necesita?i

This extension requires » libevent library. Minimal required version is 1.4.0.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/libevent.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

There are several resource types used in the extension. These resources are event, event base and buffered event.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

EV_TIMEOUT (integer)
EV_READ (integer)
EV_WRITE (integer)
EV_SIGNAL (integer)
EV_PERSIST (integer)
EVLOOP_NONBLOCK (integer)
EVLOOP_ONCE (integer)
Tipurile resurselor
Exemple
Libevent


Exemple

Example #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);

?>

Example #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);

?>

Constante predefinite
Func?ii Libevent
Libevent


Func?ii Libevent

Cuprins

  • 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_reinit — Reinitialize the event base after a fork
  • 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_priority_set — Assign a priority to an event.
  • event_set — Prepare an event
  • event_timer_add — Pseudonim pentru event_add
  • event_timer_del — Pseudonim pentru event_del
  • event_timer_new — Pseudonim pentru event_new
  • event_timer_set — Prepare a timer event
Exemple
event_add
Libevent


Add an event to the set of monitored events

Func?ii Libevent
event_base_free
Func?ii Libevent
PHP Manual

event_add

(PECL libevent >= 0.0.1)

event_add — Add an event to the set of monitored events

Descrierea

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.

Parametri

event

Valid event resource.

timeout

Optional timeout (in microseconds).

Valorile întoarse

event_add() returns TRUE on success or FALSE on error.

Func?ii Libevent
event_base_free
Func?ii Libevent


Destroy event base

event_add
event_base_loop
Func?ii Libevent
PHP Manual

event_base_free

(PECL libevent >= 0.0.1)

event_base_free — Destroy event base

Descrierea

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.

Parametri

event_base

Valid event base resource.

event_add
event_base_loop
Func?ii Libevent


Handle events

event_base_free
event_base_loopbreak
Func?ii Libevent
PHP Manual

event_base_loop

(PECL libevent >= 0.0.1)

event_base_loop — Handle events

Descrierea

int event_base_loop ( resource $event_base [, int $flags = 0 ] )

Starts event loop for the specified event base.

Parametri

event_base

Valid event base resource.

flags

Optional parameter, which can take any combination of EVLOOP_ONCE and EVLOOP_NONBLOCK.

Valorile întoarse

event_base_loop() returns 0 on success, -1 on error and 1 if no events were registered.

event_base_free
event_base_loopbreak
Func?ii Libevent


Abort event loop

event_base_loop
event_base_loopexit
Func?ii Libevent
PHP Manual

event_base_loopbreak

(PECL libevent >= 0.0.1)

event_base_loopbreak — Abort event loop

Descrierea

bool event_base_loopbreak ( resource $event_base )

Abort the active event loop immediately. The behaviour is similar to break statement.

Parametri

event_base

Valid event base resource.

Valorile întoarse

event_base_loopbreak() returns TRUE on success or FALSE on error.

event_base_loop
event_base_loopexit
Func?ii Libevent


Exit loop after a time

event_base_loopbreak
event_base_new
Func?ii Libevent
PHP Manual

event_base_loopexit

(PECL libevent >= 0.0.1)

event_base_loopexit — Exit loop after a time

Descrierea

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.

Parametri

event_base

Valid event base resource.

timeout

Optional timeout parameter (in microseconds).

Valorile întoarse

event_base_loopexit() returns TRUE on success or FALSE on error.

event_base_loopbreak
event_base_new
Func?ii Libevent


Create and initialize new event base

event_base_loopexit
event_base_priority_init
Func?ii Libevent
PHP Manual

event_base_new

(PECL libevent >= 0.0.1)

event_base_new — Create and initialize new event base

Descrierea

resource event_base_new ( void )

Returns new event base, which can be used later in event_base_set(), event_base_loop() and other functions.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

event_base_new() returns valid event base resource on success or FALSE on error.

event_base_loopexit
event_base_priority_init
Func?ii Libevent


Set the number of event priority levels

event_base_new
event_base_reinit
Func?ii Libevent
PHP Manual

event_base_priority_init

(PECL libevent >= 0.0.2)

event_base_priority_init — Set the number of event priority levels

Descrierea

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.

Parametri

event_base

Valid event base resource.

npriorities

The number of event priority levels.

Valorile întoarse

event_base_priority_init() returns TRUE on success or FALSE on error.

event_base_new
event_base_reinit
Func?ii Libevent


Reinitialize the event base after a fork

event_base_priority_init
event_base_set
Func?ii Libevent
PHP Manual

event_base_reinit

(PECL libevent >= 0.1.0)

event_base_reinit — Reinitialize the event base after a fork

Descrierea

bool event_base_reinit ( resource $event_base )

Some event mechanisms do not survive across fork. The event_base needs to be reinitialized with this function.

Parametri

event_base

Valid event base resource that needs to be re-initialized.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

event_base_priority_init
event_base_set
Func?ii Libevent


Associate event base with an event

event_base_reinit
event_buffer_base_set
Func?ii Libevent
PHP Manual

event_base_set

(PECL libevent >= 0.0.1)

event_base_set — Associate event base with an event

Descrierea

bool event_base_set ( resource $event , resource $event_base )

Associates the event_base with the event.

Parametri

event

Valid event resource.

event_base

Valid event base resource.

Valorile întoarse

event_base_set() returns TRUE on success or FALSE on error.

event_base_reinit
event_buffer_base_set
Func?ii Libevent


Associate buffered event with an event base

event_base_set
event_buffer_disable
Func?ii Libevent
PHP Manual

event_buffer_base_set

(PECL libevent >= 0.0.1)

event_buffer_base_set — Associate buffered event with an event base

Descrierea

bool event_buffer_base_set ( resource $bevent , resource $event_base )

Assign the specified bevent to the event_base.

Parametri

bevent

Valid buffered event resource.

event_base

Valid event base resource.

Valorile întoarse

event_buffer_base_set() returns TRUE on success or FALSE on error.

event_base_set
event_buffer_disable
Func?ii Libevent


Disable a buffered event

event_buffer_base_set
event_buffer_enable
Func?ii Libevent
PHP Manual

event_buffer_disable

(PECL libevent >= 0.0.1)

event_buffer_disable — Disable a buffered event

Descrierea

bool event_buffer_disable ( resource $bevent , int $events )

Disables the specified buffered event.

Parametri

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

Valorile întoarse

event_buffer_disable() returns TRUE on success or FALSE on error.

event_buffer_base_set
event_buffer_enable
Func?ii Libevent


Enable a buffered event

event_buffer_disable
event_buffer_fd_set
Func?ii Libevent
PHP Manual

event_buffer_enable

(PECL libevent >= 0.0.1)

event_buffer_enable — Enable a buffered event

Descrierea

bool event_buffer_enable ( resource $bevent , int $events )

Enables the specified buffered event.

Parametri

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

Valorile întoarse

event_buffer_enable() returns TRUE on success or FALSE on error.

event_buffer_disable
event_buffer_fd_set
Func?ii Libevent


Change a buffered event file descriptor

event_buffer_enable
event_buffer_free
Func?ii Libevent
PHP Manual

event_buffer_fd_set

(PECL libevent >= 0.0.1)

event_buffer_fd_set — Change a buffered event file descriptor

Descrierea

void event_buffer_fd_set ( resource $bevent , resource $fd )

Changes the file descriptor on which the buffered event operates.

Parametri

bevent

Valid buffered event resource.

fd

Valid PHP stream, must be castable to file descriptor.

event_buffer_enable
event_buffer_free
Func?ii Libevent


Destroy buffered event

event_buffer_fd_set
event_buffer_new
Func?ii Libevent
PHP Manual

event_buffer_free

(PECL libevent >= 0.0.1)

event_buffer_free — Destroy buffered event

Descrierea

void event_buffer_free ( resource $bevent )

Destroys the specified buffered event and frees all the resources associated.

Parametri

bevent

Valid buffered event resource.

event_buffer_fd_set
event_buffer_new
Func?ii Libevent


Create new buffered event

event_buffer_free
event_buffer_priority_set
Func?ii Libevent
PHP Manual

event_buffer_new

(PECL libevent >= 0.0.1)

event_buffer_new — Create new buffered event

Descrierea

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.

Parametri

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).

Valorile întoarse

event_buffer_new() returns new buffered event resource on success or FALSE on error.

event_buffer_free
event_buffer_priority_set
Func?ii Libevent


Assign a priority to a buffered event

event_buffer_new
event_buffer_read
Func?ii Libevent
PHP Manual

event_buffer_priority_set

(PECL libevent >= 0.0.1)

event_buffer_priority_set — Assign a priority to a buffered event

Descrierea

bool event_buffer_priority_set ( resource $bevent , int $priority )

Assign a priority to the bevent.

Parametri

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()).

Valorile întoarse

event_buffer_priority_set() returns TRUE on success or FALSE on error.

event_buffer_new
event_buffer_read
Func?ii Libevent


Read data from a buffered event

event_buffer_priority_set
event_buffer_set_callback
Func?ii Libevent
PHP Manual

event_buffer_read

(PECL libevent >= 0.0.1)

event_buffer_read — Read data from a buffered event

Descrierea

string event_buffer_read ( resource $bevent , int $data_size )

Reads data from the input buffer of the buffered event.

Parametri

bevent

Valid buffered event resource.

data_size

Data size in bytes.

event_buffer_priority_set
event_buffer_set_callback
Func?ii Libevent


Set or reset callbacks for a buffered event

event_buffer_read
event_buffer_timeout_set
Func?ii Libevent
PHP Manual

event_buffer_set_callback

(PECL libevent >= 0.0.4)

event_buffer_set_callback — Set or reset callbacks for a buffered event

Descrierea

bool event_buffer_set_callback ( resource $event , mixed $readcb , mixed $writecb , mixed $errorcb [, mixed $arg ] )

Sets or changes existing callbacks for the buffered event.

Parametri

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

event_buffer_read
event_buffer_timeout_set
Func?ii Libevent


Set read and write timeouts for a buffered event

event_buffer_set_callback
event_buffer_watermark_set
Func?ii Libevent
PHP Manual

event_buffer_timeout_set

(PECL libevent >= 0.0.1)

event_buffer_timeout_set — Set read and write timeouts for a buffered event

Descrierea

void event_buffer_timeout_set ( resource $bevent , int $read_timeout , int $write_timeout )

Sets the read and write timeouts for the specified buffered event.

Parametri

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
Func?ii Libevent


Set the watermarks for read and write events

event_buffer_timeout_set
event_buffer_write
Func?ii Libevent
PHP Manual

event_buffer_watermark_set

(PECL libevent >= 0.0.1)

event_buffer_watermark_set — Set the watermarks for read and write events

Descrierea

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.

Parametri

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
Func?ii Libevent


Write data to a buffered event

event_buffer_watermark_set
event_del
Func?ii Libevent
PHP Manual

event_buffer_write

(PECL libevent >= 0.0.1)

event_buffer_write — Write data to a buffered event

Descrierea

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.

Parametri

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.

Valorile întoarse

event_buffer_write() returns TRUE on success or FALSE on error.

event_buffer_watermark_set
event_del
Func?ii Libevent


Remove an event from the set of monitored events

event_buffer_write
event_free
Func?ii Libevent
PHP Manual

event_del

(PECL libevent >= 0.0.1)

event_del — Remove an event from the set of monitored events

Descrierea

bool event_del ( resource $event )

Cancels the event.

Parametri

event

Valid event resource.

Valorile întoarse

event_del() returns TRUE on success or FALSE on error.

event_buffer_write
event_free
Func?ii Libevent


Free event resource

event_del
event_new
Func?ii Libevent
PHP Manual

event_free

(PECL libevent >= 0.0.1)

event_free — Free event resource

Descrierea

void event_free ( resource $event )

Frees previously created event resource.

Parametri

event

Valid event resource.

event_del
event_new
Func?ii Libevent


Create new event

event_free
event_priority_set
Func?ii Libevent
PHP Manual

event_new

(PECL libevent >= 0.0.1)

event_new — Create new event

Descrierea

resource event_new ( void )

Creates and returns a new event resource.

Valorile întoarse

event_new() returns a new event resource on success or FALSE on error.

event_free
event_priority_set
Func?ii Libevent


Assign a priority to an event.

event_new
event_set
Func?ii Libevent
PHP Manual

event_priority_set

(PECL libevent >= 0.0.5)

event_priority_set — Assign a priority to an event.

Descrierea

bool event_priority_set ( resource $event , int $priority )

Assign a priority to the event.

Parametri

event

Valid 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()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

event_new
event_set
Func?ii Libevent


Prepare an event

event_priority_set
event_timer_add
Func?ii Libevent
PHP Manual

event_set

(PECL libevent >= 0.0.1)

event_set — Prepare an event

Descrierea

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.

Parametri

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.

Valorile întoarse

event_set() returns TRUE on success or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
0.0.4 | EV_SIGNAL support was added.
event_priority_set
event_timer_add
Func?ii Libevent


Pseudonim pentru event_add

event_set
event_timer_del
Func?ii Libevent
PHP Manual

event_timer_add

(PECL libevent >= 0.0.2)

event_timer_add — Pseudonim pentru event_add()

Descrierea

Aceasta func?ie este pseudonim pentru: event_add().

event_set
event_timer_del
Func?ii Libevent


Pseudonim pentru event_del

event_timer_add
event_timer_new
Func?ii Libevent
PHP Manual

event_timer_del

(PECL libevent >= 0.0.2)

event_timer_del — Pseudonim pentru event_del()

Descrierea

Aceasta func?ie este pseudonim pentru: event_del().

event_timer_add
event_timer_new
Func?ii Libevent


Pseudonim pentru event_new

event_timer_del
event_timer_set
Func?ii Libevent
PHP Manual

event_timer_new

(PECL libevent >= 0.0.2)

event_timer_new — Pseudonim pentru event_new()

Descrierea

Aceasta func?ie este pseudonim pentru: event_new().

event_timer_del
event_timer_set
Func?ii Libevent


Prepare a timer event

event_timer_new
PCNTL
Func?ii Libevent
PHP Manual

event_timer_set

(PECL libevent >= 0.0.2)

event_timer_set — Prepare a timer event

Descrierea

bool event_timer_set ( resource $event , callable $callback [, mixed $arg ] )

Prepares the timer event to be used in event_add(). The event is prepared to call the function specified by the callback when the event timeout elapses.

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. This will always be EV_TIMEOUT for timer events.

arg

Optional parameter, previously passed to event_timer_set() as arg.

Parametri

event

Valid event resource.

callback

Callback function to be called when the matching event occurs.

arg

Optional callback parameter.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

event_timer_new
PCNTL
Func?ii Libevent


Process Control

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic usage
  • Func?ii PCNTL
    • pcntl_alarm — Set an alarm clock for delivery of a signal
    • pcntl_errno — Pseudonim pentru pcntl_strerror
    • pcntl_exec — Executes specified program in current process space
    • pcntl_fork — Forks the currently running process
    • pcntl_get_last_error — Retrieve the error number set by the last pcntl function which failed
    • 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_get_handler — Get the current handler for specified signal
    • 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_strerror — Retrieve the system error message associated with the given errno
    • 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_timer_set
Introducere
Extensii de control al proceselor


Introducere

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().

Nota: Aceasta extensie nu este disponibila pe platformele Windows.

PCNTL
Instalarea / configurarea
PCNTL


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
PCNTL


Instalarea

Sus?inerea controlului proceselor în PHP nu este activata implicit. Trebuie sa compila?i versiunea CGI sau CLI a PHP cu op?iunea de configurare --enable-pcntl pentru a activa controlul proceselor.

Nota:

În prezent acest modul nu func?ioneaza pe platforme non-Unix (Windows).

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

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.
Tipurile resurselor
Exemple
PCNTL


Exemple

Cuprins

  • Basic usage
Constante predefinite
Basic usage
PCNTL


Basic usage

This example forks off a daemon process with a signal handler.

Example #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
     }

}

?>
Exemple
Func?ii PCNTL
Exemple


Func?ii PCNTL

A se vedea ?i

Va va fi util sa arunca?i o privire la func?iile POSIX.

Cuprins

  • pcntl_alarm — Set an alarm clock for delivery of a signal
  • pcntl_errno — Pseudonim pentru pcntl_strerror
  • pcntl_exec — Executes specified program in current process space
  • pcntl_fork — Forks the currently running process
  • pcntl_get_last_error — Retrieve the error number set by the last pcntl function which failed
  • 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_get_handler — Get the current handler for specified signal
  • 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_strerror — Retrieve the system error message associated with the given errno
  • 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

Func?ii PCNTL
pcntl_errno
Func?ii PCNTL
PHP Manual

pcntl_alarm

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pcntl_alarm — Set an alarm clock for delivery of a signal

Descrierea

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.

Parametri

seconds

The number of seconds to wait. If seconds is zero, no new alarm is created.

Valorile întoarse

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.

Func?ii PCNTL
pcntl_errno
Func?ii PCNTL


Pseudonim pentru pcntl_strerror

pcntl_alarm
pcntl_exec
Func?ii PCNTL
PHP Manual

pcntl_errno

(PHP 5 >= 5.3.4, PHP 7)

pcntl_errno — Pseudonim pentru pcntl_strerror()

Descrierea

Aceasta func?ie este pseudonim pentru: pcntl_strerror()

pcntl_alarm
pcntl_exec
Func?ii PCNTL


Executes specified program in current process space

pcntl_errno
pcntl_fork
Func?ii PCNTL
PHP Manual

pcntl_exec

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pcntl_exec — Executes specified program in current process space

Descrierea

bool pcntl_exec ( string $path [, array $args [, array $envs ]] )

Executes the program with the given arguments.

Parametri

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.

Valorile întoarse

Returns FALSE on error and does not return on success.

pcntl_errno
pcntl_fork
Func?ii PCNTL


Forks the currently running process

pcntl_exec
pcntl_get_last_error
Func?ii PCNTL
PHP Manual

pcntl_fork

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_fork — Forks the currently running process

Descrierea

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.

Valorile întoarse

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.

Exemple

Example #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
}

?>

A se vedea ?i

  • 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_get_last_error
Func?ii PCNTL


Retrieve the error number set by the last pcntl function which failed

pcntl_fork
pcntl_getpriority
Func?ii PCNTL
PHP Manual

pcntl_get_last_error

(PHP 5 >= 5.3.4, PHP 7)

pcntl_get_last_error — Retrieve the error number set by the last pcntl function which failed

Descrierea

int pcntl_get_last_error ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns error code.

A se vedea ?i

  • pcntl_strerror() - Retrieve the system error message associated with the given errno
pcntl_fork
pcntl_getpriority
Func?ii PCNTL


Get the priority of any process

pcntl_get_last_error
pcntl_setpriority
Func?ii PCNTL
PHP Manual

pcntl_getpriority

(PHP 5, PHP 7)

pcntl_getpriority — Get the priority of any process

Descrierea

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.

Parametri

pid

If not specified, the pid of the current process is used.

process_identifier

One of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.

Valorile întoarse

pcntl_getpriority() returns the priority of the process or FALSE on error. A lower numerical value causes more favorable scheduling.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

A se vedea ?i

  • pcntl_setpriority() - Change the priority of any process

pcntl_get_last_error
pcntl_setpriority
Func?ii PCNTL


Change the priority of any process

pcntl_getpriority
pcntl_signal_dispatch
Func?ii PCNTL
PHP Manual

pcntl_setpriority

(PHP 5, PHP 7)

pcntl_setpriority — Change the priority of any process

Descrierea

bool pcntl_setpriority ( int $priority [, int $pid = getmypid() [, int $process_identifier = PRIO_PROCESS ]] )

pcntl_setpriority() sets the priority of pid.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • pcntl_getpriority() - Get the priority of any process

pcntl_getpriority
pcntl_signal_dispatch
Func?ii PCNTL


Calls signal handlers for pending signals

pcntl_setpriority
pcntl_signal_get_handler
Func?ii PCNTL
PHP Manual

pcntl_signal_dispatch

(PHP 5 >= 5.3.0, PHP 7)

pcntl_signal_dispatch — Calls signal handlers for pending signals

Descrierea

bool pcntl_signal_dispatch ( void )

The pcntl_signal_dispatch() function calls the signal handlers installed by pcntl_signal() for each pending signal.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";

?>

Exemplul de mai sus va afi?a ceva similar cu:

Installing signal handler...
Generating signal SIGHUP to self...
Dispatching...
signal handler called
Done

A se vedea ?i

  • 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_get_handler
Func?ii PCNTL


Get the current handler for specified signal

pcntl_signal_dispatch
pcntl_signal
Func?ii PCNTL
PHP Manual

pcntl_signal_get_handler

(PHP 7.1)

pcntl_signal_get_handler — Get the current handler for specified signal

Descrierea

int|string pcntl_signal_get_handler ( int $signo )

The pcntl_signal_get_handler() function will get the current handler for the specified signo.

Parametri

signo

The signal number.

Valorile întoarse

This function may return an integer value that refers to SIG_DFL or SIG_IGN. If you set a custom handler a string value containing the function name is returned.

Istoricul schimbarilor

Versiune | Descriere
Enter the version of change here | Describe the change

Exemple

Example #1 pcntl_signal_get_handler() example

<?php
var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: int(0)

function pcntl_test($signo) {}
pcntl_signal(SIGUSR1, 'pcntl_test');
var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: string(10) "pcntl_test"

pcntl_signal(SIGUSR1, SIG_DFL);
var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: int(0)

pcntl_signal(SIGUSR1, SIG_IGN);
var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: int(1)
?>

A se vedea ?i

  • pcntl_signal() - Installs a signal handler
pcntl_signal_dispatch
pcntl_signal
Func?ii PCNTL


Installs a signal handler

pcntl_signal_get_handler
pcntl_sigprocmask
Func?ii PCNTL
PHP Manual

pcntl_signal

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_signal — Installs a signal handler

Descrierea

bool pcntl_signal ( int $signo , callable|int $handler [, bool $restart_syscalls = true ] )

The pcntl_signal() function installs a new signal handler or replaces the current signal handler for the signal indicated by signo.

Parametri

signo

The signal number.

handler

The signal handler. This may be either a callable, which will be invoked to handle the signal, or either of the two global constants SIG_IGN or SIG_DFL, which will ignore the signal or restore the default signal handler respectively.

If a callable is given, it must implement the following signature:

void handler ( int $signo , mixed $signinfo )
signo
The signal being handled.
siginfo
If operating systems supports siginfo_t structures, this will be an array of signal information dependent on the signal.

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
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 example below).
7.1.0 | As of PHP 7.1.0 the handler callback is given a second argument containing the signinfo of the specific signal. This data is only supplied if the operating system has the signinfo_t structure. If the OS does not implement siginfo_t NULL is supplied.

Exemple

Example #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 SIGUSR1 to self...\n";

// send SIGUSR1 to current process id
// posix_* functions require the posix extension
posix_kill(posix_getpid(), SIGUSR1);

echo "Done\n";

?>

Note

pcntl_signal() doesn't stack the signal handlers, but replaces them.

A se vedea ?i

  • pcntl_fork() - Forks the currently running process
  • pcntl_waitpid() - Waits on or returns the status of a forked child

pcntl_signal_get_handler
pcntl_sigprocmask
Func?ii PCNTL


Sets and retrieves blocked signals

pcntl_signal
pcntl_sigtimedwait
Func?ii PCNTL
PHP Manual

pcntl_sigprocmask

(PHP 5 >= 5.3.0, PHP 7)

pcntl_sigprocmask — Sets and retrieves blocked signals

Descrierea

bool pcntl_sigprocmask ( int $how , array $set [, array &$oldset ] )

The pcntl_sigprocmask() function adds, removes or sets blocked signals, depending on the how parameter.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 pcntl_sigprocmask() example

<?php
pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP));
$oldset = array();
pcntl_sigprocmask(SIG_UNBLOCK, array(SIGHUP), $oldset);
?>

A se vedea ?i

  • pcntl_sigwaitinfo() - Waits for signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout

pcntl_signal
pcntl_sigtimedwait
Func?ii PCNTL


Waits for signals, with a timeout

pcntl_sigprocmask
pcntl_sigwaitinfo
Func?ii PCNTL
PHP Manual

pcntl_sigtimedwait

(PHP 5 >= 5.3.0, PHP 7)

pcntl_sigtimedwait — Waits for signals, with a timeout

Descrierea

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.

Parametri

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.

Valorile întoarse

On success, pcntl_sigtimedwait() returns a signal number.

A se vedea ?i

  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigwaitinfo() - Waits for signals

pcntl_sigprocmask
pcntl_sigwaitinfo
Func?ii PCNTL


Waits for signals

pcntl_sigtimedwait
pcntl_strerror
Func?ii PCNTL
PHP Manual

pcntl_sigwaitinfo

(PHP 5 >= 5.3.0, PHP 7)

pcntl_sigwaitinfo — Waits for signals

Descrierea

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.

Parametri

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

Valorile întoarse

On success, pcntl_sigwaitinfo() returns a signal number.

Exemple

Example #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);
?>

A se vedea ?i

  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout

pcntl_sigtimedwait
pcntl_strerror
Func?ii PCNTL


Retrieve the system error message associated with the given errno

pcntl_sigwaitinfo
pcntl_wait
Func?ii PCNTL
PHP Manual

pcntl_strerror

(PHP 5 >= 5.3.4, PHP 7)

pcntl_strerror — Retrieve the system error message associated with the given errno

Descrierea

string pcntl_strerror ( int $errno )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

errno

Valorile întoarse

Returns error description on success sau FALSE în cazul e?ecului.

A se vedea ?i

  • pcntl_get_last_error() - Retrieve the error number set by the last pcntl function which failed
pcntl_sigwaitinfo
pcntl_wait
Func?ii PCNTL


Waits on or returns the status of a forked child

pcntl_strerror
pcntl_waitpid
Func?ii PCNTL
PHP Manual

pcntl_wait

(PHP 5, PHP 7)

pcntl_wait — Waits on or returns the status of a forked child

Descrierea

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.

Nota:

This function is equivalent to calling pcntl_waitpid() with a -1 pid and no options.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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_strerror
pcntl_waitpid
Func?ii PCNTL


Waits on or returns the status of a forked child

pcntl_wait
pcntl_wexitstatus
Func?ii PCNTL
PHP Manual

pcntl_waitpid

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_waitpid — Waits on or returns the status of a forked child

Descrierea

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.

Parametri

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.

Nota:

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.

Valorile întoarse

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

A se vedea ?i

  • 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
Func?ii PCNTL


Returns the return code of a terminated child

pcntl_waitpid
pcntl_wifexited
Func?ii PCNTL
PHP Manual

pcntl_wexitstatus

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_wexitstatus — Returns the return code of a terminated child

Descrierea

int pcntl_wexitstatus ( int $status )

Returns the return code of a terminated child. This function is only useful if pcntl_wifexited() returned TRUE.

Parametri

status

Parametrul status reprezinta parametrul de stare furnizat catre un apel cu succes al func?iei pcntl_waitpid().

Valorile întoarse

Returns the return code, as an integer.

A se vedea ?i

  • 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
Func?ii PCNTL


Checks if status code represents a normal exit

pcntl_wexitstatus
pcntl_wifsignaled
Func?ii PCNTL
PHP Manual

pcntl_wifexited

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_wifexited — Checks if status code represents a normal exit

Descrierea

bool pcntl_wifexited ( int $status )

Checks whether the child status code represents a normal exit.

Parametri

status

Parametrul status reprezinta parametrul de stare furnizat catre un apel cu succes al func?iei pcntl_waitpid().

Valorile întoarse

Returns TRUE if the child status code represents a normal exit, FALSE otherwise.

A se vedea ?i

  • 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
Func?ii PCNTL


Checks whether the status code represents a termination due to a signal

pcntl_wifexited
pcntl_wifstopped
Func?ii PCNTL
PHP Manual

pcntl_wifsignaled

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_wifsignaled — Checks whether the status code represents a termination due to a signal

Descrierea

bool pcntl_wifsignaled ( int $status )

Checks whether the child process exited because of a signal which was not caught.

Parametri

status

Parametrul status reprezinta parametrul de stare furnizat catre un apel cu succes al func?iei pcntl_waitpid().

Valorile întoarse

Returns TRUE if the child process exited because of a signal which was not caught, FALSE otherwise.

A se vedea ?i

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_signal() - Installs a signal handler

pcntl_wifexited
pcntl_wifstopped
Func?ii PCNTL


Checks whether the child process is currently stopped

pcntl_wifsignaled
pcntl_wstopsig
Func?ii PCNTL
PHP Manual

pcntl_wifstopped

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_wifstopped — Checks whether the child process is currently stopped

Descrierea

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.

Parametri

status

Parametrul status reprezinta parametrul de stare furnizat catre un apel cu succes al func?iei pcntl_waitpid().

Valorile întoarse

Returns TRUE if the child process which caused the return is currently stopped, FALSE otherwise.

A se vedea ?i

  • pcntl_waitpid() - Waits on or returns the status of a forked child

pcntl_wifsignaled
pcntl_wstopsig
Func?ii PCNTL


Returns the signal which caused the child to stop

pcntl_wifstopped
pcntl_wtermsig
Func?ii PCNTL
PHP Manual

pcntl_wstopsig

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_wstopsig — Returns the signal which caused the child to stop

Descrierea

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.

Parametri

status

Parametrul status reprezinta parametrul de stare furnizat catre un apel cu succes al func?iei pcntl_waitpid().

Valorile întoarse

Returns the signal number.

A se vedea ?i

  • 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
Func?ii PCNTL


Returns the signal which caused the child to terminate

pcntl_wstopsig
POSIX
Func?ii PCNTL
PHP Manual

pcntl_wtermsig

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_wtermsig — Returns the signal which caused the child to terminate

Descrierea

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.

Parametri

status

Parametrul status reprezinta parametrul de stare furnizat catre un apel cu succes al func?iei pcntl_waitpid().

Valorile întoarse

Returns the signal number, as an integer.

A se vedea ?i

  • 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
Func?ii PCNTL


POSIX

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
    • posix_access constants
    • posix_mknod constants
    • posix_setrlimit constants
  • Func?ii POSIX
    • posix_access — Determine accessibility of a file
    • posix_ctermid — Get path name of controlling terminal
    • posix_errno — Pseudonim pentru 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_setrlimit — Set system resource limits
    • 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
Introducere
Extensii de control al proceselor


Introducere

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.

Avertizare

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.

Nota: Aceasta extensie nu este disponibila pe platformele Windows.

POSIX
Instalarea / configurarea
POSIX


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
POSIX


Instalarea

Func?iile POSIX sunt activate implicit. Pute?i dezactiva func?iile POSIX cu op?iunea --disable-posix .

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Cuprins

  • posix_access constants
  • posix_mknod constants
  • posix_setrlimit constants

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Tipurile resurselor
posix_access constants
POSIX


posix_access constants

Constante predefinite
posix_mknod constants
Constante predefinite
PHP Manual

posix_access() constants

Nota:

These constants are available starting with PHP 5.1.0. Please note that some of them may not be available on your system.

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.
Constante predefinite
posix_mknod constants
Constante predefinite


posix_mknod constants

posix_access constants
posix_setrlimit constants
Constante predefinite
PHP Manual

posix_mknod() constants

Nota:

These constants are available starting with PHP 5.1.0. Please note that some of them may not be available on your system.

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
posix_access constants
posix_setrlimit constants
Constante predefinite


posix_setrlimit constants

posix_mknod constants
Func?ii POSIX
Constante predefinite
PHP Manual

posix_setrlimit() constants

Nota:

These constants are available starting with PHP 7.0.0. Please note that some of them may not be available on your system.

Nota:

You may wish to read the below notes in conjunction with the manpage for setrlimit() on your specific operating system, as there is variance in how these limits are interpreted, even across operating systems that claim to implement POSIX in full.

POSIX_RLIMIT_AS (integer)
The maximum size of the process's address space in bytes. See also PHP's memory_limit configuration directive.
POSIX_RLIMIT_CORE (integer)
The maximum size of a core file. If the limit is set to 0, no core file will be generated.
POSIX_RLIMIT_CPU (integer)
The maximum amount of CPU time that the process can use, in seconds. When the soft limit is hit, a SIGXCPU signal will be sent, which can be caught with pcntl_signal(). Depending on the operating system, additional SIGXCPU signals may be sent each second until the hard limit is hit, at which point an uncatchable SIGKILL signal is sent. See also set_time_limit().
POSIX_RLIMIT_DATA (integer)
The maximum size of the process's data segment, in bytes. It is extremely unlikely that this will have any effect on the execution of PHP unless an extension is in use that calls brk() or sbrk().
POSIX_RLIMIT_FSIZE (integer)
The maximum size of files that the process can create, in bytes.
POSIX_RLIMIT_LOCKS (integer)
The maximum number of locks that the process can create. This is only supported on extremely old Linux kernels.
POSIX_RLIMIT_MEMLOCK (integer)
The maximum number of bytes that can be locked into memory.
POSIX_RLIMIT_MSGQUEUE (integer)
The maximum number of bytes that can be allocated for POSIX message queues. PHP does not ship with support for POSIX message queues, so this limit will not have any effect unless you are using an extension that implements that support.
POSIX_RLIMIT_NICE (integer)
The maximum value to which the process can be reniced to. The value that will be used will be 20 - limit, as resource limit values cannot be negative.
POSIX_RLIMIT_NOFILE (integer)
A value one greater than the maximum file descriptor number that can be opened by this process.
POSIX_RLIMIT_NPROC (integer)
The maximum number of processes (and/or threads, on some operating systems) that can be created for the real user ID of the process.
POSIX_RLIMIT_RSS (integer)
The maximum size of the process's resident set, in pages.
POSIX_RLIMIT_RTPRIO (integer)
The maximum real time priority that can be set via the sched_setscheduler() and sched_setparam() system calls.
POSIX_RLIMIT_RTTIME (integer)
The maximum amount of CPU time, in microseconds, that the process can consume without making a blocking system call if it is using real time scheduling.
POSIX_RLIMIT_SIGPENDING (integer)
The maximum number of signals that can be queued for the real user ID of the process.
POSIX_RLIMIT_STACK (integer)
The maximum size of the process stack, in bytes.
POSIX_RLIMIT_INFINITY (integer)
Used to indicate an infinite value for a resource limit.
posix_mknod constants
Func?ii POSIX
Constante predefinite


Func?ii POSIX

A se vedea ?i

S-ar putea sa va intereseze func?iile de control al proceselor.

Cuprins

  • posix_access — Determine accessibility of a file
  • posix_ctermid — Get path name of controlling terminal
  • posix_errno — Pseudonim pentru 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_setrlimit — Set system resource limits
  • 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
posix_setrlimit constants
posix_access
POSIX


Determine accessibility of a file

Func?ii POSIX
posix_ctermid
Func?ii POSIX
PHP Manual

posix_access

(PHP 5 >= 5.1.0, PHP 7)

posix_access — Determine accessibility of a file

Descrierea

bool posix_access ( string $file [, int $mode = POSIX_F_OK ] )

posix_access() checks the user's permission of a file.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
}

?>

Note

Nota: Când este activat modul securizat, PHP verifica daca fi?ierele ?i directoarele cu care se va opera au acela?i UID (proprietar) ca ?i script-ul care se executa.

A se vedea ?i

  • 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

Func?ii POSIX
posix_ctermid
Func?ii POSIX


Get path name of controlling terminal

posix_access
posix_errno
Func?ii POSIX
PHP Manual

posix_ctermid

(PHP 4, PHP 5, PHP 7)

posix_ctermid — Get path name of controlling terminal

Descrierea

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()

Valorile întoarse

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().

Exemple

Example #1 posix_ctermid() example

This example will display the path to the current TTY.

<?php
echo "I am running from ".posix_ctermid();
?>

A se vedea ?i

  • 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
Func?ii POSIX


Pseudonim pentru posix_get_last_error

posix_ctermid
posix_get_last_error
Func?ii POSIX
PHP Manual

posix_errno

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

posix_errno — Pseudonim pentru posix_get_last_error()

Descrierea

Aceasta func?ie este pseudonim pentru: posix_get_last_error().

posix_ctermid
posix_get_last_error
Func?ii POSIX


Retrieve the error number set by the last posix function that failed

posix_errno
posix_getcwd
Func?ii POSIX
PHP Manual

posix_get_last_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

posix_get_last_error — Retrieve the error number set by the last posix function that failed

Descrierea

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().

Valorile întoarse

Returns the errno (error number) set by the last posix function that failed. If no errors exist, 0 is returned.

Exemple

Example #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 ___
?>

A se vedea ?i

  • posix_strerror() - Retrieve the system error message associated with the given errno

posix_errno
posix_getcwd
Func?ii POSIX


Pathname of current directory

posix_get_last_error
posix_getegid
Func?ii POSIX
PHP Manual

posix_getcwd

(PHP 4, PHP 5, PHP 7)

posix_getcwd — Pathname of current directory

Descrierea

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()

Valorile întoarse

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().

Exemple

Example #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();
?>

Note

Nota:

This function can fail on

  • Read or Search permission was denied
  • Pathname no longer exists

posix_get_last_error
posix_getegid
Func?ii POSIX


Return the effective group ID of the current process

posix_getcwd
posix_geteuid
Func?ii POSIX
PHP Manual

posix_getegid

(PHP 4, PHP 5, PHP 7)

posix_getegid — Return the effective group ID of the current process

Descrierea

int posix_getegid ( void )

Return the numeric effective group ID of the current process.

Valorile întoarse

Returns an integer of the effective group ID.

Exemple

Example #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
?>

Note

posix_getegid() is different than posix_getgid() because effective group ID can be changed by a calling process using posix_setegid().

A se vedea ?i

  • 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
Func?ii POSIX


Return the effective user ID of the current process

posix_getegid
posix_getgid
Func?ii POSIX
PHP Manual

posix_geteuid

(PHP 4, PHP 5, PHP 7)

posix_geteuid — Return the effective user ID of the current process

Descrierea

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.

Valorile întoarse

Returns the user id, as an integer

Exemple

Example #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
?>

A se vedea ?i

  • 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
Func?ii POSIX


Return the real group ID of the current process

posix_geteuid
posix_getgrgid
Func?ii POSIX
PHP Manual

posix_getgid

(PHP 4, PHP 5, PHP 7)

posix_getgid — Return the real group ID of the current process

Descrierea

int posix_getgid ( void )

Return the numeric real group ID of the current process.

Valorile întoarse

Returns the real group id, as an integer.

Exemple

Example #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
?>

A se vedea ?i

  • 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
Func?ii POSIX


Return info about a group by group id

posix_getgid
posix_getgrnam
Func?ii POSIX
PHP Manual

posix_getgrgid

(PHP 4, PHP 5, PHP 7)

posix_getgrgid — Return info about a group by group id

Descrierea

array posix_getgrgid ( int $gid )

Gets information about a group provided its id.

Parametri

gid

The group id.

Valorile întoarse

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.

Exemple

Example #1 Example use of posix_getgrgid()

<?php

$groupid   = posix_getegid();
$groupinfo = posix_getgrgid($groupid);

print_r($groupinfo);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

A se vedea ?i

  • posix_getegid() - Return the effective group ID of the current process
  • posix_getgrnam() - Return info about a group by name
  • filegroup() - Gets file group
  • stat() - Gives information about a file
  • safe_mode_gid
  • POSIX man page GETGRNAM(3)

posix_getgid
posix_getgrnam
Func?ii POSIX


Return info about a group by name

posix_getgrgid
posix_getgroups
Func?ii POSIX
PHP Manual

posix_getgrnam

(PHP 4, PHP 5, PHP 7)

posix_getgrnam — Return info about a group by name

Descrierea

array posix_getgrnam ( string $name )

Gets information about a group provided its name.

Parametri

name

The name of the group

Valorile întoarse

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.

Exemple

Example #1 Example use of posix_getgrnam()

<?php

$groupinfo = posix_getgrnam("toons");

print_r($groupinfo);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

A se vedea ?i

  • posix_getegid() - Return the effective group ID of the current process
  • posix_getgrgid() - Return info about a group by group id
  • filegroup() - Gets file group
  • stat() - Gives information about a file
  • safe_mode_gid
  • POSIX man page GETGRNAM(3)

posix_getgrgid
posix_getgroups
Func?ii POSIX


Return the group set of the current process

posix_getgrnam
posix_getlogin
Func?ii POSIX
PHP Manual

posix_getgroups

(PHP 4, PHP 5, PHP 7)

posix_getgroups — Return the group set of the current process

Descrierea

array posix_getgroups ( void )

Gets the group set of the current process.

Valorile întoarse

Returns an array of integers containing the numeric group ids of the group set of the current process.

Exemple

Example #1 Example use of posix_getgroups()

<?php

$groups = posix_getgroups();

print_r($groups);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • posix_getgrgid() - Return info about a group by group id

posix_getgrnam
posix_getlogin
Func?ii POSIX


Return login name

posix_getgroups
posix_getpgid
Func?ii POSIX
PHP Manual

posix_getlogin

(PHP 4, PHP 5, PHP 7)

posix_getlogin — Return login name

Descrierea

string posix_getlogin ( void )

Returns the login name of the user owning the current process.

Valorile întoarse

Returns the login name of the user, as a string.

Exemple

Example #1 Example use of posix_getlogin()

<?php
echo posix_getlogin(); //apache
?>

A se vedea ?i

  • posix_getpwnam() - Return info about a user by username
  • POSIX man page GETLOGIN(3)

posix_getgroups
posix_getpgid
Func?ii POSIX


Get process group id for job control

posix_getlogin
posix_getpgrp
Func?ii POSIX
PHP Manual

posix_getpgid

(PHP 4, PHP 5, PHP 7)

posix_getpgid — Get process group id for job control

Descrierea

int posix_getpgid ( int $pid )

Returns the process group identifier of the process pid sau FALSE în cazul e?ecului.

Parametri

pid

The process id.

Valorile întoarse

Returns the identifier, as an integer.

Exemple

Example #1 Example use of posix_getpgid()

<?php
$pid = posix_getppid();
echo posix_getpgid($pid); //35
?>

Note

Nota:

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().

A se vedea ?i

  • posix_getppid() - Return the parent process identifier
  • man page SETPGID(2)

posix_getlogin
posix_getpgrp
Func?ii POSIX


Return the current process group identifier

posix_getpgid
posix_getpid
Func?ii POSIX
PHP Manual

posix_getpgrp

(PHP 4, PHP 5, PHP 7)

posix_getpgrp — Return the current process group identifier

Descrierea

int posix_getpgrp ( void )

Return the process group identifier of the current process.

Valorile întoarse

Returns the identifier, as an integer.

A se vedea ?i

  • POSIX.1 and the getpgrp(2) manual page on the POSIX system for more information on process groups.

posix_getpgid
posix_getpid
Func?ii POSIX


Return the current process identifier

posix_getpgrp
posix_getppid
Func?ii POSIX
PHP Manual

posix_getpid

(PHP 4, PHP 5, PHP 7)

posix_getpid — Return the current process identifier

Descrierea

int posix_getpid ( void )

Return the process identifier of the current process.

Valorile întoarse

Returns the identifier, as an integer.

Exemple

Example #1 Example use of posix_getpid()

<?php
echo posix_getpid(); //8805
?>

A se vedea ?i

  • posix_kill() - Send a signal to a process
  • POSIX man page GETPID(2)

posix_getpgrp
posix_getppid
Func?ii POSIX


Return the parent process identifier

posix_getpid
posix_getpwnam
Func?ii POSIX
PHP Manual

posix_getppid

(PHP 4, PHP 5, PHP 7)

posix_getppid — Return the parent process identifier

Descrierea

int posix_getppid ( void )

Return the process identifier of the parent process of the current process.

Valorile întoarse

Returns the identifier, as an integer.

Exemple

Example #1 Example use of posix_getppid()

<?php
echo posix_getppid(); //8259
?>

posix_getpid
posix_getpwnam
Func?ii POSIX


Return info about a user by username

posix_getppid
posix_getpwuid
Func?ii POSIX
PHP Manual

posix_getpwnam

(PHP 4, PHP 5, PHP 7)

posix_getpwnam — Return info about a user by username

Descrierea

array posix_getpwnam ( string $username )

Returns an array of information about the given user.

Parametri

username

An alphanumeric username.

Valorile întoarse

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.

Exemple

Example #1 Example use of posix_getpwnam()

<?php

$userinfo = posix_getpwnam("tom");

print_r($userinfo);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [name]    => tom
    [passwd]  => x
    [uid]     => 10000
    [gid]     => 42
    [gecos]   => "tom,,,"
    [dir]     => "/home/tom"
    [shell]   => "/bin/bash"
)

A se vedea ?i

  • posix_getpwuid() - Return info about a user by user id
  • POSIX man page GETPWNAM(3)

posix_getppid
posix_getpwuid
Func?ii POSIX


Return info about a user by user id

posix_getpwnam
posix_getrlimit
Func?ii POSIX
PHP Manual

posix_getpwuid

(PHP 4, PHP 5, PHP 7)

posix_getpwuid — Return info about a user by user id

Descrierea

array posix_getpwuid ( int $uid )

Returns an array of information about the user referenced by the given user ID.

Parametri

uid

The user identifier.

Valorile întoarse

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.

Exemple

Example #1 Example use of posix_getpwuid()

<?php

$userinfo = posix_getpwuid(10000);

print_r($userinfo);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [name]    => tom
    [passwd]  => x
    [uid]     => 10000
    [gid]     => 42
    [gecos]   => "tom,,,"
    [dir]     => "/home/tom"
    [shell]   => "/bin/bash"
)

A se vedea ?i

  • posix_getpwnam() - Return info about a user by username
  • POSIX man page GETPWNAM(3)

posix_getpwnam
posix_getrlimit
Func?ii POSIX


Return info about system resource limits

posix_getpwuid
posix_getsid
Func?ii POSIX
PHP Manual

posix_getrlimit

(PHP 4, PHP 5, PHP 7)

posix_getrlimit — Return info about system resource limits

Descrierea

array posix_getrlimit ( void )

posix_getrlimit() returns an array of information about the current resource's soft and hard limits.

Fiecare resursa are asociata o limita soft ?i hard. Limita soft este valoarea pe care nucleul o impune pentru resursa corespunzatoare. Limita hard ac?ioneaza ca un plafon pentru limita soft. Un proces neprivilegiat poate sa-?i stabileasca limita soft la o valoarea între 0 ?i limita hard, sau poate sa-?i mic?oreze ireversibil limita hard.

Valorile întoarse

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.

Exemple

Example #1 Example use of posix_getrlimit()

<?php

$limits = posix_getrlimit();

print_r($limits);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • man page GETRLIMIT(2)
  • posix_setrlimit() - Set system resource limits

posix_getpwuid
posix_getsid
Func?ii POSIX


Get the current sid of the process

posix_getrlimit
posix_getuid
Func?ii POSIX
PHP Manual

posix_getsid

(PHP 4, PHP 5, PHP 7)

posix_getsid — Get the current sid of the process

Descrierea

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.

Parametri

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().

Valorile întoarse

Returns the identifier, as an integer.

Exemple

Example #1 Example use of posix_getsid()

<?php
$pid = posix_getpid();
echo posix_getsid($pid); //8805
?>

A se vedea ?i

  • 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
Func?ii POSIX


Return the real user ID of the current process

posix_getsid
posix_initgroups
Func?ii POSIX
PHP Manual

posix_getuid

(PHP 4, PHP 5, PHP 7)

posix_getuid — Return the real user ID of the current process

Descrierea

int posix_getuid ( void )

Return the numeric real user ID of the current process.

Valorile întoarse

Returns the user id, as an integer

Exemple

Example #1 Example use of posix_getuid()

<?php
echo posix_getuid(); //10000
?>

A se vedea ?i

  • posix_getpwuid() - Return info about a user by user id
  • POSIX man page GETUID(2)

posix_getsid
posix_initgroups
Func?ii POSIX


Calculate the group access list

posix_getuid
posix_isatty
Func?ii POSIX
PHP Manual

posix_initgroups

(PHP 5 >= 5.2.0, PHP 7)

posix_initgroups — Calculate the group access list

Descrierea

bool posix_initgroups ( string $name , int $base_group_id )

Calculates the group access list for the user specified in name.

Parametri

name

The user to calculate the list for.

base_group_id

Typically the group number from the password file.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • The Unix manual page for initgroups(3).

posix_getuid
posix_isatty
Func?ii POSIX


Determine if a file descriptor is an interactive terminal

posix_initgroups
posix_kill
Func?ii POSIX
PHP Manual

posix_isatty

(PHP 4, PHP 5, PHP 7)

posix_isatty — Determine if a file descriptor is an interactive terminal

Descrierea

bool posix_isatty ( mixed $fd )

Determines if the file descriptor fd refers to a valid terminal type device.

Parametri

fd

Descriptorul fi?ierului, care trebuie sa fie o resource de fi?ier, sau un integer. Un integer se va presupune a fi un descriptor de fi?ier care poate fi transmis direct catre apelul de sistem ce sta la baza.

În majoritatea cazurilor ve?i dori sa utiliza?i o resource de fi?ier.

Valorile întoarse

Returns TRUE if fd is an open descriptor connected to a terminal and FALSE otherwise.

A se vedea ?i

  • posix_ttyname() - Determine terminal device name

posix_initgroups
posix_kill
Func?ii POSIX


Send a signal to a process

posix_isatty
posix_mkfifo
Func?ii POSIX
PHP Manual

posix_kill

(PHP 4, PHP 5, PHP 7)

posix_kill — Send a signal to a process

Descrierea

bool posix_kill ( int $pid , int $sig )

Send the signal sig to the process with the process identifier pid.

Parametri

pid

The process identifier.

sig

One of the PCNTL signals constants.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii POSIX


Create a fifo special file (a named pipe)

posix_kill
posix_mknod
Func?ii POSIX
PHP Manual

posix_mkfifo

(PHP 4, PHP 5, PHP 7)

posix_mkfifo — Create a fifo special file (a named pipe)

Descrierea

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.

Parametri

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota: Când este activat modul securizat, PHP verifica daca fi?ierele ?i directoarele cu care se va opera au acela?i UID (proprietar) ca ?i script-ul care se executa.

posix_kill
posix_mknod
Func?ii POSIX


Create a special or ordinary file (POSIX.1)

posix_mkfifo
posix_setegid
Func?ii POSIX
PHP Manual

posix_mknod

(PHP 5 >= 5.1.0, PHP 7)

posix_mknod — Create a special or ordinary file (POSIX.1)

Descrierea

bool posix_mknod ( string $pathname , int $mode [, int $major = 0 [, int $minor = 0 ]] )

Creates a special or ordinary file.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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()));
}

?>

A se vedea ?i

  • posix_mkfifo() - Create a fifo special file (a named pipe)

posix_mkfifo
posix_setegid
Func?ii POSIX


Set the effective GID of the current process

posix_mknod
posix_seteuid
Func?ii POSIX
PHP Manual

posix_setegid

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

posix_setegid — Set the effective GID of the current process

Descrierea

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.

Parametri

gid

The group id.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
?>

A se vedea ?i

  • 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
Func?ii POSIX


Set the effective UID of the current process

posix_setegid
posix_setgid
Func?ii POSIX
PHP Manual

posix_seteuid

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

posix_seteuid — Set the effective UID of the current process

Descrierea

bool posix_seteuid ( int $uid )

Set the effective 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.

Parametri

uid

The user id.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • posix_geteuid() - Return the effective user ID of the current process
  • posix_setuid() - Set the UID of the current process
  • posix_getuid() - Return the real user ID of the current process

posix_setegid
posix_setgid
Func?ii POSIX


Set the GID of the current process

posix_seteuid
posix_setpgid
Func?ii POSIX
PHP Manual

posix_setgid

(PHP 4, PHP 5, PHP 7)

posix_setgid — Set the GID of the current process

Descrierea

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.

Nota:

If the caller is a super user, this will also set the effective group id.

Parametri

gid

The group id.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
?>

A se vedea ?i

  • 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
Func?ii POSIX


Set process group id for job control

posix_setgid
posix_setrlimit
Func?ii POSIX
PHP Manual

posix_setpgid

(PHP 4, PHP 5, PHP 7)

posix_setpgid — Set process group id for job control

Descrierea

bool posix_setpgid ( int $pid , int $pgid )

Let the process pid join the process group pgid.

Parametri

pid

The process id.

pgid

The process group id.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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_setrlimit
Func?ii POSIX


Set system resource limits

posix_setpgid
posix_setsid
Func?ii POSIX
PHP Manual

posix_setrlimit

(PHP 7)

posix_setrlimit — Set system resource limits

Descrierea

bool posix_setrlimit ( int $resource , int $softlimit , int $hardlimit )

posix_setrlimit() sets the soft and hard limits for a given system resource.

Fiecare resursa are asociata o limita soft ?i hard. Limita soft este valoarea pe care nucleul o impune pentru resursa corespunzatoare. Limita hard ac?ioneaza ca un plafon pentru limita soft. Un proces neprivilegiat poate sa-?i stabileasca limita soft la o valoarea între 0 ?i limita hard, sau poate sa-?i mic?oreze ireversibil limita hard.

Parametri

resource

The resource limit constant corresponding to the limit that is being set.

softlimit

The soft limit, in whatever unit the resource limit requires, or POSIX_RLIMIT_INFINITY.

hardlimit

The hard limit, in whatever unit the resource limit requires, or POSIX_RLIMIT_INFINITY.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • man page SETRLIMIT(2)
  • posix_getrlimit() - Return info about system resource limits

posix_setpgid
posix_setsid
Func?ii POSIX


Make the current process a session leader

posix_setrlimit
posix_setuid
Func?ii POSIX
PHP Manual

posix_setsid

(PHP 4, PHP 5, PHP 7)

posix_setsid — Make the current process a session leader

Descrierea

int posix_setsid ( void )

Make the current process a session leader.

Valorile întoarse

Returns the session id, or -1 on errors.

A se vedea ?i

  • The POSIX.1 and the setsid(2) manual page on the POSIX system for more information on process groups and job control.

posix_setrlimit
posix_setuid
Func?ii POSIX


Set the UID of the current process

posix_setsid
posix_strerror
Func?ii POSIX
PHP Manual

posix_setuid

(PHP 4, PHP 5, PHP 7)

posix_setuid — Set the UID of the current process

Descrierea

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.

Parametri

uid

The user id.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
?>

A se vedea ?i

  • 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
Func?ii POSIX


Retrieve the system error message associated with the given errno

posix_setuid
posix_times
Func?ii POSIX
PHP Manual

posix_strerror

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

posix_strerror — Retrieve the system error message associated with the given errno

Descrierea

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().

Parametri

errno

A POSIX error number, returned by posix_get_last_error(). If set to 0, then the string "Success" is returned.

Valorile întoarse

Returns the error message, as a string.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

No such process

A se vedea ?i

  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed

posix_setuid
posix_times
Func?ii POSIX


Get process times

posix_strerror
posix_ttyname
Func?ii POSIX
PHP Manual

posix_times

(PHP 4, PHP 5, PHP 7)

posix_times — Get process times

Descrierea

array posix_times ( void )

Gets information about the current CPU usage.

Valorile întoarse

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.

Note

Avertizare

This function isn't reliable to use, it may return negative values for high times.

Exemple

Example #1 Example use of posix_times()

<?php

$times = posix_times();

print_r($times);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [ticks] => 25814410
    [utime] => 1
    [stime] => 1
    [cutime] => 0
    [cstime] => 0
)

posix_strerror
posix_ttyname
Func?ii POSIX


Determine terminal device name

posix_times
posix_uname
Func?ii POSIX
PHP Manual

posix_ttyname

(PHP 4, PHP 5, PHP 7)

posix_ttyname — Determine terminal device name

Descrierea

string posix_ttyname ( mixed $fd )

Returns a string for the absolute path to the current terminal device that is open on the file descriptor fd.

Parametri

fd

Descriptorul fi?ierului, care trebuie sa fie o resource de fi?ier, sau un integer. Un integer se va presupune a fi un descriptor de fi?ier care poate fi transmis direct catre apelul de sistem ce sta la baza.

În majoritatea cazurilor ve?i dori sa utiliza?i o resource de fi?ier.

Valorile întoarse

On success, returns a string of the absolute path of the fd. On failure, returns FALSE

posix_times
posix_uname
Func?ii POSIX


Get system name

posix_ttyname
Program execution
Func?ii POSIX
PHP Manual

posix_uname

(PHP 4, PHP 5, PHP 7)

posix_uname — Get system name

Descrierea

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.

Valorile întoarse

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.

Exemple

Example #1 Example use of posix_uname()

<?php
$uname=posix_uname();
print_r($uname);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
Func?ii POSIX


System program execution

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Program execution Func?ii
    • 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
Introducere
Extensii de control al proceselor


Introducere

Those functions provide means to execute commands on the system itself, and means to secure such commands.

Nota:

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
Instalarea / configurarea
Program execution


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Program execution


Tipurile resurselor

This extension defines a process resource, returned by proc_open().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Program execution Func?ii
Program execution


Program execution Func?ii

Note

Avertizare

Open files with lock (especially open sessions) should be closed before executing a program in the background.

A se vedea ?i

These functions are also closely related to the backtick operator. Also, while in modul securizat you must consider the safe_mode_exec_dir directive.

Cuprins

  • 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
Constante predefinite
escapeshellarg
Program execution


Escape a string to be used as a shell argument

Program execution Func?ii
escapeshellcmd
Program execution Func?ii
PHP Manual

escapeshellarg

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

escapeshellarg — Escape a string to be used as a shell argument

Descrierea

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.

On Windows, escapeshellarg() instead replaces percent signs, exclamation marks (delayed variable substitution) and double quotes with spaces and adds double quotes around the string.

Parametri

arg

The argument that will be escaped.

Valorile întoarse

The escaped string.

Exemple

Example #1 escapeshellarg() example

<?php
system('ls '.escapeshellarg($dir));
?>

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Valoarea implicita a parametrului encoding a fost schimbata pentru a coincide cu valoarea op?iunii de configurare default_charset.
5.4.43, 5.5.27, 5.6.11 | Exclamation marks are replaced by spaces.

A se vedea ?i

  • escapeshellcmd() - Escape shell metacharacters
  • exec() - Execute an external program
  • popen() - Opens process file pointer
  • system() - Execute an external program and display the output
  • backtick operator

Program execution Func?ii
escapeshellcmd
Program execution Func?ii


Escape shell metacharacters

escapeshellarg
exec
Program execution Func?ii
PHP Manual

escapeshellcmd

(PHP 4, PHP 5, PHP 7)

escapeshellcmd — Escape shell metacharacters

Descrierea

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 % and ! are replaced by a space instead.

Parametri

command

The command that will be escaped.

Valorile întoarse

The escaped string.

Exemple

Example #1 escapeshellcmd() example

<?php
// We allow arbitrary number of arguments intentionally here.
$command = './configure '.$_POST['configure_options'];

$escaped_command = escapeshellcmd($command);

system($escaped_command);
?>

Avertizare

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.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Valoarea implicita a parametrului encoding a fost schimbata pentru a coincide cu valoarea op?iunii de configurare default_charset.
5.4.43, 5.5.27, 5.6.11 | Exclamation marks are replaced by spaces.

A se vedea ?i

  • escapeshellarg() - Escape a string to be used as a shell argument
  • exec() - Execute an external program
  • popen() - Opens process file pointer
  • system() - Execute an external program and display the output
  • backtick operator

escapeshellarg
exec
Program execution Func?ii


Execute an external program

escapeshellcmd
passthru
Program execution Func?ii
PHP Manual

exec

(PHP 4, PHP 5, PHP 7)

exec — Execute an external program

Descrierea

string exec ( string $command [, array &$output [, int &$return_var ]] )

exec() executes the given command.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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');
?>

Note

Avertizare

Când se permite ca datele introduse de utilizatori sa fie transmise acestei func?ii, utiliza?i escapeshellarg() sau escapeshellcmd() pentru a va asigura ca utilizatorii nu vor pacali sistemul sa execute comenzi arbitrare.

Nota:

Daca un program este lansat în execu?ie cu ajutorul acestei func?ii, pentru ca el sa continue sa ruleze în fundal, ie?irile acelui program trebuie redirec?ionate spre un fi?ier sau spre un alt flux de ie?ire. În caz contrar, PHP se va suspenda pâna când execu?ia programului se va încheia.

Nota: Când este activat modul securizat, pute?i executa fi?ierele aflate în safe_mode_exec_dir. Din motive practice, în prezent nu se permite de a avea componente .. în calea catre executabil.

Avertizare

Când este activat modul securizat, linia de comanda este prelucrata cu escapeshellcmd(). De aceea, echo y | echo x devine echo y \| echo x .

A se vedea ?i

  • 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 Func?ii


Execute an external program and display raw output

exec
proc_close
Program execution Func?ii
PHP Manual

passthru

(PHP 4, PHP 5, PHP 7)

passthru — Execute an external program and display raw output

Descrierea

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.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Avertizare

Când se permite ca datele introduse de utilizatori sa fie transmise acestei func?ii, utiliza?i escapeshellarg() sau escapeshellcmd() pentru a va asigura ca utilizatorii nu vor pacali sistemul sa execute comenzi arbitrare.

Nota:

Daca un program este lansat în execu?ie cu ajutorul acestei func?ii, pentru ca el sa continue sa ruleze în fundal, ie?irile acelui program trebuie redirec?ionate spre un fi?ier sau spre un alt flux de ie?ire. În caz contrar, PHP se va suspenda pâna când execu?ia programului se va încheia.

Nota: Când este activat modul securizat, pute?i executa fi?ierele aflate în safe_mode_exec_dir. Din motive practice, în prezent nu se permite de a avea componente .. în calea catre executabil.

Avertizare

Când este activat modul securizat, linia de comanda este prelucrata cu escapeshellcmd(). De aceea, echo y | echo x devine echo y \| echo x .

A se vedea ?i

  • exec() - Execute an external program
  • system() - Execute an external program and display the output
  • popen() - Opens process file pointer
  • escapeshellcmd() - Escape shell metacharacters
  • backtick operator

exec
proc_close
Program execution Func?ii


Close a process opened by proc_open and return the exit code of that process

passthru
proc_get_status
Program execution Func?ii
PHP Manual

proc_close

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

proc_close — Close a process opened by proc_open() and return the exit code of that process

Descrierea

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.

Parametri

process

The proc_open() resource that will be closed.

Valorile întoarse

Returns the termination status of the process that was run. In case of an error then -1 is returned.

Nota:

If PHP has been compiled with --enable-sigchild, the return value of this function is undefined.

passthru
proc_get_status
Program execution Func?ii


Get information about a process opened by proc_open

proc_close
proc_nice
Program execution Func?ii
PHP Manual

proc_get_status

(PHP 5, PHP 7)

proc_get_status — Get information about a process opened by proc_open()

Descrierea

array proc_get_status ( resource $process )

proc_get_status() fetches data about a process opened using proc_open().

Parametri

process

The proc_open() resource that will be evaluated.

Valorile întoarse

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).

A se vedea ?i

  • proc_open() - Execute a command and open file pointers for input/output

proc_close
proc_nice
Program execution Func?ii


Change the priority of the current process

proc_get_status
proc_open
Program execution Func?ii
PHP Manual

proc_nice

(PHP 5, PHP 7)

proc_nice — Change the priority of the current process

Descrierea

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.

Parametri

increment

The new priority value, the value of this may differ on platforms.

on Unix, a low value, such as -20 means high priority wheras a positive value have a lower priority.

For Windows the increment parameter have the following meanings:

Priority class | Possible values
High priority | increment < -9
Above normal priority | increment < -4
Normal priority | increment < 5 & increment > -5
Below normal priority | increment > 5
Idle priority | increment > 9

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. If an error occurs, like the user lacks permission to change the priority, an error of level E_WARNING is also generated.

Exemple

Example #1 Using proc_open() to set the process priority to high

<?php
// Highest priority
proc_nice(-20);
?>

Istoricul schimbarilor

Versiune | Descriere
7.2.0 | This function is now available on Windows.

Note

Nota: 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.

Nota: Windows only

proc_nice() will change the current process priority, even if PHP was compiled using thread safety.

proc_get_status
proc_open
Program execution Func?ii


Execute a command and open file pointers for input/output

proc_nice
proc_terminate
Program execution Func?ii
PHP Manual

proc_open

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

proc_open — Execute a command and open file pointers for input/output

Descrierea

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.

Parametri

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

Valorile întoarse

Returns a resource representing the process, which should be freed using proc_close() when you are finished with it. On failure returns FALSE.

Istoricul schimbarilor

Versiune | Descriere
5.2.1 | Added the bypass_shell option to the other_options parameter.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [some_option] => aeiou
    [PWD] => /tmp
    [SHLVL] => 1
    [_] => /usr/local/bin/php
)
command returned 0

Note

Nota:

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.

Nota:

If you only need a uni-directional (one-way) process pipe, use popen() instead, as it is much easier to use.

A se vedea ?i

  • popen() - Opens process file pointer
  • 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 Func?ii


Kills a process opened by proc_open

proc_open
shell_exec
Program execution Func?ii
PHP Manual

proc_terminate

(PHP 5, PHP 7)

proc_terminate — Kills a process opened by proc_open

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the termination status of the process that was run.

Istoricul schimbarilor

Versiune | Descriere
5.2.2 | Previous versions used to destroy the given process resource.

A se vedea ?i

  • 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 Func?ii


Execute command via shell and return the complete output as a string

proc_terminate
system
Program execution Func?ii
PHP Manual

shell_exec

(PHP 4, PHP 5, PHP 7)

shell_exec — Execute command via shell and return the complete output as a string

Descrierea

string shell_exec ( string $cmd )

This function is identical to the backtick operator.

Parametri

cmd

The command that will be executed.

Valorile întoarse

The output from the executed command or NULL if an error occurred or the command produces no output.

Nota:

This function can return NULL both when an error occurs or the program produces no output. It is not possible to detect execution failures using this function. exec() should be used when access to the program exit code is required.

Exemple

Example #1 A shell_exec() example

<?php
$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";
?>

Note

Nota:

Aceasta func?ie este dezactivata atunci când PHP ruleaza în modul securizat.

A se vedea ?i

  • exec() - Execute an external program
  • escapeshellcmd() - Escape shell metacharacters

proc_terminate
system
Program execution Func?ii


Execute an external program and display the output

shell_exec
pthreads
Program execution Func?ii
PHP Manual

system

(PHP 4, PHP 5, PHP 7)

system — Execute an external program and display the output

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the last line of the command output on success, and FALSE on failure.

Exemple

Example #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;
?>

Note

Avertizare

Când se permite ca datele introduse de utilizatori sa fie transmise acestei func?ii, utiliza?i escapeshellarg() sau escapeshellcmd() pentru a va asigura ca utilizatorii nu vor pacali sistemul sa execute comenzi arbitrare.

Nota:

Daca un program este lansat în execu?ie cu ajutorul acestei func?ii, pentru ca el sa continue sa ruleze în fundal, ie?irile acelui program trebuie redirec?ionate spre un fi?ier sau spre un alt flux de ie?ire. În caz contrar, PHP se va suspenda pâna când execu?ia programului se va încheia.

Nota: Când este activat modul securizat, pute?i executa fi?ierele aflate în safe_mode_exec_dir. Din motive practice, în prezent nu se permite de a avea componente .. în calea catre executabil.

Avertizare

Când este activat modul securizat, linia de comanda este prelucrata cu escapeshellcmd(). De aceea, echo y | echo x devine echo y \| echo x .

A se vedea ?i

  • exec() - Execute an external program
  • passthru() - Execute an external program and display raw output
  • popen() - Opens process file pointer
  • escapeshellcmd() - Escape shell metacharacters
  • pcntl_exec() - Executes specified program in current process space
  • backtick operator

shell_exec
pthreads
Program execution Func?ii


pthreads

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
  • Constante predefinite
  • Threaded — The Threaded class
    • Threaded::chunk — Manipulation
    • Threaded::count — Manipulation
    • Threaded::extend — Runtime Manipulation
    • Threaded::from — Creation
    • Threaded::getTerminationInfo — Error Detection
    • Threaded::isRunning — State Detection
    • Threaded::isTerminated — State Detection
    • Threaded::isWaiting — State Detection
    • Threaded::lock — Synchronization
    • Threaded::merge — Manipulation
    • Threaded::notify — Synchronization
    • Threaded::pop — Manipulation
    • Threaded::run — Execution
    • Threaded::shift — Manipulation
    • Threaded::synchronized — Synchronization
    • Threaded::unlock — Synchronization
    • Threaded::wait — Synchronization
  • Thread — The Thread class
    • Thread::detach — Execution
    • Thread::getCreatorId — Identification
    • Thread::getCurrentThread — Identification
    • Thread::getCurrentThreadId — Identification
    • Thread::getThreadId — Identification
    • Thread::globally — Execution
    • Thread::isJoined — State Detection
    • Thread::isStarted — State Detection
    • Thread::join — Synchronization
    • Thread::kill — Execution
    • Thread::start — Execution
  • Worker — The Worker class
    • Worker::collect — Collect references to completed tasks
    • Worker::getStacked — Gets the remaining stack size
    • Worker::isShutdown — State Detection
    • Worker::isWorking — State Detection
    • Worker::shutdown — Shutdown the worker
    • Worker::stack — Stacking work
    • Worker::unstack — Unstacking work
  • Collectable — The Collectable interface
    • Collectable::isGarbage — Determine whether an object has been marked as garbage
    • Collectable::setGarbage — Mark an object as garbage
  • Modifiers — Method Modifiers
  • Pool — The Pool class
    • Pool::collect — Collect references to completed tasks
    • Pool::__construct — Creates a new Pool of Workers
    • Pool::resize — Resize the Pool
    • Pool::shutdown — Shutdown all workers
    • Pool::submit — Submits an object for execution
    • Pool::submitTo — Submits a task to a specific worker for execution
  • Mutex — The Mutex class
    • Mutex::create — Create a Mutex
    • Mutex::destroy — Destroy Mutex
    • Mutex::lock — Acquire Mutex
    • Mutex::trylock — Attempt to Acquire Mutex
    • Mutex::unlock — Release Mutex
  • Cond — The Cond class
    • Cond::broadcast — Broadcast a Condition
    • Cond::create — Create a Condition
    • Cond::destroy — Destroy a Condition
    • Cond::signal — Signal a Condition
    • Cond::wait — Wait for Condition
system
Introducere
Extensii de control al proceselor


Introducere

pthreads is an object-orientated API that provides all of the tools needed for multi-threading in PHP. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects.

Avertizare

The pthreads extension cannot be used in a web server environment. Threading in PHP should therefore remain to CLI-based applications only.

The Threaded class forms the basis of the functionality that allows pthreads to operate. It exposes synchronization methods and some useful interfaces for the programmer.

The Thread class enables for threads to be created by simply extending it and implementing a run method. Any members can be written to and read by any context with a reference to the thread. Any context can also execute any public and protected methods. The body of the run method will be executed in a separate thread when the Thread::start() method of the implementation is called from the context that created it. Only the context that creates a thread can start and join it.

The Worker class has a persistent state, and will be available from the call to Thread::start() (an inherited method) until the object goes out of scope, or is explicitly shutdown (via Worker::shutdown()). Any context with a reference to the worker object can stack tasks onto the Worker (via Worker::stack()), where these tasks will be executed by the worker in a separate thread. The run method of a worker object will be executed before any objects on the worker's stack, enabling for resources to be initialized that the objects to be executed may need.

The Pool class is used to create a group of workers to distribute Threaded objects amongst them. It is the easiest and most efficient way of using multiple threads in PHP applications.

Precautie

The Pool class does not extend the Threaded class, and so pool-based objects are considered a normal PHP objects. As such, its instances of it should not be shared amongst different contexts.

The Volatile class is new to pthreads v3. It is used to denote mutable Threaded properties of Threaded classes (since these are now immutable by default).

Synchronization is an important ability when threading. All of the objects that pthreads creates have built in synchronization in the (which will be familiar to java programmers) form of Threaded::wait() and Threaded::notify(). Calling Threaded::wait() on an object will cause the context to wait for another context to call Threaded::notify() on the same object. This mechanism allows for powerful synchronization between Threaded objects in PHP.

Precautie

Any objects that are intended for use in the multi-threaded parts of your application should extend Threaded.

Method Modifiers: The protected methods of Threaded Objects are protected by pthreads, such that only one context may call that method at a time. The private methods of Threaded Objects can only be called from within the Threaded Object during execution.

Data Storage: As a rule of thumb, any data type that can be serialized can be used as a member of a Threaded object, it can be read and written from any context with a reference to the Threaded Object. Not every type of data is stored serially, basic types are stored in their true form. Complex types, Arrays, and Objects that are not Threaded are stored serially; they can be read and written to the Threaded Object from any context with a reference. With the exception of Threaded Objects any reference used to set a member of a Threaded Object is separated from the reference in the Threaded Object; the same data can be read directly from the Threaded Object at any time by any context with a reference to the Threaded Object.

Static Members: When a new context is created ( Thread or Worker ), they are generally copied, but resources and objects with internal state are nullified (for safety reasons). This allows them to function as a kind of thread local storage. For example, upon starting the context, a class whose static members include connection information for a database server, and the connection itself, will only have the simple connection information copied, not the connection. Allowing the new context to initiate a connection in the same way as the context that created it, storing the connection in the same place without affecting the original context.

Precautie

When print_r, var_dump and other object debug functions are executed, they do not include recursion protection.

Nota:

Resources: The extensions and functionality that define resources in PHP are completely unprepared for this kind of environment; pthreads makes provisions for Resources to be shared among contexts, however, for most types of resource it should be considered unsafe. Extreme caution and care should be used when sharing resources among contexts.

Precautie

In the environment which pthreads executes, some restrictions and limitations are necessary in order to provide a stable environment.

pthreads
Instalarea / configurarea
pthreads


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
Introducere
Necesita?i
pthreads


Necesita?i

pthreads requires a build of PHP with ZTS (Zend Thread Safety) enabled ( --enable-maintainer-zts or --enable-zts on Windows )

Precautie

Zend Thread Safety cannot be enabled post build; it is a build time configuration option.

pthreads should build anywhere there is a working Posix Threads header (pthread.h) and ZTS build of PHP, including Windows (using the pthread-w32 project from redhat).

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

pthreads releases are hosted by PECL and the source code by » github, the easiest route to installation is the normal PECL route: » http://pecl.php.net/package/pthreads.

Windows users can download prebuilt release binaries from the » PECL website.

Precautie

Windows users need to take the additional step of adding pthreadVC2.dll (distributed with Windows releases) to their PATH.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

PTHREADS_INHERIT_ALL (integer)
The default options for all Threads, causes pthreads to copy the environment when new Threads are started
PTHREADS_INHERIT_NONE (integer)
Do not inherit anything when new Threads are started
PTHREADS_INHERIT_INI (integer)
Inherit INI entries when new Threads are started
PTHREADS_INHERIT_CONSTANTS (integer)
Inherit user declared constants when new Threads are started
PTHREADS_INHERIT_CLASSES (integer)
Inherit user declared classes when new Threads are started
PTHREADS_INHERIT_FUNCTIONS (integer)
Inherit user declared functions when new Threads are started
PTHREADS_INHERIT_INCLUDES (integer)
Inherit included file information when new Threads are started
PTHREADS_INHERIT_COMMENTS (integer)
Inherit all comments when new Threads are started
PTHREADS_ALLOW_HEADERS (integer)
Allow new Threads to send headers to standard output (normally prohibited)

Configura?ia la rulare
Threaded
pthreads


The Threaded class

(PECL pthreads >= 2.0.0)

Introducere

Threaded objects form the basis of pthreads ability to execute user code in parallel; they expose synchronization methods and various useful interfaces.

Threaded objects, most importantly, provide implicit safety for the programmer; all operations on the object scope are safe.

Sinopsisul clasei

Threaded implements Traversable , Countable , ArrayAccess {
/* Metode */
public array chunk ( integer $size , boolean $preserve )
public integer count ( void )
public bool extend ( string $class )
public Threaded from ( Closure $run [, Closure $construct [, array $args ]] )
public array getTerminationInfo ( void )
public boolean isRunning ( void )
public boolean isTerminated ( void )
public boolean isWaiting ( void )
public boolean lock ( void )
public boolean merge ( mixed $from [, bool $overwrite ] )
public boolean notify ( void )
public boolean pop ( void )
public void run ( void )
public mixed shift ( void )
public mixed synchronized ( Closure $block [, mixed $... ] )
public boolean unlock ( void )
public boolean wait ([ integer $timeout ] )
}

Cuprins

  • Threaded::chunk — Manipulation
  • Threaded::count — Manipulation
  • Threaded::extend — Runtime Manipulation
  • Threaded::from — Creation
  • Threaded::getTerminationInfo — Error Detection
  • Threaded::isRunning — State Detection
  • Threaded::isTerminated — State Detection
  • Threaded::isWaiting — State Detection
  • Threaded::lock — Synchronization
  • Threaded::merge — Manipulation
  • Threaded::notify — Synchronization
  • Threaded::pop — Manipulation
  • Threaded::run — Execution
  • Threaded::shift — Manipulation
  • Threaded::synchronized — Synchronization
  • Threaded::unlock — Synchronization
  • Threaded::wait — Synchronization
Constante predefinite
Threaded::chunk
pthreads


Manipulation

Threaded
Threaded::count
Threaded
PHP Manual

Threaded::chunk

(PECL pthreads >= 2.0.0)

Threaded::chunk — Manipulation

Descrierea

public array Threaded::chunk ( integer $size , boolean $preserve )

Fetches a chunk of the objects property table of the given size, optionally preserving keys

Parametri

size

The number of items to fetch

preserve

Preserve the keys of members, by default false

Valorile întoarse

An array of items from the objects property table

Exemple

Example #1 Fetch a chunk of the property table

<?php
$safe = new Threaded();

while (count($safe) < 10) {
    $safe[] = count($safe);
}

var_dump($safe->chunk(5));
?>

Exemplul de mai sus va afi?a:

array(5) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
}

Threaded
Threaded::count
Threaded


Manipulation

Threaded::chunk
Threaded::extend
Threaded
PHP Manual

Threaded::count

(PECL pthreads >= 2.0.0)

Threaded::count — Manipulation

Descrierea

public integer Threaded::count ( void )

Returns the number of properties for this object

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #1 Counting the properties of an object

<?php
$safe = new Threaded();

while (count($safe) < 10) {
    $safe[] = count($safe);
}

var_dump(count($safe));
?>

Exemplul de mai sus va afi?a:

int(10)

Threaded::chunk
Threaded::extend
Threaded


Runtime Manipulation

Threaded::count
Threaded::from
Threaded
PHP Manual

Threaded::extend

(PECL pthreads >= 2.0.8)

Threaded::extend — Runtime Manipulation

Descrierea

public bool Threaded::extend ( string $class )

Makes thread safe standard class at runtime

Parametri

class

The class to extend

Valorile întoarse

A boolean indication of success

Exemple

Example #1 Runtime inheritance

<?php
class My {}

Threaded::extend(My::class);

$my = new My();

var_dump($my instanceof Threaded);
?>

Exemplul de mai sus va afi?a:

bool(true)

Threaded::count
Threaded::from
Threaded


Creation

Threaded::extend
Threaded::getTerminationInfo
Threaded
PHP Manual

Threaded::from

(PECL pthreads >= 2.0.9)

Threaded::from — Creation

Avertizare

This method has been removed in pthreads v3.

Descrierea

public Threaded Threaded::from ( Closure $run [, Closure $construct [, array $args ]] )

Creates an anonymous Threaded object from closures

Parametri

run

The closure to use for ::run

construct

The constructor to use for anonymous object

args

The arguments to pass to constructor

Valorile întoarse

A new anonymous Threaded object

Exemple

Example #1 Thread safe objects from closures

<?php
$pool = new Pool(4);
$pool->submit(Collectable::from(function(){
    echo "Hello World";
    $this->setGarbage();
}));
/* ... */
$pool->shutdown();
?>

Exemplul de mai sus va afi?a:

Hello World

Threaded::extend
Threaded::getTerminationInfo
Threaded


Error Detection

Threaded::from
Threaded::isRunning
Threaded
PHP Manual

Threaded::getTerminationInfo

(PECL pthreads < 3.0.0)

Threaded::getTerminationInfo — Error Detection

Avertizare

This method has been removed in pthreads v3.

Descrierea

public array Threaded::getTerminationInfo ( void )

Retrieves terminal error information from the referenced object

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

array containing the termination conditions of the referenced object

Exemple

Example #1 Detecting fatal errors in Threads

<?php
class My extends Thread {
    public function run() {
        @not_found();
    }
}

$my = new My();
$my->start();
$my->join();

var_dump($my->isTerminated(), $my->getTerminationInfo());
?>

Exemplul de mai sus va afi?a:

bool(true)
array(4) {
  ["scope"]=>
  string(2) "My"
  ["function"]=>
  string(3) "run"
  ["file"]=>
  string(29) "/usr/src/pthreads/sandbox.php"
  ["line"]=>
  int(4)
}

Threaded::from
Threaded::isRunning
Threaded


State Detection

Threaded::getTerminationInfo
Threaded::isTerminated
Threaded
PHP Manual

Threaded::isRunning

(PECL pthreads >= 2.0.0)

Threaded::isRunning — State Detection

Descrierea

public boolean Threaded::isRunning ( void )

Tell if the referenced object is executing

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean indication of state

Nota:

A object is considered running while executing the run method

Exemple

Example #1 Detect the state of the referenced object

<?php
class My extends Thread {
    public function run() {
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
var_dump($my->isRunning());
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
?>

Exemplul de mai sus va afi?a:

bool(true)

Threaded::getTerminationInfo
Threaded::isTerminated
Threaded


State Detection

Threaded::isRunning
Threaded::isWaiting
Threaded
PHP Manual

Threaded::isTerminated

(PECL pthreads >= 2.0.0)

Threaded::isTerminated — State Detection

Descrierea

public boolean Threaded::isTerminated ( void )

Tell if the referenced object was terminated during execution; suffered fatal errors, or threw uncaught exceptions

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean indication of state

Exemple

Example #1 Detect the state of the referenced object

<?php
class My extends Thread {
    public function run() {
        i_do_not_exist();
    }
}
$my = new My();
$my->start();
$my->join();
var_dump($my->isTerminated());
?>

Exemplul de mai sus va afi?a:

bool(true)

Threaded::isRunning
Threaded::isWaiting
Threaded


State Detection

Threaded::isTerminated
Threaded::lock
Threaded
PHP Manual

Threaded::isWaiting

(PECL pthreads < 3.0.0)

Threaded::isWaiting — State Detection

Avertizare

This method has been removed in pthreads v3.

Descrierea

public boolean Threaded::isWaiting ( void )

Tell if the referenced object is waiting for notification

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean indication of state

Exemple

Example #1 Detect the state of the referenced object

<?php
class My extends Thread {
    public function run() {
        $this->synchronized(function($thread){
            if (!$this->done)
                $thread->wait();
        }, $this);
    }

    protected $done;
}
$my = new My();
$my->start();
$my->synchronized(function($thread){
    var_dump(
        $thread->isWaiting());
    $thread->done = true;
    $thread->notify();
}, $my);
?>

Exemplul de mai sus va afi?a:

bool(true)

Threaded::isTerminated
Threaded::lock
Threaded


Synchronization

Threaded::isWaiting
Threaded::merge
Threaded
PHP Manual

Threaded::lock

(PECL pthreads < 3.0.0)

Threaded::lock — Synchronization

Avertizare

This method has been removed in pthreads v3.

Descrierea

public boolean Threaded::lock ( void )

Lock the referenced objects property table

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean indication of success

Exemple

Example #1 Locking Object Properties

<?php
class My extends Thread {
    public function run() {
        var_dump($this->lock());
        /** nobody can read or write **/
        var_dump($this->unlock());
        /** reading / writing resumed for all other contexts */
    }
}
$my = new My();
$my->start();
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)

Threaded::isWaiting
Threaded::merge
Threaded


Manipulation

Threaded::lock
Threaded::notify
Threaded
PHP Manual

Threaded::merge

(PECL pthreads >= 2.0.0)

Threaded::merge — Manipulation

Descrierea

public boolean Threaded::merge ( mixed $from [, bool $overwrite ] )

Merges data into the current object

Parametri

from

The data to merge

overwrite

Overwrite existing keys, by default true

Valorile întoarse

A boolean indication of success

Exemple

Example #1 Merging into the property table of a threaded object

<?php
$array = [];

while (count($array) < 10)
    $array[] = count($array);

$stdClass = new stdClass();
$stdClass->foo = "foo";
$stdClass->bar = "bar";
$stdClass->baz = "baz";

$safe = new Threaded();
$safe->merge($array);

$safe->foo = "bar";
$safe->merge($stdClass, false);

var_dump($safe);
?>

Exemplul de mai sus va afi?a:

object(Threaded)#2 (13) {
  ["0"]=>
  int(0)
  ["1"]=>
  int(1)
  ["2"]=>
  int(2)
  ["3"]=>
  int(3)
  ["4"]=>
  int(4)
  ["5"]=>
  int(5)
  ["6"]=>
  int(6)
  ["7"]=>
  int(7)
  ["8"]=>
  int(8)
  ["9"]=>
  int(9)
  ["foo"]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "bar"
  ["baz"]=>
  string(3) "baz"
}

Threaded::lock
Threaded::notify
Threaded


Synchronization

Threaded::merge
Threaded::pop
Threaded
PHP Manual

Threaded::notify

(PECL pthreads >= 2.0.0)

Threaded::notify — Synchronization

Descrierea

public boolean Threaded::notify ( void )

Send notification to the referenced object

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean indication of success

Exemple

Example #1 Notifications and Waiting

<?php
class My extends Thread {
    public function run() {
        /** cause this thread to wait **/
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
/** send notification to the waiting thread **/
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
var_dump($my->join());
?>

Exemplul de mai sus va afi?a:

bool(true)

Threaded::merge
Threaded::pop
Threaded


Manipulation

Threaded::notify
Threaded::run
Threaded
PHP Manual

Threaded::pop

(PECL pthreads >= 2.0.0)

Threaded::pop — Manipulation

Descrierea

public boolean Threaded::pop ( void )

Pops an item from the objects property table

Valorile întoarse

The last item from the objects property table

Exemple

Example #1 Popping the last item from the property table of a threaded object

<?php
$safe = new Threaded();

while (count($safe) < 10)
    $safe[] = count($safe);

var_dump($safe->pop());
?>

Exemplul de mai sus va afi?a:

int(9)

Threaded::notify
Threaded::run
Threaded


Execution

Threaded::pop
Threaded::shift
Threaded
PHP Manual

Threaded::run

(PECL pthreads >= 2.0.0)

Threaded::run — Execution

Descrierea

public void Threaded::run ( void )

The programmer should always implement the run method for objects that are intended for execution.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The methods return value, if used, will be ignored

Threaded::pop
Threaded::shift
Threaded


Manipulation

Threaded::run
Threaded::synchronized
Threaded
PHP Manual

Threaded::shift

(PECL pthreads >= 2.0.0)

Threaded::shift — Manipulation

Descrierea

public mixed Threaded::shift ( void )

Shifts an item from the objects property table

Valorile întoarse

The first item from the objects property table

Exemple

Example #1 Shifting the first item from the property table of a threaded object

<?php
$safe = new Threaded();

while (count($safe) < 10)
    $safe[] = count($safe);

var_dump($safe->shift());
?>

Exemplul de mai sus va afi?a:

int(0)

Threaded::run
Threaded::synchronized
Threaded


Synchronization

Threaded::shift
Threaded::unlock
Threaded
PHP Manual

Threaded::synchronized

(PECL pthreads >= 2.0.0)

Threaded::synchronized — Synchronization

Descrierea

public mixed Threaded::synchronized ( Closure $block [, mixed $... ] )

Executes the block while retaining the referenced objects synchronization lock for the calling context

Parametri

block

The block of code to execute

...

Variable length list of arguments to use as function arguments to the block

Valorile întoarse

The return value from the block

Exemple

Example #1 Synchronizing

<?php
class My extends Thread {
    public function run() {
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
var_dump($my->join());
?>

Exemplul de mai sus va afi?a:

bool(true)

Threaded::shift
Threaded::unlock
Threaded


Synchronization

Threaded::synchronized
Threaded::wait
Threaded
PHP Manual

Threaded::unlock

(PECL pthreads < 3.0.0)

Threaded::unlock — Synchronization

Avertizare

This method has been removed in pthreads v3.

Descrierea

public boolean Threaded::unlock ( void )

Unlock the referenced objects storage for the calling context

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean indication of success

Exemple

Example #1 Locking the property table of a threaded object

<?php
class My extends Thread {
    public function run() {
        var_dump($this->lock());
        /** nobody can read or write **/
        var_dump($this->unlock());
        /** reading / writing resumed for all other contexts */
    }
}
$my = new My();
$my->start();
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)

Threaded::synchronized
Threaded::wait
Threaded


Synchronization

Threaded::unlock
Thread
Threaded
PHP Manual

Threaded::wait

(PECL pthreads >= 2.0.0)

Threaded::wait — Synchronization

Descrierea

public boolean Threaded::wait ([ integer $timeout ] )

Will cause the calling context to wait for notification from the referenced object

Parametri

timeout

An optional timeout in microseconds

Valorile întoarse

A boolean indication of success

Exemple

Example #1 Notifications and Waiting

<?php
class My extends Thread {
    public function run() {
        /** cause this thread to wait **/
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
/** send notification to the waiting thread **/
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
var_dump($my->join());
?>

Exemplul de mai sus va afi?a:

bool(true)

Threaded::unlock
Thread
Threaded


The Thread class

(PECL pthreads >= 2.0.0)

Introducere

When the start method of a Thread is invoked, the run method code will be executed in separate Thread, in parallel.

After the run method is executed the Thread will exit immediately, it will be joined with the creating Thread at the appropriate time.

Avertizare

Relying on the engine to determine when a Thread should join may cause undesirable behaviour; the programmer should be explicit, where possible.

Sinopsisul clasei

Thread extends Threaded implements Countable , Traversable , ArrayAccess {
/* Metode */
public void detach ( void )
public integer getCreatorId ( void )
public static Thread getCurrentThread ( void )
public static integer getCurrentThreadId ( void )
public integer getThreadId ( void )
public static mixed globally ( void )
public boolean isJoined ( void )
public boolean isStarted ( void )
public boolean join ( void )
public void kill ( void )
public boolean start ([ integer $options ] )
/* Metode mo?tenite */
public array Threaded::chunk ( integer $size , boolean $preserve )
public integer Threaded::count ( void )
public bool Threaded::extend ( string $class )
public Threaded Threaded::from ( Closure $run [, Closure $construct [, array $args ]] )
public array Threaded::getTerminationInfo ( void )
public boolean Threaded::isRunning ( void )
public boolean Threaded::isTerminated ( void )
public boolean Threaded::isWaiting ( void )
public boolean Threaded::lock ( void )
public boolean Threaded::merge ( mixed $from [, bool $overwrite ] )
public boolean Threaded::notify ( void )
public boolean Threaded::pop ( void )
public void Threaded::run ( void )
public mixed Threaded::shift ( void )
public mixed Threaded::synchronized ( Closure $block [, mixed $... ] )
public boolean Threaded::unlock ( void )
public boolean Threaded::wait ([ integer $timeout ] )
}

Cuprins

  • Thread::detach — Execution
  • Thread::getCreatorId — Identification
  • Thread::getCurrentThread — Identification
  • Thread::getCurrentThreadId — Identification
  • Thread::getThreadId — Identification
  • Thread::globally — Execution
  • Thread::isJoined — State Detection
  • Thread::isStarted — State Detection
  • Thread::join — Synchronization
  • Thread::kill — Execution
  • Thread::start — Execution
Threaded::wait
Thread::detach
pthreads


Execution

Thread
Thread::getCreatorId
Thread
PHP Manual

Thread::detach

(PECL pthreads < 3.0.0)

Thread::detach — Execution

Avertizare

This method has been removed in pthreads v3.

Descrierea

public void Thread::detach ( void )

Detaches the referenced Thread from the calling context, dangerous!

Avertizare

This method can cause undefined, unsafe behaviour. It should not usually be used, it is present for completeness and advanced use cases.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Thread
Thread::getCreatorId
Thread


Identification

Thread::detach
Thread::getCurrentThread
Thread
PHP Manual

Thread::getCreatorId

(PECL pthreads >= 2.0.0)

Thread::getCreatorId — Identification

Descrierea

public integer Thread::getCreatorId ( void )

Will return the identity of the Thread that created the referenced Thread

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A numeric identity

Exemple

Example #1 Return the identity of the Thread or Process that created the referenced Thread

<?php
class My extends Thread {
    public function run() {
        printf("%s created by Thread #%lu\n", __CLASS__, $this->getCreatorId());
    }
}
$my = new My();
$my->start();
?>

Exemplul de mai sus va afi?a:

My created by Thread #123456778899

Thread::detach
Thread::getCurrentThread
Thread


Identification

Thread::getCreatorId
Thread::getCurrentThreadId
Thread
PHP Manual

Thread::getCurrentThread

(PECL pthreads >= 2.0.0)

Thread::getCurrentThread — Identification

Descrierea

public static Thread Thread::getCurrentThread ( void )

Return a reference to the currently executing Thread

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An object representing the currently executing Thread

Exemple

Example #1 Return the currently executing Thread

<?php
class My extends Thread {
    public function run() {
        var_dump(Thread::getCurrentThread());
    }
}
$my = new My();
$my->start();
?>

Exemplul de mai sus va afi?a:

object(My)#2 (0) {
}

Thread::getCreatorId
Thread::getCurrentThreadId
Thread


Identification

Thread::getCurrentThread
Thread::getThreadId
Thread
PHP Manual

Thread::getCurrentThreadId

(PECL pthreads >= 2.0.0)

Thread::getCurrentThreadId — Identification

Descrierea

public static integer Thread::getCurrentThreadId ( void )

Will return the identity of the currently executing Thread

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A numeric identity

Exemple

Example #1 Return the identity of the currently executing Thread

<?php
class My extends Thread {
    public function run() {
        printf("%s is Thread #%lu\n", __CLASS__, Thread::getCurrentThreadId());
    }
}
$my = new My();
$my->start();
?>

Exemplul de mai sus va afi?a:

My is Thread #123456778899

Thread::getCurrentThread
Thread::getThreadId
Thread


Identification

Thread::getCurrentThreadId
Thread::globally
Thread
PHP Manual

Thread::getThreadId

(PECL pthreads >= 2.0.0)

Thread::getThreadId — Identification

Descrierea

public integer Thread::getThreadId ( void )

Will return the identity of the referenced Thread

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A numeric identity

Exemple

Example #1 Return the identity of the referenced Thread

<?php
class My extends Thread {
    public function run() {
        printf("%s is Thread #%lu\n", __CLASS__, $this->getThreadId());
    }
}
$my = new My();
$my->start();
?>

Exemplul de mai sus va afi?a:

My is Thread #123456778899

Thread::getCurrentThreadId
Thread::globally
Thread


Execution

Thread::getThreadId
Thread::isJoined
Thread
PHP Manual

Thread::globally

(PECL pthreads < 3.0.0)

Thread::globally — Execution

Avertizare

This method has been removed in pthreads v3.

Descrierea

public static mixed Thread::globally ( void )

Will execute a Callable in the global scope

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The return value of the Callable

Exemple

Example #1 Execute in the global scope

<?php
class My extends Thread {
    public function run() {
        global $std;

        Thread::globally(function(){
            $std = new stdClass;
        });

        var_dump($std);
    }
}
$my = new My();
$my->start();
?>

Exemplul de mai sus va afi?a:

object(stdClass)#3 (0) {
}

Thread::getThreadId
Thread::isJoined
Thread


State Detection

Thread::globally
Thread::isStarted
Thread
PHP Manual

Thread::isJoined

(PECL pthreads >= 2.0.0)

Thread::isJoined — State Detection

Descrierea

public boolean Thread::isJoined ( void )

Tell if the referenced Thread has been joined

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean indication of state

Exemple

Example #1 Detect the state of the referenced Thread

<?php
class My extends Thread {
    public function run() {
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
var_dump($my->isJoined());
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
?>

Exemplul de mai sus va afi?a:

bool(false)

Thread::globally
Thread::isStarted
Thread


State Detection

Thread::isJoined
Thread::join
Thread
PHP Manual

Thread::isStarted

(PECL pthreads >= 2.0.0)

Thread::isStarted — State Detection

Descrierea

public boolean Thread::isStarted ( void )

Tell if the referenced Thread was started

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

boolean indication of state

Exemple

Example #1 Tell if the referenced Thread was started

<?php
$worker = new Worker();
$worker->start();
var_dump($worker->isStarted());
?>

Exemplul de mai sus va afi?a:

bool(true)

Thread::isJoined
Thread::join
Thread


Synchronization

Thread::isStarted
Thread::kill
Thread
PHP Manual

Thread::join

(PECL pthreads >= 2.0.0)

Thread::join — Synchronization

Descrierea

public boolean Thread::join ( void )

Causes the calling context to wait for the referenced Thread to finish executing

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean indication of success

Exemple

Example #1 Join with the referenced Thread

<?php
class My extends Thread {
    public function run() {
        /* ... */
    }
}
$my = new My();
$my->start();
/* ... */
var_dump($my->join());
/* ... */
?>

Exemplul de mai sus va afi?a:

bool(true)

Thread::isStarted
Thread::kill
Thread


Execution

Thread::join
Thread::start
Thread
PHP Manual

Thread::kill

(PECL pthreads < 3.0.0)

Thread::kill — Execution

Avertizare

This method has been removed in pthreads v3.

Descrierea

public void Thread::kill ( void )

Forces the referenced Thread to terminate

Avertizare

The programmer should not ordinarily kill Threads by force

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean indication of success

Exemple

Example #1 Kill the referenced Thread

<?php
class T extends Thread {
    public function run() {
        $stdin = fopen("php://stdin", "r");
        while(($line = fgets($stdin))) {
            echo $line;
        }
    }
}

$t = new T();
$t->start();

var_dump($t->kill());
?>

Exemplul de mai sus va afi?a:

bool(true)

Thread::join
Thread::start
Thread


Execution

Thread::kill
Worker
Thread
PHP Manual

Thread::start

(PECL pthreads >= 2.0.0)

Thread::start — Execution

Descrierea

public boolean Thread::start ([ integer $options ] )

Will start a new Thread to execute the implemented run method

Parametri

options

An optional mask of inheritance constants, by default PTHREADS_INHERIT_ALL

Valorile întoarse

A boolean indication of success

Exemple

Example #1 Starting Threads

<?php
class My extends Thread {
    public function run() {
        /** ... **/
    }
}
$my = new My();
var_dump($my->start());
?>

Exemplul de mai sus va afi?a:

bool(true)

Thread::kill
Worker
Thread


The Worker class

(PECL pthreads >= 2.0.0)

Introducere

Worker Threads have a persistent context, as such should be used over Threads in most cases.

When a Worker is started, the run method will be executed, but the Thread will not leave until one of the following conditions are met:

  • the Worker goes out of scope (no more references remain)

  • the programmer calls shutdown

  • the script dies

This means the programmer can reuse the context throughout execution; placing objects on the stack of the Worker will cause the Worker to execute the stacked objects run method.

Avertizare

The programmer must retain references to stacked objects until they are executed or unstacked; the Pool class provides a higher level abstraction of the Worker functionality and manages references for the programmer.

Sinopsisul clasei

Worker extends Thread implements Traversable , Countable , ArrayAccess {
/* Metode */
public int collect ([ Callable $collector ] )
public int getStacked ( void )
public bool isShutdown ( void )
public boolean isWorking ( void )
public bool shutdown ( void )
public int stack ( Threaded &$work )
public int unstack ( void )
/* Metode mo?tenite */
public void Thread::detach ( void )
public integer Thread::getCreatorId ( void )
public static Thread Thread::getCurrentThread ( void )
public static integer Thread::getCurrentThreadId ( void )
public integer Thread::getThreadId ( void )
public static mixed Thread::globally ( void )
public boolean Thread::isJoined ( void )
public boolean Thread::isStarted ( void )
public boolean Thread::join ( void )
public void Thread::kill ( void )
public boolean Thread::start ([ integer $options ] )
}

Cuprins

  • Worker::collect — Collect references to completed tasks
  • Worker::getStacked — Gets the remaining stack size
  • Worker::isShutdown — State Detection
  • Worker::isWorking — State Detection
  • Worker::shutdown — Shutdown the worker
  • Worker::stack — Stacking work
  • Worker::unstack — Unstacking work
Thread::start
Worker::collect
pthreads


Collect references to completed tasks

Worker
Worker::getStacked
Worker
PHP Manual

Worker::collect

(PECL pthreads >= 3.0.0)

Worker::collect — Collect references to completed tasks

Descrierea

public int Worker::collect ([ Callable $collector ] )

Allows the worker to collect references determined to be garbage by the optionally given collector.

Parametri

collector

A Callable collector that returns a boolean on whether the task can be collected or not. Only in rare cases should a custom collector need to be used.

Valorile întoarse

The number of remaining tasks on the worker's stack to be collected.

Exemple

Example #1 A basic example of Worker::collect()

<?php
$worker = new Worker();

echo "There are currently {$worker->collect()} tasks on the stack to be collected\n";

for ($i = 0; $i < 15; ++$i) {
    $worker->stack(new class extends Threaded {});
}

echo "There are {$worker->collect()} tasks remaining on the stack to be collected\n";

$worker->start();

while ($worker->collect()); // blocks until all tasks have finished executing

echo "There are now {$worker->collect()} tasks on the stack to be collected\n";

$worker->shutdown();

Exemplul de mai sus va afi?a:

There are currently 0 tasks on the stack to be collected
There are 15 tasks remaining on the stack to be collected
There are now 0 tasks on the stack to be collected

Worker
Worker::getStacked
Worker


Gets the remaining stack size

Worker::collect
Worker::isShutdown
Worker
PHP Manual

Worker::getStacked

(PECL pthreads >= 2.0.0)

Worker::getStacked — Gets the remaining stack size

Descrierea

public int Worker::getStacked ( void )

Returns the number of tasks left on the stack

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the number of tasks currently waiting to be executed by the worker

Exemple

Example #1 A basic example of Worker::getStacked

<?php
$worker = new Worker();

for ($i = 0; $i < 5; ++$i) {
    $worker->stack(new class extends Threaded {});
}

echo "There are {$worker->getStacked()} stacked tasks\n";

Exemplul de mai sus va afi?a:

There are 5 stacked tasks

Worker::collect
Worker::isShutdown
Worker


State Detection

Worker::getStacked
Worker::isWorking
Worker
PHP Manual

Worker::isShutdown

(PECL pthreads >= 2.0.0)

Worker::isShutdown — State Detection

Descrierea

public bool Worker::isShutdown ( void )

Whether the worker has been shutdown or not.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns whether the worker has been shutdown or not.

Exemple

Example #1 Detect the state of a worker

<?php
$worker = new Worker();
$worker->start();

var_dump($worker->isShutdown());

$worker->shutdown();

var_dump($worker->isShutdown());

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

Worker::getStacked
Worker::isWorking
Worker


State Detection

Worker::isShutdown
Worker::shutdown
Worker
PHP Manual

Worker::isWorking

(PECL pthreads >= 2.0.0)

Worker::isWorking — State Detection

Avertizare

This method has been removed in pthreads v3. The Worker::getStacked() method should be used to see if the worker still has tasks to execute.

Descrierea

public boolean Worker::isWorking ( void )

Tell if a Worker is executing Stackables

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean indication of state

Exemple

Example #1 Detect the state of a Worker

<?php
$my = new Worker();
$my->start();
/* ... */
if ($my->isWorking()) {
    /* ... the Worker is busy executing another object */
}
?>

Worker::isShutdown
Worker::shutdown
Worker


Shutdown the worker

Worker::isWorking
Worker::stack
Worker
PHP Manual

Worker::shutdown

(PECL pthreads >= 2.0.0)

Worker::shutdown — Shutdown the worker

Descrierea

public bool Worker::shutdown ( void )

Shuts down the worker after executing all of the stacked tasks.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Whether the worker was successfully shutdown or not.

Exemple

Example #1 Shutdown the referenced worker

<?php
$my = new Worker();
$my->start();
/* stack/execute tasks */
var_dump($my->shutdown());

Exemplul de mai sus va afi?a:

bool(true)

Worker::isWorking
Worker::stack
Worker


Stacking work

Worker::shutdown
Worker::unstack
Worker
PHP Manual

Worker::stack

(PECL pthreads >= 2.0.0)

Worker::stack — Stacking work

Descrierea

public int Worker::stack ( Threaded &$work )

Appends the new work to the stack of the referenced worker.

Parametri

work

A Threaded object to be executed by the worker.

Valorile întoarse

The new size of the stack.

Exemple

Example #1 Stacking a task for execution onto a worker

<?php
$worker = new Worker();
$work = new class extends Threaded {};

var_dump($worker->stack($work));

Exemplul de mai sus va afi?a:

int(1)

Worker::shutdown
Worker::unstack
Worker


Unstacking work

Worker::stack
Collectable
Worker
PHP Manual

Worker::unstack

(PECL pthreads >= 2.0.0)

Worker::unstack — Unstacking work

Descrierea

public int Worker::unstack ( void )

Removes the first task (the oldest one) in the stack.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The new size of the stack.

Istoricul schimbarilor

Versiune | Descriere
v3 | The parameter to specify the task to unstack has been removed. Now, only the first task in the stack is removed.

Exemple

Example #1 Removing objects from the stack of Workers

<?php
$my = new Worker();
$work = new class extends Threaded {};

var_dump($my->stack($work));
var_dump($my->unstack());

Exemplul de mai sus va afi?a:

int(1)
int(0)

Worker::stack
Collectable
Worker


The Collectable interface

(PECL pthreads >= 2.0.8)

Introducere

Precautie

Collectable was previously a class (in pthreads v2 and below). Now, it is an interface in pthreads v3 that is implemented by the Threaded class.

Represents a garbage-collectable object.

Descrierea succinta a interfe?ei

Collectable extends Threaded {
/* Metode */
public bool isGarbage ( void )
public void setGarbage ( void )
}

Cuprins

  • Collectable::isGarbage — Determine whether an object has been marked as garbage
  • Collectable::setGarbage — Mark an object as garbage
Worker::unstack
Collectable::isGarbage
pthreads


Determine whether an object has been marked as garbage

Collectable
Collectable::setGarbage
Collectable
PHP Manual

Collectable::isGarbage

(PECL pthreads >= 2.0.8)

Collectable::isGarbage — Determine whether an object has been marked as garbage

Descrierea

public bool Collectable::isGarbage ( void )

Can be called in Pool::collect() to determine if this object is garbage.

A se vedea ?i

  • Pool::collect() - Collect references to completed tasks

Collectable
Collectable::setGarbage
Collectable


Mark an object as garbage

Collectable::isGarbage
Modifiers
Collectable
PHP Manual

Collectable::setGarbage

(PECL pthreads < 3.0.0)

Collectable::setGarbage — Mark an object as garbage

Descrierea

public void Collectable::setGarbage ( void )

Should be called once per object when the object is finished being executed or referenced.

A se vedea ?i

  • Collectable::isGarbage() - Determine whether an object has been marked as garbage

Collectable::isGarbage
Modifiers
Collectable


Method Modifiers

pthreads overrides the functionality of the protected and private method modifiers in order to provide functionality more suited to multi-threaded objects. pthreads applies this functionality to all Threaded objects from creation.

Example #1 protected method example: protected methods can only be executed by one Thread at a time.

<?php
class ExampleThread extends Thread {
    public function run() {
        /* thread code */
        if ($this->synchronized()) {

        }
    }

    protected function exclusive() {
        /* synchronized method */
    }
}

$thread = new ExampleThread();
if ($thread->start()) {
    $thread->exclusive();
}
?>

Example #2 private method example: private methods may only be executed by the Threaded object during execution

<?php
class ExampleThread extends Thread {
    public function run() {
        /* thread code */
        if ($this->insideonly()) {

        }
    }

    private function insideonly() {
        /* private method */
    }
}

$thread = new ExampleThread();
if ($thread->start()) {
    $thread->insideonly();
}
?>
Collectable::setGarbage
Pool
pthreads


The Pool class

(PECL pthreads >= 2.0.0)

Introducere

A Pool is a container for, and controller of, an adjustable number of Workers.

Pooling provides a higher level abstraction of the Worker functionality, including the management of references in the way required by pthreads.

Sinopsisul clasei

Pool {
/* Proprieta?i */
protected $size ;
protected $class ;
protected $workers ;
protected $work ;
protected $ctor ;
protected $last ;
/* Metode */
public int collect ([ Callable $collector ] )
public Pool __construct ( integer $size [, string $class [, array $ctor ]] )
public void resize ( integer $size )
public void shutdown ( void )
public int submit ( Threaded $task )
public int submitTo ( int $worker , Threaded $task )
}

Proprieta?i

size

maximum number of Workers this Pool can use

class

the class of the Worker

ctor

the arguments for constructor of new Workers

workers

references to Workers

work

references to Threaded objects submitted to the Pool

last

offset in workers of the last Worker used

Cuprins

  • Pool::collect — Collect references to completed tasks
  • Pool::__construct — Creates a new Pool of Workers
  • Pool::resize — Resize the Pool
  • Pool::shutdown — Shutdown all workers
  • Pool::submit — Submits an object for execution
  • Pool::submitTo — Submits a task to a specific worker for execution
Modifiers
Pool::collect
pthreads


Collect references to completed tasks

Pool
Pool::__construct
Pool
PHP Manual

Pool::collect

(PECL pthreads >= 2.0.0)

Pool::collect — Collect references to completed tasks

Descrierea

public int Pool::collect ([ Callable $collector ] )

Allows the pool to collect references determined to be garbage by the optionally given collector.

Parametri

collector

A Callable collector that returns a boolean on whether the task can be collected or not. Only in rare cases should a custom collector need to be used.

Valorile întoarse

The number of remaining tasks in the pool to be collected.

Istoricul schimbarilor

Versiune | Descriere
v3 | An integer is now returned, and the collector parameter is now optional.

Exemple

Example #1 A basic example of Pool::collect()

<?php
$pool = new Pool(4);

for ($i = 0; $i < 15; ++$i) {
    $pool->submit(new class extends Threaded {});
}

while ($pool->collect()); // blocks until all tasks have finished executing

$pool->shutdown();

Pool
Pool::__construct
Pool


Creates a new Pool of Workers

Pool::collect
Pool::resize
Pool
PHP Manual

Pool::__construct

(PECL pthreads >= 2.0.0)

Pool::__construct — Creates a new Pool of Workers

Descrierea

public Pool Pool::__construct ( integer $size [, string $class [, array $ctor ]] )

Construct a new pool of workers. Pools lazily create their threads, which means new threads will only be spawned when they are required to execute tasks.

Parametri

size

The maximum number of workers for this pool to create

class

The class for new Workers. If no class is given, then it defaults to the Worker class.

ctor

An array of arguments to be passed to new workers' constructors

Valorile întoarse

The new pool

Exemple

Example #1 Creating Pools

<?php
class MyWorker extends Worker {

    public function __construct(Something $something) {
        $this->something = $something;
    }

    public function run() {
        /** ... **/
    }
}

$pool = new Pool(8, \MyWorker::class, [new Something()]);

var_dump($pool);
?>

Exemplul de mai sus va afi?a:

object(Pool)#1 (6) {
  ["size":protected]=>
  int(8)
  ["class":protected]=>
  string(8) "MyWorker"
  ["workers":protected]=>
  NULL
  ["work":protected]=>
  NULL
  ["ctor":protected]=>
  array(1) {
    [0]=>
    object(Something)#2 (0) {
    }
  }
  ["last":protected]=>
  int(0)
}

Pool::collect
Pool::resize
Pool


Resize the Pool

Pool::__construct
Pool::shutdown
Pool
PHP Manual

Pool::resize

(PECL pthreads >= 2.0.0)

Pool::resize — Resize the Pool

Descrierea

public void Pool::resize ( integer $size )

Resize the Pool

Parametri

size

The maximum number of Workers this Pool can create

Valorile întoarse

void

Pool::__construct
Pool::shutdown
Pool


Shutdown all workers

Pool::resize
Pool::submit
Pool
PHP Manual

Pool::shutdown

(PECL pthreads >= 2.0.0)

Pool::shutdown — Shutdown all workers

Descrierea

public void Pool::shutdown ( void )

Shuts down all of the workers in the pool. This will block until all submitted tasks have been executed.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

No value is returned.

Exemple

Example #1 Shutting down a pool

<?php
class Task extends Threaded
{
    public function run()
    {
        usleep(500000);
    }
}

$pool = new Pool(4);

for ($i = 0; $i < 10; ++$i) {
    $pool->submit(new Task());
}

$pool->shutdown(); // blocks until all submitted tasks have finished executing

Pool::resize
Pool::submit
Pool


Submits an object for execution

Pool::shutdown
Pool::submitTo
Pool
PHP Manual

Pool::submit

(PECL pthreads >= 2.0.0)

Pool::submit — Submits an object for execution

Descrierea

public int Pool::submit ( Threaded $task )

Submit the task to the next Worker in the Pool

Parametri

size

The task for execution

Valorile întoarse

the identifier of the Worker executing the object

Exemple

Example #1 Submitting Tasks

<?php
class MyWork extends Threaded {

    public function run() {
        /* ... */
    }
}

class MyWorker extends Worker {

    public function __construct(Something $something) {
        $this->something = $something;
    }

    public function run() {
        /** ... **/
    }
}

$pool = new Pool(8, \MyWorker::class, [new Something()]);
$pool->submit(new MyWork());
var_dump($pool);
?>

Exemplul de mai sus va afi?a:

object(Pool)#1 (6) {
  ["size":protected]=>
  int(8)
  ["class":protected]=>
  string(8) "MyWorker"
  ["workers":protected]=>
  array(1) {
    [0]=>
    object(MyWorker)#4 (1) {
      ["something"]=>
      object(Something)#5 (0) {
      }
    }
  }
  ["work":protected]=>
  array(1) {
    [0]=>
    object(MyWork)#3 (1) {
      ["worker"]=>
      object(MyWorker)#5 (1) {
        ["something"]=>
        object(Something)#6 (0) {
        }
      }
    }
  }
  ["ctor":protected]=>
  array(1) {
    [0]=>
    object(Something)#2 (0) {
    }
  }
  ["last":protected]=>
  int(1)
}

Pool::shutdown
Pool::submitTo
Pool


Submits a task to a specific worker for execution

Pool::submit
Mutex
Pool
PHP Manual

Pool::submitTo

(PECL pthreads >= 2.0.0)

Pool::submitTo — Submits a task to a specific worker for execution

Descrierea

public int Pool::submitTo ( int $worker , Threaded $task )

Submit a task to the specified worker in the pool. The workers are indexed from 0, and will only exist if the pool has needed to create them (since threads are lazily spawned).

Parametri

worker

The worker to stack the task onto, indexed from 0.

task

The task for execution.

Valorile întoarse

The identifier of the worker that accepted the task.

Exemple

Example #1 Submitting tasks to a specific worker

<?php
class Task extends Threaded {
    public function run() {
        var_dump(Thread::getCurrentThreadID());
    }
}

$pool = new Pool(2);

$pool->submit(new Task());

for ($i = 0; $i < 5; ++$i) {
    $pool->submitTo(0, new Task()); // stack all tasks onto the first worker
}

$pool->submitTo(1, new Task()); // cannot stack the task onto the second worker due to it not existing yet

$pool->shutdown();

Exemplul de mai sus va afi?a:

int(4475011072)
int(4475011072)
int(4475011072)
int(4475011072)
int(4475011072)
int(4475011072)

Fatal error: Uncaught Exception: The selected worker (1) does not exist in %s:%d

Pool::submit
Mutex
Pool


The Mutex class

(PECL pthreads < 3.0.0)

Introducere

Avertizare

The Mutex class has been removed in pthreads v3.

The static methods contained in the Mutex class provide direct access to Posix Mutex functionality.

Sinopsisul clasei

Mutex {
/* Metode */
final public static long create ([ boolean $lock ] )
final public static boolean destroy ( long $mutex )
final public static boolean lock ( long $mutex )
final public static boolean trylock ( long $mutex )
final public static boolean unlock ( long $mutex [, boolean $destroy ] )
}

Cuprins

  • Mutex::create — Create a Mutex
  • Mutex::destroy — Destroy Mutex
  • Mutex::lock — Acquire Mutex
  • Mutex::trylock — Attempt to Acquire Mutex
  • Mutex::unlock — Release Mutex
Pool::submitTo
Mutex::create
pthreads


Create a Mutex

Mutex
Mutex::destroy
Mutex
PHP Manual

Mutex::create

(PECL pthreads < 3.0.0)

Mutex::create — Create a Mutex

Avertizare

The Mutex class has been removed in pthreads v3.

Descrierea

final public static long Mutex::create ([ boolean $lock ] )

Create, and optionally lock a new Mutex for the caller

Parametri

lock

Setting lock to true will lock the Mutex for the caller before returning the handle

Valorile întoarse

A newly created and optionally locked Mutex handle

Exemple

Example #1 Mutex Creation and Destruction

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You have the physical address of the Mutex **/
var_dump($mutex);
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

Exemplul de mai sus va afi?a:

int(40096976)

Mutex
Mutex::destroy
Mutex


Destroy Mutex

Mutex::create
Mutex::lock
Mutex
PHP Manual

Mutex::destroy

(PECL pthreads < 3.0.0)

Mutex::destroy — Destroy Mutex

Avertizare

The Mutex class has been removed in pthreads v3.

Descrierea

final public static boolean Mutex::destroy ( long $mutex )

Destroying Mutex handles must be carried out explicitly by the programmer when they are finished with the Mutex handle.

Parametri

mutex

A handle returned by a previous call to Mutex::create(). The handle should not be locked by any Thread when Mutex::destroy() is called.

Valorile întoarse

A boolean indication of success

Exemple

Example #1 Mutex Creation and Destruction

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You have the physical address of the Mutex **/
var_dump($mutex);
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

Exemplul de mai sus va afi?a:

int(40096976)

Mutex::create
Mutex::lock
Mutex


Acquire Mutex

Mutex::destroy
Mutex::trylock
Mutex
PHP Manual

Mutex::lock

(PECL pthreads < 3.0.0)

Mutex::lock — Acquire Mutex

Avertizare

The Mutex class has been removed in pthreads v3.

Descrierea

final public static boolean Mutex::lock ( long $mutex )

Attempt to lock the Mutex for the caller.

An attempt to lock a Mutex owned (locked) by another Thread will result in blocking.

Parametri

mutex

A handle returned by a previous call to Mutex::create().

Valorile întoarse

A boolean indication of success.

Exemple

Example #1 Mutex Locking and Unlocking

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You can now lock the mutex in any context **/
var_dump(Mutex::lock($mutex));
/** It is invalid to attempt to destroy a locked Mutex **/
var_dump(Mutex::unlock($mutex));
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)

Mutex::destroy
Mutex::trylock
Mutex


Attempt to Acquire Mutex

Mutex::lock
Mutex::unlock
Mutex
PHP Manual

Mutex::trylock

(PECL pthreads < 3.0.0)

Mutex::trylock — Attempt to Acquire Mutex

Avertizare

The Mutex class has been removed in pthreads v3.

Descrierea

final public static boolean Mutex::trylock ( long $mutex )

Attempt to lock the Mutex for the caller without blocking if the Mutex is owned (locked) by another Thread.

Parametri

mutex

A handle returned by a previous call to Mutex::create().

Valorile întoarse

A boolean indication of success.

Exemple

Example #1 Mutex Locking and Unlocking

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You can now try to lock the mutex in any context **/
var_dump(Mutex::trylock($mutex));
/** It is invalid to attempt to destroy a locked Mutex **/
var_dump(Mutex::unlock($mutex));
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)

Mutex::lock
Mutex::unlock
Mutex


Release Mutex

Mutex::trylock
Cond
Mutex
PHP Manual

Mutex::unlock

(PECL pthreads < 3.0.0)

Mutex::unlock — Release Mutex

Avertizare

The Mutex class has been removed in pthreads v3.

Descrierea

final public static boolean Mutex::unlock ( long $mutex [, boolean $destroy ] )

Attempts to unlock the Mutex for the caller, optionally destroying the Mutex handle. The calling thread should own the Mutex at the time of the call.

Parametri

mutex

A handle returned by a previous call to Mutex::create().

destroy

When true pthreads will destroy the Mutex after a successful unlock.

Valorile întoarse

A boolean indication of success.

Exemple

Example #1 Mutex Locking and Unlocking

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You can now lock the mutex in any context **/
var_dump(Mutex::lock($mutex));
/** It is invalid to attempt to destroy a locked Mutex **/
var_dump(Mutex::unlock($mutex));
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)

Mutex::trylock
Cond
Mutex


The Cond class

(PECL pthreads < 3.0.0)

Introducere

Avertizare

The Cond class has been removed in pthreads v3.

The static methods contained in the Cond class provide direct access to Posix Condition Variables.

Sinopsisul clasei

Cond {
/* Metode */
final public static boolean broadcast ( long $condition )
final public static long create ( void )
final public static boolean destroy ( long $condition )
final public static boolean signal ( long $condition )
final public static boolean wait ( long $condition , long $mutex [, long $timeout ] )
}

Cuprins

  • Cond::broadcast — Broadcast a Condition
  • Cond::create — Create a Condition
  • Cond::destroy — Destroy a Condition
  • Cond::signal — Signal a Condition
  • Cond::wait — Wait for Condition
Mutex::unlock
Cond::broadcast
pthreads


Broadcast a Condition

Cond
Cond::create
Cond
PHP Manual

Cond::broadcast

(PECL pthreads < 3.0.0)

Cond::broadcast — Broadcast a Condition

Avertizare

The Cond class has been removed in pthreads v3.

Descrierea

final public static boolean Cond::broadcast ( long $condition )

Broadcast to all Threads blocking on a call to Cond::wait().

Parametri

condition

A handle to a Condition Variable returned by a previous call to Cond::create()

Valorile întoarse

A boolean indication of success.

Exemple

Example #1 Condition Broadcasting

<?php
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** The caller must lock the associated Mutex before a call to broadcast **/
var_dump(Cond::broadcast($cond));
/** Always destroy Cond you have created **/
Cond::destroy($cond);
?>

Exemplul de mai sus va afi?a:

bool(true)

Cond
Cond::create
Cond


Create a Condition

Cond::broadcast
Cond::destroy
Cond
PHP Manual

Cond::create

(PECL pthreads < 3.0.0)

Cond::create — Create a Condition

Avertizare

The Cond class has been removed in pthreads v3.

Descrierea

final public static long Cond::create ( void )

Creates a new Condition Variable for the caller.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A handle to a Condition Variable

Exemple

Example #1 Condition Creation and Destruction

<?php
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** You can now use the Cond in any context **/
var_dump($cond);
/** Always destroy Cond you have created **/
Cond::destroy($cond);
?>

Exemplul de mai sus va afi?a:

int(4540682)

Cond::broadcast
Cond::destroy
Cond


Destroy a Condition

Cond::create
Cond::signal
Cond
PHP Manual

Cond::destroy

(PECL pthreads < 3.0.0)

Cond::destroy — Destroy a Condition

Avertizare

The Cond class has been removed in pthreads v3.

Descrierea

final public static boolean Cond::destroy ( long $condition )

Destroying Condition Variable handles must be carried out explicitly by the programmer when they are finished with the Condition Variable. No Threads should be blocking on a call to Cond::wait() when the call to Cond::destroy() takes place.

Parametri

condition

A handle to a Condition Variable returned by a previous call to Cond::create()

Valorile întoarse

A boolean indication of success.

Exemple

Example #1 Condition Creation and Destruction

<?php
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** You can now use the Cond in any context **/
var_dump($cond);
/** Always destroy Cond you have created **/
Cond::destroy($cond);
?>

Exemplul de mai sus va afi?a:

int(4540682)

Cond::create
Cond::signal
Cond


Signal a Condition

Cond::destroy
Cond::wait
Cond
PHP Manual

Cond::signal

(PECL pthreads < 3.0.0)

Cond::signal — Signal a Condition

Avertizare

The Cond class has been removed in pthreads v3.

Descrierea

final public static boolean Cond::signal ( long $condition )

Parametri

condition

A handle returned by a previous call to Cond::create()

Valorile întoarse

A boolean indication of success.

Exemple

Example #1 Condition Signalling

<?php
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** The caller must lock the associated Mutex before a call to broadcast **/
var_dump(Cond::signal($cond));
/** Always destroy Cond you have created **/
Cond::destroy($cond);
?>

Exemplul de mai sus va afi?a:

bool(true)

Cond::destroy
Cond::wait
Cond


Wait for Condition

Cond::signal
Semaphore
Cond
PHP Manual

Cond::wait

(PECL pthreads < 3.0.0)

Cond::wait — Wait for Condition

Avertizare

The Cond class has been removed in pthreads v3.

Descrierea

final public static boolean Cond::wait ( long $condition , long $mutex [, long $timeout ] )

Wait for a signal on a Condition Variable, optionally specifying a timeout to limit waiting time.

Parametri

condition

A handle returned by a previous call to Cond::create().

mutex

A handle returned by a previous call to Mutex::create() and owned (locked) by the caller.

timeout

An optional timeout, in microseconds ( millionths of a second ).

Valorile întoarse

A boolean indication of success.

Exemple

Example #1 Waiting for Conditions

<?php
/** PLEASE NOTE THIS EXAMPLE WILL CAUSE THE PROCESS TO HANG **/
$mutex = Mutex::create(true);
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** The caller must lock the associated Mutex before a call to broadcast **/
var_dump(Cond::wait($cond, $mutex));
/** Always destroy Cond you have created **/
Cond::destroy($cond);
Mutex::unlock($mutex);
Mutex::destroy($mutex);
?>

Exemplul de mai sus va afi?a:

int(49685473)

Cond::signal
Semaphore
Cond


Semaphore, Shared Memory and IPC

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii de lucru cu Semafoare
    • 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
Cond::wait
Introducere
Extensii de control al proceselor


Introducere

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.

Nota: Aceasta extensie nu este disponibila pe platformele Windows.

Semaphore
Instalarea / configurarea
Semaphore


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Semaphore


Instalarea

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 .

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Semaphore Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
sysvshm.init_mem | 10000 | PHP_INI_SYSTEM |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

sysvshm.init_mem int

A default size of the shared memory segment.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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 |

Tipurile resurselor
Func?ii de lucru cu Semafoare
Semaphore


Func?ii de lucru cu Semafoare

Cuprins

  • 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
Constante predefinite
ftok
Semaphore


Convert a pathname and a project identifier to a System V IPC key

Func?ii de lucru cu Semafoare
msg_get_queue
Func?ii de lucru cu Semafoare
PHP Manual

ftok

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ftok — Convert a pathname and a project identifier to a System V IPC key

Descrierea

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.

Parametri

pathname

Path to an accessible file.

proj

Project identifier. This must be a one character string.

Valorile întoarse

On success the return value will be the created key value, otherwise -1 is returned.

A se vedea ?i

  • shmop_open() - Create or open shared memory block
  • sem_get() - Get a semaphore id

Func?ii de lucru cu Semafoare
msg_get_queue
Func?ii de lucru cu Semafoare


Create or attach to a message queue

ftok
msg_queue_exists
Func?ii de lucru cu Semafoare
PHP Manual

msg_get_queue

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

msg_get_queue — Create or attach to a message queue

Descrierea

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.

Parametri

key

Message queue numeric ID

perms

Queue permissions. Default to 0666. If the message queue already exists, the perms will be ignored.

Valorile întoarse

Returns a resource handle that can be used to access the System V message queue.

A se vedea ?i

  • 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
Func?ii de lucru cu Semafoare


Check whether a message queue exists

msg_get_queue
msg_receive
Func?ii de lucru cu Semafoare
PHP Manual

msg_queue_exists

(PHP 5 >= 5.3.0, PHP 7)

msg_queue_exists — Check whether a message queue exists

Descrierea

bool msg_queue_exists ( int $key )

Checks whether the message queue key exists.

Parametri

key

Queue key.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii de lucru cu Semafoare


Receive a message from a message queue

msg_queue_exists
msg_remove_queue
Func?ii de lucru cu Semafoare
PHP Manual

msg_receive

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

msg_receive — Receive a message from a message queue

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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.

A se vedea ?i

  • 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
Func?ii de lucru cu Semafoare


Destroy a message queue

msg_receive
msg_send
Func?ii de lucru cu Semafoare
PHP Manual

msg_remove_queue

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

msg_remove_queue — Destroy a message queue

Descrierea

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.

Parametri

queue

Message queue resource handle

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii de lucru cu Semafoare


Send a message to a message queue

msg_remove_queue
msg_set_queue
Func?ii de lucru cu Semafoare
PHP Manual

msg_send

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

msg_send — Send a message to a message queue

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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.

A se vedea ?i

  • 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
Func?ii de lucru cu Semafoare


Set information in the message queue data structure

msg_send
msg_stat_queue
Func?ii de lucru cu Semafoare
PHP Manual

msg_set_queue

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

msg_set_queue — Set information in the message queue data structure

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii de lucru cu Semafoare


Returns information from the message queue data structure

msg_set_queue
sem_acquire
Func?ii de lucru cu Semafoare
PHP Manual

msg_stat_queue

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

msg_stat_queue — Returns information from the message queue data structure

Descrierea

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.

Parametri

queue

Message queue resource handle

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii de lucru cu Semafoare


Acquire a semaphore

msg_stat_queue
sem_get
Func?ii de lucru cu Semafoare
PHP Manual

sem_acquire

(PHP 4, PHP 5, PHP 7)

sem_acquire — Acquire a semaphore

Descrierea

bool sem_acquire ( resource $sem_identifier [, bool $nowait = false ] )

sem_acquire() by default 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.

Parametri

sem_identifier

sem_identifier is a semaphore resource, obtained from sem_get().

nowait

Specifies if the process shouldn't wait for the semaphore to be acquired. If set to true, the call will return false immediately if a semaphore cannot be immediately acquired.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.6.1 | The $nowait parameter was added.

A se vedea ?i

  • sem_get() - Get a semaphore id
  • sem_release() - Release a semaphore

msg_stat_queue
sem_get
Func?ii de lucru cu Semafoare


Get a semaphore id

sem_acquire
sem_release
Func?ii de lucru cu Semafoare
PHP Manual

sem_get

(PHP 4, PHP 5, PHP 7)

sem_get — Get a semaphore id

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a positive semaphore identifier on success, or FALSE on error.

Note

Avertizare

When using sem_get() to access a semaphore created outside PHP, note that the semaphore must have been created as a set of 3 semaphores (for example, by specifying 3 as the nsems parameter when calling the C semget() function), otherwise PHP will be unable to access the semaphore.

A se vedea ?i

  • 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
Func?ii de lucru cu Semafoare


Release a semaphore

sem_get
sem_remove
Func?ii de lucru cu Semafoare
PHP Manual

sem_release

(PHP 4, PHP 5, PHP 7)

sem_release — Release a semaphore

Descrierea

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.

Parametri

sem_identifier

A Semaphore resource handle as returned by sem_get().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • sem_get() - Get a semaphore id
  • sem_acquire() - Acquire a semaphore

sem_get
sem_remove
Func?ii de lucru cu Semafoare


Remove a semaphore

sem_release
shm_attach
Func?ii de lucru cu Semafoare
PHP Manual

sem_remove

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

sem_remove — Remove a semaphore

Descrierea

bool sem_remove ( resource $sem_identifier )

sem_remove() removes the given semaphore.

After removing the semaphore, it is no longer accessible.

Parametri

sem_identifier

A semaphore resource identifier as returned by sem_get().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • sem_get() - Get a semaphore id
  • sem_release() - Release a semaphore
  • sem_acquire() - Acquire a semaphore

sem_release
shm_attach
Func?ii de lucru cu Semafoare


Creates or open a shared memory segment

sem_remove
shm_detach
Func?ii de lucru cu Semafoare
PHP Manual

shm_attach

(PHP 4, PHP 5, PHP 7)

shm_attach — Creates or open a shared memory segment

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a shared memory segment identifier.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function now returns a resource instead of an integer.

Note

Nota:

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;
?>

A se vedea ?i

  • 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
Func?ii de lucru cu Semafoare


Disconnects from shared memory segment

shm_attach
shm_get_var
Func?ii de lucru cu Semafoare
PHP Manual

shm_detach

(PHP 4, PHP 5, PHP 7)

shm_detach — Disconnects from shared memory segment

Descrierea

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.

Parametri

shm_identifier

A shared memory resource handle as returned by shm_attach()

Valorile întoarse

shm_detach() always returns TRUE.

A se vedea ?i

  • 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
Func?ii de lucru cu Semafoare


Returns a variable from shared memory

shm_detach
shm_has_var
Func?ii de lucru cu Semafoare
PHP Manual

shm_get_var

(PHP 4, PHP 5, PHP 7)

shm_get_var — Returns a variable from shared memory

Descrierea

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.

Parametri

shm_identifier

Shared memory segment, obtained from shm_attach().

variable_key

The variable key.

Valorile întoarse

Returns the variable with the given key.

A se vedea ?i

  • 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
Func?ii de lucru cu Semafoare


Check whether a specific entry exists

shm_get_var
shm_put_var
Func?ii de lucru cu Semafoare
PHP Manual

shm_has_var

(PHP 5 >= 5.3.0, PHP 7)

shm_has_var — Check whether a specific entry exists

Descrierea

bool shm_has_var ( resource $shm_identifier , int $variable_key )

Checks whether a specific key exists inside a shared memory segment.

Parametri

shm_identifier

Shared memory segment, obtained from shm_attach().

variable_key

The variable key.

Valorile întoarse

Returns TRUE if the entry exists, otherwise FALSE

A se vedea ?i

  • 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
Func?ii de lucru cu Semafoare


Inserts or updates a variable in shared memory

shm_has_var
shm_remove_var
Func?ii de lucru cu Semafoare
PHP Manual

shm_put_var

(PHP 4, PHP 5, PHP 7)

shm_put_var — Inserts or updates a variable in shared memory

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • shm_get_var() - Returns a variable from shared memory
  • shm_has_var() - Check whether a specific entry exists

shm_has_var
shm_remove_var
Func?ii de lucru cu Semafoare


Removes a variable from shared memory

shm_put_var
shm_remove
Func?ii de lucru cu Semafoare
PHP Manual

shm_remove_var

(PHP 4, PHP 5, PHP 7)

shm_remove_var — Removes a variable from shared memory

Descrierea

bool shm_remove_var ( resource $shm_identifier , int $variable_key )

Removes a variable with a given variable_key and frees the occupied memory.

Parametri

shm_identifier

The shared memory identifier as returned by shm_attach()

variable_key

The variable key.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • shm_remove() - Removes shared memory from Unix systems

shm_put_var
shm_remove
Func?ii de lucru cu Semafoare


Removes shared memory from Unix systems

shm_remove_var
Shared Memory
Func?ii de lucru cu Semafoare
PHP Manual

shm_remove

(PHP 4, PHP 5, PHP 7)

shm_remove — Removes shared memory from Unix systems

Descrierea

bool shm_remove ( resource $shm_identifier )

shm_remove() removes the shared memory shm_identifier. All data will be destroyed.

Parametri

shm_identifier

The shared memory identifier as returned by shm_attach()

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • shm_remove_var() - Removes a variable from shared memory

shm_remove_var
Shared Memory
Func?ii de lucru cu Semafoare


Shared Memory

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic usage
  • Func?ii de lucru cu memoria partajata
    • 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
Introducere
Extensii de control al proceselor


Introducere

Shmop is an easy to use set of functions that allows PHP to read, write, create and delete Unix shared memory segments.

Nota: Versions of Windows previous to Windows 2000 do not support shared memory.

Shared Memory
Instalarea / configurarea
Shared Memory


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Shared Memory


Instalarea

Pentru a utiliza shmop este necesar de a compila PHP cu op?iunea --enable-shmop în linia de configurare.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

As of PHP 7.0.0 this extension defines the resource type shmop which is a handle to a shared memory block.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
Shared Memory


Exemple

Cuprins

  • Basic usage
Constante predefinite
Basic usage
Shared Memory


Basic usage

Example #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);

?>

Exemple
Func?ii de lucru cu memoria partajata
Exemple


Func?ii de lucru cu memoria partajata

Cuprins

  • 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

Func?ii de lucru cu memoria partajata
shmop_delete
Func?ii de lucru cu memoria partajata
PHP Manual

shmop_close

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

shmop_close — Close shared memory block

Descrierea

void shmop_close ( resource $shmid )

shmop_close() is used to close a shared memory block.

Parametri

shmid

The shared memory block resource created by shmop_open()

Valorile întoarse

Nu este întoarsa nici o valoare.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | The type of shmid has been changed from int to resource.

Exemple

Example #1 Closing shared memory block

<?php
shmop_close($shm_id);
?>

This example will close shared memory block identified by $shm_id.

A se vedea ?i

  • shmop_open() - Create or open shared memory block

Func?ii de lucru cu memoria partajata
shmop_delete
Func?ii de lucru cu memoria partajata


Delete shared memory block

shmop_close
shmop_open
Func?ii de lucru cu memoria partajata
PHP Manual

shmop_delete

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

shmop_delete — Delete shared memory block

Descrierea

bool shmop_delete ( resource $shmid )

shmop_delete() is used to delete a shared memory block.

Parametri

shmid

The shared memory block resource created by shmop_open()

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | The type of shmid has been changed from int to resource.

Exemple

Example #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
Func?ii de lucru cu memoria partajata


Create or open shared memory block

shmop_delete
shmop_read
Func?ii de lucru cu memoria partajata
PHP Manual

shmop_open

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

shmop_open — Create or open shared memory block

Descrierea

resource shmop_open ( int $key , string $flags , int $mode , int $size )

shmop_open() can create or open a shared memory block.

Parametri

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

Nota:

Note: the 3rd and 4th should be entered as 0 if you are opening an existing memory segment.

Valorile întoarse

On success shmop_open() will return an resource that you can use to access the shared memory segment you've created. FALSE is returned on failure.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | The return type of shmop_open() has been changed from int to resource.

Exemple

Example #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().

A se vedea ?i

  • shmop_close() - Close shared memory block
  • shmop_delete() - Delete shared memory block

shmop_delete
shmop_read
Func?ii de lucru cu memoria partajata


Read data from shared memory block

shmop_open
shmop_size
Func?ii de lucru cu memoria partajata
PHP Manual

shmop_read

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

shmop_read — Read data from shared memory block

Descrierea

string shmop_read ( resource $shmid , int $start , int $count )

shmop_read() will read a string from shared memory block.

Parametri

shmid

The shared memory block identifier created by shmop_open()

start

Offset from which to start reading

count

The number of bytes to read

Valorile întoarse

Returns the data sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | The type of shmid has been changed from int to resource.

Exemple

Example #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.

A se vedea ?i

  • shmop_write() - Write data into shared memory block

shmop_open
shmop_size
Func?ii de lucru cu memoria partajata


Get size of shared memory block

shmop_read
shmop_write
Func?ii de lucru cu memoria partajata
PHP Manual

shmop_size

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

shmop_size — Get size of shared memory block

Descrierea

int shmop_size ( resource $shmid )

shmop_size() is used to get the size, in bytes of the shared memory block.

Parametri

shmid

The shared memory block identifier created by shmop_open()

Valorile întoarse

Returns an int, which represents the number of bytes the shared memory block occupies.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | The type of shmid has been changed from int to resource.

Exemple

Example #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
Func?ii de lucru cu memoria partajata


Write data into shared memory block

shmop_size
Sync
Func?ii de lucru cu memoria partajata
PHP Manual

shmop_write

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

shmop_write — Write data into shared memory block

Descrierea

int shmop_write ( resource $shmid , string $data , int $offset )

shmop_write() will write a string into shared memory block.

Parametri

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.

Valorile întoarse

The size of the written data, or FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | The type of shmid has been changed from int to resource.

Exemple

Example #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.

A se vedea ?i

  • shmop_read() - Read data from shared memory block

shmop_size
Sync
Func?ii de lucru cu memoria partajata


Sync

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • SyncMutex — The SyncMutex class
    • SyncMutex::__construct — Constructs a new SyncMutex object
    • SyncMutex::lock — Waits for an exclusive lock
    • SyncMutex::unlock — Unlocks the mutex
  • SyncSemaphore — The SyncSemaphore class
    • SyncSemaphore::__construct — Constructs a new SyncSemaphore object
    • SyncSemaphore::lock — Decreases the count of the semaphore or waits
    • SyncSemaphore::unlock — Increases the count of the semaphore
  • SyncEvent — The SyncEvent class
    • SyncEvent::__construct — Constructs a new SyncEvent object
    • SyncEvent::fire — Fires/sets the event
    • SyncEvent::reset — Resets a manual event
    • SyncEvent::wait — Waits for the event to be fired/set
  • SyncReaderWriter — The SyncReaderWriter class
    • SyncReaderWriter::__construct — Constructs a new SyncReaderWriter object
    • SyncReaderWriter::readlock — Waits for a read lock
    • SyncReaderWriter::readunlock — Releases a read lock
    • SyncReaderWriter::writelock — Waits for an exclusive write lock
    • SyncReaderWriter::writeunlock — Releases a write lock
  • SyncSharedMemory — The SyncSharedMemory class
    • SyncSharedMemory::__construct — Constructs a new SyncSharedMemory object
    • SyncSharedMemory::first — Check to see if the object is the first instance system-wide of named shared memory
    • SyncSharedMemory::read — Copy data from named shared memory
    • SyncSharedMemory::size — Returns the size of the named shared memory
    • SyncSharedMemory::write — Copy data to named shared memory
shmop_write
Introducere
Extensii de control al proceselor


Introducere

The 'sync' extension introduces cross-platform synchonization objects into PHP. Named and unnamed Mutex, Semaphore, Event, Reader-Writer, and named Shared Memory objects provide OS-level synchronization on both POSIX (e.g. Linux) and Windows platforms.

Automatic cleanup of acquired synchronization objects takes place during extension teardown. This means that if PHP prematurely terminates a script (e.g. script execution time is exceeded), objects will not be left in an unknown state. The only exception to this is if PHP itself crashes (e.g. an internal buffer overflow).

Unnamed synchronization objects don't have a lot of use outside of a multithreaded scenario. Unnamed objects are more useful in conjunction with the pthreads PECL extension.

Nota:

Named objects require additional care to be used on all systems. If an object is instantiated with a specific set of parameters, it must always be instantiated with those parameters or the object will probably end up in an inconsistent state until the next reboot or a system administrator cleans up the mess.

Sync
Instalarea / configurarea
Sync


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Sync


Necesita?i

A system with support for POSIX shared memory (shm_open()) or running Windows.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/sync.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
SyncMutex
Sync


The SyncMutex class

(PECL sync >= 1.0.0)

Introducere

A cross-platform, native implementation of named and unnamed countable mutex objects.

A mutex is a mutual exclusion object that restricts access to a shared resource (e.g. a file) to a single instance. Countable mutexes acquire the mutex a single time and internally track the number of times the mutex is locked. The mutex is unlocked as soon as it goes out of scope or is unlocked the same number of times that it was locked.

Sinopsisul clasei

SyncMutex {
/* Metode */
public __construct ([ string $name ] )
public bool lock ([ integer $wait = -1 ] )
public bool unlock ([ bool $all = false ] )
}

Cuprins

  • SyncMutex::__construct — Constructs a new SyncMutex object
  • SyncMutex::lock — Waits for an exclusive lock
  • SyncMutex::unlock — Unlocks the mutex
Constante predefinite
SyncMutex::__construct
Sync


Constructs a new SyncMutex object

SyncMutex
SyncMutex::lock
SyncMutex
PHP Manual

SyncMutex::__construct

(PECL sync >= 1.0.0)

SyncMutex::__construct — Constructs a new SyncMutex object

Descrierea

public SyncMutex::__construct ([ string $name ] )

Constructs a named or unnamed countable mutex.

Parametri

name

The name of the mutex if this is a named mutex object.

Nota:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

Valorile întoarse

The new SyncMutex object. An exception is thrown if the mutex cannot be created or opened.

Exemple

Example #1 SyncMutex::__construct() named mutex with lock timeout example

<?php
$mutex = new SyncMutex("UniqueName");

if (!$mutex->lock(3000))
{
    echo "Unable to lock mutex.";

    exit();
}

/* ... */

$mutex->unlock();
?>

Example #2 SyncMutex::__construct() unnamed mutex example

<?php
$mutex = new SyncMutex();

$mutex->lock();

/* ... */

$mutex->unlock();
?>

A se vedea ?i

  • SyncMutex::lock() - Waits for an exclusive lock
  • SyncMutex::unlock() - Unlocks the mutex
SyncMutex
SyncMutex::lock
SyncMutex


Waits for an exclusive lock

SyncMutex::__construct
SyncMutex::unlock
SyncMutex
PHP Manual

SyncMutex::lock

(PECL sync >= 1.0.0)

SyncMutex::lock — Waits for an exclusive lock

Descrierea

public bool SyncMutex::lock ([ integer $wait = -1 ] )

Obtains an exclusive lock on a SyncMutex object. If the lock is already acquired, then this increments an internal counter.

Parametri

wait

The number of milliseconds to wait for the exclusive lock. A value of -1 is infinite.

Valorile întoarse

A boolean of TRUE if the lock was obtained, FALSE otherwise.

Exemple

Example #1 SyncMutex::lock() example

<?php
$mutex = new SyncMutex("UniqueName");

if (!$mutex->lock(3000))
{
    echo "Unable to lock mutex.";

    exit();
}

/* ... */

$mutex->unlock();
?>

A se vedea ?i

  • SyncMutex::unlock() - Unlocks the mutex
SyncMutex::__construct
SyncMutex::unlock
SyncMutex


Unlocks the mutex

SyncMutex::lock
SyncSemaphore
SyncMutex
PHP Manual

SyncMutex::unlock

(PECL sync >= 1.0.0)

SyncMutex::unlock — Unlocks the mutex

Descrierea

public bool SyncMutex::unlock ([ bool $all = false ] )

Decreases the internal counter of a SyncMutex object. When the internal counter reaches zero, the actual lock on the object is released.

Parametri

all

Specifies whether or not to set the internal counter to zero and therefore release the lock.

Valorile întoarse

A boolean of TRUE if the unlock operation was successful, FALSE otherwise.

Exemple

Example #1 SyncMutex::unlock() example

<?php
$mutex = new SyncMutex("UniqueName");

$mutex->lock();

/* ... */

$mutex->unlock();
?>

A se vedea ?i

  • SyncMutex::lock() - Waits for an exclusive lock
SyncMutex::lock
SyncSemaphore
SyncMutex


The SyncSemaphore class

(PECL sync >= 1.0.0)

Introducere

A cross-platform, native implementation of named and unnamed sempahore objects.

A semaphore restricts access to a limited resource to a limited number of instances. Semaphores differ from mutexes in that they can allow more than one instance to access a resource at one time while a mutex only allows one instance at a time.

Sinopsisul clasei

SyncSemaphore {
/* Metode */
public __construct ([ string $name [, integer $initialval = 1 [, bool $autounlock = true ]]] )
public bool lock ([ integer $wait = -1 ] )
public bool unlock ([ integer &$prevcount ] )
}

Cuprins

  • SyncSemaphore::__construct — Constructs a new SyncSemaphore object
  • SyncSemaphore::lock — Decreases the count of the semaphore or waits
  • SyncSemaphore::unlock — Increases the count of the semaphore
SyncMutex::unlock
SyncSemaphore::__construct
Sync


Constructs a new SyncSemaphore object

SyncSemaphore
SyncSemaphore::lock
SyncSemaphore
PHP Manual

SyncSemaphore::__construct

(PECL sync >= 1.0.0)

SyncSemaphore::__construct — Constructs a new SyncSemaphore object

Descrierea

public SyncSemaphore::__construct ([ string $name [, integer $initialval = 1 [, bool $autounlock = true ]]] )

Constructs a named or unnamed semaphore.

Parametri

name

The name of the semaphore if this is a named semaphore object.

Nota:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

initialval

The initial value of the semaphore. This is the number of locks that may be obtained.

autounlock

Specifies whether or not to automatically unlock the semaphore at the conclusion of the PHP script.

Avertizare

If an object is: A named semaphore with an autounlock of FALSE, the object is locked, and the PHP script concludes before the object is unlocked, then the underlying semaphore will end up in an inconsistent state.

Valorile întoarse

The new SyncSemaphore object. An exception is thrown if the semaphore cannot be created or opened.

Exemple

Example #1 SyncSemaphore::__construct() example

<?php
$semaphore = new SyncSemaphore("LimitedResource_2clients", 2);

if (!$semaphore->lock(3000))
{
    echo "Unable to lock semaphore.";

    exit();
}

/* ... */

$semaphore->unlock();
?>

A se vedea ?i

  • SyncSemaphore::lock() - Decreases the count of the semaphore or waits
  • SyncSemaphore::unlock() - Increases the count of the semaphore
SyncSemaphore
SyncSemaphore::lock
SyncSemaphore


Decreases the count of the semaphore or waits

SyncSemaphore::__construct
SyncSemaphore::unlock
SyncSemaphore
PHP Manual

SyncSemaphore::lock

(PECL sync >= 1.0.0)

SyncSemaphore::lock — Decreases the count of the semaphore or waits

Descrierea

public bool SyncSemaphore::lock ([ integer $wait = -1 ] )

Decreases the count of a SyncSemaphore object or waits until the semaphore becomes non-zero.

Parametri

wait

The number of milliseconds to wait for the semaphore. A value of -1 is infinite.

Valorile întoarse

A boolean of TRUE if the lock operation was successful, FALSE otherwise.

Exemple

Example #1 SyncSemaphore::lock() example

<?php
$semaphore = new SyncSemaphore("LimitedResource_2clients", 2);

if (!$semaphore->lock(3000))
{
    echo "Unable to lock semaphore.";

    exit();
}

/* ... */

$semaphore->unlock();
?>

A se vedea ?i

  • SyncSemaphore::unlock() - Increases the count of the semaphore
SyncSemaphore::__construct
SyncSemaphore::unlock
SyncSemaphore


Increases the count of the semaphore

SyncSemaphore::lock
SyncEvent
SyncSemaphore
PHP Manual

SyncSemaphore::unlock

(PECL sync >= 1.0.0)

SyncSemaphore::unlock — Increases the count of the semaphore

Descrierea

public bool SyncSemaphore::unlock ([ integer &$prevcount ] )

Increases the count of a SyncSemaphore object.

Parametri

prevcount

Returns the previous count of the semaphore.

Valorile întoarse

A boolean of TRUE if the unlock operation was successful, FALSE otherwise.

Exemple

Example #1 SyncSemaphore::unlock() example

<?php
$semaphore = new SyncSemaphore("LimitedResource_2clients", 2);

if (!$semaphore->lock(3000))
{
    echo "Unable to lock semaphore.";

    exit();
}

/* ... */

$semaphore->unlock();
?>

A se vedea ?i

  • SyncSemaphore::lock() - Decreases the count of the semaphore or waits
SyncSemaphore::lock
SyncEvent
SyncSemaphore


The SyncEvent class

(PECL sync >= 1.0.0)

Introducere

A cross-platform, native implementation of named and unnamed event objects. Both automatic and manual event objects are supported.

An event object waits, without polling, for the object to be fired/set. One instance waits on the event object while another instance fires/sets the event. Event objects are useful wherever a long-running process would otherwise poll a resource (e.g. checking to see if uploaded data needs to be processed).

Sinopsisul clasei

SyncEvent {
/* Metode */
public __construct ([ string $name [, bool $manual = false [, bool $prefire = false ]]] )
public bool fire ( void )
public bool reset ( void )
public bool wait ([ integer $wait = -1 ] )
}

Cuprins

  • SyncEvent::__construct — Constructs a new SyncEvent object
  • SyncEvent::fire — Fires/sets the event
  • SyncEvent::reset — Resets a manual event
  • SyncEvent::wait — Waits for the event to be fired/set
SyncSemaphore::unlock
SyncEvent::__construct
Sync


Constructs a new SyncEvent object

SyncEvent
SyncEvent::fire
SyncEvent
PHP Manual

SyncEvent::__construct

(PECL sync >= 1.0.0)

SyncEvent::__construct — Constructs a new SyncEvent object

Descrierea

public SyncEvent::__construct ([ string $name [, bool $manual = false [, bool $prefire = false ]]] )

Constructs a named or unnamed event object.

Parametri

name

The name of the event if this is a named event object.

Nota:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

manual

Specifies whether or not the event object must be reset manually.

Nota:

Manual reset event objects allow all waiting processes through until the object is reset.

prefire

Specifies whether or not to prefire (signal) the event object.

Nota:

Only has impact if the calling process/thread is the first to create the object.

Valorile întoarse

The new SyncEvent object. An exception is thrown if the event object cannot be created or opened.

Exemple

Example #1 SyncEvent::__construct() example

<?php
// In a web application:
$event = new SyncEvent("GetAppReport");
$event->fire();

// In a cron job:
$event = new SyncEvent("GetAppReport");
$event->wait();
?>

Istoricul schimbarilor

Versiune | Descriere
1.1.0 | Added prefire.

A se vedea ?i

  • SyncEvent::fire() - Fires/sets the event
  • SyncEvent::reset() - Resets a manual event
  • SyncEvent::wait() - Waits for the event to be fired/set
SyncEvent
SyncEvent::fire
SyncEvent


Fires/sets the event

SyncEvent::__construct
SyncEvent::reset
SyncEvent
PHP Manual

SyncEvent::fire

(PECL sync >= 1.0.0)

SyncEvent::fire — Fires/sets the event

Descrierea

public bool SyncEvent::fire ( void )

Fires/sets a SyncEvent object. Lets multiple threads through that are waiting if the event object was created with a manual value of TRUE.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean of TRUE if the event was fired, FALSE otherwise.

Exemple

Example #1 SyncEvent::fire() example

<?php
// In a web application:
$event = new SyncEvent("GetAppReport");
$event->fire();

// In a cron job:
$event = new SyncEvent("GetAppReport");
$event->wait();
?>

A se vedea ?i

  • SyncEvent::reset() - Resets a manual event
  • SyncEvent::wait() - Waits for the event to be fired/set
SyncEvent::__construct
SyncEvent::reset
SyncEvent


Resets a manual event

SyncEvent::fire
SyncEvent::wait
SyncEvent
PHP Manual

SyncEvent::reset

(PECL sync >= 1.0.0)

SyncEvent::reset — Resets a manual event

Descrierea

public bool SyncEvent::reset ( void )

Resets a SyncEvent object that has been fired/set. Only valid for manual event objects.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean value of TRUE if the object was successfully reset, FALSE otherwise.

Exemple

Example #1 SyncEvent::reset() example

<?php
// In a web application:
$event = new SyncEvent("DemoApplication", true);
$event->wait();

// In a cron job:
$event = new SyncEvent("DemoApplication", true);
$event->reset();
/* ... Do some maintenance task(s) ... */
$event->fire();
?>

A se vedea ?i

  • SyncEvent::fire() - Fires/sets the event
  • SyncEvent::reset()
  • SyncEvent::wait() - Waits for the event to be fired/set
SyncEvent::fire
SyncEvent::wait
SyncEvent


Waits for the event to be fired/set

SyncEvent::reset
SyncReaderWriter
SyncEvent
PHP Manual

SyncEvent::wait

(PECL sync >= 1.0.0)

SyncEvent::wait — Waits for the event to be fired/set

Descrierea

public bool SyncEvent::wait ([ integer $wait = -1 ] )

Waits for the SyncEvent object to be fired.

Parametri

wait

The number of milliseconds to wait for the event to be fired. A value of -1 is infinite.

Valorile întoarse

A boolean of TRUE if the event was fired, FALSE otherwise.

Exemple

Example #1 SyncEvent::wait() example

<?php
// In a web application:
$event = new SyncEvent("GetAppReport");
$event->fire();

// In a cron job:
$event = new SyncEvent("GetAppReport");
$event->wait();
?>

A se vedea ?i

  • SyncEvent::fire() - Fires/sets the event
SyncEvent::reset
SyncReaderWriter
SyncEvent


The SyncReaderWriter class

(PECL sync >= 1.0.0)

Introducere

A cross-platform, native implementation of named and unnamed reader-writer objects.

A reader-writer object allows many readers or one writer to access a resource. This is an efficient solution for managing resources where access will primarily be read-only but exclusive write access is occasionally necessary.

Sinopsisul clasei

SyncReaderWriter {
/* Metode */
public __construct ([ string $name [, bool $autounlock = true ]] )
public bool readlock ([ integer $wait = -1 ] )
public bool readunlock ( void )
public bool writelock ([ integer $wait = -1 ] )
public bool writeunlock ( void )
}

Cuprins

  • SyncReaderWriter::__construct — Constructs a new SyncReaderWriter object
  • SyncReaderWriter::readlock — Waits for a read lock
  • SyncReaderWriter::readunlock — Releases a read lock
  • SyncReaderWriter::writelock — Waits for an exclusive write lock
  • SyncReaderWriter::writeunlock — Releases a write lock
SyncEvent::wait
SyncReaderWriter::__construct
Sync


Constructs a new SyncReaderWriter object

SyncReaderWriter
SyncReaderWriter::readlock
SyncReaderWriter
PHP Manual

SyncReaderWriter::__construct

(PECL sync >= 1.0.0)

SyncReaderWriter::__construct — Constructs a new SyncReaderWriter object

Descrierea

public SyncReaderWriter::__construct ([ string $name [, bool $autounlock = true ]] )

Constructs a named or unnamed reader-writer object.

Parametri

name

The name of the reader-writer if this is a named reader-writer object.

Nota:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

autounlock

Specifies whether or not to automatically unlock the reader-writer at the conclusion of the PHP script.

Avertizare

If an object is: A named reader-writer with an autounlock of FALSE, the object is locked for either reading or writing, and the PHP script concludes before the object is unlocked, then the underlying objects will end up in an inconsistent state.

Valorile întoarse

The new SyncReaderWriter object. An exception is thrown if the reader-writer cannot be created or opened.

Exemple

Example #1 SyncReaderWriter::__construct() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->readlock();
/* ... */
$readwrite->readunlock();

$readwrite->writelock();
/* ... */
$readwrite->writeunlock();
?>

A se vedea ?i

  • SyncReaderWriter::readlock() - Waits for a read lock
  • SyncReaderWriter::readunlock() - Releases a read lock
  • SyncReaderWriter::writelock() - Waits for an exclusive write lock
  • SyncReaderWriter::writeunlock() - Releases a write lock
SyncReaderWriter
SyncReaderWriter::readlock
SyncReaderWriter


Waits for a read lock

SyncReaderWriter::__construct
SyncReaderWriter::readunlock
SyncReaderWriter
PHP Manual

SyncReaderWriter::readlock

(PECL sync >= 1.0.0)

SyncReaderWriter::readlock — Waits for a read lock

Descrierea

public bool SyncReaderWriter::readlock ([ integer $wait = -1 ] )

Obtains a read lock on a SyncReaderWriter object.

Parametri

wait

The number of milliseconds to wait for a lock. A value of -1 is infinite.

Valorile întoarse

A boolean of TRUE if the lock was obtained, FALSE otherwise.

Exemple

Example #1 SyncReaderWriter::readlock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->readlock();
/* ... */
$readwrite->readunlock();
?>

A se vedea ?i

  • SyncReaderWriter::readunlock() - Releases a read lock
SyncReaderWriter::__construct
SyncReaderWriter::readunlock
SyncReaderWriter


Releases a read lock

SyncReaderWriter::readlock
SyncReaderWriter::writelock
SyncReaderWriter
PHP Manual

SyncReaderWriter::readunlock

(PECL sync >= 1.0.0)

SyncReaderWriter::readunlock — Releases a read lock

Descrierea

public bool SyncReaderWriter::readunlock ( void )

Releases a read lock on a SyncReaderWriter object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean of TRUE if the unlock operation was successful, FALSE otherwise.

Exemple

Example #1 SyncReaderWriter::readunlock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->readlock();
/* ... */
$readwrite->readunlock();
?>

A se vedea ?i

  • SyncReaderWriter::readlock() - Waits for a read lock
SyncReaderWriter::readlock
SyncReaderWriter::writelock
SyncReaderWriter


Waits for an exclusive write lock

SyncReaderWriter::readunlock
SyncReaderWriter::writeunlock
SyncReaderWriter
PHP Manual

SyncReaderWriter::writelock

(PECL sync >= 1.0.0)

SyncReaderWriter::writelock — Waits for an exclusive write lock

Descrierea

public bool SyncReaderWriter::writelock ([ integer $wait = -1 ] )

Obtains an exclusive write lock on a SyncReaderWriter object.

Parametri

wait

The number of milliseconds to wait for a lock. A value of -1 is infinite.

Valorile întoarse

A boolean of TRUE if the lock was obtained, FALSE otherwise.

Exemple

Example #1 SyncReaderWriter::writelock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->writelock();
/* ... */
$readwrite->writeunlock();
?>

A se vedea ?i

  • SyncReaderWriter::writeunlock() - Releases a write lock
SyncReaderWriter::readunlock
SyncReaderWriter::writeunlock
SyncReaderWriter


Releases a write lock

SyncReaderWriter::writelock
SyncSharedMemory
SyncReaderWriter
PHP Manual

SyncReaderWriter::writeunlock

(PECL sync >= 1.0.0)

SyncReaderWriter::writeunlock — Releases a write lock

Descrierea

public bool SyncReaderWriter::writeunlock ( void )

Releases a write lock on a SyncReaderWriter object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean of TRUE if the unlock operation was successful, FALSE otherwise.

Exemple

Example #1 SyncReaderWriter::writeunlock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->writelock();
/* ... */
$readwrite->writeunlock();
?>

A se vedea ?i

  • SyncReaderWriter::writelock() - Waits for an exclusive write lock
SyncReaderWriter::writelock
SyncSharedMemory
SyncReaderWriter


The SyncSharedMemory class

(PECL sync >= 1.1.0)

Introducere

A cross-platform, native, consistent implementation of named shared memory objects.

Shared memory lets two separate processes communicate without the need for complex pipes or sockets. There are several integer-based shared memory implementations for PHP. Named shared memory is an alternative.

Synchronization objects (e.g. SyncMutex) are still required to protect most uses of shared memory.

Sinopsisul clasei

SyncSharedMemory {
/* Metode */
public __construct ( string $name , integer $size )
public bool first ( void )
public read ([ integer $start = 0 [, integer $length ]] )
public bool size ( void )
public write ([ string $string [, integer $start = 0 ]] )
}

Cuprins

  • SyncSharedMemory::__construct — Constructs a new SyncSharedMemory object
  • SyncSharedMemory::first — Check to see if the object is the first instance system-wide of named shared memory
  • SyncSharedMemory::read — Copy data from named shared memory
  • SyncSharedMemory::size — Returns the size of the named shared memory
  • SyncSharedMemory::write — Copy data to named shared memory
SyncReaderWriter::writeunlock
SyncSharedMemory::__construct
Sync


Constructs a new SyncSharedMemory object

SyncSharedMemory
SyncSharedMemory::first
SyncSharedMemory
PHP Manual

SyncSharedMemory::__construct

(PECL sync >= 1.1.0)

SyncSharedMemory::__construct — Constructs a new SyncSharedMemory object

Descrierea

public SyncSharedMemory::__construct ( string $name , integer $size )

Constructs a named shared memory object.

Parametri

name

The name of the shared memory object.

Nota:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

size

The size, in bytes, of shared memory to reserve.

Nota:

The amount of memory cannot be resized later. Request sufficient storage up front.

Valorile întoarse

The new SyncSharedMemory object. An exception is thrown if the shared memory object cannot be created or opened.

Exemple

Example #1 SyncSharedMemory::__construct() example

<?php
// You will probably need to protect shared memory with other synchronization objects.
// Shared memory goes away when the last reference to it disappears.
$mem = new SyncSharedMemory("AppReportName", 1024);
if ($mem->first())
{
    // Do first time initialization work here.
}

$result = $mem->write(json_encode(array("name" => "my_report.txt")));
?>

A se vedea ?i

  • SyncSharedMemory::first() - Check to see if the object is the first instance system-wide of named shared memory
  • SyncSharedMemory::size() - Returns the size of the named shared memory
  • SyncSharedMemory::write() - Copy data to named shared memory
  • SyncSharedMemory::read() - Copy data from named shared memory
SyncSharedMemory
SyncSharedMemory::first
SyncSharedMemory


Check to see if the object is the first instance system-wide of named shared memory

SyncSharedMemory::__construct
SyncSharedMemory::read
SyncSharedMemory
PHP Manual

SyncSharedMemory::first

(PECL sync >= 1.1.0)

SyncSharedMemory::first — Check to see if the object is the first instance system-wide of named shared memory

Descrierea

public bool SyncSharedMemory::first ( void )

Retrieves the system-wide first instance status of a SyncSharedMemory object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A boolean of TRUE if the object is the first instance system-wide, FALSE otherwise.

Exemple

Example #1 SyncSharedMemory::first() example

<?php
$mem = new SyncSharedMemory("AppReportName", 1024);
if ($mem->first())
{
    // Do first time initialization work here.
}

var_dump($mem->first());

$mem2 = new SyncSharedMemory("AppReportName", 1024);

var_dump($mem2->first());
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(false)

A se vedea ?i

  • SyncSharedMemory::write() - Copy data to named shared memory
  • SyncSharedMemory::read() - Copy data from named shared memory
SyncSharedMemory::__construct
SyncSharedMemory::read
SyncSharedMemory


Copy data from named shared memory

SyncSharedMemory::first
SyncSharedMemory::size
SyncSharedMemory
PHP Manual

SyncSharedMemory::read

(PECL sync >= 1.1.0)

SyncSharedMemory::read — Copy data from named shared memory

Descrierea

public SyncSharedMemory::read ([ integer $start = 0 [, integer $length ]] )

Copies data from named shared memory.

Parametri

start

The start/offset, in bytes, to begin reading.

Nota:

If the value is negative, the starting position will begin at the specified number of bytes from the end of the shared memory segment.

length

The number of bytes to read.

Nota:

If unspecified, reading will stop at the end of the shared memory segment.

If the value is negative, reading will stop the specified number of bytes from the end of the shared memory segment.

Valorile întoarse

A string containing the data read from shared memory.

Exemple

Example #1 SyncSharedMemory::__construct() example

<?php
// You will probably need to protect shared memory with other synchronization objects.
// Shared memory goes away when the last reference to it disappears.
$mem = new SyncSharedMemory("AppReportName", 1024);
if ($mem->first())
{
    // Do first time initialization work here.
}

$result = $mem->write("report.txt");

$result = $mem->read(3, -4);
var_dump($result);
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(3) "ort"

A se vedea ?i

  • SyncSharedMemory::__construct() - Constructs a new SyncSharedMemory object
  • SyncSharedMemory::first() - Check to see if the object is the first instance system-wide of named shared memory
  • SyncSharedMemory::write() - Copy data to named shared memory
  • SyncSharedMemory::read()
SyncSharedMemory::first
SyncSharedMemory::size
SyncSharedMemory


Returns the size of the named shared memory

SyncSharedMemory::read
SyncSharedMemory::write
SyncSharedMemory
PHP Manual

SyncSharedMemory::size

(PECL sync >= 1.1.0)

SyncSharedMemory::size — Returns the size of the named shared memory

Descrierea

public bool SyncSharedMemory::size ( void )

Retrieves the shared memory size of a SyncSharedMemory object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An integer containing the size of the shared memory. This will be the same size that was passed to the constructor.

Exemple

Example #1 SyncSharedMemory::size() example

<?php
$mem = new SyncSharedMemory("AppReportName", 1024);
var_dump($mem->size());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(1024)

A se vedea ?i

  • SyncSharedMemory::__construct() - Constructs a new SyncSharedMemory object
  • SyncSharedMemory::write() - Copy data to named shared memory
  • SyncSharedMemory::read() - Copy data from named shared memory
SyncSharedMemory::read
SyncSharedMemory::write
SyncSharedMemory


Copy data to named shared memory

SyncSharedMemory::size
Alte extensii de baza
SyncSharedMemory
PHP Manual

SyncSharedMemory::write

(PECL sync >= 1.1.0)

SyncSharedMemory::write — Copy data to named shared memory

Descrierea

public SyncSharedMemory::write ([ string $string [, integer $start = 0 ]] )

Copies data to named shared memory.

Parametri

string

The data to write to shared memoy.

Nota:

If the size of the data exceeds the size of the shared memory, the number of bytes written returned will be less than the length of the input.

start

The start/offset, in bytes, to begin writing.

Nota:

If the value is negative, the starting position will begin at the specified number of bytes from the end of the shared memory segment.

Valorile întoarse

An integer containing the number of bytes written to shared memory.

Exemple

Example #1 SyncSharedMemory::write() example

<?php
// You will probably need to protect shared memory with other synchronization objects.
// Shared memory goes away when the last reference to it disappears.
$mem = new SyncSharedMemory("AppReportName", 1024);
if ($mem->first())
{
    // Do first time initialization work here.
}

$result = $mem->write("report.txt");
var_dump($result);

$result = $mem->write("report.txt", -3);
var_dump($result);
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(10)
int(3)

A se vedea ?i

  • SyncSharedMemory::__construct() - Constructs a new SyncSharedMemory object
  • SyncSharedMemory::first() - Check to see if the object is the first instance system-wide of named shared memory
  • SyncSharedMemory::write()
  • SyncSharedMemory::read() - Copy data from named shared memory
SyncSharedMemory::size
Alte extensii de baza
SyncSharedMemory


Alte extensii de baza

  • GeoIP — Geo IP Location
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii GeoIP
  • FANN — FANN (Fast Artificial Neural Network)
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii fann
    • FANNConnection — The FANNConnection class
  • JSON — Notarea Obiect JavaScript
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • JsonSerializable — Interfa?a JsonSerializable
    • Func?ii JSON
  • Judy — Judy Arrays
    • Introducere
    • Instalarea / configurarea
    • Judy — The Judy class
    • Func?ii Judy
  • Lua
    • Introducere
    • Instalarea / configurarea
    • Lua — The Lua class
    • LuaClosure — The LuaClosure class
  • Diverse — Func?ii diverse
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii diverse
    • Jurnalul modificarilor
  • Parsekit
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Parsekit
  • SPL — Standard PHP Library (SPL)
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Structuri de date
    • Iteratori
    • Interfe?e
    • Excep?ii
    • Func?ii SPL
    • Manipularea fi?ierelor
    • Clase ?i interfe?e diverse
  • SPL Types — SPL Type Handling
    • Introducere
    • Instalarea / configurarea
    • 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
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Stream Filters
    • Stream Contexts
    • Stream Errors
    • Exemple
    • php_user_filter — The php_user_filter class
    • streamWrapper — The streamWrapper class
    • Func?ii de flux
  • Tidy
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • tidy — The tidy class
    • tidyNode — The tidyNode class
    • Func?ii Tidy
  • Tokenizer
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Tokenizer
  • URL-uri
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii URL
  • V8js — Integrarea cu motorul Javascript V8
    • Introducere
    • Instalarea / configurarea
    • Exemple
    • V8Js — The V8Js class
    • V8JsException — Clasa V8JsException
  • Yaml — YAML Data Serialization
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Callbacks
    • Func?ii Yaml
  • Yaf — Yet Another Framework
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • 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
  • Taint
    • Introducere
    • Instalarea / configurarea
    • More Details
    • Func?ii taint
SyncSharedMemory::write
GeoIP
Informa?ii de referin?a despre func?ii


Geo IP Location

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii GeoIP
    • geoip_asnum_by_name — Get the Autonomous System Numbers (ASN)
    • 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_domain_by_name — Get the second level domain name
    • geoip_id_by_name — Get the Internet connection type
    • geoip_isp_by_name — Get the Internet Service Provider (ISP) name
    • geoip_netspeedcell_by_name — Get the Internet connection speed
    • 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_setup_custom_directory — Set a custom directory for the GeoIP database.
    • geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo
Alte extensii de baza
Introducere
Alte extensii de baza


Introducere

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
Instalarea / configurarea
GeoIP


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
GeoIP


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/geoip.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

GeoIP Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
geoip.custom_directory | "" | PHP_INI_ALL |

Iata o explica?ie pe scurt a directivelor de configurare.

geoip.custom_directory string

Empty by default, but can be set to force a different database path than the one compiled in the library.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
Tipurile resurselor
Func?ii GeoIP
GeoIP


Func?ii GeoIP

Cuprins

  • geoip_asnum_by_name — Get the Autonomous System Numbers (ASN)
  • 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_domain_by_name — Get the second level domain name
  • geoip_id_by_name — Get the Internet connection type
  • geoip_isp_by_name — Get the Internet Service Provider (ISP) name
  • geoip_netspeedcell_by_name — Get the Internet connection speed
  • 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_setup_custom_directory — Set a custom directory for the GeoIP database.
  • geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo
Constante predefinite
geoip_asnum_by_name
GeoIP


Get the Autonomous System Numbers (ASN)

Func?ii GeoIP
geoip_continent_code_by_name
Func?ii GeoIP
PHP Manual

geoip_asnum_by_name

(PECL geoip >= 1.1.0)

geoip_asnum_by_name — Get the Autonomous System Numbers (ASN)

Descrierea

string geoip_asnum_by_name ( string $hostname )

The geoip_asnum_by_name() function will return the Autonomous System Numbers (ASN) associated with an IP address.

Parametri

hostname

The hostname or IP address.

Valorile întoarse

Returns the ASN on success, or FALSE if the address cannot be found in the database.

Exemple

Example #1 A geoip_asnum_by_name() example

This will output the ASN of the host www.example.com.

<?php
$asn = geoip_asnum_by_name('www.example.com');

if ($asn) {
    echo 'The ASN is: ' $asn;
}
?>

Exemplul de mai sus va afi?a:

The ASN is: AS15133 EdgeCast Networks, Inc

Func?ii GeoIP
geoip_continent_code_by_name
Func?ii GeoIP


Get the two letter continent code

geoip_asnum_by_name
geoip_country_code_by_name
Func?ii GeoIP
PHP Manual

geoip_continent_code_by_name

(PECL geoip >= 1.0.3)

geoip_continent_code_by_name — Get the two letter continent code

Descrierea

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.

Parametri

hostname

The hostname or IP address whose location is to be looked-up.

Valorile întoarse

Returns the two letter continent code on success, or FALSE if the address cannot be found in the database.

Continent codes
Code | Continent name
AF | Africa
AN | Antarctica
AS | Asia
EU | Europe
NA | North america
OC | Oceania
SA | South america

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

 This host is located in: NA

A se vedea ?i

  • geoip_country_code_by_name() - Get the two letter country code

geoip_asnum_by_name
geoip_country_code_by_name
Func?ii GeoIP


Get the two letter country code

geoip_continent_code_by_name
geoip_country_code3_by_name
Func?ii GeoIP
PHP Manual

geoip_country_code_by_name

(PECL geoip >= 0.2.0)

geoip_country_code_by_name — Get the two letter country code

Descrierea

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.

Parametri

hostname

The hostname or IP address whose location is to be looked-up.

Valorile întoarse

Returns the two letter ISO country code on success, or FALSE if the address cannot be found in the database.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

This host is located in: US

Note

Precautie

Please see » http://www.maxmind.com/en/iso3166 for a complete list of possible return values, including special codes.

A se vedea ?i

  • 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
Func?ii GeoIP


Get the three letter country code

geoip_country_code_by_name
geoip_country_name_by_name
Func?ii GeoIP
PHP Manual

geoip_country_code3_by_name

(PECL geoip >= 0.2.0)

geoip_country_code3_by_name — Get the three letter country code

Descrierea

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.

Parametri

hostname

The hostname or IP address whose location is to be looked-up.

Valorile întoarse

Returns the three letter country code on success, or FALSE if the address cannot be found in the database.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

This host is located in: USA

A se vedea ?i

  • 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
Func?ii GeoIP


Get the full country name

geoip_country_code3_by_name
geoip_database_info
Func?ii GeoIP
PHP Manual

geoip_country_name_by_name

(PECL geoip >= 0.2.0)

geoip_country_name_by_name — Get the full country name

Descrierea

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.

Parametri

hostname

The hostname or IP address whose location is to be looked-up.

Valorile întoarse

Returns the country name on success, or FALSE if the address cannot be found in the database.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

 This host is located in: United States

A se vedea ?i

  • 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
Func?ii GeoIP


Get GeoIP Database information

geoip_country_name_by_name
geoip_db_avail
Func?ii GeoIP
PHP Manual

geoip_database_info

(PECL geoip >= 0.2.0)

geoip_database_info — Get GeoIP Database information

Descrierea

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.

Parametri

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Valorile întoarse

Returns the corresponding database version, or NULL on error.

Exemple

Example #1 A geoip_database_info() example

This will output information regarding the database.

<?php
print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>

Exemplul de mai sus va afi?a:

GEO-106FREE 20060801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved

geoip_country_name_by_name
geoip_db_avail
Func?ii GeoIP


Determine if GeoIP Database is available

geoip_database_info
geoip_db_filename
Func?ii GeoIP
PHP Manual

geoip_db_avail

(PECL geoip >= 1.0.1)

geoip_db_avail — Determine if GeoIP Database is available

Descrierea

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.

Parametri

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Valorile întoarse

Returns TRUE is database exists, FALSE if not found, or NULL on error.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

GEO-106FREE 20080801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved

geoip_database_info
geoip_db_filename
Func?ii GeoIP


Returns the filename of the corresponding GeoIP Database

geoip_db_avail
geoip_db_get_all_info
Func?ii GeoIP
PHP Manual

geoip_db_filename

(PECL geoip >= 1.0.1)

geoip_db_filename — Returns the filename of the corresponding GeoIP Database

Descrierea

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.

Parametri

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Valorile întoarse

Returns the filename of the corresponding database, or NULL on error.

Exemple

Example #1 A geoip_db_filename() example

This will output the filename of the corresponding database.

<?php

print geoip_db_filename(GEOIP_COUNTRY_EDITION);

?>

Exemplul de mai sus va afi?a:

/usr/share/GeoIP/GeoIP.dat

geoip_db_avail
geoip_db_get_all_info
Func?ii GeoIP


Returns detailed information about all GeoIP database types

geoip_db_filename
geoip_domain_by_name
Func?ii GeoIP
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

Descrierea

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())

Valorile întoarse

Returns the associative array.

Exemple

Example #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);
}
?>

Exemplul de mai sus va afi?a:

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"
  }
}

Example #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'];
}
?>

Exemplul de mai sus va afi?a:

GeoIP Country Edition

geoip_db_filename
geoip_domain_by_name
Func?ii GeoIP


Get the second level domain name

geoip_db_get_all_info
geoip_id_by_name
Func?ii GeoIP
PHP Manual

geoip_domain_by_name

(PECL geoip >= 1.1.0)

geoip_domain_by_name — Get the second level domain name

Descrierea

string geoip_domain_by_name ( string $hostname )

The geoip_domain_by_name() function will return the second level domain names associated with a hostname or an IP address.

This function is currently only available to users who have bought a commercial GeoIP Domain Edition. A warning will be issued if the proper database cannot be located.

Parametri

hostname

The hostname or IP address.

Valorile întoarse

Returns the domain name on success, or FALSE if the address cannot be found in the database.

Exemple

Example #1 A geoip_domain_by_name() example

This will output the domain associated with IP 61.106.139.1.

<?php
$domain = geoip_domain_by_name('61.106.139.1');

if ($domain) {
    echo 'The domain is: '. $domain;
}

?>

Exemplul de mai sus va afi?a:

The domain is: von.co.kr

geoip_db_get_all_info
geoip_id_by_name
Func?ii GeoIP


Get the Internet connection type

geoip_domain_by_name
geoip_isp_by_name
Func?ii GeoIP
PHP Manual

geoip_id_by_name

(PECL geoip >= 0.2.0)

geoip_id_by_name — Get the Internet connection type

Descrierea

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

Parametri

hostname

The hostname or IP address whose connection type is to be looked-up.

Valorile întoarse

Returns the connection type.

Exemple

Example #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';
}
?>

Exemplul de mai sus va afi?a:

The connection type is corporate

geoip_domain_by_name
geoip_isp_by_name
Func?ii GeoIP


Get the Internet Service Provider (ISP) name

geoip_id_by_name
geoip_netspeedcell_by_name
Func?ii GeoIP
PHP Manual

geoip_isp_by_name

(PECL geoip >= 1.0.2)

geoip_isp_by_name — Get the Internet Service Provider (ISP) name

Descrierea

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.

Parametri

hostname

The hostname or IP address.

Valorile întoarse

Returns the ISP name on success, or FALSE if the address cannot be found in the database.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

This host IP is from ISP: ICANN c/o Internet Assigned Numbers Authority

geoip_id_by_name
geoip_netspeedcell_by_name
Func?ii GeoIP


Get the Internet connection speed

geoip_isp_by_name
geoip_org_by_name
Func?ii GeoIP
PHP Manual

geoip_netspeedcell_by_name

(PECL geoip >= 1.1.0)

geoip_netspeedcell_by_name — Get the Internet connection speed

Descrierea

string geoip_netspeedcell_by_name ( string $hostname )

The geoip_netspeedcell_by_name() function will return the Internet connection type and speed corresponding to a hostname or an IP address.

This function is only available if using GeoIP Library version 1.4.8 or newer.

This function is currently only available to users who have bought a commercial GeoIP NetSpeedCell Edition. A warning will be issued if the proper database cannot be located.

The return value is a string, common values are:

  • Cable/DSL
  • Dialup
  • Cellular
  • Corporate

Parametri

hostname

The hostname or IP address.

Valorile întoarse

Returns the connection speed on success, or FALSE if the address cannot be found in the database.

Exemple

Example #1 A geoip_netspeedcell_by_name() example

This will output the connection speed of the host example.com.

<?php
$netspeed = geoip_netspeedcell_by_name('www.example.com');

if ($netspeed) {
    echo 'The connection type is: '. $netspeed;
}
?>

Exemplul de mai sus va afi?a:

The connection type is: Corporate

geoip_isp_by_name
geoip_org_by_name
Func?ii GeoIP


Get the organization name

geoip_netspeedcell_by_name
geoip_record_by_name
Func?ii GeoIP
PHP Manual

geoip_org_by_name

(PECL geoip >= 0.2.0)

geoip_org_by_name — Get the organization name

Descrierea

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.

Parametri

hostname

The hostname or IP address.

Valorile întoarse

Returns the organization name on success, or FALSE if the address cannot be found in the database.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

This host IP is allocated to: ICANN c/o Internet Assigned Numbers Authority

geoip_netspeedcell_by_name
geoip_record_by_name
Func?ii GeoIP


Returns the detailed City information found in the GeoIP Database

geoip_org_by_name
geoip_region_by_name
Func?ii GeoIP
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

Descrierea

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)

Parametri

hostname

The hostname or IP address whose record is to be looked-up.

Valorile întoarse

Returns the associative array on success, or FALSE if the address cannot be found in the database.

Istoricul schimbarilor

Versiune | Descriere
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

Exemple

Example #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);
}
?>

Exemplul de mai sus va afi?a:

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
Func?ii GeoIP


Get the country code and region

geoip_record_by_name
geoip_region_name_by_code
Func?ii GeoIP
PHP Manual

geoip_region_by_name

(PECL geoip >= 0.2.0)

geoip_region_by_name — Get the country code and region

Descrierea

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)

Parametri

hostname

The hostname or IP address whose region is to be looked-up.

Valorile întoarse

Returns the associative array on success, or FALSE if the address cannot be found in the database.

Exemple

Example #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);
}
?>

Exemplul de mai sus va afi?a:

Array
(
    [country_code] => US
    [region] => CA
)

geoip_record_by_name
geoip_region_name_by_code
Func?ii GeoIP


Returns the region name for some country and region code combo

geoip_region_by_name
geoip_setup_custom_directory
Func?ii GeoIP
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

Descrierea

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.

Parametri

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())

Valorile întoarse

Returns the region name on success, or FALSE if the country and region code combo cannot be found.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

Region name for CA/QC is: Quebec

Example #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;
}
?>

Exemplul de mai sus va afi?a:

Region name for JP/01 is: Aichi

geoip_region_by_name
geoip_setup_custom_directory
Func?ii GeoIP


Set a custom directory for the GeoIP database.

geoip_region_name_by_code
geoip_time_zone_by_country_and_region
Func?ii GeoIP
PHP Manual

geoip_setup_custom_directory

(PECL geoip >= 1.1.0)

geoip_setup_custom_directory — Set a custom directory for the GeoIP database.

Descrierea

void geoip_setup_custom_directory ( string $path )

The geoip_setup_custom_directory() function will change the default directory of the GeoIP database. This is equivalent to changing geoip.custom_directory.

Parametri

path

The full path of where the GeoIP database is on disk.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 A geoip_setup_custom_directory() example

This will change the GeoIP default database path.

<?php

geoip_setup_custom_directory('/some/other/path');

print geoip_db_filename(GEOIP_COUNTRY_EDITION);

?>

Exemplul de mai sus va afi?a:

/some/other/path/GeoIP.dat

geoip_region_name_by_code
geoip_time_zone_by_country_and_region
Func?ii GeoIP


Returns the time zone for some country and region code combo

geoip_setup_custom_directory
FANN
Func?ii GeoIP
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

Descrierea

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.

Parametri

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())

Valorile întoarse

Returns the time zone on success, or FALSE if the country and region code combo cannot be found.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

Time zone for CA/QC is: America/Montreal

Example #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;
}
?>

Exemplul de mai sus va afi?a:

Time zone for JP/01 is: Asia/Tokyo

geoip_setup_custom_directory
FANN
Func?ii GeoIP


FANN (Fast Artificial Neural Network)

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • XOR training
  • Func?ii fann
    • fann_cascadetrain_on_data — Trains on an entire dataset, for a period of time using the Cascade2 training algorithm
    • fann_cascadetrain_on_file — Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm.
    • fann_clear_scaling_params — Clears scaling parameters
    • fann_copy — Creates a copy of a fann structure
    • fann_create_from_file — Constructs a backpropagation neural network from a configuration file
    • fann_create_shortcut_array — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_shortcut — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_sparse_array — Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
    • fann_create_sparse — Creates a standard backpropagation neural network, which is not fully connected
    • fann_create_standard_array — Creates a standard fully connected backpropagation neural network using an array of layer sizes
    • fann_create_standard — Creates a standard fully connected backpropagation neural network
    • fann_create_train_from_callback — Creates the training data struct from a user supplied function
    • fann_create_train — Creates an empty training data struct
    • fann_descale_input — Scale data in input vector after get it from ann based on previously calculated parameters
    • fann_descale_output — Scale data in output vector after get it from ann based on previously calculated parameters
    • fann_descale_train — Descale input and output data based on previously calculated parameters
    • fann_destroy_train — Destructs the training data
    • fann_destroy — Destroys the entire network and properly freeing all the associated memory
    • fann_duplicate_train_data — Returns an exact copy of a fann train data
    • fann_get_activation_function — Returns the activation function
    • fann_get_activation_steepness — Returns the activation steepness for supplied neuron and layer number
    • fann_get_bias_array — Get the number of bias in each layer in the network
    • fann_get_bit_fail_limit — Returns the bit fail limit used during training
    • fann_get_bit_fail — The number of fail bits
    • fann_get_cascade_activation_functions_count — Returns the number of cascade activation functions
    • fann_get_cascade_activation_functions — Returns the cascade activation functions
    • fann_get_cascade_activation_steepnesses_count — The number of activation steepnesses
    • fann_get_cascade_activation_steepnesses — Returns the cascade activation steepnesses
    • fann_get_cascade_candidate_change_fraction — Returns the cascade candidate change fraction
    • fann_get_cascade_candidate_limit — Return the candidate limit
    • fann_get_cascade_candidate_stagnation_epochs — Returns the number of cascade candidate stagnation epochs
    • fann_get_cascade_max_cand_epochs — Returns the maximum candidate epochs
    • fann_get_cascade_max_out_epochs — Returns the maximum out epochs
    • fann_get_cascade_min_cand_epochs — Returns the minimum candidate epochs
    • fann_get_cascade_min_out_epochs — Returns the minimum out epochs
    • fann_get_cascade_num_candidate_groups — Returns the number of candidate groups
    • fann_get_cascade_num_candidates — Returns the number of candidates used during training
    • fann_get_cascade_output_change_fraction — Returns the cascade output change fraction
    • fann_get_cascade_output_stagnation_epochs — Returns the number of cascade output stagnation epochs
    • fann_get_cascade_weight_multiplier — Returns the weight multiplier
    • fann_get_connection_array — Get connections in the network
    • fann_get_connection_rate — Get the connection rate used when the network was created
    • fann_get_errno — Returns the last error number
    • fann_get_errstr — Returns the last errstr
    • fann_get_layer_array — Get the number of neurons in each layer in the network
    • fann_get_learning_momentum — Returns the learning momentum
    • fann_get_learning_rate — Returns the learning rate
    • fann_get_MSE — Reads the mean square error from the network
    • fann_get_network_type — Get the type of neural network it was created as
    • fann_get_num_input — Get the number of input neurons
    • fann_get_num_layers — Get the number of layers in the neural network
    • fann_get_num_output — Get the number of output neurons
    • fann_get_quickprop_decay — Returns the decay which is a factor that weights should decrease in each iteration during quickprop training
    • fann_get_quickprop_mu — Returns the mu factor
    • fann_get_rprop_decrease_factor — Returns the increase factor used during RPROP training
    • fann_get_rprop_delta_max — Returns the maximum step-size
    • fann_get_rprop_delta_min — Returns the minimum step-size
    • fann_get_rprop_delta_zero — Returns the initial step-size
    • fann_get_rprop_increase_factor — Returns the increase factor used during RPROP training
    • fann_get_sarprop_step_error_shift — Returns the sarprop step error shift
    • fann_get_sarprop_step_error_threshold_factor — Returns the sarprop step error threshold factor
    • fann_get_sarprop_temperature — Returns the sarprop temperature
    • fann_get_sarprop_weight_decay_shift — Returns the sarprop weight decay shift
    • fann_get_total_connections — Get the total number of connections in the entire network
    • fann_get_total_neurons — Get the total number of neurons in the entire network
    • fann_get_train_error_function — Returns the error function used during training
    • fann_get_train_stop_function — Returns the stop function used during training
    • fann_get_training_algorithm — Returns the training algorithm
    • fann_init_weights — Initialize the weights using Widrow + Nguyen’s algorithm
    • fann_length_train_data — Returns the number of training patterns in the train data
    • fann_merge_train_data — Merges the train data
    • fann_num_input_train_data — Returns the number of inputs in each of the training patterns in the train data
    • fann_num_output_train_data — Returns the number of outputs in each of the training patterns in the train data
    • fann_print_error — Prints the error string
    • fann_randomize_weights — Give each connection a random weight between min_weight and max_weight
    • fann_read_train_from_file — Reads a file that stores training data
    • fann_reset_errno — Resets the last error number
    • fann_reset_errstr — Resets the last error string
    • fann_reset_MSE — Resets the mean square error from the network
    • fann_run — Will run input through the neural network
    • fann_save_train — Save the training structure to a file
    • fann_save — Saves the entire network to a configuration file
    • fann_scale_input_train_data — Scales the inputs in the training data to the specified range
    • fann_scale_input — Scale data in input vector before feed it to ann based on previously calculated parameters
    • fann_scale_output_train_data — Scales the outputs in the training data to the specified range
    • fann_scale_output — Scale data in output vector before feed it to ann based on previously calculated parameters
    • fann_scale_train_data — Scales the inputs and outputs in the training data to the specified range
    • fann_scale_train — Scale input and output data based on previously calculated parameters
    • fann_set_activation_function_hidden — Sets the activation function for all of the hidden layers
    • fann_set_activation_function_layer — Sets the activation function for all the neurons in the supplied layer.
    • fann_set_activation_function_output — Sets the activation function for the output layer
    • fann_set_activation_function — Sets the activation function for supplied neuron and layer
    • fann_set_activation_steepness_hidden — Sets the steepness of the activation steepness for all neurons in the all hidden layers
    • fann_set_activation_steepness_layer — Sets the activation steepness for all of the neurons in the supplied layer number
    • fann_set_activation_steepness_output — Sets the steepness of the activation steepness in the output layer
    • fann_set_activation_steepness — Sets the activation steepness for supplied neuron and layer number
    • fann_set_bit_fail_limit — Set the bit fail limit used during training
    • fann_set_callback — Sets the callback function for use during training
    • fann_set_cascade_activation_functions — Sets the array of cascade candidate activation functions
    • fann_set_cascade_activation_steepnesses — Sets the array of cascade candidate activation steepnesses
    • fann_set_cascade_candidate_change_fraction — Sets the cascade candidate change fraction
    • fann_set_cascade_candidate_limit — Sets the candidate limit
    • fann_set_cascade_candidate_stagnation_epochs — Sets the number of cascade candidate stagnation epochs
    • fann_set_cascade_max_cand_epochs — Sets the max candidate epochs
    • fann_set_cascade_max_out_epochs — Sets the maximum out epochs
    • fann_set_cascade_min_cand_epochs — Sets the min candidate epochs
    • fann_set_cascade_min_out_epochs — Sets the minimum out epochs
    • fann_set_cascade_num_candidate_groups — Sets the number of candidate groups
    • fann_set_cascade_output_change_fraction — Sets the cascade output change fraction
    • fann_set_cascade_output_stagnation_epochs — Sets the number of cascade output stagnation epochs
    • fann_set_cascade_weight_multiplier — Sets the weight multiplier
    • fann_set_error_log — Sets where the errors are logged to
    • fann_set_input_scaling_params — Calculate input scaling parameters for future use based on training data
    • fann_set_learning_momentum — Sets the learning momentum
    • fann_set_learning_rate — Sets the learning rate
    • fann_set_output_scaling_params — Calculate output scaling parameters for future use based on training data
    • fann_set_quickprop_decay — Sets the quickprop decay factor
    • fann_set_quickprop_mu — Sets the quickprop mu factor
    • fann_set_rprop_decrease_factor — Sets the decrease factor used during RPROP training
    • fann_set_rprop_delta_max — Sets the maximum step-size
    • fann_set_rprop_delta_min — Sets the minimum step-size
    • fann_set_rprop_delta_zero — Sets the initial step-size
    • fann_set_rprop_increase_factor — Sets the increase factor used during RPROP training
    • fann_set_sarprop_step_error_shift — Sets the sarprop step error shift
    • fann_set_sarprop_step_error_threshold_factor — Sets the sarprop step error threshold factor
    • fann_set_sarprop_temperature — Sets the sarprop temperature
    • fann_set_sarprop_weight_decay_shift — Sets the sarprop weight decay shift
    • fann_set_scaling_params — Calculate input and output scaling parameters for future use based on training data
    • fann_set_train_error_function — Sets the error function used during training
    • fann_set_train_stop_function — Sets the stop function used during training
    • fann_set_training_algorithm — Sets the training algorithm
    • fann_set_weight_array — Set connections in the network
    • fann_set_weight — Set a connection in the network
    • fann_shuffle_train_data — Shuffles training data, randomizing the order
    • fann_subset_train_data — Returns an copy of a subset of the train data
    • fann_test_data — Test a set of training data and calculates the MSE for the training data
    • fann_test — Test with a set of inputs, and a set of desired outputs
    • fann_train_epoch — Train one epoch with a set of training data
    • fann_train_on_data — Trains on an entire dataset for a period of time
    • fann_train_on_file — Trains on an entire dataset, which is read from file, for a period of time
    • fann_train — Train one iteration with a set of inputs, and a set of desired outputs
  • FANNConnection — The FANNConnection class
    • FANNConnection::__construct — The connection constructor
    • FANNConnection::getFromNeuron — Returns the postions of starting neuron.
    • FANNConnection::getToNeuron — Returns the postions of terminating neuron
    • FANNConnection::getWeight — Returns the connection weight
    • FANNConnection::setWeight — Sets the connections weight
geoip_time_zone_by_country_and_region
Introducere
Alte extensii de baza


Introducere

PHP binding for FANN (Fast Artificial Neural Network) Library which implements multilayer artificial neural networks with support for both fully connected and sparsely connected networks. It includes a framework for easy handling of training data sets. It is easy to use, versatile, well documented, and fast.

FANN
Instalarea / configurarea
FANN


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
FANN


Necesita?i

PHP >= 5.2.0 and libfann >= 2.1.0

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

The FANN PHP extension should work on all Linux systems.

  • FANN Library Installation
  • PECL Installation
  • Manual Installation

FANN Library Installation

Before you start installation make sure that libfann is installed on your system. It's part of the main repository in the most Linux distributions (search for fann). You need a development version.

If it is not installed, you need to install it first. Either download it from the » official site or get it from your distro repository. For example on Fedora:

$ sudo yum install fann-devel
or Ubuntu:

$ sudo apt-get install libfann-dev

If the library is re-installed manually, then all old library file should be removed before re-installing otherwise the old library version could be linked.

PECL Installation

This extension is available on PECL. The installation is very simple. Just run:

$ sudo pecl install fann

Manual Installation

For developers and people interested in the latest changes, you can compile the driver from the latest source code on » Github. Go to Github and click the "Download ZIP" button. Then run:

$ unzip php-fann-master.zip
$ cd php-fann-master
$ phpize
$ ./configure
$ make all
$ sudo make install

Make the following changes to php.ini:

  • Make sure the extension_dir variable is pointing to the directory containing fann.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-non-zts-20060613/fann.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-non-zts-20060613 =>
                   /usr/lib/php/extensions/no-debug-non-zts-20060613
    If it's not, change the extension_dir in php.ini or move fann.so.

  • To load the extension on PHP startup, add a line:

extension=fann.so

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Training algorithms
FANN_TRAIN_INCREMENTAL (integer)
Standard backpropagation algorithm, where the weights are updated after each training pattern. This means that the weights are updated many times during a single epoch. For this reason some problems, will train very fast with this algorithm, while other more advanced problems will not train very well.
FANN_TRAIN_BATCH (integer)
Standard backpropagation algorithm, where the weights are updated after calculating the mean square error for the whole training set. This means that the weights are only updated once during a epoch. For this reason some problems, will train slower with this algorithm. But since the mean square error is calculated more correctly than in incremental training, some problems will reach a better solutions with this algorithm.
FANN_TRAIN_RPROP (integer)
A more advanced batch training algorithm which achieves good results for many problems. The RPROP training algorithm is adaptive, and does therefore not use the learning_rate. Some other parameters can however be set to change the way the RPROP algorithm works, but it is only recommended for users with insight in how the RPROP training algorithm works. The RPROP training algorithm is described by [Riedmiller and Braun, 1993], but the actual learning algorithm used here is the iRPROP- training algorithm which is described by [Igel and Husken, 2000] which is an variety of the standard RPROP training algorithm.
FANN_TRAIN_QUICKPROP (integer)
A more advanced batch training algorithm which achieves good results for many problems. The quickprop training algorithm uses the learning_rate parameter along with other more advanced parameters, but it is only recommended to change these advanced parameters, for users with insight in how the quickprop training algorithm works. The quickprop training algorithm is described by [Fahlman, 1988].
FANN_TRAIN_SARPROP (integer)
Even more advance training algorithm. Only for version 2.2
Activation functions
FANN_LINEAR (integer)
Linear activation function.
FANN_THRESHOLD (integer)
Threshold activation function.
FANN_THRESHOLD_SYMMETRIC (integer)
Threshold activation function.
FANN_SIGMOID (integer)
Sigmoid activation function.
FANN_SIGMOID_STEPWISE (integer)
Stepwise linear approximation to sigmoid.
FANN_SIGMOID_SYMMETRIC (integer)
Symmetric sigmoid activation function, aka. tanh.
FANN_SIGMOID_SYMMETRIC_STEPWISE (integer)
Stepwise linear approximation to symmetric sigmoid
FANN_GAUSSIAN (integer)
Gaussian activation function.
FANN_GAUSSIAN_SYMMETRIC (integer)
Symmetric gaussian activation function.
FANN_GAUSSIAN_STEPWISE (integer)
Stepwise gaussian activation function.
FANN_ELLIOT (integer)
Fast (sigmoid like) activation function defined by David Elliott.
FANN_ELLIOT_SYMMETRIC (integer)
Fast (symmetric sigmoid like) activation function defined by David Elliott.
FANN_LINEAR_PIECE (integer)
Bounded linear activation function.
FANN_LINEAR_PIECE_SYMMETRIC (integer)
Bounded linear activation function.
FANN_SIN_SYMMETRIC (integer)
Periodical sinus activation function.
FANN_COS_SYMMETRIC (integer)
Periodical cosinus activation function.
FANN_SIN (integer)
Periodical sinus activation function.
FANN_COS (integer)
Periodical cosinus activation function.
Error function used during training
FANN_ERRORFUNC_LINEAR (integer)
Standard linear error function.
FANN_ERRORFUNC_TANH (integer)
Tanh error function, usually better but can require a lower learning rate. This error function agressively targets outputs that differ much from the desired, while not targetting outputs that only differ a little that much. This activation function is not recommended for cascade training and incremental training.
Stop criteria used during training
FANN_STOPFUNC_MSE (integer)
Stop criteria is Mean Square Error (MSE) value.
FANN_STOPFUNC_BIT (integer)
Stop criteria is number of bits that fail. The number of bits means the number of output neurons which differs more than the bit fail limit (see fann_get_bit_fail_limit, fann_set_bit_fail_limit). The bits are counted in all of the training data, so this number can be higher than the number of training data.
Definition of network types used by fann_get_network_type()
FANN_NETTYPE_LAYER (integer)
Each layer only has connections to the next layer.
FANN_NETTYPE_SHORTCUT (integer)
Each layer has connections to all following layers
Errors
FANN_E_NO_ERROR (integer)
No error.
FANN_E_CANT_OPEN_CONFIG_R (integer)
Unable to open configuration file for reading.
FANN_E_CANT_OPEN_CONFIG_W (integer)
Unable to open configuration file for writing.
FANN_E_WRONG_CONFIG_VERSION (integer)
Wrong version of configuration file.
FANN_E_CANT_READ_CONFIG (integer)
Error reading info from configuration file.
FANN_E_CANT_READ_NEURON (integer)
Error reading neuron info from configuration file.
FANN_E_CANT_READ_CONNECTIONS (integer)
Error reading connections from configuration file.
FANN_E_WRONG_NUM_CONNECTIONS (integer)
Number of connections not equal to the number expected.
FANN_E_CANT_OPEN_TD_W (integer)
Unable to open train data file for writing.
FANN_E_CANT_OPEN_TD_R (integer)
Unable to open train data file for reading.
FANN_E_CANT_READ_TD (integer)
Error reading training data from file.
FANN_E_CANT_ALLOCATE_MEM (integer)
Unable to allocate memory.
FANN_E_CANT_TRAIN_ACTIVATION (integer)
Unable to train with the selected activation function.
FANN_E_CANT_USE_ACTIVATION (integer)
Unable to use the selected activation function.
FANN_E_TRAIN_DATA_MISMATCH (integer)
Irreconcilable differences between two struct fann_train_data structures.
FANN_E_CANT_USE_TRAIN_ALG (integer)
Unable to use the selected training algorithm.
FANN_E_TRAIN_DATA_SUBSET (integer)
Trying to take subset which is not within the training set.
FANN_E_INDEX_OUT_OF_BOUND (integer)
Index is out of bound.
FANN_E_SCALE_NOT_PRESENT (integer)
Scaling parameters not present.
FANN_E_INPUT_NO_MATCH (integer)
The number of input neurons in the ann data do not match
FANN_E_OUTPUT_NO_MATCH (integer)
The number of output neurons in the ann and data do not match.

Tipurile resurselor
Exemple
FANN


Exemple

Cuprins

  • XOR training
Constante predefinite
XOR training
FANN


XOR training

This example shows how to train data for XOR function

Example #1 xor.data file

4 2 1
-1 -1
-1
-1 1
1
1 -1
1
1 1
-1

Example #2 Simple train

<?php
$num_input = 2;
$num_output = 1;
$num_layers = 3;
$num_neurons_hidden = 3;
$desired_error = 0.001;
$max_epochs = 500000;
$epochs_between_reports = 1000;

$ann = fann_create_standard($num_layers, $num_input, $num_neurons_hidden, $num_output);

if ($ann) {
    fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);
    fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);

    $filename = dirname(__FILE__) . "/xor.data";
    if (fann_train_on_file($ann, $filename, $max_epochs, $epochs_between_reports, $desired_error))
        fann_save($ann, dirname(__FILE__) . "/xor_float.net");

    fann_destroy($ann);
}
?>

This example shows how to read and run data for XOR function

Example #3 Simple test

<?php
$train_file = (dirname(__FILE__) . "/xor_float.net");
if (!is_file($train_file))
    die("The file xor_float.net has not been created! Please run simple_train.php to generate it");

$ann = fann_create_from_file($train_file);
if (!$ann)
    die("ANN could not be created");

$input = array(-1, 1);
$calc_out = fann_run($ann, $input);
printf("xor test (%f,%f) -> %f\n", $input[0], $input[1], $calc_out[0]);
fann_destroy($ann);
?>

Exemple
Func?ii fann
Exemple


Func?ii fann

Cuprins

  • fann_cascadetrain_on_data — Trains on an entire dataset, for a period of time using the Cascade2 training algorithm
  • fann_cascadetrain_on_file — Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm.
  • fann_clear_scaling_params — Clears scaling parameters
  • fann_copy — Creates a copy of a fann structure
  • fann_create_from_file — Constructs a backpropagation neural network from a configuration file
  • fann_create_shortcut_array — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
  • fann_create_shortcut — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
  • fann_create_sparse_array — Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
  • fann_create_sparse — Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_standard_array — Creates a standard fully connected backpropagation neural network using an array of layer sizes
  • fann_create_standard — Creates a standard fully connected backpropagation neural network
  • fann_create_train_from_callback — Creates the training data struct from a user supplied function
  • fann_create_train — Creates an empty training data struct
  • fann_descale_input — Scale data in input vector after get it from ann based on previously calculated parameters
  • fann_descale_output — Scale data in output vector after get it from ann based on previously calculated parameters
  • fann_descale_train — Descale input and output data based on previously calculated parameters
  • fann_destroy_train — Destructs the training data
  • fann_destroy — Destroys the entire network and properly freeing all the associated memory
  • fann_duplicate_train_data — Returns an exact copy of a fann train data
  • fann_get_activation_function — Returns the activation function
  • fann_get_activation_steepness — Returns the activation steepness for supplied neuron and layer number
  • fann_get_bias_array — Get the number of bias in each layer in the network
  • fann_get_bit_fail_limit — Returns the bit fail limit used during training
  • fann_get_bit_fail — The number of fail bits
  • fann_get_cascade_activation_functions_count — Returns the number of cascade activation functions
  • fann_get_cascade_activation_functions — Returns the cascade activation functions
  • fann_get_cascade_activation_steepnesses_count — The number of activation steepnesses
  • fann_get_cascade_activation_steepnesses — Returns the cascade activation steepnesses
  • fann_get_cascade_candidate_change_fraction — Returns the cascade candidate change fraction
  • fann_get_cascade_candidate_limit — Return the candidate limit
  • fann_get_cascade_candidate_stagnation_epochs — Returns the number of cascade candidate stagnation epochs
  • fann_get_cascade_max_cand_epochs — Returns the maximum candidate epochs
  • fann_get_cascade_max_out_epochs — Returns the maximum out epochs
  • fann_get_cascade_min_cand_epochs — Returns the minimum candidate epochs
  • fann_get_cascade_min_out_epochs — Returns the minimum out epochs
  • fann_get_cascade_num_candidate_groups — Returns the number of candidate groups
  • fann_get_cascade_num_candidates — Returns the number of candidates used during training
  • fann_get_cascade_output_change_fraction — Returns the cascade output change fraction
  • fann_get_cascade_output_stagnation_epochs — Returns the number of cascade output stagnation epochs
  • fann_get_cascade_weight_multiplier — Returns the weight multiplier
  • fann_get_connection_array — Get connections in the network
  • fann_get_connection_rate — Get the connection rate used when the network was created
  • fann_get_errno — Returns the last error number
  • fann_get_errstr — Returns the last errstr
  • fann_get_layer_array — Get the number of neurons in each layer in the network
  • fann_get_learning_momentum — Returns the learning momentum
  • fann_get_learning_rate — Returns the learning rate
  • fann_get_MSE — Reads the mean square error from the network
  • fann_get_network_type — Get the type of neural network it was created as
  • fann_get_num_input — Get the number of input neurons
  • fann_get_num_layers — Get the number of layers in the neural network
  • fann_get_num_output — Get the number of output neurons
  • fann_get_quickprop_decay — Returns the decay which is a factor that weights should decrease in each iteration during quickprop training
  • fann_get_quickprop_mu — Returns the mu factor
  • fann_get_rprop_decrease_factor — Returns the increase factor used during RPROP training
  • fann_get_rprop_delta_max — Returns the maximum step-size
  • fann_get_rprop_delta_min — Returns the minimum step-size
  • fann_get_rprop_delta_zero — Returns the initial step-size
  • fann_get_rprop_increase_factor — Returns the increase factor used during RPROP training
  • fann_get_sarprop_step_error_shift — Returns the sarprop step error shift
  • fann_get_sarprop_step_error_threshold_factor — Returns the sarprop step error threshold factor
  • fann_get_sarprop_temperature — Returns the sarprop temperature
  • fann_get_sarprop_weight_decay_shift — Returns the sarprop weight decay shift
  • fann_get_total_connections — Get the total number of connections in the entire network
  • fann_get_total_neurons — Get the total number of neurons in the entire network
  • fann_get_train_error_function — Returns the error function used during training
  • fann_get_train_stop_function — Returns the stop function used during training
  • fann_get_training_algorithm — Returns the training algorithm
  • fann_init_weights — Initialize the weights using Widrow + Nguyen’s algorithm
  • fann_length_train_data — Returns the number of training patterns in the train data
  • fann_merge_train_data — Merges the train data
  • fann_num_input_train_data — Returns the number of inputs in each of the training patterns in the train data
  • fann_num_output_train_data — Returns the number of outputs in each of the training patterns in the train data
  • fann_print_error — Prints the error string
  • fann_randomize_weights — Give each connection a random weight between min_weight and max_weight
  • fann_read_train_from_file — Reads a file that stores training data
  • fann_reset_errno — Resets the last error number
  • fann_reset_errstr — Resets the last error string
  • fann_reset_MSE — Resets the mean square error from the network
  • fann_run — Will run input through the neural network
  • fann_save_train — Save the training structure to a file
  • fann_save — Saves the entire network to a configuration file
  • fann_scale_input_train_data — Scales the inputs in the training data to the specified range
  • fann_scale_input — Scale data in input vector before feed it to ann based on previously calculated parameters
  • fann_scale_output_train_data — Scales the outputs in the training data to the specified range
  • fann_scale_output — Scale data in output vector before feed it to ann based on previously calculated parameters
  • fann_scale_train_data — Scales the inputs and outputs in the training data to the specified range
  • fann_scale_train — Scale input and output data based on previously calculated parameters
  • fann_set_activation_function_hidden — Sets the activation function for all of the hidden layers
  • fann_set_activation_function_layer — Sets the activation function for all the neurons in the supplied layer.
  • fann_set_activation_function_output — Sets the activation function for the output layer
  • fann_set_activation_function — Sets the activation function for supplied neuron and layer
  • fann_set_activation_steepness_hidden — Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_set_activation_steepness_layer — Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_output — Sets the steepness of the activation steepness in the output layer
  • fann_set_activation_steepness — Sets the activation steepness for supplied neuron and layer number
  • fann_set_bit_fail_limit — Set the bit fail limit used during training
  • fann_set_callback — Sets the callback function for use during training
  • fann_set_cascade_activation_functions — Sets the array of cascade candidate activation functions
  • fann_set_cascade_activation_steepnesses — Sets the array of cascade candidate activation steepnesses
  • fann_set_cascade_candidate_change_fraction — Sets the cascade candidate change fraction
  • fann_set_cascade_candidate_limit — Sets the candidate limit
  • fann_set_cascade_candidate_stagnation_epochs — Sets the number of cascade candidate stagnation epochs
  • fann_set_cascade_max_cand_epochs — Sets the max candidate epochs
  • fann_set_cascade_max_out_epochs — Sets the maximum out epochs
  • fann_set_cascade_min_cand_epochs — Sets the min candidate epochs
  • fann_set_cascade_min_out_epochs — Sets the minimum out epochs
  • fann_set_cascade_num_candidate_groups — Sets the number of candidate groups
  • fann_set_cascade_output_change_fraction — Sets the cascade output change fraction
  • fann_set_cascade_output_stagnation_epochs — Sets the number of cascade output stagnation epochs
  • fann_set_cascade_weight_multiplier — Sets the weight multiplier
  • fann_set_error_log — Sets where the errors are logged to
  • fann_set_input_scaling_params — Calculate input scaling parameters for future use based on training data
  • fann_set_learning_momentum — Sets the learning momentum
  • fann_set_learning_rate — Sets the learning rate
  • fann_set_output_scaling_params — Calculate output scaling parameters for future use based on training data
  • fann_set_quickprop_decay — Sets the quickprop decay factor
  • fann_set_quickprop_mu — Sets the quickprop mu factor
  • fann_set_rprop_decrease_factor — Sets the decrease factor used during RPROP training
  • fann_set_rprop_delta_max — Sets the maximum step-size
  • fann_set_rprop_delta_min — Sets the minimum step-size
  • fann_set_rprop_delta_zero — Sets the initial step-size
  • fann_set_rprop_increase_factor — Sets the increase factor used during RPROP training
  • fann_set_sarprop_step_error_shift — Sets the sarprop step error shift
  • fann_set_sarprop_step_error_threshold_factor — Sets the sarprop step error threshold factor
  • fann_set_sarprop_temperature — Sets the sarprop temperature
  • fann_set_sarprop_weight_decay_shift — Sets the sarprop weight decay shift
  • fann_set_scaling_params — Calculate input and output scaling parameters for future use based on training data
  • fann_set_train_error_function — Sets the error function used during training
  • fann_set_train_stop_function — Sets the stop function used during training
  • fann_set_training_algorithm — Sets the training algorithm
  • fann_set_weight_array — Set connections in the network
  • fann_set_weight — Set a connection in the network
  • fann_shuffle_train_data — Shuffles training data, randomizing the order
  • fann_subset_train_data — Returns an copy of a subset of the train data
  • fann_test_data — Test a set of training data and calculates the MSE for the training data
  • fann_test — Test with a set of inputs, and a set of desired outputs
  • fann_train_epoch — Train one epoch with a set of training data
  • fann_train_on_data — Trains on an entire dataset for a period of time
  • fann_train_on_file — Trains on an entire dataset, which is read from file, for a period of time
  • fann_train — Train one iteration with a set of inputs, and a set of desired outputs
XOR training
fann_cascadetrain_on_data
FANN


Trains on an entire dataset, for a period of time using the Cascade2 training algorithm

Func?ii fann
fann_cascadetrain_on_file
Func?ii fann
PHP Manual

fann_cascadetrain_on_data

(PECL fann >= 1.0.0)

fann_cascadetrain_on_data — Trains on an entire dataset, for a period of time using the Cascade2 training algorithm

Descrierea

bool fann_cascadetrain_on_data ( resource $ann , resource $data , int $max_neurons , int $neurons_between_reports , float $desired_error )

The cascade output change fraction is a number between 0 and 1 determining how large a fraction the fann_get_MSE() value should change within fann_get_cascade_output_stagnation_epochs() during training of the output connections, in order for the training not to stagnate. If the training stagnates, the training of the output connections will be ended and new candidates will be prepared.

This training uses the parameters set using the fann_set_cascade_..., but it also uses another training algorithm as it’s internal training algorithm. This algorithm can be set to either FANN_TRAIN_RPROP or FANN_TRAIN_QUICKPROP by fann_set_training_algorithm(), and the parameters set for these training algorithms will also affect the cascade training.

Parametri

ann

resource a unei re?ele neuronale.

data

resource a datelor pentru antrenarea re?elei neuronale.

max_neurons

The maximum number of neurons to be added to neural network.

neurons_between_reports

The number of neurons between printing a status report. A value of zero means no reports should be printed.

desired_error

The desired fann_get_MSE() or fann_get_bit_fail(), depending on which stop function is chosen by fann_set_train_stop_function()

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_cascadetrain_on_file() - Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm.

Func?ii fann
fann_cascadetrain_on_file
Func?ii fann


Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm.

fann_cascadetrain_on_data
fann_clear_scaling_params
Func?ii fann
PHP Manual

fann_cascadetrain_on_file

(PECL fann >= 1.0.0)

fann_cascadetrain_on_file — Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm.

Descrierea

bool fann_cascadetrain_on_file ( resource $ann , string $filename , int $max_neurons , int $neurons_between_reports , float $desired_error )

Does the same as fann_cascadetrain_on_data(), but reads the training data directly from a file.

Parametri

ann

resource a unei re?ele neuronale.

filename

The maximum number of neurons to be added to neural network

max_neurons

The number of neurons between printing a status report to stdout. A value of zero means no reports should be printed.

neurons_between_reports

The number of neurons between printing a status report. A value of zero means no reports should be printed.

desired_error

The desired fann_get_MSE() or fann_get_bit_fail(), depending on which stop function is chosen by fann_set_train_stop_function().

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_cascadetrain_on_data() - Trains on an entire dataset, for a period of time using the Cascade2 training algorithm

fann_cascadetrain_on_data
fann_clear_scaling_params
Func?ii fann


Clears scaling parameters

fann_cascadetrain_on_file
fann_copy
Func?ii fann
PHP Manual

fann_clear_scaling_params

(PECL fann >= 1.0.0)

fann_clear_scaling_params — Clears scaling parameters

Descrierea

bool fann_clear_scaling_params ( resource $ann )

Clears scaling parameters.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

fann_cascadetrain_on_file
fann_copy
Func?ii fann


Creates a copy of a fann structure

fann_clear_scaling_params
fann_create_from_file
Func?ii fann
PHP Manual

fann_copy

(PECL fann >= 1.0.0)

fann_copy — Creates a copy of a fann structure

Descrierea

resource fann_copy ( resource $ann )

Creates a copy of a fann structure.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

Returns a copy of neural network resource on success, or FALSE on error

A se vedea ?i

  • fann_test() - Test with a set of inputs, and a set of desired outputs

fann_clear_scaling_params
fann_create_from_file
Func?ii fann


Constructs a backpropagation neural network from a configuration file

fann_copy
fann_create_shortcut_array
Func?ii fann
PHP Manual

fann_create_from_file

(PECL fann >= 1.0.0)

fann_create_from_file — Constructs a backpropagation neural network from a configuration file

Descrierea

resource fann_create_from_file ( string $configuration_file )

Constructs a backpropagation neural network from a configuration file, which have been saved by fann_save().

Parametri

configuration_file

The configuration file path.

Valorile întoarse

Întoarce o resource a re?elei neuronale în caz de succes, sau FALSE în caz de eroare.

A se vedea ?i

  • fann_save() - Saves the entire network to a configuration file

fann_copy
fann_create_shortcut_array
Func?ii fann


Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

fann_create_from_file
fann_create_shortcut
Func?ii fann
PHP Manual

fann_create_shortcut_array

(PECL fann >= 1.0.0)

fann_create_shortcut_array — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

Descrierea

resource fann_create_shortcut_array ( int $num_layers , array $layers )

Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections using an array of layers sizes.

Parametri

num_layers

The total number of layers including the input and the output layer.

layers

An array of layers sizes.

Valorile întoarse

Returns a neural network resource on success, or FALSE on error.

A se vedea ?i

  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_standard() - Creates a standard fully connected backpropagation neural network

fann_create_from_file
fann_create_shortcut
Func?ii fann


Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

fann_create_shortcut_array
fann_create_sparse_array
Func?ii fann
PHP Manual

fann_create_shortcut

(PECL fann >= 1.0.0)

fann_create_shortcut — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

Descrierea

reference fann_create_shortcut ( int $num_layers , int $num_neurons1 , int $num_neurons2 [, int $... ] )

Creates a standard backpropagation neural network, which is not fully connected and which also has shortcut connections.

Shortcut connections are connections that skip layers. A fully connected network with shortcut connections, is a network where all neurons are connected to all neurons in later layers. Including direct connections from the input layer to the output layer.

Parametri

num_layers

The total number of layers including the input and the output layer.

num_neurons1

Number of neurons in the first layer.

num_neurons2

Number of neurons in the second layer.

...

Number of neurons in other layers.

Valorile întoarse

Returns a neural network resource on success, or FALSE on error.

A se vedea ?i

  • fann_create_shortcut_array() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_standard() - Creates a standard fully connected backpropagation neural network

fann_create_shortcut_array
fann_create_sparse_array
Func?ii fann


Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes

fann_create_shortcut
fann_create_sparse
Func?ii fann
PHP Manual

fann_create_sparse_array

(PECL fann >= 1.0.0)

fann_create_sparse_array — Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes

Descrierea

ReturnType fann_create_sparse_array ( float $connection_rate , int $num_layers , array $layers )

Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes.

Parametri

connection_rate

The connection rate controls how many connections there will be in the network. If the connection rate is set to 1, the network will be fully connected, but if it is set to 0.5 only half of the connections will be set. A connection rate of 1 will yield the same result as fann_create_standard().

num_layers

The total number of layers including the input and the output layer.

layers

An array of layer sizes.

Valorile întoarse

Returns a neural network resource on success, or FALSE on error.

A se vedea ?i

  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_standard() - Creates a standard fully connected backpropagation neural network
  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

fann_create_shortcut
fann_create_sparse
Func?ii fann


Creates a standard backpropagation neural network, which is not fully connected

fann_create_sparse_array
fann_create_standard_array
Func?ii fann
PHP Manual

fann_create_sparse

(PECL fann >= 1.0.0)

fann_create_sparse — Creates a standard backpropagation neural network, which is not fully connected

Descrierea

ReturnType fann_create_sparse ( float $connection_rate , int $num_layers , int $num_neurons1 , int $num_neurons2 [, int $... ] )

Creates a standard backpropagation neural network, which is not fully connected.

Parametri

connection_rate

The connection rate controls how many connections there will be in the network. If the connection rate is set to 1, the network will be fully connected, but if it is set to 0.5 only half of the connections will be set. A connection rate of 1 will yield the same result as fann_create_standard().

num_layers

The total number of layers including the input and the output layer.

num_neurons1

Number of neurons in the first layer.

num_neurons2

Number of neurons in the second layer.

...

Number of neurons in other layers.

Valorile întoarse

Returns a neural network resource on success, or FALSE on error.

A se vedea ?i

  • fann_create_sparse_array() - Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
  • fann_create_standard() - Creates a standard fully connected backpropagation neural network
  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

fann_create_sparse_array
fann_create_standard_array
Func?ii fann


Creates a standard fully connected backpropagation neural network using an array of layer sizes

fann_create_sparse
fann_create_standard
Func?ii fann
PHP Manual

fann_create_standard_array

(PECL fann >= 1.0.0)

fann_create_standard_array — Creates a standard fully connected backpropagation neural network using an array of layer sizes

Descrierea

resource fann_create_standard_array ( int $num_layers , array $layers )

Creates a standard fully connected backpropagation neural network.

There will be a bias neuron in each layer (except the output layer), and this bias neuron will be connected to all neurons in the next layer. When running the network, the bias nodes always emits 1.

To destroy a neural network use the fann_destroy() function.

Parametri

num_layers

The total number of layers including the input and the output layer.

layers

An array of layer sizes.

Valorile întoarse

Returns a neural network resource on success, or FALSE on error.

A se vedea ?i

  • fann_create_standard() - Creates a standard fully connected backpropagation neural network
  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

fann_create_sparse
fann_create_standard
Func?ii fann


Creates a standard fully connected backpropagation neural network

fann_create_standard_array
fann_create_train_from_callback
Func?ii fann
PHP Manual

fann_create_standard

(PECL fann >= 1.0.0)

fann_create_standard — Creates a standard fully connected backpropagation neural network

Descrierea

resource fann_create_standard ( int $num_layers , int $num_neurons1 , int $num_neurons2 [, int $... ] )

Creates a standard fully connected backpropagation neural network.

There will be a bias neuron in each layer (except the output layer), and this bias neuron will be connected to all neurons in the next layer. When running the network, the bias nodes always emits 1.

To destroy a neural network use the fann_destroy() function.

Parametri

num_layers

The total number of layers including the input and the output layer.

num_neurons1

Number of neurons in the first layer.

num_neurons2

Number of neurons in the second layer.

...

Number of neurons in other layers.

Valorile întoarse

Returns a neural network resource on success, or FALSE on error.

A se vedea ?i

  • fann_create_standard_array() - Creates a standard fully connected backpropagation neural network using an array of layer sizes
  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

fann_create_standard_array
fann_create_train_from_callback
Func?ii fann


Creates the training data struct from a user supplied function

fann_create_standard
fann_create_train
Func?ii fann
PHP Manual

fann_create_train_from_callback

(PECL fann >= 1.0.0)

fann_create_train_from_callback — Creates the training data struct from a user supplied function

Descrierea

resource fann_create_train_from_callback ( int $num_data , int $num_input , int $num_output , callable $user_function )

Creates the training data struct from a user supplied function. As the training data are numerable (data 1, data 2...), the user must write a function that receives the number of the training data set (input, output) and returns the set.

Parametri

num_data

The number of training data

num_input

The number of inputs per training data

num_output

The number of ouputs per training data

user_function

The user supplied function with following parameters:

  • num - The number of the training data set
  • num_input - The number of inputs per training data
  • num_output - The number of ouputs per training data

The function should return an associative array with keys input and output and two array values of input and output.

Valorile întoarse

Întoarce o resource a datelor pentru antrenarea re?elei neuronale în caz de succes, sau FALSE în caz de eroare.

Exemple

Example #1 fann_create_train_from_callback() example

<?php
function create_train_callback($num_data, $num_input, $num_output) {
    return array(
        "input" => array_fill(0, $num_input, 1),
        "output" => array_fill(0, $num_output, 1),
    );
}

$num_data = 3;
$num_input = 2;
$num_output = 1;
$train_data = fann_create_train_from_callback($num_data, $num_input, $num_output, "create_train_callback");
if ($train_data) {
    // Do something with $train_data
}
?>

A se vedea ?i

  • fann_read_train_from_file() - Reads a file that stores training data
  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_destroy_train() - Destructs the training data
  • fann_save_train() - Save the training structure to a file

fann_create_standard
fann_create_train
Func?ii fann


Creates an empty training data struct

fann_create_train_from_callback
fann_descale_input
Func?ii fann
PHP Manual

fann_create_train

(PECL fann >= 1.0.0)

fann_create_train — Creates an empty training data struct

Descrierea

resource fann_create_train ( int $num_data , int $num_input , int $num_output )

Creates an empty training data struct.

Parametri

num_data

The number of training data

num_input

The number of inputs per training data

num_output

The number of ouputs per training data

Valorile întoarse

Întoarce o resource a datelor pentru antrenarea re?elei neuronale în caz de succes, sau FALSE în caz de eroare.

A se vedea ?i

  • fann_read_train_from_file() - Reads a file that stores training data
  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_destroy_train() - Destructs the training data
  • fann_save_train() - Save the training structure to a file

fann_create_train_from_callback
fann_descale_input
Func?ii fann


Scale data in input vector after get it from ann based on previously calculated parameters

fann_create_train
fann_descale_output
Func?ii fann
PHP Manual

fann_descale_input

(PECL fann >= 1.0.0)

fann_descale_input — Scale data in input vector after get it from ann based on previously calculated parameters

Descrierea

bool fann_descale_input ( resource $ann , array $input_vector )

Scale data in input vector after get it from ann based on previously calculated parameters.

Parametri

ann

resource a unei re?ele neuronale.

input_vector

Input vector that will be descaled

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_scale_input() - Scale data in input vector before feed it to ann based on previously calculated parameters
  • fann_descale_output() - Scale data in output vector after get it from ann based on previously calculated parameters

fann_create_train
fann_descale_output
Func?ii fann


Scale data in output vector after get it from ann based on previously calculated parameters

fann_descale_input
fann_descale_train
Func?ii fann
PHP Manual

fann_descale_output

(PECL fann >= 1.0.0)

fann_descale_output — Scale data in output vector after get it from ann based on previously calculated parameters

Descrierea

bool fann_descale_output ( resource $ann , array $output_vector )

Scale data in output vector after get it from ann based on previously calculated parameters.

Parametri

ann

resource a unei re?ele neuronale.

output_vector

Output vector that will be descaled

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_scale_output() - Scale data in output vector before feed it to ann based on previously calculated parameters
  • fann_descale_input() - Scale data in input vector after get it from ann based on previously calculated parameters

fann_descale_input
fann_descale_train
Func?ii fann


Descale input and output data based on previously calculated parameters

fann_descale_output
fann_destroy_train
Func?ii fann
PHP Manual

fann_descale_train

(PECL fann >= 1.0.0)

fann_descale_train — Descale input and output data based on previously calculated parameters

Descrierea

bool fann_descale_train ( resource $ann , resource $train_data )

Descale input and output data based on previously calculated parameters.

Parametri

ann

resource a unei re?ele neuronale.

train_data

resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_scale_train() - Scale input and output data based on previously calculated parameters
  • fann_set_scaling_params() - Calculate input and output scaling parameters for future use based on training data

fann_descale_output
fann_destroy_train
Func?ii fann


Destructs the training data

fann_descale_train
fann_destroy
Func?ii fann
PHP Manual

fann_destroy_train

(PECL fann >= 1.0.0)

fann_destroy_train — Destructs the training data

Descrierea

bool fann_destroy_train ( resource $train_data )

Destructs the training data

Parametri

train_data

resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

fann_descale_train
fann_destroy
Func?ii fann


Destroys the entire network and properly freeing all the associated memory

fann_destroy_train
fann_duplicate_train_data
Func?ii fann
PHP Manual

fann_destroy

(PECL fann >= 1.0.0)

fann_destroy — Destroys the entire network and properly freeing all the associated memory

Descrierea

bool fann_destroy ( resource $ann )

Destroys the entire network and properly freeing all the associated memory.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

fann_destroy_train
fann_duplicate_train_data
Func?ii fann


Returns an exact copy of a fann train data

fann_destroy
fann_get_activation_function
Func?ii fann
PHP Manual

fann_duplicate_train_data

(PECL fann >= 1.0.0)

fann_duplicate_train_data — Returns an exact copy of a fann train data

Descrierea

resource fann_duplicate_train_data ( resource $data )

Returns an exact copy of a fann train data resource.

Parametri

data

resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

Întoarce o resource a datelor pentru antrenarea re?elei neuronale în caz de succes, sau FALSE în caz de eroare.

fann_destroy
fann_get_activation_function
Func?ii fann


Returns the activation function

fann_duplicate_train_data
fann_get_activation_steepness
Func?ii fann
PHP Manual

fann_get_activation_function

(PECL fann >= 1.0.0)

fann_get_activation_function — Returns the activation function

Descrierea

int fann_get_activation_function ( resource $ann , int $layer , int $neuron )

Get the activation function for neuron number neuron in layer number layer, counting the input layer as layer 0.

It is not possible to get activation functions for the neurons in the input layer.

The return value is one of the activation functions constants.

Parametri

ann

resource a unei re?ele neuronale.

layer

Layer number.

neuron

Neuron number.

Valorile întoarse

Learning functions constant or -1 if the neuron is not defined in the neural network, or FALSE on error.

A se vedea ?i

  • fann_set_activation_function_layer() - Sets the activation function for all the neurons in the supplied layer.
  • fann_set_activation_function_hidden() - Sets the activation function for all of the hidden layers
  • fann_set_activation_function_output() - Sets the activation function for the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer

fann_duplicate_train_data
fann_get_activation_steepness
Func?ii fann


Returns the activation steepness for supplied neuron and layer number

fann_get_activation_function
fann_get_bias_array
Func?ii fann
PHP Manual

fann_get_activation_steepness

(PECL fann >= 1.0.0)

fann_get_activation_steepness — Returns the activation steepness for supplied neuron and layer number

Descrierea

float fann_get_activation_steepness ( resource $ann , int $layer , int $neuron )

Get the activation steepness for neuron number neuron in layer number layer, counting the input layer as layer 0.

It is not possible to get activation steepness for the neurons in the input layer.

The steepness of an activation function says something about how fast the activation function goes from the minimum to the maximum. A high value for the activation function will also give a more agressive training.

When training neural networks where the output values should be at the extremes (usually 0 and 1, depending on the activation function), a steep activation function can be used (e.g. 1.0).

The default activation steepness is 0.5.

Parametri

ann

resource a unei re?ele neuronale.

layer

Layer number

neuron

Neuron number

Valorile întoarse

The activation steepness for the neuron or -1 if the neuron is not defined in the neural network, or FALSE on error.

A se vedea ?i

  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer
  • fann_set_activation_steepness_layer() - Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_hidden() - Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_set_activation_steepness_output() - Sets the steepness of the activation steepness in the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number

fann_get_activation_function
fann_get_bias_array
Func?ii fann


Get the number of bias in each layer in the network

fann_get_activation_steepness
fann_get_bit_fail_limit
Func?ii fann
PHP Manual

fann_get_bias_array

(PECL fann >= 1.0.0)

fann_get_bias_array — Get the number of bias in each layer in the network

Descrierea

array fann_get_bias_array ( resource $ann )

Get the number of bias in each layer in the network.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

An array of numbers of bias in each layer

fann_get_activation_steepness
fann_get_bit_fail_limit
Func?ii fann


Returns the bit fail limit used during training

fann_get_bias_array
fann_get_bit_fail
Func?ii fann
PHP Manual

fann_get_bit_fail_limit

(PECL fann >= 1.0.0)

fann_get_bit_fail_limit — Returns the bit fail limit used during training

Descrierea

float fann_get_bit_fail_limit ( resource $ann )

Returns the bit fail limit used during training.

The bit fail limit is used during training where the stop function is set to FANN_STOPFUNC_BIT.

The limit is the maximum accepted difference between the desired output and the actual output during training. Each output that diverges more than this limit is counted as an error bit. This difference is divided by two when dealing with symmetric activation functions, so that symmetric and not symmetric activation functions can use the same limit.

The default bit fail limit is 0.35.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The bit fail limit, or FALSE on error.

A se vedea ?i

  • fann_set_bit_fail_limit() - Set the bit fail limit used during training

fann_get_bias_array
fann_get_bit_fail
Func?ii fann


The number of fail bits

fann_get_bit_fail_limit
fann_get_cascade_activation_functions_count
Func?ii fann
PHP Manual

fann_get_bit_fail

(PECL fann >= 1.0.0)

fann_get_bit_fail — The number of fail bits

Descrierea

int fann_get_bit_fail ( resource $ann )

The number of fail bits; means the number of output neurons which differ more than the bit fail limit (see fann_get_bit_fail_limit(), fann_set_bit_fail_limit()). The bits are counted in all of the training data, so this number can be higher than the number of training data.

This value is reset by fann_reset_MSE() and updated by all the same functions which also updates the MSE value (e.g. fann_test_data(), fann_train_epoch())

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The number of bits fail, or FALSE on error.

A se vedea ?i

  • fann_get_MSE() - Reads the mean square error from the network
  • fann_reset_MSE() - Resets the mean square error from the network
  • fann_test_data() - Test a set of training data and calculates the MSE for the training data
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_bit_fail_limit() - Returns the bit fail limit used during training
  • fann_set_bit_fail_limit() - Set the bit fail limit used during training

fann_get_bit_fail_limit
fann_get_cascade_activation_functions_count
Func?ii fann


Returns the number of cascade activation functions

fann_get_bit_fail
fann_get_cascade_activation_functions
Func?ii fann
PHP Manual

fann_get_cascade_activation_functions_count

(PECL fann >= 1.0.0)

fann_get_cascade_activation_functions_count — Returns the number of cascade activation functions

Descrierea

int fann_get_cascade_activation_functions_count ( resource $ann )

The number of activation functions in the fann_get_cascade_activation_functions() array.

The default number of activation functions is 6.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The number of cascade activation functions, or FALSE on error.

A se vedea ?i

  • fann_get_cascade_activation_functions() - Returns the cascade activation functions
  • fann_set_cascade_activation_functions() - Sets the array of cascade candidate activation functions

fann_get_bit_fail
fann_get_cascade_activation_functions
Func?ii fann


Returns the cascade activation functions

fann_get_cascade_activation_functions_count
fann_get_cascade_activation_steepnesses_count
Func?ii fann
PHP Manual

fann_get_cascade_activation_functions

(PECL fann >= 1.0.0)

fann_get_cascade_activation_functions — Returns the cascade activation functions

Descrierea

array fann_get_cascade_activation_functions ( resource $ann )

The cascade activation functions array is an array of the different activation functions used by the candidates

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this array.

The default activation functions are FANN_SIGMOID, FANN_SIGMOID_SYMMETRIC, FANN_GAUSSIAN, FANN_GAUSSIAN_SYMMETRIC, FANN_ELLIOT, FANN_ELLIOT_SYMMETRIC.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The cascade activation functions, or FALSE on error.

A se vedea ?i

  • fann_get_cascade_activation_functions_count() - Returns the number of cascade activation functions
  • fann_set_cascade_activation_functions() - Sets the array of cascade candidate activation functions

fann_get_cascade_activation_functions_count
fann_get_cascade_activation_steepnesses_count
Func?ii fann


The number of activation steepnesses

fann_get_cascade_activation_functions
fann_get_cascade_activation_steepnesses
Func?ii fann
PHP Manual

fann_get_cascade_activation_steepnesses_count

(PECL fann >= 1.0.0)

fann_get_cascade_activation_steepnesses_count — The number of activation steepnesses

Descrierea

int fann_get_cascade_activation_steepnesses_count ( resource $ann )

The number of activation steepnesses in the fann_get_cascade_activation_functions() array.

The default number of activation steepnesses is 4.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The number of activation steepnesses, or FALSE on error.

A se vedea ?i

  • fann_get_cascade_activation_steepnesses() - Returns the cascade activation steepnesses
  • fann_set_cascade_activation_functions() - Sets the array of cascade candidate activation functions

fann_get_cascade_activation_functions
fann_get_cascade_activation_steepnesses
Func?ii fann


Returns the cascade activation steepnesses

fann_get_cascade_activation_steepnesses_count
fann_get_cascade_candidate_change_fraction
Func?ii fann
PHP Manual

fann_get_cascade_activation_steepnesses

(PECL fann >= 1.0.0)

fann_get_cascade_activation_steepnesses — Returns the cascade activation steepnesses

Descrierea

array fann_get_cascade_activation_steepnesses ( resource $ann )

The cascade activation steepnesses array is an array of the different activation functions used by the candidates.

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this array.

The default activation steepnesses are {0.25, 0.50, 0.75, 1.00}.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The cascade activation steepnesses, or FALSE on error.

A se vedea ?i

  • fann_get_cascade_activation_steepnesses_count() - The number of activation steepnesses
  • fann_set_cascade_activation_steepnesses() - Sets the array of cascade candidate activation steepnesses

fann_get_cascade_activation_steepnesses_count
fann_get_cascade_candidate_change_fraction
Func?ii fann


Returns the cascade candidate change fraction

fann_get_cascade_activation_steepnesses
fann_get_cascade_candidate_limit
Func?ii fann
PHP Manual

fann_get_cascade_candidate_change_fraction

(PECL fann >= 1.0.0)

fann_get_cascade_candidate_change_fraction — Returns the cascade candidate change fraction

Descrierea

float fann_get_cascade_candidate_change_fraction ( resource $ann )

The cascade candidate change fraction is a number between 0 and 1 determining how large a fraction the fann_get_MSE() value should change within fann_get_cascade_candidate_stagnation_epochs() during training of the candidate neurons, in order for the training not to stagnate. If the training stagnates, the training of the candidate neurons will be ended and the best candidate will be selected.

It means that if the MSE does not change by a fraction of fann_get_cascade_candidate_change_fraction() during a period of fann_get_cascade_candidate_stagnation_epochs(), the training of the candidate neurons is stopped because the training has stagnated.

If the cascade candidate change fraction is low, the candidate neurons will be trained more and if the fraction is high they will be trained less.

The default cascade candidate change fraction is 0.01, which is equalent to a 1% change in MSE.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The cascade candidate change fraction, or FALSE on error.

A se vedea ?i

  • fann_set_cascade_candidate_change_fraction() - Sets the cascade candidate change fraction
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_get_cascade_candidate_stagnation_epochs() - Returns the number of cascade candidate stagnation epochs

fann_get_cascade_activation_steepnesses
fann_get_cascade_candidate_limit
Func?ii fann


Return the candidate limit

fann_get_cascade_candidate_change_fraction
fann_get_cascade_candidate_stagnation_epochs
Func?ii fann
PHP Manual

fann_get_cascade_candidate_limit

(PECL fann >= 1.0.0)

fann_get_cascade_candidate_limit — Return the candidate limit

Descrierea

float fann_get_cascade_candidate_limit ( resource $ann )

The candidate limit is a limit for how much the candidate neuron may be trained. The limit is a limit on the proportion between the MSE and candidate score.

Set this to a lower value to avoid overfitting and to a higher if overfitting is not a problem.

The default candidate limit is 1000.0.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The candidate limit, or FALSE on error.

A se vedea ?i

  • fann_set_cascade_candidate_limit() - Sets the candidate limit

fann_get_cascade_candidate_change_fraction
fann_get_cascade_candidate_stagnation_epochs
Func?ii fann


Returns the number of cascade candidate stagnation epochs

fann_get_cascade_candidate_limit
fann_get_cascade_max_cand_epochs
Func?ii fann
PHP Manual

fann_get_cascade_candidate_stagnation_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_candidate_stagnation_epochs — Returns the number of cascade candidate stagnation epochs

Descrierea

float fann_get_cascade_candidate_stagnation_epochs ( resource $ann )

The number of cascade candidate stagnation epochs determines the number of epochs training is allowed to continue without changing the MSE by a fraction of fann_get_cascade_candidate_change_fraction().

See more info about this parameter in fann_get_cascade_candidate_change_fraction().

The default number of cascade candidate stagnation epochs is 12.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The number of cascade candidate stagnation epochs, or FALSE on error.

A se vedea ?i

  • fann_set_cascade_candidate_stagnation_epochs() - Sets the number of cascade candidate stagnation epochs
  • fann_get_cascade_candidate_change_fraction() - Returns the cascade candidate change fraction

fann_get_cascade_candidate_limit
fann_get_cascade_max_cand_epochs
Func?ii fann


Returns the maximum candidate epochs

fann_get_cascade_candidate_stagnation_epochs
fann_get_cascade_max_out_epochs
Func?ii fann
PHP Manual

fann_get_cascade_max_cand_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_max_cand_epochs — Returns the maximum candidate epochs

Descrierea

int fann_get_cascade_max_cand_epochs ( resource $ann )

The maximum candidate epochs determines the maximum number of epochs the input connections to the candidates may be trained before adding a new candidate neuron.

The default max candidate epochs is 150.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The maximum candidate epochs, or FALSE on error.

A se vedea ?i

  • fann_set_cascade_max_cand_epochs() - Sets the max candidate epochs

fann_get_cascade_candidate_stagnation_epochs
fann_get_cascade_max_out_epochs
Func?ii fann


Returns the maximum out epochs

fann_get_cascade_max_cand_epochs
fann_get_cascade_min_cand_epochs
Func?ii fann
PHP Manual

fann_get_cascade_max_out_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_max_out_epochs — Returns the maximum out epochs

Descrierea

int fann_get_cascade_max_out_epochs ( resource $ann )

The maximum out epochs determines the maximum number of epochs the output connections may be trained after adding a new candidate neuron.

The default max out epochs is 150.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The maximum out epochs, or FALSE on error.

A se vedea ?i

  • fann_set_cascade_max_out_epochs() - Sets the maximum out epochs

fann_get_cascade_max_cand_epochs
fann_get_cascade_min_cand_epochs
Func?ii fann


Returns the minimum candidate epochs

fann_get_cascade_max_out_epochs
fann_get_cascade_min_out_epochs
Func?ii fann
PHP Manual

fann_get_cascade_min_cand_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_min_cand_epochs — Returns the minimum candidate epochs

Descrierea

int fann_get_cascade_min_cand_epochs ( resource $ann )

The minimum candidate epochs determines the minimum number of epochs the input connections to the candidates may be trained before adding a new candidate neuron.

The default min candidate epochs is 50.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The minimum candidate epochs, or FALSE on error.

A se vedea ?i

  • fann_set_cascade_min_cand_epochs() - Sets the min candidate epochs

fann_get_cascade_max_out_epochs
fann_get_cascade_min_out_epochs
Func?ii fann


Returns the minimum out epochs

fann_get_cascade_min_cand_epochs
fann_get_cascade_num_candidate_groups
Func?ii fann
PHP Manual

fann_get_cascade_min_out_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_min_out_epochs — Returns the minimum out epochs

Descrierea

int fann_get_cascade_min_out_epochs ( resource $ann )

The minimum out epochs determines the minimum number of epochs the output connections must be trained after adding a new candidate neuron.

The default min out epochs is 50.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The minimum out epochs, or FALSE on error.

A se vedea ?i

  • fann_set_cascade_min_out_epochs() - Sets the minimum out epochs

fann_get_cascade_min_cand_epochs
fann_get_cascade_num_candidate_groups
Func?ii fann


Returns the number of candidate groups

fann_get_cascade_min_out_epochs
fann_get_cascade_num_candidates
Func?ii fann
PHP Manual

fann_get_cascade_num_candidate_groups

(PECL fann >= 1.0.0)

fann_get_cascade_num_candidate_groups — Returns the number of candidate groups

Descrierea

int fann_get_cascade_num_candidate_groups ( resource $ann )

The number of candidate groups is the number of groups of identical candidates which will be used during training.

This number can be used to have more candidates without having to define new parameters for the candidates.

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this parameter.

The default number of candidate groups is 2.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The number of candidate groups, or FALSE on error.

A se vedea ?i

  • fann_set_cascade_num_candidate_groups() - Sets the number of candidate groups

fann_get_cascade_min_out_epochs
fann_get_cascade_num_candidates
Func?ii fann


Returns the number of candidates used during training

fann_get_cascade_num_candidate_groups
fann_get_cascade_output_change_fraction
Func?ii fann
PHP Manual

fann_get_cascade_num_candidates

(PECL fann >= 1.0.0)

fann_get_cascade_num_candidates — Returns the number of candidates used during training

Descrierea

int fann_get_cascade_num_candidates ( resource $ann )

The number of candidates used during training (calculated by multiplying
fann_get_cascade_activation_functions_count(),
fann_get_cascade_activation_steepnesses_count() and
fann_get_cascade_num_candidate_groups()).

The actual candidates is defined by the fann_get_cascade_activation_functions() and fann_get_cascade_activation_steepnesses() arrays. These arrays define the activation functions and activation steepnesses used for the candidate neurons. If there are 2 activation functions in the activation function array and 3 steepnesses in the steepness array, then there will be 2x3=6 different candidates which will be trained. These 6 different candidates can be copied into several candidate groups, where the only difference between these groups is the initial weights. If the number of groups is set to 2, then the number of candidate neurons will be 2x3x2=12. The number of candidate groups is defined by fann_set_cascade_num_candidate_groups().

The default number of candidates is 6x4x2 = 48

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The number of candidates used during training, or FALSE on error.

A se vedea ?i

  • fann_get_cascade_activation_functions() - Returns the cascade activation functions
  • fann_get_cascade_activation_functions_count() - Returns the number of cascade activation functions
  • fann_get_cascade_activation_steepnesses() - Returns the cascade activation steepnesses
  • fann_get_cascade_activation_steepnesses_count() - The number of activation steepnesses
  • fann_get_cascade_num_candidate_groups() - Returns the number of candidate groups

fann_get_cascade_num_candidate_groups
fann_get_cascade_output_change_fraction
Func?ii fann


Returns the cascade output change fraction

fann_get_cascade_num_candidates
fann_get_cascade_output_stagnation_epochs
Func?ii fann
PHP Manual

fann_get_cascade_output_change_fraction

(PECL fann >= 1.0.0)

fann_get_cascade_output_change_fraction — Returns the cascade output change fraction

Descrierea

float fann_get_cascade_output_change_fraction ( resource $ann )

The cascade output change fraction is a number between 0 and 1 determining how large a fraction of the fann_get_MSE() value should change within fann_get_cascade_output_stagnation_epochs() during training of the output connections, in order for the training not to stagnate. If the training stagnates, the training of the output connections will be ended and new candidates will be prepared.

It means that if the MSE does not change by a fraction of fann_get_cascade_output_change_fraction() during a period of fann_get_cascade_output_stagnation_epochs(), the training of the output connections is stopped because the training has stagnated.

If the cascade output change fraction is low, the output connections will be trained more and if the fraction is high, they will be trained less.

The default cascade output change fraction is 0.01, which is equalent to a 1% change in MSE.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The cascade output change fraction, or FALSE on error.

A se vedea ?i

  • fann_set_cascade_output_change_fraction() - Sets the cascade output change fraction
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_get_cascade_output_stagnation_epochs() - Returns the number of cascade output stagnation epochs

fann_get_cascade_num_candidates
fann_get_cascade_output_stagnation_epochs
Func?ii fann


Returns the number of cascade output stagnation epochs

fann_get_cascade_output_change_fraction
fann_get_cascade_weight_multiplier
Func?ii fann
PHP Manual

fann_get_cascade_output_stagnation_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_output_stagnation_epochs — Returns the number of cascade output stagnation epochs

Descrierea

int fann_get_cascade_output_stagnation_epochs ( resource $ann )

The number of cascade output stagnation epochs determines the number of epochs training is allowed to continue without changing the MSE by a fraction of fann_get_cascade_output_change_fraction().

See more info about this parameter in fann_get_cascade_output_change_fraction().

The default number of cascade output stagnation epochs is 12.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The number of cascade output stagnation epochs, or FALSE on error.

A se vedea ?i

  • fann_set_cascade_output_stagnation_epochs() - Sets the number of cascade output stagnation epochs
  • fann_get_cascade_output_change_fraction() - Returns the cascade output change fraction

fann_get_cascade_output_change_fraction
fann_get_cascade_weight_multiplier
Func?ii fann


Returns the weight multiplier

fann_get_cascade_output_stagnation_epochs
fann_get_connection_array
Func?ii fann
PHP Manual

fann_get_cascade_weight_multiplier

(PECL fann >= 1.0.0)

fann_get_cascade_weight_multiplier — Returns the weight multiplier

Descrierea

float fann_get_cascade_weight_multiplier ( resource $ann )

The weight multiplier is a parameter which is used to multiply the weights from the candidate neuron before adding the neuron to the neural network. This parameter is usually between 0 and 1, and is used to make the training a bit less aggressive.

The default weight multiplier is 0.4.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The weight multiplier, or FALSE on error.

A se vedea ?i

  • fann_set_cascade_weight_multiplier() - Sets the weight multiplier

fann_get_cascade_output_stagnation_epochs
fann_get_connection_array
Func?ii fann


Get connections in the network

fann_get_cascade_weight_multiplier
fann_get_connection_rate
Func?ii fann
PHP Manual

fann_get_connection_array

(PECL fann >= 1.0.0)

fann_get_connection_array — Get connections in the network

Descrierea

array fann_get_connection_array ( resource $ann )

Get connections in the network.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

An array of connections in the network

fann_get_cascade_weight_multiplier
fann_get_connection_rate
Func?ii fann


Get the connection rate used when the network was created

fann_get_connection_array
fann_get_errno
Func?ii fann
PHP Manual

fann_get_connection_rate

(PECL fann >= 1.0.0)

fann_get_connection_rate — Get the connection rate used when the network was created

Descrierea

float fann_get_connection_rate ( resource $ann )

Get the connection rate used when the network was created.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The connection rate used when the network was created, or FALSE on error.

fann_get_connection_array
fann_get_errno
Func?ii fann


Returns the last error number

fann_get_connection_rate
fann_get_errstr
Func?ii fann
PHP Manual

fann_get_errno

(PECL fann >= 1.0.0)

fann_get_errno — Returns the last error number

Descrierea

int fann_get_errno ( resource $errdat )

Returns the last error number.

Parametri

errdat

resource a unei re?ele neuronale, sau resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

The error number, or FALSE on error.

A se vedea ?i

  • fann_reset_errno() - Resets the last error number
  • fann_get_errstr() - Returns the last errstr

fann_get_connection_rate
fann_get_errstr
Func?ii fann


Returns the last errstr

fann_get_errno
fann_get_layer_array
Func?ii fann
PHP Manual

fann_get_errstr

(PECL fann >= 1.0.0)

fann_get_errstr — Returns the last errstr

Descrierea

string fann_get_errstr ( resource $errdat )

Returns the last errstr.

Parametri

errdat

resource a unei re?ele neuronale, sau resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

The last error string, or FALSE on error.

A se vedea ?i

  • fann_reset_errstr() - Resets the last error string
  • fann_get_errno() - Returns the last error number

fann_get_errno
fann_get_layer_array
Func?ii fann


Get the number of neurons in each layer in the network

fann_get_errstr
fann_get_learning_momentum
Func?ii fann
PHP Manual

fann_get_layer_array

(PECL fann >= 1.0.0)

fann_get_layer_array — Get the number of neurons in each layer in the network

Descrierea

array fann_get_layer_array ( resource $ann )

Get the number of neurons in each layer in the neural network.

Bias is not included so the layers match the fann_create functions.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

An array of numbers of neurons in each leayer

fann_get_errstr
fann_get_learning_momentum
Func?ii fann


Returns the learning momentum

fann_get_layer_array
fann_get_learning_rate
Func?ii fann
PHP Manual

fann_get_learning_momentum

(PECL fann >= 1.0.0)

fann_get_learning_momentum — Returns the learning momentum

Descrierea

float fann_get_learning_momentum ( resource $ann )

The learning momentum can be used to speed up FANN_TRAIN_INCREMENTAL training. A too high momentum will however not benefit training. Setting momentum to 0 will be the same as not using the momentum parameter. The recommended value of this parameter is between 0.0 and 1.0.

The default momentum is 0.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

The learning momentum, or FALSE on error.

A se vedea ?i

  • fann_set_learning_momentum() - Sets the learning momentum
  • fann_set_training_algorithm() - Sets the training algorithm

fann_get_layer_array
fann_get_learning_rate
Func?ii fann


Returns the learning rate

fann_get_learning_momentum
fann_get_MSE
Func?ii fann
PHP Manual

fann_get_learning_rate

(PECL fann >= 1.0.0)

fann_get_learning_rate — Returns the learning rate

Descrierea

float fann_get_learning_rate ( resource $ann )

The learning rate is used to determine how aggressive training should be for some of the training algorithms (FANN_TRAIN_INCREMENTAL, FANN_TRAIN_BATCH, FANN_TRAIN_QUICKPROP). Do however note that it is not used in FANN_TRAIN_RPROP.

The default learning rate is 0.7.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The learning rate, or FALSE on error.

A se vedea ?i

  • fann_set_learning_rate() - Sets the learning rate
  • fann_set_training_algorithm() - Sets the training algorithm

fann_get_learning_momentum
fann_get_MSE
Func?ii fann


Reads the mean square error from the network

fann_get_learning_rate
fann_get_network_type
Func?ii fann
PHP Manual

fann_get_MSE

(PECL fann >= 1.0.0)

fann_get_MSE — Reads the mean square error from the network

Descrierea

float fann_get_MSE ( resource $ann )

Reads the mean square error from the network.

Reads the mean square error from the network. This value is calculated during training or testing and can therefore sometimes be a bit off if the weights have been changed since the last calculation of the value.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The mean square error, or FALSE on error.

A se vedea ?i

  • fann_test_data() - Test a set of training data and calculates the MSE for the training data

fann_get_learning_rate
fann_get_network_type
Func?ii fann


Get the type of neural network it was created as

fann_get_MSE
fann_get_num_input
Func?ii fann
PHP Manual

fann_get_network_type

(PECL fann >= 1.0.0)

fann_get_network_type — Get the type of neural network it was created as

Descrierea

int fann_get_network_type ( resource $ann )

Get the type of neural network it was created as.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

Network type constant, or FALSE on error.

fann_get_MSE
fann_get_num_input
Func?ii fann


Get the number of input neurons

fann_get_network_type
fann_get_num_layers
Func?ii fann
PHP Manual

fann_get_num_input

(PECL fann >= 1.0.0)

fann_get_num_input — Get the number of input neurons

Descrierea

int fann_get_num_input ( resource $ann )

Get the number of input neurons.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

Number of input neurons, or FALSE on error

fann_get_network_type
fann_get_num_layers
Func?ii fann


Get the number of layers in the neural network

fann_get_num_input
fann_get_num_output
Func?ii fann
PHP Manual

fann_get_num_layers

(PECL fann >= 1.0.0)

fann_get_num_layers — Get the number of layers in the neural network

Descrierea

int fann_get_num_layers ( resource $ann )

Get the number of layers in the neural network.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The number of leayers in the neural network, or FALSE on error.

fann_get_num_input
fann_get_num_output
Func?ii fann


Get the number of output neurons

fann_get_num_layers
fann_get_quickprop_decay
Func?ii fann
PHP Manual

fann_get_num_output

(PECL fann >= 1.0.0)

fann_get_num_output — Get the number of output neurons

Descrierea

int fann_get_num_output ( resource $ann )

Get the number of output neurons.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

Number of output neurons, or FALSE on error

fann_get_num_layers
fann_get_quickprop_decay
Func?ii fann


Returns the decay which is a factor that weights should decrease in each iteration during quickprop training

fann_get_num_output
fann_get_quickprop_mu
Func?ii fann
PHP Manual

fann_get_quickprop_decay

(PECL fann >= 1.0.0)

fann_get_quickprop_decay — Returns the decay which is a factor that weights should decrease in each iteration during quickprop training

Descrierea

float fann_get_quickprop_decay ( resource $ann )

The decay is a small negative valued number which is a factor that the weights should decrease in each iteration during quickprop training. This is used to make sure that the weights do not become too high during training.

The default decay is -0.0001.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The decay, or FALSE on error.

A se vedea ?i

  • fann_set_quickprop_decay() - Sets the quickprop decay factor

fann_get_num_output
fann_get_quickprop_mu
Func?ii fann


Returns the mu factor

fann_get_quickprop_decay
fann_get_rprop_decrease_factor
Func?ii fann
PHP Manual

fann_get_quickprop_mu

(PECL fann >= 1.0.0)

fann_get_quickprop_mu — Returns the mu factor

Descrierea

float fann_get_quickprop_mu ( resource $ann )

The mu factor is used to increase and decrease the step-size during quickprop training. The mu factor should always be above 1, since it would otherwise decrease the step-size when it was suppose to increase it.

The default mu factor is 1.75.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The mu factor, or FALSE on error.

A se vedea ?i

  • fann_set_quickprop_mu() - Sets the quickprop mu factor

fann_get_quickprop_decay
fann_get_rprop_decrease_factor
Func?ii fann


Returns the increase factor used during RPROP training

fann_get_quickprop_mu
fann_get_rprop_delta_max
Func?ii fann
PHP Manual

fann_get_rprop_decrease_factor

(PECL fann >= 1.0.0)

fann_get_rprop_decrease_factor — Returns the increase factor used during RPROP training

Descrierea

float fann_get_rprop_decrease_factor ( resource $ann )

The decrease factor is a value smaller than 1, which is used to decrease the step-size during RPROP training.

The default decrease factor is 0.5.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The decrease factor, or FALSE on error.

A se vedea ?i

  • fann_set_rprop_decrease_factor() - Sets the decrease factor used during RPROP training

fann_get_quickprop_mu
fann_get_rprop_delta_max
Func?ii fann


Returns the maximum step-size

fann_get_rprop_decrease_factor
fann_get_rprop_delta_min
Func?ii fann
PHP Manual

fann_get_rprop_delta_max

(PECL fann >= 1.0.0)

fann_get_rprop_delta_max — Returns the maximum step-size

Descrierea

float fann_get_rprop_delta_max ( resource $ann )

The maximum step-size is a positive number determining how large the maximum step-size may be.

The default delta max is 50.0.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The maximum step-size, or FALSE on error.

A se vedea ?i

  • fann_set_rprop_delta_max() - Sets the maximum step-size
  • fann_get_rprop_delta_min() - Returns the minimum step-size

fann_get_rprop_decrease_factor
fann_get_rprop_delta_min
Func?ii fann


Returns the minimum step-size

fann_get_rprop_delta_max
fann_get_rprop_delta_zero
Func?ii fann
PHP Manual

fann_get_rprop_delta_min

(PECL fann >= 1.0.0)

fann_get_rprop_delta_min — Returns the minimum step-size

Descrierea

float fann_get_rprop_delta_min ( resource $ann )

The minimum step-size is a small positive number determining how small the minimum step-size may be.

The default value delta min is 0.0.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The minimum step-size, or FALSE on error.

A se vedea ?i

  • fann_set_rprop_delta_min() - Sets the minimum step-size

fann_get_rprop_delta_max
fann_get_rprop_delta_zero
Func?ii fann


Returns the initial step-size

fann_get_rprop_delta_min
fann_get_rprop_increase_factor
Func?ii fann
PHP Manual

fann_get_rprop_delta_zero

(PECL fann >= 1.0.0)

fann_get_rprop_delta_zero — Returns the initial step-size

Descrierea

ReturnType fann_get_rprop_delta_zero ( resource $ann )

The initial step-size is a positive number determining the initial step size.

The default delta zero is 0.1.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The initial step-size, or FALSE on error.

A se vedea ?i

  • fann_set_rprop_delta_zero() - Sets the initial step-size
  • fann_get_rprop_delta_min() - Returns the minimum step-size
  • fann_get_rprop_delta_max() - Returns the maximum step-size

fann_get_rprop_delta_min
fann_get_rprop_increase_factor
Func?ii fann


Returns the increase factor used during RPROP training

fann_get_rprop_delta_zero
fann_get_sarprop_step_error_shift
Func?ii fann
PHP Manual

fann_get_rprop_increase_factor

(PECL fann >= 1.0.0)

fann_get_rprop_increase_factor — Returns the increase factor used during RPROP training

Descrierea

float fann_get_rprop_increase_factor ( resource $ann )

The increase factor is a value larger than 1, which is used to increase the step-size during RPROP training.

The default increase factor is 1.2.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The increase factor, or FALSE on error.

A se vedea ?i

  • fann_set_rprop_increase_factor() - Sets the increase factor used during RPROP training

fann_get_rprop_delta_zero
fann_get_sarprop_step_error_shift
Func?ii fann


Returns the sarprop step error shift

fann_get_rprop_increase_factor
fann_get_sarprop_step_error_threshold_factor
Func?ii fann
PHP Manual

fann_get_sarprop_step_error_shift

(PECL fann >= 1.0.0)

fann_get_sarprop_step_error_shift — Returns the sarprop step error shift

Descrierea

float fann_get_sarprop_step_error_shift ( resource $ann )

Returns the sarprop step error shift.

The default step error shift is 1.385.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The sarprop step error shift , or FALSE on error.

A se vedea ?i

  • fann_set_sarprop_step_error_shift() - Sets the sarprop step error shift

fann_get_rprop_increase_factor
fann_get_sarprop_step_error_threshold_factor
Func?ii fann


Returns the sarprop step error threshold factor

fann_get_sarprop_step_error_shift
fann_get_sarprop_temperature
Func?ii fann
PHP Manual

fann_get_sarprop_step_error_threshold_factor

(PECL fann >= 1.0.0)

fann_get_sarprop_step_error_threshold_factor — Returns the sarprop step error threshold factor

Descrierea

float fann_get_sarprop_step_error_threshold_factor ( resource $ann )

The sarprop step error threshold factor.

The default factor is 0.1.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The sarprop step error threshold factor, or FALSE on error.

A se vedea ?i

  • fann_set_sarprop_step_error_threshold_factor() - Sets the sarprop step error threshold factor

fann_get_sarprop_step_error_shift
fann_get_sarprop_temperature
Func?ii fann


Returns the sarprop temperature

fann_get_sarprop_step_error_threshold_factor
fann_get_sarprop_weight_decay_shift
Func?ii fann
PHP Manual

fann_get_sarprop_temperature

(PECL fann >= 1.0.0)

fann_get_sarprop_temperature — Returns the sarprop temperature

Descrierea

float fann_get_sarprop_temperature ( resource $ann )

Returns the sarprop temperature.

The default temperature is 0.015.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The sarprop temperature, or FALSE on error.

A se vedea ?i

  • fann_set_sarprop_temperature() - Sets the sarprop temperature

fann_get_sarprop_step_error_threshold_factor
fann_get_sarprop_weight_decay_shift
Func?ii fann


Returns the sarprop weight decay shift

fann_get_sarprop_temperature
fann_get_total_connections
Func?ii fann
PHP Manual

fann_get_sarprop_weight_decay_shift

(PECL fann >= 1.0.0)

fann_get_sarprop_weight_decay_shift — Returns the sarprop weight decay shift

Descrierea

float fann_get_sarprop_weight_decay_shift ( resource $ann )

The sarprop weight decay shift.

The default delta max is -6.644.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The sarprop weight decay shift, or FALSE on error.

A se vedea ?i

  • fann_set_sarprop_weight_decay_shift() - Sets the sarprop weight decay shift

fann_get_sarprop_temperature
fann_get_total_connections
Func?ii fann


Get the total number of connections in the entire network

fann_get_sarprop_weight_decay_shift
fann_get_total_neurons
Func?ii fann
PHP Manual

fann_get_total_connections

(PECL fann >= 1.0.0)

fann_get_total_connections — Get the total number of connections in the entire network

Descrierea

int fann_get_total_connections ( resource $ann )

Get the total number of connections in the entire network.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

Total number of connections in the entire network, or FALSE on error

fann_get_sarprop_weight_decay_shift
fann_get_total_neurons
Func?ii fann


Get the total number of neurons in the entire network

fann_get_total_connections
fann_get_train_error_function
Func?ii fann
PHP Manual

fann_get_total_neurons

(PECL fann >= 1.0.0)

fann_get_total_neurons — Get the total number of neurons in the entire network

Descrierea

int fann_get_total_neurons ( resource $ann )

Get the total number of neurons in the entire network. This number does also include the bias neurons, so a 2-4-2 network has 2+4+2 +2(bias) = 10 neurons.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

Total number of neurons in the entire network, or FALSE on error.

fann_get_total_connections
fann_get_train_error_function
Func?ii fann


Returns the error function used during training

fann_get_total_neurons
fann_get_train_stop_function
Func?ii fann
PHP Manual

fann_get_train_error_function

(PECL fann >= 1.0.0)

fann_get_train_error_function — Returns the error function used during training

Descrierea

int fann_get_train_error_function ( resource $ann )

Returns the error function used during training.

The error functions are described further in error functions constants.

The default error function is FANN_ERRORFUNC_TANH.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The error function constant, or FALSE on error.

A se vedea ?i

  • fann_set_train_error_function() - Sets the error function used during training

fann_get_total_neurons
fann_get_train_stop_function
Func?ii fann


Returns the stop function used during training

fann_get_train_error_function
fann_get_training_algorithm
Func?ii fann
PHP Manual

fann_get_train_stop_function

(PECL fann >= 1.0.0)

fann_get_train_stop_function — Returns the stop function used during training

Descrierea

int fann_get_train_stop_function ( resource $ann )

Returns the stop function used during training.

The stop functions are described further in stop functions constants.

The default stop function is FANN_STOPFUNC_MSE.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

The stop function constant, or FALSE on error.

A se vedea ?i

  • fann_set_train_stop_function() - Sets the stop function used during training

fann_get_train_error_function
fann_get_training_algorithm
Func?ii fann


Returns the training algorithm

fann_get_train_stop_function
fann_init_weights
Func?ii fann
PHP Manual

fann_get_training_algorithm

(PECL fann >= 1.0.0)

fann_get_training_algorithm — Returns the training algorithm

Descrierea

int fann_get_training_algorithm ( resource $ann )

Returns the training algorithm. This training algorithm is used by fann_train_on_data() and associated functions.

Note that this algorithm is also used during fann_cascadetrain_on_data(), although only FANN_TRAIN_RPROP and FANN_TRAIN_QUICKPROP is allowed during cascade training.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

Training algorithm constant, or FALSE on error.

A se vedea ?i

  • fann_set_training_algorithm() - Sets the training algorithm

fann_get_train_stop_function
fann_init_weights
Func?ii fann


Initialize the weights using Widrow + Nguyen’s algorithm

fann_get_training_algorithm
fann_length_train_data
Func?ii fann
PHP Manual

fann_init_weights

(PECL fann >= 1.0.0)

fann_init_weights — Initialize the weights using Widrow + Nguyen’s algorithm

Descrierea

bool fann_init_weights ( resource $ann , resource $train_data )

Initialize the weights using Widrow + Nguyen’s algorithm.

This function behaves similarly to fann_randomize_weights(). It will use the algorithm developed by Derrick Nguyen and Bernard Widrow to set the weights in such a way as to speed up training. This technique is not always successful, and in some cases can be less efficient than a purely random initialization.

The algorithm requires access to the range of the input data (for example largest and smallest input), and therefore accepts a second argument, data, which is the training data that will be used to train the network.

Parametri

ann

resource a unei re?ele neuronale.

train_data

resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_randomize_weights() - Give each connection a random weight between min_weight and max_weight
  • fann_read_train_from_file() - Reads a file that stores training data

fann_get_training_algorithm
fann_length_train_data
Func?ii fann


Returns the number of training patterns in the train data

fann_init_weights
fann_merge_train_data
Func?ii fann
PHP Manual

fann_length_train_data

(PECL fann >= 1.0.0)

fann_length_train_data — Returns the number of training patterns in the train data

Descrierea

int fann_length_train_data ( resource $data )

Returns the number of training patterns in the train data resource.

Parametri

data

resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

Number of elements in the train data resource, or FALSE on error.

fann_init_weights
fann_merge_train_data
Func?ii fann


Merges the train data

fann_length_train_data
fann_num_input_train_data
Func?ii fann
PHP Manual

fann_merge_train_data

(PECL fann >= 1.0.0)

fann_merge_train_data — Merges the train data

Descrierea

resource fann_merge_train_data ( resource $data1 , resource $data2 )

Merges the data from data1 and data2 into a new train data resource.

Parametri

data1

resource a datelor pentru antrenarea re?elei neuronale.

data2

resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

New merged train data resource, or FALSE on error.

fann_length_train_data
fann_num_input_train_data
Func?ii fann


Returns the number of inputs in each of the training patterns in the train data

fann_merge_train_data
fann_num_output_train_data
Func?ii fann
PHP Manual

fann_num_input_train_data

(PECL fann >= 1.0.0)

fann_num_input_train_data — Returns the number of inputs in each of the training patterns in the train data

Descrierea

int fann_num_input_train_data ( resource $data )

Returns the number of inputs in each of the training patterns in the train data resource.

Parametri

data

resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

The number of inputs, or FALSE on error.

A se vedea ?i

  • fann_length_train_data() - Returns the number of training patterns in the train data
  • fann_num_output_train_data() - Returns the number of outputs in each of the training patterns in the train data

fann_merge_train_data
fann_num_output_train_data
Func?ii fann


Returns the number of outputs in each of the training patterns in the train data

fann_num_input_train_data
fann_print_error
Func?ii fann
PHP Manual

fann_num_output_train_data

(PECL fann >= 1.0.0)

fann_num_output_train_data — Returns the number of outputs in each of the training patterns in the train data

Descrierea

int fann_num_output_train_data ( resource $data )

Returns the number of outputs in each of the training patterns in the train data resource.

Parametri

data

resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

The number of outputs, or FALSE on error.

A se vedea ?i

  • fann_length_train_data() - Returns the number of training patterns in the train data
  • fann_num_input_train_data() - Returns the number of inputs in each of the training patterns in the train data

fann_num_input_train_data
fann_print_error
Func?ii fann


Prints the error string

fann_num_output_train_data
fann_randomize_weights
Func?ii fann
PHP Manual

fann_print_error

(PECL fann >= 1.0.0)

fann_print_error — Prints the error string

Descrierea

void fann_print_error ( string $errdat )

Prints the error string.

Parametri

errdat

resource a unei re?ele neuronale, sau resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • fann_get_errstr() - Returns the last errstr

fann_num_output_train_data
fann_randomize_weights
Func?ii fann


Give each connection a random weight between min_weight and max_weight

fann_print_error
fann_read_train_from_file
Func?ii fann
PHP Manual

fann_randomize_weights

(PECL fann >= 1.0.0)

fann_randomize_weights — Give each connection a random weight between min_weight and max_weight

Descrierea

bool fann_randomize_weights ( resource $ann , float $min_weight , float $max_weight )

Give each connection a random weight between min_weight and max_weight

From the beginning the weights are random between -0.1 and 0.1.

Parametri

ann

resource a unei re?ele neuronale.

min_weight

Minimum weight value

max_weight

Maximum weight value

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_init_weights() - Initialize the weights using Widrow + Nguyen’s algorithm

fann_print_error
fann_read_train_from_file
Func?ii fann


Reads a file that stores training data

fann_randomize_weights
fann_reset_errno
Func?ii fann
PHP Manual

fann_read_train_from_file

(PECL fann >= 1.0.0)

fann_read_train_from_file — Reads a file that stores training data

Descrierea

resource fann_read_train_from_file ( string $filename )

Reads a file that stores training data.

Parametri

filename

The input file in the following format:

num_train_data num_input num_output
inputdata seperated by space
outputdata seperated by space

.
.
.

inputdata seperated by space
outputdata seperated by space

Valorile întoarse

Întoarce o resource a datelor pentru antrenarea re?elei neuronale în caz de succes, sau FALSE în caz de eroare.

Exemple

Example #1 fann_read_train_from_file() example

<?php
$train_data = fann_read_train_from_file("xor.data");
if ($train_data) {
    // Do something with $train_data for XOR function
}
?>

Contents of xor.data

4 2 1
-1 -1
-1
-1 1
1
1 -1
1
1 1
-1

A se vedea ?i

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_destroy_train() - Destructs the training data
  • fann_save_train() - Save the training structure to a file

fann_randomize_weights
fann_reset_errno
Func?ii fann


Resets the last error number

fann_read_train_from_file
fann_reset_errstr
Func?ii fann
PHP Manual

fann_reset_errno

(PECL fann >= 1.0.0)

fann_reset_errno — Resets the last error number

Descrierea

void fann_reset_errno ( resource $errdat )

Resets the last error number.

Parametri

errdat

resource a unei re?ele neuronale, sau resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • fann_get_errno() - Returns the last error number
  • fann_reset_errstr() - Resets the last error string

fann_read_train_from_file
fann_reset_errstr
Func?ii fann


Resets the last error string

fann_reset_errno
fann_reset_MSE
Func?ii fann
PHP Manual

fann_reset_errstr

(PECL fann >= 1.0.0)

fann_reset_errstr — Resets the last error string

Descrierea

void fann_reset_errstr ( resource $errdat )

Resets the last error string.

Parametri

errdat

resource a unei re?ele neuronale, sau resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • fann_get_errstr() - Returns the last errstr
  • fann_reset_errno() - Resets the last error number

fann_reset_errno
fann_reset_MSE
Func?ii fann


Resets the mean square error from the network

fann_reset_errstr
fann_run
Func?ii fann
PHP Manual

fann_reset_MSE

(PECL fann >= 1.0.0)

fann_reset_MSE — Resets the mean square error from the network

Descrierea

bool fann_reset_MSE ( string $ann )

Resets the mean square error from the network.

This function also resets the number of bits that fail.

Parametri

ann

resource a unei re?ele neuronale.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_MSE() - Reads the mean square error from the network
  • fann_get_bit_fail() - The number of fail bits
  • fann_get_bit_fail_limit() - Returns the bit fail limit used during training

fann_reset_errstr
fann_run
Func?ii fann


Will run input through the neural network

fann_reset_MSE
fann_save_train
Func?ii fann
PHP Manual

fann_run

(PECL fann >= 1.0.0)

fann_run — Will run input through the neural network

Descrierea

array fann_run ( resource $ann , array $input )

Will run input through the neural network, returning an array of outputs, the number of which being equal to the number of neurons in the output layer.

Parametri

ann

resource a unei re?ele neuronale.

input

Array of input values

Valorile întoarse

Array of output values, or FALSE on error

fann_reset_MSE
fann_save_train
Func?ii fann


Save the training structure to a file

fann_run
fann_save
Func?ii fann
PHP Manual

fann_save_train

(PECL fann >= 1.0.0)

fann_save_train — Save the training structure to a file

Descrierea

bool fann_save_train ( resource $data , string $file_name )

Save the training data to a file, with the format as specified in fann_read_train_from_file().

Parametri

data

resource a datelor pentru antrenarea re?elei neuronale.

file_name

The file name of the file where training data is saved to.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_read_train_from_file() - Reads a file that stores training data

fann_run
fann_save
Func?ii fann


Saves the entire network to a configuration file

fann_save_train
fann_scale_input_train_data
Func?ii fann
PHP Manual

fann_save

(PECL fann >= 1.0.0)

fann_save — Saves the entire network to a configuration file

Descrierea

bool fann_save ( resource $ann , string $configuration_file )

Saves the entire network to a configuration file.

The configuration file contains all information about the neural network and enables fann_create_from_file() to create an exact copy of the neural network and all of the parameters associated with the neural network.

These three parameters (fann_set_callback(), fann_set_error_log(), fann_set_user_data()) are NOT saved to the file because they cannot safely be ported to a different location. Also temporary parameters generated during training like fann_get_MSE() is not saved.

Parametri

ann

resource a unei re?ele neuronale.

configuration_file

The configuration file path.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_create_from_file() - Constructs a backpropagation neural network from a configuration file

fann_save_train
fann_scale_input_train_data
Func?ii fann


Scales the inputs in the training data to the specified range

fann_save
fann_scale_input
Func?ii fann
PHP Manual

fann_scale_input_train_data

(PECL fann >= 1.0.0)

fann_scale_input_train_data — Scales the inputs in the training data to the specified range

Descrierea

bool fann_scale_input_train_data ( resource $train_data , float $new_min , float $new_max )

Scales the inputs in the training data to the specified range.

Parametri

train_data

resource a datelor pentru antrenarea re?elei neuronale.

new_min

New minimum after scaling inputs in training data.

new_max

New maximum after scaling inputs in training data.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_scale_output_train_data() - Scales the outputs in the training data to the specified range
  • fann_scale_train_data() - Scales the inputs and outputs in the training data to the specified range

fann_save
fann_scale_input
Func?ii fann


Scale data in input vector before feed it to ann based on previously calculated parameters

fann_scale_input_train_data
fann_scale_output_train_data
Func?ii fann
PHP Manual

fann_scale_input

(PECL fann >= 1.0.0)

fann_scale_input — Scale data in input vector before feed it to ann based on previously calculated parameters

Descrierea

bool fann_scale_input ( resource $ann , array $input_vector )

Scale data in input vector before feed it to ann based on previously calculated parameters.

Parametri

ann

resource a unei re?ele neuronale.

input_vector

Input vector that will be scaled

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_descale_input() - Scale data in input vector after get it from ann based on previously calculated parameters
  • fann_scale_output() - Scale data in output vector before feed it to ann based on previously calculated parameters

fann_scale_input_train_data
fann_scale_output_train_data
Func?ii fann


Scales the outputs in the training data to the specified range

fann_scale_input
fann_scale_output
Func?ii fann
PHP Manual

fann_scale_output_train_data

(PECL fann >= 1.0.0)

fann_scale_output_train_data — Scales the outputs in the training data to the specified range

Descrierea

bool fann_scale_output_train_data ( resource $train_data , float $new_min , float $new_max )

Scales the outputs in the training data to the specified range.

Parametri

train_data

resource a datelor pentru antrenarea re?elei neuronale.

new_min

New minimum after scaling outputs in training data.

new_max

New maximum after scaling outputs in training data.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_scale_input_train_data() - Scales the inputs in the training data to the specified range
  • fann_scale_train_data() - Scales the inputs and outputs in the training data to the specified range

fann_scale_input
fann_scale_output
Func?ii fann


Scale data in output vector before feed it to ann based on previously calculated parameters

fann_scale_output_train_data
fann_scale_train_data
Func?ii fann
PHP Manual

fann_scale_output

(PECL fann >= 1.0.0)

fann_scale_output — Scale data in output vector before feed it to ann based on previously calculated parameters

Descrierea

bool fann_scale_output ( resource $ann , array $output_vector )

Scale data in output vector before feed it to ann based on previously calculated parameters.

Parametri

ann

resource a unei re?ele neuronale.

output_vector

Output vector that will be scaled

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_descale_output() - Scale data in output vector after get it from ann based on previously calculated parameters
  • fann_scale_input() - Scale data in input vector before feed it to ann based on previously calculated parameters

fann_scale_output_train_data
fann_scale_train_data
Func?ii fann


Scales the inputs and outputs in the training data to the specified range

fann_scale_output
fann_scale_train
Func?ii fann
PHP Manual

fann_scale_train_data

(PECL fann >= 1.0.0)

fann_scale_train_data — Scales the inputs and outputs in the training data to the specified range

Descrierea

bool fann_scale_train_data ( resource $train_data , float $new_min , float $new_max )

Scales the inputs and outputs in the training data to the specified range.

Parametri

train_data

resource a datelor pentru antrenarea re?elei neuronale.

new_min

New minimum after scaling inputs and outputs in training data.

new_max

New maximum after scaling inputs and outputs in training data.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_scale_output_train_data() - Scales the outputs in the training data to the specified range
  • fann_scale_input_train_data() - Scales the inputs in the training data to the specified range

fann_scale_output
fann_scale_train
Func?ii fann


Scale input and output data based on previously calculated parameters

fann_scale_train_data
fann_set_activation_function_hidden
Func?ii fann
PHP Manual

fann_scale_train

(PECL fann >= 1.0.0)

fann_scale_train — Scale input and output data based on previously calculated parameters

Descrierea

bool fann_scale_train ( resource $ann , resource $train_data )

Scale input and output data based on previously calculated parameters.

Parametri

ann

resource a unei re?ele neuronale.

train_data

resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_descale_train() - Descale input and output data based on previously calculated parameters
  • fann_set_scaling_params() - Calculate input and output scaling parameters for future use based on training data

fann_scale_train_data
fann_set_activation_function_hidden
Func?ii fann


Sets the activation function for all of the hidden layers

fann_scale_train
fann_set_activation_function_layer
Func?ii fann
PHP Manual

fann_set_activation_function_hidden

(PECL fann >= 1.0.0)

fann_set_activation_function_hidden — Sets the activation function for all of the hidden layers

Descrierea

bool fann_set_activation_function_hidden ( resource $ann , int $activation_function )

Sets the activation function for all of the hidden layers.

Parametri

ann

resource a unei re?ele neuronale.

activation_function

The activation functions constant.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer
  • fann_set_activation_function_layer() - Sets the activation function for all the neurons in the supplied layer.
  • fann_set_activation_function_output() - Sets the activation function for the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number

fann_scale_train
fann_set_activation_function_layer
Func?ii fann


Sets the activation function for all the neurons in the supplied layer.

fann_set_activation_function_hidden
fann_set_activation_function_output
Func?ii fann
PHP Manual

fann_set_activation_function_layer

(PECL fann >= 1.0.0)

fann_set_activation_function_layer — Sets the activation function for all the neurons in the supplied layer.

Descrierea

bool fann_set_activation_function_layer ( resource $ann , int $activation_function , int $layer )

Set the activation function for all the neurons in the layer number layer, counting the input layer as layer 0.

It is not possible to set activation functions for the neurons in the input layer.

Parametri

ann

resource a unei re?ele neuronale.

activation_function

The activation functions constant.

layer

Layer number.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer
  • fann_set_activation_function_hidden() - Sets the activation function for all of the hidden layers
  • fann_set_activation_function_output() - Sets the activation function for the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number

fann_set_activation_function_hidden
fann_set_activation_function_output
Func?ii fann


Sets the activation function for the output layer

fann_set_activation_function_layer
fann_set_activation_function
Func?ii fann
PHP Manual

fann_set_activation_function_output

(PECL fann >= 1.0.0)

fann_set_activation_function_output — Sets the activation function for the output layer

Descrierea

bool fann_set_activation_function_output ( resource $ann , int $activation_function )

Sets the activation function for the output layer.

Parametri

ann

resource a unei re?ele neuronale.

activation_function

The activation functions constant.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer
  • fann_set_activation_function_layer() - Sets the activation function for all the neurons in the supplied layer.
  • fann_set_activation_function_hidden() - Sets the activation function for all of the hidden layers
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number

fann_set_activation_function_layer
fann_set_activation_function
Func?ii fann


Sets the activation function for supplied neuron and layer

fann_set_activation_function_output
fann_set_activation_steepness_hidden
Func?ii fann
PHP Manual

fann_set_activation_function

(PECL fann >= 1.0.0)

fann_set_activation_function — Sets the activation function for supplied neuron and layer

Descrierea

bool fann_set_activation_function ( resource $ann , int $activation_function , int $layer , int $neuron )

Set the activation function for neuron number neuron in layer number layer, counting the input layer as layer 0.

It is not possible to set activation functions for the neurons in the input layer.

When choosing an activation function it is important to note that the activation functions have different range. FANN_SIGMOID is e.g. in the 0 - 1 range while FANN_SIGMOID_SYMMETRIC is in the -1 - 1 range and FANN_LINEAR is unbound.

The supplied activation_function value must be one of the activation functions constants.

The return value is one of the activation functions constants.

Parametri

ann

resource a unei re?ele neuronale.

activation_function

The activation functions constant.

layer

Layer number.

neuron

Neuron number.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_set_activation_function_layer() - Sets the activation function for all the neurons in the supplied layer.
  • fann_set_activation_function_hidden() - Sets the activation function for all of the hidden layers
  • fann_set_activation_function_output() - Sets the activation function for the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_get_activation_function() - Returns the activation function

fann_set_activation_function_output
fann_set_activation_steepness_hidden
Func?ii fann


Sets the steepness of the activation steepness for all neurons in the all hidden layers

fann_set_activation_function
fann_set_activation_steepness_layer
Func?ii fann
PHP Manual

fann_set_activation_steepness_hidden

(PECL fann >= 1.0.0)

fann_set_activation_steepness_hidden — Sets the steepness of the activation steepness for all neurons in the all hidden layers

Descrierea

bool fann_set_activation_steepness_hidden ( resource $ann , float $activation_steepness )

Sets the steepness of the activation steepness for all neurons in the all hidden layers.

Parametri

ann

resource a unei re?ele neuronale.

activation_steepness

The activation steepness.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_set_activation_steepness_layer() - Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_output() - Sets the steepness of the activation steepness in the output layer
  • fann_get_activation_steepness() - Returns the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer

fann_set_activation_function
fann_set_activation_steepness_layer
Func?ii fann


Sets the activation steepness for all of the neurons in the supplied layer number

fann_set_activation_steepness_hidden
fann_set_activation_steepness_output
Func?ii fann
PHP Manual

fann_set_activation_steepness_layer

(PECL fann >= 1.0.0)

fann_set_activation_steepness_layer — Sets the activation steepness for all of the neurons in the supplied layer number

Descrierea

bool fann_set_activation_steepness_layer ( resource $ann , float $activation_steepness , int $layer )

Set the activation steepness for all of the neurons in layer number layer, counting the input layer as layer 0.

It is not possible to set activation steepness for the neurons in the input layer.

Parametri

ann

resource a unei re?ele neuronale.

activation_steepness

The activation steepness.

layer

Layer number.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_set_activation_steepness_hidden() - Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_set_activation_steepness_output() - Sets the steepness of the activation steepness in the output layer
  • fann_get_activation_steepness() - Returns the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer

fann_set_activation_steepness_hidden
fann_set_activation_steepness_output
Func?ii fann


Sets the steepness of the activation steepness in the output layer

fann_set_activation_steepness_layer
fann_set_activation_steepness
Func?ii fann
PHP Manual

fann_set_activation_steepness_output

(PECL fann >= 1.0.0)

fann_set_activation_steepness_output — Sets the steepness of the activation steepness in the output layer

Descrierea

bool fann_set_activation_steepness_output ( resource $ann , float $activation_steepness )

Sets the steepness of the activation steepness in the output layer.

Parametri

ann

resource a unei re?ele neuronale.

activation_steepness

The activation steepness.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_set_activation_steepness_layer() - Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_hidden() - Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_get_activation_steepness() - Returns the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer

fann_set_activation_steepness_layer
fann_set_activation_steepness
Func?ii fann


Sets the activation steepness for supplied neuron and layer number

fann_set_activation_steepness_output
fann_set_bit_fail_limit
Func?ii fann
PHP Manual

fann_set_activation_steepness

(PECL fann >= 1.0.0)

fann_set_activation_steepness — Sets the activation steepness for supplied neuron and layer number

Descrierea

bool fann_set_activation_steepness ( resource $ann , float $activation_steepness , int $layer , int $neuron )

Set the activation steepness for neuron number neuron in layer number layer, counting the input layer as layer 0.

It is not possible to set activation steepness for the neurons in the input layer.

The steepness of an activation function says something about how fast the activation function goes from the minimum to the maximum. A high value for the activation function will also give a more agressive training.

When training neural networks where the output values should be at the extremes (usually 0 and 1, depending on the activation function), a steep activation function can be used (e.g. 1.0).

The default activation steepness is 0.5.

Parametri

ann

resource a unei re?ele neuronale.

activation_steepness

The activation steepness.

layer

Layer number.

neuron

Neuron number.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_set_activation_steepness_layer() - Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_hidden() - Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_set_activation_steepness_output() - Sets the steepness of the activation steepness in the output layer
  • fann_get_activation_steepness() - Returns the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer

fann_set_activation_steepness_output
fann_set_bit_fail_limit
Func?ii fann


Set the bit fail limit used during training

fann_set_activation_steepness
fann_set_callback
Func?ii fann
PHP Manual

fann_set_bit_fail_limit

(PECL fann >= 1.0.0)

fann_set_bit_fail_limit — Set the bit fail limit used during training

Descrierea

bool fann_set_bit_fail_limit ( resource $ann , float $bit_fail_limit )

Set the bit fail limit used during training.

Parametri

ann

resource a unei re?ele neuronale.

bit_fail_limit

The bit fail limit.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_bit_fail_limit() - Returns the bit fail limit used during training

fann_set_activation_steepness
fann_set_callback
Func?ii fann


Sets the callback function for use during training

fann_set_bit_fail_limit
fann_set_cascade_activation_functions
Func?ii fann
PHP Manual

fann_set_callback

(PECL fann >= 1.0.0)

fann_set_callback — Sets the callback function for use during training

Descrierea

bool fann_set_callback ( resource $ann , collable $callback )

Sets the callback function for use during training. It means that it is called from fann_train_on_data() or fann_train_on_file().

Parametri

ann

resource a unei re?ele neuronale.

callback

The supplied callback function takes following parameters:

  • ann - The neural network resource
  • train - The train data resource or NULL if called from fann_train_on_file()
  • max_epochs - The maximum number of epochs the training should continue
  • epochs_between_reports - The number of epochs between calling this function
  • desired_error - The desired fann_get_MSE() or fann_get_bit_fail(), depending on the stop function chosen by fann_set_train_stop_function()
  • epochs - The current epoch

The callback should return TRUE. If it returns FALSE, the training will terminate.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_train_on_file() - Trains on an entire dataset, which is read from file, for a period of time

fann_set_bit_fail_limit
fann_set_cascade_activation_functions
Func?ii fann


Sets the array of cascade candidate activation functions

fann_set_callback
fann_set_cascade_activation_steepnesses
Func?ii fann
PHP Manual

fann_set_cascade_activation_functions

(PECL fann >= 1.0.0)

fann_set_cascade_activation_functions — Sets the array of cascade candidate activation functions

Descrierea

bool fann_set_cascade_activation_functions ( resource $ann , array $cascade_activation_functions )

Sets the array of cascade candidate activation functions.

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this array.

Parametri

ann

resource a unei re?ele neuronale.

cascade_activation_functions

The array of cascade candidate activation functions.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_cascade_activation_functions_count() - Returns the number of cascade activation functions
  • fann_set_cascade_activation_functions()

fann_set_callback
fann_set_cascade_activation_steepnesses
Func?ii fann


Sets the array of cascade candidate activation steepnesses

fann_set_cascade_activation_functions
fann_set_cascade_candidate_change_fraction
Func?ii fann
PHP Manual

fann_set_cascade_activation_steepnesses

(PECL fann >= 1.0.0)

fann_set_cascade_activation_steepnesses — Sets the array of cascade candidate activation steepnesses

Descrierea

bool fann_set_cascade_activation_steepnesses ( resource $ann , array $cascade_activation_steepnesses_count )

Sets the array of cascade candidate activation steepnesses.

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this array.

Parametri

ann

resource a unei re?ele neuronale.

cascade_activation_steepnesses_count

The array of cascade candidate activation steepnesses.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_cascade_activation_steepnesses() - Returns the cascade activation steepnesses
  • fann_get_cascade_activation_steepnesses_count() - The number of activation steepnesses

fann_set_cascade_activation_functions
fann_set_cascade_candidate_change_fraction
Func?ii fann


Sets the cascade candidate change fraction

fann_set_cascade_activation_steepnesses
fann_set_cascade_candidate_limit
Func?ii fann
PHP Manual

fann_set_cascade_candidate_change_fraction

(PECL fann >= 1.0.0)

fann_set_cascade_candidate_change_fraction — Sets the cascade candidate change fraction

Descrierea

bool fann_set_cascade_candidate_change_fraction ( resource $ann , float $cascade_candidate_change_fraction )

Sets the cascade candidate change fraction.

Parametri

ann

resource a unei re?ele neuronale.

cascade_candidate_change_fraction

The cascade candidate change fraction.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_cascade_candidate_change_fraction() - Returns the cascade candidate change fraction

fann_set_cascade_activation_steepnesses
fann_set_cascade_candidate_limit
Func?ii fann


Sets the candidate limit

fann_set_cascade_candidate_change_fraction
fann_set_cascade_candidate_stagnation_epochs
Func?ii fann
PHP Manual

fann_set_cascade_candidate_limit

(PECL fann >= 1.0.0)

fann_set_cascade_candidate_limit — Sets the candidate limit

Descrierea

bool fann_set_cascade_candidate_limit ( resource $ann , float $cascade_candidate_limit )

Sets the candidate limit.

Parametri

ann

resource a unei re?ele neuronale.

cascade_candidate_limit

The candidate limit.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_cascade_candidate_limit() - Return the candidate limit

fann_set_cascade_candidate_change_fraction
fann_set_cascade_candidate_stagnation_epochs
Func?ii fann


Sets the number of cascade candidate stagnation epochs

fann_set_cascade_candidate_limit
fann_set_cascade_max_cand_epochs
Func?ii fann
PHP Manual

fann_set_cascade_candidate_stagnation_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_candidate_stagnation_epochs — Sets the number of cascade candidate stagnation epochs

Descrierea

bool fann_set_cascade_candidate_stagnation_epochs ( resource $ann , int $cascade_candidate_stagnation_epochs )

Sets the number of cascade candidate stagnation epochs.

Parametri

ann

resource a unei re?ele neuronale.

cascade_candidate_stagnation_epochs

The number of cascade candidate stagnation epochs.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_cascade_candidate_stagnation_epochs() - Returns the number of cascade candidate stagnation epochs

fann_set_cascade_candidate_limit
fann_set_cascade_max_cand_epochs
Func?ii fann


Sets the max candidate epochs

fann_set_cascade_candidate_stagnation_epochs
fann_set_cascade_max_out_epochs
Func?ii fann
PHP Manual

fann_set_cascade_max_cand_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_max_cand_epochs — Sets the max candidate epochs

Descrierea

bool fann_set_cascade_max_cand_epochs ( resource $ann , int $cascade_max_cand_epochs )

Sets the max candidate epochs.

Parametri

ann

resource a unei re?ele neuronale.

cascade_max_cand_epochs

The max candidate epochs.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_cascade_max_cand_epochs() - Returns the maximum candidate epochs

fann_set_cascade_candidate_stagnation_epochs
fann_set_cascade_max_out_epochs
Func?ii fann


Sets the maximum out epochs

fann_set_cascade_max_cand_epochs
fann_set_cascade_min_cand_epochs
Func?ii fann
PHP Manual

fann_set_cascade_max_out_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_max_out_epochs — Sets the maximum out epochs

Descrierea

bool fann_set_cascade_max_out_epochs ( resource $ann , int $cascade_max_out_epochs )

Sets the maximum out epochs.

Parametri

ann

resource a unei re?ele neuronale.

cascade_max_out_epochs

The maximum out epochs.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_cascade_max_out_epochs() - Returns the maximum out epochs

fann_set_cascade_max_cand_epochs
fann_set_cascade_min_cand_epochs
Func?ii fann


Sets the min candidate epochs

fann_set_cascade_max_out_epochs
fann_set_cascade_min_out_epochs
Func?ii fann
PHP Manual

fann_set_cascade_min_cand_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_min_cand_epochs — Sets the min candidate epochs

Descrierea

bool fann_set_cascade_min_cand_epochs ( resource $ann , int $cascade_min_cand_epochs )

Sets the min candidate epochs.

Parametri

ann

resource a unei re?ele neuronale.

cascade_min_cand_epochs

The minimum candidate epochs.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_cascade_min_cand_epochs() - Returns the minimum candidate epochs

fann_set_cascade_max_out_epochs
fann_set_cascade_min_out_epochs
Func?ii fann


Sets the minimum out epochs

fann_set_cascade_min_cand_epochs
fann_set_cascade_num_candidate_groups
Func?ii fann
PHP Manual

fann_set_cascade_min_out_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_min_out_epochs — Sets the minimum out epochs

Descrierea

bool fann_set_cascade_min_out_epochs ( resource $ann , int $cascade_min_out_epochs )

Sets the minimum out epochs.

Parametri

ann

resource a unei re?ele neuronale.

cascade_min_out_epochs

The minimum out epochs.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_cascade_min_out_epochs() - Returns the minimum out epochs

fann_set_cascade_min_cand_epochs
fann_set_cascade_num_candidate_groups
Func?ii fann


Sets the number of candidate groups

fann_set_cascade_min_out_epochs
fann_set_cascade_output_change_fraction
Func?ii fann
PHP Manual

fann_set_cascade_num_candidate_groups

(PECL fann >= 1.0.0)

fann_set_cascade_num_candidate_groups — Sets the number of candidate groups

Descrierea

bool fann_set_cascade_num_candidate_groups ( resource $ann , int $cascade_num_candidate_groups )

Sets the number of candidate groups.

Parametri

ann

resource a unei re?ele neuronale.

cascade_num_candidate_groups

The number of candidate groups.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_cascade_num_candidate_groups() - Returns the number of candidate groups

fann_set_cascade_min_out_epochs
fann_set_cascade_output_change_fraction
Func?ii fann


Sets the cascade output change fraction

fann_set_cascade_num_candidate_groups
fann_set_cascade_output_stagnation_epochs
Func?ii fann
PHP Manual

fann_set_cascade_output_change_fraction

(PECL fann >= 1.0.0)

fann_set_cascade_output_change_fraction — Sets the cascade output change fraction

Descrierea

bool fann_set_cascade_output_change_fraction ( resource $ann , float $cascade_output_change_fraction )

Sets the cascade output change fraction.

Parametri

ann

resource a unei re?ele neuronale.

cascade_output_change_fraction

The cascade output change fraction.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_cascade_output_change_fraction() - Returns the cascade output change fraction

fann_set_cascade_num_candidate_groups
fann_set_cascade_output_stagnation_epochs
Func?ii fann


Sets the number of cascade output stagnation epochs

fann_set_cascade_output_change_fraction
fann_set_cascade_weight_multiplier
Func?ii fann
PHP Manual

fann_set_cascade_output_stagnation_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_output_stagnation_epochs — Sets the number of cascade output stagnation epochs

Descrierea

bool fann_set_cascade_output_stagnation_epochs ( resource $ann , int $cascade_output_stagnation_epochs )

Sets the number of cascade output stagnation epochs.

Parametri

ann

resource a unei re?ele neuronale.

cascade_output_stagnation_epochs

The number of cascade output stagnation epochs.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_cascade_output_stagnation_epochs() - Returns the number of cascade output stagnation epochs

fann_set_cascade_output_change_fraction
fann_set_cascade_weight_multiplier
Func?ii fann


Sets the weight multiplier

fann_set_cascade_output_stagnation_epochs
fann_set_error_log
Func?ii fann
PHP Manual

fann_set_cascade_weight_multiplier

(PECL fann >= 1.0.0)

fann_set_cascade_weight_multiplier — Sets the weight multiplier

Descrierea

bool fann_set_cascade_weight_multiplier ( resource $ann , float $cascade_weight_multiplier )

Sets the weight multiplier.

Parametri

ann

resource a unei re?ele neuronale.

cascade_weight_multiplier

The weight multiplier.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_cascade_weight_multiplier() - Returns the weight multiplier

fann_set_cascade_output_stagnation_epochs
fann_set_error_log
Func?ii fann


Sets where the errors are logged to

fann_set_cascade_weight_multiplier
fann_set_input_scaling_params
Func?ii fann
PHP Manual

fann_set_error_log

(PECL fann >= 1.0.0)

fann_set_error_log — Sets where the errors are logged to

Descrierea

void fann_set_error_log ( resource $errdat , string $log_file )

Sets where the errors are logged to.

Parametri

errdat

resource a unei re?ele neuronale, sau resource a datelor pentru antrenarea re?elei neuronale.

log_file

The log file path.

Valorile întoarse

Nu este întoarsa nici o valoare.

fann_set_cascade_weight_multiplier
fann_set_input_scaling_params
Func?ii fann


Calculate input scaling parameters for future use based on training data

fann_set_error_log
fann_set_learning_momentum
Func?ii fann
PHP Manual

fann_set_input_scaling_params

(PECL fann >= 1.0.0)

fann_set_input_scaling_params — Calculate input scaling parameters for future use based on training data

Descrierea

bool fann_set_input_scaling_params ( resource $ann , resource $train_data , float $new_input_min , float $new_input_max )

Calculate input scaling parameters for future use based on training data.

Parametri

ann

resource a unei re?ele neuronale.

train_data

resource a datelor pentru antrenarea re?elei neuronale.

new_input_min

The desired lower bound in input data after scaling (not strictly followed)

new_input_max

The desired upper bound in input data after scaling (not strictly followed)

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_set_output_scaling_params() - Calculate output scaling parameters for future use based on training data

fann_set_error_log
fann_set_learning_momentum
Func?ii fann


Sets the learning momentum

fann_set_input_scaling_params
fann_set_learning_rate
Func?ii fann
PHP Manual

fann_set_learning_momentum

(PECL fann >= 1.0.0)

fann_set_learning_momentum — Sets the learning momentum

Descrierea

bool fann_set_learning_momentum ( resource $ann , float $learning_momentum )

Sets the learning momentum.

More info available in fann_get_learning_momentum().

Parametri

ann

resource a unei re?ele neuronale.

learning_momentum

The learning momentum.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_learning_momentum() - Returns the learning momentum
  • fann_set_training_algorithm() - Sets the training algorithm

fann_set_input_scaling_params
fann_set_learning_rate
Func?ii fann


Sets the learning rate

fann_set_learning_momentum
fann_set_output_scaling_params
Func?ii fann
PHP Manual

fann_set_learning_rate

(PECL fann >= 1.0.0)

fann_set_learning_rate — Sets the learning rate

Descrierea

bool fann_set_learning_rate ( resource $ann , float $learning_rate )

Sets the learning rate.

More info available in fann_get_learning_rate().

Parametri

ann

resource a unei re?ele neuronale.

learning_rate

The learning rate.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_learning_rate() - Returns the learning rate
  • fann_set_training_algorithm() - Sets the training algorithm

fann_set_learning_momentum
fann_set_output_scaling_params
Func?ii fann


Calculate output scaling parameters for future use based on training data

fann_set_learning_rate
fann_set_quickprop_decay
Func?ii fann
PHP Manual

fann_set_output_scaling_params

(PECL fann >= 1.0.0)

fann_set_output_scaling_params — Calculate output scaling parameters for future use based on training data

Descrierea

bool fann_set_output_scaling_params ( resource $ann , resource $train_data , float $new_output_min , float $new_output_max )

Calculate output scaling parameters for future use based on training data.

Parametri

ann

resource a unei re?ele neuronale.

train_data

resource a datelor pentru antrenarea re?elei neuronale.

new_output_min

The desired lower bound in output data after scaling (not strictly followed)

new_output_max

The desired upper bound in output data after scaling (not strictly followed)

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_set_input_scaling_params() - Calculate input scaling parameters for future use based on training data

fann_set_learning_rate
fann_set_quickprop_decay
Func?ii fann


Sets the quickprop decay factor

fann_set_output_scaling_params
fann_set_quickprop_mu
Func?ii fann
PHP Manual

fann_set_quickprop_decay

(PECL fann >= 1.0.0)

fann_set_quickprop_decay — Sets the quickprop decay factor

Descrierea

bool fann_set_quickprop_decay ( resource $ann , float $quickprop_decay )

Sets the quickprop decay factor.

Parametri

ann

resource a unei re?ele neuronale.

quickprop_decay

The quickprop decay factor.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_quickprop_decay() - Returns the decay which is a factor that weights should decrease in each iteration during quickprop training

fann_set_output_scaling_params
fann_set_quickprop_mu
Func?ii fann


Sets the quickprop mu factor

fann_set_quickprop_decay
fann_set_rprop_decrease_factor
Func?ii fann
PHP Manual

fann_set_quickprop_mu

(PECL fann >= 1.0.0)

fann_set_quickprop_mu — Sets the quickprop mu factor

Descrierea

bool fann_set_quickprop_mu ( resource $ann , float $quickprop_mu )

Sets the quickprop mu factor.

Parametri

ann

resource a unei re?ele neuronale.

quickprop_mu

The mu factor.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_quickprop_mu() - Returns the mu factor

fann_set_quickprop_decay
fann_set_rprop_decrease_factor
Func?ii fann


Sets the decrease factor used during RPROP training

fann_set_quickprop_mu
fann_set_rprop_delta_max
Func?ii fann
PHP Manual

fann_set_rprop_decrease_factor

(PECL fann >= 1.0.0)

fann_set_rprop_decrease_factor — Sets the decrease factor used during RPROP training

Descrierea

bool fann_set_rprop_decrease_factor ( resource $ann , float $rprop_decrease_factor )

Sets the decrease factor used during RPROP training.

Parametri

ann

resource a unei re?ele neuronale.

rprop_decrease_factor

The decrease factor.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_rprop_decrease_factor() - Returns the increase factor used during RPROP training

fann_set_quickprop_mu
fann_set_rprop_delta_max
Func?ii fann


Sets the maximum step-size

fann_set_rprop_decrease_factor
fann_set_rprop_delta_min
Func?ii fann
PHP Manual

fann_set_rprop_delta_max

(PECL fann >= 1.0.0)

fann_set_rprop_delta_max — Sets the maximum step-size

Descrierea

bool fann_set_rprop_delta_max ( resource $ann , float $rprop_delta_max )

The maximum step-size is a positive number determining how large the maximum step-size may be.

Parametri

ann

resource a unei re?ele neuronale.

rprop_delta_max

The maximum step-size.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_rprop_delta_max() - Returns the maximum step-size
  • fann_get_rprop_delta_min() - Returns the minimum step-size

fann_set_rprop_decrease_factor
fann_set_rprop_delta_min
Func?ii fann


Sets the minimum step-size

fann_set_rprop_delta_max
fann_set_rprop_delta_zero
Func?ii fann
PHP Manual

fann_set_rprop_delta_min

(PECL fann >= 1.0.0)

fann_set_rprop_delta_min — Sets the minimum step-size

Descrierea

bool fann_set_rprop_delta_min ( resource $ann , float $rprop_delta_min )

The minimum step-size is a small positive number determining how small the minimum step-size may be.

Parametri

ann

resource a unei re?ele neuronale.

rprop_delta_min

The minimum step-size.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_rprop_delta_min() - Returns the minimum step-size

fann_set_rprop_delta_max
fann_set_rprop_delta_zero
Func?ii fann


Sets the initial step-size

fann_set_rprop_delta_min
fann_set_rprop_increase_factor
Func?ii fann
PHP Manual

fann_set_rprop_delta_zero

(PECL fann >= 1.0.0)

fann_set_rprop_delta_zero — Sets the initial step-size

Descrierea

bool fann_set_rprop_delta_zero ( resource $ann , float $rprop_delta_zero )

The initial step-size is a positive number determining the initial step size.

Parametri

ann

resource a unei re?ele neuronale.

rprop_delta_zero

The initial step-size.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_rprop_delta_zero() - Returns the initial step-size
  • fann_get_rprop_delta_min() - Returns the minimum step-size
  • fann_get_rprop_delta_max() - Returns the maximum step-size

fann_set_rprop_delta_min
fann_set_rprop_increase_factor
Func?ii fann


Sets the increase factor used during RPROP training

fann_set_rprop_delta_zero
fann_set_sarprop_step_error_shift
Func?ii fann
PHP Manual

fann_set_rprop_increase_factor

(PECL fann >= 1.0.0)

fann_set_rprop_increase_factor — Sets the increase factor used during RPROP training

Descrierea

bool fann_set_rprop_increase_factor ( resource $ann , float $rprop_increase_factor )

Sets the increase factor used during RPROP training.

Parametri

ann

resource a unei re?ele neuronale.

rprop_increase_factor

The increase factor.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_rprop_increase_factor() - Returns the increase factor used during RPROP training

fann_set_rprop_delta_zero
fann_set_sarprop_step_error_shift
Func?ii fann


Sets the sarprop step error shift

fann_set_rprop_increase_factor
fann_set_sarprop_step_error_threshold_factor
Func?ii fann
PHP Manual

fann_set_sarprop_step_error_shift

(PECL fann >= 1.0.0)

fann_set_sarprop_step_error_shift — Sets the sarprop step error shift

Descrierea

bool fann_set_sarprop_step_error_shift ( resource $ann , float $sarprop_step_error_shift )

Sets the sarprop step error shift.

Parametri

ann

resource a unei re?ele neuronale.

sarprop_step_error_shift

The sarprop step error shift.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_sarprop_step_error_shift() - Returns the sarprop step error shift

fann_set_rprop_increase_factor
fann_set_sarprop_step_error_threshold_factor
Func?ii fann


Sets the sarprop step error threshold factor

fann_set_sarprop_step_error_shift
fann_set_sarprop_temperature
Func?ii fann
PHP Manual

fann_set_sarprop_step_error_threshold_factor

(PECL fann >= 1.0.0)

fann_set_sarprop_step_error_threshold_factor — Sets the sarprop step error threshold factor

Descrierea

bool fann_set_sarprop_step_error_threshold_factor ( resource $ann , float $sarprop_step_error_threshold_factor )

Sets the sarprop step error threshold factor.

Parametri

ann

resource a unei re?ele neuronale.

sarprop_step_error_threshold_factor

The sarprop step error threshold factor.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_sarprop_step_error_threshold_factor() - Returns the sarprop step error threshold factor

fann_set_sarprop_step_error_shift
fann_set_sarprop_temperature
Func?ii fann


Sets the sarprop temperature

fann_set_sarprop_step_error_threshold_factor
fann_set_sarprop_weight_decay_shift
Func?ii fann
PHP Manual

fann_set_sarprop_temperature

(PECL fann >= 1.0.0)

fann_set_sarprop_temperature — Sets the sarprop temperature

Descrierea

bool fann_set_sarprop_temperature ( resource $ann , float $sarprop_temperature )

Sets the sarprop temperature.

Parametri

ann

resource a unei re?ele neuronale.

sarprop_temperature

The sarprop temperature.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_sarprop_temperature() - Returns the sarprop temperature

fann_set_sarprop_step_error_threshold_factor
fann_set_sarprop_weight_decay_shift
Func?ii fann


Sets the sarprop weight decay shift

fann_set_sarprop_temperature
fann_set_scaling_params
Func?ii fann
PHP Manual

fann_set_sarprop_weight_decay_shift

(PECL fann >= 1.0.0)

fann_set_sarprop_weight_decay_shift — Sets the sarprop weight decay shift

Descrierea

bool fann_set_sarprop_weight_decay_shift ( resource $ann , float $sarprop_weight_decay_shift )

Sets the sarprop weight decay shift.

Parametri

ann

resource a unei re?ele neuronale.

sarprop_weight_decay_shift

The sarprop weight decay shift.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_sarprop_weight_decay_shift() - Returns the sarprop weight decay shift

fann_set_sarprop_temperature
fann_set_scaling_params
Func?ii fann


Calculate input and output scaling parameters for future use based on training data

fann_set_sarprop_weight_decay_shift
fann_set_train_error_function
Func?ii fann
PHP Manual

fann_set_scaling_params

(PECL fann >= 1.0.0)

fann_set_scaling_params — Calculate input and output scaling parameters for future use based on training data

Descrierea

bool fann_set_scaling_params ( resource $ann , resource $train_data , float $new_input_min , float $new_input_max , float $new_output_min , float $new_output_max )

Calculate input and output scaling parameters for future use based on training data.

Parametri

ann

resource a unei re?ele neuronale.

train_data

resource a datelor pentru antrenarea re?elei neuronale.

new_input_min

The desired lower bound in input data after scaling (not strictly followed)

new_input_max

The desired upper bound in input data after scaling (not strictly followed)

new_output_min

The desired lower bound in output data after scaling (not strictly followed)

new_output_max

The desired upper bound in output data after scaling (not strictly followed)

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_set_input_scaling_params() - Calculate input scaling parameters for future use based on training data
  • fann_set_output_scaling_params() - Calculate output scaling parameters for future use based on training data

fann_set_sarprop_weight_decay_shift
fann_set_train_error_function
Func?ii fann


Sets the error function used during training

fann_set_scaling_params
fann_set_train_stop_function
Func?ii fann
PHP Manual

fann_set_train_error_function

(PECL fann >= 1.0.0)

fann_set_train_error_function — Sets the error function used during training

Descrierea

bool fann_set_train_error_function ( resource $ann , int $error_function )

Sets the error function used during training.

The error functions are described further in error functions constants.

Parametri

ann

resource a unei re?ele neuronale.

error_function

The error function constant

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_train_error_function() - Returns the error function used during training

fann_set_scaling_params
fann_set_train_stop_function
Func?ii fann


Sets the stop function used during training

fann_set_train_error_function
fann_set_training_algorithm
Func?ii fann
PHP Manual

fann_set_train_stop_function

(PECL fann >= 1.0.0)

fann_set_train_stop_function — Sets the stop function used during training

Descrierea

bool fann_set_train_stop_function ( resource $ann , int $stop_function )

Sets the stop function used during training.

The stop functions are described further in stop functions constants.

Parametri

ann

resource a unei re?ele neuronale.

stop_function

The stop function constant.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_train_stop_function() - Returns the stop function used during training

fann_set_train_error_function
fann_set_training_algorithm
Func?ii fann


Sets the training algorithm

fann_set_train_stop_function
fann_set_weight_array
Func?ii fann
PHP Manual

fann_set_training_algorithm

(PECL fann >= 1.0.0)

fann_set_training_algorithm — Sets the training algorithm

Descrierea

bool fann_set_training_algorithm ( resource $ann , int $training_algorithm )

Sets the training algorithm.

More info available in fann_get_training_algorithm().

Parametri

ann

resource a unei re?ele neuronale.

training_algorithm

Training algorithm constant

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_get_training_algorithm() - Returns the training algorithm

fann_set_train_stop_function
fann_set_weight_array
Func?ii fann


Set connections in the network

fann_set_training_algorithm
fann_set_weight
Func?ii fann
PHP Manual

fann_set_weight_array

(PECL fann >= 1.0.0)

fann_set_weight_array — Set connections in the network

Descrierea

bool fann_set_weight_array ( resource $ann , array $connections )

Set connections in the network.

Only the weights can be changed, connections and weights are ignored if they do not already exist in the network.

Parametri

ann

resource a unei re?ele neuronale.

connections

An array of FANNConnection objects

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

fann_set_training_algorithm
fann_set_weight
Func?ii fann


Set a connection in the network

fann_set_weight_array
fann_shuffle_train_data
Func?ii fann
PHP Manual

fann_set_weight

(PECL fann >= 1.0.0)

fann_set_weight — Set a connection in the network

Descrierea

bool fann_set_weight ( resource $ann , int $from_neuron , int $to_neuron , float $weight )

Set a connections in the network.

Parametri

ann

resource a unei re?ele neuronale.

from_neuron

The neuron where the connection starts

to_neuron

The neuron where the connection ends

weight

Connection weight

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

fann_set_weight_array
fann_shuffle_train_data
Func?ii fann


Shuffles training data, randomizing the order

fann_set_weight
fann_subset_train_data
Func?ii fann
PHP Manual

fann_shuffle_train_data

(PECL fann >= 1.0.0)

fann_shuffle_train_data — Shuffles training data, randomizing the order

Descrierea

bool fann_shuffle_train_data ( resource $train_data )

Shuffles training data, randomizing the order. This is recommended for incremental training, while it have no influence during batch training.

Parametri

train_data

resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

fann_set_weight
fann_subset_train_data
Func?ii fann


Returns an copy of a subset of the train data

fann_shuffle_train_data
fann_test_data
Func?ii fann
PHP Manual

fann_subset_train_data

(PECL fann >= 1.0.0)

fann_subset_train_data — Returns an copy of a subset of the train data

Descrierea

resource fann_subset_train_data ( resource $data , int $pos , int $length )

Returns an copy of a subset of the train data resource, starting at position pos and length elements forward.

The fann_subset_train_data(train_data, 0, fann_length_train_data(train_data)) do the same as fann_duplicate_train_data()

Parametri

data

resource a datelor pentru antrenarea re?elei neuronale.

pos

Starting position.

length

The number of copied elements.

Valorile întoarse

Întoarce o resource a datelor pentru antrenarea re?elei neuronale în caz de succes, sau FALSE în caz de eroare.

A se vedea ?i

  • fann_duplicate_train_data() - Returns an exact copy of a fann train data

fann_shuffle_train_data
fann_test_data
Func?ii fann


Test a set of training data and calculates the MSE for the training data

fann_subset_train_data
fann_test
Func?ii fann
PHP Manual

fann_test_data

(PECL fann >= 1.0.0)

fann_test_data — Test a set of training data and calculates the MSE for the training data

Descrierea

float fann_test_data ( resource $ann , resource $data )

Test a set of training data and calculates the MSE for the training data.

This function updates the MSE and the bit fail values.

Parametri

ann

resource a unei re?ele neuronale.

data

resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

The updated MSE, or FALSE on error.

A se vedea ?i

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_bit_fail() - The number of fail bits
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_set_training_algorithm() - Sets the training algorithm

fann_subset_train_data
fann_test
Func?ii fann


Test with a set of inputs, and a set of desired outputs

fann_test_data
fann_train_epoch
Func?ii fann
PHP Manual

fann_test

(PECL fann >= 1.0.0)

fann_test — Test with a set of inputs, and a set of desired outputs

Descrierea

bool fann_test ( resource $ann , array $input , array $desired_output )

Test with a set of inputs, and a set of desired outputs. This operation updates the mean square error, but does not change the network in any way.

Parametri

ann

resource a unei re?ele neuronale.

input

An array of inputs. This array must be exactly fann_get_num_input() long.

desired_output

An array of desired outputs. This array must be exactly fann_get_num_output() long.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_test_data() - Test a set of training data and calculates the MSE for the training data
  • fann_train() - Train one iteration with a set of inputs, and a set of desired outputs
  • fann_get_num_input() - Get the number of input neurons
  • fann_get_num_output() - Get the number of output neurons

fann_test_data
fann_train_epoch
Func?ii fann


Train one epoch with a set of training data

fann_test
fann_train_on_data
Func?ii fann
PHP Manual

fann_train_epoch

(PECL fann >= 1.0.0)

fann_train_epoch — Train one epoch with a set of training data

Descrierea

float fann_train_epoch ( resource $ann , resource $data )

Train one epoch with the training data stored in data. One epoch is where all of the training data is considered exactly once.

This function returns the MSE error as it is calculated either before or during the actual training. This is not the actual MSE after the training epoch, but since calculating this will require to go through the entire training set once more. It is more than adequate to use this value during training.

The training algorithm used by this function is chosen by fann_set_training_algorithm() function.

Parametri

ann

resource a unei re?ele neuronale.

data

resource a datelor pentru antrenarea re?elei neuronale.

Valorile întoarse

The MSE, or FALSE on error.

A se vedea ?i

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_test_data() - Test a set of training data and calculates the MSE for the training data
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_set_training_algorithm() - Sets the training algorithm

fann_test
fann_train_on_data
Func?ii fann


Trains on an entire dataset for a period of time

fann_train_epoch
fann_train_on_file
Func?ii fann
PHP Manual

fann_train_on_data

(PECL fann >= 1.0.0)

fann_train_on_data — Trains on an entire dataset for a period of time

Descrierea

bool fann_train_on_data ( resource $ann , resource $data , int $max_epochs , int $epochs_between_reports , float $desired_error )

Trains on an entire dataset for a period of time.

This training uses the training algorithm chosen by fann_set_training_algorithm() and the parameters set for these training algorithms.

Parametri

ann

resource a unei re?ele neuronale.

data

resource a datelor pentru antrenarea re?elei neuronale.

max_epochs

The maximum number of epochs the training should continue

epochs_between_reports

The number of epochs between calling a callback function. A value of zero means that user function is not called.

desired_error

The desired fann_get_MSE() or fann_get_bit_fail(), depending on the stop function chosen by fann_set_train_stop_function()

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_train_on_file() - Trains on an entire dataset, which is read from file, for a period of time
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_bit_fail() - The number of fail bits
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_set_train_stop_function() - Sets the stop function used during training
  • fann_set_training_algorithm() - Sets the training algorithm
  • fann_set_callback() - Sets the callback function for use during training

fann_train_epoch
fann_train_on_file
Func?ii fann


Trains on an entire dataset, which is read from file, for a period of time

fann_train_on_data
fann_train
Func?ii fann
PHP Manual

fann_train_on_file

(PECL fann >= 1.0.0)

fann_train_on_file — Trains on an entire dataset, which is read from file, for a period of time

Descrierea

bool fann_train_on_file ( resource $ann , string $filename , int $max_epochs , int $epochs_between_reports , float $desired_error )

Trains on an entire dataset, which is read from file, for a period of time.

This training uses the training algorithm chosen by fann_set_training_algorithm() and the parameters set for these training algorithms.

Parametri

ann

resource a unei re?ele neuronale.

filename

The file containing train data

max_epochs

The maximum number of epochs the training should continue

epochs_between_reports

The number of epochs between calling a user function. A value of zero means that user function is not called.

desired_error

The desired fann_get_MSE() or fann_get_bit_fail(), depending on the stop function chosen by fann_set_train_stop_function()

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_bit_fail() - The number of fail bits
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_set_train_stop_function() - Sets the stop function used during training
  • fann_set_training_algorithm() - Sets the training algorithm
  • fann_set_callback() - Sets the callback function for use during training

fann_train_on_data
fann_train
Func?ii fann


Train one iteration with a set of inputs, and a set of desired outputs

fann_train_on_file
FANNConnection
Func?ii fann
PHP Manual

fann_train

(PECL fann >= 1.0.0)

fann_train — Train one iteration with a set of inputs, and a set of desired outputs

Descrierea

bool fann_train ( resource $ann , array $input , array $desired_output )

Train one iteration with a set of inputs, and a set of desired outputs. This training is always incremental training, since only one pattern is presented.

Parametri

ann

resource a unei re?ele neuronale.

input

An array of inputs. This array must be exactly fann_get_num_input() long.

desired_output

An array of desired outputs. This array must be exactly fann_get_num_output() long.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

A se vedea ?i

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_num_input() - Get the number of input neurons
  • fann_get_num_output() - Get the number of output neurons

fann_train_on_file
FANNConnection
Func?ii fann


The FANNConnection class

(No version information available, might only be in Git)

Introducere

FANNConnection is used for the neural network connection. The objects of this class are used in fann_get_connection_array() and fann_set_weight_array().

Sinopsisul clasei

FANNConnection {
/* Proprieta?i */
public $from_neuron ;
public $to_neuron ;
public $weight ;
/* Metode */
public __construct ( int $from_neuron , int $to_neuron , float $weight )
public int getFromNeuron ( void )
public int getToNeuron ( void )
public void getWeight ( void )
public bool setWeight ( float $weight )
}

Proprieta?i

from_neuron

The neuron where the connection starts.

to_neuron

The neuron where the connection ends.

weight

The weight of the connection.

Cuprins

  • FANNConnection::__construct — The connection constructor
  • FANNConnection::getFromNeuron — Returns the postions of starting neuron.
  • FANNConnection::getToNeuron — Returns the postions of terminating neuron
  • FANNConnection::getWeight — Returns the connection weight
  • FANNConnection::setWeight — Sets the connections weight
fann_train
FANNConnection::__construct
FANN


The connection constructor

FANNConnection
FANNConnection::getFromNeuron
FANNConnection
PHP Manual

FANNConnection::__construct

(PECL fann >= 1.0.0)

FANNConnection::__construct — The connection constructor

Descrierea

public FANNConnection::__construct ( int $from_neuron , int $to_neuron , float $weight )

Create new connection and initialize its params. After creating the connection, only weight can be changed.

Parametri

from_neuron

The postion number of starting neuron.

to_neuron

The postion number of terminating neuron.

weight

The connection weight value.

FANNConnection
FANNConnection::getFromNeuron
FANNConnection


Returns the postions of starting neuron.

FANNConnection::__construct
FANNConnection::getToNeuron
FANNConnection
PHP Manual

FANNConnection::getFromNeuron

(PECL fann >= 1.0.0)

FANNConnection::getFromNeuron — Returns the postions of starting neuron.

Descrierea

public int FANNConnection::getFromNeuron ( void )

Returns the postions of starting neuron.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The postions of starting neuron.

FANNConnection::__construct
FANNConnection::getToNeuron
FANNConnection


Returns the postions of terminating neuron

FANNConnection::getFromNeuron
FANNConnection::getWeight
FANNConnection
PHP Manual

FANNConnection::getToNeuron

(PECL fann >= 1.0.0)

FANNConnection::getToNeuron — Returns the postions of terminating neuron

Descrierea

public int FANNConnection::getToNeuron ( void )

Returns the postions of terminating neuron.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The postions of terminating neuron.

FANNConnection::getFromNeuron
FANNConnection::getWeight
FANNConnection


Returns the connection weight

FANNConnection::getToNeuron
FANNConnection::setWeight
FANNConnection
PHP Manual

FANNConnection::getWeight

(PECL fann >= 1.0.0)

FANNConnection::getWeight — Returns the connection weight

Descrierea

public void FANNConnection::getWeight ( void )

Returns the connection weight.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The connection weight.

FANNConnection::getToNeuron
FANNConnection::setWeight
FANNConnection


Sets the connections weight

FANNConnection::getWeight
JSON
FANNConnection
PHP Manual

FANNConnection::setWeight

(PECL fann >= 1.0.0)

FANNConnection::setWeight — Sets the connections weight

Descrierea

public bool FANNConnection::setWeight ( float $weight )

Sets the connection weight.

This method is different than fann_set_weight(). It does not update the weight value in the network. The network value is updated only after calling fann_set_weight_array().

Parametri

weight

The connection weight.

Valorile întoarse

Întoarce TRUE în caz de succes, sau FALSE în caz contrar.

FANNConnection::getWeight
JSON
FANNConnection


Notarea Obiect JavaScript

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • JsonSerializable — Interfa?a JsonSerializable
    • JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON
  • Func?ii JSON
    • json_decode — Converte?te într-o variabila un ?ir reprezentat JSON
    • json_encode — Întoarce o reprezentare JSON pentru valoarea data
    • json_last_error_msg — Întoarce ?irul de eroare a ultimului apel json_encode() sau json_decode()
    • json_last_error — Întoarce ultima eroare ce a survenit
FANNConnection::setWeight
Introducere
Alte extensii de baza


Introducere

Aceasta extensie implementeaza formatul de inter-schimbare a datlor » JavaScript Object Notation (JSON). Decodificarea este efectuata de un interpretor bazat pe JSON_checker de Douglas Crockford.

Nota:

PHP implementeaza un superset al JSON, dupa cum este specificat în documentul » RFC 4627 original; de asemenea el va codifica ?i va decodifica tipuri scalare ?i NULL. RFC 4627 sus?ine aceste valori doar atunci când ele sunt încorporate într-un tablou sau obiect.

Cu toate ca acest superset este consecvent cu defini?ia extinsa de "text JSON" din noul » RFC 7159 (care are ca scop sa înlocuiasca RFC 4627) ?i ECMA-404, aceasta poate cauza probleme de interoperabilitate cu interpretorii JSON mai vechi care adera strict la RFC 4627 la codificarea unei singure valori scalare.

JSON
Instalarea / configurarea
JSON


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
JSON


Instalarea

Începând cu PHP 5.2.0 extensia JSON este încorporata ?i compilata în PHP în mod implicit.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/json

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Urmatoarele constante indica tipul erorii întoarse de func?ia json_last_error().

JSON_ERROR_NONE (integer)
Nu s-a produs vre-o eroare. Disponibila începând cu PHP 5.3.0.
JSON_ERROR_DEPTH (integer)
A fost depa?ita adâncimea maxima a stivei. Disponibila începând cu PHP 5.3.0.
JSON_ERROR_STATE_MISMATCH (integer)
Are loc în cazul unei valori ce depa?e?te limita de jos, sau când modurile nu coincid. Disponibila începând cu PHP 5.3.0.
JSON_ERROR_CTRL_CHAR (integer)
Eroare în caracterul de control, posibil a fost codificat gre?it. Disponibila începând cu PHP 5.3.0.
JSON_ERROR_SYNTAX (integer)
Eroare în sintaxa. Disponibila începând cu PHP 5.3.0.
JSON_ERROR_UTF8 (integer)
Caractere UTF-8 eronate, posibil codificate incorect. Aceasta constanta este disponibila începând cu PHP 5.3.3.
JSON_ERROR_RECURSION (integer)

Obiectul sau tabloul transmis func?iei json_encode() include referin?e recursive ?i de aceea nu pot fi codificate. Daca a fost indicata op?iunea JSON_PARTIAL_OUTPUT_ON_ERROR, în locul referin?elor recursive va fi codificat NULL.

Aceasta constanta e disponibila începând cu PHP 5.5.0.

JSON_ERROR_INF_OR_NAN (integer)

Valoarea transmisa func?iei json_encode() include NAN sau INF. Daca a fost indicata op?iunea JSON_PARTIAL_OUTPUT_ON_ERROR, în locul acestor numere speciale va fi codificat 0.

Aceasta constanta e disponivila începând cu PHP 5.5.0.

JSON_ERROR_UNSUPPORTED_TYPE (integer)

O valoare de tip nesus?inut a fost transmisa func?iei json_encode(), cum ar fi o resource. Daca a fost indicata op?iunea JSON_PARTIAL_OUTPUT_ON_ERROR, în locul valorii nesus?inute va fi codificat NULL.

Aceasta constanta e disponivila începând cu PHP 5.5.0.

Urmatoarele constante pot fi combinate pentru a forma op?iuni pentru json_encode().

JSON_HEX_TAG (integer)
Toate < ?i > sunt convertite în \u003C ?i \u003E. Disponibila începând cu PHP 5.3.0.
JSON_HEX_AMP (integer)
Toate & sunt convertite în \u0026. Disponibila începând cu PHP 5.3.0.
JSON_HEX_APOS (integer)
Toate ' sunt convertite în \u0027. Disponibila începând cu PHP 5.3.0.
JSON_HEX_QUOT (integer)
Toate " sunt convertite în \u0022. Disponibila începând cu PHP 5.3.0.
JSON_FORCE_OBJECT (integer)
Întoarce un obiect în loc de tablou când este utilizat un tablou non-associativ. Util în special când receptorul rezultatului se a?teapta la un obiect, iar tabloul este vid. Disponibila începând cu PHP 5.3.0.
JSON_NUMERIC_CHECK (integer)
Codifica ?iruri numerice ca numere. Disponibila începând cu PHP 5.3.3.
JSON_BIGINT_AS_STRING (integer)
Codifica numerele întregi mari ca ?iruri de caractere la valoarea lor originala. Disponibila începând cu PHP 5.4.0.
JSON_PRETTY_PRINT (integer)
Folose?te spa?ii în datele întoarse pentru a le formata. Disponibila începând cu PHP 5.4.0.
JSON_UNESCAPED_SLASHES (integer)
Nu evadeaza caracterele /. Disponibila începând cu PHP 5.4.0.
JSON_UNESCAPED_UNICODE (integer)
Codifica caracterele Unicode pe mai mul?i bai?i a?a cum sunt (implicit se efectueaza evadarea de tip \uXXXX). Disponibila începând cu PHP 5.4.0.
JSON_PARTIAL_OUTPUT_ON_ERROR (integer)
Substituie unele valori ce nu pot fi codificate, în loc sa e?ueze. Disponibila începând cu PHP 5.5.0.
JSON_PRESERVE_ZERO_FRACTION (integer)
Asigura ca valorile float sa fie întotdeauna codificate ca valori float. Disponibila începând cu PHP 5.6.6.
Tipurile resurselor
JsonSerializable
JSON


Interfa?a JsonSerializable

(PHP 5 >= 5.4.0, PHP 7)

Introducere

Obiectele care implementeaza JsonSerializable pot personaliza reprezentarea JSON în urma apelarii func?iei json_encode().

Descrierea succinta a interfe?ei

JsonSerializable {
/* Metode */
abstract public mixed jsonSerialize ( void )
}

Cuprins

  • JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON
Constante predefinite
JsonSerializable::jsonSerialize
JSON


Specify data which should be serialized to JSON

JsonSerializable
Func?ii JSON
JsonSerializable
PHP Manual

JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0, PHP 7)

JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON

Descrierea

abstract public mixed JsonSerializable::jsonSerialize ( void )

Serializes the object to a value that can be serialized natively by json_encode().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns data which can be serialized by json_encode(), which is a value of any type other than a resource.

Exemple

Example #1 JsonSerializable::jsonSerialize() example returning an array

<?php
class ArrayValue implements JsonSerializable {
    public function __construct(array $array) {
        $this->array = $array;
    }

    public function jsonSerialize() {
        return $this->array;
    }
}

$array = [1, 2, 3];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

Exemplul de mai sus va afi?a:

[
    1,
    2,
    3
]

Example #2 JsonSerializable::jsonSerialize() example returning an associative array

<?php
class ArrayValue implements JsonSerializable {
    public function __construct(array $array) {
        $this->array = $array;
    }

    public function jsonSerialize() {
        return $this->array;
    }
}

$array = ['foo' => 'bar', 'quux' => 'baz'];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

Exemplul de mai sus va afi?a:

{
    "foo": "bar",
    "quux": "baz"
}

Example #3 JsonSerializable::jsonSerialize() example returning an integer

<?php
class IntegerValue implements JsonSerializable {
    public function __construct($number) {
        $this->number = (integer) $number;
    }

    public function jsonSerialize() {
        return $this->number;
    }
}

echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);
?>

Exemplul de mai sus va afi?a:

1

Example #4 JsonSerializable::jsonSerialize() example returning a string

<?php
class StringValue implements JsonSerializable {
    public function __construct($string) {
        $this->string = (string) $string;
    }

    public function jsonSerialize() {
        return $this->string;
    }
}

echo json_encode(new StringValue('Hello!'), JSON_PRETTY_PRINT);
?>

Exemplul de mai sus va afi?a:

"Hello!"

JsonSerializable
Func?ii JSON
JsonSerializable


Func?ii JSON

Cuprins

  • json_decode — Converte?te într-o variabila un ?ir reprezentat JSON
  • json_encode — Întoarce o reprezentare JSON pentru valoarea data
  • json_last_error_msg — Întoarce ?irul de eroare a ultimului apel json_encode() sau json_decode()
  • json_last_error — Întoarce ultima eroare ce a survenit
JsonSerializable::jsonSerialize
json_decode
JSON


Converte?te într-o variabila un ?ir reprezentat JSON

Func?ii JSON
json_encode
Func?ii JSON
PHP Manual

json_decode

(PHP 5 >= 5.2.0, PECL json >= 1.2.0, PHP 7)

json_decode — Converte?te într-o variabila un ?ir reprezentat JSON

Descrierea

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

Preia un ?ir de caractere reprezentat JSON ?i îl converte?te într-o variabila PHP.

Parametri

json

?irul (string) reprezentat json care trebuie convertit.

Aceasta func?ie opereaza doar cu ?iruri codificate în UTF-8.

Nota:

PHP implementeaza un superset al JSON, dupa cum este specificat în documentul » RFC 4627 original; de asemenea el va codifica ?i va decodifica tipuri scalare ?i NULL. RFC 4627 sus?ine aceste valori doar atunci când ele sunt încorporate într-un tablou sau obiect.

Cu toate ca acest superset este consecvent cu defini?ia extinsa de "text JSON" din noul » RFC 7159 (care are ca scop sa înlocuiasca RFC 4627) ?i ECMA-404, aceasta poate cauza probleme de interoperabilitate cu interpretorii JSON mai vechi care adera strict la RFC 4627 la codificarea unei singure valori scalare.

assoc

Daca specifica?i TRUE, obiectul va fi convertit într-un array asociativ.

depth

Limita adâncimii de imbricare specificata de utilizator.

options

Masca de bi?i a op?iunilor de decodificare JSON. în prezent este sus?inuta doar JSON_BIGINT_AS_STRING (în mod implicit numerele întregi mari se transforma în numere cu virgula flotanta)

Valorile întoarse

Întoarce valoarea codificata în json cu tipul PHP corespunzator. Valorile true, false ?i null sunt întoarse ca TRUE, FALSE ?i NULL respectiv. NULL este întors daca parametrul json nu poate fi decodificat sau daca datele pentru codificare sunt mai adânci decât limita de imbricare.

Exemple

Example #1 Exemple 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));

?>

Exemplul de mai sus va afi?a:

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)
}

Example #2 Accesarea proprieta?ilor nevalide ale unui obiect

Accesarea elementelor dintr-un obiect, care con?in caractere nepermise conform conven?iei de denumiri PHP (de ex. liniu?a), poate fi realizata prin încapsularea denumirii elementului între paranteze figurate ?i apostrofuri.

<?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>

Example #3 Gre?eli tipice la utilizarea json_decode()

<?php

// urmatoarele ?iruri sunt valide în JavaScript, dar nu sunt valide în JSON

// denumirea ?i valoarea trebuie sa fie cuprinse între ghilimele duble
// ghilimelele singulare nu sunt valide
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// denumirea trebuie sa fie cuprinsa între ghilimele duble
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null

// virgule în plus la sfâr?it nu sunt permise
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null

?>

Example #4 Erori la parametrul depth

<?php
// Codificarea datelor.
$json = json_encode(
    array(
        1 => array(
            'English' => array(
                'One',
                'January'
            ),
            'French' => array(
                'Une',
                'Janvier'
            )
        )
    )
);

// Definirea erorilor.
$constants = get_defined_constants(true);
$json_errors = array();
foreach ($constants["json"] as $name => $value) {
    if (!strncmp($name, "JSON_ERROR_", 11)) {
        $json_errors[$value] = $name;
    }
}

// Arata erorile pentru diferite adâncimi.
foreach (range(4, 3, -1) as $depth) {
    var_dump(json_decode($json, true, $depth));
    echo 'Last error: ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
}
?>

Exemplul de mai sus va afi?a:

array(1) {
  [1]=>
  array(2) {
    ["English"]=>
    array(2) {
      [0]=>
      string(3) "One"
      [1]=>
      string(7) "January"
    }
    ["French"]=>
    array(2) {
      [0]=>
      string(3) "Une"
      [1]=>
      string(7) "Janvier"
    }
  }
}
Last error: JSON_ERROR_NONE

NULL
Last error: JSON_ERROR_DEPTH

Example #5 json_decode() cu numere întregi mari

<?php
$json = '{"number": 12345678901234567890}';

var_dump(json_decode($json));
var_dump(json_decode($json, false, 512, JSON_BIGINT_AS_STRING));

?>

Exemplul de mai sus va afi?a:

object(stdClass)#1 (1) {
  ["number"]=>
  float(1.2345678901235E+19)
}
object(stdClass)#1 (1) {
  ["number"]=>
  string(20) "12345678901234567890"
}

Note

Nota:

Specifica?ia JSON nu este JavaScript, ci un subset al JavaScript.

Nota:

În cazul decodificarii cu e?ec func?ia json_last_error() poate fi utilizata pentru a determina natura exacta a erorii.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Variantele cuvintelor-cheie true, false ?i null care nu sunt scrise în întregime cu litere minuscule nu mai sunt acceptate ca date de intrare valide ?i vor genera avertismente.
5.4.0 | A fost adaugat parametrul options.
5.3.0 | A fost adaugat parametrul op?ional depth. Limita de imbricare implicita a fost marita de la 128 la 512.
5.2.3 | Limita de imbricare a fost marita de la 20 la 128.
5.2.1 | A fost adaugata sus?inerea decodificarii JSON a tipurilor de baza.

A se vedea ?i

  • json_encode() - Întoarce o reprezentare JSON pentru valoarea data
  • json_last_error() - Întoarce ultima eroare ce a survenit

Func?ii JSON
json_encode
Func?ii JSON


Întoarce o reprezentare JSON pentru valoarea data

json_decode
json_last_error_msg
Func?ii JSON
PHP Manual

json_encode

(PHP 5 >= 5.2.0, PECL json >= 1.2.0, PHP 7)

json_encode — Întoarce o reprezentare JSON pentru valoarea data

Descrierea

string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )

Întoarce un ?ir care con?ine o reprezentare JSON pentru valoarea (value) data.

Parametri

value

Valoarea (value) care trebuie reprezentata JSON. Poate fi de orice tip cu excep?ia resource.

Toate ?irurile cu date trebuie sa fie codificate în UTF-8.

Nota:

PHP implementeaza un superset al JSON, dupa cum este specificat în documentul » RFC 4627 original; de asemenea el va codifica ?i va decodifica tipuri scalare ?i NULL. RFC 4627 sus?ine aceste valori doar atunci când ele sunt încorporate într-un tablou sau obiect.

Cu toate ca acest superset este consecvent cu defini?ia extinsa de "text JSON" din noul » RFC 7159 (care are ca scop sa înlocuiasca RFC 4627) ?i ECMA-404, aceasta poate cauza probleme de interoperabilitate cu interpretorii JSON mai vechi care adera strict la RFC 4627 la codificarea unei singure valori scalare.

options

O masca de bi?i, ce consta din JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR. Comportamentul acestor constante este descris în pagina cu constante JSON.

depth

Stabile?te adâncimea maxima. Trebuie sa fie mai mare decât zero.

Valorile întoarse

Întoarce un ?ir (string) reprezentat JSON în caz de succes, sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.6.6 | option JSON_PRESERVE_ZERO_FRACTION a fost adaugata.
5.5.0 | A fost adaugat parametrul depth.
5.4.0 | Au fost adaugate constantele JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE pentru parametrul options.
5.3.3 | A fost adaugata constanta JSON_NUMERIC_CHECK pentru parametrul option.
5.3.0 | A fost adaugat parametrul options.

Exemple

Example #1 Un exemplu json_encode()

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

Exemplul de mai sus va afi?a:

{"a":1,"b":2,"c":3,"d":4,"e":5}

Example #2 Un exemplu json_encode() ce demonstreaza utilizarea op?iunilor

<?php
$a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9");

echo "Normal: ",  json_encode($a), "\n";
echo "Tags: ",    json_encode($a, JSON_HEX_TAG), "\n";
echo "Apos: ",    json_encode($a, JSON_HEX_APOS), "\n";
echo "Quot: ",    json_encode($a, JSON_HEX_QUOT), "\n";
echo "Amp: ",     json_encode($a, JSON_HEX_AMP), "\n";
echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n";
echo "All: ",     json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "\n\n";

$b = array();

echo "Empty array output as array: ", json_encode($b), "\n";
echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";

$c = array(array(1,2,3));

echo "Non-associative array output as array: ", json_encode($c), "\n";
echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";

$d = array('foo' => 'bar', 'baz' => 'long');

echo "Associative array always output as object: ", json_encode($d), "\n";
echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n";
?>

Exemplul de mai sus va afi?a:

Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"]
Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"]
Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]
Unicode: ["<foo>","'bar'","\"baz\"","&blong&","é"]
All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"]

Empty array output as array: []
Empty array output as object: {}

Non-associative array output as array: [[1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}

Associative array always output as object: {"foo":"bar","baz":"long"}
Associative array always output as object: {"foo":"bar","baz":"long"}

Example #3 Exemplu a op?iunii JSON_NUMERIC_CHECK

<?php
echo "Strings representing numbers automatically turned into numbers".PHP_EOL;
$numbers = array('+123123', '-123123', '1.2e3', '0.00001');
var_dump(
 $numbers,
 json_encode($numbers, JSON_NUMERIC_CHECK)
);
echo "Strings containing improperly formatted numbers".PHP_EOL;
$strings = array('+a33123456789', 'a123');
var_dump(
 $strings,
 json_encode($strings, JSON_NUMERIC_CHECK)
);
?>

Exemplul de mai sus va afi?a:

Strings representing numbers automatically turned into numbers
array(4) {
  [0]=>
  string(7) "+123123"
  [1]=>
  string(7) "-123123"
  [2]=>
  string(5) "1.2e3"
  [3]=>
  string(7) "0.00001"
}
string(28) "[123123,-123123,1200,1.0e-5]"
Strings containing improperly formatted numbers
array(2) {
  [0]=>
  string(13) "+a33123456789"
  [1]=>
  string(4) "a123"
}
string(24) "["+a33123456789","a123"]"

Example #4 Un exemplu cu tablou secven?ial versus un tablou non-secven?ial

<?php
echo "Sequential array".PHP_EOL;
$sequential = array("foo", "bar", "baz", "blong");
var_dump(
 $sequential,
 json_encode($sequential)
);

echo PHP_EOL."Non-sequential array".PHP_EOL;
$nonsequential = array(1=>"foo", 2=>"bar", 3=>"baz", 4=>"blong");
var_dump(
 $nonsequential,
 json_encode($nonsequential)
);

echo PHP_EOL."Sequential array with one key unset".PHP_EOL;
unset($sequential[1]);
var_dump(
 $sequential,
 json_encode($sequential)
);
?>

Exemplul de mai sus va afi?a:

Sequential array
array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "blong"
}
string(27) "["foo","bar","baz","blong"]"

Non-sequential array
array(4) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(3) "baz"
  [4]=>
  string(5) "blong"
}
string(43) "{"1":"foo","2":"bar","3":"baz","4":"blong"}"

Sequential array with one key unset
array(3) {
  [0]=>
  string(3) "foo"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "blong"
}
string(33) "{"0":"foo","2":"baz","3":"blong"}"

Example #5 Exemplu cu op?iunea JSON_PRESERVE_ZERO_FRACTION

<?php
var_dump(json_encode(12.0, JSON_PRESERVE_ZERO_FRACTION));
var_dump(json_encode(12.0));
?>

Exemplul de mai sus va afi?a:

string(4) "12.0"
string(2) "12"

Note

Nota:

În caz daca e?ueaza codificarea, json_last_error() poate fi utilizat pentru a determina natura exacta a erorii.

Nota:

La codificarea tablourilor, daca cheile nu sunt consecutivita?i numerice începând cu 0, atunci toate cheile vor fi codificate ca ?iruri de caractere, ?i vor fi specificate explicit pentru fiecare pereche cheie-valoare.

Nota:

Ca ?i codificatorul JSON de referin?a, json_encode() va genera JSON care este o valoare simpla (adica nu este obiect sau tablou) daca îi este furnizata o valoare de tip string, integer, float sau boolean pentru parametrul value. În timp ce majoritatea decodificatorilor JSON vor accepta aceste valori ca fiind JSON valid, altele pot sa nu-l accepte, deoarece specifica?ia este ambigua în aceasta privin?a.

În concluzie, întotdeauna verifica?i ca decodificatorul JSON sa poata prelucra ceea ce se ob?ine cu json_encode().

A se vedea ?i

  • JsonSerializable
  • json_decode() - Converte?te într-o variabila un ?ir reprezentat JSON
  • json_last_error() - Întoarce ultima eroare ce a survenit
  • serialize() - Genereaza o reprezentare ce poate fi stocata a unei valori

json_decode
json_last_error_msg
Func?ii JSON


Întoarce ?irul de eroare a ultimului apel json_encode() sau json_decode()

json_encode
json_last_error
Func?ii JSON
PHP Manual

json_last_error_msg

(PHP 5 >= 5.5.0, PHP 7)

json_last_error_msg — Întoarce ?irul de eroare a ultimului apel json_encode() sau json_decode()

Descrierea

string json_last_error_msg ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce mesajul de eroare în caz de succes, "No Error" daca nu s-a produs vre-o eroare, sau FALSE în cazul e?ecului.

A se vedea ?i

  • json_last_error() - Întoarce ultima eroare ce a survenit

json_encode
json_last_error
Func?ii JSON


Întoarce ultima eroare ce a survenit

json_last_error_msg
Judy
Func?ii JSON
PHP Manual

json_last_error

(PHP 5 >= 5.3.0, PHP 7)

json_last_error — Întoarce ultima eroare ce a survenit

Descrierea

int json_last_error ( void )

Întoarce ultima eroare (daca este prezenta) care a survenit la ultima codificare / decodificare JSON.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce un întreg. Valoarea poate fi una din urmatoarele constante:

Codurile de eroare JSON
Constanta | Semnifica?ie | Disponibilitate
JSON_ERROR_NONE | Nu a survenit vre-o eroare |
JSON_ERROR_DEPTH | A fost depa?ita limita maxima de imbricare |
JSON_ERROR_STATE_MISMATCH | ?ir JSON invalid sau deteriorat |
JSON_ERROR_CTRL_CHAR | Eroare a caracterului de control, posibil este codificat incorect |
JSON_ERROR_SYNTAX | Eroare de sintaxa |
JSON_ERROR_UTF8 | Caractere UTF-8 deformate, posibil codificate incorect | PHP 5.3.3
JSON_ERROR_RECURSION | A fost gasita una sau mai multe referin?e recursive în valoarea ce trebuie codificata | PHP 5.5.0
JSON_ERROR_INF_OR_NAN | A fost gasita una sau mai multe valori NAN sau INF în valoarea ce trebuie codificata | PHP 5.5.0
JSON_ERROR_UNSUPPORTED_TYPE | A fost furnizata o valoare cu un tip ce nu poate fi codificat | PHP 5.5.0

Exemple

Example #1 Exemplu json_last_error()

<?php
// Un ?ir JSON valid
$json[] = '{"Organization": "PHP Documentation Team"}';

// Un ?ir JSON invalid ce va cauza o eroare de sintaxa.
// În cazul dat am folosit ' în loc de "
$json[] = "{'Organization': 'PHP Documentation Team'}";

foreach ($json as $string) {
    echo 'Decoding: ' . $string;
    json_decode($string);

    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            echo ' - No errors';
        break;
        case JSON_ERROR_DEPTH:
            echo ' - Maximum stack depth exceeded';
        break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Underflow or the modes mismatch';
        break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Unexpected control character found';
        break;
        case JSON_ERROR_SYNTAX:
            echo ' - Syntax error, malformed JSON';
        break;
        case JSON_ERROR_UTF8:
            echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
        break;
        default:
            echo ' - Unknown error';
        break;
    }

    echo PHP_EOL;
}
?>

Exemplul de mai sus va afi?a:

Decoding: {"Organization": "PHP Documentation Team"} - No errors
Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON

Example #2 Exemplu json_last_error() cu json_encode()

<?php
// O secven?a UTF8 invalida
$text = "\xB1\x31";

$json  = json_encode($text);
$error = json_last_error();

var_dump($json, $error === JSON_ERROR_UTF8);
?>

Exemplul de mai sus va afi?a:

string(4) "null"
bool(true)

A se vedea ?i

  • json_last_error_msg() - Întoarce ?irul de eroare a ultimului apel json_encode() sau json_decode()
  • json_decode() - Converte?te într-o variabila un ?ir reprezentat JSON
  • json_encode() - Întoarce o reprezentare JSON pentru valoarea data

json_last_error_msg
Judy
Func?ii JSON


Judy Arrays

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • 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
  • Func?ii Judy
    • judy_type — Return the type of a Judy array
    • judy_version — Return or print the current PHP Judy version
json_last_error
Introducere
Alte extensii de baza


Introducere

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
Instalarea / configurarea
Judy


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Judy


Necesita?i

This extension require the » Judy C library.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/judy

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
Judy
Instalarea / configurarea


The Judy class

(PECL judy >= 0.1.1)

Introducere

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

Example #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);
?>

Sinopsisul clasei

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 ;
/* Metode */
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 )
}

Constante predefinite

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.

Cuprins

  • 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
Tipurile resurselor
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

Descrierea

public int Judy::byCount ( int $nth_index )

Locate the Nth index present in the Judy array.

Parametri

nth_index

Nth index to return. If nth_index equal 1, then it will return the first index in the array.

Valorile întoarse

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

Descrierea

public Judy::__construct ( int $judy_type )

Construct a new Judy object. A Judy object can be accessed like a PHP Array.

Parametri

judy_type

The Judy type to be used.

Valorile întoarse

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

Descrierea

public int Judy::count ([ int $index_start = 0 [, int $index_end = -1 ]] )

Count the number of elements in the Judy array.

Parametri

index_start

Start counting from the given index. Default is first index.

index_end

Stop counting when reaching this index. Default is last index.

Valorile întoarse

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

Descrierea

public void Judy::__destruct ( void )

Destruct a Judy object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public mixed Judy::first ([ mixed $index ] )

Search (inclusive) for the first index present that is equal to or greater than the passed Index.

Parametri

index

The index can be an integer or a string corresponding to the index where to start the search.

Valorile întoarse

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

Descrierea

public int Judy::firstEmpty ([ mixed $index = 0 ] )

Search (inclusive) for the first absent index that is equal to or greater than the passed Index.

Parametri

index

The index can be an integer or a string corresponding to the index where to start the search.

Valorile întoarse

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

Descrierea

public int Judy::free ( void )

Free the entire Judy array.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int Judy::getType ( void )

Return an integer corresponding to the Judy type of the current object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public void Judy::last ([ string $index ] )

Search (inclusive) for the last index present that is equal to or less than the passed Index.

Parametri

index

The index can be an integer or a string corresponding to the index where to start the search.

Valorile întoarse

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

Descrierea

public int Judy::lastEmpty ([ int $index = -1 ] )

Search (inclusive) for the last absent index that is equal to or less than the passed Index.

Parametri

index

The index can be an integer or a string corresponding to the index where to start the search.

Valorile întoarse

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

Descrierea

public int Judy::memoryUsage ( void )

Return the memory used by the Judy array.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public mixed Judy::next ( mixed $index )

Search (exclusive) for the next index present that is greater than the passed Index.

Parametri

index

The index can be an integer or a string corresponding to the index where to start the search.

Valorile întoarse

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

Descrierea

public int Judy::nextEmpty ( int $index )

Search (exclusive) for the next absent index that is greater than the passed Index.

Parametri

index

The index can be an integer or a string corresponding to the index where to start the search.

Valorile întoarse

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

Descrierea

public bool Judy::offsetExists ( mixed $offset )

Whether or not an offset exists.

Parametri

offset

An offset to check for.

Valorile întoarse

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

Descrierea

public mixed Judy::offsetGet ( mixed $offset )

Returns the value at specified offset.

Parametri

offset

The offset to retrieve.

Valorile întoarse

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

Descrierea

public bool Judy::offsetSet ( mixed $offset , mixed $value )

Assigns a value to the specified offset.

Parametri

offset

The offset to assign the value to.

value

The value to set.

Valorile întoarse

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

Descrierea

public bool Judy::offsetUnset ( mixed $offset )

Unsets an offset.

Parametri

offset

The offset to unset.

Valorile întoarse

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

Descrierea

public mixed Judy::prev ( mixed $index )

Search (exclusive) for the previous index present that is less than the passed Index.

Parametri

index

The index can be an integer or a string corresponding to the index where to start the search.

Valorile întoarse

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

Descrierea

public int Judy::prevEmpty ( mixed $index )

Search (exclusive) for the previous index absent that is less than the passed Index.

Parametri

index

The index can be an integer or a string corresponding to the index where to start the search.

Valorile întoarse

Return the corresponding index in the array.

Judy::prev
Judy::size
Judy


Return the size of the current Judy array

Judy::prevEmpty
Func?ii Judy
Judy
PHP Manual

Judy::size

(PECL judy >= 0.1.1)

Judy::size — Return the size of the current Judy array

Descrierea

public void Judy::size ( void )

This method is an alias of Judy::count.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Return an integer.

Judy::prevEmpty
Func?ii Judy
Judy


Func?ii Judy

Cuprins

  • 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

Func?ii Judy
judy_version
Func?ii Judy
PHP Manual

judy_type

(PECL judy >= 0.1.1)

judy_type — Return the type of a Judy array

Descrierea

int judy_type ( Judy $array )

judy_type() return an integer corresponding to the Judy type of the specified Judy array.

Parametri

array

The Judy Array to test.

Valorile întoarse

Return an integer corresponding to a Judy type.

Func?ii Judy
judy_version
Func?ii Judy


Return or print the current PHP Judy version

judy_type
Lua
Func?ii Judy
PHP Manual

judy_version

(PECL judy >= 0.1.1)

judy_version — Return or print the current PHP Judy version

Descrierea

string judy_version ( void )

Return a string of the PHP Judy version. If the return value is not used, the string will be printed.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Return a string of the PHP Judy version.

judy_type
Lua
Func?ii Judy


Lua

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • 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
Introducere
Alte extensii de baza


Introducere

"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
Instalarea / configurarea
Lua


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Lua


Necesita?i

To use this extension, you will need Lua installed, available on the » Lua homepage

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/lua.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
Lua
Instalarea / configurarea


The Lua class

(PECL lua >=0.9.0)

Introducere

Sinopsisul clasei

Lua {
/* Constants */
const string LUA_VERSION = Lua 5.1.4 ;
/* Metode */
public mixed assign ( string $name , string $value )
public mixed call ( callable $lua_func [, array $args [, int $use_self = 0 ]] )
public mixed __call ( callable $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 , callable $function )
}

Constante predefinite

Lua::LUA_VERSION

Cuprins

  • 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
Tipurile resurselor
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

Descrierea

public mixed Lua::assign ( string $name , string $value )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

value

Valorile întoarse

Returns $this or NULL on failure.

Exemple

Example #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
);
?>

Exemplul de mai sus va afi?a:

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

Descrierea

public mixed Lua::call ( callable $lua_func [, array $args [, int $use_self = 0 ]] )
public mixed Lua::__call ( callable $lua_func [, array $args [, int $use_self = 0 ]] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

lua_func

Function name in lua

args

Arguments passed to the Lua function

use_self

Whether to use self

Valorile întoarse

Returns result of the called function, NULL for wrong arguments or FALSE on other failure.

Exemple

Example #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), "-")));
?>

Exemplul de mai sus va afi?a:

Lua,geiliable
Lua,geiliable
string(5) "1-2-3"

A se vedea ?i

  • __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

Descrierea

public Lua::__construct ( string $lua_script_file = NULL )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

lua_script_file

Valorile întoarse

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

Descrierea

public mixed Lua::eval ( string $statements )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

statements

Valorile întoarse

Returns result of evaled code, NULL for wrong arguments or FALSE on other failure.

Exemple

Example #1 Lua::eval()example

<?php
$lua = new Lua();
$lua->eval(<<<CODE
    print(2);
CODE
);
?>

Exemplul de mai sus va afi?a:

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

Descrierea

public string Lua::getVersion ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public mixed Lua::include ( string $file )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

file

Valorile întoarse

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 Git)

Lua::registerCallback — Register a PHP function to Lua

Descrierea

public mixed Lua::registerCallback ( string $name , callable $function )

Register a PHP function to Lua as a function named "$name"

Parametri

name

function

A valid PHP function callback

Valorile întoarse

Returns $this, NULL for wrong arguments or FALSE on other failure.

Exemple

Example #1 Lua::registerCallback()example

<?php
$lua = new Lua();
$lua->registerCallback("echo", "var_dump");
$lua->eval(<<<CODE
    echo({1, 2, 3});
CODE
);
?>

Exemplul de mai sus va afi?a:

array(3) {
  [1]=>
  float(1)
  [2]=>
  float(2)
  [3]=>
  float(3)
}
Lua::include
LuaClosure
Lua


The LuaClosure class

(PECL lua >=0.9.0)

Introducere

LuaClosure is a wrapper class for LUA_TFUNCTION which could be return from calling to Lua function.

Sinopsisul clasei

LuaClosure {
/* Metode */
public void __invoke ( mixed $arg [, mixed $... ] )
}

Cuprins

  • LuaClosure::__invoke — invoke luaclosure
Lua::registerCallback
LuaClosure::__invoke
Lua


invoke luaclosure

LuaClosure
Diverse
LuaClosure
PHP Manual

LuaClosure::__invoke

(PECL lua >=0.9.0)

LuaClosure::__invoke — invoke luaclosure

Descrierea

public void LuaClosure::__invoke ( mixed $arg [, mixed $... ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

arg

...

Valorile întoarse

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

hello worldhello world
LuaClosure
Diverse
LuaClosure


Func?ii diverse

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii diverse
    • connection_aborted — Check whether client disconnected
    • connection_status — Returns connection status bitfield
    • constant — Returns the value of a constant
    • define — Defines a named constant
    • defined — Checks whether a given named constant exists
    • die — Echivalenta cu 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 — Pseudonim pentru 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
  • Jurnalul modificarilor
LuaClosure::__invoke
Introducere
Alte extensii de baza


Introducere

Aceste func?ii au fost plasate aici deoarece nu se potrivesc cu nici o alta categorie.

Diverse
Instalarea / configurarea
Diverse


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Diverse


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Misc. Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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 |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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().

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

CONNECTION_ABORTED (integer)
CONNECTION_NORMAL (integer)
CONNECTION_TIMEOUT (integer)
__COMPILER_HALT_OFFSET__ (integer)
Added in PHP 5.1.
Tipurile resurselor
Func?ii diverse
Diverse


Func?ii diverse

Cuprins

  • connection_aborted — Check whether client disconnected
  • connection_status — Returns connection status bitfield
  • constant — Returns the value of a constant
  • define — Defines a named constant
  • defined — Checks whether a given named constant exists
  • die — Echivalenta cu 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 — Pseudonim pentru 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
Constante predefinite
connection_aborted
Diverse


Check whether client disconnected

Func?ii diverse
connection_status
Func?ii diverse
PHP Manual

connection_aborted

(PHP 4, PHP 5, PHP 7)

connection_aborted — Check whether client disconnected

Descrierea

int connection_aborted ( void )

Checks whether the client disconnected.

Valorile întoarse

Returns 1 if client disconnected, 0 otherwise.

A se vedea ?i

  • 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.

Func?ii diverse
connection_status
Func?ii diverse


Returns connection status bitfield

connection_aborted
constant
Func?ii diverse
PHP Manual

connection_status

(PHP 4, PHP 5, PHP 7)

connection_status — Returns connection status bitfield

Descrierea

int connection_status ( void )

Gets the connection status bitfield.

Valorile întoarse

Returns the connection status bitfield, which can be used against the CONNECTION_XXX constants to determine the connection status.

A se vedea ?i

  • 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
constant
Func?ii diverse


Returns the value of a constant

connection_status
define
Func?ii diverse
PHP Manual

constant

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

constant — Returns the value of a constant

Descrierea

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.

Parametri

name

The constant name.

Valorile întoarse

Returns the value of the constant, or NULL if the constant is not defined.

Erori/Excep?ii

An E_WARNING level error is generated if the constant is not defined.

Exemple

Example #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!"

?>

A se vedea ?i

  • define() - Defines a named constant
  • defined() - Checks whether a given named constant exists
  • The section on Constants

connection_status
define
Func?ii diverse


Defines a named constant

constant
defined
Func?ii diverse
PHP Manual

define

(PHP 4, PHP 5, PHP 7)

define — Defines a named constant

Descrierea

bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )

Defines a named constant at runtime.

Parametri

name

The name of the constant.

value

The value of the constant. In PHP 5, value must be a scalar value (integer, float, string, boolean, or NULL). In PHP 7, array values are also accepted.

Avertizare

While it is possible to define resource constants, 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.

Nota:

Case-insensitive constants are stored as lower-case.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | array values are allowed.

Exemple

Example #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."

// Works as of PHP 7
define('ANIMALS', array(
    'dog',
    'cat',
    'bird'
));
echo ANIMALS[1]; // outputs "cat"

?>

A se vedea ?i

  • defined() - Checks whether a given named constant exists
  • constant() - Returns the value of a constant
  • The section on Constants

constant
defined
Func?ii diverse


Checks whether a given named constant exists

define
die
Func?ii diverse
PHP Manual

defined

(PHP 4, PHP 5, PHP 7)

defined — Checks whether a given named constant exists

Descrierea

bool defined ( string $name )

Checks whether the given constant exists and is defined.

Nota:

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().

Parametri

name

The constant name.

Valorile întoarse

Returns TRUE if the named constant given by name has been defined, FALSE otherwise.

Exemple

Example #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;
}
?>

A se vedea ?i

  • 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
Func?ii diverse


Echivalenta cu exit

defined
eval
Func?ii diverse
PHP Manual

die

(PHP 4, PHP 5, PHP 7)

die — Echivalenta cu exit

Descrierea

Aceasta construc?ie a limbajului este echivalenta cu exit().

defined
eval
Func?ii diverse


Evaluate a string as PHP code

die
exit
Func?ii diverse
PHP Manual

eval

(PHP 4, PHP 5, PHP 7)

eval — Evaluate a string as PHP code

Descrierea

mixed eval ( string $code )

Evaluates the given code as PHP.

Precautie

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.

Parametri

code

Valid PHP code to be evaluated.

The code must not be wrapped in opening and closing PHP tags, i.e. 'echo "Hi!";' must be passed instead of '<?php echo "Hi!"; ?>'. It is still possible to leave and re-enter PHP mode though using the appropriate PHP tags, e.g. 'echo "In PHP mode!"; ?>In HTML mode!<?php 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.

Valorile întoarse

eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. As of PHP 7, if there is a parse error in the evaluated code, eval() throws a ParseError exception. Before PHP 7, in this case eval() returned FALSE and execution of the following code continued normally. It is not possible to catch a parse error in eval() using set_error_handler().

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

This is a $string with my $name in it.
This is a cup with my coffee in it.

Note

Nota: Deoarece aceasta este o construc?ie a limbajului ?i nu o func?ie, ea nu poate fi apelata utilizând func?ii de operare cu variabile .

Sfat

La fel ca ?i orice program/script ce afi?eaza rezultatele direct în browser, func?iile de control al ie?irilor pot fi utilizate pentru a capta ie?irea acestei func?ii ?i de a o salva într-un string (spre exemplu).

Nota:

In case of a fatal error in the evaluated code, the whole script exits.

A se vedea ?i

  • call_user_func() - Call the callback given by the first parameter

die
exit
Func?ii diverse


Output a message and terminate the current script

eval
get_browser
Func?ii diverse
PHP Manual

exit

(PHP 4, PHP 5, PHP 7)

exit — Output a message and terminate the current script

Descrierea

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.

exit is a language construct and it can be called without parentheses if no status is passed.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 exit example

<?php

$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
    or exit("unable to open file ($filename)");

?>

Example #2 exit status example

<?php

//exit program normally
exit;
exit();
exit(0);

//exit with an error code
exit(1);
exit(0376); //octal

?>

Example #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.';
?>

Exemplul de mai sus va afi?a:

 Shutdown: shutdown()
 Destruct: Foo::__destruct()

Note

Nota: Deoarece aceasta este o construc?ie a limbajului ?i nu o func?ie, ea nu poate fi apelata utilizând func?ii de operare cu variabile .

Nota:

This language construct is equivalent to die().

A se vedea ?i

  • register_shutdown_function() - Register a function for execution on shutdown

eval
get_browser
Func?ii diverse


Tells what the user's browser is capable of

exit
__halt_compiler
Func?ii diverse
PHP Manual

get_browser

(PHP 4, PHP 5, PHP 7)

get_browser — Tells what the user's browser is capable of

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #1 Listing all information about the users browser

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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] =>
)

Note

Nota:

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
Func?ii diverse


Halts the compiler execution

get_browser
highlight_file
Func?ii diverse
PHP Manual

__halt_compiler

(PHP 5 >= 5.1.0, PHP 7)

__halt_compiler — Halts the compiler execution

Descrierea

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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.)

Note

Nota:

__halt_compiler() can only be used from the outermost scope.

get_browser
highlight_file
Func?ii diverse


Syntax highlighting of a file

__halt_compiler
highlight_string
Func?ii diverse
PHP Manual

highlight_file

(PHP 4, PHP 5, PHP 7)

highlight_file — Syntax highlighting of a file

Descrierea

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

Parametri

filename

Path to the PHP file to be highlighted.

return

Set this parameter to TRUE to make this function return the highlighted code.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
4.2.1 | This function is now also affected by safe_mode and open_basedir.

Note

Precautie

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.

Nota:

Când este utilizat parametrul return, aceasta func?ie efectueaza buferizarea interna a ie?irilor, de aceea nu poate fi utilizata în interiorul func?iei de apel invers (callback) ob_start().

A se vedea ?i

  • highlight_string() - Syntax highlighting of a string
  • Highlighting INI directives

__halt_compiler
highlight_string
Func?ii diverse


Syntax highlighting of a string

highlight_file
ignore_user_abort
Func?ii diverse
PHP Manual

highlight_string

(PHP 4, PHP 5, PHP 7)

highlight_string — Syntax highlighting of a string

Descrierea

mixed highlight_string ( string $str [, bool $return = false ] )

Outputs or returns html markup for a syntax highlighted version of the given PHP code using the colors defined in the built-in syntax highlighter for PHP.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #1 highlight_string() example

<?php
highlight_string('<?php phpinfo(); ?>');
?>

Exemplul de mai sus va afi?a:

<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>

Note

Nota:

Când este utilizat parametrul return, aceasta func?ie efectueaza buferizarea interna a ie?irilor, de aceea nu poate fi utilizata în interiorul func?iei de apel invers (callback) ob_start().

The HTML markup generated is subject to change.

A se vedea ?i

  • highlight_file() - Syntax highlighting of a file
  • Highlighting INI directives

highlight_file
ignore_user_abort
Func?ii diverse


Set whether a client disconnect should abort script execution

highlight_string
pack
Func?ii diverse
PHP Manual

ignore_user_abort

(PHP 4, PHP 5, PHP 7)

ignore_user_abort — Set whether a client disconnect should abort script execution

Descrierea

int ignore_user_abort ([ bool $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

Parametri

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.

Valorile întoarse

Returns the previous setting, as an integer.

Exemple

Example #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.
?>

Note

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().

A se vedea ?i

  • 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
Func?ii diverse


Pack data into binary string

ignore_user_abort
php_check_syntax
Func?ii diverse
PHP Manual

pack

(PHP 4, PHP 5, PHP 7)

pack — Pack data into binary string

Descrierea

string pack ( string $format [, mixed $args [, mixed $... ]] )

Pack given arguments into a 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.

Parametri

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)
q | signed long long (always 64 bit, machine byte order)
Q | unsigned long long (always 64 bit, machine byte order)
J | unsigned long long (always 64 bit, big endian byte order)
P | unsigned long long (always 64 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
Z | NUL-padded string (new in PHP 5.5)
@ NUL-fill to absolute position

args

Valorile întoarse

Returns a binary string containing data.

Istoricul schimbarilor

Versiune | Descriere
5.6.3 | The "q", "Q", "J" and "P" codes were added to enable working with 64-bit numbers.
5.5.0 | The "Z" code was added with equivalent functionality to "a" for Perl compatibility.

Exemple

Example #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.

Note

Precautie

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.

A se vedea ?i

  • unpack() - Unpack data from binary string

ignore_user_abort
php_check_syntax
Func?ii diverse


Check the PHP syntax of (and execute) the specified file

pack
php_strip_whitespace
Func?ii diverse
PHP Manual

php_check_syntax

(PHP 5 <= 5.0.4)

php_check_syntax — Check the PHP syntax of (and execute) the specified file

Descrierea

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.

Nota:

For technical reasons, this function is deprecated and removed from PHP. Instead, use php -l somefile.php from the commandline.

Parametri

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.

Valorile întoarse

Returns TRUE if the lint check passed, and FALSE if the link check failed or if filename cannot be opened.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

php -l somefile.php

Exemplul de mai sus va afi?a ceva similar cu:

PHP Parse error: unexpected T_STRING in /tmp/somefile.php on line 81

A se vedea ?i

  • include - include
  • is_readable() - Tells whether a file exists and is readable

pack
php_strip_whitespace
Func?ii diverse


Return source with stripped comments and whitespace

php_check_syntax
show_source
Func?ii diverse
PHP Manual

php_strip_whitespace

(PHP 5, PHP 7)

php_strip_whitespace — Return source with stripped comments and whitespace

Descrierea

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.

Parametri

filename

Path to the PHP file.

Valorile întoarse

The stripped source code will be returned on success, or an empty string on failure.

Nota:

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.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

<?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
Func?ii diverse


Pseudonim pentru highlight_file

php_strip_whitespace
sleep
Func?ii diverse
PHP Manual

show_source

(PHP 4, PHP 5, PHP 7)

show_source — Pseudonim pentru highlight_file()

Descrierea

Aceasta func?ie este pseudonim pentru: highlight_file().

php_strip_whitespace
sleep
Func?ii diverse


Delay execution

show_source
sys_getloadavg
Func?ii diverse
PHP Manual

sleep

(PHP 4, PHP 5, PHP 7)

sleep — Delay execution

Descrierea

int sleep ( int $seconds )

Delays the program execution for the given number of seconds.

Parametri

seconds

Halt time in seconds.

Valorile întoarse

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.

Erori/Excep?ii

If the specified number of seconds is negative, this function will generate a E_WARNING.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #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

A se vedea ?i

  • 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
Func?ii diverse


Gets system load average

sleep
time_nanosleep
Func?ii diverse
PHP Manual

sys_getloadavg

(PHP 5 >= 5.1.3, PHP 7)

sys_getloadavg — Gets system load average

Descrierea

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.

Valorile întoarse

Returns an array with three samples (last 1, 5 and 15 minutes).

Exemple

Example #1 A sys_getloadavg() example

<?php
$load = sys_getloadavg();
if ($load[0] > 0.80) {
    header('HTTP/1.1 503 Too busy, try again later');
    die('Server too busy. Please try again later.');
}
?>

Note

Nota: Aceasta func?ie nu este implementata pe platformele Windows.

sleep
time_nanosleep
Func?ii diverse


Delay for a number of seconds and nanoseconds

sys_getloadavg
time_sleep_until
Func?ii diverse
PHP Manual

time_nanosleep

(PHP 5, PHP 7)

time_nanosleep — Delay for a number of seconds and nanoseconds

Descrierea

mixed time_nanosleep ( int $seconds , int $nanoseconds )

Delays program execution for the given number of seconds and nanoseconds.

Parametri

seconds

Must be a non-negative integer.

nanoseconds

Must be a non-negative integer less than 1 billion.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on Windows platforms.

Exemple

Example #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.";
}
?>

A se vedea ?i

  • 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
Func?ii diverse


Make the script sleep until the specified time

time_nanosleep
uniqid
Func?ii diverse
PHP Manual

time_sleep_until

(PHP 5 >= 5.1.0, PHP 7)

time_sleep_until — Make the script sleep until the specified time

Descrierea

bool time_sleep_until ( float $timestamp )

Makes the script sleep until the specified timestamp.

Parametri

timestamp

The timestamp when the script should wake.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on Windows platforms.

Erori/Excep?ii

If the specified timestamp is in the past, this function will generate a E_WARNING.

Exemple

Example #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));

?>

Note

Nota: All signals will be delivered after the script wakes up.

A se vedea ?i

  • 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
Func?ii diverse


Generate a unique ID

time_sleep_until
unpack
Func?ii diverse
PHP Manual

uniqid

(PHP 4, PHP 5, PHP 7)

uniqid — Generate a unique ID

Descrierea

string uniqid ([ string $prefix = "" [, bool $more_entropy = false ]] )

Gets a prefixed unique identifier based on the current time in microseconds.

Precautie

Aceasta func?ie nu genereaza valori securizate din punct de vedere criptografic ?i deci nu trebuie utilizata pentru scopuri criptografice. Daca ave?i nevoie de o valoare securizata din punct de vedere criptografic considera?i utilizarea random_int(), random_bytes() sau openssl_random_pseudo_bytes() în schimb.

Avertizare

This function does not guarantee uniqueness of return value. Since most systems adjust system clock by NTP or like, system time is changed constantly. Therefore, it is possible that this function does not return unique ID for the process/thread. Use more_entropy to increase likelihood of uniqueness.

Parametri

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 increases the likelihood that the result will be unique.

Valorile întoarse

Returns timestamp based unique identifier as a string.

Avertizare

This function tries to create unique identifier, but it does not guarantee 100% uniqueness of return value.

Exemple

Example #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));
?>

Note

Nota:

Under Cygwin, the more_entropy must be set to TRUE for this function to work.

time_sleep_until
unpack
Func?ii diverse


Unpack data from binary string

uniqid
usleep
Func?ii diverse
PHP Manual

unpack

(PHP 4, PHP 5, PHP 7)

unpack — Unpack data from binary string

Descrierea

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.

Parametri

format

See pack() for an explanation of the format codes.

data

The packed data.

Valorile întoarse

Returns an associative array containing unpacked elements of binary string.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | Changes were made to bring this function into line with Perl: The "a" code now retains trailing NULL bytes. The "A" code now strips all trailing ASCII whitespace (spaces, tabs, newlines, carriage returns, and NULL bytes). The "Z" code was added for NULL-padded strings, and removes trailing NULL bytes.

Exemple

Example #1 unpack() example

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("cchars/nint", $binarydata);
print_r($array);
?>

Exemplul de mai sus va afi?a:

Array
(
    [chars] => 4
    [int] => 160
)

Example #2 unpack() example with a repeater

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("c2chars/nint", $binarydata);
print_r($array);
?>

Exemplul de mai sus va afi?a:

Array
(
    [chars1] => 4
    [chars2] => 0
    [int] => 40960
)

Note

Precautie

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.

Precautie

If you do not name an element, numeric indices starting from 1 are used. Be aware that if you have more than one unnamed element, some data is overwritten because the numbering restarts from 1 for each element.

Example #3 unpack() example with unnamed keys

<?php
$binarydata = "\x32\x42\x00\xa0";
$array = unpack("c2/n", $binarydata);
var_dump($array);
?>

Exemplul de mai sus va afi?a:

array(2) {
  [1]=>
  int(160)
  [2]=>
  int(66)
}

Note that the first value from the c specifier is overwritten by the first value from the n specifier.

A se vedea ?i

  • pack() - Pack data into binary string

uniqid
usleep
Func?ii diverse


Delay execution in microseconds

unpack
Jurnalul modificarilor
Func?ii diverse
PHP Manual

usleep

(PHP 4, PHP 5, PHP 7)

usleep — Delay execution in microseconds

Descrierea

void usleep ( int $micro_seconds )

Delays program execution for the given number of microseconds.

Parametri

micro_seconds

Halt time in microseconds. A microsecond is one millionth of a second.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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";

?>

Exemplul de mai sus va afi?a:

11:13:28
11:13:30

A se vedea ?i

  • 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
Jurnalul modificarilor
Func?ii diverse


Jurnalul modificarilor

Au fost efectuate urmatoarele modificari ale claselor/func?iilor/metodelor acestei extensii.

Version | Function | Description
7.0.0 | define | array values are allowed.
5.6.3 | pack | The "q", "Q", "J" and "P" codes were added to enable working with 64-bit numbers.
5.5.0 | pack | The "Z" code was added with equivalent functionality to "a" for Perl compatibility.
 | unpack | Changes were made to bring this function into line with Perl: The "a" code now retains trailing NULL bytes. The "A" code now strips all trailing ASCII whitespace (spaces, tabs, newlines, carriage returns, and NULL bytes). The "Z" code was added for NULL-padded strings, and removes trailing NULL bytes.
5.3.4 | sleep | Before PHP 5.3.4, on Windows, sleep always returns NULL when sleep has occurred, regardless of whether the sleep was interrupted or not.
5.3.0 | time_nanosleep | This function is now available on Windows platforms.
 | time_sleep_until | This function is now available on Windows platforms.
5.0.5 | php_check_syntax | This function was removed from PHP.
5.0.3 | php_check_syntax | Calling exit after php_check_syntax resulted in a Segfault.
5.0.1 | php_check_syntax | error_message is passed by reference.
4.2.1 | highlight_file | This function is now also affected by safe_mode and open_basedir.
usleep
Parsekit
Diverse


Parsekit

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Parsekit
    • parsekit_compile_file — Compile a PHP file 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)
Jurnalul modificarilor
Introducere
Alte extensii de baza


Introducere

Aceste func?ii permit analiza în timpul rularii a codurilor de opera?iuni ("opcodes") din script-urile PHP.

Parsekit
Instalarea / configurarea
Parsekit


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Parsekit


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/parsekit.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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

Tipurile resurselor
Func?ii Parsekit
Parsekit


Func?ii Parsekit

Cuprins

  • parsekit_compile_file — Compile a PHP file 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)
Constante predefinite
parsekit_compile_file
Parsekit


Compile a PHP file and return the resulting op array

Func?ii Parsekit
parsekit_compile_string
Func?ii Parsekit
PHP Manual

parsekit_compile_file

(PECL parsekit >= 0.2.0)

parsekit_compile_file — Compile a PHP file and return the resulting op array

Descrierea

array parsekit_compile_file ( string $filename [, array &$errors [, int $options = PARSEKIT_QUIET ]] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

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.

Valorile întoarse

Returns a complex multi-layer array structure as detailed below.

Exemple

Example #1 parsekit_compile_file() example

<?php
var_dump(parsekit_compile_file('hello_world.php', $errors, PARSEKIT_SIMPLE));
?>

Exemplul de mai sus va afi?a:

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
}

A se vedea ?i

  • parsekit_compile_string() - Compile a string of PHP code and return the resulting op array

Func?ii Parsekit
parsekit_compile_string
Func?ii Parsekit


Compile a string of PHP code and return the resulting op array

parsekit_compile_file
parsekit_func_arginfo
Func?ii Parsekit
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

Descrierea

array parsekit_compile_string ( string $phpcode [, array &$errors [, int $options = PARSEKIT_QUIET ]] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

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.

Valorile întoarse

Returns a complex multi-layer array structure as detailed below.

Exemple

Example #1 parsekit_compile_string() example

<?php
  $ops = parsekit_compile_string('
echo "Foo\n";
', $errors, PARSEKIT_QUIET);

  var_dump($ops);
?>

Exemplul de mai sus va afi?a:

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)
    }
  }
}

A se vedea ?i

  • parsekit_compile_file() - Compile a PHP file and return the resulting op array

parsekit_compile_file
parsekit_func_arginfo
Func?ii Parsekit


Return information regarding function argument(s)

parsekit_compile_string
SPL
Func?ii Parsekit
PHP Manual

parsekit_func_arginfo

(PECL parsekit >= 0.3.0)

parsekit_func_arginfo — Return information regarding function argument(s)

Descrierea

array parsekit_func_arginfo ( mixed $function )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

function

A string describing a function, or an array describing a class/method.

Valorile întoarse

Returns an array containing argument information.

Exemple

Example #1 parsekit_func_arginfo() example

<?php
function foo($bar, stdClass $baz, &$bomb, $bling = false) {
}

var_dump(parsekit_func_arginfo('foo'));
?>

Exemplul de mai sus va afi?a:

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
Func?ii Parsekit


Standard PHP Library (SPL)

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Structuri de date
    • 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
  • Iteratori
    • 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
  • Interfe?e
    • Countable — The Countable interface
    • OuterIterator — The OuterIterator interface
    • RecursiveIterator — The RecursiveIterator interface
    • SeekableIterator — The SeekableIterator interface
  • Excep?ii
    • 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
  • Func?ii SPL
    • class_implements — Return the interfaces which are implemented by the given class or interface
    • 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
  • Manipularea fi?ierelor
    • SplFileInfo — The SplFileInfo class
    • SplFileObject — The SplFileObject class
    • SplTempFileObject — The SplTempFileObject class
  • Clase ?i interfe?e diverse
    • ArrayObject — The ArrayObject class
    • SplObserver — The SplObserver interface
    • SplSubject — The SplSubject interface
parsekit_func_arginfo
Introducere
Alte extensii de baza


Introducere

The Standard PHP Library (SPL) is a collection of interfaces and classes that are meant to solve common problems.

No external libraries are needed to build this extension and it is available and compiled by default in PHP 5.0.0.

SPL provides a set of standard datastructure, a set of iterators to traverse over objects, a set of interfaces, a set of standard Exceptions, a number of classes to work with files and it provides a set of functions like spl_autoload_register()

SPL
Instalarea / configurarea
SPL


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SPL


Instalarea

This extension is available and compiled by default in PHP 5.0.0.

Nota:

As of PHP 5.3.0 this extension can no longer be disabled and is therefore always available.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Avertizare

SPL utilizeaza constante de clasa începând cu PHP 5.1. Versiunile anterioare utilizau constante globale de forma RIT_LEAVES_ONLY.

Tipurile resurselor
Structuri de date
SPL


Structuri de date

Cuprins

  • 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 other. 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
Constante predefinite
SplDoublyLinkedList
SPL


The SplDoublyLinkedList class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

The SplDoublyLinkedList class provides the main functionalities of a doubly linked list.

Sinopsisul clasei

SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Metode */
public __construct ( void )
public void add ( mixed $index , mixed $newval )
public mixed bottom ( void )
public int count ( void )
public mixed current ( void )
public int getIteratorMode ( void )
public bool isEmpty ( void )
public mixed key ( void )
public void next ( void )
public bool offsetExists ( mixed $index )
public mixed offsetGet ( mixed $index )
public void offsetSet ( mixed $index , mixed $newval )
public void offsetUnset ( mixed $index )
public mixed pop ( void )
public void prev ( void )
public void push ( mixed $value )
public void rewind ( void )
public string serialize ( void )
public void setIteratorMode ( int $mode )
public mixed shift ( void )
public mixed top ( void )
public void unserialize ( string $serialized )
public void unshift ( mixed $value )
public bool valid ( void )
}

Cuprins

  • SplDoublyLinkedList::add — Add/insert a new value at the specified index
  • 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::serialize — Serializes the storage
  • 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::unserialize — Unserializes the storage
  • SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element
  • SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes
Structuri de date
SplDoublyLinkedList::add
Structuri de date


Add/insert a new value at the specified index

SplDoublyLinkedList
SplDoublyLinkedList::bottom
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::add

(PHP 5 >= 5.5.0, PHP 7)

SplDoublyLinkedList::add — Add/insert a new value at the specified index

Descrierea

public void SplDoublyLinkedList::add ( mixed $index , mixed $newval )

Insert the value newval at the specified index, shuffling the previous value at that index (and all subsequent values) up through the list.

Parametri

index

The index where the new value is to be inserted.

newval

The new value for the index.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.

SplDoublyLinkedList
SplDoublyLinkedList::bottom
SplDoublyLinkedList


Peeks at the node from the beginning of the doubly linked list

SplDoublyLinkedList::add
SplDoublyLinkedList::__construct
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::bottom

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::bottom — Peeks at the node from the beginning of the doubly linked list

Descrierea

public mixed SplDoublyLinkedList::bottom ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The value of the first node.

Erori/Excep?ii

Throws RuntimeException when the data-structure is empty.

SplDoublyLinkedList::add
SplDoublyLinkedList::__construct
SplDoublyLinkedList


Constructs a new doubly linked list

SplDoublyLinkedList::bottom
SplDoublyLinkedList::count
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::__construct

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::__construct — Constructs a new doubly linked list

Descrierea

public SplDoublyLinkedList::__construct ( void )

This constructs a new empty doubly linked list.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 SplDoublyLinkedList::__construct() example

<?php
$dll = new SplDoublyLinkedList();

$dll->push(2);
$dll->push(3);
$dll->unshift(5);

var_dump($dll);
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

SplDoublyLinkedList::count — Counts the number of elements in the doubly linked list.

Descrierea

public int SplDoublyLinkedList::count ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplDoublyLinkedList::current — Return current array entry

Descrierea

public mixed SplDoublyLinkedList::current ( void )

Get the current doubly linked list node.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplDoublyLinkedList::getIteratorMode — Returns the mode of iteration

Descrierea

public int SplDoublyLinkedList::getIteratorMode ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplDoublyLinkedList::isEmpty — Checks whether the doubly linked list is empty.

Descrierea

public bool SplDoublyLinkedList::isEmpty ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplDoublyLinkedList::key — Return current node index

Descrierea

public mixed SplDoublyLinkedList::key ( void )

This function returns the current node index

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplDoublyLinkedList::next — Move to next entry

Descrierea

public void SplDoublyLinkedList::next ( void )

Move the iterator to the next node.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplDoublyLinkedList::offsetExists — Returns whether the requested $index exists

Descrierea

public bool SplDoublyLinkedList::offsetExists ( mixed $index )

Parametri

index

The index being checked.

Valorile întoarse

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, PHP 7)

SplDoublyLinkedList::offsetGet — Returns the value at the specified $index

Descrierea

public mixed SplDoublyLinkedList::offsetGet ( mixed $index )

Parametri

index

The index with the value.

Valorile întoarse

The value at the specified index.

Erori/Excep?ii

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, PHP 7)

SplDoublyLinkedList::offsetSet — Sets the value at the specified $index to $newval

Descrierea

public void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )

Sets the value at the specified index to newval.

Parametri

index

The index being set.

newval

The new value for the index.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

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, PHP 7)

SplDoublyLinkedList::offsetUnset — Unsets the value at the specified $index

Descrierea

public void SplDoublyLinkedList::offsetUnset ( mixed $index )

Unsets the value at the specified index.

Parametri

index

The index being unset.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

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, PHP 7)

SplDoublyLinkedList::pop — Pops a node from the end of the doubly linked list

Descrierea

public mixed SplDoublyLinkedList::pop ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The value of the popped node.

Erori/Excep?ii

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, PHP 7)

SplDoublyLinkedList::prev — Move to previous entry

Descrierea

public void SplDoublyLinkedList::prev ( void )

Move the iterator to the previous node.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplDoublyLinkedList::push — Pushes an element at the end of the doubly linked list

Descrierea

public void SplDoublyLinkedList::push ( mixed $value )

Pushes value at the end of the doubly linked list.

Parametri

value

The value to push.

Valorile întoarse

Nu este întoarsa nici o valoare.

SplDoublyLinkedList::prev
SplDoublyLinkedList::rewind
SplDoublyLinkedList


Rewind iterator back to the start

SplDoublyLinkedList::push
SplDoublyLinkedList::serialize
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::rewind

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::rewind — Rewind iterator back to the start

Descrierea

public void SplDoublyLinkedList::rewind ( void )

This rewinds the iterator to the beginning.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

SplDoublyLinkedList::push
SplDoublyLinkedList::serialize
SplDoublyLinkedList


Serializes the storage

SplDoublyLinkedList::rewind
SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::serialize

(PHP 5 >= 5.4.0, PHP 7)

SplDoublyLinkedList::serialize — Serializes the storage

Descrierea

public string SplDoublyLinkedList::serialize ( void )

Serializes the storage.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The serialized string.

A se vedea ?i

  • SplDoublyLinkedList::unserialize() - Unserializes the storage

SplDoublyLinkedList::rewind
SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList


Sets the mode of iteration

SplDoublyLinkedList::serialize
SplDoublyLinkedList::shift
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::setIteratorMode

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::setIteratorMode — Sets the mode of iteration

Descrierea

public void SplDoublyLinkedList::setIteratorMode ( int $mode )

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

SplDoublyLinkedList::serialize
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, PHP 7)

SplDoublyLinkedList::shift — Shifts a node from the beginning of the doubly linked list

Descrierea

public mixed SplDoublyLinkedList::shift ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The value of the shifted node.

Erori/Excep?ii

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::unserialize
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::top

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::top — Peeks at the node from the end of the doubly linked list

Descrierea

public mixed SplDoublyLinkedList::top ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The value of the last node.

Erori/Excep?ii

Throws RuntimeException when the data-structure is empty.

SplDoublyLinkedList::shift
SplDoublyLinkedList::unserialize
SplDoublyLinkedList


Unserializes the storage

SplDoublyLinkedList::top
SplDoublyLinkedList::unshift
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::unserialize

(PHP 5 >= 5.4.0, PHP 7)

SplDoublyLinkedList::unserialize — Unserializes the storage

Descrierea

public void SplDoublyLinkedList::unserialize ( string $serialized )

Unserializes the storage, from SplDoublyLinkedList::serialize().

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

serialized

The serialized string.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • SplDoublyLinkedList::serialize() - Serializes the storage

SplDoublyLinkedList::top
SplDoublyLinkedList::unshift
SplDoublyLinkedList


Prepends the doubly linked list with an element

SplDoublyLinkedList::unserialize
SplDoublyLinkedList::valid
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::unshift

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element

Descrierea

public void SplDoublyLinkedList::unshift ( mixed $value )

Prepends value at the beginning of the doubly linked list.

Parametri

value

The value to unshift.

Valorile întoarse

Nu este întoarsa nici o valoare.

SplDoublyLinkedList::unserialize
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, PHP 7)

SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes

Descrierea

public bool SplDoublyLinkedList::valid ( void )

Checks if the doubly linked list contains any more nodes.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

Introducere

The SplStack class provides the main functionalities of a stack implemented using a doubly linked list.

Sinopsisul clasei

SplStack extends SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Metode */
__construct ( void )
void setIteratorMode ( int $mode )
/* Metode mo?tenite */
public void SplDoublyLinkedList::add ( mixed $index , mixed $newval )
public mixed SplDoublyLinkedList::bottom ( void )
public int SplDoublyLinkedList::count ( void )
public mixed SplDoublyLinkedList::current ( void )
public int SplDoublyLinkedList::getIteratorMode ( void )
public bool SplDoublyLinkedList::isEmpty ( void )
public mixed SplDoublyLinkedList::key ( void )
public void SplDoublyLinkedList::next ( void )
public bool SplDoublyLinkedList::offsetExists ( mixed $index )
public mixed SplDoublyLinkedList::offsetGet ( mixed $index )
public void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )
public void SplDoublyLinkedList::offsetUnset ( mixed $index )
public mixed SplDoublyLinkedList::pop ( void )
public void SplDoublyLinkedList::prev ( void )
public void SplDoublyLinkedList::push ( mixed $value )
public void SplDoublyLinkedList::rewind ( void )
public string SplDoublyLinkedList::serialize ( void )
public void SplDoublyLinkedList::setIteratorMode ( int $mode )
public mixed SplDoublyLinkedList::shift ( void )
public mixed SplDoublyLinkedList::top ( void )
public void SplDoublyLinkedList::unserialize ( string $serialized )
public void SplDoublyLinkedList::unshift ( mixed $value )
public bool SplDoublyLinkedList::valid ( void )
}

Cuprins

  • SplStack::__construct — Constructs a new stack implemented using a doubly linked list
  • SplStack::setIteratorMode — Sets the mode of iteration
SplDoublyLinkedList::valid
SplStack::__construct
Structuri de date


Constructs a new stack implemented using a doubly linked list

SplStack
SplStack::setIteratorMode
SplStack
PHP Manual

SplStack::__construct

(PHP 5 >= 5.3.0, PHP 7)

SplStack::__construct — Constructs a new stack implemented using a doubly linked list

Descrierea

SplStack::__construct ( void )

This constructs a new empty stack.

Nota:

This method automatically sets the iterator mode to SplDoublyLinkedList::IT_MODE_LIFO.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 SplStack::__construct() example

<?php
$q = new SplStack();

$q[] = 1;
$q[] = 2;
$q[] = 3;

foreach ($q as $elem)  {
 echo $elem."\n";
}
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

SplStack::setIteratorMode — Sets the mode of iteration

Descrierea

void SplStack::setIteratorMode ( int $mode )

Parametri

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

Avertizare

The direction of iteration can no longer be changed for SplStacks. Trying to do so will result in a RuntimeException being thrown.

Valorile întoarse

Nu este întoarsa nici o valoare.

SplStack::__construct
SplQueue
SplStack


The SplQueue class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

The SplQueue class provides the main functionalities of a queue implemented using a doubly linked list.

Sinopsisul clasei

SplQueue extends SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Metode */
__construct ( void )
mixed dequeue ( void )
void enqueue ( mixed $value )
void setIteratorMode ( int $mode )
/* Metode mo?tenite */
public void SplDoublyLinkedList::add ( mixed $index , mixed $newval )
public mixed SplDoublyLinkedList::bottom ( void )
public int SplDoublyLinkedList::count ( void )
public mixed SplDoublyLinkedList::current ( void )
public int SplDoublyLinkedList::getIteratorMode ( void )
public bool SplDoublyLinkedList::isEmpty ( void )
public mixed SplDoublyLinkedList::key ( void )
public void SplDoublyLinkedList::next ( void )
public bool SplDoublyLinkedList::offsetExists ( mixed $index )
public mixed SplDoublyLinkedList::offsetGet ( mixed $index )
public void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )
public void SplDoublyLinkedList::offsetUnset ( mixed $index )
public mixed SplDoublyLinkedList::pop ( void )
public void SplDoublyLinkedList::prev ( void )
public void SplDoublyLinkedList::push ( mixed $value )
public void SplDoublyLinkedList::rewind ( void )
public string SplDoublyLinkedList::serialize ( void )
public void SplDoublyLinkedList::setIteratorMode ( int $mode )
public mixed SplDoublyLinkedList::shift ( void )
public mixed SplDoublyLinkedList::top ( void )
public void SplDoublyLinkedList::unserialize ( string $serialized )
public void SplDoublyLinkedList::unshift ( mixed $value )
public bool SplDoublyLinkedList::valid ( void )
}

Cuprins

  • 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
Structuri de date


Constructs a new queue implemented using a doubly linked list

SplQueue
SplQueue::dequeue
SplQueue
PHP Manual

SplQueue::__construct

(PHP 5 >= 5.3.0, PHP 7)

SplQueue::__construct — Constructs a new queue implemented using a doubly linked list

Descrierea

SplQueue::__construct ( void )

This constructs a new empty queue.

Nota:

This method automatically sets the iterator mode to SplDoublyLinkedList::IT_MODE_FIFO.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 SplQueue::__construct() example

<?php
$q = new SplQueue();

$q[] = 1;
$q[] = 2;
$q[] = 3;

foreach ($q as $elem)  {
 echo $elem."\n";
}
?>

Exemplul de mai sus va afi?a:

1
2
3

Example #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, PHP 7)

SplQueue::dequeue — Dequeues a node from the queue

Descrierea

mixed SplQueue::dequeue ( void )

Dequeues value from the top of the queue.

Nota:

SplQueue::dequeue() is an alias of SplDoublyLinkedList::shift().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplQueue::enqueue — Adds an element to the queue.

Descrierea

void SplQueue::enqueue ( mixed $value )

Enqueues value at the end of the queue.

Nota:

SplQueue::enqueue() is an alias of SplDoublyLinkedList::push().

Parametri

value

The value to enqueue.

Valorile întoarse

Nu este întoarsa nici o valoare.

SplQueue::dequeue
SplQueue::setIteratorMode
SplQueue


Sets the mode of iteration

SplQueue::enqueue
SplHeap
SplQueue
PHP Manual

SplQueue::setIteratorMode

(PHP 5 >= 5.3.0, PHP 7)

SplQueue::setIteratorMode — Sets the mode of iteration

Descrierea

void SplQueue::setIteratorMode ( int $mode )

Parametri

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

Avertizare

The direction of iteration can not be changed for SplQueues, it is always SplDoublyLinkedList::IT_MODE_FIFO.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

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, PHP 7)

Introducere

The SplHeap class provides the main functionalities of a Heap.

Sinopsisul clasei

abstract SplHeap implements Iterator , Countable {
/* Metode */
public __construct ( void )
abstract protected int compare ( mixed $value1 , mixed $value2 )
public int count ( void )
public mixed current ( void )
public mixed extract ( void )
public void insert ( mixed $value )
public bool isEmpty ( void )
public mixed key ( void )
public void next ( void )
public void recoverFromCorruption ( void )
public void rewind ( void )
public mixed top ( void )
public bool valid ( void )
}

Cuprins

  • 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
Structuri de date


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, PHP 7)

SplHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

Descrierea

abstract protected int SplHeap::compare ( mixed $value1 , mixed $value2 )

Compare value1 with value2.

Avertizare

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.

Parametri

value1

The value of the first node being compared.

value2

The value of the second node being compared.

Valorile întoarse

Result of the comparison, positive integer if value1 is greater than value2, 0 if they are equal, negative integer otherwise.

Nota:

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, PHP 7)

SplHeap::__construct — Constructs a new empty heap

Descrierea

public SplHeap::__construct ( void )

This constructs a new empty heap.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplHeap::count — Counts the number of elements in the heap.

Descrierea

public int SplHeap::count ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplHeap::current — Return current node pointed by the iterator

Descrierea

public mixed SplHeap::current ( void )

Get the current datastructure node.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplHeap::extract — Extracts a node from top of the heap and sift up.

Descrierea

public mixed SplHeap::extract ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The value of the extracted node.

Erori/Excep?ii

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, PHP 7)

SplHeap::insert — Inserts an element in the heap by sifting it up.

Descrierea

public void SplHeap::insert ( mixed $value )

Insert value in the heap.

Parametri

value

The value to insert.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplHeap::isEmpty — Checks whether the heap is empty.

Descrierea

public bool SplHeap::isEmpty ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplHeap::key — Return current node index

Descrierea

public mixed SplHeap::key ( void )

This function returns the current node index

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplHeap::next — Move to the next node

Descrierea

public void SplHeap::next ( void )

Move to the next node. This will delete the top node of the heap.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplHeap::recoverFromCorruption — Recover from the corrupted state and allow further actions on the heap.

Descrierea

public void SplHeap::recoverFromCorruption ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplHeap::rewind — Rewind iterator back to the start (no-op)

Descrierea

public 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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplHeap::top — Peeks at the node from the top of the heap

Descrierea

public mixed SplHeap::top ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The value of the node on the top.

Erori/Excep?ii

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, PHP 7)

SplHeap::valid — Check whether the heap contains more nodes

Descrierea

public bool SplHeap::valid ( void )

Checks if the heap contains any more nodes.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the heap contains any more nodes, FALSE otherwise.

SplHeap::top
SplMaxHeap
SplHeap


The SplMaxHeap class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.

Sinopsisul clasei

SplMaxHeap extends SplHeap implements Iterator , Countable {
/* Metode */
protected int compare ( mixed $value1 , mixed $value2 )
/* Metode mo?tenite */
abstract protected int SplHeap::compare ( mixed $value1 , mixed $value2 )
public int SplHeap::count ( void )
public mixed SplHeap::current ( void )
public mixed SplHeap::extract ( void )
public void SplHeap::insert ( mixed $value )
public bool SplHeap::isEmpty ( void )
public mixed SplHeap::key ( void )
public void SplHeap::next ( void )
public void SplHeap::recoverFromCorruption ( void )
public void SplHeap::rewind ( void )
public mixed SplHeap::top ( void )
public bool SplHeap::valid ( void )
}

Cuprins

  • SplMaxHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.
SplHeap::valid
SplMaxHeap::compare
Structuri de date


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, PHP 7)

SplMaxHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

Descrierea

protected int SplMaxHeap::compare ( mixed $value1 , mixed $value2 )

Compare value1 with value2.

Parametri

value1

The value of the first node being compared.

value2

The value of the second node being compared.

Valorile întoarse

Result of the comparison, positive integer if value1 is greater than value2, 0 if they are equal, negative integer otherwise.

Nota:

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, PHP 7)

Introducere

The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.

Sinopsisul clasei

SplMinHeap extends SplHeap implements Iterator , Countable {
/* Metode */
protected int compare ( mixed $value1 , mixed $value2 )
/* Metode mo?tenite */
abstract protected int SplHeap::compare ( mixed $value1 , mixed $value2 )
public int SplHeap::count ( void )
public mixed SplHeap::current ( void )
public mixed SplHeap::extract ( void )
public void SplHeap::insert ( mixed $value )
public bool SplHeap::isEmpty ( void )
public mixed SplHeap::key ( void )
public void SplHeap::next ( void )
public void SplHeap::recoverFromCorruption ( void )
public void SplHeap::rewind ( void )
public mixed SplHeap::top ( void )
public bool SplHeap::valid ( void )
}

Cuprins

  • SplMinHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.
SplMaxHeap::compare
SplMinHeap::compare
Structuri de date


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, PHP 7)

SplMinHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

Descrierea

protected int SplMinHeap::compare ( mixed $value1 , mixed $value2 )

Compare value1 with value2.

Parametri

value1

The value of the first node being compared.

value2

The value of the second node being compared.

Valorile întoarse

Result of the comparison, positive integer if value1 is lower than value2, 0 if they are equal, negative integer otherwise.

Nota:

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, PHP 7)

Introducere

The SplPriorityQueue class provides the main functionalities of a prioritized queue, implemented using a max heap.

Sinopsisul clasei

SplPriorityQueue implements Iterator , Countable {
/* Metode */
public __construct ( void )
public int compare ( mixed $priority1 , mixed $priority2 )
public int count ( void )
public mixed current ( void )
public mixed extract ( void )
public void insert ( mixed $value , mixed $priority )
public bool isEmpty ( void )
public mixed key ( void )
public void next ( void )
public void recoverFromCorruption ( void )
public void rewind ( void )
public void setExtractFlags ( int $flags )
public mixed top ( void )
public bool valid ( void )
}

Cuprins

  • 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 shift 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
Structuri de date


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, PHP 7)

SplPriorityQueue::compare — Compare priorities in order to place elements correctly in the heap while sifting up.

Descrierea

public int SplPriorityQueue::compare ( mixed $priority1 , mixed $priority2 )

Compare priority1 with priority2.

Parametri

priority1

The priority of the first node being compared.

priority2

The priority of the second node being compared.

Valorile întoarse

Result of the comparison, positive integer if priority1 is greater than priority2, 0 if they are equal, negative integer otherwise.

Nota:

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, PHP 7)

SplPriorityQueue::__construct — Constructs a new empty queue

Descrierea

public SplPriorityQueue::__construct ( void )

This constructs a new empty queue.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplPriorityQueue::count — Counts the number of elements in the queue.

Descrierea

public int SplPriorityQueue::count ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplPriorityQueue::current — Return current node pointed by the iterator

Descrierea

public mixed SplPriorityQueue::current ( void )

Get the current datastructure node.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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 shift up.

SplPriorityQueue::current
SplPriorityQueue::insert
SplPriorityQueue
PHP Manual

SplPriorityQueue::extract

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::extract — Extracts a node from top of the heap and shift up.

Descrierea

public mixed SplPriorityQueue::extract ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplPriorityQueue::insert — Inserts an element in the queue by sifting it up.

Descrierea

public void SplPriorityQueue::insert ( mixed $value , mixed $priority )

Insert value with the priority priority in the queue.

Parametri

value

The value to insert.

priority

The associated priority.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplPriorityQueue::isEmpty — Checks whether the queue is empty.

Descrierea

public bool SplPriorityQueue::isEmpty ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplPriorityQueue::key — Return current node index

Descrierea

public mixed SplPriorityQueue::key ( void )

This function returns the current node index

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplPriorityQueue::next — Move to the next node

Descrierea

public void SplPriorityQueue::next ( void )

Extracts the top node from the queue.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplPriorityQueue::recoverFromCorruption — Recover from the corrupted state and allow further actions on the queue.

Descrierea

public void SplPriorityQueue::recoverFromCorruption ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplPriorityQueue::rewind — Rewind iterator back to the start (no-op)

Descrierea

public 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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

SplPriorityQueue::recoverFromCorruption
SplPriorityQueue::setExtractFlags
SplPriorityQueue


Sets the mode of extraction

SplPriorityQueue::rewind
SplPriorityQueue::top
SplPriorityQueue
PHP Manual

SplPriorityQueue::setExtractFlags

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::setExtractFlags — Sets the mode of extraction

Descrierea

public void SplPriorityQueue::setExtractFlags ( int $flags )

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplPriorityQueue::top — Peeks at the node from the top of the queue

Descrierea

public mixed SplPriorityQueue::top ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplPriorityQueue::valid — Check whether the queue contains more nodes

Descrierea

public bool SplPriorityQueue::valid ( void )

Checks if the queue contains any more nodes.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the queue contains any more nodes, FALSE otherwise.

SplPriorityQueue::top
SplFixedArray
SplPriorityQueue


The SplFixedArray class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

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.

Sinopsisul clasei

SplFixedArray implements Iterator , ArrayAccess , Countable {
/* Metode */
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 )
public void __wakeup ( void )
}

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

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

Cuprins

  • 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
  • SplFixedArray::__wakeup — Reinitialises the array after being unserialised
SplPriorityQueue::valid
SplFixedArray::__construct
Structuri de date


Constructs a new fixed array

SplFixedArray
SplFixedArray::count
SplFixedArray
PHP Manual

SplFixedArray::__construct

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::__construct — Constructs a new fixed array

Descrierea

public SplFixedArray::__construct ([ int $size = 0 ] )

Initializes a fixed array with a number of NULL values equal to size.

Parametri

size

The size of the fixed array. This expects a number between 0 and PHP_INT_MAX.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws InvalidArgumentException when size is a negative number.

Raises E_WARNING when size cannot be parsed as a number.

Exemple

Example #1 SplFixedArray::__construct() example

<?php
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = "foo";

foreach($array as $v) {
  var_dump($v);
}
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

SplFixedArray::count — Returns the size of the array

Descrierea

public int SplFixedArray::count ( void )

Returns the size of the array.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the size of the array.

Exemple

Example #1 SplFixedArray::count() example

<?php
$array = new SplFixedArray(5);
echo $array->count() . "\n";
echo count($array) . "\n";
?>

Exemplul de mai sus va afi?a:

5
5

Note

Nota:

This method is functionally equivalent to SplFixedArray::getSize().

Nota:

The count of elements is always equal to the set size because all values are initially initialized with NULL.

A se vedea ?i

  • 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, PHP 7)

SplFixedArray::current — Return current array entry

Descrierea

public mixed SplFixedArray::current ( void )

Get the current array element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current element value.

Erori/Excep?ii

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, PHP 7)

SplFixedArray::fromArray — Import a PHP array in a SplFixedArray instance

Descrierea

public static SplFixedArray SplFixedArray::fromArray ( array $array [, bool $save_indexes = true ] )

Import the PHP array array in a new SplFixedArray instance

Parametri

array

The array to import.

save_indexes

Try to save the numeric indexes used in the original array.

Valorile întoarse

Returns an instance of SplFixedArray containing the array content.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

SplFixedArray::getSize — Gets the size of the array

Descrierea

public int SplFixedArray::getSize ( void )

Gets the size of the array.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the size of the array, as an integer.

Exemple

Example #1 SplFixedArray::getSize() example

<?php
$array = new SplFixedArray(5);
echo $array->getSize()."\n";
$array->setSize(10);
echo $array->getSize()."\n";
?>

Exemplul de mai sus va afi?a:

5
10

Note

Nota:

This method is functionally equivalent to SplFixedArray::count()

A se vedea ?i

  • 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, PHP 7)

SplFixedArray::key — Return current array index

Descrierea

public int SplFixedArray::key ( void )

Returns the current array index.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplFixedArray::next — Move to next entry

Descrierea

public void SplFixedArray::next ( void )

Move the iterator to the next array entry.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplFixedArray::offsetExists — Returns whether the requested index exists

Descrierea

public bool SplFixedArray::offsetExists ( int $index )

Checks whether the requested index index exists.

Parametri

index

The index being checked.

Valorile întoarse

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, PHP 7)

SplFixedArray::offsetGet — Returns the value at the specified index

Descrierea

public mixed SplFixedArray::offsetGet ( int $index )

Returns the value at the index index.

Parametri

index

The index with the value.

Valorile întoarse

The value at the specified index.

Erori/Excep?ii

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, PHP 7)

SplFixedArray::offsetSet — Sets a new value at a specified index

Descrierea

public void SplFixedArray::offsetSet ( int $index , mixed $newval )

Sets the value at the specified index to newval.

Parametri

index

The index being set.

newval

The new value for the index.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

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, PHP 7)

SplFixedArray::offsetUnset — Unsets the value at the specified $index

Descrierea

public void SplFixedArray::offsetUnset ( int $index )

Unsets the value at the specified index.

Parametri

index

The index being unset.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

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, PHP 7)

SplFixedArray::rewind — Rewind iterator back to the start

Descrierea

public void SplFixedArray::rewind ( void )

Rewinds the iterator to the beginning.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SplFixedArray::setSize — Change the size of an array

Descrierea

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.

Parametri

size

The new array size. This should be a value between 0 and PHP_INT_MAX.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws InvalidArgumentException when size is less than zero.

Raises E_WARNING when size cannot be used as a number.

Exemple

Example #1 SplFixedArray::setSize() example

<?php
   $array = new SplFixedArray(5);
   echo $array->getSize()."\n";
   $array->setSize(10);
   echo $array->getSize()."\n";
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

SplFixedArray::toArray — Returns a PHP array from the fixed array

Descrierea

public array SplFixedArray::toArray ( void )

Returns a PHP array from the fixed array.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a PHP array, similar to the fixed array.

Exemple

Example #1 SplFixedArray::toArray() example

<?php
$fa = new SplFixedArray(3);
$fa[0] = 0;
$fa[2] = 2;
var_dump($fa->toArray());
?>

Exemplul de mai sus va afi?a:

array(3) {
  [0]=>
  int(0)
  [1]=>
  NULL
  [2]=>
  int(2)
}

SplFixedArray::setSize
SplFixedArray::valid
SplFixedArray


Check whether the array contains more elements

SplFixedArray::toArray
SplFixedArray::__wakeup
SplFixedArray
PHP Manual

SplFixedArray::valid

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::valid — Check whether the array contains more elements

Descrierea

public bool SplFixedArray::valid ( void )

Checks if the array contains any more elements.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the array contains any more elements, FALSE otherwise.

SplFixedArray::toArray
SplFixedArray::__wakeup
SplFixedArray


Reinitialises the array after being unserialised

SplFixedArray::valid
SplObjectStorage
SplFixedArray
PHP Manual

SplFixedArray::__wakeup

(PHP 5 >= 5.5.0, PHP 7)

SplFixedArray::__wakeup — Reinitialises the array after being unserialised

Descrierea

public void SplFixedArray::__wakeup ( void )

Reinitialises the array after being unserialised.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

SplFixedArray::valid
SplObjectStorage
SplFixedArray


The SplObjectStorage class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

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.

Sinopsisul clasei

SplObjectStorage implements Countable , Iterator , Serializable , ArrayAccess {
/* Metode */
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 ( object $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 )
}

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(false)

Example #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]);
}
?>

Exemplul de mai sus va afi?a:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

Cuprins

  • 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::__wakeup
SplObjectStorage::addAll
Structuri de date


Adds all objects from another storage

SplObjectStorage
SplObjectStorage::attach
SplObjectStorage
PHP Manual

SplObjectStorage::addAll

(PHP 5 >= 5.3.0, PHP 7)

SplObjectStorage::addAll — Adds all objects from another storage

Descrierea

public void SplObjectStorage::addAll ( SplObjectStorage $storage )

Adds all objects-data pairs from a different storage in the current storage.

Parametri

storage

The storage you want to import.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 SplObjectStorage::addAll() example

<?php
$o = new StdClass;
$a = new SplObjectStorage();
$a[$o] = "hello";

$b = new SplObjectStorage();
$b->addAll($a);
echo $b[$o]."\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

hello

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::attach — Adds an object in the storage

Descrierea

public void SplObjectStorage::attach ( object $object [, mixed $data = NULL ] )

Adds an object inside the storage, and optionally associate it to some data.

Parametri

object

The object to add.

data

The data to associate with the object.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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]);

?>

Exemplul de mai sus va afi?a ceva similar cu:

NULL
string(5) "hello"

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Added the data parameter.

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::contains — Checks if the storage contains a specific object

Descrierea

public bool SplObjectStorage::contains ( object $object )

Checks if the storage contains the object provided.

Parametri

object

The object to look for.

Valorile întoarse

Returns TRUE if the object is in the storage, FALSE otherwise.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(false)

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::count — Returns the number of objects in the storage

Descrierea

public int SplObjectStorage::count ( void )

Counts the number of objects in the storage.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The number of objects in the storage.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(2)
int(2)

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::current — Returns the current storage entry

Descrierea

public object SplObjectStorage::current ( void )

Returns the current storage entry.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The object at the current iterator position.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(stdClass)#2 (0) {
}
string(2) "d1"
object(stdClass)#3 (0) {
}
string(2) "d2"

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::detach — Removes an object from the storage

Descrierea

public void SplObjectStorage::detach ( object $object )

Removes the object from the storage.

Parametri

object

The object to remove.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(1)
int(0)

A se vedea ?i

  • 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

(PHP 5 >= 5.4.0, PHP 7)

SplObjectStorage::getHash — Calculate a unique identifier for the contained objects

Descrierea

public string SplObjectStorage::getHash ( object $object )

This method calculates an identifier for the objects added to an SplObjectStorage object.

The implementation in SplObjectStorage returns the same value as spl_object_hash().

The storage 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.

Parametri

object

The object whose identifier is to be calculated.

Valorile întoarse

A string with the calculated identifier.

Erori/Excep?ii

A RuntimeException is thrown when the returned value is not a string.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

2
3

A se vedea ?i

  • spl_object_hash() - Return hash id for given object

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, PHP 7)

SplObjectStorage::getInfo — Returns the data associated with the current iterator entry

Descrierea

public mixed SplObjectStorage::getInfo ( void )

Returns the data, or info, associated with the object pointed by the current iterator position.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The data associated with the current iterator position.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(stdClass)#2 (0) {
}
string(2) "d1"
object(stdClass)#3 (0) {
}
string(2) "d2"

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::key — Returns the index at which the iterator currently is

Descrierea

public int SplObjectStorage::key ( void )

Returns the index at which the iterator currently is.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The index corresponding to the position of the iterator.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(0)
object(stdClass)#2 (0) {
}
int(1)
object(stdClass)#3 (0) {
}

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::next — Move to the next entry

Descrierea

public void SplObjectStorage::next ( void )

Moves the iterator to the next object in the storage.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(0)
object(stdClass)#2 (0) {
}
int(1)
object(stdClass)#3 (0) {
}

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::offsetExists — Checks whether an object exists in the storage

Descrierea

public bool SplObjectStorage::offsetExists ( object $object )

Checks whether an object exists in the storage.

Nota:

SplObjectStorage::offsetExists() is an alias of SplObjectStorage::contains().

Parametri

object

The object to look for.

Valorile întoarse

Returns TRUE if the object exists in the storage, and FALSE otherwise.

Exemple

Example #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])
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(false)

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::offsetGet — Returns the data associated with an object

Descrierea

public mixed SplObjectStorage::offsetGet ( object $object )

Returns the data associated with an object in the storage.

Parametri

object

The object to look for.

Valorile întoarse

The data previously associated with the object in the storage.

Erori/Excep?ii

Throws UnexpectedValueException when object could not be found.

Exemple

Example #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]
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(5) "hello"
NULL

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::offsetSet — Associates data to an object in the storage

Descrierea

public void SplObjectStorage::offsetSet ( object $object [, mixed $data = NULL ] )

Associate data to an object in the storage.

Nota:

SplObjectStorage::offsetSet() is an alias of SplObjectStorage::attach().

Parametri

object

The object to associate data with.

data

The data to associate with the object.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 SplObjectStorage::offsetSet() example

<?php
$s = new SplObjectStorage;

$o1 = new StdClass;

$s->offsetSet($o1, "hello"); // Similar to $s[$o1] = "hello";

var_dump($s[$o1]);
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(5) "hello"

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::offsetUnset — Removes an object from the storage

Descrierea

public void SplObjectStorage::offsetUnset ( object $object )

Removes an object from the storage.

Nota:

SplObjectStorage::offsetUnset() is an alias of SplObjectStorage::detach().

Parametri

object

The object to remove.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(1)
int(0)

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::removeAll — Removes objects contained in another storage from the current storage

Descrierea

public void SplObjectStorage::removeAll ( SplObjectStorage $storage )

Removes objects contained in another storage from the current storage.

Parametri

storage

The storage containing the elements to remove.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(2)
int(1)

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::removeAllExcept — Removes all objects except for those contained in another storage from the current storage

Descrierea

public void SplObjectStorage::removeAllExcept ( SplObjectStorage $storage )

Removes all objects except for those contained in another storage from the current storage.

Parametri

storage

The storage containing the elements to retain in the current storage.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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, PHP 7)

SplObjectStorage::rewind — Rewind the iterator to the first storage element

Descrierea

public void SplObjectStorage::rewind ( void )

Rewind the iterator to the first storage element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(1)
int(0)

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::serialize — Serializes the storage

Descrierea

public string SplObjectStorage::serialize ( void )

Returns a string representation of the storage.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A string representing the storage.

Exemple

Example #1 SplObjectStorage::serialize() example

<?php
$s = new SplObjectStorage;
$o = new StdClass;
$s[$o] = "data";

echo $s->serialize()."\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

x:i:1;O:8:"stdClass":0:{},s:4:"data";;m:a:0:{}

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::setInfo — Sets the data associated with the current iterator entry

Descrierea

public void SplObjectStorage::setInfo ( mixed $data )

Associates data, or info, with the object currently pointed to by the iterator.

Parametri

data

The data to associate with the current iterator entry.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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]);
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(3) "new"
string(3) "new"

A se vedea ?i

  • 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, PHP 7)

SplObjectStorage::unserialize — Unserializes a storage from its string representation

Descrierea

public void SplObjectStorage::unserialize ( string $serialized )

Unserializes storage entries and attach them to the current storage.

Parametri

serialized

The serialized representation of a storage.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(1)

A se vedea ?i

  • SplObjectStorage::serialize() - Serializes the storage

SplObjectStorage::setInfo
SplObjectStorage::valid
SplObjectStorage


Returns if the current iterator entry is valid

SplObjectStorage::unserialize
Iteratori
SplObjectStorage
PHP Manual

SplObjectStorage::valid

(PHP 5 >= 5.1.0, PHP 7)

SplObjectStorage::valid — Returns if the current iterator entry is valid

Descrierea

public bool SplObjectStorage::valid ( void )

Returns if the current iterator entry is valid.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the iterator entry is valid, FALSE otherwise.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

0
1

A se vedea ?i

  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::getInfo() - Returns the data associated with the current iterator entry

SplObjectStorage::unserialize
Iteratori
SplObjectStorage


Iteratori

Cuprins

  • 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 ofera un set de iteratori pentru a traversa prin obiecte.

SPL Iterators Class Tree

  • ArrayIterator
    • RecursiveArrayIterator
  • EmptyIterator
  • IteratorIterator
    • AppendIterator
    • CachingIterator
      • RecursiveCachingIterator
    • FilterIterator
      • CallbackFilterIterator
        • RecursiveCallbackFilterIterator
      • RecursiveFilterIterator
        • ParentIterator
      • RegexIterator
        • RecursiveRegexIterator
    • InfiniteIterator
    • LimitIterator
    • NoRewindIterator
  • MultipleIterator
  • RecursiveIteratorIterator
    • RecursiveTreeIterator
  • DirectoryIterator (extends SplFileInfo)
    • FilesystemIterator
      • GlobIterator
      • RecursiveDirectoryIterator
SplObjectStorage::valid
AppendIterator
SPL


The AppendIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

An Iterator that iterates over several iterators one after the other.

Sinopsisul clasei

AppendIterator extends IteratorIterator implements OuterIterator {
/* Metode */
public __construct ( void )
public void append ( Iterator $iterator )
public mixed current ( void )
public ArrayIterator getArrayIterator ( void )
public Iterator getInnerIterator ( void )
public int getIteratorIndex ( void )
public scalar key ( void )
public void next ( void )
public void rewind ( void )
public bool valid ( void )
/* Metode mo?tenite */
public IteratorIterator::__construct ( Traversable $iterator )
public mixed IteratorIterator::current ( void )
public Traversable IteratorIterator::getInnerIterator ( void )
public scalar IteratorIterator::key ( void )
public void IteratorIterator::next ( void )
public void IteratorIterator::rewind ( void )
public bool IteratorIterator::valid ( void )
}

Cuprins

  • AppendIterator::append — Appends an iterator
  • AppendIterator::__construct — Constructs an AppendIterator
  • AppendIterator::current — Gets the current value
  • AppendIterator::getArrayIterator — Gets the ArrayIterator
  • AppendIterator::getInnerIterator — Gets the 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
Iteratori
AppendIterator::append
Iteratori


Appends an iterator

AppendIterator
AppendIterator::__construct
AppendIterator
PHP Manual

AppendIterator::append

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::append — Appends an iterator

Descrierea

public void AppendIterator::append ( Iterator $iterator )

Appends an iterator.

Parametri

iterator

The iterator to append.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 AppendIterator::append() example

<?php
$array_a = new ArrayIterator(array('a', 'b', 'c'));
$array_b = new ArrayIterator(array('d', 'e', 'f'));

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

foreach ($iterator as $current) {
    echo $current;
}
?>

Exemplul de mai sus va afi?a:

abcdef

A se vedea ?i

  • 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, PHP 7)

AppendIterator::__construct — Constructs an AppendIterator

Descrierea

public AppendIterator::__construct ( void )

Constructs an AppendIterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

0 => Margarita
1 => Siciliana
2 => Hawaii
0 => Cheese
1 => Anchovies
2 => Olives
3 => Pineapple
4 => Ham

Example #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();
}
?>

Exemplul de mai sus va afi?a:

0 => 0 => Margarita
0 => 1 => Siciliana
0 => 2 => Hawaii
1 => 0 => Cheese
1 => 1 => Anchovies
1 => 2 => Olives
1 => 3 => Pineapple
1 => 4 => Ham

Note

Precautie

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.

A se vedea ?i

  • 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, PHP 7)

AppendIterator::current — Gets the current value

Descrierea

public mixed AppendIterator::current ( void )

Gets the current value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current value if it is valid or NULL otherwise.

A se vedea ?i

  • Iterator::current() - Return the current element
  • AppendIterator::key() - Gets the current key
  • AppendIterator::valid() - Checks validity of the current element
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::rewind() - Rewinds the Iterator

AppendIterator::__construct
AppendIterator::getArrayIterator
AppendIterator


Gets the ArrayIterator

AppendIterator::current
AppendIterator::getInnerIterator
AppendIterator
PHP Manual

AppendIterator::getArrayIterator

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::getArrayIterator — Gets the ArrayIterator

Descrierea

public ArrayIterator AppendIterator::getArrayIterator ( void )

This method gets the ArrayIterator that is used to store the iterators added with AppendIterator::append().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an ArrayIterator containing the appended iterators.

A se vedea ?i

  • AppendIterator::getInnerIterator() - Gets the inner iterator

AppendIterator::current
AppendIterator::getInnerIterator
AppendIterator


Gets the inner iterator

AppendIterator::getArrayIterator
AppendIterator::getIteratorIndex
AppendIterator
PHP Manual

AppendIterator::getInnerIterator

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::getInnerIterator — Gets the inner iterator

Descrierea

public Iterator AppendIterator::getInnerIterator ( void )

This method returns the current inner iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current inner iterator, or NULL if there is not one.

Exemple

Example #1 AppendIterator::getInnerIterator() example

<?php
$array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara'));
$array_b = new RegexIterator($array_a, '/^[ac]/');

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

foreach ($iterator as $current) {
    $inner = $iterator->getInnerIterator();
    if ($inner instanceOf RegexIterator) {
        echo 'Filtered: ';
    } else {
        echo 'Original: ';
    }
    echo $current . PHP_EOL;
}
?>

Exemplul de mai sus va afi?a:

Original: aardwolf
Original: bear
Original: capybara
Filtered: aardwolf
Filtered: capybara

A se vedea ?i

  • AppendIterator::getIteratorIndex() - Gets an index of iterators

AppendIterator::getArrayIterator
AppendIterator::getIteratorIndex
AppendIterator


Gets an index of iterators

AppendIterator::getInnerIterator
AppendIterator::key
AppendIterator
PHP Manual

AppendIterator::getIteratorIndex

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::getIteratorIndex — Gets an index of iterators

Descrierea

public int AppendIterator::getIteratorIndex ( void )

Gets the index of the current inner iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an integer, which is the zero-based index of the current inner iterator.

Exemple

Example #1 AppendIterator.getIteratorIndex() basic example

<?php
$array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara'));
$array_b = new ArrayIterator(array('apple', 'orange', 'lemon'));

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

foreach ($iterator as $key => $current) {
    echo $iterator->getIteratorIndex() . '  ' . $key . ' ' . $current . PHP_EOL;
}
?>

Exemplul de mai sus va afi?a:

0  a aardwolf
0  b bear
0  c capybara
1  0 apple
1  1 orange
1  2 lemon

A se vedea ?i

  • AppendIterator::getInnerIterator() - Gets the inner iterator
  • AppendIterator::getArrayIterator() - Gets the ArrayIterator

AppendIterator::getInnerIterator
AppendIterator::key
AppendIterator


Gets the current key

AppendIterator::getIteratorIndex
AppendIterator::next
AppendIterator
PHP Manual

AppendIterator::key

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::key — Gets the current key

Descrierea

public scalar AppendIterator::key ( void )

Get the current key.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current key if it is valid or NULL otherwise.

Exemple

Example #1 AppendIterator::key() basic example

<?php
$array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara'));
$array_b = new ArrayIterator(array('apple', 'orange', 'lemon'));

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

// Manual iteration
$iterator->rewind();
while ($iterator->valid()) {
    echo $iterator->key() . ' ' . $iterator->current() . PHP_EOL;
    $iterator->next();
}

echo PHP_EOL;

// With foreach
foreach ($iterator as $key => $current) {
    echo $key . ' ' . $current . PHP_EOL;
}
?>

Exemplul de mai sus va afi?a:

a aardwolf
b bear
c capybara
0 apple
1 orange
2 lemon

a aardwolf
b bear
c capybara
0 apple
1 orange
2 lemon

A se vedea ?i

  • Iterator::key() - Return the key of the current element
  • AppendIterator::current() - Gets the current value
  • AppendIterator::valid() - Checks validity of the current element
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::rewind() - Rewinds the Iterator

AppendIterator::getIteratorIndex
AppendIterator::next
AppendIterator


Moves to the next element

AppendIterator::key
AppendIterator::rewind
AppendIterator
PHP Manual

AppendIterator::next

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::next — Moves to the next element

Descrierea

public void AppendIterator::next ( void )

Moves to the next element. If this means to another Iterator then it rewinds that Iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Iterator::next() - Move forward to next element
  • AppendIterator::current() - Gets the current value
  • AppendIterator::key() - Gets the current key
  • AppendIterator::valid() - Checks validity of the current element
  • 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, PHP 7)

AppendIterator::rewind — Rewinds the Iterator

Descrierea

public void AppendIterator::rewind ( void )

Rewind to the first element of the first inner Iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Iterator::rewind() - Rewind the Iterator to the first element
  • AppendIterator::current() - Gets the current value
  • AppendIterator::key() - Gets the current key
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::valid() - Checks validity of the current 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, PHP 7)

AppendIterator::valid — Checks validity of the current element

Descrierea

public bool AppendIterator::valid ( void )

Checks validity of the current element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the current iteration is valid, FALSE otherwise.

A se vedea ?i

  • AppendIterator::current() - Gets the current value
  • AppendIterator::key() - Gets the current key
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::rewind() - Rewinds the Iterator

AppendIterator::rewind
ArrayIterator
AppendIterator


The ArrayIterator class

(PHP 5, PHP 7)

Introducere

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.

Sinopsisul clasei

ArrayIterator implements ArrayAccess , SeekableIterator , Countable , Serializable {
/* Metode */
public void append ( mixed $value )
public void asort ( void )
public __construct ([ mixed $array = array() [, int $flags = 0 ]] )
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 )
}

Cuprins

  • 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
Iteratori


Append an element

ArrayIterator
ArrayIterator::asort
ArrayIterator
PHP Manual

ArrayIterator::append

(PHP 5 >= 5.0.0, PHP 7)

ArrayIterator::append — Append an element

Descrierea

public void ArrayIterator::append ( mixed $value )

Appends value as the last element.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

value

The value to append.

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Nota:

This method cannot be called when the ArrayIterator refers to an object.

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::asort — Sort array by values

Descrierea

public void ArrayIterator::asort ( void )

Sorts an array by values.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::__construct — Construct an ArrayIterator

Descrierea

public ArrayIterator::__construct ([ mixed $array = array() [, int $flags = 0 ]] )

Constructs an ArrayIterator object.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

array

The array or object to be iterated on.

flags

Flags to control the behaviour of the ArrayIterator object. See ArrayIterator::setFlags().

Valorile întoarse

An ArrayIterator object.

Erori/Excep?ii

ArrayIterator::__construct() throws an InvalidArgumentException if anything besides an array or an object is given.

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::count — Count elements

Descrierea

public int ArrayIterator::count ( void )

Gets the number of elements in the array, or the number of public properties in the object.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The number of elements or public properties in the associated array or object, respectively.

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::current — Return current array entry

Descrierea

public mixed ArrayIterator::current ( void )

Get the current array entry.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current array entry.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

ArrayIterator::getArrayCopy — Get array copy

Descrierea

public array ArrayIterator::getArrayCopy ( void )

Get a copy of an array.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A copy of the array, or array of public properties if ArrayIterator refers to an object.

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::getFlags — Get flags

Descrierea

public void ArrayIterator::getFlags ( void )

Get the current flags.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current flags.

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::key — Return current array key

Descrierea

public mixed ArrayIterator::key ( void )

This function returns the current array key

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current array key.

Exemple

Example #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, PHP 7)

ArrayIterator::ksort — Sort array by keys

Descrierea

public void ArrayIterator::ksort ( void )

Sorts an array by the keys.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::natcasesort — Sort an array naturally, case insensitive

Descrierea

public void ArrayIterator::natcasesort ( void )

Sort the entries by values using a case insensitive "natural order" algorithm.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • ArrayIterator::asort() - Sort array by values
  • ArrayIterator::ksort() - Sort array by keys
  • ArrayIterator::natsort() - Sort an array naturally
  • natcasesort() - Sort an array using a case insensitive "natural order" algorithm

ArrayIterator::ksort
ArrayIterator::natsort
ArrayIterator


Sort an array naturally

ArrayIterator::natcasesort
ArrayIterator::next
ArrayIterator
PHP Manual

ArrayIterator::natsort

(PHP 5 >= 5.2.0, PHP 7)

ArrayIterator::natsort — Sort an array naturally

Descrierea

public void ArrayIterator::natsort ( void )

Sort the entries by values using "natural order" algorithm.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • ArrayIterator::asort() - Sort array by values
  • ArrayIterator::ksort() - Sort array by keys
  • ArrayIterator::natcasesort() - Sort an array naturally, case insensitive
  • natsort() - Sort an array using a "natural order" algorithm

ArrayIterator::natcasesort
ArrayIterator::next
ArrayIterator


Move to next entry

ArrayIterator::natsort
ArrayIterator::offsetExists
ArrayIterator
PHP Manual

ArrayIterator::next

(PHP 5 >= 5.0.0, PHP 7)

ArrayIterator::next — Move to next entry

Descrierea

public void ArrayIterator::next ( void )

The iterator to the next entry.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

ArrayIterator::offsetExists — Check if offset exists

Descrierea

public void ArrayIterator::offsetExists ( string $index )

Checks if the offset exists.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

index

The offset being checked.

Valorile întoarse

TRUE if the offset exists, otherwise FALSE

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::offsetGet — Get value for an offset

Descrierea

public mixed ArrayIterator::offsetGet ( string $index )

Gets the value from the provided offset.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

index

The offset to get the value from.

Valorile întoarse

The value at offset index.

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::offsetSet — Set value for an offset

Descrierea

public void ArrayIterator::offsetSet ( string $index , string $newval )

Sets a value for a given offset.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

index

The index to set for.

newval

The new value to store at the index.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::offsetUnset — Unset value for an offset

Descrierea

public void ArrayIterator::offsetUnset ( string $index )

Unsets a value for an offset.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

index

The offset to unset.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::rewind — Rewind array back to the start

Descrierea

public void ArrayIterator::rewind ( void )

This rewinds the iterator to the beginning.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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, PHP 7)

ArrayIterator::seek — Seek to position

Descrierea

public void ArrayIterator::seek ( int $position )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

position

The position to seek to.

Valorile întoarse

Nu este întoarsa nici o valoare.

ArrayIterator::rewind
ArrayIterator::serialize
ArrayIterator


Serialize

ArrayIterator::seek
ArrayIterator::setFlags
ArrayIterator
PHP Manual

ArrayIterator::serialize

(PHP 5 >= 5.3.0, PHP 7)

ArrayIterator::serialize — Serialize

Descrierea

public string ArrayIterator::serialize ( void )

Serialize.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The serialized ArrayIterator.

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::setFlags — Set behaviour flags

Descrierea

public void ArrayIterator::setFlags ( string $flags )

Sets behaviour flags.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::uasort — User defined sort

Descrierea

public void ArrayIterator::uasort ( string $cmp_function )

Sort the entries by values using user defined function.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

cmp_function

The compare function used for the sort.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • ArrayIterator::uksort() - User defined sort
  • usort() - Sort an array by values using a user-defined comparison function

ArrayIterator::setFlags
ArrayIterator::uksort
ArrayIterator


User defined sort

ArrayIterator::uasort
ArrayIterator::unserialize
ArrayIterator
PHP Manual

ArrayIterator::uksort

(PHP 5 >= 5.2.0, PHP 7)

ArrayIterator::uksort — User defined sort

Descrierea

public void ArrayIterator::uksort ( string $cmp_function )

Sort the entries by key using user defined function.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

cmp_function

The compare function used for the sort.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • ArrayIterator::uasort() - User defined sort
  • uksort() - Sort an array by keys using a user-defined comparison function

ArrayIterator::uasort
ArrayIterator::unserialize
ArrayIterator


Unserialize

ArrayIterator::uksort
ArrayIterator::valid
ArrayIterator
PHP Manual

ArrayIterator::unserialize

(PHP 5 >= 5.3.0, PHP 7)

ArrayIterator::unserialize — Unserialize

Descrierea

public string ArrayIterator::unserialize ( string $serialized )

Unserialize.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

serialized

The serialized ArrayIterator object to be unserialized.

Valorile întoarse

The ArrayIterator.

A se vedea ?i

  • 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, PHP 7)

ArrayIterator::valid — Check whether array contains more entries

Descrierea

public bool ArrayIterator::valid ( void )

Checks if the array contains any more entries.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the iterator is valid, otherwise FALSE

Exemple

Example #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, PHP 7)

Introducere

This object supports cached iteration over another iterator.

Sinopsisul clasei

CachingIterator extends IteratorIterator implements OuterIterator , ArrayAccess , Countable {
/* Constante */
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 ;
/* Metode */
public __construct ( Iterator $iterator [, int $flags = self::CALL_TOSTRING ] )
public int count ( void )
public void current ( void )
public array getCache ( void )
public int getFlags ( void )
public Iterator getInnerIterator ( void )
public void hasNext ( void )
public scalar 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 ( int $flags )
public void __toString ( void )
public void valid ( void )
}

Constante predefinite

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.

Cuprins

  • 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 — Retrieve the contents of the cache
  • 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
Iteratori


Construct a new CachingIterator object for the iterator.

CachingIterator
CachingIterator::count
CachingIterator
PHP Manual

CachingIterator::__construct

(PHP 5, PHP 7)

CachingIterator::__construct — Construct a new CachingIterator object for the iterator.

Descrierea

public CachingIterator::__construct ( Iterator $iterator [, int $flags = self::CALL_TOSTRING ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

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, PHP 7)

CachingIterator::count — The number of elements in the iterator

Descrierea

public int CachingIterator::count ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

May return the number of elements in the iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

CachingIterator::current — Return the current element

Descrierea

public void CachingIterator::current ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

May return the current element in the iteration.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Mixed

A se vedea ?i

  • Iterator::current() - Return the current element

CachingIterator::count
CachingIterator::getCache
CachingIterator


Retrieve the contents of the cache

CachingIterator::current
CachingIterator::getFlags
CachingIterator
PHP Manual

CachingIterator::getCache

(PHP 5 >= 5.2.0, PHP 7)

CachingIterator::getCache — Retrieve the contents of the cache

Descrierea

public array CachingIterator::getCache ( void )

Retrieve the contents of the cache.

Nota:

The CachingIterator::FULL_CACHE flag must be being used.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array containing the cache items.

Erori/Excep?ii

Throws a BadMethodCallException when the CachingIterator::FULL_CACHE flag is not being used.

Exemple

Example #1 CachingIterator::getCache() example

<?php
$iterator = new ArrayIterator(array(1, 2, 3));
$cache    = new CachingIterator($iterator, CachingIterator::FULL_CACHE);

$cache->next();
$cache->next();
var_dump($cache->getCache());

$cache->next();
var_dump($cache->getCache());
?>

Exemplul de mai sus va afi?a:

array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

CachingIterator::current
CachingIterator::getFlags
CachingIterator


Get flags used

CachingIterator::getCache
CachingIterator::getInnerIterator
CachingIterator
PHP Manual

CachingIterator::getFlags

(PHP 5 >= 5.2.0, PHP 7)

CachingIterator::getFlags — Get flags used

Descrierea

public int CachingIterator::getFlags ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Get the bitmask of the flags used for this CachingIterator instance.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Description...

CachingIterator::getCache
CachingIterator::getInnerIterator
CachingIterator


Returns the inner iterator

CachingIterator::getFlags
CachingIterator::hasNext
CachingIterator
PHP Manual

CachingIterator::getInnerIterator

(PHP 5, PHP 7)

CachingIterator::getInnerIterator — Returns the inner iterator

Descrierea

public Iterator CachingIterator::getInnerIterator ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the iterator sent to the constructor.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

CachingIterator::hasNext — Check whether the inner iterator has a valid next element

Descrierea

public void CachingIterator::hasNext ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

CachingIterator::getInnerIterator
CachingIterator::key
CachingIterator


Return the key for the current element

CachingIterator::hasNext
CachingIterator::next
CachingIterator
PHP Manual

CachingIterator::key

(PHP 5, PHP 7)

CachingIterator::key — Return the key for the current element

Descrierea

public scalar CachingIterator::key ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

This method may return a key for the current element.

Parametri

Aceasta func?ie nu are parametri.

CachingIterator::hasNext
CachingIterator::next
CachingIterator


Move the iterator forward

CachingIterator::key
CachingIterator::offsetExists
CachingIterator
PHP Manual

CachingIterator::next

(PHP 5, PHP 7)

CachingIterator::next — Move the iterator forward

Descrierea

public void CachingIterator::next ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Move the iterator forward.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

CachingIterator::key
CachingIterator::offsetExists
CachingIterator


The offsetExists purpose

CachingIterator::next
CachingIterator::offsetGet
CachingIterator
PHP Manual

CachingIterator::offsetExists

(PHP 5 >= 5.2.0, PHP 7)

CachingIterator::offsetExists — The offsetExists purpose

Descrierea

public void CachingIterator::offsetExists ( string $index )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

index

The index being checked.

Valorile întoarse

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, PHP 7)

CachingIterator::offsetGet — The offsetGet purpose

Descrierea

public void CachingIterator::offsetGet ( string $index )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

index

Description...

Valorile întoarse

Description...

CachingIterator::offsetExists
CachingIterator::offsetSet
CachingIterator


The offsetSet purpose

CachingIterator::offsetGet
CachingIterator::offsetUnset
CachingIterator
PHP Manual

CachingIterator::offsetSet

(PHP 5 >= 5.2.0, PHP 7)

CachingIterator::offsetSet — The offsetSet purpose

Descrierea

public void CachingIterator::offsetSet ( string $index , string $newval )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

index

The index of the element to be set.

newval

The new value for the index.

Valorile întoarse

Nu este întoarsa nici o valoare.

CachingIterator::offsetGet
CachingIterator::offsetUnset
CachingIterator


The offsetUnset purpose

CachingIterator::offsetSet
CachingIterator::rewind
CachingIterator
PHP Manual

CachingIterator::offsetUnset

(PHP 5 >= 5.2.0, PHP 7)

CachingIterator::offsetUnset — The offsetUnset purpose

Descrierea

public void CachingIterator::offsetUnset ( string $index )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

index

The index of the element to be unset.

Valorile întoarse

Nu este întoarsa nici o valoare.

CachingIterator::offsetSet
CachingIterator::rewind
CachingIterator


Rewind the iterator

CachingIterator::offsetUnset
CachingIterator::setFlags
CachingIterator
PHP Manual

CachingIterator::rewind

(PHP 5, PHP 7)

CachingIterator::rewind — Rewind the iterator

Descrierea

public void CachingIterator::rewind ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Rewind the iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

CachingIterator::offsetUnset
CachingIterator::setFlags
CachingIterator


The setFlags purpose

CachingIterator::rewind
CachingIterator::__toString
CachingIterator
PHP Manual

CachingIterator::setFlags

(PHP 5 >= 5.2.0, PHP 7)

CachingIterator::setFlags — The setFlags purpose

Descrierea

public void CachingIterator::setFlags ( int $flags )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Set the flags for the CachingIterator object.

Parametri

flags

Bitmask of the flags to set.

Valorile întoarse

Nu este întoarsa nici o valoare.

CachingIterator::rewind
CachingIterator::__toString
CachingIterator


Return the string representation of the current element

CachingIterator::setFlags
CachingIterator::valid
CachingIterator
PHP Manual

CachingIterator::__toString

(PHP 5, PHP 7)

CachingIterator::__toString — Return the string representation of the current element

Descrierea

public void CachingIterator::__toString ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Get the string representation of the current element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

CachingIterator::valid — Check whether the current element is valid

Descrierea

public void CachingIterator::valid ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Check whether the current element is valid.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

CachingIterator::__toString
CallbackFilterIterator
CachingIterator


The CallbackFilterIterator class

(PHP 5 >= 5.4.0, PHP 7)

Introducere

Sinopsisul clasei

CallbackFilterIterator extends FilterIterator implements OuterIterator {
/* Metode */
public __construct ( Iterator $iterator , callable $callback )
public string accept ( void )
/* Metode mo?tenite */
public abstract bool FilterIterator::accept ( void )
public FilterIterator::__construct ( Iterator $iterator )
public mixed FilterIterator::current ( void )
public Iterator FilterIterator::getInnerIterator ( void )
public mixed FilterIterator::key ( void )
public void FilterIterator::next ( void )
public void FilterIterator::rewind ( void )
public bool FilterIterator::valid ( void )
}

Exemple

The callback should accept up to three arguments: the current item, the current key and the iterator, respectively.

Example #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 callable may be used; such as a string containing a function name, an array for a method, or an anonymous function.

Example #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();
});

?>

Cuprins

  • 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
Iteratori


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, PHP 7)

CallbackFilterIterator::accept — Calls the callback with the current value, the current key and the inner iterator as arguments

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE to accept the current item, or FALSE otherwise.

A se vedea ?i

  • 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, PHP 7)

CallbackFilterIterator::__construct — Create a filtered iterator from another iterator

Descrierea

public CallbackFilterIterator::__construct ( Iterator $iterator , callable $callback )

Creates a filtered iterator using the callback to determine which items are accepted or rejected.

Parametri

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 callable value.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

Introducere

The DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.

Sinopsisul clasei

DirectoryIterator extends SplFileInfo implements SeekableIterator {
/* Metode */
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 )
}

Istoricul schimbarilor

Versiune | Descriere
5.1.2 | DirectoryIterator extends SplFileInfo.

Cuprins

  • 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 — Gets the file extension
  • 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
Iteratori


Constructs a new directory iterator from a path

DirectoryIterator
DirectoryIterator::current
DirectoryIterator
PHP Manual

DirectoryIterator::__construct

(PHP 5, PHP 7)

DirectoryIterator::__construct — Constructs a new directory iterator from a path

Descrierea

public DirectoryIterator::__construct ( string $path )

Constructs a new directory iterator from a path.

Parametri

path

The path of the directory to traverse.

Erori/Excep?ii

Throws an UnexpectedValueException if the path cannot be opened.

Throws a RuntimeException if the path is an empty string.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Throws UnexpectedValueException if the path cannot be opened.
5.1.3 | Throws RuntimeException if the path is an empty string.
5.1.0 | Throws RuntimeException on error. Previously, threw Exception.

Exemple

Example #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());
    }
}
?>

A se vedea ?i

  • SplFileInfo
  • Iterator

DirectoryIterator
DirectoryIterator::current
DirectoryIterator


Return the current DirectoryIterator item.

DirectoryIterator::__construct
DirectoryIterator::getATime
DirectoryIterator
PHP Manual

DirectoryIterator::current

(PHP 5, PHP 7)

DirectoryIterator::current — Return the current DirectoryIterator item.

Descrierea

public DirectoryIterator DirectoryIterator::current ( void )

Get the current DirectoryIterator item.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current DirectoryIterator item.

Exemple

Example #1 A DirectoryIterator::current() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new DirectoryIterator(__DIR__);
while($iterator->valid()) {
    $file = $iterator->current();
    echo $iterator->key() . " => " . $file->getFilename() . "\n";
    $iterator->next();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

0 => .
1 => ..
2 => apple.jpg
3 => banana.jpg
4 => index.php
5 => pear.jpg

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::getATime — Get last access time of the current DirectoryIterator item

Descrierea

public int DirectoryIterator::getATime ( void )

Get the last access time of the current DirectoryIterator item.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the time the file was last accessed, as a Unix timestamp.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

apple.jpg 1240047118
banana.jpg 1240065176
index.php 1240047208
pear.jpg 12240047979

A se vedea ?i

  • DirectoryIterator::getCTime() - Get inode change time of the current DirectoryIterator item
  • DirectoryIterator::getMTime() - Get last modification time of current DirectoryIterator item
  • fileatime() - Gets last access time of file

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, PHP 7)

DirectoryIterator::getBasename — Get base name of current DirectoryIterator item.

Descrierea

public string DirectoryIterator::getBasename ([ string $suffix ] )

Get the base name of the current DirectoryIterator item.

Parametri

suffix

If the base name ends in suffix, this will be cut.

Valorile întoarse

The base name of the current DirectoryIterator item.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

apple.jpg
apple
banana.jpg
banana
index.php
index.php
pear.jpg
pear

A se vedea ?i

  • 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() - Returns trailing name component of path
  • pathinfo() - Returns information about a file path

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, PHP 7)

DirectoryIterator::getCTime — Get inode change time of the current DirectoryIterator item

Descrierea

public int DirectoryIterator::getCTime ( void )

Get the inode change time for the current DirectoryIterator item.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the last change time of the file, as a Unix timestamp.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

apple.jpg changed at 1240398312
banana.jpg changed at 1238605440
index.php changed at 1240398935
pear.jpg changed at 1237423740

A se vedea ?i

  • DirectoryIterator::getATime() - Get last access time of the current DirectoryIterator item
  • DirectoryIterator::getMTime() - Get last modification time of current DirectoryIterator item
  • filectime() - Gets inode change time of file

DirectoryIterator::getBasename
DirectoryIterator::getExtension
DirectoryIterator


Gets the file extension

DirectoryIterator::getCTime
DirectoryIterator::getFilename
DirectoryIterator
PHP Manual

DirectoryIterator::getExtension

(PHP 5 >= 5.3.6, PHP 7)

DirectoryIterator::getExtension — Gets the file extension

Descrierea

public string DirectoryIterator::getExtension ( void )

Retrieves the file extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string containing the file extension, or an empty string if the file has no extension.

Exemple

Example #1 DirectoryIterator::getExtension() example

<?php

$directory = new DirectoryIterator(__DIR__);
foreach ($directory as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getExtension() . "\n";
    }
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

php
txt
jpg
gz

Note

Nota:

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($fileinfo->getFilename(), PATHINFO_EXTENSION);
?>

A se vedea ?i

  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item.
  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item.
  • pathinfo() - Returns information about a file path
DirectoryIterator::getCTime
DirectoryIterator::getFilename
DirectoryIterator


Return file name of current DirectoryIterator item.

DirectoryIterator::getExtension
DirectoryIterator::getGroup
DirectoryIterator
PHP Manual

DirectoryIterator::getFilename

(PHP 5, PHP 7)

DirectoryIterator::getFilename — Return file name of current DirectoryIterator item.

Descrierea

public string DirectoryIterator::getFilename ( void )

Get the file name of the current DirectoryIterator item.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the file name of the current DirectoryIterator item.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

A se vedea ?i

  • 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() - Returns information about a file path

DirectoryIterator::getExtension
DirectoryIterator::getGroup
DirectoryIterator


Get group for the current DirectoryIterator item

DirectoryIterator::getFilename
DirectoryIterator::getInode
DirectoryIterator
PHP Manual

DirectoryIterator::getGroup

(PHP 5, PHP 7)

DirectoryIterator::getGroup — Get group for the current DirectoryIterator item

Descrierea

public int DirectoryIterator::getGroup ( void )

Get the group id of the file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the group id of the current DirectoryIterator item in numerical format.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

Directory belongs to group id 42
Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

A se vedea ?i

  • 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() - Gets file group
  • 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, PHP 7)

DirectoryIterator::getInode — Get inode for the current DirectoryIterator item

Descrierea

public int DirectoryIterator::getInode ( void )

Get the inode number for the current DirectoryIterator item.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the inode number for the file.

Exemple

Example #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();
?>

A se vedea ?i

  • 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() - Gets file inode

DirectoryIterator::getGroup
DirectoryIterator::getMTime
DirectoryIterator


Get last modification time of current DirectoryIterator item

DirectoryIterator::getInode
DirectoryIterator::getOwner
DirectoryIterator
PHP Manual

DirectoryIterator::getMTime

(PHP 5, PHP 7)

DirectoryIterator::getMTime — Get last modification time of current DirectoryIterator item

Descrierea

public int DirectoryIterator::getMTime ( void )

Get the last modification time of the current DirectoryIterator item, as a Unix timestamp.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The last modification time of the file, as a Unix timestamp.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

apple.jpg 1240047118
banana.jpg 1240065176
index.php 1240047208
pear.jpg 12240047979

A se vedea ?i

  • DirectoryIterator::getATime() - Get last access time of the current DirectoryIterator item
  • DirectoryIterator::getCTime() - Get inode change time of the current DirectoryIterator item
  • filemtime() - Gets file modification time

DirectoryIterator::getInode
DirectoryIterator::getOwner
DirectoryIterator


Get owner of current DirectoryIterator item

DirectoryIterator::getMTime
DirectoryIterator::getPath
DirectoryIterator
PHP Manual

DirectoryIterator::getOwner

(PHP 5, PHP 7)

DirectoryIterator::getOwner — Get owner of current DirectoryIterator item

Descrierea

public int DirectoryIterator::getOwner ( void )

Get the owner of the current DirectoryIterator item, in numerical format.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The file owner of the file, in numerical format.

Exemple

Example #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()));
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [name] => tom
    [passwd] => x
    [uid] => 501
    [gid] => 42
    [gecos] => Tom Cat
    [dir] => /home/tom
    [shell] => /bin/bash
)

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::getPath — Get path of current Iterator item without filename

Descrierea

public string DirectoryIterator::getPath ( void )

Get the path to the current DirectoryIterator item.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the path to the file, omitting the file name and any trailing slash.

Exemple

Example #1 DirectoryIterator::getPath() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
echo $iterator->getPath();
?>

Exemplul de mai sus va afi?a ceva similar cu:

/home/examples/public_html

A se vedea ?i

  • 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() - Returns information about a file path

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, PHP 7)

DirectoryIterator::getPathname — Return path and file name of current DirectoryIterator item

Descrierea

public string DirectoryIterator::getPathname ( void )

Get the path and file name of the current file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the path and file name of current file. Directories do not have a trailing slash.

Exemple

Example #1 DirectoryIterator::getPathname() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    echo $fileinfo->getPathname() . "\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

/home/examples/.
/home/examples/..
/home/examples/apple.jpg
/home/examples/banana.jpg
/home/examples/getpathname.php
/home/examples/pear.jpg

A se vedea ?i

  • 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() - Returns information about a file path

DirectoryIterator::getPath
DirectoryIterator::getPerms
DirectoryIterator


Get the permissions of current DirectoryIterator item

DirectoryIterator::getPathname
DirectoryIterator::getSize
DirectoryIterator
PHP Manual

DirectoryIterator::getPerms

(PHP 5, PHP 7)

DirectoryIterator::getPerms — Get the permissions of current DirectoryIterator item

Descrierea

public int DirectoryIterator::getPerms ( void )

Get the permissions of the current DirectoryIterator item.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the permissions of the file, as a decimal integer.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

apple.jpg 0644
banana.jpg 0644
index.php 0744
pear.jpg 0644

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::getSize — Get size of current DirectoryIterator item

Descrierea

public int DirectoryIterator::getSize ( void )

Get the file size for the current DirectoryIterator item.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the size of the file, in bytes.

Exemple

Example #1 DirectoryIterator::getSize() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . " " . $fileinfo->getSize() . "\n";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

apple.jpg 15385
banana.jpg 15190
example.php 170
pear.jpg 34406

A se vedea ?i

  • filesize() - Gets file size

DirectoryIterator::getPerms
DirectoryIterator::getType
DirectoryIterator


Determine the type of the current DirectoryIterator item

DirectoryIterator::getSize
DirectoryIterator::isDir
DirectoryIterator
PHP Manual

DirectoryIterator::getType

(PHP 5, PHP 7)

DirectoryIterator::getType — Determine the type of the current DirectoryIterator item

Descrierea

public string DirectoryIterator::getType ( void )

Determines which file type the current DirectoryIterator item belongs to. One of file, link, or dir.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string representing the type of the file. May be one of file, link, or dir.

Exemple

Example #1 DirectoryIterator::getType() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    echo $fileinfo->getFilename() . " " . $fileinfo->getType() . "\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

. dir
.. dir
apple.jpg file
banana.jpg file
example.php file
pear.jpg file

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::isDir — Determine if current DirectoryIterator item is a directory

Descrierea

public bool DirectoryIterator::isDir ( void )

Determines if the current DirectoryIterator item is a directory.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if it is a directory, otherwise FALSE

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

.
..
apples
bananas
pears

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::isDot — Determine if current DirectoryIterator item is '.' or '..'

Descrierea

public bool DirectoryIterator::isDot ( void )

Determines if the current DirectoryIterator item is a directory and either . or ...

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the entry is . or .., otherwise FALSE

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

apple.jpg
banana.jpg
example.php
pears.jpg

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::isExecutable — Determine if current DirectoryIterator item is executable

Descrierea

public bool DirectoryIterator::isExecutable ( void )

Determines if the current DirectoryIterator item is executable.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the entry is executable, otherwise FALSE

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

example.php
myscript.sh

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::isFile — Determine if current DirectoryIterator item is a regular file

Descrierea

public bool DirectoryIterator::isFile ( void )

Determines if the current DirectoryIterator item is a regular file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the file exists and is a regular file (not a link or dir), otherwise FALSE

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

apple.jpg
banana.jpg
example.php
pears.jpg

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::isLink — Determine if current DirectoryIterator item is a symbolic link

Descrierea

public bool DirectoryIterator::isLink ( void )

Determines if the current DirectoryIterator item is a symbolic link.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the item is a symbolic link, otherwise FALSE

Exemple

Example #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');
?>

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::isReadable — Determine if current DirectoryIterator item can be read

Descrierea

public bool DirectoryIterator::isReadable ( void )

Determines if the current DirectoryIterator item is readable.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the file is readable, otherwise FALSE

Exemple

Example #1 DirectoryIterator::isReadable() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isReadable()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

apple.jpg
banana.jpg
example.php
pears.jpg

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::isWritable — Determine if current DirectoryIterator item can be written to

Descrierea

public bool DirectoryIterator::isWritable ( void )

Determines if the current DirectoryIterator item is writable.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the file/directory is writable, otherwise FALSE

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

apples.txt
bananas.html
pears

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::key — Return the key for the current DirectoryIterator item

Descrierea

public string DirectoryIterator::key ( void )

Get the key for the current DirectoryIterator item.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The key for the current DirectoryIterator item.

Exemple

Example #1 A DirectoryIterator::key() example

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        echo $fileinfo->key() . " => " . $fileinfo->getFilename() . "\n";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

0 => apple.jpg
1 => banana.jpg
2 => index.php
3 => pear.jpg

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::next — Move forward to next DirectoryIterator item

Descrierea

public void DirectoryIterator::next ( void )

Move forward to the next DirectoryIterator item.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::rewind — Rewind the DirectoryIterator back to the start

Descrierea

public void DirectoryIterator::rewind ( void )

Rewind the DirectoryIterator back to the start.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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
?>

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::seek — Seek to a DirectoryIterator item

Descrierea

public void DirectoryIterator::seek ( int $position )

Seek to a given position in the DirectoryIterator.

Parametri

position

The zero-based numeric position to seek to.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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';
}
?>

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::__toString — Get file name as a string

Descrierea

public string DirectoryIterator::__toString ( void )

Get the file name of the current DirectoryIterator item.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the file name of the current DirectoryIterator item.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

A se vedea ?i

  • 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, PHP 7)

DirectoryIterator::valid — Check whether current DirectoryIterator position is a valid file

Descrierea

public bool DirectoryIterator::valid ( void )

Check whether current DirectoryIterator position is a valid file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the position is valid, otherwise FALSE

Exemple

Example #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

?>

A se vedea ?i

  • 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, PHP 7)

Introducere

The EmptyIterator class for an empty iterator.

Sinopsisul clasei

EmptyIterator implements Iterator {
/* Metode */
public mixed current ( void )
public scalar key ( void )
public void next ( void )
public void rewind ( void )
public bool valid ( void )
}

Cuprins

  • 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
Iteratori


The current() method

EmptyIterator
EmptyIterator::key
EmptyIterator
PHP Manual

EmptyIterator::current

(PHP 5 >= 5.1.0, PHP 7)

EmptyIterator::current — The current() method

Descrierea

public mixed EmptyIterator::current ( void )

This function must not be called. It throws an exception upon access.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Erori/Excep?ii

Throws an Exception if called.

Valorile întoarse

Nu este întoarsa nici o valoare.

EmptyIterator
EmptyIterator::key
EmptyIterator


The key() method

EmptyIterator::current
EmptyIterator::next
EmptyIterator
PHP Manual

EmptyIterator::key

(PHP 5 >= 5.1.0, PHP 7)

EmptyIterator::key — The key() method

Descrierea

public scalar EmptyIterator::key ( void )

This function must not be called. It throws an exception upon access.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Erori/Excep?ii

Throws an Exception if called.

Valorile întoarse

Nu este întoarsa nici o valoare.

EmptyIterator::current
EmptyIterator::next
EmptyIterator


The next() method

EmptyIterator::key
EmptyIterator::rewind
EmptyIterator
PHP Manual

EmptyIterator::next

(PHP 5 >= 5.1.0, PHP 7)

EmptyIterator::next — The next() method

Descrierea

public void EmptyIterator::next ( void )

No operation, nothing to do.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

EmptyIterator::key
EmptyIterator::rewind
EmptyIterator


The rewind() method

EmptyIterator::next
EmptyIterator::valid
EmptyIterator
PHP Manual

EmptyIterator::rewind

(PHP 5 >= 5.1.0, PHP 7)

EmptyIterator::rewind — The rewind() method

Descrierea

public void EmptyIterator::rewind ( void )

No operation, nothing to do.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

EmptyIterator::next
EmptyIterator::valid
EmptyIterator


The valid() method

EmptyIterator::rewind
FilesystemIterator
EmptyIterator
PHP Manual

EmptyIterator::valid

(PHP 5 >= 5.1.0, PHP 7)

EmptyIterator::valid — The valid() method

Descrierea

public bool EmptyIterator::valid ( void )

The EmptyIterator valid() method.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

FALSE

EmptyIterator::rewind
FilesystemIterator
EmptyIterator


The FilesystemIterator class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

The Filesystem iterator

Sinopsisul clasei

FilesystemIterator extends DirectoryIterator implements SeekableIterator {
/* Constante */
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 ;
/* Metode */
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 ] )
/* Metode mo?tenite */
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 )
}

Constante predefinite

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. Note that the path that is passed to the constructor is not modified.

Istoricul schimbarilor

Versiune | Descriere
5.3.1 | Added FilesystemIterator::FOLLOW_SYMLINKS

Cuprins

  • 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
Iteratori


Constructs a new filesystem iterator

FilesystemIterator
FilesystemIterator::current
FilesystemIterator
PHP Manual

FilesystemIterator::__construct

(PHP 5 >= 5.3.0, PHP 7)

FilesystemIterator::__construct — Constructs a new filesystem iterator

Descrierea

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.

Parametri

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()

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws an UnexpectedValueException if the path cannot be found.

Exemple

Example #1 FilesystemIterator::__construct() example

<?php
$it = new FilesystemIterator(dirname(__FILE__));
foreach ($it as $fileinfo) {
    echo $fileinfo->getFilename() . "\n";
}
?>

Exemplul de mai sus va afi?a:

apples.jpg
banana.jpg
example.php

A se vedea ?i

  • 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, PHP 7)

FilesystemIterator::current — The current file

Descrierea

public mixed FilesystemIterator::current ( void )

Get file information of the current element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The filename, file information, or $this depending on the set flags. See the FilesystemIterator constants.

Exemple

Example #1 FilesystemIterator::current() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new FilesystemIterator(__DIR__, FilesystemIterator::CURRENT_AS_PATHNAME);
foreach ($iterator as $fileinfo) {
    echo $iterator->current() . "\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

/www/examples/apple.jpg
/www/examples/banana.jpg
/www/examples/example.php

A se vedea ?i

  • 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, PHP 7)

FilesystemIterator::getFlags — Get the handling flags

Descrierea

public int FilesystemIterator::getFlags ( void )

Gets the handling flags, as set in FilesystemIterator::__construct() or FilesystemIterator::setFlags().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The integer value of the set flags.

A se vedea ?i

  • 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, PHP 7)

FilesystemIterator::key — Retrieve the key for the current file

Descrierea

public string FilesystemIterator::key ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the pathname or filename depending on the set flags. See the FilesystemIterator constants.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

apple.jpg
banana.jpg
example.php

A se vedea ?i

  • 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, PHP 7)

FilesystemIterator::next — Move to the next file

Descrierea

public void FilesystemIterator::next ( void )

Move to the next file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

apple.jpg
banana.jpg
example.php

A se vedea ?i

  • 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, PHP 7)

FilesystemIterator::rewind — Rewinds back to the beginning

Descrierea

public void FilesystemIterator::rewind ( void )

Rewinds the directory back to the start.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

apple.jpg
banana.jpg
apple.jpg

A se vedea ?i

  • 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, PHP 7)

FilesystemIterator::setFlags — Sets handling flags

Descrierea

public void FilesystemIterator::setFlags ([ int $flags ] )

Sets handling flags.

Parametri

flags

The handling flags to set. See the FilesystemIterator constants.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Key as Pathname:
/www/examples/apple.jpg
/www/examples/banana.jpg
/www/examples/example.php

Key as Filename:
apple.jpg
banana.jpg
example.php

A se vedea ?i

  • 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, PHP 7)

Introducere

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.

Sinopsisul clasei

abstract FilterIterator extends IteratorIterator implements OuterIterator {
/* Metode */
public abstract bool accept ( void )
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 )
}

Cuprins

  • 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
Iteratori


Check whether the current element of the iterator is acceptable

FilterIterator
FilterIterator::__construct
FilterIterator
PHP Manual

FilterIterator::accept

(PHP 5 >= 5.1.0, PHP 7)

FilterIterator::accept — Check whether the current element of the iterator is acceptable

Descrierea

public abstract bool FilterIterator::accept ( void )

Returns whether the current element of the iterator is acceptable through this filter.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the current element is acceptable, otherwise FALSE.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

FilterIterator::__construct — Construct a filterIterator

Descrierea

public FilterIterator::__construct ( Iterator $iterator )

Constructs a new FilterIterator, which consists of a passed in iterator with filters applied to it.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

iterator

The iterator that is being filtered.

Valorile întoarse

The FilterIterator.

A se vedea ?i

  • 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, PHP 7)

FilterIterator::current — Get the current element value

Descrierea

public mixed FilterIterator::current ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Get the current element value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current element value.

A se vedea ?i

  • 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, PHP 7)

FilterIterator::getInnerIterator — Get the inner iterator

Descrierea

public Iterator FilterIterator::getInnerIterator ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Get the inner iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

FilterIterator::key — Get the current key

Descrierea

public mixed FilterIterator::key ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Get the current key.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current key.

A se vedea ?i

  • 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, PHP 7)

FilterIterator::next — Move the iterator forward

Descrierea

public void FilterIterator::next ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Move the iterator forward.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

FilterIterator::rewind — Rewind the iterator

Descrierea

public void FilterIterator::rewind ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Rewind the iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

FilterIterator::valid — Check whether the current element is valid

Descrierea

public bool FilterIterator::valid ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Checks whether the current element is valid.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the current element is valid, otherwise FALSE

FilterIterator::rewind
GlobIterator
FilterIterator


The GlobIterator class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

Iterates through a file system in a similar fashion to glob().

Sinopsisul clasei

GlobIterator extends FilesystemIterator implements SeekableIterator , Countable {
/* Metode */
public __construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )
public int count ( void )
/* Metode mo?tenite */
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 ] )
}

Cuprins

  • GlobIterator::__construct — Construct a directory using glob
  • GlobIterator::count — Get the number of directories and files
FilterIterator::valid
GlobIterator::__construct
Iteratori


Construct a directory using glob

GlobIterator
GlobIterator::count
GlobIterator
PHP Manual

GlobIterator::__construct

(PHP 5 >= 5.3.0, PHP 7)

GlobIterator::__construct — Construct a directory using glob

Descrierea

public GlobIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )

Constructs a new directory iterator from a glob expression.

Parametri

path

The path of the directory.

flags

Option flags, the flags may be a bitmask of the FilesystemIterator constants.

Exemple

Example #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());
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Matched 2 item(s)
[1] php5ts.dll
[2] php_gd2.dll

A se vedea ?i

  • 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, PHP 7)

GlobIterator::count — Get the number of directories and files

Descrierea

public int GlobIterator::count ( void )

Gets the number of directories and files found by the glob expression.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The number of returned directories and files, as an integer.

Exemple

Example #1 GlobIterator::count() example

<?php
$iterator = new GlobIterator('*.xml');

printf("Matched %d item(s)\r\n", $iterator->count());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Matched 8 item(s)

A se vedea ?i

  • GlobIterator::__construct() - Construct a directory using glob
  • count() - Count all elements in an array, or something in an object
  • glob() - Find pathnames matching a pattern

GlobIterator::__construct
InfiniteIterator
GlobIterator


The InfiniteIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

The InfiniteIterator allows one to infinitely iterate over an iterator without having to manually rewind the iterator upon reaching its end.

Sinopsisul clasei

InfiniteIterator extends IteratorIterator implements OuterIterator {
/* Metode */
public __construct ( Iterator $iterator )
public void next ( void )
/* Metode mo?tenite */
public IteratorIterator::__construct ( Traversable $iterator )
public mixed IteratorIterator::current ( void )
public Traversable IteratorIterator::getInnerIterator ( void )
public scalar IteratorIterator::key ( void )
public void IteratorIterator::next ( void )
public void IteratorIterator::rewind ( void )
public bool IteratorIterator::valid ( void )
}

Cuprins

  • InfiniteIterator::__construct — Constructs an InfiniteIterator
  • InfiniteIterator::next — Moves the inner Iterator forward or rewinds it
GlobIterator::count
InfiniteIterator::__construct
Iteratori


Constructs an InfiniteIterator

InfiniteIterator
InfiniteIterator::next
InfiniteIterator
PHP Manual

InfiniteIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

InfiniteIterator::__construct — Constructs an InfiniteIterator

Descrierea

public InfiniteIterator::__construct ( Iterator $iterator )

Constructs an InfiniteIterator from an Iterator.

Parametri

iterator

The iterator to infinitely iterate over.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws an E_RECOVERABLE_ERROR if the iterator parameter is not an Iterator.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

cat
dog
cat
dog
cat
dog
cat

A se vedea ?i

  • 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, PHP 7)

InfiniteIterator::next — Moves the inner Iterator forward or rewinds it

Descrierea

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.

Nota:

Even an InfiniteIterator stops if its inner Iterator is empty.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • InfiniteIterator::__construct() - Constructs an InfiniteIterator

InfiniteIterator::__construct
IteratorIterator
InfiniteIterator


The IteratorIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

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.

Sinopsisul clasei

IteratorIterator implements OuterIterator {
/* Metode */
public __construct ( Traversable $iterator )
public mixed current ( void )
public Traversable getInnerIterator ( void )
public scalar key ( void )
public void next ( void )
public void rewind ( void )
public bool valid ( void )
}

Note

Nota:

This class permits access to methods of the inner iterator via the __call magic method.

Cuprins

  • 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
Iteratori


Create an iterator from anything that is traversable

IteratorIterator
IteratorIterator::current
IteratorIterator
PHP Manual

IteratorIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

IteratorIterator::__construct — Create an iterator from anything that is traversable

Descrierea

public IteratorIterator::__construct ( Traversable $iterator )

Creates an iterator from anything that is traversable.

Parametri

iterator

The traversable iterator.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Traversable

IteratorIterator
IteratorIterator::current
IteratorIterator


Get the current value

IteratorIterator::__construct
IteratorIterator::getInnerIterator
IteratorIterator
PHP Manual

IteratorIterator::current

(PHP 5 >= 5.1.0, PHP 7)

IteratorIterator::current — Get the current value

Descrierea

public mixed IteratorIterator::current ( void )

Get the value of the current element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The value of the current element.

A se vedea ?i

  • 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, PHP 7)

IteratorIterator::getInnerIterator — Get the inner iterator

Descrierea

public Traversable IteratorIterator::getInnerIterator ( void )

Get the inner iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The inner iterator as passed to IteratorIterator::__construct().

A se vedea ?i

  • 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, PHP 7)

IteratorIterator::key — Get the key of the current element

Descrierea

public scalar IteratorIterator::key ( void )

Get the key of the current element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The key of the current element.

A se vedea ?i

  • 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, PHP 7)

IteratorIterator::next — Forward to the next element

Descrierea

public void IteratorIterator::next ( void )

Forward to the next element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

IteratorIterator::rewind — Rewind to the first element

Descrierea

public void IteratorIterator::rewind ( void )

Rewinds to the first element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

IteratorIterator::valid — Checks if the iterator is valid

Descrierea

public bool IteratorIterator::valid ( void )

Checks if the iterator is valid.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the iterator is valid, otherwise FALSE

A se vedea ?i

  • 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, PHP 7)

Introducere

The LimitIterator class allows iteration over a limited subset of items in an Iterator.

Sinopsisul clasei

LimitIterator extends IteratorIterator implements OuterIterator {
/* Metode */
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 )
}

Exemple

Example #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);
}

?>

Exemplul de mai sus va afi?a:

string(5) "apple"
string(6) "banana"
string(6) "cherry"

string(6) "cherry"
string(6) "damson"
string(10) "elderberry"

Cuprins

  • 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
Iteratori


Construct a LimitIterator

LimitIterator
LimitIterator::current
LimitIterator
PHP Manual

LimitIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

LimitIterator::__construct — Construct a LimitIterator

Descrierea

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.

Parametri

iterator

The Iterator to limit.

offset

Optional offset of the limit.

count

Optional count of the limit.

Valorile întoarse

The new LimitIterator.

Erori/Excep?ii

Throws an OutOfRangeException if the offset is less than 0 or the count is less than -1.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

b
c
d

A se vedea ?i

  • LimitIterator examples

LimitIterator
LimitIterator::current
LimitIterator


Get current element

LimitIterator::__construct
LimitIterator::getInnerIterator
LimitIterator
PHP Manual

LimitIterator::current

(PHP 5 >= 5.1.0, PHP 7)

LimitIterator::current — Get current element

Descrierea

public mixed LimitIterator::current ( void )

Gets the current element of the inner Iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current element or NULL if there is none.

A se vedea ?i

  • 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, PHP 7)

LimitIterator::getInnerIterator — Get inner iterator

Descrierea

public Iterator LimitIterator::getInnerIterator ( void )

Gets the inner Iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The inner iterator passed to LimitIterator::__construct().

A se vedea ?i

  • 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, PHP 7)

LimitIterator::getPosition — Return the current position

Descrierea

public int LimitIterator::getPosition ( void )

Gets the current zero-based position of the inner Iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current position.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

2 cherry
3 damson
4 elderberry

A se vedea ?i

  • 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, PHP 7)

LimitIterator::key — Get current key

Descrierea

public mixed LimitIterator::key ( void )

Gets the key for the current item in the inner Iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the key for the current item.

A se vedea ?i

  • 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, PHP 7)

LimitIterator::next — Move the iterator forward

Descrierea

public void LimitIterator::next ( void )

Moves the iterator forward.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

LimitIterator::rewind — Rewind the iterator to the specified starting offset

Descrierea

public void LimitIterator::rewind ( void )

Rewinds the iterator to the starting offset specified in LimitIterator::__construct().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

LimitIterator::seek — Seek to the given position

Descrierea

public int LimitIterator::seek ( int $position )

Moves the iterator to the offset specified by position.

Parametri

position

The position to seek to.

Valorile întoarse

Returns the offset position after seeking.

Erori/Excep?ii

Throws an OutOfBoundsException if the position is outside of the limits specified in LimitIterator::__construct().

A se vedea ?i

  • 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, PHP 7)

LimitIterator::valid — Check whether the current element is valid

Descrierea

public bool LimitIterator::valid ( void )

Checks whether the current element is valid.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

Introducere

An Iterator that sequentially iterates over all attached iterators

Sinopsisul clasei

MultipleIterator implements Iterator {
/* Constante */
const integer MIT_NEED_ANY = 0 ;
const integer MIT_NEED_ALL = 1 ;
const integer MIT_KEYS_NUMERIC = 0 ;
const integer MIT_KEYS_ASSOC = 2 ;
/* Metode */
public __construct ([ int $flags = MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC ] )
public void attachIterator ( Iterator $iterator [, string $infos ] )
public bool containsIterator ( Iterator $iterator )
public int countIterators ( void )
public array current ( void )
public void detachIterator ( Iterator $iterator )
public int getFlags ( void )
public array key ( void )
public void next ( void )
public void rewind ( void )
public void setFlags ( int $flags )
public bool valid ( void )
}

Constante predefinite

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.

Cuprins

  • 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
Iteratori


Attaches iterator information

MultipleIterator
MultipleIterator::__construct
MultipleIterator
PHP Manual

MultipleIterator::attachIterator

(PHP 5 >= 5.3.0, PHP 7)

MultipleIterator::attachIterator — Attaches iterator information

Descrierea

public void MultipleIterator::attachIterator ( Iterator $iterator [, string $infos ] )

Attaches iterator information.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

iterator

The new iterator to attach.

infos

The associative information for the Iterator, which must be an integer, a string, or NULL.

Valorile întoarse

Description...

Erori/Excep?ii

An IllegalValueException if the iterator parameter is invalid, or if infos is already associated information.

A se vedea ?i

  • 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, PHP 7)

MultipleIterator::__construct — Constructs a new MultipleIterator

Descrierea

public MultipleIterator::__construct ([ int $flags = MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC ] )

Construct a new MultipleIterator.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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_ASSOC

Array
(
    [person] => John
    [role] => Developer
)
Array
(
    [person] => Jane
    [role] => Scrum Master
)
Array
(
    [person] => Jack
    [role] => Project Owner
)
Array
(
    [person] => Judy
    [role] =>
)

A se vedea ?i

  • 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, PHP 7)

MultipleIterator::containsIterator — Checks if an iterator is attached

Descrierea

public bool MultipleIterator::containsIterator ( Iterator $iterator )

Checks if an iterator is attached or not.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

iterator

The iterator to check.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

MultipleIterator::countIterators — Gets the number of attached iterator instances

Descrierea

public int MultipleIterator::countIterators ( void )

Gets the number of attached iterator instances.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The number of attached iterator instances (as an integer).

A se vedea ?i

  • 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, PHP 7)

MultipleIterator::current — Gets the registered iterator instances

Descrierea

public array MultipleIterator::current ( void )

Get the registered iterator instances current() result.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array containing the current values of each attached iterator, or FALSE if no iterators are attached.

Erori/Excep?ii

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.

A se vedea ?i

  • 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, PHP 7)

MultipleIterator::detachIterator — Detaches an iterator

Descrierea

public void MultipleIterator::detachIterator ( Iterator $iterator )

Detaches an iterator.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

iterator

The iterator to detach.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

MultipleIterator::getFlags — Gets the flag information

Descrierea

public int MultipleIterator::getFlags ( void )

Gets information about the flags.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Information about the flags, as an integer.

A se vedea ?i

  • 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, PHP 7)

MultipleIterator::key — Gets the registered iterator instances

Descrierea

public array MultipleIterator::key ( void )

Get the registered iterator instances key() result.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array of all registered iterator instances, or FALSE if no sub iterator is attached.

Erori/Excep?ii

A LogicException if mode MIT_NEED_ALL is set, and at least one attached iterator is not valid.

Calling this method from foreach triggers warning "Illegal type returned".

A se vedea ?i

  • 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, PHP 7)

MultipleIterator::next — Moves all attached iterator instances forward

Descrierea

public void MultipleIterator::next ( void )

Moves all attached iterator instances forward.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

MultipleIterator::rewind — Rewinds all attached iterator instances

Descrierea

public void MultipleIterator::rewind ( void )

Rewinds all attached iterator instances.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

MultipleIterator::setFlags — Sets flags

Descrierea

public void MultipleIterator::setFlags ( int $flags )

Sets flags.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

flags

The flags to set, according to the Flag Constants

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

MultipleIterator::valid — Checks the validity of sub iterators

Descrierea

public bool MultipleIterator::valid ( void )

Checks the validity of sub iterators.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if one or all sub iterators are valid depending on flags, otherwise FALSE

A se vedea ?i

  • MultipleIterator::__construct() - Constructs a new MultipleIterator

MultipleIterator::setFlags
NoRewindIterator
MultipleIterator


The NoRewindIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

This iterator cannot be rewound.

Sinopsisul clasei

NoRewindIterator extends IteratorIterator {
/* Metode */
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 )
/* Metode mo?tenite */
public IteratorIterator::__construct ( Traversable $iterator )
public mixed IteratorIterator::current ( void )
public Traversable IteratorIterator::getInnerIterator ( void )
public scalar IteratorIterator::key ( void )
public void IteratorIterator::next ( void )
public void IteratorIterator::rewind ( void )
public bool IteratorIterator::valid ( void )
}

Cuprins

  • 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
Iteratori


Construct a NoRewindIterator

NoRewindIterator
NoRewindIterator::current
NoRewindIterator
PHP Manual

NoRewindIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

NoRewindIterator::__construct — Construct a NoRewindIterator

Descrierea

public NoRewindIterator::__construct ( Iterator $iterator )

Constructs a NoRewindIterator.

Parametri

iterator

The iterator being used.

Valorile întoarse

A NoRewindIterator() based on the passed in iterator.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Fruit A:
apple
banana
cranberry
Fruit B:

A se vedea ?i

  • 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, PHP 7)

NoRewindIterator::current — Get the current value

Descrierea

public mixed NoRewindIterator::current ( void )

Gets the current value.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current value.

A se vedea ?i

  • 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, PHP 7)

NoRewindIterator::getInnerIterator — Get the inner iterator

Descrierea

public iterator NoRewindIterator::getInnerIterator ( void )

Gets the inner iterator, that was passed in to NoRewindIterator.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The inner iterator, as passed to NoRewindIterator::__construct().

A se vedea ?i

  • 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, PHP 7)

NoRewindIterator::key — Get the current key

Descrierea

public mixed NoRewindIterator::key ( void )

Gets the current key.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current key.

A se vedea ?i

  • 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, PHP 7)

NoRewindIterator::next — Forward to the next element

Descrierea

public void NoRewindIterator::next ( void )

Forwards to the next element.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

NoRewindIterator::rewind — Prevents the rewind operation on the inner iterator.

Descrierea

public void NoRewindIterator::rewind ( void )

Prevents the rewind operation on the inner iterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

lemon
orange

NoRewindIterator::next
NoRewindIterator::valid
NoRewindIterator


Validates the iterator

NoRewindIterator::rewind
ParentIterator
NoRewindIterator
PHP Manual

NoRewindIterator::valid

(PHP 5 >= 5.1.0, PHP 7)

NoRewindIterator::valid — Validates the iterator

Descrierea

public bool NoRewindIterator::valid ( void )

Checks whether the iterator is valid.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • NoRewindIterator::getInnerIterator() - Get the inner iterator

NoRewindIterator::rewind
ParentIterator
NoRewindIterator


The ParentIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

This extended FilterIterator allows a recursive iteration using RecursiveIteratorIterator that only shows those elements which have children.

Sinopsisul clasei

ParentIterator extends RecursiveFilterIterator implements RecursiveIterator , OuterIterator {
/* Metode */
public bool accept ( void )
public __construct ( RecursiveIterator $iterator )
public ParentIterator getChildren ( void )
public bool hasChildren ( void )
public void next ( void )
public void rewind ( void )
}

Cuprins

  • 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
Iteratori


Determines acceptability

ParentIterator
ParentIterator::__construct
ParentIterator
PHP Manual

ParentIterator::accept

(PHP 5 >= 5.1.0, PHP 7)

ParentIterator::accept — Determines acceptability

Descrierea

public bool ParentIterator::accept ( void )

Determines if the current element has children.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the current element is acceptable, otherwise FALSE.

A se vedea ?i

  • 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, PHP 7)

ParentIterator::__construct — Constructs a ParentIterator

Descrierea

public ParentIterator::__construct ( RecursiveIterator $iterator )

Constructs a ParentIterator on an iterator.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

iterator

The iterator being constructed upon.

Valorile întoarse

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, PHP 7)

ParentIterator::getChildren — Return the inner iterator's children contained in a ParentIterator

Descrierea

public ParentIterator ParentIterator::getChildren ( void )

Get the inner iterator's children contained in a ParentIterator.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

ParentIterator::hasChildren — Check whether the inner iterator's current element has children

Descrierea

public bool ParentIterator::hasChildren ( void )

Check whether the inner iterator's current element has children.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ParentIterator::getChildren
ParentIterator::next
ParentIterator


Move the iterator forward

ParentIterator::hasChildren
ParentIterator::rewind
ParentIterator
PHP Manual

ParentIterator::next

(PHP 5 >= 5.1.0, PHP 7)

ParentIterator::next — Move the iterator forward

Descrierea

public void ParentIterator::next ( void )

Moves the iterator forward.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

ParentIterator::hasChildren
ParentIterator::rewind
ParentIterator


Rewind the iterator

ParentIterator::next
RecursiveArrayIterator
ParentIterator
PHP Manual

ParentIterator::rewind

(PHP 5 >= 5.1.0, PHP 7)

ParentIterator::rewind — Rewind the iterator

Descrierea

public void ParentIterator::rewind ( void )

Rewinds the iterator.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

ParentIterator::next
RecursiveArrayIterator
ParentIterator


The RecursiveArrayIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

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.

Sinopsisul clasei

RecursiveArrayIterator extends ArrayIterator implements RecursiveIterator {
/* Constante */
const integer CHILD_ARRAYS_ONLY = 4 ;
/* Metode */
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 = array() [, int $flags = 0 ]] )
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 )
}

Constante predefinite

RecursiveArrayIterator Flags

RecursiveArrayIterator::CHILD_ARRAYS_ONLY

Treat only arrays (not objects) as having children for recursive iteration.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | CHILD_ARRAYS_ONLY flag was added.

Cuprins

  • 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
Iteratori


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, PHP 7)

RecursiveArrayIterator::getChildren — Returns an iterator for the current entry if it is an array or an object.

Descrierea

public RecursiveArrayIterator RecursiveArrayIterator::getChildren ( void )

Returns an iterator for the current iterator entry.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An iterator for the current entry, if it is an array or object.

Erori/Excep?ii

An InvalidArgumentException will be thrown if the current entry does not contain an array or an object.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a:

No children.
No children.
a : apple
p : pear

A se vedea ?i

  • 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, PHP 7)

RecursiveArrayIterator::hasChildren — Returns whether current entry is an array or an object.

Descrierea

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().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the current entry is an array or an object, otherwise FALSE is returned.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a:

No children.
No children.
a : apple
p : pear

A se vedea ?i

  • 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, PHP 7)

Introducere

...

Sinopsisul clasei

RecursiveCachingIterator extends CachingIterator implements Countable , ArrayAccess , OuterIterator , RecursiveIterator {
/* Metode */
public __construct ( Iterator $iterator [, string $flags = self::CALL_TOSTRING ] )
public RecursiveCachingIterator getChildren ( void )
public bool hasChildren ( void )
/* Inherits */
public CachingIterator::__construct ( Iterator $iterator [, int $flags = self::CALL_TOSTRING ] )
public int CachingIterator::count ( void )
public void CachingIterator::current ( void )
public array CachingIterator::getCache ( void )
public int CachingIterator::getFlags ( void )
public Iterator CachingIterator::getInnerIterator ( void )
public void CachingIterator::hasNext ( void )
public scalar 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 ( int $flags )
public void CachingIterator::__toString ( void )
public void CachingIterator::valid ( void )
}

Cuprins

  • 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
Iteratori


Construct

RecursiveCachingIterator
RecursiveCachingIterator::getChildren
RecursiveCachingIterator
PHP Manual

RecursiveCachingIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

RecursiveCachingIterator::__construct — Construct

Descrierea

public RecursiveCachingIterator::__construct ( Iterator $iterator [, string $flags = self::CALL_TOSTRING ] )

Constructs a new RecursiveCachingIterator, which consists of a passed in iterator.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

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.

Valorile întoarse

The RecursiveCachingIterator.

A se vedea ?i

  • 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, PHP 7)

RecursiveCachingIterator::getChildren — Return the inner iterator's children as a RecursiveCachingIterator

Descrierea

public RecursiveCachingIterator RecursiveCachingIterator::getChildren ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveCachingIterator::hasChildren — Check whether the current element of the inner iterator has children

Descrierea

public bool RecursiveCachingIterator::hasChildren ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the inner iterator has children, otherwise FALSE

RecursiveCachingIterator::getChildren
RecursiveCallbackFilterIterator
RecursiveCachingIterator


The RecursiveCallbackFilterIterator class

(PHP 5 >= 5.4.0, PHP 7)

Introducere

Sinopsisul clasei

RecursiveCallbackFilterIterator extends CallbackFilterIterator implements OuterIterator , RecursiveIterator {
/* Metode */
public __construct ( RecursiveIterator $iterator , string $callback )
public RecursiveCallbackFilterIterator getChildren ( void )
public bool hasChildren ( void )
/* Metode mo?tenite */
public string CallbackFilterIterator::accept ( void )
}

Exemple

The callback should accept up to three arguments: the current item, the current key and the iterator, respectively.

Example #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.

Example #2 Recursive callback basic example

<?php

$dir = new RecursiveDirectoryIterator(__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;
}

?>

Cuprins

  • 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
Iteratori


Create a RecursiveCallbackFilterIterator from a RecursiveIterator

RecursiveCallbackFilterIterator
RecursiveCallbackFilterIterator::getChildren
RecursiveCallbackFilterIterator
PHP Manual

RecursiveCallbackFilterIterator::__construct

(PHP 5 >= 5.4.0, PHP 7)

RecursiveCallbackFilterIterator::__construct — Create a RecursiveCallbackFilterIterator from a RecursiveIterator

Descrierea

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.

Parametri

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 callable value.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

RecursiveCallbackFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a RecursiveCallbackFilterIterator containing the children.

A se vedea ?i

  • 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, PHP 7)

RecursiveCallbackFilterIterator::hasChildren — Check whether the inner iterator's current element has children

Descrierea

public bool RecursiveCallbackFilterIterator::hasChildren ( void )

Returns TRUE if the current element has children, FALSE otherwise.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the current element has children, FALSE otherwise.

Exemple

Example #1 RecursiveCallbackFilterIterator::hasChildren() basic usage

<?php

$dir = new RecursiveDirectoryIterator(__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;
});

?>

A se vedea ?i

  • 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, PHP 7)

Introducere

The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories.

Sinopsisul clasei

RecursiveDirectoryIterator extends FilesystemIterator implements SeekableIterator , RecursiveIterator {
/* Metode */
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 = false ] )
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 ] )
}

Istoricul schimbarilor

Versiune | Descriere
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

Cuprins

  • 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
Iteratori


Constructs a RecursiveDirectoryIterator

RecursiveDirectoryIterator
RecursiveDirectoryIterator::getChildren
RecursiveDirectoryIterator
PHP Manual

RecursiveDirectoryIterator::__construct

(PHP 5 >= 5.1.2, PHP 7)

RecursiveDirectoryIterator::__construct — Constructs a RecursiveDirectoryIterator

Descrierea

public RecursiveDirectoryIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )

Constructs a RecursiveDirectoryIterator() for the provided path.

Parametri

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().

Valorile întoarse

Returns the newly created RecursiveDirectoryIterator.

Erori/Excep?ii

Throws an UnexpectedValueException if the path cannot be found or is not a directory.

Exemple

Example #1 RecursiveDirectoryIterator example

<?php

$directory = '/tmp';

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

$it->rewind();
while($it->valid()) {

    if (!$it->isDot()) {
        echo 'SubPathName: ' . $it->getSubPathName() . "\n";
        echo 'SubPath:     ' . $it->getSubPath() . "\n";
        echo 'Key:         ' . $it->key() . "\n\n";
    }

    $it->next();
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • 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, PHP 7)

RecursiveDirectoryIterator::getChildren — Returns an iterator for the current entry if it is a directory

Descrierea

public mixed RecursiveDirectoryIterator::getChildren ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveDirectoryIterator::getSubPath — Get sub path

Descrierea

public string RecursiveDirectoryIterator::getSubPath ( void )

Gets the sub path.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The sub path (sub directory).

A se vedea ?i

  • 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, PHP 7)

RecursiveDirectoryIterator::getSubPathname — Get sub path and name

Descrierea

public string RecursiveDirectoryIterator::getSubPathname ( void )

Gets the sub path and filename.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The sub path (sub directory) and filename.

A se vedea ?i

  • 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, PHP 7)

RecursiveDirectoryIterator::hasChildren — Returns whether current entry is a directory and not '.' or '..'

Descrierea

public bool RecursiveDirectoryIterator::hasChildren ([ bool $allow_links = false ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

allow_links

Valorile întoarse

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, PHP 7)

RecursiveDirectoryIterator::key — Return path and filename of current dir entry

Descrierea

public string RecursiveDirectoryIterator::key ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveDirectoryIterator::next — Move to next entry

Descrierea

public void RecursiveDirectoryIterator::next ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveDirectoryIterator::key
RecursiveDirectoryIterator::rewind
RecursiveDirectoryIterator


Rewind dir back to the start

RecursiveDirectoryIterator::next
RecursiveFilterIterator
RecursiveDirectoryIterator
PHP Manual

RecursiveDirectoryIterator::rewind

(PHP 5, PHP 7)

RecursiveDirectoryIterator::rewind — Rewind dir back to the start

Descrierea

public void RecursiveDirectoryIterator::rewind ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveDirectoryIterator::next
RecursiveFilterIterator
RecursiveDirectoryIterator


The RecursiveFilterIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

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.

Sinopsisul clasei

abstract RecursiveFilterIterator extends FilterIterator implements OuterIterator , RecursiveIterator {
/* Metode */
public __construct ( RecursiveIterator $iterator )
public RecursiveFilterIterator getChildren ( void )
public bool hasChildren ( void )
/* Metode mo?tenite */
public abstract bool FilterIterator::accept ( void )
public FilterIterator::__construct ( Iterator $iterator )
public mixed FilterIterator::current ( void )
public Iterator FilterIterator::getInnerIterator ( void )
public mixed FilterIterator::key ( void )
public void FilterIterator::next ( void )
public void FilterIterator::rewind ( void )
public bool FilterIterator::valid ( void )
}

Cuprins

  • 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
Iteratori


Create a RecursiveFilterIterator from a RecursiveIterator

RecursiveFilterIterator
RecursiveFilterIterator::getChildren
RecursiveFilterIterator
PHP Manual

RecursiveFilterIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

RecursiveFilterIterator::__construct — Create a RecursiveFilterIterator from a RecursiveIterator

Descrierea

public RecursiveFilterIterator::__construct ( RecursiveIterator $iterator )

Create a RecursiveFilterIterator from a RecursiveIterator.

Parametri

iterator

The RecursiveIterator to be filtered.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);
    }
}

$array    = 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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

test1
test3
test4
test5

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

test1
test3
test4
test5

A se vedea ?i

  • 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, PHP 7)

RecursiveFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveFilterIterator

Descrierea

public RecursiveFilterIterator RecursiveFilterIterator::getChildren ( void )

Return the inner iterator's children contained in a RecursiveFilterIterator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a RecursiveFilterIterator containing the inner iterator's children.

A se vedea ?i

  • 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, PHP 7)

RecursiveFilterIterator::hasChildren — Check whether the inner iterator's current element has children

Descrierea

public bool RecursiveFilterIterator::hasChildren ( void )

Check whether the inner iterator's current element has children.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the inner iterator has children, otherwise FALSE

A se vedea ?i

  • 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, PHP 7)

Introducere

Can be used to iterate through recursive iterators.

Sinopsisul clasei

RecursiveIteratorIterator implements OuterIterator {
/* Constants */
const integer LEAVES_ONLY = 0 ;
const integer SELF_FIRST = 1 ;
const integer CHILD_FIRST = 2 ;
const integer CATCH_GET_CHILD = 16 ;
/* Metode */
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 ([ int $level ] )
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 )
/* Metode mo?tenite */
public Iterator OuterIterator::getInnerIterator ( void )
}

Constante predefinite

RecursiveIteratorIterator::LEAVES_ONLY

RecursiveIteratorIterator::SELF_FIRST

RecursiveIteratorIterator::CHILD_FIRST

RecursiveIteratorIterator::CATCH_GET_CHILD

Cuprins

  • 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
Iteratori


Begin children

RecursiveIteratorIterator
RecursiveIteratorIterator::beginIteration
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::beginChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::beginChildren — Begin children

Descrierea

public void RecursiveIteratorIterator::beginChildren ( void )

Is called after calling RecursiveIteratorIterator::getChildren(), and its associated RecursiveIteratorIterator::rewind().

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveIteratorIterator
RecursiveIteratorIterator::beginIteration
RecursiveIteratorIterator


Begin Iteration

RecursiveIteratorIterator::beginChildren
RecursiveIteratorIterator::callGetChildren
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::beginIteration

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::beginIteration — Begin Iteration

Descrierea

public void RecursiveIteratorIterator::beginIteration ( void )

Called when iteration begins (after the first RecursiveIteratorIterator::rewind() call.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveIteratorIterator::beginChildren
RecursiveIteratorIterator::callGetChildren
RecursiveIteratorIterator


Get children

RecursiveIteratorIterator::beginIteration
RecursiveIteratorIterator::callHasChildren
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::callGetChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::callGetChildren — Get children

Descrierea

public RecursiveIterator RecursiveIteratorIterator::callGetChildren ( void )

Get children of the current element.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A RecursiveIterator().

RecursiveIteratorIterator::beginIteration
RecursiveIteratorIterator::callHasChildren
RecursiveIteratorIterator


Has children

RecursiveIteratorIterator::callGetChildren
RecursiveIteratorIterator::__construct
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::callHasChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::callHasChildren — Has children

Descrierea

public bool RecursiveIteratorIterator::callHasChildren ( void )

Called for each element to test whether it has children.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveIteratorIterator::__construct — Construct a RecursiveIteratorIterator

Descrierea

public RecursiveIteratorIterator::__construct ( Traversable $iterator [, int $mode = RecursiveIteratorIterator::LEAVES_ONLY [, int $flags = 0 ]] )

Creates a RecursiveIteratorIterator from a RecursiveIterator.

Parametri

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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, PHP 7)

RecursiveIteratorIterator::current — Access the current element value

Descrierea

public mixed RecursiveIteratorIterator::current ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveIteratorIterator::endChildren — End children

Descrierea

public void RecursiveIteratorIterator::endChildren ( void )

Called when end recursing one level.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveIteratorIterator::current
RecursiveIteratorIterator::endIteration
RecursiveIteratorIterator


End Iteration

RecursiveIteratorIterator::endChildren
RecursiveIteratorIterator::getDepth
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::endIteration

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::endIteration — End Iteration

Descrierea

public void RecursiveIteratorIterator::endIteration ( void )

Called when the iteration ends (when RecursiveIteratorIterator::valid() first returns FALSE.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveIteratorIterator::endChildren
RecursiveIteratorIterator::getDepth
RecursiveIteratorIterator


Get the current depth of the recursive iteration

RecursiveIteratorIterator::endIteration
RecursiveIteratorIterator::getInnerIterator
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::getDepth

(PHP 5, PHP 7)

RecursiveIteratorIterator::getDepth — Get the current depth of the recursive iteration

Descrierea

public int RecursiveIteratorIterator::getDepth ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveIteratorIterator::getInnerIterator — Get inner iterator

Descrierea

public iterator RecursiveIteratorIterator::getInnerIterator ( void )

Gets the current active sub iterator.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveIteratorIterator::getMaxDepth — Get max depth

Descrierea

public mixed RecursiveIteratorIterator::getMaxDepth ( void )

Gets the maximum allowable depth.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The maximum accepted depth, or FALSE if any depth is allowed.

A se vedea ?i

  • 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, PHP 7)

RecursiveIteratorIterator::getSubIterator — The current active sub iterator

Descrierea

public RecursiveIterator RecursiveIteratorIterator::getSubIterator ([ int $level ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

level

Valorile întoarse

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, PHP 7)

RecursiveIteratorIterator::key — Access the current key

Descrierea

public mixed RecursiveIteratorIterator::key ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveIteratorIterator::next — Move forward to the next element

Descrierea

public void RecursiveIteratorIterator::next ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveIteratorIterator::key
RecursiveIteratorIterator::nextElement
RecursiveIteratorIterator


Next element

RecursiveIteratorIterator::next
RecursiveIteratorIterator::rewind
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::nextElement

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::nextElement — Next element

Descrierea

public void RecursiveIteratorIterator::nextElement ( void )

Called when the next element is available.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

RecursiveIteratorIterator::rewind — Rewind the iterator to the first element of the top level inner iterator

Descrierea

public void RecursiveIteratorIterator::rewind ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveIteratorIterator::nextElement
RecursiveIteratorIterator::setMaxDepth
RecursiveIteratorIterator


Set max depth

RecursiveIteratorIterator::rewind
RecursiveIteratorIterator::valid
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::setMaxDepth

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::setMaxDepth — Set max depth

Descrierea

public void RecursiveIteratorIterator::setMaxDepth ([ string $max_depth = -1 ] )

Set the maximum allowed depth.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

max_depth

The maximum allowed depth. -1 is used for any depth.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

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, PHP 7)

RecursiveIteratorIterator::valid — Check whether the current position is valid

Descrierea

public bool RecursiveIteratorIterator::valid ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the current position is valid, otherwise FALSE

RecursiveIteratorIterator::setMaxDepth
RecursiveRegexIterator
RecursiveIteratorIterator


The RecursiveRegexIterator class

(PHP 5 >= 5.2.0, PHP 7)

Introducere

This recursive iterator can filter another recursive iterator via a regular expression.

Sinopsisul clasei

RecursiveRegexIterator extends RegexIterator implements RecursiveIterator {
/* Metode */
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 )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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
Iteratori


Creates a new RecursiveRegexIterator.

RecursiveRegexIterator
RecursiveRegexIterator::getChildren
RecursiveRegexIterator
PHP Manual

RecursiveRegexIterator::__construct

(PHP 5 >= 5.2.0, PHP 7)

RecursiveRegexIterator::__construct — Creates a new RecursiveRegexIterator.

Descrierea

public RecursiveRegexIterator::__construct ( RecursiveIterator $iterator , string $regex [, int $mode = self::MATCH [, int $flags = 0 [, int $preg_flags = 0 ]]] )

Creates a new regular expression iterator.

Parametri

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().

Exemple

Example #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";
    }

}
?>

Exemplul de mai sus va afi?a ceva similar cu:

No children
Children: test4 test5

A se vedea ?i

  • 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, PHP 7)

RecursiveRegexIterator::getChildren — Returns an iterator for the current entry.

Descrierea

public RecursiveRegexIterator RecursiveRegexIterator::getChildren ( void )

Returns an iterator for the current iterator entry.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An iterator for the current entry, if it can be iterated over by the inner iterator.

Erori/Excep?ii

An InvalidArgumentException will be thrown if the current entry does not contain a value that can be iterated over by the inner iterator.

Exemple

Example #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";
    }

}
?>

Exemplul de mai sus va afi?a:

No children
Children: test4 test5

A se vedea ?i

  • 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, PHP 7)

RecursiveRegexIterator::hasChildren — Returns whether an iterator can be obtained for the current entry.

Descrierea

public bool RecursiveRegexIterator::hasChildren ( void )

Returns whether an iterator can be obtained for the current entry. This iterator can be obtained via RecursiveRegexIterator::getChildren().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if an iterator can be obtained for the current entry, otherwise returns FALSE.

Exemple

Example #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());
}
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

A se vedea ?i

  • RecursiveRegexIterator::getChildren() - Returns an iterator for the current entry.

RecursiveRegexIterator::getChildren
RecursiveTreeIterator
RecursiveRegexIterator


The RecursiveTreeIterator class

(PHP 5 >= 5.3.0, PHP 7)

Introducere

Allows iterating over a RecursiveIterator to generate an ASCII graphic tree.

Sinopsisul clasei

RecursiveTreeIterator extends RecursiveIteratorIterator implements OuterIterator {
/* Constante */
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 ;
/* Metode */
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 )
/* Metode mo?tenite */
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 ([ int $level ] )
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 )
}

Constante predefinite

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

Cuprins

  • 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
Iteratori


Begin children

RecursiveTreeIterator
RecursiveTreeIterator::beginIteration
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::beginChildren

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::beginChildren — Begin children

Descrierea

public void RecursiveTreeIterator::beginChildren ( void )

Called when recursing one level down.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveTreeIterator
RecursiveTreeIterator::beginIteration
RecursiveTreeIterator


Begin iteration

RecursiveTreeIterator::beginChildren
RecursiveTreeIterator::callGetChildren
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::beginIteration

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::beginIteration — Begin iteration

Descrierea

public RecursiveIterator RecursiveTreeIterator::beginIteration ( void )

Called when iteration begins (after the first RecursiveTreeIterator::rewind() call).

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A RecursiveIterator.

RecursiveTreeIterator::beginChildren
RecursiveTreeIterator::callGetChildren
RecursiveTreeIterator


Get children

RecursiveTreeIterator::beginIteration
RecursiveTreeIterator::callHasChildren
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::callGetChildren

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::callGetChildren — Get children

Descrierea

public RecursiveIterator RecursiveTreeIterator::callGetChildren ( void )

Gets children of the current element.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A RecursiveIterator.

RecursiveTreeIterator::beginIteration
RecursiveTreeIterator::callHasChildren
RecursiveTreeIterator


Has children

RecursiveTreeIterator::callGetChildren
RecursiveTreeIterator::__construct
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::callHasChildren

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::callHasChildren — Has children

Descrierea

public bool RecursiveTreeIterator::callHasChildren ( void )

Called for each element to test whether it has children.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveTreeIterator::__construct — Construct a RecursiveTreeIterator

Descrierea

 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.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveTreeIterator::callHasChildren
RecursiveTreeIterator::current
RecursiveTreeIterator


Get current element

RecursiveTreeIterator::__construct
RecursiveTreeIterator::endChildren
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::current

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::current — Get current element

Descrierea

public string RecursiveTreeIterator::current ( void )

Gets the current element prefixed and postfixed.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveTreeIterator::endChildren — End children

Descrierea

public void RecursiveTreeIterator::endChildren ( void )

Called when end recursing one level.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveTreeIterator::current
RecursiveTreeIterator::endIteration
RecursiveTreeIterator


End iteration

RecursiveTreeIterator::endChildren
RecursiveTreeIterator::getEntry
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::endIteration

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::endIteration — End iteration

Descrierea

public void RecursiveTreeIterator::endIteration ( void )

Called when the iteration ends (when RecursiveTreeIterator::valid() first returns FALSE)

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveTreeIterator::endChildren
RecursiveTreeIterator::getEntry
RecursiveTreeIterator


Get current entry

RecursiveTreeIterator::endIteration
RecursiveTreeIterator::getPostfix
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::getEntry

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::getEntry — Get current entry

Descrierea

public string RecursiveTreeIterator::getEntry ( void )

Gets the part of the tree built for the current element.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveTreeIterator::getPostfix — Get the postfix

Descrierea

public void RecursiveTreeIterator::getPostfix ( void )

Gets the string to place after the current element.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveTreeIterator::getPrefix — Get the prefix

Descrierea

public string RecursiveTreeIterator::getPrefix ( void )

Gets the string to place in front of current element

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveTreeIterator::key — Get the key of the current element

Descrierea

public string RecursiveTreeIterator::key ( void )

Gets the current key prefixed and postfixed.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

RecursiveTreeIterator::next — Move to next element

Descrierea

public void RecursiveTreeIterator::next ( void )

Moves forward to the next element.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveTreeIterator::key
RecursiveTreeIterator::nextElement
RecursiveTreeIterator


Next element

RecursiveTreeIterator::next
RecursiveTreeIterator::rewind
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::nextElement

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::nextElement — Next element

Descrierea

public void RecursiveTreeIterator::nextElement ( void )

Called when the next element is available.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveTreeIterator::next
RecursiveTreeIterator::rewind
RecursiveTreeIterator


Rewind iterator

RecursiveTreeIterator::nextElement
RecursiveTreeIterator::setPrefixPart
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::rewind

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::rewind — Rewind iterator

Descrierea

public void RecursiveTreeIterator::rewind ( void )

Rewinds the iterator to the first element of the top level inner iterator.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

RecursiveTreeIterator::setPrefixPart — Set a part of the prefix

Descrierea

public void RecursiveTreeIterator::setPrefixPart ( int $part , string $value )

Sets a part of the prefix used in the graphic tree.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

part

One of the RecursiveTreeIterator::PREFIX_* constants.

value

The value to assign to the part of the prefix specified in part.

Valorile întoarse

Nu este întoarsa nici o valoare.

RecursiveTreeIterator::rewind
RecursiveTreeIterator::valid
RecursiveTreeIterator


Check validity

RecursiveTreeIterator::setPrefixPart
RegexIterator
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::valid

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::valid — Check validity

Descrierea

public bool RecursiveTreeIterator::valid ( void )

Check whether the current position is valid.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the current position is valid, otherwise FALSE

RecursiveTreeIterator::setPrefixPart
RegexIterator
RecursiveTreeIterator


The RegexIterator class

(PHP 5 >= 5.2.0, PHP 7)

Introducere

This iterator can be used to filter another iterator based on a regular expression.

Sinopsisul clasei

RegexIterator extends FilterIterator {
/* Constante */
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 ;
/* Metode */
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 )
/* Metode mo?tenite */
public abstract bool FilterIterator::accept ( void )
public FilterIterator::__construct ( Iterator $iterator )
public mixed FilterIterator::current ( void )
public Iterator FilterIterator::getInnerIterator ( void )
public mixed FilterIterator::key ( void )
public void FilterIterator::next ( void )
public void FilterIterator::rewind ( void )
public bool FilterIterator::valid ( void )
}

Constante predefinite

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.

Cuprins

  • 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
Iteratori


Get accept status

RegexIterator
RegexIterator::__construct
RegexIterator
PHP Manual

RegexIterator::accept

(PHP 5 >= 5.2.0, PHP 7)

RegexIterator::accept — Get accept status

Descrierea

public bool RegexIterator::accept ( void )

Matches (string) RegexIterator::current()
(or RegexIterator::key() if the
RegexIterator::USE_KEY flag is set)
against the regular expression.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if a match, FALSE otherwise.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

Bob
Charlie
David

A se vedea ?i

  • 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, PHP 7)

RegexIterator::__construct — Create a new RegexIterator

Descrierea

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.

Parametri

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().

Erori/Excep?ii

Throws an InvalidArgumentException if the regex argument is invalid.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

test 1
test 123

A se vedea ?i

  • 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, PHP 7)

RegexIterator::getFlags — Get flags

Descrierea

public int RegexIterator::getFlags ( void )

Returns the flags, see RegexIterator::setFlags() for a list of available flags.

Valorile întoarse

Returns the set flags.

Exemple

Example #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.';
}
?>

Exemplul de mai sus va afi?a:

Filtering based on the array keys.

A se vedea ?i

  • 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, PHP 7)

RegexIterator::getMode — Returns operation mode.

Descrierea

public int RegexIterator::getMode ( void )

Returns the operation mode, see RegexIterator::setMode() for the list of operation modes.

Valorile întoarse

Returns the operation mode.

Exemple

Example #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.';
}
?>

Exemplul de mai sus va afi?a:

Getting the match for each item.

A se vedea ?i

  • 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, PHP 7)

RegexIterator::getPregFlags — Returns the regular expression flags.

Descrierea

public int RegexIterator::getPregFlags ( void )

Returns the regular expression flags, see RegexIterator::__construct() for the list of flags.

Valorile întoarse

Returns a bitmask of the regular expression flags.

Exemple

Example #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';
}

?>

Exemplul de mai sus va afi?a:

Ignoring empty pieces

A se vedea ?i

  • 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

(PHP 5 >= 5.4.0, PHP 7)

RegexIterator::getRegex — Returns current regular expression

Descrierea

public string RegexIterator::getRegex ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

RegexIterator::getPregFlags
RegexIterator::setFlags
RegexIterator


Sets the flags.

RegexIterator::getRegex
RegexIterator::setMode
RegexIterator
PHP Manual

RegexIterator::setFlags

(PHP 5 >= 5.2.0, PHP 7)

RegexIterator::setFlags — Sets the flags.

Descrierea

public void RegexIterator::setFlags ( int $flags )

Sets the flags.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

teststr2 => another test

A se vedea ?i

  • 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, PHP 7)

RegexIterator::setMode — Sets the operation mode.

Descrierea

public void RegexIterator::setMode ( int $mode )

Sets the operation mode.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

str1 => 1
str3 => 123

A se vedea ?i

  • RegexIterator::getMode() - Returns operation mode.

RegexIterator::setFlags
RegexIterator::setPregFlags
RegexIterator


Sets the regular expression flags.

RegexIterator::setMode
Interfe?e
RegexIterator
PHP Manual

RegexIterator::setPregFlags

(PHP 5 >= 5.2.0, PHP 7)

RegexIterator::setPregFlags — Sets the regular expression flags.

Descrierea

public void RegexIterator::setPregFlags ( int $preg_flags )

Sets the regular expression flags.

Parametri

preg_flags

The regular expression flags. See RegexIterator::__construct() for an overview of available flags.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(4) "test"
    [1]=>
    int(0)
  }
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(4) "test"
    [1]=>
    int(0)
  }
}

A se vedea ?i

  • RegexIterator::getPregFlags() - Returns the regular expression flags.

RegexIterator::setMode
Interfe?e
RegexIterator


Interfe?e

Cuprins

  • Countable
  • OuterIterator
  • RecursiveIterator
  • SeekableIterator

SPL ofera un set de interfe?e.

Vede?i de asemenea Interfe?e ?i clase predefinite

Lista interfe?elor

  • Countable
  • OuterIterator
  • RecursiveIterator
  • SeekableIterator
  • SplObserver
  • SplSubject
RegexIterator::setPregFlags
Countable
SPL


The Countable interface

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Classes implementing Countable can be used with the count() function.

Descrierea succinta a interfe?ei

Countable {
/* Metode */
abstract public int count ( void )
}

Cuprins

  • Countable::count — Count elements of an object
Interfe?e
Countable::count
Interfe?e


Count elements of an object

Countable
OuterIterator
Countable
PHP Manual

Countable::count

(PHP 5 >= 5.1.0, PHP 7)

Countable::count — Count elements of an object

Descrierea

abstract public int Countable::count ( void )

This method is executed when using the count() function on an object implementing Countable.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The custom count as an integer.

Nota:

The return value is cast to an integer.

Exemple

Example #1 Countable::count() example

<?php
class myCounter implements Countable {
    private $count = 0;
    public function count() {
        return ++$this->count;
    }
}

$counter = new myCounter;

for($i=0; $i<10; ++$i) {
    echo "I have been count()ed " . count($counter) . " times\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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, PHP 7)

Introducere

Classes implementing OuterIterator can be used to iterate over iterators.

Descrierea succinta a interfe?ei

OuterIterator extends Iterator {
/* Metode */
public Iterator getInnerIterator ( void )
/* Metode mo?tenite */
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 )
}

Cuprins

  • OuterIterator::getInnerIterator — Returns the inner iterator for the current entry.
Countable::count
OuterIterator::getInnerIterator
Interfe?e


Returns the inner iterator for the current entry.

OuterIterator
RecursiveIterator
OuterIterator
PHP Manual

OuterIterator::getInnerIterator

(PHP 5 >= 5.1.0, PHP 7)

OuterIterator::getInnerIterator — Returns the inner iterator for the current entry.

Descrierea

public Iterator OuterIterator::getInnerIterator ( void )

Returns the inner iterator for the current iterator entry.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The inner iterator for the current entry.

OuterIterator
RecursiveIterator
OuterIterator


The RecursiveIterator interface

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Classes implementing RecursiveIterator can be used to iterate over iterators recursively.

Descrierea succinta a interfe?ei

RecursiveIterator extends Iterator {
/* Metode */
public RecursiveIterator getChildren ( void )
public bool hasChildren ( void )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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
Interfe?e


Returns an iterator for the current entry.

RecursiveIterator
RecursiveIterator::hasChildren
RecursiveIterator
PHP Manual

RecursiveIterator::getChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIterator::getChildren — Returns an iterator for the current entry.

Descrierea

public RecursiveIterator RecursiveIterator::getChildren ( void )

Returns an iterator for the current iterator entry.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An iterator for the current entry.

A se vedea ?i

  • 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, PHP 7)

RecursiveIterator::hasChildren — Returns if an iterator can be created fot the current entry.

Descrierea

public bool RecursiveIterator::hasChildren ( void )

Returns if an iterator can be created for the current entry. RecursiveIterator::getChildren().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the current entry can be iterated over, otherwise returns FALSE.

A se vedea ?i

  • RecursiveIterator::getChildren() - Returns an iterator for the current entry.

RecursiveIterator::getChildren
SeekableIterator
RecursiveIterator


The SeekableIterator interface

(PHP 5 >= 5.1.0, PHP 7)

Introducere

The Seekable iterator.

Descrierea succinta a interfe?ei

SeekableIterator extends Iterator {
/* Metode */
abstract public void seek ( int $position )
/* Metode mo?tenite */
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 )
}

Example #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;

    private $array = array(
        "first element",
        "second element",
        "third element",
        "fourth element"
    );

    /* Method required for SeekableIterator interface */

    public function seek($position) {
      if (!isset($this->array[$position])) {
          throw new OutOfBoundsException("invalid seek position ($position)");
      }

      $this->position = $position;
    }

    /* Methods required for Iterator interface */

    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();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

first element
third element
second element
invalid seek position (10)

Cuprins

  • SeekableIterator::seek — Seeks to a position
RecursiveIterator::hasChildren
SeekableIterator::seek
Interfe?e


Seeks to a position

SeekableIterator
Excep?ii
SeekableIterator
PHP Manual

SeekableIterator::seek

(PHP 5 >= 5.1.0, PHP 7)

SeekableIterator::seek — Seeks to a position

Descrierea

abstract public void SeekableIterator::seek ( int $position )

Seeks to a given position in the iterator.

Parametri

position

The position to seek to.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Implementations should throw an OutOfBoundsException if the position is not seekable.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

damson

A se vedea ?i

  • SeekableIterator
  • Iterator

SeekableIterator
Excep?ii
SeekableIterator


Excep?ii

Cuprins

  • BadFunctionCallException
  • BadMethodCallException
  • DomainException
  • InvalidArgumentException
  • LengthException
  • LogicException
  • OutOfBoundsException
  • OutOfRangeException
  • OverflowException
  • RangeException
  • RuntimeException
  • UnderflowException
  • UnexpectedValueException

SPL ofera un set standard de Excep?ii.

Vede?i de asemenea Excep?ii predefinite

SPL Exceptions Class Tree

  • LogicException (extends Exception)
    • BadFunctionCallException
      • BadMethodCallException
    • DomainException
    • InvalidArgumentException
    • LengthException
    • OutOfRangeException
  • RuntimeException (extends Exception)
    • OutOfBoundsException
    • OverflowException
    • RangeException
    • UnderflowException
    • UnexpectedValueException
SeekableIterator::seek
BadFunctionCallException
SPL


The BadFunctionCallException class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Exception thrown if a callback refers to an undefined function or if some arguments are missing.

Sinopsisul clasei

BadFunctionCallException extends LogicException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
Excep?ii
BadMethodCallException
Excep?ii


The BadMethodCallException class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Exception thrown if a callback refers to an undefined method or if some arguments are missing.

Sinopsisul clasei

BadMethodCallException extends BadFunctionCallException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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
Excep?ii


The DomainException class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Exception thrown if a value does not adhere to a defined valid data domain.

Sinopsisul clasei

DomainException extends LogicException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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
Excep?ii


The InvalidArgumentException class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Exception thrown if an argument is not of the expected type.

Sinopsisul clasei

InvalidArgumentException extends LogicException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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
Excep?ii


The LengthException class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Exception thrown if a length is invalid.

Sinopsisul clasei

LengthException extends LogicException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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
Excep?ii


The LogicException class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Exception that represents error in the program logic. This kind of exception should lead directly to a fix in your code.

Sinopsisul clasei

LogicException extends Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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
Excep?ii


The OutOfBoundsException class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Exception thrown if a value is not a valid key. This represents errors that cannot be detected at compile time.

Sinopsisul clasei

OutOfBoundsException extends RuntimeException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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
Excep?ii


The OutOfRangeException class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Exception thrown when an illegal index was requested. This represents errors that should be detected at compile time.

Sinopsisul clasei

OutOfRangeException extends LogicException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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
Excep?ii


The OverflowException class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Exception thrown when adding an element to a full container.

Sinopsisul clasei

OverflowException extends RuntimeException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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
Excep?ii


The RangeException class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

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.

Sinopsisul clasei

RangeException extends RuntimeException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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
Excep?ii


The RuntimeException class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Exception thrown if an error which can only be found on runtime occurs.

Sinopsisul clasei

RuntimeException extends Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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
Excep?ii


The UnderflowException class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Exception thrown when performing an invalid operation on an empty container, such as removing an element.

Sinopsisul clasei

UnderflowException extends RuntimeException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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
Excep?ii


The UnexpectedValueException class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

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.

Sinopsisul clasei

UnexpectedValueException extends RuntimeException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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
Func?ii SPL
Excep?ii


Func?ii SPL

Cuprins

  • class_implements — Return the interfaces which are implemented by the given class or interface
  • 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 or interface

Func?ii SPL
class_parents
Func?ii SPL
PHP Manual

class_implements

(PHP 5 >= 5.1.0, PHP 7)

class_implements — Return the interfaces which are implemented by the given class or interface

Descrierea

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.

Parametri

class

An object (class instance) or a string (class or interface name).

autoload

Whether to allow this function to load the class automatically through the __autoload() magic method.

Valorile întoarse

An array on success, or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Added the option to pass the class parameter as a string. Added the autoload parameter.

Exemple

Example #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));

?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [foo] => foo
)

Array
(
    [interface_of_not_loaded] => interface_of_not_loaded
)

A se vedea ?i

  • class_parents() - Return the parent classes of the given class
  • get_declared_interfaces() - Returns an array of all declared interfaces

Func?ii SPL
class_parents
Func?ii SPL


Return the parent classes of the given class

class_implements
class_uses
Func?ii SPL
PHP Manual

class_parents

(PHP 5 >= 5.1.0, PHP 7)

class_parents — Return the parent classes of the given class

Descrierea

array class_parents ( mixed $class [, bool $autoload = true ] )

This function returns an array with the name of the parent classes of the given class.

Parametri

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.

Valorile întoarse

An array on success, or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Added the option to pass the class parameter as a string. Added the autoload parameter.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [foo] => foo
)

Array
(
    [parent_of_not_loaded] => parent_of_not_loaded
)

A se vedea ?i

  • class_implements() - Return the interfaces which are implemented by the given class or interface

class_implements
class_uses
Func?ii SPL


Return the traits used by the given class

class_parents
iterator_apply
Func?ii SPL
PHP Manual

class_uses

(PHP 5 >= 5.4.0, PHP 7)

class_uses — Return the traits used by the given class

Descrierea

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.

Parametri

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.

Valorile întoarse

An array on success, or FALSE on error.

Exemple

Example #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_uses('not_loaded', true));

?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [foo] => foo
)

Array
(
    [foo] => foo
)

Array
(
    [trait_of_not_loaded] => trait_of_not_loaded
)

A se vedea ?i

  • class_parents() - Return the parent classes of the given class
  • get_declared_traits() - Returns an array of all declared traits

class_parents
iterator_apply
Func?ii SPL


Call a function for every element in an iterator

class_uses
iterator_count
Func?ii SPL
PHP Manual

iterator_apply

(PHP 5 >= 5.1.0, PHP 7)

iterator_apply — Call a function for every element in an iterator

Descrierea

int iterator_apply ( Traversable $iterator , callable $function [, array $args ] )

Calls a function for every element in an iterator.

Parametri

iterator

The class to iterate over.

function

The callback function to call on every element.

Nota: The function must return TRUE in order to continue iterating over the iterator.

args

Arguments to pass to the callback function.

Valorile întoarse

Returns the iteration count.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

APPLES
BANANAS
CHERRIES

A se vedea ?i

  • array_walk() - Apply a user supplied function to every member of an array

class_uses
iterator_count
Func?ii SPL


Count the elements in an iterator

iterator_apply
iterator_to_array
Func?ii SPL
PHP Manual

iterator_count

(PHP 5 >= 5.1.0, PHP 7)

iterator_count — Count the elements in an iterator

Descrierea

int iterator_count ( Traversable $iterator )

Count the elements in an iterator. iterator_count() is not guaranteed to retain the current position of the iterator.

Parametri

iterator

The iterator being counted.

Valorile întoarse

The number of elements in iterator.

Exemple

Example #1 iterator_count() example

<?php
$iterator = new ArrayIterator(array('recipe'=>'pancakes', 'egg', 'milk', 'flour'));
var_dump(iterator_count($iterator));
?>

Exemplul de mai sus va afi?a:

int(4)

Example #2 iterator_count() modifies position

<?php
$iterator = new ArrayIterator(['one', 'two', 'three']);
var_dump($iterator->current());
var_dump(iterator_count($iterator));
var_dump($iterator->current());
?>

Exemplul de mai sus va afi?a:

string(3) "one"
int(3)
NULL

Example #3 iterator_count() in foreach loops

<?php
$iterator = new ArrayIterator(['one', 'two', 'three']);
foreach ($iterator as $key => $value) {
    echo "$key: $value (", iterator_count($iterator), ")\n";
}?>

Exemplul de mai sus va afi?a:

0: one (3)

iterator_apply
iterator_to_array
Func?ii SPL


Copy the iterator into an array

iterator_count
spl_autoload_call
Func?ii SPL
PHP Manual

iterator_to_array

(PHP 5 >= 5.1.0, PHP 7)

iterator_to_array — Copy the iterator into an array

Descrierea

array iterator_to_array ( Traversable $iterator [, bool $use_keys = true ] )

Copy the elements of an iterator into an array.

Parametri

iterator

The iterator being copied.

use_keys

Whether to use the iterator element keys as index.

In PHP 5.5 and later, if a key is an array or object, a warning will be generated. NULL keys will be converted to an empty string, double keys will be truncated to their integer counterpart, resource keys will generate a warning and be converted to their resource ID, and boolean keys will be converted to integers.

Nota:

If this parameter is not set or set to TRUE, duplicate keys will be overwritten. The last value with a given key will be in the returned array. Set this paramater to FALSE to get all the values in any case.

Valorile întoarse

An array containing the elements of the iterator.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | iterator_to_array() gained support for key types other than integer and string when the use_keys parameter is enabled.
5.2.1 | The use_keys parameter was added.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

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
Func?ii SPL


Try all registered __autoload() function to load the requested class

iterator_to_array
spl_autoload_extensions
Func?ii SPL
PHP Manual

spl_autoload_call

(PHP 5 >= 5.1.2, PHP 7)

spl_autoload_call — Try all registered __autoload() function to load the requested class

Descrierea

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.

Parametri

class_name

The class name being searched.

Valorile întoarse

Nu este întoarsa nici o valoare.

iterator_to_array
spl_autoload_extensions
Func?ii SPL


Register and return default file extensions for spl_autoload

spl_autoload_call
spl_autoload_functions
Func?ii SPL
PHP Manual

spl_autoload_extensions

(PHP 5 >= 5.1.2, PHP 7)

spl_autoload_extensions — Register and return default file extensions for spl_autoload

Descrierea

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.

Parametri

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.

Valorile întoarse

A comma delimited list of default file extensions for spl_autoload().

spl_autoload_call
spl_autoload_functions
Func?ii SPL


Return all registered __autoload() functions

spl_autoload_extensions
spl_autoload_register
Func?ii SPL
PHP Manual

spl_autoload_functions

(PHP 5 >= 5.1.2, PHP 7)

spl_autoload_functions — Return all registered __autoload() functions

Descrierea

array spl_autoload_functions ( void )

Get all registered __autoload() functions.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array of all registered __autoload functions. If the autoload queue 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
Func?ii SPL


Register given function as __autoload() implementation

spl_autoload_functions
spl_autoload_unregister
Func?ii SPL
PHP Manual

spl_autoload_register

(PHP 5 >= 5.1.2, PHP 7)

spl_autoload_register — Register given function as __autoload() implementation

Descrierea

bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )

Register a function with the spl provided __autoload queue. If the queue 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 queue. 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.

Parametri

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 queue instead of appending it.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Namespaces support was introduced.
5.3.0 | The prepend parameter was added.

Exemple

Example #1 spl_autoload_register() as a replacement for an __autoload() function

<?php

// function __autoload($class) {
//     include 'classes/' . $class . '.class.php';
// }

function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});

?>

Example #2 spl_autoload_register() example where the class is not loaded

<?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;

?>

Exemplul de mai sus va afi?a ceva similar cu:

[[Foobar\InexistentClass]]
Fatal error: Class 'Foobar\InexistentClass' not found in ...

A se vedea ?i

  • __autoload() - Attempt to load undefined class

spl_autoload_functions
spl_autoload_unregister
Func?ii SPL


Unregister given function as __autoload() implementation

spl_autoload_register
spl_autoload
Func?ii SPL
PHP Manual

spl_autoload_unregister

(PHP 5 >= 5.1.2, PHP 7)

spl_autoload_unregister — Unregister given function as __autoload() implementation

Descrierea

bool spl_autoload_unregister ( mixed $autoload_function )

Removes a function from the autoload queue. If the queue is activated and empty after removing the given function then it will be deactivated.

When this function results in the queue being deactivated, any __autoload function that previously existed will not be reactivated.

Parametri

autoload_function

The autoload function being unregistered.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

spl_autoload_register
spl_autoload
Func?ii SPL


Default implementation for __autoload()

spl_autoload_unregister
spl_classes
Func?ii SPL
PHP Manual

spl_autoload

(PHP 5 >= 5.1.2, PHP 7)

spl_autoload — Default implementation for __autoload()

Descrierea

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 function will be used for any later call to __autoload().

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws LogicException when the class is not found and there are no other autoloaders registered.

spl_autoload_unregister
spl_classes
Func?ii SPL


Return available SPL classes

spl_autoload
spl_object_hash
Func?ii SPL
PHP Manual

spl_classes

(PHP 5, PHP 7)

spl_classes — Return available SPL classes

Descrierea

array spl_classes ( void )

This function returns an array with the current available SPL classes.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array containing the currently available SPL classes.

Exemple

Example #1 spl_classes() example

<?php

print_r(spl_classes());

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
Func?ii SPL


Return hash id for given object

spl_classes
Manipularea fi?ierelor
Func?ii SPL
PHP Manual

spl_object_hash

(PHP 5 >= 5.2.0, PHP 7)

spl_object_hash — Return hash id for given object

Descrierea

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, as long as the object is not destroyed. Once the object is destroyed, its hash may be reused for other objects.

Parametri

object

Any object.

Valorile întoarse

A string that is unique for each currently existing object and is always the same for each object.

Exemple

Example #1 A spl_object_hash() example

<?php
$id = spl_object_hash($object);
$storage[$id] = $object;
?>

Note

Nota:

When an object is destroyed, its hash may be reused for other objects.

spl_classes
Manipularea fi?ierelor
Func?ii SPL


Manipularea fi?ierelor

Cuprins

  • SplFileInfo
  • SplFileObject
  • SplTempFileObject

SPL ofera câteva clase pentru a lucra cu fi?iere.

spl_object_hash
SplFileInfo
SPL


The SplFileInfo class

(PHP 5 >= 5.1.2, PHP 7)

Introducere

The SplFileInfo class offers a high-level object oriented interface to information for an individual file.

Sinopsisul clasei

SplFileInfo {
/* Metode */
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 = "SplFileObject" ] )
public void setInfoClass ([ string $class_name = "SplFileInfo" ] )
public void __toString ( void )
}

Cuprins

  • 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 used with SplFileInfo::openFile
  • SplFileInfo::setInfoClass — Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo
  • SplFileInfo::__toString — Returns the path to the file as a string
Manipularea fi?ierelor
SplFileInfo::__construct
Manipularea fi?ierelor


Construct a new SplFileInfo object

SplFileInfo
SplFileInfo::getATime
SplFileInfo
PHP Manual

SplFileInfo::__construct

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::__construct — Construct a new SplFileInfo object

Descrierea

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.

Parametri

file_name

Path to the file.

Exemple

Example #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, PHP 7)

SplFileInfo::getATime — Gets last access time of the file

Descrierea

public int SplFileInfo::getATime ( void )

Gets the last access time for the file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the time the file was last accessed.

Erori/Excep?ii

Throws RunTimeException on error.

A se vedea ?i

  • fileatime() - Gets last access time of file

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, PHP 7)

SplFileInfo::getBasename — Gets the base name of the file

Descrierea

public string SplFileInfo::getBasename ([ string $suffix ] )

This method returns the base name of the file, directory, or link without path info.

Parametri

suffix

Optional suffix to omit from the base name returned.

Valorile întoarse

Returns the base name without path information.

Exemple

Example #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'));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(8) "file.txt"
string(8) "file.txt"
string(4) "file"

A se vedea ?i

  • 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, PHP 7)

SplFileInfo::getCTime — Gets the inode change time

Descrierea

public int SplFileInfo::getCTime ( void )

Returns the inode change time for the file. The time returned is a Unix timestamp.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The last change time, in a Unix timestamp.

Erori/Excep?ii

Throws RunTimeException on error.

Exemple

Example #1 SplFileInfo::getCTime() example

<?php
$info = new SplFileInfo(__FILE__);
echo 'Last changed at ' . date('g:i a', $info->getCTime());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Last changed at 1:49 pm

A se vedea ?i

  • filectime() - Gets inode change time of file

SplFileInfo::getBasename
SplFileInfo::getExtension
SplFileInfo


Gets the file extension

SplFileInfo::getCTime
SplFileInfo::getFileInfo
SplFileInfo
PHP Manual

SplFileInfo::getExtension

(PHP 5 >= 5.3.6, PHP 7)

SplFileInfo::getExtension — Gets the file extension

Descrierea

public string SplFileInfo::getExtension ( void )

Retrieves the file extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string containing the file extension, or an empty string if the file has no extension.

Exemple

Example #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());

?>

Exemplul de mai sus va afi?a:

string(3) "txt"
string(3) "jpg"
string(2) "gz"

Note

Nota:

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);
?>

A se vedea ?i

  • SplFileInfo::getFilename() - Gets the filename
  • SplFileInfo::getBasename() - Gets the base name of the file
  • pathinfo() - Returns information about a file path
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, PHP 7)

SplFileInfo::getFileInfo — Gets an SplFileInfo object for the file

Descrierea

public SplFileInfo SplFileInfo::getFileInfo ([ string $class_name ] )

This method gets an SplFileInfo object for the referenced file.

Parametri

class_name

Name of an SplFileInfo derived class to use.

Valorile întoarse

An SplFileInfo object created for the file.

A se vedea ?i

  • SplFileInfo::setInfoClass() - Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo

SplFileInfo::getExtension
SplFileInfo::getFilename
SplFileInfo


Gets the filename

SplFileInfo::getFileInfo
SplFileInfo::getGroup
SplFileInfo
PHP Manual

SplFileInfo::getFilename

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getFilename — Gets the filename

Descrierea

public string SplFileInfo::getFilename ( void )

Gets the filename without any path information.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The filename.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(7) "foo.txt"
string(7) "foo.txt"
string(0) ""
string(7) "svn.php"

A se vedea ?i

  • 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, PHP 7)

SplFileInfo::getGroup — Gets the file group

Descrierea

public int SplFileInfo::getGroup ( void )

Gets the file group. The group ID is returned in numerical format.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The group id in numerical format.

Erori/Excep?ii

Throws RuntimeException on error.

Exemple

Example #1 SplFileInfo::getGroup() example

<?php
$info = new SplFileInfo(__FILE__);
print_r(posix_getgrgid($info->getGroup()));
?>

Exemplul de mai sus va afi?a ceva similar cu:

A se vedea ?i

  • 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, PHP 7)

SplFileInfo::getInode — Gets the inode for the file

Descrierea

public int SplFileInfo::getInode ( void )

Gets the inode number for the filesystem object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the inode number for the filesystem object.

Erori/Excep?ii

Throws RuntimeException on error.

A se vedea ?i

  • fileinode() - Gets file inode

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, PHP 7)

SplFileInfo::getLinkTarget — Gets the target of a link

Descrierea

public string SplFileInfo::getLinkTarget ( void )

Gets the target of a filesystem link.

Nota:

The target may not be the real path on the filesystem. Use SplFileInfo::getRealPath() to determine the true path on the filesystem.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the target of the filesystem link.

Erori/Excep?ii

Throws RuntimeException on error.

Exemple

Example #1 SplFileInfo::getLinkTarget() example

<?php
$info = new SplFileInfo('/Users/bbieber/workspace');
if ($info->isLink()) {
    var_dump($info->getLinkTarget());
    var_dump($info->getRealPath());
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(19) "Documents/workspace"
string(34) "/Users/bbieber/Documents/workspace"

A se vedea ?i

  • 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, PHP 7)

SplFileInfo::getMTime — Gets the last modified time

Descrierea

public int SplFileInfo::getMTime ( void )

Returns the time when the contents of the file were changed. The time returned is a Unix timestamp.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the last modified time for the file, in a Unix timestamp.

A se vedea ?i

  • filemtime() - Gets file modification time

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, PHP 7)

SplFileInfo::getOwner — Gets the owner of the file

Descrierea

public int SplFileInfo::getOwner ( void )

Gets the file owner. The owner ID is returned in numerical format.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The owner id in numerical format.

Erori/Excep?ii

Throws RuntimeException on error.

Exemple

Example #1 SplFileInfo::getOwner() example

<?php
$info = new SplFileInfo('file.txt');
print_r(posix_getpwuid($info->getOwner()));
?>

A se vedea ?i

  • 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, PHP 7)

SplFileInfo::getPath — Gets the path without filename

Descrierea

public string SplFileInfo::getPath ( void )

Returns the path to the file, omitting the filename and any trailing slash.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the path to the file.

Exemple

Example #1 SplFileInfo::getPath() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->getPath());

$info = new SplFileInfo('/usr/');
var_dump($info->getPath());?>

Exemplul de mai sus va afi?a ceva similar cu:

string(8) "/usr/bin"
string(4) "/usr"

A se vedea ?i

  • 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, PHP 7)

SplFileInfo::getPathInfo — Gets an SplFileInfo object for the path

Descrierea

public SplFileInfo SplFileInfo::getPathInfo ([ string $class_name ] )

Gets an SplFileInfo object for the parent of the current file.

Parametri

class_name

Name of an SplFileInfo derived class to use.

Valorile întoarse

Returns an SplFileInfo object for the parent path of the file.

Exemple

Example #1 SplFileInfo::getPathInfo() example

<?php
$info = new SplFileInfo('/usr/bin/php');
$parent_info = $info->getPathInfo();
var_dump($parent_info->getRealPath());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(8) "/usr/bin"

A se vedea ?i

  • SplFileInfo::setInfoClass() - Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::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, PHP 7)

SplFileInfo::getPathname — Gets the path to the file

Descrierea

public string SplFileInfo::getPathname ( void )

Returns the path to the file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The path to the file.

Exemple

Example #1 SplFileInfo::getPathname() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->getPathname());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(12) "/usr/bin/php"

A se vedea ?i

  • 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, PHP 7)

SplFileInfo::getPerms — Gets file permissions

Descrierea

public int SplFileInfo::getPerms ( void )

Gets the file permissions for the file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the file permissions.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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, PHP 7)

SplFileInfo::getRealPath — Gets absolute path to file

Descrierea

public string SplFileInfo::getRealPath ( void )

This method expands all symbolic links, resolves relative references and returns the real path to the file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the path to the file, or FALSE if the file does not exist.

Exemple

Example #1 SplFileInfo::getRealPath() example

<?php
$info = new SplFileInfo('/..//./../../'.__FILE__);
var_dump($info->getRealPath());

$info = new SplFileInfo('/tmp');
var_dump($info->getRealPath());

$info = new SplFileInfo('/I/Do/Not/Exist');
var_dump($info->getRealPath());

$info = new SplFileInfo("");
var_dump($info->getRealPath());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(28) "/private/tmp/phptempfile.php"
string(12) "/private/tmp"
bool(false)
string(12) "/private/tmp"

A se vedea ?i

  • SplFileInfo::isLink() - Tells if the file is a link
  • realpath() - Returns canonicalized absolute pathname

SplFileInfo::getPerms
SplFileInfo::getSize
SplFileInfo


Gets file size

SplFileInfo::getRealPath
SplFileInfo::getType
SplFileInfo
PHP Manual

SplFileInfo::getSize

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getSize — Gets file size

Descrierea

public int SplFileInfo::getSize ( void )

Returns the filesize in bytes for the file referenced.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The filesize in bytes.

Erori/Excep?ii

A RuntimeException will be thrown if the file does not exist or an error occurs.

A se vedea ?i

  • filesize() - Gets file size

SplFileInfo::getRealPath
SplFileInfo::getType
SplFileInfo


Gets file type

SplFileInfo::getSize
SplFileInfo::isDir
SplFileInfo
PHP Manual

SplFileInfo::getType

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getType — Gets file type

Descrierea

public string SplFileInfo::getType ( void )

Returns the type of the file referenced.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A string representing the type of the entry. May be one of file, link, or dir

Erori/Excep?ii

Throws a RuntimeException on error.

Exemple

Example #1 SplFileInfo::getType() example

<?php

$info = new SplFileInfo(__FILE__);
echo $info->getType().PHP_EOL;

$info = new SplFileInfo(dirname(__FILE__));
echo $info->getType();

?>

Exemplul de mai sus va afi?a ceva similar cu:

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, PHP 7)

SplFileInfo::isDir — Tells if the file is a directory

Descrierea

public bool SplFileInfo::isDir ( void )

This method can be used to determine if the file is a directory.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if a directory, FALSE otherwise.

Exemple

Example #1 SplFileInfo::isDir() example

<?php
$d = new SplFileInfo(dirname(__FILE__));
var_dump($d->isDir());

$d = new SplFileInfo(__FILE__);
var_dump($d->isDir());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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, PHP 7)

SplFileInfo::isExecutable — Tells if the file is executable

Descrierea

public bool SplFileInfo::isExecutable ( void )

Checks if the file is executable.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if executable, FALSE otherwise.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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, PHP 7)

SplFileInfo::isFile — Tells if the object references a regular file

Descrierea

public bool SplFileInfo::isFile ( void )

Checks if the file referenced by this SplFileInfo object exists and is a regular file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the file exists and is a regular file (not a link), FALSE otherwise.

Exemple

Example #1 SplFileInfo::isFile() example

<?php
$info = new SplFileInfo(__FILE__);
var_dump($info->isFile());

$info = new SplFileInfo(dirname(__FILE__));
var_dump($info->isFile());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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, PHP 7)

SplFileInfo::isLink — Tells if the file is a link

Descrierea

public bool SplFileInfo::isLink ( void )

Use this method to check if the file referenced by the SplFileInfo object is a link.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the file is a link, FALSE otherwise.

Exemple

Example #1 SplFileInfo::isLink() example

<?php
$info = new SplFileInfo('/path/to/symlink');
if ($info->isLink()) {
    echo 'The real path is '.$info->getRealPath();
}
?>

A se vedea ?i

  • 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, PHP 7)

SplFileInfo::isReadable — Tells if file is readable

Descrierea

public bool SplFileInfo::isReadable ( void )

Check if the file is readable.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if readable, FALSE otherwise.

Exemple

Example #1 SplFileInfo::isReadable() example

<?php
$info = new SplFileInfo(__FILE__);
var_dump($info->isReadable());

$info = new SplFileInfo('foo');
var_dump($info->isReadable());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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, PHP 7)

SplFileInfo::isWritable — Tells if the entry is writable

Descrierea

public bool SplFileInfo::isWritable ( void )

Checks if the current entry is writable.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

SplFileInfo::openFile — Gets an SplFileObject object for the file

Descrierea

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.

Parametri

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

Când este stabilit în TRUE, fi?ierul este cautat ?i în caile specificate în include_path

context

Accesa?i sec?iunea context a manualului pentru descrierea contextelor.

Valorile întoarse

The opened file as an SplFileObject object.

Erori/Excep?ii

A RuntimeException if the file cannot be opened (e.g. insufficient access rights).

Exemple

Example #1 SplFileInfo::openFile() example

<?php
$fileinfo = new SplFileInfo('/tmp/foo.txt');

if ($fileinfo->isWritable()) {

    $fileobj = $fileinfo->openFile('a');

    $fileobj->fwrite("appended this sample text");
}
?>

A se vedea ?i

  • SplFileObject
  • stream_context_create() - Creates a stream context
  • fopen() - Opens file or URL

SplFileInfo::isWritable
SplFileInfo::setFileClass
SplFileInfo


Sets the class used with SplFileInfo::openFile

SplFileInfo::openFile
SplFileInfo::setInfoClass
SplFileInfo
PHP Manual

SplFileInfo::setFileClass

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::setFileClass — Sets the class used with SplFileInfo::openFile()

Descrierea

public void SplFileInfo::setFileClass ([ string $class_name = "SplFileObject" ] )

Use this method to set a custom class which will be used when SplFileInfo::openFile() is called. The class name passed to this method must be SplFileObject or a class derived from SplFileObject.

Parametri

class_name

The class name to use when SplFileInfo::openFile() is called.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(MyFoo)#2 (0) { }

A se vedea ?i

  • SplFileInfo::openFile() - Gets an SplFileObject object for the file

SplFileInfo::openFile
SplFileInfo::setInfoClass
SplFileInfo


Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo

SplFileInfo::setFileClass
SplFileInfo::__toString
SplFileInfo
PHP Manual

SplFileInfo::setInfoClass

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::setInfoClass — Sets the class used with SplFileInfo::getFileInfo() and SplFileInfo::getPathInfo()

Descrierea

public void SplFileInfo::setInfoClass ([ string $class_name = "SplFileInfo" ] )

Use this method to set a custom class which will be used when SplFileInfo::getFileInfo() and SplFileInfo::getPathInfo() are called. The class name passed to this method must be SplFileInfo or a class derived from SplFileInfo.

Parametri

class_name

The class name to use when SplFileInfo::getFileInfo() and SplFileInfo::getPathInfo() are called.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(MyFoo)#2 (0) { }

A se vedea ?i

  • 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, PHP 7)

SplFileInfo::__toString — Returns the path to the file as a string

Descrierea

public void SplFileInfo::__toString ( void )

This method will return the file name of the referenced file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the path to the file.

Exemple

Example #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;
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(3) "foo"
foo
string(12) "/usr/bin/php"
/usr/bin/php

SplFileInfo::setInfoClass
SplFileObject
SplFileInfo


The SplFileObject class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

The SplFileObject class offers an object oriented interface for a file.

Sinopsisul clasei

SplFileObject extends SplFileInfo implements RecursiveIterator , SeekableIterator {
/* Constante */
const integer DROP_NEW_LINE = 1 ;
const integer READ_AHEAD = 2 ;
const integer SKIP_EMPTY = 4 ;
const integer READ_CSV = 8 ;
/* Metode */
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 ( array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\" ]]] )
public string fread ( int $length )
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 void __toString ( void )
public bool valid ( void )
/* Metode mo?tenite */
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 = "SplFileObject" ] )
public void SplFileInfo::setInfoClass ([ string $class_name = "SplFileInfo" ] )
public void SplFileInfo::__toString ( void )
}

Constante predefinite

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. This requires the READ_AHEAD flag be enabled, to work as expected.

SplFileObject::READ_CSV

Read lines as CSV rows.

Istoricul schimbarilor

Versiune | Descriere
5.3.9 | SplFileObject::SKIP_EMPTY value changed to 4. Previously, value was 6.

Cuprins

  • 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 — Write a field array as a CSV line
  • SplFileObject::fread — Read from file
  • 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, enclosure and escape character for CSV
  • SplFileObject::getCurrentLine — Pseudonim al 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, enclosure and escape character for CSV
  • SplFileObject::setFlags — Sets flags for the SplFileObject
  • SplFileObject::setMaxLineLen — Set maximum line length
  • SplFileObject::__toString — Pseudonim al SplFileObject::current
  • SplFileObject::valid — Not at EOF
SplFileInfo::__toString
SplFileObject::__construct
Manipularea fi?ierelor


Construct a new file object.

SplFileObject
SplFileObject::current
SplFileObject
PHP Manual

SplFileObject::__construct

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::__construct — Construct a new file object.

Descrierea

public SplFileObject::__construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = false [, resource $context ]]] )

Construct a new file object.

Parametri

filename

The file to read.

Sfat

Un URL poate fi utilizat în calitate de denumire a fi?ierului în aceasta func?ie daca înveli?urile fopen au fost activate. Accesa?i fopen() pentru mai multe detalii despre modul de specificare a denumirii fi?ierului. Accesa?i Supported Protocols and Wrappers pentru referin?e la informa?ii despre posibilita?ile pe care le ofera diferite înveli?uri, note despre utilizarea lor ?i informa?ii despre variabile predefinite pe care le ofera.

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().

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws a RuntimeException if the filename cannot be opened.

Exemple

Example #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_num => $line) {
    echo "Line $line_num is $line";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Line 0 is <?php
Line 1 is $file = new SplFileObject(__FILE__);
Line 2 is foreach ($file as $line_num => $line) {
Line 3 is     echo "Line $line_num is $line";
Line 4 is }
Line 5 is ?>

A se vedea ?i

  • SplFileInfo::openFile() - Gets an SplFileObject object for the file
  • fopen() - Opens file or URL

SplFileObject
SplFileObject::current
SplFileObject


Retrieve current line of file

SplFileObject::__construct
SplFileObject::eof
SplFileObject
PHP Manual

SplFileObject::current

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::current — Retrieve current line of file

Descrierea

public string|array SplFileObject::current ( void )

Retrieves the current line of the file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Exemple

Example #1 SplFileObject::current() example

<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $k => $line) {
   echo ($file->key() + 1) . ': ' . $file->current();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

1: <?php
2: $file = new SplFileObject(__FILE__);
3: foreach ($file as $line) {
4:     echo ($file->key() + 1) . ': ' . $file->current();
5: }
6: ?>

A se vedea ?i

  • 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, PHP 7)

SplFileObject::eof — Reached end of file

Descrierea

public bool SplFileObject::eof ( void )

Determine whether the end of file has been reached

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if file is at EOF, FALSE otherwise.

Exemple

Example #1 SplFileObject::eof() example

<?php
$file = new SplFileObject("fruits.txt");
while ( ! $file->eof()) {
    echo $file->fgets();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

apple
banana
cherry
date
elderberry

A se vedea ?i

  • SplFileObject::valid() - Not at EOF
  • feof() - Tests for end-of-file on a file pointer

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, PHP 7)

SplFileObject::fflush — Flushes the output to the file

Descrierea

public bool SplFileObject::fflush ( void )

Forces a write of all buffered output to the file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 SplFileObject::fflush() example

<?php
$file = new SplFileObject('misc.txt', 'r+');
$file->rewind();
$file->fwrite("Foo");
$file->fflush();
$file->ftruncate($file->ftell());
?>

A se vedea ?i

  • 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, PHP 7)

SplFileObject::fgetc — Gets character from file

Descrierea

public string SplFileObject::fgetc ( void )

Gets a character from the file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string containing a single character read from the file or FALSE on EOF.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Exemple

Example #1 SplFileObject::fgetc() example

<?php
$file = new SplFileObject('file.txt');
while (false !== ($char = $file->fgetc())) {
    echo "$char\n";
}
?>

A se vedea ?i

  • 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, PHP 7)

SplFileObject::fgetcsv — Gets line from file and parse as CSV fields

Descrierea

 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.

Parametri

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().

Valorile întoarse

Returns an indexed array containing the fields read, or FALSE on error.

Nota:

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.

Exemple

Example #1 SplFileObject::fgetcsv() example

<?php
$file = new SplFileObject("data.csv");
while (!$file->eof()) {
    var_dump($file->fgetcsv());
}
?>

Example #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

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • SplFileObject::setCsvControl() - Set the delimiter, enclosure and escape 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, PHP 7)

SplFileObject::fgets — Gets line from file

Descrierea

public string SplFileObject::fgets ( void )

Gets a line from the file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string containing the next line from the file, or FALSE on error.

Erori/Excep?ii

Throws a RuntimeException if the file cannot be read.

Exemple

Example #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();
}
?>

A se vedea ?i

  • fgets() - Gets line from file pointer
  • 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, PHP 7)

SplFileObject::fgetss — Gets line from file and strip HTML tags

Descrierea

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.

Parametri

allowable_tags

Optional parameter to specify tags which should not be stripped.

Valorile întoarse

Returns a string containing the next line of the file with HTML and PHP code stripped, or FALSE on error.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

 Welcome! Today is the  of .

Text outside of the HTML block.

A se vedea ?i

  • fgetss() - Gets line from file pointer and strip HTML tags
  • 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, PHP 7)

SplFileObject::flock — Portable file locking

Descrierea

public bool SplFileObject::flock ( int $operation [, int &$wouldblock ] )

Locks or unlocks the file in the same portable way as flock().

Parametri

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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!";
}
?>

A se vedea ?i

  • 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, PHP 7)

SplFileObject::fpassthru — Output all remaining data on a file pointer

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the number of characters read from handle and passed through to the output.

Exemple

Example #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;

?>

A se vedea ?i

  • fpassthru() - Output all remaining data on a file pointer

SplFileObject::flock
SplFileObject::fputcsv
SplFileObject


Write a field array as a CSV line

SplFileObject::fpassthru
SplFileObject::fread
SplFileObject
PHP Manual

SplFileObject::fputcsv

(PHP 5 >= 5.4.0, PHP 7)

SplFileObject::fputcsv — Write a field array as a CSV line

Descrierea

 public int SplFileObject::fputcsv
  ( array $fields
 [, string $delimiter = ","
 [, string $enclosure = '"'
 [, string $escape = "\"
]]] )

Writes the fields array to the file as a CSV line.

Parametri

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).

escape

The optional escape parameter sets the escape character (one character only).

Valorile întoarse

Returns the length of the written string sau FALSE în cazul e?ecului.

Returns FALSE, and does not write the CSV line to the file, if the delimiter or enclosure parameter is not a single character.

Erori/Excep?ii

An E_WARNING level error is issued if the delimiter or enclosure parameter is not a single character.

Istoricul schimbarilor

Versiune | Descriere
5.5.21, 5.6.5 | Added the escape parameter.

Exemple

Example #1 SplFileObject::fputcsv() example

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$file = new SplFileObject('file.csv', 'w');

foreach ($list as $fields) {
    $file->fputcsv($fields);
}

?>

The above example will write the following to file.csv:

aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""

A se vedea ?i

  • fputcsv() - Format line as CSV and write to file pointer
  • SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields

SplFileObject::fpassthru
SplFileObject::fread
SplFileObject


Read from file

SplFileObject::fputcsv
SplFileObject::fscanf
SplFileObject
PHP Manual

SplFileObject::fread

(PHP 5 >= 5.5.11, PHP 7)

SplFileObject::fread — Read from file

Descrierea

public string SplFileObject::fread ( int $length )

Reads the given number of bytes from the file.

Parametri

length

The number of bytes to read.

Valorile întoarse

Returns the string read from the file sau FALSE în cazul e?ecului.

Exemple

Example #1 SplFileObject::fread() example

<?php
// Get contents of a file into a string
$filename = "/usr/local/something.txt";
$file = new SplFileObject($filename, "r");
$contents = $file->fread($file->getSize());
?>

Note

Nota:

Note that SplFileObject::fread() reads from the current position of the file pointer. Use SplFileObject::ftell() to find the current position of the pointer and SplFileObject::rewind() (or SplFileObject::fseek()) to rewind the pointer position.

A se vedea ?i

  • fread() - Binary-safe file read

SplFileObject::fputcsv
SplFileObject::fscanf
SplFileObject


Parses input from file according to a format

SplFileObject::fread
SplFileObject::fseek
SplFileObject
PHP Manual

SplFileObject::fscanf

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fscanf — Parses input from file according to a format

Descrierea

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.

Parametri

format

The specified format as described in the sprintf() documentation.

...

The optional assigned values.

Valorile întoarse

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.

Exemple

Example #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 $profession $countrycode
}
?>

Contents of users.txt

javier   argonaut    pe
hiroshi  sculptor    jp
robert   slacker     us
luigi    florist     it

A se vedea ?i

  • fscanf() - Parses input from a file according to a format

SplFileObject::fread
SplFileObject::fseek
SplFileObject


Seek to a position

SplFileObject::fscanf
SplFileObject::fstat
SplFileObject
PHP Manual

SplFileObject::fseek

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fseek — Seek to a position

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns 0 if the seek was successful, -1 otherwise. Note that seeking past EOF is not considered an error.

Exemple

Example #1 SplFileObject::fseek() example

<?php
$file = new SplFileObject("somefile.txt");

// Read first line
$data = $file->fgets();

// Move back to the beginning of the file
// Same as $file->rewind();
$file->fseek(0);
?>

A se vedea ?i

  • 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, PHP 7)

SplFileObject::fstat — Gets information about the file

Descrierea

public array SplFileObject::fstat ( void )

Gathers the statistics of the file. Behaves identically to fstat().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page.

Exemple

Example #1 SplFileObject::fstat() example

<?php
$file = new SplFileObject("/etc/passwd");
$stat = $file->fstat();

// Print only the associative part
print_r(array_slice($stat, 13));

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • fstat() - Gets information about a file using an open file pointer
  • 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, PHP 7)

SplFileObject::ftell — Return current file position

Descrierea

public int SplFileObject::ftell ( void )

Returns the position of the file pointer which represents the current offset in the file stream.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the position of the file pointer as an integer, or FALSE on error.

Exemple

Example #1 SplFileObject::ftell() example

<?php
$file = new SplFileObject("/etc/passwd");

// Read first line
$data = $file->fgets();

// Where are we?
echo $file->ftell();
?>

A se vedea ?i

  • ftell() - Returns the current position of the file read/write pointer

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, PHP 7)

SplFileObject::ftruncate — Truncates the file to a given length

Descrierea

public bool SplFileObject::ftruncate ( int $size )

Truncates the file to size bytes.

Parametri

size

The size to truncate to.

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Hello

A se vedea ?i

  • ftruncate() - Truncates a file to a given length

SplFileObject::ftell
SplFileObject::fwrite
SplFileObject


Write to file

SplFileObject::ftruncate
SplFileObject::getChildren
SplFileObject
PHP Manual

SplFileObject::fwrite

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fwrite — Write to file

Descrierea

public int SplFileObject::fwrite ( string $str [, int $length ] )

Writes the contents of string to the file

Parametri

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.

Valorile întoarse

Returns the number of bytes written, or NULL on error.

Exemple

Example #1 SplFileObject::fwrite() example

<?php
$file = new SplFileObject("fwrite.txt", "w");
$written = $file->fwrite("12345");
echo "Wrote $written bytes to file";
?>

Exemplul de mai sus va afi?a ceva similar cu:

Wrote 5 bytes to file

A se vedea ?i

  • fwrite() - Binary-safe file write

SplFileObject::ftruncate
SplFileObject::getChildren
SplFileObject


No purpose

SplFileObject::fwrite
SplFileObject::getCsvControl
SplFileObject
PHP Manual

SplFileObject::getChildren

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::getChildren — No purpose

Descrierea

public void SplFileObject::getChildren ( void )

An SplFileObject does not have children so this method returns NULL.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • RecursiveIterator::getChildren() - Returns an iterator for the current entry.

SplFileObject::fwrite
SplFileObject::getCsvControl
SplFileObject


Get the delimiter, enclosure and escape character for CSV

SplFileObject::getChildren
SplFileObject::getCurrentLine
SplFileObject
PHP Manual

SplFileObject::getCsvControl

(PHP 5 >= 5.2.0, PHP 7)

SplFileObject::getCsvControl — Get the delimiter, enclosure and escape character for CSV

Descrierea

public array SplFileObject::getCsvControl ( void )

Gets the delimiter, enclosure and escape character used for parsing CSV fields.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an indexed array containing the delimiter, enclosure and escape character.

Istoricul schimbarilor

Versiune | Descriere
5.6.25, 7.0.10 | Added the escape character to the returned array.

Exemple

Example #1 SplFileObject::getCsvControl() example

<?php
$file = new SplFileObject("data.txt");
print_r($file->getCsvControl());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => ,
    [1] => "
    [2] => \
)

A se vedea ?i

  • SplFileObject::setCsvControl() - Set the delimiter, enclosure and escape character for CSV
  • SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields

SplFileObject::getChildren
SplFileObject::getCurrentLine
SplFileObject


Pseudonim al SplFileObject::fgets

SplFileObject::getCsvControl
SplFileObject::getFlags
SplFileObject
PHP Manual

SplFileObject::getCurrentLine

(PHP 5 >= 5.1.2, PHP 7)

SplFileObject::getCurrentLine — Pseudonim al SplFileObject::fgets()

Descrierea

Aceasta metoda este un pseudonim al 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, PHP 7)

SplFileObject::getFlags — Gets flags for the SplFileObject

Descrierea

public int SplFileObject::getFlags ( void )

Gets the flags set for an instance of SplFileObject as an integer.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an integer representing the flags.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Not skipping empty lines
Skipping empty lines

A se vedea ?i

  • 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, PHP 7)

SplFileObject::getMaxLineLen — Get maximum line length

Descrierea

public int SplFileObject::getMaxLineLen ( void )

Gets the maximum line length as set by SplFileObject::setMaxLineLen().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the maximum line length if one has been set with SplFileObject::setMaxLineLen(), default is 0.

Exemple

Example #1 SplFileObject::getMaxLineLen() example

<?php
$file = new SplFileObject("file.txt");
var_dump($file->getMaxLineLen());

$file->setMaxLineLen(20);
var_dump($file->getMaxLineLen());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(0)
int(20)

A se vedea ?i

  • 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, PHP 7)

SplFileObject::hasChildren — SplFileObject does not have children

Descrierea

public bool SplFileObject::hasChildren ( void )

An SplFileObject does not have children so this method always return FALSE.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns FALSE

A se vedea ?i

  • 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, PHP 7)

SplFileObject::key — Get line number

Descrierea

public int SplFileObject::key ( void )

Gets the current line number.

Nota:

This number may not reflect the actual line number in the file if SplFileObject::setMaxLineLen() is used to read fixed lengths of the file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current line number.

Exemple

Example #1 SplFileObject::key() example

<?php
$file = new SplFileObject("lipsum.txt");
foreach ($file as $line) {
    echo $file->key() . ". " . $line;
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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.

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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.

A se vedea ?i

  • 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, PHP 7)

SplFileObject::next — Read next line

Descrierea

public void SplFileObject::next ( void )

Moves ahead to the next line in the file.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 SplFileObject::next() example

<?php
// Read through file line by line
$file = new SplFileObject("misc.txt");
while (!$file->eof()) {
    echo $file->current();
    $file->next();
}
?>

A se vedea ?i

  • 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, PHP 7)

SplFileObject::rewind — Rewind the file to the first line

Descrierea

public void SplFileObject::rewind ( void )

Rewinds the file back to the first line.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws a RuntimeException if cannot be rewound.

Exemple

Example #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();
?>

A se vedea ?i

  • 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, PHP 7)

SplFileObject::seek — Seek to specified line

Descrierea

public void SplFileObject::seek ( int $line_pos )

Seek to specified line in the file.

Parametri

line_pos

The zero-based line number to seek to.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws a LogicException if the line_pos is negative.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

$file->seek(2);

A se vedea ?i

  • 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, enclosure and escape character for CSV

SplFileObject::seek
SplFileObject::setFlags
SplFileObject
PHP Manual

SplFileObject::setCsvControl

(PHP 5 >= 5.2.0, PHP 7)

SplFileObject::setCsvControl — Set the delimiter, enclosure and escape character for CSV

Descrierea

 public void SplFileObject::setCsvControl
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] )

Sets the delimiter, enclosure and escape character for parsing CSV fields.

Parametri

delimiter

The field delimiter (one character only).

enclosure

The field enclosure character (one character only).

escape

The field escape character (one character only).

Valorile întoarse

Nu este întoarsa nici o valoare.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Added the escape parameter.

Exemple

Example #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
?>

A se vedea ?i

  • SplFileObject::getCsvControl() - Get the delimiter, enclosure and escape 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, PHP 7)

SplFileObject::setFlags — Sets flags for the SplFileObject

Descrierea

public void SplFileObject::setFlags ( int $flags )

Sets the flags to be used by the SplFileObject.

Parametri

flags

Bit mask of the flags to set. See SplFileObject constants for the available flags.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 SplFileObject::setFlags() example

<?php
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $fields) {
    var_dump($fields);
}
?>

A se vedea ?i

  • 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, PHP 7)

SplFileObject::setMaxLineLen — Set maximum line length

Descrierea

public void SplFileObject::setMaxLineLen ( int $max_len )

Sets the maximum length of a line to be read.

Parametri

max_len

The maximum length of a line.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws DomainException when max_len is less than zero.

Exemple

Example #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.

Exemplul de mai sus va afi?a ceva similar cu:

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.

A se vedea ?i

  • Classname::Method()

SplFileObject::setFlags
SplFileObject::__toString
SplFileObject


Pseudonim al SplFileObject::current

SplFileObject::setMaxLineLen
SplFileObject::valid
SplFileObject
PHP Manual

SplFileObject::__toString

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::__toString — Pseudonim al SplFileObject::current()

Descrierea

public void SplFileObject::__toString ( void )

Aceasta medoda este un pseudonim al SplFileObject::current().

SplFileObject::setMaxLineLen
SplFileObject::valid
SplFileObject


Not at EOF

SplFileObject::__toString
SplTempFileObject
SplFileObject
PHP Manual

SplFileObject::valid

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::valid — Not at EOF

Descrierea

public bool SplFileObject::valid ( void )

Check whether EOF has been reached.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if not reached EOF, FALSE otherwise.

Exemple

Example #1 SplFileObject::valid() example

<?php
// Loop over a file, line by line
$file = new SplFileObject("file.txt");
while ($file->valid()) {
    echo $file->fgets();
}
?>

A se vedea ?i

  • 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, PHP 7)

Introducere

The SplTempFileObject class offers an object oriented interface for a temporary file.

Sinopsisul clasei

SplTempFileObject extends SplFileObject implements SeekableIterator , RecursiveIterator {
/* Metode */
public __construct ([ int $max_memory ] )
/* Metode mo?tenite */
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
  ( array $fields
 [, string $delimiter = ","
 [, string $enclosure = '"'
 [, string $escape = "\"
]]] )
public string SplFileObject::fread ( int $length )
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 void SplFileObject::__toString ( void )
public bool SplFileObject::valid ( void )
}

Cuprins

  • SplTempFileObject::__construct — Construct a new temporary file object
SplFileObject::valid
SplTempFileObject::__construct
Manipularea fi?ierelor


Construct a new temporary file object

SplTempFileObject
Clase ?i interfe?e diverse
SplTempFileObject
PHP Manual

SplTempFileObject::__construct

(PHP 5 >= 5.1.2, PHP 7)

SplTempFileObject::__construct — Construct a new temporary file object

Descrierea

public SplTempFileObject::__construct ([ int $max_memory ] )

Construct a new temporary file object.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws a RuntimeException if an error occurs.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Written 47 bytes to temporary file.

This is the first line
And this is the second.

A se vedea ?i

  • SplFileObject
  • PHP input/output streams (for php://temp and php://memory)

SplTempFileObject
Clase ?i interfe?e diverse
SplTempFileObject


Clase ?i interfe?e diverse

Cuprins

  • ArrayObject
  • SplObserver
  • SplSubject

Clase ?i interfe?e ce nu se încadreaza în alte categorii SPL.

SplTempFileObject::__construct
ArrayObject
SPL


The ArrayObject class

(PHP 5, PHP 7)

Introducere

This class allows objects to work as arrays.

Sinopsisul clasei

ArrayObject implements IteratorAggregate , ArrayAccess , Serializable , Countable {
/* Constante */
const integer STD_PROP_LIST = 1 ;
const integer ARRAY_AS_PROPS = 2 ;
/* Metode */
public __construct ([ mixed $input = [] [, int $flags = 0 [, string $iterator_class = "ArrayIterator" ]]] )
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 string serialize ( void )
public void setFlags ( int $flags )
public void setIteratorClass ( string $iterator_class )
public void uasort ( callable $cmp_function )
public void uksort ( callable $cmp_function )
public void unserialize ( string $serialized )
}

Constante predefinite

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).

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Implements Serializable.

Cuprins

  • 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
Clase ?i interfe?e diverse
ArrayObject::append
Clase ?i interfe?e diverse


Appends the value

ArrayObject
ArrayObject::asort
ArrayObject
PHP Manual

ArrayObject::append

(PHP 5 >= 5.0.0, PHP 7)

ArrayObject::append — Appends the value

Descrierea

public void ArrayObject::append ( mixed $value )

Appends a new value as the last element.

Nota:

This method cannot be called when the ArrayObject was constructed from an object. Use ArrayObject::offsetSet() instead.

Parametri

value

The value being appended.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ArrayObject::append() example

<?php
$arrayobj = new ArrayObject(array('first','second','third'));
$arrayobj->append('fourth');
$arrayobj->append(array('five', 'six'));
var_dump($arrayobj);
?>

Exemplul de mai sus va afi?a:

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"
  }
}

A se vedea ?i

  • 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, PHP 7)

ArrayObject::asort — Sort the entries by value

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • 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, PHP 7)

ArrayObject::__construct — Construct a new array object

Descrierea

public ArrayObject::__construct ([ mixed $input = [] [, int $flags = 0 [, string $iterator_class = "ArrayIterator" ]]] )

This constructs a new array object.

Parametri

input

The input parameter accepts an array or an Object.

flags

Flags to control the behaviour of the ArrayObject object. See ArrayObject::setFlags().

iterator_class

Specify the class that will be used for iteration of the ArrayObject object.

Valorile întoarse

Returns an ArrayObject object on success.

Erori/Excep?ii

Throws InvalidArgumentException when:

  • input is not an array or object
  • flags is not an integer
  • iterator_class is not an object that implements Iterator

Exemple

Example #1 ArrayObject::__construct() example

<?php
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);

var_dump($arrayobject);
?>

Exemplul de mai sus va afi?a:

object(ArrayObject)#1 (3) {
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  string(5) "three"
}

A se vedea ?i

  • 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, PHP 7)

ArrayObject::count — Get the number of public properties in the ArrayObject

Descrierea

public int ArrayObject::count ( void )

Get the number of public properties in the ArrayObject.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The number of public properties in the ArrayObject.

Nota:

When the ArrayObject is constructed from an array all properties are public.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

ArrayObject::exchangeArray — Exchange the array for another one.

Descrierea

public array ArrayObject::exchangeArray ( mixed $input )

Exchange the current array with another array or object.

Parametri

input

The new array or object to exchange with the current array.

Valorile întoarse

Returns the old array.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

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, PHP 7)

ArrayObject::getArrayCopy — Creates a copy of the ArrayObject.

Descrierea

public array ArrayObject::getArrayCopy ( void )

Exports the ArrayObject to an array.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

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, PHP 7)

ArrayObject::getFlags — Gets the behavior flags.

Descrierea

public int ArrayObject::getFlags ( void )

Gets the behavior flags of the ArrayObject. See the ArrayObject::setFlags method for a list of the available flags.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the behavior flags of the ArrayObject.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

int(0)
int(2)

A se vedea ?i

  • 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, PHP 7)

ArrayObject::getIterator — Create a new iterator from an ArrayObject instance

Descrierea

public ArrayIterator ArrayObject::getIterator ( void )

Create a new iterator from an ArrayObject instance.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An iterator from an ArrayObject.

Exemple

Example #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();
}
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

ArrayObject::getIteratorClass — Gets the iterator classname for the ArrayObject.

Descrierea

public string ArrayObject::getIteratorClass ( void )

Gets the class name of the array iterator that is used by ArrayObject::getIterator().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the iterator class name that is used to iterate over this object.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

string(13) "ArrayIterator"
string(15) "MyArrayIterator"

A se vedea ?i

  • 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, PHP 7)

ArrayObject::ksort — Sort the entries by key

Descrierea

public void ArrayObject::ksort ( void )

Sorts the entries by key, maintaining key to entry correlations. This is useful mainly for associative arrays.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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";
}
 ?>

Exemplul de mai sus va afi?a:

a = orange
b = banana
c = apple
d = lemon

A se vedea ?i

  • 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, PHP 7)

ArrayObject::natcasesort — Sort an array using a case insensitive "natural order" algorithm

Descrierea

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".

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • 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, PHP 7)

ArrayObject::natsort — Sort entries using a "natural order" algorithm

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • 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, PHP 7)

ArrayObject::offsetExists — Returns whether the requested index exists

Descrierea

public bool ArrayObject::offsetExists ( mixed $index )

Parametri

index

The index being checked.

Valorile întoarse

TRUE if the requested index exists, otherwise FALSE

Exemple

Example #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'));
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

ArrayObject::offsetGet — Returns the value at the specified index

Descrierea

public mixed ArrayObject::offsetGet ( mixed $index )

Parametri

index

The index with the value.

Valorile întoarse

The value at the specified index or NULL.

Erori/Excep?ii

Produces an E_NOTICE error message when the specified index does not exist.

Exemple

Example #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'));
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

ArrayObject::offsetSet — Sets the value at the specified index to newval

Descrierea

public void ArrayObject::offsetSet ( mixed $index , mixed $newval )

Sets the value at the specified index to newval.

Parametri

index

The index being set.

newval

The new value for the index.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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"
}

A se vedea ?i

  • 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, PHP 7)

ArrayObject::offsetUnset — Unsets the value at the specified index

Descrierea

public void ArrayObject::offsetUnset ( mixed $index )

Unsets the value at the specified index.

Parametri

index

The index being unset.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ArrayObject::offsetUnset() example

<?php
$arrayobj = new ArrayObject(array(0=>'zero',2=>'two'));
$arrayobj->offsetUnset(2);
var_dump($arrayobj);
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

ArrayObject::serialize — Serialize an ArrayObject

Descrierea

public string ArrayObject::serialize ( void )

Serializes an ArrayObject.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The serialized representation of the ArrayObject.

Exemple

Example #1 ArrayObject::serialize() example

<?php
$o = new ArrayObject();

$s1 = serialize($o);
$s2 = $o->serialize();

var_dump($s1);
var_dump($s2);
?>

Exemplul de mai sus va afi?a:

string(45) "C:11:"ArrayObject":21:{x:i:0;a:0:{};m:a:0:{}}"
string(21) "x:i:0;a:0:{};m:a:0:{}"

A se vedea ?i

  • ArrayObject::unserialize() - Unserialize an ArrayObject
  • serialize() - Genereaza o reprezentare ce poate fi stocata a unei valori
  • 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, PHP 7)

ArrayObject::setFlags — Sets the behavior flags.

Descrierea

public void ArrayObject::setFlags ( int $flags )

Set the flags that change the behavior of the ArrayObject.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

ArrayObject::setIteratorClass — Sets the iterator classname for the ArrayObject.

Descrierea

public void ArrayObject::setIteratorClass ( string $iterator_class )

Sets the classname of the array iterator that is used by ArrayObject::getIterator().

Parametri

iterator_class

The classname of the array iterator to use when iterating over this object.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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());

?>

Exemplul de mai sus va afi?a:

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, PHP 7)

ArrayObject::uasort — Sort the entries with a user-defined comparison function and maintain key association

Descrierea

public void ArrayObject::uasort ( callable $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.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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
)

A se vedea ?i

  • 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, PHP 7)

ArrayObject::uksort — Sort the entries by keys using a user-defined comparison function

Descrierea

public void ArrayObject::uksort ( callable $cmp_function )

This function sorts the keys of the entries using a user-supplied comparison function. The key to entry correlations will be maintained.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

an apple: 3
a banana: 4
the Earth: 2
John: 1

A se vedea ?i

  • 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, PHP 7)

ArrayObject::unserialize — Unserialize an ArrayObject

Descrierea

public void ArrayObject::unserialize ( string $serialized )

Unserializes a serialized ArrayObject.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

serialized

The serialized ArrayObject.

Valorile întoarse

The unserialized ArrayObject.

A se vedea ?i

  • ArrayIterator::serialize() - Serialize
  • unserialize() - Creeaza o valoare PHP dintr-o reprezentare stocata
  • Serializing Objects

ArrayObject::uksort
SplObserver
ArrayObject


The SplObserver interface

(PHP 5 >= 5.1.0, PHP 7)

Introducere

The SplObserver interface is used alongside SplSubject to implement the Observer Design Pattern.

Descrierea succinta a interfe?ei

SplObserver {
/* Metode */
abstract public void update ( SplSubject $subject )
}

Cuprins

  • SplObserver::update — Receive update from subject
ArrayObject::unserialize
SplObserver::update
Clase ?i interfe?e diverse


Receive update from subject

SplObserver
SplSubject
SplObserver
PHP Manual

SplObserver::update

(PHP 5 >= 5.1.0, PHP 7)

SplObserver::update — Receive update from subject

Descrierea

abstract public void SplObserver::update ( SplSubject $subject )

This method is called when any SplSubject to which the observer is attached calls SplSubject::notify().

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

subject

The SplSubject notifying the observer of an update.

Valorile întoarse

Nu este întoarsa nici o valoare.

SplObserver
SplSubject
SplObserver


The SplSubject interface

(PHP 5 >= 5.1.0, PHP 7)

Introducere

The SplSubject interface is used alongside SplObserver to implement the Observer Design Pattern.

Descrierea succinta a interfe?ei

SplSubject {
/* Metode */
abstract public void attach ( SplObserver $observer )
abstract public void detach ( SplObserver $observer )
abstract public void notify ( void )
}

Cuprins

  • SplSubject::attach — Attach an SplObserver
  • SplSubject::detach — Detach an observer
  • SplSubject::notify — Notify an observer
SplObserver::update
SplSubject::attach
Clase ?i interfe?e diverse


Attach an SplObserver

SplSubject
SplSubject::detach
SplSubject
PHP Manual

SplSubject::attach

(PHP 5 >= 5.1.0, PHP 7)

SplSubject::attach — Attach an SplObserver

Descrierea

abstract public void SplSubject::attach ( SplObserver $observer )

Attaches an SplObserver so that it can be notified of updates.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

observer

The SplObserver to attach.

Valorile întoarse

Nu este întoarsa nici o valoare.

SplSubject
SplSubject::detach
SplSubject


Detach an observer

SplSubject::attach
SplSubject::notify
SplSubject
PHP Manual

SplSubject::detach

(PHP 5 >= 5.1.0, PHP 7)

SplSubject::detach — Detach an observer

Descrierea

abstract public void SplSubject::detach ( SplObserver $observer )

Detaches an observer from the subject to no longer notify it of updates.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

observer

The SplObserver to detach.

Valorile întoarse

Nu este întoarsa nici o valoare.

SplSubject::attach
SplSubject::notify
SplSubject


Notify an observer

SplSubject::detach
SPL Types
SplSubject
PHP Manual

SplSubject::notify

(PHP 5 >= 5.1.0, PHP 7)

SplSubject::notify — Notify an observer

Descrierea

abstract public void SplSubject::notify ( void )

Notifies all attached observers.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

SplSubject::detach
SPL Types
SplSubject


SPL Type Handling

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • 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
Introducere
Alte extensii de baza


Introducere

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

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

SPL Types
Instalarea / configurarea
SPL Types


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SPL Types


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/SPL_Types.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
SplType
Instalarea / configurarea


The SplType class

(PECL spl_types >= 0.1.0)

Introducere

Parent class for all SPL types.

Sinopsisul clasei

abstract SplType {
/* Constants */
const NULL __default = null ;
/* Metode */
__construct ([ mixed $initial_value [, bool $strict ]] )
}

Constante predefinite

SplType::__default

Cuprins

  • SplType::__construct — Creates a new value of some type
Tipurile resurselor
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

Descrierea

SplType::__construct ([ mixed $initial_value [, bool $strict ]] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

initial_value

Type and default value depends on the extension class.

strict

Whether to set the object's sctrictness.

Erori/Excep?ii

Throws an UnexpectedValueException if incompatible type is given.

SplType
SplInt
SplType


The SplInt class

(PECL spl_types >= 0.1.0)

Introducere

The SplInt class is used to enforce strong typing of the integer type.

Sinopsisul clasei

SplInt extends SplType {
/* Constants */
const integer __default = 0 ;
/* Metode mo?tenite */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Constante predefinite

SplInt::__default

Exemple

Example #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;
?>

Exemplul de mai sus va afi?a:

Value not an integer
94

SplType::__construct
SplFloat
SPL Types


The SplFloat class

(PECL spl_types >= 0.1.0)

Introducere

The SplFloat class is used to enforce strong typing of the float type.

Sinopsisul clasei

SplFloat extends SplType {
/* Constants */
const float __default = 0 ;
/* Metode mo?tenite */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Constante predefinite

SplFloat::__default

Exemple

Example #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 $uve->getMessage() . PHP_EOL;
}

echo $float . PHP_EOL;
echo $newFloat . PHP_EOL;
?>

Exemplul de mai sus va afi?a:

Value not a float
3.154
3

SplInt
SplEnum
SPL Types


The SplEnum class

(PECL spl_types >= 0.1.0)

Introducere

SplEnum gives the ability to emulate and create enumeration objects natively in PHP.

Sinopsisul clasei

SplEnum extends SplType {
/* Constants */
const NULL __default = null ;
/* Metode */
public array getConstList ([ bool $include_default = false ] )
/* Metode mo?tenite */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Constante predefinite

SplEnum::__default

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

6
Value not a const in enum Month

Cuprins

  • 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.

Descrierea

public array SplEnum::getConstList ([ bool $include_default = false ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

include_default

Whether to include __default property.

Valorile întoarse

Exemple

Example #1 SplEnum::getConstList() example

<?php
$bool = new SplBool;
var_dump($bool->getConstList(true));
?>

Exemplul de mai sus va afi?a:

array(3) {
  ["__default"]=>
  bool(false)
  ["false"]=>
  bool(false)
  ["true"]=>
  bool(true)
}

SplEnum
SplBool
SplEnum


The SplBool class

(PECL spl_types >= 0.1.0)

Introducere

The SplBool class is used to enforce strong typing of the bool type.

Sinopsisul clasei

SplBool extends SplEnum {
/* Constants */
const boolean __default = false ;
const boolean false = false ;
const boolean true = true ;
/* Metode mo?tenite */
public array SplEnum::getConstList ([ bool $include_default = false ] )
}

Constante predefinite

SplBool::__default

SplBool::false

SplBool::true

Exemple

Example #1 SplBool usage example

<?php
$true = new SplBool(true);
if ($true) {
    echo "TRUE\n";
}

$false = new SplBool;
if ($false) {
    echo "FALSE\n";
}
?>

Exemplul de mai sus va afi?a:

TRUE

SplEnum::getConstList
SplString
SPL Types


The SplString class

(PECL spl_types >= 0.1.0)

Introducere

The SplString class is used to enforce strong typing of the string type.

Sinopsisul clasei

SplString extends SplType {
/* Constants */
const string __default = '' ;
/* Metode mo?tenite */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Constante predefinite

SplString::__default

Exemple

Example #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"
?>

Exemplul de mai sus va afi?a:

Value not a string
object(SplString)#1 (1) {
  ["__default"]=>
  string(7) "Testing"
}
Testing

SplBool
Streams
SPL Types


Streams

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Stream Classes
  • Constante predefinite
  • Stream Filters
  • Stream Contexts
  • Stream Errors
  • Exemple
    • Example class registered as stream wrapper
  • php_user_filter — The php_user_filter class
    • php_user_filter::filter — Called when applying the filter
    • php_user_filter::onClose — Called when closing the filter
    • php_user_filter::onCreate — Called when creating the filter
  • 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 a 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 metadata
    • 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_truncate — Truncate stream
    • streamWrapper::stream_write — Write to stream
    • streamWrapper::unlink — Delete a file
    • streamWrapper::url_stat — Retrieve information about a file
  • Func?ii de flux
    • set_socket_blocking — Pseudonim pentru 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 — Creates a stream context
    • stream_context_get_default — Retrieve the default stream 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 stream 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 parameter
    • stream_register_wrapper — Pseudonim pentru 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_chunk_size — Set the stream chunk size
    • 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
Introducere
Alte extensii de baza


Introducere

Streams are the 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.

Nota:

Information on using streams within the PHP source code can be found in the Streams API for PHP Extension Authors reference.

Streams
Instalarea / configurarea
Streams


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Stream Classes
Introducere
Necesita?i
Streams


Instalarea

Streams are an integral part of PHP as of version 4.3.0. No steps are required to enable them.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Aceasta extensie nu are directive de configurare definite în php.ini.

Instalarea
Stream Classes
Instalarea / configurarea


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.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.

Nota: The constants marked with * are just available since PHP 5.0.0.

Nota: 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.

Nota: 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().

Constante predefinite
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
Exemple
Streams


Exemple

Cuprins

  • Example class registered as stream wrapper

Example #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");
?>

Example #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);

$headers = "";
while ($str = trim(fgets($sock, 4096)))
$headers .= "$str\n";

echo "\n";

$body = "";
while (!feof($sock))
$body .= fgets($sock, 4096);

fclose($sock);
?>

Example #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"].

Example #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);

?>

Exemplul de mai sus va afi?a:

line1
line2
line3
string(18) "line1
line2
line3
"

Exemple
php_user_filter
Exemple


The php_user_filter class

(PHP 5, PHP 7)

Introducere

Children of this class are passed to stream_filter_register().

Sinopsisul clasei

php_user_filter {
/* Proprieta?i */
public $filtername ;
public $params ;
/* Metode */
public int filter ( resource $in , resource $out , int &$consumed , bool $closing )
public void onClose ( void )
public bool onCreate ( void )
}

Proprieta?i

filtername

Name of the filter registered by stream_filter_append().

params

Cuprins

  • php_user_filter::filter — Called when applying the filter
  • php_user_filter::onClose — Called when closing the filter
  • php_user_filter::onCreate — Called when creating the filter
Example class registered as stream wrapper
php_user_filter::filter
Streams


Called when applying the filter

php_user_filter
php_user_filter::onClose
php_user_filter
PHP Manual

php_user_filter::filter

(PHP 5, PHP 7)

php_user_filter::filter — Called when applying the filter

Descrierea

public int php_user_filter::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()).

Parametri

in

in is a resource pointing to a bucket brigade which contains one or more bucket objects containing data to be filtered.

out

out is a resource pointing to a second bucket brigade into which your modified buckets should be placed.

consumed

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.

closing

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.

Valorile întoarse

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.

php_user_filter
php_user_filter::onClose
php_user_filter


Called when closing the filter

php_user_filter::filter
php_user_filter::onCreate
php_user_filter
PHP Manual

php_user_filter::onClose

(PHP 5, PHP 7)

php_user_filter::onClose — Called when closing the filter

Descrierea

public void php_user_filter::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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Return value is ignored.

php_user_filter::filter
php_user_filter::onCreate
php_user_filter


Called when creating the filter

php_user_filter::onClose
streamWrapper
php_user_filter
PHP Manual

php_user_filter::onCreate

(PHP 5, PHP 7)

php_user_filter::onCreate — Called when creating the filter

Descrierea

public bool php_user_filter::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.

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Your implementation of this method should return FALSE on failure, or TRUE on success.

php_user_filter::onClose
streamWrapper
php_user_filter


The streamWrapper class

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

Introducere

Allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen(), fread() etc.).

Nota:

This is NOT a real class, only a prototype of how a class defining its own protocol should be.

Nota:

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.

Sinopsisul clasei

streamWrapper {
/* Proprieta?i */
public resource $context ;
/* Metode */
__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 ( int $operation )
public bool stream_metadata ( string $path , int $option , mixed $value )
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 bool stream_truncate ( int $new_size )
public int stream_write ( string $data )
public bool unlink ( string $path )
public array url_stat ( string $path , int $flags )
}

Proprieta?i

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.

Nota:

This property must be public so PHP can populate it with the actual context resource.

Istoricul schimbarilor

Versiune | Descriere
5.0.0 | Added the context property.

A se vedea ?i

  • Example class registered as stream wrapper
  • stream_wrapper_register()
  • stream_wrapper_unregister()
  • stream_wrapper_restore()

Cuprins

  • 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 a 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 metadata
  • 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_truncate — Truncate stream
  • streamWrapper::stream_write — Write to stream
  • streamWrapper::unlink — Delete a file
  • streamWrapper::url_stat — Retrieve information about a file
php_user_filter::onCreate
streamWrapper::__construct
Streams


Constructs a new stream wrapper

streamWrapper
streamWrapper::__destruct
streamWrapper
PHP Manual

streamWrapper::__construct

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::__construct — Constructs a new stream wrapper

Descrierea

streamWrapper::__construct ( void )

Called when opening the stream wrapper, right before streamWrapper::stream_open().

Parametri

Aceasta func?ie nu are parametri.

streamWrapper
streamWrapper::__destruct
streamWrapper


Destructs an existing stream wrapper

streamWrapper::__construct
streamWrapper::dir_closedir
streamWrapper
PHP Manual

streamWrapper::__destruct

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::__destruct — Destructs an existing stream wrapper

Descrierea

streamWrapper::__destruct ( void )

Called when closing the stream wrapper, right before streamWrapper::stream_flush().

Parametri

Aceasta func?ie nu are parametri.

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, PHP 7)

streamWrapper::dir_closedir — Close directory handle

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • closedir() - Close directory handle
  • 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, PHP 7)

streamWrapper::dir_opendir — Open directory handle

Descrierea

public bool streamWrapper::dir_opendir ( string $path , int $options )

This method is called in response to opendir().

Parametri

path

Specifies the URL that was passed to opendir().

Nota:

The URL can be broken apart with parse_url().

options

Whether or not to enforce safe_mode (0x04).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • opendir() - Open directory handle
  • streamWrapper::dir_closedir() - Close directory handle
  • parse_url() - Parse a URL and return its components

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, PHP 7)

streamWrapper::dir_readdir — Read entry from directory handle

Descrierea

public string streamWrapper::dir_readdir ( void )

This method is called in response to readdir().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Should return string representing the next filename, or FALSE if there is no next file.

Nota:

The return value will be casted to string.

Erori/Excep?ii

Emite o eroare E_WARNING daca apelul acestei metode e?ueaza (de ex. nu este implementata).

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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"

A se vedea ?i

  • readdir() - Read entry from directory handle

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, PHP 7)

streamWrapper::dir_rewinddir — Rewind directory handle

Descrierea

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().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • rewinddir() - Rewind directory handle
  • 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, PHP 7)

streamWrapper::mkdir — Create a directory

Descrierea

public bool streamWrapper::mkdir ( string $path , int $mode , int $options )

This method is called in response to mkdir().

Nota:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support creating directories.

Parametri

path

Directory which should be created.

mode

The value passed to mkdir().

options

A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Emite o eroare E_WARNING daca apelul acestei metode e?ueaza (de ex. nu este implementata).

Note

Nota:

Proprietatea streamWrapper::$context este reînnoita daca un context valid este transmis func?iei apelante.

A se vedea ?i

  • mkdir() - Makes directory
  • 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, PHP 7)

streamWrapper::rename — Renames a file or directory

Descrierea

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

Nota:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support renaming files.

Parametri

path_from

The URL to the current file.

path_to

The URL which the path_from should be renamed to.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Emite o eroare E_WARNING daca apelul acestei metode e?ueaza (de ex. nu este implementata).

Note

Nota:

Proprietatea streamWrapper::$context este reînnoita daca un context valid este transmis func?iei apelante.

A se vedea ?i

  • 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, PHP 7)

streamWrapper::rmdir — Removes a directory

Descrierea

public bool streamWrapper::rmdir ( string $path , int $options )

This method is called in response to rmdir().

Nota:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support removing directories.

Parametri

path

The directory URL which should be removed.

options

A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Emite o eroare E_WARNING daca apelul acestei metode e?ueaza (de ex. nu este implementata).

Note

Nota:

Proprietatea streamWrapper::$context este reînnoita daca un context valid este transmis func?iei apelante.

A se vedea ?i

  • rmdir() - Removes directory
  • 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, PHP 7)

streamWrapper::stream_cast — Retrieve the underlaying resource

Descrierea

public resource streamWrapper::stream_cast ( int $cast_as )

This method is called in response to stream_select().

Parametri

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.

Valorile întoarse

Should return the underlying stream resource used by the wrapper, or FALSE.

A se vedea ?i

  • 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 a resource

streamWrapper::stream_cast
streamWrapper::stream_eof
streamWrapper
PHP Manual

streamWrapper::stream_close

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::stream_close — Close a resource

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • fclose() - Closes an open file pointer
  • 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, PHP 7)

streamWrapper::stream_eof — Tests for end-of-file on a file pointer

Descrierea

public bool streamWrapper::stream_eof ( void )

This method is called in response to feof().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Note

Avertizare

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.

A se vedea ?i

  • feof() - Tests for end-of-file on a file pointer

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, PHP 7)

streamWrapper::stream_flush — Flushes the output

Descrierea

public bool streamWrapper::stream_flush ( void )

This method is called in response to fflush() and when the stream is being closed while any unflushed data has been written to it before.

If you have cached data in your stream but not yet stored it into the underlying storage, you should do so now.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Note

Nota:

If not implemented, FALSE is assumed as the return value.

A se vedea ?i

  • fflush() - Flushes the output to a file

streamWrapper::stream_eof
streamWrapper::stream_lock
streamWrapper


Advisory file locking

streamWrapper::stream_flush
streamWrapper::stream_metadata
streamWrapper
PHP Manual

streamWrapper::stream_lock

(PHP 5, PHP 7)

streamWrapper::stream_lock — Advisory file locking

Descrierea

public bool streamWrapper::stream_lock ( int $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).

Parametri

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)

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Emits E_WARNING if call to this method fails (i.e. not implemented).

A se vedea ?i

  • 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 metadata

streamWrapper::stream_lock
streamWrapper::stream_open
streamWrapper
PHP Manual

streamWrapper::stream_metadata

(PHP 5 >= 5.4.0, PHP 7)

streamWrapper::stream_metadata — Change stream metadata

Descrierea

public bool streamWrapper::stream_metadata ( string $path , int $option , mixed $value )

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.

Parametri

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:

  • STREAM_META_TOUCH (The method was called in response to touch())
  • STREAM_META_OWNER_NAME (The method was called in response to chown() with string parameter)
  • STREAM_META_OWNER (The method was called in response to chown())
  • STREAM_META_GROUP_NAME (The method was called in response to chgrp())
  • STREAM_META_GROUP (The method was called in response to chgrp())
  • STREAM_META_ACCESS (The method was called in response to chmod())

value

If option is

  • STREAM_META_TOUCH: Array consisting of two arguments of the touch() function.
  • STREAM_META_OWNER_NAME or STREAM_META_GROUP_NAME: The name of the owner user/group as string.
  • STREAM_META_OWNER or STREAM_META_GROUP: The value owner user/group argument as integer.
  • STREAM_META_ACCESS: The argument of the chmod() as integer.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. If option is not implemented, FALSE should be returned.

A se vedea ?i

  • touch() - Sets access and modification time of file
  • chmod() - Changes file mode
  • chown() - Changes file owner
  • chgrp() - Changes file group

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, PHP 7)

streamWrapper::stream_open — Opens file or URL

Descrierea

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()).

Parametri

path

Specifies the URL that was passed to the original function.

Nota:

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().

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Emite o eroare E_WARNING daca apelul acestei metode e?ueaza (de ex. nu este implementata).

Note

Nota:

Proprietatea streamWrapper::$context este reînnoita daca un context valid este transmis func?iei apelante.

A se vedea ?i

  • fopen() - Opens file or URL
  • parse_url() - Parse a URL and return its components

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, PHP 7)

streamWrapper::stream_read — Read from stream

Descrierea

public string streamWrapper::stream_read ( int $count )

This method is called in response to fread() and fgets().

Nota:

Remember to update the read/write position of the stream (by the number of bytes that were successfully read).

Parametri

count

How many bytes of data from the current position should be returned.

Valorile întoarse

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.

Erori/Excep?ii

Emite o eroare E_WARNING daca apelul acestei metode e?ueaza (de ex. nu este implementata).

Nota:

If the return value is longer then count an E_WARNING error will be emitted, and excess data will be lost.

Note

Nota:

streamWrapper::stream_eof() is called directly after calling streamWrapper::stream_read() to check if EOF has been reached. If not implemented, EOF is assumed.

Avertizare

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.

A se vedea ?i

  • fread() - Binary-safe file read
  • fgets() - Gets line from file pointer

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, PHP 7)

streamWrapper::stream_seek — Seeks to specific location in a stream

Descrierea

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.

Parametri

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.

Valorile întoarse

Return TRUE if the position was updated, FALSE otherwise.

Note

Nota:

If not implemented, FALSE is assumed as the return value.

Nota:

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

Nota:

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.

A se vedea ?i

  • 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, PHP 7)

streamWrapper::stream_set_option — Change stream options

Descrierea

public bool streamWrapper::stream_set_option ( int $option , int $arg1 , int $arg2 )

This method is called to set options on the stream.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. If option is not implemented, FALSE should be returned.

A se vedea ?i

  • 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, PHP 7)

streamWrapper::stream_stat — Retrieve information about a file resource

Descrierea

public array streamWrapper::stream_stat ( void )

This method is called in response to fstat().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

See stat().

Erori/Excep?ii

Emite o eroare E_WARNING daca apelul acestei metode e?ueaza (de ex. nu este implementata).

A se vedea ?i

  • 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_truncate
streamWrapper
PHP Manual

streamWrapper::stream_tell

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::stream_tell — Retrieve the current position of a stream

Descrierea

public int streamWrapper::stream_tell ( void )

This method is called in response to fseek() to determine the current position.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Should return the current position of the stream.

A se vedea ?i

  • streamWrapper::stream_tell()

streamWrapper::stream_stat
streamWrapper::stream_truncate
streamWrapper


Truncate stream

streamWrapper::stream_tell
streamWrapper::stream_write
streamWrapper
PHP Manual

streamWrapper::stream_truncate

(PHP 5 >= 5.4.0, PHP 7)

streamWrapper::stream_truncate — Truncate stream

Descrierea

public bool streamWrapper::stream_truncate ( int $new_size )

Will respond to truncation, e.g., through ftruncate().

Parametri

new_size

The new size.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ftruncate() - Truncates a file to a given length

streamWrapper::stream_tell
streamWrapper::stream_write
streamWrapper


Write to stream

streamWrapper::stream_truncate
streamWrapper::unlink
streamWrapper
PHP Manual

streamWrapper::stream_write

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::stream_write — Write to stream

Descrierea

public int streamWrapper::stream_write ( string $data )

This method is called in response to fwrite().

Nota:

Remember to update the current position of the stream by number of bytes that were successfully written.

Parametri

data

Should be stored into the underlying stream.

Nota:

If there is not enough room in the underlying stream, store as much as possible.

Valorile întoarse

Should return the number of bytes that were successfully stored, or 0 if none could be stored.

Erori/Excep?ii

Emite o eroare E_WARNING daca apelul acestei metode e?ueaza (de ex. nu este implementata).

Nota:

If the return value is greater the length of data, E_WARNING will be emitted and the return value will truncated to its length.

A se vedea ?i

  • fwrite() - Binary-safe file write

streamWrapper::stream_truncate
streamWrapper::unlink
streamWrapper


Delete a file

streamWrapper::stream_write
streamWrapper::url_stat
streamWrapper
PHP Manual

streamWrapper::unlink

(PHP 5, PHP 7)

streamWrapper::unlink — Delete a file

Descrierea

public bool streamWrapper::unlink ( string $path )

This method is called in response to unlink().

Nota:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support removing files.

Parametri

path

The file URL which should be deleted.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Emite o eroare E_WARNING daca apelul acestei metode e?ueaza (de ex. nu este implementata).

Note

Nota:

Proprietatea streamWrapper::$context este reînnoita daca un context valid este transmis func?iei apelante.

A se vedea ?i

  • unlink() - Deletes a file
  • streamWrapper::rmdir() - Removes a directory

streamWrapper::stream_write
streamWrapper::url_stat
streamWrapper


Retrieve information about a file

streamWrapper::unlink
Func?ii de flux
streamWrapper
PHP Manual

streamWrapper::url_stat

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::url_stat — Retrieve information about a file

Descrierea

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()

Parametri

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.

Valorile întoarse

Should return as many elements as stat() does. Unknown or unavailable values should be set to a rational value (usually 0).

Erori/Excep?ii

Emite o eroare E_WARNING daca apelul acestei metode e?ueaza (de ex. nu este implementata).

Note

Nota:

Proprietatea streamWrapper::$context este reînnoita daca un context valid este transmis func?iei apelante.

A se vedea ?i

  • stat() - Gives information about a file
  • streamwrapper::stream_stat() - Retrieve information about a file resource

streamWrapper::unlink
Func?ii de flux
streamWrapper


Func?ii de flux

Cuprins

  • set_socket_blocking — Pseudonim pentru 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 — Creates a stream context
  • stream_context_get_default — Retrieve the default stream 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 stream 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 parameter
  • stream_register_wrapper — Pseudonim pentru 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_chunk_size — Set the stream chunk size
  • 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


Pseudonim pentru stream_set_blocking

Func?ii de flux
stream_bucket_append
Func?ii de flux
PHP Manual

set_socket_blocking

(PHP 4, PHP 5)

set_socket_blocking — Pseudonim pentru stream_set_blocking()

Avertizare

Acest pseudonim este ÎNVECHIT începând cu PHP 5.3.0 ?i ELIMINAT începând cu PHP 7.0.0.

Descrierea

Aceasta func?ie este pseudonim pentru: stream_set_blocking()

Func?ii de flux
stream_bucket_append
Func?ii de flux


Append bucket to brigade

set_socket_blocking
stream_bucket_make_writeable
Func?ii de flux
PHP Manual

stream_bucket_append

(PHP 5, PHP 7)

stream_bucket_append — Append bucket to brigade

Descrierea

void stream_bucket_append ( resource $brigade , object $bucket )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

set_socket_blocking
stream_bucket_make_writeable
Func?ii de flux


Return a bucket object from the brigade for operating on

stream_bucket_append
stream_bucket_new
Func?ii de flux
PHP Manual

stream_bucket_make_writeable

(PHP 5, PHP 7)

stream_bucket_make_writeable — Return a bucket object from the brigade for operating on

Descrierea

object stream_bucket_make_writeable ( resource $brigade )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

stream_bucket_append
stream_bucket_new
Func?ii de flux


Create a new bucket for use on the current stream

stream_bucket_make_writeable
stream_bucket_prepend
Func?ii de flux
PHP Manual

stream_bucket_new

(PHP 5, PHP 7)

stream_bucket_new — Create a new bucket for use on the current stream

Descrierea

object stream_bucket_new ( resource $stream , string $buffer )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

stream_bucket_make_writeable
stream_bucket_prepend
Func?ii de flux


Prepend bucket to brigade

stream_bucket_new
stream_context_create
Func?ii de flux
PHP Manual

stream_bucket_prepend

(PHP 5, PHP 7)

stream_bucket_prepend — Prepend bucket to brigade

Descrierea

void stream_bucket_prepend ( resource $brigade , object $bucket )

This function can be called to prepend a bucket to a bucket brigade. It is typically called from php_user_filter::filter().

Parametri

brigade

brigade is a resource pointing to a bucket brigade which contains one or more bucket objects.

bucket

A bucket object.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 stream_bucket_prepend() examples

<?php

class foo extends php_user_filter {
  protected $calls = 0;
  public function filter($in, $out, &$consumed, $closing) {
    while ($bucket = stream_bucket_make_writeable($in)) {
      $consumed += $bucket->datalen;
      if ($this->calls++ == 2) {
        // This bucket will appear again before any other bucket.
        stream_bucket_prepend($in, $bucket);
      }
    }
    return PSFS_FEED_ME;
  }
}
stream_filter_register('test', 'foo');
print  file_get_contents('php://filter/read=test/resource=foo');
?>

stream_bucket_new
stream_context_create
Func?ii de flux


Creates a stream context

stream_bucket_prepend
stream_context_get_default
Func?ii de flux
PHP Manual

stream_context_create

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_context_create — Creates a stream context

Descrierea

resource stream_context_create ([ array $options [, array $params ]] )

Creates and returns a stream context with any options supplied in options preset.

Parametri

options

Must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value. Refer to context options for a list of available wrappers and options.

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.

Valorile întoarse

A stream context resource.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Added the optional params argument.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii de flux


Retrieve the default stream context

stream_context_create
stream_context_get_options
Func?ii de flux
PHP Manual

stream_context_get_default

(PHP 5 >= 5.1.0, PHP 7)

stream_context_get_default — Retrieve the default stream context

Descrierea

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().

Parametri

options
options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Nota:

As of PHP 5.3.0, the stream_context_set_default() function can be used to set the default context.

Valorile întoarse

A stream context resource.

Exemple

Example #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);

?>

A se vedea ?i

  • stream_context_create() - Creates a stream context
  • Listing of supported wrappers with context options (Supported Protocols and Wrappers).

stream_context_create
stream_context_get_options
Func?ii de flux


Retrieve options for a stream/wrapper/context

stream_context_get_default
stream_context_get_params
Func?ii de flux
PHP Manual

stream_context_get_options

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_context_get_options — Retrieve options for a stream/wrapper/context

Descrierea

array stream_context_get_options ( resource $stream_or_context )

Returns an array of options on the specified stream or context.

Parametri

stream_or_context

The stream or context to get options from

Valorile întoarse

Returns an associative array with the options.

Exemple

Example #1 stream_context_get_options() example

<?php
$params = array("method" => "POST");

stream_context_set_default(array("http" => $params));

var_dump(stream_context_get_options(stream_context_get_default()));

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  ["http"]=>
  array(1) {
    ["method"]=>
    string(4) "POST"
  }
}

stream_context_get_default
stream_context_get_params
Func?ii de flux


Retrieves parameters from a context

stream_context_get_options
stream_context_set_default
Func?ii de flux
PHP Manual

stream_context_get_params

(PHP 5 >= 5.3.0, PHP 7)

stream_context_get_params — Retrieves parameters from a context

Descrierea

array stream_context_get_params ( resource $stream_or_context )

Retrieves parameter and options information from the stream or context.

Parametri

stream_or_context

A stream resource or a context resource

Valorile întoarse

Returns an associate array containing all context options and parameters.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  ["notification"]=>
  string(28) "stream_notification_callback"
  ["options"]=>
  array(0) {
  }
}

A se vedea ?i

  • 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
Func?ii de flux


Set the default stream context

stream_context_get_params
stream_context_set_option
Func?ii de flux
PHP Manual

stream_context_set_default

(PHP 5 >= 5.3.0, PHP 7)

stream_context_set_default — Set the default stream context

Descrierea

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().

Parametri

options

The options to set for the default context.

Nota:

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Valorile întoarse

Returns the default stream context.

Exemple

Example #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');
?>

A se vedea ?i

  • stream_context_create() - Creates a stream context
  • stream_context_get_default() - Retrieve the default stream context
  • Listing of supported wrappers with context options (Supported Protocols and Wrappers).

stream_context_get_params
stream_context_set_option
Func?ii de flux


Sets an option for a stream/wrapper/context

stream_context_set_default
stream_context_set_params
Func?ii de flux
PHP Manual

stream_context_set_option

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_context_set_option — Sets an option for a stream/wrapper/context

Descrierea

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

Parametri

stream_or_context

The stream or context resource to apply the options to.

options

The options to set for stream_or_context.

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

stream_context_set_default
stream_context_set_params
Func?ii de flux


Set parameters for a stream/wrapper/context

stream_context_set_option
stream_copy_to_stream
Func?ii de flux
PHP Manual

stream_context_set_params

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_context_set_params — Set parameters for a stream/wrapper/context

Descrierea

bool stream_context_set_params ( resource $stream_or_context , array $params )

Sets parameters on the specified context.

Parametri

stream_or_context

The stream or context to apply the parameters too.

params

An array of parameters to set.

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • stream_notification_callback() - A callback function for the notification context parameter
stream_context_set_option
stream_copy_to_stream
Func?ii de flux


Copies data from one stream to another

stream_context_set_params
stream_encoding
Func?ii de flux
PHP Manual

stream_copy_to_stream

(PHP 5, PHP 7)

stream_copy_to_stream — Copies data from one stream to another

Descrierea

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.

Parametri

source

The source stream

dest

The destination stream

maxlength

Maximum bytes to copy

offset

The offset where to start to copy data

Valorile întoarse

Returns the total count of bytes copied, sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Added the offset parameter

Exemple

Example #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";

?>

A se vedea ?i

  • copy() - Copies file

stream_context_set_params
stream_encoding
Func?ii de flux


Set character set for stream encoding

stream_copy_to_stream
stream_filter_append
Func?ii de flux
PHP Manual

stream_encoding

(No version information available, might only be in Git)

stream_encoding — Set character set for stream encoding

Descrierea

bool stream_encoding ( resource $stream [, string $encoding ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

stream_copy_to_stream
stream_filter_append
Func?ii de flux


Attach a filter to a stream

stream_encoding
stream_filter_prepend
Func?ii de flux
PHP Manual

stream_filter_append

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_filter_append — Attach a filter to a stream

Descrierea

resource stream_filter_append ( resource $stream , string $filtername [, int $read_write [, mixed $params ]] )

Adds filtername to the list of filters attached to stream.

Parametri

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().

Valorile întoarse

Returns a resource on success or FALSE on failure. The resource can be used to refer to this filter instance during a call to stream_filter_remove().

FALSE is returned if stream is not a resource or if filtername cannot be located.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Prior to PHP 5.1.0, this function returns TRUE on success sau FALSE în cazul e?ecului.

Exemple

Example #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

 */
?>

Note

Nota: When using custom (user) filters
stream_filter_register() must be called first in order to register the desired user filter to filtername.

Nota: 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().

Nota: 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.

A se vedea ?i

  • 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
Func?ii de flux


Attach a filter to a stream

stream_filter_append
stream_filter_register
Func?ii de flux
PHP Manual

stream_filter_prepend

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_filter_prepend — Attach a filter to a stream

Descrierea

resource stream_filter_prepend ( resource $stream , string $filtername [, int $read_write [, mixed $params ]] )

Adds filtername to the list of filters attached to stream.

Parametri

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().

Valorile întoarse

Returns a resource on success or FALSE on failure. The resource can be used to refer to this filter instance during a call to stream_filter_remove().

FALSE is returned if stream is not a resource or if filtername cannot be located.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Prior to PHP 5.1.0, this function returns TRUE on success sau FALSE în cazul e?ecului.

Note

Nota: When using custom (user) filters
stream_filter_register() must be called first in order to register the desired user filter to filtername.

Nota: 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().

Nota: 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.

A se vedea ?i

  • stream_filter_register() - Register a user defined stream filter
  • stream_filter_append() - Attach a filter to a stream
stream_filter_append
stream_filter_register
Func?ii de flux


Register a user defined stream filter

stream_filter_prepend
stream_filter_remove
Func?ii de flux
PHP Manual

stream_filter_register

(PHP 5, PHP 7)

stream_filter_register — Register a user defined stream filter

Descrierea

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.).

Parametri

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. 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 in php_user_filter - doing otherwise will lead to undefined behaviour.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

stream_filter_register() will return FALSE if the filtername is already defined.

Exemple

Example #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");

?>

Exemplul de mai sus va afi?a:

LINE1
WORD - 2
EASY AS 123

Example #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");
?>

Exemplul de mai sus va afi?a:

LINE1
WORD - 2
EASY AS 123

A se vedea ?i

  • 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
Func?ii de flux


Remove a filter from a stream

stream_filter_register
stream_get_contents
Func?ii de flux
PHP Manual

stream_filter_remove

(PHP 5 >= 5.1.0, PHP 7)

stream_filter_remove — Remove a filter from a stream

Descrierea

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.

Parametri

stream_filter

The stream filter to be removed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

Guvf vf a test

A se vedea ?i

  • 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
Func?ii de flux


Reads remainder of a stream into a string

stream_filter_remove
stream_get_filters
Func?ii de flux
PHP Manual

stream_get_contents

(PHP 5, PHP 7)

stream_get_contents — Reads remainder of a stream into a string

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a string sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | The offset was added.

Exemple

Example #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);
}

?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • fgets() - Gets line from file pointer
  • fread() - Binary-safe file read
  • fpassthru() - Output all remaining data on a file pointer

stream_filter_remove
stream_get_filters
Func?ii de flux


Retrieve list of registered filters

stream_get_contents
stream_get_line
Func?ii de flux
PHP Manual

stream_get_filters

(PHP 5, PHP 7)

stream_get_filters — Retrieve list of registered filters

Descrierea

array stream_get_filters ( void )

Retrieve the list of registered filters on the running system.

Valorile întoarse

Returns an indexed array containing the name of all stream filters available.

Exemple

Example #1 Using stream_get_filters()

<?php
$streamlist = stream_get_filters();
print_r($streamlist);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array (
  [0] => string.rot13
  [1] => string.toupper
  [2] => string.tolower
  [3] => string.base64
  [4] => string.quoted-printable
)

A se vedea ?i

  • stream_filter_register() - Register a user defined stream filter
  • stream_get_wrappers() - Retrieve list of registered streams
stream_get_contents
stream_get_line
Func?ii de flux


Gets line from stream resource up to a given delimiter

stream_get_filters
stream_get_meta_data
Func?ii de flux
PHP Manual

stream_get_line

(PHP 5, PHP 7)

stream_get_line — Gets line from stream resource up to a given delimiter

Descrierea

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.

Parametri

handle

A valid file handle.

length

The number of bytes to read from the handle.

ending

An optional string delimiter.

Valorile întoarse

Returns a string of up to length bytes read from the file pointed to by handle.

If an error occurs, returns FALSE.

A se vedea ?i

  • fread() - Binary-safe file read
  • fgets() - Gets line from file pointer
  • fgetc() - Gets character from file pointer
stream_get_filters
stream_get_meta_data
Func?ii de flux


Retrieves header/meta data from streams/file pointers

stream_get_line
stream_get_transports
Func?ii de flux
PHP Manual

stream_get_meta_data

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_get_meta_data — Retrieves header/meta data from streams/file pointers

Descrierea

array stream_get_meta_data ( resource $stream )

Returns information about an existing stream.

Parametri

stream

The stream can be any stream created by fopen(), fsockopen() and pfsockopen().

Valorile întoarse

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.

    Nota: 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.

  • 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.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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=Windows-1252
            [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] =>
)

Note

Nota:

This function does NOT work on sockets created by the Socket extension.

A se vedea ?i

  • 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
Func?ii de flux


Retrieve list of registered socket transports

stream_get_meta_data
stream_get_wrappers
Func?ii de flux
PHP Manual

stream_get_transports

(PHP 5, PHP 7)

stream_get_transports — Retrieve list of registered socket transports

Descrierea

array stream_get_transports ( void )

Returns an indexed array containing the name of all socket transports available on the running system.

Valorile întoarse

Returns an indexed array of socket transports names.

Exemple

Example #1 Using stream_get_transports()

<?php
$xportlist = stream_get_transports();
print_r($xportlist);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array (
  [0] => tcp
  [1] => udp
  [2] => unix
  [3] => udg
)

A se vedea ?i

  • stream_get_filters() - Retrieve list of registered filters
  • stream_get_wrappers() - Retrieve list of registered streams
stream_get_meta_data
stream_get_wrappers
Func?ii de flux


Retrieve list of registered streams

stream_get_transports
stream_is_local
Func?ii de flux
PHP Manual

stream_get_wrappers

(PHP 5, PHP 7)

stream_get_wrappers — Retrieve list of registered streams

Descrierea

array stream_get_wrappers ( void )

Retrieve list of registered streams available on the running system.

Valorile întoarse

Returns an indexed array containing the name of all stream wrappers available on the running system.

Exemple

Example #1 stream_get_wrappers() example

<?php
print_r(stream_get_wrappers());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => php
    [1] => file
    [2] => http
    [3] => ftp
    [4] => compress.bzip2
    [5] => compress.zlib
)

Example #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.';
}
?>

A se vedea ?i

  • stream_wrapper_register() - Register a URL wrapper implemented as a PHP class
stream_get_transports
stream_is_local
Func?ii de flux


Checks if a stream is a local stream

stream_get_wrappers
stream_notification_callback
Func?ii de flux
PHP Manual

stream_is_local

(PHP 5 >= 5.2.4, PHP 7)

stream_is_local — Checks if a stream is a local stream

Descrierea

bool stream_is_local ( mixed $stream_or_url )

Checks if a stream, or a URL, is a local one or not.

Parametri

stream_or_url

The stream resource or URL to check.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 stream_is_local() example

Basic usage example.

<?php
var_dump(stream_is_local("http://example.com"));
var_dump(stream_is_local("/etc"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
bool(true)

stream_get_wrappers
stream_notification_callback
Func?ii de flux


A callback function for the notification context parameter

stream_is_local
stream_register_wrapper
Func?ii de flux
PHP Manual

stream_notification_callback

(PHP 5 >= 5.2.0, PHP 7)

stream_notification_callback — A callback function for the notification context parameter

Descrierea

void stream_notification_callback ( int $notification_code , int $severity , string $message , int $message_code , int $bytes_transferred , int $bytes_max )

A callable function, used by the notification context parameter, called during an event.

Nota:

This is not a real function, only a prototype of how the function should be.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Connected...
Found the mime-type: text/html; CHARSET=Windows-1252
Being redirected to: http://no.php.net/contact
Connected...
Got the filesize: 0
Found the mime-type: text/html; CHARSET=Windows-1252
Being redirected to: http://no.php.net/contact.php
Connected...
Got the filesize: 4589
Found the mime-type: text/html;CHARSET=Windows-1252
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

Example #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=Windows-1252
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)

A se vedea ?i

  • Context parameters

stream_is_local
stream_register_wrapper
Func?ii de flux


Pseudonim pentru stream_wrapper_register

stream_notification_callback
stream_resolve_include_path
Func?ii de flux
PHP Manual

stream_register_wrapper

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_register_wrapper — Pseudonim pentru stream_wrapper_register()

Descrierea

Aceasta func?ie este pseudonim pentru: stream_wrapper_register().

stream_notification_callback
stream_resolve_include_path
Func?ii de flux


Resolve filename against the include path

stream_register_wrapper
stream_select
Func?ii de flux
PHP Manual

stream_resolve_include_path

(PHP 5 >= 5.3.2, PHP 7)

stream_resolve_include_path — Resolve filename against the include path

Descrierea

string stream_resolve_include_path ( string $filename )

Resolve filename against the include path according to the same rules as fopen()/include.

Parametri

filename

The filename to resolve.

Valorile întoarse

Returns a string containing the resolved absolute filename, sau FALSE în cazul e?ecului.

Exemple

Example #1 stream_resolve_include_path() example

Basic usage example.

<?php
var_dump(stream_resolve_include_path("test.php"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(22) "/var/www/html/test.php"

stream_register_wrapper
stream_select
Func?ii de flux


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
Func?ii de flux
PHP Manual

stream_select

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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

Descrierea

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.

Parametri

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.

Nota:

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).

Avertizare

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.

Valorile întoarse

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).

Exemple

Example #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 */
}
?>

Note

Nota:

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);
?>

Nota:

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";
}
?>

Nota:

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.

Nota:

Some streams (like zlib) cannot be selected by this function.

Nota:

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.

A se vedea ?i

  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
stream_resolve_include_path
stream_set_blocking
Func?ii de flux


Set blocking/non-blocking mode on a stream

stream_select
stream_set_chunk_size
Func?ii de flux
PHP Manual

stream_set_blocking

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_set_blocking — Set blocking/non-blocking mode on a stream

Descrierea

bool stream_set_blocking ( resource $stream , bool $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).

Parametri

stream

The stream.

mode

If mode is FALSE, the given stream will be switched to non-blocking mode, and if TRUE, 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

This function was previously called as set_socket_blocking() and later socket_set_blocking() but this usage is deprecated.

A se vedea ?i

  • 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_chunk_size
Func?ii de flux


Set the stream chunk size

stream_set_blocking
stream_set_read_buffer
Func?ii de flux
PHP Manual

stream_set_chunk_size

(PHP 5 >= 5.4.0, PHP 7)

stream_set_chunk_size — Set the stream chunk size

Descrierea

int stream_set_chunk_size ( resource $fp , int $chunk_size )

Set the stream chunk size.

Parametri

fp

The target stream.

chunk_size

The desired new chunk size.

Valorile întoarse

Returns the previous chunk size on success.

Will return FALSE if chunk_size is less than 1 or greater than PHP_INT_MAX.

Erori/Excep?ii

Will emit an E_WARNING level error if chunk_size is less than 1 or greater than PHP_INT_MAX.

stream_set_blocking
stream_set_read_buffer
Func?ii de flux


Set read file buffering on the given stream

stream_set_chunk_size
stream_set_timeout
Func?ii de flux
PHP Manual

stream_set_read_buffer

(PHP 5 >= 5.3.3, PHP 7)

stream_set_read_buffer — Set read file buffering on the given stream

Descrierea

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.

Parametri

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 read from that input stream.

Valorile întoarse

Returns 0 on success, or another value if the request cannot be honored.

A se vedea ?i

  • stream_set_write_buffer() - Sets write file buffering on the given stream
stream_set_chunk_size
stream_set_timeout
Func?ii de flux


Set timeout period on a stream

stream_set_read_buffer
stream_set_write_buffer
Func?ii de flux
PHP Manual

stream_set_timeout

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_set_timeout — Set timeout period on a stream

Descrierea

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.

Parametri

stream

The target stream.

seconds

The seconds part of the timeout to be set.

microseconds

The microseconds part of the timeout to be set.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #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;
    }

}
?>

Note

Nota:

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.

A se vedea ?i

  • fsockopen() - Open Internet or Unix domain socket connection
  • fopen() - Opens file or URL
stream_set_read_buffer
stream_set_write_buffer
Func?ii de flux


Sets write file buffering on the given stream

stream_set_timeout
stream_socket_accept
Func?ii de flux
PHP Manual

stream_set_write_buffer

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_set_write_buffer — Sets write file buffering on the given stream

Descrierea

int stream_set_write_buffer ( resource $stream , int $buffer )

Sets the buffering for write operations on the given stream to buffer bytes.

Parametri

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.

Valorile întoarse

Returns 0 on success, or another value if the request cannot be honored.

Exemple

Example #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) {
  if (stream_set_write_buffer($fp, 0) !== 0) {
      // changing the buffering failed
  }
  fwrite($fp, $output);
  fclose($fp);
}
?>

A se vedea ?i

  • fopen() - Opens file or URL
  • fwrite() - Binary-safe file write
stream_set_timeout
stream_socket_accept
Func?ii de flux


Accept a connection on a socket created by stream_socket_server

stream_set_write_buffer
stream_socket_client
Func?ii de flux
PHP Manual

stream_socket_accept

(PHP 5, PHP 7)

stream_socket_accept — Accept a connection on a socket created by stream_socket_server()

Descrierea

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().

Parametri

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.

Nota:

Can also be determined later using stream_socket_get_name().

Valorile întoarse

Returns a stream to the accepted socket connection sau FALSE în cazul e?ecului.

Note

Avertizare

This function should not be used with UDP server sockets. Instead, use stream_socket_recvfrom() and stream_socket_sendto().

A se vedea ?i

  • 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() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fwrite() - Binary-safe file write
  • fclose() - Closes an open file pointer
  • feof() - Tests for end-of-file on a file pointer
  • Func?ii cURL

stream_set_write_buffer
stream_socket_client
Func?ii de flux


Open Internet or Unix domain socket connection

stream_socket_accept
stream_socket_enable_crypto
Func?ii de flux
PHP Manual

stream_socket_client

(PHP 5, PHP 7)

stream_socket_client — Open Internet or Unix domain socket connection

Descrierea

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.

Nota:

The stream will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

Parametri

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.

Nota: This parameter only applies when not making asynchronous connection attempts.

Nota:

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().

Valorile întoarse

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.

Erori/Excep?ii

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.

Exemple

Example #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);
}
?>

Example #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);
}
?>

Note

Avertizare

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.

Nota: La specificarea unei adrese IPv6 numerice (de ex. fe80::1), ea trebuie cuprinsa între paranteze patrate ? de exemplu tcp://[fe80::1]:80.

Nota:

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 Lista transporturilor prin socket-e sus?inute for a list of built in transports.

A se vedea ?i

  • 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() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fwrite() - Binary-safe file write
  • fclose() - Closes an open file pointer
  • feof() - Tests for end-of-file on a file pointer
  • Func?ii cURL

stream_socket_accept
stream_socket_enable_crypto
Func?ii de flux


Turns encryption on/off on an already connected socket

stream_socket_client
stream_socket_get_name
Func?ii de flux
PHP Manual

stream_socket_enable_crypto

(PHP 5 >= 5.1.0, PHP 7)

stream_socket_enable_crypto — Turns encryption on/off on an already connected socket

Descrierea

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.

Parametri

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_ANY_CLIENT
  • STREAM_CRYPTO_METHOD_TLS_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv2_SERVER
  • STREAM_CRYPTO_METHOD_SSLv3_SERVER
  • STREAM_CRYPTO_METHOD_SSLv23_SERVER
  • STREAM_CRYPTO_METHOD_ANY_SERVER
  • STREAM_CRYPTO_METHOD_TLS_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_0_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_1_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_2_SERVER

If omitted, the crypto_type context option on the stream's SSL context will be used instead.

session_stream

Seed the stream with settings from session_stream.

Valorile întoarse

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).

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Introduce STREAM_CRYPTO_METHOD_ANY_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT, STREAM_CRYPTO_METHOD_ANY_SERVER, STREAM_CRYPTO_METHOD_TLSv1_0_SERVER, STREAM_CRYPTO_METHOD_TLSv1_1_SERVER, STREAM_CRYPTO_METHOD_TLSv1_2_SERVER.
5.6.0 | The crypto_type is now optional.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

A se vedea ?i

  • Func?ii OpenSSL
    •

  • Lista transporturilor prin socket-e sus?inute
    •

stream_socket_client

stream_socket_get_name

Func?ii de flux


Retrieve the name of the local or remote sockets

stream_socket_enable_crypto
stream_socket_pair
Func?ii de flux
PHP Manual

stream_socket_get_name

(PHP 5, PHP 7)

stream_socket_get_name — Retrieve the name of the local or remote sockets

Descrierea

string stream_socket_get_name ( resource $handle , bool $want_peer )

Returns the local or remote name of a given socket connection.

Parametri

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.

Valorile întoarse

The name of the socket.

A se vedea ?i

  • stream_socket_accept() - Accept a connection on a socket created by stream_socket_server

stream_socket_enable_crypto
stream_socket_pair
Func?ii de flux


Creates a pair of connected, indistinguishable socket streams

stream_socket_get_name
stream_socket_recvfrom
Func?ii de flux
PHP Manual

stream_socket_pair

(PHP 5 >= 5.1.0, PHP 7)

stream_socket_pair — Creates a pair of connected, indistinguishable socket streams

Descrierea

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).

Parametri

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

Nota: Please consult the Streams constant list for further details on each constant.

Valorile întoarse

Returns an array with the two socket resources on success, or FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on Windows platforms.

Exemple

Example #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]);
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

child PID: 1378
message from child

stream_socket_get_name
stream_socket_recvfrom
Func?ii de flux


Receives data from a socket, connected or not

stream_socket_pair
stream_socket_sendto
Func?ii de flux
PHP Manual

stream_socket_recvfrom

(PHP 5, PHP 7)

stream_socket_recvfrom — Receives data from a socket, connected or not

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the read data, as a string

Exemple

Example #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);
?>

Note

Nota:

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).

Nota:

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.

A se vedea ?i

  • 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
Func?ii de flux


Sends a message to a socket, whether it is connected or not

stream_socket_recvfrom
stream_socket_server
Func?ii de flux
PHP Manual

stream_socket_sendto

(PHP 5, PHP 7)

stream_socket_sendto — Sends a message to a socket, whether it is connected or not

Descrierea

int stream_socket_sendto ( resource $socket , string $data [, int $flags = 0 [, string $address ]] )

Sends the specified data through the socket.

Parametri

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.

Valorile întoarse

Returns a result code, as an integer.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii de flux


Create an Internet or Unix domain server socket

stream_socket_sendto
stream_socket_shutdown
Func?ii de flux
PHP Manual

stream_socket_server

(PHP 5, PHP 7)

stream_socket_server — Create an Internet or Unix domain server socket

Descrierea

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().

Parametri

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 Lista transporturilor prin socket-e sus?inute 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.

Nota:

For UDP sockets, you must use STREAM_SERVER_BIND as the flags parameter.

context

Valorile întoarse

Returns the created stream, or FALSE on error.

Exemple

Example #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().

Nota: Most systems require root access to create a server socket on a port below 1024.

Example #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);

?>

Note

Nota: La specificarea unei adrese IPv6 numerice (de ex. fe80::1), ea trebuie cuprinsa între paranteze patrate ? de exemplu tcp://[fe80::1]:80.

A se vedea ?i

  • 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() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fwrite() - Binary-safe file write
  • fclose() - Closes an open file pointer
  • feof() - Tests for end-of-file on a file pointer
  • Curl extension
stream_socket_sendto
stream_socket_shutdown
Func?ii de flux


Shutdown a full-duplex connection

stream_socket_server
stream_supports_lock
Func?ii de flux
PHP Manual

stream_socket_shutdown

(PHP 5 >= 5.2.1, PHP 7)

stream_socket_shutdown — Shutdown a full-duplex connection

Descrierea

bool stream_socket_shutdown ( resource $stream , int $how )

Shutdowns (partially or not) a full-duplex connection.

Nota:

The associated buffer, or buffers, may or may not be emptied.

Parametri

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(5)

Notice: fputs(): send of 5 bytes failed with errno=32 Broken pipe in test.php on line 9
int(0)

A se vedea ?i

  • fclose() - Closes an open file pointer

stream_socket_server
stream_supports_lock
Func?ii de flux


Tells whether the stream supports locking.

stream_socket_shutdown
stream_wrapper_register
Func?ii de flux
PHP Manual

stream_supports_lock

(PHP 5 >= 5.3.0, PHP 7)

stream_supports_lock — Tells whether the stream supports locking.

Descrierea

bool stream_supports_lock ( resource $stream )

Tells whether the stream supports locking through flock().

Parametri

stream

The stream to check.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • flock() - Portable advisory file locking

stream_socket_shutdown
stream_wrapper_register
Func?ii de flux


Register a URL wrapper implemented as a PHP class

stream_supports_lock
stream_wrapper_restore
Func?ii de flux
PHP Manual

stream_wrapper_register

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

stream_wrapper_register — Register a URL wrapper implemented as a PHP class

Descrierea

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.).

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

stream_wrapper_register() will return FALSE if the protocol already has a handler.

Istoricul schimbarilor

Versiune | Descriere
5.2.4 | Added the flags parameter.

Exemple

Example #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");
}

?>

Exemplul de mai sus va afi?a:

line1
line2
line3
string(18) "line1
line2
line3
"

A se vedea ?i

  • 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
Func?ii de flux


Restores a previously unregistered built-in wrapper

stream_wrapper_register
stream_wrapper_unregister
Func?ii de flux
PHP Manual

stream_wrapper_restore

(PHP 5 >= 5.1.0, PHP 7)

stream_wrapper_restore — Restores a previously unregistered built-in wrapper

Descrierea

bool stream_wrapper_restore ( string $protocol )

Restores a built-in wrapper previously unregistered with stream_wrapper_unregister().

Parametri

protocol

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

stream_wrapper_register
stream_wrapper_unregister
Func?ii de flux


Unregister a URL wrapper

stream_wrapper_restore
Tidy
Func?ii de flux
PHP Manual

stream_wrapper_unregister

(PHP 5 >= 5.1.0, PHP 7)

stream_wrapper_unregister — Unregister a URL wrapper

Descrierea

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().

Parametri

protocol

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

stream_wrapper_restore
Tidy
Func?ii de flux


Tidy

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Tidy example
  • 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 — Returns the parent node of the current node
    • tidyNode::hasChildren — Checks if a node has children
    • tidyNode::hasSiblings — Checks if a node has siblings
    • tidyNode::isAsp — Checks if this node is ASP
    • tidyNode::isComment — Checks if a node represents a comment
    • tidyNode::isHtml — Checks if a node is part of a HTML document
    • tidyNode::isJste — Checks if this node is JSTE
    • tidyNode::isPhp — Checks if a node is PHP
    • tidyNode::isText — Checks if a node represents text (no markup)
  • Func?ii Tidy
    • ob_tidyhandler — ob_start callback function to repair the buffer
    • tidy_access_count — Returns the Number of Tidy accessibility warnings encountered for specified document
    • tidy_config_count — Returns the Number of Tidy configuration errors encountered for specified document
    • tidy_error_count — Returns the Number of Tidy errors encountered for specified document
    • tidy_get_output — Return a string representing the parsed tidy markup
    • tidy_load_config — Load an ASCII Tidy configuration file with the specified encoding
    • tidy_reset_config — Restore Tidy configuration to default values
    • tidy_save_config — Save current settings to named file
    • tidy_set_encoding — Set the input/output character encoding for parsing markup
    • tidy_setopt — Updates the configuration settings for the specified tidy document
    • tidy_warning_count — Returns the Number of Tidy warnings encountered for specified document
stream_wrapper_unregister
Introducere
Alte extensii de baza


Introducere

Tidy is a binding for the Tidy HTML clean and repair utility which allows you to not only clean and otherwise manipulate HTML documents, but also traverse the document tree.

Tidy
Instalarea / configurarea
Tidy


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Tidy


Necesita?i

To use Tidy, you will need libtidy installed, available on the tidy homepage » http://tidy.sourceforge.net/.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

This extension is bundled with PHP 5 and greater, and is installed using the --with-tidy configure option.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Tidy Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
tidy.default_config | "" | PHP_INI_SYSTEM |
tidy.clean_output | "0" | PHP_INI_USER | PHP_INI_PERDIR prior to PHP 5.4.0
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

tidy.default_config string

Default path for tidy config file.

tidy.clean_output boolean

Turns on/off the output repairing by Tidy.

Avertizare

Do not turn on tidy.clean_output if you are generating non-html content such as dynamic images.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Each TIDY_TAG_XXX represents a HTML tag. For example, TIDY_TAG_A represents a "<a href="XX">link</a>" tag. Each TIDY_ATTR_XXX represents a HTML attribute. For example TIDY_ATTR_HREF would represent the href attribute in the previous example.

The following constants are defined:

tidy tag constants
constant
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_TT
TIDY_TAG_U
TIDY_TAG_UL
TIDY_TAG_VAR
TIDY_TAG_WBR
TIDY_TAG_XMP

tidy attribute constants
constant
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

tidy nodetype constants
constant | description
TIDY_NODETYPE_ROOT | root node
TIDY_NODETYPE_DOCTYPE | doctype
TIDY_NODETYPE_COMMENT | HTML comment
TIDY_NODETYPE_PROCINS | Processing Instruction
TIDY_NODETYPE_TEXT | Text
TIDY_NODETYPE_START | start tag
TIDY_NODETYPE_END | end tag
TIDY_NODETYPE_STARTEND | empty tag
TIDY_NODETYPE_CDATA | CDATA
TIDY_NODETYPE_SECTION | XML section
TIDY_NODETYPE_ASP | ASP code
TIDY_NODETYPE_JSTE | JSTE code
TIDY_NODETYPE_PHP | PHP code
TIDY_NODETYPE_XMLDECL | XML declaration

Tipurile resurselor
Exemple
Tidy


Exemple

Cuprins

  • Tidy example
Constante predefinite
Tidy example
Tidy


Tidy example

This simple example shows basic Tidy usage.

Example #1 Basic Tidy usage

<?php
ob_start();
?>
<html>a html document</html>
<?php
$html = ob_get_clean();

// Specify configuration
$config = array(
           'indent'         => true,
           'output-xhtml'   => true,
           'wrap'           => 200);

// Tidy
$tidy = new tidy;
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();

// Output
echo $tidy;
?>

Exemple
tidy
Exemple


The tidy class

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

Introducere

An HTML node in an HTML file, as detected by tidy.

Sinopsisul clasei

tidy {
/* Proprieta?i */
string $errorBuffer;
/* Metode */
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 )
}

Cuprins

  • 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
Tidy example
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, PHP 7, 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

Descrierea

Stil obiect-orientat

tidyNode tidy::body ( void )

Stil procedural

tidyNode tidy_get_body ( tidy $object )

Returns a tidyNode object starting from the <body> tag of the tidy parse tree.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Returns a tidyNode object starting from the <body> tag of the tidy parse tree.

Exemple

Example #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;
?>

Exemplul de mai sus va afi?a:

<body>
<p>paragraph</p>
</body>

Note

Nota: Aceasta func?ie este disponibila numai cu Zend Engine 2 (PHP >= 5.0.0).

A se vedea ?i

  • 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, PHP 7, PECL tidy >= 0.5.2)

tidy::cleanRepair -- tidy_clean_repair — Execute configured cleanup and repair operations on parsed markup

Descrierea

Stil obiect-orientat

bool tidy::cleanRepair ( void )

Stil procedural

bool tidy_clean_repair ( tidy $object )

This function cleans and repairs the given tidy object.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 tidy::cleanrepair() example

<?php
$html = '<p>test</I>';

$tidy = tidy_parse_string($html);
$tidy->cleanRepair();

echo $tidy;
?>

Exemplul de mai sus va afi?a:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

A se vedea ?i

  • 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, PHP 7, PECL tidy >= 0.5.2)

tidy::__construct — Constructs a new tidy object

Descrierea

tidy::__construct ([ string $filename [, mixed $config [, string $encoding [, bool $use_include_path ]]]] )

Constructs a new tidy object.

Parametri

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.

Valorile întoarse

Returns the new tidy instance.

Exemple

Example #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;
}

?>

Exemplul de mai sus va afi?a:

The following errors were detected:
line 8 column 14 - Error: <bt> is not recognized!
line 8 column 14 - Warning: discarding unexpected <bt>

A se vedea ?i

  • 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, PHP 7, PECL tidy >= 0.5.2)

tidy::diagnose -- tidy_diagnose — Run configured diagnostics on parsed and repaired markup

Descrierea

Stil obiect-orientat

bool tidy::diagnose ( void )

Stil procedural

bool tidy_diagnose ( tidy $object )

Runs diagnostic tests on the given tidy object, adding some more information about the document in the error buffer.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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;

?>

Exemplul de mai sus va afi?a:

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!

A se vedea ?i

  • 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, PHP 7, PECL tidy >= 0.5.2)

tidy::$errorBuffer -- tidy_get_error_buffer — Return warnings and errors which occurred parsing the specified document

Descrierea

Stil obiect-orientat (property):

string $tidy->errorBuffer;

Stil procedural:

string tidy_get_error_buffer ( tidy $tidy )

Returns warnings and errors which occurred parsing the specified document.

Parametri

tidy

Obiectul Tidy.

Valorile întoarse

Returns the error buffer as a string.

Exemple

Example #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;
?>

Exemplul de mai sus va afi?a:

line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 1 - Warning: inserting missing 'title' element

A se vedea ?i

  • tidy_access_count() - Returns the Number of Tidy accessibility warnings encountered for specified document
  • tidy_error_count() - Returns the Number of Tidy errors encountered for specified document
  • tidy_warning_count() - Returns the Number of Tidy warnings encountered for specified document
tidy::diagnose
tidy::getConfig
tidy


Get current Tidy configuration

tidy::$errorBuffer
tidy::getHtmlVer
tidy
PHP Manual

tidy::getConfig

tidy_get_config

(PHP 5, PHP 7, PECL tidy >= 0.7.0)

tidy::getConfig -- tidy_get_config — Get current Tidy configuration

Descrierea

Stil obiect-orientat

array tidy::getConfig ( void )

Stil procedural

array tidy_get_config ( tidy $object )

Gets the list of the configuration options in use by the given tidy object.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Returns an array of configuration options.

For an explanation about each option, visit » http://tidy.sourceforge.net/docs/quickref.html.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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
)

A se vedea ?i

  • tidy_reset_config() - Restore Tidy configuration to default values
  • tidy_save_config() - Save current settings to named file
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, PHP 7, PECL tidy >= 0.5.2)

tidy::getHtmlVer -- tidy_get_html_ver — Get the Detected HTML version for the specified document

Descrierea

Stil obiect-orientat

int tidy::getHtmlVer ( void )

Stil procedural

int tidy_get_html_ver ( tidy $object )

Returns the detected HTML version for the specified tidy object.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Returns the detected HTML version.

Avertizare

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, PHP 7, PECL tidy >= 0.5.2)

tidy::getOpt -- tidy_getopt — Returns the value of the specified configuration option for the tidy document

Descrierea

Stil obiect-orientat

mixed tidy::getOpt ( string $option )

Stil procedural

mixed tidy_getopt ( tidy $object , string $option )

Returns the value of the specified option for the specified tidy object.

Parametri

object

Obiectul Tidy.

option

You will find a list with each configuration option and their types at: » http://tidy.sourceforge.net/docs/quickref.html.

Valorile întoarse

Returns the value of the specified option. The return type depends on the type of the specified one.

Exemple

Example #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

?>

Exemplul de mai sus va afi?a:

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, PHP 7)

tidy::getOptDoc -- tidy_get_opt_doc — Returns the documentation for the given option name

Descrierea

Stil obiect-orientat

string tidy::getOptDoc ( string $optname )

Stil procedural

string tidy_get_opt_doc ( tidy $object , string $optname )

tidy_get_opt_doc() returns the documentation for the given option name.

Nota:

You need at least libtidy from 25 April, 2005 for this function be available.

Parametri

object

Obiectul Tidy.

optname

The option name

Valorile întoarse

Returns a string if the option exists and has documentation available, or FALSE otherwise.

Exemple

Example #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";
}

?>

A se vedea ?i

  • 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, PHP 7, PECL tidy >= 0.5.2)

tidy::getRelease -- tidy_get_release — Get release date (version) for Tidy library

Descrierea

Stil obiect-orientat

string tidy::getRelease ( void )

Stil procedural

string tidy_get_release ( void )

Gets the release date of the Tidy library.

Valorile întoarse

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, PHP 7, PECL tidy >= 0.5.2)

tidy::getStatus -- tidy_get_status — Get status of specified document

Descrierea

Stil obiect-orientat

int tidy::getStatus ( void )

Stil procedural

int tidy_get_status ( tidy $object )

Returns the status for the specified tidy object.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Returns 0 if no error/warning was raised, 1 for warnings or accessibility errors, or 2 for errors.

Exemple

Example #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, PHP 7, 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

Descrierea

Stil obiect-orientat

tidyNode tidy::head ( void )

Stil procedural

tidyNode tidy_get_head ( tidy $object )

Returns a tidyNode object starting from the <head> tag of the tidy parse tree.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Returns the tidyNode object.

Exemple

Example #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;
?>

Exemplul de mai sus va afi?a:

<head>
<title>test</title>
</head>

Note

Nota: Aceasta func?ie este disponibila numai cu Zend Engine 2 (PHP >= 5.0.0).

A se vedea ?i

  • 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, PHP 7, 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

Descrierea

Stil obiect-orientat

tidyNode tidy::html ( void )

Stil procedural

tidyNode tidy_get_html ( tidy $object )

Returns a tidyNode object starting from the <html> tag of the tidy parse tree.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Returns the tidyNode object.

Exemple

Example #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;
?>

Exemplul de mai sus va afi?a:

<html>
<head>
<title>test</title>
</head>
<body>
<p>paragraph</p>
</body>
</html>

Note

Nota: Aceasta func?ie este disponibila numai cu Zend Engine 2 (PHP >= 5.0.0).

A se vedea ?i

  • 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, PHP 7, PECL tidy >= 0.5.2)

tidy::isXhtml -- tidy_is_xhtml — Indicates if the document is a XHTML document

Descrierea

Stil obiect-orientat

bool tidy::isXhtml ( void )

Stil procedural

bool tidy_is_xhtml ( tidy $object )

Tells if the document is a XHTML document.

Parametri

object

Obiectul Tidy.

Valorile întoarse

This function returns TRUE if the specified tidy object is a XHTML document, or FALSE otherwise.

Avertizare

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, PHP 7, PECL tidy >= 0.5.2)

tidy::isXml -- tidy_is_xml — Indicates if the document is a generic (non HTML/XHTML) XML document

Descrierea

Stil obiect-orientat

bool tidy::isXml ( void )

Stil procedural

bool tidy_is_xml ( tidy $object )

Tells if the document is a generic (non HTML/XHTML) XML document.

Parametri

object

Obiectul Tidy.

Valorile întoarse

This function returns TRUE if the specified tidy object is a generic XML document (non HTML/XHTML), or FALSE otherwise.

Avertizare

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, PHP 7, PECL tidy >= 0.5.2)

tidy::parseFile -- tidy_parse_file — Parse markup in file or URI

Descrierea

Stil obiect-orientat

bool tidy::parseFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Stil procedural

tidy tidy_parse_file ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Parses the given file.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 tidy::parseFile() example

<?php
$tidy = new tidy();
$tidy->parseFile('file.html');

$tidy->cleanRepair();

if(!empty($tidy->errorBuffer)) {
    echo "The following errors or warnings occurred:\n";
    echo $tidy->errorBuffer;
}
?>

Note

Nota: Parametrii op?ionali config ?i encoding au fost adauga?i în Tidy 2.0.

A se vedea ?i

  • 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, PHP 7, PECL tidy >= 0.5.2)

tidy::parseString -- tidy_parse_string — Parse a document stored in a string

Descrierea

Stil obiect-orientat

bool tidy::parseString ( string $input [, mixed $config [, string $encoding ]] )

Stil procedural

tidy tidy_parse_string ( string $input [, mixed $config [, string $encoding ]] )

Parses a document stored in a string.

Parametri

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.

Valorile întoarse

Returns a new tidy instance.

Exemple

Example #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;
?>

Exemplul de mai sus va afi?a:

<!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>

Note

Nota: Parametrii op?ionali config ?i encoding au fost adauga?i în Tidy 2.0.

A se vedea ?i

  • 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, PHP 7, PECL tidy >= 0.7.0)

tidy::repairFile -- tidy_repair_file — Repair a file and return it as a string

Descrierea

Stil obiect-orientat

string tidy::repairFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Stil procedural

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.

Parametri

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.

Valorile întoarse

Returns the repaired contents as a string.

Exemple

Example #1 tidy::repairFile() example

<?php
$file = 'file.html';

$tidy = new tidy();
$repaired = $tidy->repairfile($file);
rename($file, $file . '.bak');

file_put_contents($file, $repaired);
?>

Note

Nota: Parametrii op?ionali config ?i encoding au fost adauga?i în Tidy 2.0.

A se vedea ?i

  • 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, PHP 7, PECL tidy >= 0.7.0)

tidy::repairString -- tidy_repair_string — Repair a string using an optionally provided configuration file

Descrierea

Stil obiect-orientat

string tidy::repairString ( string $data [, mixed $config [, string $encoding ]] )

Stil procedural

string tidy_repair_string ( string $data [, mixed $config [, string $encoding ]] )

Repairs the given string.

Parametri

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.

Valorile întoarse

Returns the repaired string.

Exemple

Example #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;
?>

Exemplul de mai sus va afi?a:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>test</title>
</head>
<body>
<p>error</p>
</body>
</html>

Note

Nota: Parametrii op?ionali config ?i encoding au fost adauga?i în Tidy 2.0.

A se vedea ?i

  • 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, PHP 7, 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

Descrierea

Stil obiect-orientat

tidyNode tidy::root ( void )

Stil procedural

tidyNode tidy_get_root ( tidy $object )

Returns a tidyNode object representing the root of the tidy parse tree.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Returns the tidyNode object.

Exemple

Example #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);
        }
    }
}
?>

Exemplul de mai sus va afi?a:

..html
....head
......title
....body
......p
........"paragraph"
......br

Note

Nota: Aceasta func?ie este disponibila numai cu Zend Engine 2 (PHP >= 5.0.0).

tidy::repairString
tidyNode
tidy


The tidyNode class

(PHP 5 >= 5.0.1, PHP 7)

Introducere

An HTML node in an HTML file, as detected by tidy.

Sinopsisul clasei

tidyNode {
/* Proprieta?i */
string $value;
string $name;
int $type;
int $line;
int $column;
bool $proprietary;
int $id;
array $attribute;
array $child;
/* Metode */
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 )
}

Proprieta?i

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.

Versiune | Descriere
5.1.0 | line, column and proprietary were added

Cuprins

  • tidyNode::getParent — Returns the parent node of the current node
  • tidyNode::hasChildren — Checks if a node has children
  • tidyNode::hasSiblings — Checks if a node has siblings
  • tidyNode::isAsp — Checks if this node is ASP
  • tidyNode::isComment — Checks if a node represents a comment
  • tidyNode::isHtml — Checks if a node is part of a HTML document
  • tidyNode::isJste — Checks if this node is JSTE
  • tidyNode::isPhp — Checks if a node is PHP
  • tidyNode::isText — Checks if a node represents text (no markup)
tidy::root
tidyNode::getParent
Tidy


Returns the parent node of the current node

tidyNode
tidyNode::hasChildren
tidyNode
PHP Manual

tidyNode::getParent

(PHP 5 >= 5.2.2, PHP 7)

tidyNode::getParent — Returns the parent node of the current node

Descrierea

tidyNode tidyNode::getParent ( void )

Returns the parent node of the current node.

Exemple

Example #1 tidyNode::hasChildren() example

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  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);
?>

Exemplul de mai sus va afi?a:

string(4) "head"

Valorile întoarse

Returns a tidyNode if the node has a parent, or NULL otherwise.

tidyNode
tidyNode::hasChildren
tidyNode


Checks if a node has children

tidyNode::getParent
tidyNode::hasSiblings
tidyNode
PHP Manual

tidyNode::hasChildren

(PHP 5 >= 5.0.1, PHP 7)

tidyNode::hasChildren — Checks if a node has children

Descrierea

bool tidyNode::hasChildren ( void )

Tells if the node has children.

Valorile întoarse

Returns TRUE if the node has children, FALSE otherwise.

Exemple

Example #1 tidyNode::hasChildren() example

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

// the head tag
var_dump($tidy->html()->child[0]->hasChildren());

// the php inside the head tag
var_dump($tidy->html()->child[0]->child[0]->hasChildren());

?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)

tidyNode::getParent
tidyNode::hasSiblings
tidyNode


Checks if a node has siblings

tidyNode::hasChildren
tidyNode::isAsp
tidyNode
PHP Manual

tidyNode::hasSiblings

(PHP 5 >= 5.0.1, PHP 7)

tidyNode::hasSiblings — Checks if a node has siblings

Descrierea

bool tidyNode::hasSiblings ( void )

Tells if the node has siblings.

Valorile întoarse

Returns TRUE if the node has siblings, FALSE otherwise.

Exemple

Example #1 tidyNode::hasSiblings() example

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

// the html tag
var_dump($tidy->html()->hasSiblings());

// the head tag
var_dump($tidy->html()->child[0]->hasSiblings());

?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

tidyNode::hasChildren
tidyNode::isAsp
tidyNode


Checks if this node is ASP

tidyNode::hasSiblings
tidyNode::isComment
tidyNode
PHP Manual

tidyNode::isAsp

(PHP 5 >= 5.0.1, PHP 7)

tidyNode::isAsp — Checks if this node is ASP

Descrierea

bool tidyNode::isAsp ( void )

Tells whether the current node is ASP.

Valorile întoarse

Returns TRUE if the node is ASP, FALSE otherwise.

Exemple

Example #1 Extract ASP code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isAsp()) {
        echo "\n\n# asp node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

Exemplul de mai sus va afi?a:

# asp node #1
<%
  /* ASP code */
  response.write("Hello World!")
%>

tidyNode::hasSiblings
tidyNode::isComment
tidyNode


Checks if a node represents a comment

tidyNode::isAsp
tidyNode::isHtml
tidyNode
PHP Manual

tidyNode::isComment

(PHP 5 >= 5.0.1, PHP 7)

tidyNode::isComment — Checks if a node represents a comment

Descrierea

bool tidyNode::isComment ( void )

Tells if the node is a comment.

Valorile întoarse

Returns TRUE if the node is a comment, FALSE otherwise.

Exemple

Example #1 Extract comments from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isComment()) {
        echo "\n\n# comment node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

Exemplul de mai sus va afi?a:

# jste node #1
<#
  /* JSTE code */
  alert('Hello World');
#>

tidyNode::isAsp
tidyNode::isHtml
tidyNode


Checks if a node is part of a HTML document

tidyNode::isComment
tidyNode::isJste
tidyNode
PHP Manual

tidyNode::isHtml

(PHP 5 >= 5.0.1, PHP 7)

tidyNode::isHtml — Checks if a node is part of a HTML document

Descrierea

bool tidyNode::isHtml ( void )

Tells if the node is part of HTML document.

Valorile întoarse

Returns TRUE if the node is part of a HTML document, FALSE otherwise.

Exemple

Example #1 Extract HTML code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {
    // check if the current node is of requested type
    if($node->isHtml()) {
        echo "\n\n# html node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

Exemplul de mai sus va afi?a:

# html node #1
<html>
<head>
<?php echo '<title>title</title>'; ?><#
  /* JSTE code */
  alert('Hello World');
#>
<title></title>
</head>
<body>
<?php
  // PHP code
  echo 'hello world!';
?><%
  /* ASP code */
  response.write("Hello World!")
%><!-- Comments -->
Hello WorldOutside HTML
</body>
</html>

# html node #2
<head>
<?php echo '<title>title</title>'; ?><#
  /* JSTE code */
  alert('Hello World');
#>
<title></title>
</head>

# html node #3
<?php echo '<title>title</title>'; ?>

# html node #4
<#
  /* JSTE code */
  alert('Hello World');
#>

# html node #5
<title></title>

# html node #6
<body>
<?php
  // PHP code
  echo 'hello world!';
?><%
  /* ASP code */
  response.write("Hello World!")
%><!-- Comments -->
Hello WorldOutside HTML
</body>

# html node #7
<?php
  // PHP code
  echo 'hello world!';
?>

# html node #8
<%
  /* ASP code */
  response.write("Hello World!")
%>

# html node #9
<!-- Comments -->

# html node #10
Hello World

# html node #11
Outside HTML

tidyNode::isComment
tidyNode::isJste
tidyNode


Checks if this node is JSTE

tidyNode::isHtml
tidyNode::isPhp
tidyNode
PHP Manual

tidyNode::isJste

(PHP 5 >= 5.0.1, PHP 7)

tidyNode::isJste — Checks if this node is JSTE

Descrierea

bool tidyNode::isJste ( void )

Tells if the node is JSTE.

Valorile întoarse

Returns TRUE if the node is JSTE, FALSE otherwise.

Exemple

Example #1 Extract JSTE code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isJste()) {
        echo "\n\n# jste node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

Exemplul de mai sus va afi?a:

# jste node #1
<#
  /* JSTE code */
  alert('Hello World');
#>

tidyNode::isHtml
tidyNode::isPhp
tidyNode


Checks if a node is PHP

tidyNode::isJste
tidyNode::isText
tidyNode
PHP Manual

tidyNode::isPhp

(PHP 5 >= 5.0.1, PHP 7)

tidyNode::isPhp — Checks if a node is PHP

Descrierea

bool tidyNode::isPhp ( void )

Tells if the node is PHP.

Valorile întoarse

Returns TRUE if the current node is PHP code, FALSE otherwise.

Exemple

Example #1 Extract PHP code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isPhp()) {
        echo "\n\n# php node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

Exemplul de mai sus va afi?a:

# php node #1
<?php echo '<title>title</title>'; ?>

# php node #2
<?php
  // PHP code
  echo 'hello world!';
?>

tidyNode::isJste
tidyNode::isText
tidyNode


Checks if a node represents text (no markup)

tidyNode::isPhp
Func?ii Tidy
tidyNode
PHP Manual

tidyNode::isText

(PHP 5 >= 5.0.1, PHP 7)

tidyNode::isText — Checks if a node represents text (no markup)

Descrierea

bool tidyNode::isText ( void )

Tells if the node represents a text (without any markup).

Valorile întoarse

Returns TRUE if the node represent a text, FALSE otherwise.

Exemple

Example #1 Extract text from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isText()) {
        echo "\n\n# text node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

Exemplul de mai sus va afi?a:

# text node #1
Hello World

# text node #2
Outside HTML

tidyNode::isPhp
Func?ii Tidy
tidyNode


Func?ii Tidy

Cuprins

  • ob_tidyhandler — ob_start callback function to repair the buffer
  • tidy_access_count — Returns the Number of Tidy accessibility warnings encountered for specified document
  • tidy_config_count — Returns the Number of Tidy configuration errors encountered for specified document
  • tidy_error_count — Returns the Number of Tidy errors encountered for specified document
  • tidy_get_output — Return a string representing the parsed tidy markup
  • tidy_load_config — Load an ASCII Tidy configuration file with the specified encoding
  • tidy_reset_config — Restore Tidy configuration to default values
  • tidy_save_config — Save current settings to named file
  • tidy_set_encoding — Set the input/output character encoding for parsing markup
  • tidy_setopt — Updates the configuration settings for the specified tidy document
  • tidy_warning_count — Returns the Number of Tidy warnings encountered for specified document
tidyNode::isText
ob_tidyhandler
Tidy


ob_start callback function to repair the buffer

Func?ii Tidy
tidy_access_count
Func?ii Tidy
PHP Manual

ob_tidyhandler

(PHP 5, PHP 7)

ob_tidyhandler — ob_start callback function to repair the buffer

Descrierea

string ob_tidyhandler ( string $input [, int $mode ] )

Callback function for ob_start() to repair the buffer.

Parametri

input

The buffer.

mode

The buffer mode.

Valorile întoarse

Returns the modified buffer.

Exemple

Example #1 ob_tidyhandler() example

<?php
ob_start('ob_tidyhandler');

echo '<p>test</i>';
?>

Exemplul de mai sus va afi?a:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

A se vedea ?i

  • ob_start() - Turn on output buffering

Func?ii Tidy
tidy_access_count
Func?ii Tidy


Returns the Number of Tidy accessibility warnings encountered for specified document

ob_tidyhandler
tidy_config_count
Func?ii Tidy
PHP Manual

tidy_access_count

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy_access_count — Returns the Number of Tidy accessibility warnings encountered for specified document

Descrierea

int tidy_access_count ( tidy $object )

tidy_access_count() returns the number of accessibility warnings found for the specified document.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Returns the number of warnings.

Exemple

Example #1 tidy_access_count() 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>';

// select the accessibility check level: 1, 2 or 3
$config = array('accessibility-check' => 3);

$tidy = new tidy();
$tidy->parseString($html, $config);
$tidy->cleanRepair();

/* Never forget to call this! */
$tidy->diagnose();

echo tidy_access_count($tidy); //5

?>

Note

Nota:

Due to the design of the TidyLib, you must call tidy_diagnose() before tidy_access_count() or it will return always 0. You must also need to enable the accessibility-check option.

A se vedea ?i

  • tidy_error_count() - Returns the Number of Tidy errors encountered for specified document
  • tidy_warning_count() - Returns the Number of Tidy warnings encountered for specified document

ob_tidyhandler
tidy_config_count
Func?ii Tidy


Returns the Number of Tidy configuration errors encountered for specified document

tidy_access_count
tidy_error_count
Func?ii Tidy
PHP Manual

tidy_config_count

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy_config_count — Returns the Number of Tidy configuration errors encountered for specified document

Descrierea

int tidy_config_count ( tidy $object )

Returns the number of errors encountered in the configuration of the specified tidy object.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Returns the number of errors.

Exemple

Example #1 tidy_config_count() example

<?php
$html = '<p>test</I>';

$config = array('doctype' => 'bogus');

$tidy = tidy_parse_string($html, $config);

/* This outputs 1, because 'bogus' isn't a valid doctype */
echo tidy_config_count($tidy);
?>

tidy_access_count
tidy_error_count
Func?ii Tidy


Returns the Number of Tidy errors encountered for specified document

tidy_config_count
tidy_get_output
Func?ii Tidy
PHP Manual

tidy_error_count

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy_error_count — Returns the Number of Tidy errors encountered for specified document

Descrierea

int tidy_error_count ( tidy $object )

Returns the number of Tidy errors encountered for the specified document.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Returns the number of errors.

Exemple

Example #1 tidy_error_count() example

<?php
$html = '<p>test</i>
<bogustag>bogus</bogustag>';

$tidy = tidy_parse_string($html);

echo tidy_error_count($tidy) . "\n"; //1

echo $tidy->errorBuffer;
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • tidy_access_count() - Returns the Number of Tidy accessibility warnings encountered for specified document
  • tidy_warning_count() - Returns the Number of Tidy warnings encountered for specified document
tidy_config_count
tidy_get_output
Func?ii Tidy


Return a string representing the parsed tidy markup

tidy_error_count
tidy_load_config
Func?ii Tidy
PHP Manual

tidy_get_output

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy_get_output — Return a string representing the parsed tidy markup

Descrierea

string tidy_get_output ( tidy $object )

Gets a string with the repaired html.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Returns the parsed tidy markup.

Exemple

Example #1 tidy_get_output() example

<?php

$html = '<p>paragraph</i>';
$tidy = tidy_parse_string($html);

$tidy->cleanRepair();

echo tidy_get_output($tidy);
?>

Exemplul de mai sus va afi?a:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>paragraph</p>
</body>
</html>

tidy_error_count
tidy_load_config
Func?ii Tidy


Load an ASCII Tidy configuration file with the specified encoding

tidy_get_output
tidy_reset_config
Func?ii Tidy
PHP Manual

tidy_load_config

(PECL tidy >= 0.5.2)

tidy_load_config — Load an ASCII Tidy configuration file with the specified encoding

Descrierea

void tidy_load_config ( string $filename , string $encoding )

Loads a Tidy configuration file, with the specified encoding.

Parametri

filename

encoding

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Nota: Aceasta func?ie este disponibila numai în Tidy 1.0. Ea a devenit învechita în Tidy 2.0 ?i de aceea a fost eliminata.

tidy_get_output
tidy_reset_config
Func?ii Tidy


Restore Tidy configuration to default values

tidy_load_config
tidy_save_config
Func?ii Tidy
PHP Manual

tidy_reset_config

(PECL tidy >= 0.7.0)

tidy_reset_config — Restore Tidy configuration to default values

Descrierea

bool tidy_reset_config ( void )

This function restores the Tidy configuration to the default values.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota: Aceasta func?ie este disponibila numai în Tidy 1.0. Ea a devenit învechita în Tidy 2.0 ?i de aceea a fost eliminata.

tidy_load_config
tidy_save_config
Func?ii Tidy


Save current settings to named file

tidy_reset_config
tidy_set_encoding
Func?ii Tidy
PHP Manual

tidy_save_config

(PECL tidy >= 0.5.2)

tidy_save_config — Save current settings to named file

Descrierea

bool tidy_save_config ( string $filename )

Saves current settings to the specified file. Only non-default values are written.

Parametri

filename

Path to the config file.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota: Aceasta func?ie este disponibila numai în Tidy 1.0. Ea a devenit învechita în Tidy 2.0 ?i de aceea a fost eliminata.

A se vedea ?i

  • tidy_get_config() - Get current Tidy configuration
  • tidy_getopt() - Returns the value of the specified configuration option for the tidy document
  • tidy_reset_config() - Restore Tidy configuration to default values
  • tidy_setopt() - Updates the configuration settings for the specified tidy document

tidy_reset_config
tidy_set_encoding
Func?ii Tidy


Set the input/output character encoding for parsing markup

tidy_save_config
tidy_setopt
Func?ii Tidy
PHP Manual

tidy_set_encoding

(PECL tidy >= 0.5.2)

tidy_set_encoding — Set the input/output character encoding for parsing markup

Descrierea

bool tidy_set_encoding ( string $encoding )

Sets the encoding for input/output documents.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota: Aceasta func?ie este disponibila numai în Tidy 1.0. Ea a devenit învechita în Tidy 2.0 ?i de aceea a fost eliminata.

tidy_save_config
tidy_setopt
Func?ii Tidy


Updates the configuration settings for the specified tidy document

tidy_set_encoding
tidy_warning_count
Func?ii Tidy
PHP Manual

tidy_setopt

(PECL tidy >= 0.5.2)

tidy_setopt — Updates the configuration settings for the specified tidy document

Descrierea

bool tidy_setopt ( string $option , mixed $value )

tidy_setopt() updates the specified option with a new value.

Parametri

option

The tidy option name. A list of available configuration options may be found at: » http://tidy.sourceforge.net/docs/quickref.html.

value

The tidy option name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 tidy_setopt() example

<?php
$html = '<p>test</i>';

$tidy = tidy_parse_string($html);

tidy_setopt('indent', FALSE);
?>

Note

Nota: Aceasta func?ie este disponibila numai în Tidy 1.0. Ea a devenit învechita în Tidy 2.0 ?i de aceea a fost eliminata.

A se vedea ?i

  • tidy_getopt() - Returns the value of the specified configuration option for the tidy document
  • tidy_get_config() - Get current Tidy configuration
  • tidy_reset_config() - Restore Tidy configuration to default values
  • tidy_save_config() - Save current settings to named file
tidy_set_encoding
tidy_warning_count
Func?ii Tidy


Returns the Number of Tidy warnings encountered for specified document

tidy_setopt
Tokenizer
Func?ii Tidy
PHP Manual

tidy_warning_count

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy_warning_count — Returns the Number of Tidy warnings encountered for specified document

Descrierea

int tidy_warning_count ( tidy $object )

Returns the number of Tidy warnings encountered for the specified document.

Parametri

object

Obiectul Tidy.

Valorile întoarse

Returns the number of warnings.

Exemple

Example #1 tidy_warning_count() example

<?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
?>

A se vedea ?i

  • tidy_error_count() - Returns the Number of Tidy errors encountered for specified document
  • tidy_access_count() - Returns the Number of Tidy accessibility warnings encountered for specified document

tidy_setopt
Tokenizer
Func?ii Tidy


Tokenizer

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii Tokenizer
    • token_get_all — Split given source into PHP tokens
    • token_name — Get the symbolic name of a given PHP token
tidy_warning_count
Introducere
Alte extensii de baza


Introducere

The tokenizer functions provide an interface to the PHP tokenizer embedded in the Zend Engine. Using these functions you may write your own PHP source analyzing or modification tools without having to deal with the language specification at the lexical level.

See also the appendix about tokens.

Tokenizer
Instalarea / configurarea
Tokenizer


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Tokenizer


Instalarea

These functions are enabled by default. You can disable tokenizer support with --disable-tokenizer .

Versiunea PHP pentru Windows sus?ine implicit aceasta extensie. Nu este nevoie sa încarca?i extensii suplimentare pentru a putea utiliza aceste func?ii.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

În cazul când extensia a fost compilata în PHP sau încarcata în mod dinamic la rulare, jetoanele enumerate în Lista semnelor interpretorului sunt definite ca constante.

Tipurile resurselor
Exemple
Tokenizer


Exemple

Here is a simple example PHP scripts using the tokenizer that will read in a PHP file, strip all comments from the source and print the pure code only.

Example #1 Strip comments with the tokenizer

<?php
/*
* T_ML_COMMENT does not exist in PHP 5.
* The following three lines define it in order to
* preserve backwards compatibility.
*
* The next two lines define the PHP 5 only T_DOC_COMMENT,
* which we will mask as T_ML_COMMENT for PHP 4.
*/
if (!defined('T_ML_COMMENT')) {
   define('T_ML_COMMENT', T_COMMENT);
} else {
   define('T_DOC_COMMENT', T_ML_COMMENT);
}

$source = file_get_contents('example.php');
$tokens = token_get_all($source);

foreach ($tokens as $token) {
   if (is_string($token)) {
       // simple 1-character token
       echo $token;
   } else {
       // token array
       list($id, $text) = $token;

       switch ($id) {
           case T_COMMENT:
           case T_ML_COMMENT: // we've defined this
           case T_DOC_COMMENT: // and this
               // no action on comments
               break;

           default:
               // anything else -> output "as is"
               echo $text;
               break;
       }
   }
}
?>
Constante predefinite
Func?ii Tokenizer
Tokenizer


Func?ii Tokenizer

Cuprins

  • token_get_all — Split given source into PHP tokens
  • token_name — Get the symbolic name of a given PHP token
Exemple
token_get_all
Tokenizer


Split given source into PHP tokens

Func?ii Tokenizer
token_name
Func?ii Tokenizer
PHP Manual

token_get_all

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

token_get_all — Split given source into PHP tokens

Descrierea

array token_get_all ( string $source [, int $flags = 0 ] )

token_get_all() parses the given source string into PHP language tokens using the Zend engine's lexical scanner.

For a list of parser tokens, see Lista semnelor interpretorului, or use token_name() to translate a token value into its string representation.

Parametri

source

The PHP source to parse.

flags

Valid flags:

  • TOKEN_PARSE - Recognises the ability to use reserved words in specific contexts.

Valorile întoarse

An array of token identifiers. Each individual token identifier is either a single character (i.e.: ;, ., >, !, etc...), or a three element array containing the token index in element 0, the string content of the original token in element 1 and the line number in element 2.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | Added the optional flags parameter along with the TOKEN_PARSE flag.
5.2.2 | Line numbers are returned in element 2

Exemple

Example #1 token_get_all() example

<?php
$tokens = token_get_all('<?php echo; ?>');

foreach ($tokens as $token) {
    if (is_array($token)) {
        echo "Line {$token[2]}: ", token_name($token[0]), " ('{$token[1]}')", PHP_EOL;
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Line 1: T_OPEN_TAG ('<?php ')
Line 1: T_ECHO ('echo')
Line 1: T_WHITESPACE (' ')
Line 1: T_CLOSE_TAG ('?>')

Example #2 token_get_all() incorrect usage example

<?php
$tokens = token_get_all('/* comment */');

foreach ($tokens as $token) {
    if (is_array($token)) {
        echo "Line {$token[2]}: ", token_name($token[0]), " ('{$token[1]}')", PHP_EOL;
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Line 1: T_INLINE_HTML ('/* comment */')
Note in the previous example that the string is parsed as T_INLINE_HTML rather than the expected T_COMMENT. This is because no open tag was used in the code provided. This would be equivalent to putting a comment outside of the PHP tags in a normal file.

Example #3 token_get_all() on a class using a reserved word example

<?php

$source = <<<'code'
<?php

class A
{
    const PUBLIC = 1;
}
code;

$tokens = token_get_all($source, TOKEN_PARSE);

foreach ($tokens as $token) {
    if (is_array($token)) {
        echo token_name($token[0]) , PHP_EOL;
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

T_OPEN_TAG
T_WHITESPACE
T_CLASS
T_WHITESPACE
T_STRING
T_CONST
T_WHITESPACE
T_STRING
T_LNUMBER
Without the TOKEN_PARSE flag, the penultimate token (T_STRING) would have been T_PUBLIC.

A se vedea ?i

  • token_name() - Get the symbolic name of a given PHP token

Func?ii Tokenizer
token_name
Func?ii Tokenizer


Get the symbolic name of a given PHP token

token_get_all
URL-uri
Func?ii Tokenizer
PHP Manual

token_name

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

token_name — Get the symbolic name of a given PHP token

Descrierea

string token_name ( int $token )

token_name() gets the symbolic name for a PHP token value.

Parametri

token

The token value.

Valorile întoarse

The symbolic name of the given token.

Exemple

Example #1 token_name() example

<?php
// 260 is the token value for the T_EVAL token
echo token_name(260);        // -> "T_EVAL"

// a token constant maps to its own name
echo token_name(T_FUNCTION); // -> "T_FUNCTION"
?>

A se vedea ?i

  • List of Parser Tokens

token_get_all
URL-uri
Func?ii Tokenizer


URL-uri

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii URL
    • base64_decode — Decodes data encoded with MIME base64
    • base64_encode — Encodes data with 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 — Parse a URL and return its components
    • rawurldecode — Decode URL-encoded strings
    • rawurlencode — URL-encode according to RFC 3986
    • urldecode — Decodes URL-encoded string
    • urlencode — URL-encodes string
token_name
Introducere
Alte extensii de baza


Introducere

Opera?ii asupra ?irurilor URL: codificarea, decodificarea ?i interpretarea.

URL-uri
Instalarea / configurarea
URL-uri


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
URL-uri


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

The following constants are meant to be used with parse_url() and are available since PHP 5.1.2.

PHP_URL_SCHEME (integer)
PHP_URL_HOST (integer)
Outputs the hostname of the URL parsed.
PHP_URL_PORT (integer)
Outputs the port of the URL parsed.
PHP_URL_USER (integer)
Outputs the user of the URL parsed.
PHP_URL_PASS (integer)
Outputs the password of the URL parsed.
PHP_URL_PATH (integer)
Outputs the path of the URL parsed.
PHP_URL_QUERY (integer)
Outputs the query string of the URL parsed.
PHP_URL_FRAGMENT (integer)
Outputs the fragment (string after the hashmark #) of the URL parsed.

The following constants are meant to be used with http_build_query().

PHP_QUERY_RFC1738 (integer)
Encoding is performed per » RFC 1738 and the application/x-www-form-urlencoded media type, which implies that spaces are encoded as plus (+) signs.
PHP_QUERY_RFC3986 (integer)
Encoding is performed according to » RFC 3986, and spaces will be percent encoded (%20).
Tipurile resurselor
Func?ii URL
URL-uri


Func?ii URL

Cuprins

  • base64_decode — Decodes data encoded with MIME base64
  • base64_encode — Encodes data with 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 — Parse a URL and return its components
  • rawurldecode — Decode URL-encoded strings
  • rawurlencode — URL-encode according to RFC 3986
  • urldecode — Decodes URL-encoded string
  • urlencode — URL-encodes string
Constante predefinite
base64_decode
URL-uri


Decodes data encoded with MIME base64

Func?ii URL
base64_encode
Func?ii URL
PHP Manual

base64_decode

(PHP 4, PHP 5, PHP 7)

base64_decode — Decodes data encoded with MIME base64

Descrierea

string base64_decode ( string $data [, bool $strict = false ] )

Decodes a base64 encoded data.

Parametri

data

The encoded data.

strict

Returns FALSE if input contains character from outside the base64 alphabet.

Valorile întoarse

Returns the original data sau FALSE în cazul e?ecului. The returned data may be binary.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | strict added

Exemple

Example #1 base64_decode() example

<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>

Exemplul de mai sus va afi?a:

This is an encoded string

A se vedea ?i

  • base64_encode() - Encodes data with MIME base64
  • » RFC 2045 section 6.8

Func?ii URL
base64_encode
Func?ii URL


Encodes data with MIME base64

base64_decode
get_headers
Func?ii URL
PHP Manual

base64_encode

(PHP 4, PHP 5, PHP 7)

base64_encode — Encodes data with MIME base64

Descrierea

string base64_encode ( string $data )

Encodes the given data with base64.

This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.

Base64-encoded data takes about 33% more space than the original data.

Parametri

data

The data to encode.

Valorile întoarse

The encoded data, as a string sau FALSE în cazul e?ecului.

Exemple

Example #1 base64_encode() example

<?php
$str = 'This is an encoded string';
echo base64_encode($str);
?>

Exemplul de mai sus va afi?a:

VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

A se vedea ?i

  • base64_decode() - Decodes data encoded with MIME base64
  • chunk_split() - Split a string into smaller chunks
  • convert_uuencode() - Uuencode a string
  • » RFC 2045 section 6.8

base64_decode
get_headers
Func?ii URL


Fetches all the headers sent by the server in response to a HTTP request

base64_encode
get_meta_tags
Func?ii URL
PHP Manual

get_headers

(PHP 5, PHP 7)

get_headers — Fetches all the headers sent by the server in response to a HTTP request

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns an indexed or associative array with the headers, or FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
5.1.3 | This function now uses the default stream context, which can be set/changed with the stream_context_set_default() function.

Exemple

Example #1 get_headers() example

<?php
$url = 'http://www.example.com';

print_r(get_headers($url));

print_r(get_headers($url, 1));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

Example #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');
?>

A se vedea ?i

  • apache_request_headers() - Fetch all HTTP request headers

base64_encode
get_meta_tags
Func?ii URL


Extracts all meta tag content attributes from a file and returns an array

get_headers
http_build_query
Func?ii URL
PHP Manual

get_meta_tags

(PHP 4, PHP 5, PHP 7)

get_meta_tags — Extracts all meta tag content attributes from a file and returns an array

Descrierea

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>.

Parametri

filename

The path to the HTML file, as a string. This can be a local file or an URL.

Example #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.

Valorile întoarse

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.

Exemple

Example #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
?>

Note

Nota:

Only meta tags with name attributes will be parsed. Quotes are not required.

A se vedea ?i

  • htmlentities() - Convert all applicable characters to HTML entities
  • urlencode() - URL-encodes string

get_headers
http_build_query
Func?ii URL


Generate URL-encoded query string

get_meta_tags
parse_url
Func?ii URL
PHP Manual

http_build_query

(PHP 5, PHP 7)

http_build_query — Generate URL-encoded query string

Descrierea

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.

Parametri

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 but may be overridden by specifying this parameter.

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).

Valorile întoarse

Returns a URL-encoded string.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #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;');

?>

Exemplul de mai sus va afi?a:

foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor

Example #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_');
?>

Exemplul de mai sus va afi?a:

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

Example #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

Nota:

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.

Example #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);
?>

Exemplul de mai sus va afi?a:

pub=publicParent&pub_bar%5Bpub%5D=publicChild

A se vedea ?i

  • parse_str() - Parses the string into variables
  • parse_url() - Parse a URL and return its components
  • urlencode() - URL-encodes string
  • array_walk() - Apply a user supplied function to every member of an array

get_meta_tags
parse_url
Func?ii URL


Parse a URL and return its components

http_build_query
rawurldecode
Func?ii URL
PHP Manual

parse_url

(PHP 4, PHP 5, PHP 7)

parse_url — Parse a URL and return its components

Descrierea

mixed parse_url ( string $url [, int $component = -1 ] )

This function parses a URL and returns an associative array containing any of the various components of the URL that are present.

This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.

Parametri

url

The URL to parse. Invalid characters are replaced by _.

component

Specify one of 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 to retrieve just a specific URL component as a string (except when PHP_URL_PORT is given, in which case the return value will be an integer).

Valorile întoarse

On seriously malformed URLs, parse_url() may return FALSE.

If the component parameter is omitted, an associative array is returned. At least one element will be present within the array. Potential keys within this array are:

  • scheme - e.g. http
  • host
  • port
  • user
  • pass
  • path
  • query - after the question mark ?
  • fragment - after the hashmark #

If the component parameter is specified, parse_url() returns a string (or an integer, in the case of PHP_URL_PORT) instead of an array. If the requested component doesn't exist within the given URL, NULL will be returned.

Istoricul schimbarilor

Versiune | Descriere
5.4.7 | Fixed host recognition when scheme is omitted and a leading component separator is present.
5.3.3 | Removed the E_WARNING that was emitted when URL parsing failed.
5.1.2 | Added the component parameter.

Exemple

Example #1 A parse_url() example

<?php
$url = 'http://username:password@hostname:9090/path?arg=value#anchor';

var_dump(parse_url($url));
var_dump(parse_url($url, PHP_URL_SCHEME));
var_dump(parse_url($url, PHP_URL_USER));
var_dump(parse_url($url, PHP_URL_PASS));
var_dump(parse_url($url, PHP_URL_HOST));
var_dump(parse_url($url, PHP_URL_PORT));
var_dump(parse_url($url, PHP_URL_PATH));
var_dump(parse_url($url, PHP_URL_QUERY));
var_dump(parse_url($url, PHP_URL_FRAGMENT));
?>

Exemplul de mai sus va afi?a:

array(8) {
  ["scheme"]=>
  string(4) "http"
  ["host"]=>
  string(8) "hostname"
  ["port"]=>
  int(9090)
  ["user"]=>
  string(8) "username"
  ["pass"]=>
  string(8) "password"
  ["path"]=>
  string(5) "/path"
  ["query"]=>
  string(9) "arg=value"
  ["fragment"]=>
  string(6) "anchor"
}
string(4) "http"
string(8) "username"
string(8) "password"
string(8) "hostname"
int(9090)
string(5) "/path"
string(9) "arg=value"
string(6) "anchor"

Example #2 A parse_url() example with missing scheme

<?php
$url = '//www.example.com/path?googleguy=googley';

// Prior to 5.4.7 this would show the path as "//www.example.com/path"
var_dump(parse_url($url));
?>

Exemplul de mai sus va afi?a:

array(3) {
  ["host"]=>
  string(15) "www.example.com"
  ["path"]=>
  string(5) "/path"
  ["query"]=>
  string(17) "googleguy=googley"
}

Note

Nota:

This function doesn't work with relative URLs.

Nota:

This function is intended specifically for the purpose of parsing URLs and not URIs. However, to comply with PHP's backwards compatibility requirements it makes an exception for the file:// scheme where triple slashes (file:///...) are allowed. For any other scheme this is invalid.

A se vedea ?i

  • pathinfo() - Returns information about a file path
  • parse_str() - Parses the string into variables
  • http_build_query() - Generate URL-encoded query string
  • dirname() - Returns a parent directory's path
  • basename() - Returns trailing name component of path
  • » RFC 3986

http_build_query
rawurldecode
Func?ii URL


Decode URL-encoded strings

parse_url
rawurlencode
Func?ii URL
PHP Manual

rawurldecode

(PHP 4, PHP 5, PHP 7)

rawurldecode — Decode URL-encoded strings

Descrierea

string rawurldecode ( string $str )

Returns a string in which the sequences with percent (%) signs followed by two hex digits have been replaced with literal characters.

Parametri

str

The URL to be decoded.

Valorile întoarse

Returns the decoded URL, as a string.

Exemple

Example #1 rawurldecode() example

<?php

echo rawurldecode('foo%20bar%40baz'); // foo bar@baz

?>

Note

Nota:

rawurldecode() does not decode plus symbols ('+') into spaces. urldecode() does.

A se vedea ?i

  • rawurlencode() - URL-encode according to RFC 3986
  • urldecode() - Decodes URL-encoded string
  • urlencode() - URL-encodes string
  • » RFC 3986

parse_url
rawurlencode
Func?ii URL


URL-encode according to RFC 3986

rawurldecode
urldecode
Func?ii URL
PHP Manual

rawurlencode

(PHP 4, PHP 5, PHP 7)

rawurlencode — URL-encode according to RFC 3986

Descrierea

string rawurlencode ( string $str )

Encodes the given string according to » RFC 3986.

Parametri

str

The URL to be encoded.

Valorile întoarse

Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in » RFC 3986 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).

Nota:

Prior to PHP 5.3.0, rawurlencode encoded tildes (~) as per » RFC 1738.

Istoricul schimbarilor

Versiune | Descriere
5.3.4 | Tilde characters are no longer encoded when rawurlencode() is used with EBCDIC strings.
5.3.0 | Now conforms to » RFC 3986.

Exemple

Example #1 including a password in an FTP URL

<?php
echo '<a href="ftp://user:', rawurlencode('foo @+%/'),
     '@ftp.example.com/x.txt">';
?>

Exemplul de mai sus va afi?a:

<a href="ftp://user:foo%20%40%2B%25%2F@ftp.example.com/x.txt">

Or, if you pass information in a PATH_INFO component of the URL:

Example #2 rawurlencode() example 2

<?php
echo '<a href="http://example.com/department_list_script/',
    rawurlencode('sales and marketing/Miami'), '">';
?>

Exemplul de mai sus va afi?a:

<a href="http://example.com/department_list_script/sales%20and%20marketing%2FMiami">

A se vedea ?i

  • rawurldecode() - Decode URL-encoded strings
  • urldecode() - Decodes URL-encoded string
  • urlencode() - URL-encodes string
  • » RFC 3986

rawurldecode
urldecode
Func?ii URL


Decodes URL-encoded string

rawurlencode
urlencode
Func?ii URL
PHP Manual

urldecode

(PHP 4, PHP 5, PHP 7)

urldecode — Decodes URL-encoded string

Descrierea

string urldecode ( string $str )

Decodes any %## encoding in the given string. Plus symbols ('+') are decoded to a space character.

Parametri

str

The string to be decoded.

Valorile întoarse

Returns the decoded string.

Exemple

Example #1 urldecode() example

<?php
$query = "my=apples&are=green+and+red";

foreach (explode('&', $query) as $chunk) {
    $param = explode("=", $chunk);

    if ($param) {
        printf("Value for parameter \"%s\" is \"%s\"<br/>\n", urldecode($param[0]), urldecode($param[1]));
    }
}
?>

Note

Avertizare

The superglobals $_GET and $_REQUEST are already decoded. Using urldecode() on an element in $_GET or $_REQUEST could have unexpected and dangerous results.

A se vedea ?i

  • urlencode() - URL-encodes string
  • rawurlencode() - URL-encode according to RFC 3986
  • rawurldecode() - Decode URL-encoded strings
  • » RFC 3986

rawurlencode
urlencode
Func?ii URL


URL-encodes string

urldecode
V8js
Func?ii URL
PHP Manual

urlencode

(PHP 4, PHP 5, PHP 7)

urlencode — URL-encodes string

Descrierea

string urlencode ( string $str )

This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.

Parametri

str

The string to be encoded.

Valorile întoarse

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the » RFC 3986 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.

Exemple

Example #1 urlencode() example

<?php
echo '<a href="mycgi?foo=', urlencode($userinput), '">';
?>

Example #2 urlencode() and htmlentities() example

<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>

Note

Nota:

Be careful about variables that may match HTML entities. Things like &amp, &copy and &pound are parsed by the browser and the actual entity is used instead of the desired variable name. This is an obvious hassle that the W3C has been telling people about for years. The reference is here: » http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2.

PHP supports changing the argument separator to the W3C-suggested semi-colon through the arg_separator .ini directive. Unfortunately most user agents do not send form data in this semi-colon separated format. A more portable way around this is to use &amp; instead of & as the separator. You don't need to change PHP's arg_separator for this. Leave it as &, but simply encode your URLs using htmlentities() or htmlspecialchars().

A se vedea ?i

  • urldecode() - Decodes URL-encoded string
  • htmlentities() - Convert all applicable characters to HTML entities
  • rawurlencode() - URL-encode according to RFC 3986
  • rawurldecode() - Decode URL-encoded strings
  • » RFC 3986

urldecode
V8js
Func?ii URL


Integrarea cu motorul Javascript V8

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Exemple
  • 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 — Clasa V8JsException
    • V8JsException::getJsFileName — The getJsFileName purpose
    • V8JsException::getJsLineNumber — The getJsLineNumber purpose
    • V8JsException::getJsSourceLine — The getJsSourceLine purpose
    • V8JsException::getJsTrace — The getJsTrace purpose
urlencode
Introducere
Alte extensii de baza


Introducere

Aceasta extensie încorporeaza » Motorul Javascript V8 în PHP.

V8js
Instalarea / configurarea
V8js


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
V8js


Necesita?i

PHP 5.3.3+, biblioteca ?i antetele V8 instalate în loca?iile corespunzatoare.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/v8js

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

V8js Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
v8js.max_disposed_contexts | 25 | PHP_INI_ALL |
v8js.flags |  | PHP_INI_ALL |

Iata o explica?ie pe scurt a directivelor de configurare.

v8js.max_disposed_contexts integer

Stabile?te limita contextelor disponibilizate înainte de a for?a V8 sa cure?e gunoiul.

v8js.flags string

Stabile?te fanioanele din linia de comanda a V8. Lista fanioanelor disponibile poate fi ob?inuta în regimul CLI stabilind parametrul la valoarea --help. De exemplu:

$ php -r 'ini_set("v8js.flags", "--help"); new V8Js;' | less

Nota:

Pentru ca aceste fanioane sa fie efective în timpul rularii, apelul ini_set() trebuie efectuat înainte ca obiectele V8Js sa fie instan?iate!

Instalarea
Tipurile resurselor
Instalarea / configurarea


Exemple

Utilizarea de baza

Example #1 Executarea de baza a unui Javascript

<?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);
}

?>

Exemplul de mai sus va afi?a:

Hello World!
int(13)
Tipurile resurselor
V8Js
V8js


The V8Js class

(PECL v8js >= 0.1.0)

Introducere

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.

Sinopsisul clasei

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 ]] )
}

Constante predefinite

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.

Cuprins

  • 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
Exemple
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

Descrierea

 public V8Js::__construct
  ([ string $object_name = "PHP"
 [, array $variables = array()
 [, array $extensions = array()
 [, bool $report_uncaught_exceptions = TRUE
]]]] )

Constructs a new V8Js object.

Parametri

object_name

The name of the object passed to Javascript.

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.

Nota:

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().

Valorile întoarse

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

Descrierea

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.

Parametri

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

Valorile întoarse

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

Descrierea

public static array V8Js::getExtensions ( void )

This function returns array of Javascript extensions registered using V8Js::registerExtension().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public V8JsException V8Js::getPendingException ( void )

Returns any pending uncaught Javascript exception as V8JsException left from earlier V8Js::executeString() call(s).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

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.

Parametri

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.

Nota:

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.

Valorile întoarse

Returns TRUE if extension was registered successfully, FALSE otherwise.

V8Js::getPendingException
V8JsException
V8Js


Clasa V8JsException

(PECL v8js >= 0.1.0)

Introducere

Sinopsisul clasei

V8JsException extends Exception {
/* Proprieta?i */
protected $JsFileName ;
protected $JsLineNumber ;
protected $JsSourceLine ;
protected $JsTrace ;
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode */
final public string getJsFileName ( void )
final public int getJsLineNumber ( void )
final public string getJsSourceLine ( void )
final public string getJsTrace ( void )
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Proprieta?i

JsFileName

JsLineNumber

JsSourceLine

JsTrace

Cuprins

  • 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

Descrierea

final public string V8JsException::getJsFileName ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

final public int V8JsException::getJsLineNumber ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

final public string V8JsException::getJsSourceLine ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

final public string V8JsException::getJsTrace ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

V8JsException::getJsSourceLine
Yaml
V8JsException


YAML Data Serialization

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Callbacks
    • Parse callbacks
    • Emit callbacks
  • Func?ii Yaml
    • 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
Introducere
Alte extensii de baza


Introducere

This extension implements the » YAML Ain't Markup Language (YAML) data serialization standard. Parsing and emiting are handled by the » LibYAML library.

Yaml
Instalarea / configurarea
Yaml


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Yaml


Necesita?i

This extension requires the » LibYAML C library version 0.1.0 or higher to be installed.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/yaml.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Yaml Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
yaml.decode_binary | 0 | PHP_INI_ALL |
yaml.decode_php | 1 | 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 |

Iata o explica?ie pe scurt a directivelor de configurare.

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_php boolean

On by default, but can be set to off to prevent serialized php objects which have the explicit tag "!php/object" from being unserialized.

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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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).
Tipurile resurselor
Exemple
Yaml


Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)
Constante predefinite
Callbacks
Yaml


Callbacks

Cuprins

  • Parse callbacks
  • Emit callbacks
Exemple
Parse callbacks
Yaml


Parse callbacks

Parse callbacks are invoked by yaml_parse(), yaml_parse_file() or yaml_parse_url() functions when a registered YAML tag is encountered. The callback is passed the tagged entity's value, the tag, and flags indicating the scalar entity style. The callback must return the data that the YAML parser should emit for this entity.

Example #1 Parse callback example

<?php
/**
 * Parsing callback for yaml tag.
 * @param mixed $value Data from yaml file
 * @param string $tag Tag that triggered callback
 * @param int $flags Scalar entity style (see YAML_*_SCALAR_STYLE)
 * @return mixed Value that YAML parser should emit for the given value
 */
function tag_callback ($value, $tag, $flags) {
  var_dump(func_get_args()); // debugging
  return "Hello {$value}";
}

$yaml = <<<YAML
greeting: !example/hello World
YAML;

$result = yaml_parse($yaml, 0, $ndocs, array(
    '!example/hello' => 'tag_callback',
  ));

var_dump($result);
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  [0]=>
  string(5) "World"
  [1]=>
  string(14) "!example/hello"
  [2]=>
  int(1)
}
array(1) {
  ["greeting"]=>
  string(11) "Hello World"
}
Callbacks
Emit callbacks
Callbacks


Emit callbacks

Emit callbacks are invoked when an instance of a registered class is emitted by yaml_emit() or yaml_emit_file(). The callback is passed the object to be emitted. The callback must return an array having two keys: "tag" and "data". The value associated with the "tag" key must be a string to be used as the YAML tag in the output. The value associated with the "data" key will be encoded as YAML and emitted in place of the intercepted object.

Example #1 Emit callback example

<?php
class EmitExample {
  public $data;    // data may be in any pecl/yaml suitable type

  public function __construct ($d) {
    $this->data = $d;
  }

  /**
   * Yaml emit callback function, referred on yaml_emit call by class name.
   *
   * Expected to return an array with 2 values:
   *   - 'tag': custom tag for this serialization
   *   - 'data': value to convert to yaml (array, string, bool, number)
   *
   * @param object $obj Object to be emitted
   * @return array Tag and surrogate data to emit
   */
  public static function yamlEmit (EmitExample $obj) {
    return array(
      'tag' => '!example/emit',
      'data' => $obj->data,
    );
  }
}

$emit_callbacks = array(
  'EmitExample' => array('EmitExample', 'yamlEmit')
);

$t = new EmitExample(array('a','b','c'));
$yaml = yaml_emit(
  array(
    'example' => $t,
  ),
  YAML_ANY_ENCODING,
  YAML_ANY_BREAK,
  $emit_callbacks
);
var_dump($yaml);
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(43) "---
example: !example/emit
- a
- b
- c
...
"
Parse callbacks
Func?ii Yaml
Callbacks


Func?ii Yaml

Cuprins

  • 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
Emit callbacks
yaml_emit_file
Yaml


Send the YAML representation of a value to a file

Func?ii Yaml
yaml_emit
Func?ii Yaml
PHP Manual

yaml_emit_file

(PECL yaml >= 0.5.0)

yaml_emit_file — Send the YAML representation of a value to a file

Descrierea

bool yaml_emit_file ( string $filename , mixed $data [, int $encoding = YAML_ANY_ENCODING [, int $linebreak = YAML_ANY_BREAK [, array $callbacks = null ]]] )

Generate a YAML representation of the provided data in the filename.

Parametri

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.

linebreak

Output linebreak style chosen from YAML_ANY_BREAK, YAML_CR_BREAK, YAML_LN_BREAK, YAML_CRLN_BREAK.

callbacks

Content handlers for emitting YAML nodes. Associative array of classname => callable mappings. See emit callbacks for more details.

Valorile întoarse

Returns TRUE on success.

Istoricul schimbarilor

Versiune | Descriere
1.1.0 | The callbacks parameter was added.

A se vedea ?i

  • yaml_emit() - Returns the YAML representation of a value
  • yaml_parse() - Parse a YAML stream

Func?ii Yaml
yaml_emit
Func?ii Yaml


Returns the YAML representation of a value

yaml_emit_file
yaml_parse_file
Func?ii Yaml
PHP Manual

yaml_emit

(PECL yaml >= 0.5.0)

yaml_emit — Returns the YAML representation of a value

Descrierea

string yaml_emit ( mixed $data [, int $encoding = YAML_ANY_ENCODING [, int $linebreak = YAML_ANY_BREAK [, array $callbacks = null ]]] )

Generate a YAML representation of the provided data.

Parametri

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.

linebreak

Output linebreak style chosen from YAML_ANY_BREAK, YAML_CR_BREAK, YAML_LN_BREAK, YAML_CRLN_BREAK.

callbacks

Content handlers for emitting YAML nodes. Associative array of classname => callable mappings. See emit callbacks for more details.

Valorile întoarse

Returns a YAML encoded string on success.

Istoricul schimbarilor

Versiune | Descriere
1.1.0 | The callbacks parameter was added.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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.
...
"

A se vedea ?i

  • 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
Func?ii Yaml


Parse a YAML stream from a file

yaml_emit
yaml_parse_url
Func?ii Yaml
PHP Manual

yaml_parse_file

(PECL yaml >= 0.4.0)

yaml_parse_file — Parse a YAML stream from a file

Descrierea

mixed yaml_parse_file ( string $filename [, int $pos = 0 [, int &$ndocs [, array $callbacks = null ]]] )

Convert all or part of a YAML document stream read from a file to a PHP variable.

Parametri

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 => callable mappings. See parse callbacks for more details.

Valorile întoarse

Returns the value encoded in input in appropriate PHP type sau FALSE în cazul e?ecului. If pos is -1 an array will be returned with one entry for each document found in the stream.

Note

Avertizare

Processing untrusted user input with yaml_parse_file() is dangerous if the use of unserialize() is enabled for nodes using the !php/object tag. This behavior can be disabled by using the yaml.decode_php ini setting.

A se vedea ?i

  • 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
Func?ii Yaml


Parse a Yaml stream from a URL

yaml_parse_file
yaml_parse
Func?ii Yaml
PHP Manual

yaml_parse_url

(PECL yaml >= 0.4.0)

yaml_parse_url — Parse a Yaml stream from a URL

Descrierea

mixed yaml_parse_url ( string $url [, int $pos = 0 [, int &$ndocs [, array $callbacks = null ]]] )

Convert all or part of a YAML document stream read from a URL to a PHP variable.

Parametri

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 => callable mappings. See parse callbacks for more

Valorile întoarse

Returns the value encoded in input in appropriate PHP type sau FALSE în cazul e?ecului. If pos is -1 an array will be returned with one entry for each document found in the stream.

Note

Avertizare

Processing untrusted user input with yaml_parse_url() is dangerous if the use of unserialize() is enabled for nodes using the !php/object tag. This behavior can be disabled by using the yaml.decode_php ini setting.

A se vedea ?i

  • 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
Func?ii Yaml


Parse a YAML stream

yaml_parse_url
Yaf
Func?ii Yaml
PHP Manual

yaml_parse

(PECL yaml >= 0.4.0)

yaml_parse — Parse a YAML stream

Descrierea

mixed yaml_parse ( string $input [, int $pos = 0 [, int &$ndocs [, array $callbacks = null ]]] )

Convert all or part of a YAML document stream to a PHP variable.

Parametri

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 => callable mappings. See parse callbacks for more details.

Valorile întoarse

Returns the value encoded in input in appropriate PHP type sau FALSE în cazul e?ecului. If pos is -1 an array will be returned with one entry for each document found in the stream.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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."
}

Note

Avertizare

Processing untrusted user input with yaml_parse() is dangerous if the use of unserialize() is enabled for nodes using the !php/object tag. This behavior can be disabled by using the yaml.decode_php ini setting.

A se vedea ?i

  • 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
Func?ii Yaml


Yet Another Framework

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Application Configuration
  • Yaf_Application — The Yaf_Application class
    • Yaf_Application::app — Retrieve 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::setDefaultAction — Change default action name
    • Yaf_Dispatcher::setDefaultController — Change default controller name
    • Yaf_Dispatcher::setDefaultModule — Change default module name
    • Yaf_Dispatcher::setErrorHandler — Set error handler
    • 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 — Yaf_Config_Ini constructor
    • 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 — Returns a PHP array
    • 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 — Returns a PHP array
    • 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 — foward to another action
    • Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose
    • Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose
    • Yaf_Controller_Abstract::getModuleName — Get module name
    • Yaf_Controller_Abstract::getRequest — Retrieve current request object
    • Yaf_Controller_Abstract::getResponse — Retrieve current response object
    • Yaf_Controller_Abstract::getView — Retrieve the view engine
    • Yaf_Controller_Abstract::getViewpath — The getViewpath purpose
    • Yaf_Controller_Abstract::init — Controller initializer
    • Yaf_Controller_Abstract::initView — The initView purpose
    • Yaf_Controller_Abstract::redirect — Redirect to a URL
    • Yaf_Controller_Abstract::render — Render view template
    • Yaf_Controller_Abstract::setViewpath — The setViewpath purpose
  • Yaf_Action_Abstract — The Yaf_Action_Abstract class
    • Yaf_Action_Abstract::execute — Action entry point
    • Yaf_Action_Abstract::getController — Retrieve controller object
  • 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::clear — Clear Assigned values
    • Yaf_View_Simple::__construct — Constructor of Yaf_View_Simple
    • Yaf_View_Simple::display — Render and display
    • Yaf_View_Simple::eval — Render template
    • Yaf_View_Simple::__get — Retrieve assigned variable
    • Yaf_View_Simple::getScriptPath — Get templates 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 tempaltes 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 — register local class prefix
    • 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 — Yaf_Registry implements singleton
    • Yaf_Registry::del — Remove an item from registry
    • Yaf_Registry::get — Retrieve an item from registry
    • Yaf_Registry::has — Check whether an item exists
    • Yaf_Registry::set — Add an item into registry
  • 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 — Retrieve ENV varialbe
    • 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 — Retrieve SERVER variable
    • 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 — set base URI
    • 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 — Constructor of Yaf_Request_Http
    • Yaf_Request_Http::get — Retrieve variable from client
    • Yaf_Request_Http::getCookie — Retrieve Cookie variable
    • Yaf_Request_Http::getFiles — The getFiles purpose
    • Yaf_Request_Http::getPost — Retrieve POST variable
    • Yaf_Request_Http::getQuery — Fetch a query parameter
    • Yaf_Request_Http::getRequest — The getRequest purpose
    • Yaf_Request_Http::isXmlHttpRequest — Whether a Ajax Request
  • Yaf_Request_Simple — The Yaf_Request_Simple class
    • Yaf_Request_Simple::__clone — The __clone purpose
    • Yaf_Request_Simple::__construct — Constructor of Yaf_Request_Simple
    • 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 — append to body
    • 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 — Retrieve a exists content
    • Yaf_Response_Abstract::getHeader — The getHeader purpose
    • Yaf_Response_Abstract::prependBody — The prependBody purpose
    • Yaf_Response_Abstract::response — send response
    • Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose
    • Yaf_Response_Abstract::setBody — Set content to response
    • 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::assemble — assemble a request
    • Yaf_Route_Interface::route — route a request
  • Yaf_Route_Map — The Yaf_Route_Map class
    • Yaf_Route_Map::assemble — Assemble a url
    • 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::assemble — Assemble a url
    • Yaf_Route_Regex::__construct — Yaf_Route_Regex constructor
    • Yaf_Route_Regex::route — The route purpose
  • Yaf_Route_Rewrite — The Yaf_Route_Rewrite class
    • Yaf_Route_Rewrite::assemble — Assemble a url
    • Yaf_Route_Rewrite::__construct — Yaf_Route_Rewrite constructor
    • 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 — Retrieve a route by name
    • Yaf_Router::getRoutes — Retrieve registered routes
    • Yaf_Router::route — The route purpose
  • Yaf_Route_Simple — The Yaf_Route_Simple class
    • Yaf_Route_Simple::assemble — Assemble a url
    • 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::assemble — Assemble a url
    • 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::assemble — Assemble a url
    • 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 — Constructor of Yaf_Session
    • 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
Introducere
Alte extensii de baza


Introducere

The Yet Another Framework (Yaf) extension is a PHP framework that is used to develop web applications.

Yaf requires PHP 5.2.1 or greater. Earlier versions may not work.

A simple Yaf benchmark can be found at » Yaf Performance.

For a quick start guide, please refer to the Tutorials section.

Yaf
Instalarea / configurarea
Yaf


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Yaf


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/yaf.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Yaf Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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_SYSTEM value |
yaf.environ | product | its PHP_INI_SYSTEM value |
yaf.use_namespace | 0 | its PHP_INI_ALL value |

Iata o explica?ie pe scurt a directivelor de configurare.

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, if Yaf_Loader can not find a class, it will return TRUE, and make the class autoloading failed immediately.

Nota:

Yaf will register its loader during a instantiation of Yaf_Application, so any other auto loaders which is register before the instantiation will be called before Yaf_Loader::autoload().

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 identify 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.

Nota:

Yaf examine the mtime of the ini file, if it was changed since last compiling, Yaf will reload it.

Avertizare

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.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 classes of Yaf will named in namespace style.

For example:

Yaf_Route_Rewrite => \Yaf\Route\Rewrite
Yaf_Request_Http  => \Yaf\Request\Http
There is a exception, that is some classes like Yaf_Controller_Abstract. The last component is a keyword of PHP, could not be used as a class name, so for such classes:
Yaf_Controller_Abstract => \Yaf\Controller_Abstract
Yaf_Route_Static => \Yaf\Route_Static

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)

Tipurile resurselor
Exemple
Yaf


Exemple

Example #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

Example #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();
?>

Example #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",
  )
}

Example #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

Example #5 Default controller

<?php
class IndexController extends Yaf_Controller_Abstract {
   /* default action */
   public function indexAction() {
       $this->_view->word = "hello world";
       //or
       // $this->getView()->word = "hello world";
   }
}
?>

Example #6 Default view template

<html>
 <head>
   <title>Hello World</title>
 </head>
 <body>
   <?php echo $word;?>
 </body>
</html>

Example #7 Run the Applicatioin

Exemplul de mai sus va afi?a ceva similar cu:

<html>
 <head>
   <title>Hello World</title>
 </head>
 <body>
   hello world
 </body>
</html>

Nota:

you can also generate above example by use Yaf codes generator, which could be found here yaf@github.

Constante predefinite
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 will merge the application configurations and user configurations automatically. The application configurations have prefix "yaf." or "application.". If both "yaf." and "application." exist, "application." will be accepted preferentially.

Example #1 An PHP array example

<?php
    $configs = array(
            "application" => array(
                "directory" => dirname(__FILE__),
                "dispatcher" => array(
                      "catchException" => 0,
                    ),
                "view" => array(
                       "ext" => "phtml",
                    ),
                ),
           );
    $app = new Yaf_Application($configs);
?>

Example #2 An ini file example

[yaf]
yaf.directory = APPLICATION_PATH "/appliation"
yaf.dispatcher.catchException = 0

[product : yaf]
; user configuration list here

Yaf Application Config
Denumire | Valoare implicita | Jurnal al modificarilor
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.defaultRoute |  |
application.dispatcher.throwException | 1 |
application.dispatcher.catchException | 0 |
application.dispatcher.defaultModule | "index" |
application.dispatcher.defaultController | "index" |
application.dispatcher.defaultAction | "index" |
application.system |  |

Iata o explica?ie pe scurt a directivelor de configurare.

application.directory string

The directory of the application, that is the folder which contains the "controllers", "views", "models", "plugins" folders.

Nota:

This config entry is the only one which doesn't has a default value. You should always define it manually.

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 scripts.

application.modules string

A comma-separated 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.

Nota:

After Yaf 2.1.6, this config entry can be an array. The library path will try to use the items setted in application.library.directory

application.library.directory string

Alias of application.library. 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, there is no need to set this value.

application.dispatcher.throwException bool

If it set to On, Yaf will throw an exception while some error occurring. See also Yaf_Dispatcher::throwException().

application.dispatcher.catchException bool

If it set to On, Yaf will forward to Error controller/Action while there is an unhandled exception. See also Yaf_Dispatcher::catchException().

application.dispatcher.defaultRoute string

The default Route, if it is not specificed, Static route will be used as default. See: Yaf_Router::addRoute().

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().

application.system string

Set yaf runtime configure in application.ini, like: application.system.lowcase_path

Nota:

only those PHP_INI_ALL configures can be set in this way

Exemple
Yaf_Application
Yaf


The Yaf_Application class

(No version information available, might only be in Git)

Introducere

Yaf_Application provides a bootstrapping facility for applications which provides reusable resources, common- and module-based bootstrap classes and dependency checking.

Nota:

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 problem.

Sinopsisul clasei

final Yaf_Application {
/* Proprieta?i */
protected $config ;
protected $dispatcher ;
protected static $_app ;
protected $_modules ;
protected $_running ;
protected $_environ ;
/* Metode */
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 ( callable $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 )
}

Proprieta?i

config

dispatcher

_app

_modules

_running

_environ

Cuprins

  • Yaf_Application::app — Retrieve 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


Retrieve an Application instance

Yaf_Application
Yaf_Application::bootstrap
Yaf_Application
PHP Manual

Yaf_Application::app

(Yaf >=1.0.0)

Yaf_Application::app — Retrieve an Application instance

Descrierea

public static void Yaf_Application::app ( void )

Retrieve the Yaf_Application instance. Alternatively, we also could use Yaf_Dispatcher::getApplication().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A Yaf_Application instance, if no Yaf_Application was initialized before, NULL will be returned.

A se vedea ?i

  • 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

(Yaf >=1.0.0)

Yaf_Application::bootstrap — Call bootstrap

Descrierea

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.

Parametri

bootstrap

A Yaf_Bootstrap_Abstract instance

Valorile întoarse

Yaf_Application instance

Exemple

Example #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";
    }
}
?>

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

1st called
2nd called

A se vedea ?i

  • 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

(Yaf >=2.1.2)

Yaf_Application::clearLastError — Clear the last error info

Descrierea

public Yaf_Application Yaf_Application::clearLastError ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

(Yaf >=1.0.0)

Yaf_Application::__clone — Yaf_Application can not be cloned

Descrierea

private void Yaf_Application::__clone ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Application::clearLastError
Yaf_Application::__construct
Yaf_Application


Yaf_Application constructor

Yaf_Application::__clone
Yaf_Application::__destruct
Yaf_Application
PHP Manual

Yaf_Application::__construct

(Yaf >=1.0.0)

Yaf_Application::__construct — Yaf_Application constructor

Descrierea

public Yaf_Application::__construct ( mixed $config [, string $envrion ] )

Instance a Yaf_Application.

Parametri

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.

Nota:

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:

Example #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

Valorile întoarse

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

A se vedea ?i

  • 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

(Yaf >=1.0.0)

Yaf_Application::__destruct — The __destruct purpose

Descrierea

public void Yaf_Application::__destruct ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Application::__construct
Yaf_Application::environ
Yaf_Application


Retrive environ

Yaf_Application::__destruct
Yaf_Application::execute
Yaf_Application
PHP Manual

Yaf_Application::environ

(Yaf >=1.0.0)

Yaf_Application::environ — Retrive environ

Descrierea

public void Yaf_Application::environ ( void )

Retrive environ which was defined in yaf.environ which has a default value "product".

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

(Yaf >=1.0.0)

Yaf_Application::execute — Execute a callback

Descrierea

public void Yaf_Application::execute ( callable $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.

Parametri

entry

a valid callback

...

parameters will pass to the callback

Valorile întoarse

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

(Yaf >=2.1.4)

Yaf_Application::getAppDirectory — Get the application directory

Descrierea

public Yaf_Application Yaf_Application::getAppDirectory ( void )

Parametri

directory

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Application::getConfig — Retrive the config instance

Descrierea

public Yaf_Config_Abstract Yaf_Application::getConfig ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A Yaf_Config_Abstract instance

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

(Yaf >=1.0.0)

Yaf_Application::getDispatcher — Get Yaf_Dispatcher instance

Descrierea

public Yaf_Dispatcher Yaf_Application::getDispatcher ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

(Yaf >=2.1.2)

Yaf_Application::getLastErrorMsg — Get message of the last occurred error

Descrierea

public string Yaf_Application::getLastErrorMsg ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

(Yaf >=2.1.2)

Yaf_Application::getLastErrorNo — Get code of last occurred error

Descrierea

public int Yaf_Application::getLastErrorNo ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

(Yaf >=1.0.0)

Yaf_Application::getModules — Get defined module names

Descrierea

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".

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

(Yaf >=1.0.0)

Yaf_Application::run — Start Yaf_Application

Descrierea

public void Yaf_Application::run ( void )

Run a Yaf_Application, let the Yaf_Application accept a request and route this request, dispatch to controller/action and render response. Finally, return the response to the client.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=2.1.4)

Yaf_Application::setAppDirectory — Change the application directory

Descrierea

public Yaf_Application Yaf_Application::setAppDirectory ( string $directory )

Parametri

directory

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Application::__sleep — Yaf_Application can not be serialized

Descrierea

private void Yaf_Application::__sleep ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Application::__wakeup — Yaf_Application can not be unserialized

Descrierea

private void Yaf_Application::__wakeup ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Application::__sleep
Yaf_Bootstrap_Abstract
Yaf_Application


The Yaf_Bootstrap_Abstract class

(No version information available, might only be in Git)

Introducere

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.

Exemple

Example #1 Bootstrap example

<?php
   /* bootstrap class should be defined under ./application/Bootstrap.php */
   class Bootstrap extends Yaf_Bootstrap_Abstract {
        public function _initConfig(Yaf_Dispatcher $dispatcher) {
            var_dump(__METHOD__);
        }
        public function _initPlugin(Yaf_Dispatcher $dispatcher) {
            var_dump(__METHOD__);
        }
   }

   $config = array(
       "application" => array(
           "directory" => dirname(__FILE__) . "/application/",
       ),
   );

   $app = new Yaf_Application($config);
   $app->bootstrap();
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(22) "Bootstrap::_initConfig"
string(22) "Bootstrap::_initPlugin"

Sinopsisul clasei

abstract Yaf_Bootstrap_Abstract {
/* Proprieta?i */
/* Metode */
}
Yaf_Application::__wakeup
Yaf_Dispatcher
Yaf


The Yaf_Dispatcher class

(Yaf >=1.0.0)

Introducere

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.

Sinopsisul clasei

final Yaf_Dispatcher {
/* Proprieta?i */
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 ;
/* Metode */
public Yaf_Dispatcher autoRender ([ bool $flag ] )
public Yaf_Dispatcher catchException ([ bool $flag ] )
private void __clone ( void )
public __construct ( void )
public bool 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 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 )
}

Proprieta?i

_router

_view

_request

_plugins

_instance

_auto_render

_return_response

_instantly_flush

_default_module

_default_controller

_default_action

Cuprins

  • 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::setDefaultAction — Change default action name
  • Yaf_Dispatcher::setDefaultController — Change default controller name
  • Yaf_Dispatcher::setDefaultModule — Change default module name
  • Yaf_Dispatcher::setErrorHandler — Set error handler
  • 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

(Yaf >=1.0.0)

Yaf_Dispatcher::autoRender — Switch on/off autorendering

Descrierea

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

Nota:

you can simply return FALSE in a action to prevent the auto-rendering of that action

Parametri

flag

bool

Nota:

since 2.2.0, if this parameter is not given, then the current state will be renturned

Valorile întoarse

Exemple

Example #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);
         }
     }

}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

(Yaf >=1.0.0)

Yaf_Dispatcher::catchException — Switch on/off exception catching

Descrierea

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 uncaught Exceptions will be caught by ErrorController::error if you have defined one.

Parametri

flag

bool

Valorile întoarse

Exemple

Example #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 errorAction($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;
        }
     }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

/* 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

A se vedea ?i

  • Yaf_Dispatcher::throwException() - Switch on/off exception throwing
  • Yaf_Dispatcher::setErrorHandler() - Set error handler
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

(Yaf >=1.0.0)

Yaf_Dispatcher::__clone — Yaf_Dispatcher can not be cloned

Descrierea

private void Yaf_Dispatcher::__clone ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Dispatcher::catchException
Yaf_Dispatcher::__construct
Yaf_Dispatcher


Yaf_Dispatcher constructor

Yaf_Dispatcher::__clone
Yaf_Dispatcher::disableView
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::__construct

(Yaf >=1.0.0)

Yaf_Dispatcher::__construct — Yaf_Dispatcher constructor

Descrierea

public Yaf_Dispatcher::__construct ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Dispatcher::__clone
Yaf_Dispatcher::disableView
Yaf_Dispatcher


Disable view rendering

Yaf_Dispatcher::__construct
Yaf_Dispatcher::dispatch
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::disableView

(Yaf >=1.0.0)

Yaf_Dispatcher::disableView — Disable view rendering

Descrierea

public bool Yaf_Dispatcher::disableView ( void )

disable view engine, used in some app that user will output by theirself

Nota:

you can simply return FALSE in a action to prevent the auto-rendering of that action

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Dispatcher::__construct
Yaf_Dispatcher::dispatch
Yaf_Dispatcher


Dispatch a request

Yaf_Dispatcher::disableView
Yaf_Dispatcher::enableView
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::dispatch

(Yaf >=1.0.0)

Yaf_Dispatcher::dispatch — Dispatch a request

Descrierea

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.

Parametri

request

Valorile întoarse

Yaf_Dispatcher::disableView
Yaf_Dispatcher::enableView
Yaf_Dispatcher


enable view rendering

Yaf_Dispatcher::dispatch
Yaf_Dispatcher::flushInstantly
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::enableView

(Yaf >=1.0.0)

Yaf_Dispatcher::enableView — enable view rendering

Descrierea

public Yaf_Dispatcher Yaf_Dispatcher::enableView ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Dispatcher::flushInstantly — Switch on/off the instant flushing

Descrierea

public Yaf_Dispatcher Yaf_Dispatcher::flushInstantly ([ bool $flag ] )

Parametri

flag

bool

Nota:

since 2.2.0, if this parameter is not given, then the current state will be renturned

Valorile întoarse

Yaf_Dispatcher::enableView
Yaf_Dispatcher::getApplication
Yaf_Dispatcher


Retrive the application

Yaf_Dispatcher::flushInstantly
Yaf_Dispatcher::getInstance
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::getApplication

(Yaf >=1.0.0)

Yaf_Dispatcher::getApplication — Retrive the application

Descrierea

public Yaf_Application Yaf_Dispatcher::getApplication ( void )

Retrive the Yaf_Application instance. same as Yaf_Application::app().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • Yaf_Application::app() - Retrieve 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

(Yaf >=1.0.0)

Yaf_Dispatcher::getInstance — Retrive the dispatcher instance

Descrierea

public static Yaf_Dispatcher Yaf_Dispatcher::getInstance ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Dispatcher::getRequest — Retrive the request instance

Descrierea

public Yaf_Request_Abstract Yaf_Dispatcher::getRequest ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Dispatcher::getInstance
Yaf_Dispatcher::getRouter
Yaf_Dispatcher


Retrive router instance

Yaf_Dispatcher::getRequest
Yaf_Dispatcher::initView
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::getRouter

(Yaf >=1.0.0)

Yaf_Dispatcher::getRouter — Retrive router instance

Descrierea

public Yaf_Router Yaf_Dispatcher::getRouter ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Dispatcher::initView — Initialize view and return it

Descrierea

public Yaf_View_Interface Yaf_Dispatcher::initView ( string $templates_dir [, array $options ] )

Parametri

templates_dir

options

Valorile întoarse

Yaf_Dispatcher::getRouter
Yaf_Dispatcher::registerPlugin
Yaf_Dispatcher


Register a plugin

Yaf_Dispatcher::initView
Yaf_Dispatcher::returnResponse
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::registerPlugin

(Yaf >=1.0.0)

Yaf_Dispatcher::registerPlugin — Register a plugin

Descrierea

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).

Parametri

plugin

Valorile întoarse

Exemple

Example #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);
  }
}
?>

A se vedea ?i

  • Yaf_Plugin_Abstract
  • Yaf_Bootstrap_Abstract
Yaf_Dispatcher::initView
Yaf_Dispatcher::returnResponse
Yaf_Dispatcher


The returnResponse purpose

Yaf_Dispatcher::registerPlugin
Yaf_Dispatcher::setDefaultAction
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::returnResponse

(Yaf >=1.0.0)

Yaf_Dispatcher::returnResponse — The returnResponse purpose

Descrierea

public Yaf_Dispatcher Yaf_Dispatcher::returnResponse ( bool $flag )

Parametri

flag

Valorile întoarse

Yaf_Dispatcher::registerPlugin
Yaf_Dispatcher::setDefaultAction
Yaf_Dispatcher


Change default action name

Yaf_Dispatcher::returnResponse
Yaf_Dispatcher::setDefaultController
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setDefaultAction

(Yaf >=1.0.0)

Yaf_Dispatcher::setDefaultAction — Change default action name

Descrierea

public Yaf_Dispatcher Yaf_Dispatcher::setDefaultAction ( string $action )

Parametri

action

Valorile întoarse

Yaf_Dispatcher::returnResponse
Yaf_Dispatcher::setDefaultController
Yaf_Dispatcher


Change default controller name

Yaf_Dispatcher::setDefaultAction
Yaf_Dispatcher::setDefaultModule
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setDefaultController

(Yaf >=1.0.0)

Yaf_Dispatcher::setDefaultController — Change default controller name

Descrierea

public Yaf_Dispatcher Yaf_Dispatcher::setDefaultController ( string $controller )

Parametri

controller

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Dispatcher::setDefaultModule — Change default module name

Descrierea

public Yaf_Dispatcher Yaf_Dispatcher::setDefaultModule ( string $module )

Parametri

module

Valorile întoarse

Yaf_Dispatcher::setDefaultController
Yaf_Dispatcher::setErrorHandler
Yaf_Dispatcher


Set error handler

Yaf_Dispatcher::setDefaultModule
Yaf_Dispatcher::setRequest
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setErrorHandler

(Yaf >=1.0.0)

Yaf_Dispatcher::setErrorHandler — Set error handler

Descrierea

public Yaf_Dispatcher Yaf_Dispatcher::setErrorHandler ( call $callback , int $error_types )

Set error handler for Yaf. when application.dispatcher.throwException is off, Yaf will trigger catchable error while unexpected errors occrred.

Thus, this error handler will be called while the error raise.

Parametri

callback

A callable callback

error_types

Valorile întoarse

A se vedea ?i

  • Yaf_Dispatcher::throwException() - Switch on/off exception throwing
  • Yaf_Application::getLastErrorNo() - Get code of last occurred error
  • Yaf_Application::getLastErrorMsg() - Get message of the last occurred error
Yaf_Dispatcher::setDefaultModule
Yaf_Dispatcher::setRequest
Yaf_Dispatcher


The setRequest purpose

Yaf_Dispatcher::setErrorHandler
Yaf_Dispatcher::setView
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setRequest

(Yaf >=1.0.0)

Yaf_Dispatcher::setRequest — The setRequest purpose

Descrierea

public Yaf_Dispatcher Yaf_Dispatcher::setRequest ( Yaf_Request_Abstract $request )

Parametri

plugin

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Dispatcher::setView — Set a custom view engine

Descrierea

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

Parametri

view

A Yaf_View_Interface instance

Valorile întoarse

Exemple

Example #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);
    }

}
?>

Example #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 */
    }
}
?>

A se vedea ?i

  • 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

(Yaf >=1.0.0)

Yaf_Dispatcher::__sleep — Yaf_Dispatcher can not be serialized

Descrierea

private void Yaf_Dispatcher::__sleep ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Dispatcher::throwException — Switch on/off exception throwing

Descrierea

public Yaf_Dispatcher Yaf_Dispatcher::throwException ([ bool $flag ] )

Siwtch on/off exception throwing while unexpected error occurring. When this is on, Yaf will throwing exceptions instead of triggering catchable errors.

You can also use application.dispatcher.throwException to achieve the same purpose.

Parametri

flag

bool

Valorile întoarse

Exemple

Example #1 Yaf_Dispatcher::throwexception()example

<?php

$config = array(
    'application' => array(
        'directory' => dirname(__FILE__),
    ),
);
$app = new Yaf_Application($config);

$app->getDispatcher()->throwException(true);

try {
    $app->run();
} catch (Yaf_Exception $e) {
    var_dump($e->getMessage());
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(59) "Could not find controller script /tmp/controllers/Index.php"

Example #2 Yaf_Dispatcher::throwexception()example

<?php

$config = array(
    'application' => array(
        'directory' => dirname(__FILE__),
    ),
);
$app = new Yaf_Application($config);

$app->getDispatcher()->throwException(false);

$app->run();
?>

Exemplul de mai sus va afi?a ceva similar cu:

PHP Catchable fatal error:  Yaf_Application::run(): Could not find controller script /tmp/controllers/Index.php in /tmp/1.php on line 12

A se vedea ?i

  • Yaf_Dispatcher::catchException() - Switch on/off exception catching
  • Yaf_Exception
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

(Yaf >=1.0.0)

Yaf_Dispatcher::__wakeup — Yaf_Dispatcher can not be unserialized

Descrierea

private void Yaf_Dispatcher::__wakeup ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Dispatcher::throwException
Yaf_Config_Abstract
Yaf_Dispatcher


The Yaf_Config_Abstract class

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

abstract Yaf_Config_Abstract {
/* Proprieta?i */
protected $_config ;
protected $_readonly ;
/* Metode */
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 )
}

Proprieta?i

_config

_readonly

Cuprins

  • 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

(Yaf >=1.0.0)

Yaf_Config_Abstract::get — Getter

Descrierea

abstract public mixed Yaf_Config_Abstract::get ( string $name , mixed $value )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Abstract::readonly — Find a config whether readonly

Descrierea

abstract public bool Yaf_Config_Abstract::readonly ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Abstract::set — Setter

Descrierea

abstract public Yaf_Config_Abstract Yaf_Config_Abstract::set ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Abstract::toArray — Cast to array

Descrierea

abstract public array Yaf_Config_Abstract::toArray ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Config_Abstract::set
Yaf_Config_Ini
Yaf_Config_Abstract


The Yaf_Config_Ini class

(Yaf >=1.0.0)

Introducere

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.

Nota:

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.

Sinopsisul clasei

Yaf_Config_Ini extends Yaf_Config_Abstract implements Iterator , ArrayAccess , Countable {
/* Proprieta?i */
/* Metode */
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 array toArray ( void )
public void valid ( void )
/* Metode mo?tenite */
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 )
}

Proprieta?i

_config

_readonly

Exemple

Example #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"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(15) "dev.example.com"
string(6) "dbname"
string(7) "devuser

Cuprins

  • Yaf_Config_Ini::__construct — Yaf_Config_Ini constructor
  • 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 — Returns a PHP array
  • Yaf_Config_Ini::valid — The valid purpose
Yaf_Config_Abstract::toArray
Yaf_Config_Ini::__construct
Yaf


Yaf_Config_Ini constructor

Yaf_Config_Ini
Yaf_Config_Ini::count
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::__construct

(Yaf >=1.0.0)

Yaf_Config_Ini::__construct — Yaf_Config_Ini constructor

Descrierea

public Yaf_Config_Ini::__construct ( string $config_file [, string $section ] )

Yaf_Config_Ini constructor

Parametri

config_file

path to an INI configure file

section

which section in that INI file you want to be parsed

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::count — The count purpose

Descrierea

public void Yaf_Config_Ini::count ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::current — The current purpose

Descrierea

public void Yaf_Config_Ini::current ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::__get — The __get purpose

Descrierea

public void Yaf_Config_Ini::__get ([ string $name ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::__isset — The __isset purpose

Descrierea

public void Yaf_Config_Ini::__isset ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::key — The key purpose

Descrierea

public void Yaf_Config_Ini::key ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::next — The next purpose

Descrierea

public void Yaf_Config_Ini::next ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetExists — The offsetExists purpose

Descrierea

public void Yaf_Config_Ini::offsetExists ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetGet — The offsetGet purpose

Descrierea

public void Yaf_Config_Ini::offsetGet ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetSet — The offsetSet purpose

Descrierea

public void Yaf_Config_Ini::offsetSet ( string $name , string $value )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

value

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetUnset — The offsetUnset purpose

Descrierea

public void Yaf_Config_Ini::offsetUnset ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::readonly — The readonly purpose

Descrierea

public void Yaf_Config_Ini::readonly ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::rewind — The rewind purpose

Descrierea

public void Yaf_Config_Ini::rewind ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::__set — The __set purpose

Descrierea

public void Yaf_Config_Ini::__set ( string $name , mixed $value )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

value

Valorile întoarse

Yaf_Config_Ini::rewind
Yaf_Config_Ini::toArray
Yaf_Config_Ini


Returns a PHP array

Yaf_Config_Ini::__set
Yaf_Config_Ini::valid
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::toArray

(Yaf >=1.0.0)

Yaf_Config_Ini::toArray — Returns a PHP array

Descrierea

public array Yaf_Config_Ini::toArray ( void )

Returns a PHP array from the Yaf_Config_Ini

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Ini::valid — The valid purpose

Descrierea

public void Yaf_Config_Ini::valid ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Config_Ini::toArray
Yaf_Config_Simple
Yaf_Config_Ini


The Yaf_Config_Simple class

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Config_Simple extends Yaf_Config_Abstract implements Iterator , ArrayAccess , Countable {
/* Proprieta?i */
protected $_readonly ;
/* Metode */
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 array toArray ( void )
public void valid ( void )
/* Metode mo?tenite */
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 )
}

Proprieta?i

_config

_readonly

Cuprins

  • 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 — Returns a PHP array
  • 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

(Yaf >=1.0.0)

Yaf_Config_Simple::__construct — The __construct purpose

Descrierea

public Yaf_Config_Simple::__construct ( string $config_file [, string $section ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

config_file

section

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::count — The count purpose

Descrierea

public void Yaf_Config_Simple::count ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::current — The current purpose

Descrierea

public void Yaf_Config_Simple::current ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::__get — The __get purpose

Descrierea

public void Yaf_Config_Simple::__get ([ string $name ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::__isset — The __isset purpose

Descrierea

public void Yaf_Config_Simple::__isset ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::key — The key purpose

Descrierea

public void Yaf_Config_Simple::key ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::next — The next purpose

Descrierea

public void Yaf_Config_Simple::next ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetExists — The offsetExists purpose

Descrierea

public void Yaf_Config_Simple::offsetExists ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetGet — The offsetGet purpose

Descrierea

public void Yaf_Config_Simple::offsetGet ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetSet — The offsetSet purpose

Descrierea

public void Yaf_Config_Simple::offsetSet ( string $name , string $value )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

value

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetUnset — The offsetUnset purpose

Descrierea

public void Yaf_Config_Simple::offsetUnset ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::readonly — The readonly purpose

Descrierea

public void Yaf_Config_Simple::readonly ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::rewind — The rewind purpose

Descrierea

public void Yaf_Config_Simple::rewind ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::__set — The __set purpose

Descrierea

public void Yaf_Config_Simple::__set ( string $name , string $value )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

value

Valorile întoarse

Yaf_Config_Simple::rewind
Yaf_Config_Simple::toArray
Yaf_Config_Simple


Returns a PHP array

Yaf_Config_Simple::__set
Yaf_Config_Simple::valid
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::toArray

(Yaf >=1.0.0)

Yaf_Config_Simple::toArray — Returns a PHP array

Descrierea

public array Yaf_Config_Simple::toArray ( void )

Returns a PHP array from the Yaf_Config_Simple

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Config_Simple::valid — The valid purpose

Descrierea

public void Yaf_Config_Simple::valid ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Config_Simple::toArray
Yaf_Controller_Abstract
Yaf_Config_Simple


The Yaf_Controller_Abstract class

(Yaf >=1.0.0)

Introducere

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()).

Nota:

These arguments are directly fetched without filtering, it should be carefully processed before use them.

Sinopsisul clasei

abstract Yaf_Controller_Abstract {
/* Proprieta?i */
public $actions ;
protected $_module ;
protected $_name ;
protected $_request ;
protected $_response ;
protected $_invoke_args ;
protected $_view ;
/* Metode */
final private void __clone ( void )
final private __construct ( void )
protected bool display ( string $tpl [, array $parameters ] )
public void forward ( string $action [, array $paramters ] )
public void getInvokeArg ( string $name )
public void getInvokeArgs ( void )
public string getModuleName ( void )
public Yaf_Request_Abstract getRequest ( void )
public Yaf_Response_Abstract getResponse ( void )
public Yaf_View_Interface getView ( void )
public void getViewpath ( void )
public void init ( void )
public void initView ([ array $options ] )
public bool redirect ( string $url )
protected string render ( string $tpl [, array $parameters ] )
public void setViewpath ( string $view_directory )
}

Proprieta?i

actions

You can also define a action method in a separate PHP script by using this property and Yaf_Action_Abstract.

Example #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) {
       /* $name and $id are unsafe raw data */
       assert($name == $this->getRequest()->getParam("name"));
       assert($id   == $this->_request->getParam("id"));
    }
}
?>

Example #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

controller name

_request

current request object

_response

current response object

_invoke_args

_view

view engine object

Cuprins

  • 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 — foward to another action
  • Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose
  • Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose
  • Yaf_Controller_Abstract::getModuleName — Get module name
  • Yaf_Controller_Abstract::getRequest — Retrieve current request object
  • Yaf_Controller_Abstract::getResponse — Retrieve current response object
  • Yaf_Controller_Abstract::getView — Retrieve the view engine
  • Yaf_Controller_Abstract::getViewpath — The getViewpath purpose
  • Yaf_Controller_Abstract::init — Controller initializer
  • Yaf_Controller_Abstract::initView — The initView purpose
  • Yaf_Controller_Abstract::redirect — Redirect to a URL
  • Yaf_Controller_Abstract::render — Render view template
  • 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

(Yaf >=1.0.0)

Yaf_Controller_Abstract::__clone — Yaf_Controller_Abstract can not be cloned

Descrierea

final private void Yaf_Controller_Abstract::__clone ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract constructor

Descrierea

final private Yaf_Controller_Abstract::__construct ( void )

Yaf_Controller_Abstract::__construct() is final, which means it can not be overridden. You may want to see Yaf_Controller_Abstract::init() instead.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • Yaf_Controller_Abstract::init() - Controller initializer
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

(Yaf >=1.0.0)

Yaf_Controller_Abstract::display — The display purpose

Descrierea

protected bool Yaf_Controller_Abstract::display ( string $tpl [, array $parameters ] )

Parametri

tpl

parameters

Valorile întoarse

Yaf_Controller_Abstract::__construct
Yaf_Controller_Abstract::forward
Yaf_Controller_Abstract


foward to another action

Yaf_Controller_Abstract::display
Yaf_Controller_Abstract::getInvokeArg
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::forward

(Yaf >=1.0.0)

Yaf_Controller_Abstract::forward — foward to another action

Descrierea

public void Yaf_Controller_Abstract::forward ( string $action [, array $paramters ] )
public void Yaf_Controller_Abstract::forward ( string $controller , string $action [, array $paramters ] )
public void Yaf_Controller_Abstract::forward ( string $module , string $controller , string $action [, array $paramters ] )

forward current execution process to other action.

Nota:

this method doesn't switch to the destination action immediately, it will take place after current flow finish.

Parametri

module

destination module name, if NULL was given, then default module name is assumed

controller

destination controller name

action

destination action name

paramters

calling arguments

Exemple

Example #1 Yaf_Controller_Abstract::forward()example

<?php
class IndexController extends Yaf_Controller_Abstract
{
    public function indexAction(){
         $logined = $_SESSION["login"];
         if (!$logined) {
             $this->forward("login", array("from" => "Index")); // forward to login action
             return FALSE;  // this is important, this finish current working flow
                            // and tell the Yaf do not doing auto-render
         }

         // other processes
    }

    public function loginAction() {
         echo "login, redirected from ", $this->_request->getParam("from") , " action";
    }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

   login, redirected from Index action

Valorile întoarse

return FALSE on failure

A se vedea ?i

  • Yaf_Request_Abstrace::getParam()
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

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose

Descrierea

public void Yaf_Controller_Abstract::getInvokeArg ( string $name )

Parametri

name

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose

Descrierea

public void Yaf_Controller_Abstract::getInvokeArgs ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Controller_Abstract::getInvokeArg
Yaf_Controller_Abstract::getModuleName
Yaf_Controller_Abstract


Get module name

Yaf_Controller_Abstract::getInvokeArgs
Yaf_Controller_Abstract::getRequest
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getModuleName

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getModuleName — Get module name

Descrierea

public string Yaf_Controller_Abstract::getModuleName ( void )

get the controller's module name

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Controller_Abstract::getInvokeArgs
Yaf_Controller_Abstract::getRequest
Yaf_Controller_Abstract


Retrieve current request object

Yaf_Controller_Abstract::getModuleName
Yaf_Controller_Abstract::getResponse
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getRequest

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getRequest — Retrieve current request object

Descrierea

public Yaf_Request_Abstract Yaf_Controller_Abstract::getRequest ( void )

retrieve current request object

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Request_Abstract instance

Yaf_Controller_Abstract::getModuleName
Yaf_Controller_Abstract::getResponse
Yaf_Controller_Abstract


Retrieve current response object

Yaf_Controller_Abstract::getRequest
Yaf_Controller_Abstract::getView
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getResponse

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getResponse — Retrieve current response object

Descrierea

public Yaf_Response_Abstract Yaf_Controller_Abstract::getResponse ( void )

retrieve current response object

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Response_Abstract instance

Yaf_Controller_Abstract::getRequest
Yaf_Controller_Abstract::getView
Yaf_Controller_Abstract


Retrieve the view engine

Yaf_Controller_Abstract::getResponse
Yaf_Controller_Abstract::getViewpath
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getView

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getView — Retrieve the view engine

Descrierea

public Yaf_View_Interface Yaf_Controller_Abstract::getView ( void )

retrieve view engine

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Controller_Abstract::getResponse
Yaf_Controller_Abstract::getViewpath
Yaf_Controller_Abstract


The getViewpath purpose

Yaf_Controller_Abstract::getView
Yaf_Controller_Abstract::init
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getViewpath

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getViewpath — The getViewpath purpose

Descrierea

public void Yaf_Controller_Abstract::getViewpath ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Controller_Abstract::getView
Yaf_Controller_Abstract::init
Yaf_Controller_Abstract


Controller initializer

Yaf_Controller_Abstract::getViewpath
Yaf_Controller_Abstract::initView
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::init

(Yaf >=1.0.0)

Yaf_Controller_Abstract::init — Controller initializer

Descrierea

public void Yaf_Controller_Abstract::init ( void )

Yaf_Controller_Abstract::__construct() is final, which means users can not override it. but users can define Yaf_Controller_Abstract::init(), which will be called after controller object is instantiated.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • Yaf_Controller_Abstract::__construct() - Yaf_Controller_Abstract constructor
Yaf_Controller_Abstract::getViewpath
Yaf_Controller_Abstract::initView
Yaf_Controller_Abstract


The initView purpose

Yaf_Controller_Abstract::init
Yaf_Controller_Abstract::redirect
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::initView

(Yaf >=1.0.0)

Yaf_Controller_Abstract::initView — The initView purpose

Descrierea

public void Yaf_Controller_Abstract::initView ([ array $options ] )

Parametri

options

Valorile întoarse

Yaf_Controller_Abstract::init
Yaf_Controller_Abstract::redirect
Yaf_Controller_Abstract


Redirect to a URL

Yaf_Controller_Abstract::initView
Yaf_Controller_Abstract::render
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::redirect

(Yaf >=1.0.0)

Yaf_Controller_Abstract::redirect — Redirect to a URL

Descrierea

public bool Yaf_Controller_Abstract::redirect ( string $url )

redirect to a URL by sending a 302 header

Parametri

url

a location URL

Valorile întoarse

bool

Yaf_Controller_Abstract::initView
Yaf_Controller_Abstract::render
Yaf_Controller_Abstract


Render view template

Yaf_Controller_Abstract::redirect
Yaf_Controller_Abstract::setViewpath
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::render

(Yaf >=1.0.0)

Yaf_Controller_Abstract::render — Render view template

Descrierea

protected string Yaf_Controller_Abstract::render ( string $tpl [, array $parameters ] )

Parametri

tpl

parameters

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Controller_Abstract::setViewpath — The setViewpath purpose

Descrierea

public void Yaf_Controller_Abstract::setViewpath ( string $view_directory )

Parametri

view_directory

Valorile întoarse

Yaf_Controller_Abstract::render
Yaf_Action_Abstract
Yaf_Controller_Abstract


The Yaf_Action_Abstract class

(Yaf >=1.0.0)

Introducere

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.

Sinopsisul clasei

Yaf_Action_Abstract extends Yaf_Controller_Abstract {
/* Proprieta?i */
protected $_controller ;
/* Metode */
abstract publicmixed execute ([ mixed $arg [, mixed $... ]] )
publicYaf_Controller_Abstract getController ( void )
/* Metode mo?tenite */
final private void Yaf_Controller_Abstract::__clone ( void )
final private Yaf_Controller_Abstract::__construct ( void )
protected bool Yaf_Controller_Abstract::display ( string $tpl [, array $parameters ] )
public void Yaf_Controller_Abstract::forward ( string $action [, array $paramters ] )
public void Yaf_Controller_Abstract::getInvokeArg ( string $name )
public void Yaf_Controller_Abstract::getInvokeArgs ( void )
public string Yaf_Controller_Abstract::getModuleName ( void )
public Yaf_Request_Abstract Yaf_Controller_Abstract::getRequest ( void )
public Yaf_Response_Abstract Yaf_Controller_Abstract::getResponse ( void )
public Yaf_View_Interface Yaf_Controller_Abstract::getView ( void )
public void Yaf_Controller_Abstract::getViewpath ( void )
public void Yaf_Controller_Abstract::init ( void )
public void Yaf_Controller_Abstract::initView ([ array $options ] )
public bool Yaf_Controller_Abstract::redirect ( string $url )
protected string Yaf_Controller_Abstract::render ( string $tpl [, array $parameters ] )
public void Yaf_Controller_Abstract::setViewpath ( string $view_directory )
}

Proprieta?i

_module

_name

_request

_response

_invoke_args

_view

_controller

Cuprins

  • Yaf_Action_Abstract::execute — Action entry point
  • Yaf_Action_Abstract::getController — Retrieve controller object
Yaf_Controller_Abstract::setViewpath
Yaf_Action_Abstract::execute
Yaf


Action entry point

Yaf_Action_Abstract
Yaf_Action_Abstract::getController
Yaf_Action_Abstract
PHP Manual

Yaf_Action_Abstract::execute

(Yaf >=1.0.0)

Yaf_Action_Abstract::execute — Action entry point

Descrierea

abstract publicmixed Yaf_Action_Abstract::execute ([ mixed $arg [, mixed $... ]] )

user should always define this method for a action, this is the entry point of an action. Yaf_Action_Abstract::execute() may have agruments.

Nota:

The value retrived from the request is not safe. you should do some filtering work before you use it.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #1 Yaf_Action_Abstract::execute()example

<?php
/**
 * A controller example
 */
class ProductController extends Yaf_Controller_Abstract {
      protected $actions = array(
          "index" => "actions/Index.php",
      );
}
?>

Example #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"));
     }
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

/**
 * 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)

A se vedea ?i

Yaf_Action_Abstract
Yaf_Action_Abstract::getController
Yaf_Action_Abstract


Retrieve controller object

Yaf_Action_Abstract::execute
Yaf_View_Interface
Yaf_Action_Abstract
PHP Manual

Yaf_Action_Abstract::getController

(Yaf >=1.0.0)

Yaf_Action_Abstract::getController — Retrieve controller object

Descrierea

publicYaf_Controller_Abstract Yaf_Action_Abstract::getController ( void )

retrieve current controller object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Controller_Abstract instance

Yaf_Action_Abstract::execute
Yaf_View_Interface
Yaf_Action_Abstract


The Yaf_View_Interface class

(Yaf >=1.0.0)

Introducere

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().

Sinopsisul clasei

Yaf_View_Interface {
/* Metode */
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 )
}

Cuprins

  • 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

(Yaf >=1.0.0)

Yaf_View_Interface::assign — Assign value to View engine

Descrierea

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.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

value

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_View_Interface::display — Render and output a template

Descrierea

abstract public bool Yaf_View_Interface::display ( string $tpl [, array $tpl_vars ] )

Render a template and output the result immediatly.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

tpl

tpl_vars

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_View_Interface::getScriptPath — The getScriptPath purpose

Descrierea

abstract public void Yaf_View_Interface::getScriptPath ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_View_Interface::render — Render a template

Descrierea

abstract public string Yaf_View_Interface::render ( string $tpl [, array $tpl_vars ] )

Render a template and return the result.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

tpl

tpl_vars

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_View_Interface::setScriptPath — The setScriptPath purpose

Descrierea

abstract public void Yaf_View_Interface::setScriptPath ( string $template_dir )

Set the templates base directory, this is usually called by Yaf_Dispatcher

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

template_dir

A absolute path to the template directory, by default, Yaf_Dispatcher use application.directory . "/views" as this paramter.

Valorile întoarse

Yaf_View_Interface::render
Yaf_View_Simple
Yaf_View_Interface


The Yaf_View_Simple class

(Yaf >=1.0.0)

Introducere

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.

Sinopsisul clasei

Yaf_View_Simple implements Yaf_View_Interface {
/* Proprieta?i */
protected $_tpl_vars ;
protected $_tpl_dir ;
/* Metode */
public bool assign ( string $name [, mixed $value ] )
public bool assignRef ( string $name , mixed &$value )
public bool clear ([ string $name ] )
final public __construct ( string $template_dir [, array $options ] )
public bool display ( string $tpl [, array $tpl_vars ] )
public string eval ( string $tpl_content [, 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 )
}

Proprieta?i

_tpl_vars

_tpl_dir

Cuprins

  • Yaf_View_Simple::assign — Assign values
  • Yaf_View_Simple::assignRef — The assignRef purpose
  • Yaf_View_Simple::clear — Clear Assigned values
  • Yaf_View_Simple::__construct — Constructor of Yaf_View_Simple
  • Yaf_View_Simple::display — Render and display
  • Yaf_View_Simple::eval — Render template
  • Yaf_View_Simple::__get — Retrieve assigned variable
  • Yaf_View_Simple::getScriptPath — Get templates 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 tempaltes 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

(Yaf >=1.0.0)

Yaf_View_Simple::assign — Assign values

Descrierea

public bool Yaf_View_Simple::assign ( string $name [, mixed $value ] )

assign variable to view engine

Parametri

name

A string or an array.

if is string, then the next argument $value is required.

value

mixed value

Valorile întoarse

Exemple

Example #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"));
    }
?>

Example #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>

A se vedea ?i

  • Yaf_View_Simple::assignRef() - The assignRef purpose
  • Yaf_View_Interface::clear()
  • 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::clear
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::assignRef

(Yaf >=1.0.0)

Yaf_View_Simple::assignRef — The assignRef purpose

Descrierea

public bool Yaf_View_Simple::assignRef ( string $name , mixed &$value )

unlike Yaf_View_Simple::assign(), this method assign a ref value to engine.

Parametri

name

A string name which will be used to access the value in the tempalte.

value

mixed value

Valorile întoarse

Exemple

Example #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);
    }
?>

Example #2 template()example

<html>
 <head>
  <title><?php echo $foo;  $foo = "changed"; ?></title>
 </head>
<body>
</body>
</html>

Exemplul de mai sus va afi?a ceva similar cu:

/* access the index controller will result: */
changed

A se vedea ?i

  • Yaf_View_Simple::assign() - Assign values
  • Yaf_View_Simple::__set() - Set value to engine
Yaf_View_Simple::assign
Yaf_View_Simple::clear
Yaf_View_Simple


Clear Assigned values

Yaf_View_Simple::assignRef
Yaf_View_Simple::__construct
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::clear

(Yaf >=2.2.0)

Yaf_View_Simple::clear — Clear Assigned values

Descrierea

public bool Yaf_View_Simple::clear ([ string $name ] )

clear assigned variable

Parametri

name

assigned variable name

if empty, will clear all assigned variables

Valorile întoarse

Exemple

Example #1 Yaf_View_Simple::clear()example

<?php
class IndexController extends Yaf_Controller_Abstract {
    public function indexAction() {
        $this->getView()->clear("foo")->clear("bar"); // clear "foo" and "bar"
        $this->_view->clear(); //clear all assigned variables
    }
?>

A se vedea ?i

  • 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::assignRef
Yaf_View_Simple::__construct
Yaf_View_Simple


Constructor of Yaf_View_Simple

Yaf_View_Simple::clear
Yaf_View_Simple::display
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::__construct

(Yaf >=1.0.0)

Yaf_View_Simple::__construct — Constructor of Yaf_View_Simple

Descrierea

final public Yaf_View_Simple::__construct ( string $template_dir [, array $options ] )

Parametri

template_dir

The base directory of the templates, by default, it is APPLICATOIN . "/views" for Yaf.

options

Options for the engine, as of Yaf 2.1.13, you can use short tag
      "<?=$var?>" in your template(regardless of "short_open_tag"),
      so comes a option named "short_tag",  you can switch this off
      to prevent use short_tag in template.

Exemple

Example #1 Yaf_View_Simple::__constructor()example

<?php
   define ("TEMPLATE_DIRECTORY", APPLICATOIN_PATH . '/views');
   $view = new Yaf_View_Simple(TEMPLATE_DIRECTORY, array(
                           'short_tag' => false //doesn't allow use short tag in template
   ));
?>

Valorile întoarse

Yaf_View_Simple::clear
Yaf_View_Simple::display
Yaf_View_Simple


Render and display

Yaf_View_Simple::__construct
Yaf_View_Simple::eval
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::display

(Yaf >=1.0.0)

Yaf_View_Simple::display — Render and display

Descrierea

public bool Yaf_View_Simple::display ( string $tpl [, array $tpl_vars ] )

Render a template and display the result instantly.

Parametri

tpl

tpl_vars

Valorile întoarse

Yaf_View_Simple::__construct
Yaf_View_Simple::eval
Yaf_View_Simple


Render template

Yaf_View_Simple::display
Yaf_View_Simple::__get
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::eval

(Yaf >=2.2.0)

Yaf_View_Simple::eval — Render template

Descrierea

public string Yaf_View_Simple::eval ( string $tpl_content [, array $tpl_vars ] )

Render a string tempalte and return the result.

Parametri

tpl_content

string template

tpl_vars

Valorile întoarse

Yaf_View_Simple::display
Yaf_View_Simple::__get
Yaf_View_Simple


Retrieve assigned variable

Yaf_View_Simple::eval
Yaf_View_Simple::getScriptPath
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::__get

(Yaf >=1.0.0)

Yaf_View_Simple::__get — Retrieve assigned variable

Descrierea

public void Yaf_View_Simple::__get ([ string $name ] )

Retrieve assigned varaiable

Nota:

parameter can be empty since 2.1.11

Parametri

name

the assigned variable name

if this is empty, all assigned variables will be returned

Valorile întoarse

Yaf_View_Simple::eval
Yaf_View_Simple::getScriptPath
Yaf_View_Simple


Get templates directory

Yaf_View_Simple::__get
Yaf_View_Simple::__isset
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::getScriptPath

(Yaf >=1.0.0)

Yaf_View_Simple::getScriptPath — Get templates directory

Descrierea

public string Yaf_View_Simple::getScriptPath ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_View_Simple::__isset — The __isset purpose

Descrierea

public void Yaf_View_Simple::__isset ( string $name )

Parametri

name

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_View_Simple::render — Render template

Descrierea

public string Yaf_View_Simple::render ( string $tpl [, array $tpl_vars ] )

Render a template and return the result.

Parametri

tpl

tpl_vars

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_View_Simple::__set — Set value to engine

Descrierea

public void Yaf_View_Simple::__set ( string $name , mixed $value )

This is a alternative and easier way to Yaf_View_Simple::assign().

Parametri

name

A string value name.

value

Mixed value.

Valorile întoarse

Exemple

Example #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");
    }
?>

A se vedea ?i

  • 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 tempaltes directory

Yaf_View_Simple::__set
Yaf_Loader
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::setScriptPath

(Yaf >=1.0.0)

Yaf_View_Simple::setScriptPath — Set tempaltes directory

Descrierea

public bool Yaf_View_Simple::setScriptPath ( string $template_dir )

Parametri

template_dir

Valorile întoarse

Yaf_View_Simple::__set
Yaf_Loader
Yaf_View_Simple


The Yaf_Loader class

(Yaf >=1.0.0)

Introducere

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).

Nota:

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 . "/library"), you should register the class prefix using the Yaf_Loader::registerLocalNameSpace()

Let's see some examples(assuming APPLICATION_PATH is application.directory):

Example #1 Config example

// Assuming the following configure in php.ini:
yaf.library = "/global_dir"

//Assuming the following configure in application.ini
application.library = APPLICATION_PATH "/library"
Assuming the following local name space registerd:

Example #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:

Example #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:

Example #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:

Example #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:

Example #6 MVC class distinctions

Controller Classes =>
    // ***Controller

Model Classes =>
    // ***Model

Plugin Classes =>
    // ***Plugin
some examples:

Example #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

Nota:

As of 2.1.18, Yaf supports Controllers autoloading for user script side, (which means the autoloading triggered by user php script, eg: access a controller static property in Bootstrap or Plugins), but autoloader only try to locate controller class script under the default module folder, which is "APPLICATION_PATH/controllers/".

also, the directory will be affected by yaf.lowcase_path.

Sinopsisul clasei

Yaf_Loader {
/* Proprieta?i */
protected $_local_ns ;
protected $_library ;
protected $_global_library ;
static $_instance ;
/* Metode */
public void autoload ( void )
public void clearLocalNamespace ( void )
private void __clone ( void )
private __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 ( mixed $prefix )
public Yaf_Loader setLibraryPath ( string $directory [, bool $is_global = false ] )
private void __sleep ( void )
private void __wakeup ( void )
}

Proprieta?i

_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

Cuprins

  • 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 — register local class prefix
  • 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

(Yaf >=1.0.0)

Yaf_Loader::autoload — The autoload purpose

Descrierea

public void Yaf_Loader::autoload ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Loader
Yaf_Loader::clearLocalNamespace
Yaf_Loader


The clearLocalNamespace purpose

Yaf_Loader::autoload
Yaf_Loader::__clone
Yaf_Loader
PHP Manual

Yaf_Loader::clearLocalNamespace

(Yaf >=1.0.0)

Yaf_Loader::clearLocalNamespace — The clearLocalNamespace purpose

Descrierea

public void Yaf_Loader::clearLocalNamespace ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Loader::autoload
Yaf_Loader::__clone
Yaf_Loader


The __clone purpose

Yaf_Loader::clearLocalNamespace
Yaf_Loader::__construct
Yaf_Loader
PHP Manual

Yaf_Loader::__clone

(Yaf >=1.0.0)

Yaf_Loader::__clone — The __clone purpose

Descrierea

private void Yaf_Loader::__clone ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Loader::clearLocalNamespace
Yaf_Loader::__construct
Yaf_Loader


The __construct purpose

Yaf_Loader::__clone
Yaf_Loader::getInstance
Yaf_Loader
PHP Manual

Yaf_Loader::__construct

(Yaf >=1.0.0)

Yaf_Loader::__construct — The __construct purpose

Descrierea

private Yaf_Loader::__construct ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Loader::__clone
Yaf_Loader::getInstance
Yaf_Loader


The getInstance purpose

Yaf_Loader::__construct
Yaf_Loader::getLibraryPath
Yaf_Loader
PHP Manual

Yaf_Loader::getInstance

(Yaf >=1.0.0)

Yaf_Loader::getInstance — The getInstance purpose

Descrierea

public static void Yaf_Loader::getInstance ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=2.1.4)

Yaf_Loader::getLibraryPath — get the library path

Descrierea

public Yaf_Loader Yaf_Loader::getLibraryPath ([ bool $is_global = false ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Loader::getInstance
Yaf_Loader::getLocalNamespace
Yaf_Loader


The getLocalNamespace purpose

Yaf_Loader::getLibraryPath
Yaf_Loader::import
Yaf_Loader
PHP Manual

Yaf_Loader::getLocalNamespace

(Yaf >=1.0.0)

Yaf_Loader::getLocalNamespace — The getLocalNamespace purpose

Descrierea

public void Yaf_Loader::getLocalNamespace ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Loader::getLibraryPath
Yaf_Loader::import
Yaf_Loader


The import purpose

Yaf_Loader::getLocalNamespace
Yaf_Loader::isLocalName
Yaf_Loader
PHP Manual

Yaf_Loader::import

(Yaf >=1.0.0)

Yaf_Loader::import — The import purpose

Descrierea

public static void Yaf_Loader::import ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Loader::getLocalNamespace
Yaf_Loader::isLocalName
Yaf_Loader


The isLocalName purpose

Yaf_Loader::import
Yaf_Loader::registerLocalNamespace
Yaf_Loader
PHP Manual

Yaf_Loader::isLocalName

(Yaf >=1.0.0)

Yaf_Loader::isLocalName — The isLocalName purpose

Descrierea

public void Yaf_Loader::isLocalName ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Loader::import
Yaf_Loader::registerLocalNamespace
Yaf_Loader


register local class prefix

Yaf_Loader::isLocalName
Yaf_Loader::setLibraryPath
Yaf_Loader
PHP Manual

Yaf_Loader::registerLocalNamespace

(Yaf >=1.0.0)

Yaf_Loader::registerLocalNamespace — register local class prefix

Descrierea

public void Yaf_Loader::registerLocalNamespace ( mixed $prefix )

Register local class prefix name, Yaf_Loader search classes in two library directories, the one is configured via application.library.directory(in application.ini) which is called local libraray directory; the other is configured via yaf.library (in php.ini) which is callled global library directory, since it can be shared by many applications in the same server.

When an autloading is trigger, Yaf_Loader will determine which library directory should be searched in by exame the prefix name of the missed classname. If the prefix name is registered as a localnamespack then look for it in local library directory, otherwise look for it in global library directory.

Nota:

If yaf.library is not configured, then the global library directory is assumed to be the local library directory. in that case, all autoloading will look for local library directory. But if you want your Yaf application be strong, then always register your own classes as local classes.

Parametri

prefix

a string or a array of class name prefix. all class prefix with these prefix will be loaded in local library path.

Valorile întoarse

bool

Exemple

Example #1 Yaf_Loader::registerLocalNamespace()example

<?php
$loader = Yaf_Loader::getInstance('/local/library/', '/global/library');
$loader->registerLocalNamespace("Baidu");
$loader->registerLocalNamespace(array("Sina", "Weibo"));

$loader->autoload("Baidu_Name"); // search in '/local/library/'
$loader->autoload("Sina");       // search '/local/library/'
$loader->autoload("Global_Name");// search in '/global/library/'
$loader->autoload("Foo_Bar");    // search in '/global/library/'

?>
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

(Yaf >=2.1.4)

Yaf_Loader::setLibraryPath — Change the library path

Descrierea

public Yaf_Loader Yaf_Loader::setLibraryPath ( string $directory [, bool $is_global = false ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Loader::registerLocalNamespace
Yaf_Loader::__sleep
Yaf_Loader


The __sleep purpose

Yaf_Loader::setLibraryPath
Yaf_Loader::__wakeup
Yaf_Loader
PHP Manual

Yaf_Loader::__sleep

(Yaf >=1.0.0)

Yaf_Loader::__sleep — The __sleep purpose

Descrierea

private void Yaf_Loader::__sleep ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Loader::setLibraryPath
Yaf_Loader::__wakeup
Yaf_Loader


The __wakeup purpose

Yaf_Loader::__sleep
Yaf_Plugin_Abstract
Yaf_Loader
PHP Manual

Yaf_Loader::__wakeup

(Yaf >=1.0.0)

Yaf_Loader::__wakeup — The __wakeup purpose

Descrierea

private void Yaf_Loader::__wakeup ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Loader::__sleep
Yaf_Plugin_Abstract
Yaf_Loader


The Yaf_Plugin_Abstract class

(Yaf >=1.0.0)

Introducere

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.

Exemple

Example #1 Plugin example

<?php
   /* bootstrap class should be defined under ./application/Bootstrap.php */
   class Bootstrap extends Yaf_Bootstrap_Abstract {
        public function _initPlugin(Yaf_Dispatcher $dispatcher) {
            /* register a plugin */
            $dispatcher->registerPlugin(new TestPlugin());
        }
   }

   /* plugin class should be placed under ./application/plugins/ */
   class TestPlugin extends Yaf_Plugin_Abstract {
        public function routerStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            /* before router
               in this hook,  user can do some url rewrite */
            var_dump("routerStartup");
        }
        public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            /* router complete
               in this hook, user can do login check */
            var_dump("routerShutdown");
        }
        public function dispatchLoopStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            var_dump("dispatchLoopStartup");
        }
        public function preDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            var_dump("preDispatch");
        }
        public function postDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            var_dump("postDispatch");
        }
        public function dispatchLoopShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            /* final hoook
               in this hook user can do loging or implement layout */
            var_dump("dispatchLoopShutdown");
        }
   }

   Class IndexController extends Yaf_Controller_Abstract {
        public function indexAction() {
            return FALSE; //prevent rendering
        }
   }

   $config = array(
       "application" => array(
           "directory" => dirname(__FILE__) . "/application/",
       ),
   );

   $app = new Yaf_Application($config);
   $app->bootstrap()->run();
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(13) "routerStartup"
string(14) "routerShutdown"
string(19) "dispatchLoopStartup"
string(11) "preDispatch"
string(12) "postDispatch"
string(20) "dispatchLoopShutdown"

Sinopsisul clasei

Yaf_Plugin_Abstract {
/* Metode */
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 )
}

Cuprins

  • 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

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::dispatchLoopShutdown — The dispatchLoopShutdown purpose

Descrierea

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.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

request

response

Valorile întoarse

A se vedea ?i

  • 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

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::dispatchLoopStartup — The dispatchLoopStartup purpose

Descrierea

public void Yaf_Plugin_Abstract::dispatchLoopStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

request

response

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::postDispatch — The postDispatch purpose

Descrierea

public void Yaf_Plugin_Abstract::postDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

request

response

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::preDispatch — The preDispatch purpose

Descrierea

public void Yaf_Plugin_Abstract::preDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

request

response

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::preResponse — The preResponse purpose

Descrierea

public void Yaf_Plugin_Abstract::preResponse ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

request

response

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::routerShutdown — The routerShutdown purpose

Descrierea

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.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

request

response

Valorile întoarse

Exemple

Example #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;
    }
?>

A se vedea ?i

  • 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

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::routerStartup — RouterStartup hook

Descrierea

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.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

request

response

Valorile întoarse

A se vedea ?i

  • 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

(Yaf >=1.0.0)

Introducere

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.

Sinopsisul clasei

Yaf_Registry {
/* Proprieta?i */
static $_instance ;
protected $_entries ;
/* Metode */
private void __clone ( void )
private __construct ( void )
public static void del ( string $name )
public static mixed get ( string $name )
public static bool has ( string $name )
public static bool set ( string $name , string $value )
}

Proprieta?i

_instance

_entries

Cuprins

  • Yaf_Registry::__clone — The __clone purpose
  • Yaf_Registry::__construct — Yaf_Registry implements singleton
  • Yaf_Registry::del — Remove an item from registry
  • Yaf_Registry::get — Retrieve an item from registry
  • Yaf_Registry::has — Check whether an item exists
  • Yaf_Registry::set — Add an item into registry
Yaf_Plugin_Abstract::routerStartup
Yaf_Registry::__clone
Yaf


The __clone purpose

Yaf_Registry
Yaf_Registry::__construct
Yaf_Registry
PHP Manual

Yaf_Registry::__clone

(Yaf >=1.0.0)

Yaf_Registry::__clone — The __clone purpose

Descrierea

private void Yaf_Registry::__clone ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Registry
Yaf_Registry::__construct
Yaf_Registry


Yaf_Registry implements singleton

Yaf_Registry::__clone
Yaf_Registry::del
Yaf_Registry
PHP Manual

Yaf_Registry::__construct

(Yaf >=1.0.0)

Yaf_Registry::__construct — Yaf_Registry implements singleton

Descrierea

private Yaf_Registry::__construct ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Registry::__clone
Yaf_Registry::del
Yaf_Registry


Remove an item from registry

Yaf_Registry::__construct
Yaf_Registry::get
Yaf_Registry
PHP Manual

Yaf_Registry::del

(Yaf >=1.0.0)

Yaf_Registry::del — Remove an item from registry

Descrierea

public static void Yaf_Registry::del ( string $name )

Remove an item from registry

Parametri

name

Valorile întoarse

Yaf_Registry::__construct
Yaf_Registry::get
Yaf_Registry


Retrieve an item from registry

Yaf_Registry::del
Yaf_Registry::has
Yaf_Registry
PHP Manual

Yaf_Registry::get

(Yaf >=1.0.0)

Yaf_Registry::get — Retrieve an item from registry

Descrierea

public static mixed Yaf_Registry::get ( string $name )

Retrieve an item from registry

Parametri

name

Valorile întoarse

Yaf_Registry::del
Yaf_Registry::has
Yaf_Registry


Check whether an item exists

Yaf_Registry::get
Yaf_Registry::set
Yaf_Registry
PHP Manual

Yaf_Registry::has

(Yaf >=1.0.0)

Yaf_Registry::has — Check whether an item exists

Descrierea

public static bool Yaf_Registry::has ( string $name )

Check whether an item exists

Parametri

name

Valorile întoarse

Yaf_Registry::get
Yaf_Registry::set
Yaf_Registry


Add an item into registry

Yaf_Registry::has
Yaf_Request_Abstract
Yaf_Registry
PHP Manual

Yaf_Registry::set

(Yaf >=1.0.0)

Yaf_Registry::set — Add an item into registry

Descrierea

public static bool Yaf_Registry::set ( string $name , string $value )

Add an item into registry

Parametri

name

value

Valorile întoarse

Yaf_Registry::has
Yaf_Request_Abstract
Yaf_Registry


The Yaf_Request_Abstract class

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Request_Abstract {
/* Constants */
const string SCHEME_HTTP = http ;
const string SCHEME_HTTPS = https ;
/* Proprieta?i */
public $module ;
public $controller ;
public $action ;
public $method ;
protected $params ;
protected $language ;
protected $_exception ;
protected $_base_uri ;
protected $uri ;
protected $dispatched ;
protected $routed ;
/* Metode */
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 bool 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 ] )
}

Proprieta?i

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

Constante predefinite

Yaf_Request_Abstract::SCHEME_HTTP

Yaf_Request_Abstract::SCHEME_HTTPS

Cuprins

  • 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 — Retrieve ENV varialbe
  • 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 — Retrieve SERVER variable
  • 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 — set base URI
  • 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

(Yaf >=1.0.0)

Yaf_Request_Abstract::getActionName — The getActionName purpose

Descrierea

public void Yaf_Request_Abstract::getActionName ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::getBaseUri — The getBaseUri purpose

Descrierea

public void Yaf_Request_Abstract::getBaseUri ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::getControllerName — The getControllerName purpose

Descrierea

public void Yaf_Request_Abstract::getControllerName ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Request_Abstract::getBaseUri
Yaf_Request_Abstract::getEnv
Yaf_Request_Abstract


Retrieve ENV varialbe

Yaf_Request_Abstract::getControllerName
Yaf_Request_Abstract::getException
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getEnv

(Yaf >=1.0.0)

Yaf_Request_Abstract::getEnv — Retrieve ENV varialbe

Descrierea

public void Yaf_Request_Abstract::getEnv ( string $name [, string $default ] )

Retrieve ENV variable

Parametri

name

the variable name

default

if this parameter is provide, this will be returned if the varialbe can not be found

Valorile întoarse

A se vedea ?i

  • Yaf_Request_Abstract::getServer
  • Yaf_Request_Abstract::getParam
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

(Yaf >=1.0.0)

Yaf_Request_Abstract::getException — The getException purpose

Descrierea

public void Yaf_Request_Abstract::getException ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::getLanguage — The getLanguage purpose

Descrierea

public void Yaf_Request_Abstract::getLanguage ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::getMethod — The getMethod purpose

Descrierea

public void Yaf_Request_Abstract::getMethod ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::getModuleName — The getModuleName purpose

Descrierea

public void Yaf_Request_Abstract::getModuleName ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::getParam — The getParam purpose

Descrierea

public void Yaf_Request_Abstract::getParam ( string $name [, string $default ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

default

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::getParams — The getParams purpose

Descrierea

public void Yaf_Request_Abstract::getParams ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::getRequestUri — The getRequestUri purpose

Descrierea

public void Yaf_Request_Abstract::getRequestUri ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Request_Abstract::getParams
Yaf_Request_Abstract::getServer
Yaf_Request_Abstract


Retrieve SERVER variable

Yaf_Request_Abstract::getRequestUri
Yaf_Request_Abstract::isCli
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getServer

(Yaf >=1.0.0)

Yaf_Request_Abstract::getServer — Retrieve SERVER variable

Descrierea

public void Yaf_Request_Abstract::getServer ( string $name [, string $default ] )

Retrieve SERVER variable

Parametri

name

the variable name

default

if this parameter is provide, this will be returned if the variable can not be found

Valorile întoarse

A se vedea ?i

  • Yaf_Request_Abstract::getParam
  • Yaf_Request_Abstract::getEnv
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

(Yaf >=1.0.0)

Yaf_Request_Abstract::isCli — The isCli purpose

Descrierea

public void Yaf_Request_Abstract::isCli ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::isDispatched — The isDispatched purpose

Descrierea

public void Yaf_Request_Abstract::isDispatched ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::isGet — The isGet purpose

Descrierea

public void Yaf_Request_Abstract::isGet ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::isHead — The isHead purpose

Descrierea

public void Yaf_Request_Abstract::isHead ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::isOptions — The isOptions purpose

Descrierea

public void Yaf_Request_Abstract::isOptions ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::isPost — The isPost purpose

Descrierea

public void Yaf_Request_Abstract::isPost ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::isPut — The isPut purpose

Descrierea

public void Yaf_Request_Abstract::isPut ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::isRouted — The isRouted purpose

Descrierea

public void Yaf_Request_Abstract::isRouted ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::isXmlHttpRequest — The isXmlHttpRequest purpose

Descrierea

public void Yaf_Request_Abstract::isXmlHttpRequest ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::setActionName — The setActionName purpose

Descrierea

public void Yaf_Request_Abstract::setActionName ( string $action )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

action

Valorile întoarse

Yaf_Request_Abstract::isXmlHttpRequest
Yaf_Request_Abstract::setBaseUri
Yaf_Request_Abstract


set base URI

Yaf_Request_Abstract::setActionName
Yaf_Request_Abstract::setControllerName
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setBaseUri

(Yaf >=1.0.0)

Yaf_Request_Abstract::setBaseUri — set base URI

Descrierea

public bool Yaf_Request_Abstract::setBaseUri ( string $uir )

Set base URI, base URI is used when doing routing, in routing phase request URI is used to route a request, while base URI is used to skip the leadding part(base URI) of request URI. That is, if comes a request with request URI a/b/c, then if you set base URI to "a/b", only "/c" will be used in routing phase.

Nota:

generally, you don't need to set this, Yaf will determine it automatically.

Parametri

uir

base URI

Valorile întoarse

bool

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::setControllerName — The setControllerName purpose

Descrierea

public void Yaf_Request_Abstract::setControllerName ( string $controller )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

controller

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::setDispatched — The setDispatched purpose

Descrierea

public void Yaf_Request_Abstract::setDispatched ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::setModuleName — The setModuleName purpose

Descrierea

public void Yaf_Request_Abstract::setModuleName ( string $module )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

module

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::setParam — The setParam purpose

Descrierea

public void Yaf_Request_Abstract::setParam ( string $name [, string $value ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

value

Valorile întoarse

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

(Yaf >=2.1.0)

Yaf_Request_Abstract::setRequestUri — The setRequestUri purpose

Descrierea

public void Yaf_Request_Abstract::setRequestUri ( string $uir )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

uir

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Abstract::setRouted — The setRouted purpose

Descrierea

public void Yaf_Request_Abstract::setRouted ([ string $flag ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

flag

Valorile întoarse

Yaf_Request_Abstract::setRequestUri
Yaf_Request_Http
Yaf_Request_Abstract


The Yaf_Request_Http class

(Yaf >=1.0.0)

Introducere

Any request from client is initialized as a Yaf_Request_Http. you can get the rquest infomations like, uri query and post parameters via methods of this class.

Nota:

For security, $_GET/$_POST are readonly in Yaf, which means if you set a value to these global variables, you can not get it from Yaf_Request_Http::getQurey() or Yaf_Request_Http::getPost().

But there do is some usage need such feature, like unit testing. thus Yaf can be built with --enable-yaf-debug, which will allow Yaf read the value user set via script.

in such case, Yaf will throw a E_STRICT warning to remind you about that: Strict Standards: you are running yaf in debug mode

Sinopsisul clasei

Yaf_Request_Http extends Yaf_Request_Abstract {
/* Proprieta?i */
/* Metode */
private void __clone ( void )
public __construct ([ string $request_uri [, string $base_uri ]] )
public mixed get ( string $name [, string $default ] )
public mixed getCookie ( string $name [, string $default ] )
public void getFiles ( void )
public mixed getPost ( string $name [, string $default ] )
public mixed getQuery ( string $name [, string $default ] )
public void getRequest ( void )
public bool isXmlHttpRequest ( void )
/* Metode mo?tenite */
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 bool 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 ] )
}

Proprieta?i

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

Cuprins

  • Yaf_Request_Http::__clone — The __clone purpose
  • Yaf_Request_Http::__construct — Constructor of Yaf_Request_Http
  • Yaf_Request_Http::get — Retrieve variable from client
  • Yaf_Request_Http::getCookie — Retrieve Cookie variable
  • Yaf_Request_Http::getFiles — The getFiles purpose
  • Yaf_Request_Http::getPost — Retrieve POST variable
  • Yaf_Request_Http::getQuery — Fetch a query parameter
  • Yaf_Request_Http::getRequest — The getRequest purpose
  • Yaf_Request_Http::isXmlHttpRequest — Whether a Ajax Request
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

(Yaf >=1.0.0)

Yaf_Request_Http::__clone — The __clone purpose

Descrierea

private void Yaf_Request_Http::__clone ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Request_Http
Yaf_Request_Http::__construct
Yaf_Request_Http


Constructor of Yaf_Request_Http

Yaf_Request_Http::__clone
Yaf_Request_Http::get
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::__construct

(Yaf >=1.0.0)

Yaf_Request_Http::__construct — Constructor of Yaf_Request_Http

Descrierea

public Yaf_Request_Http::__construct ([ string $request_uri [, string $base_uri ]] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Request_Http::__clone
Yaf_Request_Http::get
Yaf_Request_Http


Retrieve variable from client

Yaf_Request_Http::__construct
Yaf_Request_Http::getCookie
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::get

(Yaf >=1.0.0)

Yaf_Request_Http::get — Retrieve variable from client

Descrierea

public mixed Yaf_Request_Http::get ( string $name [, string $default ] )

Retrieve variable from client, this method will search the name in request pramas, if the name is not found, then will search in POST, GET, Cookie, Server

Parametri

name

the variable name

default

if this parameter is provide, this will be returned if the varialbe can not be found

Valorile întoarse

A se vedea ?i

  • Yaf_Request_Http::getQuery
  • Yaf_Request_Http::getPost
  • Yaf_Request_Http::getCookie
  • Yaf_Request_Http::getServer
  • Yaf_Request_Http::getParam
Yaf_Request_Http::__construct
Yaf_Request_Http::getCookie
Yaf_Request_Http


Retrieve Cookie variable

Yaf_Request_Http::get
Yaf_Request_Http::getFiles
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::getCookie

(Yaf >=1.0.0)

Yaf_Request_Http::getCookie — Retrieve Cookie variable

Descrierea

public mixed Yaf_Request_Http::getCookie ( string $name [, string $default ] )

Retrieve Cookie variable

Parametri

name

the cookie name

default

if this parameter is provide, this will be returned if the cookie can not be found

Valorile întoarse

A se vedea ?i

  • Yaf_Request_Http::get
  • Yaf_Request_Http::getQuery
  • Yaf_Request_Http::getPost
  • Yaf_Request_Http::getServer
  • Yaf_Request_Http::getParam
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

(Yaf >=1.0.0)

Yaf_Request_Http::getFiles — The getFiles purpose

Descrierea

public void Yaf_Request_Http::getFiles ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Request_Http::getCookie
Yaf_Request_Http::getPost
Yaf_Request_Http


Retrieve POST variable

Yaf_Request_Http::getFiles
Yaf_Request_Http::getQuery
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::getPost

(Yaf >=1.0.0)

Yaf_Request_Http::getPost — Retrieve POST variable

Descrierea

public mixed Yaf_Request_Http::getPost ( string $name [, string $default ] )

Retrieve POST variable

Parametri

name

the variable name

default

if this parameter is provide, this will be returned if the varialbe can not be found

Valorile întoarse

A se vedea ?i

  • Yaf_Request_Http::get
  • Yaf_Request_Http::getQuery
  • Yaf_Request_Http::getCookie
  • Yaf_Request_Http::getServer
  • Yaf_Request_Http::getParam
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

(Yaf >=1.0.0)

Yaf_Request_Http::getQuery — Fetch a query parameter

Descrierea

public mixed Yaf_Request_Http::getQuery ( string $name [, string $default ] )

Retrieve GET variable

Parametri

name

the variable name

default

if this parameter is provide, this will be returned if the variable can not be found

Valorile întoarse

A se vedea ?i

  • Yaf_Request_Http::get
  • Yaf_Request_Http::getPost
  • Yaf_Request_Http::getCookie
  • Yaf_Request_Http::getServer
  • Yaf_Request_Http::getParam
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

(Yaf >=1.0.0)

Yaf_Request_Http::getRequest — The getRequest purpose

Descrierea

public void Yaf_Request_Http::getRequest ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Request_Http::getQuery
Yaf_Request_Http::isXmlHttpRequest
Yaf_Request_Http


Whether a Ajax Request

Yaf_Request_Http::getRequest
Yaf_Request_Simple
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::isXmlHttpRequest

(Yaf >=1.0.0)

Yaf_Request_Http::isXmlHttpRequest — Whether a Ajax Request

Descrierea

public bool Yaf_Request_Http::isXmlHttpRequest ( void )

Check the request whether it is a Ajax Request.

Nota:

This method depends on the request header: HTTP_X_REQUESTED_WITH, some Javascript library doesn't set this header while doing Ajax request

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Request_Http::getRequest
Yaf_Request_Simple
Yaf_Request_Http


The Yaf_Request_Simple class

(Yaf >=1.0.0)

Introducere

Yaf_Request_Simple is particularlly used for test puporse. ie. simulate some espacial request under CLI mode.

Sinopsisul clasei

Yaf_Request_Simple extends Yaf_Request_Abstract {
/* Constants */
const string SCHEME_HTTP = http ;
const string SCHEME_HTTPS = https ;
/* Proprieta?i */
/* Metode */
private void __clone ( void )
public __construct ([ string $method [, string $module [, string $controller [, string $action [, array $params ]]]]] )
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 )
/* Metode mo?tenite */
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 bool 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 ] )
}

Proprieta?i

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

Constante predefinite

Yaf_Request_Simple::SCHEME_HTTP

Yaf_Request_Simple::SCHEME_HTTPS

Cuprins

  • Yaf_Request_Simple::__clone — The __clone purpose
  • Yaf_Request_Simple::__construct — Constructor of Yaf_Request_Simple
  • 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

(Yaf >=1.0.0)

Yaf_Request_Simple::__clone — The __clone purpose

Descrierea

private void Yaf_Request_Simple::__clone ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Request_Simple
Yaf_Request_Simple::__construct
Yaf_Request_Simple


Constructor of Yaf_Request_Simple

Yaf_Request_Simple::__clone
Yaf_Request_Simple::get
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::__construct

(Yaf >=1.0.0)

Yaf_Request_Simple::__construct — Constructor of Yaf_Request_Simple

Descrierea

public Yaf_Request_Simple::__construct ([ string $method [, string $module [, string $controller [, string $action [, array $params ]]]]] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Simple::get — The get purpose

Descrierea

public void Yaf_Request_Simple::get ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Simple::getCookie — The getCookie purpose

Descrierea

public void Yaf_Request_Simple::getCookie ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Simple::getFiles — The getFiles purpose

Descrierea

public void Yaf_Request_Simple::getFiles ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Simple::getPost — The getPost purpose

Descrierea

public void Yaf_Request_Simple::getPost ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Simple::getQuery — The getQuery purpose

Descrierea

public void Yaf_Request_Simple::getQuery ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Simple::getRequest — The getRequest purpose

Descrierea

public void Yaf_Request_Simple::getRequest ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Request_Simple::isXmlHttpRequest — The isXmlHttpRequest purpose

Descrierea

public void Yaf_Request_Simple::isXmlHttpRequest ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Request_Simple::getRequest
Yaf_Response_Abstract
Yaf_Request_Simple


The Yaf_Response_Abstract class

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Response_Abstract {
/* Constants */
const string DEFAULT_BODY = "content" ;
/* Proprieta?i */
protected $_header ;
protected $_body ;
protected $_sendheader ;
/* Metode */
public bool appendBody ( string $content [, string $key ] )
public bool clearBody ([ string $key ] )
public void clearHeaders ( void )
private void __clone ( void )
public __construct ( void )
public void __destruct ( void )
public mixed getBody ([ string $key ] )
public void getHeader ( void )
public bool prependBody ( string $content [, string $key ] )
public void response ( void )
protected void setAllHeaders ( void )
public bool setBody ( string $content [, string $key ] )
public void setHeader ( void )
public void setRedirect ( void )
private void __toString ( void )
}

Proprieta?i

_header

_body

_sendheader

Cuprins

  • Yaf_Response_Abstract::appendBody — append to body
  • 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 — Retrieve a exists content
  • Yaf_Response_Abstract::getHeader — The getHeader purpose
  • Yaf_Response_Abstract::prependBody — The prependBody purpose
  • Yaf_Response_Abstract::response — send response
  • Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose
  • Yaf_Response_Abstract::setBody — Set content to response
  • 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


append to body

Yaf_Response_Abstract
Yaf_Response_Abstract::clearBody
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::appendBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::appendBody — append to body

Descrierea

public bool Yaf_Response_Abstract::appendBody ( string $content [, string $key ] )

append a content to a exists content block

Parametri

body

content string

key

the content key, you can set a content with a key, if you don't specific, then Yaf_Response_Abstract::DEFAULT_BODY will be used

Nota:

this parameter is introduced as of 2.2.0

Valorile întoarse

bool

Exemple

Example #1 Yaf_Response_Abstract::appendBody()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->prependBody(" World");

echo $response;
?>

Exemplul de mai sus va afi?a ceva similar cu:

Hello World

A se vedea ?i

  • Yaf_Config_Ini

A se vedea ?i

  • Yaf_Response_Abstract::getBody() - Retrieve a exists content
  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::clearBody() - The clearBody purpose
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

(Yaf >=1.0.0)

Yaf_Response_Abstract::clearBody — The clearBody purpose

Descrierea

public bool Yaf_Response_Abstract::clearBody ([ string $key ] )

Clear existsed content

Parametri

key

the content key, if you don't specific, then all contents will be cleared.

Nota:

this parameter is introduced as of 2.2.0

Valorile întoarse

A se vedea ?i

  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::appendBody() - append to body
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::getBody() - Retrieve a exists content
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

(Yaf >=1.0.0)

Yaf_Response_Abstract::clearHeaders — The clearHeaders purpose

Descrierea

public void Yaf_Response_Abstract::clearHeaders ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Response_Abstract::__clone — The __clone purpose

Descrierea

private void Yaf_Response_Abstract::__clone ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Response_Abstract::__construct — The __construct purpose

Descrierea

public Yaf_Response_Abstract::__construct ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Response_Abstract::__destruct — The __destruct purpose

Descrierea

public void Yaf_Response_Abstract::__destruct ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Response_Abstract::__construct
Yaf_Response_Abstract::getBody
Yaf_Response_Abstract


Retrieve a exists content

Yaf_Response_Abstract::__destruct
Yaf_Response_Abstract::getHeader
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::getBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::getBody — Retrieve a exists content

Descrierea

public mixed Yaf_Response_Abstract::getBody ([ string $key ] )

Retrieve a exists content

Parametri

key

the content key, if you don't specific, then Yaf_Response_Abstract::DEFAULT_BODY will be used. if you pass in a NULL, then all contents will be returned as a array

Nota:

this parameter is introduced as of 2.2.0

Valorile întoarse

Exemple

Example #1 Yaf_Response_Abstract::getBody()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->setBody(" World", "footer");

var_dump($response->getBody()); //default
var_dump($response->getBody(Yaf_Response_Abstract::DEFAULT_BODY)); //same as above
var_dump($response->getBody("footer"));
var_dump($response->getBody(NULL)); //get all
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(5) "Hello"
string(5) "Hello"
string(6) " World"
array(2) {
  ["content"]=>
  string(5) "Hello"
  ["footer"]=>
  string(6) " World"
}

A se vedea ?i

  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::appendBody() - append to body
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::clearBody() - The clearBody purpose
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

(Yaf >=1.0.0)

Yaf_Response_Abstract::getHeader — The getHeader purpose

Descrierea

public void Yaf_Response_Abstract::getHeader ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Response_Abstract::prependBody — The prependBody purpose

Descrierea

public bool Yaf_Response_Abstract::prependBody ( string $content [, string $key ] )

prepend a content to a exists content block

Parametri

body

content string

key

the content key, you can set a content with a key, if you don't specific, then Yaf_Response_Abstract::DEFAULT_BODY will be used

Nota:

this parameter is introduced as of 2.2.0

Valorile întoarse

bool

Exemple

Example #1 Yaf_Response_Abstract::prependBody()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("World")->prependBody("Hello ");

echo $response;
?>

Exemplul de mai sus va afi?a ceva similar cu:

Hello World

A se vedea ?i

  • Yaf_Response_Abstract::getBody() - Retrieve a exists content
  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::appendBody() - append to body
  • Yaf_Response_Abstract::clearBody() - The clearBody purpose
Yaf_Response_Abstract::getHeader
Yaf_Response_Abstract::response
Yaf_Response_Abstract


send response

Yaf_Response_Abstract::prependBody
Yaf_Response_Abstract::setAllHeaders
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::response

(Yaf >=1.0.0)

Yaf_Response_Abstract::response — send response

Descrierea

public void Yaf_Response_Abstract::response ( void )

send response

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #1 Yaf_Response_Abstract::response()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->setBody(" World", "footer");

$response->response();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Hello World

A se vedea ?i

  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::clearBody() - The clearBody purpose
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

(Yaf >=1.0.0)

Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose

Descrierea

protected void Yaf_Response_Abstract::setAllHeaders ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Response_Abstract::response
Yaf_Response_Abstract::setBody
Yaf_Response_Abstract


Set content to response

Yaf_Response_Abstract::setAllHeaders
Yaf_Response_Abstract::setHeader
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::setBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::setBody — Set content to response

Descrierea

public bool Yaf_Response_Abstract::setBody ( string $content [, string $key ] )

Set content to response

Parametri

body

content string

key

the content key, you can set a content with a key, if you don't specific, then Yaf_Response_Abstract::DEFAULT_BODY will be used

Nota:

this parameter is introduced as of 2.2.0

Valorile întoarse

Exemple

Example #1 Yaf_Response_Abstract::setBody()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->setBody(" World", "footer");

print_r($response);
echo $response;
?>

Exemplul de mai sus va afi?a ceva similar cu:

Yaf_Response_Http Object
(
    [_header:protected] => Array
        (
        )

    [_body:protected] => Array
        (
            [content] => Hello
            [footer] =>  World
        )

    [_sendheader:protected] => 1
    [_response_code:protected] => 200
)
Hello World

A se vedea ?i

  • Yaf_Response_Abstract::getBody() - Retrieve a exists content
  • Yaf_Response_Abstract::appendBody() - append to body
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::clearBody() - The clearBody purpose
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

(Yaf >=1.0.0)

Yaf_Response_Abstract::setHeader — The setHeader purpose

Descrierea

public void Yaf_Response_Abstract::setHeader ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Response_Abstract::setRedirect — The setRedirect purpose

Descrierea

public void Yaf_Response_Abstract::setRedirect ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Response_Abstract::__toString — The __toString purpose

Descrierea

private void Yaf_Response_Abstract::__toString ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Response_Abstract::setRedirect
Yaf_Route_Interface
Yaf_Response_Abstract


The Yaf_Route_Interface class

(Yaf >=1.0.0)

Introducere

Yaf_Route_Interface used for developer defined their custom route.

Sinopsisul clasei

Yaf_Route_Interface {
/* Metode */
abstract public string assemble ( array $info [, array $query ] )
abstract public bool route ( Yaf_Request_Abstract $request )
}

Cuprins

  • Yaf_Route_Interface::assemble — assemble a request
  • Yaf_Route_Interface::route — route a request
Yaf_Response_Abstract::__toString
Yaf_Route_Interface::assemble
Yaf


assemble a request

Yaf_Route_Interface
Yaf_Route_Interface::route
Yaf_Route_Interface
PHP Manual

Yaf_Route_Interface::assemble

(Yaf >=2.3.0)

Yaf_Route_Interface::assemble — assemble a request

Descrierea

abstract public string Yaf_Route_Interface::assemble ( array $info [, array $query ] )

this method returns a url according to the argument info, and append query strings to the url according to the argument query.

a route should implement this method according to its own route rules, and do a reverse progress.

Parametri

info

query

Valorile întoarse

Yaf_Route_Interface
Yaf_Route_Interface::route
Yaf_Route_Interface


route a request

Yaf_Route_Interface::assemble
Yaf_Route_Map
Yaf_Route_Interface
PHP Manual

Yaf_Route_Interface::route

(Yaf >=1.0.0)

Yaf_Route_Interface::route — route a request

Descrierea

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.

Nota:

since of 2.3.0, there is another method should also be implemented, see Yaf_Route_Interface::assemble().

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.

Parametri

request

A Yaf_Request_Abstract instance.

Valorile întoarse

Yaf_Route_Interface::assemble
Yaf_Route_Map
Yaf_Route_Interface


The Yaf_Route_Map class

(Yaf >=1.0.0)

Introducere

Yaf_Route_Map is a built-in route, it simply convert a URI endpoint (that part of the URI which comes after the base URI: see Yaf_Request_Abstract::setBaseUri()) to a controller name or action name(depends on the paramter passed to Yaf_Route_Map::__construct()) in following rule: A => controller A. A/B/C => controller A_B_C. A/B/C/D/E => controller A_B_C_D_E.

If the second parameter of Yaf_Route_Map::__construct() is specificed, then only the part before delimeter of URI will used to routing, the part after it is used to routing request parameters (see the example section of Yaf_Route_Map::__construct()).

Sinopsisul clasei

Yaf_Route_Map implements Yaf_Route_Interface {
/* Proprieta?i */
protected $_ctl_router ;
protected $_delimeter ;
/* Metode */
public string assemble ( array $info [, array $query ] )
public __construct ([ string $controller_prefer = false [, string $delimiter = "" ]] )
public bool route ( Yaf_Request_Abstract $request )
}

Proprieta?i

_ctl_router

_delimeter

Cuprins

  • Yaf_Route_Map::assemble — Assemble a url
  • Yaf_Route_Map::__construct — The __construct purpose
  • Yaf_Route_Map::route — The route purpose
Yaf_Route_Interface::route
Yaf_Route_Map::assemble
Yaf


Assemble a url

Yaf_Route_Map
Yaf_Route_Map::__construct
Yaf_Route_Map
PHP Manual

Yaf_Route_Map::assemble

(Yaf >=2.3.0)

Yaf_Route_Map::assemble — Assemble a url

Descrierea

public string Yaf_Route_Map::assemble ( array $info [, array $query ] )

Assemble a url.

Parametri

info

query

Exemple

Example #1 Yaf_Route_Map::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Map();

$router->addRoute("map", $route);

var_dump($router->getRoute('map')->assemble(
                        array(
                                ':c' => 'foo_bar'
                        ),
                        array(
                                'tkey1' => 'tval1',
                                'tkey2' => 'tval2'
                        )
                   )
);

$route = new Yaf_Route_Map(true, '_');
$router->addRoute("map", $route);

var_dump($router->getRoute('map')->assemble(
                        array(
                                ':a' => 'foo_bar'
                        ),
                        array(
                                'tkey1' => 'tval1',
                                'tkey2' => 'tval2'
                        )
                   )
);

Exemplul de mai sus va afi?a ceva similar cu:

string(%d) "/foo/bar?tkey1=tval1&tkey2=tval2"
string(%d) "/foo/bar/_/tkey1/tval1/tkey2/tval2"

Valorile întoarse

Yaf_Route_Map
Yaf_Route_Map::__construct
Yaf_Route_Map


The __construct purpose

Yaf_Route_Map::assemble
Yaf_Route_Map::route
Yaf_Route_Map
PHP Manual

Yaf_Route_Map::__construct

(Yaf >=1.0.0)

Yaf_Route_Map::__construct — The __construct purpose

Descrierea

public Yaf_Route_Map::__construct ([ string $controller_prefer = false [, string $delimiter = "" ]] )

Parametri

controller_prefer

Whether the result should considering as controller or action

delimiter

Valorile întoarse

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a ceva similar cu:

/* for http://yourdomain.com/product/foo/bar
 * route will result in following values:
 */
array(
  "controller" => "product_foo_bar",
)

Example #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, "_"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

/* for http://yourdomain.com/user/list/_/foo/22
 * route will result in following values:
 */
array(
    "action" => "user_list",
)

/**
 * and request parameters:
 */
array(
  "foo"   => 22,
)

Example #3 Yaf_Route_Map()example

<?php
   /**
    * Add a map route to Yaf_Router route stack by calling addconfig
    */
    $config = array(
        "name" => array(
           "type"  => "map",         //Yaf_Route_Map route
           "controllerPrefer" => FALSE,
           "delimiter"        => "#!",
           ),
    );
    Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
        new Yaf_Config_Simple($config));
?>

A se vedea ?i

  • 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::assemble
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

(Yaf >=1.0.0)

Yaf_Route_Map::route — The route purpose

Descrierea

public bool Yaf_Route_Map::route ( Yaf_Request_Abstract $request )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

request

Valorile întoarse

Yaf_Route_Map::__construct
Yaf_Route_Regex
Yaf_Route_Map


The Yaf_Route_Regex class

(Yaf >=1.0.0)

Introducere

Yaf_Route_Regex is the most flexible route among the Yaf built-in routes.

Sinopsisul clasei

Yaf_Route_Regex extends Yaf_Route_Interface implements Yaf_Route_Interface {
/* Proprieta?i */
protected $_route ;
protected $_default ;
protected $_maps ;
protected $_verify ;
/* Metode */
public string assemble ( array $info [, array $query ] )
public __construct ( string $match , array $route [, array $map [, array $verify [, string $reverse ]]] )
public bool route ( Yaf_Request_Abstract $request )
/* Metode mo?tenite */
abstract public string Yaf_Route_Interface::assemble ( array $info [, array $query ] )
abstract public bool Yaf_Route_Interface::route ( Yaf_Request_Abstract $request )
}

Proprieta?i

_route

_default

_maps

_verify

Cuprins

  • Yaf_Route_Regex::assemble — Assemble a url
  • Yaf_Route_Regex::__construct — Yaf_Route_Regex constructor
  • Yaf_Route_Regex::route — The route purpose
Yaf_Route_Map::route
Yaf_Route_Regex::assemble
Yaf


Assemble a url

Yaf_Route_Regex
Yaf_Route_Regex::__construct
Yaf_Route_Regex
PHP Manual

Yaf_Route_Regex::assemble

(Yaf >=2.3.0)

Yaf_Route_Regex::assemble — Assemble a url

Descrierea

public string Yaf_Route_Regex::assemble ( array $info [, array $query ] )

Assemble a url.

Parametri

info

query

Exemple

Example #1 Yaf_Route_Regex::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Regex(
            "#^/product/([^/]+)/([^/])+#",
            array(
                'controller' => "product",  //route to product controller,
                ),
            array(),
            array(),
            '/:m/:c/:a'
        );

$router->addRoute("regex", $route);

var_dump($router->getRoute('regex')->assemble(
            array(
                ':m' => 'module',
                ':c' => 'controller',
                ':a' => 'action'
                ),
            array(
                'tkey1' => 'tval1',
                'tkey2' =>
                'tval2'
                )
            )
        );

Exemplul de mai sus va afi?a ceva similar cu:

string(49) "/module/controller/action?tkey1=tval1&tkey2=tval2"

Valorile întoarse

Yaf_Route_Regex
Yaf_Route_Regex::__construct
Yaf_Route_Regex


Yaf_Route_Regex constructor

Yaf_Route_Regex::assemble
Yaf_Route_Regex::route
Yaf_Route_Regex
PHP Manual

Yaf_Route_Regex::__construct

(Yaf >=1.0.0)

Yaf_Route_Regex::__construct — Yaf_Route_Regex constructor

Descrierea

public Yaf_Route_Regex::__construct ( string $match , array $route [, array $map [, array $verify [, string $reverse ]]] )

Parametri

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

reverse

a string, used to assemble url, see Yaf_Route_Regex::assemble().

Nota:

this parameter is introduced in 2.3.0

Valorile întoarse

Exemple

Example #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.
           )
        )
    );
?>

Example #2 Yaf_Route_Regex(as of 2.3.0)()example

<?php
   /**
    * Use match result as MVC name
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Regex(
           "#^/product/([^/]+)/([^/])+#i", //match request uri leading "/product"
           array(
              'controller' => ":name", // route to :name, which is $1 in the match result as controller name
           ),
           array(
              1 => "name",   // now you can call $request->getParam("name")
              2 => "id",     // to get the first captrue in the match pattern.
           )
        )
    );
?>

Example #3 Yaf_Route_Regex and named capture ground(as of 2.3.0)()example

<?php
   /**
    * Use match result as MVC name
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Regex(
           "#^/product/(?<name>[^/]+)/([^/])+#i", //match request uri leading "/product"
           array(
           'controller' => ":name", // route to :name,
                                    // which is named capture group 'name' in the match result as controller name
           ),
           array(
              2 => "id",     // to get the first captrue in the match pattern.
           )
        )
    );
?>

Example #4 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));
?>

A se vedea ?i

  • 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::assemble
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

(Yaf >=1.0.0)

Yaf_Route_Regex::route — The route purpose

Descrierea

public bool Yaf_Route_Regex::route ( Yaf_Request_Abstract $request )

Route a incoming request.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

request

Valorile întoarse

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

(Yaf >=1.0.0)

Introducere

For usage, please see the example section of Yaf_Route_Rewrite::__construct()

Sinopsisul clasei

Yaf_Route_Rewrite extends Yaf_Route_Interface implements Yaf_Route_Interface {
/* Proprieta?i */
protected $_route ;
protected $_default ;
protected $_verify ;
/* Metode */
public string assemble ( array $info [, array $query ] )
public __construct ( string $match , array $route [, array $verify ] )
public bool route ( Yaf_Request_Abstract $request )
/* Metode mo?tenite */
abstract public string Yaf_Route_Interface::assemble ( array $info [, array $query ] )
abstract public bool Yaf_Route_Interface::route ( Yaf_Request_Abstract $request )
}

Proprieta?i

_route

_default

_verify

Cuprins

  • Yaf_Route_Rewrite::assemble — Assemble a url
  • Yaf_Route_Rewrite::__construct — Yaf_Route_Rewrite constructor
  • Yaf_Route_Rewrite::route — The route purpose
Yaf_Route_Regex::route
Yaf_Route_Rewrite::assemble
Yaf


Assemble a url

Yaf_Route_Rewrite
Yaf_Route_Rewrite::__construct
Yaf_Route_Rewrite
PHP Manual

Yaf_Route_Rewrite::assemble

(Yaf >=2.3.0)

Yaf_Route_Rewrite::assemble — Assemble a url

Descrierea

public string Yaf_Route_Rewrite::assemble ( array $info [, array $query ] )

Assemble a url.

Parametri

info

query

Exemple

Example #1 Yaf_Route_Rewrite::assemble()example

router = new Yaf_Router();

$route  = new Yaf_Route_Rewrite(
                "/product/:name/:id/*",
                array(
                        'controller' => "product",
                ),
                array()
);

$router->addRoute("rewrite", $route);

var_dump($router->getRoute('rewrite')->assemble(
                        array(
                                ':name' => 'foo',
                                ':id' => 'bar',
                                ':tmpkey1' => 'tmpval1'
                        ),
                        array(
                                'tkey1' => 'tval1',
                                'tkey2' => 'tval2'
                             )
                        )
);

Exemplul de mai sus va afi?a ceva similar cu:

string(57) "/product/foo/bar/tmpkey1/tmpval1/?tkey1=tval1&tkey2=tval2"

Valorile întoarse

Yaf_Route_Rewrite
Yaf_Route_Rewrite::__construct
Yaf_Route_Rewrite


Yaf_Route_Rewrite constructor

Yaf_Route_Rewrite::assemble
Yaf_Route_Rewrite::route
Yaf_Route_Rewrite
PHP Manual

Yaf_Route_Rewrite::__construct

(Yaf >=1.0.0)

Yaf_Route_Rewrite::__construct — Yaf_Route_Rewrite constructor

Descrierea

public Yaf_Route_Rewrite::__construct ( string $match , array $route [, array $verify ] )

Parametri

match

A pattern, will be used to match a request uri, if it doesn't match, Yaf_Route_Rewrite will return FALSE.

You can use :name style to name segments matched, and use * to match the rest of the URL segments.

route

When the match pattern matches the request uri, Yaf_Route_Rewrite will use this to decide which module/controller/action is the destination.

Either of module/controller/action in this array is optional, if you don't assign a specific value, it will be routed to default.

verify

Valorile întoarse

Exemple

Example #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,
           ),
        )
    );
?>

Exemplul de mai sus va afi?a ceva similar cu:

/* 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
)

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

/* 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,
)

Example #3 Yaf_Route_Rewrite(as of 2.3.0)()example

<?php
   /**
    * Add a rewrite route use match result as m/c/a name
    */
    $config = array(
        "name" => array(
           "type"  => "rewrite",
           "match" => "/user-list/:a/:id", //match only /user-list/*
           "route" => array(
               'controller' => "user",   //route to user controller,
               'action'     => ":a",     //route to :a action
           ),
        ),
    );
    Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
        new Yaf_Config_Simple($config));
?>

Exemplul de mai sus va afi?a ceva similar cu:

/* for http://yourdomain.com/user-list/list/22
 * route will result in following values:
 */
array(
  "controller" => "user",
  "action"     => "list",
  "module"     => "index", //(default)
)

/**
 * and request parameters:
 */
array(
  "id"   => 22,
)

A se vedea ?i

  • 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::assemble
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

(Yaf >=1.0.0)

Yaf_Route_Rewrite::route — The route purpose

Descrierea

public bool Yaf_Route_Rewrite::route ( Yaf_Request_Abstract $request )

Parametri

request

Valorile întoarse

Yaf_Route_Rewrite::__construct
Yaf_Router
Yaf_Route_Rewrite


The Yaf_Router class

(Yaf >=1.0.0)

Introducere

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 URI: see Yaf_Request_Abstract::setBaseUri()) 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):

Example #1 Rewrite rule for Apache

RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css|html)$ index.php
or (preferred):

Example #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:

Example #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:

Example #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 Yaf_Route_Static, 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.

Nota:

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:

Example #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

Sinopsisul clasei

Yaf_Router {
/* Proprieta?i */
protected $_routes ;
protected $_current ;
/* Metode */
public bool addConfig ( Yaf_Config_Abstract $config )
public bool addRoute ( string $name , Yaf_Route_Abstract $route )
public __construct ( void )
public string getCurrentRoute ( void )
public Yaf_Route_Interface getRoute ( string $name )
public mixed getRoutes ( void )
public bool route ( Yaf_Request_Abstract $request )
}

Proprieta?i

_routes

registered routes stack

_current

after routing phase, this indicated the name of which route is used to route current request. you can get this name by Yaf_Router::getCurrentRoute().

Cuprins

  • 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 — Retrieve a route by name
  • Yaf_Router::getRoutes — Retrieve registered routes
  • 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

(Yaf >=1.0.0)

Yaf_Router::addConfig — Add config-defined routes into Router

Descrierea

public bool Yaf_Router::addConfig ( Yaf_Config_Abstract $config )

Add routes defined by configs into Yaf_Router's route stack

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An Yaf_Config_Abstract instance, which should contains one or more valid route configs

Exemple

Example #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 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

;a simple router match /**?r=PATH_INFO
routes.route_name3.type="supervar"
routes.route_name3.varname=r

;a map route match any request to controller
routes.route_name4.type="map"
routes.route_name4.controllerPrefer=TRUE
routes.route_namer.delimiter="#!"

Example #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);
    }
?>

A se vedea ?i

  • 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

(Yaf >=1.0.0)

Yaf_Router::addRoute — Add new Route into Router

Descrierea

public bool 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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #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);
    }
?>

A se vedea ?i

  • 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

(Yaf >=1.0.0)

Yaf_Router::__construct — Yaf_Router constructor

Descrierea

public Yaf_Router::__construct ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

(Yaf >=1.0.0)

Yaf_Router::getCurrentRoute — Get the effective route name

Descrierea

public string Yaf_Router::getCurrentRoute ( void )

Get the name of the route which is effective in the route process.

Nota:

You should call this method after the route process finished, since before that, this method will always return NULL.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

String, the name of the effective route.

Exemple

Example #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());
    }
?>

Example #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());
    }
?>
?>

Exemplul de mai sus va afi?a ceva similar cu:

/* 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"

A se vedea ?i

  • Yaf_Bootstrap_Abstract
  • Yaf_Plugin_Abstract
  • Yaf_Router::addRoute() - Add new Route into Router
Yaf_Router::__construct
Yaf_Router::getRoute
Yaf_Router


Retrieve a route by name

Yaf_Router::getCurrentRoute
Yaf_Router::getRoutes
Yaf_Router
PHP Manual

Yaf_Router::getRoute

(Yaf >=1.0.0)

Yaf_Router::getRoute — Retrieve a route by name

Descrierea

public Yaf_Route_Interface Yaf_Router::getRoute ( string $name )

Retrieve a route by name, see also Yaf_Router::getCurrentRoute()

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • Yaf_Bootstrap_Abstract
  • Yaf_Plugin_Abstract
  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Router::getCurrentRoute() - Get the effective route name
Yaf_Router::getCurrentRoute
Yaf_Router::getRoutes
Yaf_Router


Retrieve registered routes

Yaf_Router::getRoute
Yaf_Router::route
Yaf_Router
PHP Manual

Yaf_Router::getRoutes

(Yaf >=1.0.0)

Yaf_Router::getRoutes — Retrieve registered routes

Descrierea

public mixed Yaf_Router::getRoutes ( void )

Retrieve registered routes

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Router::getRoute
Yaf_Router::route
Yaf_Router


The route purpose

Yaf_Router::getRoutes
Yaf_Route_Simple
Yaf_Router
PHP Manual

Yaf_Router::route

(Yaf >=1.0.0)

Yaf_Router::route — The route purpose

Descrierea

public bool Yaf_Router::route ( Yaf_Request_Abstract $request )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Router::getRoutes
Yaf_Route_Simple
Yaf_Router


The Yaf_Route_Simple class

(Yaf >=1.0.0)

Introducere

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.

Sinopsisul clasei

Yaf_Route_Simple implements Yaf_Route_Interface {
/* Proprieta?i */
protected $controller ;
protected $module ;
protected $action ;
/* Metode */
public string assemble ( array $info [, array $query ] )
public __construct ( string $module_name , string $controller_name , string $action_name )
public bool route ( Yaf_Request_Abstract $request )
}

Proprieta?i

controller

module

action

Cuprins

  • Yaf_Route_Simple::assemble — Assemble a url
  • Yaf_Route_Simple::__construct — Yaf_Route_Simple constructor
  • Yaf_Route_Simple::route — Route a request
Yaf_Router::route
Yaf_Route_Simple::assemble
Yaf


Assemble a url

Yaf_Route_Simple
Yaf_Route_Simple::__construct
Yaf_Route_Simple
PHP Manual

Yaf_Route_Simple::assemble

(Yaf >=2.3.0)

Yaf_Route_Simple::assemble — Assemble a url

Descrierea

public string Yaf_Route_Simple::assemble ( array $info [, array $query ] )

Assemble a url.

Parametri

info

query

Exemple

Example #1 Yaf_Route_Simple::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Simple('m', 'c', 'a');

$router->addRoute("simple", $route);

var_dump($router->getRoute('simple')->assemble(
            array(
                ':a' => 'yafaction',
                'tkey' => 'tval',
                ':c' => 'yafcontroller',
                ':m' => 'yafmodule'
                ),
            array(
                'tkey1' => 'tval1',
                'tkey2' => 'tval2'
                )
            ));

Exemplul de mai sus va afi?a ceva similar cu:

string(64) "?m=yafmodule&c=yafcontroller&a=yafaction&tkey1=tval1&tkey2=tval2"

Valorile întoarse

Yaf_Route_Simple
Yaf_Route_Simple::__construct
Yaf_Route_Simple


Yaf_Route_Simple constructor

Yaf_Route_Simple::assemble
Yaf_Route_Simple::route
Yaf_Route_Simple
PHP Manual

Yaf_Route_Simple::__construct

(Yaf >=1.0.0)

Yaf_Route_Simple::__construct — Yaf_Route_Simple constructor

Descrierea

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.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

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.

Valorile întoarse

Always return TRUE.

Exemple

Example #1 Yaf_Route_Simple::route()example

<?php
   $route = new Yaf_Route_Simple("m", "controller", "act");
   Yaf_Router::getInstance()->addRoute("simple", $route);
?>

Example #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)

A se vedea ?i

  • 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::assemble
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

(Yaf >=1.0.0)

Yaf_Route_Simple::route — Route a request

Descrierea

public bool Yaf_Route_Simple::route ( Yaf_Request_Abstract $request )

see Yaf_Route_Simple::__construct()

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

request

Valorile întoarse

always be TRUE

A se vedea ?i

  • 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

(Yaf >=1.0.0)

Introducere

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 routes stack, since there is always be one in Yaf_Router's routes stack, and always be called at the last time.

Sinopsisul clasei

Yaf_Route_Static implements Yaf_Router {
/* Metode */
public string assemble ( array $info [, array $query ] )
public void match ( string $uri )
public bool route ( Yaf_Request_Abstract $request )
}

Cuprins

  • Yaf_Route_Static::assemble — Assemble a url
  • Yaf_Route_Static::match — The match purpose
  • Yaf_Route_Static::route — Route a request
Yaf_Route_Simple::route
Yaf_Route_Static::assemble
Yaf


Assemble a url

Yaf_Route_Static
Yaf_Route_Static::match
Yaf_Route_Static
PHP Manual

Yaf_Route_Static::assemble

(Yaf >=2.3.0)

Yaf_Route_Static::assemble — Assemble a url

Descrierea

public string Yaf_Route_Static::assemble ( array $info [, array $query ] )

Assemble a url.

Parametri

info

query

Exemple

Example #1 Yaf_Route_Static::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Static();

$router->addRoute("static", $route);

var_dump($router->getRoute('static')->assemble(
            array(
                ':a' => 'yafaction',
                'tkey' => 'tval',
                ':c' => 'yafcontroller',
                ':m' => 'yafmodule'
            ),
        )
);

var_dump($router->getRoute('static')->assemble(
            array(
                ':a' => 'yafaction',
                'tkey' => 'tval',
                ':c' => 'yafcontroller',
                ':m' => 'yafmodule'
            ),
            array(
                'tkey1' => 'tval1',
                'tkey2' => 'tval2'
            )
        )
);

Exemplul de mai sus va afi?a ceva similar cu:

string(%d) "/yafmodule/yafcontroller/yafaction"
string(%d) "/yafmodule/yafcontroller/yafaction?tkey1=tval1&tkey2=tval2"

Valorile întoarse

Yaf_Route_Static
Yaf_Route_Static::match
Yaf_Route_Static


The match purpose

Yaf_Route_Static::assemble
Yaf_Route_Static::route
Yaf_Route_Static
PHP Manual

Yaf_Route_Static::match

(Yaf >=1.0.0)

Yaf_Route_Static::match — The match purpose

Descrierea

public void Yaf_Route_Static::match ( string $uri )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

uri

Valorile întoarse

Yaf_Route_Static::assemble
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

(Yaf >=1.0.0)

Yaf_Route_Static::route — Route a request

Descrierea

public bool Yaf_Route_Static::route ( Yaf_Request_Abstract $request )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

request

Valorile întoarse

always be TRUE

Exemple

Example #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

A se vedea ?i

  • 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

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Route_Supervar implements Yaf_Route_Interface {
/* Proprieta?i */
protected $_var_name ;
/* Metode */
public string assemble ( array $info [, array $query ] )
public __construct ( string $supervar_name )
public bool route ( Yaf_Request_Abstract $request )
}

Proprieta?i

_var_name

Cuprins

  • Yaf_Route_Supervar::assemble — Assemble a url
  • Yaf_Route_Supervar::__construct — The __construct purpose
  • Yaf_Route_Supervar::route — The route purpose
Yaf_Route_Static::route
Yaf_Route_Supervar::assemble
Yaf


Assemble a url

Yaf_Route_Supervar
Yaf_Route_Supervar::__construct
Yaf_Route_Supervar
PHP Manual

Yaf_Route_Supervar::assemble

(Yaf >=2.3.0)

Yaf_Route_Supervar::assemble — Assemble a url

Descrierea

public string Yaf_Route_Supervar::assemble ( array $info [, array $query ] )

Assemble a url.

Parametri

info

query

Exemple

Example #1 Yaf_Route_Supervar::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Supervar('r');

$router->addRoute("supervar", $route);

var_dump($router->getRoute('supervar')->assemble(
        array(
              ':a' => 'yafaction',
              'tkey' => 'tval',
              ':c' => 'yafcontroller',
              ':m' => 'yafmodule'
        ),
        array(
              'tkey1' => 'tval1',
              'tkey2' => 'tval2'
        )
));

try {
var_dump($router->getRoute('supervar')->assemble(
        array(
              ':a' => 'yafaction',
              'tkey' => 'tval',
              ':m' => 'yafmodule'
        ),
        array(
              'tkey1' => 'tval1',
              'tkey2' => 'tval2',
              1 => array(),
        )
));
} catch (Exception $e) {
    var_dump($e->getMessage());
}

Exemplul de mai sus va afi?a ceva similar cu:

string(%d) "?r=/yafmodule/yafcontroller/yafaction&tkey1=tval1&tkey2=tval2"
string(%d) "You need to specify the controller by ':c'"

Valorile întoarse

Yaf_Route_Supervar
Yaf_Route_Supervar::__construct
Yaf_Route_Supervar


The __construct purpose

Yaf_Route_Supervar::assemble
Yaf_Route_Supervar::route
Yaf_Route_Supervar
PHP Manual

Yaf_Route_Supervar::__construct

(Yaf >=1.0.0)

Yaf_Route_Supervar::__construct — The __construct purpose

Descrierea

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.

Parametri

supervar_name

The name of key.

Valorile întoarse

Exemple

Example #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"));
    );
?>

Exemplul de mai sus va afi?a ceva similar cu:

/** 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,
     )
  )

A se vedea ?i

  • 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::assemble
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

(Yaf >=1.0.0)

Yaf_Route_Supervar::route — The route purpose

Descrierea

public bool Yaf_Route_Supervar::route ( Yaf_Request_Abstract $request )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

request

Valorile întoarse

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

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Session implements Iterator , ArrayAccess , Countable {
/* Proprieta?i */
protected static $_instance ;
protected $_session ;
protected $_started ;
/* Metode */
private void __clone ( void )
private __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 )
}

Proprieta?i

_instance

_session

_started

Cuprins

  • Yaf_Session::__clone — The __clone purpose
  • Yaf_Session::__construct — Constructor of Yaf_Session
  • 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

(Yaf >=1.0.0)

Yaf_Session::__clone — The __clone purpose

Descrierea

private void Yaf_Session::__clone ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Session
Yaf_Session::__construct
Yaf_Session


Constructor of Yaf_Session

Yaf_Session::__clone
Yaf_Session::count
Yaf_Session
PHP Manual

Yaf_Session::__construct

(Yaf >=1.0.0)

Yaf_Session::__construct — Constructor of Yaf_Session

Descrierea

private Yaf_Session::__construct ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Session::__clone
Yaf_Session::count
Yaf_Session


The count purpose

Yaf_Session::__construct
Yaf_Session::current
Yaf_Session
PHP Manual

Yaf_Session::count

(Yaf >=1.0.0)

Yaf_Session::count — The count purpose

Descrierea

public void Yaf_Session::count ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Session::__construct
Yaf_Session::current
Yaf_Session


The current purpose

Yaf_Session::count
Yaf_Session::del
Yaf_Session
PHP Manual

Yaf_Session::current

(Yaf >=1.0.0)

Yaf_Session::current — The current purpose

Descrierea

public void Yaf_Session::current ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Session::count
Yaf_Session::del
Yaf_Session


The del purpose

Yaf_Session::current
Yaf_Session::__get
Yaf_Session
PHP Manual

Yaf_Session::del

(Yaf >=1.0.0)

Yaf_Session::del — The del purpose

Descrierea

public void Yaf_Session::del ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

Yaf_Session::current
Yaf_Session::__get
Yaf_Session


The __get purpose

Yaf_Session::del
Yaf_Session::getInstance
Yaf_Session
PHP Manual

Yaf_Session::__get

(Yaf >=1.0.0)

Yaf_Session::__get — The __get purpose

Descrierea

public void Yaf_Session::__get ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

Yaf_Session::del
Yaf_Session::getInstance
Yaf_Session


The getInstance purpose

Yaf_Session::__get
Yaf_Session::has
Yaf_Session
PHP Manual

Yaf_Session::getInstance

(Yaf >=1.0.0)

Yaf_Session::getInstance — The getInstance purpose

Descrierea

public static void Yaf_Session::getInstance ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Session::__get
Yaf_Session::has
Yaf_Session


The has purpose

Yaf_Session::getInstance
Yaf_Session::__isset
Yaf_Session
PHP Manual

Yaf_Session::has

(Yaf >=1.0.0)

Yaf_Session::has — The has purpose

Descrierea

public void Yaf_Session::has ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

Yaf_Session::getInstance
Yaf_Session::__isset
Yaf_Session


The __isset purpose

Yaf_Session::has
Yaf_Session::key
Yaf_Session
PHP Manual

Yaf_Session::__isset

(Yaf >=1.0.0)

Yaf_Session::__isset — The __isset purpose

Descrierea

public void Yaf_Session::__isset ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

Yaf_Session::has
Yaf_Session::key
Yaf_Session


The key purpose

Yaf_Session::__isset
Yaf_Session::next
Yaf_Session
PHP Manual

Yaf_Session::key

(Yaf >=1.0.0)

Yaf_Session::key — The key purpose

Descrierea

public void Yaf_Session::key ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Session::__isset
Yaf_Session::next
Yaf_Session


The next purpose

Yaf_Session::key
Yaf_Session::offsetExists
Yaf_Session
PHP Manual

Yaf_Session::next

(Yaf >=1.0.0)

Yaf_Session::next — The next purpose

Descrierea

public void Yaf_Session::next ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Session::key
Yaf_Session::offsetExists
Yaf_Session


The offsetExists purpose

Yaf_Session::next
Yaf_Session::offsetGet
Yaf_Session
PHP Manual

Yaf_Session::offsetExists

(Yaf >=1.0.0)

Yaf_Session::offsetExists — The offsetExists purpose

Descrierea

public void Yaf_Session::offsetExists ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

Yaf_Session::next
Yaf_Session::offsetGet
Yaf_Session


The offsetGet purpose

Yaf_Session::offsetExists
Yaf_Session::offsetSet
Yaf_Session
PHP Manual

Yaf_Session::offsetGet

(Yaf >=1.0.0)

Yaf_Session::offsetGet — The offsetGet purpose

Descrierea

public void Yaf_Session::offsetGet ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

Yaf_Session::offsetExists
Yaf_Session::offsetSet
Yaf_Session


The offsetSet purpose

Yaf_Session::offsetGet
Yaf_Session::offsetUnset
Yaf_Session
PHP Manual

Yaf_Session::offsetSet

(Yaf >=1.0.0)

Yaf_Session::offsetSet — The offsetSet purpose

Descrierea

public void Yaf_Session::offsetSet ( string $name , string $value )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

value

Valorile întoarse

Yaf_Session::offsetGet
Yaf_Session::offsetUnset
Yaf_Session


The offsetUnset purpose

Yaf_Session::offsetSet
Yaf_Session::rewind
Yaf_Session
PHP Manual

Yaf_Session::offsetUnset

(Yaf >=1.0.0)

Yaf_Session::offsetUnset — The offsetUnset purpose

Descrierea

public void Yaf_Session::offsetUnset ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

Yaf_Session::offsetSet
Yaf_Session::rewind
Yaf_Session


The rewind purpose

Yaf_Session::offsetUnset
Yaf_Session::__set
Yaf_Session
PHP Manual

Yaf_Session::rewind

(Yaf >=1.0.0)

Yaf_Session::rewind — The rewind purpose

Descrierea

public void Yaf_Session::rewind ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Session::offsetUnset
Yaf_Session::__set
Yaf_Session


The __set purpose

Yaf_Session::rewind
Yaf_Session::__sleep
Yaf_Session
PHP Manual

Yaf_Session::__set

(Yaf >=1.0.0)

Yaf_Session::__set — The __set purpose

Descrierea

public void Yaf_Session::__set ( string $name , string $value )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

value

Valorile întoarse

Yaf_Session::rewind
Yaf_Session::__sleep
Yaf_Session


The __sleep purpose

Yaf_Session::__set
Yaf_Session::start
Yaf_Session
PHP Manual

Yaf_Session::__sleep

(Yaf >=1.0.0)

Yaf_Session::__sleep — The __sleep purpose

Descrierea

private void Yaf_Session::__sleep ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Session::__set
Yaf_Session::start
Yaf_Session


The start purpose

Yaf_Session::__sleep
Yaf_Session::__unset
Yaf_Session
PHP Manual

Yaf_Session::start

(Yaf >=1.0.0)

Yaf_Session::start — The start purpose

Descrierea

public void Yaf_Session::start ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Session::__sleep
Yaf_Session::__unset
Yaf_Session


The __unset purpose

Yaf_Session::start
Yaf_Session::valid
Yaf_Session
PHP Manual

Yaf_Session::__unset

(Yaf >=1.0.0)

Yaf_Session::__unset — The __unset purpose

Descrierea

public void Yaf_Session::__unset ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

Yaf_Session::start
Yaf_Session::valid
Yaf_Session


The valid purpose

Yaf_Session::__unset
Yaf_Session::__wakeup
Yaf_Session
PHP Manual

Yaf_Session::valid

(Yaf >=1.0.0)

Yaf_Session::valid — The valid purpose

Descrierea

public void Yaf_Session::valid ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Session::__unset
Yaf_Session::__wakeup
Yaf_Session


The __wakeup purpose

Yaf_Session::valid
Yaf_Exception
Yaf_Session
PHP Manual

Yaf_Session::__wakeup

(Yaf >=1.0.0)

Yaf_Session::__wakeup — The __wakeup purpose

Descrierea

private void Yaf_Session::__wakeup ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Session::valid
Yaf_Exception
Yaf_Session


The Yaf_Exception class

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Exception extends Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode */
public __construct ( void )
public void getPrevious ( void )
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Cuprins

  • 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

(Yaf >=1.0.0)

Yaf_Exception::__construct — The __construct purpose

Descrierea

public Yaf_Exception::__construct ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Exception
Yaf_Exception::getPrevious
Yaf_Exception


The getPrevious purpose

Yaf_Exception::__construct
Yaf_Exception_TypeError
Yaf_Exception
PHP Manual

Yaf_Exception::getPrevious

(Yaf >=1.0.0)

Yaf_Exception::getPrevious — The getPrevious purpose

Descrierea

public void Yaf_Exception::getPrevious ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Yaf_Exception::__construct
Yaf_Exception_TypeError
Yaf_Exception


The Yaf_Exception_TypeError class

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Exception_TypeError extends Yaf_Exception {
/* Proprieta?i */
/* Metode */
/* Metode mo?tenite */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception::getPrevious
Yaf_Exception_StartupError
Yaf


The Yaf_Exception_StartupError class

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Exception_StartupError extends Yaf_Exception {
/* Proprieta?i */
/* Metode */
/* Metode mo?tenite */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception_TypeError
Yaf_Exception_DispatchFailed
Yaf


The Yaf_Exception_DispatchFailed class

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Exception_DispatchFailed extends Yaf_Exception {
/* Proprieta?i */
/* Metode */
/* Metode mo?tenite */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception_StartupError
Yaf_Exception_RouterFailed
Yaf


The Yaf_Exception_RouterFailed class

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Exception_RouterFailed extends Yaf_Exception {
/* Proprieta?i */
/* Metode */
/* Metode mo?tenite */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception_DispatchFailed
Yaf_Exception_LoadFailed
Yaf


The Yaf_Exception_LoadFailed class

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Exception_LoadFailed extends Yaf_Exception {
/* Proprieta?i */
/* Metode */
/* Metode mo?tenite */
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

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Exception_LoadFailed_Module extends Yaf_Exception_LoadFailed {
/* Proprieta?i */
/* Metode */
/* Metode mo?tenite */
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

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Exception_LoadFailed_Controller extends Yaf_Exception_LoadFailed {
/* Proprieta?i */
/* Metode */
/* Metode mo?tenite */
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

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Exception_LoadFailed_Action extends Yaf_Exception_LoadFailed {
/* Proprieta?i */
/* Metode */
/* Metode mo?tenite */
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

(Yaf >=1.0.0)

Introducere

Sinopsisul clasei

Yaf_Exception_LoadFailed_View extends Yaf_Exception_LoadFailed {
/* Proprieta?i */
/* Metode */
/* Metode mo?tenite */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception_LoadFailed_Action
Taint
Yaf


Taint

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • More Details
    • Functions and Statements which will spread the tainted mark of a tainted string
    • Functions and statements which will check tainted string
    • Functions which untaint the tainted string
  • Func?ii taint
    • is_tainted — Checks whether a string is tainted
    • taint — Taint a string
    • untaint — Untaint strings
Yaf_Exception_LoadFailed_View
Introducere
Alte extensii de baza


Introducere

Taint is an extension, which is used for detecting XSS codes(tainted string). And also can be used to spot sql injection vulnerabilities, and shell inject, etc.

When taint is enabled, if you pass a tainted string (comes from $_GET, $_POST or $_COOKIE) to some functions, taint will warn you about that.

Example #1 Taint()example

<?php
$a = trim($_GET['a']);

$file_name = '/tmp' .  $a;
$output    = "Welcome, {$a} !!!";
$var       = "output";
$sql       = "Select *  from " . $a;
$sql      .= "ooxx";

echo $output;

print $$var;

include($file_name);

mysql_query($sql);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Warning: main() [function.echo]: Attempt to echo a string that might be tainted

Warning: main() [function.echo]: Attempt to print a string that might be tainted

Warning: include() [function.include]: File path contains data that might be tainted

Warning: mysql_query() [function.mysql-query]: SQL statement contains data that might be tainted
Taint
Instalarea / configurarea
Taint


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Taint


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/taint.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Taint Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
taint.enable | 0 | its PHP_INI_SYS value |
taint.error_level | E_WARNING | its PHP_INI_ALL value |

Iata o explica?ie pe scurt a directivelor de configurare.

taint.enable integer

Whether enable the taint.

taint.error_level integer

the error type which taint will report as when taint find a tainted string.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
More Details
Instalarea / configurarea


More Details

Cuprins

  • Functions and Statements which will spread the tainted mark of a tainted string
  • Functions and statements which will check tainted string
  • Functions which untaint the tainted string
Tipurile resurselor
Functions and Statements which will spread the tainted mark of a tainted string
Taint


Functions and Statements which will spread the tainted mark of a tainted string

Function/Statement | Since
= (assign) | 0.1.0
. (concat) | 0.1.0
"{$var}" (variable substitution) | 0.1.0
.= (assign concat) | 0.1.0
strval | 0.3.0
explode | 0.3.0
implode | 0.3.0
sprintf | 0.3.0
vsprintf | 0.3.0
trim | 0.4.0
rtrim | 0.4.0
ltrim | 0.4.0

More Details
Functions and statements which will check tainted string
More Details


Functions and statements which will check tainted string

Function/Statement | Since
Basic statments
eval | 0.1.0
include/include_once | 0.1.0
require/require_once | 0.1.0
Outputing Functions
echo | 0.1.0
print | 0.1.0
printf | 0.1.0
file_put_contents | 0.1.0
File System Functions
fopen | 0.2.0
opendir | 0.2.0
basename | 0.2.0
dirname | 0.2.0
file | 0.2.0
pathinfo | 0.2.0
Database relevant Functions
mysql_query | 0.2.0
mysqli_query/MySQLi::query | 0.2.0
sqlite_query/SqliteDataBase::query | 0.3.0
sqlite_single_query/SqliteDataBase::singleQuery | 0.3.0
oci_parse | 0.3.0
PDO::query | 0.3.0
PDO::prepare | 0.3.0
Command Line relevant Functions
system | 0.1.0
exec | 0.1.0
proc_open | 0.1.0
passthru | 0.1.0
shell_exec | 0.3.0

Functions and Statements which will spread the tainted mark of a tainted string
Functions which untaint the tainted string
More Details


Functions which untaint the tainted string

Function | Since
addslashes | 0.1.0
addcslashes | 0.1.0
htmlspecialchars | 0.1.0
htmlentities | 0.1.0
escapeshellcmd | 0.1.0
mysql_escape_string | 0.1.0
mysql_real_escape_string | 0.1.0
mysqli_escape_string/MySQLi::escape_string | 0.1.0
mysqli_real_escape_string/MySQLi::real_escape_string | 0.1.0
sqlite_escape_string/SqliteDataBase::escapeString | 0.3.0
PDO::quote | 0.3.0

Functions and statements which will check tainted string
Func?ii taint
More Details


Func?ii taint

Cuprins

  • is_tainted — Checks whether a string is tainted
  • taint — Taint a string
  • untaint — Untaint strings
Functions which untaint the tainted string
is_tainted
Taint


Checks whether a string is tainted

Func?ii taint
taint
Func?ii taint
PHP Manual

is_tainted

(PECL taint >=0.1.0)

is_tainted — Checks whether a string is tainted

Descrierea

bool is_tainted ( string $string )

Checks whether a string is tainted

Parametri

string

Valorile întoarse

Return TRUE if the string is tainted, FALSE otherwise.

Func?ii taint
taint
Func?ii taint


Taint a string

is_tainted
untaint
Func?ii taint
PHP Manual

taint

(PECL taint >=0.1.0)

taint — Taint a string

Descrierea

bool taint ( string &$string [, string $... ] )

Make a string tainted. This is used for testing purpose only.

Parametri

string

...

Valorile întoarse

Return TRUE if the transformation is done. Always return TRUE if the taint extension is not enabled.

is_tainted
untaint
Func?ii taint


Untaint strings

taint
Alte servicii
Func?ii taint
PHP Manual

untaint

(PECL taint >=0.1.0)

untaint — Untaint strings

Descrierea

bool untaint ( string &$string [, string $... ] )

Untaint strings

Parametri

string

...

Valorile întoarse

taint
Alte servicii
Func?ii taint


Alte servicii

  • chdb — Constant hash database
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • chdb — The chdb class
    • Func?ii chdb
  • cURL — Client URL Library
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii cURL
    • CURLFile — The CURLFile class
  • Event
    • Introducere
    • Instalarea / configurarea
    • Exemple
    • Event flags
    • About event persistence
    • Event callbacks
    • Constructing signal events
    • Event — The Event class
    • EventBase — The EventBase class
    • EventBuffer — The EventBuffer class
    • EventBufferEvent — The EventBufferEvent class
    • About buffer event callbacks
    • EventConfig — The EventConfig class
    • EventDnsBase — The EventDnsBase class
    • EventHttp — The EventHttp class
    • EventHttpConnection — The EventHttpConnection class
    • EventHttpRequest — The EventHttpRequest class
    • EventListener — The EventListener class
    • EventSslContext — The EventSslContext class
    • EventUtil — The EventUtil class
  • FAM — File Alteration Monitor
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii FAM
  • FTP
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii FTP
  • Gearman
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • GearmanClient — The GearmanClient class
    • GearmanJob — The GearmanJob class
    • GearmanTask — The GearmanTask class
    • GearmanWorker — The GearmanWorker class
    • GearmanException — The GearmanException class
  • Gopher — Net Gopher
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Gopher
  • Gupnp
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Gupnp
  • Hyperwave API
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Integration with Apache
    • Hyperwave API Func?ii
  • LDAP — Lightweight Directory Access Protocol
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Using the PHP LDAP calls
    • Exemple
    • Func?ii LDAP
  • Memcache
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Memcache — The Memcache class
    • Func?ii Memcache
  • Memcached
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Expiration Times
    • Callbacks
    • Sessions support
    • Memcached — The Memcached class
    • MemcachedException — The MemcachedException class
  • mqseries
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii mqseries
  • Network
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii de re?ea
  • RRD — RRDtool
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii RRD
    • RRDCreator — The RRDCreator class
    • RRDGraph — The RRDGraph class
    • RRDUpdater — The RRDUpdater class
  • SAM — Simple Asynchronous Messaging
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • SAM Func?ii
  • SNMP
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii SNMP
    • SNMP — The SNMP class
    • SNMPException — The SNMPException class
  • Sockets
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Socket Errors
    • Func?ii Socket
  • SSH2 — Secure Shell2
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii SSH2
  • Stomp — Stomp Client
    • Introducere
    • Instalarea / configurarea
    • Exemple
    • Func?ii Stomp
    • Stomp — The Stomp class
    • StompFrame — The StompFrame class
    • StompException — The StompException class
  • SVM — Support Vector Machine
    • Introducere
    • Instalarea / configurarea
    • Exemple
    • SVM — The SVM class
    • SVMModel — The SVMModel class
  • SVN — Subversion
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii SVN
  • TCP — TCP Wrappers
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii TCP
  • Varnish
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • VarnishAdmin — The VarnishAdmin class
    • VarnishStat — The VarnishStat class
    • VarnishLog — The VarnishLog class
  • YAZ
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii YAZ
  • YP/NIS
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii YP/NIS
  • 0MQ messaging — ZMQ
    • Introducere
    • Instalarea / configurarea
    • ZMQ — The ZMQ class
    • ZMQContext — The ZMQContext class
    • ZMQSocket — The ZMQSocket class
    • ZMQPoll — The ZMQPoll class
    • ZMQDevice — The ZMQDevice class
  • ZooKeeper
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • ZooKeeper — The ZooKeeper class
untaint
chdb
Informa?ii de referin?a despre func?ii


Constant hash database

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • chdb — The chdb class
    • chdb::__construct — Creates a chdb instance
    • chdb::get — Gets the value associated with a key
  • Func?ii chdb
    • chdb_create — Creates a chdb file
Alte servicii
Introducere
Alte servicii


Introducere

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
Instalarea / configurarea
chdb


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
chdb


Necesita?i

This module uses » cmph (version 0.9) for providing the » perfect hashing function.

cmph 0.9 is required to install this module.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » 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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
chdb


Exemple

Example #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.

Example #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;

?>

Exemplul de mai sus va afi?a ceva similar cu:

value1
value2
Constante predefinite
chdb
chdb


The chdb class

(PECL chdb >= 0.1.0)

Introducere

Represents a loaded chdb file.

Sinopsisul clasei

chdb {
/* Methods */
public __construct ( string $pathname )
public string get ( string $key )
}

Cuprins

  • chdb::__construct — Creates a chdb instance
  • chdb::get — Gets the value associated with a key
Exemple
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

Descrierea

public chdb::__construct ( string $pathname )

Loads a chdb file, by mapping it into memory.

Nota:

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.

Parametri

pathname

The name of the file to load.

Erori/Excep?ii

Throws an exception in case the chdb file hasn't been successfully loaded.

Nota:

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
Func?ii chdb
chdb
PHP Manual

chdb::get

(PECL chdb >= 0.1.0)

chdb::get — Gets the value associated with a key

Descrierea

public string chdb::get ( string $key )

Gets the value associated with a key from a chdb database.

Parametri

key

The key for which to get the value.

Valorile întoarse

Returns a string containing the value associated with the given key, or NULL if not found.

Exemple

Example #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;

?>

Exemplul de mai sus va afi?a ceva similar cu:

value1
value2
chdb::__construct
Func?ii chdb
chdb


Func?ii chdb

Cuprins

  • chdb_create — Creates a chdb file
chdb::get
chdb_create
chdb


Creates a chdb file

Func?ii chdb
cURL
Func?ii chdb
PHP Manual

chdb_create

(PECL chdb >= 0.1.0)

chdb_create — Creates a chdb file

Descrierea

bool chdb_create ( string $pathname , array $data )

chdb_create() creates a chdb file containing the specified key-value pairs.

Nota:

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws an exception in case the chdb file hasn't been successfully created.

Exemple

Example #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.

Func?ii chdb
cURL
Func?ii chdb


Client URL Library

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic curl example
  • Func?ii cURL
    • 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_escape — URL encodes the given string
    • curl_exec — Perform a cURL session
    • curl_file_create — Creeaza un obiect CURLFile
    • 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_multi_setopt — Set an option for the cURL multi handle
    • curl_multi_strerror — Return string describing error code
    • curl_pause — Pause and unpause a connection
    • curl_reset — Reset all options of a libcurl session handle
    • curl_setopt_array — Set multiple options for a cURL transfer
    • curl_setopt — Set an option for a cURL transfer
    • curl_share_close — Close a cURL share handle
    • curl_share_init — Initialize a cURL share handle
    • curl_share_setopt — Set an option for a cURL share handle.
    • curl_strerror — Return string describing the given error code
    • curl_unescape — Decodes the given URL encoded string
    • curl_version — Gets cURL version information
  • CURLFile — The CURLFile class
    • CURLFile::__construct — Create a CURLFile object
    • CURLFile::getFilename — Get file name
    • CURLFile::getMimeType — Get MIME type
    • CURLFile::getPostFilename — Get file name for POST
    • CURLFile::setMimeType — Set MIME type
    • CURLFile::setPostFilename — Set file name for POST
    • CURLFile::__wakeup — Unserialization handler
chdb_create
Introducere
Alte servicii


Introducere

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.

cURL
Instalarea / configurarea
cURL


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
cURL


Necesita?i

In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires libcurl version 7.10.5 or later.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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 . This feature was moved to PECL as of PHP 5.5.0.

Nota: 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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

cURL Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
curl.cainfo | NULL | PHP_INI_SYSTEM | Available since PHP 5.3.7.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

curl.cainfo string

A default value for the CURLOPT_CAINFO option. This is required to be an absolute path.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

This extension defines two resource types: a cURL handle and a cURL multi handle.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Descriptions and uses for these constants are described within the curl_setopt(), curl_multi_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
CURLFTP_CREATE_DIR (integer)
Available since PHP 7.0.7 and cURL 7.19.3
CURLFTP_CREATE_DIR_NONE (integer)
Available since PHP 7.0.7 and cURL 7.19.3
CURLFTP_CREATE_DIR_RETRY (integer)
Available since PHP 7.0.7 and cURL 7.19.3
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)
CURL_SSLVERSION_DEFAULT (integer)
CURL_SSLVERSION_TLSv1 (integer)
CURL_SSLVERSION_SSLv2 (integer)
CURL_SSLVERSION_SSLv3 (integer)
CURL_SSLVERSION_TLSv1_0 (integer)
Available since PHP 5.5.19 and 5.6.3
CURL_SSLVERSION_TLSv1_1 (integer)
Available since PHP 5.5.19 and 5.6.3
CURL_SSLVERSION_TLSv1_2 (integer)
Available since PHP 5.5.19 and 5.6.3
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)
Removed in PHP 5.6.0.
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)
Available as of cURL 7.10.
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_NEGOTIATE (integer)
Available since PHP 7.0.7 and cURL 7.38.0.
CURLAUTH_NTLM (integer)
CURLAUTH_NTLM_WB (integer)
Available since PHP 7.0.7 and cURL 7.22.0
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
CURLOPT_HEADEROPT (integer)
Available since PHP 7.0.7 and cURL 7.37.0
CURLOPT_PROXYHEADER (integer)
Available since PHP 7.0.7 and cURL 7.37.0
CURLCLOSEPOLICY_LEAST_RECENTLY_USED (integer)
Removed in PHP 5.6.0.
CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)
Removed in PHP 5.6.0.
CURLCLOSEPOLICY_SLOWEST (integer)
Removed in PHP 5.6.0.
CURLCLOSEPOLICY_CALLBACK (integer)
Removed in PHP 5.6.0.
CURLCLOSEPOLICY_OLDEST (integer)
Removed in PHP 5.6.0.
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)
CURLINFO_REDIRECT_URL (string)
Available since PHP 5.3.7
CURLINFO_PRIMARY_IP (string)
Available since PHP 5.4.7
CURLINFO_PRIMARY_PORT (integer)
Available since PHP 5.4.7
CURLINFO_LOCAL_IP (string)
Available since PHP 5.4.7
CURLINFO_LOCAL_PORT (integer)
Available since PHP 5.4.7
CURL_PUSH_OK (integer)
Available since PHP 7.1.0 and cURL 7.44.0
CURL_PUSH_DENY (integer)
Available since PHP 7.1.0 and cURL 7.44.0
CURL_REDIR_POST_301 (integer)
Available since PHP 7.0.7 and cURL 7.18.2
CURL_REDIR_POST_302 (integer)
Available since PHP 7.0.7 and cURL 7.18.2
CURL_REDIR_POST_303 (integer)
Available since PHP 7.0.7 and cURL 7.25.1
CURL_REDIR_POST_ALL (integer)
Available since PHP 7.0.7 and cURL 7.18.2
CURL_TIMECOND_IFMODSINCE (integer)
CURL_TIMECOND_IFUNMODSINCE (integer)
CURL_TIMECOND_LASTMOD (integer)
CURL_VERSION_IPV6 (integer)
CURL_VERSION_KERBEROS4 (integer)
CURL_VERSION_KERBEROS5 (integer)
Available since PHP 7.0.7 and cURL 7.40.0
CURL_VERSION_HTTP2 (integer)
Available since PHP 5.5.24 and 5.6.8 and cURL 7.33.0
CURL_VERSION_PSL (integer)
Available since PHP 7.0.7 and cURL 7.47.0
CURL_VERSION_SSL (integer)
CURL_VERSION_UNIX_SOCKETS (integer)
Available since PHP 7.0.7 and cURL 7.40.0
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)
CURLE_SSH (integer)
Available since PHP 5.3.0 and cURL 7.16.1.
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)
Available since cURL 7.10.
CURLPROXY_HTTP_1_0 (integer)
Available since PHP 7.0.7 and cURL 7.19.3
CURLPROXY_SOCKS4 (integer)
Available since PHP 5.2.10 and cURL 7.10.
CURLPROXY_SOCKS5 (integer)
Available since cURL 7.10.
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)
CURL_HTTP_VERSION_2 (integer)
Available since PHP 7.0.7 and cURL 7.43.0
CURL_HTTP_VERSION_2TLS (integer)
Available since PHP 7.0.7 and cURL 7.47.0
CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE (integer)
Available since PHP 7.0.7 and cURL 7.49.0
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)
CURLOPT_KEYPASSWD (integer)
CURLOPT_SSH_AUTH_TYPES (integer)
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 (integer)
CURLOPT_SSH_PRIVATE_KEYFILE (integer)
CURLOPT_SSH_PUBLIC_KEYFILE (integer)
CURLOPT_SSL_OPTIONS (integer)
Available since PHP 5.5.0 and cURL 7.25.0
CURLSSLOPT_ALLOW_BEAST (integer)
Available since PHP 5.5.0 and cURL 7.25.0
CURLSSLOPT_NO_REVOKE (integer)
Available since PHP 7.0.7 and cURL 7.44.0
CURLOPT_USERNAME (integer)
Available since PHP 5.5.0 and cURL 7.19.1
CURLOPT_SASL_IR (integer)
Available since PHP 7.0.7 and cURL 7.31.0
CURLOPT_DNS_INTERFACE (integer)
Available since PHP 7.0.7 and cURL 7.33.0
CURLOPT_DNS_LOCAL_IP4 (integer)
Available since PHP 7.0.7 and cURL 7.33.0
CURLOPT_DNS_LOCAL_IP6 (integer)
Available since PHP 7.0.7 and cURL 7.33.0
CURLOPT_XOAUTH2_BEARER (integer)
Available since PHP 7.0.7 and cURL 7.33.0
CURLOPT_LOGIN_OPTIONS (integer)
Available since PHP 7.0.7 and cURL 7.34.0
CURLOPT_EXPECT_100_TIMEOUT_MS (integer)
Available since PHP 7.0.7 and cURL 7.36.0
CURLOPT_SSL_ENABLE_ALPN (integer)
Available since PHP 7.0.7 and cURL 7.36.0
CURLOPT_SSL_ENABLE_NPN (integer)
Available since PHP 7.0.7 and cURL 7.36.0
CURLOPT_PINNEDPUBLICKEY (integer)
Available since PHP 7.0.7 and cURL 7.39.0
CURLOPT_UNIX_SOCKET_PATH (integer)
Available since PHP 7.0.7 and cURL 7.40.0
CURLOPT_SSL_VERIFYSTATUS (integer)
Available since PHP 7.0.7 and cURL 7.41.0
CURLOPT_PATH_AS_IS (integer)
Available since PHP 7.0.7 and cURL 7.42.0
CURLOPT_SSL_FALSESTART (integer)
Available since PHP 7.0.7 and cURL 7.42.0
CURLOPT_PIPEWAIT (integer)
Available since PHP 7.0.7 and cURL 7.43.0
CURLOPT_PROXY_SERVICE_NAME (integer)
Available since PHP 7.0.7 and cURL 7.43.0
CURLOPT_SERVICE_NAME (integer)
Available since PHP 7.0.7 and cURL 7.43.0
CURLOPT_DEFAULT_PROTOCOL (integer)
Available since PHP 7.0.7 and cURL 7.45.0
CURLOPT_STREAM_WEIGHT (integer)
Available since PHP 7.0.7 and cURL 7.46.0
CURLOPT_TFTP_NO_OPTIONS (integer)
Available since PHP 7.0.7 and cURL 7.48.0
CURLOPT_CONNECT_TO (integer)
Available since PHP 7.0.7 and cURL 7.49.0
CURLOPT_TCP_FASTOPEN (integer)
Available since PHP 7.0.7 and cURL 7.49.0
CURLMOPT_PIPELINING (integer)
Available since PHP 5.5.0 and cURL 7.16.0.
CURLMOPT_MAXCONNECTS (integer)
Available since PHP 5.5.0 and cURL 7.16.3.
CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE (integer)
Available since PHP 7.0.7 and cURL 7.30.0
CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE (integer)
Available since PHP 7.0.7 and cURL 7.30.0
CURLMOPT_MAX_HOST_CONNECTIONS (integer)
Available since PHP 7.0.7 and cURL 7.30.0
CURLMOPT_MAX_PIPELINE_LENGTH (integer)
Available since PHP 7.0.7 and cURL 7.30.0
CURLMOPT_MAX_TOTAL_CONNECTIONS (integer)
Available since PHP 7.0.7 and cURL 7.30.0
CURLMOPT_PUSHFUNCTION (integer)
Available since PHP 7.1.0 and cURL 7.44.0
CURLSSH_AUTH_AGENT (integer)
Available since PHP 7.0.7 and cURL 7.28.0
CURLSSH_AUTH_ANY (integer)
CURLSSH_AUTH_DEFAULT (integer)
CURLSSH_AUTH_HOST (integer)
CURLSSH_AUTH_KEYBOARD (integer)
CURLSSH_AUTH_NONE (integer)
CURLSSH_AUTH_PASSWORD (integer)
CURLSSH_AUTH_PUBLICKEY (integer)
CURL_WRAPPERS_ENABLED (integer)
Defined if PHP was configured with --with-curlwrappers . Moved to PECL in PHP 5.5.0.
CURLPAUSE_ALL (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_CONT (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_RECV (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_RECV_CONT (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_SEND (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_SEND_CONT (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPIPE_NOTHING (integer)
Available since PHP 7.0.0 and cURL 7.43.0.
CURLPIPE_HTTP1 (integer)
Available since PHP 7.0.0 and cURL 7.43.0.
CURLPIPE_MULTIPLEX (integer)
Available since PHP 7.0.0 and cURL 7.43.0.
CURLPROXY_SOCKS4A (integer)
Available since PHP 5.5.23 and PHP 5.6.7 and cURL 7.18.0.
CURLPROXY_SOCKS5_HOSTNAME (integer)
Available since PHP 5.5.23 and PHP 5.6.7 and cURL 7.18.0.
CURLHEADER_SEPARATE (integer)
Available since PHP 7.0.7 and cURL 7.37.0.
CURLHEADER_UNIFIED (integer)
Available since PHP 7.0.7 and cURL 7.37.0.
CURLPROTO_SMB (integer)
Available since PHP 7.0.7 and cURL 7.40.0.
CURLPROTO_SMBS (integer)
Available since PHP 7.0.7 and cURL 7.40.0.
Tipurile resurselor
Exemple
cURL


Exemple

Cuprins

  • Basic curl example
Constante predefinite
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:

Example #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);
?>

Exemple
Func?ii cURL
Exemple


Func?ii cURL

Cuprins

  • 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_escape — URL encodes the given string
  • curl_exec — Perform a cURL session
  • curl_file_create — Creeaza un obiect CURLFile
  • 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_multi_setopt — Set an option for the cURL multi handle
  • curl_multi_strerror — Return string describing error code
  • curl_pause — Pause and unpause a connection
  • curl_reset — Reset all options of a libcurl session handle
  • curl_setopt_array — Set multiple options for a cURL transfer
  • curl_setopt — Set an option for a cURL transfer
  • curl_share_close — Close a cURL share handle
  • curl_share_init — Initialize a cURL share handle
  • curl_share_setopt — Set an option for a cURL share handle.
  • curl_strerror — Return string describing the given error code
  • curl_unescape — Decodes the given URL encoded string
  • curl_version — Gets cURL version information
Basic curl example
curl_close
cURL


Close a cURL session

Func?ii cURL
curl_copy_handle
Func?ii cURL
PHP Manual

curl_close

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

curl_close — Close a cURL session

Descrierea

void curl_close ( resource $ch )

Closes a cURL session and frees all resources. The cURL handle, ch, is also deleted.

Parametri

ch

Un handle cURL întors de curl_init().

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);
?>

A se vedea ?i

  • curl_init() - Initialize a cURL session
  • curl_multi_close() - Close a set of cURL handles

Func?ii cURL
curl_copy_handle
Func?ii cURL


Copy a cURL handle along with all of its preferences

curl_close
curl_errno
Func?ii cURL
PHP Manual

curl_copy_handle

(PHP 5, PHP 7)

curl_copy_handle — Copy a cURL handle along with all of its preferences

Descrierea

resource curl_copy_handle ( resource $ch )

Copies a cURL handle keeping the same preferences.

Parametri

ch

Un handle cURL întors de curl_init().

Valorile întoarse

Returns a new cURL handle.

Exemple

Example #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
Func?ii cURL


Return the last error number

curl_copy_handle
curl_error
Func?ii cURL
PHP Manual

curl_errno

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

curl_errno — Return the last error number

Descrierea

int curl_errno ( resource $ch )

Returns the error number for the last cURL operation.

Parametri

ch

Un handle cURL întors de curl_init().

Valorile întoarse

Returns the error number or 0 (zero) if no error occurred.

Exemple

Example #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 occurred
if(curl_errno($ch))
{
    echo 'Curl error: ' . curl_error($ch);
}

// Close handle
curl_close($ch);
?>

A se vedea ?i

  • curl_error() - Return a string containing the last error for the current session
  • » Curl error codes

curl_copy_handle
curl_error
Func?ii cURL


Return a string containing the last error for the current session

curl_errno
curl_escape
Func?ii cURL
PHP Manual

curl_error

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

curl_error — Return a string containing the last error for the current session

Descrierea

string curl_error ( resource $ch )

Returns a clear text error message for the last cURL operation.

Parametri

ch

Un handle cURL întors de curl_init().

Valorile întoarse

Returns the error message or '' (the empty string) if no error occurred.

Exemple

Example #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);
?>

A se vedea ?i

  • curl_errno() - Return the last error number
  • » Curl error codes

curl_errno
curl_escape
Func?ii cURL


URL encodes the given string

curl_error
curl_exec
Func?ii cURL
PHP Manual

curl_escape

(PHP 5 >= 5.5.0, PHP 7)

curl_escape — URL encodes the given string

Descrierea

string curl_escape ( resource $ch , string $str )

This function URL encodes the given string according to » RFC 3986.

Parametri

ch

Un handle cURL întors de curl_init().

str

The string to be encoded.

Valorile întoarse

Returns escaped string sau FALSE în cazul e?ecului.

Exemple

Example #1 curl_escape() example

<?php
// Create a curl handle
$ch = curl_init();

// Escape a string used as a GET parameter
$location = curl_escape($ch, 'Hofbräuhaus / München');
// Result: Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen

// Compose an URL with the escaped string
$url = "http://example.com/add_location.php?location={$location}";
// Result: http://example.com/add_location.php?location=Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen

// Send HTTP request and close the handle
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
?>

A se vedea ?i

  • curl_unescape() - Decodes the given URL encoded string
  • urlencode() - URL-encodes string
  • rawurlencode() - URL-encode according to RFC 3986
  • » RFC 3986

curl_error
curl_exec
Func?ii cURL


Perform a cURL session

curl_escape
curl_file_create
Func?ii cURL
PHP Manual

curl_exec

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

curl_exec — Perform a cURL session

Descrierea

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.

Parametri

ch

Un handle cURL întors de curl_init().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Exemple

Example #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);
?>

A se vedea ?i

  • curl_multi_exec() - Run the sub-connections of the current cURL handle

curl_escape
curl_file_create
Func?ii cURL


Creeaza un obiect CURLFile

curl_exec
curl_getinfo
Func?ii cURL
PHP Manual

curl_file_create

(PHP 5 >= 5.5.0, PHP 7)

curl_file_create — Creeaza un obiect CURLFile

Descrierea

Aceasta func?ie este pseudonim pentru: CURLFile::__construct()

curl_exec
curl_getinfo
Func?ii cURL


Get information regarding a specific transfer

curl_file_create
curl_init
Func?ii cURL
PHP Manual

curl_getinfo

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

curl_getinfo — Get information regarding a specific transfer

Descrierea

mixed curl_getinfo ( resource $ch [, int $opt ] )

Gets information about the last transfer.

Parametri

ch

Un handle cURL întors de 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, with the CURLOPT_FILETIME enabled; 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_COUNT - Number of redirects, with the CURLOPT_FOLLOWLOCATION option enabled
  • CURLINFO_REDIRECT_TIME - Time in seconds of all redirection steps before final transaction was started, with the CURLOPT_FOLLOWLOCATION option enabled
  • CURLINFO_REDIRECT_URL - With the CURLOPT_FOLLOWLOCATION option disabled: redirect URL found in the last transaction, that should be requested manually next. With the CURLOPT_FOLLOWLOCATION option enabled: this is empty. The redirect URL in this case is available in CURLINFO_EFFECTIVE_URL
  • CURLINFO_PRIMARY_IP - IP address of the most recent connection
  • CURLINFO_PRIMARY_PORT - Destination port of the most recent connection
  • CURLINFO_LOCAL_IP - Local (source) IP address of the most recent connection
  • CURLINFO_LOCAL_PORT - Local (source) port of the most recent connection
  • 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
  • CURLINFO_PRIVATE - Private data associated with this cURL handle, previously set with the CURLOPT_PRIVATE option of curl_setopt()
  • CURLINFO_RESPONSE_CODE - The last response code
  • CURLINFO_HTTP_CONNECTCODE - The CONNECT response code
  • CURLINFO_HTTPAUTH_AVAIL - Bitmask indicating the authentication method(s) available according to the previous response
  • CURLINFO_PROXYAUTH_AVAIL - Bitmask indicating the proxy authentication method(s) available according to the previous response
  • CURLINFO_OS_ERRNO - Errno from a connect failure. The number is OS and system specific.
  • CURLINFO_NUM_CONNECTS - Number of connections curl had to create to achieve the previous transfer
  • CURLINFO_SSL_ENGINES - OpenSSL crypto-engines supported
  • CURLINFO_COOKIELIST - All known cookies
  • CURLINFO_FTP_ENTRY_PATH - Entry path in FTP server
  • CURLINFO_APPCONNECT_TIME - Time in seconds it took from the start until the SSL/SSH connect/handshake to the remote host was completed
  • CURLINFO_CERTINFO - TLS certificate chain
  • CURLINFO_CONDITION_UNMET - Info on unmet time conditional
  • CURLINFO_RTSP_CLIENT_CSEQ - Next RTSP client CSeq
  • CURLINFO_RTSP_CSEQ_RECV - Recently received CSeq
  • CURLINFO_RTSP_SERVER_CSEQ - Next RTSP server CSeq
  • CURLINFO_RTSP_SESSION_ID - RTSP session ID

Valorile întoarse

If opt is given, returns its value. 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"
  • "primary_ip"
  • "primary_port"
  • "local_ip"
  • "local_port"
  • "redirect_url"
  • "request_header" (This is only set if the CURLINFO_HEADER_OUT is set by a previous call to curl_setopt())
Note that private data is not included in the associative array and must be retrieved individually with the CURLINFO_PRIVATE option.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | Introduced CURLINFO_RESPONSE_CODE, CURLINFO_HTTP_CONNECTCODE, CURLINFO_HTTPAUTH_AVAIL, CURLINFO_PROXYAUTH_AVAIL, CURLINFO_OS_ERRNO, CURLINFO_NUM_CONNECTS, CURLINFO_SSL_ENGINES, CURLINFO_COOKIELIST, CURLINFO_FTP_ENTRY_PATH, CURLINFO_APPCONNECT_TIME, CURLINFO_CONDITION_UNMET, CURLINFO_RTSP_CLIENT_CSEQ, CURLINFO_RTSP_CSEQ_RECV, CURLINFO_RTSP_SERVER_CSEQ and CURLINFO_RTSP_SESSION_ID.
5.4.7 | Introduced CURLINFO_PRIMARY_IP, CURLINFO_PRIMARY_PORT, CURLINFO_LOCAL_IP and CURLINFO_LOCAL_PORT.
5.3.7 | Introduced CURLINFO_REDIRECT_URL.
5.3.0 | Introduced CURLINFO_CERTINFO.
5.2.4 | Introduced CURLINFO_PRIVATE.
5.1.3 | Introduced CURLINFO_HEADER_OUT.

Exemple

Example #1 curl_getinfo() example

<?php
// Create a cURL handle
$ch = curl_init('http://www.example.com/');

// Execute
curl_exec($ch);

// Check if any error occurred
if (!curl_errno($ch)) {
  $info = curl_getinfo($ch);
  echo 'Took ', $info['total_time'], ' seconds to send a request to ', $info['url'], "\n";
}

// Close handle
curl_close($ch);
?>

Example #2 curl_getinfo() example with opt parameter

<?php
// Create a cURL handle
$ch = curl_init('http://www.example.com/');

// Execute
curl_exec($ch);

// Check HTTP status code
if (!curl_errno($ch)) {
  switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
    case 200:  # OK
      break;
    default:
      echo 'Unexpected HTTP code: ', $http_code, "\n";
  }
}

// Close handle
curl_close($ch);
?>

Note

Nota:

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_file_create
curl_init
Func?ii cURL


Initialize a cURL session

curl_getinfo
curl_multi_add_handle
Func?ii cURL
PHP Manual

curl_init

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

curl_init — Initialize a cURL session

Descrierea

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.

Parametri

url

If provided, the CURLOPT_URL option will be set to its value. You can manually set this using the curl_setopt() function.

Nota:

The file protocol is disabled by cURL if open_basedir is set.

Valorile întoarse

Returns a cURL handle on success, FALSE on errors.

Exemple

Example #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);
?>

A se vedea ?i

  • curl_close() - Close a cURL session
  • curl_multi_init() - Returns a new cURL multi handle

curl_getinfo
curl_multi_add_handle
Func?ii cURL


Add a normal cURL handle to a cURL multi handle

curl_init
curl_multi_close
Func?ii cURL
PHP Manual

curl_multi_add_handle

(PHP 5, PHP 7)

curl_multi_add_handle — Add a normal cURL handle to a cURL multi handle

Descrierea

int curl_multi_add_handle ( resource $mh , resource $ch )

Adds the ch handle to the multi handle mh

Parametri

mh

Un multi-handle cURL întors de curl_multi_init().

ch

Un handle cURL întors de curl_init().

Valorile întoarse

Returns 0 on success, or one of the CURLM_XXX errors code.

Exemple

Example #1 curl_multi_add_handle() example

This example will create two cURL handles, add them to a multi handle, and process them asynchronously.

<?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);
?>

A se vedea ?i

  • 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
Func?ii cURL


Close a set of cURL handles

curl_multi_add_handle
curl_multi_exec
Func?ii cURL
PHP Manual

curl_multi_close

(PHP 5, PHP 7)

curl_multi_close — Close a set of cURL handles

Descrierea

void curl_multi_close ( resource $mh )

Closes a set of cURL handles.

Parametri

mh

Un multi-handle cURL întors de curl_multi_init().

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 curl_multi_close() example

This example will create two cURL handles, add them to a multi handle, and process them asynchronously.

<?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_close($ch1);
curl_multi_remove_handle($mh, $ch2);
curl_close($ch2);
curl_multi_close($mh);

?>

A se vedea ?i

  • curl_multi_init() - Returns a new cURL multi handle
  • curl_close() - Close a cURL session

curl_multi_add_handle
curl_multi_exec
Func?ii cURL


Run the sub-connections of the current cURL handle

curl_multi_close
curl_multi_getcontent
Func?ii cURL
PHP Manual

curl_multi_exec

(PHP 5, PHP 7)

curl_multi_exec — Run the sub-connections of the current cURL handle

Descrierea

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.

Parametri

mh

Un multi-handle cURL întors de curl_multi_init().

still_running

A reference to a flag to tell whether the operations are still running.

Valorile întoarse

A cURL code defined in the cURL Predefined Constants.

Nota:

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.

Exemple

Example #1 curl_multi_exec() example

This example will create two cURL handles, add them to a multi handle, and process them asynchronously.

<?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);

?>

A se vedea ?i

  • 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
Func?ii cURL


Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

curl_multi_exec
curl_multi_info_read
Func?ii cURL
PHP Manual

curl_multi_getcontent

(PHP 5, PHP 7)

curl_multi_getcontent — Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

Descrierea

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.

Parametri

ch

Un handle cURL întors de curl_init().

Valorile întoarse

Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set.

A se vedea ?i

  • curl_multi_init() - Returns a new cURL multi handle

curl_multi_exec
curl_multi_info_read
Func?ii cURL


Get information about the current transfers

curl_multi_getcontent
curl_multi_init
Func?ii cURL
PHP Manual

curl_multi_info_read

(PHP 5, PHP 7)

curl_multi_info_read — Get information about the current transfers

Descrierea

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.

Avertizare

The data the returned resource points to will not survive calling curl_multi_remove_handle().

Parametri

mh

Un multi-handle cURL întors de curl_multi_init().

msgs_in_queue

Number of messages that are still in the queue

Valorile întoarse

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.

Exemple

Example #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));

?>

Exemplul de mai sus va afi?a ceva similar cu:

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)

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | msgs_in_queue was added.

A se vedea ?i

  • curl_multi_init() - Returns a new cURL multi handle

curl_multi_getcontent
curl_multi_init
Func?ii cURL


Returns a new cURL multi handle

curl_multi_info_read
curl_multi_remove_handle
Func?ii cURL
PHP Manual

curl_multi_init

(PHP 5, PHP 7)

curl_multi_init — Returns a new cURL multi handle

Descrierea

resource curl_multi_init ( void )

Allows the processing of multiple cURL handles asynchronously.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a cURL multi handle resource on success, FALSE on failure.

Exemple

Example #1 curl_multi_init() example

This example will create two cURL handles, add them to a multi handle, and process them asynchronously.

<?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);

?>

A se vedea ?i

  • curl_init() - Initialize a cURL session
  • curl_multi_close() - Close a set of cURL handles

curl_multi_info_read
curl_multi_remove_handle
Func?ii cURL


Remove a multi handle from a set of cURL handles

curl_multi_init
curl_multi_select
Func?ii cURL
PHP Manual

curl_multi_remove_handle

(PHP 5, PHP 7)

curl_multi_remove_handle — Remove a multi handle from a set of cURL handles

Descrierea

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.

Parametri

mh

Un multi-handle cURL întors de curl_multi_init().

ch

Un handle cURL întors de curl_init().

Valorile întoarse

Returns 0 on success, or one of the CURLM_XXX error codes.

A se vedea ?i

  • 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
Func?ii cURL


Wait for activity on any curl_multi connection

curl_multi_remove_handle
curl_multi_setopt
Func?ii cURL
PHP Manual

curl_multi_select

(PHP 5, PHP 7)

curl_multi_select — Wait for activity on any curl_multi connection

Descrierea

int curl_multi_select ( resource $mh [, float $timeout = 1.0 ] )

Blocks until there is activity on any of the curl_multi connections.

Parametri

mh

Un multi-handle cURL întors de curl_multi_init().

timeout

Time, in seconds, to wait for a response.

Valorile întoarse

On success, returns the number of descriptors contained in the descriptor sets. This may be 0 if there was no activity on any of the descriptors. On failure, this function will return -1 on a select failure (from the underlying select system call).

A se vedea ?i

  • curl_multi_init() - Returns a new cURL multi handle

curl_multi_remove_handle
curl_multi_setopt
Func?ii cURL


Set an option for the cURL multi handle

curl_multi_select
curl_multi_strerror
Func?ii cURL
PHP Manual

curl_multi_setopt

(PHP 5 >= 5.5.0, PHP 7)

curl_multi_setopt — Set an option for the cURL multi handle

Descrierea

bool curl_multi_setopt ( resource $mh , int $option , mixed $value )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

mh

option

One of the CURLMOPT_* constants.

value

The value to be set on option.

value should be an int for the following values of the option parameter:

Option | Set value to
CURLMOPT_PIPELINING | Pass 1 to enable or 0 to disable. Enabling pipelining on a multi handle will make it attempt to perform HTTP Pipelining as far as possible for transfers using this handle. This means that if you add a second request that can use an already existing connection, the second request will be "piped" on the same connection. As of cURL 7.43.0 you can also pass 2 to try to multiplex the new transfer over an existing HTTP/2 connection if possible. Instead of integer literals, you can also use the CURLPIPE_* constants if available.
CURLMOPT_MAXCONNECTS | Pass a number that will be used as the maximum amount of simultaneously open connections that libcurl may cache. By default the size will be enlarged to fit four times the number of handles added via curl_multi_add_handle(). When the cache is full, curl closes the oldest one in the cache to prevent the number of open connections from increasing.
CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE | Pass a number that specifies the chunk length threshold for pipelining in bytes.
CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE | Pass a number that specifies the size threshold for pipelining penalty in bytes.
CURLMOPT_MAX_HOST_CONNECTIONS | Pass a number that specifies the maximum number of connections to a single host.
CURLMOPT_MAX_PIPELINE_LENGTH | Pass a number that specifies the maximum number of requests in a pipeline.
CURLMOPT_MAX_TOTAL_CONNECTIONS | Pass a number that specifies the maximum number of simultaneously open connections.
CURLMOPT_PUSHFUNCTION Pass a callable that will be registered to handle server pushes and should have the following signature:
int pushfunction ( resource $parent_ch , resource $pushed_ch , array $headers )
parent_ch

The parent cURL handle (the request the client made).

pushed_ch

A new cURL handle for the pushed request.

headers

The push promise headers.

The push function is supposed to return either CURL_PUSH_OK if it can handle the push, or CURL_PUSH_DENY to reject it.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Introduced CURLMOPT_PUSHFUNCTION.
7.0.7 | Introduced CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLMOPT_MAX_HOST_CONNECTIONS, CURLMOPT_MAX_PIPELINE_LENGTH and CURLMOPT_MAX_TOTAL_CONNECTIONS.

curl_multi_select
curl_multi_strerror
Func?ii cURL


Return string describing error code

curl_multi_setopt
curl_pause
Func?ii cURL
PHP Manual

curl_multi_strerror

(PHP 5 >= 5.5.0, PHP 7)

curl_multi_strerror — Return string describing error code

Descrierea

string curl_multi_strerror ( int $errornum )

Returns a text error message describing the given CURLM error code.

Parametri

errornum

One of the » CURLM error codes constants.

Valorile întoarse

Returns error string for valid error code, NULL otherwise.

Exemple

Example #1 curl_multi_strerror() example

<?php
// Create cURL handles
$ch1 = curl_init("http://example.com"/);
$ch2 = curl_init("http://php.net/");

// Create a cURL multi handle
$mh = curl_multi_init();

// Add the handles to the multi handle
curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);

// Execute the multi handle
do {
    $status = curl_multi_exec($mh, $active);
    // Check for errors
    if($status > 0) {
        // Display error message
        echo "ERROR!\n " . curl_multi_strerror($status);
    }
} while ($status === CURLM_CALL_MULTI_PERFORM || $active);
?>

A se vedea ?i

  • curl_strerror() - Return string describing the given error code
  • » cURL error codes

curl_multi_setopt
curl_pause
Func?ii cURL


Pause and unpause a connection

curl_multi_strerror
curl_reset
Func?ii cURL
PHP Manual

curl_pause

(PHP 5 >= 5.5.0, PHP 7)

curl_pause — Pause and unpause a connection

Descrierea

int curl_pause ( resource $ch , int $bitmask )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

ch

Un handle cURL întors de curl_init().

bitmask

One of CURLPAUSE_* constants.

Valorile întoarse

Returns an error code (CURLE_OK for no error).

curl_multi_strerror
curl_reset
Func?ii cURL


Reset all options of a libcurl session handle

curl_pause
curl_setopt_array
Func?ii cURL
PHP Manual

curl_reset

(PHP 5 >= 5.5.0, PHP 7)

curl_reset — Reset all options of a libcurl session handle

Descrierea

void curl_reset ( resource $ch )

This function re-initializes all options set on the given cURL handle to the default values.

Parametri

ch

Un handle cURL întors de curl_init().

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 curl_reset() example

<?php
// Create a curl handle
$ch = curl_init();

// Set CURLOPT_USERAGENT option
curl_setopt($ch, CURLOPT_USERAGENT, "My test user-agent");

// Reset all previously set options
curl_reset($ch);

// Send HTTP request
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
curl_exec($ch); // the previously set user-agent will be not sent, it has been reset by curl_reset

// Close the handle
curl_close($ch);
?>

Note

Nota:

curl_reset() also resets the URL given as the curl_init() parameter.

A se vedea ?i

  • curl_setopt() - Set an option for a cURL transfer

curl_pause
curl_setopt_array
Func?ii cURL


Set multiple options for a cURL transfer

curl_reset
curl_setopt
Func?ii cURL
PHP Manual

curl_setopt_array

(PHP 5 >= 5.1.3, PHP 7)

curl_setopt_array — Set multiple options for a cURL transfer

Descrierea

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().

Parametri

ch

Un handle cURL întors de 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.

Valorile întoarse

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.

Exemple

Example #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:

Example #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;
   }
}
?>

Note

Nota:

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.

A se vedea ?i

  • curl_setopt() - Set an option for a cURL transfer

curl_reset
curl_setopt
Func?ii cURL


Set an option for a cURL transfer

curl_setopt_array
curl_share_close
Func?ii cURL
PHP Manual

curl_setopt

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

curl_setopt — Set an option for a cURL transfer

Descrierea

bool curl_setopt ( resource $ch , int $option , mixed $value )

Sets an option on the given cURL session handle.

Parametri

ch

Un handle cURL întors de 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. | From PHP 5.1.3, this option has no effect: the raw output will always be returned 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. | Added in cURL 7.19.1. Available since PHP 5.3.2. Requires CURLOPT_VERBOSE to be on to have an effect.
CURLOPT_CONNECT_ONLY | TRUE tells the library to perform all the required proxy authentication and connection setup, but no data transfer. This option is implemented for HTTP, SMTP and POP3. | Added in 7.15.2. Available since PHP 5.5.0.
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 verbosely 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_SSL_FALSESTART | TRUE to enable TLS false start. | Added in cURL 7.42.0. Available since PHP 7.0.7.
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_TCP_NODELAY | TRUE to disable TCP's Nagle algorithm, which tries to minimize the number of small packets on the network. | Available since PHP 5.2.1 for versions compiled with libcurl 7.11.2 or greater.
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. | Removed in cURL 7.15.5 (You can use CURLOPT_RETURNTRANSFER instead)
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.

Nota:

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_PATH_AS_IS | TRUE to not handle dot dot sequences. | Added in cURL 7.42.0. Available since PHP 7.0.7.
CURLOPT_PIPEWAIT | TRUE to wait for pipelining/multiplexing. | Added in cURL 7.43.0. Available since PHP 7.0.7.
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_SAFE_UPLOAD | TRUE to disable support for the @ prefix for uploading files in CURLOPT_POSTFIELDS, which means that values starting with @ can be safely passed as fields. CURLFile may be used for uploads instead. | Added in PHP 5.5.0 with FALSE as the default value. PHP 5.6.0 changes the default value to TRUE. PHP 7 removes this option; the CURLFile interface must be used to upload files.
CURLOPT_SASL_IR | TRUE to enable sending the initial response in the first packet. | Added in cURL 7.31.10. Available since PHP 7.0.7.
CURLOPT_SSL_ENABLE_ALPN | FALSE to disable ALPN in the SSL handshake (if the SSL backend libcurl is built to use supports it), which can be used to negotiate http2. | Added in cURL 7.36.0. Available since PHP 7.0.7.
CURLOPT_SSL_ENABLE_NPN | FALSE to disable NPN in the SSL handshake (if the SSL backend libcurl is built to use supports it), which can be used to negotiate http2. | Added in cURL 7.36.0. Available since PHP 7.0.7.
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_SSL_VERIFYSTATUS | TRUE to verify the certificate's status. | Added in cURL 7.41.0. Available since PHP 7.0.7.
CURLOPT_TCP_FASTOPEN | TRUE to enable TCP Fast Open. | Added in cURL 7.49.0. Available since PHP 7.0.7.
CURLOPT_TFTP_NO_OPTIONS | TRUE to not send TFTP options requests. | Added in cURL 7.48.0. Available since PHP 7.0.7.
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 One of the CURLCLOSEPOLICY_* values.

Nota:

This option is deprecated, as it was never implemented in cURL and never had any effect.

Removed in PHP 5.6.0.
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_EXPECT_100_TIMEOUT_MS | The timeout for Expect: 100-continue responses in milliseconds. Defaults to 1000 milliseconds. | Added in cURL 7.36.0. Available since PHP 7.0.7.
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_HEADEROPT | How to deal with headers. One of the following constants: CURLHEADER_UNIFIED: the headers specified in CURLOPT_HTTPHEADER will be used in requests both to servers and proxies. With this option enabled, CURLOPT_PROXYHEADER will not have any effect. CURLHEADER_SEPARATE: makes CURLOPT_HTTPHEADER headers only get sent to a server and not to a proxy. Proxy headers must be set with CURLOPT_PROXYHEADER to get used. Note that if a non-CONNECT request is sent to a proxy, libcurl will send both server headers and proxy headers. When doing CONNECT, libcurl will send CURLOPT_PROXYHEADER headers only to the proxy and then CURLOPT_HTTPHEADER headers only to the server. Defaults to CURLHEADER_SEPARATE as of cURL 7.42.1, and CURLHEADER_UNIFIED before. | Added in cURL 7.37.0. Available since PHP 7.0.7.
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_POSTREDIR | A bitmask of 1 (301 Moved Permanently), 2 (302 Found) and 4 (303 See Other) if the HTTP POST method should be maintained when CURLOPT_FOLLOWLOCATION is set and a specific type of redirect occurs. | Added in cURL 7.19.1. Available since PHP 5.3.2.
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), CURLPROXY_SOCKS4, CURLPROXY_SOCKS5, CURLPROXY_SOCKS4A or CURLPROXY_SOCKS5_HOSTNAME. | 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_OPTIONS | Set SSL behavior options, which is a bitmask of any of the following constants: CURLSSLOPT_ALLOW_BEAST: do not attempt to use any workarounds for a security flaw in the SSL3 and TLS1.0 protocols. CURLSSLOPT_NO_REVOKE: disable certificate revocation checks for those SSL backends where such behavior is present. | Added in cURL 7.25.0. Available since PHP 7.0.7.
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. 0 to not check the names. In production environments the value of this option should be kept at 2 (default value). | Support for value 1 removed in cURL 7.28.1.
CURLOPT_SSLVERSION One of CURL_SSLVERSION_DEFAULT (0), CURL_SSLVERSION_TLSv1 (1), CURL_SSLVERSION_SSLv2 (2), CURL_SSLVERSION_SSLv3 (3), CURL_SSLVERSION_TLSv1_0 (4), CURL_SSLVERSION_TLSv1_1 (5) or CURL_SSLVERSION_TLSv1_2 (6).

Nota:

Your best bet is to not set this and let it use the default. Setting it to 2 or 3 is very dangerous given the known vulnerabilities in SSLv2 and SSLv3.

CURLOPT_STREAM_WEIGHT | Set the numerical stream weight (a number between 1 and 256). | Added in cURL 7.46.0. Available since PHP 7.0.7.
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.
CURLOPT_SSH_AUTH_TYPES | A bitmask consisting of one or more of CURLSSH_AUTH_PUBLICKEY, CURLSSH_AUTH_PASSWORD, CURLSSH_AUTH_HOST, CURLSSH_AUTH_KEYBOARD. Set to CURLSSH_AUTH_ANY to let libcurl pick one. | Added in cURL 7.16.1.
CURLOPT_IPRESOLVE | Allows an application to select what kind of IP addresses to use when resolving host names. This is only interesting when using host names that resolve addresses using more than one version of IP, possible values are CURL_IPRESOLVE_WHATEVER, CURL_IPRESOLVE_V4, CURL_IPRESOLVE_V6, by default CURL_IPRESOLVE_WHATEVER. | Added in cURL 7.10.8.
CURLOPT_FTP_FILEMETHOD | Tell curl which method to use to reach a file on a FTP(S) server. Possible values are CURLFTPMETHOD_MULTICWD, CURLFTPMETHOD_NOCWD and CURLFTPMETHOD_SINGLECWD. | Added in cURL 7.15.1. Available since PHP 5.3.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. | Might require an 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.

Nota:

Don't do this without making sure the server supports the custom request method first.

CURLOPT_DEFAULT_PROTOCOL

The default protocol to use if the URL is missing a scheme name.

Added in cURL 7.45.0. Available since PHP 7.0.7.
CURLOPT_DNS_INTERFACE

Set the name of the network interface that the DNS resolver should bind to. This must be an interface name (not an address).

Added in cURL 7.33.0. Available since PHP 7.0.7.
CURLOPT_DNS_LOCAL_IP4

Set the local IPv4 address that the resolver should bind to. The argument should contain a single numerical IPv4 address as a string.

Added in cURL 7.33.0. Available since PHP 7.0.7.
CURLOPT_DNS_LOCAL_IP6

Set the local IPv6 address that the resolver should bind to. The argument should contain a single numerical IPv6 address as a string.

Added in cURL 7.33.0. Available since PHP 7.0.7.
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 "PORT" instruction. The "PORT" 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_KEYPASSWD | The password required to use the CURLOPT_SSLKEY or CURLOPT_SSH_PRIVATE_KEYFILE private key. | Added in cURL 7.16.1.
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_LOGIN_OPTIONS | Can be used to set protocol specific login options, such as the preferred authentication mechanism via "AUTH=NTLM" or "AUTH=*", and should be used in conjunction with the CURLOPT_USERNAME option. | Added in cURL 7.34.0. Available since PHP 7.0.7.
CURLOPT_PINNEDPUBLICKEY | Set the pinned public key. The string can be the file name of your pinned public key. The file format expected is "PEM" or "DER". The string can also be any number of base64 encoded sha256 hashes preceded by "sha256//" and separated by ";". | Added in cURL 7.39.0. Available since PHP 7.0.7.
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. As of PHP 5.5.0, the @ prefix is deprecated and files can be sent using CURLFile. The @ prefix can be disabled for safe passing of values beginning with @ by setting the CURLOPT_SAFE_UPLOAD option to TRUE.
CURLOPT_PRIVATE | Any data that should be associated with this cURL handle. This data can subsequently be retrieved with the CURLINFO_PRIVATE option of curl_getinfo(). cURL does nothing with this data. When using a cURL multi handle, this private data is typically a unique key to identify a standard cURL handle. | Added in cURL 7.10.3.
CURLOPT_PROXY | The HTTP proxy to tunnel requests through.
CURLOPT_PROXY_SERVICE_NAME | The proxy authentication service name. | Added in cURL 7.34.0. Available since PHP 7.0.7.
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_SERVICE_NAME | The authentication service name. | Added in cURL 7.43.0. Available since PHP 7.0.7.
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 | A string containing 32 hexadecimal digits. The string should be the MD5 checksum of the remote host's public key, and libcurl will reject the connection to the host unless the md5sums match. This option is only for SCP and SFTP transfers. | Added in cURL 7.17.1.
CURLOPT_SSH_PUBLIC_KEYFILE | The file name for your public key. If not used, libcurl defaults to $HOME/.ssh/id_dsa.pub if the HOME environment variable is set, and just "id_dsa.pub" in the current directory if HOME is not set. | Added in cURL 7.16.1.
CURLOPT_SSH_PRIVATE_KEYFILE | The file name for your private key. If not used, libcurl defaults to $HOME/.ssh/id_dsa if the HOME environment variable is set, and just "id_dsa" in the current directory if HOME is not set. If the file is password-protected, set the password with CURLOPT_KEYPASSWD. | Added in cURL 7.16.1.
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.

Nota:

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_UNIX_SOCKET_PATH | Enables the use of Unix domain sockets as connection endpoint and sets the path to the given string. | Added in cURL 7.40.0. Available since PHP 7.0.7.
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_USERNAME | The user name to use in authentication. | Added in cURL 7.19.1. Available since PHP 5.5.0.
CURLOPT_USERPWD | A username and password formatted as "[username]:[password]" to use for the connection.
CURLOPT_XOAUTH2_BEARER | Specifies the OAuth 2.0 access token. | Added in cURL 7.33.0. Available since PHP 7.0.7.

value should be an array for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_CONNECT_TO | Connect to a specific host and port instead of the URL's host and port. Accepts an array of strings with the format HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT. | Added in cURL 7.49.0. Available since PHP 7.0.7.
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_PROXYHEADER | An array of custom HTTP headers to pass to proxies. | Added in cURL 7.37.0. Available since PHP 7.0.7.
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 the name of a valid function or a Closure for the following values of the option parameter:

Option | Set value to
CURLOPT_HEADERFUNCTION | A callback accepting 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 by this callback. Return the number of bytes written.
CURLOPT_PASSWDFUNCTION | A callback accepting 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

A callback accepting five parameters. The first is the cURL resource, the second is the total number of bytes expected to be downloaded in this transfer, the third is the number of bytes downloaded so far, the fourth is the total number of bytes expected to be uploaded in this transfer, and the fifth is the number of bytes uploaded so far.

Nota:

The callback is only called when the CURLOPT_NOPROGRESS option is set to FALSE.

Return a non-zero value to abort the transfer. In which case, the transfer will set a CURLE_ABORTED_BY_CALLBACK error.

CURLOPT_READFUNCTION | A callback accepting 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 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 | A callback accepting 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 this callback. It must return the exact number of bytes written or the transfer will be aborted with an error.

Other values:

Option | Set value to
CURLOPT_SHARE | A result of curl_share_init(). Makes the cURL handle to use the data from the shared handle.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.0.7 | Introduced CURL_HTTP_VERSION_2, CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, CURL_HTTP_VERSION_2TLS, CURL_REDIR_POST_301, CURL_REDIR_POST_302, CURL_REDIR_POST_303, CURL_REDIR_POST_ALL, CURL_VERSION_KERBEROS5, CURL_VERSION_PSL, CURL_VERSION_UNIX_SOCKETS, CURLAUTH_NEGOTIATE, CURLAUTH_NTLM_WB, CURLFTP_CREATE_DIR, CURLFTP_CREATE_DIR_NONE, CURLFTP_CREATE_DIR_RETRY, CURLHEADER_SEPARATE, CURLHEADER_UNIFIED, CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLMOPT_MAX_HOST_CONNECTIONS, CURLMOPT_MAX_PIPELINE_LENGTH, CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPT_CONNECT_TO, CURLOPT_DEFAULT_PROTOCOL, CURLOPT_DNS_INTERFACE, CURLOPT_DNS_LOCAL_IP4, CURLOPT_DNS_LOCAL_IP6, CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOPT_HEADEROPT, CURLOPT_LOGIN_OPTIONS, CURLOPT_PATH_AS_IS, CURLOPT_PINNEDPUBLICKEY, CURLOPT_PIPEWAIT, CURLOPT_PROXY_SERVICE_NAME, CURLOPT_PROXYHEADER, CURLOPT_SASL_IR, CURLOPT_SERVICE_NAME, CURLOPT_SSL_ENABLE_ALPN, CURLOPT_SSL_ENABLE_NPN, CURLOPT_SSL_FALSESTART, CURLOPT_SSL_VERIFYSTATUS, CURLOPT_STREAM_WEIGHT, CURLOPT_TCP_FASTOPEN, CURLOPT_TFTP_NO_OPTIONS, CURLOPT_UNIX_SOCKET_PATH, CURLOPT_XOAUTH2_BEARER, CURLPROTO_SMB, CURLPROTO_SMBS, CURLPROXY_HTTP_1_0, CURLSSH_AUTH_AGENT and CURLSSLOPT_NO_REVOKE.
7.0.0 | Support for disabling the CURLOPT_SAFE_UPLOAD option has been removed. All curl file uploads must use CURLFile.
5.6.0 | CURLOPT_SAFE_UPLOAD is now TRUE by default.
5.6.0 | Removed CURLOPT_CLOSEPOLICY and associated values.
5.5.0 | Added the cURL resource as the first argument to the CURLOPT_PROGRESSFUNCTION callback.
5.5.0 | Introduced CURLOPT_SHARE.
5.3.0 | Introduced CURLOPT_PROGRESSFUNCTION.
5.2.10 | Introduced CURLOPT_PROTOCOLS, and CURLOPT_REDIR_PROTOCOLS.
5.2.4 | Introduced CURLOPT_PRIVATE.
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.

Exemple

Example #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);
?>

Example #2 Uploading file (deprecated as of PHP 5.5.0)

<?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_SAFE_UPLOAD, false); // required as of PHP 5.6.0
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>

Exemplul de mai sus va afi?a:

Array
(
    [name] => Foo
)
Array
(
    [file] => Array
        (
            [name] => test.png
            [type] => image/png
            [tmp_name] => /tmp/phpcpjNeQ
            [error] => 0
            [size] => 279
        )

)

Note

Nota:

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.

A se vedea ?i

  • curl_setopt_array() - Set multiple options for a cURL transfer

curl_setopt_array
curl_share_close
Func?ii cURL


Close a cURL share handle

curl_setopt
curl_share_init
Func?ii cURL
PHP Manual

curl_share_close

(PHP 5 >= 5.5.0, PHP 7)

curl_share_close — Close a cURL share handle

Descrierea

void curl_share_close ( resource $sh )

Closes a cURL share handle and frees all resources.

Parametri

sh

A cURL share handle returned by curl_share_init()

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 curl_share_setopt() example

This example will create a cURL share handle, add two cURL handles to it, and then run them with cookie data sharing.

<?php
// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);

// Execute the first cURL handle
curl_exec($ch1);

// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);

// Execute the second cURL handle
//  all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);

// Close the cURL share handle
curl_share_close($sh);

// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
?>

A se vedea ?i

  • curl_share_init() - Initialize a cURL share handle

curl_setopt
curl_share_init
Func?ii cURL


Initialize a cURL share handle

curl_share_close
curl_share_setopt
Func?ii cURL
PHP Manual

curl_share_init

(PHP 5 >= 5.5.0, PHP 7)

curl_share_init — Initialize a cURL share handle

Descrierea

resource curl_share_init ( void )

Allows to share data between cURL handles.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns resource of type "cURL Share Handle".

Exemple

Example #1 curl_share_init() example

This example will create a cURL share handle, add two cURL handles to it, and then run them with cookie data sharing.

<?php
// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);

// Execute the first cURL handle
curl_exec($ch1);

// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);

// Execute the second cURL handle
//  all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);

// Close the cURL share handle
curl_share_close($sh);

// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
?>

A se vedea ?i

  • curl_share_setopt() - Set an option for a cURL share handle.
  • curl_share_close() - Close a cURL share handle

curl_share_close
curl_share_setopt
Func?ii cURL


Set an option for a cURL share handle.

curl_share_init
curl_strerror
Func?ii cURL
PHP Manual

curl_share_setopt

(PHP 5 >= 5.5.0, PHP 7)

curl_share_setopt — Set an option for a cURL share handle.

Descrierea

bool curl_share_setopt ( resource $sh , int $option , string $value )

Sets an option on the given cURL share handle.

Parametri

sh

A cURL share handle returned by curl_share_init().

option

Option | Description
CURLSHOPT_SHARE | Specifies a type of data that should be shared.
CURLSHOPT_UNSHARE | Specifies a type of data that will be no longer shared.

value

Value | Description
CURL_LOCK_DATA_COOKIE | Shares cookie data.
CURL_LOCK_DATA_DNS | Shares DNS cache. Note that when you use cURL multi handles, all handles added to the same multi handle will share DNS cache by default.
CURL_LOCK_DATA_SSL_SESSION | Shares SSL session IDs, reducing the time spent on the SSL handshake when reconnecting to the same server. Note that SSL session IDs are reused within the same handle by default.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 curl_share_setopt() example

This example will create a cURL share handle, add two cURL handles to it, and then run them with cookie data sharing.

<?php
// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);

// Execute the first cURL handle
curl_exec($ch1);

// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);

// Execute the second cURL handle
//  all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);

// Close the cURL share handle
curl_share_close($sh);

// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
?>

curl_share_init
curl_strerror
Func?ii cURL


Return string describing the given error code

curl_share_setopt
curl_unescape
Func?ii cURL
PHP Manual

curl_strerror

(PHP 5 >= 5.5.0, PHP 7)

curl_strerror — Return string describing the given error code

Descrierea

string curl_strerror ( int $errornum )

Returns a text error message describing the given error code.

Parametri

errornum

One of the » cURL error codes constants.

Valorile întoarse

Returns error description or NULL for invalid error code.

Exemple

Example #1 curl_errno() example

<?php
// Create a curl handle with a mispelled protocol in URL
$ch = curl_init("htp://example.com/");

// Send request
curl_exec($ch);

// Check for errors and display the error message
if($errno = curl_errno($ch)) {
    $error_message = curl_strerror($errno);
    echo "cURL error ({$errno}):\n {$error_message}";
}

// Close the handle
curl_close($ch);
?>

Exemplul de mai sus va afi?a:

cURL error (1):
 Unsupported protocol

A se vedea ?i

  • curl_errno() - Return the last error number
  • curl_error() - Return a string containing the last error for the current session
  • » Curl error codes

curl_share_setopt
curl_unescape
Func?ii cURL


Decodes the given URL encoded string

curl_strerror
curl_version
Func?ii cURL
PHP Manual

curl_unescape

(PHP 5 >= 5.5.0, PHP 7)

curl_unescape — Decodes the given URL encoded string

Descrierea

string curl_unescape ( resource $ch , string $str )

This function decodes the given URL encoded string.

Parametri

ch

Un handle cURL întors de curl_init().

str

The URL encoded string to be decoded.

Valorile întoarse

Returns decoded string sau FALSE în cazul e?ecului.

Exemple

Example #1 curl_escape() example

<?php
// Create a curl handle
$ch = curl_init('http://example.com/redirect.php');

// Send HTTP request and follow redirections
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($ch);

// Get the last effective URL
$effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
// ie. "http://example.com/show_location.php?loc=M%C3%BCnchen"

// Decode the URL
$effective_url_decoded = curl_unescape($ch, $effective_url);
// "http://example.com/show_location.php?loc=München"

// Close the handle
curl_close($ch);
?>

Note

Nota:

curl_unescape() does not decode plus symbols (+) into spaces. urldecode() does.

A se vedea ?i

  • curl_escape() - URL encodes the given string
  • urlencode() - URL-encodes string
  • urldecode() - Decodes URL-encoded string
  • rawurlencode() - URL-encode according to RFC 3986
  • rawurldecode() - Decode URL-encoded strings

curl_strerror
curl_version
Func?ii cURL


Gets cURL version information

curl_unescape
CURLFile
Func?ii cURL
PHP Manual

curl_version

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

curl_version — Gets cURL version information

Descrierea

array curl_version ([ int $age = CURLVERSION_NOW ] )

Returns information about the cURL version.

Parametri

age

Valorile întoarse

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

Exemple

Example #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_unescape
CURLFile
Func?ii cURL


The CURLFile class

(PHP 5 >= 5.5.0, PHP 7)

Introducere

CURLFile should be used to upload a file with CURLOPT_POSTFIELDS.

Sinopsisul clasei

CURLFile {
/* Proprieta?i */
public $name ;
public $mime ;
public $postname ;
/* Metode */
public __construct ( string $filename [, string $mimetype [, string $postname ]] )
public string getFilename ( void )
public string getMimeType ( void )
public string getPostFilename ( void )
public void setMimeType ( string $mime )
public void setPostFilename ( string $postname )
public void __wakeup ( void )
}

Proprieta?i

name

Name of the file to be uploaded.

mime

MIME type of the file (default is application/octet-stream).

postname

The name of the file in the upload data (defaults to the name property).

A se vedea ?i

  • curl_setopt()

Cuprins

  • CURLFile::__construct — Create a CURLFile object
  • CURLFile::getFilename — Get file name
  • CURLFile::getMimeType — Get MIME type
  • CURLFile::getPostFilename — Get file name for POST
  • CURLFile::setMimeType — Set MIME type
  • CURLFile::setPostFilename — Set file name for POST
  • CURLFile::__wakeup — Unserialization handler
curl_version
CURLFile::__construct
cURL


Create a CURLFile object

CURLFile
CURLFile::getFilename
CURLFile
PHP Manual

CURLFile::__construct

curl_file_create

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::__construct -- curl_file_create — Create a CURLFile object

Descrierea

Stil obiect-orientat

public CURLFile::__construct ( string $filename [, string $mimetype [, string $postname ]] )

Stil procedural

CURLFile curl_file_create ( string $filename [, string $mimetype [, string $postname ]] )

Creates a CURLFile object, used to upload a file with CURLOPT_POSTFIELDS.

Parametri

filename

Path to the file which will be uploaded.

mimetype

Mimetype of the file.

postname

Name of the file to be used in the upload data.

Valorile întoarse

Returns a CURLFile object.

Exemple

Example #1 CURLFile::__construct() example

Stil obiect-orientat

<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/

// Create a cURL handle
$ch = curl_init('http://example.com/upload.php');

// Create a CURLFile object
$cfile = new CURLFile('cats.jpg','image/jpeg','test_name');

// Assign POST data
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Execute the handle
curl_exec($ch);
?>

Stil procedural

<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/

// Create a cURL handle
$ch = curl_init('http://example.com/upload.php');

// Create a CURLFile object
$cfile = curl_file_create('cats.jpg','image/jpeg','test_name');

// Assign POST data
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Execute the handle
curl_exec($ch);
?>

Exemplul de mai sus va afi?a:

array(1) {
  ["test_file"]=>
  array(5) {
    ["name"]=>
    string(9) "test_name"
    ["type"]=>
    string(10) "image/jpeg"
    ["tmp_name"]=>
    string(14) "/tmp/phpPC9Kbx"
    ["error"]=>
    int(0)
    ["size"]=>
    int(46334)
  }
}

A se vedea ?i

  • curl_setopt() - Set an option for a cURL transfer

CURLFile
CURLFile::getFilename
CURLFile


Get file name

CURLFile::__construct
CURLFile::getMimeType
CURLFile
PHP Manual

CURLFile::getFilename

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::getFilename — Get file name

Descrierea

public string CURLFile::getFilename ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns file name.

CURLFile::__construct
CURLFile::getMimeType
CURLFile


Get MIME type

CURLFile::getFilename
CURLFile::getPostFilename
CURLFile
PHP Manual

CURLFile::getMimeType

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::getMimeType — Get MIME type

Descrierea

public string CURLFile::getMimeType ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns MIME type.

CURLFile::getFilename
CURLFile::getPostFilename
CURLFile


Get file name for POST

CURLFile::getMimeType
CURLFile::setMimeType
CURLFile
PHP Manual

CURLFile::getPostFilename

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::getPostFilename — Get file name for POST

Descrierea

public string CURLFile::getPostFilename ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns file name for POST.

CURLFile::getMimeType
CURLFile::setMimeType
CURLFile


Set MIME type

CURLFile::getPostFilename
CURLFile::setPostFilename
CURLFile
PHP Manual

CURLFile::setMimeType

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::setMimeType — Set MIME type

Descrierea

public void CURLFile::setMimeType ( string $mime )

Parametri

mime

MIME type to be used in POST data.

Valorile întoarse

Nu este întoarsa nici o valoare.

CURLFile::getPostFilename
CURLFile::setPostFilename
CURLFile


Set file name for POST

CURLFile::setMimeType
CURLFile::__wakeup
CURLFile
PHP Manual

CURLFile::setPostFilename

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::setPostFilename — Set file name for POST

Descrierea

public void CURLFile::setPostFilename ( string $postname )

Parametri

postname

Filename to be used in POST data.

Valorile întoarse

Nu este întoarsa nici o valoare.

CURLFile::setMimeType
CURLFile::__wakeup
CURLFile


Unserialization handler

CURLFile::setPostFilename
Event
CURLFile
PHP Manual

CURLFile::__wakeup

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::__wakeup — Unserialization handler

Descrierea

public void CURLFile::__wakeup ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

CURLFile is not serializable.

CURLFile::setPostFilename
Event
CURLFile


Event

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Exemple
  • Event flags
  • About event persistence
  • Event callbacks
  • Constructing signal events
  • Event — The Event class
    • Event::add — Makes event pending
    • Event::addSignal — Makes signal event pending
    • Event::addTimer — Makes timer event pending
    • Event::__construct — Constructs Event object
    • Event::del — Makes event non-pending
    • Event::delSignal — Makes signal event non-pending
    • Event::delTimer — Makes timer event non-pending
    • Event::free — Make event non-pending and free resources allocated for this event.
    • Event::getSupportedMethods — Returns array with of the names of the methods supported in this version of Libevent
    • Event::pending — Detects whether event is pending or scheduled
    • Event::set — Re-configures event
    • Event::setPriority — Set event priority
    • Event::setTimer — Re-configures timer event
    • Event::signal — Constructs signal event object
    • Event::timer — Constructs timer event object
  • EventBase — The EventBase class
    • EventBase::__construct — Constructs EventBase object
    • EventBase::dispatch — Dispatch pending events
    • EventBase::exit — Stop dispatching events
    • EventBase::free — Free resources allocated for this event base
    • EventBase::getFeatures — Returns bitmask of features supported
    • EventBase::getMethod — Returns event method in use
    • EventBase::getTimeOfDayCached — Returns the current event base time
    • EventBase::gotExit — Checks if the event loop was told to exit
    • EventBase::gotStop — Checks if the event loop was told to exit
    • EventBase::loop — Dispatch pending events
    • EventBase::priorityInit — Sets number of priorities per event base
    • EventBase::reInit — Re-initialize event base(after a fork).
    • EventBase::stop — Tells event_base to stop dispatching events
  • EventBuffer — The EventBuffer class
    • EventBuffer::add — Append data to the end of an event buffer
    • EventBuffer::addBuffer — Move all data from a buffer provided to the current instance of EventBuffer
    • EventBuffer::appendFrom — Moves the specified number of bytes from a source buffer to the end of the current buffer
    • EventBuffer::__construct — Constructs EventBuffer object
    • EventBuffer::copyout — Copies out specified number of bytes from the front of the buffer
    • EventBuffer::drain — Removes specified number of bytes from the front of the buffer without copying it anywhere
    • EventBuffer::enableLocking — Descrierea
    • EventBuffer::expand — Reserves space in buffer
    • EventBuffer::freeze — Prevent calls that modify an event buffer from succeeding
    • EventBuffer::lock — Acquires a lock on buffer
    • EventBuffer::prepend — Prepend data to the front of the buffer
    • EventBuffer::prependBuffer — Moves all data from source buffer to the front of current buffer
    • EventBuffer::pullup — Linearizes data within buffer and returns it's contents as a string
    • EventBuffer::read — Read data from an evbuffer and drain the bytes read
    • EventBuffer::readFrom — Read data from a file onto the end of the buffer
    • EventBuffer::readLine — Extracts a line from the front of the buffer
    • EventBuffer::search — Scans the buffer for an occurrence of a string
    • EventBuffer::searchEol — Scans the buffer for an occurrence of an end of line
    • EventBuffer::substr — Substracts a portion of the buffer data
    • EventBuffer::unfreeze — Re-enable calls that modify an event buffer
    • EventBuffer::unlock — Releases lock acquired by EventBuffer::lock
    • EventBuffer::write — Write contents of the buffer to a file or socket
  • EventBufferEvent — The EventBufferEvent class
    • EventBufferEvent::close — Closes file descriptor associated with the current buffer event
    • EventBufferEvent::connect — Connect buffer event's file descriptor to given address or UNIX socket
    • EventBufferEvent::connectHost — Connects to a hostname with optionally asyncronous DNS resolving
    • EventBufferEvent::__construct — Constructs EventBufferEvent object
    • EventBufferEvent::createPair — Creates two buffer events connected to each other
    • EventBufferEvent::disable — Disable events read, write, or both on a buffer event.
    • EventBufferEvent::enable — Enable events read, write, or both on a buffer event.
    • EventBufferEvent::free — Free a buffer event
    • EventBufferEvent::getDnsErrorString — Returns string describing the last failed DNS lookup attempt
    • EventBufferEvent::getEnabled — Returns bitmask of events currently enabled on the buffer event
    • EventBufferEvent::getInput — Returns underlying input buffer associated with current buffer event
    • EventBufferEvent::getOutput — Returns underlying output buffer associated with current buffer event
    • EventBufferEvent::read — Read buffer's data
    • EventBufferEvent::readBuffer — Drains the entire contents of the input buffer and places them into buf
    • EventBufferEvent::setCallbacks — Assigns read, write and event(status) callbacks
    • EventBufferEvent::setPriority — Assign a priority to a bufferevent
    • EventBufferEvent::setTimeouts — Set the read and write timeout for a buffer event
    • EventBufferEvent::setWatermark — Adjusts read and/or write watermarks
    • EventBufferEvent::sslError — Returns most recent OpenSSL error reported on the buffer event
    • EventBufferEvent::sslFilter — Create a new SSL buffer event to send its data over another buffer event
    • EventBufferEvent::sslGetCipherInfo — Returns a textual description of the cipher.
    • EventBufferEvent::sslGetCipherName — Returns the current cipher name of the SSL connection.
    • EventBufferEvent::sslGetCipherVersion — Returns version of cipher used by current SSL connection.
    • EventBufferEvent::sslGetProtocol — Returns the name of the protocol used for current SSL connection.
    • EventBufferEvent::sslRenegotiate — Tells a bufferevent to begin SSL renegotiation.
    • EventBufferEvent::sslSocket — Creates a new SSL buffer event to send its data over an SSL on a socket
    • EventBufferEvent::write — Adds data to a buffer event's output buffer
    • EventBufferEvent::writeBuffer — Adds contents of the entire buffer to a buffer event's output buffer
  • About buffer event callbacks
  • EventConfig — The EventConfig class
    • EventConfig::avoidMethod — Tells libevent to avoid specific event method
    • EventConfig::__construct — Constructs EventConfig object
    • EventConfig::requireFeatures — Enters a required event method feature that the application demands
    • EventConfig::setMaxDispatchInterval — Prevents priority inversion
  • EventDnsBase — The EventDnsBase class
    • EventDnsBase::addNameserverIp — Adds a nameserver to the DNS base
    • EventDnsBase::addSearch — Adds a domain to the list of search domains
    • EventDnsBase::clearSearch — Removes all current search suffixes
    • EventDnsBase::__construct — Constructs EventDnsBase object
    • EventDnsBase::countNameservers — Gets the number of configured nameservers
    • EventDnsBase::loadHosts — Loads a hosts file (in the same format as /etc/hosts) from hosts file
    • EventDnsBase::parseResolvConf — Scans the resolv.conf-formatted file
    • EventDnsBase::setOption — Set the value of a configuration option
    • EventDnsBase::setSearchNdots — Set the 'ndots' parameter for searches
  • EventHttp — The EventHttp class
    • EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource
    • EventHttp::addServerAlias — Adds a server alias to the HTTP server object
    • EventHttp::bind — Binds an HTTP server on the specified address and port
    • EventHttp::__construct — Constructs EventHttp object(the HTTP server)
    • EventHttp::removeServerAlias — Removes server alias
    • EventHttp::setAllowedMethods — Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks
    • EventHttp::setCallback — Sets a callback for specified URI
    • EventHttp::setDefaultCallback — Sets default callback to handle requests that are not caught by specific callbacks
    • EventHttp::setMaxBodySize — Sets maximum request body size
    • EventHttp::setMaxHeadersSize — Sets maximum HTTP header size
    • EventHttp::setTimeout — Sets the timeout for an HTTP request
  • EventHttpConnection — The EventHttpConnection class
    • EventHttpConnection::__construct — Constructs EventHttpConnection object
    • EventHttpConnection::getBase — Returns event base associated with the connection
    • EventHttpConnection::getPeer — Gets the remote address and port associated with the connection
    • EventHttpConnection::makeRequest — Makes an HTTP request over the specified connection
    • EventHttpConnection::setCloseCallback — Set callback for connection close
    • EventHttpConnection::setLocalAddress — Sets the IP address from which HTTP connections are made
    • EventHttpConnection::setLocalPort — Sets the local port from which connections are made
    • EventHttpConnection::setMaxBodySize — Sets maximum body size for the connection
    • EventHttpConnection::setMaxHeadersSize — Sets maximum header size
    • EventHttpConnection::setRetries — Sets the retry limit for the connection
    • EventHttpConnection::setTimeout — Sets the timeout for the connection
  • EventHttpRequest — The EventHttpRequest class
    • EventHttpRequest::addHeader — Adds an HTTP header to the headers of the request
    • EventHttpRequest::cancel — Cancels a pending HTTP request
    • EventHttpRequest::clearHeaders — Removes all output headers from the header list of the request
    • EventHttpRequest::closeConnection — Closes associated HTTP connection
    • EventHttpRequest::__construct — Constructs EventHttpRequest object
    • EventHttpRequest::findHeader — Finds the value belonging a header
    • EventHttpRequest::free — Frees the object and removes associated events
    • EventHttpRequest::getBufferEvent — Returns EventBufferEvent object
    • EventHttpRequest::getCommand — Returns the request command(method)
    • EventHttpRequest::getConnection — Returns EventHttpConnection object
    • EventHttpRequest::getHost — Returns the request host
    • EventHttpRequest::getInputBuffer — Returns the input buffer
    • EventHttpRequest::getInputHeaders — Returns associative array of the input headers
    • EventHttpRequest::getOutputBuffer — Returns the output buffer of the request
    • EventHttpRequest::getOutputHeaders — Returns associative array of the output headers
    • EventHttpRequest::getResponseCode — Returns the response code
    • EventHttpRequest::getUri — Returns the request URI
    • EventHttpRequest::removeHeader — Removes an HTTP header from the headers of the request
    • EventHttpRequest::sendError — Send an HTML error message to the client
    • EventHttpRequest::sendReply — Send an HTML reply to the client
    • EventHttpRequest::sendReplyChunk — Send another data chunk as part of an ongoing chunked reply
    • EventHttpRequest::sendReplyEnd — Complete a chunked reply, freeing the request as appropriate
    • EventHttpRequest::sendReplyStart — Initiate a chunked reply
  • EventListener — The EventListener class
    • EventListener::__construct — Creates new connection listener associated with an event base
    • EventListener::disable — Disables an event connect listener object
    • EventListener::enable — Enables an event connect listener object
    • EventListener::getBase — Returns event base associated with the event listener
    • EventListener::getSocketName — Retreives the current address to which the listener's socket is bound.
    • EventListener::setCallback — The setCallback purpose
    • EventListener::setErrorCallback — Set event listener's error callback
  • EventSslContext — The EventSslContext class
    • EventSslContext::__construct — Constructs an OpenSSL context for use with Event classes
  • EventUtil — The EventUtil class
    • EventUtil::__construct — The abstract constructor
    • EventUtil::getLastSocketErrno — Returns the most recent socket error number
    • EventUtil::getLastSocketError — Returns the most recent socket error
    • EventUtil::getSocketFd — Returns numeric file descriptor of a socket, or stream
    • EventUtil::getSocketName — Retreives the current address to which the socket is bound.
    • EventUtil::setSocketOption — Sets socket options
    • EventUtil::sslRandPoll — Generates entropy by means of OpenSSL's RAND_poll()
CURLFile::__wakeup
Introducere
Alte servicii


Introducere

This is an extension to efficiently schedule I/O, time and signal based events using the best I/O notification mechanism available for specific platform. This is a port of libevent to the PHP infrastructure.

Nota:

Note, Windows support introduced in event-1.9.0 .

Version 1.0.0 introduces new object-oriented API (breaking backwards compatibility), and support of libevent 2+ including HTTP, DNS, OpenSSL and the event listener.

Nota:

Note, event-1.0.0 and greater is not compatible with previous versions.

Event
Instalarea / configurarea
Event


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Event


Necesita?i

This extension requires » libevent library. Most modern distributions provide packages for libevent.

OpenSSL features require » OpenSSL library.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/event .

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Exemple

Example #1 Simple HTTP client

<?php
// Read callback
function readcb($bev, $base) {
    //$input = $bev->input; //$bev->getInput();

    //$pos = $input->search("TTP");
    $pos = $bev->input->search("TTP");

    while (($n = $bev->input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}

// Event callback
function eventcb($bev, $events, $base) {
    if ($events & EventBufferEvent::CONNECTED) {
        echo "Connected.\n";
    } elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
        if ($events & EventBufferEvent::ERROR) {
            echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
        }

        echo "Closing\n";
        $base->exit();
        exit("Done\n");
    }
}

if ($argc != 3) {
    echo <<<EOS
Trivial HTTP 0.x client
Syntax: php {$argv[0]} [hostname] [resource]
Example: php {$argv[0]} www.google.com /

EOS;
    exit();
}

$base = new EventBase();

$dns_base = new EventDnsBase($base, TRUE); // We'll use async DNS resolving
if (!$dns_base) {
    exit("Failed to init DNS Base\n");
}

$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,
    "readcb", /* writecb */ NULL, "eventcb"
);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

//$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

$output = $bev->output; //$bev->getOutput();
if (!$output->add(
    "GET {$argv[2]} HTTP/1.0\r\n".
    "Host: {$argv[1]}\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

if (!$bev->connectHost($dns_base, $argv[1], 80, EventUtil::AF_UNSPEC)) {
    exit("Can't connect to host {$argv[1]}\n");
}

$base->dispatch();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Connected.
HTTP/1.1 301 Moved Permanently
Date: Fri, 01 Mar 2013 18:47:48 GMT
Location: http://www.google.co.uk/
Content-Type: text/html; CHARSET=Windows-1252
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Age: 133438
Expires: Sat, 30 Mar 2013 05:39:28 GMT
Connection: close

<HTML><HEAD><meta http-equiv="content-type" content="text/html;CHARSET=Windows-1252">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.co.uk/">here</A>.
</BODY></HTML>
Closing
Done

Example #2 HTTP client using asynchronous DNS resolver

<?php
/*
 * 1. Connect to 127.0.0.1 at port 80
 * by means of EventBufferEvent::connect().
 *
 * 2. Request /index.cphp via HTTP/1.0
 * using the output buffer.
 *
 * 3. Asyncronously read the response and print it to stdout.
 */

// Read callback
function readcb($bev, $base) {
    $input = $bev->getInput();

    while (($n = $input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}

// Event callback
function eventcb($bev, $events, $base) {
    if ($events & EventBufferEvent::CONNECTED) {
        echo "Connected.\n";
    } elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
        if ($events & EventBufferEvent::ERROR) {
            echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
        }

        echo "Closing\n";
        $base->exit();
        exit("Done\n");
    }
}

$base = new EventBase();

echo "step 1\n";
$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

echo "step 2\n";
$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

echo "step 3\n";
// Send request
$output = $bev->getOutput();
if (!$output->add(
    "GET /index.cphp HTTP/1.0\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

/* Connect to the host syncronously.
We know the IP, and don't need to resolve DNS. */
if (!$bev->connect("127.0.0.1:80")) {
    exit("Can't connect to host\n");
}

// Dispatch pending events
$base->dispatch();
?>

Example #3 Echo server

<?php
/*
 * Simple echo server based on libevent's connection listener.
 *
 * Usage:
 * 1) In one terminal window run:
 *
 * $ php listener.php 9881
 *
 * 2) In another terminal window open up connection, e.g.:
 *
 * $ nc 127.0.0.1 9881
 *
 * 3) start typing. The server should repeat the input.
 */

class MyListenerConnection {
    private $bev, $base;

    public function __destruct() {
        $this->bev->free();
    }

    public function __construct($base, $fd) {
        $this->base = $base;

        $this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);

        $this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,
            array($this, "echoEventCallback"), NULL);

        if (!$this->bev->enable(Event::READ)) {
            echo "Failed to enable READ\n";
            return;
        }
    }

    public function echoReadCallback($bev, $ctx) {
        // Copy all the data from the input buffer to the output buffer

        // Variant #1
        $bev->output->addBuffer($bev->input);

        /* Variant #2 */
        /*
        $input    = $bev->getInput();
        $output = $bev->getOutput();
        $output->addBuffer($input);
        */
    }

    public function echoEventCallback($bev, $events, $ctx) {
        if ($events & EventBufferEvent::ERROR) {
            echo "Error from bufferevent\n";
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            //$bev->free();
            $this->__destruct();
        }
    }
}

class MyListener {
    public $base,
        $listener,
        $socket;
    private $conn = array();

    public function __destruct() {
        foreach ($this->conn as &$c) $c = NULL;
    }

    public function __construct($port) {
        $this->base = new EventBase();
        if (!$this->base) {
            echo "Couldn't open event base";
            exit(1);
        }

        // Variant #1
        /*
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if (!socket_bind($this->socket, '0.0.0.0', $port)) {
            echo "Unable to bind socket\n";
            exit(1);
        }
        $this->listener = new EventListener($this->base,
            array($this, "acceptConnCallback"), $this->base,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1, $this->socket);
         */

        // Variant #2
         $this->listener = new EventListener($this->base,
             array($this, "acceptConnCallback"), $this->base,
             EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,
             "0.0.0.0:$port");

        if (!$this->listener) {
            echo "Couldn't create listener";
            exit(1);
        }

        $this->listener->setErrorCallback(array($this, "accept_error_cb"));
    }

    public function dispatch() {
        $this->base->dispatch();
    }

    // This callback is invoked when there is data to read on $bev
    public function acceptConnCallback($listener, $fd, $address, $ctx) {
        // We got a new connection! Set up a bufferevent for it. */
        $base = $this->base;
        $this->conn[] = new MyListenerConnection($base, $fd);
    }

    public function accept_error_cb($listener, $ctx) {
        $base = $this->base;

        fprintf(STDERR, "Got an error %d (%s) on the listener. "
            ."Shutting down.\n",
            EventUtil::getLastSocketErrno(),
            EventUtil::getLastSocketError());

        $base->exit(NULL);
    }
}

$port = 9808;

if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$l = new MyListener($port);
$l->dispatch();
?>

Example #4 SSL echo server

<?php
/*
 * SSL echo server
 *
 * To test:
 * 1) Run:
 * $ php examples/ssl-echo-server/server.php 9998
 *
 * 2) in another terminal window run:
 * $ socat - SSL:127.0.0.1:9998,verify=1,cafile=examples/ssl-echo-server/cert.pem
 */

class MySslEchoServer {
    public $port,
        $base,
        $bev,
        $listener,
        $ctx;

    function __construct ($port, $host = "127.0.0.1") {
        $this->port = $port;
        $this->ctx = $this->init_ssl();
        if (!$this->ctx) {
            exit("Failed creating SSL context\n");
        }

        $this->base = new EventBase();
        if (!$this->base) {
            exit("Couldn't open event base\n");
        }

        $this->listener = new EventListener($this->base,
            array($this, "ssl_accept_cb"), $this->ctx,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1, "$host:$port");
        if (!$this->listener) {
            exit("Couldn't create listener\n");
        }

        $this->listener->setErrorCallback(array($this, "accept_error_cb"));
    }
    function dispatch() {
        $this->base->dispatch();
    }

    // This callback is invoked when there is data to read on $bev.
    function ssl_read_cb($bev, $ctx) {
        $in = $bev->input; //$bev->getInput();

        printf("Received %zu bytes\n", $in->length);
        printf("----- data ----\n");
        printf("%ld:\t%s\n", (int) $in->length, $in->pullup(-1));

        $bev->writeBuffer($in);
    }

    // This callback is invoked when some even occurs on the event listener,
    // e.g. connection closed, or an error occured
    function ssl_event_cb($bev, $events, $ctx) {
        if ($events & EventBufferEvent::ERROR) {
            // Fetch errors from the SSL error stack
            while ($err = $bev->sslError()) {
                fprintf(STDERR, "Bufferevent error %s.\n", $err);
            }
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            $bev->free();
        }
    }

    // This callback is invoked when a client accepts new connection
    function ssl_accept_cb($listener, $fd, $address, $ctx) {
        // We got a new connection! Set up a bufferevent for it.
        $this->bev = EventBufferEvent::sslSocket($this->base, $fd, $this->ctx,
            EventBufferEvent::SSL_ACCEPTING, EventBufferEvent::OPT_CLOSE_ON_FREE);

        if (!$this->bev) {
            echo "Failed creating ssl buffer\n";
            $this->base->exit(NULL);
            exit(1);
        }

        $this->bev->enable(Event::READ);
        $this->bev->setCallbacks(array($this, "ssl_read_cb"), NULL,
            array($this, "ssl_event_cb"), NULL);
    }

    // This callback is invoked when we failed to setup new connection for a client
    function accept_error_cb($listener, $ctx) {
        fprintf(STDERR, "Got an error %d (%s) on the listener. "
            ."Shutting down.\n",
            EventUtil::getLastSocketErrno(),
            EventUtil::getLastSocketError());

        $this->base->exit(NULL);
    }

    // Initialize SSL structures, create an EventSslContext
    // Optionally create self-signed certificates
    function init_ssl() {
        // We *must* have entropy. Otherwise there's no point to crypto.
        if (!EventUtil::sslRandPoll()) {
            exit("EventUtil::sslRandPoll failed\n");
        }

        $local_cert = __DIR__."/cert.pem";
        $local_pk   = __DIR__."/privkey.pem";

        if (!file_exists($local_cert) || !file_exists($local_pk)) {
            echo "Couldn't read $local_cert or $local_pk file.  To generate a key\n",
                "and self-signed certificate, run:\n",
                "  openssl genrsa -out $local_pk 2048\n",
                "  openssl req -new -key $local_pk -out cert.req\n",
                "  openssl x509 -req -days 365 -in cert.req -signkey $local_pk -out $local_cert\n";

            return FALSE;
        }

        $ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array (
             EventSslContext::OPT_LOCAL_CERT  => $local_cert,
             EventSslContext::OPT_LOCAL_PK    => $local_pk,
             //EventSslContext::OPT_PASSPHRASE  => "echo server",
             EventSslContext::OPT_VERIFY_PEER => true,
             EventSslContext::OPT_ALLOW_SELF_SIGNED => false,
        ));

        return $ctx;
    }
}

// Allow to override the port
$port = 9999;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port\n");
}

$l = new MySslEchoServer($port);
$l->dispatch();
?>

Example #5 Signal handler

<?php
/*
Launch it in a terminal window:

$ php examples/signal.php

In another terminal window find out the pid and send SIGTERM, e.g.:

$ ps aux | grep examp
ruslan    3976  0.2  0.0 139896 11256 pts/1    S+   10:25   0:00 php examples/signal.php
ruslan    3978  0.0  0.0   9572   864 pts/2    S+   10:26   0:00 grep --color=auto examp
$ kill -TERM 3976

At the first terminal window you should catch the following:

Caught signal 15
*/
class MyEventSignal {
    private $base;

    function __construct($base) {
        $this->base = $base;
    }

    function eventSighandler($no, $c) {
        echo "Caught signal $no\n";
        event_base_loopexit($c->base);
    }
}

$base = event_base_new();
$c    = new MyEventSignal($base);
$no   = SIGTERM;
$ev   = evsignal_new($base, $no, array($c,'eventSighandler'), $c);

evsignal_add($ev);

event_base_loop($base);
?>

Example #6 Use libevent's loop to process requests of `eio' extension

<?php
// Callback for eio_nop()
function my_nop_cb($d, $r) {
    echo "step 6\n";
}

$dir = "/tmp/abc-eio-temp";
if (file_exists($dir)) {
    rmdir($dir);
}

echo "step 1\n";

$base = new EventBase();

echo "step 2\n";

eio_init();

eio_mkdir($dir, 0750, EIO_PRI_DEFAULT, "my_nop_cb");

$event = new Event($base, eio_get_event_stream(),
    Event::READ | Event::PERSIST, function ($fd, $events, $base) {
    echo "step 5\n";

    while (eio_nreqs()) {
        eio_poll();
    }

    $base->stop();
}, $base);

echo "step 3\n";

$event->add();

echo "step 4\n";

$base->dispatch();

echo "Done\n";
?>

Example #7 Miscellaneous

<?php
/* {{{ Config & supported stuff */
echo "Supported methods:\n";
foreach (Event::getSupportedMethods() as $m) {
    echo $m, PHP_EOL;
}

// Avoiding "select" method
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}

// Create event_base associated with the config
$base = new EventBase($cfg);
echo "Event method used: ", $base->getMethod(), PHP_EOL;

echo "Features:\n";
$features = $base->getFeatures();
($features & EventConfig::FEATURE_ET) and print("ET - edge-triggered IO\n");
($features & EventConfig::FEATURE_O1) and print("O1 - O(1) operation for adding/deletting events\n");
($features & EventConfig::FEATURE_FDS) and print("FDS - arbitrary file descriptor types, and not just sockets\n");

// Require FDS feature
if ($cfg->requireFeatures(EventConfig::FEATURE_FDS)) {
    echo "FDS feature is now requried\n";

    $base = new EventBase($cfg);
    ($base->getFeatures() & EventConfig::FEATURE_FDS)
        and print("FDS - arbitrary file descriptor types, and not just sockets\n");
}
/* }}} */

/* {{{ Base */
$base = new EventBase();
$event = new Event($base, STDIN, Event::READ | Event::PERSIST, function ($fd, $events, $arg) {
    static $max_iterations = 0;

    if (++$max_iterations >= 5) {
        /* exit after 5 iterations with timeout of 2.33 seconds */
        echo "Stopping...\n";
        $arg[0]->exit(2.33);
    }

    echo fgets($fd);
}, array (&$base));

$event->add();
$base->loop();
/* Base }}} */
?>

Example #8 Simple HTTP server

<?php
/*
 * Simple HTTP server.
 *
 * To test it:
 * 1) Run it on a port of your choice, e.g.:
 * $ php examples/http.php 8010
 * 2) In another terminal connect to some address on this port
 * and make GET or POST request(others are turned off here), e.g.:
 * $ nc -t 127.0.0.1 8010
 * POST /about HTTP/1.0
 * Content-Type: text/plain
 * Content-Length: 4
 * Connection: close
 * (press Enter)
 *
 * It will output
 * a=12
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * $ nc -t 127.0.0.1 8010
 * GET /dump HTTP/1.0
 * Content-Type: text/plain
 * Content-Encoding: UTF-8
 * Connection: close
 * (press Enter)
 *
 * It will output:
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 * (press Enter)
 *
 * $ nc -t 127.0.0.1 8010
 * GET /unknown HTTP/1.0
 * Connection: close
 *
 * It will output:
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * 3) See what the server outputs on the previous terminal window.
 */

function _http_dump($req, $data) {
    static $counter      = 0;
    static $max_requests = 2;

    if (++$counter >= $max_requests)  {
        echo "Counter reached max requests $max_requests. Exiting\n";
        exit();
    }

    echo __METHOD__, " called\n";
    echo "request:"; var_dump($req);
    echo "data:"; var_dump($data);

    echo "\n===== DUMP =====\n";
    echo "Command:", $req->getCommand(), PHP_EOL;
    echo "URI:", $req->getUri(), PHP_EOL;
    echo "Input headers:"; var_dump($req->getInputHeaders());
    echo "Output headers:"; var_dump($req->getOutputHeaders());

    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";

    echo "\n >> Reading input buffer ...\n";
    $buf = $req->getInputBuffer();
    while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
        echo $s, PHP_EOL;
    }
    echo "No more data in the buffer\n";
}

function _http_about($req) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_default($req, $data) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

$port = 8010;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

Exemplul de mai sus va afi?a ceva similar cu:

a=12
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close
(press Enter)

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

Example #9 Simple HTTPS server

<?php
/*
 * Simple HTTPS server.
 *
 * 1) Run the server: `php examples/https.php 9999`
 * 2) Test it: `php examples/ssl-connection.php 9999`
 */

function _http_dump($req, $data) {
    static $counter      = 0;
    static $max_requests = 200;

    if (++$counter >= $max_requests)  {
        echo "Counter reached max requests $max_requests. Exiting\n";
        exit();
    }

    echo __METHOD__, " called\n";
    echo "request:"; var_dump($req);
    echo "data:"; var_dump($data);

    echo "\n===== DUMP =====\n";
    echo "Command:", $req->getCommand(), PHP_EOL;
    echo "URI:", $req->getUri(), PHP_EOL;
    echo "Input headers:"; var_dump($req->getInputHeaders());
    echo "Output headers:"; var_dump($req->getOutputHeaders());

    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";

    $buf = $req->getInputBuffer();
    echo "\n >> Reading input buffer (", $buf->length, ") ...\n";
    while ($s = $buf->read(1024)) {
        echo $s;
    }
    echo "\nNo more data in the buffer\n";
}

function _http_about($req) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_default($req, $data) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_400($req) {
    $req->sendError(400);
}

function _init_ssl() {
    $local_cert = __DIR__."/ssl-echo-server/cert.pem";
    $local_pk   = __DIR__."/ssl-echo-server/privkey.pem";

    $ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array (
        EventSslContext::OPT_LOCAL_CERT  => $local_cert,
        EventSslContext::OPT_LOCAL_PK    => $local_pk,
        //EventSslContext::OPT_PASSPHRASE  => "test",
        EventSslContext::OPT_ALLOW_SELF_SIGNED => true,
    ));

    return $ctx;
}

$port = 9999;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}
$ip = '0.0.0.0';

$base = new EventBase();
$ctx  = _init_ssl();
$http = new EventHttp($base, $ctx);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setCallback("/err400", "_http_400");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind($ip, $port);
$base->dispatch();

Example #10 OpenSSL connection

<?php
/*
 * Sample OpenSSL client.
 *
 * Usage:
 * 1) Launch a server, e.g.:
 * $ php examples/https.php 9999
 *
 * 2) Launch the client in another terminal:
 * $ php examples/ssl-connection.php 9999
 */

function _request_handler($req, $base) {
    echo __FUNCTION__, PHP_EOL;

    if (is_null($req)) {
        echo "Timed out\n";
    } else {
        $response_code = $req->getResponseCode();

        if ($response_code == 0) {
            echo "Connection refused\n";
        } elseif ($response_code != 200) {
            echo "Unexpected response: $response_code\n";
        } else {
            echo "Success: $response_code\n";
            $buf = $req->getInputBuffer();
            echo "Body:\n";
            while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
                echo $s, PHP_EOL;
            }
        }
    }

    $base->exit(NULL);
}

function _init_ssl() {
    $ctx = new EventSslContext(EventSslContext::SSLv3_CLIENT_METHOD, array ());

    return $ctx;
}

// Allow to override the port
$port = 9999;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port\n");
}
$host = '127.0.0.1';

$ctx = _init_ssl();
if (!$ctx) {
    trigger_error("Failed creating SSL context", E_USER_ERROR);
}

$base = new EventBase();
if (!$base) {
    trigger_error("Failed to initialize event base", E_USER_ERROR);
}

$conn = new EventHttpConnection($base, NULL, $host, $port, $ctx);
$conn->setTimeout(50);

$req = new EventHttpRequest("_request_handler", $base);
$req->addHeader("Host", $host, EventHttpRequest::OUTPUT_HEADER);
$buf = $req->getOutputBuffer();
$buf->add("<html>HTML TEST</html>");
//$req->addHeader("Content-Length", $buf->length, EventHttpRequest::OUTPUT_HEADER);
//$req->addHeader("Connection", "close", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_POST, "/dump");

$base->dispatch();
echo "END\n";
?>

Example #11 EventHttpConnection::makeRequest() example

<?php
function _request_handler($req, $base) {
    echo __FUNCTION__, PHP_EOL;

    if (is_null($req)) {
        echo "Timed out\n";
    } else {
        $response_code = $req->getResponseCode();

        if ($response_code == 0) {
            echo "Connection refused\n";
        } elseif ($response_code != 200) {
            echo "Unexpected response: $response_code\n";
        } else {
            echo "Success: $response_code\n";
            $buf = $req->getInputBuffer();
            echo "Body:\n";
            while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
                echo $s, PHP_EOL;
            }
        }
    }

    $base->exit(NULL);
}

$address = "127.0.0.1";
$port = 80;

$base = new EventBase();
$conn = new EventHttpConnection($base, NULL, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest("_request_handler", $base);

$req->addHeader("Host", $address, EventHttpRequest::OUTPUT_HEADER);
$req->addHeader("Content-Length", "0", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_GET, "/index.cphp");

$base->loop();
?>

Exemplul de mai sus va afi?a ceva similar cu:

_request_handler
Success: 200
Body:
PHP, date:
2013-03-13T20:27:52+05:00

Example #12 Connection listener based on a UNIX domain socket

<?php
/*
 * Simple echo server based on libevent's connection listener.
 *
 * Usage:
 * 1) In one terminal window run:
 *
 * $ php unix-domain-listener.php [path-to-socket]
 *
 * 2) In another terminal window open up connection
 * to the socket, e.g.:
 *
 * $ socat - GOPEN:/tmp/1.sock
 *
 * 3) Start typing. The server should repeat the input.
 */

class MyListenerConnection {
    private $bev, $base;

    public function __destruct() {
        if ($this->bev) {
            $this->bev->free();
        }
    }

    public function __construct($base, $fd) {
        $this->base = $base;

        $this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);

        $this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,
            array($this, "echoEventCallback"), NULL);

        if (!$this->bev->enable(Event::READ)) {
            echo "Failed to enable READ\n";
            return;
        }
    }

    public function echoReadCallback($bev, $ctx) {
        // Copy all the data from the input buffer to the output buffer
        $bev->output->addBuffer($bev->input);
    }

    public function echoEventCallback($bev, $events, $ctx) {
        if ($events & EventBufferEvent::ERROR) {
            echo "Error from bufferevent\n";
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            $bev->free();
            $bev = NULL;
        }
    }
}

class MyListener {
    public $base,
        $listener,
        $socket;
    private $conn = array();

    public function __destruct() {
        foreach ($this->conn as &$c) $c = NULL;
    }

    public function __construct($sock_path) {
        $this->base = new EventBase();
        if (!$this->base) {
            echo "Couldn't open event base";
            exit(1);
        }

        if (file_exists($sock_path)) {
            unlink($sock_path);
        }

         $this->listener = new EventListener($this->base,
             array($this, "acceptConnCallback"), $this->base,
             EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,
             "unix:$sock_path");

        if (!$this->listener) {
            trigger_error("Couldn't create listener", E_USER_ERROR);
        }

        $this->listener->setErrorCallback(array($this, "accept_error_cb"));
    }

    public function dispatch() {
        $this->base->dispatch();
    }

    // This callback is invoked when there is data to read on $bev
    public function acceptConnCallback($listener, $fd, $address, $ctx) {
        // We got a new connection! Set up a bufferevent for it. */
        $base = $this->base;
        $this->conn[] = new MyListenerConnection($base, $fd);
    }

    public function accept_error_cb($listener, $ctx) {
        $base = $this->base;

        fprintf(STDERR, "Got an error %d (%s) on the listener. "
            ."Shutting down.\n",
            EventUtil::getLastSocketErrno(),
            EventUtil::getLastSocketError());

        $base->exit(NULL);
    }
}

if ($argc <= 1) {
    exit("Socket path is not provided\n");
}
$sock_path = $argv[1];

$l = new MyListener($sock_path);
$l->dispatch();
?>

Example #13 Simple SMTP server

<?php
 /*
 * Author: Andrew Rose <hello at andrewrose dot co dot uk>
 *
 * Usage:
 * 1) Prepare cert.pem certificate and privkey.pem private key files.
 * 2) Launch the server script
 * 3) Open TLS connection, e.g.:
 *      $ openssl s_client -connect localhost:25 -starttls smtp -crlf
 * 4) Start testing the commands listed in `cmd` method below.
 */

class Handler {
    public $domainName = FALSE;
    public $connections = [];
    public $buffers = [];
    public $maxRead = 256000;

    public function __construct() {
        $this->ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, [
            EventSslContext::OPT_LOCAL_CERT  => 'cert.pem',
            EventSslContext::OPT_LOCAL_PK    => 'privkey.pem',
            //EventSslContext::OPT_PASSPHRASE  => '',
            EventSslContext::OPT_VERIFY_PEER => false, // change to true with authentic cert
            EventSslContext::OPT_ALLOW_SELF_SIGNED => true // change to false with authentic cert
        ]);

        $this->base = new EventBase();
        if (!$this->base) {
            exit("Couldn't open event base\n");
        }

        if (!$this->listener = new EventListener($this->base,
            [$this, 'ev_accept'],
            $this->ctx,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1,
            '0.0.0.0:25'))
        {
            exit("Couldn't create listener\n");
        }

        $this->listener->setErrorCallback([$this, 'ev_error']);
        $this->base->dispatch();
    }

    public function ev_accept($listener, $fd, $address, $ctx) {
        static $id = 0;
        $id += 1;

        $this->connections[$id]['clientData'] = '';
        $this->connections[$id]['cnx'] = new EventBufferEvent($this->base, $fd,
            EventBufferEvent::OPT_CLOSE_ON_FREE);

        if (!$this->connections[$id]['cnx']) {
            echo "Failed creating buffer\n";
            $this->base->exit(NULL);
            exit(1);
        }

        $this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL,
            [$this, 'ev_error'], $id);
        $this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);

        $this->ev_write($id, '220 '.$this->domainName." wazzzap?\r\n");
    }

    function ev_error($listener, $ctx) {
        $errno = EventUtil::getLastSocketErrno();

        fprintf(STDERR, "Got an error %d (%s) on the listener. Shutting down.\n",
            $errno, EventUtil::getLastSocketError());

        if ($errno != 0) {
            $this->base->exit(NULL);
            exit();
        }
    }

    public function ev_close($id) {
        $this->connections[$id]['cnx']->disable(Event::READ | Event::WRITE);
        unset($this->connections[$id]);
    }

    protected function ev_write($id, $string) {
        echo 'S('.$id.'): '.$string;
        $this->connections[$id]['cnx']->write($string);
    }

    public function ev_read($buffer, $id) {
        while($buffer->input->length > 0) {
            $this->connections[$id]['clientData'] .= $buffer->input->read($this->maxRead);
            $clientDataLen = strlen($this->connections[$id]['clientData']);

            if($this->connections[$id]['clientData'][$clientDataLen-1] == "\n"
                && $this->connections[$id]['clientData'][$clientDataLen-2] == "\r")
            {
                // remove the trailing \r\n
                $line = substr($this->connections[$id]['clientData'], 0,
                    strlen($this->connections[$id]['clientData']) - 2);

                $this->connections[$id]['clientData'] = '';
                $this->cmd($buffer, $id, $line);
            }
        }
    }

    protected function cmd($buffer, $id, $line) {
        switch ($line) {
            case strncmp('EHLO ', $line, 4):
                $this->ev_write($id, "250-STARTTLS\r\n");
                $this->ev_write($id, "250 OK ehlo\r\n");
                break;

            case strncmp('HELO ', $line, 4):
                $this->ev_write($id, "250-STARTTLS\r\n");
                $this->ev_write($id, "250 OK helo\r\n");
                break;

            case strncmp('QUIT', $line, 3):
                $this->ev_write($id, "250 OK quit\r\n");
                $this->ev_close($id);
                break;

            case strncmp('STARTTLS', $line, 3):
                $this->ev_write($id, "220 Ready to start TLS\r\n");
                $this->connections[$id]['cnx'] = EventBufferEvent::sslFilter($this->base,
                    $this->connections[$id]['cnx'], $this->ctx,
                    EventBufferEvent::SSL_ACCEPTING,
                    EventBufferEvent::OPT_CLOSE_ON_FREE);
                $this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL, [$this, 'ev_error'], $id);
                $this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);
                break;

            default:
                echo 'unknown command: '.$line."\n";
                break;
        }
    }
}

new Handler();
Tipurile resurselor
Event flags
Event


Event flags

Event::READ This flag indicates an event that becomes active when the provided file descriptor (usually a stream resource, or socket) is ready for reading.

Event::WRITE flag indicates an event that becomes active when the provided file descriptor (usually a stream resource, or socket) is ready for writing.

Event::SIGNAL used to implement signal detection. See "Constructing signal events" below.

Event::TIMEOUT indicates an event that becomes active after a timeout elapses. The Event::TIMEOUT flag is ignored when constructing an event: one can either set a timeout when event is added , or not. It is set in the $what argument to the callback function when a timeout has occurred.

See also » Fast portable non-blocking network programming with Libevent, Working with events, Event flags

Exemple
About event persistence
Event


About event persistence

By default, whenever a pending event becomes active (because its file descriptor is ready to read or write, or because its timeout expires), it becomes non-pending right before its callback is executed. Thus, to make the event pending again one may call Event::add() on it again from inside the callback function.

If the Event::PERSIST flag is set on an event, however, the event is persistent . This means that event remains pending even when its callback is activated. Event::del() method can be called to make it non-pending.

The timeout on a persistent event resets whenever the event's callback runs. Thus, if one has an event with flags Event::READ | Event::PERSIST and a timeout of five seconds, the event will become active:

  1. Whenever the socket or file descriptor is ready for reading.

  2. Whenever five seconds have passed since the event last became active.

See also » Fast portable non-blocking network programming with Libevent, About Event Persistence

Event flags
Event callbacks
Event


Event callbacks

If a callback is registered for an event, it will be called when the event becomes active. To associate a callback with event one can pass a callable to either Event::__construct() , or Event::set() , or one of the factory methods like Event::timer() .

An event callback should match the following prototype:

void callback ([ mixed $fd = NULL [, int $what [, mixed $arg = NULL ]]] )

fd

The file descriptor, stream resource or socket associated with the event. For signal event fd is equal to the signal number.

what

Bit mask of all events triggered.

arg

User custom data.

Event::timer() expects the callback to match the following prototype:

void callback ([ mixed $arg = NULL ] )

arg

User custom data.

Event::signal() expects the callback to match the following prototype:

void callback ([ int $signum [, mixed $arg = NULL ]] )

signum

The number of the triggered signal(e.g. SIGTERM ).

arg

User custom data.

About event persistence
Constructing signal events
Event


Constructing signal events

Event can also watch for POSIX-style signals. To construct a handler for a signal, use Event::__construct() constructor with Event::SIGNAL flag, or Event::signal() factory method.

Example #1 Handling SIGTERM signal

<?php
/*
Launch it in a terminal window:

$ php examples/signal.php

In another terminal window find out the pid and send SIGTERM, e.g.:

$ ps aux | grep examp
ruslan    3976  0.2  0.0 139896 11256 pts/1    S+   10:25   0:00 php examples/signal.php
ruslan    3978  0.0  0.0   9572   864 pts/2    S+   10:26   0:00 grep --color=auto examp
$ kill -TERM 3976

At the first terminal window you should catch the following:

Caught signal 15
*/
class MyEventSignal {
    private $base, $ev;

    public function __construct($base) {
        $this->base = $base;
        $this->ev = Event::signal($base, SIGTERM, array($this, 'eventSighandler'));
        $this->ev->add();
    }

    public function eventSighandler($no, $c) {
        echo "Caught signal $no\n";
        $this->base->exit();
    }
}

$base = new EventBase();
$c    = new MyEventSignal($base);

$base->loop();
?>

Note that signal callbacks are run in the event loop after the signal occurs, so it is safe for them to call functions that you are not supposed to call from a regular POSIX signal handler.

See also » Fast portable non-blocking network programming with Libevent, Constructing Signal Events .

Event callbacks
Event
Event


The Event class

(PECL event >= 1.2.6-beta)

Introducere

Event class represents and event firing on a file descriptor being ready to read from or write to; a file descriptor becoming ready to read from or write to(edge-triggered I/O only); a timeout expiring; a signal occuring; a user-triggered event.

Every event is associated with EventBase . However, event will never fire until it is added (via Event::add() ). An added event remains in pending state until the registered event occurs, thus turning it to active state. To handle events user may register a callback which is called when event becomes active. If event is configured persistent , it remains pending. If it is not persistent, it stops being pending when it's callback runs. Event::del() method deletes event, thus making it non-pending. By means of Event::add() method it could be added again.

Sinopsisul clasei

final Event {
/* Constants */
const integer ET = 32 ;
const integer PERSIST = 16 ;
const integer READ = 2 ;
const integer WRITE = 4 ;
const integer SIGNAL = 8 ;
const integer TIMEOUT = 1 ;
/* Proprieta?i */
public readonly bool $pending ;
/* Metode */
public bool add ([ double $timeout ] )
public bool addSignal ([ double $timeout ] )
public bool addTimer ([ double $timeout ] )
public __construct ( EventBase $base , mixed $fd , int $what , callable $cb [, mixed $arg = NULL ] )
public bool del ( void )
public bool delSignal ( void )
public bool delTimer ( void )
public void free ( void )
public static array getSupportedMethods ( void )
public bool pending ( int $flags )
public bool set ( EventBase $base , mixed $fd [, int $what [, callable $cb [, mixed $arg ]]] )
public bool setPriority ( int $priority )
public bool setTimer ( EventBase $base , callable $cb [, mixed $arg ] )
public static Event signal ( EventBase $base , int $signum , callable $cb [, mixed $arg ] )
public static Event timer ( EventBase $base , callable $cb [, mixed $arg ] )
}

Proprieta?i

pending

Whether event is pending. See About event persistence .

Constante predefinite

Event::ET

Indicates that the event should be edge-triggered, if the underlying event base backend supports edge-triggered events. This affects the semantics of Event::READ and Event::WRITE .

Event::PERSIST

Indicates that the event is persistent. See About event persistence .

Event::READ

This flag indicates an event that becomes active when the provided file descriptor(usually a stream resource, or socket) is ready for reading.

Event::WRITE

This flag indicates an event that becomes active when the provided file descriptor(usually a stream resource, or socket) is ready for reading.

Event::SIGNAL

Used to implement signal detection. See "Constructing signal events" below.

Event::TIMEOUT

This flag indicates an event that becomes active after a timeout elapses.

The Event::TIMEOUT flag is ignored when constructing an event: one can either set a timeout when event is added , or not. It is set in the $what argument to the callback function when a timeout has occurred.

Cuprins

  • Event::add — Makes event pending
  • Event::addSignal — Makes signal event pending
  • Event::addTimer — Makes timer event pending
  • Event::__construct — Constructs Event object
  • Event::del — Makes event non-pending
  • Event::delSignal — Makes signal event non-pending
  • Event::delTimer — Makes timer event non-pending
  • Event::free — Make event non-pending and free resources allocated for this event.
  • Event::getSupportedMethods — Returns array with of the names of the methods supported in this version of Libevent
  • Event::pending — Detects whether event is pending or scheduled
  • Event::set — Re-configures event
  • Event::setPriority — Set event priority
  • Event::setTimer — Re-configures timer event
  • Event::signal — Constructs signal event object
  • Event::timer — Constructs timer event object
Constructing signal events
Event::add
Event


Makes event pending

Event
Event::addSignal
Event
PHP Manual

Event::add

(PECL libevent >= 0.0.1)

Event::add — Makes event pending

Descrierea

public bool Event::add ([ double $timeout ] )

Marks event pending. Non-pending event will never occur, and the event callback will never be called. In conjuction with Event::del() an event could be re-scheduled by user at any time.

If Event::add() is called on an already pending event, libevent will leave it pending and re-schedule it with the given timeout(if specified). If in this case timeout is not specified, Event::add() has no effect.

Parametri

timeout

Timeout in seconds.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE

A se vedea ?i

  • Event::addSignal() - Makes signal event pending
  • Event::addTimer() - Makes timer event pending
  • Event::del() - Makes event non-pending
Event
Event::addSignal
Event


Makes signal event pending

Event::add
Event::addTimer
Event
PHP Manual

Event::addSignal

(PECL event >= 1.2.6-beta)

Event::addSignal — Makes signal event pending

Descrierea

public bool Event::addSignal ([ double $timeout ] )

Event::addSignal() is an alias of Event::add()

Exemple

Example #1 Event::addSignal() example

<?php
/*
Launch it in a terminal window:

$ php examples/signal.php

In another terminal window find out the pid and send SIGTERM, e.g.:

$ ps aux | grep examp
ruslan    3976  0.2  0.0 139896 11256 pts/1    S+   10:25   0:00 php examples/signal.php
ruslan    3978  0.0  0.0   9572   864 pts/2    S+   10:26   0:00 grep --color=auto examp
$ kill -TERM 3976

At the first terminal window you should catch the following:

Caught signal 15
*/
class MyEventSignal {
    private $base, $ev;

    public function __construct($base) {
        $this->base = $base;
        $this->ev = Event::signal($base, SIGTERM, array($this, 'eventSighandler'));
        $this->ev->addSignal();
    }

    public function eventSighandler($no, $c) {
        echo "Caught signal $no\n";
        $this->base->exit();
    }
}

$base = new EventBase();
$c    = new MyEventSignal($base);

$base->loop();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Caught signal 15

A se vedea ?i

  • Event::add() - Makes event pending
  • Event::del() - Makes event non-pending
  • Event::delSignal() - Makes signal event non-pending
  • Event::signal() - Constructs signal event object
Event::add
Event::addTimer
Event


Makes timer event pending

Event::addSignal
Event::__construct
Event
PHP Manual

Event::addTimer

(PECL event >= 1.2.6-beta)

Event::addTimer — Makes timer event pending

Descrierea

public bool Event::addTimer ([ double $timeout ] )

Event::addTimer() is an alias of Event::add()

Valorile întoarse

Exemple

Example #1 Event::addTimer() example

<?php
$base = new EventBase();
$n = 2;
$e = Event::timer($base, function($n) use (&$e) {
    echo "$n seconds elapsed\n";
    $e->delTimer();
}, $n);
$e->addTimer($n);
$base->loop();
?>

Exemplul de mai sus va afi?a ceva similar cu:

2 seconds elapsed

A se vedea ?i

  • Event::add() - Makes event pending
  • Event::del() - Makes event non-pending
  • Event::delTimer() - Makes timer event non-pending
Event::addSignal
Event::__construct
Event


Constructs Event object

Event::addTimer
Event::del
Event
PHP Manual

Event::__construct

(PECL event >= 1.2.6-beta)

Event::__construct — Constructs Event object

Descrierea

public Event::__construct ( EventBase $base , mixed $fd , int $what , callable $cb [, mixed $arg = NULL ] )

Constructs Event object.

Parametri

base

The event base to associate with.

fd

stream resource, socket resource, or numeric file descriptor. For timer events pass -1 . For signal events pass the signal number, e.g. SIGHUP .

what

Event flags. See Event flags .

cb

The event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

Valorile întoarse

Returns Event object.

A se vedea ?i

  • Event::signal() - Constructs signal event object
  • Event::timer() - Constructs timer event object
Event::addTimer
Event::del
Event


Makes event non-pending

Event::__construct
Event::delSignal
Event
PHP Manual

Event::del

(PECL libevent >= 0.0.1)

Event::del — Makes event non-pending

Descrierea

public bool Event::del ( void )

Removes an event from the set of monitored events, i.e. makes it non-pending.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE

A se vedea ?i

  • Event::add() - Makes event pending
Event::__construct
Event::delSignal
Event


Makes signal event non-pending

Event::del
Event::delTimer
Event
PHP Manual

Event::delSignal

(PECL event >= 1.2.6-beta)

Event::delSignal — Makes signal event non-pending

Descrierea

public bool Event::delSignal ( void )

Event::delSignal() is an alias of Event::del()

A se vedea ?i

  • Event::del() - Makes event non-pending
Event::del
Event::delTimer
Event


Makes timer event non-pending

Event::delSignal
Event::free
Event
PHP Manual

Event::delTimer

(PECL event >= 1.2.6-beta)

Event::delTimer — Makes timer event non-pending

Descrierea

public bool Event::delTimer ( void )

Event::delTimer() is an alias of Event::del() .

A se vedea ?i

  • Event::del() - Makes event non-pending
Event::delSignal
Event::free
Event


Make event non-pending and free resources allocated for this event.

Event::delTimer
Event::getSupportedMethods
Event
PHP Manual

Event::free

(PECL libevent >= 0.0.1)

Event::free — Make event non-pending and free resources allocated for this event.

Descrierea

public void Event::free ( void )

Removes event from the list of events monitored by libevent, and free resources allocated for the event.

Avertizare

The Event::free() method currently doesn't destruct the object itself. To destruct the object completely call unset() , or assign NULL.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • Event::__construct() - Constructs Event object
Event::delTimer
Event::getSupportedMethods
Event


Returns array with of the names of the methods supported in this version of Libevent

Event::free
Event::pending
Event
PHP Manual

Event::getSupportedMethods

(PECL event >= 1.2.6-beta)

Event::getSupportedMethods — Returns array with of the names of the methods supported in this version of Libevent

Descrierea

public static array Event::getSupportedMethods ( void )

Returns array with of the names of the methods(backends) supported in this version of Libevent.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns array.

A se vedea ?i

  • EventConfig
Event::free
Event::pending
Event


Detects whether event is pending or scheduled

Event::getSupportedMethods
Event::set
Event
PHP Manual

Event::pending

(PECL event >= 1.2.6-beta)

Event::pending — Detects whether event is pending or scheduled

Descrierea

public bool Event::pending ( int $flags )

Detects whether event is pending or scheduled

Parametri

flags

One of, or a composition of the following constants: Event::READ , Event::WRITE , Event::TIMEOUT , Event::SIGNAL .

Valorile întoarse

Returns TRUE if event is pending or scheduled. Otherwise FALSE.

Event::getSupportedMethods
Event::set
Event


Re-configures event

Event::pending
Event::setPriority
Event
PHP Manual

Event::set

(PECL libevent >= 0.0.1)

Event::set — Re-configures event

Descrierea

public bool Event::set ( EventBase $base , mixed $fd [, int $what [, callable $cb [, mixed $arg ]]] )

Re-configures event. Note, this function doesn't invoke obsolete libevent's event_set. It calls event_assign instead.

Parametri

base

The event base to associate the event with.

fd

A stream, socket resource, or numeric file descriptor; for signal events pass -1 .

what

See Event flags .

cb

The event callback. See Event callbacks .

arg

Custom data associated with the event. It will be passed to the callback when the event becomes active.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

Event::pending
Event::setPriority
Event


Set event priority

Event::set
Event::setTimer
Event
PHP Manual

Event::setPriority

(PECL event >= 1.2.6-beta)

Event::setPriority — Set event priority

Descrierea

public bool Event::setPriority ( int $priority )

Set event priority.

Parametri

priority

The event priority.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

Event::set
Event::setTimer
Event


Re-configures timer event

Event::setPriority
Event::signal
Event
PHP Manual

Event::setTimer

(PECL event >= 1.2.6-beta)

Event::setTimer — Re-configures timer event

Descrierea

public bool Event::setTimer ( EventBase $base , callable $cb [, mixed $arg ] )

Re-configures timer event. Note, this function doesn't invoke obsolete libevent's event_set . It calls event_assign instead.

Parametri

base

The event base to associate with.

cb

The timer event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • Event::__construct() - Constructs Event object
  • Event::timer() - Constructs timer event object
Event::setPriority
Event::signal
Event


Constructs signal event object

Event::setTimer
Event::timer
Event
PHP Manual

Event::signal

(PECL event >= 1.2.6-beta)

Event::signal — Constructs signal event object

Descrierea

public static Event Event::signal ( EventBase $base , int $signum , callable $cb [, mixed $arg ] )

Constructs signal event object. This is a straightforward method to create a signal event. Note, the generic Event::__construct() method can contruct signal event objects too.

Parametri

base

The associated event base object.

signum

The signal number.

cb

The signal event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

Valorile întoarse

Returns Event object on success. Otherwise FALSE.

A se vedea ?i

  • Constructing signal events
Event::setTimer
Event::timer
Event


Constructs timer event object

Event::signal
EventBase
Event
PHP Manual

Event::timer

(PECL event >= 1.2.6-beta)

Event::timer — Constructs timer event object

Descrierea

public static Event Event::timer ( EventBase $base , callable $cb [, mixed $arg ] )

Constructs timer event object. This is a straightforward method to create a timer event. Note, the generic Event::__construct() method can contruct signal event objects too.

Parametri

base

The associated event base object.

cb

The signal event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

Valorile întoarse

Returns Event object on success. Otherwise FALSE.

Event::signal
EventBase
Event


The EventBase class

(PECL event >= 1.2.6-beta)

Introducere

EventBase class represents libevent's event base structure. It holds a set of events and can poll to determine which events are active.

Each event base has a method , or a backend that it uses to determine which events are ready. The recognized methods are: select , poll , epoll , kqueue , devpoll , evport and win32 .

To configure event base to use, or avoid specific backend EventConfig class can be used.

Avertizare

Do NOT destroy the EventBase object as long as resources of the associated Event objects are not released. Otherwise, it will lead to unpredictable results!

Sinopsisul clasei

final EventBase {
/* Constants */
const integer LOOP_ONCE = 1 ;
const integer LOOP_NONBLOCK = 2 ;
const integer NOLOCK = 1 ;
const integer STARTUP_IOCP = 4 ;
const integer NO_CACHE_TIME = 8 ;
const integer EPOLL_USE_CHANGELIST = 16 ;
/* Metode */
public __construct ([ EventConfig $cfg ] )
public void dispatch ( void )
public bool exit ([ double $timeout ] )
public void free ( void )
public int getFeatures ( void )
public string getMethod ( void )
public double getTimeOfDayCached ( void )
public bool gotExit ( void )
public bool gotStop ( void )
public bool loop ([ int $flags ] )
public bool priorityInit ( int $n_priorities )
public bool reInit ( void )
public bool stop ( void )
}

Constante predefinite

EventBase::LOOP_ONCE

Flag used with EventBase::loop() method which means: "block until libevent has an active event, then exit once all active events have had their callbacks run".

EventBase::LOOP_NONBLOCK

Flag used with EventBase::loop() method which means: "do not block: see which events are ready now, run the callbacks of the highest-priority ones, then exit".

EventBase::NOLOCK

Configuration flag. Do not allocate a lock for the event base, even if we have locking set up".

EventBase::STARTUP_IOCP

Windows-only configuration flag. Enables the IOCP dispatcher at startup.

EventBase::NO_CACHE_TIME

Configuration flag. Instead of checking the current time every time the event loop is ready to run timeout callbacks, check after each timeout callback.

EventBase::EPOLL_USE_CHANGELIST

If we are using the epoll backend, this flag says that it is safe to use Libevent's internal change-list code to batch up adds and deletes in order to try to do as few syscalls as possible.

Setting this flag can make code run faster, but it may trigger a Linux bug: it is not safe to use this flag if one has any fds cloned by dup(), or its variants. Doing so will produce strange and hard-to-diagnose bugs.

This flag can also be activated by settnig the EVENT_EPOLL_USE_CHANGELIST environment variable.

This flag has no effect if one winds up using a backend other than epoll .

Cuprins

  • EventBase::__construct — Constructs EventBase object
  • EventBase::dispatch — Dispatch pending events
  • EventBase::exit — Stop dispatching events
  • EventBase::free — Free resources allocated for this event base
  • EventBase::getFeatures — Returns bitmask of features supported
  • EventBase::getMethod — Returns event method in use
  • EventBase::getTimeOfDayCached — Returns the current event base time
  • EventBase::gotExit — Checks if the event loop was told to exit
  • EventBase::gotStop — Checks if the event loop was told to exit
  • EventBase::loop — Dispatch pending events
  • EventBase::priorityInit — Sets number of priorities per event base
  • EventBase::reInit — Re-initialize event base(after a fork).
  • EventBase::stop — Tells event_base to stop dispatching events
Event::timer
EventBase::__construct
Event


Constructs EventBase object

EventBase
EventBase::dispatch
EventBase
PHP Manual

EventBase::__construct

(PECL event >= 1.2.6-beta)

EventBase::__construct — Constructs EventBase object

Descrierea

public EventBase::__construct ([ EventConfig $cfg ] )

Constructs EventBase object

Parametri

cfg

Optional EventConfig object.

Valorile întoarse

Returns EventBase object.

A se vedea ?i

  • EventConfig
EventBase
EventBase::dispatch
EventBase


Dispatch pending events

EventBase::__construct
EventBase::exit
EventBase
PHP Manual

EventBase::dispatch

(PECL event >= 1.2.6-beta)

EventBase::dispatch — Dispatch pending events

Descrierea

public void EventBase::dispatch ( void )

Wait for events to become active, and run their callbacks. The same as EventBase::loop() with no flags set.

Avertizare

Do NOT destroy the EventBase object as long as resources of the associated Event objects are not released. Otherwise, it will lead to unpredictable results!

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBase::loop() - Dispatch pending events
EventBase::__construct
EventBase::exit
EventBase


Stop dispatching events

EventBase::dispatch
EventBase::free
EventBase
PHP Manual

EventBase::exit

(PECL event >= 1.2.6-beta)

EventBase::exit — Stop dispatching events

Descrierea

public bool EventBase::exit ([ double $timeout ] )

Tells event base to stop optionally after given number of seconds.

Parametri

timeout

Optional number of seconds after which the event base should stop dispatching events.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBase::stop() - Tells event_base to stop dispatching events
EventBase::dispatch
EventBase::free
EventBase


Free resources allocated for this event base

EventBase::exit
EventBase::getFeatures
EventBase
PHP Manual

EventBase::free

(PECL event >= 1.10.0)

EventBase::free — Free resources allocated for this event base

Descrierea

public void EventBase::free ( void )

Deallocates resources allocated by libevent for the EventBase object.

Avertizare

The EventBase::free() method doesn't destruct the object itself. To destruct the object completely call unset() , or assign NULL.

This method does not deallocate or detach any of the events that are currently associated with the EventBase object, or close any of their sockets - beware.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventBase::__construct() - Constructs EventBase object
EventBase::exit
EventBase::getFeatures
EventBase


Returns bitmask of features supported

EventBase::free
EventBase::getMethod
EventBase
PHP Manual

EventBase::getFeatures

(PECL event >= 1.2.6-beta)

EventBase::getFeatures — Returns bitmask of features supported

Descrierea

public int EventBase::getFeatures ( void )

Returns bitmask of features supported.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns integer representing a bitmask of supported features. See EventConfig::FEATURE_* constants .

Exemple

Example #1 EventBase::getFeatures() example

<?php
// Avoiding "select" method
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}

$base = new EventBase($cfg);

echo "Features:\n";
$features = $base->getFeatures();
($features & EventConfig::FEATURE_ET) and print("ET - edge-triggered IO\n");
($features & EventConfig::FEATURE_O1) and print("O1 - O(1) operation for adding/deletting events\n");
($features & EventConfig::FEATURE_FDS) and print("FDS - arbitrary file descriptor types, and not just sockets\n");
?>

A se vedea ?i

  • EventBase::getMethod() - Returns event method in use
  • EventConfig
EventBase::free
EventBase::getMethod
EventBase


Returns event method in use

EventBase::getFeatures
EventBase::getTimeOfDayCached
EventBase
PHP Manual

EventBase::getMethod

(PECL event >= 1.2.6-beta)

EventBase::getMethod — Returns event method in use

Descrierea

public string EventBase::getMethod ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

String representing used event method(backend).

Exemple

Example #1 EventBase::getMethod() example

<?php
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}

// Create event_base associated with the config
$base = new EventBase($cfg);
echo "Event method used: ", $base->getMethod(), PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

`select' method avoided
Event method used: epoll

A se vedea ?i

  • EventBase::getFeatures() - Returns bitmask of features supported
EventBase::getFeatures
EventBase::getTimeOfDayCached
EventBase


Returns the current event base time

EventBase::getMethod
EventBase::gotExit
EventBase
PHP Manual

EventBase::getTimeOfDayCached

(PECL event >= 1.2.6-beta)

EventBase::getTimeOfDayCached — Returns the current event base time

Descrierea

public double EventBase::getTimeOfDayCached ( void )

On success returns the current time(as returned by gettimeofday() ), looking at the cached value in base if possible, and calling gettimeofday() or clock_gettime() as appropriate if there is no cached time.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current event base time. On failure returns NULL.

EventBase::getMethod
EventBase::gotExit
EventBase


Checks if the event loop was told to exit

EventBase::getTimeOfDayCached
EventBase::gotStop
EventBase
PHP Manual

EventBase::gotExit

(PECL event >= 1.2.6-beta)

EventBase::gotExit — Checks if the event loop was told to exit

Descrierea

public bool EventBase::gotExit ( void )

Checks if the event loop was told to exit by EventBase::exit() .

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE, event loop was told to exit by EventBase::exit() . Otherwise FALSE.

A se vedea ?i

  • EventBase::exit() - Stop dispatching events
  • EventBase::stop() - Tells event_base to stop dispatching events
  • EventBase::gotStop() - Checks if the event loop was told to exit
EventBase::getTimeOfDayCached
EventBase::gotStop
EventBase


Checks if the event loop was told to exit

EventBase::gotExit
EventBase::loop
EventBase
PHP Manual

EventBase::gotStop

(PECL event >= 1.2.6-beta)

EventBase::gotStop — Checks if the event loop was told to exit

Descrierea

public bool EventBase::gotStop ( void )

Checks if the event loop was told to exit by EventBase::stop() .

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE, event loop was told to stop by EventBase::stop() . Otherwise FALSE.

A se vedea ?i

  • EventBase::exit() - Stop dispatching events
  • EventBase::stop() - Tells event_base to stop dispatching events
  • EventBase::gotExit() - Checks if the event loop was told to exit
EventBase::gotExit
EventBase::loop
EventBase


Dispatch pending events

EventBase::gotStop
EventBase::priorityInit
EventBase
PHP Manual

EventBase::loop

(PECL event >= 1.2.6-beta)

EventBase::loop — Dispatch pending events

Descrierea

public bool EventBase::loop ([ int $flags ] )

Wait for events to become active, and run their callbacks.

Avertizare

Do NOT destroy the EventBase object as long as resources of the associated Event objects are not released. Otherwise, it will lead to unpredictable results!

Parametri

flags

Optional flags. One of EventBase::LOOP_* constants. See EventBase constants .

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBase::dispatch() - Dispatch pending events
EventBase::gotStop
EventBase::priorityInit
EventBase


Sets number of priorities per event base

EventBase::loop
EventBase::reInit
EventBase
PHP Manual

EventBase::priorityInit

(PECL event >= 1.2.6-beta)

EventBase::priorityInit — Sets number of priorities per event base

Descrierea

public bool EventBase::priorityInit ( int $n_priorities )

Sets number of priorities per event base.

Parametri

n_priorities

The number of priorities per event base.

Valorile întoarse

Returns TRUE on success, otherwise FALSE.

A se vedea ?i

  • Event::setPriority() - Set event priority
EventBase::loop
EventBase::reInit
EventBase


Re-initialize event base(after a fork).

EventBase::priorityInit
EventBase::stop
EventBase
PHP Manual

EventBase::reInit

(PECL event >= 1.2.6-beta)

EventBase::reInit — Re-initialize event base(after a fork).

Descrierea

public bool EventBase::reInit ( void )

Re-initialize event base. Should be called after a fork.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

EventBase::priorityInit
EventBase::stop
EventBase


Tells event_base to stop dispatching events

EventBase::reInit
EventBuffer
EventBase
PHP Manual

EventBase::stop

(PECL event >= 1.2.6-beta)

EventBase::stop — Tells event_base to stop dispatching events

Descrierea

public bool EventBase::stop ( void )

Tells event_base to stop dispatching events

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBase::exit() - Stop dispatching events
  • EventBase::gotStop() - Checks if the event loop was told to exit
EventBase::reInit
EventBuffer
EventBase


The EventBuffer class

(PECL event >= 1.5.0)

Introducere

EventBuffer represents Libevent's "evbuffer", an utility functionality for buffered I/O.

Event buffers are meant to be generally useful for doing the "buffer" part of buffered network I/O.

Sinopsisul clasei

EventBuffer {
/* Constants */
const integer EOL_ANY = 0 ;
const integer EOL_CRLF = 1 ;
const integer EOL_CRLF_STRICT = 2 ;
const integer EOL_LF = 3 ;
const integer PTR_SET = 0 ;
const integer PTR_ADD = 1 ;
/* Proprieta?i */
public readonly int $length ;
public readonly int $contiguous_space ;
/* Metode */
public bool add ( string $data )
public bool addBuffer ( EventBuffer $buf )
public int appendFrom ( EventBuffer $buf , int $len )
public __construct ( void )
public int copyout ( string &$data , int $max_bytes )
public bool drain ( int $len )
public void enableLocking ( void )
public bool expand ( int $len )
public bool freeze ( bool $at_front )
public void lock ( void )
public bool prepend ( string $data )
public bool prependBuffer ( EventBuffer $buf )
public string pullup ( int $size )
public string read ( int $max_bytes )
public int read ( mixed $fd , int $howmuch )
public string readLine ( int $eol_style )
public mixed search ( string $what [, int $start = -1 [, int $end = -1 ]] )
public mixed searchEol ([ int $start = -1 [, int $eol_style = EventBuffer::EOL_ANY ]] )
public string substr ( int $start [, int $length ] )
public bool unfreeze ( bool $at_front )
public bool unlock ( void )
public int write ( mixed $fd [, int $howmuch ] )
}

Proprieta?i

length

The number of bytes stored in an event buffer.

contiguous_space

The number of bytes stored contiguously at the front of the buffer. The bytes in a buffer may be stored in multiple separate chunks of memory; the property returns the number of bytes currently stored in the first chunk.

Constante predefinite

EventBuffer::EOL_ANY

The end of line is any sequence of any number of carriage return and linefeed characters. This format is not very useful; it exists mainly for backward compatibility.

EventBuffer::EOL_CRLF

The end of the line is an optional carriage return, followed by a linefeed. (In other words, it is either a "\r\n" or a "\n" .) This format is useful in parsing text-based Internet protocols, since the standards generally prescribe a "\r\n" line-terminator, but nonconformant clients sometimes say just "\n" .

EventBuffer::EOL_CRLF_STRICT

The end of a line is a single carriage return, followed by a single linefeed. (This is also known as "\r\n" . The ASCII values are 0x0D 0x0A ).

EventBuffer::EOL_LF

The end of a line is a single linefeed character. (This is also known as "\n" . It is ASCII value is 0x0A .)

EventBuffer::PTR_SET

Flag used as argument of EventBuffer::setPosition() method. If this flag specified, the position pointer is moved to an absolute position within the buffer.

EventBuffer::PTR_ADD

The same as EventBuffer::PTR_SET , except this flag causes EventBuffer::setPosition() method to move position forward up to the specified number of bytes(instead of setting absolute position).

Cuprins

  • EventBuffer::add — Append data to the end of an event buffer
  • EventBuffer::addBuffer — Move all data from a buffer provided to the current instance of EventBuffer
  • EventBuffer::appendFrom — Moves the specified number of bytes from a source buffer to the end of the current buffer
  • EventBuffer::__construct — Constructs EventBuffer object
  • EventBuffer::copyout — Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain — Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::enableLocking — Descrierea
  • EventBuffer::expand — Reserves space in buffer
  • EventBuffer::freeze — Prevent calls that modify an event buffer from succeeding
  • EventBuffer::lock — Acquires a lock on buffer
  • EventBuffer::prepend — Prepend data to the front of the buffer
  • EventBuffer::prependBuffer — Moves all data from source buffer to the front of current buffer
  • EventBuffer::pullup — Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::read — Read data from an evbuffer and drain the bytes read
  • EventBuffer::readFrom — Read data from a file onto the end of the buffer
  • EventBuffer::readLine — Extracts a line from the front of the buffer
  • EventBuffer::search — Scans the buffer for an occurrence of a string
  • EventBuffer::searchEol — Scans the buffer for an occurrence of an end of line
  • EventBuffer::substr — Substracts a portion of the buffer data
  • EventBuffer::unfreeze — Re-enable calls that modify an event buffer
  • EventBuffer::unlock — Releases lock acquired by EventBuffer::lock
  • EventBuffer::write — Write contents of the buffer to a file or socket
EventBase::stop
EventBuffer::add
Event


Append data to the end of an event buffer

EventBuffer
EventBuffer::addBuffer
EventBuffer
PHP Manual

EventBuffer::add

(PECL event >= 1.2.6-beta)

EventBuffer::add — Append data to the end of an event buffer

Descrierea

public bool EventBuffer::add ( string $data )

Append data to the end of an event buffer.

Parametri

data

String to be appended to the end of the buffer.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBuffer::addBuffer() - Move all data from a buffer provided to the current instance of EventBuffer
EventBuffer
EventBuffer::addBuffer
EventBuffer


Move all data from a buffer provided to the current instance of EventBuffer

EventBuffer::add
EventBuffer::appendFrom
EventBuffer
PHP Manual

EventBuffer::addBuffer

(PECL event >= 1.2.6-beta)

EventBuffer::addBuffer — Move all data from a buffer provided to the current instance of EventBuffer

Descrierea

public bool EventBuffer::addBuffer ( EventBuffer $buf )

Move all data from the buffer provided in buf parameter to the end of current EventBuffer . This is a destructive add. The data from one buffer moves into the other buffer. However, no unnecessary memory copies occur.

Parametri

buf

The source EventBuffer object.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBuffer::add() - Append data to the end of an event buffer
EventBuffer::add
EventBuffer::appendFrom
EventBuffer


Moves the specified number of bytes from a source buffer to the end of the current buffer

EventBuffer::addBuffer
EventBuffer::__construct
EventBuffer
PHP Manual

EventBuffer::appendFrom

(PECL event >= 1.6.0)

EventBuffer::appendFrom — Moves the specified number of bytes from a source buffer to the end of the current buffer

Descrierea

public int EventBuffer::appendFrom ( EventBuffer $buf , int $len )

Moves the specified number of bytes from a source buffer to the end of the current buffer. If there are fewer number of bytes, it moves all the bytes available from the source buffer.

Parametri

buf

Source buffer.

len

Valorile întoarse

Returns the number of bytes read.

Istoricul schimbarilor

Versiune | Descriere
1.6.0 | Renamed EventBuffer::appendFrom()(the old method name) to EventBuffer::appendFrom().

A se vedea ?i

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
EventBuffer::addBuffer
EventBuffer::__construct
EventBuffer


Constructs EventBuffer object

EventBuffer::appendFrom
EventBuffer::copyout
EventBuffer
PHP Manual

EventBuffer::__construct

(PECL event >= 1.2.6-beta)

EventBuffer::__construct — Constructs EventBuffer object

Descrierea

public EventBuffer::__construct ( void )

Constructs EventBuffer object

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns EventBuffer object.

EventBuffer::appendFrom
EventBuffer::copyout
EventBuffer


Copies out specified number of bytes from the front of the buffer

EventBuffer::__construct
EventBuffer::drain
EventBuffer
PHP Manual

EventBuffer::copyout

(PECL event >= 1.2.6-beta)

EventBuffer::copyout — Copies out specified number of bytes from the front of the buffer

Descrierea

public int EventBuffer::copyout ( string &$data , int $max_bytes )

Behaves just like EventBuffer::read() , but does not drain any data from the buffer. I.e. it copies the first max_bytes bytes from the front of the buffer into data . If there are fewer than max_bytes bytes available, the function copies all the bytes there are.

Parametri

data

Output string.

max_bytes

The number of bytes to copy.

Valorile întoarse

Returns the number of bytes copied, or -1 on failure.

A se vedea ?i

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer
EventBuffer::__construct
EventBuffer::drain
EventBuffer


Removes specified number of bytes from the front of the buffer without copying it anywhere

EventBuffer::copyout
EventBuffer::enableLocking
EventBuffer
PHP Manual

EventBuffer::drain

(PECL event >= 1.2.6-beta)

EventBuffer::drain — Removes specified number of bytes from the front of the buffer without copying it anywhere

Descrierea

public bool EventBuffer::drain ( int $len )

Behaves as EventBuffer::read() , except that it does not copy the data: it just removes it from the front of the buffer.

Parametri

len

The number of bytes to remove from the buffer.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer
EventBuffer::copyout
EventBuffer::enableLocking
EventBuffer


EventBuffer::drain
EventBuffer::expand
EventBuffer
PHP Manual

EventBuffer::enableLocking

(PECL event >= 1.2.6-beta)

EventBuffer::enableLocking —

Descrierea

public void EventBuffer::enableLocking ( void )

Enable locking on an EventBuffer so that it can safely be used by multiple threads at the same time. When locking is enabled, the lock will be held when callbacks are invoked. This could result in deadlock if you aren't careful. Plan accordingly!

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • » Evbuffers and Thread-safety
EventBuffer::drain
EventBuffer::expand
EventBuffer


Reserves space in buffer

EventBuffer::enableLocking
EventBuffer::freeze
EventBuffer
PHP Manual

EventBuffer::expand

(PECL event >= 1.2.6-beta)

EventBuffer::expand — Reserves space in buffer

Descrierea

public bool EventBuffer::expand ( int $len )

Alters the last chunk of memory in the buffer, or adds a new chunk, such that the buffer is now large enough to contain len bytes without any further allocations.

Parametri

len

The number of bytes to reserve for the buffer

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

EventBuffer::enableLocking
EventBuffer::freeze
EventBuffer


Prevent calls that modify an event buffer from succeeding

EventBuffer::expand
EventBuffer::lock
EventBuffer
PHP Manual

EventBuffer::freeze

(PECL event >= 1.2.6-beta)

EventBuffer::freeze — Prevent calls that modify an event buffer from succeeding

Descrierea

public bool EventBuffer::freeze ( bool $at_front )

Prevent calls that modify an event buffer from succeeding

Parametri

at_front

Whether to disable changes to the front or end of the buffer.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBuffer::unfreeze() - Re-enable calls that modify an event buffer
EventBuffer::expand
EventBuffer::lock
EventBuffer


Acquires a lock on buffer

EventBuffer::freeze
EventBuffer::prepend
EventBuffer
PHP Manual

EventBuffer::lock

(PECL event >= 1.2.6-beta)

EventBuffer::lock — Acquires a lock on buffer

Descrierea

public void EventBuffer::lock ( void )

Acquires a lock on buffer. Can be used in pair with EventBuffer::unlock() to make a set of operations atomic, i.e. thread-safe. Note, it is not needed to lock buffers for individual operations. When locking is enabled(see EventBuffer::enableLocking() ), individual operations on event buffers are already atomic.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventBuffer::unlock() - Releases lock acquired by EventBuffer::lock
EventBuffer::freeze
EventBuffer::prepend
EventBuffer


Prepend data to the front of the buffer

EventBuffer::lock
EventBuffer::prependBuffer
EventBuffer
PHP Manual

EventBuffer::prepend

(PECL event >= 1.2.6-beta)

EventBuffer::prepend — Prepend data to the front of the buffer

Descrierea

public bool EventBuffer::prepend ( string $data )

Prepend data to the front of the buffer.

Parametri

data

String to be prepended to the front of the buffer.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBuffer::prependBuffer() - Moves all data from source buffer to the front of current buffer
  • EventBuffer::add() - Append data to the end of an event buffer
  • EventBuffer::addBuffer() - Move all data from a buffer provided to the current instance of EventBuffer
EventBuffer::lock
EventBuffer::prependBuffer
EventBuffer


Moves all data from source buffer to the front of current buffer

EventBuffer::prepend
EventBuffer::pullup
EventBuffer
PHP Manual

EventBuffer::prependBuffer

(PECL event >= 1.2.6-beta)

EventBuffer::prependBuffer — Moves all data from source buffer to the front of current buffer

Descrierea

public bool EventBuffer::prependBuffer ( EventBuffer $buf )

Behaves as EventBuffer::addBuffer() , except that it moves data to the front of the buffer.

Parametri

buf

Source buffer.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBuffer::add() - Append data to the end of an event buffer
  • EventBuffer::addBuffer() - Move all data from a buffer provided to the current instance of EventBuffer
  • EventBuffer::prepend() - Prepend data to the front of the buffer
EventBuffer::prepend
EventBuffer::pullup
EventBuffer


Linearizes data within buffer and returns it's contents as a string

EventBuffer::prependBuffer
EventBuffer::read
EventBuffer
PHP Manual

EventBuffer::pullup

(PECL event >= 1.2.6-beta)

EventBuffer::pullup — Linearizes data within buffer and returns it's contents as a string

Descrierea

public string EventBuffer::pullup ( int $size )

"Linearizes" the first size bytes of the buffer, copying or moving them as needed to ensure that they are all contiguous and occupying the same chunk of memory. If size is negative, the function linearizes the entire buffer.

Avertizare

Calling EventBuffer::pullup() with a large size can be quite slow, since it potentially needs to copy the entire buffer's contents.

Parametri

size

The number of bytes required to be contiguous within the buffer.

Valorile întoarse

If size is greater than the number of bytes in the buffer, the function returns NULL. Otherwise, EventBuffer::pullup() returns string.

A se vedea ?i

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer
EventBuffer::prependBuffer
EventBuffer::read
EventBuffer


Read data from an evbuffer and drain the bytes read

EventBuffer::pullup
EventBuffer::readFrom
EventBuffer
PHP Manual

EventBuffer::read

(PECL event >= 1.6.0)

EventBuffer::read — Read data from an evbuffer and drain the bytes read

Descrierea

public string EventBuffer::read ( int $max_bytes )

Read the first max_bytes from the buffer and drain the bytes read. If more max_bytes are requested than are available in the buffer, it only extracts as many bytes as available.

Parametri

max_bytes

Maxmimum number of bytes to read from the buffer.

Valorile întoarse

Returns string read, or FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
1.6.0 | Renamed EventBuffer::read()(the old method name) to EventBuffer::read(). EventBuffer::read() now takes only max_bytes argument; returns string instead of integer.

A se vedea ?i

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer
EventBuffer::pullup
EventBuffer::readFrom
EventBuffer


Read data from a file onto the end of the buffer

EventBuffer::read
EventBuffer::readLine
EventBuffer
PHP Manual

EventBuffer::readFrom

(PECL event >= 1.7.0)

EventBuffer::readFrom — Read data from a file onto the end of the buffer

Descrierea

public int EventBuffer::read ( mixed $fd , int $howmuch )

Read data from the file specified by fd onto the end of the buffer.

Parametri

fd

Socket resource, stream, or numeric file descriptor.

howmuch

Maxmimum number of bytes to read.

Valorile întoarse

Returns the number of bytes read, or FALSE on failure.

A se vedea ?i

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer
EventBuffer::read
EventBuffer::readLine
EventBuffer


Extracts a line from the front of the buffer

EventBuffer::readFrom
EventBuffer::search
EventBuffer
PHP Manual

EventBuffer::readLine

(PECL event >= 1.2.6-beta)

EventBuffer::readLine — Extracts a line from the front of the buffer

Descrierea

public string EventBuffer::readLine ( int $eol_style )

Extracts a line from the front of the buffer and returns it in a newly allocated string. If there is not a whole line to read, the function returns NULL. The line terminator is not included in the copied string.

Parametri

eol_style

One of EventBuffer:EOL_* constants .

Valorile întoarse

On success returns the line read from the buffer, otherwise NULL.

A se vedea ?i

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer
EventBuffer::readFrom
EventBuffer::search
EventBuffer


Scans the buffer for an occurrence of a string

EventBuffer::readLine
EventBuffer::searchEol
EventBuffer
PHP Manual

EventBuffer::search

(PECL event >= 1.2.6-beta)

EventBuffer::search — Scans the buffer for an occurrence of a string

Descrierea

public mixed EventBuffer::search ( string $what [, int $start = -1 [, int $end = -1 ]] )

Scans the buffer for an occurrence of the string what . It returns numeric position of the string, or FALSE if the string was not found.

If the start argument is provided, it points to the position at which the search should begin; otherwise, the search is performed from the start of the string. If end argument provided, the search is performed between start and end buffer positions.

Parametri

what

String to search.

start

Start search position.

end

End search position.

Valorile întoarse

Returns numeric position of the first occurance of the string in the buffer, or FALSE if string is not found.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Exemple

Example #1 EventBuffer::search() example

<?php
// Count total occurances of 'str' in 'buf'
function count_instances($buf, $str) {
    $total = 0;
    $p     = 0;
    $i     = 0;

    while (1) {
        $p = $buf->search($str, $p);
        if ($p === FALSE) {
            break;
        }
        ++$total;
        ++$p;
    }

    return $total;
}

$buf = new EventBuffer();
$buf->add("Some string within a string inside another string");
var_dump(count_instances($buf, "str"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)

A se vedea ?i

  • EventBuffer::searchEol() - Scans the buffer for an occurrence of an end of line
EventBuffer::readLine
EventBuffer::searchEol
EventBuffer


Scans the buffer for an occurrence of an end of line

EventBuffer::search
EventBuffer::substr
EventBuffer
PHP Manual

EventBuffer::searchEol

(PECL event >= 1.5.0)

EventBuffer::searchEol — Scans the buffer for an occurrence of an end of line

Descrierea

public mixed EventBuffer::searchEol ([ int $start = -1 [, int $eol_style = EventBuffer::EOL_ANY ]] )

Scans the buffer for an occurrence of an end of line specified by eol_style parameter . It returns numeric position of the string, or FALSE if the string was not found.

If the start argument is provided, it represents the position at which the search should begin; otherwise, the search is performed from the start of the string. If end argument provided, the search is performed between start and end buffer positions.

Parametri

start

Start search position.

eol_style

One of EventBuffer:EOL_* constants .

Valorile întoarse

Returns numeric position of the first occurance of end-of-line symbol in the buffer, or FALSE if not found.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

A se vedea ?i

  • EventBuffer::search() - Scans the buffer for an occurrence of a string
EventBuffer::search
EventBuffer::substr
EventBuffer


Substracts a portion of the buffer data

EventBuffer::searchEol
EventBuffer::unfreeze
EventBuffer
PHP Manual

EventBuffer::substr

(PECL event >= 1.6.0)

EventBuffer::substr — Substracts a portion of the buffer data

Descrierea

public string EventBuffer::substr ( int $start [, int $length ] )

Substracts up to length bytes of the buffer data beginning at start position.

Parametri

start

The start position of data to be substracted.

length

Maximum number of bytes to substract.

Valorile întoarse

Returns the data substracted as a string on success, or FALSE on failure.

A se vedea ?i

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
EventBuffer::searchEol
EventBuffer::unfreeze
EventBuffer


Re-enable calls that modify an event buffer

EventBuffer::substr
EventBuffer::unlock
EventBuffer
PHP Manual

EventBuffer::unfreeze

(PECL event >= 1.2.6-beta)

EventBuffer::unfreeze — Re-enable calls that modify an event buffer

Descrierea

public bool EventBuffer::unfreeze ( bool $at_front )

Re-enable calls that modify an event buffer.

Parametri

at_front

Whether to enable events at the front or at the end of the buffer.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBuffer::freeze() - Prevent calls that modify an event buffer from succeeding
EventBuffer::substr
EventBuffer::unlock
EventBuffer


Releases lock acquired by EventBuffer::lock

EventBuffer::unfreeze
EventBuffer::write
EventBuffer
PHP Manual

EventBuffer::unlock

(PECL event >= 1.2.6-beta)

EventBuffer::unlock — Releases lock acquired by EventBuffer::lock

Descrierea

public bool EventBuffer::unlock ( void )

Releases lock acquired by EventBuffer::lock() .

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBuffer::lock() - Acquires a lock on buffer
EventBuffer::unfreeze
EventBuffer::write
EventBuffer


Write contents of the buffer to a file or socket

EventBuffer::unlock
EventBufferEvent
EventBuffer
PHP Manual

EventBuffer::write

(PECL event >= 1.6.0)

EventBuffer::write — Write contents of the buffer to a file or socket

Descrierea

public int EventBuffer::write ( mixed $fd [, int $howmuch ] )

Write contents of the buffer to a file descriptor. The buffer will be drained after the bytes have been successfully written.

Parametri

fd

Socket resource, stream or numeric file descriptor associated normally associated with a socket.

howmuch

The maximum number of bytes to write.

Valorile întoarse

Returns the number of bytes written, or FALSE on error.

A se vedea ?i

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
EventBuffer::unlock
EventBufferEvent
EventBuffer


The EventBufferEvent class

(PECL event >= 1.2.6-beta)

Introducere

Represents Libevent's buffer event.

Usually an application wants to perform some amount of data buffering in addition to just responding to events. When we want to write data, for example, the usual pattern looks like:

  1. Decide that we want to write some data to a connection; put that data in a buffer.

  2. Wait for the connection to become writable

  3. Write as much of the data as we can

  4. Remember how much we wrote, and if we still have more data to write, wait for the connection to become writable again.

This buffered I/O pattern is common enough that Libevent provides a generic mechanism for it. A "buffer event" consists of an underlying transport (like a socket), a read buffer, and a write buffer. Instead of regular events, which give callbacks when the underlying transport is ready to be read or written, a buffer event invokes its user-supplied callbacks when it has read or written enough data.

Sinopsisul clasei

final EventBufferEvent {
/* Constants */
const integer READING = 1 ;
const integer WRITING = 2 ;
const integer EOF = 16 ;
const integer ERROR = 32 ;
const integer TIMEOUT = 64 ;
const integer CONNECTED = 128 ;
const integer OPT_CLOSE_ON_FREE = 1 ;
const integer OPT_THREADSAFE = 2 ;
const integer OPT_DEFER_CALLBACKS = 4 ;
const integer OPT_UNLOCK_CALLBACKS = 8 ;
const integer SSL_OPEN = 0 ;
const integer SSL_CONNECTING = 1 ;
const integer SSL_ACCEPTING = 2 ;
/* Proprieta?i */
public integer $fd ;
public integer $priority ;
public readonly EventBuffer $input ;
public readonly EventBuffer $output ;
/* Metode */
public void close ( void )
public bool connect ( string $addr )
public bool connectHost ( EventDnsBase $dns_base , string $hostname , int $port [, int $family = EventUtil::AF_UNSPEC ] )
public __construct ( EventBase $base [, mixed $socket = NULL [, int $options = 0 [, callable $readcb = NULL [, callable $writecb = NULL [, callable $eventcb = NULL ]]]]] )
public static array createPair ( EventBase $base [, int $options = 0 ] )
public bool disable ( int $events )
public bool enable ( int $events )
public void free ( void )
public string getDnsErrorString ( void )
public int getEnabled ( void )
public EventBuffer getInput ( void )
public EventBuffer getOutput ( void )
public string read ( int $size )
public bool readBuffer ( EventBuffer $buf )
public void setCallbacks ( callable $readcb , callable $writecb , callable $eventcb [, string $arg ] )
public bool setPriority ( int $priority )
public bool setTimeouts ( float $timeout_read , float $timeout_write )
public void setWatermark ( int $events , int $lowmark , int $highmark )
public string sslError ( void )
public static EventBufferEvent sslFilter ( EventBase $base , EventBufferEvent $underlying , EventSslContext $ctx , int $state [, int $options = 0 ] )
public string sslGetCipherInfo ( void )
public string sslGetCipherName ( void )
public string sslGetCipherVersion ( void )
public string sslGetProtocol ( void )
public void sslRenegotiate ( void )
public static EventBufferEvent sslSocket ( EventBase $base , mixed $socket , EventSslContext $ctx , int $state [, int $options ] )
public bool write ( string $data )
public bool writeBuffer ( EventBuffer $buf )
}

Proprieta?i

fd

Numeric file descriptor associated with the buffer event. Normally represents a bound socket. Equals to NULL, if there is no file descriptor(socket) associated with the buffer event.

priority

The priority of the events used to implement the buffer event.

input

Underlying input buffer object( EventBuffer )

output

Underlying output buffer object( EventBuffer )

Constante predefinite

EventBufferEvent::READING

An event occured during a read operation on the bufferevent. See the other flags for which event it was.

EventBufferEvent::WRITING

An event occured during a write operation on the bufferevent. See the other flags for which event it was.

EventBufferEvent::EOF

Got an end-of-file indication on the buffer event.

EventBufferEvent::ERROR

An error occurred during a bufferevent operation. For more information on what the error was, call EventUtil::getLastSocketErrno() and/or EventUtil::getLastSocketError() .

EventBufferEvent::TIMEOUT

EventBufferEvent::CONNECTED

Finished a requested connection on the bufferevent.

EventBufferEvent::OPT_CLOSE_ON_FREE

When the buffer event is freed, close the underlying transport. This will close an underlying socket, free an underlying buffer event, etc.

EventBufferEvent::OPT_THREADSAFE

Automatically allocate locks for the bufferevent, so that it’s safe to use from multiple threads.

EventBufferEvent::OPT_DEFER_CALLBACKS

When this flag is set, the bufferevent defers all of its callbacks. See » Fast portable non-blocking network programming with Libevent, Deferred callbacks .

EventBufferEvent::OPT_UNLOCK_CALLBACKS

By default, when the bufferevent is set up to be threadsafe, the buffer event’s locks are held whenever the any user-provided callback is invoked. Setting this option makes Libevent release the buffer event’s lock when it’s invoking the callbacks.

EventBufferEvent::SSL_OPEN

The SSL handshake is done

EventBufferEvent::SSL_CONNECTING

SSL is currently performing negotiation as a client

EventBufferEvent::SSL_ACCEPTING

SSL is currently performing negotiation as a server

Cuprins

  • EventBufferEvent::close — Closes file descriptor associated with the current buffer event
  • EventBufferEvent::connect — Connect buffer event's file descriptor to given address or UNIX socket
  • EventBufferEvent::connectHost — Connects to a hostname with optionally asyncronous DNS resolving
  • EventBufferEvent::__construct — Constructs EventBufferEvent object
  • EventBufferEvent::createPair — Creates two buffer events connected to each other
  • EventBufferEvent::disable — Disable events read, write, or both on a buffer event.
  • EventBufferEvent::enable — Enable events read, write, or both on a buffer event.
  • EventBufferEvent::free — Free a buffer event
  • EventBufferEvent::getDnsErrorString — Returns string describing the last failed DNS lookup attempt
  • EventBufferEvent::getEnabled — Returns bitmask of events currently enabled on the buffer event
  • EventBufferEvent::getInput — Returns underlying input buffer associated with current buffer event
  • EventBufferEvent::getOutput — Returns underlying output buffer associated with current buffer event
  • EventBufferEvent::read — Read buffer's data
  • EventBufferEvent::readBuffer — Drains the entire contents of the input buffer and places them into buf
  • EventBufferEvent::setCallbacks — Assigns read, write and event(status) callbacks
  • EventBufferEvent::setPriority — Assign a priority to a bufferevent
  • EventBufferEvent::setTimeouts — Set the read and write timeout for a buffer event
  • EventBufferEvent::setWatermark — Adjusts read and/or write watermarks
  • EventBufferEvent::sslError — Returns most recent OpenSSL error reported on the buffer event
  • EventBufferEvent::sslFilter — Create a new SSL buffer event to send its data over another buffer event
  • EventBufferEvent::sslGetCipherInfo — Returns a textual description of the cipher.
  • EventBufferEvent::sslGetCipherName — Returns the current cipher name of the SSL connection.
  • EventBufferEvent::sslGetCipherVersion — Returns version of cipher used by current SSL connection.
  • EventBufferEvent::sslGetProtocol — Returns the name of the protocol used for current SSL connection.
  • EventBufferEvent::sslRenegotiate — Tells a bufferevent to begin SSL renegotiation.
  • EventBufferEvent::sslSocket — Creates a new SSL buffer event to send its data over an SSL on a socket
  • EventBufferEvent::write — Adds data to a buffer event's output buffer
  • EventBufferEvent::writeBuffer — Adds contents of the entire buffer to a buffer event's output buffer
EventBuffer::write
EventBufferEvent::close
Event


Closes file descriptor associated with the current buffer event

EventBufferEvent
EventBufferEvent::connect
EventBufferEvent
PHP Manual

EventBufferEvent::close

(PECL event >= 1.10.0)

EventBufferEvent::close — Closes file descriptor associated with the current buffer event

Descrierea

public void EventBufferEvent::close ( void )

Closes file descriptor associated with the current buffer event.

This method may be used in cases when the EventBufferEvent::OPT_CLOSE_ON_FREE option is not appropriate.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventBufferEvent
EventBufferEvent::connect
EventBufferEvent


Connect buffer event's file descriptor to given address or UNIX socket

EventBufferEvent::close
EventBufferEvent::connectHost
EventBufferEvent
PHP Manual

EventBufferEvent::connect

(PECL event >= 1.2.6-beta)

EventBufferEvent::connect — Connect buffer event's file descriptor to given address or UNIX socket

Descrierea

public bool EventBufferEvent::connect ( string $addr )

Connect buffer event's file descriptor to given address(optionally with port), or a UNIX domain socket.

If socket is not assigned to the buffer event, this function allocates a new socket and makes it non-blocking internally.

To resolve DNS names(asyncronously), use EventBufferEvent::connectHost() method.

Parametri

addr

Should contain an IP address with optional port number, or a path to UNIX domain socket. Recognized formats are:

[IPv6Address]:port
[IPv6Address]
IPv6Address
IPv4Address:port
IPv4Address
unix:path
Note, 'unix:' prefix is currently not case sensitive.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

Exemple

Example #1 EventBufferEvent::connect() example

<?php
/*
 * 1. Connect to 127.0.0.1 at port 80
 * by means of EventBufferEvent::connect().
 *
 * 2. Request /index.cphp via HTTP/1.0
 * using the output buffer.
 *
 * 3. Asyncronously read the response and print it to stdout.
 */

/* Read callback */
function readcb($bev, $base) {
    $input = $bev->getInput();

    while (($n = $input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}

/* Event callback */
function eventcb($bev, $events, $base) {
    if ($events & EventBufferEvent::CONNECTED) {
        echo "Connected.\n";
    } elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
        if ($events & EventBufferEvent::ERROR) {
            echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
        }

        echo "Closing\n";
        $base->exit();
        exit("Done\n");
    }
}

$base = new EventBase();

echo "step 1\n";
$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

echo "step 2\n";
$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

echo "step 3\n";
/* Send request */
$output = $bev->getOutput();
if (!$output->add(
    "GET /index.cphp HTTP/1.0\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

/* Connect to the host syncronously.
 * We know the IP, and don't need to resolve DNS. */
if (!$bev->connect("127.0.0.1:80")) {
    exit("Can't connect to host\n");
}

/* Dispatch pending events */
$base->dispatch();

Exemplul de mai sus va afi?a ceva similar cu:

step 1
step 2
step 3
Connected.
HTTP/1.1 200 OK
Server: nginx/1.2.6
Date: Sat, 09 Mar 2013 10:06:58 GMT
Content-Type: text/html; CHARSET=Windows-1252
Connection: close
X-Powered-By: PHP/5.4.11--pl2-gentoo

sdfsdfsf
Closing
Done

Example #2 Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console

<?php
class MyUnixSocketClient {
    private $base, $bev;

    function __construct($base, $sock_path) {
        $this->base = $base;
        $this->bev = new EventBufferEvent($base, NULL, EventBufferEvent::OPT_CLOSE_ON_FREE,
            array ($this, "read_cb"), NULL, array ($this, "event_cb"));

        if (!$this->bev->connect("unix:$sock_path")) {
            trigger_error("Failed to connect to socket `$sock_path'", E_USER_ERROR);
        }

        $this->bev->enable(Event::READ);
    }

    function __destruct() {
        if ($this->bev) {
            $this->bev->free();
            $this->bev = NULL;
        }
    }

    function dispatch() {
        $this->base->dispatch();
    }

    function read_cb($bev, $unused) {
        $in = $bev->input;

        printf("Received %ld bytes\n", $in->length);
        printf("----- data ----\n");
        printf("%ld:\t%s\n", (int) $in->length, $in->pullup(-1));

        $this->bev->free();
        $this->bev = NULL;
        $this->base->exit(NULL);
    }

    function event_cb($bev, $events, $unused) {
        if ($events & EventBufferEvent::ERROR) {
            echo "Error from bufferevent\n";
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            $bev->free();
            $bev = NULL;
        } elseif ($events & EventBufferEvent::CONNECTED) {
            $bev->output->add("test\n");
        }
    }
}

if ($argc <= 1) {
    exit("Socket path is not provided\n");
}
$sock_path = $argv[1];

$base = new EventBase();
$cl = new MyUnixSocketClient($base, $sock_path);
$cl->dispatch();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Received 5 bytes
----- data ----
5:  test

A se vedea ?i

  • EventBufferEvent::connectHost() - Connects to a hostname with optionally asyncronous DNS resolving
EventBufferEvent::close
EventBufferEvent::connectHost
EventBufferEvent


Connects to a hostname with optionally asyncronous DNS resolving

EventBufferEvent::connect
EventBufferEvent::__construct
EventBufferEvent
PHP Manual

EventBufferEvent::connectHost

(PECL event >= 1.2.6-beta)

EventBufferEvent::connectHost — Connects to a hostname with optionally asyncronous DNS resolving

Descrierea

public bool EventBufferEvent::connectHost ( EventDnsBase $dns_base , string $hostname , int $port [, int $family = EventUtil::AF_UNSPEC ] )

Resolves the DNS name hostname, looking for addresses of type family ( EventUtil::AF_* constants). If the name resolution fails, it invokes the event callback with an error event. If it succeeds, it launches a connection attempt just as EventBufferEvent::connect() would.

dns_base is optional. May be NULL, or an object created with EventDnsBase::__construct() . For asyncronous hostname resolving pass a valid event dns base resource. Otherwise the hostname resolving will block.

Nota:

EventDnsBase is available only if Event configured --with-event-extra ( event_extra library, libevent protocol-specific functionality support including HTTP, DNS, and RPC ).

Nota:

EventBufferEvent::connectHost() requires libevent-2.0.3-alpha or greater.

Parametri

dns_base

Object of EventDnsBase in case if DNS is to be resolved asyncronously. Otherwise NULL.

hostname

Hostname to connect to. Recognized formats are:

www.example.com (hostname)
 1.2.3.4 (ipv4address)
 ::1 (ipv6address)
[::1] ([ipv6address])

port

Port number

family

Address family. EventUtil::AF_UNSPEC , EventUtil::AF_INET , or EventUtil::AF_INET6 . See EventUtil constants .

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

Exemple

Example #1 EventBufferEvent::connectHost() example

<?php
/* Read callback */
function readcb($bev, $base) {
    //$input = $bev->input; //$bev->getInput();

    //$pos = $input->search("TTP");
    $pos = $bev->input->search("TTP");

    while (($n = $bev->input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}

/* Event callback */
function eventcb($bev, $events, $base) {
    if ($events & EventBufferEvent::CONNECTED) {
        echo "Connected.\n";
    } elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
        if ($events & EventBufferEvent::ERROR) {
            echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
        }

        echo "Closing\n";
        $base->exit();
        exit("Done\n");
    }
}

$base = new EventBase();

$dns_base = new EventDnsBase($base, TRUE); // We'll use async DNS resolving
if (!$dns_base) {
    exit("Failed to init DNS Base\n");
}

$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,
    "readcb", /* writecb */ NULL, "eventcb", $base
);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

//$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

$output = $bev->output; //$bev->getOutput();
if (!$output->add(
    "GET {$argv[2]} HTTP/1.0\r\n".
    "Host: {$argv[1]}\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

if (!$bev->connectHost($dns_base, $argv[1], 80, EventUtil::AF_UNSPEC)) {
    exit("Can't connect to host {$argv[1]}\n");
}

$base->dispatch();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Connected.
HTTP/1.0 301 Moved Permanently
Location: http://www.google.co.uk/
Content-Type: text/html; CHARSET=Windows-1252
Date: Sat, 09 Mar 2013 12:21:19 GMT
Expires: Mon, 08 Apr 2013 12:21:19 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN

<HTML><HEAD><meta http-equiv="content-type" content="text/html;CHARSET=Windows-1252">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.co.uk/">here</A>.
</BODY></HTML>
Closing
Done

A se vedea ?i

  • EventBufferEvent::connect() - Connect buffer event's file descriptor to given address or UNIX socket
EventBufferEvent::connect
EventBufferEvent::__construct
EventBufferEvent


Constructs EventBufferEvent object

EventBufferEvent::connectHost
EventBufferEvent::createPair
EventBufferEvent
PHP Manual

EventBufferEvent::__construct

(PECL event >= 1.2.6-beta)

EventBufferEvent::__construct — Constructs EventBufferEvent object

Descrierea

public EventBufferEvent::__construct ( EventBase $base [, mixed $socket = NULL [, int $options = 0 [, callable $readcb = NULL [, callable $writecb = NULL [, callable $eventcb = NULL ]]]]] )

Create a buffer event on a socket, stream or a file descriptor. Passing NULL to socket means that the socket should be created later, e.g. by means of EventBufferEvent::connect() .

Parametri

base

Event base that should be associated with the new buffer event.

socket

May be created as a stream(not necessarily by means of sockets extension)

options

One of EventBufferEvent::OPT_* constants , or 0 .

readcb

Read event callback. See About buffer event callbacks .

writecb

Write event callback. See About buffer event callbacks .

eventcb

Status-change event callback. See About buffer event callbacks .

arg

A variable that will be passed to all the callbacks.

Valorile întoarse

Returns buffer event resource optionally associated with socket resource. */

A se vedea ?i

  • EventBufferEvent::sslFilter() - Create a new SSL buffer event to send its data over another buffer event
  • EventBufferEvent::sslSocket() - Creates a new SSL buffer event to send its data over an SSL on a socket
EventBufferEvent::connectHost
EventBufferEvent::createPair
EventBufferEvent


Creates two buffer events connected to each other

EventBufferEvent::__construct
EventBufferEvent::disable
EventBufferEvent
PHP Manual

EventBufferEvent::createPair

(PECL event >= 1.2.6-beta)

EventBufferEvent::createPair — Creates two buffer events connected to each other

Descrierea

public static array EventBufferEvent::createPair ( EventBase $base [, int $options = 0 ] )

Returns array of two EventBufferEvent objects connected to each other. All the usual options are supported, except for EventBufferEvent::OPT_CLOSE_ON_FREE , which has no effect, and EventBufferEvent::OPT_DEFER_CALLBACKS , which is always on.

Parametri

base

Associated event base

options

EventBufferEvent::OPT_* constants combined with bitwise OR operator.

Valorile întoarse

Returns array of two EventBufferEvent objects connected to each other.

Istoricul schimbarilor

Versiune | Descriere
1.9.0 | Method made static.

EventBufferEvent::__construct
EventBufferEvent::disable
EventBufferEvent


Disable events read, write, or both on a buffer event.

EventBufferEvent::createPair
EventBufferEvent::enable
EventBufferEvent
PHP Manual

EventBufferEvent::disable

(PECL event >= 1.2.6-beta)

EventBufferEvent::disable — Disable events read, write, or both on a buffer event.

Descrierea

public bool EventBufferEvent::disable ( int $events )

Disable events Event::READ , Event::WRITE , or Event::READ | Event::WRITE on a buffer event.

Parametri

events

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBufferEvent::enable() - Enable events read, write, or both on a buffer event.
EventBufferEvent::createPair
EventBufferEvent::enable
EventBufferEvent


Enable events read, write, or both on a buffer event.

EventBufferEvent::disable
EventBufferEvent::free
EventBufferEvent
PHP Manual

EventBufferEvent::enable

(PECL event >= 1.2.6-beta)

EventBufferEvent::enable — Enable events read, write, or both on a buffer event.

Descrierea

public bool EventBufferEvent::enable ( int $events )

Enable events Event::READ , Event::WRITE , or Event::READ | Event::WRITE on a buffer event.

Parametri

events

Event::READ , Event::WRITE , or Event::READ | Event::WRITE on a buffer event.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBufferEvent::disable() - Disable events read, write, or both on a buffer event.
EventBufferEvent::disable
EventBufferEvent::free
EventBufferEvent


Free a buffer event

EventBufferEvent::enable
EventBufferEvent::getDnsErrorString
EventBufferEvent
PHP Manual

EventBufferEvent::free

(PECL event >= 1.2.6-beta)

EventBufferEvent::free — Free a buffer event

Descrierea

public void EventBufferEvent::free ( void )

Free resources allocated by buffer event.

Usually there is no need to call this method, since normally it is done within internal object destructors. However, sometimes we have a long-time script allocating lots of instances, or a script with a heavy memory usage, where we need to free resources as soon as possible. In such cases EventBufferEvent::free() may be used to protect the script against running up to the memory_limit .

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventBufferEvent::enable
EventBufferEvent::getDnsErrorString
EventBufferEvent


Returns string describing the last failed DNS lookup attempt

EventBufferEvent::free
EventBufferEvent::getEnabled
EventBufferEvent
PHP Manual

EventBufferEvent::getDnsErrorString

(PECL event >= 1.2.6-beta)

EventBufferEvent::getDnsErrorString — Returns string describing the last failed DNS lookup attempt

Descrierea

public string EventBufferEvent::getDnsErrorString ( void )

Returns string describing the last failed DNS lookup attempt made by EventBufferEvent::connectHost() , or an empty string, if there is no DNS error detected.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string describing DNS lookup error, or an empty string for no error.

A se vedea ?i

  • EventBufferEvent::connectHost() - Connects to a hostname with optionally asyncronous DNS resolving
EventBufferEvent::free
EventBufferEvent::getEnabled
EventBufferEvent


Returns bitmask of events currently enabled on the buffer event

EventBufferEvent::getDnsErrorString
EventBufferEvent::getInput
EventBufferEvent
PHP Manual

EventBufferEvent::getEnabled

(PECL event >= 1.2.6-beta)

EventBufferEvent::getEnabled — Returns bitmask of events currently enabled on the buffer event

Descrierea

public int EventBufferEvent::getEnabled ( void )

Returns bitmask of events currently enabled on the buffer event

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns integer representing a bitmask of events currently enabled on the buffer event

A se vedea ?i

  • EventBufferEvent::enable() - Enable events read, write, or both on a buffer event.
  • EventBufferEvent::disable() - Disable events read, write, or both on a buffer event.
EventBufferEvent::getDnsErrorString
EventBufferEvent::getInput
EventBufferEvent


Returns underlying input buffer associated with current buffer event

EventBufferEvent::getEnabled
EventBufferEvent::getOutput
EventBufferEvent
PHP Manual

EventBufferEvent::getInput

(PECL event >= 1.2.6-beta)

EventBufferEvent::getInput — Returns underlying input buffer associated with current buffer event

Descrierea

public EventBuffer EventBufferEvent::getInput ( void )

Returns underlying input buffer associated with current buffer event. An input buffer is a storage for data to read.

Note, there is also input property of EventBufferEvent class.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns instance of EventBuffer input buffer associated with current buffer event.

Exemple

Example #1 Buffer event's read callback

<?php
function readcb($bev, $base) {
    $input = $bev->input; //$bev->getInput();

    while (($n = $input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}
?>

A se vedea ?i

  • EventBufferEvent::getOutput() - Returns underlying output buffer associated with current buffer event
EventBufferEvent::getEnabled
EventBufferEvent::getOutput
EventBufferEvent


Returns underlying output buffer associated with current buffer event

EventBufferEvent::getInput
EventBufferEvent::read
EventBufferEvent
PHP Manual

EventBufferEvent::getOutput

(PECL event >= 1.2.6-beta)

EventBufferEvent::getOutput — Returns underlying output buffer associated with current buffer event

Descrierea

public EventBuffer EventBufferEvent::getOutput ( void )

Returns underlying output buffer associated with current buffer event. An output buffer is a storage for data to be written.

Note, there is also output property of EventBufferEvent class.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns instance of EventBuffer output buffer associated with current buffer event.

Exemple

Example #1 EventBufferEvent::getOutput() example

<?php
$base = new EventBase();

$dns_base = new EventDnsBase($base, TRUE); // Use async DNS resolving
if (!$dns_base) {
    exit("Failed to init DNS Base\n");
}

$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,
    "readcb", /* writecb */ NULL, "eventcb", $base
);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

$bev->enable(Event::READ | Event::WRITE);

$output = $bev->getOutput();
if (!$output->add(
    "GET {$argv[2]} HTTP/1.0\r\n".
    "Host: {$argv[1]}\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

/* ... */
?>

A se vedea ?i

  • EventBufferEvent::getInput() - Returns underlying input buffer associated with current buffer event
EventBufferEvent::getInput
EventBufferEvent::read
EventBufferEvent


Read buffer's data

EventBufferEvent::getOutput
EventBufferEvent::readBuffer
EventBufferEvent
PHP Manual

EventBufferEvent::read

(PECL event >= 1.2.6-beta)

EventBufferEvent::read — Read buffer's data

Descrierea

public string EventBufferEvent::read ( int $size )

Removes up to size bytes from the input buffer. Returns a string of data read from the input buffer.

Parametri

size

Maximum number of bytes to read

Valorile întoarse

Returns string of data read from the input buffer.

A se vedea ?i

  • EventBufferEvent::readBuffer() - Drains the entire contents of the input buffer and places them into buf
EventBufferEvent::getOutput
EventBufferEvent::readBuffer
EventBufferEvent


Drains the entire contents of the input buffer and places them into buf

EventBufferEvent::read
EventBufferEvent::setCallbacks
EventBufferEvent
PHP Manual

EventBufferEvent::readBuffer

(PECL event >= 1.2.6-beta)

EventBufferEvent::readBuffer — Drains the entire contents of the input buffer and places them into buf

Descrierea

public bool EventBufferEvent::readBuffer ( EventBuffer $buf )

Drains the entire contents of the input buffer and places them into buf .

Parametri

buf

Target buffer

Valorile întoarse

Returns TRUE on success; Otherwise FALSE.

A se vedea ?i

  • EventBufferEvent::read() - Read buffer's data
EventBufferEvent::read
EventBufferEvent::setCallbacks
EventBufferEvent


Assigns read, write and event(status) callbacks

EventBufferEvent::readBuffer
EventBufferEvent::setPriority
EventBufferEvent
PHP Manual

EventBufferEvent::setCallbacks

(PECL event >= 1.2.6-beta)

EventBufferEvent::setCallbacks — Assigns read, write and event(status) callbacks

Descrierea

public void EventBufferEvent::setCallbacks ( callable $readcb , callable $writecb , callable $eventcb [, string $arg ] )

Assigns read, write and event(status) callbacks.

Parametri

readcb

Read event callback. See About buffer event callbacks .

writecb

Write event callback. See About buffer event callbacks .

eventcb

Status-change event callback. See About buffer event callbacks .

arg

A variable that will be passed to all the callbacks.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventBufferEvent::__construct() - Constructs EventBufferEvent object
EventBufferEvent::readBuffer
EventBufferEvent::setPriority
EventBufferEvent


Assign a priority to a bufferevent

EventBufferEvent::setCallbacks
EventBufferEvent::setTimeouts
EventBufferEvent
PHP Manual

EventBufferEvent::setPriority

(PECL event >= 1.2.6-beta)

EventBufferEvent::setPriority — Assign a priority to a bufferevent

Descrierea

public bool EventBufferEvent::setPriority ( int $priority )

Assign a priority to a bufferevent

Avertizare

Only supported for socket buffer events

Parametri

priority

Priority value.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

EventBufferEvent::setCallbacks
EventBufferEvent::setTimeouts
EventBufferEvent


Set the read and write timeout for a buffer event

EventBufferEvent::setPriority
EventBufferEvent::setWatermark
EventBufferEvent
PHP Manual

EventBufferEvent::setTimeouts

(PECL event >= 1.2.6-beta)

EventBufferEvent::setTimeouts — Set the read and write timeout for a buffer event

Descrierea

public bool EventBufferEvent::setTimeouts ( float $timeout_read , float $timeout_write )

Set the read and write timeout for a buffer event

Parametri

timeout_read

Read timeout

timeout_write

Write timeout

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

EventBufferEvent::setPriority
EventBufferEvent::setWatermark
EventBufferEvent


Adjusts read and/or write watermarks

EventBufferEvent::setTimeouts
EventBufferEvent::sslError
EventBufferEvent
PHP Manual

EventBufferEvent::setWatermark

(PECL event >= 1.2.6-beta)

EventBufferEvent::setWatermark — Adjusts read and/or write watermarks

Descrierea

public void EventBufferEvent::setWatermark ( int $events , int $lowmark , int $highmark )

Adjusts the read watermarks, the write watermarks , or both, of a single buffer event.

A buffer event watermark is an edge, a value specifying number of bytes to be read or written before callback is invoked. By default every read/write event triggers a callback invokation. See » Fast portable non-blocking network programming with Libevent: Callbacks and watermarks

Parametri

events

Bitmask of Event::READ , Event::WRITE , or both.

lowmark

Minimum watermark value.

highmark

Maximum watermark value. 0 means "unlimited".

Valorile întoarse

Nu este întoarsa nici o valoare.

EventBufferEvent::setTimeouts
EventBufferEvent::sslError
EventBufferEvent


Returns most recent OpenSSL error reported on the buffer event

EventBufferEvent::setWatermark
EventBufferEvent::sslFilter
EventBufferEvent
PHP Manual

EventBufferEvent::sslError

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslError — Returns most recent OpenSSL error reported on the buffer event

Descrierea

public string EventBufferEvent::sslError ( void )

Returns most recent OpenSSL error reported on the buffer event.

Nota:

This function is available only if Event is compiled with OpenSSL support.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns OpenSSL error string reported on the buffer event, or FALSE, if there is no more error to return.

Exemple

Example #1 EventBufferEvent::sslError() example

<?php
// This callback is invoked when some even occurs on the event listener,
// e.g. connection closed, or an error occured
function ssl_event_cb($bev, $events, $ctx) {
    if ($events & EventBufferEvent::ERROR) {
        // Fetch errors from the SSL error stack
        while ($err = $bev->sslError()) {
            fprintf(STDERR, "Bufferevent error %s.\n", $err);
        }
    }

    if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
        $bev->free();
    }
}
?>

A se vedea ?i

  • EventBufferEvent::sslRenegotiate() - Tells a bufferevent to begin SSL renegotiation.
EventBufferEvent::setWatermark
EventBufferEvent::sslFilter
EventBufferEvent


Create a new SSL buffer event to send its data over another buffer event

EventBufferEvent::sslError
EventBufferEvent::sslGetCipherInfo
EventBufferEvent
PHP Manual

EventBufferEvent::sslFilter

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslFilter — Create a new SSL buffer event to send its data over another buffer event

Descrierea

public static EventBufferEvent EventBufferEvent::sslFilter ( EventBase $base , EventBufferEvent $underlying , EventSslContext $ctx , int $state [, int $options = 0 ] )

Create a new SSL buffer event to send its data over another buffer event

Nota:

This function is available only if Event is compiled with OpenSSL support.

Parametri

base

Associated event base.

underlying

A socket buffer event to use for this SSL.

ctx

Object of EventSslContext class.

state

The current state of SSL connection: EventBufferEvent::SSL_OPEN , EventBufferEvent::SSL_ACCEPTING or EventBufferEvent::SSL_CONNECTING .

options

One or more buffer event options.

Valorile întoarse

Returns a new SSL EventBufferEvent object.

Exemple

Example #1 Simple SMTP server

<?php
 /*
 * Author: Andrew Rose <hello at andrewrose dot co dot uk>
 *
 * Usage:
 * 1) Prepare cert.pem certificate and privkey.pem private key files.
 * 2) Launch the server script
 * 3) Open TLS connection, e.g.:
 *      $ openssl s_client -connect localhost:25 -starttls smtp -crlf
 * 4) Start testing the commands listed in `cmd` method below.
 */

class Handler {
    public $domainName = FALSE;
    public $connections = [];
    public $buffers = [];
    public $maxRead = 256000;

    public function __construct() {
        $this->ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, [
            EventSslContext::OPT_LOCAL_CERT  => 'cert.pem',
            EventSslContext::OPT_LOCAL_PK    => 'privkey.pem',
            //EventSslContext::OPT_PASSPHRASE  => '',
            EventSslContext::OPT_VERIFY_PEER => false, // change to true with authentic cert
            EventSslContext::OPT_ALLOW_SELF_SIGNED => true // change to false with authentic cert
        ]);

        $this->base = new EventBase();
        if (!$this->base) {
            exit("Couldn't open event base\n");
        }

        if (!$this->listener = new EventListener($this->base,
            [$this, 'ev_accept'],
            $this->ctx,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1,
            '0.0.0.0:25'))
        {
            exit("Couldn't create listener\n");
        }

        $this->listener->setErrorCallback([$this, 'ev_error']);
        $this->base->dispatch();
    }

    public function ev_accept($listener, $fd, $address, $ctx) {
        static $id = 0;
        $id += 1;

        $this->connections[$id]['clientData'] = '';
        $this->connections[$id]['cnx'] = new EventBufferEvent($this->base, $fd,
            EventBufferEvent::OPT_CLOSE_ON_FREE);

        if (!$this->connections[$id]['cnx']) {
            echo "Failed creating buffer\n";
            $this->base->exit(NULL);
            exit(1);
        }

        $this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL,
            [$this, 'ev_error'], $id);
        $this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);

        $this->ev_write($id, '220 '.$this->domainName." wazzzap?\r\n");
    }

    function ev_error($listener, $ctx) {
        $errno = EventUtil::getLastSocketErrno();

        fprintf(STDERR, "Got an error %d (%s) on the listener. Shutting down.\n",
            $errno, EventUtil::getLastSocketError());

        if ($errno != 0) {
            $this->base->exit(NULL);
            exit();
        }
    }

    public function ev_close($id) {
        $this->connections[$id]['cnx']->disable(Event::READ | Event::WRITE);
        unset($this->connections[$id]);
    }

    protected function ev_write($id, $string) {
        echo 'S('.$id.'): '.$string;
        $this->connections[$id]['cnx']->write($string);
    }

    public function ev_read($buffer, $id) {
        while($buffer->input->length > 0) {
            $this->connections[$id]['clientData'] .= $buffer->input->read($this->maxRead);
            $clientDataLen = strlen($this->connections[$id]['clientData']);

            if($this->connections[$id]['clientData'][$clientDataLen-1] == "\n"
                && $this->connections[$id]['clientData'][$clientDataLen-2] == "\r")
            {
                // remove the trailing \r\n
                $line = substr($this->connections[$id]['clientData'], 0,
                    strlen($this->connections[$id]['clientData']) - 2);

                $this->connections[$id]['clientData'] = '';
                $this->cmd($buffer, $id, $line);
            }
        }
    }

    protected function cmd($buffer, $id, $line) {
        switch ($line) {
            case strncmp('EHLO ', $line, 4):
                $this->ev_write($id, "250-STARTTLS\r\n");
                $this->ev_write($id, "250 OK ehlo\r\n");
                break;

            case strncmp('HELO ', $line, 4):
                $this->ev_write($id, "250-STARTTLS\r\n");
                $this->ev_write($id, "250 OK helo\r\n");
                break;

            case strncmp('QUIT', $line, 3):
                $this->ev_write($id, "250 OK quit\r\n");
                $this->ev_close($id);
                break;

            case strncmp('STARTTLS', $line, 3):
                $this->ev_write($id, "220 Ready to start TLS\r\n");
                $this->connections[$id]['cnx'] = EventBufferEvent::sslFilter($this->base,
                    $this->connections[$id]['cnx'], $this->ctx,
                    EventBufferEvent::SSL_ACCEPTING,
                    EventBufferEvent::OPT_CLOSE_ON_FREE);
                $this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL, [$this, 'ev_error'], $id);
                $this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);
                break;

            default:
                echo 'unknown command: '.$line."\n";
                break;
        }
    }
}

new Handler();

A se vedea ?i

  • EventBufferEvent::sslSocket() - Creates a new SSL buffer event to send its data over an SSL on a socket
EventBufferEvent::sslError
EventBufferEvent::sslGetCipherInfo
EventBufferEvent


Returns a textual description of the cipher.

EventBufferEvent::sslFilter
EventBufferEvent::sslGetCipherName
EventBufferEvent
PHP Manual

EventBufferEvent::sslGetCipherInfo

(PECL event >= 1.10.0)

EventBufferEvent::sslGetCipherInfo — Returns a textual description of the cipher.

Descrierea

public string EventBufferEvent::sslGetCipherInfo ( void )

Retrieves description of the current cipher by means of the SSL_CIPHER_description SSL API function (see SSL_CIPHER_get_name(3) man page).

Nota:

This function is available only if Event is compiled with OpenSSL support.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a textual description of the cipher on success, or FALSE on error.

EventBufferEvent::sslFilter
EventBufferEvent::sslGetCipherName
EventBufferEvent


Returns the current cipher name of the SSL connection.

EventBufferEvent::sslGetCipherInfo
EventBufferEvent::sslGetCipherVersion
EventBufferEvent
PHP Manual

EventBufferEvent::sslGetCipherName

(PECL event >= 1.10.0)

EventBufferEvent::sslGetCipherName — Returns the current cipher name of the SSL connection.

Descrierea

public string EventBufferEvent::sslGetCipherName ( void )

Retrieves name of cipher used by current SSL connection.

Nota:

This function is available only if Event is compiled with OpenSSL support.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current cipher name of the SSL connection, or FALSE on error.

EventBufferEvent::sslGetCipherInfo
EventBufferEvent::sslGetCipherVersion
EventBufferEvent


Returns version of cipher used by current SSL connection.

EventBufferEvent::sslGetCipherName
EventBufferEvent::sslGetProtocol
EventBufferEvent
PHP Manual

EventBufferEvent::sslGetCipherVersion

(PECL event >= 1.10.0)

EventBufferEvent::sslGetCipherVersion — Returns version of cipher used by current SSL connection.

Descrierea

public string EventBufferEvent::sslGetCipherVersion ( void )

Retrieves version of cipher used by current SSL connection.

Nota:

This function is available only if Event is compiled with OpenSSL support.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current cipher version of the SSL connection, or FALSE on error.

EventBufferEvent::sslGetCipherName
EventBufferEvent::sslGetProtocol
EventBufferEvent


Returns the name of the protocol used for current SSL connection.

EventBufferEvent::sslGetCipherVersion
EventBufferEvent::sslRenegotiate
EventBufferEvent
PHP Manual

EventBufferEvent::sslGetProtocol

(PECL event >= 1.10.0)

EventBufferEvent::sslGetProtocol — Returns the name of the protocol used for current SSL connection.

Descrierea

public string EventBufferEvent::sslGetProtocol ( void )

Returns the name of the protocol used for current SSL connection.

Nota:

This function is available only if Event is compiled with OpenSSL support.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the name of the protocol used for current SSL connection.

EventBufferEvent::sslGetCipherVersion
EventBufferEvent::sslRenegotiate
EventBufferEvent


Tells a bufferevent to begin SSL renegotiation.

EventBufferEvent::sslGetProtocol
EventBufferEvent::sslSocket
EventBufferEvent
PHP Manual

EventBufferEvent::sslRenegotiate

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslRenegotiate — Tells a bufferevent to begin SSL renegotiation.

Descrierea

public void EventBufferEvent::sslRenegotiate ( void )

Tells a bufferevent to begin SSL renegotiation.

Avertizare

Calling this function tells the SSL to renegotiate, and the buffer event to invoke appropriate callbacks. This is an advanced topic; this should be generally avoided unless one really knows what he/she does, especially since many SSL versions have had known security issues related to renegotiation.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventBufferEvent::sslGetProtocol
EventBufferEvent::sslSocket
EventBufferEvent


Creates a new SSL buffer event to send its data over an SSL on a socket

EventBufferEvent::sslRenegotiate
EventBufferEvent::write
EventBufferEvent
PHP Manual

EventBufferEvent::sslSocket

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslSocket — Creates a new SSL buffer event to send its data over an SSL on a socket

Descrierea

public static EventBufferEvent EventBufferEvent::sslSocket ( EventBase $base , mixed $socket , EventSslContext $ctx , int $state [, int $options ] )

Creates a new SSL buffer event to send its data over an SSL on a socket.

Parametri

base

Associated event base.

socket

Socket to use for this SSL. Can be stream or socket resource, numeric file descriptor, or NULL. If socket is NULL, it is assumed that the file descriptor for the socket will be assigned later, for instance, by means of EventBufferEvent::connectHost() method.

ctx

Object of EventSslContext class.

state

The current state of SSL connection: EventBufferEvent::SSL_OPEN , EventBufferEvent::SSL_ACCEPTING or EventBufferEvent::SSL_CONNECTING .

options

The buffer event options.

Valorile întoarse

Returns EventBufferEvent object.

A se vedea ?i

  • EventBufferEvent::sslFilter() - Create a new SSL buffer event to send its data over another buffer event
EventBufferEvent::sslRenegotiate
EventBufferEvent::write
EventBufferEvent


Adds data to a buffer event's output buffer

EventBufferEvent::sslSocket
EventBufferEvent::writeBuffer
EventBufferEvent
PHP Manual

EventBufferEvent::write

(PECL event >= 1.2.6-beta)

EventBufferEvent::write — Adds data to a buffer event's output buffer

Descrierea

public bool EventBufferEvent::write ( string $data )

Adds data to a buffer event's output buffer

Parametri

data

Data to be added to the underlying buffer.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBufferEvent::writeBuffer() - Adds contents of the entire buffer to a buffer event's output buffer
EventBufferEvent::sslSocket
EventBufferEvent::writeBuffer
EventBufferEvent


Adds contents of the entire buffer to a buffer event's output buffer

EventBufferEvent::write
About buffer event callbacks
EventBufferEvent
PHP Manual

EventBufferEvent::writeBuffer

(PECL event >= 1.2.6-beta)

EventBufferEvent::writeBuffer — Adds contents of the entire buffer to a buffer event's output buffer

Descrierea

public bool EventBufferEvent::writeBuffer ( EventBuffer $buf )

Adds contents of the entire buffer to a buffer event's output buffer

Parametri

buf

Source EventBuffer object.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventBufferEvent::write() - Adds data to a buffer event's output buffer
EventBufferEvent::write
About buffer event callbacks
EventBufferEvent


About buffer event callbacks

An object of EventBufferEvent class represents a buffer event . The asynchronous nature of I/O performed by Libevent implies that a socket(or other kind of file descriptor) is not always available. Event invokes corresponding callbacks when the resource becomes available for reading or writing, or when some event occurs(e.g. error, "end of line" etc.).

Read and write callbacks should match the following prototype:

void callback ([ EventBufferEvent $bev = NULL [, mixed $arg = NULL ]] )

bev

Associated EventBufferEvent object.

arg

Custom variable attached to all callbacks via EventBufferEvent::__construct() , or EventBufferEvent::setCallbacks() .

Event callback should match the following prototype:

void callback ([ EventBufferEvent $bev = NULL [, int $events = 0 [, mixed $arg = NULL ]]] )

bev

Associated EventBufferEvent object.

events

Bit mask of events: EventBufferEvent::READING , EventBufferEvent::WRITING , EventBufferEvent::EOL , EventBufferEvent::ERROR and EventBufferEvent::TIMEOUT . See EventBufferEvent constants

arg

Custom variable attached to all callbacks via EventBufferEvent::__construct() , or EventBufferEvent::setCallbacks() .

EventBufferEvent::writeBuffer
EventConfig
Event


The EventConfig class

(PECL event >= 1.2.6-beta)

Introducere

Represents configuration structure which could be used in construction of the EventBase .

Sinopsisul clasei

final EventConfig {
/* Constants */
const integer FEATURE_ET = 1 ;
const integer FEATURE_O1 = 2 ;
const integer FEATURE_FDS = 4 ;
/* Metode */
public bool avoidMethod ( string $method )
public __construct ( void )
public bool requireFeatures ( int $feature )
public void setMaxDispatchInterval ( int $max_interval , int $max_callbacks , int $min_priority )
}

Constante predefinite

EventConfig::FEATURE_ET

Requires a backend method that supports edge-triggered I/O.

EventConfig::FEATURE_O1

Requires a backend method where adding or deleting a single event, or having a single event become active, is an O(1) operation.

EventConfig::FEATURE_FDS

Requires a backend method that can support arbitrary file descriptor types, and not just sockets.

Cuprins

  • EventConfig::avoidMethod — Tells libevent to avoid specific event method
  • EventConfig::__construct — Constructs EventConfig object
  • EventConfig::requireFeatures — Enters a required event method feature that the application demands
  • EventConfig::setMaxDispatchInterval — Prevents priority inversion
About buffer event callbacks
EventConfig::avoidMethod
Event


Tells libevent to avoid specific event method

EventConfig
EventConfig::__construct
EventConfig
PHP Manual

EventConfig::avoidMethod

(PECL event >= 1.2.6-beta)

EventConfig::avoidMethod — Tells libevent to avoid specific event method

Descrierea

public bool EventConfig::avoidMethod ( string $method )

Tells libevent to avoid specific event method(backend). See » Creating an event base .

Parametri

method

The backend method to avoid. See EventConfig constants .

Valorile întoarse

Returns TRUE on success, otherwise FALSE.

Exemple

Example #1 EventConfig::avoidMethod() example

<?php
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}
?>

A se vedea ?i

  • EventBase::__construct() - Constructs EventBase object
EventConfig
EventConfig::__construct
EventConfig


Constructs EventConfig object

EventConfig::avoidMethod
EventConfig::requireFeatures
EventConfig
PHP Manual

EventConfig::__construct

(PECL event >= 1.2.6-beta)

EventConfig::__construct — Constructs EventConfig object

Descrierea

public EventConfig::__construct ( void )

Constructs EventConfig object which could be passed to EventBase::__construct() constructor.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns EventConfig object.

Exemple

Example #1 EventConfig::__construct() example

<?php
// Avoiding "select" method
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}

// Create event_base associated with the config
$base = new EventBase($cfg);

/* Now $base is configured to avoid select backend(method) */
?>

A se vedea ?i

  • EventBase::__construct() - Constructs EventBase object
EventConfig::avoidMethod
EventConfig::requireFeatures
EventConfig


Enters a required event method feature that the application demands

EventConfig::__construct
EventConfig::setMaxDispatchInterval
EventConfig
PHP Manual

EventConfig::requireFeatures

(PECL event >= 1.2.6-beta)

EventConfig::requireFeatures — Enters a required event method feature that the application demands

Descrierea

public bool EventConfig::requireFeatures ( int $feature )

Enters a required event method feature that the application demands

Parametri

feature

Bitmask of required features. See EventConfig::FEATURE_* constants

Valorile întoarse

Exemple

Example #1 EventConfig::requireFeatures() example

<?php
$cfg = new EventConfig();

// Create event_base associated with the config
$base = new EventBase($cfg);

// Require FDS feature
if ($cfg->requireFeatures(EventConfig::FEATURE_FDS)) {
    echo "FDS feature is now requried\n";

    $base = new EventBase($cfg);
    ($base->getFeatures() & EventConfig::FEATURE_FDS)
        and print("FDS - arbitrary file descriptor types, and not just sockets\n");
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

FDS feature is now requried
FDS - arbitrary file descriptor types, and not just sockets

A se vedea ?i

  • EventBase::getFeatures() - Returns bitmask of features supported
EventConfig::__construct
EventConfig::setMaxDispatchInterval
EventConfig


Prevents priority inversion

EventConfig::requireFeatures
EventDnsBase
EventConfig
PHP Manual

EventConfig::setMaxDispatchInterval

(No version information available, might only be in Git)

EventConfig::setMaxDispatchInterval — Prevents priority inversion

Descrierea

public void EventConfig::setMaxDispatchInterval ( int $max_interval , int $max_callbacks , int $min_priority )

Prevents priority inversion by limiting how many low-priority event callbacks can be invoked before checking for more high-priority events.

Nota:

Available since libevent 2.1.0-alpha .

Parametri

max_interval

An interval after which Libevent should stop running callbacks and check for more events, or 0 , if there should be no such interval.

max_callbacks

A number of callbacks after which Libevent should stop running callbacks and check for more events, or -1 , if there should be no such limit.

min_priority

A priority below which max_interval and max_callbacks should not be enforced. If this is set to 0 , they are enforced for events of every priority; if it's set to 1 , they're enforced for events of priority 1 and above, and so on.

Valorile întoarse

Returns TRUE on success, otherwise FALSE.

EventConfig::requireFeatures
EventDnsBase
EventConfig


The EventDnsBase class

(PECL event >= 1.2.6-beta)

Introducere

Represents Libevent's DNS base structure. Used to resolve DNS asyncronously, parse configuration files like resolv.conf etc.

Sinopsisul clasei

final EventDnsBase {
/* Constants */
const integer OPTION_SEARCH = 1 ;
const integer OPTION_NAMESERVERS = 2 ;
const integer OPTION_MISC = 4 ;
const integer OPTION_HOSTSFILE = 8 ;
const integer OPTIONS_ALL = 15 ;
/* Metode */
public bool addNameserverIp ( string $ip )
public void addSearch ( string $domain )
public void clearSearch ( void )
public __construct ( EventBase $base , bool $initialize )
public int countNameservers ( void )
public bool loadHosts ( string $hosts )
public bool parseResolvConf ( int $flags , string $filename )
public bool setOption ( string $option , string $value )
public bool setSearchNdots ( int $ndots )
}

Constante predefinite

EventDnsBase::OPTION_SEARCH

Tells to read the domain and search fields from the resolv.conf file and the ndots option, and use them to decide which domains(if any) to search for hostnames that aren’t fully-qualified.

EventDnsBase::OPTION_NAMESERVERS

Tells to learn the nameservers from the resolv.conf file.

EventDnsBase::OPTION_MISC

EventDnsBase::OPTION_HOSTSFILE

Tells to read a list of hosts from /etc/hosts as part of loading the resolv.conf file.

EventDnsBase::OPTIONS_ALL

Tells to learn as much as it can from the resolv.conf file.

Cuprins

  • EventDnsBase::addNameserverIp — Adds a nameserver to the DNS base
  • EventDnsBase::addSearch — Adds a domain to the list of search domains
  • EventDnsBase::clearSearch — Removes all current search suffixes
  • EventDnsBase::__construct — Constructs EventDnsBase object
  • EventDnsBase::countNameservers — Gets the number of configured nameservers
  • EventDnsBase::loadHosts — Loads a hosts file (in the same format as /etc/hosts) from hosts file
  • EventDnsBase::parseResolvConf — Scans the resolv.conf-formatted file
  • EventDnsBase::setOption — Set the value of a configuration option
  • EventDnsBase::setSearchNdots — Set the 'ndots' parameter for searches
EventConfig::setMaxDispatchInterval
EventDnsBase::addNameserverIp
Event


Adds a nameserver to the DNS base

EventDnsBase
EventDnsBase::addSearch
EventDnsBase
PHP Manual

EventDnsBase::addNameserverIp

(PECL event >= 1.2.6-beta)

EventDnsBase::addNameserverIp — Adds a nameserver to the DNS base

Descrierea

public bool EventDnsBase::addNameserverIp ( string $ip )

Adds a nameserver to the evdns_base.

Parametri

ip

The nameserver string, either as an IPv4 address, an IPv6 address, an IPv4 address with a port ( IPv4:Port ), or an IPv6 address with a port ( [IPv6]:Port ).

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

EventDnsBase
EventDnsBase::addSearch
EventDnsBase


Adds a domain to the list of search domains

EventDnsBase::addNameserverIp
EventDnsBase::clearSearch
EventDnsBase
PHP Manual

EventDnsBase::addSearch

(PECL event >= 1.2.6-beta)

EventDnsBase::addSearch — Adds a domain to the list of search domains

Descrierea

public void EventDnsBase::addSearch ( string $domain )

Adds a domain to the list of search domains

Parametri

domain

Search domain.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventDnsBase::addNameserverIp
EventDnsBase::clearSearch
EventDnsBase


Removes all current search suffixes

EventDnsBase::addSearch
EventDnsBase::__construct
EventDnsBase
PHP Manual

EventDnsBase::clearSearch

(PECL event >= 1.2.6-beta)

EventDnsBase::clearSearch — Removes all current search suffixes

Descrierea

public void EventDnsBase::clearSearch ( void )

Removes all current search suffixes from the DNS base; the EventDnsBase::addSearch() function adds a suffix.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventDnsBase::addSearch() - Adds a domain to the list of search domains
EventDnsBase::addSearch
EventDnsBase::__construct
EventDnsBase


Constructs EventDnsBase object

EventDnsBase::clearSearch
EventDnsBase::countNameservers
EventDnsBase
PHP Manual

EventDnsBase::__construct

(PECL event >= 1.2.6-beta)

EventDnsBase::__construct — Constructs EventDnsBase object

Descrierea

public EventDnsBase::__construct ( EventBase $base , bool $initialize )

Constructs EventDnsBase object.

Parametri

base

Event base.

initialize

If the initialize argument is TRUE, it tries to configure the DNS base sensibly given your operating system’s default. Otherwise, it leaves the event DNS base empty, with no nameservers or options configured. In the latter case DNS base should be configured manually, e.g. with EventDnsBase::parseResolvConf() .

Valorile întoarse

Returns EventDnsBase object.

EventDnsBase::clearSearch
EventDnsBase::countNameservers
EventDnsBase


Gets the number of configured nameservers

EventDnsBase::__construct
EventDnsBase::loadHosts
EventDnsBase
PHP Manual

EventDnsBase::countNameservers

(PECL event >= 1.2.6-beta)

EventDnsBase::countNameservers — Gets the number of configured nameservers

Descrierea

public int EventDnsBase::countNameservers ( void )

Gets the number of configured nameservers

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the number of configured nameservers(not necessarily the number of running nameservers). This is useful for double-checking whether our calls to the various nameserver configuration functions have been successful.

EventDnsBase::__construct
EventDnsBase::loadHosts
EventDnsBase


Loads a hosts file (in the same format as /etc/hosts) from hosts file

EventDnsBase::countNameservers
EventDnsBase::parseResolvConf
EventDnsBase
PHP Manual

EventDnsBase::loadHosts

(PECL event >= 1.2.6-beta)

EventDnsBase::loadHosts — Loads a hosts file (in the same format as /etc/hosts) from hosts file

Descrierea

public bool EventDnsBase::loadHosts ( string $hosts )

Loads a hosts file (in the same format as /etc/hosts ) from hosts file.

Parametri

hosts

Path to the hosts' file.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

EventDnsBase::countNameservers
EventDnsBase::parseResolvConf
EventDnsBase


Scans the resolv.conf-formatted file

EventDnsBase::loadHosts
EventDnsBase::setOption
EventDnsBase
PHP Manual

EventDnsBase::parseResolvConf

(PECL event >= 1.2.6-beta)

EventDnsBase::parseResolvConf — Scans the resolv.conf-formatted file

Descrierea

public bool EventDnsBase::parseResolvConf ( int $flags , string $filename )

Scans the resolv.conf-formatted file stored in filename, and read in all the options from it that are listed in flags

Parametri

flags

Determines what information is parsed from the resolv.conf file. See the man page for resolv.conf for the format of this file.

The following directives are not parsed from the file: sortlist, rotate, no-check-names, inet6, debug .

If this function encounters an error, the possible return values are:

  • 1 = failed to open file
  • 2 = failed to stat file
  • 3 = file too large
  • 4 = out of memory
  • 5 = short read from file
  • 6 = no nameservers listed in the file

filename

Path to resolv.conf file.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

EventDnsBase::loadHosts
EventDnsBase::setOption
EventDnsBase


Set the value of a configuration option

EventDnsBase::parseResolvConf
EventDnsBase::setSearchNdots
EventDnsBase
PHP Manual

EventDnsBase::setOption

(PECL event >= 1.2.6-beta)

EventDnsBase::setOption — Set the value of a configuration option

Descrierea

public bool EventDnsBase::setOption ( string $option , string $value )

Set the value of a configuration option.

Parametri

option

The currently available configuration options are: "ndots" , "timeout" , "max-timeouts" , "max-inflight" , and "attempts" .

value

Option value.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

EventDnsBase::parseResolvConf
EventDnsBase::setSearchNdots
EventDnsBase


Set the 'ndots' parameter for searches

EventDnsBase::setOption
EventHttp
EventDnsBase
PHP Manual

EventDnsBase::setSearchNdots

(PECL event >= 1.2.6-beta)

EventDnsBase::setSearchNdots — Set the 'ndots' parameter for searches

Descrierea

public bool EventDnsBase::setSearchNdots ( int $ndots )

Set the 'ndots' parameter for searches. Sets the number of dots which, when found in a name, causes the first query to be without any search domain.

Parametri

ndots

The number of dots.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

EventDnsBase::setOption
EventHttp
EventDnsBase


The EventHttp class

(PECL event >= 1.4.0-beta)

Introducere

Represents HTTP server.

Sinopsisul clasei

final EventHttp {
/* Metode */
public bool accept ( mixed $socket )
public bool addServerAlias ( string $alias )
public void bind ( string $address , int $port )
public __construct ( EventBase $base [, EventSslContext $ctx = NULL ] )
public bool removeServerAlias ( string $alias )
public void setAllowedMethods ( int $methods )
public void setCallback ( string $path , string $cb [, string $arg ] )
public void setDefaultCallback ( string $cb [, string $arg ] )
public void setMaxBodySize ( int $value )
public void setMaxHeadersSize ( int $value )
public void setTimeout ( int $value )
}

Cuprins

  • EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource
  • EventHttp::addServerAlias — Adds a server alias to the HTTP server object
  • EventHttp::bind — Binds an HTTP server on the specified address and port
  • EventHttp::__construct — Constructs EventHttp object(the HTTP server)
  • EventHttp::removeServerAlias — Removes server alias
  • EventHttp::setAllowedMethods — Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks
  • EventHttp::setCallback — Sets a callback for specified URI
  • EventHttp::setDefaultCallback — Sets default callback to handle requests that are not caught by specific callbacks
  • EventHttp::setMaxBodySize — Sets maximum request body size
  • EventHttp::setMaxHeadersSize — Sets maximum HTTP header size
  • EventHttp::setTimeout — Sets the timeout for an HTTP request
EventDnsBase::setSearchNdots
EventHttp::accept
Event


Makes an HTTP server accept connections on the specified socket stream or resource

EventHttp
EventHttp::addServerAlias
EventHttp
PHP Manual

EventHttp::accept

(PECL event >= 1.2.6-beta)

EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource

Descrierea

public bool EventHttp::accept ( mixed $socket )

Makes an HTTP server accept connections on the specified socket stream or resource. The socket should be ready to accept connections.

Can be called multiple times to accept connections on different sockets.

Nota:

To bind a socket, listen , and accept connections on the socket in s single call use EventHttp::bind() . EventHttp::accept() is needed only if one already has a socket ready to accept connections.

Parametri

socket

Socket resource, stream or numeric file descriptor representing a socket ready to accept connections.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

Exemple

Example #1 EventHttp::accept() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$addresses = array (
     8091 => "127.0.0.1",
     8092 => "127.0.0.2",
);
$i = 0;

$socket = array();

foreach ($addresses as $port => $ip) {
    echo $ip, " ", $port, PHP_EOL;
    $socket[$i] = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (!socket_bind($socket[$i], $ip, $port)) {
        exit("socket_bind failed\n");
    }
    socket_listen($socket[$i], 0);
    socket_set_nonblock($socket[$i]);

    if (!$http->accept($socket[$i])) {
        echo "Accept failed\n";
        exit(1);
    }

    ++$i;
}

$http->setCallback("/some-page", function() {
 echo "(some-page)\n";
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
    echo "OK\n";
});

$http->setDefaultCallback(function($req) {
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
    echo "OK\n";
});

$signal = Event::signal($base, SIGINT, function () use ($base) {
    echo "Caught SIGINT. Stopping...\n";
    $base->stop();
});
$signal->add();

$base->dispatch();
echo "END\n";
// We didn't close sockets, since Libevent already sets
// CLOSE_ON_FREE and CLOSE_ON_EXEC flags on the file
// descriptor associated with the sockets.
?>

Exemplul de mai sus va afi?a ceva similar cu:

Client:
$ nc 127.0.0.1 8091
GET /about HTTP/1.0
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

Server:
127.0.0.1 8091
127.0.0.2 8092
URI: /about
OK

A se vedea ?i

  • EventHttp::bind() - Binds an HTTP server on the specified address and port
EventHttp
EventHttp::addServerAlias
EventHttp


Adds a server alias to the HTTP server object

EventHttp::accept
EventHttp::bind
EventHttp
PHP Manual

EventHttp::addServerAlias

(PECL event >= 1.4.0-beta)

EventHttp::addServerAlias — Adds a server alias to the HTTP server object

Descrierea

public bool EventHttp::addServerAlias ( string $alias )

Adds a server alias to the HTTP server object.

Parametri

alias

The alias to add.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

Exemple

Example #1 EventHttp::addServerAlias() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!$http->bind("127.0.0.1", 8088)) {
    exit("bind(1) failed\n");
};

if (!$http->addServerAlias("local.net")) {
    exit("Failed to add server alias\n");
}

$http->setCallback("/about", function($req) {
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
});
$base->dispatch();
?>

A se vedea ?i

  • EventHttp::removeServerAlias() - Removes server alias
EventHttp::accept
EventHttp::bind
EventHttp


Binds an HTTP server on the specified address and port

EventHttp::addServerAlias
EventHttp::__construct
EventHttp
PHP Manual

EventHttp::bind

(PECL event >= 1.2.6-beta)

EventHttp::bind — Binds an HTTP server on the specified address and port

Descrierea

public void EventHttp::bind ( string $address , int $port )

Binds an HTTP server on the specified address and port.

Can be called multiple times to bind the same HTTP server to multiple different ports.

Parametri

address

A string containing the IP address to listen(2) on.

port

The port number to listen on.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

Exemple

Example #1 EventHttp::bind() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!$http->bind("127.0.0.1", 8088)) {
    exit("bind(1) failed\n");
};
if (!$http->bind("127.0.0.1", 8089)) {
    exit("bind(2) failed\n");
};

$http->setCallback("/about", function($req) {
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
    echo "OK\n";
});

$base->dispatch();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Client:

$ nc 127.0.0.1 8088
GET /about HTTP/1.0
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

$ nc 127.0.0.1 8089
GET /unknown HTTP/1.0
Connection: close

HTTP/1.1 404 Not Found
Content-Type: text/html
Date: Wed, 13 Mar 2013 04:14:41 GMT
Content-Length: 149
Connection: close

<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL /unknown was not found on this server.</p></body></html>

Server:
URI: /about
OK

A se vedea ?i

  • EventHttp::accept() - Makes an HTTP server accept connections on the specified socket stream or resource
EventHttp::addServerAlias
EventHttp::__construct
EventHttp


Constructs EventHttp object(the HTTP server)

EventHttp::bind
EventHttp::removeServerAlias
EventHttp
PHP Manual

EventHttp::__construct

(PECL event >= 1.2.6-beta)

EventHttp::__construct — Constructs EventHttp object(the HTTP server)

Descrierea

public EventHttp::__construct ( EventBase $base [, EventSslContext $ctx = NULL ] )

Constructs the HTTP server object.

Parametri

base

Associated event base.

ctx

EventSslContext class object. Turns plain HTTP server into HTTPS server. It means that if ctx is configured correctly, then the underlying buffer events will be based on OpenSSL sockets. Thus, all traffic will pass through the SSL or TLS.

Nota:

This parameter is available only if Event is compiled with OpenSSL support and only with Libevent 2.1.0-alpha and higher.

Valorile întoarse

Returns EventHttp object.

Istoricul schimbarilor

Versiune | Descriere
1.9.0 | OpenSSL support (ctx) added.

Exemple

Example #1 Simple HTTP server

<?php
/*
 * Simple HTTP server.
 *
 * To test it:
 * 1) Run it on a port of your choice, e.g.:
 * $ php examples/http.php 8010
 * 2) In another terminal connect to some address on this port
 * and make GET or POST request(others are turned off here), e.g.:
 * $ nc -t 127.0.0.1 8010
 * POST /about HTTP/1.0
 * Content-Type: text/plain
 * Content-Length: 4
 * Connection: close
 * (press Enter)
 *
 * It will output
 * a=12
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * $ nc -t 127.0.0.1 8010
 * GET /dump HTTP/1.0
 * Content-Type: text/plain
 * Content-Encoding: UTF-8
 * Connection: close
 * (press Enter)
 *
 * It will output:
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 * (press Enter)
 *
 * $ nc -t 127.0.0.1 8010
 * GET /unknown HTTP/1.0
 * Connection: close
 *
 * It will output:
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * 3) See what the server outputs on the previous terminal window.
 */

function _http_dump($req, $data) {
    static $counter      = 0;
    static $max_requests = 2;

    if (++$counter >= $max_requests)  {
        echo "Counter reached max requests $max_requests. Exiting\n";
        exit();
    }

    echo __METHOD__, " called\n";
    echo "request:"; var_dump($req);
    echo "data:"; var_dump($data);

    echo "\n===== DUMP =====\n";
    echo "Command:", $req->getCommand(), PHP_EOL;
    echo "URI:", $req->getUri(), PHP_EOL;
    echo "Input headers:"; var_dump($req->getInputHeaders());
    echo "Output headers:"; var_dump($req->getOutputHeaders());

    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";

    echo "\n >> Reading input buffer ...\n";
    $buf = $req->getInputBuffer();
    while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
        echo $s, PHP_EOL;
    }
    echo "No more data in the buffer\n";
}

function _http_about($req) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_default($req, $data) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

$port = 8010;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

Exemplul de mai sus va afi?a ceva similar cu:

a=12
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close
(press Enter)

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close
EventHttp::bind
EventHttp::removeServerAlias
EventHttp


Removes server alias

EventHttp::__construct
EventHttp::setAllowedMethods
EventHttp
PHP Manual

EventHttp::removeServerAlias

(PECL event >= 1.4.0-beta)

EventHttp::removeServerAlias — Removes server alias

Descrierea

public bool EventHttp::removeServerAlias ( string $alias )

Removes server alias added with EventHttp::addServerAlias()

Parametri

alias

The alias to remove.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventHttp::addServerAlias() - Adds a server alias to the HTTP server object
EventHttp::__construct
EventHttp::setAllowedMethods
EventHttp


Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

EventHttp::removeServerAlias
EventHttp::setCallback
EventHttp
PHP Manual

EventHttp::setAllowedMethods

(PECL event >= 1.4.0-beta)

EventHttp::setAllowedMethods — Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

Descrierea

public void EventHttp::setAllowedMethods ( int $methods )

Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

If not supported they will generate a "405 Method not allowed" response.

By default this includes the following methods: GET , POST , HEAD , PUT , DELETE . See EventHttpRequest::CMD_* constants.

Parametri

methods

A bit mask of EventHttpRequest::CMD_* constants .

Valorile întoarse

Nu este întoarsa nici o valoare.

EventHttp::removeServerAlias
EventHttp::setCallback
EventHttp


Sets a callback for specified URI

EventHttp::setAllowedMethods
EventHttp::setDefaultCallback
EventHttp
PHP Manual

EventHttp::setCallback

(PECL event >= 1.4.0-beta)

EventHttp::setCallback — Sets a callback for specified URI

Descrierea

public void EventHttp::setCallback ( string $path , string $cb [, string $arg ] )

Sets a callback for specified URI.

Parametri

path

The path for which to invoke the callback.

cb

The callback callable that gets invoked on requested path . It should match the following prototype:

void callback ([ EventHttpRequest $req = NULL [, mixed $arg = NULL ]] )

req

EventHttpRequest object.

arg

Custom data.

arg

Custom data.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

Exemple

Example #1 EventHttp::setCallback() example

<?php
/*
 * Simple HTTP server.
 *
 * To test it:
 * 1) Run it on a port of your choice, e.g.:
 * $ php examples/http.php 8010
 * 2) In another terminal connect to some address on this port
 * and make GET or POST request(others are turned off here), e.g.:
 * $ nc -t 127.0.0.1 8010
 * POST /about HTTP/1.0
 * Content-Type: text/plain
 * Content-Length: 4
 * Connection: close
 * (press Enter)
 *
 * It will output
 * a=12
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * 3) See what the server outputs on the previous terminal window.
 */

function _http_dump($req, $data) {
    static $counter      = 0;
    static $max_requests = 2;

    if (++$counter >= $max_requests)  {
        echo "Counter reached max requests $max_requests. Exiting\n";
        exit();
    }

    echo __METHOD__, " called\n";
    echo "request:"; var_dump($req);
    echo "data:"; var_dump($data);

    echo "\n===== DUMP =====\n";
    echo "Command:", $req->getCommand(), PHP_EOL;
    echo "URI:", $req->getUri(), PHP_EOL;
    echo "Input headers:"; var_dump($req->getInputHeaders());
    echo "Output headers:"; var_dump($req->getOutputHeaders());

    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";

    echo "\n >> Reading input buffer ...\n";
    $buf = $req->getInputBuffer();
    while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
        echo $s, PHP_EOL;
    }
    echo "No more data in the buffer\n";
}

function _http_about($req) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_default($req, $data) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

$port = 8010;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

Exemplul de mai sus va afi?a ceva similar cu:

a=12
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

A se vedea ?i

  • EventHttp::setDefaultCallback() - Sets default callback to handle requests that are not caught by specific callbacks
EventHttp::setAllowedMethods
EventHttp::setDefaultCallback
EventHttp


Sets default callback to handle requests that are not caught by specific callbacks

EventHttp::setCallback
EventHttp::setMaxBodySize
EventHttp
PHP Manual

EventHttp::setDefaultCallback

(PECL event >= 1.4.0-beta)

EventHttp::setDefaultCallback — Sets default callback to handle requests that are not caught by specific callbacks

Descrierea

public void EventHttp::setDefaultCallback ( string $cb [, string $arg ] )

Sets default callback to handle requests that are not caught by specific callbacks

Parametri

cb

The callback callable . It should match the following prototype:

void callback ([ EventHttpRequest $req = NULL [, mixed $arg = NULL ]] )

req

EventHttpRequest object.

arg

Custom data.

arg

User custom data passed to the callback.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

Exemple

Example #1 EventHttp::setDefaultCallback() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!$http->bind("127.0.0.1", 8088)) {
    exit("bind(1) failed\n");
};

$http->setDefaultCallback(function($req) {
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
});

$base->dispatch();
?>

A se vedea ?i

  • EventHttp::setCallback() - Sets a callback for specified URI
EventHttp::setCallback
EventHttp::setMaxBodySize
EventHttp


Sets maximum request body size

EventHttp::setDefaultCallback
EventHttp::setMaxHeadersSize
EventHttp
PHP Manual

EventHttp::setMaxBodySize

(PECL event >= 1.4.0-beta)

EventHttp::setMaxBodySize — Sets maximum request body size

Descrierea

public void EventHttp::setMaxBodySize ( int $value )

Sets maximum request body size.

Parametri

value

The body size in bytes.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventHttp::setMaxHeadersSize() - Sets maximum HTTP header size
EventHttp::setDefaultCallback
EventHttp::setMaxHeadersSize
EventHttp


Sets maximum HTTP header size

EventHttp::setMaxBodySize
EventHttp::setTimeout
EventHttp
PHP Manual

EventHttp::setMaxHeadersSize

(PECL event >= 1.4.0-beta)

EventHttp::setMaxHeadersSize — Sets maximum HTTP header size

Descrierea

public void EventHttp::setMaxHeadersSize ( int $value )

Sets maximum HTTP header size.

Parametri

value

The header size in bytes.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventHttp::setMaxHeadersSize()
EventHttp::setMaxBodySize
EventHttp::setTimeout
EventHttp


Sets the timeout for an HTTP request

EventHttp::setMaxHeadersSize
EventHttpConnection
EventHttp
PHP Manual

EventHttp::setTimeout

(PECL event >= 1.4.0-beta)

EventHttp::setTimeout — Sets the timeout for an HTTP request

Descrierea

public void EventHttp::setTimeout ( int $value )

Sets the timeout for an HTTP request.

Parametri

value

The timeout in seconds.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventHttp::setMaxHeadersSize
EventHttpConnection
EventHttp


The EventHttpConnection class

(PECL event >= 1.4.0-beta)

Introducere

Represents an HTTP connection.

Sinopsisul clasei

EventHttpConnection {
/* Metode */
public __construct ( EventBase $base , EventDnsBase $dns_base , string $address , int $port [, EventSslContext $ctx = NULL ] )
public EventBase getBase ( void )
public void getPeer ( string &$address , int &$port )
public bool makeRequest ( EventHttpRequest $req , int $type , string $uri )
public void setCloseCallback ( callable $callback [, mixed $data ] )
public void setLocalAddress ( string $address )
public void setLocalPort ( int $port )
public void setMaxBodySize ( string $max_size )
public void setMaxHeadersSize ( string $max_size )
public void setRetries ( int $retries )
public void setTimeout ( int $timeout )
}

Cuprins

  • EventHttpConnection::__construct — Constructs EventHttpConnection object
  • EventHttpConnection::getBase — Returns event base associated with the connection
  • EventHttpConnection::getPeer — Gets the remote address and port associated with the connection
  • EventHttpConnection::makeRequest — Makes an HTTP request over the specified connection
  • EventHttpConnection::setCloseCallback — Set callback for connection close
  • EventHttpConnection::setLocalAddress — Sets the IP address from which HTTP connections are made
  • EventHttpConnection::setLocalPort — Sets the local port from which connections are made
  • EventHttpConnection::setMaxBodySize — Sets maximum body size for the connection
  • EventHttpConnection::setMaxHeadersSize — Sets maximum header size
  • EventHttpConnection::setRetries — Sets the retry limit for the connection
  • EventHttpConnection::setTimeout — Sets the timeout for the connection
EventHttp::setTimeout
EventHttpConnection::__construct
Event


Constructs EventHttpConnection object

EventHttpConnection
EventHttpConnection::getBase
EventHttpConnection
PHP Manual

EventHttpConnection::__construct

(PECL event >= 1.2.6-beta)

EventHttpConnection::__construct — Constructs EventHttpConnection object

Descrierea

public EventHttpConnection::__construct ( EventBase $base , EventDnsBase $dns_base , string $address , int $port [, EventSslContext $ctx = NULL ] )

Constructs EventHttpConnection object.

Parametri

base

Associated event base.

dns_base

If dns_base is NULL, hostname resolution will block.

address

The address to connect to.

port

The port to connect to.

ctx

EventSslContext class object. Enables OpenSSL.

Nota:

This parameter is available only if Event is compiled with OpenSSL support and only with Libevent 2.1.0-alpha and higher.

Valorile întoarse

Returns EventHttpConnection object.

Istoricul schimbarilor

Versiune | Descriere
1.9.0 | OpenSSL support (ctx) added.

EventHttpConnection
EventHttpConnection::getBase
EventHttpConnection


Returns event base associated with the connection

EventHttpConnection::__construct
EventHttpConnection::getPeer
EventHttpConnection
PHP Manual

EventHttpConnection::getBase

(PECL event >= 1.2.6-beta)

EventHttpConnection::getBase — Returns event base associated with the connection

Descrierea

public EventBase EventHttpConnection::getBase ( void )

Returns event base associated with the connection.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

On success returns EventBase object associated with the connection. Otherwise FALSE.

EventHttpConnection::__construct
EventHttpConnection::getPeer
EventHttpConnection


Gets the remote address and port associated with the connection

EventHttpConnection::getBase
EventHttpConnection::makeRequest
EventHttpConnection
PHP Manual

EventHttpConnection::getPeer

(PECL event >= 1.2.6-beta)

EventHttpConnection::getPeer — Gets the remote address and port associated with the connection

Descrierea

public void EventHttpConnection::getPeer ( string &$address , int &$port )

Gets the remote address and port associated with the connection

Parametri

address

Address of the peer.

port

Port of the peer.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventHttpConnection::getBase
EventHttpConnection::makeRequest
EventHttpConnection


Makes an HTTP request over the specified connection

EventHttpConnection::getPeer
EventHttpConnection::setCloseCallback
EventHttpConnection
PHP Manual

EventHttpConnection::makeRequest

(PECL event >= 1.4.0-beta)

EventHttpConnection::makeRequest — Makes an HTTP request over the specified connection

Descrierea

public bool EventHttpConnection::makeRequest ( EventHttpRequest $req , int $type , string $uri )

Makes an HTTP request over the specified connection. type is one of EventHttpRequest::CMD_* constants.

Parametri

req

The connection object over which to send the request.

type

One of EventHttpRequest::CMD_* constants .

uri

The URI associated with the request.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

Exemple

Example #1 EventHttpConnection::makeRequest() example

<?php
function _request_handler($req, $base) {
    echo __FUNCTION__, PHP_EOL;

    if (is_null($req)) {
        echo "Timed out\n";
    } else {
        $response_code = $req->getResponseCode();

        if ($response_code == 0) {
            echo "Connection refused\n";
        } elseif ($response_code != 200) {
            echo "Unexpected response: $response_code\n";
        } else {
            echo "Success: $response_code\n";
            $buf = $req->getInputBuffer();
            echo "Body:\n";
            while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
                echo $s, PHP_EOL;
            }
        }
    }

    $base->exit(NULL);
}

$address = "127.0.0.1";
$port = 80;

$base = new EventBase();
$conn = new EventHttpConnection($base, NULL, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest("_request_handler", $base);

$req->addHeader("Host", $address, EventHttpRequest::OUTPUT_HEADER);
$req->addHeader("Content-Length", "0", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_GET, "/index.cphp");

$base->loop();
?>

Exemplul de mai sus va afi?a ceva similar cu:

_request_handler
Success: 200
Body:
PHP, date:
2013-03-13T20:27:52+05:00

A se vedea ?i

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request
EventHttpConnection::getPeer
EventHttpConnection::setCloseCallback
EventHttpConnection


Set callback for connection close

EventHttpConnection::makeRequest
EventHttpConnection::setLocalAddress
EventHttpConnection
PHP Manual

EventHttpConnection::setCloseCallback

(PECL event >= 1.8.0)

EventHttpConnection::setCloseCallback — Set callback for connection close

Descrierea

public void EventHttpConnection::setCloseCallback ( callable $callback [, mixed $data ] )

Sets callback for connection close.

Parametri

callback

Callback which is called when connection is closed. Should match the following prototype:

void callback ([ EventHttpConnection $conn = NULL [, mixed $arg = NULL ]] )

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 EventHttpConnection::setCloseCallback() example

<?php
/*
 * Setting up close-connection callback
 *
 * The script handles closed connections using HTTP API.
 *
 * Usage:
 * 1) Launch the server:
 * $ php examples/http_closecb.php 4242
 *
 * 2) Launch a client in another terminal. Telnet-like
 * session should look like the following:
 *
 * $ nc -t 127.0.0.1 4242
 * GET / HTTP/1.0
 * Connection: close
 *
 * The server will output something similar to the following:
 *
 * HTTP/1.0 200 OK
 * Content-Type: multipart/x-mixed-replace;boundary=boundarydonotcross
 * Connection: close
 *
 * <html>
 *
 * 3) Terminate the client connection abruptly,
 * i.e. kill the process, or just press Ctrl-C.
 *
 * 4) Check if the server called _close_callback.
 * The script should output "_close_callback" string to standard output.
 *
 * 5) Check if the server's process has no orphaned connections,
 * e.g. with `lsof` utility.
 */

function _close_callback($conn)
{
    echo __FUNCTION__, PHP_EOL;
}

function _http_default($req, $dummy)
{
    $conn = $req->getConnection();
    $conn->setCloseCallback('_close_callback', NULL);

    /*
    By enabling Event::READ we protect the server against unclosed conections.
    This is a peculiarity of Libevent. The library disables Event::READ events
     on this connection, and the server is not notified about terminated
    connections.

    So each time client terminates connection abruptly, we get an orphaned
    connection. For instance, the following is a part of `lsof -p $PID | grep TCP`
    command after client has terminated connection:

    57-php     15057 ruslan  6u  unix 0xffff8802fb59c780   0t0  125187 socket
    58:php     15057 ruslan  7u  IPv4             125189   0t0     TCP *:4242 (LISTEN)
    59:php     15057 ruslan  8u  IPv4             124342   0t0     TCP localhost:4242->localhost:37375 (CLOSE_WAIT)

    where $PID is our process ID.

    The following block of code fixes such kind of orphaned connections.
     */
    $bev = $req->getBufferEvent();
    $bev->enable(Event::READ);
    // We have to free it explicitly. See
EventHttpRequest::getConnection()
$bev->free(); // we have to free it explicitly

    $req->addHeader(
        'Content-Type',
        'multipart/x-mixed-replace;boundary=boundarydonotcross',
        EventHttpRequest::OUTPUT_HEADER
    );

    $buf = new EventBuffer();
    $buf->add('<html>');

    $req->sendReply(200, "OK");
    $req->sendReplyChunk($buf);
}

$port = 4242;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);

$http->setDefaultCallback("_http_default", NULL);
$http->bind("0.0.0.0", $port);
$base->loop();

?>
EventHttpConnection::makeRequest
EventHttpConnection::setLocalAddress
EventHttpConnection


Sets the IP address from which HTTP connections are made

EventHttpConnection::setCloseCallback
EventHttpConnection::setLocalPort
EventHttpConnection
PHP Manual

EventHttpConnection::setLocalAddress

(PECL event >= 1.2.6-beta)

EventHttpConnection::setLocalAddress — Sets the IP address from which HTTP connections are made

Descrierea

public void EventHttpConnection::setLocalAddress ( string $address )

Sets the IP address from which http connections are made.

Parametri

address

The IP address from which HTTP connections are made.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventHttpConnection::setLocalPort() - Sets the local port from which connections are made
EventHttpConnection::setCloseCallback
EventHttpConnection::setLocalPort
EventHttpConnection


Sets the local port from which connections are made

EventHttpConnection::setLocalAddress
EventHttpConnection::setMaxBodySize
EventHttpConnection
PHP Manual

EventHttpConnection::setLocalPort

(PECL event >= 1.2.6-beta)

EventHttpConnection::setLocalPort — Sets the local port from which connections are made

Descrierea

public void EventHttpConnection::setLocalPort ( int $port )

Sets the local port from which connections are made.

Parametri

port

The port number.

Valorile întoarse

A se vedea ?i

  • EventHttpConnection::setLocalAddress() - Sets the IP address from which HTTP connections are made
EventHttpConnection::setLocalAddress
EventHttpConnection::setMaxBodySize
EventHttpConnection


Sets maximum body size for the connection

EventHttpConnection::setLocalPort
EventHttpConnection::setMaxHeadersSize
EventHttpConnection
PHP Manual

EventHttpConnection::setMaxBodySize

(PECL event >= 1.2.6-beta)

EventHttpConnection::setMaxBodySize — Sets maximum body size for the connection

Descrierea

public void EventHttpConnection::setMaxBodySize ( string $max_size )

Sets maximum body size for the connection.

Parametri

max_size

The maximum body size in bytes.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventHttpConnection::setMaxHeadersSize() - Sets maximum header size
EventHttpConnection::setLocalPort
EventHttpConnection::setMaxHeadersSize
EventHttpConnection


Sets maximum header size

EventHttpConnection::setMaxBodySize
EventHttpConnection::setRetries
EventHttpConnection
PHP Manual

EventHttpConnection::setMaxHeadersSize

(PECL event >= 1.2.6-beta)

EventHttpConnection::setMaxHeadersSize — Sets maximum header size

Descrierea

public void EventHttpConnection::setMaxHeadersSize ( string $max_size )

Sets maximum header size for the connection.

Parametri

max_size

The maximum header size in bytes.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventHttpConnection::setMaxBodySize() - Sets maximum body size for the connection
EventHttpConnection::setMaxBodySize
EventHttpConnection::setRetries
EventHttpConnection


Sets the retry limit for the connection

EventHttpConnection::setMaxHeadersSize
EventHttpConnection::setTimeout
EventHttpConnection
PHP Manual

EventHttpConnection::setRetries

(PECL event >= 1.2.6-beta)

EventHttpConnection::setRetries — Sets the retry limit for the connection

Descrierea

public void EventHttpConnection::setRetries ( int $retries )

Sets the retry limit for the connection

Parametri

retries

The retry limit. -1 means infinity.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventHttpConnection::setMaxHeadersSize
EventHttpConnection::setTimeout
EventHttpConnection


Sets the timeout for the connection

EventHttpConnection::setRetries
EventHttpRequest
EventHttpConnection
PHP Manual

EventHttpConnection::setTimeout

(PECL event >= 1.2.6-beta)

EventHttpConnection::setTimeout — Sets the timeout for the connection

Descrierea

public void EventHttpConnection::setTimeout ( int $timeout )

Sets the timeout for the connection

Parametri

timeout

Timeout in seconds.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventHttpConnection::setRetries
EventHttpRequest
EventHttpConnection


The EventHttpRequest class

(PECL event >= 1.4.0-beta)

Introducere

Represents an HTTP request.

Sinopsisul clasei

EventHttpRequest {
/* Constants */
const integer CMD_GET = 1 ;
const integer CMD_POST = 2 ;
const integer CMD_HEAD = 4 ;
const integer CMD_PUT = 8 ;
const integer CMD_DELETE = 16 ;
const integer CMD_OPTIONS = 32 ;
const integer CMD_TRACE = 64 ;
const integer CMD_CONNECT = 128 ;
const integer CMD_PATCH = 256 ;
const integer INPUT_HEADER = 1 ;
const integer OUTPUT_HEADER = 2 ;
/* Metode */
public bool addHeader ( string $key , string $value , int $type )
public void cancel ( void )
public void clearHeaders ( void )
public void closeConnection ( void )
public __construct ( callable $callback [, mixed $data = NULL ] )
public void findHeader ( string $key , string $type )
public void free ( void )
public EventBufferEvent closeConnection ( void )
public void getCommand ( void )
public EventHttpConnection closeConnection ( void )
public string getHost ( void )
public EventBuffer getInputBuffer ( void )
public array getInputHeaders ( void )
public EventBuffer getOutputBuffer ( void )
public void getOutputHeaders ( void )
public int getResponseCode ( void )
public string getUri ( void )
public void removeHeader ( string $key , string $type )
public void sendError ( int $error [, string $reason = NULL ] )
public void sendReply ( int $code , string $reason [, EventBuffer $buf ] )
public void sendReplyChunk ( EventBuffer $buf )
public void sendReplyEnd ( void )
public void sendReplyStart ( int $code , string $reason )
}

Constante predefinite

EventHttpRequest::CMD_GET

GET method(command)

EventHttpRequest::CMD_POST

POST method(command)

EventHttpRequest::CMD_HEAD

HEAD method(command)

EventHttpRequest::CMD_PUT

PUT method(command)

EventHttpRequest::CMD_DELETE

DELETE command(method)

EventHttpRequest::CMD_OPTIONS

OPTIONS method(command)

EventHttpRequest::CMD_TRACE

TRACE method(command)

EventHttpRequest::CMD_CONNECT

CONNECT method(command)

EventHttpRequest::CMD_PATCH

PATCH method(command)

EventHttpRequest::INPUT_HEADER

Request input header type.

EventHttpRequest::OUTPUT_HEADER

Request output header type.

Cuprins

  • EventHttpRequest::addHeader — Adds an HTTP header to the headers of the request
  • EventHttpRequest::cancel — Cancels a pending HTTP request
  • EventHttpRequest::clearHeaders — Removes all output headers from the header list of the request
  • EventHttpRequest::closeConnection — Closes associated HTTP connection
  • EventHttpRequest::__construct — Constructs EventHttpRequest object
  • EventHttpRequest::findHeader — Finds the value belonging a header
  • EventHttpRequest::free — Frees the object and removes associated events
  • EventHttpRequest::getBufferEvent — Returns EventBufferEvent object
  • EventHttpRequest::getCommand — Returns the request command(method)
  • EventHttpRequest::getConnection — Returns EventHttpConnection object
  • EventHttpRequest::getHost — Returns the request host
  • EventHttpRequest::getInputBuffer — Returns the input buffer
  • EventHttpRequest::getInputHeaders — Returns associative array of the input headers
  • EventHttpRequest::getOutputBuffer — Returns the output buffer of the request
  • EventHttpRequest::getOutputHeaders — Returns associative array of the output headers
  • EventHttpRequest::getResponseCode — Returns the response code
  • EventHttpRequest::getUri — Returns the request URI
  • EventHttpRequest::removeHeader — Removes an HTTP header from the headers of the request
  • EventHttpRequest::sendError — Send an HTML error message to the client
  • EventHttpRequest::sendReply — Send an HTML reply to the client
  • EventHttpRequest::sendReplyChunk — Send another data chunk as part of an ongoing chunked reply
  • EventHttpRequest::sendReplyEnd — Complete a chunked reply, freeing the request as appropriate
  • EventHttpRequest::sendReplyStart — Initiate a chunked reply
EventHttpConnection::setTimeout
EventHttpRequest::addHeader
Event


Adds an HTTP header to the headers of the request

EventHttpRequest
EventHttpRequest::cancel
EventHttpRequest
PHP Manual

EventHttpRequest::addHeader

(PECL event >= 1.4.0-beta)

EventHttpRequest::addHeader — Adds an HTTP header to the headers of the request

Descrierea

public bool EventHttpRequest::addHeader ( string $key , string $value , int $type )

Adds an HTTP header to the headers of the request.

Parametri

key

Header name.

value

Header value.

type

One of EventHttpRequest::*_HEADER constants .

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventHttpRequest::removeHeader() - Removes an HTTP header from the headers of the request
EventHttpRequest
EventHttpRequest::cancel
EventHttpRequest


Cancels a pending HTTP request

EventHttpRequest::addHeader
EventHttpRequest::clearHeaders
EventHttpRequest
PHP Manual

EventHttpRequest::cancel

(PECL event >= 1.4.0-beta)

EventHttpRequest::cancel — Cancels a pending HTTP request

Descrierea

public void EventHttpRequest::cancel ( void )

Cancels a pending HTTP request.

Cancels an ongoing HTTP request. The callback associated with this request is not executed and the request object is freed. If the request is currently being processed, e.g. it is ongoing, the corresponding EventHttpConnection object is going to get reset.

A request cannot be canceled if its callback has executed already. A request may be canceled reentrantly from its chunked callback.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventHttpRequest::addHeader
EventHttpRequest::clearHeaders
EventHttpRequest


Removes all output headers from the header list of the request

EventHttpRequest::cancel
EventHttpRequest::closeConnection
EventHttpRequest
PHP Manual

EventHttpRequest::clearHeaders

(PECL event >= 1.4.0-beta)

EventHttpRequest::clearHeaders — Removes all output headers from the header list of the request

Descrierea

public void EventHttpRequest::clearHeaders ( void )

Removes all output headers from the header list of the request.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request
EventHttpRequest::cancel
EventHttpRequest::closeConnection
EventHttpRequest


Closes associated HTTP connection

EventHttpRequest::clearHeaders
EventHttpRequest::__construct
EventHttpRequest
PHP Manual

EventHttpRequest::closeConnection

(PECL event >= 1.8.0)

EventHttpRequest::closeConnection — Closes associated HTTP connection

Descrierea

public void EventHttpRequest::closeConnection ( void )

Closes HTTP connection associated with the request.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventHttpRequest::clearHeaders
EventHttpRequest::__construct
EventHttpRequest


Constructs EventHttpRequest object

EventHttpRequest::closeConnection
EventHttpRequest::findHeader
EventHttpRequest
PHP Manual

EventHttpRequest::__construct

(PECL event >= 1.4.0-beta)

EventHttpRequest::__construct — Constructs EventHttpRequest object

Descrierea

public EventHttpRequest::__construct ( callable $callback [, mixed $data = NULL ] )

Constructs EventHttpRequest object.

Parametri

callback

Gets invoked on requesting path. Should match the following prototype:

void callback ([ EventHttpRequest $req = NULL [, mixed $arg = NULL ]] )
data

User custom data passed to the callback.

Valorile întoarse

Returns EventHttpRequest object.

Exemple

Example #1 EventHttpRequest::__construct() example

<?php

function _request_handler($req, $base) {
    echo __FUNCTION__, PHP_EOL;

    if (is_null($req)) {
        echo "Timed out\n";
    } else {
        $response_code = $req->getResponseCode();

        if ($response_code == 0) {
            echo "Connection refused\n";
        } elseif ($response_code != 200) {
            echo "Unexpected response: $response_code\n";
        } else {
            echo "Success: $response_code\n";
            $buf = $req->getInputBuffer();
            echo "Body:\n";
            while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
                echo $s, PHP_EOL;
            }
        }
    }

    $base->exit(NULL);
}

$address = "127.0.0.1";
$port = 80;

$base = new EventBase();
$conn = new EventHttpConnection($base, NULL, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest("_request_handler", $base);

$req->addHeader("Host", $address, EventHttpRequest::OUTPUT_HEADER);
$req->addHeader("Content-Length", "0", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_GET, "/index.cphp");

$base->loop();
?>

A se vedea ?i

  • EventHttpRequest::cancel() - Cancels a pending HTTP request
  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request
EventHttpRequest::closeConnection
EventHttpRequest::findHeader
EventHttpRequest


Finds the value belonging a header

EventHttpRequest::__construct
EventHttpRequest::free
EventHttpRequest
PHP Manual

EventHttpRequest::findHeader

(PECL event >= 1.4.0-beta)

EventHttpRequest::findHeader — Finds the value belonging a header

Descrierea

public void EventHttpRequest::findHeader ( string $key , string $type )

Finds the value belonging a header.

Parametri

key

The header name.

type

One of EventHttpRequest::*_HEADER constants .

Valorile întoarse

Returns NULL if header not found.

A se vedea ?i

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request
EventHttpRequest::__construct
EventHttpRequest::free
EventHttpRequest


Frees the object and removes associated events

EventHttpRequest::findHeader
EventHttpRequest::getBufferEvent
EventHttpRequest
PHP Manual

EventHttpRequest::free

(PECL event >= 1.4.0-beta)

EventHttpRequest::free — Frees the object and removes associated events

Descrierea

public void EventHttpRequest::free ( void )

Frees the object and removes associated events.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventHttpRequest::findHeader
EventHttpRequest::getBufferEvent
EventHttpRequest


Returns EventBufferEvent object

EventHttpRequest::free
EventHttpRequest::getCommand
EventHttpRequest
PHP Manual

EventHttpRequest::getBufferEvent

(PECL event >= 1.8.0)

EventHttpRequest::getBufferEvent — Returns EventBufferEvent object

Descrierea

public EventBufferEvent EventHttpRequest::closeConnection ( void )

Returns EventBufferEvent object which represents buffer event that the connection is using.

Avertizare

The reference counter of the returned object will be incremented by one to protect internal structures against premature destruction when the method is called from a user callback. So the EventBufferEvent object should be freed explicitly with EventBufferEvent::free() method. Otherwise memory will leak.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns EventBufferEvent object.

A se vedea ?i

  • EventHttpRequest::getConnection() - Returns EventHttpConnection object
EventHttpRequest::free
EventHttpRequest::getCommand
EventHttpRequest


Returns the request command(method)

EventHttpRequest::getBufferEvent
EventHttpRequest::getConnection
EventHttpRequest
PHP Manual

EventHttpRequest::getCommand

(PECL event >= 1.4.0-beta)

EventHttpRequest::getCommand — Returns the request command(method)

Descrierea

public void EventHttpRequest::getCommand ( void )

Returns the request command, one of EventHttpRequest::CMD_* constants.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the request command, one of EventHttpRequest::CMD_* constants.

EventHttpRequest::getBufferEvent
EventHttpRequest::getConnection
EventHttpRequest


Returns EventHttpConnection object

EventHttpRequest::getCommand
EventHttpRequest::getHost
EventHttpRequest
PHP Manual

EventHttpRequest::getConnection

(PECL event >= 1.8.0)

EventHttpRequest::getConnection — Returns EventHttpConnection object

Descrierea

public EventHttpConnection EventHttpRequest::closeConnection ( void )

Returns EventHttpConnection object which represents HTTP connection associated with the request.

Avertizare

Libevent API allows HTTP request objects to be not bound to any HTTP connection. Therefore we can't unambiguously associate EventHttpRequest with EventHttpConnection . Thus, we construct EventHttpConnection object on-the-fly. Having no information about the event base, DNS base and connection-close callback, we just leave these fields unset.

EventHttpRequest::getConnection() method is usually useful when we need to set up a callback on connection close. See EventHttpConnection::setCloseCallback() .

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns EventHttpConnection object.

A se vedea ?i

  • EventHttpConnection::setCloseCallback() - Set callback for connection close
  • EventHttpRequest::getBufferEvent() - Returns EventBufferEvent object
EventHttpRequest::getCommand
EventHttpRequest::getHost
EventHttpRequest


Returns the request host

EventHttpRequest::getConnection
EventHttpRequest::getInputBuffer
EventHttpRequest
PHP Manual

EventHttpRequest::getHost

(PECL event >= 1.4.0-beta)

EventHttpRequest::getHost — Returns the request host

Descrierea

public string EventHttpRequest::getHost ( void )

Returns the request host.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the request host.

A se vedea ?i

  • EventHttpRequest::getUri() - Returns the request URI
  • EventHttpRequest::getCommand() - Returns the request command(method)
EventHttpRequest::getConnection
EventHttpRequest::getInputBuffer
EventHttpRequest


Returns the input buffer

EventHttpRequest::getHost
EventHttpRequest::getInputHeaders
EventHttpRequest
PHP Manual

EventHttpRequest::getInputBuffer

(PECL event >= 1.4.0-beta)

EventHttpRequest::getInputBuffer — Returns the input buffer

Descrierea

public EventBuffer EventHttpRequest::getInputBuffer ( void )

Returns the input buffer.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the input buffer.

A se vedea ?i

  • EventHttpRequest::getOutputBuffer() - Returns the output buffer of the request
EventHttpRequest::getHost
EventHttpRequest::getInputHeaders
EventHttpRequest


Returns associative array of the input headers

EventHttpRequest::getInputBuffer
EventHttpRequest::getOutputBuffer
EventHttpRequest
PHP Manual

EventHttpRequest::getInputHeaders

(PECL event >= 1.4.0-beta)

EventHttpRequest::getInputHeaders — Returns associative array of the input headers

Descrierea

public array EventHttpRequest::getInputHeaders ( void )

Returns associative array of the input headers.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns associative array of the input headers.

A se vedea ?i

  • EventHttpRequest::getOutputHeaders() - Returns associative array of the output headers
EventHttpRequest::getInputBuffer
EventHttpRequest::getOutputBuffer
EventHttpRequest


Returns the output buffer of the request

EventHttpRequest::getInputHeaders
EventHttpRequest::getOutputHeaders
EventHttpRequest
PHP Manual

EventHttpRequest::getOutputBuffer

(PECL event >= 1.4.0-beta)

EventHttpRequest::getOutputBuffer — Returns the output buffer of the request

Descrierea

public EventBuffer EventHttpRequest::getOutputBuffer ( void )

Returns the output buffer of the request.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the output buffer of the request.

A se vedea ?i

  • EventHttpRequest::getInputBuffer() - Returns the input buffer
EventHttpRequest::getInputHeaders
EventHttpRequest::getOutputHeaders
EventHttpRequest


Returns associative array of the output headers

EventHttpRequest::getOutputBuffer
EventHttpRequest::getResponseCode
EventHttpRequest
PHP Manual

EventHttpRequest::getOutputHeaders

(PECL event >= 1.4.0-beta)

EventHttpRequest::getOutputHeaders — Returns associative array of the output headers

Descrierea

public void EventHttpRequest::getOutputHeaders ( void )

Returns associative array of the output headers.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • EventHttpRequest::getInputHeaders() - Returns associative array of the input headers
EventHttpRequest::getOutputBuffer
EventHttpRequest::getResponseCode
EventHttpRequest


Returns the response code

EventHttpRequest::getOutputHeaders
EventHttpRequest::getUri
EventHttpRequest
PHP Manual

EventHttpRequest::getResponseCode

(PECL event >= 1.4.0-beta)

EventHttpRequest::getResponseCode — Returns the response code

Descrierea

public int EventHttpRequest::getResponseCode ( void )

Returns the response code.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the response code of the request.

A se vedea ?i

  • EventHttpRequest::getCommand() - Returns the request command(method)
  • EventHttpRequest::getHost() - Returns the request host
  • EventHttpRequest::getUri() - Returns the request URI
EventHttpRequest::getOutputHeaders
EventHttpRequest::getUri
EventHttpRequest


Returns the request URI

EventHttpRequest::getResponseCode
EventHttpRequest::removeHeader
EventHttpRequest
PHP Manual

EventHttpRequest::getUri

(PECL event >= 1.4.0-beta)

EventHttpRequest::getUri — Returns the request URI

Descrierea

public string EventHttpRequest::getUri ( void )

Returns the request URI

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the request URI

A se vedea ?i

  • EventHttpRequest::getCommand() - Returns the request command(method)
  • EventHttpRequest::getHost() - Returns the request host
  • EventHttpRequest::getResponseCode() - Returns the response code
EventHttpRequest::getResponseCode
EventHttpRequest::removeHeader
EventHttpRequest


Removes an HTTP header from the headers of the request

EventHttpRequest::getUri
EventHttpRequest::sendError
EventHttpRequest
PHP Manual

EventHttpRequest::removeHeader

(PECL event >= 1.4.0-beta)

EventHttpRequest::removeHeader — Removes an HTTP header from the headers of the request

Descrierea

public void EventHttpRequest::removeHeader ( string $key , string $type )

Removes an HTTP header from the headers of the request.

Parametri

key

The header name.

type

type is one of EventHttpRequest::*_HEADER constants.

Valorile întoarse

Removes an HTTP header from the headers of the request.

A se vedea ?i

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request
EventHttpRequest::getUri
EventHttpRequest::sendError
EventHttpRequest


Send an HTML error message to the client

EventHttpRequest::removeHeader
EventHttpRequest::sendReply
EventHttpRequest
PHP Manual

EventHttpRequest::sendError

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendError — Send an HTML error message to the client

Descrierea

public void EventHttpRequest::sendError ( int $error [, string $reason = NULL ] )

Send an HTML error message to the client.

Parametri

error

The HTTP error code.

reason

A brief explanation ofthe error. If NULL, the standard meaning of the error code will be used.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 EventHttpRequest::sendError() example

<?php
function _http_400($req) {
    $req->sendError(400);
}

$base = new EventBase();
$http = new EventHttp($base);

$http->setCallback("/err400", "_http_400");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

A se vedea ?i

  • EventHttpRequest::sendReply() - Send an HTML reply to the client
EventHttpRequest::removeHeader
EventHttpRequest::sendReply
EventHttpRequest


Send an HTML reply to the client

EventHttpRequest::sendError
EventHttpRequest::sendReplyChunk
EventHttpRequest
PHP Manual

EventHttpRequest::sendReply

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReply — Send an HTML reply to the client

Descrierea

public void EventHttpRequest::sendReply ( int $code , string $reason [, EventBuffer $buf ] )

Send an HTML reply to the client. The body of the reply consists of data in optional buf parameter.

Parametri

code

The HTTP response code to send.

reason

A brief message to send with the response code.

buf

The body of the response.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventHttpRequest::sendError() - Send an HTML error message to the client
  • EventHttpRequest::sendReplyChunk() - Send another data chunk as part of an ongoing chunked reply
EventHttpRequest::sendError
EventHttpRequest::sendReplyChunk
EventHttpRequest


Send another data chunk as part of an ongoing chunked reply

EventHttpRequest::sendReply
EventHttpRequest::sendReplyEnd
EventHttpRequest
PHP Manual

EventHttpRequest::sendReplyChunk

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReplyChunk — Send another data chunk as part of an ongoing chunked reply

Descrierea

public void EventHttpRequest::sendReplyChunk ( EventBuffer $buf )

Send another data chunk as part of an ongoing chunked reply. After calling this method buf will be empty.

Parametri

buf

The data chunk to send as part of the reply.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventHttpRequest::sendReplyStart() - Initiate a chunked reply
  • EventHttpRequest::sendReplyEnd() - Complete a chunked reply, freeing the request as appropriate
EventHttpRequest::sendReply
EventHttpRequest::sendReplyEnd
EventHttpRequest


Complete a chunked reply, freeing the request as appropriate

EventHttpRequest::sendReplyChunk
EventHttpRequest::sendReplyStart
EventHttpRequest
PHP Manual

EventHttpRequest::sendReplyEnd

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReplyEnd — Complete a chunked reply, freeing the request as appropriate

Descrierea

public void EventHttpRequest::sendReplyEnd ( void )

Complete a chunked reply, freeing the request as appropriate.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventHttpRequest::sendReplyStart() - Initiate a chunked reply
  • EventHttpRequest::sendReplyChunk() - Send another data chunk as part of an ongoing chunked reply
EventHttpRequest::sendReplyChunk
EventHttpRequest::sendReplyStart
EventHttpRequest


Initiate a chunked reply

EventHttpRequest::sendReplyEnd
EventListener
EventHttpRequest
PHP Manual

EventHttpRequest::sendReplyStart

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReplyStart — Initiate a chunked reply

Descrierea

public void EventHttpRequest::sendReplyStart ( int $code , string $reason )

Initiate a reply that uses Transfer-Encoding chunked .

This allows the caller to stream the reply back to the client and is useful when either not all of the reply data is immediately available or when sending very large replies.

The caller needs to supply data chunks with EventHttpRequest::sendReplyChunk() and complete the reply by calling EventHttpRequest::sendReplyEnd() .

Parametri

code

The HTTP response code to send.

reason

A brief message to send with the response code.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • EventHttpRequest::sendReplyChunk() - Send another data chunk as part of an ongoing chunked reply
  • EventHttpRequest::sendReplyEnd() - Complete a chunked reply, freeing the request as appropriate
EventHttpRequest::sendReplyEnd
EventListener
EventHttpRequest


The EventListener class

(PECL event >= 1.5.0)

Introducere

Represents a connection listener.

Sinopsisul clasei

final EventListener {
/* Constants */
const integer OPT_LEAVE_SOCKETS_BLOCKING = 1 ;
const integer OPT_CLOSE_ON_FREE = 2 ;
const integer OPT_CLOSE_ON_EXEC = 4 ;
const integer OPT_REUSEABLE = 8 ;
const integer OPT_THREADSAFE = 16 ;
/* Proprieta?i */
public readonly int $fd ;
/* Metode */
public __construct ( EventBase $base , callable $cb , mixed $data , int $flags , int $backlog , mixed $target )
public bool disable ( void )
public bool enable ( void )
public void getBase ( void )
public static bool getSocketName ( string &$address [, mixed &$port ] )
public void setCallback ( callable $cb [, mixed $arg = NULL ] )
public void setErrorCallback ( string $cb )
}

Proprieta?i

fd

Numeric file descriptor of the underlying socket. (Added in event-1.6.0 .)

Constante predefinite

EventListener::OPT_LEAVE_SOCKETS_BLOCKING

By default Libevent turns underlying file descriptors, or sockets, to non-blocking mode. This flag tells to leave them non-blocking.

EventListener::OPT_CLOSE_ON_FREE

If this option is set, the connection listener closes its underlying socket when the EventListener object is freed.

EventListener::OPT_CLOSE_ON_EXEC

If this option is set, the connection listener sets the close-on-exec flag on the underlying listener socket. See platform documentation for fcntl and FD_CLOEXEC for more information.

EventListener::OPT_REUSEABLE

By default on some platforms, once a listener socket is closed, no other socket can bind to the same port until a while has passed. Setting this option makes Libevent mark the socket as reusable, so that once it is closed, another socket can be opened to listen on the same port.

EventListener::OPT_THREADSAFE

Allocate locks for the listener, so that it’s safe to use it from multiple threads.

Cuprins

  • EventListener::__construct — Creates new connection listener associated with an event base
  • EventListener::disable — Disables an event connect listener object
  • EventListener::enable — Enables an event connect listener object
  • EventListener::getBase — Returns event base associated with the event listener
  • EventListener::getSocketName — Retreives the current address to which the listener's socket is bound.
  • EventListener::setCallback — The setCallback purpose
  • EventListener::setErrorCallback — Set event listener's error callback
EventHttpRequest::sendReplyStart
EventListener::__construct
Event


Creates new connection listener associated with an event base

EventListener
EventListener::disable
EventListener
PHP Manual

EventListener::__construct

(PECL event >= 1.2.6-beta)

EventListener::__construct — Creates new connection listener associated with an event base

Descrierea

public EventListener::__construct ( EventBase $base , callable $cb , mixed $data , int $flags , int $backlog , mixed $target )

Creates new connection listener associated with an event base.

Parametri

base

Associated event base.

cb

A callable that will be invoked when new connection received.

data

Custom user data attached to cb .

flags

Bit mask of EventListener::OPT_* constants. See EventListener constants .

backlog

Controls the maximum number of pending connections that the network stack should allow to wait in a not-yet-accepted state at any time; see documentation for your system’s listen function for more details. If backlog is negative, Libevent tries to pick a good value for the backlog ; if it is zero, Event assumes that listen is already called on the socket( target )

target

May be string, socket resource, or a stream associated with a socket. In case if target is a string, the string will be parsed as network address. It will be interpreted as a UNIX domain socket path, if prefixed with 'unix:' , e.g. 'unix:/tmp/my.sock' .

Valorile întoarse

Returns EventListener object representing the event connection listener.

Istoricul schimbarilor

Versiune | Descriere
1.5.0 | UNIX domain sockets' support added.

Exemple

Example #1 EventListener::__construct() example

<?php
/*
 * Simple echo server based on libevent's connection listener.
 *
 * Usage:
 * 1) In one terminal window run:
 *
 * $ php listener.php 9881
 *
 * 2) In another terminal window open up connection, e.g.:
 *
 * $ nc 127.0.0.1 9881
 *
 * 3) start typing. The server should repeat the input.
 */

class MyListenerConnection {
    private $bev, $base;

    public function __destruct() {
        $this->bev->free();
    }

    public function __construct($base, $fd) {
        $this->base = $base;

        $this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);

        $this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,
            array($this, "echoEventCallback"), NULL);

        if (!$this->bev->enable(Event::READ)) {
            echo "Failed to enable READ\n";
            return;
        }
    }

    public function echoReadCallback($bev, $ctx) {
        // Copy all the data from the input buffer to the output buffer

        // Variant #1
        $bev->output->addBuffer($bev->input);

        /* Variant #2 */
        /*
        $input    = $bev->getInput();
        $output = $bev->getOutput();
        $output->addBuffer($input);
        */
    }

    public function echoEventCallback($bev, $events, $ctx) {
        if ($events & EventBufferEvent::ERROR) {
            echo "Error from bufferevent\n";
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            //$bev->free();
            $this->__destruct();
        }
    }
}

class MyListener {
    public $base,
        $listener,
        $socket;
    private $conn = array();

    public function __destruct() {
        foreach ($this->conn as &$c) $c = NULL;
    }

    public function __construct($port) {
        $this->base = new EventBase();
        if (!$this->base) {
            echo "Couldn't open event base";
            exit(1);
        }

        // Variant #1
        /*
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if (!socket_bind($this->socket, '0.0.0.0', $port)) {
            echo "Unable to bind socket\n";
            exit(1);
        }
        $this->listener = new EventListener($this->base,
            array($this, "acceptConnCallback"), $this->base,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1, $this->socket);
         */

        // Variant #2
         $this->listener = new EventListener($this->base,
             array($this, "acceptConnCallback"), $this->base,
             EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,
             "0.0.0.0:$port");

        if (!$this->listener) {
            echo "Couldn't create listener";
            exit(1);
        }

        $this->listener->setErrorCallback(array($this, "accept_error_cb"));
    }

    public function dispatch() {
        $this->base->dispatch();
    }

    // This callback is invoked when there is data to read on $bev
    public function acceptConnCallback($listener, $fd, $address, $ctx) {
        // We got a new connection! Set up a bufferevent for it. */
        $base = $this->base;
        $this->conn[] = new MyListenerConnection($base, $fd);
    }

    public function accept_error_cb($listener, $ctx) {
        $base = $this->base;

        fprintf(STDERR, "Got an error %d (%s) on the listener. "
            ."Shutting down.\n",
            EventUtil::getLastSocketErrno(),
            EventUtil::getLastSocketError());

        $base->exit(NULL);
    }
}

$port = 9808;

if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$l = new MyListener($port);
$l->dispatch();
?>
EventListener
EventListener::disable
EventListener


Disables an event connect listener object

EventListener::__construct
EventListener::enable
EventListener
PHP Manual

EventListener::disable

(PECL event >= 1.2.6-beta)

EventListener::disable — Disables an event connect listener object

Descrierea

public bool EventListener::disable ( void )

Disables an event connect listener object

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventListener::enable() - Enables an event connect listener object
EventListener::__construct
EventListener::enable
EventListener


Enables an event connect listener object

EventListener::disable
EventListener::getBase
EventListener
PHP Manual

EventListener::enable

(PECL event >= 1.2.6-beta)

EventListener::enable — Enables an event connect listener object

Descrierea

public bool EventListener::enable ( void )

Enables an event connect listener object

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • EventListener::disable() - Disables an event connect listener object
EventListener::disable
EventListener::getBase
EventListener


Returns event base associated with the event listener

EventListener::enable
EventListener::getSocketName
EventListener
PHP Manual

EventListener::getBase

(PECL event >= 1.2.6-beta)

EventListener::getBase — Returns event base associated with the event listener

Descrierea

public void EventListener::getBase ( void )

Returns event base associated with the event listener.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns event base associated with the event listener.

EventListener::enable
EventListener::getSocketName
EventListener


Retreives the current address to which the listener's socket is bound.

EventListener::getBase
EventListener::setCallback
EventListener
PHP Manual

EventListener::getSocketName

(PECL event >= 1.5.0)

EventListener::getSocketName — Retreives the current address to which the listener's socket is bound.

Descrierea

public static bool EventListener::getSocketName ( string &$address [, mixed &$port ] )

Retreives the current address to which the listener's socket is bound.

Parametri

address

Output parameter. IP-address depending on the socket address family.

port

Output parameter. The port the socket is bound to.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

EventListener::getBase
EventListener::setCallback
EventListener


The setCallback purpose

EventListener::getSocketName
EventListener::setErrorCallback
EventListener
PHP Manual

EventListener::setCallback

(PECL event >= 1.2.6-beta)

EventListener::setCallback — The setCallback purpose

Descrierea

public void EventListener::setCallback ( callable $cb [, mixed $arg = NULL ] )

Adjust event connect listener's callback and optionally the callback argument.

Parametri

cb

The new callback for new connections. Ignored if NULL.

Should match the following prototype:

void callback ([ EventListener $listener = NULL [, mixed $fd = NULL [, array $address = NULL [, mixed $arg = NULL ]]]] )

listener

The EventListener object.

fd

The file descriptor or a resource associated with the listener.

address

Array of two elements: IP address and the server port.

arg

User custom data attached to the callback.

arg

Custom user data attached to the callback. Ignored if NULL.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventListener::getSocketName
EventListener::setErrorCallback
EventListener


Set event listener's error callback

EventListener::setCallback
EventSslContext
EventListener
PHP Manual

EventListener::setErrorCallback

(PECL event >= 1.2.6-beta)

EventListener::setErrorCallback — Set event listener's error callback

Descrierea

public void EventListener::setErrorCallback ( string $cb )

Set event listener's error callback

Parametri

cb

The error callback. Should match the following prototype:

void callback ([ EventListener $listener = NULL [, mixed $data = NULL ]] )

listener

The EventListener object.

data

User custom data attached to the callback.

Valorile întoarse

A se vedea ?i

  • EventListener::setCallback() - The setCallback purpose
EventListener::setCallback
EventSslContext
EventListener


The EventSslContext class

(PECL event >= 1.2.6-beta)

Introducere

Represents SSL_CTX structure. Provides methods and properties to configure the SSL context.

Sinopsisul clasei

final EventSslContext {
/* Constants */
const integer SSLv2_CLIENT_METHOD = 1 ;
const integer SSLv3_CLIENT_METHOD = 2 ;
const integer SSLv23_CLIENT_METHOD = 3 ;
const integer TLS_CLIENT_METHOD = 4 ;
const integer SSLv2_SERVER_METHOD = 5 ;
const integer SSLv3_SERVER_METHOD = 6 ;
const integer SSLv23_SERVER_METHOD = 7 ;
const integer TLS_SERVER_METHOD = 8 ;
const integer OPT_LOCAL_CERT = 1 ;
const integer OPT_LOCAL_PK = 2 ;
const integer OPT_PASSPHRASE = 3 ;
const integer OPT_CA_FILE = 4 ;
const integer OPT_CA_PATH = 5 ;
const integer OPT_ALLOW_SELF_SIGNED = 6 ;
const integer OPT_VERIFY_PEER = 7 ;
const integer OPT_VERIFY_DEPTH = 8 ;
const integer OPT_CIPHERS = 9 ;
/* Proprieta?i */
public string $local_cert ;
public string $local_pk ;
/* Metode */
public __construct ( string $method , string $options )
}

Proprieta?i

local_cert

Path to local certificate file on filesystem. It must be a PEM-encoded file which contains certificate. It can optionally contain the certificate chain of issuers.

local_pk

Path to local private key file

Constante predefinite

EventSslContext::SSLv2_CLIENT_METHOD

SSLv2 client method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv3_CLIENT_METHOD

SSLv3 client method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv23_CLIENT_METHOD

SSLv23 client method. See SSL_CTX_new(3) man page.

EventSslContext::TLS_CLIENT_METHOD

TLS client method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv2_SERVER_METHOD

SSLv2 server method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv3_SERVER_METHOD

SSLv3 server method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv23_SERVER_METHOD

SSLv23 server method. See SSL_CTX_new(3) man page.

EventSslContext::TLS_SERVER_METHOD

TLS server method. See SSL_CTX_new(3) man page.

EventSslContext::OPT_LOCAL_CERT

Key for an item of the options' array used in EventSslContext::__construct() . The option points to path of local certificate.

EventSslContext::OPT_LOCAL_PK

Key for an item of the options' array used in EventSslContext::__construct() . The option points to path of the private key.

EventSslContext::OPT_PASSPHRASE

Key for an item of the options' array used in EventSslContext::__construct() . Represents passphrase of the certificate.

EventSslContext::OPT_CA_FILE

Key for an item of the options' array used in EventSslContext::__construct() . Represents path of the certificate authority file.

EventSslContext::OPT_CA_PATH

Key for an item of the options' array used in EventSslContext::__construct() . Represents path where the certificate authority file should be searched for.

EventSslContext::OPT_ALLOW_SELF_SIGNED

Key for an item of the options' array used in EventSslContext::__construct() . Represents option that allows self-signed certificates.

EventSslContext::OPT_VERIFY_PEER

Key for an item of the options' array used in EventSslContext::__construct() . Represents option that tells Event to verify peer.

EventSslContext::OPT_VERIFY_DEPTH

Key for an item of the options' array used in EventSslContext::__construct() . Represents maximum depth for the certificate chain verification that shall be allowed for the SSL context.

EventSslContext::OPT_CIPHERS

Key for an item of the options' array used in EventSslContext::__construct() . Represents the cipher list for the SSL context.

Cuprins

  • EventSslContext::__construct — Constructs an OpenSSL context for use with Event classes
EventListener::setErrorCallback
EventSslContext::__construct
Event


Constructs an OpenSSL context for use with Event classes

EventSslContext
EventUtil
EventSslContext
PHP Manual

EventSslContext::__construct

(PECL event >= 1.2.6-beta)

EventSslContext::__construct — Constructs an OpenSSL context for use with Event classes

Descrierea

public EventSslContext::__construct ( string $method , string $options )

Creates SSL context holding pointer to SSL_CTX (see the system manual).

Parametri

method

One of EventSslContext::*_METHOD constants .

options

Associative array of SSL context options One of EventSslContext::OPT_* constants .

Valorile întoarse

Returns EventSslContext object.

Exemple

Example #1 EventSslContext::__construct() example

<?php
$ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array(
     EventSslContext::OPT_LOCAL_CERT        => $local_cert,
     EventSslContext::OPT_LOCAL_PK          => $local_pk,
     EventSslContext::OPT_PASSPHRASE        => "echo server",
     EventSslContext::OPT_VERIFY_PEER       => true,
     EventSslContext::OPT_ALLOW_SELF_SIGNED => false,
));
?>
EventSslContext
EventUtil
EventSslContext


The EventUtil class

(PECL event >= 1.5.0)

Introducere

EventUtil is a singleton with supplimentary methods and constants.

Sinopsisul clasei

final EventUtil {
/* Constants */
const integer AF_INET = 2 ;
const integer AF_INET6 = 10 ;
const integer AF_UNSPEC = 0 ;
const integer LIBEVENT_VERSION_NUMBER = 33559808 ;
const integer SO_DEBUG = 1 ;
const integer SO_REUSEADDR = 2 ;
const integer SO_KEEPALIVE = 9 ;
const integer SO_DONTROUTE = 5 ;
const integer SO_LINGER = 13 ;
const integer SO_BROADCAST = 6 ;
const integer SO_OOBINLINE = 10 ;
const integer SO_SNDBUF = 7 ;
const integer SO_RCVBUF = 8 ;
const integer SO_SNDLOWAT = 19 ;
const integer SO_RCVLOWAT = 18 ;
const integer SO_SNDTIMEO = 21 ;
const integer SO_RCVTIMEO = 20 ;
const integer SO_TYPE = 3 ;
const integer SO_ERROR = 4 ;
const integer SOL_SOCKET = 1 ;
const integer SOL_TCP = 6 ;
const integer SOL_UDP = 17 ;
const integer IPPROTO_IP = 0 ;
const integer IPPROTO_IPV6 = 41 ;
/* Metode */
abstract public __construct ( void )
public static int getLastSocketErrno ([ mixed $socket = NULL ] )
public static string getLastSocketError ([ mixed $socket ] )
public static int getSocketFd ( mixed $socket )
public static bool getSocketName ( mixed $socket , string &$address [, mixed &$port ] )
public static bool setSocketOption ( mixed $socket , int $level , int $optname , mixed $optval )
public static void sslRandPoll ( void )
}

Constante predefinite

EventUtil::AF_INET

IPv4 address family

EventUtil::AF_INET6

IPv6 address family

EventUtil::AF_UNSPEC

Unspecified IP address family

EventUtil::SO_DEBUG

Socket option. Enable socket debugging. Only allowed for processes with the CAP_NET_ADMIN capability or an effective user ID of 0 . (Added in event-1.6.0.)

EventUtil::SO_REUSEADDR

Socket option. Indicates that the rules used in validating addresses supplied in a bind(2) call should allow reuse of local addresses. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_KEEPALIVE

Socket option. Enable sending of keep-alive messages on connection-oriented sockets. Expects an integer boolean flag. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_DONTROUTE

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_LINGER

Socket option. When enabled, a close(2) or shutdown(2) will not return until all queued messages for the socket have been successfully sent or the linger timeout has been reached. Otherwise, the call returns immediately and the closing is done in the background. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_BROADCAST

Socket option. Reports whether transmission of broadcast messages is supported. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_OOBINLINE

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_SNDBUF

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_RCVBUF

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_SNDLOWAT

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_RCVLOWAT

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_SNDTIMEO

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_RCVTIMEO

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_TYPE

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_ERROR

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SOL_SOCKET

Socket option level. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SOL_TCP

Socket option level. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SOL_UDP

Socket option level. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::IPPROTO_IP

See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::IPPROTO_IPV6

See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::LIBEVENT_VERSION_NUMBER

Libevent' version number at the time when Event extension had been compiled with the library.

Cuprins

  • EventUtil::__construct — The abstract constructor
  • EventUtil::getLastSocketErrno — Returns the most recent socket error number
  • EventUtil::getLastSocketError — Returns the most recent socket error
  • EventUtil::getSocketFd — Returns numeric file descriptor of a socket, or stream
  • EventUtil::getSocketName — Retreives the current address to which the socket is bound.
  • EventUtil::setSocketOption — Sets socket options
  • EventUtil::sslRandPoll — Generates entropy by means of OpenSSL's RAND_poll()
EventSslContext::__construct
EventUtil::__construct
Event


The abstract constructor

EventUtil
EventUtil::getLastSocketErrno
EventUtil
PHP Manual

EventUtil::__construct

(PECL event >= 1.2.6-beta)

EventUtil::__construct — The abstract constructor

Descrierea

abstract public EventUtil::__construct ( void )

EventUtil is a singleton. Therefore the constructor is abstract, and it is impossible to create objects based on this class.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventUtil
EventUtil::getLastSocketErrno
EventUtil


Returns the most recent socket error number

EventUtil::__construct
EventUtil::getLastSocketError
EventUtil
PHP Manual

EventUtil::getLastSocketErrno

(PECL event >= 1.2.6-beta)

EventUtil::getLastSocketErrno — Returns the most recent socket error number

Descrierea

public static int EventUtil::getLastSocketErrno ([ mixed $socket = NULL ] )

Returns the most recent socket error number( errno ).

Parametri

socket

Socket resource, stream or a file descriptor of a socket.

Valorile întoarse

Returns the most recent socket error number( errno ).

A se vedea ?i

  • EventUtil::getLastSocketError() - Returns the most recent socket error
EventUtil::__construct
EventUtil::getLastSocketError
EventUtil


Returns the most recent socket error

EventUtil::getLastSocketErrno
EventUtil::getSocketFd
EventUtil
PHP Manual

EventUtil::getLastSocketError

(PECL event >= 1.2.6-beta)

EventUtil::getLastSocketError — Returns the most recent socket error

Descrierea

public static string EventUtil::getLastSocketError ([ mixed $socket ] )

Returns the most recent socket error.

Parametri

socket

Socket resource, stream or a file descriptor of a socket.

Valorile întoarse

Returns the most recent socket error.

A se vedea ?i

  • EventUtil::getLastSocketErrno() - Returns the most recent socket error number
EventUtil::getLastSocketErrno
EventUtil::getSocketFd
EventUtil


Returns numeric file descriptor of a socket, or stream

EventUtil::getLastSocketError
EventUtil::getSocketName
EventUtil
PHP Manual

EventUtil::getSocketFd

(PECL event >= 1.7.0)

EventUtil::getSocketFd — Returns numeric file descriptor of a socket, or stream

Descrierea

public static int EventUtil::getSocketFd ( mixed $socket )

Returns numeric file descriptor of a socket or stream specified by socket argument just like the Event extension does it internally for all methods accepting socket resource or stream.

Parametri

socket

Socket resource or stream.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE. EventUtil::getSocketFd() returns FALSE in case if it is whether failed to recognize the type of the underlying file, or detected that the file descriptor associated with socket is not valid.

EventUtil::getLastSocketError
EventUtil::getSocketName
EventUtil


Retreives the current address to which the socket is bound.

EventUtil::getSocketFd
EventUtil::setSocketOption
EventUtil
PHP Manual

EventUtil::getSocketName

(PECL event >= 1.5.0)

EventUtil::getSocketName — Retreives the current address to which the socket is bound.

Descrierea

public static bool EventUtil::getSocketName ( mixed $socket , string &$address [, mixed &$port ] )

Retreives the current address to which the socket is bound.

Parametri

socket

Socket resource, stream or a file descriptor of a socket.

address

Output parameter. IP-address, or the UNIX domain socket path depending on the socket address family.

port

Output parameter. The port the socket is bound to. Has no meaning for UNIX domain sockets.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

EventUtil::getSocketFd
EventUtil::setSocketOption
EventUtil


Sets socket options

EventUtil::getSocketName
EventUtil::sslRandPoll
EventUtil
PHP Manual

EventUtil::setSocketOption

(PECL event >= 1.6.0)

EventUtil::setSocketOption — Sets socket options

Descrierea

public static bool EventUtil::setSocketOption ( mixed $socket , int $level , int $optname , mixed $optval )

Sets socket options.

Parametri

socket

Socket resource, stream, or numeric file descriptor associated with the socket.

level

One of EventUtil::SOL_* constants. Specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of EventUtil::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. See EventUtil constants .

optname

Option name(type). Has the same meaning as corresponding parameter of socket_get_option() function. See EventUtil constants .

optval

Accepts the same values as optval parameter of the socket_get_option() function.

Valorile întoarse

Returns TRUE on success. Otherwise FALSE.

A se vedea ?i

  • socket_get_option() - Gets socket options for the socket
  • socket_set_option() - Sets socket options for the socket
EventUtil::getSocketName
EventUtil::sslRandPoll
EventUtil


Generates entropy by means of OpenSSL's RAND_poll()

EventUtil::setSocketOption
FAM
EventUtil
PHP Manual

EventUtil::sslRandPoll

(PECL event >= 1.2.6-beta)

EventUtil::sslRandPoll — Generates entropy by means of OpenSSL's RAND_poll()

Descrierea

public static void EventUtil::sslRandPoll ( void )

Generates entropy by means of OpenSSL's RAND_poll() (see the system manual).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

EventUtil::setSocketOption
FAM
EventUtil


File Alteration Monitor

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii FAM
    • 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
EventUtil::sslRandPoll
Introducere
Alte servicii


Introducere

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.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.1.0.

Nota: Aceasta extensie nu este disponibila pe platformele Windows.

FAM
Instalarea / configurarea
FAM


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
FAM


Necesita?i

This extension uses the functions of the » FAM library, developed by SGI. Therefore you have to download and install the FAM library.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie este considerata ne-între?inuta ?i moarta. Oricum însa codul-sursa al acestei extensii este înca disponibil în PECL SVN aici: » http://svn.php.net/viewvc/pecl/fam.

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.1.0

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

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.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
Func?ii FAM
FAM


Func?ii FAM

Cuprins

  • 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
Constante predefinite
fam_cancel_monitor
FAM


Terminate monitoring

Func?ii FAM
fam_close
Func?ii FAM
PHP Manual

fam_cancel_monitor

(PHP 5 <= 5.0.5)

fam_cancel_monitor — Terminate monitoring

Descrierea

bool fam_cancel_monitor ( resource $fam , resource $fam_monitor )

Terminates monitoring on a resource.

In addition an FAMAcknowledge event occurs.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Func?ii FAM
fam_close
Func?ii FAM


Close FAM connection

fam_cancel_monitor
fam_monitor_collection
Func?ii FAM
PHP Manual

fam_close

(PHP 5 <= 5.0.5)

fam_close — Close FAM connection

Descrierea

void fam_close ( resource $fam )

Closes a connection to the FAM service.

Parametri

fam

A resource representing a connection to the FAM service returned by fam_open()

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • fam_monitor_open()

fam_cancel_monitor
fam_monitor_collection
Func?ii FAM


Monitor a collection of files in a directory for changes

fam_close
fam_monitor_directory
Func?ii FAM
PHP Manual

fam_monitor_collection

(PHP 5 <= 5.0.5)

fam_monitor_collection — Monitor a collection of files in a directory for changes

Descrierea

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.

Parametri

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

Valorile întoarse

Returns a monitoring resource or FALSE on errors.

A se vedea ?i

  • 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
Func?ii FAM


Monitor a directory for changes

fam_monitor_collection
fam_monitor_file
Func?ii FAM
PHP Manual

fam_monitor_directory

(PHP 5 <= 5.0.5)

fam_monitor_directory — Monitor a directory for changes

Descrierea

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.

Parametri

fam

A resource representing a connection to the FAM service returned by fam_open()

dirname

Path to the monitored directory

Valorile întoarse

Returns a monitoring resource or FALSE on errors.

A se vedea ?i

  • 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
Func?ii FAM


Monitor a regular file for changes

fam_monitor_directory
fam_next_event
Func?ii FAM
PHP Manual

fam_monitor_file

(PHP 5 <= 5.0.5)

fam_monitor_file — Monitor a regular file for changes

Descrierea

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.

Parametri

fam

A resource representing a connection to the FAM service returned by fam_open()

filename

Path to the monitored file

Valorile întoarse

Returns a monitoring resource or FALSE on errors.

A se vedea ?i

  • 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
Func?ii FAM


Get next pending FAM event

fam_monitor_file
fam_open
Func?ii FAM
PHP Manual

fam_next_event

(PHP 5 <= 5.0.5)

fam_next_event — Get next pending FAM event

Descrierea

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().

Parametri

fam

A resource representing a connection to the FAM service returned by fam_open()

Valorile întoarse

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.

A se vedea ?i

  • fam_pending() - Check for pending FAM events

fam_monitor_file
fam_open
Func?ii FAM


Open connection to FAM daemon

fam_next_event
fam_pending
Func?ii FAM
PHP Manual

fam_open

(PHP 5 <= 5.0.5)

fam_open — Open connection to FAM daemon

Descrierea

resource fam_open ([ string $appname ] )

Opens a connection to the FAM service daemon.

Parametri

appname

A string identifying the application for logging reasons

Valorile întoarse

Returns a resource representing a connection to the FAM service on success or FALSE on errors.

A se vedea ?i

  • fam_close() - Close FAM connection

fam_next_event
fam_pending
Func?ii FAM


Check for pending FAM events

fam_open
fam_resume_monitor
Func?ii FAM
PHP Manual

fam_pending

(PHP 5 <= 5.0.5)

fam_pending — Check for pending FAM events

Descrierea

int fam_pending ( resource $fam )

Checks for pending FAM events.

Parametri

fam

A resource representing a connection to the FAM service returned by fam_open()

Valorile întoarse

Returns non-zero if events are available to be fetched using fam_next_event(), zero otherwise.

A se vedea ?i

  • fam_next_event() - Get next pending FAM event

fam_open
fam_resume_monitor
Func?ii FAM


Resume suspended monitoring

fam_pending
fam_suspend_monitor
Func?ii FAM
PHP Manual

fam_resume_monitor

(PHP 5 <= 5.0.5)

fam_resume_monitor — Resume suspended monitoring

Descrierea

bool fam_resume_monitor ( resource $fam , resource $fam_monitor )

Resumes monitoring of a resource previously suspended using fam_suspend_monitor().

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fam_suspend_monitor() - Temporarily suspend monitoring

fam_pending
fam_suspend_monitor
Func?ii FAM


Temporarily suspend monitoring

fam_resume_monitor
FTP
Func?ii FAM
PHP Manual

fam_suspend_monitor

(PHP 5 <= 5.0.5)

fam_suspend_monitor — Temporarily suspend monitoring

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • fam_cancel_monitor() - Terminate monitoring
  • fam_resume_monitor() - Resume suspended monitoring

fam_resume_monitor
FTP
Func?ii FAM


FTP

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic usage
  • Func?ii FTP
    • ftp_alloc — Allocates space for a file to be uploaded
    • ftp_cdup — Changes to the parent directory
    • ftp_chdir — Changes the current directory on a FTP server
    • ftp_chmod — Set permissions on a file via FTP
    • ftp_close — Closes an FTP connection
    • ftp_connect — Opens an FTP connection
    • ftp_delete — Deletes a file on the FTP server
    • ftp_exec — Requests execution of a command on the FTP server
    • ftp_fget — Downloads a file from the FTP server and saves to an open file
    • ftp_fput — Uploads from an open file to the FTP server
    • ftp_get_option — Retrieves various runtime behaviours of the current FTP stream
    • ftp_get — Downloads a file from the FTP server
    • ftp_login — Logs in to an FTP connection
    • ftp_mdtm — Returns the last modified time of the given file
    • ftp_mkdir — Creates a directory
    • 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 — Returns a list of files in the given directory
    • ftp_pasv — Turns passive mode on or off
    • ftp_put — Uploads a file to the FTP server
    • ftp_pwd — Returns the current directory name
    • ftp_quit — Pseudonim pentru ftp_close
    • ftp_raw — Sends an arbitrary command to an FTP server
    • ftp_rawlist — Returns a detailed list of files in the given directory
    • ftp_rename — Renames a file or a directory on the FTP server
    • ftp_rmdir — Removes a directory
    • ftp_set_option — Set miscellaneous runtime FTP options
    • ftp_site — Sends a SITE command to the server
    • ftp_size — Returns the size of the given file
    • ftp_ssl_connect — Opens an Secure SSL-FTP connection
    • ftp_systype — Returns the system type identifier of the remote FTP server
fam_suspend_monitor
Introducere
Alte servicii


Introducere

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
Instalarea / configurarea
FTP


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
FTP


Instalarea

Pentru a utiliza func?iile FTP în PHP este necesar de a adauga op?iunea --enable-ftp la instalarea PHP.

Versiunea Windows a PHP 5 poseda suport încorporat pentru aceasta extensie. Nu trebuie încarcate careva extensii suplimentare pentru a utiliza aceste func?ii.

Începând cu PHP 7.0.0 pe Windows aceasta extensie este întotdeauna compilata ca extensie partajata ?i deci trebuie sa fie activata în php.ini.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

This extension uses one resource type, which is the link identifier of the FTP connection, returned by ftp_connect() or ftp_ssl_connect().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

FTP_ASCII (integer)

FTP_AUTOSEEK (integer)

See ftp_set_option() for information.

FTP_AUTORESUME (integer)

Automatically determine resume position and start position for GET and PUT requests (only works if FTP_AUTOSEEK is enabled)

FTP_FAILED (integer)

Asynchronous transfer has failed

FTP_FINISHED (integer)

Asynchronous transfer has finished

FTP_MOREDATA (integer)

Asynchronous transfer is still active

FTP_TEXT (integer)

Alias of FTP_ASCII.

FTP_BINARY (integer)

FTP_IMAGE (integer)

Alias of FTP_BINARY.

FTP_TIMEOUT_SEC (integer)

See ftp_set_option() for information.

Tipurile resurselor
Exemple
FTP


Exemple

Cuprins

  • Basic usage
Constante predefinite
Basic usage
FTP


Basic usage

Example #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);
?>

Exemple
Func?ii FTP
Exemple


Func?ii FTP

Cuprins

  • ftp_alloc — Allocates space for a file to be uploaded
  • ftp_cdup — Changes to the parent directory
  • ftp_chdir — Changes the current directory on a FTP server
  • ftp_chmod — Set permissions on a file via FTP
  • ftp_close — Closes an FTP connection
  • ftp_connect — Opens an FTP connection
  • ftp_delete — Deletes a file on the FTP server
  • ftp_exec — Requests execution of a command on the FTP server
  • ftp_fget — Downloads a file from the FTP server and saves to an open file
  • ftp_fput — Uploads from an open file to the FTP server
  • ftp_get_option — Retrieves various runtime behaviours of the current FTP stream
  • ftp_get — Downloads a file from the FTP server
  • ftp_login — Logs in to an FTP connection
  • ftp_mdtm — Returns the last modified time of the given file
  • ftp_mkdir — Creates a directory
  • 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 — Returns a list of files in the given directory
  • ftp_pasv — Turns passive mode on or off
  • ftp_put — Uploads a file to the FTP server
  • ftp_pwd — Returns the current directory name
  • ftp_quit — Pseudonim pentru ftp_close
  • ftp_raw — Sends an arbitrary command to an FTP server
  • ftp_rawlist — Returns a detailed list of files in the given directory
  • ftp_rename — Renames a file or a directory on the FTP server
  • ftp_rmdir — Removes a directory
  • ftp_set_option — Set miscellaneous runtime FTP options
  • ftp_site — Sends a SITE command to the server
  • ftp_size — Returns the size of the given file
  • ftp_ssl_connect — Opens an Secure SSL-FTP connection
  • ftp_systype — Returns the system type identifier of the remote FTP server
Basic usage
ftp_alloc
FTP


Allocates space for a file to be uploaded

Func?ii FTP
ftp_cdup
Func?ii FTP
PHP Manual

ftp_alloc

(PHP 5, PHP 7)

ftp_alloc — Allocates space for a file to be uploaded

Descrierea

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.

Nota:

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

A se vedea ?i

  • ftp_put() - Uploads a file to the FTP server
  • ftp_fput() - Uploads from an open file to the FTP server

Func?ii FTP
ftp_cdup
Func?ii FTP


Changes to the parent directory

ftp_alloc
ftp_chdir
Func?ii FTP
PHP Manual

ftp_cdup

(PHP 4, PHP 5, PHP 7)

ftp_cdup — Changes to the parent directory

Descrierea

bool ftp_cdup ( resource $ftp_stream )

Changes to the parent directory.

Parametri

ftp_stream

The link identifier of the FTP connection.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ftp_cdup() 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);

// change the current directory to html
ftp_chdir($conn_id, 'html');

echo ftp_pwd($conn_id); // /html

// return to the parent directory
if (ftp_cdup($conn_id)) {
  echo "cdup successful\n";
} else {
  echo "cdup not successful\n";
}

echo ftp_pwd($conn_id); // /

ftp_close($conn_id);
?>

A se vedea ?i

  • ftp_chdir() - Changes the current directory on a FTP server
  • ftp_pwd() - Returns the current directory name

ftp_alloc
ftp_chdir
Func?ii FTP


Changes the current directory on a FTP server

ftp_cdup
ftp_chmod
Func?ii FTP
PHP Manual

ftp_chdir

(PHP 4, PHP 5, PHP 7)

ftp_chdir — Changes the current directory on a FTP server

Descrierea

bool ftp_chdir ( resource $ftp_stream , string $directory )

Changes the current directory to the specified one.

Parametri

ftp_stream

The link identifier of the FTP connection.

directory

The target directory.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. If changing directory fails, PHP will also throw a warning.

Exemple

Example #1 ftp_chdir() 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)) {
    die("FTP connection has failed !");
}

echo "Current directory: " . ftp_pwd($conn_id) . "\n";

// try to change the directory to somedir
if (ftp_chdir($conn_id, "somedir")) {
    echo "Current directory is now: " . ftp_pwd($conn_id) . "\n";
} else {
    echo "Couldn't change directory\n";
}

// close the connection
ftp_close($conn_id);
?>

A se vedea ?i

  • ftp_cdup() - Changes to the parent directory
  • ftp_pwd() - Returns the current directory name

ftp_cdup
ftp_chmod
Func?ii FTP


Set permissions on a file via FTP

ftp_chdir
ftp_close
Func?ii FTP
PHP Manual

ftp_chmod

(PHP 5, PHP 7)

ftp_chmod — Set permissions on a file via FTP

Descrierea

int ftp_chmod ( resource $ftp_stream , int $mode , string $filename )

Sets the permissions on the specified remote file to mode.

Parametri

ftp_stream

The link identifier of the FTP connection.

mode

The new permissions, given as an octal value.

filename

The remote file.

Valorile întoarse

Returns the new file permissions on success or FALSE on error.

Exemple

Example #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);
?>

A se vedea ?i

  • chmod() - Changes file mode

ftp_chdir
ftp_close
Func?ii FTP


Closes an FTP connection

ftp_chmod
ftp_connect
Func?ii FTP
PHP Manual

ftp_close

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ftp_close — Closes an FTP connection

Descrierea

bool ftp_close ( resource $ftp_stream )

ftp_close() closes the given link identifier and releases the resource.

Nota:

After calling this function, you can no longer use the FTP connection and must create a new one with ftp_connect().

Parametri

ftp_stream

The link identifier of the FTP connection.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ftp_close() 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);

// print the current directory
echo ftp_pwd($conn_id); // /

// close this connection
ftp_close($conn_id);
?>

A se vedea ?i

  • ftp_connect() - Opens an FTP connection

ftp_chmod
ftp_connect
Func?ii FTP


Opens an FTP connection

ftp_close
ftp_delete
Func?ii FTP
PHP Manual

ftp_connect

(PHP 4, PHP 5, PHP 7)

ftp_connect — Opens an FTP connection

Descrierea

resource ftp_connect ( string $host [, int $port = 21 [, int $timeout = 90 ]] )

ftp_connect() opens an FTP connection to the specified host.

Parametri

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().

Valorile întoarse

Returns a FTP stream on success or FALSE on error.

Exemple

Example #1 ftp_connect() example

<?php

$ftp_server = "ftp.example.com";

// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

?>

A se vedea ?i

  • ftp_close() - Closes an FTP connection
  • ftp_ssl_connect() - Opens an Secure SSL-FTP connection

ftp_close
ftp_delete
Func?ii FTP


Deletes a file on the FTP server

ftp_connect
ftp_exec
Func?ii FTP
PHP Manual

ftp_delete

(PHP 4, PHP 5, PHP 7)

ftp_delete — Deletes a file on the FTP server

Descrierea

bool ftp_delete ( resource $ftp_stream , string $path )

ftp_delete() deletes the file specified by path from the FTP server.

Parametri

ftp_stream

The link identifier of the FTP connection.

path

The file to delete.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ftp_delete() example

<?php
$file = 'public_html/old.txt';

// 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 delete $file
if (ftp_delete($conn_id, $file)) {
 echo "$file deleted successful\n";
} else {
 echo "could not delete $file\n";
}

// close the connection
ftp_close($conn_id);
?>

ftp_connect
ftp_exec
Func?ii FTP


Requests execution of a command on the FTP server

ftp_delete
ftp_fget
Func?ii FTP
PHP Manual

ftp_exec

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

ftp_exec — Requests execution of a command on the FTP server

Descrierea

bool ftp_exec ( resource $ftp_stream , string $command )

Sends a SITE EXEC command request to the FTP server.

Parametri

ftp_stream

The link identifier of the FTP connection.

command

The command to execute.

Valorile întoarse

Returns TRUE if the command was successful (server sent response code: 200); otherwise returns FALSE.

Exemple

Example #1 ftp_exec() example

<?php

// variable initialization
$command = 'ls -al >files.txt';

// 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);

// execute command
if (ftp_exec($conn_id, $command)) {
    echo "$command executed successfully\n";
} else {
    echo "could not execute $command\n";
}

// close the connection
ftp_close($conn_id);

?>

A se vedea ?i

  • ftp_raw() - Sends an arbitrary command to an FTP server

ftp_delete
ftp_fget
Func?ii FTP


Downloads a file from the FTP server and saves to an open file

ftp_exec
ftp_fput
Func?ii FTP
PHP Manual

ftp_fget

(PHP 4, PHP 5, PHP 7)

ftp_fget — Downloads a file from the FTP server and saves to an open file

Descrierea

bool ftp_fget ( resource $ftp_stream , resource $handle , string $remote_file , int $mode [, int $resumepos = 0 ] )

ftp_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ftp_fget() example

<?php

// path to remote file
$remote_file = 'somefile.txt';
$local_file = 'localfile.txt';

// open some file to write to
$handle = fopen($local_file, 'w');

// 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 download $remote_file and save it to $handle
if (ftp_fget($conn_id, $handle, $remote_file, FTP_ASCII, 0)) {
 echo "successfully written to $local_file\n";
} else {
 echo "There was a problem while downloading $remote_file to $local_file\n";
}

// close the connection and the file handler
ftp_close($conn_id);
fclose($handle);
?>

A se vedea ?i

  • ftp_get() - Downloads a file from the FTP server
  • 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
Func?ii FTP


Uploads from an open file to the FTP server

ftp_fget
ftp_get_option
Func?ii FTP
PHP Manual

ftp_fput

(PHP 4, PHP 5, PHP 7)

ftp_fput — Uploads from an open file to the FTP server

Descrierea

bool ftp_fput ( resource $ftp_stream , string $remote_file , resource $handle , int $mode [, int $startpos = 0 ] )

ftp_fput() uploads the data from a file pointer to a remote file on the FTP server.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ftp_fput() example

<?php

// open some file for reading
$file = 'somefile.txt';
$fp = fopen($file, 'r');

// 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 upload $file
if (ftp_fput($conn_id, $file, $fp, FTP_ASCII)) {
    echo "Successfully uploaded $file\n";
} else {
    echo "There was a problem while uploading $file\n";
}

// close the connection and the file handler
ftp_close($conn_id);
fclose($fp);

?>

A se vedea ?i

  • ftp_put() - Uploads a file to the FTP server
  • 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
Func?ii FTP


Retrieves various runtime behaviours of the current FTP stream

ftp_fput
ftp_get
Func?ii FTP
PHP Manual

ftp_get_option

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ftp_get_option — Retrieves various runtime behaviours of the current FTP stream

Descrierea

mixed ftp_get_option ( resource $ftp_stream , int $option )

This function returns the value for the requested option from the specified FTP connection.

Parametri

ftp_stream

The link identifier of the FTP connection.

option

Currently, the following options are supported:

Supported runtime FTP options
FTP_TIMEOUT_SEC | Returns the current timeout used for network related operations.
FTP_AUTOSEEK | Returns TRUE if this option is on, FALSE otherwise.

Valorile întoarse

Returns the value on success or FALSE if the given option is not supported. In the latter case, a warning message is also thrown.

Exemple

Example #1 ftp_get_option() example

<?php
// Get the timeout of the given FTP stream
$timeout = ftp_get_option($conn_id, FTP_TIMEOUT_SEC);
?>

A se vedea ?i

  • ftp_set_option() - Set miscellaneous runtime FTP options

ftp_fput
ftp_get
Func?ii FTP


Downloads a file from the FTP server

ftp_get_option
ftp_login
Func?ii FTP
PHP Manual

ftp_get

(PHP 4, PHP 5, PHP 7)

ftp_get — Downloads a file from the FTP server

Descrierea

bool ftp_get ( resource $ftp_stream , string $local_file , string $remote_file , int $mode [, int $resumepos = 0 ] )

ftp_get() retrieves a remote file from the FTP server, and saves it into a local file.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ftp_get() example

<?php

// define some variables
$local_file = 'local.zip';
$server_file = 'server.zip';

// 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 download $server_file and save to $local_file
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully written to $local_file\n";
} else {
    echo "There was a problem\n";
}

// close the connection
ftp_close($conn_id);

?>

A se vedea ?i

  • ftp_pasv() - Turns passive mode on or off
  • ftp_fget() - Downloads a file from the FTP server and saves to an open file
  • 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
Func?ii FTP


Logs in to an FTP connection

ftp_get
ftp_mdtm
Func?ii FTP
PHP Manual

ftp_login

(PHP 4, PHP 5, PHP 7)

ftp_login — Logs in to an FTP connection

Descrierea

bool ftp_login ( resource $ftp_stream , string $username , string $password )

Logs in to the given FTP stream.

Parametri

ftp_stream

The link identifier of the FTP connection.

username

The username (USER).

password

The password (PASS).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. If login fails, PHP will also throw a warning.

Exemple

Example #1 ftp_login() example

<?php

$ftp_server = "ftp.example.com";
$ftp_user = "foo";
$ftp_pass = "bar";

// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

// try to login
if (@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
    echo "Connected as $ftp_user@$ftp_server\n";
} else {
    echo "Couldn't connect as $ftp_user\n";
}

// close the connection
ftp_close($conn_id);
?>

ftp_get
ftp_mdtm
Func?ii FTP


Returns the last modified time of the given file

ftp_login
ftp_mkdir
Func?ii FTP
PHP Manual

ftp_mdtm

(PHP 4, PHP 5, PHP 7)

ftp_mdtm — Returns the last modified time of the given file

Descrierea

int ftp_mdtm ( resource $ftp_stream , string $remote_file )

ftp_mdtm() gets the last modified time for a remote file.

Nota:

Not all servers support this feature!

Nota:

ftp_mdtm() does not work with directories.

Parametri

ftp_stream

The link identifier of the FTP connection.

remote_file

The file from which to extract the last modification time.

Valorile întoarse

Returns the last modified time as a Unix timestamp on success, or -1 on error.

Exemple

Example #1 ftp_mdtm() example

<?php

$file = 'somefile.txt';

// 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);

//  get the last modified time
$buff = ftp_mdtm($conn_id, $file);

if ($buff != -1) {
    // somefile.txt was last modified on: March 26 2003 14:16:41.
    echo "$file was last modified on : " . date("F d Y H:i:s.", $buff);
} else {
    echo "Couldn't get mdtime";
}

// close the connection
ftp_close($conn_id);

?>

ftp_login
ftp_mkdir
Func?ii FTP


Creates a directory

ftp_mdtm
ftp_nb_continue
Func?ii FTP
PHP Manual

ftp_mkdir

(PHP 4, PHP 5, PHP 7)

ftp_mkdir — Creates a directory

Descrierea

string ftp_mkdir ( resource $ftp_stream , string $directory )

Creates the specified directory on the FTP server.

Parametri

ftp_stream

The link identifier of the FTP connection.

directory

The name of the directory that will be created.

Valorile întoarse

Returns the newly created directory name on success or FALSE on error.

Exemple

Example #1 ftp_mkdir() example

<?php

$dir = 'www';

// 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 create the directory $dir
if (ftp_mkdir($conn_id, $dir)) {
 echo "successfully created $dir\n";
} else {
 echo "There was a problem while creating $dir\n";
}

// close the connection
ftp_close($conn_id);
?>

A se vedea ?i

  • ftp_rmdir() - Removes a directory

ftp_mdtm
ftp_nb_continue
Func?ii FTP


Continues retrieving/sending a file (non-blocking)

ftp_mkdir
ftp_nb_fget
Func?ii FTP
PHP Manual

ftp_nb_continue

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ftp_nb_continue — Continues retrieving/sending a file (non-blocking)

Descrierea

int ftp_nb_continue ( resource $ftp_stream )

Continues retrieving/sending a file non-blocking.

Parametri

ftp_stream

The link identifier of the FTP connection.

Valorile întoarse

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Exemple

Example #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
Func?ii FTP


Retrieves a file from the FTP server and writes it to an open file (non-blocking)

ftp_nb_continue
ftp_nb_fput
Func?ii FTP
PHP Manual

ftp_nb_fget

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ftp_nb_fget — Retrieves a file from the FTP server and writes it to an open file (non-blocking)

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Exemple

Example #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);
?>

A se vedea ?i

  • 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() - Downloads a file from the FTP server and saves to an open file
  • ftp_get() - Downloads a file from the FTP server

ftp_nb_continue
ftp_nb_fput
Func?ii FTP


Stores a file from an open file to the FTP server (non-blocking)

ftp_nb_fget
ftp_nb_get
Func?ii FTP
PHP Manual

ftp_nb_fput

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ftp_nb_fput — Stores a file from an open file to the FTP server (non-blocking)

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Exemple

Example #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);
?>

A se vedea ?i

  • ftp_nb_put() - Stores a file on the FTP server (non-blocking)
  • ftp_nb_continue() - Continues retrieving/sending a file (non-blocking)
  • ftp_put() - Uploads a file to the FTP server
  • ftp_fput() - Uploads from an open file to the FTP server

ftp_nb_fget
ftp_nb_get
Func?ii FTP


Retrieves a file from the FTP server and writes it to a local file (non-blocking)

ftp_nb_fput
ftp_nb_put
Func?ii FTP
PHP Manual

ftp_nb_get

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ftp_nb_get — Retrieves a file from the FTP server and writes it to a local file (non-blocking)

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Exemple

Example #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);
}
?>

Example #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);
}
?>

Example #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'.

A se vedea ?i

  • 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() - Downloads a file from the FTP server and saves to an open file
  • ftp_get() - Downloads a file from the FTP server

ftp_nb_fput
ftp_nb_put
Func?ii FTP


Stores a file on the FTP server (non-blocking)

ftp_nb_get
ftp_nlist
Func?ii FTP
PHP Manual

ftp_nb_put

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ftp_nb_put — Stores a file on the FTP server (non-blocking)

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Exemple

Example #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);
}
?>

Example #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);
}
?>

A se vedea ?i

  • 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() - Uploads a file to the FTP server
  • ftp_fput() - Uploads from an open file to the FTP server

ftp_nb_get
ftp_nlist
Func?ii FTP


Returns a list of files in the given directory

ftp_nb_put
ftp_pasv
Func?ii FTP
PHP Manual

ftp_nlist

(PHP 4, PHP 5, PHP 7)

ftp_nlist — Returns a list of files in the given directory

Descrierea

array ftp_nlist ( resource $ftp_stream , string $directory )

Parametri

ftp_stream

The link identifier of the FTP connection.

directory

The directory to be listed. This parameter can also include arguments, eg. ftp_nlist($conn_id, "-la /your/dir"); Note that this parameter isn't escaped so there may be some issues with filenames containing spaces and other characters.

Valorile întoarse

Returns an array of filenames from the specified directory on success or FALSE on error.

Exemple

Example #1 ftp_nlist() 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);

// get contents of the current directory
$contents = ftp_nlist($conn_id, ".");

// output $contents
var_dump($contents);

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  [0]=>
  string(11) "public_html"
  [1]=>
  string(10) "public_ftp"
  [2]=>
  string(3) "www"

A se vedea ?i

  • ftp_rawlist() - Returns a detailed list of files in the given directory

ftp_nb_put
ftp_pasv
Func?ii FTP


Turns passive mode on or off

ftp_nlist
ftp_put
Func?ii FTP
PHP Manual

ftp_pasv

(PHP 4, PHP 5, PHP 7)

ftp_pasv — Turns passive mode on or off

Descrierea

bool ftp_pasv ( resource $ftp_stream , bool $pasv )

ftp_pasv() turns on or off passive mode. In passive mode, data connections are initiated by the client, rather than by the server. It may be needed if the client is behind firewall.

Please note that ftp_pasv() can only be called after a successful login or otherwise it will fail.

Parametri

ftp_stream

The link identifier of the FTP connection.

pasv

If TRUE, the passive mode is turned on, else it's turned off.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ftp_pasv() example

<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// 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);

// turn passive mode on
ftp_pasv($conn_id, true);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
 echo "successfully uploaded $file\n";
} else {
 echo "There was a problem while uploading $file\n";
}

// close the connection
ftp_close($conn_id);
?>

ftp_nlist
ftp_put
Func?ii FTP


Uploads a file to the FTP server

ftp_pasv
ftp_pwd
Func?ii FTP
PHP Manual

ftp_put

(PHP 4, PHP 5, PHP 7)

ftp_put — Uploads a file to the FTP server

Descrierea

bool ftp_put ( resource $ftp_stream , string $remote_file , string $local_file , int $mode [, int $startpos = 0 ] )

ftp_put() stores a local file on the FTP server.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ftp_put() example

<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// 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);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
 echo "successfully uploaded $file\n";
} else {
 echo "There was a problem while uploading $file\n";
}

// close the connection
ftp_close($conn_id);
?>

A se vedea ?i

  • ftp_pasv() - Turns passive mode on or off
  • ftp_fput() - Uploads from an open file to the FTP server
  • 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
Func?ii FTP


Returns the current directory name

ftp_put
ftp_quit
Func?ii FTP
PHP Manual

ftp_pwd

(PHP 4, PHP 5, PHP 7)

ftp_pwd — Returns the current directory name

Descrierea

string ftp_pwd ( resource $ftp_stream )

Parametri

ftp_stream

The link identifier of the FTP connection.

Valorile întoarse

Returns the current directory name or FALSE on error.

Exemple

Example #1 ftp_pwd() 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);

// change directory to public_html
ftp_chdir($conn_id, 'public_html');

// print current directory
echo ftp_pwd($conn_id); // /public_html

// close the connection
ftp_close($conn_id);
?>

A se vedea ?i

  • ftp_chdir() - Changes the current directory on a FTP server
  • ftp_cdup() - Changes to the parent directory

ftp_put
ftp_quit
Func?ii FTP


Pseudonim pentru ftp_close

ftp_pwd
ftp_raw
Func?ii FTP
PHP Manual

ftp_quit

(PHP 4, PHP 5, PHP 7)

ftp_quit — Pseudonim pentru ftp_close()

Descrierea

Aceasta func?ie este pseudonim pentru: ftp_close().

ftp_pwd
ftp_raw
Func?ii FTP


Sends an arbitrary command to an FTP server

ftp_quit
ftp_rawlist
Func?ii FTP
PHP Manual

ftp_raw

(PHP 5, PHP 7)

ftp_raw — Sends an arbitrary command to an FTP server

Descrierea

array ftp_raw ( resource $ftp_stream , string $command )

Sends an arbitrary command to the FTP server.

Parametri

ftp_stream

The link identifier of the FTP connection.

command

The command to execute.

Valorile întoarse

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.

Exemple

Example #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");
?>

A se vedea ?i

  • ftp_exec() - Requests execution of a command on the FTP server

ftp_quit
ftp_rawlist
Func?ii FTP


Returns a detailed list of files in the given directory

ftp_raw
ftp_rename
Func?ii FTP
PHP Manual

ftp_rawlist

(PHP 4, PHP 5, PHP 7)

ftp_rawlist — Returns a detailed list of files in the given directory

Descrierea

mixed ftp_rawlist ( resource $ftp_stream , string $directory [, bool $recursive = false ] )

ftp_rawlist() executes the FTP LIST command, and returns the result as an array.

Parametri

ftp_stream

The link identifier of the FTP connection.

directory

The directory path. May include arguments for the LIST command.

recursive

If set to TRUE, the issued command will be LIST -R.

Valorile întoarse

Returns an array where each element corresponds to one line of text. Returns FALSE when passed directory is invalid.

The output is not parsed in any way. The system type identifier returned by ftp_systype() can be used to determine how the results should be interpreted.

Exemple

Example #1 ftp_rawlist() 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);

// get the file list for /
$buff = ftp_rawlist($conn_id, '/');

// close the connection
ftp_close($conn_id);

// output the buffer
var_dump($buff);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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"
}

A se vedea ?i

  • ftp_nlist() - Returns a list of files in the given directory

ftp_raw
ftp_rename
Func?ii FTP


Renames a file or a directory on the FTP server

ftp_rawlist
ftp_rmdir
Func?ii FTP
PHP Manual

ftp_rename

(PHP 4, PHP 5, PHP 7)

ftp_rename — Renames a file or a directory on the FTP server

Descrierea

bool ftp_rename ( resource $ftp_stream , string $oldname , string $newname )

ftp_rename() renames a file or a directory on the FTP server.

Parametri

ftp_stream

The link identifier of the FTP connection.

oldname

The old file/directory name.

newname

The new name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Upon failure (such as attempting to rename a non-existent file), an E_WARNING error will be emitted.

Exemple

Example #1 ftp_rename() example

<?php
$old_file = 'somefile.txt.bak';
$new_file = 'somefile.txt';

// 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 rename $old_file to $new_file
if (ftp_rename($conn_id, $old_file, $new_file)) {
 echo "successfully renamed $old_file to $new_file\n";
} else {
 echo "There was a problem while renaming $old_file to $new_file\n";
}

// close the connection
ftp_close($conn_id);
?>

ftp_rawlist
ftp_rmdir
Func?ii FTP


Removes a directory

ftp_rename
ftp_set_option
Func?ii FTP
PHP Manual

ftp_rmdir

(PHP 4, PHP 5, PHP 7)

ftp_rmdir — Removes a directory

Descrierea

bool ftp_rmdir ( resource $ftp_stream , string $directory )

Removes the specified directory on the FTP server.

Parametri

ftp_stream

The link identifier of the FTP connection.

directory

The directory to delete. This must be either an absolute or relative path to an empty directory.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ftp_rmdir() example

<?php

$dir = 'www/';

// 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 delete the directory $dir
if (ftp_rmdir($conn_id, $dir)) {
    echo "Successfully deleted $dir\n";
} else {
    echo "There was a problem while deleting $dir\n";
}

ftp_close($conn_id);

?>

A se vedea ?i

  • ftp_mkdir() - Creates a directory

ftp_rename
ftp_set_option
Func?ii FTP


Set miscellaneous runtime FTP options

ftp_rmdir
ftp_site
Func?ii FTP
PHP Manual

ftp_set_option

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ftp_set_option — Set miscellaneous runtime FTP options

Descrierea

bool ftp_set_option ( resource $ftp_stream , int $option , mixed $value )

This function controls various runtime options for the specified FTP stream.

Parametri

ftp_stream

The link identifier of the FTP connection.

option

Currently, the following options are supported:

Supported runtime FTP options
FTP_TIMEOUT_SEC | Changes the timeout in seconds used for all network related functions. value must be an integer that is greater than 0. The default timeout is 90 seconds.
FTP_AUTOSEEK | When enabled, GET or PUT requests with a resumepos or startpos parameter will first seek to the requested position within the file. This is enabled by default.

value

This parameter depends on which option is chosen to be altered.

Valorile întoarse

Returns TRUE if the option could be set; FALSE if not. A warning message will be thrown if the option is not supported or the passed value doesn't match the expected value for the given option.

Exemple

Example #1 ftp_set_option() example

<?php
// Set the network timeout to 10 seconds
ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 10);
?>

A se vedea ?i

  • ftp_get_option() - Retrieves various runtime behaviours of the current FTP stream

ftp_rmdir
ftp_site
Func?ii FTP


Sends a SITE command to the server

ftp_set_option
ftp_size
Func?ii FTP
PHP Manual

ftp_site

(PHP 4, PHP 5, PHP 7)

ftp_site — Sends a SITE command to the server

Descrierea

bool ftp_site ( resource $ftp_stream , string $command )

ftp_site() sends the given SITE command to the FTP server.

SITE commands are not standardized, and vary from server to server. They are useful for handling such things as file permissions and group membership.

Parametri

ftp_stream

The link identifier of the FTP connection.

command

The SITE command. Note that this parameter isn't escaped so there may be some issues with filenames containing spaces and other characters.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Sending a SITE command to an ftp server

<?php
// Connect to FTP server
$conn = ftp_connect('ftp.example.com');
if (!$conn) die('Unable to connect to ftp.example.com');

// Login as "user" with password "pass"
if (!ftp_login($conn, 'user', 'pass')) die('Error logging into ftp.example.com');

// Issue: "SITE CHMOD 0600 /home/user/privatefile" command to ftp server
if (ftp_site($conn, 'CHMOD 0600 /home/user/privatefile')) {
   echo "Command executed successfully.\n";
} else {
   die('Command failed.');
}
?>

A se vedea ?i

  • ftp_raw() - Sends an arbitrary command to an FTP server

ftp_set_option
ftp_size
Func?ii FTP


Returns the size of the given file

ftp_site
ftp_ssl_connect
Func?ii FTP
PHP Manual

ftp_size

(PHP 4, PHP 5, PHP 7)

ftp_size — Returns the size of the given file

Descrierea

int ftp_size ( resource $ftp_stream , string $remote_file )

ftp_size() returns the size of the given file in bytes.

Nota:

Not all servers support this feature.

Parametri

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file.

Valorile întoarse

Returns the file size on success, or -1 on error.

Exemple

Example #1 ftp_size() example

<?php

$file = 'somefile.txt';

// 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);

// get the size of $file
$res = ftp_size($conn_id, $file);

if ($res != -1) {
    echo "size of $file is $res bytes";
} else {
    echo "couldn't get the size";
}

// close the connection
ftp_close($conn_id);

?>

A se vedea ?i

  • ftp_rawlist() - Returns a detailed list of files in the given directory

ftp_site
ftp_ssl_connect
Func?ii FTP


Opens an Secure SSL-FTP connection

ftp_size
ftp_systype
Func?ii FTP
PHP Manual

ftp_ssl_connect

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ftp_ssl_connect — Opens an Secure SSL-FTP connection

Descrierea

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. That implies that ftp_ssl_connect() will succeed even if the server is not configured for SSL-FTP, or its certificate is invalid. Only when ftp_login() is called, the client will send the appropriate AUTH FTP command, so ftp_login() will fail in the mentioned cases.

Nota: 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.

Nota:

ftp_ssl_connect() is not intended for use with sFTP. To use sFTP with PHP, please see ssh2_sftp().

Parametri

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().

Valorile întoarse

Returns a SSL-FTP stream on success or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #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);

if (!$login_result) {
    // PHP will already have raised an E_WARNING level message in this case
    die("can't login");
}

echo ftp_pwd($conn_id); // /

// close the ssl connection
ftp_close($conn_id);
?>

A se vedea ?i

  • ftp_connect() - Opens an FTP connection

ftp_size
ftp_systype
Func?ii FTP


Returns the system type identifier of the remote FTP server

ftp_ssl_connect
Gearman
Func?ii FTP
PHP Manual

ftp_systype

(PHP 4, PHP 5, PHP 7)

ftp_systype — Returns the system type identifier of the remote FTP server

Descrierea

string ftp_systype ( resource $ftp_stream )

Returns the system type identifier of the remote FTP server.

Parametri

ftp_stream

The link identifier of the FTP connection.

Valorile întoarse

Returns the remote system type, or FALSE on error.

Exemple

Example #1 ftp_systype() example

<?php

// ftp connection
$ftp = ftp_connect('ftp.example.com');
ftp_login($ftp, 'user', 'password');

// get the system type
if ($type = ftp_systype($ftp)) {
    echo "Example.com is powered by $type\n";
} else {
    echo "Couldn't get the systype";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

Example.com is powered by UNIX

ftp_ssl_connect
Gearman
Func?ii FTP


Gearman

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • 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::setId — Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers.
    • 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
  • GearmanException — The GearmanException class
ftp_systype
Introducere
Alte servicii


Introducere

» 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
Instalarea / configurarea
Gearman


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Gearman


Necesita?i

This extension requires the » libgearman, » libevent and » uuid libraries, and a running Gearman server.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/gearman

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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_GENERATE_UNIQUE (integer)
Generate a unique id (UUID) for each task.
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)

Tipurile resurselor
Exemple
Gearman


Exemple

Cuprins

  • Basic usage
  • Basic Gearman client and worker, background
  • Basic Gearman client and worker, submitting tasks
Constante predefinite
Basic usage
Gearman


Basic usage

Example #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->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:
      echo "Success: $result\n";
      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());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

% 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

Exemple
Basic Gearman client and worker, background
Exemple


Basic Gearman client and worker, background

Example #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());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

% 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
Exemple


Basic Gearman client and worker, submitting tasks

Example #1 Basic Gearman client and worker, submitting tasks

In this example, 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());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

% 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
Exemple


The GearmanClient class

(PECL gearman >= 0.5.0)

Introducere

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 registered by a Gearman worker and the data passed is opaque to the job server.

Sinopsisul clasei

GearmanClient {
/* Metode */
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 ( callable $callback )
public bool setCompleteCallback ( callable $callback )
public bool setContext ( string $context )
public bool setCreatedCallback ( string $callback )
public bool setData ( string $data )
public bool setDataCallback ( callable $callback )
public bool setExceptionCallback ( callable $callback )
public bool setFailCallback ( callable $callback )
public bool setOptions ( int $options )
public bool setStatusCallback ( callable $callback )
public bool setTimeout ( int $timeout )
public bool setWarningCallback ( callable $callback )
public bool setWorkloadCallback ( callable $callback )
public int timeout ( void )
}

Cuprins

  • 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

Descrierea

public bool GearmanClient::addOptions ( int $options )

Adds one or more options to those already set.

Parametri

options

The options to add. One of the following constants, or a combination of them using the bitwise OR operator ("|"): GEARMAN_CLIENT_GENERATE_UNIQUE, GEARMAN_CLIENT_NON_BLOCKING, GEARMAN_CLIENT_UNBUFFERED_RESULT or GEARMAN_CLIENT_FREE_TASKS.

Valorile întoarse

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

Descrierea

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.

Parametri

host

Denumirea gazdei serverului executor.

port

Portul serverului executor.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

servers

A comma-separated list of servers, each server specified in the format 'host:port'.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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");

?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

function_name

O func?ie înregistrata pe care trebuie sa o execute serverul executor

workload

Datele serializate pentru a fi procesate

context

Contextul aplica?iei pentru a fi asociat cu o sarcina

unique

Un ID unical utilizat pentru a identifica o anumita sarcina

Valorile întoarse

A GearmanTask object or FALSE if the task could not be added.

Exemple

Example #1 Basic submission of two tasks

<?php

# Create our gearman client
$gmclient= new GearmanClient();

# add the default job server
$gmclient->addServer();

# set a function to be called when the work is complete
$gmclient->setCompleteCallback("complete");

# 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");

# run the tasks
$gmclient->runTasks();

function complete($task)
{
  print "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

COMPLETE: 2, Hello World!
COMPLETE: 1, !dlroW olleH

Example #2 Basic submission of two tasks with passing application context

<?php

$client = new GearmanClient();
$client->addServer();

# set a function to be called when the work is complete
$client->setCompleteCallback("reverse_complete");

# 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->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());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

t2: H.foo:21, Hello World!
t1: H:foo:22, !dlroW olleH

A se vedea ?i

  • 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

Descrierea

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.

Parametri

function_name

O func?ie înregistrata pe care trebuie sa o execute serverul executor

workload

Datele serializate pentru a fi procesate

context

Contextul aplica?iei pentru a fi asociat cu o sarcina

unique

Un ID unical utilizat pentru a identifica o anumita sarcina

Valorile întoarse

A GearmanTask object or FALSE if the task could not be added.

Exemple

Example #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)
Sending status: 1/12 complete
Sending status: 2/12 complete
Sending status: 2/12 complete
Sending status: 3/12 complete
Sending status: 3/12 complete
Sending status: 4/12 complete
Sending status: 4/12 complete
Sending status: 5/12 complete
Sending status: 5/12 complete
Sending status: 6/12 complete
Sending status: 6/12 complete
Sending status: 7/12 complete
Sending status: 7/12 complete
Sending status: 8/12 complete
Sending status: 8/12 complete
Sending status: 9/12 complete
Sending status: 9/12 complete
Sending status: 10/12 complete
Sending status: 10/12 complete
Sending status: 11/12 complete
Sending status: 11/12 complete
Sending status: 12/12 complete
Sending status: 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

A se vedea ?i

  • 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

Descrierea

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.

Parametri

function_name

O func?ie înregistrata pe care trebuie sa o execute serverul executor

workload

Datele serializate pentru a fi procesate

context

Contextul aplica?iei pentru a fi asociat cu o sarcina

unique

Un ID unical utilizat pentru a identifica o anumita sarcina

Valorile întoarse

A GearmanTask object or FALSE if the task could not be added.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

COMPLETE: 2, Hello World!
COMPLETE: 3, !dlroW olleH
COMPLETE: 1, !dlroW olleH
DONE

A se vedea ?i

  • 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

Descrierea

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.

Parametri

function_name

O func?ie înregistrata pe care trebuie sa o execute serverul executor

workload

Datele serializate pentru a fi procesate

context

Contextul aplica?iei pentru a fi asociat cu o sarcina

unique

Un ID unical utilizat pentru a identifica o anumita sarcina

Valorile întoarse

A GearmanTask object or FALSE if the task could not be added.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

function_name

O func?ie înregistrata pe care trebuie sa o execute serverul executor

workload

Datele serializate pentru a fi procesate

context

Contextul aplica?iei pentru a fi asociat cu o sarcina

unique

Un ID unical utilizat pentru a identifica o anumita sarcina

Valorile întoarse

A GearmanTask object or FALSE if the task could not be added.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

COMPLETE: 3, !dlroW olleH
COMPLETE: 1, !dlroW olleH
COMPLETE: 2, Hello World!
DONE

A se vedea ?i

  • 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

Descrierea

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.

Parametri

function_name

O func?ie înregistrata pe care trebuie sa o execute serverul executor

workload

Datele serializate pentru a fi procesate

context

Contextul aplica?iei pentru a fi asociat cu o sarcina

unique

Un ID unical utilizat pentru a identifica o anumita sarcina

Valorile întoarse

A GearmanTask object or FALSE if the task could not be added.

A se vedea ?i

  • 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

Descrierea

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()).

Parametri

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

Valorile întoarse

A GearmanTask object.

Exemple

Example #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++;
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • 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

Descrierea

public bool GearmanClient::clearCallbacks ( void )

Clears all the task callback functions that have previously been set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Always returns TRUE.

A se vedea ?i

  • 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

Descrierea

public GearmanClient GearmanClient::clone ( void )

Creates a copy of a GearmanClient object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public GearmanClient::__construct ( void )

Creates a GearmanClient instance representing a client that connects to the job server and submits tasks to complete.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A GearmanClient object.

A se vedea ?i

  • 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

Descrierea

public string GearmanClient::context ( void )

Get the application context previously set with GearmanClient::setContext().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The same context data structure set with GearmanClient::setContext()

A se vedea ?i

  • 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)

Descrierea

public string GearmanClient::data ( void )

Get the application data previously set with GearmanClient::setData().

Nota:

This method was replaced by GearmanClient::setContext() in the 0.6.0 release of the Gearman extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The same string data set with GearmanClient::setData()

A se vedea ?i

  • 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]

Descrierea

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().

Parametri

function_name

O func?ie înregistrata pe care trebuie sa o execute serverul executor

workload

Datele serializate pentru a fi procesate

unique

Un ID unical utilizat pentru a identifica o anumita sarcina

Valorile întoarse

A string representing the results of running a task.

Exemple

Example #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());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

Starting
Sending job
Success: !olleH

Example #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;
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • 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

Descrierea

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.

Parametri

function_name

O func?ie înregistrata pe care trebuie sa o execute serverul executor

workload

Datele serializate pentru a fi procesate

unique

Un ID unical utilizat pentru a identifica o anumita sarcina

Valorile întoarse

The job handle for the submitted task.

Exemple

Example #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";

?>

Exemplul de mai sus va afi?a ceva similar cu:

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!

A se vedea ?i

  • 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

Descrierea

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.

Parametri

function_name

O func?ie înregistrata pe care trebuie sa o execute serverul executor

workload

Datele serializate pentru a fi procesate

unique

Un ID unical utilizat pentru a identifica o anumita sarcina

Valorile întoarse

A string representing the results of running a task.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

function_name

O func?ie înregistrata pe care trebuie sa o execute serverul executor

workload

Datele serializate pentru a fi procesate

unique

Un ID unical utilizat pentru a identifica o anumita sarcina

Valorile întoarse

The job handle for the submitted task.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The job handle for the running task.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

function_name

O func?ie înregistrata pe care trebuie sa o execute serverul executor

workload

Datele serializate pentru a fi procesate

unique

Un ID unical utilizat pentru a identifica o anumita sarcina

Valorile întoarse

A string representing the results of running a task.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

function_name

O func?ie înregistrata pe care trebuie sa o execute serverul executor

workload

Datele serializate pentru a fi procesate

unique

Un ID unical utilizat pentru a identifica o anumita sarcina

Valorile întoarse

The job handle for the submitted task.

A se vedea ?i

  • 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 Git)

GearmanClient::doNormal — Run a single task and return a result

Descrierea

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.

Parametri

function_name

O func?ie înregistrata pe care trebuie sa o execute serverul executor

workload

Datele serializate pentru a fi procesate

unique

Un ID unical utilizat pentru a identifica o anumita sarcina

Valorile întoarse

A string representing the results of running a task.

Exemple

Example #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());
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

Starting
Sending job
Success: !olleH

Example #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;
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • 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

Descrierea

public array GearmanClient::doStatus ( void )

Returns the status for the running task. This should be used between repeated GearmanClient::doNormal() calls.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array representing the percentage completion given as a fraction, with the first element the numerator and the second element the denomintor.

Exemple

Example #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";

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • 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]

Descrierea

public bool GearmanClient::echo ( string $workload )

The GearmanClient::echo() method is deprecated as of pecl/gearman 1.0.0. Use GearmanClient::ping().

Parametri

workload

Some arbitrary serialized data to be echo back

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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.

Descrierea

public string GearmanClient::error ( void )

Returns an error string for the last error encountered.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A human readable error string.

A se vedea ?i

  • 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

Descrierea

public int GearmanClient::getErrno ( void )

Value of errno in the case of a GEARMAN_ERRNO return value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A valid Gearman errno.

A se vedea ?i

  • 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

Descrierea

Stil obiect-orientat (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.

Parametri

job_handle

Handle-ul sarcinii atribuit de catre serverul Gearman

Valorile întoarse

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.

Exemple

Example #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";

?>

Exemplul de mai sus va afi?a ceva similar cu:

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!

A se vedea ?i

  • 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 Git)

GearmanClient::ping — Send data to all job servers to see if they echo it back

Descrierea

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.

Parametri

workload

Some arbitrary serialized data to be echo back

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public bool GearmanClient::removeOptions ( int $options )

Removes (unsets) one or more options.

Parametri

options

The options to be removed (unset)

Valorile întoarse

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

Descrierea

public int GearmanClient::returnCode ( void )

Returns the last Gearman return code.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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)

Descrierea

public void GearmanClient::setClientCallback ( callable $callback )

Sets the callback function for accepting data packets for a task. The callback function should take a single argument, a GearmanTask object.

Nota:

This method has been replaced by GearmanClient::setDataCallback() in the 0.6.0 release of the Gearman extension.

Parametri

callback

A function or method to call

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public bool GearmanClient::setCompleteCallback ( callable $callback )

Use to set a function to be called when a GearmanTask is completed, or when GearmanJob::sendComplete() is invoked by a worker (whichever happens first).

This callback executes only when executing a GearmanTask using GearmanClient::runTasks(). It is not used for individual jobs.

Parametri

callback

A function to be called

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public bool GearmanClient::setContext ( string $context )

Sets an arbitrary string to provide application context that can later be retrieved by GearmanClient::context().

Parametri

context

Arbitrary context data

Valorile întoarse

Always returns TRUE.

A se vedea ?i

  • 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

Descrierea

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 GearmanTask oject.

Parametri

callback

A function to call

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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)

Descrierea

public bool GearmanClient::setData ( string $data )

Sets some arbitrary application data that can later be retrieved by GearmanClient::data().

Nota:

This method has been replaced by GearmanCient::setContext() in the 0.6.0 release of the Gearman extension.

Parametri

data

Valorile întoarse

Always returns TRUE.

A se vedea ?i

  • 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

Descrierea

public bool GearmanClient::setDataCallback ( callable $callback )

Sets the callback function for accepting data packets for a task. The callback function should take a single argument, a GearmanTask object.

Parametri

callback

A function or method to call

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public bool GearmanClient::setExceptionCallback ( callable $callback )

Specifies a function to call when a worker for a task sends an exception.

Parametri

callback

Function to call when the worker throws an exception

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public bool GearmanClient::setFailCallback ( callable $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.

Parametri

callback

A function to call

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public bool GearmanClient::setOptions ( int $options )

Sets one or more client options.

Parametri

options

The options to be set

Valorile întoarse

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

Descrierea

public bool GearmanClient::setStatusCallback ( callable $callback )

Sets a callback function used for getting updated status information from a worker. The function should accept a single argument, a GearmanTask object.

Parametri

callback

A function to call

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public bool GearmanClient::setTimeout ( int $timeout )

Sets the timeout for socket I/O activity.

Parametri

timeout

An interval of time in milliseconds

Valorile întoarse

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

Descrierea

public bool GearmanClient::setWarningCallback ( callable $callback )

Sets a function to be called when a worker sends a warning. The callback should accept a single argument, a GearmanTask object.

Parametri

callback

A function to call

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public bool GearmanClient::setWorkloadCallback ( callable $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.

Parametri

callback

A function to call

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public int GearmanClient::timeout ( void )

Returns the timeout in milliseconds to wait for I/O activity.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Timeout in milliseconds to wait for I/O activity. A negative value means an infinite timeout.

A se vedea ?i

  • GearmanClient::setTimeout() - Set socket I/O activity timeout

GearmanClient::setWorkloadCallback
GearmanJob
GearmanClient


The GearmanJob class

(PECL gearman >= 0.5.0)

Introducere

Sinopsisul clasei

GearmanJob {
/* Metode */
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 )
}

Cuprins

  • 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)

Descrierea

public bool GearmanJob::complete ( string $result )

Sends result data and the complete status update for this job.

Nota:

This method has been replaced by GearmanJob::sendComplete() in the 0.6.0 release of the Gearman extension.

Parametri

result

Serialized result data.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public GearmanJob::__construct ( void )

Creates a GearmanJob instance representing a job the worker is to complete.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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)

Descrierea

public bool GearmanJob::data ( string $data )

Sends data to the job server (and any listening clients) for this job.

Nota:

This method has been replaced by GearmanJob::sendData() in the 0.6.0 release of the Gearman extension.

Parametri

data

Arbitrary serialized data.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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)

Descrierea

public bool GearmanJob::exception ( string $exception )

Sends the supplied exception when this job is running.

Nota:

This method has been replaced by GearmanJob::sendException() in the 0.6.0 release of the Gearman extension.

Parametri

exception

An exception description.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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)

Descrierea

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).

Nota:

This method has been replaced by GearmanJob::sendFail() in the 0.6.0 release of the Gearman extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public string GearmanJob::functionName ( void )

Returns the function name for this job. This is the function the work will execute to perform the job.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The name of a function.

A se vedea ?i

  • 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

Descrierea

public string GearmanJob::handle ( void )

Returns the opaque job handle assigned by the job server.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An opaque job handle.

A se vedea ?i

  • 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

Descrierea

public int GearmanJob::returnCode ( void )

Returns the last return code issued by the job server.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A valid Gearman return code.

A se vedea ?i

  • 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

Descrierea

public bool GearmanJob::sendComplete ( string $result )

Sends result data and the complete status update for this job.

Parametri

result

Serialized result data.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public bool GearmanJob::sendData ( string $data )

Sends data to the job server (and any listening clients) for this job.

Parametri

data

Arbitrary serialized data.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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)

Descrierea

public bool GearmanJob::sendException ( string $exception )

Sends the supplied exception when this job is running.

Parametri

exception

An exception description.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

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).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

numerator

The numerator of the precentage completed expressed as a fraction.

denominator

The denominator of the precentage completed expressed as a fraction.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public bool GearmanJob::sendWarning ( string $warning )

Sends a warning for this job while it is running.

Parametri

warning

A warning message.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public bool GearmanJob::setReturn ( int $gearman_return_t )

Sets the return value for this job, indicates how the job completed.

Parametri

gearman_return_t

A valid Gearman return value.

Valorile întoarse

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)

Descrierea

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.

Nota:

This method has been replaced by GearmanJob::sendStatus() in the 0.6.0 release of the Gearman extenstion.

Parametri

numerator

The numerator of the precentage completed expressed as a fraction.

denominator

The denominator of the precentage completed expressed as a fraction.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public string GearmanJob::unique ( void )

Returns the unique identifiter for this job. The identifier is assigned by the client.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An opaque unique identifier.

A se vedea ?i

  • 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)

Descrierea

public bool GearmanJob::warning ( string $warning )

Sends a warning for this job while it is running.

Nota:

This method has been replaced by GearmanJob::sendWarning() in the 0.6.0 release of the Gearman extension.

Parametri

warning

A warning messages.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public string GearmanJob::workload ( void )

Returns the workload for the job. This is serialized data that is to be processed by the worker.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Serialized data.

A se vedea ?i

  • 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

Descrierea

public int GearmanJob::workloadSize ( void )

Returns the size of the job's work load (the data the worker is to process) in bytes.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The size in bytes.

A se vedea ?i

  • GearmanJob::workload() - Get workload

GearmanJob::workload
GearmanTask
GearmanJob


The GearmanTask class

(PECL gearman >= 0.5.0)

Introducere

Sinopsisul clasei

GearmanTask {
/* Metode */
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 )
}

Cuprins

  • 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

Descrierea

public GearmanTask::__construct ( void )

Creates a GearmanTask instance representing a task to be submitted to a job server.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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)

Descrierea

public GearmanTask GearmanTask::create ( void )

Returns a new GearmanTask object.

Nota:

This method was removed in the 0.6.0 version of the Gearman extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A GearmanTask oject sau FALSE în cazul e?ecului.

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

Descrierea

public string GearmanTask::data ( void )

Returns data being returned for a task by a worker.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The serialized data, or FALSE if no data is present.

A se vedea ?i

  • 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

Descrierea

public int GearmanTask::dataSize ( void )

Returns the size of the data being returned for a task.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The data size, or FALSE if there is no data.

A se vedea ?i

  • 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)

Descrierea

public string GearmanTask::function ( void )

Returns the name of the function this task is associated with, i.e., the function the Gearman worker calls.

Nota:

This method has been replaced by GearmanTask::functionName() in the 0.6.0 release of the Gearman extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string GearmanTask::functionName ( void )

Returns the name of the function this task is associated with, i.e., the function the Gearman worker calls.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool GearmanTask::isKnown ( void )

Gets the status information for whether or not this task is known to the job server.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool GearmanTask::isRunning ( void )

Indicates whether or not this task is currently running.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string GearmanTask::jobHandle ( void )

Returns the job handle for this task.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The opaque job handle.

A se vedea ?i

  • 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

Descrierea

public array GearmanTask::recvData ( int $data_len )

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

data_len

Length of data to be read.

Valorile întoarse

An array whose first element is the length of data read and the second is the data buffer. Returns FALSE if the read failed.

A se vedea ?i

  • 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

Descrierea

public int GearmanTask::returnCode ( void )

Returns the last Gearman return code for this task.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A valid Gearman return code.

A se vedea ?i

  • 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)

Descrierea

public int GearmanTask::sendData ( string $data )

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

data

Data to send to the worker.

Valorile întoarse

The length of data sent, or FALSE if the send failed.

A se vedea ?i

  • 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

Descrierea

public int GearmanTask::sendWorkload ( string $data )

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

data

Data to send to the worker.

Valorile întoarse

The length of data sent, or FALSE if the send failed.

A se vedea ?i

  • 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

Descrierea

public int GearmanTask::taskDenominator ( void )

Returns the denominator of the percentage of the task that is complete expressed as a fraction.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A number between 0 and 100, or FALSE if cannot be determined.

A se vedea ?i

  • 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

Descrierea

public int GearmanTask::taskNumerator ( void )

Returns the numerator of the percentage of the task that is complete expressed as a fraction.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A number between 0 and 100, or FALSE if cannot be determined.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The unique identifier, or FALSE if no identifier is assigned.

A se vedea ?i

  • 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)

Descrierea

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.

Nota:

This method has been replaced by GearmanTask::unique() in the 0.6.0 release of the Gearman extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The unique identifier, or FALSE if no identifier is assigned.

A se vedea ?i

  • 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

(PECL gearman >= 0.5.0)

Introducere

Sinopsisul clasei

GearmanWorker {
/* Metode */
public bool addFunction ( string $function_name , callable $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 setId ( string $id )
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 )
}

Cuprins

  • 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::setId — Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers.
  • 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

Descrierea

public bool GearmanWorker::addFunction ( string $function_name , callable $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.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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

A se vedea ?i

  • 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

Descrierea

public bool GearmanWorker::addOptions ( int $option )

Adds one or more options to the options previously set.

Parametri

option

The options to be added

Valorile întoarse

Always returns TRUE.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

host

Denumirea gazdei serverului executor.

port

Portul serverului executor.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Add alternate Gearman servers

<?php
$worker= new GearmanWorker();
$worker->addServer("10.0.0.1");
$worker->addServer("10.0.0.2", 7003);
?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

servers

A comma separated list of job servers in the format host:port. If no port is specified, it defaults to 4730.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Add two job servers

<?php

$worker= new GearmanWorker();
$worker->addServers("10.0.0.1,10.0.0.2:7003");

?>

A se vedea ?i

  • 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

Descrierea

public void GearmanWorker::clone ( void )

Creates a copy of the worker.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public GearmanWorker::__construct ( void )

Creates a GearmanWorker instance representing a worker that connects to the job server and accepts tasks to run.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A GearmanWorker object

A se vedea ?i

  • 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

Descrierea

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.

Parametri

workload

Arbitrary serialized data

Valorile întoarse

Standard Gearman return value.

A se vedea ?i

  • 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

Descrierea

public string GearmanWorker::error ( void )

Returns an error string for the last error encountered.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An error string.

A se vedea ?i

  • 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

Descrierea

public int GearmanWorker::getErrno ( void )

Returns the value of errno in the case of a GEARMAN_ERRNO return value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A valid errno.

A se vedea ?i

  • 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

Descrierea

public int GearmanWorker::options ( void )

Gets the options previously set for the worker.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The options currently set for the worker.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

function_name

The name of a function to register with the job server

timeout

An interval of time in seconds

Valorile întoarse

A standard Gearman return value.

A se vedea ?i

  • 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

Descrierea

public bool GearmanWorker::removeOptions ( int $option )

Removes (unsets) one or more worker options.

Parametri

option

The options to be removed (unset)

Valorile întoarse

Always returns TRUE.

A se vedea ?i

  • 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::setId
GearmanWorker
PHP Manual

GearmanWorker::returnCode

(PECL gearman >= 0.5.0)

GearmanWorker::returnCode — Get last Gearman return code

Descrierea

public int GearmanWorker::returnCode ( void )

Returns the last Gearman return code.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A valid Gearman return code.

A se vedea ?i

  • GearmanWorker::error() - Get the last error encountered
  • GearmanWorker::getErrno() - Get errno

GearmanWorker::removeOptions
GearmanWorker::setId
GearmanWorker


Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers.

GearmanWorker::returnCode
GearmanWorker::setOptions
GearmanWorker
PHP Manual

GearmanWorker::setId

(No version information available, might only be in Git)

GearmanWorker::setId — Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers.

Descrierea

public bool GearmanWorker::setId ( string $id )

Assigns the worker an identifier.

Parametri

id

A string identifier.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 GearmanWorker::setId() example

Set an identifier for a simple worker.

<?php
$worker= new GearmanWorker();
$worker->setId('test');
?>

Exemplul de mai sus va afi?a ceva similar cu:

Run the following command:
gearadmin --workers

Output:
30 ::3a3a:3361:3361:3a33%976303667 - : test
GearmanWorker::returnCode
GearmanWorker::setOptions
GearmanWorker


Set worker options

GearmanWorker::setId
GearmanWorker::setTimeout
GearmanWorker
PHP Manual

GearmanWorker::setOptions

(PECL gearman >= 0.5.0)

GearmanWorker::setOptions — Set worker options

Descrierea

public bool GearmanWorker::setOptions ( int $option )

Sets one or more options to the supplied value.

Parametri

option

The options to be set

Valorile întoarse

Always returns TRUE.

A se vedea ?i

  • GearmanWorker::options() - Get worker options
  • GearmanWorker::addOptions() - Add worker options
  • GearmanWorker::removeOptions() - Remove worker options
  • GearmanClient::setOptions() - Set client options

GearmanWorker::setId
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

Descrierea

public bool GearmanWorker::setTimeout ( int $timeout )

Sets the interval of time to wait for socket I/O activity.

Parametri

timeout

An interval of time in milliseconds. A negative value indicates an infinite timeout.

Valorile întoarse

Always returns TRUE.

Exemple

Example #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...

A se vedea ?i

  • 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

Descrierea

public int GearmanWorker::timeout ( void )

Returns the current time to wait, in milliseconds, for socket I/O activity.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A time period is milliseconds. A negative value indicates an infinite timeout.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

function_name

The name of a function to register with the job server

Valorile întoarse

A standard Gearman return value.

A se vedea ?i

  • 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

Descrierea

public bool GearmanWorker::unregisterAll ( void )

Unregisters all previously registered functions, ensuring that no more jobs are sent to this worker.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A standard Gearman return value.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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());
}

?>

A se vedea ?i

  • GearmanWorker::work() - Wait for and perform jobs

GearmanWorker::unregisterAll
GearmanWorker::work
GearmanWorker


Wait for and perform jobs

GearmanWorker::wait
GearmanException
GearmanWorker
PHP Manual

GearmanWorker::work

(PECL gearman >= 0.5.0)

GearmanWorker::work — Wait for and perform jobs

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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());
}

?>

A se vedea ?i

  • GearmanWorker::addFunction() - Register and add callback function

GearmanWorker::wait
GearmanException
GearmanWorker


The GearmanException class

(PECL gearman >= 0.5.0)

Introducere

Sinopsisul clasei

GearmanException extends Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode */
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
GearmanWorker::work
Gopher
Gearman


Net Gopher

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Exemplu de baza
  • Func?ii Gopher
    • gopher_parsedir — Translate a gopher formatted directory entry into an associative array.
GearmanException
Introducere
Alte servicii


Introducere

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
Instalarea / configurarea
Gopher


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Gopher


Instalarea

Necesita PHP 4.3.0 sau ulterior.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/net_gopher

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
Exemple
Gopher


Exemple

Cuprins

  • Exemplu de baza
Constante predefinite
Exemplu de baza
Gopher


Exemplu de baza

<?php
readfile("gopher://gopher.example.com/somedocument");
?>
Exemple
Func?ii Gopher
Exemple


Func?ii Gopher

Cuprins

  • gopher_parsedir — Translate a gopher formatted directory entry into an associative array.
Exemplu de baza
gopher_parsedir
Gopher


Translate a gopher formatted directory entry into an associative array.

Func?ii Gopher
Gupnp
Func?ii Gopher
PHP Manual

gopher_parsedir

(PECL net_gopher >= 0.1)

gopher_parsedir — Translate a gopher formatted directory entry into an associative array.

Descrierea

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.

Parametri

dirent

The directory entry.

Valorile întoarse

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.

Exemple

Example #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.

Example #2 Using gopher_parsedir()

<?php
$directory = file("gopher://gopher.example.com");

foreach($directory as $dirent) {
    print_r(gopher_parsedir($dirent));
}
?>

Exemplul de mai sus va afi?a:

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
)

Func?ii Gopher
Gupnp
Func?ii Gopher


Gupnp

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Browsing devices and services
    • Implementing the BinaryLight device
  • Func?ii Gupnp
    • 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 successfully
    • 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
Introducere
Alte servicii


Introducere

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
Instalarea / configurarea
Gupnp


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Gupnp


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/gupnp

Nota: 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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)

Tipurile resurselor
Exemple
Gupnp


Exemple

Cuprins

  • Browsing devices and services
  • Implementing the BinaryLight device
Constante predefinite
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.

Example #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);

?>

Exemple
Implementing the BinaryLight device
Exemple


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.

Example #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);

?>

Example #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
Func?ii Gupnp
Exemple


Func?ii Gupnp

Cuprins

  • 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 successfully
  • 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

Func?ii Gupnp
gupnp_context_get_port
Func?ii Gupnp
PHP Manual

gupnp_context_get_host_ip

(PECL gupnp >= 0.1.0)

gupnp_context_get_host_ip — Get the IP address

Descrierea

string gupnp_context_get_host_ip ( resource $context )

Get the IP address we advertise ourselves as using.

Parametri

context

A context identifier, returned by gupnp_context_new().

Valorile întoarse

Returns the IP address for the current context and FALSE on error.

Exemple

Example #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;

?>

A se vedea ?i

  • gupnp_context_new() - Create a new context
  • gupnp_context_get_port() - Get the port

Func?ii Gupnp
gupnp_context_get_port
Func?ii Gupnp


Get the port

gupnp_context_get_host_ip
gupnp_context_get_subscription_timeout
Func?ii Gupnp
PHP Manual

gupnp_context_get_port

(PECL gupnp >= 0.1.0)

gupnp_context_get_port — Get the port

Descrierea

int gupnp_context_get_port ( resource $context )

Get the port that the SOAP server is running on.

Parametri

context

A context identifier, returned by gupnp_context_new().

Valorile întoarse

Returns the port number for the current context and FALSE on error.

Exemple

Example #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;

?>

A se vedea ?i

  • 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
Func?ii Gupnp


Get the event subscription timeout

gupnp_context_get_port
gupnp_context_host_path
Func?ii Gupnp
PHP Manual

gupnp_context_get_subscription_timeout

(PECL gupnp >= 0.1.0)

gupnp_context_get_subscription_timeout — Get the event subscription timeout

Descrierea

int gupnp_context_get_subscription_timeout ( resource $context )

Get the event subscription timeout (in seconds), or 0 meaning there is no timeout.

Parametri

context

A context identifier, returned by gupnp_context_new().

Valorile întoarse

The event subscription timeout in seconds.

A se vedea ?i

  • 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
Func?ii Gupnp


Start hosting

gupnp_context_get_subscription_timeout
gupnp_context_new
Func?ii Gupnp
PHP Manual

gupnp_context_host_path

(PECL gupnp >= 0.1.0)

gupnp_context_host_path — Start hosting

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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", "");

?>

A se vedea ?i

  • gupnp_context_new() - Create a new context
  • gupnp_context_unhost_path() - Stop hosting

gupnp_context_get_subscription_timeout
gupnp_context_new
Func?ii Gupnp


Create a new context

gupnp_context_host_path
gupnp_context_set_subscription_timeout
Func?ii Gupnp
PHP Manual

gupnp_context_new

(PECL gupnp >= 0.1.0)

gupnp_context_new — Create a new context

Descrierea

resource gupnp_context_new ([ string $host_ip [, int $port = 0 ]] )

Create a new context with the specified host_ip and port.

Parametri

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.

Valorile întoarse

A context identifier.

Exemple

Example #1 Create new UPnP context

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

?>

Erori/Excep?ii

Issues E_WARNING with unable to create context.

gupnp_context_host_path
gupnp_context_set_subscription_timeout
Func?ii Gupnp


Sets the event subscription timeout

gupnp_context_new
gupnp_context_timeout_add
Func?ii Gupnp
PHP Manual

gupnp_context_set_subscription_timeout

(PECL gupnp >= 0.1.0)

gupnp_context_set_subscription_timeout — Sets the event subscription timeout

Descrierea

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.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • gupnp_context_new() - Create a new context
  • gupnp_context_get_subscription_timeout() - Get the event subscription timeout

gupnp_context_new
gupnp_context_timeout_add
Func?ii Gupnp


Sets a function to be called at regular intervals

gupnp_context_set_subscription_timeout
gupnp_context_unhost_path
Func?ii Gupnp
PHP Manual

gupnp_context_timeout_add

(PECL gupnp >= 0.1.0)

gupnp_context_timeout_add — Sets a function to be called at regular intervals

Descrierea

bool gupnp_context_timeout_add ( resource $context , int $timeout , mixed $callback [, mixed $arg ] )

Sets a function to be called at regular intervals.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Erori/Excep?ii

Issues E_WARNING with not valid callback function.

A se vedea ?i

  • gupnp_context_new() - Create a new context

gupnp_context_set_subscription_timeout
gupnp_context_unhost_path
Func?ii Gupnp


Stop hosting

gupnp_context_timeout_add
gupnp_control_point_browse_start
Func?ii Gupnp
PHP Manual

gupnp_context_unhost_path

(PECL gupnp >= 0.1.0)

gupnp_context_unhost_path — Stop hosting

Descrierea

bool gupnp_context_unhost_path ( resource $context , string $server_path )

Stop hosting the file or folder at server_path.

Parametri

context

A context identifier, returned by gupnp_context_new().

server_path

Web server path where the file or folder is hosted.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • gupnp_context_new() - Create a new context
  • gupnp_context_host_path() - Start hosting

gupnp_context_timeout_add
gupnp_control_point_browse_start
Func?ii Gupnp


Start browsing

gupnp_context_unhost_path
gupnp_control_point_browse_stop
Func?ii Gupnp
PHP Manual

gupnp_control_point_browse_start

(PECL gupnp >= 0.1.0)

gupnp_control_point_browse_start — Start browsing

Descrierea

bool gupnp_control_point_browse_start ( resource $cpoint )

Start the search and calls user-defined callback.

Parametri

cpoint

A control point identifier, returned by gupnp_control_point_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

A se vedea ?i

  • 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
Func?ii Gupnp


Stop browsing

gupnp_control_point_browse_start
gupnp_control_point_callback_set
Func?ii Gupnp
PHP Manual

gupnp_control_point_browse_stop

(PECL gupnp >= 0.1.0)

gupnp_control_point_browse_stop — Stop browsing

Descrierea

bool gupnp_control_point_browse_stop ( resource $cpoint )

Stop the search and calls user-defined callback.

Parametri

cpoint

A control point identifier, returned by gupnp_control_point_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii Gupnp


Set control point callback

gupnp_control_point_browse_stop
gupnp_control_point_new
Func?ii Gupnp
PHP Manual

gupnp_control_point_callback_set

(PECL gupnp >= 0.1.0)

gupnp_control_point_callback_set — Set control point callback

Descrierea

bool gupnp_control_point_callback_set ( resource $cpoint , int $signal , mixed $callback [, mixed $arg ] )

Set control point callback function for signal.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Erori/Excep?ii

Issues E_WARNING with not valid callback function.

A se vedea ?i

  • 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
Func?ii Gupnp


Create a new control point

gupnp_control_point_callback_set
gupnp_device_action_callback_set
Func?ii Gupnp
PHP Manual

gupnp_control_point_new

(PECL gupnp >= 0.1.0)

gupnp_control_point_new — Create a new control point

Descrierea

resource gupnp_control_point_new ( resource $context , string $target )

Create a new control point with the specified target.

Parametri

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.

Valorile întoarse

A control point identifier.

gupnp_control_point_callback_set
gupnp_device_action_callback_set
Func?ii Gupnp


Set device callback function

gupnp_control_point_new
gupnp_device_info_get_service
Func?ii Gupnp
PHP Manual

gupnp_device_action_callback_set

(PECL gupnp >= 0.1.0)

gupnp_device_action_callback_set — Set device callback function

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Issues E_WARNING either with not valid callback function or with not valid signal.

A se vedea ?i

  • gupnp_root_device_new() - Create a new root device

gupnp_control_point_new
gupnp_device_info_get_service
Func?ii Gupnp


Get the service with type

gupnp_device_action_callback_set
gupnp_device_info_get
Func?ii Gupnp
PHP Manual

gupnp_device_info_get_service

(PECL gupnp >= 0.1.0)

gupnp_device_info_get_service — Get the service with type

Descrierea

resource gupnp_device_info_get_service ( resource $root_device , string $type )

Get the service with type or false if no such device was found.

Parametri

root_device

A root device identifier, returned by gupnp_root_device_new().

type

The type of the service to be retrieved.

Valorile întoarse

A service identifier.

Exemple

Example #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
Func?ii Gupnp


Get info of root device

gupnp_device_info_get_service
gupnp_root_device_get_available
Func?ii Gupnp
PHP Manual

gupnp_device_info_get

(PECL gupnp >= 0.1.0)

gupnp_device_info_get — Get info of root device

Descrierea

array gupnp_device_info_get ( resource $root_device )

Get info of root device.

Parametri

root_device

A root device identifier, returned by gupnp_root_device_new().

Valorile întoarse

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
Func?ii Gupnp


Check whether root device is available

gupnp_device_info_get
gupnp_root_device_get_relative_location
Func?ii Gupnp
PHP Manual

gupnp_root_device_get_available

(PECL gupnp >= 0.1.0)

gupnp_root_device_get_available — Check whether root device is available

Descrierea

bool gupnp_root_device_get_available ( resource $root_device )

Get whether or not root_device is available (announcing its presence).

Parametri

root_device

A root device identifier, returned by gupnp_root_device_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • gupnp_root_device_set_available() - Set whether or not root_device is available

gupnp_device_info_get
gupnp_root_device_get_relative_location
Func?ii Gupnp


Get the relative location of root device.

gupnp_root_device_get_available
gupnp_root_device_new
Func?ii Gupnp
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.

Descrierea

string gupnp_root_device_get_relative_location ( resource $root_device )

Get the relative location of root device.

Parametri

root_device

A root device identifier, returned by gupnp_root_device_new().

Valorile întoarse

The relative location of root device

gupnp_root_device_get_available
gupnp_root_device_new
Func?ii Gupnp


Create a new root device

gupnp_root_device_get_relative_location
gupnp_root_device_set_available
Func?ii Gupnp
PHP Manual

gupnp_root_device_new

(PECL gupnp >= 0.1.0)

gupnp_root_device_new — Create a new root device

Descrierea

resource gupnp_root_device_new ( resource $context , string $location , string $description_dir )

Create a new root device, automatically downloading and parsing location.

Parametri

context

A context identifier, returned by gupnp_context_new().

location

Location of the description file for this device, relative to the HTTP root

Valorile întoarse

A root device identifier.

Exemple

Example #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);

?>

A se vedea ?i

  • 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
Func?ii Gupnp


Set whether or not root_device is available

gupnp_root_device_new
gupnp_root_device_start
Func?ii Gupnp
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

Descrierea

bool gupnp_root_device_set_available ( resource $root_device , bool $available )

Controls whether or not root_device is available (announcing its presence).

Parametri

root_device

A root device identifier, returned by gupnp_root_device_new().

available

Set TRUE if root_device should be available.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • gupnp_root_device_get_available() - Check whether root device is available

gupnp_root_device_new
gupnp_root_device_start
Func?ii Gupnp


Start main loop

gupnp_root_device_set_available
gupnp_root_device_stop
Func?ii Gupnp
PHP Manual

gupnp_root_device_start

(PECL gupnp >= 0.1.0)

gupnp_root_device_start — Start main loop

Descrierea

bool gupnp_root_device_start ( resource $root_device )

Start root server's main loop.

Parametri

root_device

A root device identifier, returned by gupnp_root_device_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • gupnp_root_device_stop() - Stop main loop

gupnp_root_device_set_available
gupnp_root_device_stop
Func?ii Gupnp


Stop main loop

gupnp_root_device_start
gupnp_service_action_get
Func?ii Gupnp
PHP Manual

gupnp_root_device_stop

(PECL gupnp >= 0.1.0)

gupnp_root_device_stop — Stop main loop

Descrierea

bool gupnp_root_device_stop ( resource $root_device )

Stop root server's main loop.

Parametri

root_device

A root device identifier, returned by gupnp_root_device_new().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • gupnp_root_device_start() - Start main loop

gupnp_root_device_start
gupnp_service_action_get
Func?ii Gupnp


Retrieves the specified action arguments

gupnp_root_device_stop
gupnp_service_action_return_error
Func?ii Gupnp
PHP Manual

gupnp_service_action_get

(PECL gupnp >= 0.1.0)

gupnp_service_action_get — Retrieves the specified action arguments

Descrierea

mixed gupnp_service_action_get ( resource $action , string $name , int $type )

Retrieves the specified action arguments.

Parametri

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.

Valorile întoarse

The value of the variable.

Erori/Excep?ii

Issues E_WARNING with not correctly defined type of the variable.

A se vedea ?i

  • gupnp_service_action_set() - Sets the specified action return values

gupnp_root_device_stop
gupnp_service_action_return_error
Func?ii Gupnp


Return error code

gupnp_service_action_get
gupnp_service_action_return
Func?ii Gupnp
PHP Manual

gupnp_service_action_return_error

(PECL gupnp >= 0.1.0)

gupnp_service_action_return_error — Return error code

Descrierea

bool gupnp_service_action_return_error ( resource $action , int $error_code [, string $error_description ] )

Return error code.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • gupnp_service_action_return() - Return successfully

gupnp_service_action_get
gupnp_service_action_return
Func?ii Gupnp


Return successfully

gupnp_service_action_return_error
gupnp_service_action_set
Func?ii Gupnp
PHP Manual

gupnp_service_action_return

(PECL gupnp >= 0.1.0)

gupnp_service_action_return — Return successfully

Descrierea

bool gupnp_service_action_return ( resource $action )

Return successfully.

Parametri

action

A service action identifier.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • gupnp_service_action_return_error() - Return error code

gupnp_service_action_return_error
gupnp_service_action_set
Func?ii Gupnp


Sets the specified action return values

gupnp_service_action_return
gupnp_service_freeze_notify
Func?ii Gupnp
PHP Manual

gupnp_service_action_set

(PECL gupnp >= 0.1.0)

gupnp_service_action_set — Sets the specified action return values

Descrierea

bool gupnp_service_action_set ( resource $action , string $name , int $type , mixed $value )

Sets the specified action return values.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Issues E_WARNING with neither not correctly defined type of the variable or the value is not corresponding to the defined type.

A se vedea ?i

  • gupnp_service_action_get() - Retrieves the specified action arguments

gupnp_service_action_return
gupnp_service_freeze_notify
Func?ii Gupnp


Freeze new notifications

gupnp_service_action_set
gupnp_service_info_get_introspection
Func?ii Gupnp
PHP Manual

gupnp_service_freeze_notify

(PECL gupnp >= 0.1.0)

gupnp_service_freeze_notify — Freeze new notifications

Descrierea

bool gupnp_service_freeze_notify ( resource $service )

Causes new notifications to be queued up until gupnp_service_thaw_notify() is called.

Parametri

service

A service identifier.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii Gupnp


Get resource introspection of service

gupnp_service_freeze_notify
gupnp_service_info_get
Func?ii Gupnp
PHP Manual

gupnp_service_info_get_introspection

(PECL gupnp >= 0.1.0)

gupnp_service_info_get_introspection — Get resource introspection of service

Descrierea

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.

Parametri

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.

Valorile întoarse

Return true if callback function was defined. Return introspection identifier if callback function was omited.

Erori/Excep?ii

Issues E_WARNING with not valid callback function.

gupnp_service_freeze_notify
gupnp_service_info_get
Func?ii Gupnp


Get full info of service

gupnp_service_info_get_introspection
gupnp_service_introspection_get_state_variable
Func?ii Gupnp
PHP Manual

gupnp_service_info_get

(PECL gupnp >= 0.1.0)

gupnp_service_info_get — Get full info of service

Descrierea

array gupnp_service_info_get ( resource $proxy )

Get full info of service.

Parametri

proxy

A service proxy identifier.

Valorile întoarse

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
Func?ii Gupnp


Returns the state variable data

gupnp_service_info_get
gupnp_service_notify
Func?ii Gupnp
PHP Manual

gupnp_service_introspection_get_state_variable

(PECL gupnp >= 0.1.0)

gupnp_service_introspection_get_state_variable — Returns the state variable data

Descrierea

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.

Parametri

introspection

A introspection identifier.

variable_name

The name of the variable to retreive.

Valorile întoarse

Return the state variable data or FALSE.

gupnp_service_info_get
gupnp_service_notify
Func?ii Gupnp


Notifies listening clients

gupnp_service_introspection_get_state_variable
gupnp_service_proxy_action_get
Func?ii Gupnp
PHP Manual

gupnp_service_notify

(PECL gupnp >= 0.1.0)

gupnp_service_notify — Notifies listening clients

Descrierea

bool gupnp_service_notify ( resource $service , string $name , int $type , mixed $value )

Notifies listening clients that the property have changed to the specified values.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Issues E_WARNING with either not correctly defined type of the variable or the value is not corresponding to the defined type.

A se vedea ?i

  • 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
Func?ii Gupnp


Send action to the service and get value

gupnp_service_notify
gupnp_service_proxy_action_set
Func?ii Gupnp
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Return value of the action.

Erori/Excep?ii

Issues E_WARNING with either not correctly defined type of the action or unable to send action.

A se vedea ?i

  • 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
Func?ii Gupnp


Send action to the service and set value

gupnp_service_proxy_action_get
gupnp_service_proxy_add_notify
Func?ii Gupnp
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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Issues E_WARNING with either not correctly defined type of the action or unable to send action.

A se vedea ?i

  • 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
Func?ii Gupnp


Sets up callback for variable change notification

gupnp_service_proxy_action_set
gupnp_service_proxy_callback_set
Func?ii Gupnp
PHP Manual

gupnp_service_proxy_add_notify

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_add_notify — Sets up callback for variable change notification

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • gupnp_service_proxy_remove_notify() - Cancels the variable change notification

gupnp_service_proxy_action_set
gupnp_service_proxy_callback_set
Func?ii Gupnp


Set service proxy callback for signal

gupnp_service_proxy_add_notify
gupnp_service_proxy_get_subscribed
Func?ii Gupnp
PHP Manual

gupnp_service_proxy_callback_set

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_callback_set — Set service proxy callback for signal

Descrierea

bool gupnp_service_proxy_callback_set ( resource $proxy , int $signal , mixed $callback [, mixed $arg ] )

Set service proxy callback for signal.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Issues E_WARNING either with not valid callback function or with not valid signal.

gupnp_service_proxy_add_notify
gupnp_service_proxy_get_subscribed
Func?ii Gupnp


Check whether subscription is valid to the service

gupnp_service_proxy_callback_set
gupnp_service_proxy_remove_notify
Func?ii Gupnp
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

Descrierea

bool gupnp_service_proxy_get_subscribed ( resource $proxy )

Check whether subscription is valid to the service.

Parametri

proxy

A service proxy identifier.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • gupnp_service_proxy_set_subscribed() - (Un)subscribes to the service.

gupnp_service_proxy_callback_set
gupnp_service_proxy_remove_notify
Func?ii Gupnp


Cancels the variable change notification

gupnp_service_proxy_get_subscribed
gupnp_service_proxy_send_action
Func?ii Gupnp
PHP Manual

gupnp_service_proxy_remove_notify

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_remove_notify — Cancels the variable change notification

Descrierea

bool gupnp_service_proxy_remove_notify ( resource $proxy , string $value )

Cancels the variable change notification.

Parametri

proxy

A service proxy identifier.

value

The variable to add notification for.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • gupnp_service_proxy_add_notify() - Sets up callback for variable change notification

gupnp_service_proxy_get_subscribed
gupnp_service_proxy_send_action
Func?ii Gupnp


Send action with multiple parameters synchronously

gupnp_service_proxy_remove_notify
gupnp_service_proxy_set_subscribed
Func?ii Gupnp
PHP Manual

gupnp_service_proxy_send_action

(PECL gupnp >= 0.2.0)

gupnp_service_proxy_send_action — Send action with multiple parameters synchronously

Descrierea

array gupnp_service_proxy_send_action ( resource $proxy , string $action , array $in_params , array $out_params )

Send action with parameters in_params to the service exposed by proxy synchronously and return out_params with values or FALSE on error.

Parametri

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.

Valorile întoarse

Return out_params array with values or FALSE on error.

Erori/Excep?ii

Issues E_WARNING with either not correctly defined in_params and out_params or unable to send action.

A se vedea ?i

  • 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
Func?ii Gupnp


(Un)subscribes to the service.

gupnp_service_proxy_send_action
gupnp_service_thaw_notify
Func?ii Gupnp
PHP Manual

gupnp_service_proxy_set_subscribed

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_set_subscribed — (Un)subscribes to the service.

Descrierea

bool gupnp_service_proxy_set_subscribed ( resource $proxy , bool $subscribed )

(Un)subscribes to the service.

Parametri

proxy

A service proxy identifier.

subscribed

Set TRUE to subscribe to this service.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • gupnp_service_proxy_get_subscribed() - Check whether subscription is valid to the service

gupnp_service_proxy_send_action
gupnp_service_thaw_notify
Func?ii Gupnp


Sends out any pending notifications and stops queuing of new ones.

gupnp_service_proxy_set_subscribed
Hyperwave API
Func?ii Gupnp
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.

Descrierea

bool gupnp_service_thaw_notify ( resource $service )

Sends out any pending notifications and stops queuing of new ones.

Parametri

service

A service identifier.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • gupnp_service_notify() - Notifies listening clients
  • gupnp_service_freeze_notify() - Freeze new notifications

gupnp_service_proxy_set_subscribed
Hyperwave API
Func?ii Gupnp


Hyperwave API

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Integration with Apache
  • Hyperwave API Func?ii
    • 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
gupnp_service_thaw_notify
Introducere
Alte servicii


Introducere

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).

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.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.2.0.

Hyperwave API
Instalarea / configurarea
Hyperwave API


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Hyperwave API


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/hwapi.

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.2.0

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Hyperwave API configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
hwapi.allow_persistent | "0" | PHP_INI_SYSTEM |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Integration with Apache
Hyperwave API


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.

Constante predefinite
Hyperwave API Func?ii
Hyperwave API


Integration with Apache
hw_api::checkin
Hyperwave API
PHP Manual

Hyperwave API Func?ii

Integration with Apache

The integration with Apache and possible other servers has been described in the separate chapter.

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().

Nota:

Methods returning boolean can return TRUE, FALSE or HW_API_Error object.

Cuprins

  • 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
Integration with Apache
hw_api::checkin
Hyperwave API


Checks in an object

Hyperwave API Func?ii
hw_api::checkout
Hyperwave API Func?ii
PHP Manual

hw_api::checkin

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::checkin — Checks in an object

Descrierea

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.

Parametri

parameter

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • hw_api::checkout

Hyperwave API Func?ii
hw_api::checkout
Hyperwave API Func?ii


Checks out an object

hw_api::checkin
hw_api::children
Hyperwave API Func?ii
PHP Manual

hw_api::checkout

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::checkout — Checks out an object

Descrierea

bool hw_api::checkout ( array $parameter )

This function checks out an object or a whole hierarchy of objects.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • hw_api::checkin

hw_api::checkin
hw_api::children
Hyperwave API Func?ii


Returns children of an object

hw_api::checkout
hw_api::content
Hyperwave API Func?ii
PHP Manual

hw_api::children

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::children — Returns children of an object

Descrierea

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.

Parametri

parameter

The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Valorile întoarse

The return value is an array of objects of type HW_API_Object or HW_API_Error.

A se vedea ?i

  • hw_api::parents

hw_api::checkout
hw_api::content
Hyperwave API Func?ii


Returns content of an object

hw_api::children
hw_api::copy
Hyperwave API Func?ii
PHP Manual

hw_api::content

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::content — Returns content of an object

Descrierea

HW_API_Content hw_api::content ( array $parameter )

This function returns the content of a document as an object of type hw_api_content.

Parametri

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.

Valorile întoarse

Returns an instance of hw_api_content.

hw_api::children
hw_api::copy
Hyperwave API Func?ii


Copies physically

hw_api::content
hw_api::dbstat
Hyperwave API Func?ii
PHP Manual

hw_api::copy

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::copy — Copies physically

Descrierea

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.

Parametri

parameter

The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. The optional parameter is 'attributeSelector'`

Valorile întoarse

Returns the copied object.

A se vedea ?i

  • hw_api::move
  • hw_api::link

hw_api::content
hw_api::dbstat
Hyperwave API Func?ii


Returns statistics about database server

hw_api::copy
hw_api::dcstat
Hyperwave API Func?ii
PHP Manual

hw_api::dbstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dbstat — Returns statistics about database server

Descrierea

hw_api_object hw_api::dbstat ( array $parameter )

Returns statistics about database server.

Parametri

parameter

Valorile întoarse

A se vedea ?i

  • hw_api::dcstat
  • hw_api::hwstat
  • hw_api::ftstat

hw_api::copy
hw_api::dcstat
Hyperwave API Func?ii


Returns statistics about document cache server

hw_api::dbstat
hw_api::dstanchors
Hyperwave API Func?ii
PHP Manual

hw_api::dcstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dcstat — Returns statistics about document cache server

Descrierea

hw_api_object hw_api::dcstat ( array $parameter )

Returns statistics about document cache server.

Parametri

parameter

Valorile întoarse

A se vedea ?i

  • hw_api::dbstat
  • hw_api::hwstat
  • hw_api::ftstat

hw_api::dbstat
hw_api::dstanchors
Hyperwave API Func?ii


Returns a list of all destination anchors

hw_api::dcstat
hw_api::dstofsrcanchor
Hyperwave API Func?ii
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

Descrierea

array hw_api::dstanchors ( array $parameter )

Retrieves all destination anchors of an object.

Parametri

parameter

The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Valorile întoarse

A se vedea ?i

  • hw_api::srcanchors

hw_api::dcstat
hw_api::dstofsrcanchor
Hyperwave API Func?ii


Returns destination of a source anchor

hw_api::dstanchors
hw_api::find
Hyperwave API Func?ii
PHP Manual

hw_api::dstofsrcanchor

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dstofsrcanchor — Returns destination of a source anchor

Descrierea

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.

Parametri

parameter

The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

Valorile întoarse

A se vedea ?i

  • hw_api::srcanchors
  • hw_api::dstanchors
  • hw_api::objectbyanchor

hw_api::dstanchors
hw_api::find
Hyperwave API Func?ii


Search for objects

hw_api::dstofsrcanchor
hw_api::ftstat
Hyperwave API Func?ii
PHP Manual

hw_api::find

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::find — Search for objects

Descrierea

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.

Parametri

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.

Valorile întoarse

hw_api::dstofsrcanchor
hw_api::ftstat
Hyperwave API Func?ii


Returns statistics about fulltext server

hw_api::find
hw_api::hwstat
Hyperwave API Func?ii
PHP Manual

hw_api::ftstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::ftstat — Returns statistics about fulltext server

Descrierea

hw_api_object hw_api::ftstat ( array $parameter )

Returns statistics about fulltext server.

Parametri

parameter

Valorile întoarse

A se vedea ?i

  • hw_api::dcstat
  • hw_api::dbstat
  • hw_api::hwstat

hw_api::find
hw_api::hwstat
Hyperwave API Func?ii


Returns statistics about Hyperwave server

hw_api::ftstat
hw_api::identify
Hyperwave API Func?ii
PHP Manual

hw_api::hwstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::hwstat — Returns statistics about Hyperwave server

Descrierea

hw_api_object hw_api::hwstat ( array $parameter )

Returns statistics about Hyperwave server.

Parametri

parameter

Valorile întoarse

A se vedea ?i

  • hw_api::dcstat
  • hw_api::dbstat
  • hw_api::ftstat

hw_api::ftstat
hw_api::identify
Hyperwave API Func?ii


Log into Hyperwave Server

hw_api::hwstat
hw_api::info
Hyperwave API Func?ii
PHP Manual

hw_api::identify

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::identify — Log into Hyperwave Server

Descrierea

bool hw_api::identify ( array $parameter )

Logs into the Hyperwave Server.

Parametri

parameter

The parameter array must contain the elements 'username' and 'password'.

Valorile întoarse

Returns an object of typeHW_API_Error if identification failed or TRUE if it was successful.

hw_api::hwstat
hw_api::info
Hyperwave API Func?ii


Returns information about server configuration

hw_api::identify
hw_api::insert
Hyperwave API Func?ii
PHP Manual

hw_api::info

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::info — Returns information about server configuration

Descrierea

array hw_api::info ( array $parameter )

Returns information about server configuration.

Parametri

parameter

Valorile întoarse

A se vedea ?i

  • hw_api::dcstat
  • hw_api::dbstat
  • hw_api::ftstat
  • hw_api::hwstat

hw_api::identify
hw_api::insert
Hyperwave API Func?ii


Inserts a new object

hw_api::info
hw_api::insertanchor
Hyperwave API Func?ii
PHP Manual

hw_api::insert

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::insert — Inserts a new object

Descrierea

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.

Parametri

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

Valorile întoarse

A se vedea ?i

  • hw_api::replace

hw_api::info
hw_api::insertanchor
Hyperwave API Func?ii


Inserts a new object of type anchor

hw_api::insert
hw_api::insertcollection
Hyperwave API Func?ii
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

Descrierea

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.

Parametri

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.

Valorile întoarse

A se vedea ?i

  • hw_api::insert
  • hw_api::insertdocument
  • hw_api::insertcollection

hw_api::insert
hw_api::insertcollection
Hyperwave API Func?ii


Inserts a new object of type collection

hw_api::insertanchor
hw_api::insertdocument
Hyperwave API Func?ii
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

Descrierea

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.

Parametri

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.

Valorile întoarse

A se vedea ?i

  • hw_api::insert
  • hw_api::insertdocument
  • hw_api::insertanchor

hw_api::insertanchor
hw_api::insertdocument
Hyperwave API Func?ii


Inserts a new object of type document

hw_api::insertcollection
hw_api::link
Hyperwave API Func?ii
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

Descrierea

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.

Parametri

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.

Valorile întoarse

A se vedea ?i

  • hw_api::insert
  • hw_api::insertcollection
  • hw_api::insertanchor

hw_api::insertcollection
hw_api::link
Hyperwave API Func?ii


Creates a link to an object

hw_api::insertdocument
hw_api::lock
Hyperwave API Func?ii
PHP Manual

hw_api::link

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::link — Creates a link to an object

Descrierea

bool hw_api::link ( array $parameter )

Creates a link to an object. Accessing this link is like accessing the object to links points to.

Parametri

parameter

The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. 'destinationParentIdentifier' is the target collection.

Valorile întoarse

The function returns TRUE on success or an error object.

A se vedea ?i

  • hw_api::copy

hw_api::insertdocument
hw_api::lock
Hyperwave API Func?ii


Locks an object

hw_api::link
hw_api::move
Hyperwave API Func?ii
PHP Manual

hw_api::lock

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::lock — Locks an object

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • hw_api::unlock

hw_api::link
hw_api::move
Hyperwave API Func?ii


Moves object between collections

hw_api::lock
hw_api::object
Hyperwave API Func?ii
PHP Manual

hw_api::move

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::move — Moves object between collections

Descrierea

bool hw_api::move ( array $parameter )

Moves object between collections.

Parametri

parameter

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • hw_objrec2array()

hw_api::lock
hw_api::object
Hyperwave API Func?ii


Retrieve attribute information

hw_api::move
hw_api::objectbyanchor
Hyperwave API Func?ii
PHP Manual

hw_api::object

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::object — Retrieve attribute information

Descrierea

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.

Parametri

parameter

The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'version'.

Valorile întoarse

The returned object is an instance of class HW_API_Object on success or HW_API_Error if an error occurred.

Exemple

This simple example retrieves an object and checks for errors.

Example #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);
?>

A se vedea ?i

  • hw_api::content

hw_api::move
hw_api::objectbyanchor
Hyperwave API Func?ii


Returns the object an anchor belongs to

hw_api::object
hw_api::parents
Hyperwave API Func?ii
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

Descrierea

hw_api_object hw_api::objectbyanchor ( array $parameter )

This function retrieves an object the specified anchor belongs to.

Parametri

parameter

The parameter array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

Valorile întoarse

A se vedea ?i

  • hw_api::dstofsrcanchor
  • hw_api::srcanchors
  • hw_api::dstanchors

hw_api::object
hw_api::parents
Hyperwave API Func?ii


Returns parents of an object

hw_api::objectbyanchor
hw_api::remove
Hyperwave API Func?ii
PHP Manual

hw_api::parents

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::parents — Returns parents of an object

Descrierea

array hw_api::parents ( array $parameter )

Retrieves the parents of an object. The parents can be further filtered by specifying an object query.

Parametri

parameter

The parameter array contains the required elements 'objectidentifier' and the optional elements 'attributeselector' and 'objectquery'.

Valorile întoarse

The return value is an array of objects of type HW_API_Object or HW_API_Error.

A se vedea ?i

  • hw_api::children

hw_api::objectbyanchor
hw_api::remove
Hyperwave API Func?ii


Delete an object

hw_api::parents
hw_api::replace
Hyperwave API Func?ii
PHP Manual

hw_api::remove

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::remove — Delete an object

Descrierea

bool hw_api::remove ( array $parameter )

Removes an object from the specified parent. Collections will be removed recursively.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • hw_api::move

hw_api::parents
hw_api::replace
Hyperwave API Func?ii


Replaces an object

hw_api::remove
hw_api::setcommittedversion
Hyperwave API Func?ii
PHP Manual

hw_api::replace

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::replace — Replaces an object

Descrierea

hw_api_object hw_api::replace ( array $parameter )

Replaces the attributes and the content of an object.

Parametri

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

Valorile întoarse

A se vedea ?i

  • hw_api::insert

hw_api::remove
hw_api::setcommittedversion
Hyperwave API Func?ii


Commits version other than last version

hw_api::replace
hw_api::srcanchors
Hyperwave API Func?ii
PHP Manual

hw_api::setcommittedversion

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::setcommittedversion — Commits version other than last version

Descrierea

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.

Parametri

parameter

Valorile întoarse

A se vedea ?i

  • hw_api::checkin
  • hw_api::checkout

hw_api::replace
hw_api::srcanchors
Hyperwave API Func?ii


Returns a list of all source anchors

hw_api::setcommittedversion
hw_api::srcsofdst
Hyperwave API Func?ii
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

Descrierea

array hw_api::srcanchors ( array $parameter )

Retrieves all source anchors of an object.

Parametri

parameter

The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Valorile întoarse

A se vedea ?i

  • hw_api::dstanchors

hw_api::setcommittedversion
hw_api::srcsofdst
Hyperwave API Func?ii


Returns source of a destination object

hw_api::srcanchors
hw_api::unlock
Hyperwave API Func?ii
PHP Manual

hw_api::srcsofdst

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::srcsofdst — Returns source of a destination object

Descrierea

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.

Parametri

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.

Valorile întoarse

A se vedea ?i

  • hw_api::dstofsrcanchor

hw_api::srcanchors
hw_api::unlock
Hyperwave API Func?ii


Unlocks a locked object

hw_api::srcsofdst
hw_api::user
Hyperwave API Func?ii
PHP Manual

hw_api::unlock

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::unlock — Unlocks a locked object

Descrierea

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.

Parametri

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().

Valorile întoarse

Returns TRUE on success or an object of class HW_API_Error.

A se vedea ?i

  • hw_api::lock

hw_api::srcsofdst
hw_api::user
Hyperwave API Func?ii


Returns the own user object

hw_api::unlock
hw_api::userlist
Hyperwave API Func?ii
PHP Manual

hw_api::user

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::user — Returns the own user object

Descrierea

hw_api_object hw_api::user ( array $parameter )

Returns the own user object.

Parametri

parameter

Valorile întoarse

A se vedea ?i

  • hw_api::userlist

hw_api::unlock
hw_api::userlist
Hyperwave API Func?ii


Returns a list of all logged in users

hw_api::user
hw_api_attribute::key
Hyperwave API Func?ii
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

Descrierea

array hw_api::userlist ( array $parameter )

Returns a list of all logged in users.

Parametri

parameter

Valorile întoarse

A se vedea ?i

  • hw_api::user

hw_api::user
hw_api_attribute::key
Hyperwave API Func?ii


Returns key of the attribute

hw_api::userlist
hw_api_attribute::langdepvalue
Hyperwave API Func?ii
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

Descrierea

string hw_api_attribute::key ( void )

Returns the name of the attribute.

Valorile întoarse

Returns the name of the attribute as a string.

A se vedea ?i

  • hw_api_attribute::value

hw_api::userlist
hw_api_attribute::langdepvalue
Hyperwave API Func?ii


Returns value for a given language

hw_api_attribute::key
hw_api_attribute::value
Hyperwave API Func?ii
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

Descrierea

string hw_api_attribute::langdepvalue ( string $language )

Returns the value in the given language of the attribute.

Parametri

language

Valorile întoarse

Returns the value of the attribute as a string.

A se vedea ?i

  • hw_api_attribute::value

hw_api_attribute::key
hw_api_attribute::value
Hyperwave API Func?ii


Returns value of the attribute

hw_api_attribute::langdepvalue
hw_api_attribute::values
Hyperwave API Func?ii
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

Descrierea

string hw_api_attribute::value ( void )

Gets the value of the attribute.

Valorile întoarse

Returns the value, as a string.

A se vedea ?i

  • hw_api_attribute::key
  • hw_api_attribute::values

hw_api_attribute::langdepvalue
hw_api_attribute::values
Hyperwave API Func?ii


Returns all values of the attribute

hw_api_attribute::value
hw_api_content::mimetype
Hyperwave API Func?ii
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

Descrierea

array hw_api_attribute::values ( void )

Gets all values of the attribute.

Valorile întoarse

Returns an array of attribute values.

A se vedea ?i

  • hw_api_attribute::value

hw_api_attribute::value
hw_api_content::mimetype
Hyperwave API Func?ii


Returns mimetype

hw_api_attribute::values
hw_api_content::read
Hyperwave API Func?ii
PHP Manual

hw_api_content::mimetype

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_content::mimetype — Returns mimetype

Descrierea

string hw_api_content::mimetype ( void )

Returns the mimetype of the content.

Valorile întoarse

Returns the mimetype as a string.

hw_api_attribute::values
hw_api_content::read
Hyperwave API Func?ii


Read content

hw_api_content::mimetype
hw_api_error::count
Hyperwave API Func?ii
PHP Manual

hw_api_content::read

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_content::read — Read content

Descrierea

string hw_api_content::read ( string $buffer , int $len )

Reads len bytes from the content into the given buffer.

Parametri

buffer

len

Number of bytes to read.

Valorile întoarse

hw_api_content::mimetype
hw_api_error::count
Hyperwave API Func?ii


Returns number of reasons

hw_api_content::read
hw_api_error::reason
Hyperwave API Func?ii
PHP Manual

hw_api_error::count

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_error::count — Returns number of reasons

Descrierea

int hw_api_error::count ( void )

Returns the number of error reasons.

Valorile întoarse

Returns the number of errors, as an integer.

A se vedea ?i

  • hw_api_error::reason

hw_api_content::read
hw_api_error::reason
Hyperwave API Func?ii


Returns reason of error

hw_api_error::count
hw_api_object::assign
Hyperwave API Func?ii
PHP Manual

hw_api_error::reason

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_error::reason — Returns reason of error

Descrierea

HW_API_Reason hw_api_error::reason ( void )

Returns the first error reason.

Valorile întoarse

A se vedea ?i

  • hw_api_error::count

hw_api_error::count
hw_api_object::assign
Hyperwave API Func?ii


Clones object

hw_api_error::reason
hw_api_object::attreditable
Hyperwave API Func?ii
PHP Manual

hw_api_object::assign

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::assign — Clones object

Descrierea

bool hw_api_object::assign ( array $parameter )

Clones the attributes of an object.

Parametri

parameter

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

hw_api_error::reason
hw_api_object::attreditable
Hyperwave API Func?ii


Checks whether an attribute is editable

hw_api_object::assign
hw_api_object::count
Hyperwave API Func?ii
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

Descrierea

bool hw_api_object::attreditable ( array $parameter )

Checks whether an attribute is editable.

Parametri

parameter

Valorile întoarse

Returns TRUE if the attribute is editable, FALSE otherwise.

hw_api_object::assign
hw_api_object::count
Hyperwave API Func?ii


Returns number of attributes

hw_api_object::attreditable
hw_api_object::insert
Hyperwave API Func?ii
PHP Manual

hw_api_object::count

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::count — Returns number of attributes

Descrierea

int hw_api_object::count ( array $parameter )

Returns the number of attributes.

Parametri

parameter

Valorile întoarse

Returns the number as an integer.

hw_api_object::attreditable
hw_api_object::insert
Hyperwave API Func?ii


Inserts new attribute

hw_api_object::count
hw_api_object::remove
Hyperwave API Func?ii
PHP Manual

hw_api_object::insert

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::insert — Inserts new attribute

Descrierea

bool hw_api_object::insert ( HW_API_Attribute $attribute )

Adds an attribute to the object.

Parametri

attribute

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • hw_api_object::remove

hw_api_object::count
hw_api_object::remove
Hyperwave API Func?ii


Removes attribute

hw_api_object::insert
hw_api_object::title
Hyperwave API Func?ii
PHP Manual

hw_api_object::remove

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::remove — Removes attribute

Descrierea

bool hw_api_object::remove ( string $name )

Removes the attribute with the given name.

Parametri

name

The attribute name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • hw_api_object::insert

hw_api_object::insert
hw_api_object::title
Hyperwave API Func?ii


Returns the title attribute

hw_api_object::remove
hw_api_object::value
Hyperwave API Func?ii
PHP Manual

hw_api_object::title

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::title — Returns the title attribute

Descrierea

string hw_api_object::title ( array $parameter )

Returns the title attribute.

Parametri

parameter

Valorile întoarse

Returns the title as a string.

hw_api_object::remove
hw_api_object::value
Hyperwave API Func?ii


Returns value of attribute

hw_api_object::title
hw_api_reason::description
Hyperwave API Func?ii
PHP Manual

hw_api_object::value

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::value — Returns value of attribute

Descrierea

string hw_api_object::value ( string $name )

Returns value of an attribute.

Parametri

name

The attribute name.

Valorile întoarse

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 Func?ii


Returns description of reason

hw_api_object::value
hw_api_reason::type
Hyperwave API Func?ii
PHP Manual

hw_api_reason::description

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_reason::description — Returns description of reason

Descrierea

string hw_api_reason::description ( void )

Returns the description of a reason

Valorile întoarse

Returns the description, as a string.

hw_api_object::value
hw_api_reason::type
Hyperwave API Func?ii


Returns type of reason

hw_api_reason::description
hwapi_attribute_new
Hyperwave API Func?ii
PHP Manual

hw_api_reason::type

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_reason::type — Returns type of reason

Descrierea

HW_API_Reason hw_api_reason::type ( void )

Returns the type of a reason.

Valorile întoarse

Returns an instance of HW_API_Reason.

hw_api_reason::description
hwapi_attribute_new
Hyperwave API Func?ii


Creates instance of class hw_api_attribute

hw_api_reason::type
hwapi_content_new
Hyperwave API Func?ii
PHP Manual

hwapi_attribute_new

(No version information available, might only be in Git)

hwapi_attribute_new — Creates instance of class hw_api_attribute

Descrierea

HW_API_Attribute hwapi_attribute_new ([ string $name [, string $value ]] )

Creates a new instance of hw_api_attribute with the given name and value.

Parametri

name

The attribute name.

value

The attribute value.

Valorile întoarse

Returns an instance of hw_api_attribute.

hw_api_reason::type
hwapi_content_new
Hyperwave API Func?ii


Create new instance of class hw_api_content

hwapi_attribute_new
hwapi_hgcsp
Hyperwave API Func?ii
PHP Manual

hwapi_content_new

(No version information available, might only be in Git)

hwapi_content_new — Create new instance of class hw_api_content

Descrierea

HW_API_Content hwapi_content_new ( string $content , string $mimetype )

Creates a new content object from the string content.

Parametri

content

mimetype

The mimetype for the contents.

Valorile întoarse

hwapi_attribute_new
hwapi_hgcsp
Hyperwave API Func?ii


Returns object of class hw_api

hwapi_content_new
hwapi_object_new
Hyperwave API Func?ii
PHP Manual

hwapi_hgcsp

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hwapi_hgcsp — Returns object of class hw_api

Descrierea

HW_API hwapi_hgcsp ( string $hostname [, int $port ] )

Opens a connection to the Hyperwave server on host hostname. The protocol used is HGCSP.

Parametri

hostname

The host name.

port

If you do not pass a port number, 418 is used.

Valorile întoarse

Returns an instance of HW_API.

hwapi_content_new
hwapi_object_new
Hyperwave API Func?ii


Creates a new instance of class hwapi_object_new

hwapi_hgcsp
LDAP
Hyperwave API Func?ii
PHP Manual

hwapi_object_new

(No version information available, might only be in Git)

hwapi_object_new — Creates a new instance of class hwapi_object_new

Descrierea

hw_api_object hwapi_object_new ( array $parameter )

Creates a new instance of the class hw_api_object.

Parametri

parameter

Valorile întoarse

A se vedea ?i

  • hw_api::lock

hwapi_hgcsp
LDAP
Hyperwave API Func?ii


Lightweight Directory Access Protocol

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Using the PHP LDAP calls
  • Exemple
    • Basic usage
  • Func?ii LDAP
    • 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 — Pseudonim pentru ldap_unbind
    • ldap_compare — Compare value of attribute found in entry specified with DN
    • ldap_connect — Connect to an LDAP server
    • ldap_control_paged_result_response — Retrieve the LDAP pagination cookie
    • ldap_control_paged_result — Send LDAP pagination control
    • 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_escape — Escape a string for use in an LDAP filter or DN
    • 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_batch — Batch and execute modifications on an LDAP entry
    • 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 on the client side
    • ldap_start_tls — Ini?iaza TLS
    • ldap_t61_to_8859 — Transleaza caractere t61 în caractere 8859
    • ldap_unbind — Unbind from LDAP directory
hwapi_object_new
Introducere
Alte servicii


Introducere

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

  • Internet Engineering Taskforce RFCs » 4510 through » 4519.

The Netscape SDK contains a helpful » Programmer's Guide in HTML format.

LDAP
Instalarea / configurarea
LDAP


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
LDAP


Necesita?i

You will need to get and compile LDAP client libraries from either » OpenLDAP or » Bind9.net in order to compile PHP with LDAP support. For PHP 5.6 or newer you will need OpenLDAP 2.4 or newer.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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.

Nota: Note to Win32 Users

Pentru ca aceasta extensie sa func?ioneze, anumite fi?iere DLL trebuie sa fie accesibile în calea de sistem a Windows din variabila PATH. Pentru informa?ii despre cum poate fi realizat acest lucru, accesa?i FAQ întitulat " Cum sa adaug directorul meu PHP la variabila PATH din Windows" pentru informa?ii despre cum sa realiza?i aceasta. Cu toate ca copierea fi?ierelor DLL din directorul PHP în directorul de sistem al Windows de asemenea func?ioneaza (deoarece directorul de sistem este în mod implicit inclus în variabila PATH), acest lucru nu este recomandabil. Aceasta extensie necesita ca urmatoarele fi?iere sa existe în calea PATH : libeay32.dll and ssleay32.dll

In order to use Oracle LDAP libraries, proper Oracle environment has to be set.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

LDAP configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
ldap.max_links | "-1" | PHP_INI_SYSTEM |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

ldap.max_links integer

The maximum number of LDAP connections per process.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Most LDAP functions operate on or return resources (e.g. ldap_connect() returns a positive LDAP link identifier required by most LDAP functions).

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.

Nota: 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.

Nota: 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_DIAGNOSTIC_MESSAGE (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.
LDAP_OPT_X_KEEPALIVE_IDLE (integer)
Specifies the number of seconds a connection needs to remain idle before TCP starts sending keepalive probes.
LDAP_OPT_X_KEEPALIVE_PROBES (integer)
Specifies the maximum number of keepalive probes TCP should send before dropping the connection.
LDAP_OPT_X_KEEPALIVE_INTERVAL (integer)
Specifies the interval in seconds between individual keepalive probes.
LDAP_OPT_X_TLS_CACERTDIR (string)
Specifies the path of the directory containing CA certificates.
LDAP_OPT_X_TLS_CACERTFILE (string)
Specifies the full-path of the CA certificate file.
LDAP_OPT_X_TLS_CERTFILE (string)
Specifies the full-path of the certificate file.
LDAP_OPT_X_TLS_CIPHER_SUITE (string)
Specifies the allowed cipher suite.
LDAP_OPT_X_TLS_CRLCHECK (integer)
Specifies the CRL evaluation strategy. This must be one of: LDAP_OPT_X_TLS_CRL_NONE,LDAP_OPT_X_TLS_CRL_PEER, LDAP_OPT_X_TLS_CRL_ALL.

Nota: This option is only valid for OpenSSL.

LDAP_OPT_X_TLS_CRLFILE (string)
Specifies the full-path of the CRL file.

Nota: This option is only valid for GnuTLS.

LDAP_OPT_X_TLS_DHFILE (string)
Specifies the full-path of the file containing the parameters for Diffie-Hellman ephemeral key exchange.

Nota: This option is ignored by GnuTLS and Mozilla NSS.

LDAP_OPT_X_TLS_KEYFILE (string)
Specifies the full-path of the certificate key file.
LDAP_OPT_X_TLS_PROTOCOL_MIN (integer)
Specifies the minimum protocol version. This can be one of: LDAP_OPT_X_TLS_PROTOCOL_SSL2,LDAP_OPT_X_TLS_PROTOCOL_SSL3, LDAP_OPT_X_TLS_PROTOCOL_TLS1_0, LDAP_OPT_X_TLS_PROTOCOL_TLS1_1, LDAP_OPT_X_TLS_PROTOCOL_TLS1_2
LDAP_OPT_X_TLS_RANDOM_FILE (string)
LDAP_OPT_X_TLS_REQUIRE_CERT (integer)
Specifies the certificate checking checking strategy. This must be one of: LDAP_OPT_X_TLS_NEVER,LDAP_OPT_X_TLS_HARD, LDAP_OPT_X_TLS_DEMAND, LDAP_OPT_X_TLS_ALLOW, LDAP_OPT_X_TLS_TRY. (Available as of PHP 7.0.0)
GSLC_SSL_NO_AUTH (integer)
GSLC_SSL_ONEWAY_AUTH (integer)
GSLC_SSL_TWOWAY_AUTH (integer)
Tipurile resurselor
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"

Constante predefinite
Exemple
LDAP


Exemple

Cuprins

  • 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.

Example #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 entries 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>";
}
?>
Exemple
Func?ii LDAP
Exemple


Func?ii LDAP

Cuprins

  • 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 — Pseudonim pentru ldap_unbind
  • ldap_compare — Compare value of attribute found in entry specified with DN
  • ldap_connect — Connect to an LDAP server
  • ldap_control_paged_result_response — Retrieve the LDAP pagination cookie
  • ldap_control_paged_result — Send LDAP pagination control
  • 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_escape — Escape a string for use in an LDAP filter or DN
  • 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_batch — Batch and execute modifications on an LDAP entry
  • 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 on the client side
  • ldap_start_tls — Ini?iaza TLS
  • ldap_t61_to_8859 — Transleaza caractere t61 în caractere 8859
  • ldap_unbind — Unbind from LDAP directory
Basic usage
ldap_8859_to_t61
LDAP


Translate 8859 characters to t61 characters

Func?ii LDAP
ldap_add
Func?ii LDAP
PHP Manual

ldap_8859_to_t61

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

ldap_8859_to_t61 — Translate 8859 characters to t61 characters

Descrierea

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.

Parametri

value

The text to be translated.

Valorile întoarse

Return the t61 translation of value.

A se vedea ?i

  • ldap_t61_to_8859() - Transleaza caractere t61 în caractere 8859

Func?ii LDAP
ldap_add
Func?ii LDAP


Add entries to LDAP directory

ldap_8859_to_t61
ldap_bind
Func?ii LDAP
PHP Manual

ldap_add

(PHP 4, PHP 5, PHP 7)

ldap_add — Add entries to LDAP directory

Descrierea

bool ldap_add ( resource $link_identifier , string $dn , array $entry )

Add entries in the LDAP directory.

Parametri

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
$entry["attribute1"] = "value";
$entry["attribute2"][0] = "value1";
$entry["attribute2"][1] = "value2";
?>

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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["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";
}
?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • ldap_delete() - Delete an entry from a directory

ldap_8859_to_t61
ldap_bind
Func?ii LDAP


Bind to LDAP directory

ldap_add
ldap_close
Func?ii LDAP
PHP Manual

ldap_bind

(PHP 4, PHP 5, PHP 7)

ldap_bind — Bind to LDAP directory

Descrierea

bool ldap_bind ( resource $link_identifier [, string $bind_rdn = NULL [, string $bind_password = NULL ]] )

Binds to the LDAP directory with specified RDN and password.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

bind_rdn

bind_password

If bind_password is not specified or is empty, an anonymous bind is attempted. The bind_dn can also be left empty for an anonymous bind. This is defined in https://tools.ietf.org/html/rfc2251#section-4.2.2

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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...";
    }

}

?>

Example #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...";
    }

}

?>

A se vedea ?i

  • ldap_unbind() - Unbind from LDAP directory

ldap_add
ldap_close
Func?ii LDAP


Pseudonim pentru ldap_unbind

ldap_bind
ldap_compare
Func?ii LDAP
PHP Manual

ldap_close

(PHP 4, PHP 5, PHP 7)

ldap_close — Pseudonim pentru ldap_unbind()

Descrierea

Aceasta func?ie este pseudonim pentru: ldap_unbind().

ldap_bind
ldap_compare
Func?ii LDAP


Compare value of attribute found in entry specified with DN

ldap_close
ldap_connect
Func?ii LDAP
PHP Manual

ldap_compare

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

ldap_compare — Compare value of attribute found in entry specified with DN

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE if value matches otherwise returns FALSE. Returns -1 on error.

Exemple

The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry.

Example #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.";
}
?>

Note

Avertizare

ldap_compare() can NOT be used to compare BINARY values!

ldap_close
ldap_connect
Func?ii LDAP


Connect to an LDAP server

ldap_compare
ldap_control_paged_result_response
Func?ii LDAP
PHP Manual

ldap_connect

(PHP 4, PHP 5, PHP 7)

ldap_connect — Connect to an LDAP server

Descrierea

resource ldap_connect ([ string $host = NULL [, int $port = 389 ]] )

Creates an LDAP link identifier and checks whether the given host and port are plausible.

Note: This function does not open a connection. It checks whether the given parameters are plausible and can be used to open a connection as soon as one is needed.

Parametri

host

This field supports using a hostname or, with OpenLDAP 2.x.x and later, a full LDAP URI of the form ldap://hostname:port or ldaps://hostname:port for SSL encryption.

You can also provide multiple LDAP-URIs separated by a space as one string

Note that hostname:port is not a supported LDAP URI as the schema is missing.

port

The port to connect to. Not used when using LDAP URIs.

Valorile întoarse

Returns a positive LDAP link identifier when the provided hostname/port combination or LDAP URI seems plausible. It's a syntactic check of the provided parameters but the server(s) will not be contacted! If the syntactic check fails it returns FALSE. 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.

Exemple

Example #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");

?>

Example #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}");

?>

A se vedea ?i

  • ldap_bind() - Bind to LDAP directory

ldap_compare
ldap_control_paged_result_response
Func?ii LDAP


Retrieve the LDAP pagination cookie

ldap_connect
ldap_control_paged_result
Func?ii LDAP
PHP Manual

ldap_control_paged_result_response

(PHP 5 >= 5.4.0, PHP 7)

ldap_control_paged_result_response — Retrieve the LDAP pagination cookie

Descrierea

bool ldap_control_paged_result_response ( resource $link , resource $result [, string &$cookie [, int &$estimated ]] )

Retrieve the pagination information send by the server.

Parametri

link

An LDAP link identifier, returned by ldap_connect().

result

cookie

An opaque structure sent by the server.

estimated

The estimated number of entries to retrieve.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ldap_control_paged_result() - Send LDAP pagination control
  • » RFC2696 : LDAP Control Extension for Simple Paged Results Manipulation

ldap_connect
ldap_control_paged_result
Func?ii LDAP


Send LDAP pagination control

ldap_control_paged_result_response
ldap_count_entries
Func?ii LDAP
PHP Manual

ldap_control_paged_result

(PHP 5 >= 5.4.0, PHP 7)

ldap_control_paged_result — Send LDAP pagination control

Descrierea

bool ldap_control_paged_result ( resource $link , int $pagesize [, bool $iscritical = false [, string $cookie = "" ]] )

Enable LDAP pagination by sending the pagination control (page size, cookie...).

Parametri

link

An LDAP link identifier, returned by ldap_connect().

pagesize

The number of entries by page.

iscritical

Indicates whether the pagination is critical or not. If true and if the server doesn't support pagination, the search will return no result.

cookie

An opaque structure sent by the server (ldap_control_paged_result_response()).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

The example below show the retrieval of the first page of a search paginated with one entry by page.

Example #1 LDAP pagination

<?php
     // $ds is a valid link identifier (see ldap_connect)
     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

     $dn        = 'ou=example,dc=org';
     $filter    = '(|(sn=Doe*)(givenname=John*))';
     $justthese = array('ou', 'sn', 'givenname', 'mail');

     // enable pagination with a page size of 1.
     ldap_control_paged_result($ds, 1);

     $sr = ldap_search($ds, $dn, $filter, $justthese);

     $info = ldap_get_entries($ds, $sr);

     echo $info['count'] . ' entries returned' . PHP_EOL;

The example below show the retrieval of all the result paginated with 100 entries by page.

Example #2 LDAP pagination

<?php
     // $ds is a valid link identifier (see ldap_connect)
     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

     $dn        = 'ou=example,dc=org';
     $filter    = '(|(sn=Doe*)(givenname=John*))';
     $justthese = array('ou', 'sn', 'givenname', 'mail');

     // enable pagination with a page size of 100.
     $pageSize = 100;

     $cookie = '';
     do {
         ldap_control_paged_result($ds, $pageSize, true, $cookie);

         $result  = ldap_search($ds, $dn, $filter, $justthese);
         $entries = ldap_get_entries($ds, $result);

         foreach ($entries as $e) {
             echo $e['dn'] . PHP_EOL;
         }

         ldap_control_paged_result_response($ds, $result, $cookie);

     } while($cookie !== null && $cookie != '');

Note

Nota:

Pagination control is a LDAPv3 protocol feature.

A se vedea ?i

  • ldap_control_paged_result_response() - Retrieve the LDAP pagination cookie
  • » RFC2696 : LDAP Control Extension for Simple Paged Results Manipulation

ldap_control_paged_result_response
ldap_count_entries
Func?ii LDAP


Count the number of entries in a search

ldap_control_paged_result
ldap_delete
Func?ii LDAP
PHP Manual

ldap_count_entries

(PHP 4, PHP 5, PHP 7)

ldap_count_entries — Count the number of entries in a search

Descrierea

int ldap_count_entries ( resource $link_identifier , resource $result_identifier )

Returns the number of entries stored in the result of previous search operations.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_identifier

The internal LDAP result.

Valorile întoarse

Returns number of entries in the result or FALSE on error.

Exemple

Example #1 ldap-count-entries() example

Retrieve number of entries in the result.

// $ds is a valid link identifier (see ldap_connect)

     $dn        = 'ou=example,dc=org';
     $filter    = '(|(sn=Doe*)(givenname=John*))';
     $justthese = array('ou', 'sn', 'givenname', 'mail');

     $sr = ldap_search($ds, $dn, $filter, $justthese);

     var_dump(ldap_count_entries($ds, $sr));

Exemplul de mai sus va afi?a ceva similar cu:

     int(1)

ldap_control_paged_result
ldap_delete
Func?ii LDAP


Delete an entry from a directory

ldap_count_entries
ldap_dn2ufn
Func?ii LDAP
PHP Manual

ldap_delete

(PHP 4, PHP 5, PHP 7)

ldap_delete — Delete an entry from a directory

Descrierea

bool ldap_delete ( resource $link_identifier , string $dn )

Deletes a particular entry in LDAP directory.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ldap_add() - Add entries to LDAP directory

ldap_count_entries
ldap_dn2ufn
Func?ii LDAP


Convert DN to User Friendly Naming format

ldap_delete
ldap_err2str
Func?ii LDAP
PHP Manual

ldap_dn2ufn

(PHP 4, PHP 5, PHP 7)

ldap_dn2ufn — Convert DN to User Friendly Naming format

Descrierea

string ldap_dn2ufn ( string $dn )

Turns the specified dn, into a more user-friendly form, stripping off type names.

Parametri

dn

The distinguished name of an LDAP entity.

Valorile întoarse

Returns the user friendly name.

ldap_delete
ldap_err2str
Func?ii LDAP


Convert LDAP error number into string error message

ldap_dn2ufn
ldap_errno
Func?ii LDAP
PHP Manual

ldap_err2str

(PHP 4, PHP 5, PHP 7)

ldap_err2str — Convert LDAP error number into string error message

Descrierea

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.

Parametri

errno

The error number.

Valorile întoarse

Returns the error message, as a string.

Exemple

Example #1 Enumerating all LDAP error messages

<?php
  for ($i=0; $i<100; $i++) {
    printf("Error $i: %s<br />\n", ldap_err2str($i));
  }
?>

A se vedea ?i

  • 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
Func?ii LDAP


Return the LDAP error number of the last LDAP command

ldap_err2str
ldap_error
Func?ii LDAP
PHP Manual

ldap_errno

(PHP 4, PHP 5, PHP 7)

ldap_errno — Return the LDAP error number of the last LDAP command

Descrierea

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().

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

Valorile întoarse

Return the LDAP error number of the last LDAP command for this link.

Exemple

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.

Example #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";
?>

A se vedea ?i

  • 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
Func?ii LDAP


Return the LDAP error message of the last LDAP command

ldap_errno
ldap_escape
Func?ii LDAP
PHP Manual

ldap_error

(PHP 4, PHP 5, PHP 7)

ldap_error — Return the LDAP error message of the last LDAP command

Descrierea

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.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

Valorile întoarse

Returns string error message.

A se vedea ?i

  • 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_escape
Func?ii LDAP


Escape a string for use in an LDAP filter or DN

ldap_error
ldap_explode_dn
Func?ii LDAP
PHP Manual

ldap_escape

(PHP 5 >= 5.6.0, PHP 7)

ldap_escape — Escape a string for use in an LDAP filter or DN

Descrierea

string ldap_escape ( string $value [, string $ignore [, int $flags ]] )

Escapes value for use in the context implied by flags.

Parametri

value

The value to escape.

ignore

Characters to ignore when escaping.

flags

The context the escaped string will be used in: LDAP_ESCAPE_FILTER for filters to be used with ldap_search(), or LDAP_ESCAPE_DN for DNs.

Valorile întoarse

Returns the escaped string.

ldap_error
ldap_explode_dn
Func?ii LDAP


Splits DN into its component parts

ldap_escape
ldap_first_attribute
Func?ii LDAP
PHP Manual

ldap_explode_dn

(PHP 4, PHP 5, PHP 7)

ldap_explode_dn — Splits DN into its component parts

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns an array of all DN components, sau FALSE în cazul e?ecului. The first element in the array has count key and represents the number of returned values, next elements are numerically indexed DN components.

ldap_escape
ldap_first_attribute
Func?ii LDAP


Return first attribute

ldap_explode_dn
ldap_first_entry
Func?ii LDAP
PHP Manual

ldap_first_attribute

(PHP 4, PHP 5, PHP 7)

ldap_first_attribute — Return first attribute

Descrierea

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.

Parametri

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.

Nota:

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.

Valorile întoarse

Returns the first attribute in the entry on success and FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
5.2.4 | The ber_identifier was removed. This is now handled automatically by PHP.

A se vedea ?i

  • 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
Func?ii LDAP


Return first result id

ldap_first_attribute
ldap_first_reference
Func?ii LDAP
PHP Manual

ldap_first_entry

(PHP 4, PHP 5, PHP 7)

ldap_first_entry — Return first result id

Descrierea

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.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_identifier

Valorile întoarse

Returns the result entry identifier for the first entry on success and FALSE on error.

A se vedea ?i

  • ldap_get_entries() - Get all result entries

ldap_first_attribute
ldap_first_reference
Func?ii LDAP


Return first reference

ldap_first_entry
ldap_free_result
Func?ii LDAP
PHP Manual

ldap_first_reference

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

ldap_first_reference — Return first reference

Descrierea

resource ldap_first_reference ( resource $link , resource $result )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ldap_first_entry
ldap_free_result
Func?ii LDAP


Free result memory

ldap_first_reference
ldap_get_attributes
Func?ii LDAP
PHP Manual

ldap_free_result

(PHP 4, PHP 5, PHP 7)

ldap_free_result — Free result memory

Descrierea

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.

Parametri

result_identifier

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

ldap_first_reference
ldap_get_attributes
Func?ii LDAP


Get attributes from a search result entry

ldap_free_result
ldap_get_dn
Func?ii LDAP
PHP Manual

ldap_get_attributes

(PHP 4, PHP 5, PHP 7)

ldap_get_attributes — Get attributes from a search result entry

Descrierea

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

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

Valorile întoarse

Returns a complete entry information in a multi-dimensional array on success and FALSE on error.

Exemple

Example #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 />";
}
?>

A se vedea ?i

  • ldap_first_attribute() - Return first attribute
  • ldap_next_attribute() - Get the next attribute in result

ldap_free_result
ldap_get_dn
Func?ii LDAP


Get the DN of a result entry

ldap_get_attributes
ldap_get_entries
Func?ii LDAP
PHP Manual

ldap_get_dn

(PHP 4, PHP 5, PHP 7)

ldap_get_dn — Get the DN of a result entry

Descrierea

string ldap_get_dn ( resource $link_identifier , resource $result_entry_identifier )

Finds out the DN of an entry in the result.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

Valorile întoarse

Returns the DN of the result entry and FALSE on error.

ldap_get_attributes
ldap_get_entries
Func?ii LDAP


Get all result entries

ldap_get_dn
ldap_get_option
Func?ii LDAP
PHP Manual

ldap_get_entries

(PHP 4, PHP 5, PHP 7)

ldap_get_entries — Get all result entries

Descrierea

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.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_identifier

Valorile întoarse

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

A se vedea ?i

  • ldap_first_entry() - Return first result id
  • ldap_next_entry() - Get next result entry

ldap_get_dn
ldap_get_option
Func?ii LDAP


Get the current value for given option

ldap_get_entries
ldap_get_values_len
Func?ii LDAP
PHP Manual

ldap_get_option

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ldap_get_option — Get the current value for given option

Descrierea

bool ldap_get_option ( resource $link_identifier , int $option , mixed &$retval )

Sets retval to the value of the specified option.

Parametri

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
LDAP_OPT_X_KEEPALIVE_IDLE | int
LDAP_OPT_X_KEEPALIVE_PROBES | int
LDAP_OPT_X_KEEPALIVE_INTERVAL | int
LDAP_OPT_X_TLS_CACERTDIR | string
LDAP_OPT_X_TLS_CACERTFILE | string
LDAP_OPT_X_TLS_CERTFILE | string
LDAP_OPT_X_TLS_CIPHER_SUITE | string
LDAP_OPT_X_TLS_CRLCHECK | integer
LDAP_OPT_X_TLS_CRLFILE | string
LDAP_OPT_X_TLS_DHFILE | string
LDAP_OPT_X_TLS_KEYILE | string
LDAP_OPT_X_TLS_PACKAGE | string
LDAP_OPT_X_TLS_PROTOCOL_MIN | integer
LDAP_OPT_X_TLS_RANDOM_FILE | string
LDAP_OPT_X_TLS_REQUIRE_CERT | integer

retval

This will be set to the option value.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
}
?>

Note

Nota:

This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

A se vedea ?i

  • ldap_set_option() - Set the value of the given option

ldap_get_entries
ldap_get_values_len
Func?ii LDAP


Get all binary values from a result entry

ldap_get_option
ldap_get_values
Func?ii LDAP
PHP Manual

ldap_get_values_len

(PHP 4, PHP 5, PHP 7)

ldap_get_values_len — Get all binary values from a result entry

Descrierea

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.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

attribute

Valorile întoarse

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.

A se vedea ?i

  • ldap_get_values() - Get all values from a result entry

ldap_get_option
ldap_get_values
Func?ii LDAP


Get all values from a result entry

ldap_get_values_len
ldap_list
Func?ii LDAP
PHP Manual

ldap_get_values

(PHP 4, PHP 5, PHP 7)

ldap_get_values — Get all values from a result entry

Descrierea

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.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

attribute

Valorile întoarse

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

Exemple

Example #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 />";
}
?>

A se vedea ?i

  • ldap_get_values_len() - Get all binary values from a result entry

ldap_get_values_len
ldap_list
Func?ii LDAP


Single-level search

ldap_get_values
ldap_mod_add
Func?ii LDAP
PHP Manual

ldap_list

(PHP 4, PHP 5, PHP 7)

ldap_list — Single-level search

Descrierea

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.)

Parametri

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.

Nota:

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.

Nota:

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.

Valorile întoarse

Returns a search result identifier or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
4.0.5 | Parallel searches support was added. See ldap_search() for details.

Exemple

Example #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];
}
?>

A se vedea ?i

  • ldap_search() - Search LDAP tree

ldap_get_values
ldap_mod_add
Func?ii LDAP


Add attribute values to current attributes

ldap_list
ldap_mod_del
Func?ii LDAP
PHP Manual

ldap_mod_add

(PHP 4, PHP 5, PHP 7)

ldap_mod_add — Add attribute values to current attributes

Descrierea

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.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • ldap_mod_del() - Delete attribute values from current attributes
  • ldap_mod_replace() - Replace attribute values with new ones

ldap_list
ldap_mod_del
Func?ii LDAP


Delete attribute values from current attributes

ldap_mod_add
ldap_mod_replace
Func?ii LDAP
PHP Manual

ldap_mod_del

(PHP 4, PHP 5, PHP 7)

ldap_mod_del — Delete attribute values from current attributes

Descrierea

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.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ldap_mod_add() - Add attribute values to current attributes
  • ldap_mod_replace() - Replace attribute values with new ones

ldap_mod_add
ldap_mod_replace
Func?ii LDAP


Replace attribute values with new ones

ldap_mod_del
ldap_modify_batch
Func?ii LDAP
PHP Manual

ldap_mod_replace

(PHP 4, PHP 5, PHP 7)

ldap_mod_replace — Replace attribute values with new ones

Descrierea

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.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • ldap_mod_del() - Delete attribute values from current attributes
  • ldap_mod_add() - Add attribute values to current attributes

ldap_mod_del
ldap_modify_batch
Func?ii LDAP


Batch and execute modifications on an LDAP entry

ldap_mod_replace
ldap_modify
Func?ii LDAP
PHP Manual

ldap_modify_batch

(PHP 5.4 >= 5.4.26, PHP 5.5 >= 5.5.10, PHP 5.6 >= 5.6.0, PHP 7)

ldap_modify_batch — Batch and execute modifications on an LDAP entry

Descrierea

bool ldap_modify_batch ( resource $link_identifier , string $dn , array $entry )

Modifies an existing entry in the LDAP directory. Allows detailed specification of the modifications to perform.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

An array that specifies the modifications to make. Each entry in this array is an associative array with two or three keys: attrib maps to the name of the attribute to modify, modtype maps to the type of modification to perform, and (depending on the type of modification) values maps to an array of attribute values relevant to the modification.

Possible values for modtype include:

LDAP_MODIFY_BATCH_ADD

Each value specified through values is added (as an additional value) to the attribute named by attrib.

LDAP_MODIFY_BATCH_REMOVE

Each value specified through values is removed from the attribute named by attrib. Any value of the attribute not contained in the values array will remain untouched.

LDAP_MODIFY_BATCH_REMOVE_ALL

All values are removed from the attribute named by attrib. A values entry must not be provided.

LDAP_MODIFY_BATCH_REPLACE

All current values of the attribute named by attrib are replaced with the values specified through values.

Note that any value for attrib must be a string, any value for values must be an array of strings, and any value for modtype must be one of the LDAP_MODIFY_BATCH_* constants listed above.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Add a telephone number to a contact

<?php
$dn = "cn=John Smith,ou=Wizards,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "telephoneNumber",
        "modtype" => LDAP_MODIFY_BATCH_ADD,
        "values"  => ["+1 555 555 1717"],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);
?>

Example #2 Rename a user

<?php
$dn = "cn=John Smith,ou=Wizards,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "sn",
        "modtype" => LDAP_MODIFY_BATCH_REPLACE,
        "values"  => ["Smith-Jones"],
    ],
    [
        "attrib"  => "givenName",
        "modtype" => LDAP_MODIFY_BATCH_REPLACE,
        "values"  => ["Jack"],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);
ldap_rename($connection, $dn, "cn=Jack Smith-Jones", NULL, TRUE);
?>

Example #3 Add two e-mail addresses to a user

<?php
$dn = "cn=Jack Smith-Jones,ou=Wizards,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "mail",
        "modtype" => LDAP_MODIFY_BATCH_ADD,
        "values"  => [
            "jack.smith@example.com",
            "jack.smith-jones@example.com",
        ],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);
?>

Example #4 Change a user's password

<?php
$dn = "cn=Jack Smith-Jones,ou=Wizards,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "userPassword",
        "modtype" => LDAP_MODIFY_BATCH_REMOVE,
        "values"  => ["Tr0ub4dor&3"],
    ],
    [
        "attrib"  => "userPassword",
        "modtype" => LDAP_MODIFY_BATCH_ADD,
        "values"  => ["correct horse battery staple"],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);
?>

Example #5 Change a user's password (Active Directory)

<?php
function adifyPw($pw)
{
    return iconv("UTF-8", "UTF-16LE", '"' . $pw . '"');
}

$dn = "cn=Jack Smith-Jones,ou=Wizards,dc=ad,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "unicodePwd",
        "modtype" => LDAP_MODIFY_BATCH_REMOVE,
        "values"  => [adifyPw("Tr0ub4dor&3")],
    ],
    [
        "attrib"  => "unicodePwd",
        "modtype" => LDAP_MODIFY_BATCH_ADD,
        "values"  => [adifyPw("correct horse battery staple")],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);

ldap_mod_replace
ldap_modify
Func?ii LDAP


Modify an LDAP entry

ldap_modify_batch
ldap_next_attribute
Func?ii LDAP
PHP Manual

ldap_modify

(PHP 4, PHP 5, PHP 7)

ldap_modify — Modify an LDAP entry

Descrierea

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().

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • ldap_rename() - Modify the name of an entry

ldap_modify_batch
ldap_next_attribute
Func?ii LDAP


Get the next attribute in result

ldap_modify
ldap_next_entry
Func?ii LDAP
PHP Manual

ldap_next_attribute

(PHP 4, PHP 5, PHP 7)

ldap_next_attribute — Get the next attribute in result

Descrierea

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().

Parametri

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.

Nota:

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.

Valorile întoarse

Returns the next attribute in an entry on success and FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
5.2.4 | The ber_identifier was removed. This is now handled automatically by PHP.

A se vedea ?i

  • ldap_get_attributes() - Get attributes from a search result entry

ldap_modify
ldap_next_entry
Func?ii LDAP


Get next result entry

ldap_next_attribute
ldap_next_reference
Func?ii LDAP
PHP Manual

ldap_next_entry

(PHP 4, PHP 5, PHP 7)

ldap_next_entry — Get next result entry

Descrierea

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().

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

Valorile întoarse

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.

A se vedea ?i

  • ldap_get_entries() - Get all result entries

ldap_next_attribute
ldap_next_reference
Func?ii LDAP


Get next reference

ldap_next_entry
ldap_parse_reference
Func?ii LDAP
PHP Manual

ldap_next_reference

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

ldap_next_reference — Get next reference

Descrierea

resource ldap_next_reference ( resource $link , resource $entry )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ldap_next_entry
ldap_parse_reference
Func?ii LDAP


Extract information from reference entry

ldap_next_reference
ldap_parse_result
Func?ii LDAP
PHP Manual

ldap_parse_reference

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

ldap_parse_reference — Extract information from reference entry

Descrierea

bool ldap_parse_reference ( resource $link , resource $entry , array &$referrals )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ldap_next_reference
ldap_parse_result
Func?ii LDAP


Extract information from result

ldap_parse_reference
ldap_read
Func?ii LDAP
PHP Manual

ldap_parse_result

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

ldap_parse_result — Extract information from result

Descrierea

bool ldap_parse_result ( resource $link , resource $result , int &$errcode [, string &$matcheddn [, string &$errmsg [, array &$referrals ]]] )

Parses an LDAP search result.

Parametri

link

An LDAP link identifier, returned by ldap_connect().

result_identifier

An LDAP result resource, returned by ldap_list() or ldap_search().

errcode

A reference to a variable that will be set to the LDAP error code in the result, or 0 if no error occurred.

matcheddn

A reference to a variable that will be set to a matched DN if one was recognised within the request, otherwise it will be set to NULL.

errmsg

A reference to a variable that will be set to the LDAP error message in the result, or an empty string if no error occurred.

referrals

A reference to a variable that will be set to an array set to all of the referral strings in the result, or an empty array if no referrals were returned.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ldap_parse_result() example

<?php
$result = ldap_search($link, "cn=userref,dc=my-domain,dc=com", "(cn=user*)");
$errcode = $dn = $errmsg = $refs =  null;
if (ldap_parse_result($link, $result, $errcode, $dn, $errmsg, $refs)) {
    // do something with $errcode, $dn, $errmsg and $refs
}
?>

ldap_parse_reference
ldap_read
Func?ii LDAP


Read an entry

ldap_parse_result
ldap_rename
Func?ii LDAP
PHP Manual

ldap_read

(PHP 4, PHP 5, PHP 7)

ldap_read — Read an entry

Descrierea

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.

Parametri

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.

Nota:

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.

Nota:

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.

Valorile întoarse

Returns a search result identifier or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
4.0.5 | Parallel searches support was added. See ldap_search() for details.

ldap_parse_result
ldap_rename
Func?ii LDAP


Modify the name of an entry

ldap_read
ldap_sasl_bind
Func?ii LDAP
PHP Manual

ldap_rename

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

ldap_rename — Modify the name of an entry

Descrierea

bool ldap_rename ( resource $link_identifier , string $dn , string $newrdn , string $newparent , bool $deleteoldrdn )

The entry specified by dn is renamed/moved.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

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.

A se vedea ?i

  • ldap_modify() - Modify an LDAP entry

ldap_read
ldap_sasl_bind
Func?ii LDAP


Bind to LDAP directory using SASL

ldap_rename
ldap_search
Func?ii LDAP
PHP Manual

ldap_sasl_bind

(PHP 5, PHP 7)

ldap_sasl_bind — Bind to LDAP directory using SASL

Descrierea

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 ]]]]]]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota: 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.

Istoricul schimbarilor

Versiune | Descriere
5.3.3 | Support on Windows was added.

ldap_rename
ldap_search
Func?ii LDAP


Search LDAP tree

ldap_sasl_bind
ldap_set_option
Func?ii LDAP
PHP Manual

ldap_search

(PHP 4, PHP 5, PHP 7)

ldap_search — Search LDAP tree

Descrierea

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.

Parametri

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 or » RFC4515 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.

Nota:

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.

Nota:

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.

Valorile întoarse

Returns a search result identifier or FALSE on error.

Exemple

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.

Example #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
Func?ii LDAP


Set the value of the given option

ldap_search
ldap_set_rebind_proc
Func?ii LDAP
PHP Manual

ldap_set_option

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ldap_set_option — Set the value of the given option

Descrierea

bool ldap_set_option ( resource $link_identifier , int $option , mixed $newval )

Sets the value of the specified option to be newval.

Parametri

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_DIAGNOSTIC_MESSAGE | string
LDAP_OPT_MATCHED_DN | string
LDAP_OPT_SERVER_CONTROLS | array
LDAP_OPT_CLIENT_CONTROLS | array
LDAP_OPT_X_KEEPALIVE_IDLE | int
LDAP_OPT_X_KEEPALIVE_PROBES | int
LDAP_OPT_X_KEEPALIVE_INTERVAL | int
LDAP_OPT_X_TLS_CACERTDIR | string
LDAP_OPT_X_TLS_CACERTFILE | string
LDAP_OPT_X_TLS_CERTFILE | string
LDAP_OPT_X_TLS_CIPHER_SUITE | string
LDAP_OPT_X_TLS_CRLCHECK | integer
LDAP_OPT_X_TLS_CRLFILE | string
LDAP_OPT_X_TLS_DHFILE | string
LDAP_OPT_X_TLS_KEYILE | string
LDAP_OPT_X_TLS_PROTOCOL_MIN | integer
LDAP_OPT_X_TLS_RANDOM_FILE | string
LDAP_OPT_X_TLS_REQUIRE_CERT | integer | PHP 7.1.0

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
}
?>

Example #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";
}
?>

Note

Nota:

This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

A se vedea ?i

  • ldap_get_option() - Get the current value for given option

ldap_search
ldap_set_rebind_proc
Func?ii LDAP


Set a callback function to do re-binds on referral chasing

ldap_set_option
ldap_sort
Func?ii LDAP
PHP Manual

ldap_set_rebind_proc

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ldap_set_rebind_proc — Set a callback function to do re-binds on referral chasing

Descrierea

bool ldap_set_rebind_proc ( resource $link , callable $callback )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ldap_set_option
ldap_sort
Func?ii LDAP


Sort LDAP result entries on the client side

ldap_set_rebind_proc
ldap_start_tls
Func?ii LDAP
PHP Manual

ldap_sort

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ldap_sort — Sort LDAP result entries on the client side

Descrierea

bool ldap_sort ( resource $link , resource $result , string $sortfilter )

Sort the result of a LDAP search, returned by ldap_search().

As this function sorts the returned values on the client side it is possible that you might not get the expected results in case you reach the sizelimit either of the server or defined within ldap_search().

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 7.0.0. Utilizarea acestei facilita?i este foarte discurajata.

Parametri

link

An LDAP link identifier, returned by ldap_connect().

result

An search result identifier, returned by ldap_search().

sortfilter

The attribute to use as a key in the sort.

Exemple

Sorting the result of a search.

Example #1 LDAP sort

<?php
     // $ds is a valid link identifier (see ldap_connect)

     $dn        = 'ou=example,dc=org';
     $filter    = '(|(sn=Doe*)(givenname=John*))';
     $justthese = array('ou', 'sn', 'givenname', 'mail');

     $sr = ldap_search($ds, $dn, $filter, $justthese);

     // Sort
     ldap_sort($ds, $sr, 'sn');

     // Retrieving the data
     $info = ldap_get_entries($ds, $sr);

ldap_set_rebind_proc
ldap_start_tls
Func?ii LDAP


Ini?iaza TLS

ldap_sort
ldap_t61_to_8859
Func?ii LDAP
PHP Manual

ldap_start_tls

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ldap_start_tls — Ini?iaza TLS

Descrierea

bool ldap_start_tls ( resource $link )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ldap_sort
ldap_t61_to_8859
Func?ii LDAP


Transleaza caractere t61 în caractere 8859

ldap_start_tls
ldap_unbind
Func?ii LDAP
PHP Manual

ldap_t61_to_8859

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

ldap_t61_to_8859 — Transleaza caractere t61 în caractere 8859

Descrierea

string ldap_t61_to_8859 ( string $value )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

ldap_start_tls
ldap_unbind
Func?ii LDAP


Unbind from LDAP directory

ldap_t61_to_8859
Memcache
Func?ii LDAP
PHP Manual

ldap_unbind

(PHP 4, PHP 5, PHP 7)

ldap_unbind — Unbind from LDAP directory

Descrierea

bool ldap_unbind ( resource $link_identifier )

Unbinds from the LDAP directory.

Parametri

link_identifier

An LDAP link identifier, returned by ldap_connect().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ldap_bind() - Bind to LDAP directory

ldap_t61_to_8859
Memcache
Func?ii LDAP


Memcache

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • 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
  • Func?ii Memcache
    • memcache_debug — Turn debug output on/off
ldap_unbind
Introducere
Alte servicii


Introducere

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
Instalarea / configurarea
Memcache


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Memcache


Necesita?i

This module uses functions of » zlib to support on-the-fly data compression. Zlib is required to install this module.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP. Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/memcache.

Nota:

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Memcache Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

There is only one resource type used in memcache module - it's the link identifier for a cache server connection.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

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.
MEMCACHE_USER1 (integer) | Used to turn user-defined application flag on with Memcache::set(), Memcache::add() ?i Memcache::replace().
MEMCACHE_USER2 (integer) | Used to turn user-defined application flag on with Memcache::set(), Memcache::add() ?i Memcache::replace().
MEMCACHE_USER3 (integer) | Used to turn user-defined application flag on with Memcache::set(), Memcache::add() ?i Memcache::replace().
MEMCACHE_USER4 (integer) | Used to turn user-defined application flag on with Memcache::set(), Memcache::add() ?i Memcache::replace().
Tipurile resurselor
Exemple
Memcache


Exemple

Cuprins

  • Basic usage
Constante predefinite
Basic usage
Memcache


Basic usage

Example #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);

?>

Example #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);

?>

Exemple
Memcache
Exemple


The Memcache class

(PECL memcache >= 0.2.0)

Introducere

Represents a connection to a set of memcache servers.

Sinopsisul clasei

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 [, callable $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 [, callable $failure_callback ]]]]] )
}

Cuprins

  • 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

Descrierea

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.

Parametri

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Returns FALSE if such key already exist. For the rest Memcache::add() behaves similarly to Memcache::set().

Exemple

Example #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);

?>

A se vedea ?i

  • 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

Descrierea

bool Memcache::addServer ( string $host [, int $port = 11211 [, bool $persistent [, int $weight [, int $timeout [, int $retry_interval [, bool $status [, callable $failure_callback [, int $timeoutms ]]]]]]]] )

Memcache::addServer() adds a server to the connection pool. 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.

Nota:

This function has been added to Memcache version 2.0.0.

Parametri

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.

Please note: port defaults to memcache.default_port if not specified. For this reason it is wise to specify the port explicitly in this method call.

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

Note

Avertizare

When the port is unspecified, this method defaults to the value set of the PHP ini directive memcache.default_port If this value was changed elsewhere in your application it might lead to unexpected results: for this reason it is wise to always specify the port explicitly in this method call.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

A se vedea ?i

  • 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

Descrierea

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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();

?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

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.

Please note: port defaults to memcache.default_port if not specified. For this reason it is wise to specify the port explicitly in this method call.

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.

Note

Avertizare

When the port is unspecified, this method defaults to the value set of the PHP ini directive memcache.default_port If this value was changed elsewhere in your application it might lead to unexpected results: for this reason it is wise to always specify the port explicitly in this method call.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Memcache::connect() example

<?php

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);

/* OO API */

$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);

?>

A se vedea ?i

  • 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

Descrierea

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 subtracted.

Nota:

New item's value will not be less than zero.

Nota:

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.

Parametri

key

Key of the item do decrement.

value

Decrement the item by value.

Valorile întoarse

Returns item's new value on success sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • 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

Descrierea

bool Memcache::delete ( string $key [, int $timeout = 0 ] )

Memcache::delete() deletes an item with the key.

Parametri

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.

Istoricul schimbarilor

Versiune | Descriere
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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');

?>

A se vedea ?i

  • 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

Descrierea

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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

Descrierea

string Memcache::get ( string $key [, int &$flags ] )
array Memcache::get ( array $keys [, array &$flags ] )

Memcache::get() returns previously stored data of an item, if 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.

Parametri

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).

Valorile întoarse

Returns the value associated with the key or an array of found key-value pairs when key is an array. Returns FALSE on failure, key is not found or key is an empty array.

Exemple

Example #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

Descrierea

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.

Nota:

This function has been added to Memcache version 2.0.0.

Parametri

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.

Avertizare

The cachedump stat type has been removed from the memcached daemon due to security reasons.

Valorile întoarse

Returns a two-dimensional associative array of server statistics or FALSE on failure.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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
)

A se vedea ?i

  • 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

Descrierea

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.

Nota:

This function has been added to Memcache version 2.1.0.

Parametri

host

Point to the host where memcached is listening for connections.

port

Point to the port where memcached is listening for connections.

Valorile întoarse

Returns a the servers status. 0 if server is failed, non-zero otherwise

Exemple

Example #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);

?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns an associative array of server statistics sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

string Memcache::getVersion ( void )

Memcache::getVersion() returns a string with server's version number. Also you can use memcache_get_version() function.

Valorile întoarse

Returns a string of server version number sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

A se vedea ?i

  • 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

Descrierea

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.

Nota:

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.

Parametri

key

Key of the item to increment.

value

Increment the item by value.

Valorile întoarse

Returns new items value on success sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a Memcache object sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

A se vedea ?i

  • 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

Descrierea

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).

Nota:

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.

Parametri

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).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');

?>

Example #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');

?>

A se vedea ?i

  • 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

Descrierea

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.

Nota:

This function has been added to Memcache version 2.0.0.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii Memcache
Memcache
PHP Manual

Memcache::setServerParams

(PECL memcache >= 2.1.0)

Memcache::setServerParams — Changes server parameters and status at runtime

Descrierea

bool Memcache::setServerParams ( string $host [, int $port = 11211 [, int $timeout [, int $retry_interval = false [, bool $status [, callable $failure_callback ]]]]] )

Memcache::setServerParams() changes server parameters at runtime. You can also use the memcache_set_server_params() function.

Nota:

This function has been added to Memcache version 2.1.0.

Parametri

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 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');

?>

A se vedea ?i

  • Memcache::addServer() - Add a memcached server to connection pool
  • Memcache::getServerStatus() - Returns server status

Memcache::setCompressThreshold
Func?ii Memcache
Memcache


Func?ii Memcache

Cuprins

  • memcache_debug — Turn debug output on/off
Memcache::setServerParams
memcache_debug
Memcache


Turn debug output on/off

Func?ii Memcache
Memcached
Func?ii Memcache
PHP Manual

memcache_debug

(PECL memcache >= 0.2.0)

memcache_debug — Turn debug output on/off

Descrierea

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.

Nota:

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.

Parametri

on_off

Turns debug output on if equals to TRUE. Turns debug output off if equals to FALSE.

Valorile întoarse

Returns TRUE if PHP was built with --enable-debug option, otherwise returns FALSE.

Func?ii Memcache
Memcached
Func?ii Memcache


Memcached

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • 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::decrementByKey — Decrement numeric item's value, stored on a specific server
    • Memcached::delete — Delete an item
    • Memcached::deleteByKey — Delete an item from a specific server
    • Memcached::deleteMulti — Delete multiple items
    • Memcached::deleteMultiByKey — Delete multiple items 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::getAllKeys — Gets the keys stored on all the servers
    • 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::incrementByKey — Increment numeric item's value, stored on a specific server
    • Memcached::isPersistent — Check if a persitent connection to memcache is being used
    • Memcached::isPristine — Check if the instance was recently created
    • Memcached::prepend — Prepend data to an existing item
    • Memcached::prependByKey — Prepend data to an existing item on a specific server
    • Memcached::quit — Close any open connections
    • Memcached::replace — Replace the item under an existing key
    • Memcached::replaceByKey — Replace the item under an existing key on a specific server
    • Memcached::resetServerList — Clears all servers from the server list
    • 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::setOptions — Set Memcached options
    • Memcached::setSaslAuthData — Set the credentials to use for authentication
    • Memcached::touch — Set a new expiration on an item
    • Memcached::touchByKey — Set a new expiration on an item on a specific server
  • MemcachedException — The MemcachedException class
memcache_debug
Introducere
Alte servicii


Introducere

» 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 the libmemcached library to provide an 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
Instalarea / configurarea
Memcached


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Memcached


Necesita?i

This extension requires » libmemcached client library (version 1.0.0 or greater). For SASL authentication support, libmemcached must be built with SASL enabled.

Since version 0.2.0, this extension requires PHP version 5.2.0 or higher.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » 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.

SASL authentication support is disabled by default. To enable it, use --enable-memcached-sasl switch. This requires that libsasl2 has been installed and that libmemcached has been built with SASL support enabled.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Memcached Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
memcached.sess_locking | 1 | PHP_INI_ALL |
memcached.sess_consistent_hash | 0 | PHP_INI_ALL |
memcached.sess_binary | 0 | PHP_INI_ALL |
memcached.sess_lock_wait | 150000 | PHP_INI_ALL |
memcached.sess_prefix | memc.sess.key. | PHP_INI_ALL |
memcached.sess_number_of_replicas | 0 | PHP_INI_ALL |
memcached.sess_randomize_replica_read | 0 | PHP_INI_ALL |
memcached.sess_remove_failed | 0 | PHP_INI_ALL |
memcached.compression_type | fastlz | PHP_INI_ALL |
memcached.compression_factor | 1.3 | PHP_INI_ALL |
memcached.compression_threshold | 2000 | PHP_INI_ALL |
memcached.serializer | php | PHP_INI_ALL |
memcached.use_sasl | 0 | PHP_INI_SYSTEM |

Iata o explica?ie pe scurt a directivelor de configurare.

memcached.sess_locking integer

Use session locking. Valid values: On, Off, the default is On.

memcached.sess_consistent_hash integer

Memcached session consistent hash mode. If set to On, consistent hashing is used for session handling. When consistent hashing is used, one can add or remove cache node(s) without messing up too much with existing keys. The default is Off.

memcached.sess_binary integer

Use memcached session binary mode. Libmemcached replicas only work if binary mode is enabled. The default is Off.

memcached.sess_lock_wait integer

Session spin lock retry wait time in microseconds. Be carefull when setting this value. Valid values are integers, where 0 is interpreted as the default value. Negative values result in a reduces locking to a try lock. The default is 150000.

memcached.sess_prefix string

Memcached session key prefix. Valid values are strings less than 219 bytes long. The default value is "memc.sess.key."

memcached.sess_number_of_replicas integer

The memcached session number of replicas.

memcached.sess_randomize_replica_read integer

Memcached session replica read randomize.

memcached.sess_remove_failed integer

Allow failed memcached server to automatically be removed.

memcached.compression_type string

Set the compression type, valid values are: fastlz, zlib. The default is fastlz.

memcached.compression_factor float

Compression factor. Store compressed value only if the compression factor (saving) exceeds the set limit. Store compressed if: plain_len > comp_len * factor. The default value is 1.3 (23% space saving).

memcached.compression_threshold integer

The compression threshold. Do not compress serialized values below this threshold. The default is 2000 bytes.

memcached.serializer string

Set the default serializer for new memcached objects. Valid values are: php, igbinary, json, json_array.

json

Standard php JSON encoding. This serializer is fast and compact but only works on UTF-8 encoded data and does not fully implement serializing. See the JSON extension.

json_array

As json, but decodes into arrays.

php

The standard PHP serializer.

igbinary

A binary serializer

The default is igbinary if available and php otherwise.

memcached.use_sasl integer

Use SASL authentication for connections. Valid values: On, Off. The default is Off.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.

Nota:

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.

Tipurile resurselor
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).

Constante predefinite
Callbacks
Memcached


Callbacks

Cuprins

  • 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.

Example #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);
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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.

Example #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

(PECL memcached >= 0.1.0)

Introducere

Represents a connection to a set of memcached servers.

Sinopsisul clasei

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 [, int $initial_value = 0 [, int $expiry = 0 ]]] )
public int decrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )
public bool delete ( string $key [, int $time = 0 ] )
public bool deleteByKey ( string $server_key , string $key [, int $time = 0 ] )
public array deleteMulti ( array $keys [, int $time = 0 ] )
public bool deleteMultiByKey ( string $server_key , array $keys [, int $time = 0 ] )
public array fetch ( void )
public array fetchAll ( void )
public bool flush ([ int $delay = 0 ] )
public mixed get ( string $key [, callable $cache_cb [, float &$cas_token ]] )
public array getAllKeys ( void )
public mixed getByKey ( string $server_key , string $key [, callable $cache_cb [, float &$cas_token ]] )
public bool getDelayed ( array $keys [, bool $with_cas [, callable $value_cb ]] )
public bool getDelayedByKey ( string $server_key , array $keys [, bool $with_cas [, callable $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 [, int $initial_value = 0 [, int $expiry = 0 ]]] )
public int incrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )
public bool isPersistent ( void )
public bool isPristine ( void )
public bool prepend ( string $key , string $value )
public bool prependByKey ( string $server_key , string $key , string $value )
public bool quit ( void )
public bool replace ( string $key , mixed $value [, int $expiration ] )
public bool replaceByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )
public bool resetServerList ( void )
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 )
public bool setOptions ( array $options )
public void setSaslAuthData ( string $username , string $password )
public bool touch ( string $key , int $expiration )
public bool touchByKey ( string $server_key , string $key , int $expiration )
}

Cuprins

  • 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::decrementByKey — Decrement numeric item's value, stored on a specific server
  • Memcached::delete — Delete an item
  • Memcached::deleteByKey — Delete an item from a specific server
  • Memcached::deleteMulti — Delete multiple items
  • Memcached::deleteMultiByKey — Delete multiple items 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::getAllKeys — Gets the keys stored on all the servers
  • 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::incrementByKey — Increment numeric item's value, stored on a specific server
  • Memcached::isPersistent — Check if a persitent connection to memcache is being used
  • Memcached::isPristine — Check if the instance was recently created
  • Memcached::prepend — Prepend data to an existing item
  • Memcached::prependByKey — Prepend data to an existing item on a specific server
  • Memcached::quit — Close any open connections
  • Memcached::replace — Replace the item under an existing key
  • Memcached::replaceByKey — Replace the item under an existing key on a specific server
  • Memcached::resetServerList — Clears all servers from the server list
  • 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::setOptions — Set Memcached options
  • Memcached::setSaslAuthData — Set the credentials to use for authentication
  • Memcached::touch — Set a new expiration on an item
  • Memcached::touchByKey — Set a new expiration on an item on a specific server
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

Descrierea

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.

Parametri

key

Cheia sub care se stocheaza valoarea.

value

Valoarea pentru a fi stocata.

expiration

Timpul expirarii, implicit este 0. Accesa?i Timpurile de expirare pentru informa?ii suplimentare.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key already exists.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

key

Cheia sub care se stocheaza valoarea.

value

Valoarea pentru a fi stocata.

expiration

Timpul expirarii, implicit este 0. Accesa?i Timpurile de expirare pentru informa?ii suplimentare.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key already exists.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

host

The hostname of the memcache server. If the hostname is invalid, data-related operations will set Memcached::RES_HOST_LOOKUP_FAILURE result code. As of version 2.0.0b1, this parameter may also specify the path of a unix socket filepath ex. /path/to/memcached.sock to use UNIX domain sockets, in this case port must also be set to 0.

port

The port on which memcache is running. Usually, this is 11211. As of version 2.0.0b1, set this parameter to 0 when using UNIX domain sockets.

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • Memcached::addServers() - Add multiple servers to the server pool
  • Memcached::resetServerList() - Clears all servers from the server list

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

Descrierea

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.

Parametri

array

Array of the servers to add to the pool.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • Memcached::addServer() - Add a server to the server pool
  • Memcached::resetServerList() - Clears all servers from the server list

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

Descrierea

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.

Nota:

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.

Parametri

key

Cheia sub care se stocheaza valoarea.

value

The string to append.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

Exemple

Example #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'));
?>

Exemplul de mai sus va afi?a:

string(6) "abcdef"

A se vedea ?i

  • 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

Descrierea

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.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

key

Cheia sub care se stocheaza valoarea.

value

The string to append.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

cas_token

Unique value associated with the existing item. Generated by memcache.

key

Cheia sub care se stocheaza valoarea.

value

Valoarea pentru a fi stocata.

expiration

Timpul expirarii, implicit este 0. Accesa?i Timpurile de expirare pentru informa?ii suplimentare.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. 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.

Exemple

Example #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);

?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

cas_token

Unique value associated with the existing item. Generated by memcache.

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

key

Cheia sub care se stocheaza valoarea.

value

Valoarea pentru a fi stocata.

expiration

Timpul expirarii, implicit este 0. Accesa?i Timpurile de expirare pentru informa?ii suplimentare.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. 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.

A se vedea ?i

  • 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

Descrierea

public Memcached::__construct ([ string $persistent_id ] )

Creates a Memcached instance representing the connection to the memcache servers.

Parametri

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.

Valorile întoarse

A Memcached object.

Exemple

Example #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::decrementByKey
Memcached
PHP Manual

Memcached::decrement

(PECL memcached >= 0.1.0)

Memcached::decrement — Decrement numeric item's value

Descrierea

public int Memcached::decrement ( string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )

Memcached::decrement() decrements a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. If the operation would decrease the value below 0, the new value will be 0. Memcached::decrement() will set the item to the initial_value parameter if the key doesn't exist.

Parametri

key

The key of the item to decrement.

offset

The amount by which to decrement the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

Valorile întoarse

Returns item's new value on success sau FALSE în cazul e?ecului.

Exemple

Example #1 Memcached::decrement() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('counter', 5);
$n = $m->decrement('counter');
var_dump($n);

$n = $m->decrement('counter', 10);
var_dump($n);

var_dump($m->get('counter'));

$m->set('counter', 'abc');
$n = $m->increment('counter');
// ^ will fail due to item value not being numeric
var_dump($n);
?>

Exemplul de mai sus va afi?a:

int(4)
int(0)
int(0)
bool(false)

A se vedea ?i

  • Memcached::increment() - Increment numeric item's value
  • Memcached::incrementByKey() - Increment numeric item's value, stored on a specific server
  • Memcached::decrementByKey() - Decrement numeric item's value, stored on a specific server

Memcached::__construct
Memcached::decrementByKey
Memcached


Decrement numeric item's value, stored on a specific server

Memcached::decrement
Memcached::delete
Memcached
PHP Manual

Memcached::decrementByKey

(PECL memcached >= 2.0.0)

Memcached::decrementByKey — Decrement numeric item's value, stored on a specific server

Descrierea

public int Memcached::decrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )

Memcached::decrementByKey() decrements a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. If the operation would decrease the value below 0, the new value will be 0. Memcached::decrementByKey() will set the item to the initial_value parameter if the key doesn't exist.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

key

The key of the item to decrement.

offset

The amount by which to decrement the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

Valorile întoarse

Returns item's new value on success sau FALSE în cazul e?ecului.

A se vedea ?i

  • Memcached::decrement() - Decrement numeric item's value
  • Memcached::increment() - Increment numeric item's value
  • Memcached::incrementByKey() - Increment numeric item's value, stored on a specific server

Memcached::decrement
Memcached::delete
Memcached


Delete an item

Memcached::decrementByKey
Memcached::deleteByKey
Memcached
PHP Manual

Memcached::delete

(PECL memcached >= 0.1.0)

Memcached::delete — Delete an item

Descrierea

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).

Parametri

key

The key to be deleted.

time

The amount of time the server will wait to delete the item.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Exemple

Example #1 Memcached::delete() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->delete('key1');
?>

A se vedea ?i

  • Memcached::deleteByKey() - Delete an item from a specific server
  • Memcached::deleteMulti() - Delete multiple items

Memcached::decrementByKey
Memcached::deleteByKey
Memcached


Delete an item from a specific server

Memcached::delete
Memcached::deleteMulti
Memcached
PHP Manual

Memcached::deleteByKey

(PECL memcached >= 0.1.0)

Memcached::deleteByKey — Delete an item from a specific server

Descrierea

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.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

key

The key to be deleted.

time

The amount of time the server will wait to delete the item.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

A se vedea ?i

  • Memcached::delete() - Delete an item
  • Memcached::deleteMulti() - Delete multiple items
  • Memcached::deleteMultiByKey() - Delete multiple items from a specific server

Memcached::delete
Memcached::deleteMulti
Memcached


Delete multiple items

Memcached::deleteByKey
Memcached::deleteMultiByKey
Memcached
PHP Manual

Memcached::deleteMulti

(PECL memcached >= 2.0.0)

Memcached::deleteMulti — Delete multiple items

Descrierea

public array Memcached::deleteMulti ( array $keys [, int $time = 0 ] )

Memcached::deleteMulti() deletes the array of keys 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 these keys. For this amount of time, the item is put into a delete queue, which means that it won't be possible to retrieve it by the get command, but add and replace command with these keys 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 these keys will succeed).

Parametri

keys

The keys to be deleted.

time

The amount of time the server will wait to delete the items.

Valorile întoarse

Returns array indexed by keys and where values are indicating whether operation succeeded or not. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

A se vedea ?i

  • Memcached::delete() - Delete an item
  • Memcached::deleteByKey() - Delete an item from a specific server
  • Memcached::deleteMultiByKey() - Delete multiple items from a specific server

Memcached::deleteByKey
Memcached::deleteMultiByKey
Memcached


Delete multiple items from a specific server

Memcached::deleteMulti
Memcached::fetch
Memcached
PHP Manual

Memcached::deleteMultiByKey

(PECL memcached >= 2.0.0)

Memcached::deleteMultiByKey — Delete multiple items from a specific server

Descrierea

public bool Memcached::deleteMultiByKey ( string $server_key , array $keys [, int $time = 0 ] )

Memcached::deleteMultiByKey() is functionally equivalent to Memcached::deleteMulti(), except that the free-form server_key can be used to map the keys to a specific server.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

keys

The keys to be deleted.

time

The amount of time the server will wait to delete the items.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

A se vedea ?i

  • Memcached::delete() - Delete an item
  • Memcached::deleteByKey() - Delete an item from a specific server
  • Memcached::deleteMulti() - Delete multiple items

Memcached::deleteMulti
Memcached::fetch
Memcached


Fetch the next result

Memcached::deleteMultiByKey
Memcached::fetchAll
Memcached
PHP Manual

Memcached::fetch

(PECL memcached >= 0.1.0)

Memcached::fetch — Fetch the next result

Descrierea

public array Memcached::fetch ( void )

Memcached::fetch() retrieves the next result from the last request.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the next result or FALSE otherwise. The Memcached::getResultCode() will return Memcached::RES_END if result set is exhausted.

Exemple

Example #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);
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)
}

A se vedea ?i

  • Memcached::fetchAll() - Fetch all the remaining results
  • Memcached::getDelayed() - Request multiple items

Memcached::deleteMultiByKey
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

Descrierea

public array Memcached::fetchAll ( void )

Memcached::fetchAll() retrieves all the remaining results from the last request.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the results sau FALSE în cazul e?ecului. Utiliza?i Memcached::getResultCode() daca e necesar.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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)
  }
}

A se vedea ?i

  • 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

Descrierea

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.

Parametri

delay

Number of seconds to wait before invalidating the items.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Utiliza?i Memcached::getResultCode() daca e necesar.

Exemple

Example #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::getAllKeys
Memcached
PHP Manual

Memcached::get

(PECL memcached >= 0.1.0)

Memcached::get — Retrieve an item

Descrierea

public mixed Memcached::get ( string $key [, callable $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.

Parametri

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.

Valorile întoarse

Returns the value stored in the cache or FALSE otherwise. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Exemple

Example #1 Memcached::get() example #1

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('foo', 100);
var_dump($m->get('foo'));
?>

Exemplul de mai sus va afi?a:

int(100)

Example #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 */
        /* ...       */
    }
}
?>

A se vedea ?i

  • Memcached::getByKey() - Retrieve an item from a specific server
  • Memcached::getMulti() - Retrieve multiple items
  • Memcached::getDelayed() - Request multiple items

Memcached::flush
Memcached::getAllKeys
Memcached


Gets the keys stored on all the servers

Memcached::get
Memcached::getByKey
Memcached
PHP Manual

Memcached::getAllKeys

(PECL memcached >= 2.0.0)

Memcached::getAllKeys — Gets the keys stored on all the servers

Descrierea

public array Memcached::getAllKeys ( void )

Memcached::getAllKeys() queries each memcache server and retrieves an array of all keys stored on them at that point in time. This is not an atomic operation, so it isn't a truly consistent snapshot of the keys at point in time. As memcache doesn't guarantee to return all keys you also cannot assume that all keys have been returned.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the keys stored on all the servers on success sau FALSE în cazul e?ecului.

Memcached::get
Memcached::getByKey
Memcached


Retrieve an item from a specific server

Memcached::getAllKeys
Memcached::getDelayed
Memcached
PHP Manual

Memcached::getByKey

(PECL memcached >= 0.1.0)

Memcached::getByKey — Retrieve an item from a specific server

Descrierea

public mixed Memcached::getByKey ( string $server_key , string $key [, callable $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.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

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.

Valorile întoarse

Returns the value stored in the cache or FALSE otherwise. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

A se vedea ?i

  • Memcached::get() - Retrieve an item
  • Memcached::getMulti() - Retrieve multiple items
  • Memcached::getDelayed() - Request multiple items

Memcached::getAllKeys
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

Descrierea

public bool Memcached::getDelayed ( array $keys [, bool $with_cas [, callable $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.

Parametri

keys

Array of keys to request.

with_cas

Whether to request CAS token values also.

value_cb

The result callback or NULL.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Utiliza?i Memcached::getResultCode() daca e necesar.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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)
  }
}

A se vedea ?i

  • 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

Descrierea

public bool Memcached::getDelayedByKey ( string $server_key , array $keys [, bool $with_cas [, callable $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.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

keys

Array of keys to request.

with_cas

Whether to request CAS token values also.

value_cb

The result callback or NULL.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Utiliza?i Memcached::getResultCode() daca e necesar.

A se vedea ?i

  • 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

Descrierea

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.

Nota:

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.

Parametri

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.

Valorile întoarse

Returns the array of found items sau FALSE în cazul e?ecului. Utiliza?i Memcached::getResultCode() daca e necesar.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  ["key1"]=>
  string(6) "value1"
  ["key3"]=>
  string(6) "value3"
}
array(2) {
  ["key1"]=>
  float(2360)
  ["key3"]=>
  float(2362)
}

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

foo foo-data
bar bar-data
baz baz-data
lol lol-data
kek kek-data
zoo

A se vedea ?i

  • 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

Descrierea

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.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

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.

Valorile întoarse

Returns the array of found items sau FALSE în cazul e?ecului. Utiliza?i Memcached::getResultCode() daca e necesar.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

option

One of the Memcached::OPT_* constants.

Valorile întoarse

Returns the value of the requested option, or FALSE on error.

Exemple

Example #1 Retrieving Memcached options

<?php
$m = new Memcached();
var_dump($m->getOption(Memcached::OPT_COMPRESSION));
var_dump($m->getOption(Memcached::OPT_POLL_TIMEOUT));
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
int(1000)

A se vedea ?i

  • Memcached::getOption()
  • 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

Descrierea

public int Memcached::getResultCode ( void )

Memcached::getResultCode() returns one of the Memcached::RES_* constants that is the result of the last executed Memcached method.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Result code of the last Memcached operation.

Exemple

Example #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

Descrierea

public string Memcached::getResultMessage ( void )

Memcached::getResultMessage() returns a string that describes the result code of the last executed Memcached method.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Message describing the result of the last Memcached operation.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

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

Descrierea

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.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

Valorile întoarse

Returns an array containing three keys of host, port, and weight on success or FALSE on failure. Utiliza?i Memcached::getResultCode() daca e necesar.

Exemple

Example #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'));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

public array Memcached::getServerList ( void )

Memcached::getServerList() returns the list of all servers that are in its server pool.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The list of all servers in the server pool.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Array of server statistics, one entry per server.

Exemple

Example #1 Memcached::getStats() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

print_r($m->getStats());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

public array Memcached::getVersion ( void )

Memcached::getVersion() returns an array containing the version info for all available memcache servers.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Array of server versions, one entry per server.

Exemple

Example #1 Memcached::getVersion() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

print_r($m->getVersion());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [localhost:11211] => 1.2.6
)

Memcached::getStats
Memcached::increment
Memcached


Increment numeric item's value

Memcached::getVersion
Memcached::incrementByKey
Memcached
PHP Manual

Memcached::increment

(PECL memcached >= 0.1.0)

Memcached::increment — Increment numeric item's value

Descrierea

public int Memcached::increment ( string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )

Memcached::increment() increments a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. Memcached::increment() will set the item to the initial_value parameter if the key doesn't exist.

Parametri

key

The key of the item to increment.

offset

The amount by which to increment the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

Valorile întoarse

Returns new item's value on success sau FALSE în cazul e?ecului.

Exemple

Example #1 Memcached::increment() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('counter', 0);
$m->increment('counter');
$n = $m->increment('counter', 10);
var_dump($n);

$m->set('counter', 'abc');
$n = $m->increment('counter');
// ^ will fail due to item value not being numeric
var_dump($n);
?>

Exemplul de mai sus va afi?a:

int(11)
bool(false)

A se vedea ?i

  • Memcached::decrement() - Decrement numeric item's value
  • Memcached::decrementByKey() - Decrement numeric item's value, stored on a specific server
  • Memcached::incrementByKey() - Increment numeric item's value, stored on a specific server

Memcached::getVersion
Memcached::incrementByKey
Memcached


Increment numeric item's value, stored on a specific server

Memcached::increment
Memcached::isPersistent
Memcached
PHP Manual

Memcached::incrementByKey

(PECL memcached >= 2.0.0)

Memcached::incrementByKey — Increment numeric item's value, stored on a specific server

Descrierea

public int Memcached::incrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )

Memcached::incrementByKey() increments a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. Memcached::incrementByKey() will set the item to the initial_value parameter if the key doesn't exist.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

key

The key of the item to increment.

offset

The amount by which to increment the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

Valorile întoarse

Returns new item's value on success sau FALSE în cazul e?ecului.

A se vedea ?i

  • Memcached::decrement() - Decrement numeric item's value
  • Memcached::decrementByKey() - Decrement numeric item's value, stored on a specific server
  • Memcached::increment() - Increment numeric item's value

Memcached::increment
Memcached::isPersistent
Memcached


Check if a persitent connection to memcache is being used

Memcached::incrementByKey
Memcached::isPristine
Memcached
PHP Manual

Memcached::isPersistent

(PECL memcached >= 2.0.0)

Memcached::isPersistent — Check if a persitent connection to memcache is being used

Descrierea

public bool Memcached::isPersistent ( void )

Memcached::isPersistent() checks if the connections to the memcache servers are persistent connections.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns true if Memcache instance uses a persistent connection, false otherwise.

A se vedea ?i

  • Memcached::isPristine() - Check if the instance was recently created

Memcached::incrementByKey
Memcached::isPristine
Memcached


Check if the instance was recently created

Memcached::isPersistent
Memcached::prepend
Memcached
PHP Manual

Memcached::isPristine

(PECL memcached >= 2.0.0)

Memcached::isPristine — Check if the instance was recently created

Descrierea

public bool Memcached::isPristine ( void )

Memcached::isPristine() checks if the Memcache instance was recently created.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the true if instance is recently created, false otherwise.

A se vedea ?i

  • Memcached::isPersistent() - Check if a persitent connection to memcache is being used

Memcached::isPersistent
Memcached::prepend
Memcached


Prepend data to an existing item

Memcached::isPristine
Memcached::prependByKey
Memcached
PHP Manual

Memcached::prepend

(PECL memcached >= 0.1.0)

Memcached::prepend — Prepend data to an existing item

Descrierea

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.

Nota:

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.

Parametri

key

The key of the item to prepend the data to.

value

The string to prepend.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

Exemple

Example #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'));
?>

Exemplul de mai sus va afi?a:

string(6) "defabc"

A se vedea ?i

  • Memcached::prependByKey() - Prepend data to an existing item on a specific server
  • Memcached::append() - Append data to an existing item

Memcached::isPristine
Memcached::prependByKey
Memcached


Prepend data to an existing item on a specific server

Memcached::prepend
Memcached::quit
Memcached
PHP Manual

Memcached::prependByKey

(PECL memcached >= 0.1.0)

Memcached::prependByKey — Prepend data to an existing item on a specific server

Descrierea

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.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

key

The key of the item to prepend the data to.

value

The string to prepend.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

A se vedea ?i

  • Memcached::prepend() - Prepend data to an existing item
  • Memcached::append() - Append data to an existing item

Memcached::prepend
Memcached::quit
Memcached


Close any open connections

Memcached::prependByKey
Memcached::replace
Memcached
PHP Manual

Memcached::quit

(PECL memcached >= 2.0.0)

Memcached::quit — Close any open connections

Descrierea

public bool Memcached::quit ( void )

Memcached::quit() closes any open connections to the memcache servers.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Memcached::prependByKey
Memcached::replace
Memcached


Replace the item under an existing key

Memcached::quit
Memcached::replaceByKey
Memcached
PHP Manual

Memcached::replace

(PECL memcached >= 0.1.0)

Memcached::replace — Replace the item under an existing key

Descrierea

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.

Parametri

key

Cheia sub care se stocheaza valoarea.

value

Valoarea pentru a fi stocata.

expiration

Timpul expirarii, implicit este 0. Accesa?i Timpurile de expirare pentru informa?ii suplimentare.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

A se vedea ?i

  • 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::quit
Memcached::replaceByKey
Memcached


Replace the item under an existing key on a specific server

Memcached::replace
Memcached::resetServerList
Memcached
PHP Manual

Memcached::replaceByKey

(PECL memcached >= 0.1.0)

Memcached::replaceByKey — Replace the item under an existing key on a specific server

Descrierea

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.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

key

Cheia sub care se stocheaza valoarea.

value

Valoarea pentru a fi stocata.

expiration

Timpul expirarii, implicit este 0. Accesa?i Timpurile de expirare pentru informa?ii suplimentare.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

A se vedea ?i

  • 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::resetServerList
Memcached


Clears all servers from the server list

Memcached::replaceByKey
Memcached::set
Memcached
PHP Manual

Memcached::resetServerList

(PECL memcached >= 2.0.0)

Memcached::resetServerList — Clears all servers from the server list

Descrierea

public bool Memcached::resetServerList ( void )

Memcached::resetserverlist() removes all memcache servers from the known server list, reseting it back to empty.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • Memcached::addServer() - Add a server to the server pool
  • Memcached::addServers() - Add multiple servers to the server pool

Memcached::replaceByKey
Memcached::set
Memcached


Store an item

Memcached::resetServerList
Memcached::setByKey
Memcached
PHP Manual

Memcached::set

(PECL memcached >= 0.1.0)

Memcached::set — Store an item

Descrierea

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.

Parametri

key

Cheia sub care se stocheaza valoarea.

value

Valoarea pentru a fi stocata.

expiration

Timpul expirarii, implicit este 0. Accesa?i Timpurile de expirare pentru informa?ii suplimentare.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Utiliza?i Memcached::getResultCode() daca e necesar.

Exemple

Example #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'));
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(99)
string(15) "a simple string"
array(2) {
  [0]=>
  int(11)
  [1]=>
  int(12)
}
object(stdClass)#1 (0) {
}

A se vedea ?i

  • 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::resetServerList
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

Descrierea

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.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

key

Cheia sub care se stocheaza valoarea.

value

Valoarea pentru a fi stocata.

expiration

Timpul expirarii, implicit este 0. Accesa?i Timpurile de expirare pentru informa?ii suplimentare.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Utiliza?i Memcached::getResultCode() daca e necesar.

Exemple

Example #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);
?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

items

Un tablou cu perechi de chei/valori pentru a fi stocate pe server.

expiration

Timpul expirarii, implicit este 0. Accesa?i Timpurile de expirare pentru informa?ii suplimentare.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Utiliza?i Memcached::getResultCode() daca e necesar.

Exemple

Example #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);
?>

A se vedea ?i

  • 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

Descrierea

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.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

items

Un tablou cu perechi de chei/valori pentru a fi stocate pe server.

expiration

Timpul expirarii, implicit este 0. Accesa?i Timpurile de expirare pentru informa?ii suplimentare.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Utiliza?i Memcached::getResultCode() daca e necesar.

A se vedea ?i

  • Memcached::setMulti() - Store multiple items
  • Memcached::set() - Store an item

Memcached::setMulti
Memcached::setOption
Memcached


Set a Memcached option

Memcached::setMultiByKey
Memcached::setOptions
Memcached
PHP Manual

Memcached::setOption

(PECL memcached >= 0.1.0)

Memcached::setOption — Set a Memcached option

Descrierea

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

bool(true)
Prefix key is now: widgets

A se vedea ?i

  • Memcached::getOption() - Retrieve a Memcached option value
  • Memcached::setOptions() - Set Memcached options
  • Memcached Constants

Memcached::setMultiByKey
Memcached::setOptions
Memcached


Set Memcached options

Memcached::setOption
Memcached::setSaslAuthData
Memcached
PHP Manual

Memcached::setOptions

(PECL memcached >= 2.0.0)

Memcached::setOptions — Set Memcached options

Descrierea

public bool Memcached::setOptions ( array $options )

Memcached::setOptions() is a variation of the Memcached::setOption() that takes an array of options to be set.

Parametri

options

An associative array of options where the key is the option to set and the value is the new value for the option.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Setting Memcached options

<?php
$m = new Memcached();
var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);

$m->setOptions(array(Memcached::OPT_HASH => Memcached::HASH_MURMUR, Memcached::OPT_PREFIX_KEY => "widgets"));

var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);
echo "Prefix key is now: ", $m->getOption(Memcached::OPT_PREFIX_KEY), "\n";
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)
Prefix key is now: widgets

A se vedea ?i

  • Memcached::getOption() - Retrieve a Memcached option value
  • Memcached::setOption() - Set a Memcached option
  • Memcached Constants

Memcached::setOption
Memcached::setSaslAuthData
Memcached


Set the credentials to use for authentication

Memcached::setOptions
Memcached::touch
Memcached
PHP Manual

Memcached::setSaslAuthData

(PECL memcached >= 2.0.0)

Memcached::setSaslAuthData — Set the credentials to use for authentication

Descrierea

public void Memcached::setSaslAuthData ( string $username , string $password )

Memcached::setSaslAuthData() sets the username and password that should be used for SASL authentication with the memcache servers.

This method is only available when the memcached extension is built with SASL support. Please refer to Memcached setup for how to do this.

Parametri

username

The username to use for authentication.

password

The password to use for authentication.

Valorile întoarse

Nu este întoarsa nici o valoare.

Memcached::setOptions
Memcached::touch
Memcached


Set a new expiration on an item

Memcached::setSaslAuthData
Memcached::touchByKey
Memcached
PHP Manual

Memcached::touch

(PECL memcached >= 2.0.0)

Memcached::touch — Set a new expiration on an item

Descrierea

public bool Memcached::touch ( string $key , int $expiration )

Memcached::touch() sets a new expiration value on the given key.

Parametri

key

Cheia sub care se stocheaza valoarea.

expiration

Timpul expirarii, implicit este 0. Accesa?i Timpurile de expirare pentru informa?ii suplimentare.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Utiliza?i Memcached::getResultCode() daca e necesar.

A se vedea ?i

  • Memcached::touchByKey() - Set a new expiration on an item on a specific server

Memcached::setSaslAuthData
Memcached::touchByKey
Memcached


Set a new expiration on an item on a specific server

Memcached::touch
MemcachedException
Memcached
PHP Manual

Memcached::touchByKey

(PECL memcached >= 2.0.0)

Memcached::touchByKey — Set a new expiration on an item on a specific server

Descrierea

public bool Memcached::touchByKey ( string $server_key , string $key , int $expiration )

Memcached::touchByKey() is functionally equivalent to Memcached::touch(), except that the free-form server_key can be used to map the key to a specific server.

Parametri

server_key

Cheia ce identifica serverul pe care se înscrie, sau de pe care se cite?te valoarea. În loc de a efectua hash asupra cheii nemijlocite a elementului, se efectuaeaza hash asupra cheii serverului, atunci când se decide cu care server memcached sa se comunice. Aceasta permite ca elementele asociate sa fie grupate împreuna pe un singur server pentru a mari eficien?a opera?iilor multiple.

key

Cheia sub care se stocheaza valoarea.

expiration

Timpul expirarii, implicit este 0. Accesa?i Timpurile de expirare pentru informa?ii suplimentare.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. Utiliza?i Memcached::getResultCode() daca e necesar.

A se vedea ?i

  • Memcached::touch() - Set a new expiration on an item

Memcached::touch
MemcachedException
Memcached


The MemcachedException class

(PECL memcached >= 0.1.0)

Introducere

Sinopsisul clasei

MemcachedException extends RuntimeException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
Memcached::touchByKey
mqseries
Memcached


mqseries

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii mqseries
    • 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).
MemcachedException
Introducere
Alte servicii


Introducere

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
Instalarea / configurarea
mqseries


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
mqseries


Necesita?i

A working IBM WebSphere MQ installation. If building the extension the SDK for IBM WebSphere MQ is also required.

Nota: 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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/mqseries.

Nota: 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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Nu sunt al?i parametri de configurare.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie define?te resurse de tip connection ?i object_handle.

Func?iile mqseries_conn() ?i mqseries_connx() definesc descriptorii conexiunii.

Func?ia mqseries_open() define?te descriptorul obiectului.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

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

Tipurile resurselor
Func?ii mqseries
mqseries


Func?ii mqseries

Cuprins

  • 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).
Constante predefinite
mqseries_back
mqseries


MQSeries MQBACK

Func?ii mqseries
mqseries_begin
Func?ii mqseries
PHP Manual

mqseries_back

(PECL mqseries >= 0.10.0)

mqseries_back — MQSeries MQBACK

Descrierea

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.

Parametri

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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));
    }
?>

Note

Nota:

mqseries_back() will not function when using MQSeries Client to connect to a Queueu Manager.

A se vedea ?i

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_begin() - MQseries MQBEGIN

Func?ii mqseries
mqseries_begin
Func?ii mqseries


MQseries MQBEGIN

mqseries_back
mqseries_close
Func?ii mqseries
PHP Manual

mqseries_begin

(PECL mqseries >= 0.10.0)

mqseries_begin — MQseries MQBEGIN

Descrierea

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.

Parametri

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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));
        }
    }
?>

Note

Nota:

mqseries_begin() will not function when using MQSeries Client to connect to a Queueu Manager.

A se vedea ?i

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_back() - MQSeries MQBACK
  • mqseries_cmit() - MQSeries MQCMIT

mqseries_back
mqseries_close
Func?ii mqseries


MQSeries MQCLOSE

mqseries_begin
mqseries_cmit
Func?ii mqseries
PHP Manual

mqseries_close

(PECL mqseries >= 0.10.0)

mqseries_close — MQSeries MQCLOSE

Descrierea

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.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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));
    }
?>

A se vedea ?i

  • mqseries_open() - MQSeries MQOPEN
  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX

mqseries_begin
mqseries_cmit
Func?ii mqseries


MQSeries MQCMIT

mqseries_close
mqseries_conn
Func?ii mqseries
PHP Manual

mqseries_cmit

(PECL mqseries >= 0.10.0)

mqseries_cmit — MQSeries MQCMIT

Descrierea

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.

Parametri

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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));
    }
?>

Note

Nota:

mqseries_back() will not function when using MQSeries Client to connect to a Queueu Manager.

A se vedea ?i

  • mqseries_begin() - MQseries MQBEGIN
  • mqseries_back() - MQSeries MQBACK
  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX

mqseries_close
mqseries_conn
Func?ii mqseries


MQSeries MQCONN

mqseries_cmit
mqseries_connx
Func?ii mqseries
PHP Manual

mqseries_conn

(PECL mqseries >= 0.10.0)

mqseries_conn — MQSeries MQCONN

Descrierea

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.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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;
    }
?>

A se vedea ?i

  • mqseries_disc() - MQSeries MQDISC

mqseries_cmit
mqseries_connx
Func?ii mqseries


MQSeries MQCONNX

mqseries_conn
mqseries_disc
Func?ii mqseries
PHP Manual

mqseries_connx

(PECL mqseries >= 0.10.0)

mqseries_connx — MQSeries MQCONNX

Descrierea

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.

The mqseries_connx() call is like the mqseries_conn() (MQCONN) call, except that MQCONNX allows options to be specified to control the way that the call works.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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;
    }

?>

Example #2 mqseries_connx() example using SSL connection & OCSP Responder URL

<?php
    $mqcno = array(
        'Version' => 4, //MQCNO_VERSION_4
        'Options' => MQSERIES_MQCNO_STANDARD_BINDING,
        'MQCD' => array(
            'Version' => 7, //MQCD_VERSION_7
            'ConnectionName' => 'localhost',
            'TransportType' => MQSERIES_MQXPT_TCP,
            'ChannelName' => 'CONNECTIONCHANNEL',
            'SSLCipherSpec' => 'NULL_SHA'
        ),
        'MQSCO' => array(
            'KeyRepository' => '/var/mqm/qmgrs/QUEUEMGR/ssl/key', //Local path where the SSL key repository can be found
            'MQAIR' => array(
                'Version' => 2, //MQAIR_VERSION_2
                'AuthInfoType' => 2, //MQAIT_OCSP
                'OCSPResponderURL' => 'http://dummy.OCSP.responder'
            )
        )
    );

    mqseries_connx('QUEUEMGR', $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;
    }

?>

A se vedea ?i

  • mqseries_disc() - MQSeries MQDISC

mqseries_conn
mqseries_disc
Func?ii mqseries


MQSeries MQDISC

mqseries_connx
mqseries_get
Func?ii mqseries
PHP Manual

mqseries_disc

(PECL mqseries >= 0.10.0)

mqseries_disc — MQSeries MQDISC

Descrierea

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.

Parametri

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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));
    }
?>

A se vedea ?i

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX

mqseries_connx
mqseries_get
Func?ii mqseries


MQSeries MQGET

mqseries_disc
mqseries_inq
Func?ii mqseries
PHP Manual

mqseries_get

(PECL mqseries >= 0.10.0)

mqseries_get — MQSeries MQGET

Descrierea

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

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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));
    }

// 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);

?>

A se vedea ?i

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_put() - MQSeries MQPUT

mqseries_disc
mqseries_inq
Func?ii mqseries


MQSeries MQINQ

mqseries_get
mqseries_open
Func?ii mqseries
PHP Manual

mqseries_inq

(PECL mqseries >= 0.10.0)

mqseries_inq — MQSeries MQINQ

Descrierea

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.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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";
    }
?>

A se vedea ?i

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN

mqseries_get
mqseries_open
Func?ii mqseries


MQSeries MQOPEN

mqseries_inq
mqseries_put1
Func?ii mqseries
PHP Manual

mqseries_open

(PECL mqseries >= 0.10.0)

mqseries_open — MQSeries MQOPEN

Descrierea

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.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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;
    }
?>

A se vedea ?i

  • mqseries_close() - MQSeries MQCLOSE

mqseries_inq
mqseries_put1
Func?ii mqseries


MQSeries MQPUT1

mqseries_open
mqseries_put
Func?ii mqseries
PHP Manual

mqseries_put1

(PECL mqseries >= 0.10.0)

mqseries_put1 — MQSeries MQPUT1

Descrierea

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.

You can use both the mqseries_put() and mqseries_put1() calls to put messages on a queue; which call to use depends on the circumstances. Use the mqseries_put() (MQPUT) call to place multiple messages on the same queue. Use the mqseries_put1() (MQPUT1) call to put only one message on a queue. This call encapsulates the MQOPEN, MQPUT, and MQCLOSE calls into a single call, minimizing the number of calls that must be issued.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_get() - MQSeries MQGET

mqseries_open
mqseries_put
Func?ii mqseries


MQSeries MQPUT

mqseries_put1
mqseries_set
Func?ii mqseries
PHP Manual

mqseries_put

(PECL mqseries >= 0.10.0)

mqseries_put — MQSeries MQPUT

Descrierea

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.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);

?>

A se vedea ?i

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_get() - MQSeries MQGET

mqseries_put1
mqseries_set
Func?ii mqseries


MQSeries MQSET

mqseries_put
mqseries_strerror
Func?ii mqseries
PHP Manual

mqseries_set

(PECL mqseries >= 0.10.0)

mqseries_set — MQSeries MQSET

Descrierea

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.

Parametri

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.

intAttrCount

Count of integer attributes.

intAttrs

Array of integer attributes.

charAttrLength

Length of character attributes buffer.

charAttrs

Character attributes.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • mqseries_inq() - MQSeries MQINQ

mqseries_put
mqseries_strerror
Func?ii mqseries


Returns the error message corresponding to a result code (MQRC).

mqseries_set
Network
Func?ii mqseries
PHP Manual

mqseries_strerror

(PECL mqseries >= 0.10.0)

mqseries_strerror — Returns the error message corresponding to a result code (MQRC).

Descrierea

string mqseries_strerror ( int $reason )

mqseries_strerror() returns the message that correspond to the reason result code.

Parametri

reason

Reason code qualifying the compCode.

Valorile întoarse

string representation of the reason code message.

Exemple

Example #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;
    }
?>

Exemplul de mai sus va afi?a:

Connx CompCode:2 Reason:2059 Text:Queue manager not available for connection.

mqseries_set
Network
Func?ii mqseries


Network

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii de re?ea
    • 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 — Pseudonim pentru checkdnsrr
    • dns_get_mx — Pseudonim pentru 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 — Checks if or where headers have been sent
    • 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 long integer
    • long2ip — Converts an long integer address into a string in (IPv4) 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 — Pseudonim pentru stream_get_meta_data
    • socket_set_blocking — Pseudonim pentru stream_set_blocking
    • socket_set_timeout — Pseudonim pentru stream_set_timeout
    • syslog — Generate a system log message
mqseries_strerror
Introducere
Alte servicii


Introducere

Ofera diverse func?ii de re?ea.

Network
Instalarea / configurarea
Network


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Network


Necesita?i

Functions checkdnsrr(), getmxrr() and dns_get_record() requires Bind on Linux.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Network Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
define_syslog_variables | "0" | PHP_INI_ALL | Deprecated in PHP 5.3.0. Removed in PHP 5.4.0.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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().

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

This extension defines a file pointer resource returned by fsockopen() and pfsockopen().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt întotdeauna disponibile ca parte componenta a nucleului PHP.

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.
Tipurile resurselor
Func?ii de re?ea
Network


Func?ii de re?ea

Cuprins

  • 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 — Pseudonim pentru checkdnsrr
  • dns_get_mx — Pseudonim pentru 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 — Checks if or where headers have been sent
  • 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 long integer
  • long2ip — Converts an long integer address into a string in (IPv4) 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 — Pseudonim pentru stream_get_meta_data
  • socket_set_blocking — Pseudonim pentru stream_set_blocking
  • socket_set_timeout — Pseudonim pentru stream_set_timeout
  • syslog — Generate a system log message
Constante predefinite
checkdnsrr
Network


Check DNS records corresponding to a given Internet host name or IP address

Func?ii de re?ea
closelog
Func?ii de re?ea
PHP Manual

checkdnsrr

(PHP 4, PHP 5, PHP 7)

checkdnsrr — Check DNS records corresponding to a given Internet host name or IP address

Descrierea

bool checkdnsrr ( string $host [, string $type = "MX" ] )

Searches DNS for records of type type corresponding to host.

Parametri

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.

Valorile întoarse

Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on Windows platforms.
5.2.4 | TXT type was added.

Note

Nota:

For compatibility with Windows before this was implemented, then try the » PEAR class » Net_DNS.

A se vedea ?i

  • 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

Func?ii de re?ea
closelog
Func?ii de re?ea


Close connection to system logger

checkdnsrr
define_syslog_variables
Func?ii de re?ea
PHP Manual

closelog

(PHP 4, PHP 5, PHP 7)

closelog — Close connection to system logger

Descrierea

bool closelog ( void )

closelog() closes the descriptor being used to write to the system logger. The use of closelog() is optional.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • syslog() - Generate a system log message
  • openlog() - Open connection to system logger

checkdnsrr
define_syslog_variables
Func?ii de re?ea


Initializes all syslog related variables

closelog
dns_check_record
Func?ii de re?ea
PHP Manual

define_syslog_variables

(PHP 4, PHP 5 < 5.4.0)

define_syslog_variables — Initializes all syslog related variables

Descrierea

void define_syslog_variables ( void )

Initializes all variables used in the syslog functions.

Valorile întoarse

Nu este întoarsa nici o valoare.

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
Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

Exemple

Example #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 ...
?>

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | This function was removed from PHP.
5.3.0 | This function now throws an E_DEPRECATED notice.

A se vedea ?i

  • openlog() - Open connection to system logger
  • syslog() - Generate a system log message
  • closelog() - Close connection to system logger

closelog
dns_check_record
Func?ii de re?ea


Pseudonim pentru checkdnsrr

define_syslog_variables
dns_get_mx
Func?ii de re?ea
PHP Manual

dns_check_record

(PHP 5, PHP 7)

dns_check_record — Pseudonim pentru checkdnsrr()

Descrierea

Aceasta func?ie este pseudonim pentru: checkdnsrr().

define_syslog_variables
dns_get_mx
Func?ii de re?ea


Pseudonim pentru getmxrr

dns_check_record
dns_get_record
Func?ii de re?ea
PHP Manual

dns_get_mx

(PHP 5, PHP 7)

dns_get_mx — Pseudonim pentru getmxrr()

Descrierea

Aceasta func?ie este pseudonim pentru: getmxrr().

dns_check_record
dns_get_record
Func?ii de re?ea


Fetch DNS Resource Records associated with a hostname

dns_get_mx
fsockopen
Func?ii de re?ea
PHP Manual

dns_get_record

(PHP 5, PHP 7)

dns_get_record — Fetch DNS Resource Records associated with a hostname

Descrierea

array dns_get_record ( string $hostname [, int $type = DNS_ANY [, array &$authns [, array &$addtl [, bool $raw = false ]]]] )

Fetch DNS Resource Records associated with the given hostname.

Parametri

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.

Nota:

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_CAA, DNS_MX, DNS_NS, DNS_PTR, DNS_SOA, DNS_TXT, DNS_AAAA, DNS_SRV, DNS_NAPTR, DNS_A6, DNS_ALL or DNS_ANY.

Nota:

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.

raw

In case of raw mode, we query only the requested type instead of looping type by type before going with the additional info stuff.

Valorile întoarse

This function returns an array of associative arrays, sau FALSE în cazul e?ecului. 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.
CAA | flags: A one-byte bitfield; currently only bit 0 is defined, meaning 'critical'; other bits are reserved and should be ignored. tag: The CAA tag name (alphanumeric ASCII string). value: The CAA tag value (binary string, may use subformats). For additional information see: » RFC 6844
SOA | mname: FQDN of the machine from which the resource records originated. rname: Email address of the administrative contact 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.

Istoricul schimbarilor

Versiune | Descriere
7.0.16 | Added support for CAA record type.
5.4.0 | Added raw parameter.
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.

Exemple

Example #1 Using dns_get_record()

<?php
$result = dns_get_record("php.net");
print_r($result);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

)

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

)

Note

Nota:

For compatibility with versions before PHP 5.3.0 on some operating systems, try the » PEAR class » Net_DNS.

A se vedea ?i

  • dns_get_mx() - Pseudonim pentru getmxrr
  • dns_check_record() - Pseudonim pentru checkdnsrr

dns_get_mx
fsockopen
Func?ii de re?ea


Open Internet or Unix domain socket connection

dns_get_record
gethostbyaddr
Func?ii de re?ea
PHP Manual

fsockopen

(PHP 4, PHP 5, PHP 7)

fsockopen — Open Internet or Unix domain socket connection

Descrierea

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 Lista transporturilor prin socket-e sus?inute. 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.

Parametri

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. This can be omitted and skipped with -1 for transports that do not use ports, such as unix://.

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.

Nota:

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.

Valorile întoarse

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

Erori/Excep?ii

Throws E_WARNING if hostname is not a valid domain.

Exemple

Example #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);
}
?>

Example #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);
}
?>

Note

Nota:

Depending on the environment, the Unix domain or the optional connect timeout may not be available.

Avertizare

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.

Nota: La specificarea unei adrese IPv6 numerice (de ex. fe80::1), ea trebuie cuprinsa între paranteze patrate ? de exemplu tcp://[fe80::1]:80.

A se vedea ?i

  • 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() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fwrite() - Binary-safe file write
  • fclose() - Closes an open file pointer
  • feof() - Tests for end-of-file on a file pointer
  • socket_connect() - Initiates a connection on a socket
  • The Curl extension

dns_get_record
gethostbyaddr
Func?ii de re?ea


Get the Internet host name corresponding to a given IP address

fsockopen
gethostbyname
Func?ii de re?ea
PHP Manual

gethostbyaddr

(PHP 4, PHP 5, PHP 7)

gethostbyaddr — Get the Internet host name corresponding to a given IP address

Descrierea

string gethostbyaddr ( string $ip_address )

Returns the host name of the Internet host specified by ip_address.

Parametri

ip_address

The host IP address.

Valorile întoarse

Returns the host name on success, the unmodified ip_address on failure, or FALSE on malformed input.

Exemple

Example #1 A simple gethostbyaddr() example

<?php
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);

echo $hostname;
?>

A se vedea ?i

  • 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
Func?ii de re?ea


Get the IPv4 address corresponding to a given Internet host name

gethostbyaddr
gethostbynamel
Func?ii de re?ea
PHP Manual

gethostbyname

(PHP 4, PHP 5, PHP 7)

gethostbyname — Get the IPv4 address corresponding to a given Internet host name

Descrierea

string gethostbyname ( string $hostname )

Returns the IPv4 address of the Internet host specified by hostname.

Parametri

hostname

The host name.

Valorile întoarse

Returns the IPv4 address or a string containing the unmodified hostname on failure.

Exemple

Example #1 A simple gethostbyname() example

<?php
$ip = gethostbyname('www.example.com');

echo $ip;
?>

A se vedea ?i

  • 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
Func?ii de re?ea


Get a list of IPv4 addresses corresponding to a given Internet host name

gethostbyname
gethostname
Func?ii de re?ea
PHP Manual

gethostbynamel

(PHP 4, PHP 5, PHP 7)

gethostbynamel — Get a list of IPv4 addresses corresponding to a given Internet host name

Descrierea

array gethostbynamel ( string $hostname )

Returns a list of IPv4 addresses to which the Internet host specified by hostname resolves.

Parametri

hostname

The host name.

Valorile întoarse

Returns an array of IPv4 addresses or FALSE if hostname could not be resolved.

Exemple

Example #1 gethostbynamel() example

<?php
$hosts = gethostbynamel('www.example.com');
print_r($hosts);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => 192.0.34.166
)

A se vedea ?i

  • 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
Func?ii de re?ea


Gets the host name

gethostbynamel
getmxrr
Func?ii de re?ea
PHP Manual

gethostname

(PHP >= 5.3.0)

gethostname — Gets the host name

Descrierea

string gethostname ( void )

gethostname() gets the standard host name for the local machine.

Valorile întoarse

Returns a string with the hostname on success, otherwise FALSE is returned.

Exemple

Example #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
?>

A se vedea ?i

  • 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
Func?ii de re?ea


Get MX records corresponding to a given Internet host name

gethostname
getprotobyname
Func?ii de re?ea
PHP Manual

getmxrr

(PHP 4, PHP 5, PHP 7)

getmxrr — Get MX records corresponding to a given Internet host name

Descrierea

bool getmxrr ( string $hostname , array &$mxhosts [, array &$weight ] )

Searches DNS for MX records corresponding to hostname.

Parametri

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.

Valorile întoarse

Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on Windows platforms.

Note

Nota:

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.

Nota:

For compatibility with Windows before this was implemented, then try the » PEAR class » Net_DNS.

A se vedea ?i

  • 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
Func?ii de re?ea


Get protocol number associated with protocol name

getmxrr
getprotobynumber
Func?ii de re?ea
PHP Manual

getprotobyname

(PHP 4, PHP 5, PHP 7)

getprotobyname — Get protocol number associated with protocol name

Descrierea

int getprotobyname ( string $name )

getprotobyname() returns the protocol number associated with the protocol name as per /etc/protocols.

Parametri

name

The protocol name.

Valorile întoarse

Returns the protocol number, sau FALSE în cazul e?ecului.

Exemple

Example #1 getprotobyname() example

<?php
$protocol = 'tcp';
$get_prot = getprotobyname($protocol);
if ($get_prot === FALSE) {
    echo 'Invalid Protocol';
} else {
    echo 'Protocol #' . $get_prot;
}
?>

A se vedea ?i

  • getprotobynumber() - Get protocol name associated with protocol number

getmxrr
getprotobynumber
Func?ii de re?ea


Get protocol name associated with protocol number

getprotobyname
getservbyname
Func?ii de re?ea
PHP Manual

getprotobynumber

(PHP 4, PHP 5, PHP 7)

getprotobynumber — Get protocol name associated with protocol number

Descrierea

string getprotobynumber ( int $number )

getprotobynumber() returns the protocol name associated with protocol number as per /etc/protocols.

Parametri

number

The protocol number.

Valorile întoarse

Returns the protocol name as a string, sau FALSE în cazul e?ecului.

A se vedea ?i

  • getprotobyname() - Get protocol number associated with protocol name

getprotobyname
getservbyname
Func?ii de re?ea


Get port number associated with an Internet service and protocol

getprotobynumber
getservbyport
Func?ii de re?ea
PHP Manual

getservbyname

(PHP 4, PHP 5, PHP 7)

getservbyname — Get port number associated with an Internet service and protocol

Descrierea

int getservbyname ( string $service , string $protocol )

getservbyname() returns the Internet port which corresponds to service for the specified protocol as per /etc/services.

Parametri

service

The Internet service name, as a string.

protocol

protocol is either "tcp" or "udp" (in lowercase).

Valorile întoarse

Returns the port number, or FALSE if service or protocol is not found.

Exemple

Example #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";
}
?>

A se vedea ?i

  • 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
Func?ii de re?ea


Get Internet service which corresponds to port and protocol

getservbyname
header_register_callback
Func?ii de re?ea
PHP Manual

getservbyport

(PHP 4, PHP 5, PHP 7)

getservbyport — Get Internet service which corresponds to port and protocol

Descrierea

string getservbyport ( int $port , string $protocol )

getservbyport() returns the Internet service associated with port for the specified protocol as per /etc/services.

Parametri

port

The port number.

protocol

protocol is either "tcp" or "udp" (in lowercase).

Valorile întoarse

Returns the Internet service name as a string.

A se vedea ?i

  • getservbyname() - Get port number associated with an Internet service and protocol

getservbyname
header_register_callback
Func?ii de re?ea


Call a header function

getservbyport
header_remove
Func?ii de re?ea
PHP Manual

header_register_callback

(PHP 5 >= 5.4.0, PHP 7)

header_register_callback — Call a header function

Descrierea

bool header_register_callback ( callable $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.

Parametri

callback

Function called just before the headers are sent. It gets no parameters and the return value is ignored.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

Content-Type: text/plain

a

Note

header_register_callback() is executed just as the headers are about to be sent out, so any output from this function can break output.

Nota:

Antetele vor fi accesibile ?i afi?ate doar atunci când este utilizat un SAPI care le sus?ine.

A se vedea ?i

  • 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
Func?ii de re?ea


Remove previously set headers

header_register_callback
header
Func?ii de re?ea
PHP Manual

header_remove

(PHP 5 >= 5.3.0, PHP 7)

header_remove — Remove previously set headers

Descrierea

void header_remove ([ string $name ] )

Removes an HTTP header previously set using header().

Parametri

name

The header name to be removed.

Nota: This parameter is case-insensitive.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Unsetting specific header.

<?php
header("X-Foo: Bar");
header("X-Bar: Baz");
header_remove("X-Foo");
?>

Exemplul de mai sus va afi?a ceva similar cu:

X-Bar: Baz

Example #2 Unsetting all previously set headers.

<?php
header("X-Foo: Bar");
header("X-Bar: Baz");
header_remove();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Note

Precautie

    This function will remove all headers set by PHP,
    including cookies, session and the X-Powered-By headers.

Nota:

Antetele vor fi accesibile ?i afi?ate doar atunci când este utilizat un
SAPI care le sus?ine.

A se vedea ?i

  • header() - Send a raw HTTP header
    •

  • headers_sent() - Checks if or where headers have been sent
    •

header_register_callback

header

Func?ii de re?ea


Send a raw HTTP header

header_remove
headers_list
Func?ii de re?ea
PHP Manual

header

(PHP 4, PHP 5, PHP 7)

header — Send a raw HTTP header

Descrierea

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/');
exit;
?>

Parametri

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");
?>

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Istoricul schimbarilor

Versiune | Descriere
5.1.2 | This function now prevents more than one header to be sent at once as a protection against header injection attacks.

Exemple

Example #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');
?>

Example #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
?>

Nota:

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.

Note

Nota:

Antetele vor fi accesibile ?i afi?ate doar atunci când este utilizat un SAPI care le sus?ine.

Nota:

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.

Nota:

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.

Nota:

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.

Nota: 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).

Nota:

Most contemporary clients accept relative URIs as argument to » Location:, but some older clients require an absolute URI including the scheme, hostname and absolute path. 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;
?>

Nota:

Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant.

A se vedea ?i

  • headers_sent() - Checks if or where headers have been sent
  • setcookie() - Send a cookie
  • http_response_code() - Get or Set the HTTP response code
  • The section on HTTP authentication

header_remove
headers_list
Func?ii de re?ea


Returns a list of response headers sent (or ready to send)

header
headers_sent
Func?ii de re?ea
PHP Manual

headers_list

(PHP 5, PHP 7)

headers_list — Returns a list of response headers sent (or ready to send)

Descrierea

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().

Valorile întoarse

Returns a numerically indexed array of headers.

Exemple

Example #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());

?>

Exemplul de mai sus va afi?a:

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"
}

Note

Nota:

Antetele vor fi accesibile ?i afi?ate doar atunci când este utilizat un SAPI care le sus?ine.

A se vedea ?i

  • headers_sent() - Checks if or where headers have been sent
  • header() - Send a raw HTTP header
  • setcookie() - Send a cookie
  • apache_response_headers() - Fetch all HTTP response headers
  • http_response_code() - Get or Set the HTTP response code

header
headers_sent
Func?ii de re?ea


Checks if or where headers have been sent

headers_list
http_response_code
Func?ii de re?ea
PHP Manual

headers_sent

(PHP 4, PHP 5, PHP 7)

headers_sent — Checks if or where headers have been sent

Descrierea

bool headers_sent ([ string &$file [, int &$line ]] )

Checks if or where headers have been sent.

You can't add any more header lines using the header() function once the header block has already been sent. Using this function you can at least prevent getting HTTP header related error messages. Another option is to use Output Buffering.

Parametri

file

If the optional file and line parameters are set, headers_sent() will put the PHP source file name and line number where output started in the file and line variables.

line

The line number where the output started.

Valorile întoarse

headers_sent() will return FALSE if no HTTP headers have already been sent or TRUE otherwise.

Exemple

Example #1 Examples using 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
// 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;
}

?>

Note

Nota:

Antetele vor fi accesibile ?i afi?ate doar atunci când este utilizat un SAPI care le sus?ine.

A se vedea ?i

  • ob_start() - Turn on output buffering
  • trigger_error() - Genereaza un mesaj de eroare/avertizare/notificare la nivelul utilizatorului
  • headers_list() - Returns a list of response headers sent (or ready to send)
  • header() - Send a raw HTTP header for a more detailed discussion of the matters involved.

headers_list
http_response_code
Func?ii de re?ea


Get or Set the HTTP response code

headers_sent
inet_ntop
Func?ii de re?ea
PHP Manual

http_response_code

(PHP 5 >= 5.4.0, PHP 7)

http_response_code — Get or Set the HTTP response code

Descrierea

mixed http_response_code ([ int $response_code ] )

Gets or sets the HTTP response status code.

Parametri

response_code

The optional response_code will set the response code.

Valorile întoarse

If response_code is provided, then the previous status code will be returned. If response_code is not provided, then the current status code will be returned. Both of these values will default to a 200 status code if used in a web server environment.

FALSE will be returned if response_code is not provided and it is not invoked in a web server environment (such as from a CLI application). TRUE will be returned if response_code is provided and it is not invoked in a web server environment (but only when no previous response status has been set).

Exemple

Example #1 Using http_response_code() in a web server environment

<?php

// Get the current response code and set a new one
var_dump(http_response_code(404));

// Get the new response code
var_dump(http_response_code());
?>

Exemplul de mai sus va afi?a:

int(200)
int(404)

Example #2 Using http_response_code() in a CLI environment

<?php

// Get the current default response code
var_dump(http_response_code());

// Set a response code
var_dump(http_response_code(201));

// Get the new response code
var_dump(http_response_code());
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)
int(201)

A se vedea ?i

  • header() - Send a raw HTTP header
  • headers_list() - Returns a list of response headers sent (or ready to send)

headers_sent
inet_ntop
Func?ii de re?ea


Converts a packed internet address to a human readable representation

http_response_code
inet_pton
Func?ii de re?ea
PHP Manual

inet_ntop

(PHP 5 >= 5.1.0, PHP 7)

inet_ntop — Converts a packed internet address to a human readable representation

Descrierea

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.

Parametri

in_addr

A 32bit IPv4, or 128bit IPv6 address.

Valorile întoarse

Returns a string representation of the address sau FALSE în cazul e?ecului.

Exemple

Example #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;
?>

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on Windows platforms.

A se vedea ?i

  • long2ip() - Converts an long integer address into a string in (IPv4) Internet standard dotted format
  • ip2long() - Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer
  • inet_pton() - Converts a human readable IP address to its packed in_addr representation

http_response_code
inet_pton
Func?ii de re?ea


Converts a human readable IP address to its packed in_addr representation

inet_ntop
ip2long
Func?ii de re?ea
PHP Manual

inet_pton

(PHP 5 >= 5.1.0, PHP 7)

inet_pton — Converts a human readable IP address to its packed in_addr representation

Descrierea

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.

Parametri

address

A human readable IPv4 or IPv6 address.

Valorile întoarse

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).

Exemple

Example #1 inet_pton() Example

<?php
$in_addr = inet_pton('127.0.0.1');

$in6_addr = inet_pton('::1');
?>

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function is now available on Windows platforms.

A se vedea ?i

  • ip2long() - Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer
  • long2ip() - Converts an long integer address into a string in (IPv4) Internet standard dotted format
  • inet_ntop() - Converts a packed internet address to a human readable representation

inet_ntop
ip2long
Func?ii de re?ea


Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer

inet_pton
long2ip
Func?ii de re?ea
PHP Manual

ip2long

(PHP 4, PHP 5, PHP 7)

ip2long — Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer

Descrierea

int ip2long ( string $ip_address )

The function ip2long() generates an long integer representation of 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.

Parametri

ip_address

A standard format address.

Valorile întoarse

Returns the long integer or FALSE if ip_address is invalid.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | Prior to this version, on Windows ip2long() would sometimes return a valid number even if passed a value which was not an (IPv4) Internet Protocol dotted address.
5.2.10 | Prior to this version, ip2long() would sometimes return a valid number even if passed a value which was not an (IPv4) Internet Protocol dotted address.

Exemple

Example #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;
?>

Example #2 Displaying an IP address

This second example shows how to print a converted address with the printf() function:

<?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
}
?>

Note

Nota:

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.

Nota:

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.

A se vedea ?i

  • long2ip() - Converts an long integer address into a string in (IPv4) Internet standard dotted format
  • sprintf() - Return a formatted string

inet_pton
long2ip
Func?ii de re?ea


Converts an long integer address into a string in (IPv4) Internet standard dotted format

ip2long
openlog
Func?ii de re?ea
PHP Manual

long2ip

(PHP 4, PHP 5, PHP 7)

long2ip — Converts an long integer address into a string in (IPv4) Internet standard dotted format

Descrierea

string long2ip ( string $proper_address )

The function long2ip() generates an Internet address in dotted format (i.e.: aaa.bbb.ccc.ddd) from the long integer representation.

Parametri

proper_address

A proper address representation in long integer.

Valorile întoarse

Returns the Internet IP address as a string.

A se vedea ?i

  • ip2long() - Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer

ip2long
openlog
Func?ii de re?ea


Open connection to system logger

long2ip
pfsockopen
Func?ii de re?ea
PHP Manual

openlog

(PHP 4, PHP 5, PHP 7)

openlog — Open connection to system logger

Descrierea

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.

Parametri

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

Nota:

LOG_USER is the only valid log type under Windows operating systems

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • syslog() - Generate a system log message
  • closelog() - Close connection to system logger

long2ip
pfsockopen
Func?ii de re?ea


Open persistent Internet or Unix domain socket connection

openlog
setcookie
Func?ii de re?ea
PHP Manual

pfsockopen

(PHP 4, PHP 5, PHP 7)

pfsockopen — Open persistent Internet or Unix domain socket connection

Descrierea

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().

Parametri

For parameter information, see the fsockopen() documentation.

A se vedea ?i

  • fsockopen() - Open Internet or Unix domain socket connection

openlog
setcookie
Func?ii de re?ea


Send a cookie

pfsockopen
setrawcookie
Func?ii de re?ea
PHP Manual

setcookie

(PHP 4, PHP 5, PHP 7)

setcookie — Send a cookie

Descrierea

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 array. Cookie values may also exist in $_REQUEST.

Parametri

» 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).

Nota:

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 (sub)domain that the cookie is available to. Setting this to a subdomain (such as 'www.example.com') will make the cookie available to that subdomain and all other sub-domains of it (i.e. w2.www.example.com). To make the cookie available to the whole domain (including all subdomains of it), simply set the value to the domain name ('example.com', in this case).

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

Valorile întoarse

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.

Exemple

Some examples follow how to send cookies:

Example #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"];

// Another way to debug/test is to view all cookies
print_r($_COOKIE);
?>

Example #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);
?>

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

three : cookiethree
two : cookietwo
one : cookieone

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | A Max-Age attribute is now included in the Set-Cookie header sent to the client.
5.2.0 | The httponly parameter was added.

Note

Nota:

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.

Nota:

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.

A se vedea ?i

  • header() - Send a raw HTTP header
  • setrawcookie() - Send a cookie without urlencoding the cookie value
  • cookies section
  • » RFC 6265
  • » RFC 2109

pfsockopen
setrawcookie
Func?ii de re?ea


Send a cookie without urlencoding the cookie value

setcookie
socket_get_status
Func?ii de re?ea
PHP Manual

setrawcookie

(PHP 5, PHP 7)

setrawcookie — Send a cookie without urlencoding the cookie value

Descrierea

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.

Parametri

For parameter information, see the setcookie() documentation.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | A Max-Age attribute is now included in the Set-Cookie header sent to the client.
5.2.0 | The httponly parameter was added.

A se vedea ?i

  • setcookie() - Send a cookie

setcookie
socket_get_status
Func?ii de re?ea


Pseudonim pentru stream_get_meta_data

setrawcookie
socket_set_blocking
Func?ii de re?ea
PHP Manual

socket_get_status

(PHP 4, PHP 5, PHP 7)

socket_get_status — Pseudonim pentru stream_get_meta_data()

Descrierea

Aceasta func?ie este pseudonim pentru: stream_get_meta_data().

setrawcookie
socket_set_blocking
Func?ii de re?ea


Pseudonim pentru stream_set_blocking

socket_get_status
socket_set_timeout
Func?ii de re?ea
PHP Manual

socket_set_blocking

(PHP 4, PHP 5, PHP 7)

socket_set_blocking — Pseudonim pentru stream_set_blocking()

Descrierea

Aceasta func?ie este pseudonim pentru: stream_set_blocking().

socket_get_status
socket_set_timeout
Func?ii de re?ea


Pseudonim pentru stream_set_timeout

socket_set_blocking
syslog
Func?ii de re?ea
PHP Manual

socket_set_timeout

(PHP 4, PHP 5, PHP 7)

socket_set_timeout — Pseudonim pentru stream_set_timeout()

Descrierea

Aceasta func?ie este pseudonim pentru: stream_set_timeout().

socket_set_blocking
syslog
Func?ii de re?ea


Generate a system log message

socket_set_timeout
RRD
Func?ii de re?ea
PHP Manual

syslog

(PHP 4, PHP 5, PHP 7)

syslog — Generate a system log message

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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();
?>

Note

On Windows NT, the syslog service is emulated using the Event Log.

Nota:

Use of LOG_LOCAL0 through LOG_LOCAL7 for the facility parameter of openlog() is not available in Windows.

A se vedea ?i

  • openlog() - Open connection to system logger
  • closelog() - Close connection to system logger

socket_set_timeout
RRD
Func?ii de re?ea


RRDtool

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Procedural PECL/rrd example
    • OOP PECL/rrd example
  • Func?ii RRD
    • 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.
    • rrdc_disconnect — Close any outstanding connection to rrd caching daemon
  • 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
Introducere
Alte servicii


Introducere

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
Instalarea / configurarea
RRD


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
RRD


Necesita?i

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.

Avertizare

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/rrd.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
RRD


Exemple

Cuprins

  • Procedural PECL/rrd example
  • OOP PECL/rrd example
Constante predefinite
Procedural PECL/rrd example
RRD


Procedural PECL/rrd example

Example #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"
 )
);
?>

Exemple
OOP PECL/rrd example
Exemple


OOP PECL/rrd example

Example #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
Func?ii RRD
Exemple


Func?ii RRD

Cuprins

  • 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.
  • rrdc_disconnect — Close any outstanding connection to rrd caching daemon
OOP PECL/rrd example
rrd_create
RRD


Creates rrd database file

Func?ii RRD
rrd_error
Func?ii RRD
PHP Manual

rrd_create

(PECL rrd >= 0.9.0)

rrd_create — Creates rrd database file

Descrierea

bool rrd_create ( string $filename , array $options )

Creates the rdd database file.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Func?ii RRD
rrd_error
Func?ii RRD


Gets latest error message.

rrd_create
rrd_fetch
Func?ii RRD
PHP Manual

rrd_error

(PECL rrd >= 0.9.0)

rrd_error — Gets latest error message.

Descrierea

string rrd_error ( void )

Returns latest global rrd error message.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Latest error message.

rrd_create
rrd_fetch
Func?ii RRD


Fetch the data for graph as array.

rrd_error
rrd_first
Func?ii RRD
PHP Manual

rrd_fetch

(PECL rrd >= 0.9.0)

rrd_fetch — Fetch the data for graph as array.

Descrierea

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.

Parametri

filename

RRD database file name.

options

Array of options for resolution specification.

Valorile întoarse

Returns information about retrieved graph data.

rrd_error
rrd_first
Func?ii RRD


Gets the timestamp of the first sample from rrd file.

rrd_fetch
rrd_graph
Func?ii RRD
PHP Manual

rrd_first

(PECL rrd >= 0.9.0)

rrd_first — Gets the timestamp of the first sample from rrd file.

Descrierea

int rrd_first ( string $file [, int $raaindex = 0 ] )

Returns the first data sample from the specified RRA of the RRD file.

Parametri

file

RRD database file name.

raaindex

The index number of the RRA that is to be examined. Default value is 0.

Valorile întoarse

Integer number of unix timestamp, FALSE if some error occurs.

rrd_fetch
rrd_graph
Func?ii RRD


Creates image from a data.

rrd_first
rrd_info
Func?ii RRD
PHP Manual

rrd_graph

(PECL rrd >= 0.9.0)

rrd_graph — Creates image from a data.

Descrierea

array rrd_graph ( string $filename , array $options )

Creates image for a particular data from RRD file.

Parametri

filename

The filename to output the graph to. This will generally end in either .png, .svg or .eps, depending on the format you want to output.

options

Options for generating image. See man page of rrd graph for all possible options. All options (data definitions, variable defintions, etc.) are allowed.

Valorile întoarse

Array with information about generated image is returned, FALSE when error occurs.

rrd_first
rrd_info
Func?ii RRD


Gets information about rrd file

rrd_graph
rrd_last
Func?ii RRD
PHP Manual

rrd_info

(PECL rrd >= 0.9.0)

rrd_info — Gets information about rrd file

Descrierea

array rrd_info ( string $filename )

Returns information about particular RRD database file.

Parametri

file

RRD database file name.

Valorile întoarse

Array with information about requsted RRD file, FALSE when error occurs.

rrd_graph
rrd_last
Func?ii RRD


Gets unix timestamp of the last sample.

rrd_info
rrd_lastupdate
Func?ii RRD
PHP Manual

rrd_last

(PECL rrd >= 0.9.0)

rrd_last — Gets unix timestamp of the last sample.

Descrierea

int rrd_last ( string $filename )

Returns the UNIX timestamp of the most recent update of the RRD database.

Parametri

filename

RRD database file name.

Valorile întoarse

Integer as unix timestamp of the most recent data from the RRD database.

rrd_info
rrd_lastupdate
Func?ii RRD


Gets information about last updated data.

rrd_last
rrd_restore
Func?ii RRD
PHP Manual

rrd_lastupdate

(PECL rrd >= 0.9.0)

rrd_lastupdate — Gets information about last updated data.

Descrierea

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.

Parametri

file

RRD database file name.

Valorile întoarse

Array of information about last update, FALSE when error occurs.

rrd_last
rrd_restore
Func?ii RRD


Restores the RRD file from XML dump.

rrd_lastupdate
rrd_tune
Func?ii RRD
PHP Manual

rrd_restore

(PECL rrd >= 0.9.0)

rrd_restore — Restores the RRD file from XML dump.

Descrierea

bool rrd_restore ( string $xml_file , string $rrd_file [, array $options ] )

Restores the RRD file from the XML dump.

Parametri

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.

Valorile întoarse

Returns TRUE on success, FALSE otherwise.

rrd_lastupdate
rrd_tune
Func?ii RRD


Tunes some RRD database file header options.

rrd_restore
rrd_update
Func?ii RRD
PHP Manual

rrd_tune

(PECL rrd >= 0.9.0)

rrd_tune — Tunes some RRD database file header options.

Descrierea

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.

Parametri

filename

RRD database file name.

options

Options with RRD database file properties which will be changed. See rrd tune man page for details.

Valorile întoarse

Returns TRUE on success, FALSE otherwise.

rrd_restore
rrd_update
Func?ii RRD


Updates the RRD database.

rrd_tune
rrd_version
Func?ii RRD
PHP Manual

rrd_update

(PECL rrd >= 0.9.0)

rrd_update — Updates the RRD database.

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns TRUE on success, FALSE when error occurs.

rrd_tune
rrd_version
Func?ii RRD


Gets information about underlying rrdtool library

rrd_update
rrd_xport
Func?ii RRD
PHP Manual

rrd_version

(PECL rrd >= 1.0.0)

rrd_version — Gets information about underlying rrdtool library

Descrierea

string rrd_version ( void )

Returns information about underlying rrdtool library.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

String with rrdtool version number e.g. "1.4.3".

rrd_update
rrd_xport
Func?ii RRD


Exports the information about RRD database.

rrd_version
rrdc_disconnect
Func?ii RRD
PHP Manual

rrd_xport

(PECL rrd >= 0.9.0)

rrd_xport — Exports the information about RRD database.

Descrierea

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.

Parametri

options

Array of options for the export, see rrd xport man page.

Valorile întoarse

Array with information about RRD database file, FALSE when error occurs.

rrd_version
rrdc_disconnect
Func?ii RRD


Close any outstanding connection to rrd caching daemon

rrd_xport
RRDCreator
Func?ii RRD
PHP Manual

rrdc_disconnect

(PECL rrd >= 1.1.2)

rrdc_disconnect — Close any outstanding connection to rrd caching daemon

Descrierea

void rrdc_disconnect ( void )

Close any outstanding connection to rrd caching daemon.

This function is automatically called when the whole PHP process is terminated. It depends on used SAPI. For example, it's called automatically at the end of command line script.

It's up user whether he wants to call this function at the end of every request or otherwise.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

rrd_xport
RRDCreator
Func?ii RRD


The RRDCreator class

(PECL rrd >= 0.9.0)

Introducere

Class for creation of RRD database file.

Sinopsisul clasei

RRDCreator {
/* Metode */
public void addArchive ( string $description )
public void addDataSource ( string $description )
public __construct ( string $path [, string $startTime [, int $step = 0 ]] )
public bool save ( void )
}

Cuprins

  • 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
rrdc_disconnect
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.

Descrierea

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.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

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.

Descrierea

public void RRDCreator::addDataSource ( string $description )

RRD can accept input from several data sources (DS), e.g incoming and outgoing traffic. This method adds data source by description. You need call this method for each data source.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

public RRDCreator::__construct ( string $path [, string $startTime [, int $step = 0 ]] )

Creates new RRDCreator instance.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

public bool RRDCreator::save ( void )

Saves the RRD database into file, which name is defined by RRDCreator::__construct().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

RRDCreator::__construct
RRDGraph
RRDCreator


The RRDGraph class

(PECL rrd >= 0.9.0)

Introducere

Class for exporting data from RRD database to image file.

Sinopsisul clasei

RRDGraph {
/* Metode */
public __construct ( string $path )
public array save ( void )
public array saveVerbose ( void )
public void setOptions ( array $options )
}

Cuprins

  • 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

Descrierea

public RRDGraph::__construct ( string $path )

Creates new RRDGraph instance. This instance is responsible for rendering the result of RRD database query into image.

Parametri

path

Full path for the newly created image.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

public array RRDGraph::save ( void )

Saves the result of RRD database query into image defined by RRDGraph::__construct().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public void RRDGraph::setOptions ( array $options )

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 RRDGraph::setOptions() example

<?php
$graphObj->setOptions(array(
    "--start" => "920804400",
    "--end" => 920808000,
    "--vertical-label" => "m/s",
    "DEF:myspeed=$rrdFile:speed:AVERAGE",
    "CDEF:realspeed=myspeed,1000,*",
    "LINE2:realspeed#FF0000"
));
?>

Example #2 Set multiple color options

<?php
$graphObj->setOptions(array(
    "--start" => "920804400",
    "--end" => 920808000,
    "--vertical-label" => "m/s",
    "--color=BACK#00000000",
    "--color=GRID#00000000",
    "--color=MGRID#00000000",
    "DEF:myspeed=$rrdFile:speed:AVERAGE",
    "CDEF:realspeed=myspeed,1000,*",
    "LINE2:realspeed#FF0000"
));
?>

Don't use key value syntax for same rrd option. It looks more readable, but it doesn't work.

<?php
$graphObj->setOptions(array(
    "--color" => "BACK#00000000",
    "--color" => "GRID#00000000",
    "--color" => "MGRID#00000000"
));
?>

In nature of php it's same as

<?php
$graphObj->setOptions(array(
    "--color" => "MGRID#00000000"
));
?>

RRDGraph::saveVerbose
RRDUpdater
RRDGraph


The RRDUpdater class

(PECL rrd >= 0.9.0)

Introducere

Class for updating RDD database file.

Sinopsisul clasei

RRDUpdater {
/* Metode */
public __construct ( string $path )
public bool update ( array $values [, string $time = time() ] )
}

Cuprins

  • 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

Descrierea

public RRDUpdater::__construct ( string $path )

Creates new RRDUpdater instance. This instance is responsible for updating the RRD database file.

Parametri

path

Filesystem path for RRD database file, which will be updated.

Valorile întoarse

Nu este întoarsa nici o valoare.

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Throws a Exception on error.

Exemple

Example #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

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Connections
    • Messages
    • Messaging operations
    • Publish/Subscribe and subscriptions to topics
    • Error handling
  • SAM Func?ii
    • 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
Introducere
Alte servicii


Introducere

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
Instalarea / configurarea
SAM


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SAM


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » 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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
Exemple
SAM


Exemple

Cuprins

  • Connections
  • Messages
  • Messaging operations
  • Publish/Subscribe and subscriptions to topics
  • Error handling
Constante predefinite
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.

Example #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'));
?>

Example #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'));
?>

Example #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));
?>

Exemple
Messages
Exemple


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.

Example #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:

Example #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:

Example #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.

Example #4 Retrieving a property from a message header

<?php
$myProperty = $msg->header->myPropertyName;
?>

Connections
Messaging operations
Exemple


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.

Example #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
Exemple


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.

Example #1 Creating a durable subscription to a topic

<?php

$subName = $conn->subscribe('topic://A');

if (!$subName) {
   echo "Subscribe failed";
} else {
   # Subscribe was OK
   // ...
}
?>

Example #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
   // ...
}
?>

Example #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";
}

?>

Example #4 Deleting a durable subscription to a topic

<?php

if (!$conn->unsubscribe($subName)) {
   echo "Unsubscribe failed";
}

?>

Messaging operations
Error handling
Exemple


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.

Example #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";
}
?>

Example #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 Func?ii
Exemple


SAM Func?ii

Clase predefinite

SAMConnection

Object representing a connection to a Messaging Server

Constructorul

  • new SAMConnection - construct a new connection object to allow connection to a messaging infrastructure.

Metode

  • 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

Proprieta?i

  • 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

Constructorul

  • new SAMMessage - construct a new message.

Proprieta?i

  • body - the body of the message.

  • header - the header properties of the message.

Cuprins

  • 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 Func?ii
SAMConnection::connect
SAM Func?ii
PHP Manual

SAMConnection::commit

(PECL sam >= 0.1.0)

SAMConnection::commit — Commits (completes) the current unit of work.

Descrierea

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.

Valorile întoarse

This method returns FALSE if an error occurs.

Exemple

Example #1 Committing the current unit of work

<?php
  if (!$conn->commit()) {
    // The commit failed!
    echo "Commit failed ($conn->errno) $conn->error";
  }
?>

A se vedea ?i

  • SAMConnection::rollback

SAM Func?ii
SAMConnection::connect
SAM Func?ii


Establishes a connection to a Messaging Server

SAMConnection::commit
SAMConnection::__construct
SAM Func?ii
PHP Manual

SAMConnection::connect

(PECL sam >= 0.1.0)

SAMConnection::connect — Establishes a connection to a Messaging Server

Descrierea

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.

Parametri

Valorile întoarse

This method returns FALSE if an error occurs.

Exemple

Example #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'));

?>

Example #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));

?>

Example #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'));

?>

A se vedea ?i

  • SAMConnection::isConnected
  • SAMConnection::disconnect

SAMConnection::commit
SAMConnection::__construct
SAM Func?ii


Creates a new connection to a Messaging Server

SAMConnection::connect
SAMConnection::disconnect
SAM Func?ii
PHP Manual

SAMConnection::__construct

(PECL sam >= 0.1.0)

SAMConnection::__construct — Creates a new connection to a Messaging Server

Descrierea

SAMConnection::__construct ( void )

Creates a new SAMConnection object.

Exemple

Example #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 Func?ii


Disconnects from a Messaging Server

SAMConnection::__construct
SAMConnection::errno
SAM Func?ii
PHP Manual

SAMConnection::disconnect

(PECL sam >= 0.1.0)

SAMConnection::disconnect — Disconnects from a Messaging Server

Descrierea

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Disconnecting from a Messaging Server

<?php

$conn->disconnect();

?>

A se vedea ?i

  • SAMConnection::isConnected
  • SAMConnection::connect

SAMConnection::__construct
SAMConnection::errno
SAM Func?ii


Contains the unique numeric error code of the last executed SAM operation.

SAMConnection::disconnect
SAMConnection::error
SAM Func?ii
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.

Valorile întoarse

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.

Exemple

Example #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";
}
?>

A se vedea ?i

  • SAMConnection::error

SAMConnection::disconnect
SAMConnection::error
SAM Func?ii


Contains the text description of the last failed SAM operation.

SAMConnection::errno
SAMConnection::isConnected
SAM Func?ii
PHP Manual

SAMConnection::error

(PECL sam >= 0.1.0)

SAMConnection::error — Contains the text description of the last failed SAM operation.

Descrierea

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.

Valorile întoarse

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.

Exemple

Example #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";
}
?>

A se vedea ?i

  • SAMConnection::errno

SAMConnection::errno
SAMConnection::isConnected
SAM Func?ii


Queries whether a connection is established to a Messaging Server

SAMConnection::error
SAMConnection::peek
SAM Func?ii
PHP Manual

SAMConnection::isConnected

(PECL sam >= 0.1.0)

SAMConnection::isConnected — Queries whether a connection is established to a Messaging Server

Descrierea

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.

Valorile întoarse

This method returns TRUE if the SAMConnection object is successfully connected to a Messaging server or FALSE otherwise.

Exemple

Example #1 Checking whether there us a connection to a Messaging Server

<?php

if ($conn->isConnected()) {
  echo 'Connection is active.';
} else {
  echo 'No active connection!';
}

?>

A se vedea ?i

  • SAMConnection::disconnect
  • SAMConnection::connect

SAMConnection::error
SAMConnection::peek
SAM Func?ii


Read a message from a queue without removing it from the queue.

SAMConnection::isConnected
SAMConnection::peekAll
SAM Func?ii
PHP Manual

SAMConnection::peek

(PECL sam >= 0.1.0)

SAMConnection::peek — Read a message from a queue without removing it from the queue.

Descrierea

SAMMessage SAMConnection::peek ( string $target [, array $properties ] )

Parametri

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.

Valorile întoarse

This method returns a SAMMessage object or FALSE if an error occurs.

Exemple

Example #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";
}
?>

Example #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));

?>

A se vedea ?i

  • SAMConnection::peekAll

SAMConnection::isConnected
SAMConnection::peekAll
SAM Func?ii


Read one or more messages from a queue without removing it from the queue.

SAMConnection::peek
SAMConnection::receive
SAM Func?ii
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.

Descrierea

array SAMConnection::peekAll ( string $target [, array $properties ] )

Parametri

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.

Valorile întoarse

This method returns an array of SAMMessage objects or FALSE if an error occurs.

Exemple

Example #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";
}
?>

Example #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";
   }

?>

A se vedea ?i

  • SAMConnection::peek

SAMConnection::peek
SAMConnection::receive
SAM Func?ii


Receive a message from a queue or subscription.

SAMConnection::peekAll
SAMConnection::remove
SAM Func?ii
PHP Manual

SAMConnection::receive

(PECL sam >= 0.1.0)

SAMConnection::receive — Receive a message from a queue or subscription.

Descrierea

SAMMessage SAMConnection::receive ( string $target [, array $properties ] )

Parametri

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.

Valorile întoarse

This method returns a SAMMessage object or FALSE if an error occurs.

Exemple

Example #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";
}
?>

Example #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));

?>

Example #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.

A se vedea ?i

  • SAMConnection::send

SAMConnection::peekAll
SAMConnection::remove
SAM Func?ii


Remove a message from a queue.

SAMConnection::receive
SAMConnection::rollback
SAM Func?ii
PHP Manual

SAMConnection::remove

(PECL sam >= 0.1.0)

SAMConnection::remove — Remove a message from a queue.

Descrierea

SAMMessage SAMConnection::remove ( string $target [, array $properties ] )

Removes a message from a queue.

Parametri

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.

Valorile întoarse

This method returns FALSE if an error occurs.

Exemple

Example #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 Func?ii


Cancels (rolls back) an in-flight unit of work.

SAMConnection::remove
SAMConnection::send
SAM Func?ii
PHP Manual

SAMConnection::rollback

(PECL sam >= 0.1.0)

SAMConnection::rollback — Cancels (rolls back) an in-flight unit of work.

Descrierea

bool SAMConnection::rollback ( void )

Rolls back an in-flight unit of work.

Valorile întoarse

This method returns FALSE if an error occurs.

Exemple

Example #1 Cancelling an in-flight unit of work

<?php
if (!$conn->rollback()) {
  // The rollback failed!
  echo "Rollback failed ($conn->errno) $conn->error";
}
?>

A se vedea ?i

  • SAMConnection::commit

SAMConnection::remove
SAMConnection::send
SAM Func?ii


Send a message to a queue or publish an item to a topic.

SAMConnection::rollback
SAMConnection::setDebug
SAM Func?ii
PHP Manual

SAMConnection::send

(PECL sam >= 0.1.0)

SAMConnection::send — Send a message to a queue or publish an item to a topic.

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Nota:

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.

Exemple

Example #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";
}

?>

Example #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";
}
?>

Example #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));
}
?>

A se vedea ?i

  • SAMConnection::receive

SAMConnection::rollback
SAMConnection::setDebug
SAM Func?ii


Turn on or off additional debugging output.

SAMConnection::send
SAMConnection::subscribe
SAM Func?ii
PHP Manual

SAMConnection::setDebug

(PECL sam >= 1.1.0)

SAMConnection::setDebug — Turn on or off additional debugging output.

Descrierea

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 )

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Turn on debugging output

<?php
$conn->setdebug(TRUE);
?>

Example #2 Turn off debugging output

<?php
$conn->setdebug(FALSE);
?>

SAMConnection::send
SAMConnection::subscribe
SAM Func?ii


Create a subscription to a specified topic.

SAMConnection::setDebug
SAMConnection::unsubscribe
SAM Func?ii
PHP Manual

SAMConnection::subscribe

(PECL sam >= 0.1.0)

SAMConnection::subscribe — Create a subscription to a specified topic.

Descrierea

string SAMConnection::subscribe ( string $targetTopic )

The "subscribe" method is used to create a new subscription to a specified topic.

Parametri

targetTopic

The identity of the topic (topic://topicname) to subscribe to.

Valorile întoarse

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.

Exemple

Example #1 Subscribe to a topic

<?php
$subid = $conn->subscribe('topic://A');
if (!$subid) {
  // The subscribe failed!
  echo "Subscribe failed ($conn->errno) $conn->error";
}
?>

A se vedea ?i

  • SAMConnection::unsubscribe

SAMConnection::setDebug
SAMConnection::unsubscribe
SAM Func?ii


Cancel a subscription to a specified topic.

SAMConnection::subscribe
SAMMessage::body
SAM Func?ii
PHP Manual

SAMConnection::unsubscribe

(PECL sam >= 0.1.0)

SAMConnection::unsubscribe — Cancel a subscription to a specified topic.

Descrierea

bool SAMConnection::unsubscribe ( string $subscriptionId [, string $targetTopic ] )

The "unsubscribe" method is used to delete an existing subscription to a specified topic.

Parametri

subscriptionId

The identifier of an existing subscription as returned by a call to the subscribe method.

Valorile întoarse

This method returns FALSE if an error occurs.

Exemple

Example #1 Delete a subscription

<?php
if (!$conn->unsubscribe($subid)) {
    // The unsubscribe failed!
    echo "Unsubscribe failed ($conn->errno) $conn->error";
}
?>

A se vedea ?i

  • SAMConnection::subscribe

SAMConnection::subscribe
SAMMessage::body
SAM Func?ii


The body of the message.

SAMConnection::unsubscribe
SAMMessage::__construct
SAM Func?ii
PHP Manual

SAMMessage::body

(PECL sam >= 0.1.0)

SAMMessage::body — The body of the message.

Descrierea

string $SAMMessage->body;

The "body" property contains the actual body of the message. It may not always be set.

Exemple

Example #1 Setting a text string into the body of a message

<?php
$msg = new SAMMessage();
$msg->body = 'This is a simple message';

?>

A se vedea ?i

  • SAMMessage::header

SAMConnection::unsubscribe
SAMMessage::__construct
SAM Func?ii


Creates a new Message object

SAMMessage::body
SAMMessage::header
SAM Func?ii
PHP Manual

SAMMessage::__construct

(PECL sam >= 0.1.0)

SAMMessage::__construct — Creates a new Message object

Descrierea

SAMMessage::__construct ([ mixed $body ] )

Creates a new SAMMessage object optionally specifying a message body.

Parametri

body

The optional body for the message.

Exemple

Example #1 Creating a message

<?php

$msg = new SAMMessage();

?>

Example #2 Creating a message with a simple text payload

<?php

$msg = new SAMMessage('This is a simple text message');

?>

SAMMessage::body
SAMMessage::header
SAM Func?ii


The header properties of the message.

SAMMessage::__construct
SNMP
SAM Func?ii
PHP Manual

SAMMessage::header

(PECL sam >= 0.1.0)

SAMMessage::header — The header properties of the message.

Descrierea

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:

Example #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:

Example #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.

Exemple

Example #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);
?>

Example #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;

?>

A se vedea ?i

  • SAMMessage::body

SAMMessage::__construct
SNMP
SAM Func?ii


SNMP

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii SNMP
    • 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 — Set the OID output format
    • 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
Introducere
Alte servicii


Introducere

Extensia SNMP ofera un instrumentar foarte simplu ?i u?or utilizabil pentru gestiunea echipamentelor la distan?a print protocolul ”Simple Network Management Protocol”.

Deoarece acesta este doar un înveli? pentru biblioteca de nivel mai jos Net-SNMP (sau UCD-SNMP pe sisteme mai vechi), toate conceptele de baza sunt la fel, iar func?iile PHP î?i schimba comportamentul în dependen?a de fi?ierele de configurare Net-SNMP ?i variabilele de mediu.

Începând cu PHP 5.4 este disponibil un API OO.

Informa?ii suplimentare despre Net-SNMP pot fi gasite la » http://www.net-snmp.org/

SNMP
Instalarea / configurarea
SNMP


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SNMP


Necesita?i

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.

Beginning with PHP 5.4.0 Net-SNMP version 5.3+ is required for Unix installations and Net-SNMP version 5.4+ for Windows.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

PHP 5.3.0, 5.3.1 and 5.3.2 do not have SNMP support. SNMP support has been restored in PHP 5.3.3.

The Windows distribution of Net-SNMP contains support files for SNMP in the mibs directory. This directory should added to Windows' environment variables, as MIBDIRS, with the value being the full path to the mibs directory: e.g. c:\usr\mibs.

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
Tipurile resurselor
Func?ii SNMP
SNMP


Func?ii SNMP

Cuprins

  • 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 — Set the OID output format
  • 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
Constante predefinite
snmp_get_quick_print
SNMP


Fetches the current value of the UCD library's quick_print setting

Func?ii SNMP
snmp_get_valueretrieval
Func?ii SNMP
PHP Manual

snmp_get_quick_print

(PHP 4, PHP 5, PHP 7)

snmp_get_quick_print — Fetches the current value of the UCD library's quick_print setting

Descrierea

bool snmp_get_quick_print ( void )

Returns the current value stored in the UCD Library for quick_print. quick_print is off by default.

Valorile întoarse

Returns TRUE if quick_print is on, FALSE otherwise.

Exemple

Example #1 snmp_get_quick_print() example

<?php
$quickprint = snmp_get_quick_print();
?>

A se vedea ?i

  • snmp_set_quick_print() - Set the value of quick_print within the UCD SNMP library for a full description of what quick_print does.

Func?ii SNMP
snmp_get_valueretrieval
Func?ii SNMP


Return the method how the SNMP values will be returned

snmp_get_quick_print
snmp_read_mib
Func?ii SNMP
PHP Manual

snmp_get_valueretrieval

(PHP 4 >= 4.3.3, PHP 5, PHP 7)

snmp_get_valueretrieval — Return the method how the SNMP values will be returned

Descrierea

int snmp_get_valueretrieval ( void )

Valorile întoarse

OR-ed combitantion of constants ( SNMP_VALUE_LIBRARY or SNMP_VALUE_PLAIN ) with possible SNMP_VALUE_OBJECT set.

Exemple

Example #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;
 }
?>

A se vedea ?i

  • snmp_set_valueretrieval() - Specify the method how the SNMP values will be returned
  • Constante predefinite

snmp_get_quick_print
snmp_read_mib
Func?ii SNMP


Reads and parses a MIB file into the active MIB tree

snmp_get_valueretrieval
snmp_set_enum_print
Func?ii SNMP
PHP Manual

snmp_read_mib

(PHP 5, PHP 7)

snmp_read_mib — Reads and parses a MIB file into the active MIB tree

Descrierea

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.

Parametri

filename

The filename of the MIB.

Exemple

Example #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
Func?ii SNMP


Return all values that are enums with their enum value instead of the raw integer

snmp_read_mib
snmp_set_oid_numeric_print
Func?ii SNMP
PHP Manual

snmp_set_enum_print

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

snmp_set_enum_print — Return all values that are enums with their enum value instead of the raw integer

Descrierea

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.

Parametri

enum_print

As the value is interpreted as boolean by the Net-SNMP library, it can only be "0" or "1".

Exemple

Example #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

Note

Nota:

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
Func?ii SNMP


Set the OID output format

snmp_set_enum_print
snmp_set_oid_output_format
Func?ii SNMP
PHP Manual

snmp_set_oid_numeric_print

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

snmp_set_oid_numeric_print — Set the OID output format

Descrierea

void snmp_set_oid_numeric_print ( int $oid_format )

Aceasta func?ie este pseudonim pentru: snmp_set_oid_output_format().

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | Since PHP 5.2.0.

A se vedea ?i

  • snmp_set_oid_output_format() - Set the OID output format

snmp_set_enum_print
snmp_set_oid_output_format
Func?ii SNMP


Set the OID output format

snmp_set_oid_numeric_print
snmp_set_quick_print
Func?ii SNMP
PHP Manual

snmp_set_oid_output_format

(PHP 5 >= 5.2.0, PHP 7)

snmp_set_oid_output_format — Set the OID output format

Descrierea

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.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Nota:

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.

Exemple

Example #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
Func?ii SNMP


Set the value of quick_print within the UCD SNMP library

snmp_set_oid_output_format
snmp_set_valueretrieval
Func?ii SNMP
PHP Manual

snmp_set_quick_print

(PHP 4, PHP 5, PHP 7)

snmp_set_quick_print — Set the value of quick_print within the UCD SNMP library

Descrierea

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.

Parametri

quick_print

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Setting quick_print is often used when using the information returned rather than displaying it.

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

'Timeticks: (0) 0:00:00.00'
'0:00:00.00'

A se vedea ?i

  • snmp_get_quick_print() - Fetches the current value of the UCD library's quick_print setting

snmp_set_oid_output_format
snmp_set_valueretrieval
Func?ii SNMP


Specify the method how the SNMP values will be returned

snmp_set_quick_print
snmp2_get
Func?ii SNMP
PHP Manual

snmp_set_valueretrieval

(PHP 4 >= 4.3.3, PHP 5, PHP 7)

snmp_set_valueretrieval — Specify the method how the SNMP values will be returned

Descrierea

bool snmp_set_valueretrieval ( int $method = SNMP_VALUE_LIBRARY )

Parametri

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.

Exemple

Example #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
 // )

?>

Istoricul schimbarilor

Versiune | Descriere
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.

A se vedea ?i

  • snmp_get_valueretrieval() - Return the method how the SNMP values will be returned
  • Constante predefinite

snmp_set_quick_print
snmp2_get
Func?ii SNMP


Fetch an SNMP object

snmp_set_valueretrieval
snmp2_getnext
Func?ii SNMP
PHP Manual

snmp2_get

(PHP 5 >= 5.2.0, PHP 7)

snmp2_get — Fetch an SNMP object

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns SNMP object value on success or FALSE on error.

Exemple

Example #1 Using snmp2_get()

<?php
$syscontact = snmp2_get("127.0.0.1", "public", "system.SysContact.0");
?>

A se vedea ?i

  • snmp2_set() - Set the value of an SNMP object

snmp_set_valueretrieval
snmp2_getnext
Func?ii SNMP


Fetch the SNMP object which follows the given object id

snmp2_get
snmp2_real_walk
Func?ii SNMP
PHP Manual

snmp2_getnext

(PHP >= 5.2.0)

snmp2_getnext — Fetch the SNMP object which follows the given object id

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns SNMP object value on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Exemple

Example #1 Using snmp2_get_next()

<?php
$nameOfSecondInterface = snmp2_get_next('localhost', 'public', 'IF-MIB::ifName.1';
?>

A se vedea ?i

  • snmp2_get() - Fetch an SNMP object
  • snmp2_walk() - Fetch all the SNMP objects from an agent

snmp2_get
snmp2_real_walk
Func?ii SNMP


Return all objects including their respective object ID within the specified one

snmp2_getnext
snmp2_set
Func?ii SNMP
PHP Manual

snmp2_real_walk

(PHP >= 5.2.0)

snmp2_real_walk — Return all objects including their respective object ID within the specified one

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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
    )

A se vedea ?i

  • snmp2_walk() - Fetch all the SNMP objects from an agent

snmp2_getnext
snmp2_set
Func?ii SNMP


Set the value of an SNMP object

snmp2_real_walk
snmp2_walk
Func?ii SNMP
PHP Manual

snmp2_set

(PHP >= 5.2.0)

snmp2_set — Set the value of an SNMP object

Descrierea

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.

Parametri

host

The hostname of the SNMP agent (server).

community

The write community.

object_id

The SNMP object id.

type

Regulile MIB definesc tipul fiecarui identificator al obiectului. El trebuie specificat printr-un singur caracter din lista ce urmeaza.

types
= Tipul este extras din MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

Daca a fost definit OPAQUE_SPECIAL_TYPES la compilarea bibliotecii SNMP, urmatoarele de asemenea sunt valide:

types
U | int64 fara semn
I | int64 cu semn
F | float
D | double

Majoritatea acestora vor utiliza tipul cel mai evident în coresponden?a cu ASN.1. 's', 'x', 'd' ?i 'b' sunt toate diferite modalita?i de a specifica o valoare OCTET STRING, iar tipul 'u' fara semn este utilizat ?i pentru a men?ine valori Gauge32.

Daca fi?ierele MIB sunt încarcate în arborele MIB cu "snmp_read_mib" sau specificându-le în configura?ia libsnmp, '=' poate fi utilizat în calitate de parametru type pentru toate identificatoarele obiectelor, deoarece tipul poate fi apoi citit automat din MIB.

Atrage?i aten?ia ca exista doua modalita?i de a stabili o variabila de tip BITS ca de exemplu "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Utilizând tipul "b" ?i o lista de numere-bi?i. Aceasta metoda nu este recomandata deoarece o interpelare GET pentru acela?i OID va întoarce de ex. 0xF8.
  • Utilizând tipul "x" ?i un numar hexadecimal, dar fara(!) prefixul obi?nuit "0x".

Vede?i sec?iunea cu exemple pentru mai multe detalii.

value

The new value.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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".

Exemple

Example #1 Using snmp2_set()

<?php
  snmp2_set("localhost", "public", "IF-MIB::ifAlias.3", "s", "foo");
?>

Example #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');
?>

A se vedea ?i

  • snmp2_get() - Fetch an SNMP object

snmp2_real_walk
snmp2_walk
Func?ii SNMP


Fetch all the SNMP objects from an agent

snmp2_set
snmp3_get
Func?ii SNMP
PHP Manual

snmp2_walk

(PHP >= 5.2.0)

snmp2_walk — Fetch all the SNMP objects from an agent

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns an array of SNMP object values starting from the object_id as root or FALSE on error.

Exemple

Example #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

A se vedea ?i

  • snmp2_real_walk() - Return all objects including their respective object ID within the specified one

snmp2_set
snmp3_get
Func?ii SNMP


Fetch an SNMP object

snmp2_walk
snmp3_getnext
Func?ii SNMP
PHP Manual

snmp3_get

(PHP 4, PHP 5, PHP 7)

snmp3_get — Fetch an SNMP object

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns SNMP object value on success or FALSE on error.

Exemple

Example #1 Using snmp3_get()

<?php
$nameOfSecondInterface = snmp3_get('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName.2');
?>

A se vedea ?i

  • snmp3_set() - Set the value of an SNMP object

snmp2_walk
snmp3_getnext
Func?ii SNMP


Fetch the SNMP object which follows the given object id

snmp3_get
snmp3_real_walk
Func?ii SNMP
PHP Manual

snmp3_getnext

(PHP 5, PHP 7)

snmp3_getnext — Fetch the SNMP object which follows the given object id

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns SNMP object value on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Exemple

Example #1 Using snmp3_getnext()

<?php
$nameOfSecondInterface = snmp3_getnext('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName.1');
?>

A se vedea ?i

  • snmp3_get() - Fetch an SNMP object
  • snmp3_walk() - Fetch all the SNMP objects from an agent

snmp3_get
snmp3_real_walk
Func?ii SNMP


Return all objects including their respective object ID within the specified one

snmp3_getnext
snmp3_set
Func?ii SNMP
PHP Manual

snmp3_real_walk

(PHP 4, PHP 5, PHP 7)

snmp3_real_walk — Return all objects including their respective object ID within the specified one

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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',
)

A se vedea ?i

  • snmpwalk() - Fetch all the SNMP objects from an agent

snmp3_getnext
snmp3_set
Func?ii SNMP


Set the value of an SNMP object

snmp3_real_walk
snmp3_walk
Func?ii SNMP
PHP Manual

snmp3_set

(PHP 4, PHP 5, PHP 7)

snmp3_set — Set the value of an SNMP object

Descrierea

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.

Parametri

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

Regulile MIB definesc tipul fiecarui identificator al obiectului. El trebuie specificat printr-un singur caracter din lista ce urmeaza.

types
= Tipul este extras din MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

Daca a fost definit OPAQUE_SPECIAL_TYPES la compilarea bibliotecii SNMP, urmatoarele de asemenea sunt valide:

types
U | int64 fara semn
I | int64 cu semn
F | float
D | double

Majoritatea acestora vor utiliza tipul cel mai evident în coresponden?a cu ASN.1. 's', 'x', 'd' ?i 'b' sunt toate diferite modalita?i de a specifica o valoare OCTET STRING, iar tipul 'u' fara semn este utilizat ?i pentru a men?ine valori Gauge32.

Daca fi?ierele MIB sunt încarcate în arborele MIB cu "snmp_read_mib" sau specificându-le în configura?ia libsnmp, '=' poate fi utilizat în calitate de parametru type pentru toate identificatoarele obiectelor, deoarece tipul poate fi apoi citit automat din MIB.

Atrage?i aten?ia ca exista doua modalita?i de a stabili o variabila de tip BITS ca de exemplu "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Utilizând tipul "b" ?i o lista de numere-bi?i. Aceasta metoda nu este recomandata deoarece o interpelare GET pentru acela?i OID va întoarce de ex. 0xF8.
  • Utilizând tipul "x" ?i un numar hexadecimal, dar fara(!) prefixul obi?nuit "0x".

Vede?i sec?iunea cu exemple pentru mai multe detalii.

value

The new value

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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".

Exemple

Example #1 Using snmp3_set()

<?php
  snmp3_set('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifAlias.3', 's', "foo");
?>

Example #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
Func?ii SNMP


Fetch all the SNMP objects from an agent

snmp3_set
snmpget
Func?ii SNMP
PHP Manual

snmp3_walk

(PHP 4, PHP 5, PHP 7)

snmp3_walk — Fetch all the SNMP objects from an agent

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns an array of SNMP object values starting from the object_id as root or FALSE on error.

Exemple

Example #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',
)

A se vedea ?i

  • snmp3_real_walk() - Return all objects including their respective object ID within the specified one

snmp3_set
snmpget
Func?ii SNMP


Fetch an SNMP object

snmp3_walk
snmpgetnext
Func?ii SNMP
PHP Manual

snmpget

(PHP 4, PHP 5, PHP 7)

snmpget — Fetch an SNMP object

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns SNMP object value on success or FALSE on error.

Exemple

Example #1 Using snmpget()

<?php
$syscontact = snmpget("127.0.0.1", "public", "system.SysContact.0");
?>

A se vedea ?i

  • snmpset() - Set the value of an SNMP object

snmp3_walk
snmpgetnext
Func?ii SNMP


Fetch the SNMP object which follows the given object id

snmpget
snmprealwalk
Func?ii SNMP
PHP Manual

snmpgetnext

(PHP 5, PHP 7)

snmpgetnext — Fetch the SNMP object which follows the given object id

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns SNMP object value on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Exemple

Example #1 Using snmpgetnext()

<?php
$nameOfSecondInterface = snmpgetnetxt('localhost', 'public', 'IF-MIB::ifName.1';
?>

A se vedea ?i

  • snmpget() - Fetch an SNMP object
  • snmpwalk() - Fetch all the SNMP objects from an agent

snmpget
snmprealwalk
Func?ii SNMP


Return all objects including their respective object ID within the specified one

snmpgetnext
snmpset
Func?ii SNMP
PHP Manual

snmprealwalk

(PHP 4, PHP 5, PHP 7)

snmprealwalk — Return all objects including their respective object ID within the specified one

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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
    )

A se vedea ?i

  • snmpwalk() - Fetch all the SNMP objects from an agent

snmpgetnext
snmpset
Func?ii SNMP


Set the value of an SNMP object

snmprealwalk
snmpwalk
Func?ii SNMP
PHP Manual

snmpset

(PHP 4, PHP 5, PHP 7)

snmpset — Set the value of an SNMP object

Descrierea

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.

Parametri

host

The hostname of the SNMP agent (server).

community

The write community.

object_id

The SNMP object id.

type

Regulile MIB definesc tipul fiecarui identificator al obiectului. El trebuie specificat printr-un singur caracter din lista ce urmeaza.

types
= Tipul este extras din MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

Daca a fost definit OPAQUE_SPECIAL_TYPES la compilarea bibliotecii SNMP, urmatoarele de asemenea sunt valide:

types
U | int64 fara semn
I | int64 cu semn
F | float
D | double

Majoritatea acestora vor utiliza tipul cel mai evident în coresponden?a cu ASN.1. 's', 'x', 'd' ?i 'b' sunt toate diferite modalita?i de a specifica o valoare OCTET STRING, iar tipul 'u' fara semn este utilizat ?i pentru a men?ine valori Gauge32.

Daca fi?ierele MIB sunt încarcate în arborele MIB cu "snmp_read_mib" sau specificându-le în configura?ia libsnmp, '=' poate fi utilizat în calitate de parametru type pentru toate identificatoarele obiectelor, deoarece tipul poate fi apoi citit automat din MIB.

Atrage?i aten?ia ca exista doua modalita?i de a stabili o variabila de tip BITS ca de exemplu "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Utilizând tipul "b" ?i o lista de numere-bi?i. Aceasta metoda nu este recomandata deoarece o interpelare GET pentru acela?i OID va întoarce de ex. 0xF8.
  • Utilizând tipul "x" ?i un numar hexadecimal, dar fara(!) prefixul obi?nuit "0x".

Vede?i sec?iunea cu exemple pentru mai multe detalii.

value

The new value.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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".

Exemple

Example #1 Using snmpset()

<?php
  snmpset("localhost", "public", "IF-MIB::ifAlias.3", "s", "foo");
?>

Example #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');
?>

A se vedea ?i

  • snmpget() - Fetch an SNMP object

snmprealwalk
snmpwalk
Func?ii SNMP


Fetch all the SNMP objects from an agent

snmpset
snmpwalkoid
Func?ii SNMP
PHP Manual

snmpwalk

(PHP 4, PHP 5, PHP 7)

snmpwalk — Fetch all the SNMP objects from an agent

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns an array of SNMP object values starting from the object_id as root or FALSE on error.

Exemple

Example #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

A se vedea ?i

  • snmprealwalk() - Return all objects including their respective object ID within the specified one

snmpset
snmpwalkoid
Func?ii SNMP


Query for a tree of information about a network entity

snmpwalk
SNMP
Func?ii SNMP
PHP Manual

snmpwalkoid

(PHP 4, PHP 5, PHP 7)

snmpwalkoid — Query for a tree of information about a network entity

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns an associative array with object ids and their respective object value starting from the object_id as root or FALSE on error.

Exemple

Example #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

A se vedea ?i

  • snmpwalk() - Fetch all the SNMP objects from an agent

snmpwalk
SNMP
Func?ii SNMP


The SNMP class

(PHP 5 >= 5.4.0, PHP 7)

Introducere

Represents SNMP session.

Sinopsisul clasei

SNMP {
/* Proprieta?i */
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 ;
/* Metode */
public __construct ( int $version , string $hostname , string $community [, int $timeout = 1000000 [, int $retries = 5 ]] )
public bool close ( void )
public mixed get ( mixed $object_id [, bool $preserve_keys = false ] )
public int getErrno ( void )
public string getError ( void )
public mixed getnext ( mixed $object_id )
public bool set ( mixed $object_id , mixed $type , mixed $value )
public bool setSecurity ( string $sec_level [, string $auth_protocol = [, string $auth_passphrase = [, string $priv_protocol = [, string $priv_passphrase = [, string $contextName = [, string $contextEngineID = ]]]]]] )
public array walk ( string $object_id [, bool $suffix_as_key = FALSE [, int $max_repetitions [, int $non_repeaters ]]] )
/* Constante */
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 ;
}

Proprieta?i

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

Constante predefinite

SNMP Error Types

SNMP::ERRNO_NOERROR

No SNMP-specific error occurred.

SNMP::ERRNO_GENERIC

A generic SNMP error occurred.

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

Cuprins

  • 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, PHP 7)

SNMP::close — Close SNMP session

Descrierea

public bool SNMP::close ( void )

Frees previously allocated SNMP session object.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 SNMP::close() example

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  # ...
  # get, walk, etc goes here
  # ...
  $session->close();
?>

A se vedea ?i

  • 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, PHP 7)

SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent

Descrierea

public SNMP::__construct ( int $version , string $hostname , string $community [, int $timeout = 1000000 [, int $retries = 5 ]] )

The function description goes here.

Parametri

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.

Valorile întoarse

Returns SNMP object representing remote SNMP agent.

Erori/Excep?ii

SNMP::__construct() throws an exception when parameters count or types are wrong or unknown SNMP protocol version specified.

Exemple

Example #1 Fetching sysLocation

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $sysdescr = $session->get("sysDescr.0");
  echo "$sysdescr\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

STRING: Test server

A se vedea ?i

  • 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, PHP 7)

SNMP::get — Fetch an SNMP object

Descrierea

public mixed SNMP::get ( mixed $object_id [, bool $preserve_keys = false ] )

Fetch an SNMP object specified in object_id using GET query.

Parametri

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.

Valorile întoarse

Returns SNMP objects requested as string or array depending on object_id type or FALSE on error.

Erori/Excep?ii

Aceasta metoda nu emite careva excep?ii în mod implicit. Pentru a activa emiterea unei excep?ii SNMPException când au loc erori în biblioteca trebuie stabilita o valoare corespunzatoare a parametrului clasei SNMP exceptions_enabled. Vede?i explica?ia SNMP::$exceptions_enabled pentru mai multe detalii.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

STRING: Test server
Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
)

Example #2 Multiple 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();

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
    [SNMPv2-MIB::sysName.0] => STRING: myhost.nodomain
)

A se vedea ?i

  • 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, PHP 7)

SNMP::getErrno — Get last error code

Descrierea

public int SNMP::getErrno ( void )

Returns error code from last SNMP request.

Valorile întoarse

Returns one of SNMP error code values described in constants chapter.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

A se vedea ?i

  • 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, PHP 7)

SNMP::getError — Get last error message

Descrierea

public string SNMP::getError ( void )

Returns string with error from last SNMP request.

Valorile întoarse

String describing error from last SNMP request.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

bool(false)
string(26) "No response from 127.0.0.1"

A se vedea ?i

  • 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, PHP 7)

SNMP::getnext — Fetch an SNMP object which follows the given object id

Descrierea

public mixed SNMP::getnext ( mixed $object_id )

Fetch an SNMP object that follows specified object_id.

Parametri

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

Valorile întoarse

Returns SNMP objects requested as string or array depending on object_id type or FALSE on error.

Erori/Excep?ii

Aceasta metoda nu emite careva excep?ii în mod implicit. Pentru a activa emiterea unei excep?ii SNMPException când au loc erori în biblioteca trebuie stabilita o valoare corespunzatoare a parametrului clasei SNMP exceptions_enabled. Vede?i explica?ia SNMP::$exceptions_enabled pentru mai multe detalii.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
Array
(
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
)

Example #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();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
    [SNMPv2-MIB::sysLocation.0] => STRING: Nowhere
)

A se vedea ?i

  • 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, PHP 7)

SNMP::set — Set the value of an SNMP object

Descrierea

public 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.

Parametri

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

Regulile MIB definesc tipul fiecarui identificator al obiectului. El trebuie specificat printr-un singur caracter din lista ce urmeaza.

types
= Tipul este extras din MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

Daca a fost definit OPAQUE_SPECIAL_TYPES la compilarea bibliotecii SNMP, urmatoarele de asemenea sunt valide:

types
U | int64 fara semn
I | int64 cu semn
F | float
D | double

Majoritatea acestora vor utiliza tipul cel mai evident în coresponden?a cu ASN.1. 's', 'x', 'd' ?i 'b' sunt toate diferite modalita?i de a specifica o valoare OCTET STRING, iar tipul 'u' fara semn este utilizat ?i pentru a men?ine valori Gauge32.

Daca fi?ierele MIB sunt încarcate în arborele MIB cu "snmp_read_mib" sau specificându-le în configura?ia libsnmp, '=' poate fi utilizat în calitate de parametru type pentru toate identificatoarele obiectelor, deoarece tipul poate fi apoi citit automat din MIB.

Atrage?i aten?ia ca exista doua modalita?i de a stabili o variabila de tip BITS ca de exemplu "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Utilizând tipul "b" ?i o lista de numere-bi?i. Aceasta metoda nu este recomandata deoarece o interpelare GET pentru acela?i OID va întoarce de ex. 0xF8.
  • Utilizând tipul "x" ?i un numar hexadecimal, dar fara(!) prefixul obi?nuit "0x".

Vede?i sec?iunea cu exemple pentru mai multe detalii.

value

The new value.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Aceasta metoda nu emite careva excep?ii în mod implicit. Pentru a activa emiterea unei excep?ii SNMPException când au loc erori în biblioteca trebuie stabilita o valoare corespunzatoare a parametrului clasei SNMP exceptions_enabled. Vede?i explica?ia SNMP::$exceptions_enabled pentru mai multe detalii.

Exemple

Example #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");
?>

Example #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"));
?>

Example #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');
?>

A se vedea ?i

  • 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, PHP 7)

SNMP::setSecurity — Configures security-related SNMPv3 session parameters

Descrierea

public 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

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');
?>

A se vedea ?i

  • 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, PHP 7)

SNMP::walk — Fetch SNMP object subtree

Descrierea

public 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.

Parametri

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.

Valorile întoarse

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.

Erori/Excep?ii

Aceasta metoda nu emite careva excep?ii în mod implicit. Pentru a activa emiterea unei excep?ii SNMPException când au loc erori în biblioteca trebuie stabilita o valoare corespunzatoare a parametrului clasei SNMP exceptions_enabled. Vede?i explica?ia SNMP::$exceptions_enabled pentru mai multe detalii.

Exemple

Example #1 SNMP::walk() example

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $fulltree = $session->walk(".");
  print_r($fulltree);
  $session->close();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
    ...
)

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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)
)

A se vedea ?i

  • SNMP::getErrno() - Get last error code
  • SNMP::getError() - Get last error message
SNMP::setSecurity
SNMPException
SNMP


The SNMPException class

(PHP 5 >= 5.4.0, PHP 7)

Introducere

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.

Sinopsisul clasei

SNMPException extends RuntimeException {
/* Proprieta?i */
protected string $code ;
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Proprieta?i

code

SNMPlibrary error code. Use Exception::getCode() to access it.

SNMP::walk
Sockets
SNMP


Sockets

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Socket Errors
  • Func?ii Socket
    • 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_cmsg_space — Calculate message buffer size
    • 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_getopt — Pseudonim pentru socket_get_option
    • 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_import_stream — Import a stream
    • 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_recvmsg — Read a message
    • 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_sendmsg — Send a message
    • 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_setopt — Pseudonim pentru socket_set_option
    • 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
Introducere
Alte servicii


Introducere

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
Instalarea / configurarea
Sockets


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Sockets


Instalarea

Func?iile socket descrise aici fac parte dintr-o extensie PHP ce trebuie activata la momentul compilarii adaugând op?iunea --enable-sockets la configure.

Nota: Sus?inerea IPv6 a fost adaugata în PHP 5.0.0.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

socket_accept(),
socket_create_listen() and
socket_create() return socket resources.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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_REUSEPORT (integer)
This constant is only available in PHP 5.4.10 or later on platforms that support the SO_REUSEPORT socket option: this includes Mac OS X and FreeBSD, but does not include Linux or Windows.
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 defined under Windows and UNIX-like platforms. Each constant is only defined if their equal is available on the platform.

SOCKET_EINTR (integer)
Interrupted system call.
SOCKET_EBADF (integer)
Bad file number.
SOCKET_EACCES (integer)
Permission denied.
SOCKET_EFAULT (integer)
Bad address.
SOCKET_EINVAL (integer)
Invalid argument.
SOCKET_EMFILE (integer)
Too many open files.
SOCKET_ENAMETOOLONG (integer)
File name too long.
SOCKET_ENOTEMPTY (integer)
Directory not empty.
SOCKET_ELOOP (integer)
Too many symbolic links encountered.
SOCKET_EWOULDBLOCK (integer)
Operation would block.
SOCKET_EREMOTE (integer)
Object is remote.
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_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_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_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.

The following constants are only defined under Windows.

SOCKET_ENOPROTOOPT (integer)
SOCKET_EADDRINUSE (integer)
SOCKET_ETOOMYREFS (integer)
SOCKET_EPROCLIM (integer)
SOCKET_EDUOT (integer)
SOCKET_ESTALE (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_EIO (integer)
I/O error.
SOCKET_ENXIO (integer)
No such device or address.
SOCKET_E2BIG (integer)
Arg list too long.
SOCKET_EAGAIN (integer)
Try again.
SOCKET_ENOMEM (integer)
Out of memory.
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_ENFILE (integer)
File table overflow.
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_ENOLCK (integer)
No record locks available.
SOCKET_ENOSYS (integer)
Function not implemented.
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_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_EPROTOOPT (integer)
Protocol not available.
SOCKET_ADDRINUSE (integer)
Address already in use.
SOCKET_ETOOMANYREFS (integer)
Too many references: cannot splice.
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.
Tipurile resurselor
Exemple
Sockets


Exemple

Example #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);
?>

Example #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";
?>

Constante predefinite
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.

Nota:

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

Exemple
Func?ii Socket
Sockets


Func?ii Socket

Cuprins

  • 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_cmsg_space — Calculate message buffer size
  • 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_getopt — Pseudonim pentru socket_get_option
  • 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_import_stream — Import a stream
  • 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_recvmsg — Read a message
  • 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_sendmsg — Send a message
  • 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_setopt — Pseudonim pentru socket_set_option
  • 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

Func?ii Socket
socket_bind
Func?ii Socket
PHP Manual

socket_accept

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_accept — Accepts a connection on a socket

Descrierea

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.

Parametri

socket

A valid socket resource created with socket_create().

Valorile întoarse

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.

A se vedea ?i

  • 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

Func?ii Socket
socket_bind
Func?ii Socket


Binds a name to a socket

socket_accept
socket_clear_error
Func?ii Socket
PHP Manual

socket_bind

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_bind — Binds a name to a socket

Descrierea

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().

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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.

Exemple

Example #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);

?>

Note

Nota:

This function must be used on the socket before socket_connect().

Nota:

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.

A se vedea ?i

  • 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
Func?ii Socket


Clears the error on the socket or the last error code

socket_bind
socket_close
Func?ii Socket
PHP Manual

socket_clear_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

socket_clear_error — Clears the error on the socket or the last error code

Descrierea

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.

Parametri

socket

A valid socket resource created with socket_create().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

socket_bind
socket_close
Func?ii Socket


Closes a socket resource

socket_clear_error
socket_cmsg_space
Func?ii Socket
PHP Manual

socket_close

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_close — Closes a socket resource

Descrierea

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.

Parametri

socket

A valid socket resource created with socket_create() or socket_accept().

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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_cmsg_space
Func?ii Socket


Calculate message buffer size

socket_close
socket_connect
Func?ii Socket
PHP Manual

socket_cmsg_space

(PHP 5 >= 5.5.0, PHP 7)

socket_cmsg_space — Calculate message buffer size

Descrierea

int socket_cmsg_space ( int $level , int $type )

Calculates the size of the buffer that should be allocated for receiving the ancillary data.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

level

type

Valorile întoarse

A se vedea ?i

  • socket_recvmsg() - Read a message
  • socket_sendmsg() - Send a message

socket_close
socket_connect
Func?ii Socket


Initiates a connection on a socket

socket_cmsg_space
socket_create_listen
Func?ii Socket
PHP Manual

socket_connect

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_connect — Initiates a connection on a socket

Descrierea

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().

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. 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.

Nota:

If the socket is non-blocking then this function returns FALSE with an error Operation now in progress.

A se vedea ?i

  • 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_cmsg_space
socket_create_listen
Func?ii Socket


Opens a socket on port to accept connections

socket_connect
socket_create_pair
Func?ii Socket
PHP Manual

socket_create_listen

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_create_listen — Opens a socket on port to accept connections

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Note

Nota:

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().

A se vedea ?i

  • 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
Func?ii Socket


Creates a pair of indistinguishable sockets and stores them in an array

socket_create_listen
socket_create
Func?ii Socket
PHP Manual

socket_create_pair

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_create_pair — Creates a pair of indistinguishable sockets and stores them in an array

Descrierea

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).

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #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]);
?>

Example #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]);
}
?>

A se vedea ?i

  • 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
Func?ii Socket


Create a socket (endpoint for communication)

socket_create_pair
socket_get_option
Func?ii Socket
PHP Manual

socket_create

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_create — Create a socket (endpoint for communication)

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Erori/Excep?ii

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.

A se vedea ?i

  • 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
Func?ii Socket


Gets socket options for the socket

socket_create
socket_getopt
Func?ii Socket
PHP Manual

socket_get_option

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

socket_get_option — Gets socket options for the socket

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the value of the given option, or FALSE on errors.

Exemple

Example #1 socket_get_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));
?>

A se vedea ?i

  • socket_create_listen() - Opens a socket on port to accept connections
  • socket_set_option() - Sets socket options for the socket

socket_create
socket_getopt
Func?ii Socket


Pseudonim pentru socket_get_option

socket_get_option
socket_getpeername
Func?ii Socket
PHP Manual

socket_getopt

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_getopt — Pseudonim pentru socket_get_option()

Descrierea

Aceasta func?ie este pseudonim pentru: socket_get_option().

socket_get_option
socket_getpeername
Func?ii Socket


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_getopt
socket_getsockname
Func?ii Socket
PHP Manual

socket_getpeername

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. 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.

Note

Nota:

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.

Nota:

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.

A se vedea ?i

  • 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_getopt
socket_getsockname
Func?ii Socket


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_import_stream
Func?ii Socket
PHP Manual

socket_getsockname

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

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

Descrierea

bool socket_getsockname ( resource $socket , string &$addr [, int &$port ] )

Nota: 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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. 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.

A se vedea ?i

  • 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_import_stream
Func?ii Socket


Import a stream

socket_getsockname
socket_last_error
Func?ii Socket
PHP Manual

socket_import_stream

(PHP 5 >= 5.4.0, PHP 7)

socket_import_stream — Import a stream

Descrierea

resource socket_import_stream ( resource $stream )

Imports a stream that encapsulates a socket into a socket extension resource.

Parametri

stream

The stream resource to import.

Valorile întoarse

Returns FALSE or NULL on failure.

Exemple

Example #1 socket_import_stream() example

<?php
$stream = stream_socket_server("udp://0.0.0.0:58380", $errno, $errstr, STREAM_SERVER_BIND);
$sock   = socket_import_stream($stream);
?>

A se vedea ?i

  • stream_socket_server() - Create an Internet or Unix domain server socket

socket_getsockname
socket_last_error
Func?ii Socket


Returns the last error on the socket

socket_import_stream
socket_listen
Func?ii Socket
PHP Manual

socket_last_error

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_last_error — Returns the last error on the socket

Descrierea

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.

If no error had occurred, or the error had been cleared with socket_clear_error(), the function returns 0.

Parametri

socket

A valid socket resource created with socket_create().

Valorile întoarse

This function returns a socket error code.

Exemple

Example #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");
}
?>

Note

Nota:

socket_last_error() does not clear the error code, use socket_clear_error() for this purpose.

socket_import_stream
socket_listen
Func?ii Socket


Listens for a connection on a socket

socket_last_error
socket_read
Func?ii Socket
PHP Manual

socket_listen

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_listen — Listens for a connection on a socket

Descrierea

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.

Parametri

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.

Nota:

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. 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.

A se vedea ?i

  • 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
Func?ii Socket


Reads a maximum of length bytes from a socket

socket_listen
socket_recv
Func?ii Socket
PHP Manual

socket_read

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_read — Reads a maximum of length bytes from a socket

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Nota:

socket_read() returns a zero length string ("") when there is no more data to read.

A se vedea ?i

  • 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
Func?ii Socket


Receives data from a connected socket

socket_read
socket_recvfrom
Func?ii Socket
PHP Manual

socket_recv

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_recv — Receives data from a connected socket

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #1 socket_recv() example

This example is a simple rewrite of the first example from Exemple 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:

Read 123 bytes from socket_recv(). 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=Windows-1252

OK.

socket_read
socket_recvfrom
Func?ii Socket


Receives data from a socket whether or not it is connection-oriented

socket_recv
socket_recvmsg
Func?ii Socket
PHP Manual

socket_recvfrom

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_recvfrom — Receives data from a socket whether or not it is connection-oriented

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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.

Istoricul schimbarilor

Versiune | Descriere
4.3.0 | socket_recvfrom() is now binary safe.

A se vedea ?i

  • 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_recvmsg
Func?ii Socket


Read a message

socket_recvfrom
socket_select
Func?ii Socket
PHP Manual

socket_recvmsg

(PHP 5 >= 5.5.0, PHP 7)

socket_recvmsg — Read a message

Descrierea

int socket_recvmsg ( resource $socket , string $message [, int $flags ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

socket

message

flags

Valorile întoarse

A se vedea ?i

  • socket_sendmsg() - Send a message
  • socket_cmsg_space() - Calculate message buffer size

socket_recvfrom
socket_select
Func?ii Socket


Runs the select() system call on the given arrays of sockets with a specified timeout

socket_recvmsg
socket_send
Func?ii Socket
PHP Manual

socket_select

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_select — Runs the select() system call on the given arrays of sockets with a specified timeout

Descrierea

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.

Parametri

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

Avertizare

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.

Nota:

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:

Example #1 Using NULL with socket_select()

<?php
$e = NULL;
socket_select($r, $w, $e, 0);
?>

Valorile întoarse

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().

Nota:

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:

Example #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";
}
?>

Exemple

Example #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 */
}
?>

Note

Nota:

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.

A se vedea ?i

  • 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_recvmsg
socket_send
Func?ii Socket


Sends data to a connected socket

socket_select
socket_sendmsg
Func?ii Socket
PHP Manual

socket_send

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_send — Sends data to a connected socket

Descrierea

int socket_send ( resource $socket , string $buf , int $len , int $flags )

The function socket_send() sends len bytes to the socket socket from buf.

Parametri

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.

Valorile întoarse

socket_send() returns the number of bytes sent, or FALSE on error.

A se vedea ?i

  • socket_sendto() - Sends a message to a socket, whether it is connected or not

socket_select
socket_sendmsg
Func?ii Socket


Send a message

socket_send
socket_sendto
Func?ii Socket
PHP Manual

socket_sendmsg

(PHP 5 >= 5.5.0, PHP 7)

socket_sendmsg — Send a message

Descrierea

int socket_sendmsg ( resource $socket , array $message , int $flags )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

socket

message

flags

Valorile întoarse

Returns the number of bytes sent, sau FALSE în cazul e?ecului.

A se vedea ?i

  • socket_recvmsg() - Read a message
  • socket_cmsg_space() - Calculate message buffer size

socket_send
socket_sendto
Func?ii Socket


Sends a message to a socket, whether it is connected or not

socket_sendmsg
socket_set_block
Func?ii Socket
PHP Manual

socket_sendto

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_sendto — Sends a message to a socket, whether it is connected or not

Descrierea

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.

Parametri

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.

Valorile întoarse

socket_sendto() returns the number of bytes sent to the remote host, or FALSE if an error occurred.

Exemple

Example #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);
?>

A se vedea ?i

  • socket_send() - Sends data to a connected socket

socket_sendmsg
socket_set_block
Func?ii Socket


Sets blocking mode on a socket resource

socket_sendto
socket_set_nonblock
Func?ii Socket
PHP Manual

socket_set_block

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

socket_set_block — Sets blocking mode on a socket resource

Descrierea

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.

Parametri

socket

A valid socket resource created with socket_create() or socket_accept().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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.

A se vedea ?i

  • socket_set_nonblock() - Sets nonblocking mode for file descriptor fd
  • socket_set_option() - Sets socket options for the socket

socket_sendto
socket_set_nonblock
Func?ii Socket


Sets nonblocking mode for file descriptor fd

socket_set_block
socket_set_option
Func?ii Socket
PHP Manual

socket_set_nonblock

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_set_nonblock — Sets nonblocking mode for file descriptor fd

Descrierea

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.

Parametri

socket

A valid socket resource created with socket_create() or socket_accept().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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.

A se vedea ?i

  • socket_set_block() - Sets blocking mode on a socket resource
  • socket_set_option() - Sets socket options for the socket
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream

socket_set_block
socket_set_option
Func?ii Socket


Sets socket options for the socket

socket_set_nonblock
socket_setopt
Func?ii Socket
PHP Manual

socket_set_option

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

socket_set_option — Sets socket options for the socket

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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;
}
?>

A se vedea ?i

  • 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_last_error() - Returns the last error on the socket
  • socket_get_option() - Gets socket options for the socket

socket_set_nonblock
socket_setopt
Func?ii Socket


Pseudonim pentru socket_set_option

socket_set_option
socket_shutdown
Func?ii Socket
PHP Manual

socket_setopt

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_setopt — Pseudonim pentru socket_set_option()

Descrierea

Aceasta func?ie este pseudonim pentru: socket_set_option().

socket_set_option
socket_shutdown
Func?ii Socket


Shuts down a socket for receiving, sending, or both

socket_setopt
socket_strerror
Func?ii Socket
PHP Manual

socket_shutdown

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_shutdown — Shuts down a socket for receiving, sending, or both

Descrierea

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

Nota:

The associated buffer, or buffers, may or may not be emptied.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

socket_setopt
socket_strerror
Func?ii Socket


Return a string describing a socket error

socket_shutdown
socket_write
Func?ii Socket
PHP Manual

socket_strerror

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_strerror — Return a string describing a socket error

Descrierea

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.

Nota:

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).

Parametri

errno

A valid socket error number, likely produced by socket_last_error().

Valorile întoarse

Returns the error message associated with the errno parameter.

Exemple

Example #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

A se vedea ?i

  • 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
Func?ii Socket


Write to a socket

socket_strerror
SSH2
Func?ii Socket
PHP Manual

socket_write

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_write — Write to a socket

Descrierea

int socket_write ( resource $socket , string $buffer [, int $length ] )

The function socket_write() writes to the socket from the given buffer.

Parametri

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 than the buffer length, it is silently truncated to the length of the buffer.

Valorile întoarse

Returns the number of bytes successfully written to the socket sau FALSE în cazul e?ecului. 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.

Nota:

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.

Note

Nota:

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.

A se vedea ?i

  • 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
Func?ii Socket


Secure Shell2

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii SSH2
    • ssh2_auth_agent — Authenticate over SSH using the ssh agent
    • 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_chmod — Changes file mode
    • 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
Introducere
Alte servicii


Introducere

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
Instalarea / configurarea
SSH2


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SSH2


Necesita?i

The » OpenSSL and » libssh2 libraries are required. Ensure that the development libraries are installed, where a typical package name might be openssl-dev.

Version 1.2 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).

The ssh2_auth_agent() function will only be available with libssh >= 1.2.3.

support for stream_set_timeout() to channel streams will only be available with libssh >= 1.2.9.

Libssh2 comes in two flavours: gcrypt or openssl. Some linux distributions build libssh2 with the gcrypt library, some use openssl. Libssh2 has some issues when compiled with gcrypt, please use openssl.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/ssh2.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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().
Tipurile resurselor
Func?ii SSH2
SSH2


Func?ii SSH2

Cuprins

  • ssh2_auth_agent — Authenticate over SSH using the ssh agent
  • 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_chmod — Changes file mode
  • 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
Constante predefinite
ssh2_auth_agent
SSH2


Authenticate over SSH using the ssh agent

Func?ii SSH2
ssh2_auth_hostbased_file
Func?ii SSH2
PHP Manual

ssh2_auth_agent

(PECL ssh2 >= 0.12)

ssh2_auth_agent — Authenticate over SSH using the ssh agent

Descrierea

bool ssh2_auth_agent ( resource $session , string $username )

Authenticate over SSH using the ssh agent

Nota: The ssh2_auth_agent() function will only be available when the ssh2 extension is compiled with libssh >= 1.2.3.

Parametri

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Authenticating with a ssh agent

<?php
$connection = ssh2_connect('shell.example.com', 22);

if (ssh2_auth_agent($connection, 'username')) {
  echo "Authentication Successful!\n";
} else {
  die('Authentication Failed...');
}
?>

Func?ii SSH2
ssh2_auth_hostbased_file
Func?ii SSH2


Authenticate using a public hostkey

ssh2_auth_agent
ssh2_auth_none
Func?ii SSH2
PHP Manual

ssh2_auth_hostbased_file

(PECL ssh2 >= 0.9.0)

ssh2_auth_hostbased_file — Authenticate using a public hostkey

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');
}
?>

Note

Nota:

ssh2_auth_hostbased_file() requires libssh2 >= 0.7 and PHP/SSH2 >= 0.7

ssh2_auth_agent
ssh2_auth_none
Func?ii SSH2


Authenticate as "none"

ssh2_auth_hostbased_file
ssh2_auth_password
Func?ii SSH2
PHP Manual

ssh2_auth_none

(PECL ssh2 >= 0.9.0)

ssh2_auth_none — Authenticate as "none"

Descrierea

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.

Parametri

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

Valorile întoarse

Returns TRUE if the server does accept "none" as an authentication method, or an array of accepted authentication methods on failure.

Exemple

Example #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
Func?ii SSH2


Authenticate over SSH using a plain password

ssh2_auth_none
ssh2_auth_pubkey_file
Func?ii SSH2
PHP Manual

ssh2_auth_password

(PECL ssh2 >= 0.9.0)

ssh2_auth_password — Authenticate over SSH using a plain password

Descrierea

bool ssh2_auth_password ( resource $session , string $username , string $password )

Authenticate over SSH using a plain password. Since version 0.12 this function also supports keyboard_interactive method.

Parametri

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

password

Password for username

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii SSH2


Authenticate using a public key

ssh2_auth_password
ssh2_connect
Func?ii SSH2
PHP Manual

ssh2_auth_pubkey_file

(PECL ssh2 >= 0.9.0)

ssh2_auth_pubkey_file — Authenticate using a public key

Descrierea

bool ssh2_auth_pubkey_file ( resource $session , string $username , string $pubkeyfile , string $privkeyfile [, string $passphrase ] )

Authenticate using a public key read from a file.

Parametri

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

pubkeyfile

The public key file needs to be in OpenSSH's format. It should look something like:

ssh-rsa AAAAB3NzaC1yc2EAAA....NX6sqSnHA8= rsa-key-20121110

privkeyfile

passphrase

If privkeyfile is encrypted (which it should be), the passphrase must be provided.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');
}
?>

Note

Nota:

The underlying libssh library doesn't support partial auths very cleanly That is, if you need to supply both a public key and a password it will appear as if this function has failed. In this particular case a failure from this call may just mean that auth hasn't been completed yet. You would need to ignore this failure and continue on and call ssh2_auth_password() in order to complete authentication.

ssh2_auth_password
ssh2_connect
Func?ii SSH2


Connect to an SSH server

ssh2_auth_pubkey_file
ssh2_exec
Func?ii SSH2
PHP Manual

ssh2_connect

(PECL ssh2 >= 0.9.0)

ssh2_connect — Connect to an SSH server

Descrierea

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.

Parametri

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, comma 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, comma separated in order of preference. | hmac-sha1, hmac-sha1-96, hmac-ripemd160, hmac-ripemd160@openssh.com, and none**

Nota: 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)

Valorile întoarse

Returns a resource on success, or FALSE on error.

Exemple

Example #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');
?>

A se vedea ?i

  • 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
Func?ii SSH2


Execute a command on a remote server

ssh2_connect
ssh2_fetch_stream
Func?ii SSH2
PHP Manual

ssh2_exec

(PECL ssh2 >= 0.9.0)

ssh2_exec — Execute a command on a remote server

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a stream on success sau FALSE în cazul e?ecului.

Exemple

Example #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');
?>

A se vedea ?i

  • 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
Func?ii SSH2


Fetch an extended data stream

ssh2_exec
ssh2_fingerprint
Func?ii SSH2
PHP Manual

ssh2_fetch_stream

(PECL ssh2 >= 0.9.0)

ssh2_fetch_stream — Fetch an extended data stream

Descrierea

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).

Parametri

channel

streamid

An SSH2 channel stream.

Valorile întoarse

Returns the requested stream resource.

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii SSH2


Retrieve fingerprint of remote server

ssh2_fetch_stream
ssh2_methods_negotiated
Func?ii SSH2
PHP Manual

ssh2_fingerprint

(PECL ssh2 >= 0.9.0)

ssh2_fingerprint — Retrieve fingerprint of remote server

Descrierea

string ssh2_fingerprint ( resource $session [, int $flags = SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX ] )

Returns a server hostkey hash from an active session.

Parametri

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.

Valorile întoarse

Returns the hostkey hash as a string.

Exemple

Example #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
Func?ii SSH2


Return list of negotiated methods

ssh2_fingerprint
ssh2_publickey_add
Func?ii SSH2
PHP Manual

ssh2_methods_negotiated

(PECL ssh2 >= 0.9.0)

ssh2_methods_negotiated — Return list of negotiated methods

Descrierea

array ssh2_methods_negotiated ( resource $session )

Returns list of negotiated methods.

Parametri

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

Valorile întoarse

Exemple

Example #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";

?>

A se vedea ?i

  • ssh2_connect() - Connect to an SSH server

ssh2_fingerprint
ssh2_publickey_add
Func?ii SSH2


Add an authorized publickey

ssh2_methods_negotiated
ssh2_publickey_init
Func?ii SSH2
PHP Manual

ssh2_publickey_add

(PECL ssh2 >= 0.10)

ssh2_publickey_add — Add an authorized publickey

Descrierea

bool ssh2_publickey_add ( resource $pkey , string $algoname , string $blob [, bool $overwrite = false [, array $attributes ]] )

Nota: Subsistemul de chei publice este utilizat pentru a gestiona cheile publice de pe un server la care clientul este deja autentificat. Pentru autentificare pe un sistem îndepartat utilizând autentificarea cu chei publice, utiliza?i func?ia ssh2_auth_pubkey_file() în loc.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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"));
?>

A se vedea ?i

  • 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
Func?ii SSH2


Initialize Publickey subsystem

ssh2_publickey_add
ssh2_publickey_list
Func?ii SSH2
PHP Manual

ssh2_publickey_init

(PECL ssh2 >= 0.10)

ssh2_publickey_init — Initialize Publickey subsystem

Descrierea

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.

Parametri

session

Valorile întoarse

Returns an SSH2 Publickey Subsystem resource for use with all other ssh2_publickey_*() methods sau FALSE în cazul e?ecului.

Note

Nota: Subsistemul de chei publice este utilizat pentru a gestiona cheile publice de pe un server la care clientul este deja autentificat. Pentru autentificare pe un sistem îndepartat utilizând autentificarea cu chei publice, utiliza?i func?ia ssh2_auth_pubkey_file() în loc.

A se vedea ?i

  • 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
Func?ii SSH2


List currently authorized publickeys

ssh2_publickey_init
ssh2_publickey_remove
Func?ii SSH2
PHP Manual

ssh2_publickey_list

(PECL ssh2 >= 0.10)

ssh2_publickey_list — List currently authorized publickeys

Descrierea

array ssh2_publickey_list ( resource $pkey )

List currently authorized publickeys.

Parametri

pkey

Publickey Subsystem resource

Valorile întoarse

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.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

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

Note

Nota: Subsistemul de chei publice este utilizat pentru a gestiona cheile publice de pe un server la care clientul este deja autentificat. Pentru autentificare pe un sistem îndepartat utilizând autentificarea cu chei publice, utiliza?i func?ia ssh2_auth_pubkey_file() în loc.

A se vedea ?i

  • 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
Func?ii SSH2


Remove an authorized publickey

ssh2_publickey_list
ssh2_scp_recv
Func?ii SSH2
PHP Manual

ssh2_publickey_remove

(PECL ssh2 >= 0.10)

ssh2_publickey_remove — Remove an authorized publickey

Descrierea

bool ssh2_publickey_remove ( resource $pkey , string $algoname , string $blob )

Removes an authorized publickey.

Parametri

pkey

Publickey Subsystem Resource

algoname

Publickey algorithm (e.g.): ssh-dss, ssh-rsa

blob

Publickey blob as raw binary data

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota: Subsistemul de chei publice este utilizat pentru a gestiona cheile publice de pe un server la care clientul este deja autentificat. Pentru autentificare pe un sistem îndepartat utilizând autentificarea cu chei publice, utiliza?i func?ia ssh2_auth_pubkey_file() în loc.

A se vedea ?i

  • 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
Func?ii SSH2


Request a file via SCP

ssh2_publickey_remove
ssh2_scp_send
Func?ii SSH2
PHP Manual

ssh2_scp_recv

(PECL ssh2 >= 0.9.0)

ssh2_scp_recv — Request a file via SCP

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');
?>

A se vedea ?i

  • ssh2_scp_send() - Send a file via SCP
  • copy() - Copies file

ssh2_publickey_remove
ssh2_scp_send
Func?ii SSH2


Send a file via SCP

ssh2_scp_recv
ssh2_sftp_chmod
Func?ii SSH2
PHP Manual

ssh2_scp_send

(PECL ssh2 >= 0.9.0)

ssh2_scp_send — Send a file via SCP

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

A se vedea ?i

  • ssh2_scp_recv() - Request a file via SCP
  • copy() - Copies file

ssh2_scp_recv
ssh2_sftp_chmod
Func?ii SSH2


Changes file mode

ssh2_scp_send
ssh2_sftp_lstat
Func?ii SSH2
PHP Manual

ssh2_sftp_chmod

(PECL ssh2 >= 0.12)

ssh2_sftp_chmod — Changes file mode

Descrierea

bool ssh2_sftp_chmod ( resource $sftp , string $filename , int $mode )

Attempts to change the mode of the specified file to that given in mode.

Parametri

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

Path to the file.

mode

Permissions on the file. See the chmod() for more details on this parameter.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Changing the mode of a file on a remote server

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_chmod($sftp, '/somedir/somefile', 0755);
?>

A se vedea ?i

  • chmod() - Changes file mode
  • ssh2_sftp() - Initialize SFTP subsystem
  • ssh2_connect() - Connect to an SSH server

ssh2_scp_send
ssh2_sftp_lstat
Func?ii SSH2


Stat a symbolic link

ssh2_sftp_chmod
ssh2_sftp_mkdir
Func?ii SSH2
PHP Manual

ssh2_sftp_lstat

(PECL ssh2 >= 0.9.0)

ssh2_sftp_lstat — Stat a symbolic link

Descrierea

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.

Parametri

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

path

Path to the remote symbolic link.

Valorile întoarse

See the documentation for stat() for details on the values which may be returned.

Exemple

Example #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'];
?>

A se vedea ?i

  • ssh2_sftp_stat() - Stat a file on a remote filesystem
  • lstat() - Gives information about a file or symbolic link
  • stat() - Gives information about a file

ssh2_sftp_chmod
ssh2_sftp_mkdir
Func?ii SSH2


Create a directory

ssh2_sftp_lstat
ssh2_sftp_readlink
Func?ii SSH2
PHP Manual

ssh2_sftp_mkdir

(PECL ssh2 >= 0.9.0)

ssh2_sftp_mkdir — Create a directory

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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"); */
?>

A se vedea ?i

  • mkdir() - Makes directory
  • ssh2_sftp_rmdir() - Remove a directory

ssh2_sftp_lstat
ssh2_sftp_readlink
Func?ii SSH2


Return the target of a symbolic link

ssh2_sftp_mkdir
ssh2_sftp_realpath
Func?ii SSH2
PHP Manual

ssh2_sftp_readlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_readlink — Return the target of a symbolic link

Descrierea

string ssh2_sftp_readlink ( resource $sftp , string $link )

Returns the target of a symbolic link.

Parametri

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

link

Path of the symbolic link.

Valorile întoarse

Returns the target of the symbolic link.

Exemple

Example #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' */
?>

A se vedea ?i

  • readlink() - Returns the target of a symbolic link
  • ssh2_sftp_symlink() - Create a symlink

ssh2_sftp_mkdir
ssh2_sftp_realpath
Func?ii SSH2


Resolve the realpath of a provided path string

ssh2_sftp_readlink
ssh2_sftp_rename
Func?ii SSH2
PHP Manual

ssh2_sftp_realpath

(PECL ssh2 >= 0.9.0)

ssh2_sftp_realpath — Resolve the realpath of a provided path string

Descrierea

string ssh2_sftp_realpath ( resource $sftp , string $filename )

Translates filename into the effective real path on the remote filesystem.

Parametri

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

Valorile întoarse

Returns the real path as a string.

Exemple

Example #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' */
?>

A se vedea ?i

  • 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
Func?ii SSH2


Rename a remote file

ssh2_sftp_realpath
ssh2_sftp_rmdir
Func?ii SSH2
PHP Manual

ssh2_sftp_rename

(PECL ssh2 >= 0.9.0)

ssh2_sftp_rename — Rename a remote file

Descrierea

bool ssh2_sftp_rename ( resource $sftp , string $from , string $to )

Renames a file on the remote filesystem.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');
?>

A se vedea ?i

  • rename() - Renames a file or directory

ssh2_sftp_realpath
ssh2_sftp_rmdir
Func?ii SSH2


Remove a directory

ssh2_sftp_rename
ssh2_sftp_stat
Func?ii SSH2
PHP Manual

ssh2_sftp_rmdir

(PECL ssh2 >= 0.9.0)

ssh2_sftp_rmdir — Remove a directory

Descrierea

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.

Parametri

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

dirname

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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"); */
?>

A se vedea ?i

  • rmdir() - Removes directory
  • ssh2_sftp_mkdir() - Create a directory

ssh2_sftp_rename
ssh2_sftp_stat
Func?ii SSH2


Stat a file on a remote filesystem

ssh2_sftp_rmdir
ssh2_sftp_symlink
Func?ii SSH2
PHP Manual

ssh2_sftp_stat

(PECL ssh2 >= 0.9.0)

ssh2_sftp_stat — Stat a file on a remote filesystem

Descrierea

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.

Parametri

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

path

Valorile întoarse

See the documentation for stat() for details on the values which may be returned.

Exemple

Example #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'];
?>

A se vedea ?i

  • ssh2_sftp_lstat() - Stat a symbolic link
  • lstat() - Gives information about a file or symbolic link
  • stat() - Gives information about a file

ssh2_sftp_rmdir
ssh2_sftp_symlink
Func?ii SSH2


Create a symlink

ssh2_sftp_stat
ssh2_sftp_unlink
Func?ii SSH2
PHP Manual

ssh2_sftp_symlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_symlink — Create a symlink

Descrierea

bool ssh2_sftp_symlink ( resource $sftp , string $target , string $link )

Creates a symbolic link named link on the remote filesystem pointing to target.

Parametri

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

target

Target of the symbolic link.

link

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');
?>

A se vedea ?i

  • ssh2_sftp_readlink() - Return the target of a symbolic link
  • symlink() - Creates a symbolic link

ssh2_sftp_stat
ssh2_sftp_unlink
Func?ii SSH2


Delete a file

ssh2_sftp_symlink
ssh2_sftp
Func?ii SSH2
PHP Manual

ssh2_sftp_unlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_unlink — Delete a file

Descrierea

bool ssh2_sftp_unlink ( resource $sftp , string $filename )

Deletes a file on the remote filesystem.

Parametri

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');
?>

A se vedea ?i

  • unlink() - Deletes a file

ssh2_sftp_symlink
ssh2_sftp
Func?ii SSH2


Initialize SFTP subsystem

ssh2_sftp_unlink
ssh2_shell
Func?ii SSH2
PHP Manual

ssh2_sftp

(PECL ssh2 >= 0.9.0)

ssh2_sftp — Initialize SFTP subsystem

Descrierea

resource ssh2_sftp ( resource $session )

Request the SFTP subsystem from an already connected SSH2 server.

Parametri

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

Valorile întoarse

This method returns an SSH2 SFTP resource for use with all other ssh2_sftp_*() methods and the ssh2.sftp:// fopen wrapper.

Exemple

Example #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');
?>

A se vedea ?i

  • ssh2_scp_recv() - Request a file via SCP
  • ssh2_scp_send() - Send a file via SCP

ssh2_sftp_unlink
ssh2_shell
Func?ii SSH2


Request an interactive shell

ssh2_sftp
ssh2_tunnel
Func?ii SSH2
PHP Manual

ssh2_shell

(PECL ssh2 >= 0.9.0)

ssh2_shell — Request an interactive shell

Descrierea

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.

Parametri

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.

Valorile întoarse

Exemple

Example #1 Requesting an interactive shell

<?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);
?>

A se vedea ?i

  • 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
Func?ii SSH2


Open a tunnel through a remote server

ssh2_shell
Stomp
Func?ii SSH2
PHP Manual

ssh2_tunnel

(PECL ssh2 >= 0.9.0)

ssh2_tunnel — Open a tunnel through a remote server

Descrierea

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.

Parametri

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

host

port

Valorile întoarse

Exemple

Example #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);
?>

A se vedea ?i

  • ssh2_connect() - Connect to an SSH server
  • fsockopen() - Open Internet or Unix domain socket connection

ssh2_shell
Stomp
Func?ii SSH2


Stomp Client

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Exemple
  • Func?ii Stomp
    • 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
Introducere
Alte servicii


Introducere

This extension allows php applications to communicate with any Stomp compliant Message Brokers through easy object oriented and procedural interfaces. » Stomp official site

Stomp
Instalarea / configurarea
Stomp


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Stomp


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/stomp

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Stomp Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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 |

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

There is only one resource type used in the stomp extension - it's the link identifier for a stomp connection.

Configura?ia la rulare
Exemple
Instalarea / configurarea


Exemple

Example #1 Stil obiect-orientat

<?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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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"
}

Example #2 Stil procedural

<?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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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"
  }
}

Tipurile resurselor
Func?ii Stomp
Stomp


Func?ii Stomp

Cuprins

  • stomp_connect_error — Returns a string description of the last connect error
  • stomp_version — Gets the current stomp extension version
Exemple
stomp_connect_error
Stomp


Returns a string description of the last connect error

Func?ii Stomp
stomp_version
Func?ii Stomp
PHP Manual

stomp_connect_error

(PECL stomp >= 0.3.0)

stomp_connect_error — Returns a string description of the last connect error

Descrierea

string stomp_connect_error ( void )

Returns a string description of the last connect error.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A string that describes the error, or NULL if no error occurred.

Exemple

Example #1 stomp_connect_error() example

<?php
$link = stomp_connect('http://localhost:61613');

if(!$link) {
    die('Connection failed: ' . stomp_connect_error());
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Connection failed: Invalid Broker URI scheme

Func?ii Stomp
stomp_version
Func?ii Stomp


Gets the current stomp extension version

stomp_connect_error
Stomp
Func?ii Stomp
PHP Manual

stomp_version

(PECL stomp >= 0.1.0)

stomp_version — Gets the current stomp extension version

Descrierea

string stomp_version ( void )

Returns a string containing the version of the current stomp extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

It returns the current stomp extension version

Exemple

Example #1 stomp_version() example

<?php

var_dump(stomp_version());

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(5) "0.2.0"

stomp_connect_error
Stomp
Func?ii Stomp


The Stomp class

(PECL stomp >= 0.1.0)

Introducere

Represents a connection between PHP and a Stomp compliant Message Broker.

Sinopsisul clasei

Stomp {
/* Metode */
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 ] )
}

Cuprins

  • 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

Descrierea

Stil obiect-orientat (method):

public bool Stomp::abort ( string $transaction_id [, array $headers ] )

Stil procedural:

bool stomp_abort ( resource $link , string $transaction_id [, array $headers ] )

Rolls back a transaction in progress.

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

transaction_id

The transaction to abort.

headers

Un tablou asociativ con?inând antetele suplimentare (de exemplu: receipt).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Sfat

Stomp este în mod inerent asincron. O comunicare sincrona poate fi implementata adaugând un antet cu confirmare. Aceasta va face ca metodele sa nu întoarca nimic pâna când serverul confirma primirea mesajului sau pâna când se atinge limita maxima de timp pentru citire.

Exemple

Example #1 Stil obiect-orientat

<?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);
?>

Example #2 Stil procedural

<?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

Descrierea

Stil obiect-orientat (method):

public bool Stomp::ack ( mixed $msg [, array $headers ] )

Stil procedural:

bool stomp_ack ( resource $link , mixed $msg [, array $headers ] )

Acknowledges consumption of a message from a subscription using client acknowledgment.

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

msg

The message/messageId to be acknowledged.

headers

Un tablou asociativ con?inând antetele suplimentare (de exemplu: receipt).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

Poate fi specificat un antet al tranzac?iei, indicând faptul ca confirmarea mesajului trebuie sa fie parte componenta a tranzac?iei cu nume.

Sfat

Stomp este în mod inerent asincron. O comunicare sincrona poate fi implementata adaugând un antet cu confirmare. Aceasta va face ca metodele sa nu întoarca nimic pâna când serverul confirma primirea mesajului sau pâna când se atinge limita maxima de timp pentru citire.

Exemple

Example #1 Stil obiect-orientat

<?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);

?>

Example #2 Stil procedural

<?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

Descrierea

Stil obiect-orientat (method):

public bool Stomp::begin ( string $transaction_id [, array $headers ] )

Stil procedural:

bool stomp_begin ( resource $link , string $transaction_id [, array $headers ] )

Starts a transaction.

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

transaction_id

The transaction id.

headers

Un tablou asociativ con?inând antetele suplimentare (de exemplu: receipt).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Sfat

Stomp este în mod inerent asincron. O comunicare sincrona poate fi implementata adaugând un antet cu confirmare. Aceasta va face ca metodele sa nu întoarca nimic pâna când serverul confirma primirea mesajului sau pâna când se atinge limita maxima de timp pentru citire.

Exemple

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

Descrierea

Stil obiect-orientat (method):

public bool Stomp::commit ( string $transaction_id [, array $headers ] )

Stil procedural:

bool stomp_commit ( resource $link , string $transaction_id [, array $headers ] )

Commits a transaction in progress.

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

transaction_id

The transaction id.

headers

Un tablou asociativ con?inând antetele suplimentare (de exemplu: receipt).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Sfat

Stomp este în mod inerent asincron. O comunicare sincrona poate fi implementata adaugând un antet cu confirmare. Aceasta va face ca metodele sa nu întoarca nimic pâna când serverul confirma primirea mesajului sau pâna când se atinge limita maxima de timp pentru citire.

Exemple

Example #1 Stil obiect-orientat

<?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);

?>

Example #2 Stil procedural

<?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

Descrierea

Stil obiect-orientat (constructor):

public Stomp::__construct ([ string $broker = ini_get("stomp.default_broker_uri") [, string $username [, string $password [, array $headers ]]]] )

Stil procedural:

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.

Parametri

broker

The broker URI

username

The username.

password

The password.

headers

Un tablou asociativ con?inând antetele suplimentare (de exemplu: receipt).

Valorile întoarse

Nota:

Poate fi specificat un antet al tranzac?iei, indicând faptul ca confirmarea mesajului trebuie sa fie parte componenta a tranzac?iei cu nume.

Istoricul schimbarilor

Versiune | Descriere
1.0.1 | The headers parameter was added

Exemple

Example #1 Stil obiect-orientat

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* close connection */
unset($stomp);

?>

Example #2 Stil procedural

<?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

Descrierea

Stil obiect-orientat (destructor):

public bool Stomp::__destruct ( void )

Stil procedural:

bool stomp_close ( resource $link )

Closes a previously opened connection.

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

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

Descrierea

Stil obiect-orientat (method):

public string Stomp::error ( void )

Stil procedural:

string stomp_error ( resource $link )

Gets the last stomp error.

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

Valorile întoarse

Returns an error string or FALSE if no error occurred.

Exemple

Example #1 Stil obiect-orientat

<?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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
string(43) "Invalid transaction id: unknown-transaction"

Example #2 Stil procedural

<?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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

Stil obiect-orientat (method):

public array Stomp::getReadTimeout ( void )

Stil procedural:

array stomp_get_read_timeout ( resource $link )

Gets read timeout

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

Valorile întoarse

Returns an array with 2 elements: sec and usec.

Exemple

Example #1 Stil obiect-orientat

<?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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  ["sec"]=>
  int(2)
  ["usec"]=>
  int(0)
}

Example #2 Stil procedural

<?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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

Stil obiect-orientat (method):

public string Stomp::getSessionId ( void )

Stil procedural:

string stomp_get_session_id ( resource $link )

Gets the current stomp session ID.

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

Valorile întoarse

string session id on success sau FALSE în cazul e?ecului.

Exemple

Example #1 Stil obiect-orientat

<?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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(35) "ID:php.net-52873-1257291895530-4:14"

Example #2 Stil procedural

<?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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

Stil obiect-orientat (method):

public bool Stomp::hasFrame ( void )

Stil procedural:

bool stomp_has_frame ( resource $link )

Indicates whether or not there is a frame ready to read.

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

Valorile întoarse

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

Descrierea

Stil obiect-orientat (method):

public stompframe Stomp::readFrame ([ string $class_name = "stompFrame" ] )

Stil procedural:

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.

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

class_name

The name of the class to instantiate. If not specified, a stompFrame object is returned.

Valorile întoarse

Nota:

Poate fi specificat un antet al tranzac?iei, indicând faptul ca confirmarea mesajului trebuie sa fie parte componenta a tranzac?iei cu nume.

Istoricul schimbarilor

Versiune | Descriere
Stomp 0.4.0 | class_name parameter was added.

Exemple

Example #1 Stil obiect-orientat

<?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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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"
}

Example #2 Stil procedural

<?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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

Stil obiect-orientat (method):

public bool Stomp::send ( string $destination , mixed $msg [, array $headers ] )

Stil procedural:

bool stomp_send ( resource $link , string $destination , mixed $msg [, array $headers ] )

Sends a message to the Message Broker.

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

destination

Where to send the message

msg

Message to send.

headers

Un tablou asociativ con?inând antetele suplimentare (de exemplu: receipt).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

Poate fi specificat un antet al tranzac?iei, indicând faptul ca confirmarea mesajului trebuie sa fie parte componenta a tranzac?iei cu nume.

Sfat

Stomp este în mod inerent asincron. O comunicare sincrona poate fi implementata adaugând un antet cu confirmare. Aceasta va face ca metodele sa nu întoarca nimic pâna când serverul confirma primirea mesajului sau pâna când se atinge limita maxima de timp pentru citire.

Exemple

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

Descrierea

Stil obiect-orientat (method):

public void Stomp::setReadTimeout ( int $seconds [, int $microseconds ] )

Stil procedural:

void stomp_set_read_timeout ( resource $link , int $seconds [, int $microseconds ] )

Sets read timeout.

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

seconds

The seconds part of the timeout to be set.

microseconds

The microseconds part of the timeout to be set.

Exemple

Example #1 Stil obiect-orientat

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

$stomp->setReadTimeout(10);

/* close connection */
unset($stomp);

?>

Example #2 Stil procedural

<?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

Descrierea

Stil obiect-orientat (method):

public bool Stomp::subscribe ( string $destination [, array $headers ] )

Stil procedural:

bool stomp_subscribe ( resource $link , string $destination [, array $headers ] )

Registers to listen to a given destination.

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

destination

Destination to subscribe to.

headers

Un tablou asociativ con?inând antetele suplimentare (de exemplu: receipt).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Sfat

Stomp este în mod inerent asincron. O comunicare sincrona poate fi implementata adaugând un antet cu confirmare. Aceasta va face ca metodele sa nu întoarca nimic pâna când serverul confirma primirea mesajului sau pâna când se atinge limita maxima de timp pentru citire.

Exemple

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

Descrierea

Stil obiect-orientat (method):

public bool Stomp::unsubscribe ( string $destination [, array $headers ] )

Stil procedural:

bool stomp_unsubscribe ( resource $link , string $destination [, array $headers ] )

Removes an existing subscription.

Parametri

link

Doar stilul procedural: Identificatorul legaturii stomp întors de stomp_connect().

destination

Subscription to remove.

headers

Un tablou asociativ con?inând antetele suplimentare (de exemplu: receipt).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Sfat

Stomp este în mod inerent asincron. O comunicare sincrona poate fi implementata adaugând un antet cu confirmare. Aceasta va face ca metodele sa nu întoarca nimic pâna când serverul confirma primirea mesajului sau pâna când se atinge limita maxima de timp pentru citire.

Exemple

See stomp_ack().

Stomp::subscribe
StompFrame
Stomp


The StompFrame class

(PECL stomp >= 0.1.0)

Introducere

Represents a message which was sent or received from a Stomp compliant Message Broker.

Sinopsisul clasei

StompFrame {
/* Proprieta?i */
public $command ;
public $headers ;
public $body ;
/* Metode */
__construct ([ string $command [, array $headers [, string $body ]]] )
}

Proprieta?i

command

Frame command.

headers

Frame headers (array).

body

Frame body.

Cuprins

  • StompFrame::__construct — Constructor
Stomp::unsubscribe
StompFrame::__construct
Stomp


Constructor

StompFrame
StompException
StompFrame
PHP Manual

StompFrame::__construct

(PECL stomp >= 0.1.0)

StompFrame::__construct — Constructor

Descrierea

StompFrame::__construct ([ string $command [, array $headers [, string $body ]]] )

Constructor.

Parametri

command

Frame command

headers

Frame headers (array).

body

Frame body.

StompFrame
StompException
StompFrame


The StompException class

(PECL stomp >= 0.1.0)

Introducere

Represents an error raised by the stomp extension. See Exceptions for more information about Exceptions in PHP.

Sinopsisul clasei

StompException extends Exception {
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
/* Metode */
public string getDetails ( void )
}

Cuprins

  • StompException::getDetails — Get exception details
StompFrame::__construct
StompException::getDetails
Stomp


Get exception details

StompException
SVM
StompException
PHP Manual

StompException::getDetails

(PECL stomp >= 0.1.0)

StompException::getDetails — Get exception details

Descrierea

public string StompException::getDetails ( void )

Get exception details.

Valorile întoarse

string containing the error details.

StompException
SVM
StompException


Support Vector Machine

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Exemple
  • 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
Introducere
Alte servicii


Introducere

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
Instalarea / configurarea
SVM


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SVM


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/svm

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Exemple

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.

Example #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');
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(-1)

Example #2 Train from a file

<?php
$svm = new SVM();
$model = $svm->train("traindata.txt");
?>

Tipurile resurselor
SVM
SVM


The SVM class

(PECL svm >= 0.1.0)

Introducere

Sinopsisul clasei

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 ] )
}

Constante predefinite

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

Cuprins

  • 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
Exemple
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

Descrierea

public SVM::__construct ( void )

Constructs a new SVM object ready to accept training data.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

A se vedea ?i

  • 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

Descrierea

public array SVM::getOptions ( void )

Retrieve an array containing the training parameters. The parameters will be keyed on the predefined SVM constants.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SVM::setOptions ( array $params )

Set one or more training parameters.

Parametri

params

An array of training parameters, keyed on the SVM constants.

Valorile întoarse

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

Descrierea

public SVMModel svm::train ( array $problem [, array $weights ] )

Train a support vector machine based on the supplied training data.

Parametri

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.

Valorile întoarse

Returns an SVMModel that can be used to classify previously unseen data. Throws SVMException on error

SVM::setOptions
SVMModel
SVM


The SVMModel class

(PECL svm >= 0.1.0)

Introducere

The SVMModel is the end result of the training process. It can be used to classify previously unseen data.

Sinopsisul clasei

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 )
}

Cuprins

  • 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

Descrierea

public bool SVMModel::checkProbabilityModel ( void )

Returns true if the model contains probability information.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

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.

Parametri

filename

The filename for the saved model file this model should load.

Valorile întoarse

Throws SVMException on error

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Return an array of labels

A se vedea ?i

  • 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

Descrierea

public int SVMModel::getNrClass ( void )

Returns the number of classes the model was trained with, will return 2 for one class and regression models.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SVMModel::getSvmType ( void )

Returns an integer value representing the type of the SVM model used, e.g SVM::C_SVC.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SVMModel::load ( string $filename )

Load a model file ready for classification or regression.

Parametri

filename

The filename of the model.

Valorile întoarse

Throws SVMException on error. Returns true on success.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

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.

Valorile întoarse

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

A se vedea ?i

  • 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

Descrierea

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.

Parametri

data

The array to be classified. This should be a series of key => value pairs in increasing key order, but not necessarily continuous.

Valorile întoarse

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

A se vedea ?i

  • 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

Descrierea

public bool SVMModel::save ( string $filename )

Save the model data to a file, for later use.

Parametri

filename

The file to save the model to.

Valorile întoarse

Throws SVMException on error. Returns true on success.

A se vedea ?i

  • SVMModel::load() - Load a saved SVM Model

SVMModel::predict
SVN
SVMModel


Subversion

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii SVN
    • 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
Introducere
Alte servicii


Introducere

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.

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

SVN
Instalarea / configurarea
SVN


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SVN


Necesita?i

The Subversion binaries are not necessary to use this extension. However, when compiling the extension, libsvn (the Subversion headers) must be available.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » 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.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Avertizare

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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
Tipurile resurselor
Func?ii SVN
SVN


Func?ii SVN

Cuprins

  • 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
Constante predefinite
svn_add
SVN


Schedules the addition of an item in a working directory

Func?ii SVN
svn_auth_get_parameter
Func?ii SVN
PHP Manual

svn_add

(PECL svn >= 0.1.0)

svn_add — Schedules the addition of an item in a working directory

Descrierea

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.

Parametri

path

Path of item to add.

Nota: Caile relative vor fi rezolvate ca ?i cum directorul curent este cel ce con?ine binarul PHP. Pentru a utiliza directorul de lucru al scriptului apelant, utiliza?i realpath() sau 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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Exemple

Example #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.

A se vedea ?i

  • » SVN documentation on svn add

Func?ii SVN
svn_auth_get_parameter
Func?ii SVN


Retrieves authentication parameter

svn_add
svn_auth_set_parameter
Func?ii SVN
PHP Manual

svn_auth_get_parameter

(PECL svn >= 0.1.0)

svn_auth_get_parameter — Retrieves authentication parameter

Descrierea

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.

Parametri

key

String key name. Use the authentication constants defined by this extension to specify a key.

Valorile întoarse

Returns the string value of the parameter at key; returns NULL if parameter does not exist.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • svn_auth_set_parameter() - Sets an authentication parameter
  • Authentication constants

svn_add
svn_auth_set_parameter
Func?ii SVN


Sets an authentication parameter

svn_auth_get_parameter
svn_blame
Func?ii SVN
PHP Manual

svn_auth_set_parameter

(PECL svn >= 0.1.0)

svn_auth_set_parameter — Sets an authentication parameter

Descrierea

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.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Exemple

Example #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');
?>

A se vedea ?i

  • svn_auth_get_parameter() - Retrieves authentication parameter
  • Authentication constants

svn_auth_get_parameter
svn_blame
Func?ii SVN


Get the SVN blame for a file

svn_auth_set_parameter
svn_cat
Func?ii SVN
PHP Manual

svn_blame

(PECL svn >= 0.3.0)

svn_blame — Get the SVN blame for a file

Descrierea

array svn_blame ( string $repository_url [, int $revision_no = SVN_REVISION_HEAD ] )

Get the SVN blame of a file from a repository URL.

Parametri

repository_url

The repository URL.

revision_no

The revision number.

Valorile întoarse

An array of SVN blame information separated by line which includes the revision number, line number, line of code, author, and date.

Exemple

Example #1 svn_blame() example

<?php
$svnurl = 'http://svn.example.org/svnroot/foo/trunk/index.php';

print_r( svn_blame($svnurl) );

?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] = Array
          (
           [rev] = 1
           [line_no] = 1
           [line] = Hello World
           [author] = joesmith
           [date] = 2007-07-02T05:51:26.628396Z
          )
    [1] = Array
          ...

A se vedea ?i

  • 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
Func?ii SVN


Returns the contents of a file in a repository

svn_blame
svn_checkout
Func?ii SVN
PHP Manual

svn_cat

(PECL svn >= 0.1.0)

svn_cat — Returns the contents of a file in a repository

Descrierea

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.

Parametri

repos_url

String URL path to item in a repository.

revision_no

Integer revision number of item to retrieve, default is the HEAD revision.

Valorile întoarse

Returns the string contents of the item from the repository on success, and FALSE on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Exemple

Example #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)
?>

A se vedea ?i

  • svn_list()
  • » SVN documentation on svn cat

svn_blame
svn_checkout
Func?ii SVN


Checks out a working copy from the repository

svn_cat
svn_cleanup
Func?ii SVN
PHP Manual

svn_checkout

(PECL svn >= 0.1.0)

svn_checkout — Checks out a working copy from the repository

Descrierea

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.

Parametri

repos

String URL path to directory in repository to check out.

targetpath

String local path to directory to check out in to

Nota: Caile relative vor fi rezolvate ca ?i cum directorul curent este cel ce con?ine binarul PHP. Pentru a utiliza directorul de lucru al scriptului apelant, utiliza?i realpath() sau 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Exemple

Example #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.

A se vedea ?i

  • 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
Func?ii SVN


Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

svn_checkout
svn_client_version
Func?ii SVN
PHP Manual

svn_cleanup

(PECL svn >= 0.1.0)

svn_cleanup — Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

Descrierea

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.

Parametri

workingdir

String path to local working directory to cleanup

Nota: Caile relative vor fi rezolvate ca ?i cum directorul curent este cel ce con?ine binarul PHP. Pentru a utiliza directorul de lucru al scriptului apelant, utiliza?i realpath() sau dirname(__FILE__).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Exemple

Example #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.

A se vedea ?i

  • update()
  • » SVN documentation on svn cleanup

svn_checkout
svn_client_version
Func?ii SVN


Returns the version of the SVN client libraries

svn_cleanup
svn_commit
Func?ii SVN
PHP Manual

svn_client_version

(PECL svn >= 0.1.0)

svn_client_version — Returns the version of the SVN client libraries

Descrierea

string svn_client_version ( void )

Returns the version of the SVN client libraries

Valorile întoarse

String version number, usually in form of x.y.z.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Exemple

Example #1 Basic example

<?php
echo svn_client_version();
?>

Exemplul de mai sus va afi?a ceva similar cu:

1.3.1

svn_cleanup
svn_commit
Func?ii SVN


Sends changes from the local working copy to the repository

svn_client_version
svn_delete
Func?ii SVN
PHP Manual

svn_commit

(PECL svn >= 0.1.0)

svn_commit — Sends changes from the local working copy to the repository

Descrierea

array svn_commit ( string $log , array $targets [, bool $recursive = true ] )

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 recursive is set to FALSE.

Nota: This function does not have any parameters for specifying authentication, so a username and password must be set using svn_auth_set_parameter()

Parametri

log

String log text to commit

targets

Array of local paths of files to be committed

Avertizare

This parameter must be an array, a string for a single target is not acceptable.

Nota: Caile relative vor fi rezolvate ca ?i cum directorul curent este cel ce con?ine binarul PHP. Pentru a utiliza directorul de lucru al scriptului apelant, utiliza?i realpath() sau dirname(__FILE__).

recursive

Boolean flag to disable recursive committing of directories in the targets array. Default is TRUE.

Valorile întoarse

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.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Exemple

Example #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'))));
?>

Exemplul de mai sus va afi?a:

array(
  0 => 1415,
  1 => '2007-05-26T01:44:28.453125Z',
  2 => 'Bob'
)

A se vedea ?i

  • svn_auth_set_parameter() - Sets an authentication parameter
  • » SVN documentation on svn commit

svn_client_version
svn_delete
Func?ii SVN


Delete items from a working copy or repository.

svn_commit
svn_diff
Func?ii SVN
PHP Manual

svn_delete

(PECL svn >= 0.4.0)

svn_delete — Delete items from a working copy or repository.

Descrierea

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.

Parametri

path

Path of item to delete.

Nota: Caile relative vor fi rezolvate ca ?i cum directorul curent este cel ce con?ine binarul PHP. Pentru a utiliza directorul de lucru al scriptului apelant, utiliza?i realpath() sau 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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A se vedea ?i

  • » SVN documentation on svn delete

svn_commit
svn_diff
Func?ii SVN


Recursively diffs two paths

svn_delete
svn_export
Func?ii SVN
PHP Manual

svn_diff

(PECL svn >= 0.1.0)

svn_diff — Recursively diffs two paths

Descrierea

array svn_diff ( string $path1 , int $rev1 , string $path2 , int $rev2 )

Recursively diffs two paths, path1 and path2.

Nota:

This is not a general-purpose diff utility. Only local files that are versioned may be diffed: other files will fail.

Parametri

path1

First path to diff. This can be a URL to a file/directory in an SVN repository or a local file/directory path.

Nota: Caile relative vor fi rezolvate ca ?i cum directorul curent este cel ce con?ine binarul PHP. Pentru a utiliza directorul de lucru al scriptului apelant, utiliza?i realpath() sau dirname(__FILE__).

Avertizare

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.

Valorile întoarse

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.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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

Example #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);
}
?>

Example #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);
}
?>

A se vedea ?i

  • » SVN documentation on svn diff

svn_delete
svn_export
Func?ii SVN


Export the contents of a SVN directory

svn_diff
svn_fs_abort_txn
Func?ii SVN
PHP Manual

svn_export

(PECL svn >= 0.3.0)

svn_export — Export the contents of a SVN directory

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 svn_export() example

<?php
$working_dir     = '../';
$new_working_dir = '/home/user/devel/foo/trunk';

svn_export($working_dir, $new_working_dir);
?>

A se vedea ?i

  • svn_import() - Imports an unversioned path into a repository

svn_diff
svn_fs_abort_txn
Func?ii SVN


Abort a transaction, returns true if everything is okay, false otherwise

svn_export
svn_fs_apply_text
Func?ii SVN
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

Descrierea

bool svn_fs_abort_txn ( resource $txn )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Abort a transaction, returns true if everything is okay, false otherwise

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_export
svn_fs_apply_text
Func?ii SVN


Creates and returns a stream that will be used to replace

svn_fs_abort_txn
svn_fs_begin_txn2
Func?ii SVN
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

Descrierea

resource svn_fs_apply_text ( resource $root , string $path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Creates and returns a stream that will be used to replace

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_abort_txn
svn_fs_begin_txn2
Func?ii SVN


Create a new transaction

svn_fs_apply_text
svn_fs_change_node_prop
Func?ii SVN
PHP Manual

svn_fs_begin_txn2

(PECL svn >= 0.2.0)

svn_fs_begin_txn2 — Create a new transaction

Descrierea

resource svn_fs_begin_txn2 ( resource $repos , int $rev )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Create a new transaction

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_apply_text
svn_fs_change_node_prop
Func?ii SVN


Return true if everything is ok, false otherwise

svn_fs_begin_txn2
svn_fs_check_path
Func?ii SVN
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

Descrierea

bool svn_fs_change_node_prop ( resource $root , string $path , string $name , string $value )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Return true if everything is ok, false otherwise

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_begin_txn2
svn_fs_check_path
Func?ii SVN


Determines what kind of item lives at path in a given repository fsroot

svn_fs_change_node_prop
svn_fs_contents_changed
Func?ii SVN
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

Descrierea

int svn_fs_check_path ( resource $fsroot , string $path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Determines what kind of item lives at path in a given repository fsroot

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_change_node_prop
svn_fs_contents_changed
Func?ii SVN


Return true if content is different, false otherwise

svn_fs_check_path
svn_fs_copy
Func?ii SVN
PHP Manual

svn_fs_contents_changed

(PECL svn >= 0.2.0)

svn_fs_contents_changed — Return true if content is different, false otherwise

Descrierea

bool svn_fs_contents_changed ( resource $root1 , string $path1 , resource $root2 , string $path2 )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Return true if content is different, false otherwise

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_check_path
svn_fs_copy
Func?ii SVN


Copies a file or a directory, returns true if all is ok, false otherwise

svn_fs_contents_changed
svn_fs_delete
Func?ii SVN
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

Descrierea

bool svn_fs_copy ( resource $from_root , string $from_path , resource $to_root , string $to_path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Copies a file or a directory, returns true if all is ok, false otherwise

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_contents_changed
svn_fs_delete
Func?ii SVN


Deletes a file or a directory, return true if all is ok, false otherwise

svn_fs_copy
svn_fs_dir_entries
Func?ii SVN
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

Descrierea

bool svn_fs_delete ( resource $root , string $path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Deletes a file or a directory, return true if all is ok, false otherwise

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_copy
svn_fs_dir_entries
Func?ii SVN


Enumerates the directory entries under path; returns a hash of dir names to file type

svn_fs_delete
svn_fs_file_contents
Func?ii SVN
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

Descrierea

array svn_fs_dir_entries ( resource $fsroot , string $path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Enumerates the directory entries under path; returns a hash of dir names to file type

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_delete
svn_fs_file_contents
Func?ii SVN


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
Func?ii SVN
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

Descrierea

resource svn_fs_file_contents ( resource $fsroot , string $path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns a stream to access the contents of a file from a given version of the fs

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_dir_entries
svn_fs_file_length
Func?ii SVN


Returns the length of a file from a given version of the fs

svn_fs_file_contents
svn_fs_is_dir
Func?ii SVN
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

Descrierea

int svn_fs_file_length ( resource $fsroot , string $path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the length of a file from a given version of the fs

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_file_contents
svn_fs_is_dir
Func?ii SVN


Return true if the path points to a directory, false otherwise

svn_fs_file_length
svn_fs_is_file
Func?ii SVN
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

Descrierea

bool svn_fs_is_dir ( resource $root , string $path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Return true if the path points to a directory, false otherwise

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_file_length
svn_fs_is_file
Func?ii SVN


Return true if the path points to a file, false otherwise

svn_fs_is_dir
svn_fs_make_dir
Func?ii SVN
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

Descrierea

bool svn_fs_is_file ( resource $root , string $path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Return true if the path points to a file, false otherwise

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_is_dir
svn_fs_make_dir
Func?ii SVN


Creates a new empty directory, returns true if all is ok, false otherwise

svn_fs_is_file
svn_fs_make_file
Func?ii SVN
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

Descrierea

bool svn_fs_make_dir ( resource $root , string $path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Creates a new empty directory, returns true if all is ok, false otherwise

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_is_file
svn_fs_make_file
Func?ii SVN


Creates a new empty file, returns true if all is ok, false otherwise

svn_fs_make_dir
svn_fs_node_created_rev
Func?ii SVN
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

Descrierea

bool svn_fs_make_file ( resource $root , string $path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Creates a new empty file, returns true if all is ok, false otherwise

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_make_dir
svn_fs_node_created_rev
Func?ii SVN


Returns the revision in which path under fsroot was created

svn_fs_make_file
svn_fs_node_prop
Func?ii SVN
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

Descrierea

int svn_fs_node_created_rev ( resource $fsroot , string $path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the revision in which path under fsroot was created

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_make_file
svn_fs_node_prop
Func?ii SVN


Returns the value of a property for a node

svn_fs_node_created_rev
svn_fs_props_changed
Func?ii SVN
PHP Manual

svn_fs_node_prop

(PECL svn >= 0.1.0)

svn_fs_node_prop — Returns the value of a property for a node

Descrierea

string svn_fs_node_prop ( resource $fsroot , string $path , string $propname )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the value of a property for a node

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_node_created_rev
svn_fs_props_changed
Func?ii SVN


Return true if props are different, false otherwise

svn_fs_node_prop
svn_fs_revision_prop
Func?ii SVN
PHP Manual

svn_fs_props_changed

(PECL svn >= 0.2.0)

svn_fs_props_changed — Return true if props are different, false otherwise

Descrierea

bool svn_fs_props_changed ( resource $root1 , string $path1 , resource $root2 , string $path2 )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Return true if props are different, false otherwise

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_node_prop
svn_fs_revision_prop
Func?ii SVN


Fetches the value of a named property

svn_fs_props_changed
svn_fs_revision_root
Func?ii SVN
PHP Manual

svn_fs_revision_prop

(PECL svn >= 0.1.0)

svn_fs_revision_prop — Fetches the value of a named property

Descrierea

string svn_fs_revision_prop ( resource $fs , int $revnum , string $propname )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Fetches the value of a named property

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_props_changed
svn_fs_revision_root
Func?ii SVN


Get a handle on a specific version of the repository root

svn_fs_revision_prop
svn_fs_txn_root
Func?ii SVN
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

Descrierea

resource svn_fs_revision_root ( resource $fs , int $revnum )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Get a handle on a specific version of the repository root

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_revision_prop
svn_fs_txn_root
Func?ii SVN


Creates and returns a transaction root

svn_fs_revision_root
svn_fs_youngest_rev
Func?ii SVN
PHP Manual

svn_fs_txn_root

(PECL svn >= 0.2.0)

svn_fs_txn_root — Creates and returns a transaction root

Descrierea

resource svn_fs_txn_root ( resource $txn )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Creates and returns a transaction root

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_revision_root
svn_fs_youngest_rev
Func?ii SVN


Returns the number of the youngest revision in the filesystem

svn_fs_txn_root
svn_import
Func?ii SVN
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

Descrierea

int svn_fs_youngest_rev ( resource $fs )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Returns the number of the youngest revision in the filesystem

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_fs_txn_root
svn_import
Func?ii SVN


Imports an unversioned path into a repository

svn_fs_youngest_rev
svn_log
Func?ii SVN
PHP Manual

svn_import

(PECL svn >= 0.2.0)

svn_import — Imports an unversioned path into a repository

Descrierea

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.

Parametri

path

Path of file or directory to import.

Nota: Caile relative vor fi rezolvate ca ?i cum directorul curent este cel ce con?ine binarul PHP. Pentru a utiliza directorul de lucru al scriptului apelant, utiliza?i realpath() sau dirname(__FILE__).

url

Repository URL to import into.

nonrecursive

Whether or not to refrain from recursively processing directories.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Exemple

Example #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);
?>

A se vedea ?i

  • svn_add() - Schedules the addition of an item in a working directory
  • » SVN documentation for svn import

svn_fs_youngest_rev
svn_log
Func?ii SVN


Returns the commit log messages of a repository URL

svn_import
svn_ls
Func?ii SVN
PHP Manual

svn_log

(PECL svn >= 0.1.0)

svn_log — Returns the commit log messages of a repository URL

Descrierea

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.

Parametri

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.

Valorile întoarse

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] => ...

Nota:

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.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Exemple

Example #1 svn_log() example

<?php
print_r( svn_log('http://www.example.com/', 23) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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'
                    )
            )
    )
)

A se vedea ?i

  • » SVN documentation on svn log

svn_import
svn_ls
Func?ii SVN


Returns list of directory contents in repository URL, optionally at revision number

svn_log
svn_mkdir
Func?ii SVN
PHP Manual

svn_ls

(PECL svn >= 0.1.0)

svn_ls — Returns list of directory contents in repository URL, optionally at revision number

Descrierea

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]

Nota:

This function does not work with working copies. repos_url must be a repository URL.

Parametri

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.

Valorile întoarse

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] => ...

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Exemple

Example #1 svn_ls() example

<?php
print_r( svn_ls('http://www.example.com/svnroot/') );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )
)

A se vedea ?i

  • » SVN documentation on svn list

svn_log
svn_mkdir
Func?ii SVN


Creates a directory in a working copy or repository

svn_ls
svn_repos_create
Func?ii SVN
PHP Manual

svn_mkdir

(PECL svn >= 0.4.0)

svn_mkdir — Creates a directory in a working copy or repository

Descrierea

bool svn_mkdir ( string $path [, string $log_message ] )

Creates a directory in a working copy or repository.

Parametri

path

The path to the working copy or repository.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • svn_add() - Schedules the addition of an item in a working directory
  • svn_copy()

svn_ls
svn_repos_create
Func?ii SVN


Create a new subversion repository at path

svn_mkdir
svn_repos_fs_begin_txn_for_commit
Func?ii SVN
PHP Manual

svn_repos_create

(PECL svn >= 0.1.0)

svn_repos_create — Create a new subversion repository at path

Descrierea

resource svn_repos_create ( string $path [, array $config [, array $fsconfig ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Create a new subversion repository at path

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_mkdir
svn_repos_fs_begin_txn_for_commit
Func?ii SVN


Create a new transaction

svn_repos_create
svn_repos_fs_commit_txn
Func?ii SVN
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

Descrierea

resource svn_repos_fs_begin_txn_for_commit ( resource $repos , int $rev , string $author , string $log_msg )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Create a new transaction

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_repos_create
svn_repos_fs_commit_txn
Func?ii SVN


Commits a transaction and returns the new revision

svn_repos_fs_begin_txn_for_commit
svn_repos_fs
Func?ii SVN
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

Descrierea

int svn_repos_fs_commit_txn ( resource $txn )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Commits a transaction and returns the new revision

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_repos_fs_begin_txn_for_commit
svn_repos_fs
Func?ii SVN


Gets a handle on the filesystem for a repository

svn_repos_fs_commit_txn
svn_repos_hotcopy
Func?ii SVN
PHP Manual

svn_repos_fs

(PECL svn >= 0.1.0)

svn_repos_fs — Gets a handle on the filesystem for a repository

Descrierea

resource svn_repos_fs ( resource $repos )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Gets a handle on the filesystem for a repository

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_repos_fs_commit_txn
svn_repos_hotcopy
Func?ii SVN


Make a hot-copy of the repos at repospath; copy it to destpath

svn_repos_fs
svn_repos_open
Func?ii SVN
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

Descrierea

bool svn_repos_hotcopy ( string $repospath , string $destpath , bool $cleanlogs )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Make a hot-copy of the repos at repospath; copy it to destpath

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_repos_fs
svn_repos_open
Func?ii SVN


Open a shared lock on a repository.

svn_repos_hotcopy
svn_repos_recover
Func?ii SVN
PHP Manual

svn_repos_open

(PECL svn >= 0.1.0)

svn_repos_open — Open a shared lock on a repository.

Descrierea

resource svn_repos_open ( string $path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Open a shared lock on a repository.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_repos_hotcopy
svn_repos_recover
Func?ii SVN


Run recovery procedures on the repository located at path.

svn_repos_open
svn_revert
Func?ii SVN
PHP Manual

svn_repos_recover

(PECL svn >= 0.1.0)

svn_repos_recover — Run recovery procedures on the repository located at path.

Descrierea

bool svn_repos_recover ( string $path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Run recovery procedures on the repository located at path.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

svn_repos_open
svn_revert
Func?ii SVN


Revert changes to the working copy

svn_repos_recover
svn_status
Func?ii SVN
PHP Manual

svn_revert

(PECL svn >= 0.3.0)

svn_revert — Revert changes to the working copy

Descrierea

bool svn_revert ( string $path [, bool $recursive = false ] )

Revert any local changes to the path in a working copy.

Parametri

path

The path to the working repository.

recursive

Optionally make recursive changes.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • svn_delete() - Delete items from a working copy or repository.
  • svn_export() - Export the contents of a SVN directory

svn_repos_recover
svn_status
Func?ii SVN


Returns the status of working copy files and directories

svn_revert
svn_update
Func?ii SVN
PHP Manual

svn_status

(PECL svn >= 0.1.0)

svn_status — Returns the status of working copy files and directories

Descrierea

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.

Parametri

path

Local path to file or directory to retrieve status of.

Nota: Caile relative vor fi rezolvate ca ?i cum directorul curent este cel ce con?ine binarul PHP. Pentru a utiliza directorul de lucru al scriptului apelant, utiliza?i realpath() sau 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.

Valorile întoarse

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. Accesa?i constantele de starepentru a afla valorile posibile.
repos_text_status
Status of item's text in repository. Only accurate if update was set to TRUE. Accesa?i constantele de starepentru a afla valorile posibile.
prop_status
Status of item's properties. Accesa?i constantele de starepentru a afla valorile posibile.
repos_prop_status
Status of item's property in repository. Only accurate if update was set to TRUE. Accesa?i constantele de starepentru a afla valorile posibile.
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. Accesa?i constante de tip pentru a afla valorile posibile.
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

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Exemple

Example #1 Basic example

This example demonstrates a basic, theoretical usage of this function.

<?php
print_r(svn_status(realpath('wc')));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
    )
)

A se vedea ?i

  • 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
Func?ii SVN


Update working copy

svn_status
TCP
Func?ii SVN
PHP Manual

svn_update

(PECL svn >= 0.1.0)

svn_update — Update working copy

Descrierea

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.

Parametri

path

Path to local working copy.

Nota: Caile relative vor fi rezolvate ca ?i cum directorul curent este cel ce con?ine binarul PHP. Pentru a utiliza directorul de lucru al scriptului apelant, utiliza?i realpath() sau dirname(__FILE__).

revno

Revision number to update to, default is SVN_REVISION_HEAD.

recurse

Whether or not to recursively update directories.

Valorile întoarse

Returns new revision number on success, returns FALSE on failure.

Note

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Exemple

Example #1 Basic example

This example demonstrates basic usage of this function:

<?php
echo svn_update(realpath('working-copy'));
?>

Exemplul de mai sus va afi?a ceva similar cu:

234

A se vedea ?i

  • 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
Func?ii SVN


TCP Wrappers

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii TCP
    • tcpwrap_check — Performs a tcpwrap check
svn_update
Introducere
Alte servicii


Introducere

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
Instalarea / configurarea
TCP


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
TCP


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/tcpwrap.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii TCP
TCP


Func?ii TCP

Cuprins

  • tcpwrap_check — Performs a tcpwrap check
Constante predefinite
tcpwrap_check
TCP


Performs a tcpwrap check

Func?ii TCP
Varnish
Func?ii TCP
PHP Manual

tcpwrap_check

(PECL tcpwrap >= 0.1.0)

tcpwrap_check — Performs a tcpwrap check

Descrierea

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.

Parametri

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.

Valorile întoarse

This function returns TRUE if access should be granted, FALSE otherwise.

Exemple

Example #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');
}
?>

A se vedea ?i

For more details please consult hosts_access(3) man page.

Func?ii TCP
Varnish
Func?ii TCP


Varnish

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • 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::disconnect — Disconnect from 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
  • 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
Introducere
Alte servicii


Introducere

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
Instalarea / configurarea
Varnish


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Varnish


Necesita?i

To use this extension, you will need Varnish Cache of the version >=3.0 installed, available on the » Varnish Cache homepage

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/varnish.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/varnish/.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)

Tipurile resurselor
Exemple
Varnish


Exemple

Cuprins

  • Basic VarnishAdmin usage
  • Basic VarnishStat usage
  • Basic VarnishLog usage
Constante predefinite
Basic VarnishAdmin usage
Varnish


Basic VarnishAdmin usage

The example illustrates a simple usage of the ban functionality

Example #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);

?>
Exemple
Basic VarnishStat usage
Exemple


Basic VarnishStat usage

The example illustrates getting varnish statistic snapshot from shared memory

Example #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
Exemple


Basic VarnishLog usage

The example illustrates reading varnish log lines from shared memory

Example #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
Exemple


The VarnishAdmin class

(PECL varnish >= 0.3)

Introducere

Sinopsisul clasei

VarnishAdmin {
/* Metode */
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 bool disconnect ( void )
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 )
}

Cuprins

  • 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::disconnect — Disconnect from 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
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

Descrierea

public bool VarnishAdmin::auth ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public int VarnishAdmin::ban ( string $vcl_regex )

Parametri

vcl_regex

Varnish VCL expression. It's based on the varnish ban command.

Valorile întoarse

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

Descrierea

public int VarnishAdmin::banUrl ( string $vcl_regex )

Parametri

vcl_regex

URL regular expression in PCRE compatible syntax. It's based on the ban.url varnish command.

Valorile întoarse

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

Descrierea

public int VarnishAdmin::clearPanic ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool VarnishAdmin::connect ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

VarnishAdmin::clearPanic
VarnishAdmin::__construct
VarnishAdmin


VarnishAdmin constructor

VarnishAdmin::connect
VarnishAdmin::disconnect
VarnishAdmin
PHP Manual

VarnishAdmin::__construct

(PECL varnish >= 0.3)

VarnishAdmin::__construct — VarnishAdmin constructor

Descrierea

public VarnishAdmin::__construct ([ array $args ] )

Parametri

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

Valorile întoarse

Exemple

Example #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::disconnect
VarnishAdmin


Disconnect from a varnish instance administration interface

VarnishAdmin::__construct
VarnishAdmin::getPanic
VarnishAdmin
PHP Manual

VarnishAdmin::disconnect

(PECL varnish >= 1.0.0)

VarnishAdmin::disconnect — Disconnect from a varnish instance administration interface

Descrierea

public bool VarnishAdmin::disconnect ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

VarnishAdmin::__construct
VarnishAdmin::getPanic
VarnishAdmin


Get the last panic message on a varnish instance

VarnishAdmin::disconnect
VarnishAdmin::getParams
VarnishAdmin
PHP Manual

VarnishAdmin::getPanic

(PECL varnish >= 0.4)

VarnishAdmin::getPanic — Get the last panic message on a varnish instance

Descrierea

public string VarnishAdmin::getPanic ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the last panic message on the current varnish instance.

VarnishAdmin::disconnect
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

Descrierea

public array VarnishAdmin::getParams ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool VarnishAdmin::isRunning ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public void VarnishAdmin::setCompat ( int $compat )

Parametri

compat

Varnish compatibility option.

Valorile întoarse

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

Descrierea

public void VarnishAdmin::setHost ( string $host )

Parametri

host

Connection host configuration parameter.

Valorile întoarse

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

Descrierea

public void VarnishAdmin::setIdent ( string $ident )

Parametri

ident

Connection ident configuration parameter.

Valorile întoarse

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

Descrierea

public int VarnishAdmin::setParam ( string $name , string|integer $value )

Parametri

name

Varnish configuration param name.

value

Varnish configuration param value.

Valorile întoarse

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

Descrierea

public void VarnishAdmin::setPort ( int $port )

Parametri

port

Connection port configuration parameter.

Valorile întoarse

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

Descrierea

public void VarnishAdmin::setSecret ( string $secret )

Parametri

secret

Connection secret configuration parameter.

Valorile întoarse

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

Descrierea

public void VarnishAdmin::setTimeout ( int $timeout )

Parametri

timeout

Connection timeout configuration parameter.

Valorile întoarse

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

Descrierea

public int VarnishAdmin::start ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int VarnishAdmin::stop ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the varnish command status.

VarnishAdmin::start
VarnishStat
VarnishAdmin


The VarnishStat class

(PECL varnish >= 0.3)

Introducere

Sinopsisul clasei

VarnishStat {
/* Metode */
public __construct ([ array $args ] )
public array getSnapshot ( void )
}

Cuprins

  • 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

Descrierea

public VarnishStat::__construct ([ array $args ] )

Parametri

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident path

Valorile întoarse

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

Descrierea

public array VarnishStat::getSnapshot ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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)

Introducere

Sinopsisul clasei

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 ;
/* Metode */
public __construct ([ array $args ] )
public array getLine ( void )
public static string getTagName ( int $index )
}

Constante predefinite

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

Cuprins

  • 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

Descrierea

public VarnishLog::__construct ([ array $args ] )

Parametri

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident path

Valorile întoarse

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

Descrierea

public array VarnishLog::getLine ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public static string VarnishLog::getTagName ( int $index )

Parametri

index

Log tag index.

Valorile întoarse

Returns the log tag name as string.

VarnishLog::getLine
YAZ
VarnishLog


YAZ

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii YAZ
    • 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
Introducere
Alte servicii


Introducere

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/.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.0.0.

YAZ
Instalarea / configurarea
YAZ


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
YAZ


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/yaz

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Nota: 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.

Avertizare

Extensiile IMAP, recode, YAZ ?i Cyrus nu pot fi utilizate împreuna, deoarece ele utilizeaza acelea?i simboluri interne. Nota: Yaz 2.0 ?i ulterior nu manifesta aceasta problema

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
YAZ


Exemple

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.

Example #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>';
    }
}
?>

Constante predefinite
Func?ii YAZ
YAZ


Func?ii YAZ

Cuprins

  • 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
Exemple
yaz_addinfo
YAZ


Returns additional error information

Func?ii YAZ
yaz_ccl_conf
Func?ii YAZ
PHP Manual

yaz_addinfo

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_addinfo — Returns additional error information

Descrierea

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().

Parametri

id

The connection resource returned by yaz_connect().

Valorile întoarse

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.

A se vedea ?i

  • yaz_error() - Returns error description
  • yaz_errno() - Returns error number

Func?ii YAZ
yaz_ccl_conf
Func?ii YAZ


Configure CCL parser

yaz_addinfo
yaz_ccl_parse
Func?ii YAZ
PHP Manual

yaz_ccl_conf

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_ccl_conf — Configure CCL parser

Descrierea

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.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

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.

Example #1 CCL configuration

<?php
$fields = array(
  "ti" => "1=4",
  "au"   => "1=1",
  "isbn" => "1=7"
);
yaz_ccl_conf($id, $fields);
?>

A se vedea ?i

  • yaz_ccl_parse() - Invoke CCL Parser

yaz_addinfo
yaz_ccl_parse
Func?ii YAZ


Invoke CCL Parser

yaz_ccl_conf
yaz_close
Func?ii YAZ
PHP Manual

yaz_ccl_parse

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_ccl_parse — Invoke CCL Parser

Descrierea

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.

Parametri

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)

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii YAZ


Close YAZ connection

yaz_ccl_parse
yaz_connect
Func?ii YAZ
PHP Manual

yaz_close

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_close — Close YAZ connection

Descrierea

bool yaz_close ( resource $id )

Closes the connection given by parameter id.

Nota:

This function will only close a non-persistent connection opened by setting the persistent option to FALSE with yaz_connect().

Parametri

id

The connection resource returned by yaz_connect().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • yaz_connect() - Prepares for a connection to a Z39.50 server

yaz_ccl_parse
yaz_connect
Func?ii YAZ


Prepares for a connection to a Z39.50 server

yaz_close
yaz_database
Func?ii YAZ
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

Descrierea

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.

Nota:

The » YAZ proxy is a freely available Z39.50 proxy.

Parametri

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.

Nota:

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.

Nota:

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.

Nota:

This option is supported in PECL YAZ 1.0.5 or later.

Valorile întoarse

A connection resource on success, FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
4.1.0 | The parameter options was added.

A se vedea ?i

  • yaz_close() - Close YAZ connection

yaz_close
yaz_database
Func?ii YAZ


Specifies the databases within a session

yaz_connect
yaz_element
Func?ii YAZ
PHP Manual

yaz_database

(PHP 4 >= 4.0.6, PECL yaz >= 0.9.0)

yaz_database — Specifies the databases within a session

Descrierea

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().

Parametri

id

The connection resource returned by yaz_connect().

databases

A string containing one or more databases. Multiple databases are separated by a plus sign +.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

yaz_connect
yaz_element
Func?ii YAZ


Specifies Element-Set Name for retrieval

yaz_database
yaz_errno
Func?ii YAZ
PHP Manual

yaz_element

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_element — Specifies Element-Set Name for retrieval

Descrierea

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.

Nota:

If this function appears to have no effect, see the description of the piggybacking option in yaz_connect().

Parametri

id

The connection resource returned by yaz_connect().

elementset

Most servers support F (for full records) and B (for brief records).

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

yaz_database
yaz_errno
Func?ii YAZ


Returns error number

yaz_element
yaz_error
Func?ii YAZ
PHP Manual

yaz_errno

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_errno — Returns error number

Descrierea

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).

Parametri

id

The connection resource returned by yaz_connect().

Valorile întoarse

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.

A se vedea ?i

  • yaz_error() - Returns error description
  • yaz_addinfo() - Returns additional error information

yaz_element
yaz_error
Func?ii YAZ


Returns error description

yaz_errno
yaz_es_result
Func?ii YAZ
PHP Manual

yaz_error

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_error — Returns error description

Descrierea

string yaz_error ( resource $id )

yaz_error() returns an English text message corresponding to the last error number as returned by yaz_errno().

Parametri

id

The connection resource returned by yaz_connect().

Valorile întoarse

Returns an error text message for server (last request), identified by parameter id. An empty string is returned if the last operation was successful.

A se vedea ?i

  • yaz_errno() - Returns error number
  • yaz_addinfo() - Returns additional error information

yaz_errno
yaz_es_result
Func?ii YAZ


Inspects Extended Services Result

yaz_error
yaz_es
Func?ii YAZ
PHP Manual

yaz_es_result

(PHP 4 >= 4.2.0, PECL yaz >= 0.9.0)

yaz_es_result — Inspects Extended Services Result

Descrierea

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().

Parametri

id

The connection resource returned by yaz_connect().

Valorile întoarse

Returns array with element targetReference for the reference for the extended service operation (generated and returned from the server).

A se vedea ?i

  • yaz_es() - Prepares for an Extended Service Request

yaz_error
yaz_es
Func?ii YAZ


Prepares for an Extended Service Request

yaz_es_result
yaz_get_option
Func?ii YAZ
PHP Manual

yaz_es

(PECL yaz >= 0.9.0)

yaz_es — Prepares for an Extended Service Request

Descrierea

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.

Nota:

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().

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);
?>

A se vedea ?i

  • yaz_es_result() - Inspects Extended Services Result

yaz_es_result
yaz_get_option
Func?ii YAZ


Returns value of option for connection

yaz_es
yaz_hits
Func?ii YAZ
PHP Manual

yaz_get_option

(PECL yaz >= 0.9.0)

yaz_get_option — Returns value of option for connection

Descrierea

string yaz_get_option ( resource $id , string $name )

Returns the value of the option specified with name.

Parametri

id

The connection resource returned by yaz_connect().

name

The option name.

Valorile întoarse

Returns the value of the specified option or an empty string if the option wasn't set.

A se vedea ?i

  • The description of yaz_set_option() - Sets one or more options for connection for available options

yaz_es
yaz_hits
Func?ii YAZ


Returns number of hits for last search

yaz_get_option
yaz_itemorder
Func?ii YAZ
PHP Manual

yaz_hits

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_hits — Returns number of hits for last search

Descrierea

int yaz_hits ( resource $id [, array &$searchresult ] )

yaz_hits() returns the number of hits for the last search.

Parametri

id

The connection resource returned by yaz_connect().

searchresult

Result array for detailed search result information.

Valorile întoarse

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)

Nota:

The SearchResult facility requires PECL YAZ 1.0.5 or later and YAZ 2.1.9 or later.

Nota:

Very few Z39.50 implementations support the SearchResult facility.

yaz_get_option
yaz_itemorder
Func?ii YAZ


Prepares for Z39.50 Item Order with an ILL-Request package

yaz_hits
yaz_present
Func?ii YAZ
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

Descrierea

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.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

yaz_hits
yaz_present
Func?ii YAZ


Prepares for retrieval (Z39.50 present)

yaz_itemorder
yaz_range
Func?ii YAZ
PHP Manual

yaz_present

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_present — Prepares for retrieval (Z39.50 present)

Descrierea

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.

Parametri

id

The connection resource returned by yaz_connect().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

yaz_itemorder
yaz_range
Func?ii YAZ


Specifies a range of records to retrieve

yaz_present
yaz_record
Func?ii YAZ
PHP Manual

yaz_range

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_range — Specifies a range of records to retrieve

Descrierea

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().

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

yaz_present
yaz_record
Func?ii YAZ


Returns a record

yaz_range
yaz_scan_result
Func?ii YAZ
PHP Manual

yaz_record

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_record — Returns a record

Descrierea

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.

Parametri

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.

Nota:

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).

Valorile întoarse

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.

Exemple

Example #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.
        )
)

Example #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
Func?ii YAZ


Returns Scan Response result

yaz_record
yaz_scan
Func?ii YAZ
PHP Manual

yaz_scan_result

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_scan_result — Returns Scan Response result

Descrierea

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().

Parametri

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

Valorile întoarse

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
Func?ii YAZ


Prepares for a scan

yaz_scan_result
yaz_schema
Func?ii YAZ
PHP Manual

yaz_scan

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_scan — Prepares for a scan

Descrierea

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.

Parametri

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).

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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
Func?ii YAZ


Specifies schema for retrieval

yaz_scan
yaz_search
Func?ii YAZ
PHP Manual

yaz_schema

(PHP 4 >= 4.2.0, PECL yaz >= 0.9.0)

yaz_schema — Specifies schema for retrieval

Descrierea

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().

Parametri

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, ...

Valorile întoarse

Nu este întoarsa nici o valoare.

yaz_scan
yaz_search
Func?ii YAZ


Prepares for a search

yaz_schema
yaz_set_option
Func?ii YAZ
PHP Manual

yaz_search

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_search — Prepares for a search

Descrierea

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.

Parametri

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.

Nota:

If you would like to use a more friendly notation, use the CCL parser - functions yaz_ccl_conf() and yaz_ccl_parse().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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
Func?ii YAZ


Sets one or more options for connection

yaz_search
yaz_sort
Func?ii YAZ
PHP Manual

yaz_set_option

(PECL yaz >= 0.9.0)

yaz_set_option — Sets one or more options for connection

Descrierea

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.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

yaz_search
yaz_sort
Func?ii YAZ


Sets sorting criteria

yaz_set_option
yaz_syntax
Func?ii YAZ
PHP Manual

yaz_sort

(PHP 4 >= 4.0.7, PECL yaz >= 0.9.0)

yaz_sort — Sets sorting criteria

Descrierea

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().

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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
Func?ii YAZ


Specifies the preferred record syntax for retrieval

yaz_sort
yaz_wait
Func?ii YAZ
PHP Manual

yaz_syntax

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_syntax — Specifies the preferred record syntax for retrieval

Descrierea

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().

Parametri

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.).

Valorile întoarse

Nu este întoarsa nici o valoare.

yaz_sort
yaz_wait
Func?ii YAZ


Wait for Z39.50 requests to complete

yaz_syntax
YP/NIS
Func?ii YAZ
PHP Manual

yaz_wait

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_wait — Wait for Z39.50 requests to complete

Descrierea

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).

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. In event mode, returns resource sau FALSE în cazul e?ecului.

yaz_syntax
YP/NIS
Func?ii YAZ


YP/NIS

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii YP/NIS
    • 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
Introducere
Alte servicii


Introducere

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.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.1.0.

Nota: Aceasta extensie nu este disponibila pe platformele Windows.

YP/NIS
Instalarea / configurarea
YP/NIS


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
YP/NIS


Necesita?i

None besides functions from standard Unix libraries which are always available (either libc or libnsl, configure will detect which one to use).

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie este considerata ne-între?inuta ?i moarta. Oricum însa codul-sursa al acestei extensii este înca disponibil în PECL SVN aici: » http://svn.php.net/viewvc/pecl/yp

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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
Tipurile resurselor
Func?ii YP/NIS
YP/NIS


Func?ii YP/NIS

Cuprins

  • 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
Constante predefinite
yp_all
YP/NIS


Traverse the map and call a function on each entry

Func?ii YP/NIS
yp_cat
Func?ii YP/NIS
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

Descrierea

void yp_all ( string $domain , string $map , string $callback )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

domain

The NIS domain name.

map

The NIS map.

callback

Valorile întoarse

Nu este întoarsa nici o valoare.

Func?ii YP/NIS
yp_cat
Func?ii YP/NIS


Return an array containing the entire map

yp_all
yp_err_string
Func?ii YP/NIS
PHP Manual

yp_cat

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5)

yp_cat — Return an array containing the entire map

Descrierea

array yp_cat ( string $domain , string $map )

Returns all map entries.

Parametri

domain

The NIS domain name.

map

The NIS map.

Valorile întoarse

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
Func?ii YP/NIS


Returns the error string associated with the given error code

yp_cat
yp_errno
Func?ii YP/NIS
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

Descrierea

string yp_err_string ( int $errorcode )

Returns the error message associated with the given error code. Useful to indicate what exactly went wrong.

Parametri

errorcode

The error code.

Valorile întoarse

Returns the error message, as a string.

Exemple

Example #1 Example for NIS errors

<?php
echo "Error: " . yp_err_string(yp_errno());
?>

A se vedea ?i

  • yp_errno() - Returns the error code of the previous operation

yp_cat
yp_errno
Func?ii YP/NIS


Returns the error code of the previous operation

yp_err_string
yp_first
Func?ii YP/NIS
PHP Manual

yp_errno

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5)

yp_errno — Returns the error code of the previous operation

Descrierea

int yp_errno ( void )

Returns the error code of the previous operation.

Valorile întoarse

Returns one of the YPERR_XXX error constants.

A se vedea ?i

  • yp_err_string() - Returns the error string associated with the given error code

yp_err_string
yp_first
Func?ii YP/NIS


Returns the first key-value pair from the named map

yp_errno
yp_get_default_domain
Func?ii YP/NIS
PHP Manual

yp_first

(PHP 4, PHP 5 <= 5.0.5)

yp_first — Returns the first key-value pair from the named map

Descrierea

array yp_first ( string $domain , string $map )

Gets the first key-value pair from the named map in the named domain.

Parametri

domain

The NIS domain name.

map

The NIS map.

Valorile întoarse

Returns the first key-value pair as an array on success, or FALSE on errors.

Exemple

Example #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;
?>

A se vedea ?i

  • 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
Func?ii YP/NIS


Fetches the machine's default NIS domain

yp_first
yp_master
Func?ii YP/NIS
PHP Manual

yp_get_default_domain

(PHP 4, PHP 5 <= 5.0.5)

yp_get_default_domain — Fetches the machine's default NIS domain

Descrierea

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.

Valorile întoarse

Returns the default domain of the node or FALSE. Can be used as the domain parameter for successive NIS calls.

Exemple

Example #1 Example for the default domain

<?php
$domain = yp_get_default_domain();
echo "Default NIS domain is: " . $domain;
?>

yp_first
yp_master
Func?ii YP/NIS


Returns the machine name of the master NIS server for a map

yp_get_default_domain
yp_match
Func?ii YP/NIS
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

Descrierea

string yp_master ( string $domain , string $map )

Returns the machine name of the master NIS server for a map.

Parametri

domain

The NIS domain name.

map

The NIS map.

Valorile întoarse

Exemple

Example #1 Example for the NIS master

<?php
$number = yp_master($domain, $mapname);
echo "Master for this map is: " . $master;
?>

A se vedea ?i

  • yp_get_default_domain() - Fetches the machine's default NIS domain

yp_get_default_domain
yp_match
Func?ii YP/NIS


Returns the matched line

yp_master
yp_next
Func?ii YP/NIS
PHP Manual

yp_match

(PHP 4, PHP 5 <= 5.0.5)

yp_match — Returns the matched line

Descrierea

string yp_match ( string $domain , string $map , string $key )

Returns the value associated with the passed key out of the specified map.

Parametri

domain

The NIS domain name.

map

The NIS map.

key

This key must be exact.

Valorile întoarse

Returns the value, or FALSE on errors.

Exemple

Example #1 Example for NIS match

<?php
$entry = yp_match($domain, "passwd.byname", "joe");
echo "Matched entry is: " . $entry;
?>

Exemplul de mai sus va afi?a ceva similar cu:

joe:##joe:11111:100:Joe User:/home/j/joe:/usr/local/bin/bash

A se vedea ?i

  • yp_get_default_domain() - Fetches the machine's default NIS domain

yp_master
yp_next
Func?ii YP/NIS


Returns the next key-value pair in the named map

yp_match
yp_order
Func?ii YP/NIS
PHP Manual

yp_next

(PHP 4, PHP 5 <= 5.0.5)

yp_next — Returns the next key-value pair in the named map

Descrierea

array yp_next ( string $domain , string $map , string $key )

Returns the next key-value pair in the named map after the specified key.

Parametri

domain

map

key

Valorile întoarse

Returns the next key-value pair as an array, or FALSE on errors.

Exemple

Example #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];
?>

A se vedea ?i

  • 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
Func?ii YP/NIS


Returns the order number for a map

yp_next
0MQ messaging
Func?ii YP/NIS
PHP Manual

yp_order

(PHP 4, PHP 5 <= 5.0.5)

yp_order — Returns the order number for a map

Descrierea

int yp_order ( string $domain , string $map )

Gets the order number for a map.

Parametri

domain

map

Valorile întoarse

Returns the order number for a map or FALSE on error.

Exemple

Example #1 Example for the NIS order

<?php
    $number = yp_order($domain, $mapname);
    echo "Order number for this map is: " . $number;
?>

A se vedea ?i

  • yp_get_default_domain() - Fetches the machine's default NIS domain

yp_next
0MQ messaging
Func?ii YP/NIS


ZMQ

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
  • ZMQ — The ZMQ class
    • ZMQ::__construct — ZMQ constructor
  • ZMQContext — The ZMQContext class
    • ZMQContext::__construct — Construct a new ZMQContext object
    • ZMQContext::getOpt — Get context option
    • ZMQContext::getSocket — Create a new socket
    • ZMQContext::isPersistent — Whether the context is persistent
    • ZMQContext::setOpt — Set a socket option
  • ZMQSocket — The ZMQSocket class
    • ZMQSocket::bind — Bind the socket
    • ZMQSocket::connect — Connect the socket
    • ZMQSocket::__construct — Construct a new ZMQSocket
    • ZMQSocket::disconnect — Disconnect a socket
    • ZMQSocket::getEndpoints — Get list of endpoints
    • ZMQSocket::getPersistentId — Get the persistent id
    • ZMQSocket::getSocketType — Get the socket type
    • ZMQSocket::getSockOpt — Get socket option
    • ZMQSocket::isPersistent — Whether the socket is persistent
    • ZMQSocket::recv — Receives a message
    • ZMQSocket::recvMulti — Receives a multipart message
    • ZMQSocket::send — Sends a message
    • ZMQSocket::sendmulti — Sends a multipart message
    • ZMQSocket::setSockOpt — Set a socket option
    • ZMQSocket::unbind — Unbind the socket
  • ZMQPoll — The ZMQPoll class
    • ZMQPoll::add — Add item to the poll set
    • ZMQPoll::clear — Clear the poll set
    • ZMQPoll::count — Count items in the poll set
    • ZMQPoll::getLastErrors — Get poll errors
    • ZMQPoll::poll — Poll the items
    • ZMQPoll::remove — Remove item from poll set
  • ZMQDevice — The ZMQDevice class
    • ZMQDevice::__construct — Construct a new device
    • ZMQDevice::getIdleTimeout — Get the idle timeout
    • ZMQDevice::getTimerTimeout — Get the timer timeout
    • ZMQDevice::run — Run the new device
    • ZMQDevice::setIdleCallback — Set the idle callback function
    • ZMQDevice::setIdleTimeout — Set the idle timeout
    • ZMQDevice::setTimerCallback — Set the timer callback function
    • ZMQDevice::setTimerTimeout — Set the timer timeout
yp_order
Introducere
Alte servicii


Introducere

"ØMQ is a software library that lets you quickly design and implement a fast message-based application." --0MQ Website

For more information about 0MQ, see » http://zeromq.org/.

0MQ messaging
Instalarea / configurarea
0MQ messaging


Instalarea / configurarea

Cuprins

  • Necesita?i
Introducere
Necesita?i
0MQ messaging


Necesita?i

Extensia ZMQ necesita 0MQ de versiunea 2.0.7 sau ulterioara. 0MQ poate fi ob?inut la adresa » http://zeromq.org/area:download.

Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/zmq

Instalarea / configurarea
ZMQ
Instalarea / configurarea


The ZMQ class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

ZMQ {
/* Constants */
const integer SOCKET_PAIR ;
const integer SOCKET_PUB ;
const integer SOCKET_SUB ;
const integer SOCKET_REQ ;
const integer SOCKET_REP ;
const integer SOCKET_XREQ ;
const integer SOCKET_XREP ;
const integer SOCKET_PUSH ;
const integer SOCKET_PULL ;
const integer SOCKET_ROUTER ;
const integer SOCKET_DEALER ;
const integer SOCKET_XPUB ;
const integer SOCKET_XSUB ;
const integer SOCKET_STREAM ;
const integer SOCKOPT_HWM ;
const integer SOCKOPT_SNDHWM ;
const integer SOCKOPT_RCVHWM ;
const integer SOCKOPT_AFFINITY ;
const integer SOCKOPT_IDENTITY ;
const integer SOCKOPT_SUBSCRIBE ;
const integer SOCKOPT_UNSUBSCRIBE ;
const integer SOCKOPT_RATE ;
const integer SOCKOPT_RECOVERY_IVL ;
const integer SOCKOPT_RECONNECT_IVL ;
const integer SOCKOPT_RECONNECT_IVL_MAX ;
const integer SOCKOPT_MCAST_LOOP ;
const integer SOCKOPT_SNDBUF ;
const integer SOCKOPT_RCVBUF ;
const integer SOCKOPT_RCVMORE ;
const integer SOCKOPT_TYPE ;
const integer SOCKOPT_LINGER ;
const integer SOCKOPT_BACKLOG ;
const integer SOCKOPT_MAXMSGSIZE ;
const integer SOCKOPT_SNDTIMEO ;
const integer SOCKOPT_RCVTIMEO ;
const integer SOCKOPT_IPV4ONLY ;
const integer SOCKOPT_LAST_ENDPOINT ;
const integer SOCKOPT_TCP_KEEPALIVE_IDLE ;
const integer SOCKOPT_TCP_KEEPALIVE_CNT ;
const integer SOCKOPT_TCP_KEEPALIVE_INTVL ;
const integer SOCKOPT_TCP_ACCEPT_FILTER ;
const integer SOCKOPT_TCP_ACCEPT_FILTER ;
const integer SOCKOPT_DELAY_ATTACH_ON_CONNECT ;
const integer SOCKOPT_XPUB_VERBOSE ;
const integer SOCKOPT_ROUTER_RAW ;
const integer SOCKOPT_IPV6 ;
const integer CTXOPT_MAX_SOCKETS ;
const integer POLL_IN ;
const integer POLL_OUT ;
const integer MODE_NOBLOCK ;
const integer MODE_DONTWAIT ;
const integer MODE_SNDMORE ;
const integer ERR_INTERNAL ;
const integer ERR_EAGAIN ;
const integer ERR_ENOTSUP ;
const integer ERR_EFSM ;
const integer ERR_ETERM ;
/* Methods */
private__construct ( void )
}

Constante predefinite

ZMQ Constant Types

ZMQ::SOCKET_PAIR

Exclusive pair pattern

ZMQ::SOCKET_PUB

Publisher socket

ZMQ::SOCKET_SUB

Subscriber socket

ZMQ::SOCKET_REQ

Request socket

ZMQ::SOCKET_REP

Reply socket

ZMQ::SOCKET_XREQ

Alias for SOCKET_DEALER

ZMQ::SOCKET_XREP

Alias for SOCKET_ROUTER

ZMQ::SOCKET_PUSH

Pipeline upstream push socket

ZMQ::SOCKET_PULL

Pipeline downstream pull socket

ZMQ::SOCKET_ROUTER

Extended REP socket that can route replies to requesters

ZMQ::SOCKET_DEALER

Extended REQ socket that load balances to all connected peers

ZMQ::SOCKET_XPUB

Similar to SOCKET_PUB, except you can receive subscriptions as messages. The subscription message is 0 (unsubscribe) or 1 (subscribe) followed by the topic.

ZMQ::SOCKET_XSUB

Similar to SOCKET_SUB, except you can send subscriptions as messages. See SOCKET_XPUB for format.

ZMQ::SOCKET_STREAM

Used to send and receive TCP data from a non-ØMQ peer. Available if compiled against ZeroMQ 4.x or higher (Value: integer).

ZMQ::SOCKOPT_HWM

The high water mark for inbound and outbound messages is a hard limit on the maximum number of outstanding messages ØMQ shall queue in memory for any single peer that the specified socket is communicating with. Setting this option on a socket will only affect connections made after the option has been set. On ZeroMQ 3.x this is a wrapper for setting both SNDHWM and RCVHWM. (Value: integer).

ZMQ::SOCKOPT_SNDHWM

The ZMQ_SNDHWM option shall set the high water mark for outbound messages on the specified socket. Available if compiled against ZeroMQ 3.x or higher (Value: integer).

ZMQ::SOCKOPT_RCVHWM

The ZMQ_SNDHWM option shall set the high water mark for inbound messages on the specified socket. Available if compiled against ZeroMQ 3.x or higher (Value: integer).

ZMQ::SOCKOPT_AFFINITY

Set I/O thread affinity (Value: integer)

ZMQ::SOCKOPT_IDENTITY

Set socket identity (Value: string)

ZMQ::SOCKOPT_SUBSCRIBE

Establish message filter. Valid for subscriber socket (Value: string)

ZMQ::SOCKOPT_UNSUBSCRIBE

Remove message filter. Valid for subscriber socket (Value: string)

ZMQ::SOCKOPT_RATE

Set rate for multicast sockets (pgm) (Value: integer >= 0)

ZMQ::SOCKOPT_RECOVERY_IVL

Set multicast recovery interval (Value: integer >= 0)

ZMQ::SOCKOPT_RECONNECT_IVL

Set the initial reconnection interval (Value: integer >= 0)

ZMQ::SOCKOPT_RECONNECT_IVL_MAX

Set the max reconnection interval (Value: integer >= 0)

ZMQ::SOCKOPT_MCAST_LOOP

Control multicast loopback (Value: integer >= 0)

ZMQ::SOCKOPT_SNDBUF

Set kernel transmit buffer size (Value: integer >= 0)

ZMQ::SOCKOPT_RCVBUF

Set kernel receive buffer size (Value: integer >= 0)

ZMQ::SOCKOPT_RCVMORE

Receive multi-part messages (Value: integer)

ZMQ::SOCKOPT_TYPE

Get the socket type. Valid for getSockOpt (Value: integer)

ZMQ::SOCKOPT_LINGER

The linger value of the socket. Specifies how long the socket blocks trying flush messages after it has been closed (Value: integer)

ZMQ::SOCKOPT_BACKLOG

The SOCKOPT_BACKLOG option shall set the maximum length of the queue of outstanding peer connections for the specified socket; this only applies to connection-oriented transports. (Value: integer)

ZMQ::SOCKOPT_MAXMSGSIZE

Limits the maximum size of the inbound message. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_SNDTIMEO

Sets the timeout for send operation on the socket. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_RCVTIMEO

Sets the timeout for receive operation on the socket. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_IPV4ONLY

Disable IPV6 support if 1. Available if compiled against ZeroMQ 3.x (Value: integer)

ZMQ::SOCKOPT_LAST_ENDPOINT

Retrieve the last connected endpoint - for use with * wildcard ports. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_TCP_KEEPALIVE_IDLE

Idle time for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_TCP_KEEPALIVE_CNT

Count time for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_TCP_KEEPALIVE_INTVL

Interval for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_DELAY_ATTACH_ON_CONNECT

Set a CIDR string to match against incoming TCP connections. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_TCP_ACCEPT_FILTER

Set a CIDR string to match against incoming TCP connections. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_XPUB_VERBOSE

Set the XPUB to receive an application message on each instance of a subscription. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_ROUTER_RAW

Sets the raw mode on the ROUTER, when set to 1. In raw mode when using tcp:// transport the socket will read and write without ZeroMQ framing. Available if compiled against ZeroMQ 4.0 or higher (Value: string)

ZMQ::SOCKOPT_IPV6

Enable IPV6. Available if compiled against ZeroMQ 4.0 or higher (Value: string)

ZMQ::CTXOPT_MAX_SOCKETS

The socket limit for this context. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::POLL_IN

Poll for incoming data

ZMQ::POLL_OUT

Poll for outgoing data

ZMQ::MODE_NOBLOCK

Non-blocking operation. Deprecated, use ZMQ::MODE_DONTWAIT instead

ZMQ::MODE_DONTWAIT

Non-blocking operation

ZMQ::MODE_SNDMORE

Send multi-part message

ZMQ::DEVICE_FORWARDER

Forwarder device

ZMQ::DEVICE_QUEUE

Queue device

ZMQ::DEVICE_STREAMER

Streamer device

ZMQ::ERR_INTERNAL

ZMQ extension internal error

ZMQ::ERR_EAGAIN

Implies that the operation would block when ZMQ::MODE_DONTWAIT is used

ZMQ::ERR_ENOTSUP

The operation is not supported by the socket type

ZMQ::ERR_EFSM

The operation can not be executed because the socket is not in correct state

ZMQ::ERR_ETERM

The context has been terminated

Cuprins

  • ZMQ::__construct — ZMQ constructor
Necesita?i
ZMQ::__construct
0MQ messaging


ZMQ constructor

ZMQ
ZMQContext
ZMQ
PHP Manual

ZMQ::__construct

(PECL zmq >= 0.5.0)

ZMQ::__construct — ZMQ constructor

Descrierea

privateZMQ::__construct ( void )

Private constructor to prevent direct initialization. This class holds the constants for ZMQ extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ZMQ
ZMQContext
ZMQ


The ZMQContext class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

ZMQContext {
/* Methods */
__construct ([ integer $io_threads = 1 [, boolean $is_persistent = true ]] )
public mixed getOpt ( string $key )
public ZMQSocket getSocket ( integer $type [, string $persistent_id = null [, callback $on_new_socket = null ]] )
public boolean isPersistent ( void )
public ZMQContext setOpt ( integer $key , mixed $value )
}

Cuprins

  • ZMQContext::__construct — Construct a new ZMQContext object
  • ZMQContext::getOpt — Get context option
  • ZMQContext::getSocket — Create a new socket
  • ZMQContext::isPersistent — Whether the context is persistent
  • ZMQContext::setOpt — Set a socket option
ZMQ::__construct
ZMQContext::__construct
0MQ messaging


Construct a new ZMQContext object

ZMQContext
ZMQContext::getOpt
ZMQContext
PHP Manual

ZMQContext::__construct

(PECL zmq >= 0.5.0)

ZMQContext::__construct — Construct a new ZMQContext object

Descrierea

ZMQContext::__construct ([ integer $io_threads = 1 [, boolean $is_persistent = true ]] )

Constructs a new ZMQ context. The context is used to initialize sockets. A persistent context is required to initialize persistent sockets.

Parametri

io_threads

Number of io-threads in the context.

is_persistent

Whether the context is persistent. Persistent context is stored over multiple requests and is a requirement for persistent sockets.

Exemple

Example #1 A ZMQContext() example

Construct a new context and allocate request socket from it

<?php
/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REQ, 'my sock');

/* Connect the socket */
$socket->connect("tcp://example.com:1234");

/* Send a request */
$socket->send("Hello there");

/* Receive back the response */
$message = $socket->recv();
?>

Valorile întoarse

Throws ZMQContextException if context initialization fails.

ZMQContext
ZMQContext::getOpt
ZMQContext


Get context option

ZMQContext::__construct
ZMQContext::getSocket
ZMQContext
PHP Manual

ZMQContext::getOpt

(PECL zmq >= 1.0.4)

ZMQContext::getOpt — Get context option

Descrierea

public mixed ZMQContext::getOpt ( string $key )

Returns the value of a context option.

Parametri

key

An integer representing the option. See the ZMQ::CTXOPT_* constants.

Valorile întoarse

Returns either a string or an integer depending on key. Throws ZMQContextException on error.

ZMQContext::__construct
ZMQContext::getSocket
ZMQContext


Create a new socket

ZMQContext::getOpt
ZMQContext::isPersistent
ZMQContext
PHP Manual

ZMQContext::getSocket

(PECL zmq >= 0.5.0)

ZMQContext::getSocket — Create a new socket

Descrierea

public ZMQSocket ZMQContext::getSocket ( integer $type [, string $persistent_id = null [, callback $on_new_socket = null ]] )

Shortcut for creating new sockets from the context. If the context is not persistent the persistent_id parameter is ignored and the socket falls back to being non-persistent. The on_new_socket is called only when a new underlying socket structure is created.

Parametri

type

ZMQ::SOCKET_* constant to specify socket type.

persistent_id

If persistent_id is specified the socket will be persisted over multiple requests.

on_new_socket

Callback function, which is executed when a new socket structure is created. This function does not get invoked if the underlying persistent connection is re-used. The callback takes ZMQSocket and persistent_id as two arguments.

Exemple

Example #1 A ZMQContext() example

Basic usage

<?php
/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REQ, 'my sock');

/* Connect the socket */
$socket->connect("tcp://example.com:1234");

/* Send a request */
$socket->send("Hello there");

/* Receive back the response */
$message = $socket->recv();
echo "Received message: {$message}\n";
?>

Valorile întoarse

Returns a ZMQSocket object on success. Throws ZMQSocketException on error.

ZMQContext::getOpt
ZMQContext::isPersistent
ZMQContext


Whether the context is persistent

ZMQContext::getSocket
ZMQContext::setOpt
ZMQContext
PHP Manual

ZMQContext::isPersistent

(PECL zmq >= 0.5.0)

ZMQContext::isPersistent — Whether the context is persistent

Descrierea

public boolean ZMQContext::isPersistent ( void )

Whether the context is persistent. Persistent context is needed for persistent connections as each socket is allocated from a context.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the context is persistent and FALSE if the context is non-persistent.

ZMQContext::getSocket
ZMQContext::setOpt
ZMQContext


Set a socket option

ZMQContext::isPersistent
ZMQSocket
ZMQContext
PHP Manual

ZMQContext::setOpt

(PECL zmq >= 1.0.4)

ZMQContext::setOpt — Set a socket option

Descrierea

public ZMQContext ZMQContext::setOpt ( integer $key , mixed $value )

Sets a ZMQ context option. The type of the value depends on the key. See ZMQ Constant Types for more information.

Parametri

key

One of the ZMQ::CTXOPT_* constants.

value

The value of the parameter.

Valorile întoarse

Returns the current object. Throws ZMQContextException on error.

ZMQContext::isPersistent
ZMQSocket
ZMQContext


The ZMQSocket class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

ZMQSocket {
/* Methods */
public ZMQSocket bind ( string $dsn [, boolean $force = false ] )
public ZMQSocket connect ( string $dsn [, boolean $force = false ] )
__construct ( ZMQContext $context , int $type [, string $persistent_id = null [, callback $on_new_socket = null ]] )
public ZMQSocket disconnect ( string $dsn )
public array getEndpoints ( void )
public string getPersistentId ( void )
public integer getSocketType ( void )
public mixed getSockOpt ( string $key )
public boolean isPersistent ( void )
public string recv ([ integer $mode = 0 ] )
public string recvMulti ([ integer $mode = 0 ] )
public ZMQSocket send ( string $message [, integer $mode = 0 ] )
public ZMQSocket send ( array $message [, integer $mode = 0 ] )
public ZMQSocket setSockOpt ( integer $key , mixed $value )
public ZMQSocket unbind ( string $dsn )
}

Cuprins

  • ZMQSocket::bind — Bind the socket
  • ZMQSocket::connect — Connect the socket
  • ZMQSocket::__construct — Construct a new ZMQSocket
  • ZMQSocket::disconnect — Disconnect a socket
  • ZMQSocket::getEndpoints — Get list of endpoints
  • ZMQSocket::getPersistentId — Get the persistent id
  • ZMQSocket::getSocketType — Get the socket type
  • ZMQSocket::getSockOpt — Get socket option
  • ZMQSocket::isPersistent — Whether the socket is persistent
  • ZMQSocket::recv — Receives a message
  • ZMQSocket::recvMulti — Receives a multipart message
  • ZMQSocket::send — Sends a message
  • ZMQSocket::sendmulti — Sends a multipart message
  • ZMQSocket::setSockOpt — Set a socket option
  • ZMQSocket::unbind — Unbind the socket
ZMQContext::setOpt
ZMQSocket::bind
0MQ messaging


Bind the socket

ZMQSocket
ZMQSocket::connect
ZMQSocket
PHP Manual

ZMQSocket::bind

(PECL zmq >= 0.5.0)

ZMQSocket::bind — Bind the socket

Descrierea

public ZMQSocket ZMQSocket::bind ( string $dsn [, boolean $force = false ] )

Bind the socket to an endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

Parametri

dsn

The bind dsn, for example transport://address.

force

Tries to bind even if the socket has already been bound to the given endpoint.

Valorile întoarse

Returns the current object. Throws ZMQSocketException on error.

ZMQSocket
ZMQSocket::connect
ZMQSocket


Connect the socket

ZMQSocket::bind
ZMQSocket::__construct
ZMQSocket
PHP Manual

ZMQSocket::connect

(PECL zmq >= 0.5.0)

ZMQSocket::connect — Connect the socket

Descrierea

public ZMQSocket ZMQSocket::connect ( string $dsn [, boolean $force = false ] )

Connect the socket to a remote endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

Parametri

dsn

The connect dsn, for example transport://address.

force

Tries to connect even if the socket has already been connected to given endpoint.

Exemple

Example #1 A ZMQContext() example

Construct a new context and allocate request socket from it

<?php
/* Server hostname */
$dsn = "tcp://127.0.0.1:5555";

/* Create a socket */
$socket = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ, 'my socket');

/* Get list of connected endpoints */
$endpoints = $socket->getEndpoints();

/* Check if the socket is connected */
if (!in_array($dsn, $endpoints['connect'])) {
    echo "<p>Connecting to $dsn</p>";
    $socket->connect($dsn);
} else {
    echo "<p>Already connected to $dsn</p>";
}

/* Send and receive */
$socket->send("Hello!");
$message = $socket->recv();

echo "<p>Server said: {$message}</p>";
?>

Valorile întoarse

Returns the current object. Throws ZMQSocketException on error.

ZMQSocket::bind
ZMQSocket::__construct
ZMQSocket


Construct a new ZMQSocket

ZMQSocket::connect
ZMQSocket::disconnect
ZMQSocket
PHP Manual

ZMQSocket::__construct

(PECL zmq >= 0.5.0)

ZMQSocket::__construct — Construct a new ZMQSocket

Descrierea

ZMQSocket::__construct ( ZMQContext $context , int $type [, string $persistent_id = null [, callback $on_new_socket = null ]] )

Constructs a ZMQSocket object. persistent_id parameter can be used to allocated a persistent socket. A persistent socket has to be allocated from a persistent context and it stays connected over multiple requests. The persistent_id parameter can be used to recall the same socket over multiple requests. The on_new_socket is called only when a new underlying socket structure is created.

Parametri

context

ZMQContext object.

type

The socket type. See ZMQ::SOCKET_* constants.

persistent_id

If persistent_id is specified the socket will be persisted over multiple requests. If context is not persistent the socket falls back to non-persistent mode.

on_new_socket

Callback function, which is executed when a new socket structure is created. This function does not get invoked if the underlying persistent connection is re-used.

Exemple

Example #1 A ZMQSocket() example

Using callback the bind/connect socket

<?php

/*
  The socket is persistent so this function is called only on the
  first request to the script.
*/
function on_new_socket_cb(ZMQSocket $socket, $persistent_id = null)
{
    if ($persistent_id === 'server') {
        $socket->bind("tcp://localhost:12122");
    } else {
        $socket->connect("tcp://localhost:12122");
    }
}

/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REP, 'server', 'on_new_socket_cb');

$message = $socket->recv();
echo "Received message: {$message}\n";
?>

The callback signature

Nota:

function on_new_socket_cb(ZMQSocket $socket, string $persistent_id = null);

Valorile întoarse

Throws ZMQSocketException on error.

ZMQSocket::connect
ZMQSocket::disconnect
ZMQSocket


Disconnect a socket

ZMQSocket::__construct
ZMQSocket::getEndpoints
ZMQSocket
PHP Manual

ZMQSocket::disconnect

(PECL zmq >= 1.0.4)

ZMQSocket::disconnect — Disconnect a socket

Descrierea

public ZMQSocket ZMQSocket::disconnect ( string $dsn )

Disconnect the socket from a previously connected remote endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

Parametri

dsn

The connect dsn, for example transport://address.

Valorile întoarse

Returns the current object. Throws ZMQSocketException on error.

ZMQSocket::__construct
ZMQSocket::getEndpoints
ZMQSocket


Get list of endpoints

ZMQSocket::disconnect
ZMQSocket::getPersistentId
ZMQSocket
PHP Manual

ZMQSocket::getEndpoints

(PECL zmq >= 0.5.0)

ZMQSocket::getEndpoints — Get list of endpoints

Descrierea

public array ZMQSocket::getEndpoints ( void )

Returns a list of endpoints where the socket is connected or bound to.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array containing elements 'bind' and 'connect'.

ZMQSocket::disconnect
ZMQSocket::getPersistentId
ZMQSocket


Get the persistent id

ZMQSocket::getEndpoints
ZMQSocket::getSocketType
ZMQSocket
PHP Manual

ZMQSocket::getPersistentId

(PECL zmq >= 0.5.0)

ZMQSocket::getPersistentId — Get the persistent id

Descrierea

public string ZMQSocket::getPersistentId ( void )

Returns the persistent id of the socket.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the persistent id string assigned of the object and NULL if socket is not persistent.

ZMQSocket::getEndpoints
ZMQSocket::getSocketType
ZMQSocket


Get the socket type

ZMQSocket::getPersistentId
ZMQSocket::getSockOpt
ZMQSocket
PHP Manual

ZMQSocket::getSocketType

(PECL zmq >= 0.5.0)

ZMQSocket::getSocketType — Get the socket type

Descrierea

public integer ZMQSocket::getSocketType ( void )

Gets the socket type.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an integer representing the socket type. The integer can be compared against ZMQ::SOCKET_* constants.

ZMQSocket::getPersistentId
ZMQSocket::getSockOpt
ZMQSocket


Get socket option

ZMQSocket::getSocketType
ZMQSocket::isPersistent
ZMQSocket
PHP Manual

ZMQSocket::getSockOpt

(PECL zmq >= 0.5.0)

ZMQSocket::getSockOpt — Get socket option

Descrierea

public mixed ZMQSocket::getSockOpt ( string $key )

Returns the value of a socket option.

Parametri

key

An integer representing the option. See the ZMQ::SOCKOPT_* constants.

Valorile întoarse

Returns either a string or an integer depending on key. Throws ZMQSocketException on error.

ZMQSocket::getSocketType
ZMQSocket::isPersistent
ZMQSocket


Whether the socket is persistent

ZMQSocket::getSockOpt
ZMQSocket::recv
ZMQSocket
PHP Manual

ZMQSocket::isPersistent

(PECL zmq >= 0.5.0)

ZMQSocket::isPersistent — Whether the socket is persistent

Descrierea

public boolean ZMQSocket::isPersistent ( void )

Check whether the socket is persistent.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a boolean based on whether the socket is persistent or not.

ZMQSocket::getSockOpt
ZMQSocket::recv
ZMQSocket


Receives a message

ZMQSocket::isPersistent
ZMQSocket::recvMulti
ZMQSocket
PHP Manual

ZMQSocket::recv

(PECL zmq >= 0.5.0)

ZMQSocket::recv — Receives a message

Descrierea

public string ZMQSocket::recv ([ integer $mode = 0 ] )

Receive a message from a socket. By default receiving will block until a message is available unless ZMQ::MODE_NOBLOCK flag is used. ZMQ::SOCKOPT_RCVMORE socket option can be used for receiving multi-part messages. See ZMQSocket::setSockOpt() for more information.

Parametri

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

Exemple

Example #1 A send/recv example

Non-blocking send / receive

<?php

/* Create new queue object, there needs to be a server at the other end */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ);
$queue->connect("tcp://127.0.0.1:5555");

/* Assign socket 1 to the queue, send and receive */
$retries = 5;
$sending = true;

/* Start a loop */
do {
    try {
        /* Try to send / receive */
        if ($sending) {
            echo "Sending message\n";
            $queue->send("This is a message", ZMQ::MODE_NOBLOCK);
            $sending = false;
        } else {
            echo "Got response: " . $queue->recv(ZMQ::MODE_NOBLOCK) . "\n";
            break;
        }
    } catch (ZMQSocketException $e) {
        /* EAGAIN means that the operation would have blocked, retry */
        if ($e->getCode() === ZMQ::ERR_EAGAIN) {
            echo " - Got EAGAIN, retrying ($retries)\n";
        } else {
            die(" - Error: " . $e->getMessage());
        }
    }
    /* Sleep a bit between operations */
    usleep(5);
} while (--$retries);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Sending message
 - Unable to execute operation, retrying (4)
Got response: This is a message

Valorile întoarse

Returns the message. Throws ZMQSocketException in error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.

ZMQSocket::isPersistent
ZMQSocket::recvMulti
ZMQSocket


Receives a multipart message

ZMQSocket::recv
ZMQSocket::send
ZMQSocket
PHP Manual

ZMQSocket::recvMulti

(PECL zmq >= 0.8.0)

ZMQSocket::recvMulti — Receives a multipart message

Descrierea

public string ZMQSocket::recvMulti ([ integer $mode = 0 ] )

Receive an array multipart message from a socket. By default receiving will block until a message is available unless ZMQ::MODE_NOBLOCK flag is used.

Parametri

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

Valorile întoarse

Returns the array of message parts. Throws ZMQSocketException in error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.

ZMQSocket::recv
ZMQSocket::send
ZMQSocket


Sends a message

ZMQSocket::recvMulti
ZMQSocket::sendmulti
ZMQSocket
PHP Manual

ZMQSocket::send

(PECL zmq >= 0.5.0)

ZMQSocket::send — Sends a message

Descrierea

public ZMQSocket ZMQSocket::send ( string $message [, integer $mode = 0 ] )

Send a message using the socket. The operation can block unless ZMQ::MODE_NOBLOCK is used.

Parametri

message

The message to send.

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

Valorile întoarse

Returns the current object. Throws ZMQSocketException on error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.

ZMQSocket::recvMulti
ZMQSocket::sendmulti
ZMQSocket


Sends a multipart message

ZMQSocket::send
ZMQSocket::setSockOpt
ZMQSocket
PHP Manual

ZMQSocket::sendmulti

(PECL zmq >= 0.8.0)

ZMQSocket::sendmulti — Sends a multipart message

Descrierea

public ZMQSocket ZMQSocket::send ( array $message [, integer $mode = 0 ] )

Send a multipart message using the socket. The operation can block unless ZMQ::MODE_NOBLOCK is used.

Parametri

message

The message to send - an array of strings

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

Valorile întoarse

Returns the current object. Throws ZMQSocketException on error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.

ZMQSocket::send
ZMQSocket::setSockOpt
ZMQSocket


Set a socket option

ZMQSocket::sendmulti
ZMQSocket::unbind
ZMQSocket
PHP Manual

ZMQSocket::setSockOpt

(PECL zmq >= 0.5.0)

ZMQSocket::setSockOpt — Set a socket option

Descrierea

public ZMQSocket ZMQSocket::setSockOpt ( integer $key , mixed $value )

Sets a ZMQ socket option. The type of the value depends on the key. See ZMQ Constant Types for more information.

Parametri

key

One of the ZMQ::SOCKOPT_* constants.

value

The value of the parameter.

Valorile întoarse

Returns the current object. Throws ZMQSocketException on error.

ZMQSocket::sendmulti
ZMQSocket::unbind
ZMQSocket


Unbind the socket

ZMQSocket::setSockOpt
ZMQPoll
ZMQSocket
PHP Manual

ZMQSocket::unbind

(PECL zmq >= 1.0.4)

ZMQSocket::unbind — Unbind the socket

Descrierea

public ZMQSocket ZMQSocket::unbind ( string $dsn )

Unbind the socket from an endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

Parametri

dsn

The previously bound dsn, for example transport://address.

Valorile întoarse

Returns the current object. Throws ZMQSocketException on error.

ZMQSocket::setSockOpt
ZMQPoll
ZMQSocket


The ZMQPoll class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

ZMQPoll {
/* Methods */
public string add ( mixed $entry , integer $type )
public ZMQPoll clear ( void )
public integer count ( void )
public array getLastErrors ( void )
public integer poll ( array &$readable , array &$writable [, integer $timeout = -1 ] )
public boolean remove ( mixed $item )
}

Cuprins

  • ZMQPoll::add — Add item to the poll set
  • ZMQPoll::clear — Clear the poll set
  • ZMQPoll::count — Count items in the poll set
  • ZMQPoll::getLastErrors — Get poll errors
  • ZMQPoll::poll — Poll the items
  • ZMQPoll::remove — Remove item from poll set
ZMQSocket::unbind
ZMQPoll::add
0MQ messaging


Add item to the poll set

ZMQPoll
ZMQPoll::clear
ZMQPoll
PHP Manual

ZMQPoll::add

(PECL zmq >= 0.5.0)

ZMQPoll::add — Add item to the poll set

Descrierea

public string ZMQPoll::add ( mixed $entry , integer $type )

Adds a new item to the poll set and returns the internal id of the added item. The item can be removed from the poll set using the returned string id.

Parametri

entry

ZMQSocket object or a PHP stream resource

type

Defines what activity the socket is polled for. See ZMQ::POLL_IN and ZMQ::POLL_OUT constants.

Valorile întoarse

Returns a string id of the added item which can be later used to remove the item. Throws ZMQPollException on error.

ZMQPoll
ZMQPoll::clear
ZMQPoll


Clear the poll set

ZMQPoll::add
ZMQPoll::count
ZMQPoll
PHP Manual

ZMQPoll::clear

(PECL zmq >= 0.5.0)

ZMQPoll::clear — Clear the poll set

Descrierea

public ZMQPoll ZMQPoll::clear ( void )

Clears all elements from the poll set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current object.

ZMQPoll::add
ZMQPoll::count
ZMQPoll


Count items in the poll set

ZMQPoll::clear
ZMQPoll::getLastErrors
ZMQPoll
PHP Manual

ZMQPoll::count

(PECL zmq >= 0.5.0)

ZMQPoll::count — Count items in the poll set

Descrierea

public integer ZMQPoll::count ( void )

Count the items in the poll set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an integer representing the amount of items in the poll set.

ZMQPoll::clear
ZMQPoll::getLastErrors
ZMQPoll


Get poll errors

ZMQPoll::count
ZMQPoll::poll
ZMQPoll
PHP Manual

ZMQPoll::getLastErrors

(PECL zmq >= 0.5.0)

ZMQPoll::getLastErrors — Get poll errors

Descrierea

public array ZMQPoll::getLastErrors ( void )

Returns the ids of the objects that had errors in the last poll.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array containing ids for the items that had errors in the last poll. Empty array is returned if there were no errors.

ZMQPoll::count
ZMQPoll::poll
ZMQPoll


Poll the items

ZMQPoll::getLastErrors
ZMQPoll::remove
ZMQPoll
PHP Manual

ZMQPoll::poll

(PECL zmq >= 0.5.0)

ZMQPoll::poll — Poll the items

Descrierea

public integer ZMQPoll::poll ( array &$readable , array &$writable [, integer $timeout = -1 ] )

Polls the items in the current poll set. The readable and writable items are returned in the readable and writable parameters. ZMQPoll::getLastErrors() can be used to check if there were errors.

Parametri

readable

Array where readable ZMQSockets/PHP streams are returned. The array will be cleared at the beginning of the operation.

writable

Array where writable ZMQSockets/PHP streams are returned. The array will be cleared at the beginning of the operation.

timeout

Timeout for the operation. -1 means that poll waits until at least one item has activity. Please note that starting from version 1.0.0 the poll timeout is defined in milliseconds, rather than microseconds.

Exemple

Example #1 A ZMQPoll() example

Create a simple poll server

<?php

/* Create socket, request-reply pattern (reply socket) */
$context = new ZMQContext();
$server  = $context->getSocket(ZMQ::SOCKET_REP);

/* Bind to port 5555 on 127.0.0.1 */
$server->bind("tcp://127.0.0.1:5555");

/* Create new pollset for incoming/outgoing message */
$poll = new ZMQPoll();

/* Add the object and listen for poll in/out */
$id = $poll->add($server, ZMQ::POLL_IN | ZMQ::POLL_OUT);
echo "Added object with id " . $id . "\n";

/* Initialise readable and writable arrays */
$readable = array();
$writable = array();

while (true) {
   /* Amount of events retrieved */
   $events = 0;

   try {
       /* Poll until there is something to do */
       $events = $poll->poll($readable, $writable, -1);
       $errors = $poll->getLastErrors();

       if (count($errors) > 0) {
           foreach ($errors as $error) {
               echo "Error polling object " . $error . "\n";
           }
       }
   } catch (ZMQPollException $e) {
       echo "poll failed: " . $e->getMessage() . "\n";
   }

   if ($events > 0) {
       /* Loop through readable objects and recv messages */
       foreach ($readable as $r) {
           try {
               echo "Received message: " . $r->recv() . "\n";
           } catch (ZMQException $e) {
               echo "recv failed: " . $e->getMessage() . "\n";
           }
       }

       /* Loop through writable and send back messages */
       foreach ($writable as $w) {
           try {
               $w->send("Got it!");
           } catch (ZMQException $e) {
               echo "send failed: " . $e->getMessage() . "\n";
           }
       }
   }
}
?>

Valorile întoarse

Returns an integer representing amount of items with activity. Throws ZMQPollException on error.

ZMQPoll::getLastErrors
ZMQPoll::remove
ZMQPoll


Remove item from poll set

ZMQPoll::poll
ZMQDevice
ZMQPoll
PHP Manual

ZMQPoll::remove

(PECL zmq >= 0.5.0)

ZMQPoll::remove — Remove item from poll set

Descrierea

public boolean ZMQPoll::remove ( mixed $item )

Remove item from the poll set. The item parameter can be ZMQSocket object, a stream resource or the id returned from ZMQPoll::add() method.

Parametri

item

The ZMQSocket object, PHP stream or string id of the item.

Valorile întoarse

Returns true if the item was removed and false if the object with given id does not exist in the poll set.

ZMQPoll::poll
ZMQDevice
ZMQPoll


The ZMQDevice class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

ZMQDevice {
/* Methods */
__construct ( ZMQSocket $frontend , ZMQSocket $backend [, ZMQSocket $listener ] )
public ZMQDevice getIdleTimeout ( void )
public ZMQDevice getTimerTimeout ( void )
public void run ( void )
public ZMQDevice setIdleCallback ( callable $cb_func , integer $timeout [, mixed $user_data ] )
public ZMQDevice setIdleTimeout ( integer $timeout )
public ZMQDevice setTimerCallback ( callable $cb_func , integer $timeout [, mixed $user_data ] )
public ZMQDevice setTimerTimeout ( integer $timeout )
}

Cuprins

  • ZMQDevice::__construct — Construct a new device
  • ZMQDevice::getIdleTimeout — Get the idle timeout
  • ZMQDevice::getTimerTimeout — Get the timer timeout
  • ZMQDevice::run — Run the new device
  • ZMQDevice::setIdleCallback — Set the idle callback function
  • ZMQDevice::setIdleTimeout — Set the idle timeout
  • ZMQDevice::setTimerCallback — Set the timer callback function
  • ZMQDevice::setTimerTimeout — Set the timer timeout
ZMQPoll::remove
ZMQDevice::__construct
0MQ messaging


Construct a new device

ZMQDevice
ZMQDevice::getIdleTimeout
ZMQDevice
PHP Manual

ZMQDevice::__construct

(PECL zmq >= 0.5.0)

ZMQDevice::__construct — Construct a new device

Descrierea

ZMQDevice::__construct ( ZMQSocket $frontend , ZMQSocket $backend [, ZMQSocket $listener ] )

"ØMQ devices can do intermediation of addresses, services, queues, or any other abstraction you care to define above the message and socket layers." -- zguide

Parametri

frontend

Frontend parameter for the devices. Usually where there messages are coming.

backend

Backend parameter for the devices. Usually where there messages going to.

listener

Listener socket, which receives a copy of all messages going both directions. The type of this socket should be SUB, PULL or DEALER.

Valorile întoarse

Call to this method will prepare the device. Usually devices are very long running processes so running this method from interactive script is not recommended. This method throw ZMQDeviceException if the device cannot be started.

ZMQDevice
ZMQDevice::getIdleTimeout
ZMQDevice


Get the idle timeout

ZMQDevice::__construct
ZMQDevice::getTimerTimeout
ZMQDevice
PHP Manual

ZMQDevice::getIdleTimeout

(No version information available, might only be in Git)

ZMQDevice::getIdleTimeout — Get the idle timeout

Descrierea

public ZMQDevice ZMQDevice::getIdleTimeout ( void )

Gets the idle callback timeout value. Added in ZMQ extension version 1.1.0.

Valorile întoarse

This method returns the idle callback timeout value.

ZMQDevice::__construct
ZMQDevice::getTimerTimeout
ZMQDevice


Get the timer timeout

ZMQDevice::getIdleTimeout
ZMQDevice::run
ZMQDevice
PHP Manual

ZMQDevice::getTimerTimeout

(No version information available, might only be in Git)

ZMQDevice::getTimerTimeout — Get the timer timeout

Descrierea

public ZMQDevice ZMQDevice::getTimerTimeout ( void )

Gets the timer callback timeout value. Added in ZMQ extension version 1.1.0.

Valorile întoarse

This method returns the timer timeout value.

ZMQDevice::getIdleTimeout
ZMQDevice::run
ZMQDevice


Run the new device

ZMQDevice::getTimerTimeout
ZMQDevice::setIdleCallback
ZMQDevice
PHP Manual

ZMQDevice::run

(No version information available, might only be in Git)

ZMQDevice::run — Run the new device

Descrierea

public void ZMQDevice::run ( void )

Runs the device.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Call to this method will block until the device is running. It is not recommended that devices are used from interactive scripts. On failure this method will throw ZMQDeviceException.

ZMQDevice::getTimerTimeout
ZMQDevice::setIdleCallback
ZMQDevice


Set the idle callback function

ZMQDevice::run
ZMQDevice::setIdleTimeout
ZMQDevice
PHP Manual

ZMQDevice::setIdleCallback

(No version information available, might only be in Git)

ZMQDevice::setIdleCallback — Set the idle callback function

Descrierea

public ZMQDevice ZMQDevice::setIdleCallback ( callable $cb_func , integer $timeout [, mixed $user_data ] )

Sets the idle callback function. If idle timeout is defined the idle callback function shall be called if the internal poll loop times out without events. If the callback function returns false or a value that evaluates to false the device is stopped. The callback function signature is callback (mixed $user_data).

Parametri

cb_func

Callback function to invoke when the device is idle. Returning false or a value that evaluates to false from this function will cause the device to stop.

timeout

How often to invoke the idle callback in milliseconds. The idle callback is invoked periodically when there is no activity on the device. The timeout value guarantees that there is at least this amount of milliseconds between invocations of the callback function.

user_data

Additional data to pass to the callback function.

Valorile întoarse

On success this method returns the current object.

ZMQDevice::run
ZMQDevice::setIdleTimeout
ZMQDevice


Set the idle timeout

ZMQDevice::setIdleCallback
ZMQDevice::setTimerCallback
ZMQDevice
PHP Manual

ZMQDevice::setIdleTimeout

(No version information available, might only be in Git)

ZMQDevice::setIdleTimeout — Set the idle timeout

Descrierea

public ZMQDevice ZMQDevice::setIdleTimeout ( integer $timeout )

Sets the idle callback timeout value. The idle callback is invoked periodically when the device is idle.

Parametri

timeout

The idle callback timeout value.

Valorile întoarse

On success this method returns the current object.

ZMQDevice::setIdleCallback
ZMQDevice::setTimerCallback
ZMQDevice


Set the timer callback function

ZMQDevice::setIdleTimeout
ZMQDevice::setTimerTimeout
ZMQDevice
PHP Manual

ZMQDevice::setTimerCallback

(No version information available, might only be in Git)

ZMQDevice::setTimerCallback — Set the timer callback function

Descrierea

public ZMQDevice ZMQDevice::setTimerCallback ( callable $cb_func , integer $timeout [, mixed $user_data ] )

Sets the timer callback function. The timer callback will be invoked after timeout has passed. The difference between idle and timer callbacks are that idle callback is invoked only when the device is idle. The callback function signature is callback (mixed $user_data). Added in ZMQ extension version 1.1.0.

Parametri

cb_func

Callback function to invoke when the device is idle. Returning false or a value that evaluates to false from this function will cause the device to stop.

timeout

How often to invoke the idle callback in milliseconds. The idle callback is invoked periodically when there is no activity on the device. The timeout value guarantees that there is at least this amount of milliseconds between invocations of the callback function.

user_data

Additional data to pass to the callback function.

Valorile întoarse

On success this method returns the current object.

ZMQDevice::setIdleTimeout
ZMQDevice::setTimerTimeout
ZMQDevice


Set the timer timeout

ZMQDevice::setTimerCallback
ZooKeeper
ZMQDevice
PHP Manual

ZMQDevice::setTimerTimeout

(No version information available, might only be in Git)

ZMQDevice::setTimerTimeout — Set the timer timeout

Descrierea

public ZMQDevice ZMQDevice::setTimerTimeout ( integer $timeout )

Sets the timer callback timeout value. The timer callback is invoked periodically if it's set. Added in ZMQ extension version 1.1.0.

Parametri

timeout

The timer callback timeout value.

Valorile întoarse

On success this method returns the current object.

ZMQDevice::setTimerCallback
ZooKeeper
ZMQDevice


ZooKeeper

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • ZooKeeper — The ZooKeeper class
    • Zookeeper::addAuth — Specify application credentials.
    • Zookeeper::connect — Create a handle to used communicate with zookeeper.
    • Zookeeper::__construct — Create a handle to used communicate with zookeeper.
    • Zookeeper::create — Create a node synchronously.
    • Zookeeper::delete — Delete a node in zookeeper synchronously.
    • Zookeeper::exists — Checks the existence of a node in zookeeper synchronously.
    • Zookeeper::get — Gets the data associated with a node synchronously.
    • Zookeeper::getAcl — Gets the acl associated with a node synchronously.
    • Zookeeper::getClientId — return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
    • Zookeeper::getRecvTimeout — Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect.
    • Zookeeper::getState — Get the state of the zookeeper connection.
    • Zookeeper::isRecoverable — Checks if the current zookeeper connection state can be recovered.
    • Zookeeper::set — Sets the data associated with a node.
    • Zookeeper::setAcl — Sets the acl associated with a node synchronously.
    • Zookeeper::setDebugLevel — Sets the debugging level for the library.
    • Zookeeper::setDeterministicConnOrder — Enable/disable quorum endpoint order randomization.
    • Zookeeper::setLogStream — Sets the stream to be used by the library for logging.
    • Zookeeper::setWatcher — Set a watcher function.
ZMQDevice::setTimerTimeout
Introducere
Alte servicii


Introducere

This extension uses libzookeeper library to provide API for communicating with ZooKeeper service.

ZooKeeper is an Apache project that enables centralized service for maintaining configuration information, naming, providing distributed synchronization, and providing group services.

ZooKeeper
Instalarea / configurarea
ZooKeeper


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
ZooKeeper


Necesita?i

This extension requires » ZooKeeper C Binding (version 3.4.1 or greater). For more information, see » ZooKeeper Programmer's Guide.

This extension requires PHP version 5.2.0 or higher.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/zookeeper.

To enable zookeeper support, configure with --with-libzookeeper-dir=DIR . DIR is the install prefix of ZooKeeper C Binding, which must contain the include/zookeeper/zookeeper.h

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Zookeeper Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Changelog
zookeeper.recv_timeout | 10000 | PHP_INI_ALL |
zookeeper.session_lock | 1 | PHP_INI_SYSTEM |
zookeeper.sess_lock_wait | 150000 | PHP_INI_ALL |
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

zookeeper.recv_timeout integer

Default the timeout for any ZooKeeper session.

zookeeper.session_lock integer

Enable PHP session locking.

zookeeper.sess_lock_wait integer

PHP Session spin lock retry wait time in microseconds. Be carefull when setting this value. Valid values are integers, where 0 is interpreted as the default value. Negative values result in a reduces locking to a try lock.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
ZooKeeper
ZooKeeper


Constante predefinite
Zookeeper::addAuth
ZooKeeper
PHP Manual

The ZooKeeper class

(PECL zookeeper >= 0.1.0)

Introducere

Represents ZooKeeper session.

Sinopsisul clasei

Zookeeper {
/* Metode */
public __construct ([ string $host = '' [, callable $watcher_cb = null [, int $recv_timeout = 10000 ]]] )
public bool addAuth ( string $scheme , string $cert [, callable $completion_cb = null ] )
public void connect ( string $host [, callable $watcher_cb = null [, int $recv_timeout = 10000 ]] )
public string create ( string $path , string $value , array $acls [, int $flags = null ] )
public bool delete ( string $path [, int $version = -1 ] )
public bool exists ( string $path [, callable $watcher_cb = null ] )
public string get ( string $path [, callable $watcher_cb = null [, array &$stat = null [, int $max_size = 0 ]]] )
public array getAcl ( string $path )
public int getClientId ( void )
public int getRecvTimeout ( void )
public int getState ( void )
public bool isRecoverable ( void )
public bool set ( string $path , string $value [, int $version = -1 [, array &$stat = null ]] )
public bool setAcl ( string $path , int $version , array $acl )
public static bool setDebugLevel ( int $logLevel )
public static bool setDeterministicConnOrder ( bool $yesOrNo )
public bool setLogStream ( resource $stream )
public bool setWatcher ( callable $watcher_cb )
/* Constante */
const integer PERM_READ = 1 ;
const integer PERM_WRITE = 2 ;
const integer PERM_CREATE = 4 ;
const integer PERM_DELETE = 8 ;
const integer PERM_ADMIN = 16 ;
const integer PERM_ALL = 31 ;
const integer LOG_LEVEL_ERROR = 1 ;
const integer LOG_LEVEL_WARN = 2 ;
const integer LOG_LEVEL_INFO = 3 ;
const integer LOG_LEVEL_DEBUG = 4 ;
const integer EXPIRED_SESSION_STATE = -112 ;
const integer AUTH_FAILED_STATE = -113 ;
const integer CONNECTING_STATE = 1 ;
const integer ASSOCIATING_STATE = 2 ;
const integer CONNECTED_STATE = 3 ;
const integer READONLY_STATE = 5 ;
const integer NOTCONNECTED_STATE = 999 ;
}

Constante predefinite

ZooKeeper Permissions

Zookeeper::PERM_READ

Can read nodes value and list its children

Zookeeper::PERM_WRITE

Can set the nodes value

Zookeeper::PERM_CREATE

Can create children

Zookeeper::PERM_DELETE

Can delete children

Zookeeper::PERM_ADMIN

Can execute set_acl()

Zookeeper::PERM_ALL

All of the above flags ORd together

ZooKeeper Log Levels

Zookeeper::LOG_LEVEL_ERROR

Outputs only error mesages

Zookeeper::LOG_LEVEL_WARN

Outputs errors/warnings

Zookeeper::LOG_LEVEL_INFO

Outputs big action messages besides errors/warnings

Zookeeper::LOG_LEVEL_DEBUG

Outputs all

ZooKeeper States

Zookeeper::EXPIRED_SESSION_STATE

Connected but session expired

Zookeeper::AUTH_FAILED_STATE

Connected but auth failed

Zookeeper::CONNECTING_STATE

Connecting

Zookeeper::ASSOCIATING_STATE

Associating

Zookeeper::CONNECTED_STATE

Connected

Zookeeper::READONLY_STATE

TODO: help us improve this extension.

Zookeeper::NOTCONNECTED_STATE

Connection failed

Cuprins

  • Zookeeper::addAuth — Specify application credentials.
  • Zookeeper::connect — Create a handle to used communicate with zookeeper.
  • Zookeeper::__construct — Create a handle to used communicate with zookeeper.
  • Zookeeper::create — Create a node synchronously.
  • Zookeeper::delete — Delete a node in zookeeper synchronously.
  • Zookeeper::exists — Checks the existence of a node in zookeeper synchronously.
  • Zookeeper::get — Gets the data associated with a node synchronously.
  • Zookeeper::getAcl — Gets the acl associated with a node synchronously.
  • Zookeeper::getClientId — return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
  • Zookeeper::getRecvTimeout — Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect.
  • Zookeeper::getState — Get the state of the zookeeper connection.
  • Zookeeper::isRecoverable — Checks if the current zookeeper connection state can be recovered.
  • Zookeeper::set — Sets the data associated with a node.
  • Zookeeper::setAcl — Sets the acl associated with a node synchronously.
  • Zookeeper::setDebugLevel — Sets the debugging level for the library.
  • Zookeeper::setDeterministicConnOrder — Enable/disable quorum endpoint order randomization.
  • Zookeeper::setLogStream — Sets the stream to be used by the library for logging.
  • Zookeeper::setWatcher — Set a watcher function.
Constante predefinite
Zookeeper::addAuth
ZooKeeper


Specify application credentials.

ZooKeeper
Zookeeper::connect
ZooKeeper
PHP Manual

Zookeeper::addAuth

(PECL zookeeper >= 0.1.0)

Zookeeper::addAuth — Specify application credentials.

Descrierea

public bool Zookeeper::addAuth ( string $scheme , string $cert [, callable $completion_cb = null ] )

The application calls this function to specify its credentials for purposes of authentication. The server will use the security provider specified by the scheme parameter to authenticate the client connection. If the authentication request has failed: - the server connection is dropped. - the watcher is called with the ZOO_AUTH_FAILED_STATE value as the state parameter.

Parametri

scheme

The id of authentication scheme. Natively supported: "digest" password-based authentication

cert

Application credentials. The actual value depends on the scheme.

completion_cb

The routine to invoke when the request completes. One of the following result codes may be passed into the completion callback: - ZOK operation completed successfully - ZAUTHFAILED authentication failed

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or operation fails.

Exemple

Example #1 Zookeeper::addAuth() example

Add auth before requesting node value.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$value = 'nodevalue';
$zookeeper->set($path, $value);

$zookeeper->addAuth('digest', 'user0:passwd0');
$r = $zookeeper->get($path);
if ($r)
  echo $r;
else
  echo 'ERR';
?>

Exemplul de mai sus va afi?a:

nodevalue

A se vedea ?i

  • Zookeeper::create() - Create a node synchronously.
  • Zookeeper::setAcl() - Sets the acl associated with a node synchronously.
  • Zookeeper::getAcl() - Gets the acl associated with a node synchronously.
  • ZooKeeper States
ZooKeeper
Zookeeper::connect
ZooKeeper


Create a handle to used communicate with zookeeper.

Zookeeper::addAuth
Zookeeper::__construct
ZooKeeper
PHP Manual

Zookeeper::connect

(PECL zookeeper >= 0.2.0)

Zookeeper::connect — Create a handle to used communicate with zookeeper.

Descrierea

public void Zookeeper::connect ( string $host [, callable $watcher_cb = null [, int $recv_timeout = 10000 ]] )

This method creates a new handle and a zookeeper session that corresponds to that handle. Session establishment is asynchronous, meaning that the session should not be considered established until (and unless) an event of state ZOO_CONNECTED_STATE is received.

Parametri

host

Comma separated host:port pairs, each corresponding to a zk server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002"

watcher_cb

The global watcher callback function. When notifications are triggered this function will be invoked.

recv_timeout

The timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE).

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or could not init instance.

A se vedea ?i

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper.
Zookeeper::addAuth
Zookeeper::__construct
ZooKeeper


Create a handle to used communicate with zookeeper.

Zookeeper::connect
Zookeeper::create
ZooKeeper
PHP Manual

Zookeeper::__construct

(PECL zookeeper >= 0.1.0)

Zookeeper::__construct — Create a handle to used communicate with zookeeper.

Descrierea

public Zookeeper::__construct ([ string $host = '' [, callable $watcher_cb = null [, int $recv_timeout = 10000 ]]] )

This method creates a new handle and a zookeeper session that corresponds to that handle. Session establishment is asynchronous, meaning that the session should not be considered established until (and unless) an event of state ZOO_CONNECTED_STATE is received.

Parametri

host

comma separated host:port pairs, each corresponding to a zk server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002"

watcher_cb

the global watcher callback function. When notifications are triggered this function will be invoked.

recv_timeout

the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE).

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or could not init instance.

A se vedea ?i

  • Zookeeper::connect() - Create a handle to used communicate with zookeeper.
Zookeeper::connect
Zookeeper::create
ZooKeeper


Create a node synchronously.

Zookeeper::__construct
Zookeeper::delete
ZooKeeper
PHP Manual

Zookeeper::create

(PECL zookeeper >= 0.1.0)

Zookeeper::create — Create a node synchronously.

Descrierea

public string Zookeeper::create ( string $path , string $value , array $acls [, int $flags = null ] )

This method will create a node in ZooKeeper. A node can only be created if it does not already exists. The Create Flags affect the creation of nodes. If ZOO_EPHEMERAL flag is set, the node will automatically get removed if the client session goes away. If the ZOO_SEQUENCE flag is set, a unique monotonically increasing sequence number is appended to the path name.

Parametri

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

value

The data to be stored in the node.

acls

The initial ACL of the node. The ACL must not be null or empty.

flags

this parameter can be set to 0 for normal create or an OR of the Create Flags

Valorile întoarse

Returns the path of the new node (this might be different than the supplied path because of the ZOO_SEQUENCE flag) on success, and false on failure.

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or fail to create node.

Exemple

Example #1 Zookeeper::create() example

Create a new node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$aclArray = array(
  array(
    'perms'  => Zookeeper::PERM_ALL,
    'scheme' => 'world',
    'id'     => 'anyone',
  )
);
$path = '/path/to/newnode';
$realPath = $zookeeper->create($path, null, $aclArray);
if ($realPath)
  echo $realPath;
else
  echo 'ERR';
?>

Exemplul de mai sus va afi?a:

/path/to/newnode

A se vedea ?i

  • Zookeeper::delete() - Delete a node in zookeeper synchronously.
  • ZooKeeper Permissions
Zookeeper::__construct
Zookeeper::delete
ZooKeeper


Delete a node in zookeeper synchronously.

Zookeeper::create
Zookeeper::exists
ZooKeeper
PHP Manual

Zookeeper::delete

(PECL zookeeper >= 0.2.0)

Zookeeper::delete — Delete a node in zookeeper synchronously.

Descrierea

public bool Zookeeper::delete ( string $path [, int $version = -1 ] )

Parametri

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

version

The expected version of the node. The function will fail if the actual version of the node does not match the expected version. If -1 is used the version check will not take place.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or fail to delete node.

Exemple

Example #1 Zookeeper::delete() example

Delete a existing node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$r = $zookeeper->delete($path);
if ($r)
  echo 'SUCCESS';
else
  echo 'ERR';
?>

Exemplul de mai sus va afi?a:

SUCCESS

A se vedea ?i

  • Zookeeper::create() - Create a node synchronously.
Zookeeper::create
Zookeeper::exists
ZooKeeper


Checks the existence of a node in zookeeper synchronously.

Zookeeper::delete
Zookeeper::get
ZooKeeper
PHP Manual

Zookeeper::exists

(PECL zookeeper >= 0.1.0)

Zookeeper::exists — Checks the existence of a node in zookeeper synchronously.

Descrierea

public bool Zookeeper::exists ( string $path [, callable $watcher_cb = null ] )

Parametri

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

watcher_cb

if nonzero, a watch will be set at the server to notify the client if the node changes. The watch will be set even if the node does not

Valorile întoarse

Returns true/false on success, and false on failure.

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or fail to check the existence of a node.

Exemple

Example #1 Zookeeper::exists() example

Check the existence of a node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$r = $zookeeper->exists($path);
if ($r)
  echo 'EXISTS';
else
  echo 'N/A or ERR';
?>

Exemplul de mai sus va afi?a:

EXISTS

A se vedea ?i

  • Zookeeper::get() - Gets the data associated with a node synchronously.
Zookeeper::delete
Zookeeper::get
ZooKeeper


Gets the data associated with a node synchronously.

Zookeeper::exists
Zookeeper::getAcl
ZooKeeper
PHP Manual

Zookeeper::get

(PECL zookeeper >= 0.1.0)

Zookeeper::get — Gets the data associated with a node synchronously.

Descrierea

public string Zookeeper::get ( string $path [, callable $watcher_cb = null [, array &$stat = null [, int $max_size = 0 ]]] )

Parametri

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

watcher_cb

If nonzero, a watch will be set at the server to notify the client if the node changes.

stat

If not NULL, will hold the value of stat for the path on return.

max_size

Max size of the data. If 0 is used, this method will return the whole data.

Valorile întoarse

Returns the data on success, and false on failure.

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or fail to get value from node.

Exemple

Example #1 Zookeeper::get() example

Get value from node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$value = 'nodevalue';
$zookeeper->set($path, $value);

$r = $zookeeper->get($path);
if ($r)
  echo $r;
else
  echo 'ERR';
?>

Exemplul de mai sus va afi?a:

nodevalue

A se vedea ?i

  • Zookeeper::set() - Sets the data associated with a node.
Zookeeper::exists
Zookeeper::getAcl
ZooKeeper


Gets the acl associated with a node synchronously.

Zookeeper::get
Zookeeper::getClientId
ZooKeeper
PHP Manual

Zookeeper::getAcl

(PECL zookeeper >= 0.1.0)

Zookeeper::getAcl — Gets the acl associated with a node synchronously.

Descrierea

public array Zookeeper::getAcl ( string $path )

Parametri

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

Valorile întoarse

Return acl array on success and false on failure.

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or fail to get ACL of a node.

Exemple

Example #1 Zookeeper::getAcl() example

Get ACL of a node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$aclArray = array(
  array(
    'perms'  => Zookeeper::PERM_ALL,
    'scheme' => 'world',
    'id'     => 'anyone',
  )
);
$path = '/path/to/newnode';
$zookeeper->setAcl($path, $aclArray);

$r = $zookeeper->getAcl($path);
if ($r)
  var_dump($r);
else
  echo 'ERR';
?>

Exemplul de mai sus va afi?a:

array(1) {
  [0]=>
  array(3) {
    ["perms"]=>
    int(31)
    ["scheme"]=>
    string(5) "world"
    ["id"]=>
    string(6) "anyone"
  }
}

A se vedea ?i

  • Zookeeper::create() - Create a node synchronously.
  • Zookeeper::setAcl() - Sets the acl associated with a node synchronously.
  • ZooKeeper Permissions
Zookeeper::get
Zookeeper::getClientId
ZooKeeper


return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)

Zookeeper::getAcl
Zookeeper::getRecvTimeout
ZooKeeper
PHP Manual

Zookeeper::getClientId

(PECL zookeeper >= 0.1.0)

Zookeeper::getClientId — return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)

Descrierea

public int Zookeeper::getClientId ( void )

Valorile întoarse

Returns the client session id on success, and false on failure.

Erori/Excep?ii

This method emits PHP error/warning when it could not get client session id.

A se vedea ?i

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper.
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper.
  • Zookeeper::getState() - Get the state of the zookeeper connection.
  • ZooKeeper States
Zookeeper::getAcl
Zookeeper::getRecvTimeout
ZooKeeper


Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect.

Zookeeper::getClientId
Zookeeper::getState
ZooKeeper
PHP Manual

Zookeeper::getRecvTimeout

(PECL zookeeper >= 0.1.0)

Zookeeper::getRecvTimeout — Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect.

Descrierea

public int Zookeeper::getRecvTimeout ( void )

Valorile întoarse

Returns the timeout for this session on success, and false on failure.

Erori/Excep?ii

This method emits PHP error/warning when operation fails.

A se vedea ?i

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper.
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper.
Zookeeper::getClientId
Zookeeper::getState
ZooKeeper


Get the state of the zookeeper connection.

Zookeeper::getRecvTimeout
Zookeeper::isRecoverable
ZooKeeper
PHP Manual

Zookeeper::getState

(PECL zookeeper >= 0.1.0)

Zookeeper::getState — Get the state of the zookeeper connection.

Descrierea

public int Zookeeper::getState ( void )

Valorile întoarse

Returns the state of zookeeper connection on success, and false on failure.

Erori/Excep?ii

This method emits PHP error/warning when it fails to get state of zookeeper connection.

A se vedea ?i

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper.
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper.
  • Zookeeper::getClientId() - return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
  • ZooKeeper States
Zookeeper::getRecvTimeout
Zookeeper::isRecoverable
ZooKeeper


Checks if the current zookeeper connection state can be recovered.

Zookeeper::getState
Zookeeper::set
ZooKeeper
PHP Manual

Zookeeper::isRecoverable

(PECL zookeeper >= 0.1.0)

Zookeeper::isRecoverable — Checks if the current zookeeper connection state can be recovered.

Descrierea

public bool Zookeeper::isRecoverable ( void )

The application must close the zhandle and try to reconnect.

Valorile întoarse

Returns true/false on success, and false on failure.

Erori/Excep?ii

This method emits PHP error/warning when operation fails.

A se vedea ?i

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper.
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper.
  • Zookeeper::getClientId() - return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
  • ZooKeeper States
Zookeeper::getState
Zookeeper::set
ZooKeeper


Sets the data associated with a node.

Zookeeper::isRecoverable
Zookeeper::setAcl
ZooKeeper
PHP Manual

Zookeeper::set

(PECL zookeeper >= 0.1.0)

Zookeeper::set — Sets the data associated with a node.

Descrierea

public bool Zookeeper::set ( string $path , string $value [, int $version = -1 [, array &$stat = null ]] )

Parametri

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

value

The data to be stored in the node.

version

The expected version of the node. The function will fail if the actual version of the node does not match the expected version. If -1 is used the version check will not take place.

stat

If not NULL, will hold the value of stat for the path on return.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or fail to save value to node.

Exemple

Example #1 Zookeeper::set() example

Save value to node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$value = 'nodevalue';
$r = $zookeeper->set($path, $value);
if ($r)
  echo 'SUCCESS';
else
  echo 'ERR';
?>

Exemplul de mai sus va afi?a:

SUCCESS

A se vedea ?i

  • Zookeeper::create() - Create a node synchronously.
  • Zookeeper::get() - Gets the data associated with a node synchronously.
Zookeeper::isRecoverable
Zookeeper::setAcl
ZooKeeper


Sets the acl associated with a node synchronously.

Zookeeper::set
Zookeeper::setDebugLevel
ZooKeeper
PHP Manual

Zookeeper::setAcl

(PECL zookeeper >= 0.1.0)

Zookeeper::setAcl — Sets the acl associated with a node synchronously.

Descrierea

public bool Zookeeper::setAcl ( string $path , int $version , array $acl )

Parametri

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

version

The expected version of the path.

acl

The acl to be set on the path.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or fail to set ACL for a node.

Exemple

Example #1 Zookeeper::setAcl() example

Set ACL for a node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$aclArray = array(
  array(
    'perms'  => Zookeeper::PERM_ALL,
    'scheme' => 'world',
    'id'     => 'anyone',
  )
);
$path = '/path/to/newnode';
$zookeeper->setAcl($path, $aclArray);

$r = $zookeeper->getAcl($path);
if ($r)
  var_dump($r);
else
  echo 'ERR';
?>

Exemplul de mai sus va afi?a:

array(1) {
  [0]=>
  array(3) {
    ["perms"]=>
    int(31)
    ["scheme"]=>
    string(5) "world"
    ["id"]=>
    string(6) "anyone"
  }
}

A se vedea ?i

  • Zookeeper::create() - Create a node synchronously.
  • Zookeeper::getAcl() - Gets the acl associated with a node synchronously.
  • ZooKeeper Permissions
Zookeeper::set
Zookeeper::setDebugLevel
ZooKeeper


Sets the debugging level for the library.

Zookeeper::setAcl
Zookeeper::setDeterministicConnOrder
ZooKeeper
PHP Manual

Zookeeper::setDebugLevel

(PECL zookeeper >= 0.1.0)

Zookeeper::setDebugLevel — Sets the debugging level for the library.

Descrierea

public static bool Zookeeper::setDebugLevel ( int $logLevel )

Parametri

logLevel

ZooKeeper log level constants.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or fail to set debug level.

Exemple

Example #1 Zookeeper::setDebugLevel() example

Set debugl level.

<?php
$r = Zookeeper::setDebugLevel(Zookeeper::LOG_LEVEL_WARN);
if ($r)
  echo 'SUCCESS';
else
  echo 'ERR';
?>
?>

Exemplul de mai sus va afi?a:

SUCCESS

A se vedea ?i

  • ZooKeeper Log Levels
Zookeeper::setAcl
Zookeeper::setDeterministicConnOrder
ZooKeeper


Enable/disable quorum endpoint order randomization.

Zookeeper::setDebugLevel
Zookeeper::setLogStream
ZooKeeper
PHP Manual

Zookeeper::setDeterministicConnOrder

(PECL zookeeper >= 0.1.0)

Zookeeper::setDeterministicConnOrder — Enable/disable quorum endpoint order randomization.

Descrierea

public static bool Zookeeper::setDeterministicConnOrder ( bool $yesOrNo )

If passed a non-zero value, will make the client connect to quorum peers in the order as specified in the zookeeper_init() call. A zero value causes zookeeper_init() to permute the peer endpoints which is good for more even client connection distribution among the quorum peers.

Parametri

yesOrNo

Enable/disable quorum endpoint order randomization.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or operation fails.

Note

Precautie

Note: typically this method should NOT be used outside of testing.

Nota: Deoarece aceasta este o construc?ie a limbajului ?i nu o func?ie, ea nu poate fi apelata utilizând func?ii de operare cu variabile .

Avertizare

Aceasta func?ie nu func?ioneaza stabil (deocamdata) cu date binare!

Nota: register_globals: nota importanta

Începând cu PHP 4.2.0, valoarea implicita pentru directiva PHP register_globals este off. Comunitatea PHP îi încurajeaza pe to?i programatorii sa nu se bazeze pe aceasta directiva, dar sa utilizeze alte mijloace, cum ar fi superglobals.

A se vedea ?i

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper.
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper.
Zookeeper::setDebugLevel
Zookeeper::setLogStream
ZooKeeper


Sets the stream to be used by the library for logging.

Zookeeper::setDeterministicConnOrder
Zookeeper::setWatcher
ZooKeeper
PHP Manual

Zookeeper::setLogStream

(PECL zookeeper >= 0.1.0)

Zookeeper::setLogStream — Sets the stream to be used by the library for logging.

Descrierea

public bool Zookeeper::setLogStream ( resource $stream )

The zookeeper library uses stderr as its default log stream. Application must make sure the stream is writable. Passing in NULL resets the stream to its default value (stderr).

Parametri

stream

The stream to be used by the library for logging.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or operation fails.

A se vedea ?i

  • Zookeeper::setDebugLevel() - Sets the debugging level for the library.
Zookeeper::setDeterministicConnOrder
Zookeeper::setWatcher
ZooKeeper


Set a watcher function.

Zookeeper::setLogStream
Extensii ale motorului de cautare
ZooKeeper
PHP Manual

Zookeeper::setWatcher

(PECL zookeeper >= 0.1.0)

Zookeeper::setWatcher — Set a watcher function.

Descrierea

public bool Zookeeper::setWatcher ( callable $watcher_cb )

Parametri

watcher_cb

A watch will be set at the server to notify the client if the node changes.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

This method emits PHP error/warning when parameters count or types are wrong or fail to set watcher.

A se vedea ?i

  • Zookeeper::exists() - Checks the existence of a node in zookeeper synchronously.
  • Zookeeper::get() - Gets the data associated with a node synchronously.
Zookeeper::setLogStream
Extensii ale motorului de cautare
ZooKeeper


Extensii ale motorului de cautare

  • mnoGoSearch
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii mnoGoSearch
  • Solr — Apache Solr
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Solr
    • Exemple
    • 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
    • SolrDisMaxQuery — The SolrDisMaxQuery class
    • SolrCollapseFunction — The SolrCollapseFunction class
    • SolrException — The SolrException class
    • SolrClientException — The SolrClientException class
    • SolrServerException — The SolrServerException class
    • SolrIllegalArgumentException — The SolrIllegalArgumentException class
    • SolrIllegalOperationException — The SolrIllegalOperationException class
    • SolrMissingMandatoryParameterException — The SolrMissingMandatoryParameterException class
  • Sphinx — Sphinx Client
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • SphinxClient — The SphinxClient class
  • Swish — Swish Indexing
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii swish
Zookeeper::setWatcher
mnoGoSearch
Informa?ii de referin?a despre func?ii


mnoGoSearch

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii mnoGoSearch
    • 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_clear_search_limits — Clear all mnoGoSearch search restrictions
    • 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 given string
    • udm_load_ispell_data — Load ispell data
    • udm_set_agent_param — Set mnoGoSearch agent session parameters
Extensii ale motorului de cautare
Introducere
Extensii ale motorului de cautare


Introducere

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/.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.1.0.

Nota: Aceasta extensie nu este disponibila pe platformele Windows.

mnoGoSearch
Instalarea / configurarea
mnoGoSearch


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
mnoGoSearch


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/mnogosearch.

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.1.0

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Nota:

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 .

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
Tipurile resurselor
Func?ii mnoGoSearch
mnoGoSearch


Func?ii mnoGoSearch

Cuprins

  • 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_clear_search_limits — Clear all mnoGoSearch search restrictions
  • 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 given string
  • udm_load_ispell_data — Load ispell data
  • udm_set_agent_param — Set mnoGoSearch agent session parameters
Constante predefinite
udm_add_search_limit
mnoGoSearch


Add various search limits

Func?ii mnoGoSearch
udm_alloc_agent_array
Func?ii mnoGoSearch
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

Descrierea

bool udm_add_search_limit ( resource $agent , int $var , string $val )

udm_add_search_limit() adds search restrictions.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Func?ii mnoGoSearch
udm_alloc_agent_array
Func?ii mnoGoSearch


Allocate mnoGoSearch session

udm_add_search_limit
udm_alloc_agent
Func?ii mnoGoSearch
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

Descrierea

resource udm_alloc_agent_array ( array $databases )

udm_alloc_agent_array() will create an agent with multiple database connections.

Parametri

databases

The array databases must contain one database URL per element, analog to the first parameter of udm_alloc_agent().

Valorile întoarse

Returns a resource link identifier on success sau FALSE în cazul e?ecului.

A se vedea ?i

  • udm_alloc_agent() - Allocate mnoGoSearch session

udm_add_search_limit
udm_alloc_agent
Func?ii mnoGoSearch


Allocate mnoGoSearch session

udm_alloc_agent_array
udm_api_version
Func?ii mnoGoSearch
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

Descrierea

resource udm_alloc_agent ( string $dbaddr [, string $dbmode ] )

Allocate a mnoGoSearch session.

Parametri

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.

Nota:

dbaddr and dbmode must match those used during indexing.

Valorile întoarse

Returns a mnogosearch agent identifier on success, FALSE on failure. This function creates a session with database parameters.

Note

Nota:

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
Func?ii mnoGoSearch


Get mnoGoSearch API version

udm_alloc_agent
udm_cat_list
Func?ii mnoGoSearch
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

Descrierea

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.

Valorile întoarse

udm_api_version() returns the mnoGoSearch API version number. E.g. if mnoGoSearch 3.1.10 API is used, this function will return 30110.

Exemple

Example #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
Func?ii mnoGoSearch


Get all the categories on the same level with the current one

udm_api_version
udm_cat_path
Func?ii mnoGoSearch
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

Descrierea

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.

Parametri

agent

A link to Agent, received after call to udm_alloc_agent().

category

Valorile întoarse

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.

Exemple

Following is an example of displaying links of the current level in format:

Audi
  BMW
  Opel
  ...

Example #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 />";
 }
?>

A se vedea ?i

  • udm_cat_path() - Get the path to the current category

udm_api_version
udm_cat_path
Func?ii mnoGoSearch


Get the path to the current category

udm_cat_list
udm_check_charset
Func?ii mnoGoSearch
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

Descrierea

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.

Parametri

agent

A link to Agent, received after call to udm_alloc_agent().

category

Valorile întoarse

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'

Exemple

Example #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> ";
  }
?>

A se vedea ?i

  • udm_cat_list() - Get all the categories on the same level with the current one

udm_cat_list
udm_check_charset
Func?ii mnoGoSearch


Check if the given charset is known to mnogosearch

udm_cat_path
udm_clear_search_limits
Func?ii mnoGoSearch
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

Descrierea

bool udm_check_charset ( resource $agent , string $charset )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

udm_cat_path
udm_clear_search_limits
Func?ii mnoGoSearch


Clear all mnoGoSearch search restrictions

udm_check_charset
udm_crc32
Func?ii mnoGoSearch
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

Descrierea

bool udm_clear_search_limits ( resource $agent )

udm_clear_search_limits() resets defined search limitations.

Parametri

agent

A link to Agent, received after call to udm_alloc_agent().

Valorile întoarse

Returns TRUE.

A se vedea ?i

  • udm_add_search_limit() - Add various search limits

udm_check_charset
udm_crc32
Func?ii mnoGoSearch


Return CRC32 checksum of given string

udm_clear_search_limits
udm_errno
Func?ii mnoGoSearch
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

Descrierea

int udm_crc32 ( resource $agent , string $str )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

udm_clear_search_limits
udm_errno
Func?ii mnoGoSearch


Get mnoGoSearch error number

udm_crc32
udm_error
Func?ii mnoGoSearch
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

Descrierea

int udm_errno ( resource $agent )

Receiving numeric agent error code.

Parametri

agent

A link to Agent, received after call to udm_alloc_agent().

Valorile întoarse

Returns the mnoGoSearch error number, zero if no error.

udm_crc32
udm_error
Func?ii mnoGoSearch


Get mnoGoSearch error message

udm_errno
udm_find
Func?ii mnoGoSearch
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

Descrierea

string udm_error ( resource $agent )

Gets the agent error message.

Parametri

agent

A link to Agent, received after call to udm_alloc_agent().

Valorile întoarse

udm_error() returns mnoGoSearch error message, empty string if no error.

udm_errno
udm_find
Func?ii mnoGoSearch


Perform search

udm_error
udm_free_agent
Func?ii mnoGoSearch
PHP Manual

udm_find

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_find — Perform search

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a result link identifier on success sau FALSE în cazul e?ecului.

udm_error
udm_free_agent
Func?ii mnoGoSearch


Free mnoGoSearch session

udm_find
udm_free_ispell_data
Func?ii mnoGoSearch
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

Descrierea

int udm_free_agent ( resource $agent )

Freeing up memory allocated for agent session.

Parametri

agent

A link to Agent, received after call to udm_alloc_agent().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

udm_find
udm_free_ispell_data
Func?ii mnoGoSearch


Free memory allocated for ispell data

udm_free_agent
udm_free_res
Func?ii mnoGoSearch
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

Descrierea

bool udm_free_ispell_data ( int $agent )

Frees the memory allocated for ispell data.

Parametri

agent

A link to Agent, received after call to udm_alloc_agent().

Valorile întoarse

udm_free_ispell_data() always returns TRUE.

Note

Nota:

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
Func?ii mnoGoSearch


Free mnoGoSearch result

udm_free_ispell_data
udm_get_doc_count
Func?ii mnoGoSearch
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

Descrierea

bool udm_free_res ( resource $res )

Freeing up memory allocated for results.

Parametri

res

A link to a result identifier, received after call to udm_find().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

udm_free_ispell_data
udm_get_doc_count
Func?ii mnoGoSearch


Get total number of documents in database

udm_free_res
udm_get_res_field
Func?ii mnoGoSearch
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

Descrierea

int udm_get_doc_count ( resource $agent )

udm_get_doc_count() returns the number of documents in the database.

Parametri

agent

A link to Agent, received after call to udm_alloc_agent().

Valorile întoarse

Returns the number of documents.

Note

Nota:

This function is supported only in mnoGoSearch 3.1.11 or later.

udm_free_res
udm_get_res_field
Func?ii mnoGoSearch


Fetch a result field

udm_get_doc_count
udm_get_res_param
Func?ii mnoGoSearch
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

Descrierea

string udm_get_res_field ( resource $res , int $row , int $field )

Fetch a mnoGoSearch result field.

Parametri

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.

Valorile întoarse

udm_get_res_field() returns result field value on success, FALSE on error.

udm_get_doc_count
udm_get_res_param
Func?ii mnoGoSearch


Get mnoGoSearch result parameters

udm_get_res_field
udm_hash32
Func?ii mnoGoSearch
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

Descrierea

string udm_get_res_param ( resource $res , int $param )

Gets the mnoGoSearch result parameters.

Parametri

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.

Valorile întoarse

udm_get_res_param() returns result parameter value on success, FALSE on error.

udm_get_res_field
udm_hash32
Func?ii mnoGoSearch


Return Hash32 checksum of given string

udm_get_res_param
udm_load_ispell_data
Func?ii mnoGoSearch
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 given string

Descrierea

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.

Parametri

agent

A link to Agent, received after call to udm_alloc_agent().

str

The input string.

Valorile întoarse

Returns a 32-bit hash number.

A se vedea ?i

  • udm_alloc_agent() - Allocate mnoGoSearch session

udm_get_res_param
udm_load_ispell_data
Func?ii mnoGoSearch


Load ispell data

udm_hash32
udm_set_agent_param
Func?ii mnoGoSearch
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

Descrierea

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.

Parametri

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.

    Nota:

    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.

    Example #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;
    }
    ?>

    Nota:

    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;
     }
    ?>

    Nota:

    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.

    Nota:

    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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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_set_agent_param
Func?ii mnoGoSearch


Set mnoGoSearch agent session parameters

udm_load_ispell_data
Solr
Func?ii mnoGoSearch
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

Descrierea

bool udm_set_agent_param ( resource $agent , int $var , string $val )

Defines mnoGoSearch session parameters.

Parametri

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

Istoricul schimbarilor

Versiune | Descriere
4.1.0 | UDM_PARAM_VARDIR was added.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota: Crosswords are supported only in mnoGoSearch 3.1.11 or later.

udm_load_ispell_data
Solr
Func?ii mnoGoSearch


Apache Solr

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Solr
    • solr_get_version — Returns the current version of the Apache Solr extension
  • Exemple
  • 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::addChildDocument — Adds a child document for block indexing
    • SolrInputDocument::addChildDocuments — Adds an array of child documents
    • 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::getChildDocuments — Returns an array of child documents (SolrInputDocument)
    • SolrInputDocument::getChildDocumentsCount — Returns the number of child documents
    • 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::hasChildDocuments — Returns true if the document has any child documents
    • 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 — Access the field as a property
    • SolrDocument::getChildDocuments — Returns an array of child documents (SolrDocument)
    • SolrDocument::getChildDocumentsCount — Returns the number of child documents
    • 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::hasChildDocuments — Checks whether the document has any child documents
    • 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 — Unsets 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::getById — Get Document By Id. Utilizes Solr Realtime Get (RTG).
    • SolrClient::getByIds — Get Documents by their Ids. Utilizes Solr Realtime Get (RTG).
    • 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::system — Retrieve Solr Server information
    • 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::addExpandFilterQuery — Overrides main filter query, determines which documents to include in the main group.
    • SolrQuery::addExpandSortField — Orders the documents within the expanded groups (expand.sort parameter).
    • 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::addGroupField — Add a field to be used to group results.
    • SolrQuery::addGroupFunction — Allows grouping results based on the unique values of a function query (group.func parameter).
    • SolrQuery::addGroupQuery — Allows grouping of documents that match the given query.
    • SolrQuery::addGroupSortField — Add a group sort field (group.sort parameter).
    • 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::collapse — Collapses the result set to a single document per group
    • SolrQuery::__construct — Constructor
    • SolrQuery::__destruct — Destructor
    • SolrQuery::getExpand — Returns true if group expanding is enabled
    • SolrQuery::getExpandFilterQueries — Returns the expand filter queries
    • SolrQuery::getExpandQuery — Returns the expand query expand.q parameter
    • SolrQuery::getExpandRows — Returns The number of rows to display in each group (expand.rows)
    • SolrQuery::getExpandSortFields — Returns an array of fields
    • 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::getGroup — Returns true if grouping is enabled
    • SolrQuery::getGroupCachePercent — Returns group cache percent value
    • SolrQuery::getGroupFacet — Returns the group.facet parameter value
    • SolrQuery::getGroupFields — Returns group fields (group.field parameter values)
    • SolrQuery::getGroupFormat — Returns the group.format value
    • SolrQuery::getGroupFunctions — Returns group functions (group.func parameter values)
    • SolrQuery::getGroupLimit — Returns the group.limit value
    • SolrQuery::getGroupMain — Returns the group.main value
    • SolrQuery::getGroupNGroups — Returns the group.ngroups value
    • SolrQuery::getGroupOffset — Returns the group.offset value
    • SolrQuery::getGroupQueries — Returns all the group.query parameter values
    • SolrQuery::getGroupSortFields — Returns the group.sort value
    • SolrQuery::getGroupTruncate — Returns the group.truncate value
    • 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::removeExpandFilterQuery — Removes an expand filter query
    • SolrQuery::removeExpandSortField — Removes an expand sort field from the expand.sort parameter.
    • 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::setExpand — Enables/Disables the Expand Component
    • SolrQuery::setExpandQuery — Sets the expand.q parameter
    • SolrQuery::setExpandRows — Sets the number of rows to display in each group (expand.rows). Server Default 5
    • 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::setGroup — Enable/Disable result grouping (group parameter)
    • SolrQuery::setGroupCachePercent — Enables caching for result grouping
    • SolrQuery::setGroupFacet — Sets group.facet parameter
    • SolrQuery::setGroupFormat — Sets the group format, result structure (group.format parameter).
    • SolrQuery::setGroupLimit — Specifies the number of results to return for each group. The server default value is 1.
    • SolrQuery::setGroupMain — If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
    • SolrQuery::setGroupNGroups — If true, Solr includes the number of groups that have matched the query in the results.
    • SolrQuery::setGroupOffset — Sets the group.offset parameter.
    • SolrQuery::setGroupTruncate — If true, facet counts are based on the most relevant document of each group matching the query.
    • 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
  • SolrDisMaxQuery — The SolrDisMaxQuery class
    • SolrDisMaxQuery::addBigramPhraseField — Adds a Phrase Bigram Field (pf2 parameter)
    • SolrDisMaxQuery::addBoostQuery — Adds a boost query field with value and optional boost (bq parameter)
    • SolrDisMaxQuery::addPhraseField — Adds a Phrase Field (pf parameter)
    • SolrDisMaxQuery::addQueryField — Add a query field with optional boost (qf parameter)
    • SolrDisMaxQuery::addTrigramPhraseField — Adds a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::addUserField — Adds a field to User Fields Parameter (uf)
    • SolrDisMaxQuery::__construct — Class Constructor
    • SolrDisMaxQuery::removeBigramPhraseField — Removes phrase bigram field (pf2 parameter)
    • SolrDisMaxQuery::removeBoostQuery — Removes a boost query partial by field name (bq)
    • SolrDisMaxQuery::removePhraseField — Removes a Phrase Field (pf parameter)
    • SolrDisMaxQuery::removeQueryField — Removes a Query Field (qf parameter)
    • SolrDisMaxQuery::removeTrigramPhraseField — Removes a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::removeUserField — Removes a field from The User Fields Parameter (uf)
    • SolrDisMaxQuery::setBigramPhraseFields — Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setBigramPhraseSlop — Sets Bigram Phrase Slop (ps2 parameter)
    • SolrDisMaxQuery::setBoostFunction — Sets a Boost Function (bf parameter).
    • SolrDisMaxQuery::setBoostQuery — Directly Sets Boost Query Parameter (bq)
    • SolrDisMaxQuery::setMinimumMatch — Set Minimum "Should" Match (mm)
    • SolrDisMaxQuery::setPhraseFields — Sets Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setPhraseSlop — Sets the default slop on phrase queries (ps parameter)
    • SolrDisMaxQuery::setQueryAlt — Set Query Alternate (q.alt parameter)
    • SolrDisMaxQuery::setQueryPhraseSlop — specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)
    • SolrDisMaxQuery::setTieBreaker — Sets Tie Breaker parameter (tie parameter)
    • SolrDisMaxQuery::setTrigramPhraseFields — Directly Sets Trigram Phrase Fields (pf3 parameter)
    • SolrDisMaxQuery::setTrigramPhraseSlop — Sets Trigram Phrase Slop (ps3 parameter)
    • SolrDisMaxQuery::setUserFields — Sets User Fields parameter (uf)
    • SolrDisMaxQuery::useDisMaxQueryParser — Switch QueryParser to be DisMax Query Parser
    • SolrDisMaxQuery::useEDisMaxQueryParser — Switch QueryParser to be EDisMax
  • SolrCollapseFunction — The SolrCollapseFunction class
    • SolrCollapseFunction::__construct — Constructor
    • SolrCollapseFunction::getField — Returns the field that is being collapsed on.
    • SolrCollapseFunction::getHint — Returns collapse hint
    • SolrCollapseFunction::getMax — Returns max parameter
    • SolrCollapseFunction::getMin — Returns min parameter
    • SolrCollapseFunction::getNullPolicy — Returns null policy
    • SolrCollapseFunction::getSize — Returns size parameter
    • SolrCollapseFunction::setField — Sets the field to collapse on
    • SolrCollapseFunction::setHint — Sets collapse hint
    • SolrCollapseFunction::setMax — Selects the group heads by the max value of a numeric field or function query.
    • SolrCollapseFunction::setMin — Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::setNullPolicy — Sets the NULL Policy
    • SolrCollapseFunction::setSize — Sets the initial size of the collapse data structures when collapsing on a numeric field only.
    • SolrCollapseFunction::__toString — Returns a string representing the constructed collapse function
  • 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
  • SolrServerException — The SolrServerException class
    • SolrServerException::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
  • SolrMissingMandatoryParameterException — The SolrMissingMandatoryParameterException class
udm_set_agent_param
Introducere
Extensii ale motorului de cautare


Introducere

The Solr extension allows you to communicate effectively with the Apache Solr Server in PHP.

The Solr extension is an extremely fast, light-weight, feature-rich library that allows PHP developers to communicate effectively with Solr server instances.

Versions 1.x of The PECL Extension supports Apache Solr Server 1.3-3.x

Versions 2.x of The PECL Extension supports Apache Solr Server 4.0+

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
Instalarea / configurarea
Solr


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Solr


Necesita?i

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

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/solr.

For help and support, please visit the extension google group. » Apache Solr PHP Extension

Windows binaries (DLL files) for this PECL extension are available from the PECL website.

Nota:

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

SOLR_MAJOR_VERSION (integer)
SOLR_MINOR_VERSION (integer)
SOLR_PATCH_VERSION (integer)
SOLR_EXTENSION_VERSION (string)

Tipurile resurselor
Func?ii Solr
Solr


Func?ii Solr

Cuprins

  • solr_get_version — Returns the current version of the Apache Solr extension
Constante predefinite
solr_get_version
Solr


Returns the current version of the Apache Solr extension

Func?ii Solr
Exemple
Func?ii Solr
PHP Manual

solr_get_version

(PECL solr >= 0.9.1)

solr_get_version — Returns the current version of the Apache Solr extension

Descrierea

string solr_get_version ( void )

This function returns the current version of the extension as a string.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

It returns a string on success and FALSE on failure.

Erori/Excep?ii

This function throws no errors or exceptions.

Exemple

Example #1 solr_get_version() example

<?php

$solr_version = solr_get_version();

print $solr_version;

?>

Exemplul de mai sus va afi?a ceva similar cu:

0.9.6

A se vedea ?i

  • SolrUtils::getSolrVersion() - Returns the current version of the Solr extension

Func?ii Solr
Exemple
Func?ii Solr


Exemple

Examples of how to use the Apache Solr extension in PHP

Example #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/');

?>

Example #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());

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 446
        )

)

Example #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());

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
                        )

                )

        )

)

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
                        )

                )

        )

)

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
                        )

                )

        )

)

Example #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());

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
                )

        )

)

Example #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());

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [card] => 2
                    [connector] => 2
                    [camera] => 1
                    [copier] => 1
                )

        )

)

Example #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());

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 0
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [card] => 2
                    [connector] => 2
                )

        )

)

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

)

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

)

Example #11 Facet Date 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->addFacetDateField('manufacturedate_dt');

$query->setFacetDateStart('2006-02-13T00:00:00Z');

$query->setFacetDateEnd('2012-02-13T00:00:00Z');

$query->setFacetDateGap('+1YEAR');

$query->setFacetDateHardEnd(1);

$query->addFacetDateOther('before');

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_dates;

print_r($facet_data);

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [manufacturedate_dt] => SolrObject Object
        (
            [2006-02-13T00:00:00Z] => 9
            [2007-02-13T00:00:00Z] => 0
            [2008-02-13T00:00:00Z] => 0
            [2009-02-13T00:00:00Z] => 0
            [2010-02-13T00:00:00Z] => 0
            [2011-02-13T00:00:00Z] => 0
            [gap] => +1YEAR
            [start] => 2006-02-13T00:00:00Z
            [end] => 2012-02-13T00:00:00Z
            [before] => 2
        )

)

Example #12 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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

)

Example #13 Collapsing a SolrQuery

<?php
include "bootstrap.php";

$options = array
(
        'hostname' => SOLR_SERVER_HOSTNAME,
        'login'    => SOLR_SERVER_USERNAME,
        'password' => SOLR_SERVER_PASSWORD,
        'port'     => SOLR_SERVER_PORT,
        'path'     => SOLR_SERVER_PATH
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$collapseFunction = new SolrCollapseFunction('manu_id_s');

$collapseFunction
->setSize(2)
->setNullPolicy(SolrCollapseFunction::NULLPOLICY_IGNORE);

$query
->collapse($collapseFunction)
->setRows(4);

$queryResponse = $client->query($query);

$response = $queryResponse->getResponse();

print_r($response);
?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [q] => *:*
                    [indent] => on
                    [fq] => {!collapse field=manu_id_s size=2 nullPolicy=ignore}
                    [rows] => 4
                    [version] => 2.2
                    [wt] => xml
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 14
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [id] => SP2514N
                            [name] => Array
                                (
                                    [0] => Samsung SpinPoint P120 SP2514N - hard drive - 250 GB - ATA-133
                                )

                            [manu] => Array
                                (
                                    [0] => Samsung Electronics Co. Ltd.
                                )

                            [manu_id_s] => samsung
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => 7200RPM, 8MB cache, IDE Ultra ATA-133
                                    [1] => NoiseGuard, SilentSeek technology, Fluid Dynamic Bearing (FDB) motor
                                )

                            [price] => Array
                                (
                                    [0] => 92
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [store] => Array
                                (
                                    [0] => 35.0752,-97.032
                                )

                            [_version_] => 1510294336412057600
                        )

                    [1] => SolrObject Object
                        (
                            [id] => 6H500F0
                            [name] => Array
                                (
                                    [0] => Maxtor DiamondMax 11 - hard drive - 500 GB - SATA-300
                                )

                            [manu] => Array
                                (
                                    [0] => Maxtor Corp.
                                )

                            [manu_id_s] => maxtor
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => SATA 3.0Gb/s, NCQ
                                    [1] => 8.5ms seek
                                    [2] => 16MB cache
                                )

                            [price] => Array
                                (
                                    [0] => 350
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 45.17614,-93.87341
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [_version_] => 1510294336449806336
                        )

                    [2] => SolrObject Object
                        (
                            [id] => F8V7067-APL-KIT
                            [name] => Array
                                (
                                    [0] => Belkin Mobile Power Cord for iPod w/ Dock
                                )

                            [manu] => Array
                                (
                                    [0] => Belkin
                                )

                            [manu_id_s] => belkin
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => connector
                                )

                            [features] => Array
                                (
                                    [0] => car power adapter, white
                                )

                            [weight] => Array
                                (
                                    [0] => 4
                                )

                            [price] => Array
                                (
                                    [0] => 19.95
                                )

                            [popularity] => Array
                                (
                                    [0] => 1
                                )

                            [inStock] => Array
                                (
                                    [0] =>
                                )

                            [store] => Array
                                (
                                    [0] => 45.18014,-93.87741
                                )

                            [manufacturedate_dt] => 2005-08-01T16:30:25Z
                            [_version_] => 1510294336458194944
                        )

                    [3] => SolrObject Object
                        (
                            [id] => MA147LL/A
                            [name] => Array
                                (
                                    [0] => Apple 60 GB iPod with Video Playback Black
                                )

                            [manu] => Array
                                (
                                    [0] => Apple Computer Inc.
                                )

                            [manu_id_s] => apple
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => music
                                )

                            [features] => Array
                                (
                                    [0] => iTunes, Podcasts, Audiobooks
                                    [1] => Stores up to 15,000 songs, 25,000 photos, or 150 hours of video
                                    [2] => 2.5-inch, 320x240 color TFT LCD display with LED backlight
                                    [3] => Up to 20 hours of battery life
                                    [4] => Plays AAC, MP3, WAV, AIFF, Audible, Apple Lossless, H.264 video
                                    [5] => Notes, Calendar, Phone book, Hold button, Date display, Photo wallet, Built-in games, JPEG photo playback, Upgradeable firmware, USB 2.0 compatibility, Playback speed control, Rechargeable capability, Battery level indication
                                )

                            [includes] => Array
                                (
                                    [0] => earbud headphones, USB cable
                                )

                            [weight] => Array
                                (
                                    [0] => 5.5
                                )

                            [price] => Array
                                (
                                    [0] => 399
                                )

                            [popularity] => Array
                                (
                                    [0] => 10
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 37.7752,-100.0232
                                )

                            [manufacturedate_dt] => 2005-10-12T08:00:00Z
                            [_version_] => 1510294336562003968
                        )

                )

        )

)

Example #14 Solr Real Time Get (RTG) example SolrClient::getById()

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_SERVER_PATH
);

$client = new SolrClient($options);
$response = $client->getById('GB18030TEST');
print_r($response->getResponse());

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [doc] => SolrObject Object
        (
            [id] => GB18030TEST
            [name] => Array
                (
                    [0] => Test with some GB18030 encoded characters
                )

            [features] => Array
                (
                    [0] => No accents here
                    [1] => ??????
                    [2] => This is a feature (translated)
                    [3] => ?????????
                    [4] => This document is very shiny (translated)
                )

            [price] => Array
                (
                    [0] => 0
                )

            [inStock] => Array
                (
                    [0] => 1
                )

            [_version_] => 1510294336239042560
        )

)
solr_get_version
SolrUtils
Solr


The SolrUtils class

(PECL solr >= 0.9.2)

Introducere

Contains utility methods for retrieving the current extension version and preparing query phrases.

Also contains method for escaping query strings and parsing XML responses.

Sinopsisul clasei

abstract SolrUtils {
/* Metode */
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 )
}

Cuprins

  • 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
Exemple
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

Descrierea

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.

Parametri

xmlresponse

The XML response string from the Solr server.

parse_mode

Use SolrResponse::PARSE_SOLR_OBJ or SolrResponse::PARSE_SOLR_DOC

Valorile întoarse

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

Descrierea

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

Parametri

str

This is the query string to be escaped.

Valorile întoarse

Returns the escaped string sau FALSE în cazul e?ecului.

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

Descrierea

public static string SolrUtils::getSolrVersion ( void )

Returns the current Solr version.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public static string SolrUtils::queryPhrase ( string $str )

Prepares a phrase from an unescaped lucene string.

Parametri

str

The lucene phrase.

Valorile întoarse

Returns the phrase contained in double quotes.

SolrUtils::getSolrVersion
SolrInputDocument
SolrUtils


The SolrInputDocument class

(PECL solr >= 0.9.2)

Introducere

This class represents a Solr document that is about to be submitted to the Solr index.

Sinopsisul clasei

final SolrInputDocument {
/* Constante */
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 ;
/* Metode */
public void addChildDocument ( SolrInputDocument $child )
public void addChildDocuments ( array &$docs )
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 array getChildDocuments ( void )
public integer getChildDocumentsCount ( void )
public SolrDocumentField getField ( string $fieldName )
public float getFieldBoost ( string $fieldName )
public int getFieldCount ( void )
public array getFieldNames ( void )
public boolean hasChildDocuments ( 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 )
}

Constante predefinite

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.

Cuprins

  • SolrInputDocument::addChildDocument — Adds a child document for block indexing
  • SolrInputDocument::addChildDocuments — Adds an array of child documents
  • 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::getChildDocuments — Returns an array of child documents (SolrInputDocument)
  • SolrInputDocument::getChildDocumentsCount — Returns the number of child documents
  • 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::hasChildDocuments — Returns true if the document has any child documents
  • 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::addChildDocument
Solr


Adds a child document for block indexing

SolrInputDocument
SolrInputDocument::addChildDocuments
SolrInputDocument
PHP Manual

SolrInputDocument::addChildDocument

(PECL solr >= 2.3.0)

SolrInputDocument::addChildDocument — Adds a child document for block indexing

Descrierea

public void SolrInputDocument::addChildDocument ( SolrInputDocument $child )

Adds a child document to construct a document block with nested documents.

Parametri

child

A SolrInputDocument object.

Erori/Excep?ii

Throws SolrIllegalArgumentException on failure.

Throws SolrException on internal failure.

Valorile întoarse

Exemple

Example #1 SolrInputDocument::addChildDocument() example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_SERVER_STORE_PATH,
);

$client = new SolrClient($options);

$product = new SolrInputDocument();

$product->addField('id', 'P-BLACK');
$product->addField('cat', 'tshirt');
$product->addField('cat', 'polo');
$product->addField('content_type', 'product');

$small = new SolrInputDocument();
$small->addField('id', 'TS-BLK-S');
$small->addField('content_type', 'sku');
$small->addField('size', 'S');
$small->addField('inventory', 100);

$medium = new SolrInputDocument();
$medium->addField('id', 'TS-BLK-M');
$medium->addField('content_type', 'sku');
$medium->addField('size', 'M');
$medium->addField('inventory', 200);

$large = new SolrInputDocument();
$large->addField('id', 'TS-BLK-L');
$large->addField('content_type', 'sku');
$large->addField('size', 'L');
$large->addField('inventory', 300);

// add child documents
$product->addChildDocument($small);
$product->addChildDocument($medium);
$product->addChildDocument($large);

// add product document block to the index
$updateResponse = $client->addDocument(
        $product,
        true, // overwrite if the document exists
        10000 // commit within 10 seconds
);

print_r($updateResponse->getResponse());

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 5
        )
)

A se vedea ?i

  • SolrInputDocument::addChildDocuments() - Adds an array of child documents
  • SolrInputDocument::hasChildDocuments() - Returns true if the document has any child documents
  • SolrInputDocument::getChildDocuments() - Returns an array of child documents (SolrInputDocument)
  • SolrInputDocument::getChildDocumentsCount() - Returns the number of child documents
SolrInputDocument
SolrInputDocument::addChildDocuments
SolrInputDocument


Adds an array of child documents

SolrInputDocument::addChildDocument
SolrInputDocument::addField
SolrInputDocument
PHP Manual

SolrInputDocument::addChildDocuments

(PECL solr >= 2.3.0)

SolrInputDocument::addChildDocuments — Adds an array of child documents

Descrierea

public void SolrInputDocument::addChildDocuments ( array &$docs )

Adds an array of child documents to the current input document.

Parametri

docs

An array of SolrInputDocument objects.

Erori/Excep?ii

Throws SolrIllegalArgumentException on failure.

Throws SolrException on internal failure.

Valorile întoarse

Exemple

Example #1 SolrInputDocument::addChildDocuments() example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_SERVER_STORE_PATH,
);

$client = new SolrClient($options);

$product = new SolrInputDocument();

$product->addField('id', 'P-BLACK');
$product->addField('cat', 'tshirt');
$product->addField('cat', 'polo');
$product->addField('content_type', 'product');

$small = new SolrInputDocument();
$small->addField('id', 'TS-BLK-S');
$small->addField('content_type', 'sku');
$small->addField('size', 'S');
$small->addField('inventory', 100);

$medium = new SolrInputDocument();
$medium->addField('id', 'TS-BLK-M');
$medium->addField('content_type', 'sku');
$medium->addField('size', 'M');
$medium->addField('inventory', 200);

$large = new SolrInputDocument();
$large->addField('id', 'TS-BLK-L');
$large->addField('content_type', 'sku');
$large->addField('size', 'L');
$large->addField('inventory', 300);

// add child documents
$skus = [$small, $medium, $large];
$product->addChildDocuments($skus);

// add the product document block to the index
$updateResponse = $client->addDocument(
        $product,
        true, // overwrite if the document exists
        10000 // commit within 10 seconds
);

print_r($updateResponse->getResponse());

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 5
        )
)

A se vedea ?i

  • SolrInputDocument::addChildDocument() - Adds a child document for block indexing
  • SolrInputDocument::hasChildDocuments() - Returns true if the document has any child documents
  • SolrInputDocument::getChildDocuments() - Returns an array of child documents (SolrInputDocument)
  • SolrInputDocument::getChildDocumentsCount() - Returns the number of child documents
SolrInputDocument::addChildDocument
SolrInputDocument::addField
SolrInputDocument


Adds a field to the document

SolrInputDocument::addChildDocuments
SolrInputDocument::clear
SolrInputDocument
PHP Manual

SolrInputDocument::addField

(PECL solr >= 0.9.2)

SolrInputDocument::addField — Adds a field to the document

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

SolrInputDocument::addChildDocuments
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

Descrierea

public bool SolrInputDocument::clear ( void )

Resets the document by dropping all the fields and resets the document boost to zero.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public void SolrInputDocument::__clone ( void )

Should not be called directly. It is used to create a deep copy of a SolrInputDocument.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public SolrInputDocument::__construct ( void )

Constructor.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrInputDocument::deleteField ( string $fieldName )

Removes a field from the document.

Parametri

fieldName

The name of the field.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

SolrInputDocument::__construct
SolrInputDocument::__destruct
SolrInputDocument


Destructor

SolrInputDocument::deleteField
SolrInputDocument::fieldExists
SolrInputDocument
PHP Manual

SolrInputDocument::__destruct

(PECL solr >= 0.9.2)

SolrInputDocument::__destruct — Destructor

Descrierea

public void SolrInputDocument::__destruct ( void )

Destructor

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrInputDocument::fieldExists ( string $fieldName )

Checks if a field exists

Parametri

fieldName

Name of the field.

Valorile întoarse

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::getChildDocuments
SolrInputDocument
PHP Manual

SolrInputDocument::getBoost

(PECL solr >= 0.9.2)

SolrInputDocument::getBoost — Retrieves the current boost value for the document

Descrierea

public float SolrInputDocument::getBoost ( void )

Retrieves the current boost value for the document.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the boost value on success and FALSE on failure.

SolrInputDocument::fieldExists
SolrInputDocument::getChildDocuments
SolrInputDocument


Returns an array of child documents (SolrInputDocument)

SolrInputDocument::getBoost
SolrInputDocument::getChildDocumentsCount
SolrInputDocument
PHP Manual

SolrInputDocument::getChildDocuments

(PECL solr >= 2.3.0)

SolrInputDocument::getChildDocuments — Returns an array of child documents (SolrInputDocument)

Descrierea

public array SolrInputDocument::getChildDocuments ( void )

Returns an array of child documents (SolrInputDocument)

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrInputDocument::addChildDocument() - Adds a child document for block indexing
  • SolrInputDocument::addChildDocuments() - Adds an array of child documents
  • SolrInputDocument::hasChildDocuments() - Returns true if the document has any child documents
  • SolrInputDocument::getChildDocumentsCount() - Returns the number of child documents
SolrInputDocument::getBoost
SolrInputDocument::getChildDocumentsCount
SolrInputDocument


Returns the number of child documents

SolrInputDocument::getChildDocuments
SolrInputDocument::getField
SolrInputDocument
PHP Manual

SolrInputDocument::getChildDocumentsCount

(PECL solr >= 2.3.0)

SolrInputDocument::getChildDocumentsCount — Returns the number of child documents

Descrierea

public integer SolrInputDocument::getChildDocumentsCount ( void )

Returns the number of child documents

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrInputDocument::addChildDocument() - Adds a child document for block indexing
  • SolrInputDocument::addChildDocuments() - Adds an array of child documents
  • SolrInputDocument::hasChildDocuments() - Returns true if the document has any child documents
  • SolrInputDocument::getChildDocuments() - Returns an array of child documents (SolrInputDocument)
SolrInputDocument::getChildDocuments
SolrInputDocument::getField
SolrInputDocument


Retrieves a field by name

SolrInputDocument::getChildDocumentsCount
SolrInputDocument::getFieldBoost
SolrInputDocument
PHP Manual

SolrInputDocument::getField

(PECL solr >= 0.9.2)

SolrInputDocument::getField — Retrieves a field by name

Descrierea

public SolrDocumentField SolrInputDocument::getField ( string $fieldName )

Retrieves a field in the document.

Parametri

fieldName

The name of the field.

Valorile întoarse

Returns a SolrDocumentField object on success and FALSE on failure.

SolrInputDocument::getChildDocumentsCount
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

Descrierea

public float SolrInputDocument::getFieldBoost ( string $fieldName )

Retrieves the boost value for a particular field.

Parametri

fieldName

The name of the field.

Valorile întoarse

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

Descrierea

public int SolrInputDocument::getFieldCount ( void )

Returns the number of fields in the document.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an integer on success sau FALSE în cazul e?ecului.

SolrInputDocument::getFieldBoost
SolrInputDocument::getFieldNames
SolrInputDocument


Returns an array containing all the fields in the document

SolrInputDocument::getFieldCount
SolrInputDocument::hasChildDocuments
SolrInputDocument
PHP Manual

SolrInputDocument::getFieldNames

(PECL solr >= 0.9.2)

SolrInputDocument::getFieldNames — Returns an array containing all the fields in the document

Descrierea

public array SolrInputDocument::getFieldNames ( void )

Returns an array containing all the fields in the document.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array on success and FALSE on failure.

SolrInputDocument::getFieldCount
SolrInputDocument::hasChildDocuments
SolrInputDocument


Returns true if the document has any child documents

SolrInputDocument::getFieldNames
SolrInputDocument::merge
SolrInputDocument
PHP Manual

SolrInputDocument::hasChildDocuments

(PECL solr >= 2.3.0)

SolrInputDocument::hasChildDocuments — Returns true if the document has any child documents

Descrierea

public boolean SolrInputDocument::hasChildDocuments ( void )

Checks whether the document has any child documents

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrInputDocument::addChildDocument() - Adds a child document for block indexing
  • SolrInputDocument::addChildDocuments() - Adds an array of child documents
  • SolrInputDocument::getChildDocuments() - Returns an array of child documents (SolrInputDocument)
  • SolrInputDocument::getChildDocumentsCount() - Returns the number of child documents
SolrInputDocument::getFieldNames
SolrInputDocument::merge
SolrInputDocument


Merges one input document into another

SolrInputDocument::hasChildDocuments
SolrInputDocument::reset
SolrInputDocument
PHP Manual

SolrInputDocument::merge

(PECL solr >= 0.9.2)

SolrInputDocument::merge — Merges one input document into another

Descrierea

public bool SolrInputDocument::merge ( SolrInputDocument $sourceDoc [, bool $overwrite = true ] )

Merges one input document into another.

Parametri

sourceDoc

The source document.

overwrite

If this is TRUE it will replace matching fields in the destination document.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. In the future, this will be modified to return the number of fields in the new document.

SolrInputDocument::hasChildDocuments
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

Descrierea

public bool SolrInputDocument::reset ( void )

This is an alias of SolrInputDocument::clear

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public bool SolrInputDocument::setBoost ( float $documentBoostValue )

Sets the boost value for this document.

Parametri

documentBoostValue

The index-time boost value for this document.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

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.

Parametri

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

Descrierea

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

Parametri

sortOrderBy

The sort criteria

sortDirection

The sort direction

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public array SolrInputDocument::toArray ( void )

Returns an array representation of the input document.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array containing the fields. It returns FALSE on failure.

SolrInputDocument::sort
SolrDocument
SolrInputDocument


The SolrDocument class

(PECL solr >= 0.9.2)

Introducere

Represents a Solr document retrieved from a query response.

Sinopsisul clasei

final SolrDocument implements ArrayAccess , Iterator , Serializable {
/* Constante */
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 ;
/* Metode */
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 array getChildDocuments ( void )
public integer getChildDocumentsCount ( void )
public SolrDocumentField getField ( string $fieldName )
public int getFieldCount ( void )
public array getFieldNames ( void )
public SolrInputDocument getInputDocument ( void )
public bool hasChildDocuments ( 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 )
}

Constante predefinite

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.

Cuprins

  • 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 — Access the field as a property
  • SolrDocument::getChildDocuments — Returns an array of child documents (SolrDocument)
  • SolrDocument::getChildDocumentsCount — Returns the number of child documents
  • 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::hasChildDocuments — Checks whether the document has any child documents
  • 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

Descrierea

public bool SolrDocument::addField ( string $fieldName , string $fieldValue )

This method adds a field to the SolrDocument instance.

Parametri

fieldName

The name of the field

fieldValue

The value of the field.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public bool SolrDocument::clear ( void )

Resets the current object. Discards all the fields and resets the document boost to zero.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public void SolrDocument::__clone ( void )

Creates a copy of a SolrDocument object. Not to be called directly.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None.

SolrDocument::clear
SolrDocument::__construct
SolrDocument


Constructor

SolrDocument::__clone
SolrDocument::current
SolrDocument
PHP Manual

SolrDocument::__construct

(PECL solr >= 0.9.2)

SolrDocument::__construct — Constructor

Descrierea

public SolrDocument::__construct ( void )

Constructor for SolrDocument

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public SolrDocumentField SolrDocument::current ( void )

Retrieves the current field

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrDocument::deleteField ( string $fieldName )

Removes a field from the document.

Parametri

fieldName

Name of the field

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

SolrDocument::current
SolrDocument::__destruct
SolrDocument


Destructor

SolrDocument::deleteField
SolrDocument::fieldExists
SolrDocument
PHP Manual

SolrDocument::__destruct

(PECL solr >= 0.9.2)

SolrDocument::__destruct — Destructor

Descrierea

public void SolrDocument::__destruct ( void )

Destructor for SolrDocument.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrDocument::fieldExists ( string $fieldName )

Checks if the requested field as a valid fieldname in the document.

Parametri

fieldName

The name of the field.

Valorile întoarse

Returns TRUE if the field is present and FALSE if it does not.

SolrDocument::__destruct
SolrDocument::__get
SolrDocument


Access the field as a property

SolrDocument::fieldExists
SolrDocument::getChildDocuments
SolrDocument
PHP Manual

SolrDocument::__get

(PECL solr >= 0.9.2)

SolrDocument::__get — Access the field as a property

Descrierea

public SolrDocumentField SolrDocument::__get ( string $fieldName )

Magic method for accessing the field as a property.

Parametri

fieldName

The name of the field.

Valorile întoarse

Returns a SolrDocumentField instance.

SolrDocument::fieldExists
SolrDocument::getChildDocuments
SolrDocument


Returns an array of child documents (SolrDocument)

SolrDocument::__get
SolrDocument::getChildDocumentsCount
SolrDocument
PHP Manual

SolrDocument::getChildDocuments

(PECL solr >= 2.3.0)

SolrDocument::getChildDocuments — Returns an array of child documents (SolrDocument)

Descrierea

public array SolrDocument::getChildDocuments ( void )

Returns an array of child documents (SolrDocument)

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrDocument::hasChildDocuments() - Checks whether the document has any child documents
  • SolrDocument::getChildDocumentsCount() - Returns the number of child documents
SolrDocument::__get
SolrDocument::getChildDocumentsCount
SolrDocument


Returns the number of child documents

SolrDocument::getChildDocuments
SolrDocument::getField
SolrDocument
PHP Manual

SolrDocument::getChildDocumentsCount

(PECL solr >= 2.3.0)

SolrDocument::getChildDocumentsCount — Returns the number of child documents

Descrierea

public integer SolrDocument::getChildDocumentsCount ( void )

Returns the number of child documents

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrDocument::hasChildDocuments() - Checks whether the document has any child documents
  • SolrDocument::getChildDocuments() - Returns an array of child documents (SolrDocument)
SolrDocument::getChildDocuments
SolrDocument::getField
SolrDocument


Retrieves a field by name

SolrDocument::getChildDocumentsCount
SolrDocument::getFieldCount
SolrDocument
PHP Manual

SolrDocument::getField

(PECL solr >= 0.9.2)

SolrDocument::getField — Retrieves a field by name

Descrierea

public SolrDocumentField SolrDocument::getField ( string $fieldName )

Retrieves a field by name.

Parametri

fieldName

Name of the field.

Valorile întoarse

Returns a SolrDocumentField on success and FALSE on failure.

SolrDocument::getChildDocumentsCount
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

Descrierea

public int SolrDocument::getFieldCount ( void )

Returns the number of fields in this document. Multi-value fields are only counted once.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public array SolrDocument::getFieldNames ( void )

Returns an array of fields names in the document.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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::hasChildDocuments
SolrDocument
PHP Manual

SolrDocument::getInputDocument

(PECL solr >= 0.9.2)

SolrDocument::getInputDocument — Returns a SolrInputDocument equivalent of the object

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a SolrInputDocument on success and NULL on failure.

SolrDocument::getFieldNames
SolrDocument::hasChildDocuments
SolrDocument


Checks whether the document has any child documents

SolrDocument::getInputDocument
SolrDocument::__isset
SolrDocument
PHP Manual

SolrDocument::hasChildDocuments

(PECL solr >= 2.3.0)

SolrDocument::hasChildDocuments — Checks whether the document has any child documents

Descrierea

public bool SolrDocument::hasChildDocuments ( void )

Checks whether the document has any child documents

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrDocument::getChildDocuments() - Returns an array of child documents (SolrDocument)
  • SolrDocument::getChildDocumentsCount() - Returns the number of child documents
SolrDocument::getInputDocument
SolrDocument::__isset
SolrDocument


Checks if a field exists

SolrDocument::hasChildDocuments
SolrDocument::key
SolrDocument
PHP Manual

SolrDocument::__isset

(PECL solr >= 0.9.2)

SolrDocument::__isset — Checks if a field exists

Descrierea

public bool SolrDocument::__isset ( string $fieldName )

Checks if a field exists

Parametri

fieldName

Name of the field.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

SolrDocument::hasChildDocuments
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

Descrierea

public string SolrDocument::key ( void )

Retrieves the current key.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrDocument::merge ( SolrDocument $sourceDoc [, bool $overwrite = true ] )

Merges source to the current SolrDocument.

Parametri

sourceDoc

The source document.

overwrite

If this is TRUE then fields with the same name in the destination document will be overwritten.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public void SolrDocument::next ( void )

Moves the internal pointer to the next field.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrDocument::offsetExists ( string $fieldName )

Checks if a particular field exists. This is used when the object is treated as an array.

Parametri

fieldName

The name of the field.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public SolrDocumentField SolrDocument::offsetGet ( string $fieldName )

This is used to retrieve the field when the object is treated as an array.

Parametri

fieldName

The name of the field.

Valorile întoarse

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

Descrierea

public void SolrDocument::offsetSet ( string $fieldName , string $fieldValue )

Used when the object is treated as an array to add a field to the document.

Parametri

fieldName

The name of the field.

fieldValue

The value for this field.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public void SolrDocument::offsetUnset ( string $fieldName )

Removes a field from the document.

Parametri

fieldName

The name of the field.

Valorile întoarse

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()

Descrierea

public bool SolrDocument::reset ( void )

This is an alias to SolrDocument::clear()

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public void SolrDocument::rewind ( void )

Resets the internal pointer to the beginning.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrDocument::serialize ( void )

Used for custom serialization.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrDocument::__set ( string $fieldName , string $fieldValue )

Adds another field to the document. Used to set the fields as new properties.

Parametri

fieldName

Name of the field.

fieldValue

Field value.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

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.

Parametri

sortOrderBy

The sort criteria.

sortDirection

The sort direction.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public array SolrDocument::toArray ( void )

Returns an array representation of the document.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array representation of the document.

Exemple

Example #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());

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

public void SolrDocument::unserialize ( string $serialized )

Custom serialization of SolrDocument objects

Parametri

serialized

An XML representation of the document.

Valorile întoarse

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

Descrierea

public bool SolrDocument::__unset ( string $fieldName )

Removes a field from the document when the field is access as an object property.

Parametri

fieldName

The name of the field.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public bool SolrDocument::valid ( void )

Checks if the current position internally is still valid. It is used during foreach operations.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE on success and FALSE if the current position is no longer valid.

SolrDocument::__unset
SolrDocumentField
SolrDocument


The SolrDocumentField class

(PECL solr >= 0.9.2)

Introducere

This represents a field in a Solr document. All its properties are read-only.

Sinopsisul clasei

final SolrDocumentField {
/* Proprieta?i */
readonly public string $name ;
readonly public float $boost ;
readonly public array $values ;
/* Metode */
public __construct ( void )
public void __destruct ( void )
}

Proprieta?i

name

The name of the field.

boost

The boost value for the field

values

An array of values for this field

Cuprins

  • 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

Descrierea

public SolrDocumentField::__construct ( void )

Constructor.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None.

SolrDocumentField
SolrDocumentField::__destruct
SolrDocumentField


Destructor

SolrDocumentField::__construct
SolrObject
SolrDocumentField
PHP Manual

SolrDocumentField::__destruct

(PECL solr >= 0.9.2)

SolrDocumentField::__destruct — Destructor

Descrierea

public void SolrDocumentField::__destruct ( void )

Destructor.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None.

SolrDocumentField::__construct
SolrObject
SolrDocumentField


The SolrObject class

(PECL solr >= 0.9.2)

Introducere

This is an object whose properties can also by accessed using the array syntax. All its properties are read-only.

Sinopsisul clasei

final SolrObject implements ArrayAccess {
/* Metode */
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 )
}

Cuprins

  • 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 — Unsets 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

Descrierea

public SolrObject::__construct ( void )

Creates Solr object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None

Exemple

Example #1 SolrObject::__construct() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

SolrObject
SolrObject::__destruct
SolrObject


Destructor

SolrObject::__construct
SolrObject::getPropertyNames
SolrObject
PHP Manual

SolrObject::__destruct

(PECL solr >= 0.9.2)

SolrObject::__destruct — Destructor

Descrierea

public void SolrObject::__destruct ( void )

The destructor

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public array SolrObject::getPropertyNames ( void )

Returns an array of all the names of the properties

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrObject::offsetExists ( string $property_name )

Checks if the property exists. This is used when the object is treated as an array.

Parametri

property_name

The name of the property.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

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.

Parametri

property_name

Name of the property.

Valorile întoarse

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

Descrierea

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.

Parametri

property_name

The name of the property.

property_value

The new value.

Valorile întoarse

None.

SolrObject::offsetGet
SolrObject::offsetUnset
SolrObject


Unsets the value for the property

SolrObject::offsetSet
SolrClient
SolrObject
PHP Manual

SolrObject::offsetUnset

(PECL solr >= 0.9.2)

SolrObject::offsetUnset — Unsets the value for the property

Descrierea

public void SolrObject::offsetUnset ( string $property_name )

Unsets 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.

Parametri

property_name

The name of the property.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 SolrObject::offsetUnset() example

<?php
/* ... */
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

  • Classname::Method()

SolrObject::offsetSet
SolrClient
SolrObject


The SolrClient class

(PECL solr >= 0.9.2)

Introducere

Used to send requests to a Solr server. Currently, cloning and serialization of SolrClient instances is not supported.

Sinopsisul clasei

final SolrClient {
/* Constante */
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 integer SYSTEM_SERVLET_TYPE = 32 ;
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 ;
const string DEFAULT_SYSTEM_SERVLET = admin/system ;
/* Metode */
public SolrUpdateResponse addDocument ( SolrInputDocument $doc [, bool $overwrite = true [, int $commitWithin = 0 ]] )
public void addDocuments ( array $docs [, bool $overwrite = true [, int $commitWithin = 0 ]] )
public SolrUpdateResponse commit ([ bool $softCommit = false [, bool $waitSearcher = true [, bool $expungeDeletes = false ]]] )
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 SolrQueryResponse getById ( string $id )
public SolrQueryResponse getByIds ( array $ids )
public string getDebug ( void )
public array getOptions ( void )
public SolrUpdateResponse optimize ([ int $maxSegments = 1 [, bool $softCommit = true [, bool $waitSearcher = true ]]] )
public SolrPingResponse ping ( void )
public SolrQueryResponse query ( SolrParams $query )
public SolrUpdateResponse request ( string $raw_request )
public SolrUpdateResponse rollback ( void )
public void setResponseWriter ( string $responseWriter )
public bool setServlet ( int $type , string $value )
public void system ( void )
public void threads ( void )
}

Constante predefinite

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::SYSTEM_SERVLET_TYPE

Used when retrieving system information from the system 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

SolrClient::DEFAULT_SYSTEM_SERVLET

This is the intial value for the system servlet used to obtain Solr Server information

Cuprins

  • 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::getById — Get Document By Id. Utilizes Solr Realtime Get (RTG).
  • SolrClient::getByIds — Get Documents by their Ids. Utilizes Solr Realtime Get (RTG).
  • 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::system — Retrieve Solr Server information
  • 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

Descrierea

public SolrUpdateResponse SolrClient::addDocument ( SolrInputDocument $doc [, bool $overwrite = true [, int $commitWithin = 0 ]] )

This method adds a document to the index.

Parametri

doc

The SolrInputDocument instance.

overwrite

Whether to overwrite existing document or not. If FALSE there will be duplicates (several documents with the same ID).

Avertizare

PECL Solr < 2.0 $allowDups was used instead of $overwrite, which does the same functionality with exact opposite bool flag.

$allowDups = false is the same as $overwrite = true

commitWithin

Number of milliseconds within which to auto commit this document. Available since Solr 1.4 . Default (0) means disabled.

When this value specified, it leaves the control of when to do the commit to Solr itself, optimizing number of commits to a minimum while still fulfilling the update latency requirements, and Solr will automatically do a commit when the oldest add in the buffer is due.

Valorile întoarse

Returns a SolrUpdateResponse object or throws an Exception on failure.

Erori/Excep?ii

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Exemple

Example #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);

// you will have to commit changes to be written if you didn't use $commitWithin
$client->commit();

print_r($updateResponse->getResponse());

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

)

Example #2 SolrClient::addDocument() example 2

<?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');

// No need to call commit() because $commitWithin is passed, so Solr Server will auto commit within 10 seconds
$updateResponse = $client->addDocument($doc, false, 10000);

print_r($updateResponse->getResponse());

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

)

A se vedea ?i

  • SolrClient::addDocuments() - Adds a collection of SolrInputDocument instances to the index
  • SolrClient::commit() - Finalizes all add/deletes made 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

Descrierea

public void SolrClient::addDocuments ( array $docs [, bool $overwrite = true [, int $commitWithin = 0 ]] )

Adds a collection of documents to the index.

Parametri

docs

An array containing the collection of SolrInputDocument instances. This array must be an actual variable.

overwrite

Whether to overwrite existing documents or not. If FALSE there will be duplicates (several documents with the same ID).

Avertizare

PECL Solr < 2.0 $allowDups was used instead of $overwrite, which does the same functionality with exact opposite bool flag.

$allowDups = false is the same as $overwrite = true

commitWithin

Number of milliseconds within which to auto commit this document. Available since Solr 1.4 . Default (0) means disabled.

When this value specified, it leaves the control of when to do the commit to Solr itself, optimizing number of commits to a minimum while still fulfilling the update latency requirements, and Solr will automatically do a commit when the oldest add in the buffer is due.

Valorile întoarse

Returns a SolrUpdateResponse object or throws an exception on failure.

Erori/Excep?ii

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Exemple

Example #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);

// no changes will be written to disk unless $commitWithin is passed or SolrClient::commit is called

print_r($updateResponse->getResponse());

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 2
        )

)

A se vedea ?i

  • SolrClient::addDocument() - Adds a document to the index
  • SolrClient::commit() - Finalizes all add/deletes made 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

Descrierea

public SolrUpdateResponse SolrClient::commit ([ bool $softCommit = false [, bool $waitSearcher = true [, bool $expungeDeletes = false ]]] )

This method finalizes all add/deletes made to the index.

Parametri

softCommit

This will refresh the 'view' of the index in a more performant manner, but without "on-disk" guarantees. (Solr4.0+)

A soft commit is much faster since it only makes index changes visible and does not fsync index files or write a new index descriptor. If the JVM crashes or there is a loss of power, changes that occurred after the last hard commit will be lost. Search collections that have near-real-time requirements (that want index changes to be quickly visible to searches) will want to soft commit often but hard commit less frequently.

waitSearcher

block until a new searcher is opened and registered as the main query searcher, making the changes visible.

expungeDeletes

Merge segments with deletes away. (Solr1.4+)

Valorile întoarse

Returns a SolrUpdateResponse object on success or throws an exception on failure.

Erori/Excep?ii

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Istoricul schimbarilor

Versiune | Descriere
1.1.0, 2.0.0 | $maxSegments removed
2.0.0b | API Changed: SolrClient::commit ([ int $maxSegments = 0 [, bool $softCommit = false [, bool $waitSearcher = true[, bool $expungeDeletes = false ]]] )
0.9.2 | Signature: SolrClient::commit ([ int $maxSegments = 1 [, bool $waitFlush = true [, bool $waitSearcher = true ]]] ). $waitFlush: Block until index changes are flushed to disk.

Note

Avertizare

PECL Solr >= 2.0 only supports Solr Server >= 4.0

A se vedea ?i

  • 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

Descrierea

public SolrClient::__construct ( array $clientOptions )

Constructor for the SolrClient object

Parametri

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, json)
 - 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.

Erori/Excep?ii

Throws SolrIllegalArgumentException on failure.

Exemple

Example #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'       => 'xml',
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

?>

Exemplul de mai sus va afi?a ceva similar cu:

A se vedea ?i

  • 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

Descrierea

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

Parametri

id

The value of the uniqueKey field declared in the schema

Valorile întoarse

Returns a SolrUpdateResponse on success and throws an exception on failure.

Erori/Excep?ii

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

A se vedea ?i

  • 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

Descrierea

public SolrUpdateResponse SolrClient::deleteByIds ( array $ids )

Deletes a collection of documents with the specified set of ids.

Parametri

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.

Valorile întoarse

Returns a SolrUpdateResponse on success and throws an exception on failure.

Erori/Excep?ii

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

A se vedea ?i

  • 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

Descrierea

public SolrUpdateResponse SolrClient::deleteByQueries ( array $queries )

Removes all documents matching any of the queries

Parametri

queries

The array of queries. This must be an actual php variable.

Valorile întoarse

Returns a SolrUpdateResponse on success and throws a SolrClientException on failure.

Erori/Excep?ii

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

A se vedea ?i

  • 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

Descrierea

public SolrUpdateResponse SolrClient::deleteByQuery ( string $query )

Deletes all documents matching the given query.

Parametri

query

The query

Valorile întoarse

Returns a SolrUpdateResponse on success and throws an exception on failure.

Erori/Excep?ii

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Exemple

Example #1 SolrQuery::deleteByQuery() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

//This will erase the entire index
$client->deleteByQuery("*:*");
$client->commit();

?>

A se vedea ?i

  • 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::getById
SolrClient
PHP Manual

SolrClient::__destruct

(PECL solr >= 0.9.2)

SolrClient::__destruct — Destructor for SolrClient

Descrierea

public void SolrClient::__destruct ( void )

Destructor

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Destructor for SolrClient

A se vedea ?i

  • SolrClient::__construct() - Constructor for the SolrClient object

SolrClient::deleteByQuery
SolrClient::getById
SolrClient


Get Document By Id. Utilizes Solr Realtime Get (RTG).

SolrClient::__destruct
SolrClient::getByIds
SolrClient
PHP Manual

SolrClient::getById

(PECL solr >= 2.2.0)

SolrClient::getById — Get Document By Id. Utilizes Solr Realtime Get (RTG).

Descrierea

public SolrQueryResponse SolrClient::getById ( string $id )

Get Document By Id. Utilizes Solr Realtime Get (RTG).

Parametri

id

Document ID

Valorile întoarse

SolrQueryResponse

Exemple

Example #1 SolrClient::getById() example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_SERVER_PATH
);

$client = new SolrClient($options);
$response = $client->getById('GB18030TEST');
print_r($response->getResponse());

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [doc] => SolrObject Object
        (
            [id] => GB18030TEST
            [name] => Array
                (
                    [0] => Test with some GB18030 encoded characters
                )

            [features] => Array
                (
                    [0] => No accents here
                    [1] => ??????
                    [2] => This is a feature (translated)
                    [3] => ?????????
                    [4] => This document is very shiny (translated)
                )

            [price] => Array
                (
                    [0] => 0
                )

            [inStock] => Array
                (
                    [0] => 1
                )

            [_version_] => 1510294336239042560
        )

)

A se vedea ?i

  • SolrClient::getByIds() - Get Documents by their Ids. Utilizes Solr Realtime Get (RTG).
SolrClient::__destruct
SolrClient::getByIds
SolrClient


Get Documents by their Ids. Utilizes Solr Realtime Get (RTG).

SolrClient::getById
SolrClient::getDebug
SolrClient
PHP Manual

SolrClient::getByIds

(PECL solr >= 2.2.0)

SolrClient::getByIds — Get Documents by their Ids. Utilizes Solr Realtime Get (RTG).

Descrierea

public SolrQueryResponse SolrClient::getByIds ( array $ids )

Get Documents by their Ids. Utilizes Solr Realtime Get (RTG).

Parametri

ids

Document ids

Valorile întoarse

SolrQueryResponse

Exemple

Example #1 SolrClient::getByIds() example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_SERVER_PATH
);

$client = new SolrClient($options);
$response = $client->getByIds(['GB18030TEST', '6H500F0']);

print_r($response->getResponse());

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [response] => SolrObject Object
        (
            [numFound] => 2
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [id] => GB18030TEST
                            [name] => Array
                                (
                                    [0] => Test with some GB18030 encoded characters
                                )

                            [features] => Array
                                (
                                    [0] => No accents here
                                    [1] => ??????
                                    [2] => This is a feature (translated)
                                    [3] => ?????????
                                    [4] => This document is very shiny (translated)
                                )

                            [price] => Array
                                (
                                    [0] => 0
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [_version_] => 1510294336239042560
                        )

                    [1] => SolrObject Object
                        (
                            [id] => 6H500F0
                            [name] => Array
                                (
                                    [0] => Maxtor DiamondMax 11 - hard drive - 500 GB - SATA-300
                                )

                            [manu] => Array
                                (
                                    [0] => Maxtor Corp.
                                )

                            [manu_id_s] => maxtor
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => SATA 3.0Gb/s, NCQ
                                    [1] => 8.5ms seek
                                    [2] => 16MB cache
                                )

                            [price] => Array
                                (
                                    [0] => 350
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 45.17614,-93.87341
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [_version_] => 1510294336449806336
                        )

                )

        )

)

A se vedea ?i

  • SolrClient::getById() - Get Document By Id. Utilizes Solr Realtime Get (RTG).
SolrClient::getById
SolrClient::getDebug
SolrClient


Returns the debug data for the last connection attempt

SolrClient::getByIds
SolrClient::getOptions
SolrClient
PHP Manual

SolrClient::getDebug

(PECL solr >= 0.9.7)

SolrClient::getDebug — Returns the debug data for the last connection attempt

Descrierea

public string SolrClient::getDebug ( void )

Returns the debug data for the last connection attempt

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string on success and null if there is nothing to return.

SolrClient::getByIds
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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array containing all the options for the SolrClient object set internally.

A se vedea ?i

  • 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

Descrierea

public SolrUpdateResponse SolrClient::optimize ([ int $maxSegments = 1 [, bool $softCommit = true [, bool $waitSearcher = true ]]] )

Defragments the index for faster search performance.

Parametri

maxSegments

Optimizes down to at most this number of segments. Since Solr 1.3

softCommit

This will refresh the 'view' of the index in a more performant manner, but without "on-disk" guarantees. (Solr4.0+)

waitSearcher

Block until a new searcher is opened and registered as the main query searcher, making the changes visible.

Valorile întoarse

Returns a SolrUpdateResponse on success or throws an exception on failure.

Erori/Excep?ii

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Note

Avertizare

PECL Solr >= 2.0 only supports Solr Server >= 4.0

Prior to PECL Solr 2.0 this method used to accept these arguments "int $maxSegments, bool $waitFlush, bool $waitSearcher".

A se vedea ?i

  • 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

Descrierea

public SolrPingResponse SolrClient::ping ( void )

Checks if the Solr server is still alive. Sends a HEAD request to the Apache Solr server.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a SolrPingResponse object on success and throws an exception on failure.

Erori/Excep?ii

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to satisfy the request.

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

public SolrQueryResponse SolrClient::query ( SolrParams $query )

Sends a query to the server.

Parametri

query

A SolrParams object. It is recommended to use SolrQuery for advanced queries.

Valorile întoarse

Returns a SolrQueryResponse object on success and throws an exception on failure.

Erori/Excep?ii

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to satisfy the query.

Exemple

Example #1 SolrClient::query() example

<?php

$options = array
(
    'hostname' => 'localhost',
    'login'    => 'username',
    'password' => 'password',
    'port'     => '8983',
);

$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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 3
            [params] => SolrObject Object
                (
                    [fl] => cat,features,id,timestamp
                    [indent] => on
                    [start] => 0
                    [q] => lucene
                    [wt] => xml
                    [version] => 2.2
                    [rows] => 50
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 1
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [id] => SOLR1000
                            [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)
                                )

                        )

                )

        )

)

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

Descrierea

public SolrUpdateResponse SolrClient::request ( string $raw_request )

Sends a raw XML update request to the server

Parametri

raw_request

An XML string with the raw request to the server.

Valorile întoarse

Returns a SolrUpdateResponse on success. Throws an exception on failure.

Erori/Excep?ii

Throws SolrIllegalArgumentException if raw_request was an empty string

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to satisfy the query.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

...

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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a SolrUpdateResponse on success or throws a SolrClientException on failure.

A se vedea ?i

  • 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

Descrierea

public void SolrClient::setResponseWriter ( string $responseWriter )

Sets the response writer used to prepare the response from Solr

Parametri

responseWriter

One of the following:

  • json
  • phps
  • xml

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);

$client->setResponseWriter("json");

//$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);

}

?>

SolrClient::rollback
SolrClient::setServlet
SolrClient


Changes the specified servlet type to a new value

SolrClient::setResponseWriter
SolrClient::system
SolrClient
PHP Manual

SolrClient::setServlet

(PECL solr >= 0.9.2)

SolrClient::setServlet — Changes the specified servlet type to a new value

Descrierea

public bool SolrClient::setServlet ( int $type , string $value )

Changes the specified servlet type to a new value

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

SolrClient::setResponseWriter
SolrClient::system
SolrClient


Retrieve Solr Server information

SolrClient::setServlet
SolrClient::threads
SolrClient
PHP Manual

SolrClient::system

(PECL solr >= 2.0.0)

SolrClient::system — Retrieve Solr Server information

Descrierea

public void SolrClient::system ( void )

Retrieve Solr Server information

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a SolrGenericResponse object on success.

Erori/Excep?ii

Emits SolrClientException if the client failed, or there was a connection issue.

Emits SolrServerException if the Solr Server failed to satisfy the query.

SolrClient::setServlet
SolrClient::threads
SolrClient


Checks the threads status

SolrClient::system
SolrResponse
SolrClient
PHP Manual

SolrClient::threads

(PECL solr >= 0.9.2)

SolrClient::threads — Checks the threads status

Descrierea

public void SolrClient::threads ( void )

Checks the threads status

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a SolrGenericResponse object.

Erori/Excep?ii

Throws SolrClientException if the client failed, or there was a connection issue.

throws SolrServerException if the Solr Server failed to process the request.

SolrClient::system
SolrResponse
SolrClient


The SolrResponse class

(PECL solr >= 0.9.2)

Introducere

Represents a response from the Solr server.

Sinopsisul clasei

abstract SolrResponse {
/* Constante */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Proprieta?i */
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 ;
/* Metode */
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 )
}

Proprieta?i

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.

Constante predefinite

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.

Cuprins

  • 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

Descrierea

public string SolrResponse::getDigestedResponse ( void )

Returns the XML response as serialized PHP data

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrResponse::getHttpStatus ( void )

Returns the HTTP status of the response.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrResponse::getHttpStatusMessage ( void )

Returns more details on the HTTP status.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrResponse::getRawRequest ( void )

Returns the raw request sent to the Solr server.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrResponse::getRawRequestHeaders ( void )

Returns the raw request headers sent to the Solr server.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrResponse::getRawResponse ( void )

Returns the raw response from the server.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrResponse::getRawResponseHeaders ( void )

Returns the raw response headers from the server.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrResponse::getRequestUrl ( void )

Returns the full URL the request was sent to.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public SolrObject SolrResponse::getResponse ( void )

Returns a SolrObject representing the XML response from the server.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrResponse::setParseMode ([ int $parser_mode = 0 ] )

Sets the parse mode.

Parametri

parser_mode

SolrResponse::PARSE_SOLR_DOC parses documents in SolrDocument instances. SolrResponse::PARSE_SOLR_OBJ parses document into SolrObjects.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public bool SolrResponse::success ( void )

Used to check if the request to the server was successful.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if it was successful and FALSE if it was not.

SolrResponse::setParseMode
SolrQueryResponse
SolrResponse


The SolrQueryResponse class

(PECL solr >= 0.9.2)

Introducere

Represents a response to a query request.

Sinopsisul clasei

final SolrQueryResponse extends SolrResponse {
/* Constante */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Proprieta?i mo?tenite */
const integer SolrResponse::PARSE_SOLR_OBJ = 0 ;
const integer SolrResponse::PARSE_SOLR_DOC = 1 ;
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 ;
/* Metode */
public __construct ( void )
public void __destruct ( void )
/* Metode mo?tenite */
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 )
}

Constante predefinite

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.

Cuprins

  • 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

Descrierea

public SolrQueryResponse::__construct ( void )

Constructor

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None

SolrQueryResponse
SolrQueryResponse::__destruct
SolrQueryResponse


Destructor

SolrQueryResponse::__construct
SolrUpdateResponse
SolrQueryResponse
PHP Manual

SolrQueryResponse::__destruct

(PECL solr >= 0.9.2)

SolrQueryResponse::__destruct — Destructor

Descrierea

public void SolrQueryResponse::__destruct ( void )

Destructor.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None

SolrQueryResponse::__construct
SolrUpdateResponse
SolrQueryResponse


The SolrUpdateResponse class

(PECL solr >= 0.9.2)

Introducere

Represents a response to an update request.

Sinopsisul clasei

final SolrUpdateResponse extends SolrResponse {
/* Constante */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Proprieta?i mo?tenite */
const integer SolrResponse::PARSE_SOLR_OBJ = 0 ;
const integer SolrResponse::PARSE_SOLR_DOC = 1 ;
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 ;
/* Metode */
public __construct ( void )
public void __destruct ( void )
/* Metode mo?tenite */
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 )
}

Constante predefinite

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.

Cuprins

  • 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

Descrierea

public SolrUpdateResponse::__construct ( void )

Constructor

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None

SolrUpdateResponse
SolrUpdateResponse::__destruct
SolrUpdateResponse


Destructor

SolrUpdateResponse::__construct
SolrPingResponse
SolrUpdateResponse
PHP Manual

SolrUpdateResponse::__destruct

(PECL solr >= 0.9.2)

SolrUpdateResponse::__destruct — Destructor

Descrierea

public void SolrUpdateResponse::__destruct ( void )

Destructor

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None

SolrUpdateResponse::__construct
SolrPingResponse
SolrUpdateResponse


The SolrPingResponse class

(PECL solr >= 0.9.2)

Introducere

Represents a response to a ping request to the server

Sinopsisul clasei

final SolrPingResponse extends SolrResponse {
/* Constante */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Proprieta?i */
/* Metode */
public __construct ( void )
public void __destruct ( void )
public string getResponse ( void )
/* Metode mo?tenite */
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 )
}

Proprieta?i

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.

Constante predefinite

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.

Cuprins

  • 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

Descrierea

public SolrPingResponse::__construct ( void )

Constructor

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None

SolrPingResponse
SolrPingResponse::__destruct
SolrPingResponse


Destructor

SolrPingResponse::__construct
SolrPingResponse::getResponse
SolrPingResponse
PHP Manual

SolrPingResponse::__destruct

(PECL solr >= 0.9.2)

SolrPingResponse::__destruct — Destructor

Descrierea

public void SolrPingResponse::__destruct ( void )

Destructor

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrPingResponse::getResponse ( void )

Returns the response from the server. This should be empty because the request as a HEAD request.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an empty string.

SolrPingResponse::__destruct
SolrGenericResponse
SolrPingResponse


The SolrGenericResponse class

(PECL solr >= 0.9.2)

Introducere

Represents a response from the solr server.

Sinopsisul clasei

final SolrGenericResponse extends SolrResponse {
/* Constante */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Proprieta?i mo?tenite */
const integer SolrResponse::PARSE_SOLR_OBJ = 0 ;
const integer SolrResponse::PARSE_SOLR_DOC = 1 ;
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 ;
/* Metode */
public __construct ( void )
public void __destruct ( void )
/* Metode mo?tenite */
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 )
}

Constante predefinite

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.

Cuprins

  • 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

Descrierea

public SolrGenericResponse::__construct ( void )

Constructor

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None

SolrGenericResponse
SolrGenericResponse::__destruct
SolrGenericResponse


Destructor

SolrGenericResponse::__construct
SolrParams
SolrGenericResponse
PHP Manual

SolrGenericResponse::__destruct

(PECL solr >= 0.9.2)

SolrGenericResponse::__destruct — Destructor

Descrierea

public void SolrGenericResponse::__destruct ( void )

Destructor.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None

SolrGenericResponse::__construct
SolrParams
SolrGenericResponse


The SolrParams class

(PECL solr >= 0.9.2)

Introducere

Represents a collection of name-value pairs sent to the Solr server during a request.

Sinopsisul clasei

abstract SolrParams implements Serializable {
/* Metode */
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 )
}

Cuprins

  • 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

Descrierea

final public SolrParams SolrParams::add ( string $name , string $value )

This is an alias for SolrParams::addParam

Parametri

name

The name of the parameter

value

The value of the parameter

Valorile întoarse

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

Descrierea

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.

Parametri

name

Name of parameter

value

Value of parameter

Valorile întoarse

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

Descrierea

final public mixed SolrParams::get ( string $param_name )

This is an alias for SolrParams::getParam

Parametri

param_name

Then name of the parameter

Valorile întoarse

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

Descrierea

final public mixed SolrParams::getParam ([ string $param_name ] )

Returns a parameter with name param_name

Parametri

param_name

The name of the parameter

Valorile întoarse

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

Descrierea

final public array SolrParams::getParams ( void )

Returns an array of non URL-encoded parameters

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

final public array SolrParams::getPreparedParams ( void )

Returns an array on URL-encoded parameters

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

final public string SolrParams::serialize ( void )

Used for custom serialization

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

final public void SolrParams::set ( string $name , string $value )

An alias of SolrParams::setParam

Parametri

name

Then name of the parameter

value

The parameter value

Valorile întoarse

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

Descrierea

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

Parametri

name

Name of the parameter

value

Value of the parameter

Valorile întoarse

Returns a SolrParam object on success and FALSE on value.

Exemple

Example #1 SolrParams::setParam() example

<?php

$param = new SolrParams();

$param->setParam('q', 'solr')->setParam('rows', 2);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

final public string SolrParams::toString ([ bool $url_encode = false ] )

Returns all the name-value pair parameters in the object

Parametri

url_encode

Whether to return URL-encoded values

Valorile întoarse

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

Descrierea

final public void SolrParams::unserialize ( string $serialized )

Used for custom serialization

Parametri

serialized

The serialized representation of the object

Valorile întoarse

None

SolrParams::toString
SolrModifiableParams
SolrParams


The SolrModifiableParams class

(PECL solr >= 0.9.2)

Introducere

Represents a collection of name-value pairs sent to the Solr server during a request.

Sinopsisul clasei

SolrModifiableParams extends SolrParams implements Serializable {
/* Metode */
public __construct ( void )
public void __destruct ( void )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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

Descrierea

public SolrModifiableParams::__construct ( void )

Constructor

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None

SolrModifiableParams
SolrModifiableParams::__destruct
SolrModifiableParams


Destructor

SolrModifiableParams::__construct
SolrQuery
SolrModifiableParams
PHP Manual

SolrModifiableParams::__destruct

(PECL solr >= 0.9.2)

SolrModifiableParams::__destruct — Destructor

Descrierea

public void SolrModifiableParams::__destruct ( void )

Destructor

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None

SolrModifiableParams::__construct
SolrQuery
SolrModifiableParams


The SolrQuery class

(PECL solr >= 0.9.2)

Introducere

Represents a collection of name-value pairs sent to the Solr server during a request.

Sinopsisul clasei

SolrQuery extends SolrModifiableParams implements Serializable {
/* Constante */
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 ;
/* Proprieta?i */
/* Metode */
public SolrQuery addExpandFilterQuery ( string $fq )
public SolrQuery addExpandSortField ( string $field [, string $order ] )
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 addGroupField ( string $value )
public SolrQuery addGroupFunction ( string $value )
public SolrQuery addGroupQuery ( string $value )
public SolrQuery addGroupSortField ( string $field [, integer $order ] )
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 SolrQuery collapse ( SolrCollapseFunction $collapseFunction )
public __construct ([ string $q ] )
public void __destruct ( void )
public bool getExpand ( void )
public array getExpandFilterQueries ( void )
public array getExpandQuery ( void )
public integer getExpandRows ( void )
public array getExpandSortFields ( 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 getGroup ( void )
public integer getGroupCachePercent ( void )
public bool getGroupFacet ( void )
public array getGroupFields ( void )
public string getGroupFormat ( void )
public array getGroupFunctions ( void )
public integer getGroupLimit ( void )
public bool getGroupMain ( void )
public bool getGroupNGroups ( void )
public integer getGroupOffset ( void )
public array getGroupQueries ( void )
public array getGroupSortFields ( void )
public bool getGroupTruncate ( 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 removeExpandFilterQuery ( string $fq )
public SolrQuery removeExpandSortField ( string $field )
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 setExpand ( bool $value )
public SolrQuery setExpandQuery ( string $q )
public SolrQuery setExpandRows ( integer $value )
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 setGroup ( bool $value )
public SolrQuery setGroupCachePercent ( integer $percent )
public SolrQuery setGroupFacet ( bool $value )
public SolrQuery setGroupFormat ( string $value )
public SolrQuery setGroupLimit ( integer $value )
public SolrQuery setGroupMain ( string $value )
public SolrQuery setGroupNGroups ( bool $value )
public SolrQuery setGroupOffset ( integer $value )
public SolrQuery setGroupTruncate ( bool $value )
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 )
/* Metode mo?tenite */
public SolrModifiableParams::__construct ( void )
public void SolrModifiableParams::__destruct ( void )
}

Constante predefinite

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

Cuprins

  • SolrQuery::addExpandFilterQuery — Overrides main filter query, determines which documents to include in the main group.
  • SolrQuery::addExpandSortField — Orders the documents within the expanded groups (expand.sort parameter).
  • 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::addGroupField — Add a field to be used to group results.
  • SolrQuery::addGroupFunction — Allows grouping results based on the unique values of a function query (group.func parameter).
  • SolrQuery::addGroupQuery — Allows grouping of documents that match the given query.
  • SolrQuery::addGroupSortField — Add a group sort field (group.sort parameter).
  • 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::collapse — Collapses the result set to a single document per group
  • SolrQuery::__construct — Constructor
  • SolrQuery::__destruct — Destructor
  • SolrQuery::getExpand — Returns true if group expanding is enabled
  • SolrQuery::getExpandFilterQueries — Returns the expand filter queries
  • SolrQuery::getExpandQuery — Returns the expand query expand.q parameter
  • SolrQuery::getExpandRows — Returns The number of rows to display in each group (expand.rows)
  • SolrQuery::getExpandSortFields — Returns an array of fields
  • 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::getGroup — Returns true if grouping is enabled
  • SolrQuery::getGroupCachePercent — Returns group cache percent value
  • SolrQuery::getGroupFacet — Returns the group.facet parameter value
  • SolrQuery::getGroupFields — Returns group fields (group.field parameter values)
  • SolrQuery::getGroupFormat — Returns the group.format value
  • SolrQuery::getGroupFunctions — Returns group functions (group.func parameter values)
  • SolrQuery::getGroupLimit — Returns the group.limit value
  • SolrQuery::getGroupMain — Returns the group.main value
  • SolrQuery::getGroupNGroups — Returns the group.ngroups value
  • SolrQuery::getGroupOffset — Returns the group.offset value
  • SolrQuery::getGroupQueries — Returns all the group.query parameter values
  • SolrQuery::getGroupSortFields — Returns the group.sort value
  • SolrQuery::getGroupTruncate — Returns the group.truncate value
  • 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::removeExpandFilterQuery — Removes an expand filter query
  • SolrQuery::removeExpandSortField — Removes an expand sort field from the expand.sort parameter.
  • 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::setExpand — Enables/Disables the Expand Component
  • SolrQuery::setExpandQuery — Sets the expand.q parameter
  • SolrQuery::setExpandRows — Sets the number of rows to display in each group (expand.rows). Server Default 5
  • 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::setGroup — Enable/Disable result grouping (group parameter)
  • SolrQuery::setGroupCachePercent — Enables caching for result grouping
  • SolrQuery::setGroupFacet — Sets group.facet parameter
  • SolrQuery::setGroupFormat — Sets the group format, result structure (group.format parameter).
  • SolrQuery::setGroupLimit — Specifies the number of results to return for each group. The server default value is 1.
  • SolrQuery::setGroupMain — If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
  • SolrQuery::setGroupNGroups — If true, Solr includes the number of groups that have matched the query in the results.
  • SolrQuery::setGroupOffset — Sets the group.offset parameter.
  • SolrQuery::setGroupTruncate — If true, facet counts are based on the most relevant document of each group matching the query.
  • 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::addExpandFilterQuery
Solr


Overrides main filter query, determines which documents to include in the main group.

SolrQuery
SolrQuery::addExpandSortField
SolrQuery
PHP Manual

SolrQuery::addExpandFilterQuery

(PECL solr >= 2.2.0)

SolrQuery::addExpandFilterQuery — Overrides main filter query, determines which documents to include in the main group.

Descrierea

public SolrQuery SolrQuery::addExpandFilterQuery ( string $fq )

Overrides main filter query, determines which documents to include in the main group.

Parametri

fq

Valorile întoarse

SolrQuery

A se vedea ?i

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter).
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter.
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query
SolrQuery
SolrQuery::addExpandSortField
SolrQuery


Orders the documents within the expanded groups (expand.sort parameter).

SolrQuery::addExpandFilterQuery
SolrQuery::addFacetDateField
SolrQuery
PHP Manual

SolrQuery::addExpandSortField

(PECL solr >= 2.2.0)

SolrQuery::addExpandSortField — Orders the documents within the expanded groups (expand.sort parameter).

Descrierea

public SolrQuery SolrQuery::addExpandSortField ( string $field [, string $order ] )

Orders the documents within the expanded groups (expand.sort parameter).

Parametri

field

field name

order

Order ASC/DESC, utilizes SolrQuery::ORDER_* constants.

Default: SolrQuery::ORDER_DESC

Valorile întoarse

SolrQuery

A se vedea ?i

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter.
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group.
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query
SolrQuery::addExpandFilterQuery
SolrQuery::addFacetDateField
SolrQuery


Maps to facet.date

SolrQuery::addExpandSortField
SolrQuery::addFacetDateOther
SolrQuery
PHP Manual

SolrQuery::addFacetDateField

(PECL solr >= 0.9.2)

SolrQuery::addFacetDateField — Maps to facet.date

Descrierea

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

Parametri

dateField

The name of the date field.

Valorile întoarse

Returns a SolrQuery object.

SolrQuery::addExpandSortField
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

Descrierea

public SolrQuery SolrQuery::addFacetDateOther ( string $value [, string $field_override ] )

Sets the facet.date.other parameter. Accepts an optional field override

Parametri

value

The value to use.

field_override

The field name for the override.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::addFacetField ( string $field )

Adds another field to the facet

Parametri

field

The name of the field

Valorile întoarse

Returns the current SolrQuery object, if the return value is used.

Exemple

Example #1 SolrQuery::addFacetField() example

<?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($query);

$query->addField('price')->addField('color');

$query->setFacet(true);

$query->addFacetField('price')->addFacetField('color');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response['facet_counts']['facet_fields']);

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [color] => SolrObject Object
        (
            [blue] => 20
            [green] => 100
        )

)

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

Descrierea

public SolrQuery SolrQuery::addFacetQuery ( string $facetQuery )

Adds a facet query

Parametri

facetQuery

The facet query

Valorile întoarse

Returns the current SolrQuery object, if the return value is used.

Exemple

Example #1 SolrQuery::addFacetField() example

<?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->addFacetQuery('price:[* TO 500]')->addFacetQuery('price:[500 TO *]');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response->facet_counts->facet_queries);

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [price:[* TO 500]] => 14
    [price:[500 TO *]] => 2
)

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

Descrierea

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.

Parametri

field

The name of the field

Valorile întoarse

Returns the current SolrQuery object

SolrQuery::addFacetQuery
SolrQuery::addFilterQuery
SolrQuery


Specifies a filter query

SolrQuery::addField
SolrQuery::addGroupField
SolrQuery
PHP Manual

SolrQuery::addFilterQuery

(PECL solr >= 0.9.2)

SolrQuery::addFilterQuery — Specifies a filter query

Descrierea

public SolrQuery SolrQuery::addFilterQuery ( string $fq )

Specifies a filter query

Parametri

fq

The filter query

Valorile întoarse

Returns the current SolrQuery object.

Exemple

Example #1 SolrQuery::addFilterQuery() example

<?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('*:*');

$query->addFilterQuery('color:blue,green');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response['facet_counts']['facet_fields']);

?>

Exemplul de mai sus va afi?a ceva similar cu:

 &fq=color:blue,green

SolrQuery::addField
SolrQuery::addGroupField
SolrQuery


Add a field to be used to group results.

SolrQuery::addFilterQuery
SolrQuery::addGroupFunction
SolrQuery
PHP Manual

SolrQuery::addGroupField

(PECL solr >= 2.2.0)

SolrQuery::addGroupField — Add a field to be used to group results.

Descrierea

public SolrQuery SolrQuery::addGroupField ( string $value )

The name of the field by which to group results. The field must be single-valued, and either be indexed or a field type that has a value source and works in a function query, such as ExternalFileField. It must also be a string-based field, such as StrField or TextField Uses group.field parameter

Parametri

value

A se vedea ?i

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter).
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query.
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter).
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter.
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1.
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results.
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query.
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter).
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping
SolrQuery::addFilterQuery
SolrQuery::addGroupFunction
SolrQuery


Allows grouping results based on the unique values of a function query (group.func parameter).

SolrQuery::addGroupField
SolrQuery::addGroupQuery
SolrQuery
PHP Manual

SolrQuery::addGroupFunction

(PECL solr >= 2.2.0)

SolrQuery::addGroupFunction — Allows grouping results based on the unique values of a function query (group.func parameter).

Descrierea

public SolrQuery SolrQuery::addGroupFunction ( string $value )

Adds a group function (group.func parameter) Allows grouping results based on the unique values of a function query.

Parametri

value

Valorile întoarse

SolrQuery

A se vedea ?i

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results.
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query.
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter).
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter.
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1.
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results.
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query.
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter).
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping
SolrQuery::addGroupField
SolrQuery::addGroupQuery
SolrQuery


Allows grouping of documents that match the given query.

SolrQuery::addGroupFunction
SolrQuery::addGroupSortField
SolrQuery
PHP Manual

SolrQuery::addGroupQuery

(PECL solr >= 2.2.0)

SolrQuery::addGroupQuery — Allows grouping of documents that match the given query.

Descrierea

public SolrQuery SolrQuery::addGroupQuery ( string $value )

Allows grouping of documents that match the given query. Adds query to the group.query parameter

Parametri

value

Valorile întoarse

SolrQuery

A se vedea ?i

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results.
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter).
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter).
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter.
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1.
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results.
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query.
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter).
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping
SolrQuery::addGroupFunction
SolrQuery::addGroupSortField
SolrQuery


Add a group sort field (group.sort parameter).

SolrQuery::addGroupQuery
SolrQuery::addHighlightField
SolrQuery
PHP Manual

SolrQuery::addGroupSortField

(PECL solr >= 2.2.0)

SolrQuery::addGroupSortField — Add a group sort field (group.sort parameter).

Descrierea

public SolrQuery SolrQuery::addGroupSortField ( string $field [, integer $order ] )

Allow sorting group documents, using group sort field (group.sort parameter).

Parametri

field

Field name

order

Order ASC/DESC, utilizes SolrQuery::ORDER_* constants

Valorile întoarse

Exemple

Example #1 SolrQuery::addGroupSortField() example

<?php

$solrQuery = new SolrQuery('*:*');
$solrQuery
    ->setGroup(true)
    ->addGroupSortField('price', SolrQuery::ORDER_ASC);

echo $solrQuery;
?>

Exemplul de mai sus va afi?a ceva similar cu:

q=*:*&group=true&group.sort=price asc

A se vedea ?i

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results.
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter).
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query.
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter.
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1.
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results.
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query.
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter).
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping
SolrQuery::addGroupQuery
SolrQuery::addHighlightField
SolrQuery


Maps to hl.fl

SolrQuery::addGroupSortField
SolrQuery::addMltField
SolrQuery
PHP Manual

SolrQuery::addHighlightField

(PECL solr >= 0.9.2)

SolrQuery::addHighlightField — Maps to hl.fl

Descrierea

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

Parametri

field

Name of the field

Valorile întoarse

Returns the current SolrQuery object, if the return value is used.

SolrQuery::addGroupSortField
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

Descrierea

public SolrQuery SolrQuery::addMltField ( string $field )

Maps to mlt.fl. It specifies that a field should be used for similarity.

Parametri

field

The name of the field

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::addMltQueryField ( string $field , float $boost )

Maps to mlt.qf. It is used to specify query fields and their boosts

Parametri

field

The name of the field

boost

Its boost value

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::addSortField ( string $field [, int $order = SolrQuery::ORDER_DESC ] )

Used to control how the results should be sorted.

Parametri

field

The name of the field

order

The sort direction. This should be either SolrQuery::ORDER_ASC or SolrQuery::ORDER_DESC.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::addStatsFacet ( string $field )

Requests a return of sub results for values within the given facet. Maps to the stats.facet field

Parametri

field

The name of the field

Valorile întoarse

Returns the current SolrQuery object, if the return value is used.

SolrQuery::addSortField
SolrQuery::addStatsField
SolrQuery


Maps to stats.field parameter

SolrQuery::addStatsFacet
SolrQuery::collapse
SolrQuery
PHP Manual

SolrQuery::addStatsField

(PECL solr >= 0.9.2)

SolrQuery::addStatsField — Maps to stats.field parameter

Descrierea

public SolrQuery SolrQuery::addStatsField ( string $field )

Maps to stats.field parameter This methods adds another stats.field parameter.

Parametri

field

The name of the field

Valorile întoarse

Returns the current SolrQuery object, if the return value is used.

SolrQuery::addStatsFacet
SolrQuery::collapse
SolrQuery


Collapses the result set to a single document per group

SolrQuery::addStatsField
SolrQuery::__construct
SolrQuery
PHP Manual

SolrQuery::collapse

(No version information available, might only be in Git)

SolrQuery::collapse — Collapses the result set to a single document per group

Descrierea

public SolrQuery SolrQuery::collapse ( SolrCollapseFunction $collapseFunction )

Collapses the result set to a single document per group before it forwards the result set to the rest of the search components.

So all downstream components (faceting, highlighting, etc...) will work with the collapsed result set.

Parametri

collapseFunction

Valorile întoarse

Returns the current SolrQuery object

Exemple

Example #1 SolrQuery::collapse() example

<?php

include "bootstrap.php";

$options = array
(
        'hostname' => SOLR_SERVER_HOSTNAME,
        'login'    => SOLR_SERVER_USERNAME,
        'password' => SOLR_SERVER_PASSWORD,
        'port'     => SOLR_SERVER_PORT,
        'path'     => SOLR_SERVER_PATH
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$collapseFunction = new SolrCollapseFunction('manu_id_s');

$collapseFunction
->setSize(2)
->setNullPolicy(SolrCollapseFunction::NULLPOLICY_IGNORE);

$query
->collapse($collapseFunction)
->setRows(4);

$queryResponse = $client->query($query);

$response = $queryResponse->getResponse();

print_r($response);

?>

Exemplul de mai sus va afi?a ceva similar cu:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [q] => *:*
                    [indent] => on
                    [fq] => {!collapse field=manu_id_s size=2 nullPolicy=ignore}
                    [rows] => 4
                    [version] => 2.2
                    [wt] => xml
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 14
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [id] => SP2514N
                            [name] => Array
                                (
                                    [0] => Samsung SpinPoint P120 SP2514N - hard drive - 250 GB - ATA-133
                                )

                            [manu] => Array
                                (
                                    [0] => Samsung Electronics Co. Ltd.
                                )

                            [manu_id_s] => samsung
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => 7200RPM, 8MB cache, IDE Ultra ATA-133
                                    [1] => NoiseGuard, SilentSeek technology, Fluid Dynamic Bearing (FDB) motor
                                )

                            [price] => Array
                                (
                                    [0] => 92
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [store] => Array
                                (
                                    [0] => 35.0752,-97.032
                                )

                            [_version_] => 1510294336412057600
                        )

                    [1] => SolrObject Object
                        (
                            [id] => 6H500F0
                            [name] => Array
                                (
                                    [0] => Maxtor DiamondMax 11 - hard drive - 500 GB - SATA-300
                                )

                            [manu] => Array
                                (
                                    [0] => Maxtor Corp.
                                )

                            [manu_id_s] => maxtor
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => SATA 3.0Gb/s, NCQ
                                    [1] => 8.5ms seek
                                    [2] => 16MB cache
                                )

                            [price] => Array
                                (
                                    [0] => 350
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 45.17614,-93.87341
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [_version_] => 1510294336449806336
                        )

                    [2] => SolrObject Object
                        (
                            [id] => F8V7067-APL-KIT
                            [name] => Array
                                (
                                    [0] => Belkin Mobile Power Cord for iPod w/ Dock
                                )

                            [manu] => Array
                                (
                                    [0] => Belkin
                                )

                            [manu_id_s] => belkin
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => connector
                                )

                            [features] => Array
                                (
                                    [0] => car power adapter, white
                                )

                            [weight] => Array
                                (
                                    [0] => 4
                                )

                            [price] => Array
                                (
                                    [0] => 19.95
                                )

                            [popularity] => Array
                                (
                                    [0] => 1
                                )

                            [inStock] => Array
                                (
                                    [0] =>
                                )

                            [store] => Array
                                (
                                    [0] => 45.18014,-93.87741
                                )

                            [manufacturedate_dt] => 2005-08-01T16:30:25Z
                            [_version_] => 1510294336458194944
                        )

                    [3] => SolrObject Object
                        (
                            [id] => MA147LL/A
                            [name] => Array
                                (
                                    [0] => Apple 60 GB iPod with Video Playback Black
                                )

                            [manu] => Array
                                (
                                    [0] => Apple Computer Inc.
                                )

                            [manu_id_s] => apple
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => music
                                )

                            [features] => Array
                                (
                                    [0] => iTunes, Podcasts, Audiobooks
                                    [1] => Stores up to 15,000 songs, 25,000 photos, or 150 hours of video
                                    [2] => 2.5-inch, 320x240 color TFT LCD display with LED backlight
                                    [3] => Up to 20 hours of battery life
                                    [4] => Plays AAC, MP3, WAV, AIFF, Audible, Apple Lossless, H.264 video
                                    [5] => Notes, Calendar, Phone book, Hold button, Date display, Photo wallet, Built-in games, JPEG photo playback, Upgradeable firmware, USB 2.0 compatibility, Playback speed control, Rechargeable capability, Battery level indication
                                )

                            [includes] => Array
                                (
                                    [0] => earbud headphones, USB cable
                                )

                            [weight] => Array
                                (
                                    [0] => 5.5
                                )

                            [price] => Array
                                (
                                    [0] => 399
                                )

                            [popularity] => Array
                                (
                                    [0] => 10
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 37.7752,-100.0232
                                )

                            [manufacturedate_dt] => 2005-10-12T08:00:00Z
                            [_version_] => 1510294336562003968
                        )

                )

        )

)
SolrQuery::addStatsField
SolrQuery::__construct
SolrQuery


Constructor

SolrQuery::collapse
SolrQuery::__destruct
SolrQuery
PHP Manual

SolrQuery::__construct

(PECL solr >= 0.9.2)

SolrQuery::__construct — Constructor

Descrierea

public SolrQuery::__construct ([ string $q ] )

Constructor.

Parametri

q

Optional search query

Valorile întoarse

None

Erori/Excep?ii

Emits SolrIllegalArgumentException in case of an invalid parameter was passed.

Istoricul schimbarilor

Versiune | Descriere
2.0.0 | If q was invalid, then a SolrIllegalArgumentException is now thrown. Previously an error was emitted.

SolrQuery::collapse
SolrQuery::__destruct
SolrQuery


Destructor

SolrQuery::__construct
SolrQuery::getExpand
SolrQuery
PHP Manual

SolrQuery::__destruct

(PECL solr >= 0.9.2)

SolrQuery::__destruct — Destructor

Descrierea

public void SolrQuery::__destruct ( void )

Destructor

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

None.

SolrQuery::__construct
SolrQuery::getExpand
SolrQuery


Returns true if group expanding is enabled

SolrQuery::__destruct
SolrQuery::getExpandFilterQueries
SolrQuery
PHP Manual

SolrQuery::getExpand

(PECL solr >= 2.2.0)

SolrQuery::getExpand — Returns true if group expanding is enabled

Descrierea

public bool SolrQuery::getExpand ( void )

Returns TRUE if group expanding is enabled

SolrQuery::__destruct
SolrQuery::getExpandFilterQueries
SolrQuery


Returns the expand filter queries

SolrQuery::getExpand
SolrQuery::getExpandQuery
SolrQuery
PHP Manual

SolrQuery::getExpandFilterQueries

(PECL solr >= 2.2.0)

SolrQuery::getExpandFilterQueries — Returns the expand filter queries

Descrierea

public array SolrQuery::getExpandFilterQueries ( void )

Returns the expand filter queries

SolrQuery::getExpand
SolrQuery::getExpandQuery
SolrQuery


Returns the expand query expand.q parameter

SolrQuery::getExpandFilterQueries
SolrQuery::getExpandRows
SolrQuery
PHP Manual

SolrQuery::getExpandQuery

(PECL solr >= 2.2.0)

SolrQuery::getExpandQuery — Returns the expand query expand.q parameter

Descrierea

public array SolrQuery::getExpandQuery ( void )

Returns the expand query expand.q parameter

SolrQuery::getExpandFilterQueries
SolrQuery::getExpandRows
SolrQuery


Returns The number of rows to display in each group (expand.rows)

SolrQuery::getExpandQuery
SolrQuery::getExpandSortFields
SolrQuery
PHP Manual

SolrQuery::getExpandRows

(PECL solr >= 2.2.0)

SolrQuery::getExpandRows — Returns The number of rows to display in each group (expand.rows)

Descrierea

public integer SolrQuery::getExpandRows ( void )

Returns The number of rows to display in each group (expand.rows)

SolrQuery::getExpandQuery
SolrQuery::getExpandSortFields
SolrQuery


Returns an array of fields

SolrQuery::getExpandRows
SolrQuery::getFacet
SolrQuery
PHP Manual

SolrQuery::getExpandSortFields

(PECL solr >= 2.2.0)

SolrQuery::getExpandSortFields — Returns an array of fields

Descrierea

public array SolrQuery::getExpandSortFields ( void )

Returns an array of fields

SolrQuery::getExpandRows
SolrQuery::getFacet
SolrQuery


Returns the value of the facet parameter

SolrQuery::getExpandSortFields
SolrQuery::getFacetDateEnd
SolrQuery
PHP Manual

SolrQuery::getFacet

(PECL solr >= 0.9.2)

SolrQuery::getFacet — Returns the value of the facet parameter

Descrierea

public bool SolrQuery::getFacet ( void )

Returns the value of the facet parameter.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a boolean on success and NULL if not set

SolrQuery::getExpandSortFields
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

Descrierea

public string SolrQuery::getFacetDateEnd ([ string $field_override ] )

Returns the value for the facet.date.end parameter. This method accepts an optional field override

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public array SolrQuery::getFacetDateFields ( void )

Returns all the facet.date fields

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrQuery::getFacetDateGap ([ string $field_override ] )

Returns the value of the facet.date.gap parameter. It accepts an optional field override

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public string SolrQuery::getFacetDateHardEnd ([ string $field_override ] )

Returns the value of the facet.date.hardend parameter. Accepts an optional field override

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public array SolrQuery::getFacetDateOther ([ string $field_override ] )

Returns the value for the facet.date.other parameter. This method accepts an optional field override.

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

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

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public array SolrQuery::getFacetFields ( void )

Returns all the facet fields

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

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

Parametri

field_override

The name of the field to override for

Valorile întoarse

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

Descrierea

public string SolrQuery::getFacetMethod ([ string $field_override ] )

Returns the value of the facet.method parameter. This accepts an optional field override.

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

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

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public bool SolrQuery::getFacetMissing ([ string $field_override ] )

Returns the current state of the facet.missing parameter. This accepts an optional field override

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

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

Parametri

field_override

The name of the field to override for.

Valorile întoarse

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

Descrierea

public string SolrQuery::getFacetPrefix ([ string $field_override ] )

Returns the facet prefix

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public array SolrQuery::getFacetQueries ( void )

Returns all the facet queries

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrQuery::getFacetSort ([ string $field_override ] )

Returns an integer (SolrQuery::FACET_SORT_INDEX or SolrQuery::FACET_SORT_COUNT)

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public array SolrQuery::getFields ( void )

Returns the list of fields that will be returned in the response

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array on success and NULL if not set.

SolrQuery::getFacetSort
SolrQuery::getFilterQueries
SolrQuery


Returns an array of filter queries

SolrQuery::getFields
SolrQuery::getGroup
SolrQuery
PHP Manual

SolrQuery::getFilterQueries

(PECL solr >= 0.9.2)

SolrQuery::getFilterQueries — Returns an array of filter queries

Descrierea

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

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array on success and NULL if not set.

SolrQuery::getFields
SolrQuery::getGroup
SolrQuery


Returns true if grouping is enabled

SolrQuery::getFilterQueries
SolrQuery::getGroupCachePercent
SolrQuery
PHP Manual

SolrQuery::getGroup

(PECL solr >= 2.2.0)

SolrQuery::getGroup — Returns true if grouping is enabled

Descrierea

public bool SolrQuery::getGroup ( void )

Returns true if grouping is enabled

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
SolrQuery::getFilterQueries
SolrQuery::getGroupCachePercent
SolrQuery


Returns group cache percent value

SolrQuery::getGroup
SolrQuery::getGroupFacet
SolrQuery
PHP Manual

SolrQuery::getGroupCachePercent

(PECL solr >= 2.2.0)

SolrQuery::getGroupCachePercent — Returns group cache percent value

Descrierea

public integer SolrQuery::getGroupCachePercent ( void )

Returns group cache percent value

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping
SolrQuery::getGroup
SolrQuery::getGroupFacet
SolrQuery


Returns the group.facet parameter value

SolrQuery::getGroupCachePercent
SolrQuery::getGroupFields
SolrQuery
PHP Manual

SolrQuery::getGroupFacet

(PECL solr >= 2.2.0)

SolrQuery::getGroupFacet — Returns the group.facet parameter value

Descrierea

public bool SolrQuery::getGroupFacet ( void )

Returns the group.facet parameter value

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroupFacet() - Sets group.facet parameter
SolrQuery::getGroupCachePercent
SolrQuery::getGroupFields
SolrQuery


Returns group fields (group.field parameter values)

SolrQuery::getGroupFacet
SolrQuery::getGroupFormat
SolrQuery
PHP Manual

SolrQuery::getGroupFields

(PECL solr >= 2.2.0)

SolrQuery::getGroupFields — Returns group fields (group.field parameter values)

Descrierea

public array SolrQuery::getGroupFields ( void )

Returns group fields (group.field parameter values)

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrQuery::addGroupField() - Add a field to be used to group results.
SolrQuery::getGroupFacet
SolrQuery::getGroupFormat
SolrQuery


Returns the group.format value

SolrQuery::getGroupFields
SolrQuery::getGroupFunctions
SolrQuery
PHP Manual

SolrQuery::getGroupFormat

(PECL solr >= 2.2.0)

SolrQuery::getGroupFormat — Returns the group.format value

Descrierea

public string SolrQuery::getGroupFormat ( void )

Returns the group.format value

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter).
SolrQuery::getGroupFields
SolrQuery::getGroupFunctions
SolrQuery


Returns group functions (group.func parameter values)

SolrQuery::getGroupFormat
SolrQuery::getGroupLimit
SolrQuery
PHP Manual

SolrQuery::getGroupFunctions

(PECL solr >= 2.2.0)

SolrQuery::getGroupFunctions — Returns group functions (group.func parameter values)

Descrierea

public array SolrQuery::getGroupFunctions ( void )

Returns group functions (group.func parameter values)

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter).
SolrQuery::getGroupFormat
SolrQuery::getGroupLimit
SolrQuery


Returns the group.limit value

SolrQuery::getGroupFunctions
SolrQuery::getGroupMain
SolrQuery
PHP Manual

SolrQuery::getGroupLimit

(PECL solr >= 2.2.0)

SolrQuery::getGroupLimit — Returns the group.limit value

Descrierea

public integer SolrQuery::getGroupLimit ( void )

Returns the group.limit value

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1.
SolrQuery::getGroupFunctions
SolrQuery::getGroupMain
SolrQuery


Returns the group.main value

SolrQuery::getGroupLimit
SolrQuery::getGroupNGroups
SolrQuery
PHP Manual

SolrQuery::getGroupMain

(PECL solr >= 2.2.0)

SolrQuery::getGroupMain — Returns the group.main value

Descrierea

public bool SolrQuery::getGroupMain ( void )

Returns the group.main value

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
SolrQuery::getGroupLimit
SolrQuery::getGroupNGroups
SolrQuery


Returns the group.ngroups value

SolrQuery::getGroupMain
SolrQuery::getGroupOffset
SolrQuery
PHP Manual

SolrQuery::getGroupNGroups

(PECL solr >= 2.2.0)

SolrQuery::getGroupNGroups — Returns the group.ngroups value

Descrierea

public bool SolrQuery::getGroupNGroups ( void )

Returns the group.ngroups value

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results.
SolrQuery::getGroupMain
SolrQuery::getGroupOffset
SolrQuery


Returns the group.offset value

SolrQuery::getGroupNGroups
SolrQuery::getGroupQueries
SolrQuery
PHP Manual

SolrQuery::getGroupOffset

(PECL solr >= 2.2.0)

SolrQuery::getGroupOffset — Returns the group.offset value

Descrierea

public integer SolrQuery::getGroupOffset ( void )

Returns the group.offset value

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroupOffset() - Sets the group.offset parameter.
SolrQuery::getGroupNGroups
SolrQuery::getGroupQueries
SolrQuery


Returns all the group.query parameter values

SolrQuery::getGroupOffset
SolrQuery::getGroupSortFields
SolrQuery
PHP Manual

SolrQuery::getGroupQueries

(PECL solr >= 2.2.0)

SolrQuery::getGroupQueries — Returns all the group.query parameter values

Descrierea

public array SolrQuery::getGroupQueries ( void )

Returns all the group.query parameter values

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

array

A se vedea ?i

  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query.
SolrQuery::getGroupOffset
SolrQuery::getGroupSortFields
SolrQuery


Returns the group.sort value

SolrQuery::getGroupQueries
SolrQuery::getGroupTruncate
SolrQuery
PHP Manual

SolrQuery::getGroupSortFields

(PECL solr >= 2.2.0)

SolrQuery::getGroupSortFields — Returns the group.sort value

Descrierea

public array SolrQuery::getGroupSortFields ( void )

Returns the group.sort value

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter).
SolrQuery::getGroupQueries
SolrQuery::getGroupTruncate
SolrQuery


Returns the group.truncate value

SolrQuery::getGroupSortFields
SolrQuery::getHighlight
SolrQuery
PHP Manual

SolrQuery::getGroupTruncate

(PECL solr >= 2.2.0)

SolrQuery::getGroupTruncate — Returns the group.truncate value

Descrierea

public bool SolrQuery::getGroupTruncate ( void )

Returns the group.truncate value

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query.
SolrQuery::getGroupSortFields
SolrQuery::getHighlight
SolrQuery


Returns the state of the hl parameter

SolrQuery::getGroupTruncate
SolrQuery::getHighlightAlternateField
SolrQuery
PHP Manual

SolrQuery::getHighlight

(PECL solr >= 0.9.2)

SolrQuery::getHighlight — Returns the state of the hl parameter

Descrierea

public bool SolrQuery::getHighlight ( void )

Returns a boolean indicating whether or not to enable highlighted snippets to be generated in the query response.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a boolean on success and NULL if not set.

SolrQuery::getGroupTruncate
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

Descrierea

public string SolrQuery::getHighlightAlternateField ([ string $field_override ] )

Returns the highlight field to use as backup or default. It accepts an optional override.

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public array SolrQuery::getHighlightFields ( void )

Returns all the fields that Solr should generate highlighted snippets for

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrQuery::getHighlightFormatter ([ string $field_override ] )

Returns the formatter for the highlighted output

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public string SolrQuery::getHighlightFragmenter ([ string $field_override ] )

Returns the text snippet generator for highlighted text. Accepts an optional field override.

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

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.

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public bool SolrQuery::getHighlightHighlightMultiTerm ( void )

Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrQuery::getHighlightMaxAlternateFieldLength ([ string $field_override ] )

Returns the maximum number of characters of the field to return

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public int SolrQuery::getHighlightMaxAnalyzedChars ( void )

Returns the maximum number of characters into a document to look for suitable snippets

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrQuery::getHighlightMergeContiguous ([ string $field_override ] )

Returns whether or not the collapse contiguous fragments into a single fragment. Accepts an optional field override.

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public int SolrQuery::getHighlightRegexMaxAnalyzedChars ( void )

Returns the maximum number of characters from a field when using the regex fragmenter

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrQuery::getHighlightRegexPattern ( void )

Returns the regular expression used for fragmenting

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

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

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrQuery::getHighlightRequireFieldMatch ( void )

Returns if a field will only be highlighted if the query matched in this particular field.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrQuery::getHighlightSimplePost ([ string $field_override ] )

Returns the text which appears after a highlighted term. Accepts an optional field override

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public string SolrQuery::getHighlightSimplePre ([ string $field_override ] )

Returns the text which appears before a highlighted term. Accepts an optional field override

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

public int SolrQuery::getHighlightSnippets ([ string $field_override ] )

Returns the maximum number of highlighted snippets to generate per field. Accepts an optional field override

Parametri

field_override

The name of the field

Valorile întoarse

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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrQuery::getMlt ( void )

Returns whether or not MoreLikeThis results should be enabled

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrQuery::getMltBoost ( void )

Returns whether or not the query will be boosted by the interesting term relevance

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrQuery::getMltCount ( void )

Returns the number of similar documents to return for each result

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public array SolrQuery::getMltFields ( void )

Returns all the fields to use for similarity

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrQuery::getMltMaxNumQueryTerms ( void )

Returns the maximum number of query terms that will be included in any generated query

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrQuery::getMltMaxNumTokens ( void )

Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrQuery::getMltMaxWordLength ( void )

Returns the maximum word length above which words will be ignored

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

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

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrQuery::getMltMinTermFrequency ( void )

Returns the frequency below which terms will be ignored in the source document

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrQuery::getMltMinWordLength ( void )

Returns the minimum word length below which words will be ignored

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public array SolrQuery::getMltQueryFields ( void )

Returns the query fields and their boosts

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrQuery::getQuery ( void )

Returns the main search query

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrQuery::getRows ( void )

Returns the maximum number of documents from the complete result set to return to the client for every request

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public array SolrQuery::getSortFields ( void )

Returns all the sort fields

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrQuery::getStart ( void )

Returns the offset in the complete result set for the queries where the set of returned documents should begin.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrQuery::getStats ( void )

Returns whether or not stats is enabled

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public array SolrQuery::getStatsFacets ( void )

Returns all the stats facets that were set

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public array SolrQuery::getStatsFields ( void )

Returns all the statistics fields

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrQuery::getTerms ( void )

Returns whether or not the TermsComponent is enabled

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrQuery::getTermsField ( void )

Returns the field from which the terms are retrieved

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrQuery::getTermsIncludeLowerBound ( void )

Returns whether or not to include the lower bound in the result set

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public bool SolrQuery::getTermsIncludeUpperBound ( void )

Returns whether or not to include the upper bound term in the result set

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrQuery::getTermsLimit ( void )

Returns the maximum number of terms Solr should return

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrQuery::getTermsLowerBound ( void )

Returns the term to start at

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrQuery::getTermsMaxCount ( void )

Returns the maximum document frequency

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public int SolrQuery::getTermsMinCount ( void )

Returns the minimum document frequency to return in order to be included

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

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

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

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

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

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)

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string SolrQuery::getTermsUpperBound ( void )

Returns the term to stop at

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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::removeExpandFilterQuery
SolrQuery
PHP Manual

SolrQuery::getTimeAllowed

(PECL solr >= 0.9.2)

SolrQuery::getTimeAllowed — Returns the time in milliseconds allowed for the query to finish

Descrierea

public int SolrQuery::getTimeAllowed ( void )

Returns the time in milliseconds allowed for the query to finish.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns and integer on success and NULL if it is not set.

SolrQuery::getTermsUpperBound
SolrQuery::removeExpandFilterQuery
SolrQuery


Removes an expand filter query

SolrQuery::getTimeAllowed
SolrQuery::removeExpandSortField
SolrQuery
PHP Manual

SolrQuery::removeExpandFilterQuery

(PECL solr >= 2.2.0)

SolrQuery::removeExpandFilterQuery — Removes an expand filter query

Descrierea

public SolrQuery SolrQuery::removeExpandFilterQuery ( string $fq )

Removes an expand filter query.

Parametri

fq

Valorile întoarse

SolrQuery

A se vedea ?i

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter).
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter.
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group.
SolrQuery::getTimeAllowed
SolrQuery::removeExpandSortField
SolrQuery


Removes an expand sort field from the expand.sort parameter.

SolrQuery::removeExpandFilterQuery
SolrQuery::removeFacetDateField
SolrQuery
PHP Manual

SolrQuery::removeExpandSortField

(PECL solr >= 2.2.0)

SolrQuery::removeExpandSortField — Removes an expand sort field from the expand.sort parameter.

Descrierea

public SolrQuery SolrQuery::removeExpandSortField ( string $field )

Removes an expand sort field from the expand.sort parameter.

Parametri

field

field name

Valorile întoarse

SolrQuery

A se vedea ?i

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter).
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group.
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query
SolrQuery::removeExpandFilterQuery
SolrQuery::removeFacetDateField
SolrQuery


Removes one of the facet date fields

SolrQuery::removeExpandSortField
SolrQuery::removeFacetDateOther
SolrQuery
PHP Manual

SolrQuery::removeFacetDateField

(PECL solr >= 0.9.2)

SolrQuery::removeFacetDateField — Removes one of the facet date fields

Descrierea

public SolrQuery SolrQuery::removeFacetDateField ( string $field )

The name of the field

Parametri

field

The name of the date field to remove

Valorile întoarse

Returns the current SolrQuery object, if the return value is used.

SolrQuery::removeExpandSortField
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

Descrierea

public SolrQuery SolrQuery::removeFacetDateOther ( string $value [, string $field_override ] )

Removes one of the facet.date.other parameters

Parametri

value

The value

field_override

The name of the field.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::removeFacetField ( string $field )

Removes one of the facet.date parameters

Parametri

field

The name of the field

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::removeFacetQuery ( string $value )

Removes one of the facet.query parameters.

Parametri

value

The value

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::removeField ( string $field )

Removes a field from the list of fields

Parametri

field

Name of the field.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::removeFilterQuery ( string $fq )

Removes a filter query.

Parametri

fq

The filter query to remove

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::removeHighlightField ( string $field )

Removes one of the fields used for highlighting.

Parametri

field

The name of the field

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::removeMltField ( string $field )

Removes one of the moreLikeThis fields.

Parametri

field

Name of the field

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::removeMltQueryField ( string $queryField )

Removes one of the moreLikeThis query fields.

Parametri

queryField

The query field

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::removeSortField ( string $field )

Removes one of the sort fields

Parametri

field

The name of the field

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::removeStatsFacet ( string $value )

Removes one of the stats.facet parameters

Parametri

value

The value

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::removeStatsField ( string $field )

Removes one of the stats.field parameters

Parametri

field

The name of the field.

Valorile întoarse

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

Descrierea

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.

Parametri

flag

TRUE or FALSE

Valorile întoarse

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::setExpand
SolrQuery
PHP Manual

SolrQuery::setEchoParams

(PECL solr >= 0.9.2)

SolrQuery::setEchoParams — Determines what kind of parameters to include in the response

Descrierea

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.

Parametri

type

The type of parameters to include

Valorile întoarse

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setEchoHandler
SolrQuery::setExpand
SolrQuery


Enables/Disables the Expand Component

SolrQuery::setEchoParams
SolrQuery::setExpandQuery
SolrQuery
PHP Manual

SolrQuery::setExpand

(PECL solr >= 2.2.0)

SolrQuery::setExpand — Enables/Disables the Expand Component

Descrierea

public SolrQuery SolrQuery::setExpand ( bool $value )

Enables/Disables the Expand Component.

Parametri

value

Bool flag

Valorile întoarse

SolrQuery

Exemple

Example #1 SolrQuery::setExpand() example

<?php

$query = new SolrQuery('lucene');

$query
    ->setExpand(true)
    ->setExpandRows(50)
    ->setExpandQuery('text:product')
    ->addExpandFilterQuery('manu:apple')
    ->addExpandFilterQuery('inStock:true')
    ->addExpandSortField('score', SolrQuery::ORDER_DESC)
    ->addExpandSortField('title', SolrQuery::ORDER_ASC);

echo $query.PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&expand=true&expand.rows=50&expand.q=text:product&expand.fq=manu:apple&expand.fq=inStock:true&expand.sort=score desc,title asc

A se vedea ?i

  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter).
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter.
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group.
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query
SolrQuery::setEchoParams
SolrQuery::setExpandQuery
SolrQuery


Sets the expand.q parameter

SolrQuery::setExpand
SolrQuery::setExpandRows
SolrQuery
PHP Manual

SolrQuery::setExpandQuery

(PECL solr >= 2.2.0)

SolrQuery::setExpandQuery — Sets the expand.q parameter

Descrierea

public SolrQuery SolrQuery::setExpandQuery ( string $q )

Sets the expand.q parameter.

Overrides the main q parameter, determines which documents to include in the main group.

Parametri

q

Valorile întoarse

SolrQuery

A se vedea ?i

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter).
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter.
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group.
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query
SolrQuery::setExpand
SolrQuery::setExpandRows
SolrQuery


Sets the number of rows to display in each group (expand.rows). Server Default 5

SolrQuery::setExpandQuery
SolrQuery::setExplainOther
SolrQuery
PHP Manual

SolrQuery::setExpandRows

(PECL solr >= 2.2.0)

SolrQuery::setExpandRows — Sets the number of rows to display in each group (expand.rows). Server Default 5

Descrierea

public SolrQuery SolrQuery::setExpandRows ( integer $value )

Sets the number of rows to display in each group (expand.rows). Server Default 5

Parametri

value

Valorile întoarse

SolrQuery

A se vedea ?i

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter).
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter.
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group.
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query
SolrQuery::setExpandQuery
SolrQuery::setExplainOther
SolrQuery


Sets the explainOther common query parameter

SolrQuery::setExpandRows
SolrQuery::setFacet
SolrQuery
PHP Manual

SolrQuery::setExplainOther

(PECL solr >= 0.9.2)

SolrQuery::setExplainOther — Sets the explainOther common query parameter

Descrierea

public SolrQuery SolrQuery::setExplainOther ( string $query )

Sets the explainOther common query parameter

Parametri

query

The Lucene query to identify a set of documents

Valorile întoarse

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setExpandRows
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

Descrierea

public SolrQuery SolrQuery::setFacet ( bool $flag )

Enables or disables faceting.

Parametri

value

TRUE enables faceting and FALSE disables it.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setFacetDateEnd ( string $value [, string $field_override ] )

Maps to facet.date.end

Parametri

value

See facet.date.end

field_override

Name of the field

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setFacetDateGap ( string $value [, string $field_override ] )

Maps to facet.date.gap

Parametri

value

See facet.date.gap

field_override

The name of the field

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setFacetDateHardEnd ( bool $value [, string $field_override ] )

Maps to facet.date.hardend

Parametri

value

See facet.date.hardend

field_override

The name of the field

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setFacetDateStart ( string $value [, string $field_override ] )

Maps to facet.date.start

Parametri

value

See facet.date.start

field_override

The name of the field.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setFacetEnumCacheMinDefaultFrequency ( int $frequency [, string $field_override ] )

Sets the minimum document frequency used for determining term count

Parametri

value

The minimum frequency

field_override

The name of the field.

Valorile întoarse

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

Descrierea

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.

Parametri

limit

The maximum number of constraint counts

field_override

The name of the field.

Valorile întoarse

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

Descrierea

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.

Parametri

method

The method to use.

field_override

The name of the field.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setFacetMinCount ( int $mincount [, string $field_override ] )

Sets the minimum counts for facet fields that should be included in the response

Parametri

mincount

The minimum count

field_override

The name of the field.

Valorile întoarse

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

Descrierea

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

Parametri

flag

TRUE turns this feature on. FALSE disables it.

field_override

The name of the field.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setFacetOffset ( int $offset [, string $field_override ] )

Sets the offset into the list of constraints to allow for pagination.

Parametri

offset

The offset

field_override

The name of the field.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setFacetPrefix ( string $prefix [, string $field_override ] )

Specifies a string prefix with which to limits the terms on which to facet.

Parametri

prefix

The prefix string

field_override

The name of the field.

Valorile întoarse

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::setGroup
SolrQuery
PHP Manual

SolrQuery::setFacetSort

(PECL solr >= 0.9.2)

SolrQuery::setFacetSort — Determines the ordering of the facet field constraints

Descrierea

public SolrQuery SolrQuery::setFacetSort ( int $facetSort [, string $field_override ] )

Determines the ordering of the facet field constraints

Parametri

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.

Valorile întoarse

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacetPrefix
SolrQuery::setGroup
SolrQuery


Enable/Disable result grouping (group parameter)

SolrQuery::setFacetSort
SolrQuery::setGroupCachePercent
SolrQuery
PHP Manual

SolrQuery::setGroup

(PECL solr >= 2.2.0)

SolrQuery::setGroup — Enable/Disable result grouping (group parameter)

Descrierea

public SolrQuery SolrQuery::setGroup ( bool $value )

Enable/Disable result grouping (group parameter)

Parametri

value

Valorile întoarse

A se vedea ?i

  • SolrQuery::getGroup() - Returns true if grouping is enabled
  • SolrQuery::addGroupField() - Add a field to be used to group results.
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter).
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query.
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter).
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter.
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1.
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results.
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query.
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter).
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping
SolrQuery::setFacetSort
SolrQuery::setGroupCachePercent
SolrQuery


Enables caching for result grouping

SolrQuery::setGroup
SolrQuery::setGroupFacet
SolrQuery
PHP Manual

SolrQuery::setGroupCachePercent

(PECL solr >= 2.2.0)

SolrQuery::setGroupCachePercent — Enables caching for result grouping

Descrierea

public SolrQuery SolrQuery::setGroupCachePercent ( integer $percent )

Setting this parameter to a number greater than 0 enables caching for result grouping. Result Grouping executes two searches; this option caches the second search. The server default value is 0. Testing has shown that group caching only improves search time with Boolean, wildcard, and fuzzy queries. For simple queries like term or "match all" queries, group caching degrades performance. group.cache.percent parameter

Parametri

percent

Valorile întoarse

Erori/Excep?ii

Emits SolrIllegalArgumentException in case of an invalid parameter was passed.

A se vedea ?i

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results.
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter).
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query.
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter).
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter.
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1.
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results.
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query.
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter).
SolrQuery::setGroup
SolrQuery::setGroupFacet
SolrQuery


Sets group.facet parameter

SolrQuery::setGroupCachePercent
SolrQuery::setGroupFormat
SolrQuery
PHP Manual

SolrQuery::setGroupFacet

(PECL solr >= 2.2.0)

SolrQuery::setGroupFacet — Sets group.facet parameter

Descrierea

public SolrQuery SolrQuery::setGroupFacet ( bool $value )

Determines whether to compute grouped facets for the field facets specified in facet.field parameters. Grouped facets are computed based on the first specified group.

Parametri

value

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results.
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter).
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query.
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter).
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter.
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1.
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results.
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query.
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter).
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping
SolrQuery::setGroupCachePercent
SolrQuery::setGroupFormat
SolrQuery


Sets the group format, result structure (group.format parameter).

SolrQuery::setGroupFacet
SolrQuery::setGroupLimit
SolrQuery
PHP Manual

SolrQuery::setGroupFormat

(PECL solr >= 2.2.0)

SolrQuery::setGroupFormat — Sets the group format, result structure (group.format parameter).

Descrierea

public SolrQuery SolrQuery::setGroupFormat ( string $value )

Sets the group.format parameter. If this parameter is set to simple, the grouped documents are presented in a single flat list, and the start and rows parameters affect the numbers of documents instead of groups. Accepts: grouped/simple

Parametri

value

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results.
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter).
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query.
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter).
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter.
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1.
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results.
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query.
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping
SolrQuery::setGroupFacet
SolrQuery::setGroupLimit
SolrQuery


Specifies the number of results to return for each group. The server default value is 1.

SolrQuery::setGroupFormat
SolrQuery::setGroupMain
SolrQuery
PHP Manual

SolrQuery::setGroupLimit

(PECL solr >= 2.2.0)

SolrQuery::setGroupLimit — Specifies the number of results to return for each group. The server default value is 1.

Descrierea

public SolrQuery SolrQuery::setGroupLimit ( integer $value )

Specifies the number of results to return for each group. The server default value is 1.

Parametri

value

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results.
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter).
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query.
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter).
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter.
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results.
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query.
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter).
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping
SolrQuery::setGroupFormat
SolrQuery::setGroupMain
SolrQuery


If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.

SolrQuery::setGroupLimit
SolrQuery::setGroupNGroups
SolrQuery
PHP Manual

SolrQuery::setGroupMain

(PECL solr >= 2.2.0)

SolrQuery::setGroupMain — If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.

Descrierea

public SolrQuery SolrQuery::setGroupMain ( string $value )

If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.

Parametri

value

Valorile întoarse

A se vedea ?i

A se vedea ?i

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results.
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter).
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query.
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter).
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter.
  • SolrQuery::setGroupMain()
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results.
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query.
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter).
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping
SolrQuery::setGroupLimit
SolrQuery::setGroupNGroups
SolrQuery


If true, Solr includes the number of groups that have matched the query in the results.

SolrQuery::setGroupMain
SolrQuery::setGroupOffset
SolrQuery
PHP Manual

SolrQuery::setGroupNGroups

(PECL solr >= 2.2.0)

SolrQuery::setGroupNGroups — If true, Solr includes the number of groups that have matched the query in the results.

Descrierea

public SolrQuery SolrQuery::setGroupNGroups ( bool $value )

If true, Solr includes the number of groups that have matched the query in the results.

Parametri

value

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results.
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter).
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query.
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter).
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter.
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1.
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query.
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter).
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping
SolrQuery::setGroupMain
SolrQuery::setGroupOffset
SolrQuery


Sets the group.offset parameter.

SolrQuery::setGroupNGroups
SolrQuery::setGroupTruncate
SolrQuery
PHP Manual

SolrQuery::setGroupOffset

(PECL solr >= 2.2.0)

SolrQuery::setGroupOffset — Sets the group.offset parameter.

Descrierea

public SolrQuery SolrQuery::setGroupOffset ( integer $value )

Sets the group.offset parameter.

Parametri

value

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results.
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter).
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query.
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter).
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1.
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results.
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query.
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter).
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping
SolrQuery::setGroupNGroups
SolrQuery::setGroupTruncate
SolrQuery


If true, facet counts are based on the most relevant document of each group matching the query.

SolrQuery::setGroupOffset
SolrQuery::setHighlight
SolrQuery
PHP Manual

SolrQuery::setGroupTruncate

(PECL solr >= 2.2.0)

SolrQuery::setGroupTruncate — If true, facet counts are based on the most relevant document of each group matching the query.

Descrierea

public SolrQuery SolrQuery::setGroupTruncate ( bool $value )

If true, facet counts are based on the most relevant document of each group matching the query. The server default value is false. group.truncate parameter

Parametri

value

Valorile întoarse

A se vedea ?i

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results.
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter).
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query.
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter).
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter.
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1.
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results.
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter).
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping
SolrQuery::setGroupOffset
SolrQuery::setHighlight
SolrQuery


Enables or disables highlighting

SolrQuery::setGroupTruncate
SolrQuery::setHighlightAlternateField
SolrQuery
PHP Manual

SolrQuery::setHighlight

(PECL solr >= 0.9.2)

SolrQuery::setHighlight — Enables or disables highlighting

Descrierea

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

Parametri

flag

Enable or disable highlighting

Valorile întoarse

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setGroupTruncate
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

Descrierea

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

Parametri

field

The name of the backup field

field_override

The name of the field we are overriding this setting for.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setHighlightFormatter ( string $formatter [, string $field_override ] )

Specify a formatter for the highlight output.

Parametri

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

Descrierea

public SolrQuery SolrQuery::setHighlightFragmenter ( string $fragmenter [, string $field_override ] )

Specify a text snippet generator for highlighted text.

Parametri

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.

Valorile întoarse

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

Descrierea

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).

Parametri

size

The size, in characters, of fragments to consider for highlighting

field_override

The name of the field.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setHighlightHighlightMultiTerm ( bool $flag )

Use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

Parametri

flag

Whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

Valorile întoarse

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

Descrierea

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.

Parametri

fieldLength

The length of the field

field_override

The name of the field.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setHighlightMaxAnalyzedChars ( int $value )

Specifies the number of characters into a document to look for suitable snippets

Parametri

value

The number of characters into a document to look for suitable snippets

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setHighlightMergeContiguous ( bool $flag [, string $field_override ] )

Whether or not to collapse contiguous fragments into a single fragment

Parametri

value

Whether or not to collapse contiguous fragments into a single fragment

field_override

The name of the field.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setHighlightRegexMaxAnalyzedChars ( int $maxAnalyzedChars )

Specify the maximum number of characters to analyze from a field when using the regex fragmenter

Parametri

maxAnalyzedChars

The maximum number of characters to analyze from a field when using the regex fragmenter

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setHighlightRegexPattern ( string $value )

Specifies the regular expression for fragmenting. This could be used to extract sentences

Parametri

value

The regular expression for fragmenting. This could be used to extract sentences

Valorile întoarse

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

Descrierea

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 accommodate the regular expression

Parametri

factor

The factor by which the regex fragmenter can stray from the ideal fragment size

Valorile întoarse

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

Descrierea

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

Parametri

flag

TRUE or FALSE

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setHighlightSimplePost ( string $simplePost [, string $field_override ] )

Sets the text which appears before a highlighted term

Parametri

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

Descrierea

public SolrQuery SolrQuery::setHighlightSimplePre ( string $simplePre [, string $field_override ] )

Sets the text which appears before a highlighted term

The default is <em>

Parametri

simplePre

The text which appears before a highlighted term

field_override

The name of the field.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setHighlightSnippets ( int $value [, string $field_override ] )

Sets the maximum number of highlighted snippets to generate per field

Parametri

value

The maximum number of highlighted snippets to generate per field

field_override

The name of the field.

Valorile întoarse

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

Descrierea

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

Parametri

value

Whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setMlt ( bool $flag )

Enables or disables moreLikeThis

Parametri

flag

TRUE enables it and FALSE turns it off.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setMltBoost ( bool $flag )

Set if the query will be boosted by the interesting term relevance

Parametri

value

Sets to TRUE or FALSE

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setMltCount ( int $count )

Set the number of similar documents to return for each result

Parametri

count

The number of similar documents to return for each result

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setMltMaxNumQueryTerms ( int $value )

Sets the maximum number of query terms that will be included in any generated query.

Parametri

value

The maximum number of query terms that will be included in any generated query

Valorile întoarse

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

Descrierea

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.

Parametri

value

The maximum number of tokens to parse

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setMltMaxWordLength ( int $maxWordLength )

Sets the maximum word length above which words will be ignored.

Parametri

maxWordLength

The maximum word length above which words will be ignored

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setMltMinDocFrequency ( int $minDocFrequency )

The frequency at which words will be ignored which do not occur in at least this many docs.

Parametri

minDocFrequency

Sets the frequency at which words will be ignored which do not occur in at least this many docs.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setMltMinTermFrequency ( int $minTermFrequency )

Sets the frequency below which terms will be ignored in the source docs

Parametri

minTermFrequency

The frequency below which terms will be ignored in the source docs

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setMltMinWordLength ( int $minWordLength )

Sets the minimum word length below which words will be ignored.

Parametri

minWordLength

The minimum word length below which words will be ignored

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setOmitHeader ( bool $flag )

Exclude the header from the returned results.

Parametri

flag

TRUE excludes the header from the result.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setQuery ( string $query )

Sets the search query.

Parametri

query

The search query

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setRows ( int $rows )

Specifies the maximum number of rows to return in the result

Parametri

rows

The maximum number of rows to return

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setShowDebugInfo ( bool $flag )

Whether to show debug info

Parametri

flag

Whether to show debug info. TRUE or FALSE

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setStart ( int $start )

Specifies the number of rows to skip. Useful in pagination of results.

Parametri

start

The number of rows to skip.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setStats ( bool $flag )

Enables or disables the Stats component.

Parametri

flag

TRUE turns on the stats component and FALSE disables it.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setTerms ( bool $flag )

Enables or disables the TermsComponent

Parametri

flag

TRUE enables it. FALSE turns it off

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setTermsField ( string $fieldname )

Sets the name of the field to get the terms from

Parametri

fieldname

The field name

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setTermsIncludeLowerBound ( bool $flag )

Include the lower bound term in the result set.

Parametri

flag

Include the lower bound term in the result set

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setTermsIncludeUpperBound ( bool $flag )

Include the upper bound term in the result set.

Parametri

flag

TRUE or FALSE

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setTermsLimit ( int $limit )

Sets the maximum number of terms to return

Parametri

limit

The maximum number of terms to return. All the terms will be returned if the limit is negative.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setTermsLowerBound ( string $lowerBound )

Specifies the Term to start from

Parametri

lowerBound

The lower bound Term

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setTermsMaxCount ( int $frequency )

Sets the maximum document frequency.

Parametri

frequency

The maximum document frequency.

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setTermsMinCount ( int $frequency )

Sets the minimum doc frequency to return in order to be included

Parametri

frequency

The minimum frequency

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setTermsPrefix ( string $prefix )

Restrict matches to terms that start with the prefix

Parametri

prefix

Restrict matches to terms that start with the prefix

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setTermsReturnRaw ( bool $flag )

If true, return the raw characters of the indexed term, regardless of if it is human readable

Parametri

value

TRUE or FALSE

Valorile întoarse

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

Descrierea

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

Parametri

sortType

SolrQuery::TERMS_SORT_INDEX or SolrQuery::TERMS_SORT_COUNT

Valorile întoarse

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

Descrierea

public SolrQuery SolrQuery::setTermsUpperBound ( string $upperBound )

Sets the term to stop at

Parametri

upperBound

The term to stop at

Valorile întoarse

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
SolrDisMaxQuery
SolrQuery
PHP Manual

SolrQuery::setTimeAllowed

(PECL solr >= 0.9.2)

SolrQuery::setTimeAllowed — The time allowed for search to finish

Descrierea

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.

Parametri

timeAllowed

The time allowed for a search to finish.

Valorile întoarse

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setTermsUpperBound
SolrDisMaxQuery
SolrQuery


The SolrDisMaxQuery class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

SolrDisMaxQuery extends SolrQuery implements Serializable {
/* Proprieta?i mo?tenite */
const integer SolrQuery::ORDER_ASC = 0 ;
const integer SolrQuery::ORDER_DESC = 1 ;
const integer SolrQuery::FACET_SORT_INDEX = 0 ;
const integer SolrQuery::FACET_SORT_COUNT = 1 ;
const integer SolrQuery::TERMS_SORT_INDEX = 0 ;
const integer SolrQuery::TERMS_SORT_COUNT = 1 ;
/* Metode */
public SolrDisMaxQuery addBigramPhraseField ( string $field , string $boost [, string $slop ] )
public SolrDisMaxQuery addBoostQuery ( string $field , string $value [, string $boost ] )
public SolrDisMaxQuery addPhraseField ( string $field , string $boost [, string $slop ] )
public SolrDisMaxQuery addQueryField ( string $field [, string $boost ] )
public SolrDisMaxQuery addTrigramPhraseField ( string $field , string $boost [, string $slop ] )
public SolrDisMaxQuery addUserField ( string $field )
public __construct ([ string $q ] )
public SolrDisMaxQuery removeBigramPhraseField ( string $field )
public SolrDisMaxQuery removeBoostQuery ( string $field )
public SolrDisMaxQuery removePhraseField ( string $field )
public SolrDisMaxQuery removeQueryField ( string $field )
public SolrDisMaxQuery removeTrigramPhraseField ( string $field )
public SolrDisMaxQuery removeUserField ( string $field )
public SolrDisMaxQuery setBigramPhraseFields ( string $fields )
public SolrDisMaxQuery setBigramPhraseSlop ( string $slop )
public SolrDisMaxQuery setBoostFunction ( string $function )
public SolrDisMaxQuery setBoostQuery ( string $q )
public SolrDisMaxQuery setMinimumMatch ( string $value )
public SolrDisMaxQuery setPhraseFields ( string $fields )
public SolrDisMaxQuery setPhraseSlop ( string $slop )
public SolrDisMaxQuery setQueryAlt ( string $q )
public SolrDisMaxQuery setQueryPhraseSlop ( string $slop )
public SolrDisMaxQuery setTieBreaker ( string $tieBreaker )
public SolrDisMaxQuery setTrigramPhraseFields ( string $fields )
public SolrDisMaxQuery setTrigramPhraseSlop ( string $slop )
public SolrDisMaxQuery setUserFields ( string $fields )
public SolrDisMaxQuery useDisMaxQueryParser ( void )
public SolrDisMaxQuery useEDisMaxQueryParser ( void )
/* Metode mo?tenite */
public SolrQuery SolrQuery::addExpandFilterQuery ( string $fq )
public SolrQuery SolrQuery::addExpandSortField ( string $field [, string $order ] )
public SolrQuery SolrQuery::addFacetDateField ( string $dateField )
public SolrQuery SolrQuery::addFacetDateOther ( string $value [, string $field_override ] )
public SolrQuery SolrQuery::addFacetField ( string $field )
public SolrQuery SolrQuery::addFacetQuery ( string $facetQuery )
public SolrQuery SolrQuery::addField ( string $field )
public SolrQuery SolrQuery::addFilterQuery ( string $fq )
public SolrQuery SolrQuery::addGroupField ( string $value )
public SolrQuery SolrQuery::addGroupFunction ( string $value )
public SolrQuery SolrQuery::addGroupQuery ( string $value )
public SolrQuery SolrQuery::addGroupSortField ( string $field [, integer $order ] )
public SolrQuery SolrQuery::addHighlightField ( string $field )
public SolrQuery SolrQuery::addMltField ( string $field )
public SolrQuery SolrQuery::addMltQueryField ( string $field , float $boost )
public SolrQuery SolrQuery::addSortField ( string $field [, int $order = SolrQuery::ORDER_DESC ] )
public SolrQuery SolrQuery::addStatsFacet ( string $field )
public SolrQuery SolrQuery::addStatsField ( string $field )
public SolrQuery SolrQuery::collapse ( SolrCollapseFunction $collapseFunction )
public SolrQuery::__construct ([ string $q ] )
public void SolrQuery::__destruct ( void )
public bool SolrQuery::getExpand ( void )
public array SolrQuery::getExpandFilterQueries ( void )
public array SolrQuery::getExpandQuery ( void )
public integer SolrQuery::getExpandRows ( void )
public array SolrQuery::getExpandSortFields ( void )
public bool SolrQuery::getFacet ( void )
public string SolrQuery::getFacetDateEnd ([ string $field_override ] )
public array SolrQuery::getFacetDateFields ( void )
public string SolrQuery::getFacetDateGap ([ string $field_override ] )
public string SolrQuery::getFacetDateHardEnd ([ string $field_override ] )
public array SolrQuery::getFacetDateOther ([ string $field_override ] )
public string SolrQuery::getFacetDateStart ([ string $field_override ] )
public array SolrQuery::getFacetFields ( void )
public int SolrQuery::getFacetLimit ([ string $field_override ] )
public string SolrQuery::getFacetMethod ([ string $field_override ] )
public int SolrQuery::getFacetMinCount ([ string $field_override ] )
public bool SolrQuery::getFacetMissing ([ string $field_override ] )
public int SolrQuery::getFacetOffset ([ string $field_override ] )
public string SolrQuery::getFacetPrefix ([ string $field_override ] )
public array SolrQuery::getFacetQueries ( void )
public int SolrQuery::getFacetSort ([ string $field_override ] )
public array SolrQuery::getFields ( void )
public array SolrQuery::getFilterQueries ( void )
public bool SolrQuery::getGroup ( void )
public integer SolrQuery::getGroupCachePercent ( void )
public bool SolrQuery::getGroupFacet ( void )
public array SolrQuery::getGroupFields ( void )
public string SolrQuery::getGroupFormat ( void )
public array SolrQuery::getGroupFunctions ( void )
public integer SolrQuery::getGroupLimit ( void )
public bool SolrQuery::getGroupMain ( void )
public bool SolrQuery::getGroupNGroups ( void )
public integer SolrQuery::getGroupOffset ( void )
public array SolrQuery::getGroupQueries ( void )
public array SolrQuery::getGroupSortFields ( void )
public bool SolrQuery::getGroupTruncate ( void )
public bool SolrQuery::getHighlight ( void )
public string SolrQuery::getHighlightAlternateField ([ string $field_override ] )
public array SolrQuery::getHighlightFields ( void )
public string SolrQuery::getHighlightFormatter ([ string $field_override ] )
public string SolrQuery::getHighlightFragmenter ([ string $field_override ] )
public int SolrQuery::getHighlightFragsize ([ string $field_override ] )
public bool SolrQuery::getHighlightHighlightMultiTerm ( void )
public int SolrQuery::getHighlightMaxAlternateFieldLength ([ string $field_override ] )
public int SolrQuery::getHighlightMaxAnalyzedChars ( void )
public bool SolrQuery::getHighlightMergeContiguous ([ string $field_override ] )
public int SolrQuery::getHighlightRegexMaxAnalyzedChars ( void )
public string SolrQuery::getHighlightRegexPattern ( void )
public float SolrQuery::getHighlightRegexSlop ( void )
public bool SolrQuery::getHighlightRequireFieldMatch ( void )
public string SolrQuery::getHighlightSimplePost ([ string $field_override ] )
public string SolrQuery::getHighlightSimplePre ([ string $field_override ] )
public int SolrQuery::getHighlightSnippets ([ string $field_override ] )
public bool SolrQuery::getHighlightUsePhraseHighlighter ( void )
public bool SolrQuery::getMlt ( void )
public bool SolrQuery::getMltBoost ( void )
public int SolrQuery::getMltCount ( void )
public array SolrQuery::getMltFields ( void )
public int SolrQuery::getMltMaxNumQueryTerms ( void )
public int SolrQuery::getMltMaxNumTokens ( void )
public int SolrQuery::getMltMaxWordLength ( void )
public int SolrQuery::getMltMinDocFrequency ( void )
public int SolrQuery::getMltMinTermFrequency ( void )
public int SolrQuery::getMltMinWordLength ( void )
public array SolrQuery::getMltQueryFields ( void )
public string SolrQuery::getQuery ( void )
public int SolrQuery::getRows ( void )
public array SolrQuery::getSortFields ( void )
public int SolrQuery::getStart ( void )
public bool SolrQuery::getStats ( void )
public array SolrQuery::getStatsFacets ( void )
public array SolrQuery::getStatsFields ( void )
public bool SolrQuery::getTerms ( void )
public string SolrQuery::getTermsField ( void )
public bool SolrQuery::getTermsIncludeLowerBound ( void )
public bool SolrQuery::getTermsIncludeUpperBound ( void )
public int SolrQuery::getTermsLimit ( void )
public string SolrQuery::getTermsLowerBound ( void )
public int SolrQuery::getTermsMaxCount ( void )
public int SolrQuery::getTermsMinCount ( void )
public string SolrQuery::getTermsPrefix ( void )
public bool SolrQuery::getTermsReturnRaw ( void )
public int SolrQuery::getTermsSort ( void )
public string SolrQuery::getTermsUpperBound ( void )
public int SolrQuery::getTimeAllowed ( void )
public SolrQuery SolrQuery::removeExpandFilterQuery ( string $fq )
public SolrQuery SolrQuery::removeExpandSortField ( string $field )
public SolrQuery SolrQuery::removeFacetDateField ( string $field )
public SolrQuery SolrQuery::removeFacetDateOther ( string $value [, string $field_override ] )
public SolrQuery SolrQuery::removeFacetField ( string $field )
public SolrQuery SolrQuery::removeFacetQuery ( string $value )
public SolrQuery SolrQuery::removeField ( string $field )
public SolrQuery SolrQuery::removeFilterQuery ( string $fq )
public SolrQuery SolrQuery::removeHighlightField ( string $field )
public SolrQuery SolrQuery::removeMltField ( string $field )
public SolrQuery SolrQuery::removeMltQueryField ( string $queryField )
public SolrQuery SolrQuery::removeSortField ( string $field )
public SolrQuery SolrQuery::removeStatsFacet ( string $value )
public SolrQuery SolrQuery::removeStatsField ( string $field )
public SolrQuery SolrQuery::setEchoHandler ( bool $flag )
public SolrQuery SolrQuery::setEchoParams ( string $type )
public SolrQuery SolrQuery::setExpand ( bool $value )
public SolrQuery SolrQuery::setExpandQuery ( string $q )
public SolrQuery SolrQuery::setExpandRows ( integer $value )
public SolrQuery SolrQuery::setExplainOther ( string $query )
public SolrQuery SolrQuery::setFacet ( bool $flag )
public SolrQuery SolrQuery::setFacetDateEnd ( string $value [, string $field_override ] )
public SolrQuery SolrQuery::setFacetDateGap ( string $value [, string $field_override ] )
public SolrQuery SolrQuery::setFacetDateHardEnd ( bool $value [, string $field_override ] )
public SolrQuery SolrQuery::setFacetDateStart ( string $value [, string $field_override ] )
public SolrQuery SolrQuery::setFacetEnumCacheMinDefaultFrequency ( int $frequency [, string $field_override ] )
public SolrQuery SolrQuery::setFacetLimit ( int $limit [, string $field_override ] )
public SolrQuery SolrQuery::setFacetMethod ( string $method [, string $field_override ] )
public SolrQuery SolrQuery::setFacetMinCount ( int $mincount [, string $field_override ] )
public SolrQuery SolrQuery::setFacetMissing ( bool $flag [, string $field_override ] )
public SolrQuery SolrQuery::setFacetOffset ( int $offset [, string $field_override ] )
public SolrQuery SolrQuery::setFacetPrefix ( string $prefix [, string $field_override ] )
public SolrQuery SolrQuery::setFacetSort ( int $facetSort [, string $field_override ] )
public SolrQuery SolrQuery::setGroup ( bool $value )
public SolrQuery SolrQuery::setGroupCachePercent ( integer $percent )
public SolrQuery SolrQuery::setGroupFacet ( bool $value )
public SolrQuery SolrQuery::setGroupFormat ( string $value )
public SolrQuery SolrQuery::setGroupLimit ( integer $value )
public SolrQuery SolrQuery::setGroupMain ( string $value )
public SolrQuery SolrQuery::setGroupNGroups ( bool $value )
public SolrQuery SolrQuery::setGroupOffset ( integer $value )
public SolrQuery SolrQuery::setGroupTruncate ( bool $value )
public SolrQuery SolrQuery::setHighlight ( bool $flag )
public SolrQuery SolrQuery::setHighlightAlternateField ( string $field [, string $field_override ] )
public SolrQuery SolrQuery::setHighlightFormatter ( string $formatter [, string $field_override ] )
public SolrQuery SolrQuery::setHighlightFragmenter ( string $fragmenter [, string $field_override ] )
public SolrQuery SolrQuery::setHighlightFragsize ( int $size [, string $field_override ] )
public SolrQuery SolrQuery::setHighlightHighlightMultiTerm ( bool $flag )
public SolrQuery SolrQuery::setHighlightMaxAlternateFieldLength ( int $fieldLength [, string $field_override ] )
public SolrQuery SolrQuery::setHighlightMaxAnalyzedChars ( int $value )
public SolrQuery SolrQuery::setHighlightMergeContiguous ( bool $flag [, string $field_override ] )
public SolrQuery SolrQuery::setHighlightRegexMaxAnalyzedChars ( int $maxAnalyzedChars )
public SolrQuery SolrQuery::setHighlightRegexPattern ( string $value )
public SolrQuery SolrQuery::setHighlightRegexSlop ( float $factor )
public SolrQuery SolrQuery::setHighlightRequireFieldMatch ( bool $flag )
public SolrQuery SolrQuery::setHighlightSimplePost ( string $simplePost [, string $field_override ] )
public SolrQuery SolrQuery::setHighlightSimplePre ( string $simplePre [, string $field_override ] )
public SolrQuery SolrQuery::setHighlightSnippets ( int $value [, string $field_override ] )
public SolrQuery SolrQuery::setHighlightUsePhraseHighlighter ( bool $flag )
public SolrQuery SolrQuery::setMlt ( bool $flag )
public SolrQuery SolrQuery::setMltBoost ( bool $flag )
public SolrQuery SolrQuery::setMltCount ( int $count )
public SolrQuery SolrQuery::setMltMaxNumQueryTerms ( int $value )
public SolrQuery SolrQuery::setMltMaxNumTokens ( int $value )
public SolrQuery SolrQuery::setMltMaxWordLength ( int $maxWordLength )
public SolrQuery SolrQuery::setMltMinDocFrequency ( int $minDocFrequency )
public SolrQuery SolrQuery::setMltMinTermFrequency ( int $minTermFrequency )
public SolrQuery SolrQuery::setMltMinWordLength ( int $minWordLength )
public SolrQuery SolrQuery::setOmitHeader ( bool $flag )
public SolrQuery SolrQuery::setQuery ( string $query )
public SolrQuery SolrQuery::setRows ( int $rows )
public SolrQuery SolrQuery::setShowDebugInfo ( bool $flag )
public SolrQuery SolrQuery::setStart ( int $start )
public SolrQuery SolrQuery::setStats ( bool $flag )
public SolrQuery SolrQuery::setTerms ( bool $flag )
public SolrQuery SolrQuery::setTermsField ( string $fieldname )
public SolrQuery SolrQuery::setTermsIncludeLowerBound ( bool $flag )
public SolrQuery SolrQuery::setTermsIncludeUpperBound ( bool $flag )
public SolrQuery SolrQuery::setTermsLimit ( int $limit )
public SolrQuery SolrQuery::setTermsLowerBound ( string $lowerBound )
public SolrQuery SolrQuery::setTermsMaxCount ( int $frequency )
public SolrQuery SolrQuery::setTermsMinCount ( int $frequency )
public SolrQuery SolrQuery::setTermsPrefix ( string $prefix )
public SolrQuery SolrQuery::setTermsReturnRaw ( bool $flag )
public SolrQuery SolrQuery::setTermsSort ( int $sortType )
public SolrQuery SolrQuery::setTermsUpperBound ( string $upperBound )
public SolrQuery SolrQuery::setTimeAllowed ( int $timeAllowed )
}

Constante predefinite

SolrDisMaxQuery::ORDER_ASC

Used to specify that the sorting should be in acending order (Duplicated for easier migration)

SolrDisMaxQuery::ORDER_DESC

Used to specify that the sorting should be in descending order (Duplicated for easier migration)

SolrDisMaxQuery::FACET_SORT_INDEX

Used to specify that the facet should sort by index (Duplicated for easier migration)

SolrDisMaxQuery::FACET_SORT_COUNT

Used to specify that the facet should sort by count (Duplicated for easier migration)

SolrDisMaxQuery::TERMS_SORT_INDEX

Used in the TermsComponent (Duplicated for easier migration)

SolrDisMaxQuery::TERMS_SORT_COUNT

Used in the TermsComponent (Duplicated for easier migration)

Cuprins

  • SolrDisMaxQuery::addBigramPhraseField — Adds a Phrase Bigram Field (pf2 parameter)
  • SolrDisMaxQuery::addBoostQuery — Adds a boost query field with value and optional boost (bq parameter)
  • SolrDisMaxQuery::addPhraseField — Adds a Phrase Field (pf parameter)
  • SolrDisMaxQuery::addQueryField — Add a query field with optional boost (qf parameter)
  • SolrDisMaxQuery::addTrigramPhraseField — Adds a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::addUserField — Adds a field to User Fields Parameter (uf)
  • SolrDisMaxQuery::__construct — Class Constructor
  • SolrDisMaxQuery::removeBigramPhraseField — Removes phrase bigram field (pf2 parameter)
  • SolrDisMaxQuery::removeBoostQuery — Removes a boost query partial by field name (bq)
  • SolrDisMaxQuery::removePhraseField — Removes a Phrase Field (pf parameter)
  • SolrDisMaxQuery::removeQueryField — Removes a Query Field (qf parameter)
  • SolrDisMaxQuery::removeTrigramPhraseField — Removes a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::removeUserField — Removes a field from The User Fields Parameter (uf)
  • SolrDisMaxQuery::setBigramPhraseFields — Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
  • SolrDisMaxQuery::setBigramPhraseSlop — Sets Bigram Phrase Slop (ps2 parameter)
  • SolrDisMaxQuery::setBoostFunction — Sets a Boost Function (bf parameter).
  • SolrDisMaxQuery::setBoostQuery — Directly Sets Boost Query Parameter (bq)
  • SolrDisMaxQuery::setMinimumMatch — Set Minimum "Should" Match (mm)
  • SolrDisMaxQuery::setPhraseFields — Sets Phrase Fields and their boosts (and slops) using pf2 parameter
  • SolrDisMaxQuery::setPhraseSlop — Sets the default slop on phrase queries (ps parameter)
  • SolrDisMaxQuery::setQueryAlt — Set Query Alternate (q.alt parameter)
  • SolrDisMaxQuery::setQueryPhraseSlop — specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)
  • SolrDisMaxQuery::setTieBreaker — Sets Tie Breaker parameter (tie parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields — Directly Sets Trigram Phrase Fields (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseSlop — Sets Trigram Phrase Slop (ps3 parameter)
  • SolrDisMaxQuery::setUserFields — Sets User Fields parameter (uf)
  • SolrDisMaxQuery::useDisMaxQueryParser — Switch QueryParser to be DisMax Query Parser
  • SolrDisMaxQuery::useEDisMaxQueryParser — Switch QueryParser to be EDisMax
SolrQuery::setTimeAllowed
SolrDisMaxQuery::addBigramPhraseField
Solr


Adds a Phrase Bigram Field (pf2 parameter)

SolrDisMaxQuery
SolrDisMaxQuery::addBoostQuery
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::addBigramPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::addBigramPhraseField — Adds a Phrase Bigram Field (pf2 parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::addBigramPhraseField ( string $field , string $boost [, string $slop ] )

Adds a Phrase Bigram Field (pf2 parameter) output format: field~slop^boost OR field^boost Slop is optional

Parametri

field

boost

slop

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::addBigramPhraseField() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
    ->addBigramPhraseField('cat', 2, 5.1)
    ->addBigramPhraseField('feature', 4.5)
;
echo $dismaxQuery;

?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&pf2=cat~5.1^2 feature^4.5

A se vedea ?i

  • SolrDisMaxQuery::removeBigramPhraseField() - Removes phrase bigram field (pf2 parameter)
  • SolrDisMaxQuery::setBigramPhraseFields() - Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
  • SolrDisMaxQuery::setBigramPhraseSlop() - Sets Bigram Phrase Slop (ps2 parameter)
SolrDisMaxQuery
SolrDisMaxQuery::addBoostQuery
SolrDisMaxQuery


Adds a boost query field with value and optional boost (bq parameter)

SolrDisMaxQuery::addBigramPhraseField
SolrDisMaxQuery::addPhraseField
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::addBoostQuery

(No version information available, might only be in Git)

SolrDisMaxQuery::addBoostQuery — Adds a boost query field with value and optional boost (bq parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::addBoostQuery ( string $field , string $value [, string $boost ] )

Adds a Boost Query field with value [and boost] (bq parameter)

Parametri

field

value

boost

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::addBoostQuery() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
    ->addBoostQuery('cat', 'clothing', 2)
    ->addBoostQuery('cat', 'electronics', 5.1)
;
echo $dismaxQuery.PHP_EOL;
?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&bq=cat:clothing^2 cat:electronics^5.1

A se vedea ?i

  • SolrDisMaxQuery::removeBoostQuery() - Removes a boost query partial by field name (bq)
  • SolrDisMaxQuery::setBoostQuery() - Directly Sets Boost Query Parameter (bq)
SolrDisMaxQuery::addBigramPhraseField
SolrDisMaxQuery::addPhraseField
SolrDisMaxQuery


Adds a Phrase Field (pf parameter)

SolrDisMaxQuery::addBoostQuery
SolrDisMaxQuery::addQueryField
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::addPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::addPhraseField — Adds a Phrase Field (pf parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::addPhraseField ( string $field , string $boost [, string $slop ] )

Adds a Phrase Field (pf parameter)

Parametri

field

field name

boost

slop

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::addPhraseField() example

<?php
$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
    ->addPhraseField('cat', 3, 1)
    ->addPhraseField('third', 4, 2)
    ->addPhraseField('source', 55)
;
echo $dismaxQuery;
?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&pf=cat~1^3 third~2^4 source^55

A se vedea ?i

  • SolrDisMaxQuery::removePhraseField() - Removes a Phrase Field (pf parameter)
  • SolrDisMaxQuery::setPhraseFields() - Sets Phrase Fields and their boosts (and slops) using pf2 parameter
SolrDisMaxQuery::addBoostQuery
SolrDisMaxQuery::addQueryField
SolrDisMaxQuery


Add a query field with optional boost (qf parameter)

SolrDisMaxQuery::addPhraseField
SolrDisMaxQuery::addTrigramPhraseField
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::addQueryField

(No version information available, might only be in Git)

SolrDisMaxQuery::addQueryField — Add a query field with optional boost (qf parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::addQueryField ( string $field [, string $boost ] )

Add a query field with optional boost (qf parameter)

Parametri

field

field name

boost

Boost value. Boosts documents with matching terms.

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::addQueryField() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
    ->addQueryField("location", 4)
    ->addQueryField("price")
    ->addQueryField("sku")
    ->addQueryField("title",3.4)
;
echo $dismaxQuery;

?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&qf=location^4 price sku title^3.4

A se vedea ?i

  • SolrDisMaxQuery::removeQueryField() - Removes a Query Field (qf parameter)
SolrDisMaxQuery::addPhraseField
SolrDisMaxQuery::addTrigramPhraseField
SolrDisMaxQuery


Adds a Trigram Phrase Field (pf3 parameter)

SolrDisMaxQuery::addQueryField
SolrDisMaxQuery::addUserField
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::addTrigramPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::addTrigramPhraseField — Adds a Trigram Phrase Field (pf3 parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::addTrigramPhraseField ( string $field , string $boost [, string $slop ] )

Adds a Trigram Phrase Field (pf3 parameter)

Parametri

field

Field Name

boost

Field Boost

slop

Field Slop

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::addTrigramPhraseField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addTrigramPhraseField('cat', 2, 5.1)
->addTrigramPhraseField('feature', 4.5)
;
echo $dismaxQuery.PHP_EOL;

?>

Exemplul de mai sus va afi?a:

q=lucene&defType=%s&pf3=cat~5.1^2 feature^4.5

A se vedea ?i

  • SolrDisMaxQuery::removeTrigramPhraseField() - Removes a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields() - Directly Sets Trigram Phrase Fields (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseSlop() - Sets Trigram Phrase Slop (ps3 parameter)
SolrDisMaxQuery::addQueryField
SolrDisMaxQuery::addUserField
SolrDisMaxQuery


Adds a field to User Fields Parameter (uf)

SolrDisMaxQuery::addTrigramPhraseField
SolrDisMaxQuery::__construct
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::addUserField

(No version information available, might only be in Git)

SolrDisMaxQuery::addUserField — Adds a field to User Fields Parameter (uf)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::addUserField ( string $field )

Adds a field to The User Fields Parameter (uf)

Parametri

field

Field Name

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::addUserField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addUserField('cat')
->addUserField('text')
->addUserField('*_dt');

echo $dismaxQuery.PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&uf=cat text *_dt

A se vedea ?i

  • SolrDisMaxQuery::removeUserField() - Removes a field from The User Fields Parameter (uf)
  • SolrDisMaxQuery::setUserFields() - Sets User Fields parameter (uf)
SolrDisMaxQuery::addTrigramPhraseField
SolrDisMaxQuery::__construct
SolrDisMaxQuery


Class Constructor

SolrDisMaxQuery::addUserField
SolrDisMaxQuery::removeBigramPhraseField
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::__construct

(No version information available, might only be in Git)

SolrDisMaxQuery::__construct — Class Constructor

Descrierea

public SolrDisMaxQuery::__construct ([ string $q ] )

Class constructor initializes the object and sets the q parameter if passed

Parametri

q

Search Query (q parameter)

Valorile întoarse

Erori/Excep?ii

Emits SolrIllegalArgumentException in case of an invalid parameter was passed.

Exemple

Example #1 SolrDisMaxQuery::__construct() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
echo $dismaxQuery;

?>

Exemplul de mai sus va afi?a:

q=lucene&defType=edismax

A se vedea ?i

SolrDisMaxQuery::addUserField
SolrDisMaxQuery::removeBigramPhraseField
SolrDisMaxQuery


Removes phrase bigram field (pf2 parameter)

SolrDisMaxQuery::__construct
SolrDisMaxQuery::removeBoostQuery
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::removeBigramPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::removeBigramPhraseField — Removes phrase bigram field (pf2 parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::removeBigramPhraseField ( string $field )

Removes a Bigram Phrase Field (pf2 parameter) that was previously added using SolrDisMaxQuery::addBigramPhraseField()

Parametri

field

The Field Name

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::removeBigramPhraseField() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
    ->addBigramPhraseField('cat', 2, 5.1)
    ->addBigramPhraseField('feature', 4.5)
;
echo $dismaxQuery.PHP_EOL;

// remove cat from pf2
$dismaxQuery
    ->removeBigramPhraseField('cat');
echo $dismaxQuery.PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&pf2=cat~5.1^2 feature^4.5
q=lucene&defType=edismax&pf2=feature^4.5

A se vedea ?i

  • SolrDisMaxQuery::addBigramPhraseField() - Adds a Phrase Bigram Field (pf2 parameter)
  • SolrDisMaxQuery::setBigramPhraseFields() - Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
  • SolrDisMaxQuery::setBigramPhraseSlop() - Sets Bigram Phrase Slop (ps2 parameter)
SolrDisMaxQuery::__construct
SolrDisMaxQuery::removeBoostQuery
SolrDisMaxQuery


Removes a boost query partial by field name (bq)

SolrDisMaxQuery::removeBigramPhraseField
SolrDisMaxQuery::removePhraseField
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::removeBoostQuery

(No version information available, might only be in Git)

SolrDisMaxQuery::removeBoostQuery — Removes a boost query partial by field name (bq)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::removeBoostQuery ( string $field )

Removes a boost query partial from the existing query, only if SolrDisMaxQuery::addBoostQuery() was used.

Parametri

field

Field Name

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::removeBoostQuery() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
    ->addBoostQuery('cat', 'electronics', 5.1)
    ->addBoostQuery('cat', 'hard drive')
;
echo $dismaxQuery.PHP_EOL;
// now remove a query part with field 'cat'
$dismaxQuery
->removeBoostQuery('cat');
echo $dismaxQuery . PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&bq=cat:electronics^5.1 cat:hard drive
q=lucene&defType=edismax&bq=cat:hard drive

A se vedea ?i

  • SolrDisMaxQuery::addBoostQuery() - Adds a boost query field with value and optional boost (bq parameter)
  • SolrDisMaxQuery::setBoostQuery() - Directly Sets Boost Query Parameter (bq)
SolrDisMaxQuery::removeBigramPhraseField
SolrDisMaxQuery::removePhraseField
SolrDisMaxQuery


Removes a Phrase Field (pf parameter)

SolrDisMaxQuery::removeBoostQuery
SolrDisMaxQuery::removeQueryField
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::removePhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::removePhraseField — Removes a Phrase Field (pf parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::removePhraseField ( string $field )

Removes a Phrase Field (pf parameter) that was previously added using SolrDisMaxQuery::addPhraseField

Parametri

field

Field Name

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::removePhraseField() example

<?php
$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
    ->addPhraseField('first', 3, 1)
    ->addPhraseField('second', 4, 1)
    ->addPhraseField('cat', 55);
echo $dismaxQuery . PHP_EOL;
echo $dismaxQuery->removePhraseField('second');
?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&pf=first~1^3 second~1^4 cat^55
q=lucene&defType=edismax&pf=first~1^3 cat^55

A se vedea ?i

  • SolrDisMaxQuery::addPhraseField() - Adds a Phrase Field (pf parameter)
  • SolrDisMaxQuery::setPhraseFields() - Sets Phrase Fields and their boosts (and slops) using pf2 parameter
SolrDisMaxQuery::removeBoostQuery
SolrDisMaxQuery::removeQueryField
SolrDisMaxQuery


Removes a Query Field (qf parameter)

SolrDisMaxQuery::removePhraseField
SolrDisMaxQuery::removeTrigramPhraseField
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::removeQueryField

(No version information available, might only be in Git)

SolrDisMaxQuery::removeQueryField — Removes a Query Field (qf parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::removeQueryField ( string $field )

Removes a Query Field (qf parameter) from the field list added by SolrDisMaxQuery::addQueryField()

qf: When building DisjunctionMaxQueries from the user's query it specifies the fields to search in, and boosts for those fields.

Parametri

field

Field Name

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::removeQueryField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
    ->addQueryField('first', 3)
    ->addQueryField('second', 0.2)
    ->addQueryField('cat');
echo $dismaxQuery . PHP_EOL;
// remove field 'second'
echo $dismaxQuery->removeQueryField('second');
?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&qf=first^3 second^0.2 cat
q=lucene&defType=edismax&qf=first^3 cat

A se vedea ?i

  • SolrDisMaxQuery::addQueryField() - Add a query field with optional boost (qf parameter)
SolrDisMaxQuery::removePhraseField
SolrDisMaxQuery::removeTrigramPhraseField
SolrDisMaxQuery


Removes a Trigram Phrase Field (pf3 parameter)

SolrDisMaxQuery::removeQueryField
SolrDisMaxQuery::removeUserField
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::removeTrigramPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::removeTrigramPhraseField — Removes a Trigram Phrase Field (pf3 parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::removeTrigramPhraseField ( string $field )

Removes a Trigram Phrase Field (pf3 parameter)

Parametri

field

Field Name

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::removeTrigramPhraseField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addTrigramPhraseField('cat', 2, 5.1)
->addTrigramPhraseField('feature', 4.5)
;
echo $dismaxQuery.PHP_EOL;
// reverse
$dismaxQuery
->removeTrigramPhraseField('cat');
echo $dismaxQuery.PHP_EOL;

?>

Exemplul de mai sus va afi?a:

q=lucene&defType=%s&pf3=cat~5.1^2 feature^4.5
q=lucene&defType=%s&pf3=feature^4.5

A se vedea ?i

  • SolrDisMaxQuery::addTrigramPhraseField() - Adds a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields() - Directly Sets Trigram Phrase Fields (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseSlop() - Sets Trigram Phrase Slop (ps3 parameter)
SolrDisMaxQuery::removeQueryField
SolrDisMaxQuery::removeUserField
SolrDisMaxQuery


Removes a field from The User Fields Parameter (uf)

SolrDisMaxQuery::removeTrigramPhraseField
SolrDisMaxQuery::setBigramPhraseFields
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::removeUserField

(No version information available, might only be in Git)

SolrDisMaxQuery::removeUserField — Removes a field from The User Fields Parameter (uf)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::removeUserField ( string $field )

Removes a field from The User Fields Parameter (uf)

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

field

Field Name

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::removeUserField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addUserField('cat')
->addUserField('text')
->addUserField('*_dt')
;
echo $dismaxQuery.PHP_EOL;

// remove field named 'text'
$dismaxQuery
->removeUserField('text');
echo $dismaxQuery.PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=%s&uf=cat text *_dt
q=lucene&defType=%s&uf=cat *_dt

A se vedea ?i

  • SolrDisMaxQuery::addUserField() - Adds a field to User Fields Parameter (uf)
  • SolrDisMaxQuery::setUserFields() - Sets User Fields parameter (uf)
SolrDisMaxQuery::removeTrigramPhraseField
SolrDisMaxQuery::setBigramPhraseFields
SolrDisMaxQuery


Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter

SolrDisMaxQuery::removeUserField
SolrDisMaxQuery::setBigramPhraseSlop
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::setBigramPhraseFields

(No version information available, might only be in Git)

SolrDisMaxQuery::setBigramPhraseFields — Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::setBigramPhraseFields ( string $fields )

Sets Bigram Phrase Fields (pf2) and their boosts (and slops)

Parametri

fields

Fields boosts (slops)

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::setBigramPhraseFields() example

<?php
$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery->setBigramPhraseFields("cat~5.1^2 feature^4.5");
echo $dismaxQuery.PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&pf2=cat~5.1^2 feature^4.5

A se vedea ?i

  • SolrDisMaxQuery::setBigramPhraseSlop() - Sets Bigram Phrase Slop (ps2 parameter)
  • SolrDisMaxQuery::addBigramPhraseFields()
  • SolrDisMaxQuery::removeBigramPhraseField() - Removes phrase bigram field (pf2 parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields() - Directly Sets Trigram Phrase Fields (pf3 parameter)
SolrDisMaxQuery::removeUserField
SolrDisMaxQuery::setBigramPhraseSlop
SolrDisMaxQuery


Sets Bigram Phrase Slop (ps2 parameter)

SolrDisMaxQuery::setBigramPhraseFields
SolrDisMaxQuery::setBoostFunction
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::setBigramPhraseSlop

(No version information available, might only be in Git)

SolrDisMaxQuery::setBigramPhraseSlop — Sets Bigram Phrase Slop (ps2 parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::setBigramPhraseSlop ( string $slop )

Sets Bigram Phrase Slop (ps2 parameter). A default slop for Bigram phrase fields.

Parametri

slop

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::setBigramPhraseSlop() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');

$dismaxQuery->setBigramPhraseSlop(5);
echo $dismaxQuery.PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&ps2=5

A se vedea ?i

SolrDisMaxQuery::setBigramPhraseFields
SolrDisMaxQuery::setBoostFunction
SolrDisMaxQuery


Sets a Boost Function (bf parameter).

SolrDisMaxQuery::setBigramPhraseSlop
SolrDisMaxQuery::setBoostQuery
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::setBoostFunction

(No version information available, might only be in Git)

SolrDisMaxQuery::setBoostFunction — Sets a Boost Function (bf parameter).

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::setBoostFunction ( string $function )

Sets Boost Function (bf parameter).

Functions (with optional boosts) that will be included in the user's query to influence the score. Any function supported natively by Solr can be used, along with a boost value. e.g.:

recip(rord(myfield),1,2,3)^1.5

Parametri

function

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::setBoostFunction() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');

$boostRecentDocsFunction = "recip(ms(NOW,mydatefield),3.16e-11,1,1)";
$dismaxQuery->setBoostFunction($boostRecentDocsFunction);

echo $dismaxQuery.PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&bf=recip(ms(NOW,mydatefield),3.16e-11,1,1)

A se vedea ?i

SolrDisMaxQuery::setBigramPhraseSlop
SolrDisMaxQuery::setBoostQuery
SolrDisMaxQuery


Directly Sets Boost Query Parameter (bq)

SolrDisMaxQuery::setBoostFunction
SolrDisMaxQuery::setMinimumMatch
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::setBoostQuery

(No version information available, might only be in Git)

SolrDisMaxQuery::setBoostQuery — Directly Sets Boost Query Parameter (bq)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::setBoostQuery ( string $q )

Sets Boost Query Parameter (bq)

Parametri

q

query

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::setBoostQuery() example

<?php
$dismaxQuery = new SolrDisMaxQuery("lucene");

$dismaxQuery->setBoostQuery('cat:electronics manu:local^2');
echo $dismaxQuery.PHP_EOL;
?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&bq=cat:electronics manu:local^2

A se vedea ?i

  • SolrDisMaxQuery::addBoostQuery() - Adds a boost query field with value and optional boost (bq parameter)
  • SolrDisMaxQuery::removeBoostQuery() - Removes a boost query partial by field name (bq)
SolrDisMaxQuery::setBoostFunction
SolrDisMaxQuery::setMinimumMatch
SolrDisMaxQuery


Set Minimum "Should" Match (mm)

SolrDisMaxQuery::setBoostQuery
SolrDisMaxQuery::setPhraseFields
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::setMinimumMatch

(No version information available, might only be in Git)

SolrDisMaxQuery::setMinimumMatch — Set Minimum "Should" Match (mm)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::setMinimumMatch ( string $value )

Set Minimum "Should" Match parameter (mm). If the default query operator is AND then mm=100%, if the default query operator (q.op) is OR, then mm=0%.

Parametri

value

Minimum match value/expression

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::setMinimumMatch() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
// 75% of the query clauses must match
$dismaxQuery->setMinimumMatch("75%");
echo $dismaxQuery . PHP_EOL;

?>

Exemplul de mai sus va afi?a:

q=lucene&defType=edismax&mm=75%
SolrDisMaxQuery::setBoostQuery
SolrDisMaxQuery::setPhraseFields
SolrDisMaxQuery


Sets Phrase Fields and their boosts (and slops) using pf2 parameter

SolrDisMaxQuery::setMinimumMatch
SolrDisMaxQuery::setPhraseSlop
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::setPhraseFields

(No version information available, might only be in Git)

SolrDisMaxQuery::setPhraseFields — Sets Phrase Fields and their boosts (and slops) using pf2 parameter

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::setPhraseFields ( string $fields )

Sets Phrase Fields (pf) and their boosts (and slops)

Parametri

fields

Fields, boosts [, slops]

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::setPhraseFields() example

<?php
$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery->setPhraseFields("cat~5.1^2 feature^4.5");
echo $dismaxQuery.PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&pf=cat~5.1^2 feature^4.5

A se vedea ?i

  • SolrDisMaxQuery::addPhraseFields()
  • SolrDisMaxQuery::removePhraseField() - Removes a Phrase Field (pf parameter)
SolrDisMaxQuery::setMinimumMatch
SolrDisMaxQuery::setPhraseSlop
SolrDisMaxQuery


Sets the default slop on phrase queries (ps parameter)

SolrDisMaxQuery::setPhraseFields
SolrDisMaxQuery::setQueryAlt
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::setPhraseSlop

(No version information available, might only be in Git)

SolrDisMaxQuery::setPhraseSlop — Sets the default slop on phrase queries (ps parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::setPhraseSlop ( string $slop )

Sets the default amount of slop on phrase queries built with "pf", "pf2" and/or "pf3" fields (affects boosting). "ps" parameter

Parametri

slop

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::setPhraseSlop() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');

$dismaxQuery->setPhraseSlop(4);
echo $dismaxQuery.PHP_EOL;

?>

Exemplul de mai sus va afi?a:

q=lucene&defType=edismax&ps=4

A se vedea ?i

SolrDisMaxQuery::setPhraseFields
SolrDisMaxQuery::setQueryAlt
SolrDisMaxQuery


Set Query Alternate (q.alt parameter)

SolrDisMaxQuery::setPhraseSlop
SolrDisMaxQuery::setQueryPhraseSlop
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::setQueryAlt

(No version information available, might only be in Git)

SolrDisMaxQuery::setQueryAlt — Set Query Alternate (q.alt parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::setQueryAlt ( string $q )

Set Query Alternate (q.alt parameter)

When the main q parameter is not specified or is blank. The q.alt parameter is used

Parametri

q

Query String

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::setQueryAlt() example

<?php

$dismaxQuery = new DisMaxQuery();
$dismaxQuery->setQueryAlt('*:*');

?>

Exemplul de mai sus va afi?a ceva similar cu:

defType=edismax&q.alt=*:*&q=
SolrDisMaxQuery::setPhraseSlop
SolrDisMaxQuery::setQueryPhraseSlop
SolrDisMaxQuery


specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)

SolrDisMaxQuery::setQueryAlt
SolrDisMaxQuery::setTieBreaker
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::setQueryPhraseSlop

(No version information available, might only be in Git)

SolrDisMaxQuery::setQueryPhraseSlop — specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::setQueryPhraseSlop ( string $slop )

The Query Phrase Slop is the amount of slop permitted on phrase queries explicitly included in the user's query string with the qf parameter.

slop refers to the number of positions one token needs to be moved in relation to another token in order to match a phrase specified in a query.

Parametri

slop

Amount of slop

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::setQueryPhraseSlop() example

<?php

$dismaxQuery = new SolrDisMaxQuery();
$dismaxQuery->setQueryPhraseSlop(3);
echo $dismaxQuery;
?>

Exemplul de mai sus va afi?a ceva similar cu:

defType=edismax&qs=3
SolrDisMaxQuery::setQueryAlt
SolrDisMaxQuery::setTieBreaker
SolrDisMaxQuery


Sets Tie Breaker parameter (tie parameter)

SolrDisMaxQuery::setQueryPhraseSlop
SolrDisMaxQuery::setTrigramPhraseFields
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::setTieBreaker

(No version information available, might only be in Git)

SolrDisMaxQuery::setTieBreaker — Sets Tie Breaker parameter (tie parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::setTieBreaker ( string $tieBreaker )

Sets Tie Breaker parameter (tie parameter)

Parametri

tieBreaker

The tie parameter specifies a float value (which should be something much less than 1) to use as tiebreaker in DisMax queries.

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::setTieBreaker() example

<?php

$dismaxQuery = new SolrDisMaxQuery();
$dismaxQuery->setTieBreaker(0.1);

echo $dismaxQuery;

?>

Exemplul de mai sus va afi?a:

defType=edismax&tie=0.1
SolrDisMaxQuery::setQueryPhraseSlop
SolrDisMaxQuery::setTrigramPhraseFields
SolrDisMaxQuery


Directly Sets Trigram Phrase Fields (pf3 parameter)

SolrDisMaxQuery::setTieBreaker
SolrDisMaxQuery::setTrigramPhraseSlop
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::setTrigramPhraseFields

(No version information available, might only be in Git)

SolrDisMaxQuery::setTrigramPhraseFields — Directly Sets Trigram Phrase Fields (pf3 parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::setTrigramPhraseFields ( string $fields )

Directly Sets Trigram Phrase Fields (pf3 parameter)

Parametri

fields

Trigram Phrase Fields

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::setTrigramPhraseFields() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery->setTrigramPhraseFields('cat~5.1^2 feature^4.5');
echo $dismaxQuery.PHP_EOL;

?>

Exemplul de mai sus va afi?a:

q=lucene&defType=edismax&pf3=cat~5.1^2 feature^4.5

A se vedea ?i

  • SolrDisMaxQuery::addTrigramPhraseField() - Adds a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::removeTrigramPhraseField() - Removes a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseSlop() - Sets Trigram Phrase Slop (ps3 parameter)
SolrDisMaxQuery::setTieBreaker
SolrDisMaxQuery::setTrigramPhraseSlop
SolrDisMaxQuery


Sets Trigram Phrase Slop (ps3 parameter)

SolrDisMaxQuery::setTrigramPhraseFields
SolrDisMaxQuery::setUserFields
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::setTrigramPhraseSlop

(No version information available, might only be in Git)

SolrDisMaxQuery::setTrigramPhraseSlop — Sets Trigram Phrase Slop (ps3 parameter)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::setTrigramPhraseSlop ( string $slop )

Sets Trigram Phrase Slop (ps3 parameter)

Parametri

slop

Phrase slop

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::setTrigramPhraseSlop() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery->setTrigramPhraseSlop(2);
echo $dismaxQuery.PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&ps3=2

A se vedea ?i

  • SolrDisMaxQuery::addTrigramPhraseField() - Adds a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::removeTrigramPhraseField() - Removes a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields() - Directly Sets Trigram Phrase Fields (pf3 parameter)
SolrDisMaxQuery::setTrigramPhraseFields
SolrDisMaxQuery::setUserFields
SolrDisMaxQuery


Sets User Fields parameter (uf)

SolrDisMaxQuery::setTrigramPhraseSlop
SolrDisMaxQuery::useDisMaxQueryParser
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::setUserFields

(No version information available, might only be in Git)

SolrDisMaxQuery::setUserFields — Sets User Fields parameter (uf)

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::setUserFields ( string $fields )

Sets User Fields parameter (uf)

User Fields: Specifies which schema fields the end user shall be allowed to query.

Parametri

fields

Fields names separated by space

This parameter supports wildcards.

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::setUserFields() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery->setUserFields('field1 field2 *_txt');
echo $dismaxQuery.PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

q=lucene&defType=edismax&uf=field1 field2 *_txt

A se vedea ?i

  • SolrDisMaxQuery::addUserField() - Adds a field to User Fields Parameter (uf)
  • SolrDisMaxQuery::removeUserField() - Removes a field from The User Fields Parameter (uf)
SolrDisMaxQuery::setTrigramPhraseSlop
SolrDisMaxQuery::useDisMaxQueryParser
SolrDisMaxQuery


Switch QueryParser to be DisMax Query Parser

SolrDisMaxQuery::setUserFields
SolrDisMaxQuery::useEDisMaxQueryParser
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::useDisMaxQueryParser

(No version information available, might only be in Git)

SolrDisMaxQuery::useDisMaxQueryParser — Switch QueryParser to be DisMax Query Parser

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::useDisMaxQueryParser ( void )

Switch QueryParser to be DisMax Query Parser

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::useDisMaxQueryParser() example

<?php

$dismaxQuery = new SolrDisMaxQuery();
$dismaxQuery->useDisMaxQueryParser();
echo $dismaxQuery;
?>

Exemplul de mai sus va afi?a ceva similar cu:

defType=dismax

A se vedea ?i

  • SolrDisMaxQuery::useDisMaxQueryParser()
SolrDisMaxQuery::setUserFields
SolrDisMaxQuery::useEDisMaxQueryParser
SolrDisMaxQuery


Switch QueryParser to be EDisMax

SolrDisMaxQuery::useDisMaxQueryParser
SolrCollapseFunction
SolrDisMaxQuery
PHP Manual

SolrDisMaxQuery::useEDisMaxQueryParser

(No version information available, might only be in Git)

SolrDisMaxQuery::useEDisMaxQueryParser — Switch QueryParser to be EDisMax

Descrierea

public SolrDisMaxQuery SolrDisMaxQuery::useEDisMaxQueryParser ( void )

Switch QueryParser to be EDisMax. By default the query builder uses edismax, if it was switched using SolrDisMaxQuery::useDisMaxQueryParser(), it can be switched back using this method.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

SolrDisMaxQuery

Exemple

Example #1 SolrDisMaxQuery::useEDisMaxQueryParser() example

<?php

$dismaxQuery = new SolrDisMaxQuery();
$dismaxQuery->useEDisMaxQueryParser();
echo $dismaxQuery;

?>

Exemplul de mai sus va afi?a ceva similar cu:

defType=edismax

A se vedea ?i

SolrDisMaxQuery::useDisMaxQueryParser
SolrCollapseFunction
SolrDisMaxQuery


The SolrCollapseFunction class

(PECL solr >= 2.2.0)

Introducere

Sinopsisul clasei

SolrCollapseFunction {
/* Constants */
const string NULLPOLICY_IGNORE = ignore ;
const string NULLPOLICY_EXPAND = expand ;
const string NULLPOLICY_COLLAPSE = collapse ;
/* Metode */
public __construct ([ string $field ] )
public string getField ( void )
public string getHint ( void )
public string getMax ( void )
public string getMin ( void )
public string getNullPolicy ( void )
public integer getSize ( void )
public SolrCollapseFunction setField ( string $fieldName )
public SolrCollapseFunction setHint ( string $hint )
public SolrCollapseFunction setMax ( string $max )
public SolrCollapseFunction setMin ( string $min )
public SolrCollapseFunction setNullPolicy ( string $nullPolicy )
public SolrCollapseFunction setSize ( integer $size )
public string __toString ( void )
}

Constante predefinite

SolrCollapseFunction::NULLPOLICY_IGNORE

SolrCollapseFunction::NULLPOLICY_EXPAND

SolrCollapseFunction::NULLPOLICY_COLLAPSE

Cuprins

  • SolrCollapseFunction::__construct — Constructor
  • SolrCollapseFunction::getField — Returns the field that is being collapsed on.
  • SolrCollapseFunction::getHint — Returns collapse hint
  • SolrCollapseFunction::getMax — Returns max parameter
  • SolrCollapseFunction::getMin — Returns min parameter
  • SolrCollapseFunction::getNullPolicy — Returns null policy
  • SolrCollapseFunction::getSize — Returns size parameter
  • SolrCollapseFunction::setField — Sets the field to collapse on
  • SolrCollapseFunction::setHint — Sets collapse hint
  • SolrCollapseFunction::setMax — Selects the group heads by the max value of a numeric field or function query.
  • SolrCollapseFunction::setMin — Sets the initial size of the collapse data structures when collapsing on a numeric field only
  • SolrCollapseFunction::setNullPolicy — Sets the NULL Policy
  • SolrCollapseFunction::setSize — Sets the initial size of the collapse data structures when collapsing on a numeric field only.
  • SolrCollapseFunction::__toString — Returns a string representing the constructed collapse function
SolrDisMaxQuery::useEDisMaxQueryParser
SolrCollapseFunction::__construct
Solr


Constructor

SolrCollapseFunction
SolrCollapseFunction::getField
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::__construct

(PECL solr >= 2.2.0)

SolrCollapseFunction::__construct — Constructor

Descrierea

public SolrCollapseFunction::__construct ([ string $field ] )

Collapse Function constructor

Parametri

field

The field name to collapse on.

In order to collapse a result. The field type must be a single valued String, Int or Float.

Exemple

Example #1 SolrCollapseFunction::__construct() example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_SERVER_PATH
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$func = new SolrCollapseFunction('field_name');

$func->setMax('sum(cscore(),field(some_other_field))');
$func->setSize(100);
$func->setNullPolicy(SolrCollapseFunction::NULLPOLICY_EXPAND);

$query->collapse($func);

$queryResponse = $client->query($query);

$response = $queryResponse->getResponse();

print_r($response);

?>

A se vedea ?i

  • SolrQuery::collapse() - Collapses the result set to a single document per group
SolrCollapseFunction
SolrCollapseFunction::getField
SolrCollapseFunction


Returns the field that is being collapsed on.

SolrCollapseFunction::__construct
SolrCollapseFunction::getHint
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::getField

(PECL solr >= 2.2.0)

SolrCollapseFunction::getField — Returns the field that is being collapsed on.

Descrierea

public string SolrCollapseFunction::getField ( void )

Returns the field that is being collapsed on.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrCollapseFunction::setField() - Sets the field to collapse on
SolrCollapseFunction::__construct
SolrCollapseFunction::getHint
SolrCollapseFunction


Returns collapse hint

SolrCollapseFunction::getField
SolrCollapseFunction::getMax
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::getHint

(PECL solr >= 2.2.0)

SolrCollapseFunction::getHint — Returns collapse hint

Descrierea

public string SolrCollapseFunction::getHint ( void )

Returns collapse hint

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrCollapseFunction::setHint() - Sets collapse hint
SolrCollapseFunction::getField
SolrCollapseFunction::getMax
SolrCollapseFunction


Returns max parameter

SolrCollapseFunction::getHint
SolrCollapseFunction::getMin
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::getMax

(PECL solr >= 2.2.0)

SolrCollapseFunction::getMax — Returns max parameter

Descrierea

public string SolrCollapseFunction::getMax ( void )

Returns max parameter

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrCollapseFunction::setMax() - Selects the group heads by the max value of a numeric field or function query.
SolrCollapseFunction::getHint
SolrCollapseFunction::getMin
SolrCollapseFunction


Returns min parameter

SolrCollapseFunction::getMax
SolrCollapseFunction::getNullPolicy
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::getMin

(PECL solr >= 2.2.0)

SolrCollapseFunction::getMin — Returns min parameter

Descrierea

public string SolrCollapseFunction::getMin ( void )

Returns min parameter

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrCollapseFunction::setMin() - Sets the initial size of the collapse data structures when collapsing on a numeric field only
SolrCollapseFunction::getMax
SolrCollapseFunction::getNullPolicy
SolrCollapseFunction


Returns null policy

SolrCollapseFunction::getMin
SolrCollapseFunction::getSize
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::getNullPolicy

(PECL solr >= 2.2.0)

SolrCollapseFunction::getNullPolicy — Returns null policy

Descrierea

public string SolrCollapseFunction::getNullPolicy ( void )

Returns null policy used or null

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrCollapseFunction::setNullPolicy() - Sets the NULL Policy
SolrCollapseFunction::getMin
SolrCollapseFunction::getSize
SolrCollapseFunction


Returns size parameter

SolrCollapseFunction::getNullPolicy
SolrCollapseFunction::setField
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::getSize

(PECL solr >= 2.2.0)

SolrCollapseFunction::getSize — Returns size parameter

Descrierea

public integer SolrCollapseFunction::getSize ( void )

Gets the initial size of the collapse data structures when collapsing on a numeric field only

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • SolrCollapseFunction::setSize() - Sets the initial size of the collapse data structures when collapsing on a numeric field only.
SolrCollapseFunction::getNullPolicy
SolrCollapseFunction::setField
SolrCollapseFunction


Sets the field to collapse on

SolrCollapseFunction::getSize
SolrCollapseFunction::setHint
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::setField

(PECL solr >= 2.2.0)

SolrCollapseFunction::setField — Sets the field to collapse on

Descrierea

public SolrCollapseFunction SolrCollapseFunction::setField ( string $fieldName )

The field name to collapse on. In order to collapse a result. The field type must be a single valued String, Int or Float.

Parametri

fieldName

Valorile întoarse

SolrCollapseFunction

SolrCollapseFunction::getSize
SolrCollapseFunction::setHint
SolrCollapseFunction


Sets collapse hint

SolrCollapseFunction::setField
SolrCollapseFunction::setMax
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::setHint

(PECL solr >= 2.2.0)

SolrCollapseFunction::setHint — Sets collapse hint

Descrierea

public SolrCollapseFunction SolrCollapseFunction::setHint ( string $hint )

Sets collapse hint

Parametri

hint

Currently there is only one hint available "top_fc", which stands for top level FieldCache

Valorile întoarse

SolrCollapseFunction

Exemple

Example #1 SolrCollapseFunction::setHint() example

<?php

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...
SolrCollapseFunction::setField
SolrCollapseFunction::setMax
SolrCollapseFunction


Selects the group heads by the max value of a numeric field or function query.

SolrCollapseFunction::setHint
SolrCollapseFunction::setMin
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::setMax

(PECL solr >= 2.2.0)

SolrCollapseFunction::setMax — Selects the group heads by the max value of a numeric field or function query.

Descrierea

public SolrCollapseFunction SolrCollapseFunction::setMax ( string $max )

Selects the group heads by the max value of a numeric field or function query.

Parametri

max

Valorile întoarse

SolrCollapseFunction

Exemple

Example #1 SolrCollapseFunction::setMax() example

<?php

$func = new SolrCollapseFunction('field_name');

$func->setMax('sum(cscore(),field(some_field))');

$query = new SolrQuery('*:*');

$query->collapse($func);

?>
SolrCollapseFunction::setHint
SolrCollapseFunction::setMin
SolrCollapseFunction


Sets the initial size of the collapse data structures when collapsing on a numeric field only

SolrCollapseFunction::setMax
SolrCollapseFunction::setNullPolicy
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::setMin

(PECL solr >= 2.2.0)

SolrCollapseFunction::setMin — Sets the initial size of the collapse data structures when collapsing on a numeric field only

Descrierea

public SolrCollapseFunction SolrCollapseFunction::setMin ( string $min )

Sets the initial size of the collapse data structures when collapsing on a numeric field only

Parametri

min

Valorile întoarse

SolrCollapseFunction

SolrCollapseFunction::setMax
SolrCollapseFunction::setNullPolicy
SolrCollapseFunction


Sets the NULL Policy

SolrCollapseFunction::setMin
SolrCollapseFunction::setSize
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::setNullPolicy

(PECL solr >= 2.2.0)

SolrCollapseFunction::setNullPolicy — Sets the NULL Policy

Descrierea

public SolrCollapseFunction SolrCollapseFunction::setNullPolicy ( string $nullPolicy )

Sets the NULL Policy. One of the 3 policies defined as class constants shall be passed. Accepts ignore, expand, or collapse policies.

Parametri

nullPolicy

Valorile întoarse

SolrCollapseFunction

SolrCollapseFunction::setMin
SolrCollapseFunction::setSize
SolrCollapseFunction


Sets the initial size of the collapse data structures when collapsing on a numeric field only.

SolrCollapseFunction::setNullPolicy
SolrCollapseFunction::__toString
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::setSize

(PECL solr >= 2.2.0)

SolrCollapseFunction::setSize — Sets the initial size of the collapse data structures when collapsing on a numeric field only.

Descrierea

public SolrCollapseFunction SolrCollapseFunction::setSize ( integer $size )

Sets the initial size of the collapse data structures when collapsing on a numeric field only.

Parametri

size

Valorile întoarse

SolrCollapseFunction

SolrCollapseFunction::setNullPolicy
SolrCollapseFunction::__toString
SolrCollapseFunction


Returns a string representing the constructed collapse function

SolrCollapseFunction::setSize
SolrException
SolrCollapseFunction
PHP Manual

SolrCollapseFunction::__toString

(PECL solr >= 2.2.0)

SolrCollapseFunction::__toString — Returns a string representing the constructed collapse function

Descrierea

public string SolrCollapseFunction::__toString ( void )

Returns a string representing the constructed collapse function

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

SolrCollapseFunction::setSize
SolrException
SolrCollapseFunction


The SolrException class

(PECL solr >= 0.9.2)

Introducere

This is the base class for all exception thrown by the Solr extension classes.

Sinopsisul clasei

SolrException extends Exception {
/* Proprieta?i */
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode */
public array getInternalInfo ( void )
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Proprieta?i

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

Cuprins

  • SolrException::getInternalInfo — Returns internal information where the Exception was thrown
SolrCollapseFunction::__toString
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

Descrierea

public array SolrException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

SolrException
SolrClientException
SolrException


The SolrClientException class

(PECL solr >= 0.9.2)

Introducere

An exception thrown when there is an error while making a request to the server from the client.

Sinopsisul clasei

SolrClientException extends SolrException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Metode */
public array getInternalInfo ( void )
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
public array SolrException::getInternalInfo ( void )
}

Cuprins

  • SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown
SolrException::getInternalInfo
SolrClientException::getInternalInfo
Solr


Returns internal information where the Exception was thrown

SolrClientException
SolrServerException
SolrClientException
PHP Manual

SolrClientException::getInternalInfo

(PECL solr >= 0.9.2)

SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown

Descrierea

public array SolrClientException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

SolrClientException
SolrServerException
SolrClientException


The SolrServerException class

(PECL Solr >= 1.1.0, >=2.0.0)

Introducere

An exception thrown when there is an error produced by the Solr Server itself.

Sinopsisul clasei

SolrServerException extends SolrException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Metode */
public array getInternalInfo ( void )
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
public array SolrException::getInternalInfo ( void )
}

Cuprins

  • SolrServerException::getInternalInfo — Returns internal information where the Exception was thrown
SolrClientException::getInternalInfo
SolrServerException::getInternalInfo
Solr


Returns internal information where the Exception was thrown

SolrServerException
SolrIllegalArgumentException
SolrServerException
PHP Manual

SolrServerException::getInternalInfo

(PECL solr >= 1.1.0, >=2.0.0)

SolrServerException::getInternalInfo — Returns internal information where the Exception was thrown

Descrierea

public array SolrServerException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

SolrServerException
SolrIllegalArgumentException
SolrServerException


The SolrIllegalArgumentException class

(PECL solr >= 0.9.2)

Introducere

This object is thrown when an illeglal or invalid argument is passed to a method.

Sinopsisul clasei

SolrIllegalArgumentException extends SolrException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Metode */
public array getInternalInfo ( void )
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
public array SolrException::getInternalInfo ( void )
}

Cuprins

  • SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown
SolrServerException::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

Descrierea

public array SolrIllegalArgumentException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

SolrIllegalArgumentException
SolrIllegalOperationException
SolrIllegalArgumentException


The SolrIllegalOperationException class

(PECL solr >= 0.9.2)

Introducere

This object is thrown when an illegal or unsupported operation is performed on an object.

Sinopsisul clasei

SolrIllegalOperationException extends SolrException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Metode */
public array getInternalInfo ( void )
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
public array SolrException::getInternalInfo ( void )
}

Cuprins

  • SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown
SolrIllegalArgumentException::getInternalInfo
SolrIllegalOperationException::getInternalInfo
Solr


Returns internal information where the Exception was thrown

SolrIllegalOperationException
SolrMissingMandatoryParameterException
SolrIllegalOperationException
PHP Manual

SolrIllegalOperationException::getInternalInfo

(PECL solr >= 0.9.2)

SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown

Descrierea

public array SolrIllegalOperationException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

SolrIllegalOperationException
SolrMissingMandatoryParameterException
SolrIllegalOperationException


The SolrMissingMandatoryParameterException class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

SolrMissingMandatoryParameterException extends SolrException {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
public array SolrException::getInternalInfo ( void )
}
SolrIllegalOperationException::getInternalInfo
Sphinx
Solr


Sphinx Client

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • 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
SolrMissingMandatoryParameterException
Introducere
Extensii ale motorului de cautare


Introducere

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
Instalarea / configurarea
Sphinx


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Sphinx


Necesita?i

PECL/sphinx requires PHP 5.2.2 or newer.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » 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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)

Tipurile resurselor
Exemple
Sphinx


Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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)
    }
  }
}
Constante predefinite
SphinxClient
Sphinx


The SphinxClient class

(PECL sphinx >= 0.1.0)

Introducere

The SphinxClient class provides object-oriented interface to Sphinx.

Sinopsisul clasei

SphinxClient {
/* Metode */
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 ] )
}

Cuprins

  • 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
Exemple
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

Descrierea

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.

Parametri

query

Query string.

index

An index name (or names).

comment

Valorile întoarse

Returns an index in an array of results that will be returned by SphinxClient::runQueries call or false on error.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns array of snippets on success sau FALSE în cazul e?ecului.

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

Descrierea

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.

Parametri

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.

Valorile întoarse

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

Descrierea

public bool SphinxClient::close ( void )

Closes previously opened persistent connection.

Parametri

Aceasta func?ie nu are parametri.

Istoricul schimbarilor

PECL/sphinx Versiune | Descriere
1.0.3 | Added SphinxClient::close(), available only if compiled with libsphinxclient >= 0.9.9.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public SphinxClient::__construct ( void )

Creates a new SphinxClient object.

Parametri

Aceasta func?ie nu are parametri.

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

Descrierea

public string SphinxClient::escapeString ( string $string )

Escapes characters that are treated as special operators by the query language parser.

Parametri

string

String to escape.

Valorile întoarse

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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the last error message or an empty string if there were no errors.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the last warning message or an empty string if there were no warnings.

A se vedea ?i

  • 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

Descrierea

public bool SphinxClient::open ( void )

Opens persistent connection to the server.

Parametri

Aceasta func?ie nu are parametri.

Istoricul schimbarilor

PECL/sphinx Versiune | Descriere
1.0.3 | Added SphinxClient::open(), available only if compiled with libsphinxclient >= 0.9.9.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

query

Query string.

index

An index name (or names).

comment

Valorile întoarse

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

A se vedea ?i

  • 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

Descrierea

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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

Descrierea

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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

Descrierea

public array SphinxClient::runQueries ( void )

Connects to searchd, runs a batch of all queries added using SphinxClient::addQuery, obtains and returns the result sets.

Valorile întoarse

Returns FALSE on failure and array of result sets on success.

A se vedea ?i

  • 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

Descrierea

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).

Parametri

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.

Valorile întoarse

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

Descrierea

public bool SphinxClient::setConnectTimeout ( float $timeout )

Sets connection timeout (in seconds) for searchd connection.

Parametri

timeout

Timeout in seconds.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

weights

Associative array of field names and field weights.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public bool SphinxClient::setFilter ( string $attribute , array $values [, bool $exclude = false ] )

Adds new integer values set filter to the existing list of filters.

Parametri

attribute

An attribute name.

values

Plain array of integer values.

exclude

If set to TRUE, matching documents are excluded from the result set.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

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).

Parametri

attribute

An attribute name.

min

Minimum value.

max

Maximum value.

exclude

If set to TRUE, matching documents are excluded from the result set.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

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).

Parametri

attribute

An attribute name.

min

Minimum value.

max

Maximum value.

exclude

If set to TRUE, matching documents are excluded from the result set.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

attrlat

Name of a latitude attribute.

attrlong

Name of a longitude attribute.

latitude

Anchor latitude in radians.

longitude

Anchor longitude in radians.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

attribute

A string containing group-by attribute name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

min

Minimum ID value.

max

Maximum ID value.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public bool SphinxClient::setIndexWeights ( array $weights )

Sets per-index weights and enables weighted summing of match weights across different indexes.

Parametri

weights

An associative array mapping string index names to integer weights. Default is empty array, i.e. weighting summing is disabled.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

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).

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

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.

Parametri

mode

Matching mode.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public bool SphinxClient::setMaxQueryTime ( int $qtime )

Sets maximum search query time.

Parametri

qtime

Maximum query time, in milliseconds. It must be a non-negative integer. Default value is 0, i.e. no limit.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

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

Parametri

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.

Istoricul schimbarilor

PECL/sphinx Versiune | Descriere
1.0.3 | Added SphinxClient::setOverride(), available only if compiled with libsphinxclient >= 0.9.9.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

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.

Parametri

ranker

Ranking mode.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

count

Number of retries.

delay

Delay between retries, in milliseconds.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public bool SphinxClient::setSelect ( string $clause )

Sets the select clause, listing specific attributes to fetch, and expressions to compute and fetch.

Parametri

clause

SQL-like clause.

Istoricul schimbarilor

PECL/sphinx Versiune | Descriere
1.0.1 | Added SphinxClient::setSelect(), available only if compiled with libsphinxclient >= 0.9.9.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

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.

Parametri

server

IP or hostname.

port

Port number.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

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.

Parametri

mode

Sorting mode.

sortby

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

public array SphinxClient::status ( void )

Queries searchd status, and returns an array of status variable name and value pairs.

Parametri

Aceasta func?ie nu are parametri.

Istoricul schimbarilor

PECL/sphinx Versiune | Descriere
1.0.3 | Added SphinxClient::status(), available only if compiled with libsphinxclient >= 0.9.9.

Valorile întoarse

Returns an associative array of search server statistics sau FALSE în cazul e?ecului.

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

Descrierea

public int SphinxClient::updateAttributes ( string $index , array $attributes , array $values [, bool $mva = false ] )

Instantly updates given attribute values in given documents.

Parametri

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.

Valorile întoarse

Returns number of actually updated documents (0 or more) on success, or FALSE on failure.

SphinxClient::status
Swish
SphinxClient


Swish Indexing

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic usage
  • Func?ii swish
    • 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
Introducere
Extensii ale motorului de cautare


Introducere

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.

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

Swish
Instalarea / configurarea
Swish


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Swish


Necesita?i

PECL/swish requires PHP 5.1.3 or newer.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/swish.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
Tipurile resurselor
Exemple
Swish


Exemple

Cuprins

  • Basic usage
Constante predefinite
Basic usage
Swish


Basic usage

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

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)
}
Exemple
Func?ii swish
Exemple


Func?ii swish

Cuprins

  • 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

Func?ii swish
Swish::getMetaList
Func?ii swish
PHP Manual

Swish::__construct

(PECL swish >= 0.1.0)

Swish::__construct — Construct a Swish object

Descrierea

void Swish::__construct ( string $index_names )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

index_names

The list of index files separated by spaces.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws SwishException on error.

Exemple

Example #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"]);
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(6) "index1"
int(1888)
string(6) "index2"
int(2429)

Func?ii swish
Swish::getMetaList
Func?ii swish


Get the list of meta entries for the index

Swish::__construct
Swish::getPropertyList
Func?ii swish
PHP Manual

Swish::getMetaList

(PECL swish >= 0.1.0)

Swish::getMetaList — Get the list of meta entries for the index

Descrierea

array Swish::getMetaList ( string $index_name )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

index_name

The name of the index file.

Valorile întoarse

Returns an array of meta entries for the given index.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [0]=>
  array(3) {
    ["Name"]=>
    string(12) "swishdefault"
    ["Type"]=>
    int(0)
    ["ID"]=>
    int(1)
  }
}

Swish::__construct
Swish::getPropertyList
Func?ii swish


Get the list of properties for the index

Swish::getMetaList
Swish::prepare
Func?ii swish
PHP Manual

Swish::getPropertyList

(PECL swish >= 0.1.0)

Swish::getPropertyList — Get the list of properties for the index

Descrierea

array Swish::getPropertyList ( string $index_name )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

index_name

The name of the index file.

Valorile întoarse

Returns an array of properties for the given index.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

swishreccount
swishrank
swishfilenum
swishdbfile
swishdocpath
swishtitle
swishdocsize
swishlastmodified

Swish::getMetaList
Swish::prepare
Func?ii swish


Prepare a search query

Swish::getPropertyList
Swish::query
Func?ii swish
PHP Manual

Swish::prepare

(PECL swish >= 0.1.0)

Swish::prepare — Prepare a search query

Descrierea

object Swish::prepare ([ string $query ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Prepare and return a search object, which you can later use for unlimited number of queries.

Parametri

query

Optional query string. The query can be also set using SwishSearch::execute() method.

Valorile întoarse

Returns SwishSearch object.

Erori/Excep?ii

Throws SwishException on error.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

Found: 2 hits
Found: 5 hits

Swish::getPropertyList
Swish::query
Func?ii swish


Execute a query and return results object

Swish::prepare
SwishResult::getMetaList
Func?ii swish
PHP Manual

Swish::query

(PECL swish >= 0.1.0)

Swish::query — Execute a query and return results object

Descrierea

object Swish::query ( string $query )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

A quick method to execute a search with default parameters.

Parametri

query

Query string.

Valorile întoarse

Returns SwishResults object.

Erori/Excep?ii

Throws SwishException on error.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

Found: 1 hits

Swish::prepare
SwishResult::getMetaList
Func?ii swish


Get a list of meta entries

Swish::query
SwishResult::stem
Func?ii swish
PHP Manual

SwishResult::getMetaList

(PECL swish >= 0.1.0)

SwishResult::getMetaList — Get a list of meta entries

Descrierea

array SwishResult::getMetaList ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Valorile întoarse

Returns the same array as swish::getmetalist(), but uses the index file from the result handle.

Swish::query
SwishResult::stem
Func?ii swish


Stems the given word

SwishResult::getMetaList
SwishResults::getParsedWords
Func?ii swish
PHP Manual

SwishResult::stem

(PECL swish >= 0.1.0)

SwishResult::stem — Stems the given word

Descrierea

array SwishResult::stem ( string $word )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

word

The word to stem.

Valorile întoarse

Returns array containing the stemmed word variants (usually just one).

Erori/Excep?ii

Throws SwishException on error.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [0]=>
  string(4) "test"
}
array(1) {
  [0]=>
  string(5) "other"
}

SwishResult::getMetaList
SwishResults::getParsedWords
Func?ii swish


Get an array of parsed words

SwishResult::stem
SwishResults::getRemovedStopwords
Func?ii swish
PHP Manual

SwishResults::getParsedWords

(PECL swish >= 0.1.0)

SwishResults::getParsedWords — Get an array of parsed words

Descrierea

array SwishResults::getParsedWords ( string $index_name )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

indexi_name

The name of the index used to initialize Swish object.

Valorile întoarse

An array of parsed words with stopwords removed. The list of parsed words may be useful for highlighting search terms in the results.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
Func?ii swish


Get an array of stopwords removed from the query

SwishResults::getParsedWords
SwishResults::nextResult
Func?ii swish
PHP Manual

SwishResults::getRemovedStopwords

(PECL swish >= 0.1.0)

SwishResults::getRemovedStopwords — Get an array of stopwords removed from the query

Descrierea

array SwishResults::getRemovedStopwords ( string $index_name )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

index_name

The name of the index used to initialize Swish object.

Valorile întoarse

Returns array of stopwords removed from the query.

SwishResults::getParsedWords
SwishResults::nextResult
Func?ii swish


Get the next search result

SwishResults::getRemovedStopwords
SwishResults::seekResult
Func?ii swish
PHP Manual

SwishResults::nextResult

(PECL swish >= 0.1.0)

SwishResults::nextResult — Get the next search result

Descrierea

object SwishResults::nextResult ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Valorile întoarse

Returns the next SwishResult object in the result set or FALSE if there are no more results available.

Exemple

Example #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
Func?ii swish


Set current seek pointer to the given position

SwishResults::nextResult
SwishSearch::execute
Func?ii swish
PHP Manual

SwishResults::seekResult

(PECL swish >= 0.1.0)

SwishResults::seekResult — Set current seek pointer to the given position

Descrierea

int SwishResults::seekResult ( int $position )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

position

Zero-based position number. Cannot be less than zero.

Valorile întoarse

Returns new position value on success.

Erori/Excep?ii

Throws SwishException on error.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(0)
Error: No more results

SwishResults::nextResult
SwishSearch::execute
Func?ii swish


Execute the search and get the results

SwishResults::seekResult
SwishSearch::resetLimit
Func?ii swish
PHP Manual

SwishSearch::execute

(PECL swish >= 0.1.0)

SwishSearch::execute — Execute the search and get the results

Descrierea

object SwishSearch::execute ([ string $query ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Searches the index file(s) based on the parameters set in the search object.

Parametri

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.

Valorile întoarse

Returns SwishResults object.

Erori/Excep?ii

Throws SwishException on error.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

First query found: 2 hits
Second query found: 12 hits

SwishResults::seekResult
SwishSearch::resetLimit
Func?ii swish


Reset the search limits

SwishSearch::execute
SwishSearch::setLimit
Func?ii swish
PHP Manual

SwishSearch::resetLimit

(PECL swish >= 0.1.0)

SwishSearch::resetLimit — Reset the search limits

Descrierea

void SwishSearch::resetLimit ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Reset the search limits previous set by SwishSearch::setLimit.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

First query found: 5 hits
Second query found: 2 hits
Third query found: 5 hits

SwishSearch::execute
SwishSearch::setLimit
Func?ii swish


Set the search limits

SwishSearch::resetLimit
SwishSearch::setPhraseDelimiter
Func?ii swish
PHP Manual

SwishSearch::setLimit

(PECL swish >= 0.1.0)

SwishSearch::setLimit — Set the search limits

Descrierea

void SwishSearch::setLimit ( string $property , string $low , string $high )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

property

Search result property name.

low

The lowest value of the property.

high

The highest value of the property.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws SwishException on error.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
Func?ii swish


Set the phrase delimiter

SwishSearch::setLimit
SwishSearch::setSort
Func?ii swish
PHP Manual

SwishSearch::setPhraseDelimiter

(PECL swish >= 0.1.0)

SwishSearch::setPhraseDelimiter — Set the phrase delimiter

Descrierea

void SwishSearch::setPhraseDelimiter ( string $delimiter )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

delimiter

Phrase delimiter character. The default delimiter is double-quotes.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
Func?ii swish


Set the sort order

SwishSearch::setPhraseDelimiter
SwishSearch::setStructure
Func?ii swish
PHP Manual

SwishSearch::setSort

(PECL swish >= 0.1.0)

SwishSearch::setSort — Set the sort order

Descrierea

void SwishSearch::setSort ( string $sort )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

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
Func?ii swish


Set the structure flag in the search object

SwishSearch::setSort
Extensii specifice serverului
Func?ii swish
PHP Manual

SwishSearch::setStructure

(PECL swish >= 0.1.0)

SwishSearch::setStructure — Set the structure flag in the search object

Descrierea

void SwishSearch::setStructure ( int $structure )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

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

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

First query found: 5 hits
Second query found: 0 hits
Third query found: 5 hits

SwishSearch::setSort
Extensii specifice serverului
Func?ii swish


Extensii specifice serverului

  • Apache
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Apache
  • Managerul de procese FastCGI
    • Introducere
    • Instalarea / configurarea
    • Func?ii FPM
  • IIS — IIS Administration
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii IIS
  • NSAPI
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • NSAPI Func?ii
SwishSearch::setStructure
Apache
Informa?ii de referin?a despre func?ii


Apache

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Apache
    • apache_child_terminate — Termina (lichideaza) procesul apache dupa aceasta cerere
    • 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 — Efectueaza o interpelare par?iala pentru URI specificat ?i întoarce toate informa?iile despre el
    • apache_note — Ob?ine ?i stabile?te note ale interpelarilor apache
    • apache_request_headers — Fetch all HTTP request headers
    • apache_reset_timeout — Reset the Apache write timer
    • apache_response_headers — Fetch all HTTP response headers
    • apache_setenv — Stabile?te o variabila de mediu a unui subprocess Apache
    • getallheaders — Ob?ine toate antetele interpelarii HTTP
    • virtual — Efectueaza o sub-interpelare Apache
Extensii specifice serverului
Introducere
Extensii specifice serverului


Introducere

Aceste func?ii sunt disponibile doar atunci când PHP ruleaza ca modul Apache.

Nota: Începând cu PHP 4.3.2, PATH_TRANSLATED nu mai este stabilita implicit de catre SAPI al Apache 2, spre deosebire de situa?ia din Apache 1, unde ea este stabilita la aceea?i valoare ca ?i variabila de server SCRIPT_FILENAME, atunci când nu este populata de Apache. Aceasta schimbare a fost facuta pentru conformarea cu specifica?ia CGI ca PATH_TRANSLATED trebuie sa existe numai daca PATH_INFO este definita. Utilizatorii Apache 2 pot sa utilizeze AcceptPathInfo = On în interiorul httpd.conf pentru a defini PATH_INFO.

Apache
Instalarea / configurarea
Apache


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Apache


Instalarea

Pentru informa?ii despre instalarea PHP pe Apache vede?i capitolul despre instalare.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul modulului PHP pentru Apache este afectat de parametrii din php.ini. Parametrii de configurare din php.ini pot fi modifica?i de cei stabili?i cu ajutorul php_flag în fi?ierul de configurare al serverului sau din fi?ierele locale .htaccess.

Example #1 Deconectarea prelucrarii PHP pentru un director utilizând .htaccess

php_flag engine off

Op?iunile de configurare Apache
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
engine | "1" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.5.
child_terminate | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.5.
last_modified | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.5.
xbithack | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.5.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

engine boolean

Conecteaza sau deconecteaza prelucrarea PHP. Aceasta directiva este utila doar pentru versiunea PHP ca modul al Apache. Este utilizata de site-uri care doresc sa conecteze sau sa deconecteze prelucrarea PHP pentru unele directoare sau servere virtuale. Stabilind engine off în locurile corespunzatoare din fi?ierul httpd.conf PHP poate fi conectat sau deconectat.

child_terminate boolean

Specifica daca scripturile PHP pot cere terminarea procesului-fiu la sfâr?itul interpelarii, vede?i de asemenea apache_child_terminate().

last_modified boolean

Transmite data modificarii sripturilor PHP ca antet Last-Modified: pentru aceasta interpelare.

xbithack boolean

Prelucreaza fi?iere cu bitul de execu?ie stabilit ca fi?iere PHP indiferent de termina?ia denumirii fi?ierului.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii Apache
Apache


Func?ii Apache

Cuprins

  • apache_child_terminate — Termina (lichideaza) procesul apache dupa aceasta cerere
  • 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 — Efectueaza o interpelare par?iala pentru URI specificat ?i întoarce toate informa?iile despre el
  • apache_note — Ob?ine ?i stabile?te note ale interpelarilor apache
  • apache_request_headers — Fetch all HTTP request headers
  • apache_reset_timeout — Reset the Apache write timer
  • apache_response_headers — Fetch all HTTP response headers
  • apache_setenv — Stabile?te o variabila de mediu a unui subprocess Apache
  • getallheaders — Ob?ine toate antetele interpelarii HTTP
  • virtual — Efectueaza o sub-interpelare Apache
Constante predefinite
apache_child_terminate
Apache


Termina (lichideaza) procesul apache dupa aceasta cerere

Func?ii Apache
apache_get_modules
Func?ii Apache
PHP Manual

apache_child_terminate

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

apache_child_terminate — Termina (lichideaza) procesul apache dupa aceasta cerere

Descrierea

bool apache_child_terminate ( void )

apache_child_terminate() va înregistra procesul Apache, ce executa interpelarea data PHP, pentru a fi terminat (lichidat) odata cu finalizarea executarii codului PHP. Aceasta func?ie poate fi utilizata pentru a termina un proces dupa rularea unui script cu un consum de memorie substan?ial, deoarece memoria de obicei este eliberata intern ?i nu este întoarsa sistemului de operare.

Valorile întoarse

Întoarce TRUE daca PHP ruleaza în calitate de modul Apache 1, Apache nu ruleaza pe mai multe fire de execu?ie ?i directiva PHP child_terminate este activata (ea este dezactivata implicit). Daca aceste condi?ii nu sunt satisfacute, este întors FALSE ?i este generata o eroare de nivel E_WARNING.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Aceasta func?ie a devenit disponibila în FastCGI. Anterior ea era sus?inuta doar când PHP era instalat ca modul Apache.

Note

Nota: Aceasta func?ie nu este implementata pe platformele Windows.

A se vedea ?i

  • exit() - Output a message and terminate the current script

Func?ii Apache
apache_get_modules
Func?ii Apache


Get a list of loaded Apache modules

apache_child_terminate
apache_get_version
Func?ii Apache
PHP Manual

apache_get_modules

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

apache_get_modules — Get a list of loaded Apache modules

Descrierea

array apache_get_modules ( void )

Get a list of loaded Apache modules.

Valorile întoarse

An array of loaded Apache modules.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #1 apache_get_modules() example

<?php
print_r(apache_get_modules());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => core
    [1] => http_core
    [2] => mod_so
    [3] => sapi_apache2
    [4] => mod_mime
    [5] => mod_rewrite
)

apache_child_terminate
apache_get_version
Func?ii Apache


Fetch Apache version

apache_get_modules
apache_getenv
Func?ii Apache
PHP Manual

apache_get_version

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

apache_get_version — Fetch Apache version

Descrierea

string apache_get_version ( void )

Fetch the Apache version.

Valorile întoarse

Returns the Apache version on success sau FALSE în cazul e?ecului.

Exemple

Example #1 apache_get_version() example

<?php
$version = apache_get_version();
echo "$version\n";
?>

Exemplul de mai sus va afi?a ceva similar cu:

Apache/1.3.29 (Unix) PHP/4.3.4

A se vedea ?i

  • phpinfo() - Outputs information about PHP's configuration

apache_get_modules
apache_getenv
Func?ii Apache


Get an Apache subprocess_env variable

apache_get_version
apache_lookup_uri
Func?ii Apache
PHP Manual

apache_getenv

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

apache_getenv — Get an Apache subprocess_env variable

Descrierea

string apache_getenv ( string $variable [, bool $walk_to_top = false ] )

Retrieve an Apache environment variable specified by variable.

This function requires Apache 2 otherwise it's undefined.

Parametri

variable

The Apache environment variable

walk_to_top

Whether to get the top-level variable available to all Apache layers.

Valorile întoarse

The value of the Apache environment variable on success, or FALSE on failure

Exemple

Example #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;
?>

Exemplul de mai sus va afi?a ceva similar cu:

42.24.42.240

A se vedea ?i

  • apache_setenv() - Stabile?te o variabila de mediu a unui subprocess Apache
  • getenv() - Gets the value of an environment variable
  • Superglobals

apache_get_version
apache_lookup_uri
Func?ii Apache


Efectueaza o interpelare par?iala pentru URI specificat ?i întoarce toate informa?iile despre el

apache_getenv
apache_note
Func?ii Apache
PHP Manual

apache_lookup_uri

(PHP 4, PHP 5, PHP 7)

apache_lookup_uri — Efectueaza o interpelare par?iala pentru URI specificat ?i întoarce toate informa?iile despre el

Descrierea

object apache_lookup_uri ( string $filename )

Aceasta efectueaza o interpelare par?iala pentru un URI. Interpelarea se deruleaza doar pâna la etapa ob?inerii tuturor informa?iilor importante despre resursa data.

Aceasta func?ie e sus?inuta atunci când PHP este instalat ca modul Apache sau ca Modul server NSAPI în servere web Netscape/iPlanet/SunONE.

Parametri

filename

Denumirea fi?ierului (URI) care este interpelat.

Valorile întoarse

Un object cu informa?iile ce se refera la URI. Proprieta?ile acestui object sunt:

  • 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

Exemple

Example #1 Exemplu apache_lookup_uri()

<?php
$info = apache_lookup_uri('index.php?var=value');
print_r($info);

if (file_exists($info->filename)) {
    echo 'file exists!';
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

stdClass Object
(
    [status] => 200
    [the_request] => GET /dir/file.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] => /dir/index.php?var=value
    [uri] => /dir/index.php
    [filename] => /home/htdocs/dir/index.php
    [args] => var=value
    [allowed] => 0
    [sent_bodyct] => 0
    [bytes_sent] => 0
    [request_time] => 1074282764
)
file exists!

apache_getenv
apache_note
Func?ii Apache


Ob?ine ?i stabile?te note ale interpelarilor apache

apache_lookup_uri
apache_request_headers
Func?ii Apache
PHP Manual

apache_note

(PHP 4, PHP 5, PHP 7)

apache_note — Ob?ine ?i stabile?te note ale interpelarilor apache

Descrierea

string apache_note ( string $note_name [, string $note_value = "" ] )

Aceasta func?ie este un înveli? pentru table_get ?i table_set ale Apache. Ea redacteaza tabelul notelor care exista în timpul derularii interpelarii. Scopul tabelului este de a permite modulelor Apache sa comunice între ele.

Utilizarea de baza a apache_note() este pentru a transmite informa?ii dintr-un modul în altul în cadrul aceleia?i interpelari.

Parametri

note_name

Denumirea notei.

note_value

Valoarea notei.

Valorile întoarse

Daca este apelata cu un singur argument, func?ia întoarce valoarea curenta a notei note_name. Daca este apelata cu doi argumen?i, func?ia stabile?te valoarea notei note_name în note_value ?i întoarce valoarea precedenta a notei note_name. Daca nota nu poate fi ob?inuta se întoarce FALSE.

Exemple

Example #1 Transmiterea informa?iei între PHP ?i Perl

<?php

apache_note('name', 'Fredrik Ekengren');

// Call perl script
virtual("/perl/some_script.pl");

$result = apache_note("resultdata");
?>
# Get Apache request object
my $r = Apache->request()->main();

# Get passed data
my $name = $r->notes('name');

# some processing

# Pass result back to PHP
$r->notes('resultdata', $result);

Example #2 Logarea valorilor în access.log

<?php

apache_note('sessionID', session_id());

?>
# "%{sessionID}n" poate fi utilizat în directiva LogFormat

A se vedea ?i

  • virtual() - Efectueaza o sub-interpelare Apache

apache_lookup_uri
apache_request_headers
Func?ii Apache


Fetch all HTTP request headers

apache_note
apache_reset_timeout
Func?ii Apache
PHP Manual

apache_request_headers

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

apache_request_headers — Fetch all HTTP request headers

Descrierea

array apache_request_headers ( void )

Fetches all HTTP request headers from the current request.

Valorile întoarse

An associative array of all the HTTP headers in the current request, or FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
5.5.7 | This function became available in the CLI server.
5.4.0 | This function became available under FastCGI. Previously, it was supported when PHP was installed as an Apache module or by the NSAPI server module in Netscape/iPlanet/SunONE webservers.

Exemple

Example #1 apache_request_headers() example

<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive

Note

Nota:

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.

A se vedea ?i

  • apache_response_headers() - Fetch all HTTP response headers

apache_note
apache_reset_timeout
Func?ii Apache


Reset the Apache write timer

apache_request_headers
apache_response_headers
Func?ii Apache
PHP Manual

apache_reset_timeout

(PHP 5 >= 5.1.0, PHP 7)

apache_reset_timeout — Reset the Apache write timer

Descrierea

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota: Aceasta func?ie este dezactivata atunci când PHP ruleaza în modul securizat.

A se vedea ?i

  • 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
Func?ii Apache


Fetch all HTTP response headers

apache_reset_timeout
apache_setenv
Func?ii Apache
PHP Manual

apache_response_headers

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

apache_response_headers — Fetch all HTTP response headers

Descrierea

array apache_response_headers ( void )

Fetch all HTTP response headers.

Valorile întoarse

An array of all Apache response headers on success sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.7 | This function became available in the CLI server.
5.4.0 | This function became available under FastCGI. Previously, it was supported when PHP was installed as an Apache module or by the NSAPI server module in Netscape/iPlanet/SunONE webservers.

Exemple

Example #1 apache_response_headers() example

<?php
print_r(apache_response_headers());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [Accept-Ranges] => bytes
    [X-Powered-By] => PHP/4.3.8
)

A se vedea ?i

  • apache_request_headers() - Fetch all HTTP request headers
  • headers_sent() - Checks if or where headers have been sent
  • headers_list() - Returns a list of response headers sent (or ready to send)

apache_reset_timeout
apache_setenv
Func?ii Apache


Stabile?te o variabila de mediu a unui subprocess Apache

apache_response_headers
getallheaders
Func?ii Apache
PHP Manual

apache_setenv

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

apache_setenv — Stabile?te o variabila de mediu a unui subprocess Apache

Descrierea

bool apache_setenv ( string $variable , string $value [, bool $walk_to_top = false ] )

apache_setenv() stabile?te valoarea unei variabile de mediu Apache specificata prin variable.

Nota:

La stabilirea unei variabile de mediu Apache, variabila $_SERVER corespunzatoare nu este schimbata.

Parametri

variable

Variabila de mediu ce se stabile?te.

value

Valoarea noua a variable.

walk_to_top

Determina daca se va stabili variabila de cel mai înalt nivel, disponibila la toate nivelele Apache.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Stabilirea unei variabile de mediu Apache cu ajutorul apache_setenv()

<?php
apache_setenv("EXAMPLE_VAR", "Example Value");
?>

Note

Nota:

apache_setenv() poate fi utilizata împreuna cu apache_getenv() pe diferite pagini, sau pentru a stabili variabile ce vor fi transmise catre Incluziunile de Partea Server-ului (Server Side Includes) (.shtml) care au fost incluse în script-uri PHP.

A se vedea ?i

  • apache_getenv() - Get an Apache subprocess_env variable

apache_response_headers
getallheaders
Func?ii Apache


Ob?ine toate antetele interpelarii HTTP

apache_setenv
virtual
Func?ii Apache
PHP Manual

getallheaders

(PHP 4, PHP 5, PHP 7)

getallheaders — Ob?ine toate antetele interpelarii HTTP

Descrierea

array getallheaders ( void )

Ob?ine toate antetele HTTP ale interpelarii curente.

Aceasta func?ie este un pseudonim al apache_request_headers(). Va rugam sa citi?i documenta?ia apache_request_headers() pentru informa?ii suplimentare despre cum func?ioneaza aceasta func?ie.

Valorile întoarse

Un tablou asociativ cu toate antetele HTTP din interpelarea curenta, sau FALSE în caz de e?ec.

Istoricul schimbarilor

Versiune | Descriere
5.5.7 | Aceasta func?ie a devenit disponibila în serverul CLI.
5.4.0 | Aceasta func?ie a devenit disponibila în FastCGI. Anterior ea era sus?inuta daca PHP era instalat ca modul Apache sau ca modul server NSAPI în serverele web Netscape/iPlanet/SunONE.

Exemple

Example #1 Exemplu getallheaders()

<?php

foreach (getallheaders() as $name => $value) {
    echo "$name: $value\n";
}

?>

A se vedea ?i

  • apache_response_headers() - Fetch all HTTP response headers

apache_setenv
virtual
Func?ii Apache


Efectueaza o sub-interpelare Apache

getallheaders
Managerul de procese FastCGI
Func?ii Apache
PHP Manual

virtual

(PHP 4, PHP 5, PHP 7)

virtual — Efectueaza o sub-interpelare Apache

Descrierea

bool virtual ( string $filename )

virtual() este o func?ie specifica Apache, care este similara cu <!--#include virtual...--> în mod_include. Ea efectueaza o sub-interpelare Apache. Ea este utila pentru includerea script-urilor CGI, sau a fi?ierelor .shtml, sau orice altceva ce se interpreteaza de catre Apache. Atrage?i aten?ia ca în cazul unui script CGI, acesta trebuie sa genereze antete CGI valide. Aceasta înseamna ca el trebuie sa genereze cel pu?in un antet Content-type.

Pentru a rula sub-interpelarea toate zonele-tampon sunt închise ?i trimise catre navigator, antetele ramase sunt de asemenea trimise.

Aceasta func?ie e sus?inuta atunci când PHP este instalat ca modul Apache sau ca Modul server NSAPI în servere web Netscape/iPlanet/SunONE.

Parametri

filename

Fi?ierul asupra caruia se va efectua comanda virtuala.

Valorile întoarse

Efectueaza comanda virtuala în cazul de succes, sau întoarce FALSE în caz de e?ec.

Exemple

Accesa?i apache_note() pentru un exemplu.

Note

Avertizare

String-ul cu interpelarea poate fi transmis fi?ierului inclus, însa $_GET este copiat din script-ul parinte ?i numai $_SERVER['QUERY_STRING'] este completata cu string-ul cu interpelarea. String-ul cu interpelarea poate fi transmis când se utilizeaza Apache 2. Fi?ierul interpelat nu va fi afi?at în jurnalul de acces al Apache.

Nota:

Variabilele de mediu stabilite în fi?ierul interpelat nu sunt vizibile script-ului apelant.

Nota:

Aceasta func?ie poate fi aplicata asupra fi?ierelor PHP. Însa de obicei e mai bine de a utiliza include sau require pentru fi?iere PHP.

A se vedea ?i

  • apache_note() - Ob?ine ?i stabile?te note ale interpelarilor apache

getallheaders
Managerul de procese FastCGI
Func?ii Apache


Managerul de procese FastCGI

  • Introducere
  • Instalarea / configurarea
  • Func?ii FPM
    • fastcgi_finish_request — Flushes all response data to the client
virtual
Introducere
Extensii specifice serverului


Introducere

FPM (FastCGI Process Manager) -- Managerul de procese FastCGI -- este o implementare alternativa PHP FastCGI, cu unele facilita?i suplimentare, utile îndeosebi pentru site-uri cu încarcatura sporita.

Acest SAPI este furnizat cu PHP 5.3.3 ?i versiunile ulterioare.

Managerul de procese FastCGI
Instalarea / configurarea
Managerul de procese FastCGI


Instalarea / configurarea

Informa?ii despre instalarea ?i configurarea FPM pot fi gasite în sec?iunea de instalare ?i configurare a manualului PHP.

Introducere
Func?ii FPM
Managerul de procese FastCGI


Func?ii FPM

Cuprins

  • fastcgi_finish_request — Flushes all response data to the client
Instalarea / configurarea
fastcgi_finish_request
Managerul de procese FastCGI


Flushes all response data to the client

Func?ii FPM
IIS
Func?ii FPM
PHP Manual

fastcgi_finish_request

(PHP 5 >= 5.3.3, PHP 7)

fastcgi_finish_request — Flushes all response data to the client

Descrierea

boolean fastcgi_finish_request ( void )

This function flushes all response data to the client and finishes the request. This allows for time consuming tasks to be performed without leaving the connection to the client open.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Func?ii FPM
IIS
Func?ii FPM


IIS Administration

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii IIS
    • iis_add_server — Creeaza un nou web server virtual
    • iis_get_dir_security — Ob?ine Securitatea Directorului
    • iis_get_script_map — Ob?ine maparea script-urilor într-un director virtual pentru o extensie specifica
    • iis_get_server_by_comment — Întoarce numarul instan?ei asociate cu Comentariul
    • iis_get_server_by_path — Întoarce numarul instan?ei asociate cu Calea
    • iis_get_server_rights — Ob?ine permisiunile serverului
    • iis_get_service_state — Întoarce starea serviciului definit prin ServiceId
    • iis_remove_server — Elimina web serverul virtual indicat de ServerInstance
    • iis_set_app_settings — Creeaza domeniul aplica?iei pentru un director virtual
    • iis_set_dir_security — Stabile?te Securitatea Directorului
    • iis_set_script_map — Stabile?te maparea script-urilor într-un director virtual
    • iis_set_server_rights — Stabile?te drepturile serverului
    • iis_start_server — Porne?te serverul web virtual
    • iis_start_service — Porne?te serviciul definit prin ServiceId
    • iis_stop_server — Opre?te serverul web virtual
    • iis_stop_service — Opre?te serviciul definit prin ServiceId
fastcgi_finish_request
Introducere
Extensii specifice serverului


Introducere

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
Instalarea / configurarea
IIS


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
IIS


Instalarea

Aceasta extensie este considerata ne-între?inuta ?i moarta. Oricum însa codul-sursa al acestei extensii este înca disponibil în PECL SVN aici: » http://svn.php.net/viewvc/pecl/iisfunc.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
Tipurile resurselor
Func?ii IIS
IIS


Func?ii IIS

Cuprins

  • iis_add_server — Creeaza un nou web server virtual
  • iis_get_dir_security — Ob?ine Securitatea Directorului
  • iis_get_script_map — Ob?ine maparea script-urilor într-un director virtual pentru o extensie specifica
  • iis_get_server_by_comment — Întoarce numarul instan?ei asociate cu Comentariul
  • iis_get_server_by_path — Întoarce numarul instan?ei asociate cu Calea
  • iis_get_server_rights — Ob?ine permisiunile serverului
  • iis_get_service_state — Întoarce starea serviciului definit prin ServiceId
  • iis_remove_server — Elimina web serverul virtual indicat de ServerInstance
  • iis_set_app_settings — Creeaza domeniul aplica?iei pentru un director virtual
  • iis_set_dir_security — Stabile?te Securitatea Directorului
  • iis_set_script_map — Stabile?te maparea script-urilor într-un director virtual
  • iis_set_server_rights — Stabile?te drepturile serverului
  • iis_start_server — Porne?te serverul web virtual
  • iis_start_service — Porne?te serviciul definit prin ServiceId
  • iis_stop_server — Opre?te serverul web virtual
  • iis_stop_service — Opre?te serviciul definit prin ServiceId
Constante predefinite
iis_add_server
IIS


Creeaza un nou web server virtual

Func?ii IIS
iis_get_dir_security
Func?ii IIS
PHP Manual

iis_add_server

(PECL iisfunc SVN)

iis_add_server — Creeaza un nou web server virtual

Descrierea

int iis_add_server ( string $path , string $comment , string $server_ip , int $port , string $host_name , int $rights , int $start_server )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Func?ii IIS
iis_get_dir_security
Func?ii IIS


Ob?ine Securitatea Directorului

iis_add_server
iis_get_script_map
Func?ii IIS
PHP Manual

iis_get_dir_security

(PECL iisfunc SVN)

iis_get_dir_security — Ob?ine Securitatea Directorului

Descrierea

int iis_get_dir_security ( int $server_instance , string $virtual_path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_add_server
iis_get_script_map
Func?ii IIS


Ob?ine maparea script-urilor într-un director virtual pentru o extensie specifica

iis_get_dir_security
iis_get_server_by_comment
Func?ii IIS
PHP Manual

iis_get_script_map

(PECL iisfunc SVN)

iis_get_script_map — Ob?ine maparea script-urilor într-un director virtual pentru o extensie specifica

Descrierea

string iis_get_script_map ( int $server_instance , string $virtual_path , string $script_extension )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_get_dir_security
iis_get_server_by_comment
Func?ii IIS


Întoarce numarul instan?ei asociate cu Comentariul

iis_get_script_map
iis_get_server_by_path
Func?ii IIS
PHP Manual

iis_get_server_by_comment

(PECL iisfunc SVN)

iis_get_server_by_comment — Întoarce numarul instan?ei asociate cu Comentariul

Descrierea

int iis_get_server_by_comment ( string $comment )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_get_script_map
iis_get_server_by_path
Func?ii IIS


Întoarce numarul instan?ei asociate cu Calea

iis_get_server_by_comment
iis_get_server_rights
Func?ii IIS
PHP Manual

iis_get_server_by_path

(PECL iisfunc SVN)

iis_get_server_by_path — Întoarce numarul instan?ei asociate cu Calea

Descrierea

int iis_get_server_by_path ( string $path )

Fiecare server virtual în IIS este asociat cu un numar de instan?a. Func?ia iis_get_server_by_path() gase?te numarul instan?ei utilizând calea catre directorul de baza.

Parametri

path

Calea catre directorul de baza

Valorile întoarse

Întoarce numarul instan?ei pe server.

iis_get_server_by_comment
iis_get_server_rights
Func?ii IIS


Ob?ine permisiunile serverului

iis_get_server_by_path
iis_get_service_state
Func?ii IIS
PHP Manual

iis_get_server_rights

(PECL iisfunc SVN)

iis_get_server_rights — Ob?ine permisiunile serverului

Descrierea

int iis_get_server_rights ( int $server_instance , string $virtual_path )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_get_server_by_path
iis_get_service_state
Func?ii IIS


Întoarce starea serviciului definit prin ServiceId

iis_get_server_rights
iis_remove_server
Func?ii IIS
PHP Manual

iis_get_service_state

(PECL iisfunc SVN)

iis_get_service_state — Întoarce starea serviciului definit prin ServiceId

Descrierea

int iis_get_service_state ( string $service_id )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_get_server_rights
iis_remove_server
Func?ii IIS


Elimina web serverul virtual indicat de ServerInstance

iis_get_service_state
iis_set_app_settings
Func?ii IIS
PHP Manual

iis_remove_server

(PECL iisfunc SVN)

iis_remove_server — Elimina web serverul virtual indicat de ServerInstance

Descrierea

int iis_remove_server ( int $server_instance )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_get_service_state
iis_set_app_settings
Func?ii IIS


Creeaza domeniul aplica?iei pentru un director virtual

iis_remove_server
iis_set_dir_security
Func?ii IIS
PHP Manual

iis_set_app_settings

(PECL iisfunc SVN)

iis_set_app_settings — Creeaza domeniul aplica?iei pentru un director virtual

Descrierea

int iis_set_app_settings ( int $server_instance , string $virtual_path , string $application_scope )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_remove_server
iis_set_dir_security
Func?ii IIS


Stabile?te Securitatea Directorului

iis_set_app_settings
iis_set_script_map
Func?ii IIS
PHP Manual

iis_set_dir_security

(PECL iisfunc SVN)

iis_set_dir_security — Stabile?te Securitatea Directorului

Descrierea

int iis_set_dir_security ( int $server_instance , string $virtual_path , int $directory_flags )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_set_app_settings
iis_set_script_map
Func?ii IIS


Stabile?te maparea script-urilor într-un director virtual

iis_set_dir_security
iis_set_server_rights
Func?ii IIS
PHP Manual

iis_set_script_map

(PECL iisfunc SVN)

iis_set_script_map — Stabile?te maparea script-urilor într-un director virtual

Descrierea

int iis_set_script_map ( int $server_instance , string $virtual_path , string $script_extension , string $engine_path , int $allow_scripting )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_set_dir_security
iis_set_server_rights
Func?ii IIS


Stabile?te drepturile serverului

iis_set_script_map
iis_start_server
Func?ii IIS
PHP Manual

iis_set_server_rights

(PECL iisfunc SVN)

iis_set_server_rights — Stabile?te drepturile serverului

Descrierea

int iis_set_server_rights ( int $server_instance , string $virtual_path , int $directory_flags )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_set_script_map
iis_start_server
Func?ii IIS


Porne?te serverul web virtual

iis_set_server_rights
iis_start_service
Func?ii IIS
PHP Manual

iis_start_server

(PECL iisfunc SVN)

iis_start_server — Porne?te serverul web virtual

Descrierea

int iis_start_server ( int $server_instance )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_set_server_rights
iis_start_service
Func?ii IIS


Porne?te serviciul definit prin ServiceId

iis_start_server
iis_stop_server
Func?ii IIS
PHP Manual

iis_start_service

(PECL iisfunc SVN)

iis_start_service — Porne?te serviciul definit prin ServiceId

Descrierea

int iis_start_service ( string $service_id )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_start_server
iis_stop_server
Func?ii IIS


Opre?te serverul web virtual

iis_start_service
iis_stop_service
Func?ii IIS
PHP Manual

iis_stop_server

(PECL iisfunc SVN)

iis_stop_server — Opre?te serverul web virtual

Descrierea

int iis_stop_server ( int $server_instance )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_start_service
iis_stop_service
Func?ii IIS


Opre?te serviciul definit prin ServiceId

iis_stop_server
NSAPI
Func?ii IIS
PHP Manual

iis_stop_service

(PECL iisfunc SVN)

iis_stop_service — Opre?te serviciul definit prin ServiceId

Descrierea

int iis_stop_service ( string $service_id )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

iis_stop_server
NSAPI
Func?ii IIS


NSAPI

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • NSAPI Func?ii
    • 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
Introducere
Extensii specifice serverului


Introducere

Aceste func?ii sunt disponibile doar atunci când PHP ruleaza ca modul NSAPI în serverele web Netscape/iPlanet/Sun.

NSAPI
Instalarea / configurarea
NSAPI


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
NSAPI


Instalarea

For PHP installation on Netscape/iPlanet/Sun webservers see the NSAPI section (UNIX, Windows) in the installation chapter.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

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
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
nsapi.read_timeout | "60" | PHP_INI_ALL | Available since PHP 4.3.3.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

nsapi.read_timeout integer

Sets the time in seconds the plugin is waiting for POST data from the client.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
NSAPI Func?ii
NSAPI


NSAPI Func?ii

A se vedea ?i

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

Cuprins

  • nsapi_request_headers — Fetch all HTTP request headers
  • nsapi_response_headers — Fetch all HTTP response headers
  • nsapi_virtual — Perform an NSAPI sub-request
Constante predefinite
nsapi_request_headers
NSAPI


Fetch all HTTP request headers

NSAPI Func?ii
nsapi_response_headers
NSAPI Func?ii
PHP Manual

nsapi_request_headers

(PHP 4 >= 4.3.3, PHP 5, PHP 7)

nsapi_request_headers — Fetch all HTTP request headers

Descrierea

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.

Nota:

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.

Nota:

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.

Valorile întoarse

Returns an associative array with all the HTTP headers.

Exemple

Example #1 nsapi_request_headers() example

<?php
$headers = nsapi_request_headers();

foreach ($headers as $header => $value) {
  echo "$header: $value <br />\n";
}
?>

NSAPI Func?ii
nsapi_response_headers
NSAPI Func?ii


Fetch all HTTP response headers

nsapi_request_headers
nsapi_virtual
NSAPI Func?ii
PHP Manual

nsapi_response_headers

(PHP 4 >= 4.3.3, PHP 5, PHP 7)

nsapi_response_headers — Fetch all HTTP response headers

Descrierea

array nsapi_response_headers ( void )

Gets all the NSAPI response headers.

Valorile întoarse

Returns an associative array with all the NSAPI response headers.

A se vedea ?i

  • nsapi_request_headers() - Fetch all HTTP request headers
  • headers_sent() - Checks if or where headers have been sent

nsapi_request_headers
nsapi_virtual
NSAPI Func?ii


Perform an NSAPI sub-request

nsapi_response_headers
Extensii de lucru cu sesiuni
NSAPI Func?ii
PHP Manual

nsapi_virtual

(PHP 4 >= 4.3.3, PHP 5, PHP 7)

nsapi_virtual — Perform an NSAPI sub-request

Descrierea

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.

Nota:

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.

Parametri

uri

The URI of the script.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

nsapi_response_headers
Extensii de lucru cu sesiuni
NSAPI Func?ii


Extensii de lucru cu sesiuni

  • Msession — Mohawk Software Session Handler Functions
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Msession
  • Sessions — Session Handling
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Session Upload Progress
    • Sessions and Security
    • Func?ii de sesiuni
    • SessionHandler — The SessionHandler class
    • SessionHandlerInterface — The SessionHandlerInterface class
  • Session PgSQL — PostgreSQL Session Save Handler
    • Introducere
    • Instalarea / configurarea
    • Table definitions
    • Constante predefinite
    • Session PgSQL Func?ii
nsapi_virtual
Msession
Informa?ii de referin?a despre func?ii


Mohawk Software Session Handler Functions

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Msession
    • msession_connect — Efectueaza conectarea la un server msession
    • msession_count — Ob?ine numarul de sesiuni
    • msession_create — Creeaza o sesiune
    • msession_destroy — Distruge o sesiune
    • msession_disconnect — Închide conexiunea catre serverul msession
    • msession_find — Gase?te toate sesiunile dupa denumire ?i valoare
    • msession_get_array — Ob?ine tabloul variabilelor msession
    • msession_get_data — Ob?ine datele nestructurate a unei sesiuni de date
    • msession_get — Ob?ine valoarea din sesiune
    • msession_inc — Incrementeaza valoarea din sesiune
    • msession_list — Listeaza toate sesiunile
    • msession_listvar — Listeaza sessiunile cu variabila
    • msession_lock — Încuie o sesiune
    • msession_plugin — Apeleaza o func?ie de evadare în interiorul personalita?ii modulului msession
    • msession_randstr — Ob?ine un ?ir aleator
    • msession_set_array — Stabile?te variabilele msession dintr-un tablou
    • msession_set_data — Stabile?te datele nestructurate a unei sesiuni de date
    • msession_set — Stabile?te o valoare în sesiune
    • msession_timeout — Stabile?te/ob?ine limita de timp pentru sesiune
    • msession_uniq — Ob?ine un identificator unic
    • msession_unlock — Descuie o sesiune
Extensii de lucru cu sesiuni
Introducere
Extensii de lucru cu sesiuni


Introducere

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.

Nota: Aceasta extensie nu este disponibila pe platformele Windows.

Nota:

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.1.3.

Msession
Instalarea / configurarea
Msession


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Msession


Instalarea

Aceasta extensie este considerata ne-între?inuta ?i moarta. Oricum însa codul-sursa al acestei extensii este înca disponibil în PECL SVN aici: » http://svn.php.net/viewvc/pecl/msession.

Aceasta extensie a fost transferata în repozitoriul » PECL ?i nu mai este furnizata împreuna cu PHP începând cu versiunea 5.1.3

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii Msession
Msession


Func?ii Msession

Cuprins

  • msession_connect — Efectueaza conectarea la un server msession
  • msession_count — Ob?ine numarul de sesiuni
  • msession_create — Creeaza o sesiune
  • msession_destroy — Distruge o sesiune
  • msession_disconnect — Închide conexiunea catre serverul msession
  • msession_find — Gase?te toate sesiunile dupa denumire ?i valoare
  • msession_get_array — Ob?ine tabloul variabilelor msession
  • msession_get_data — Ob?ine datele nestructurate a unei sesiuni de date
  • msession_get — Ob?ine valoarea din sesiune
  • msession_inc — Incrementeaza valoarea din sesiune
  • msession_list — Listeaza toate sesiunile
  • msession_listvar — Listeaza sessiunile cu variabila
  • msession_lock — Încuie o sesiune
  • msession_plugin — Apeleaza o func?ie de evadare în interiorul personalita?ii modulului msession
  • msession_randstr — Ob?ine un ?ir aleator
  • msession_set_array — Stabile?te variabilele msession dintr-un tablou
  • msession_set_data — Stabile?te datele nestructurate a unei sesiuni de date
  • msession_set — Stabile?te o valoare în sesiune
  • msession_timeout — Stabile?te/ob?ine limita de timp pentru sesiune
  • msession_uniq — Ob?ine un identificator unic
  • msession_unlock — Descuie o sesiune
Constante predefinite
msession_connect
Msession


Efectueaza conectarea la un server msession

Func?ii Msession
msession_count
Func?ii Msession
PHP Manual

msession_connect

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_connect — Efectueaza conectarea la un server msession

Descrierea

bool msession_connect ( string $host , string $port )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Func?ii Msession
msession_count
Func?ii Msession


Ob?ine numarul de sesiuni

msession_connect
msession_create
Func?ii Msession
PHP Manual

msession_count

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_count — Ob?ine numarul de sesiuni

Descrierea

int msession_count ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_connect
msession_create
Func?ii Msession


Creeaza o sesiune

msession_count
msession_destroy
Func?ii Msession
PHP Manual

msession_create

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_create — Creeaza o sesiune

Descrierea

bool msession_create ( string $session [, string $classname [, string $data ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_count
msession_destroy
Func?ii Msession


Distruge o sesiune

msession_create
msession_disconnect
Func?ii Msession
PHP Manual

msession_destroy

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_destroy — Distruge o sesiune

Descrierea

bool msession_destroy ( string $name )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_create
msession_disconnect
Func?ii Msession


Închide conexiunea catre serverul msession

msession_destroy
msession_find
Func?ii Msession
PHP Manual

msession_disconnect

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_disconnect — Închide conexiunea catre serverul msession

Descrierea

void msession_disconnect ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_destroy
msession_find
Func?ii Msession


Gase?te toate sesiunile dupa denumire ?i valoare

msession_disconnect
msession_get_array
Func?ii Msession
PHP Manual

msession_find

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_find — Gase?te toate sesiunile dupa denumire ?i valoare

Descrierea

array msession_find ( string $name , string $value )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_disconnect
msession_get_array
Func?ii Msession


Ob?ine tabloul variabilelor msession

msession_find
msession_get_data
Func?ii Msession
PHP Manual

msession_get_array

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_get_array — Ob?ine tabloul variabilelor msession

Descrierea

array msession_get_array ( string $session )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_find
msession_get_data
Func?ii Msession


Ob?ine datele nestructurate a unei sesiuni de date

msession_get_array
msession_get
Func?ii Msession
PHP Manual

msession_get_data

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_get_data — Ob?ine datele nestructurate a unei sesiuni de date

Descrierea

string msession_get_data ( string $session )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_get_array
msession_get
Func?ii Msession


Ob?ine valoarea din sesiune

msession_get_data
msession_inc
Func?ii Msession
PHP Manual

msession_get

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_get — Ob?ine valoarea din sesiune

Descrierea

string msession_get ( string $session , string $name , string $value )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_get_data
msession_inc
Func?ii Msession


Incrementeaza valoarea din sesiune

msession_get
msession_list
Func?ii Msession
PHP Manual

msession_inc

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_inc — Incrementeaza valoarea din sesiune

Descrierea

string msession_inc ( string $session , string $name )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_get
msession_list
Func?ii Msession


Listeaza toate sesiunile

msession_inc
msession_listvar
Func?ii Msession
PHP Manual

msession_list

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_list — Listeaza toate sesiunile

Descrierea

array msession_list ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_inc
msession_listvar
Func?ii Msession


Listeaza sessiunile cu variabila

msession_list
msession_lock
Func?ii Msession
PHP Manual

msession_listvar

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_listvar — Listeaza sessiunile cu variabila

Descrierea

array msession_listvar ( string $name )

Utilizata pentru a cauta sesiuni cu atribute comune.

Parametri

name

Denumirea dupa care de efectueaza cautarea.

Valorile întoarse

Întoarce un tablou asociativ cu valoarea/sesiunea pentru toate sesiunile ce con?in variabila cu denumirea name.

msession_list
msession_lock
Func?ii Msession


Încuie o sesiune

msession_listvar
msession_plugin
Func?ii Msession
PHP Manual

msession_lock

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_lock — Încuie o sesiune

Descrierea

int msession_lock ( string $name )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_listvar
msession_plugin
Func?ii Msession


Apeleaza o func?ie de evadare în interiorul personalita?ii modulului msession

msession_lock
msession_randstr
Func?ii Msession
PHP Manual

msession_plugin

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_plugin — Apeleaza o func?ie de evadare în interiorul personalita?ii modulului msession

Descrierea

string msession_plugin ( string $session , string $val [, string $param ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_lock
msession_randstr
Func?ii Msession


Ob?ine un ?ir aleator

msession_plugin
msession_set_array
Func?ii Msession
PHP Manual

msession_randstr

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_randstr — Ob?ine un ?ir aleator

Descrierea

string msession_randstr ( int $param )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_plugin
msession_set_array
Func?ii Msession


Stabile?te variabilele msession dintr-un tablou

msession_randstr
msession_set_data
Func?ii Msession
PHP Manual

msession_set_array

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_set_array — Stabile?te variabilele msession dintr-un tablou

Descrierea

void msession_set_array ( string $session , array $tuples )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_randstr
msession_set_data
Func?ii Msession


Stabile?te datele nestructurate a unei sesiuni de date

msession_set_array
msession_set
Func?ii Msession
PHP Manual

msession_set_data

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_set_data — Stabile?te datele nestructurate a unei sesiuni de date

Descrierea

bool msession_set_data ( string $session , string $value )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_set_array
msession_set
Func?ii Msession


Stabile?te o valoare în sesiune

msession_set_data
msession_timeout
Func?ii Msession
PHP Manual

msession_set

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_set — Stabile?te o valoare în sesiune

Descrierea

bool msession_set ( string $session , string $name , string $value )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_set_data
msession_timeout
Func?ii Msession


Stabile?te/ob?ine limita de timp pentru sesiune

msession_set
msession_uniq
Func?ii Msession
PHP Manual

msession_timeout

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_timeout — Stabile?te/ob?ine limita de timp pentru sesiune

Descrierea

int msession_timeout ( string $session [, int $param ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_set
msession_uniq
Func?ii Msession


Ob?ine un identificator unic

msession_timeout
msession_unlock
Func?ii Msession
PHP Manual

msession_uniq

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_uniq — Ob?ine un identificator unic

Descrierea

string msession_uniq ( int $param [, string $classname [, string $data ]] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_timeout
msession_unlock
Func?ii Msession


Descuie o sesiune

msession_uniq
Sessions
Func?ii Msession
PHP Manual

msession_unlock

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_unlock — Descuie o sesiune

Descrierea

int msession_unlock ( string $session , int $key )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

msession_uniq
Sessions
Func?ii Msession


Session Handling

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Basic usage
    • Passing the Session ID
    • Custom Session Handlers
  • Session Upload Progress
  • Sessions and Security
    • Session Management Basics
    • Securing Session INI Settings
  • Func?ii de sesiuni
    • session_abort — Discard session array changes and finish session
    • session_cache_expire — Return current cache expire
    • session_cache_limiter — Get and/or set the current cache limiter
    • session_commit — Pseudonim pentru session_write_close
    • session_create_id — Create new session id
    • session_decode — Decodes session data from a session encoded string
    • session_destroy — Destroys all data registered to a session
    • session_encode — Encodes the current session data as a session encoded string
    • session_gc — Perform session data garbage collection
    • session_get_cookie_params — Get the session cookie parameters
    • session_id — Get and/or set the current session id
    • session_is_registered — Find out whether a global variable is registered in a session
    • session_module_name — Get and/or set the current session module
    • session_name — Get and/or set the current session name
    • session_regenerate_id — Update the current session id with a newly generated one
    • session_register_shutdown — Session shutdown function
    • session_register — Register one or more global variables with the current session
    • session_reset — Re-initialize session array with original values
    • session_save_path — Get and/or set the current session save path
    • session_set_cookie_params — Set the session cookie parameters
    • session_set_save_handler — Sets user-level session storage functions
    • session_start — Start new or resume existing session
    • session_status — Returns the current session status
    • session_unregister — Unregister a global variable from the current session
    • session_unset — Free all session variables
    • session_write_close — Write session data and end session
  • SessionHandler — The SessionHandler class
    • SessionHandler::close — Close the session
    • SessionHandler::create_sid — Return a new session ID
    • SessionHandler::destroy — Destroy a session
    • SessionHandler::gc — Cleanup old sessions
    • SessionHandler::open — Initialize session
    • SessionHandler::read — Read session data
    • SessionHandler::write — Write session data
  • SessionHandlerInterface — The SessionHandlerInterface class
    • SessionHandlerInterface::close — Close the session
    • SessionHandlerInterface::destroy — Destroy a session
    • SessionHandlerInterface::gc — Cleanup old sessions
    • SessionHandlerInterface::open — Initialize session
    • SessionHandlerInterface::read — Read session data
    • SessionHandlerInterface::write — Write session data
msession_unlock
Introducere
Extensii de lucru cu sesiuni


Introducere

Session support in PHP consists of a way to preserve certain data across subsequent accesses.

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()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.

Precautie

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 internally by PHP using the serialization handler specified by the session.serialize_handler ini setting, 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.

Avertizare

Because session data is serialized, resource variables cannot be stored in the session.

Serialize handlers (php and php_binary) inherit register_globals limitations. Therefore, numeric index or string index contains special characters (| and !) cannot be used. Using these will end up with errors at script shutdown. php_serialize does not have such limitations. php_serialize is available from PHP 5.5.4.

Nota:

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.

Nota:

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
Instalarea / configurarea
Sessions


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Sessions


Necesita?i

Nu sunt necesare biblioteci externe pentru a asambla aceasta extensie.

Nota:

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Session support is enabled in PHP by default. If you would not like to build your PHP with session support, you should specify the --disable-session option to configure. To use shared memory allocation (mm) for session storage configure PHP --with-mm[=DIR] .

Versiunea PHP pentru Windows sus?ine implicit aceasta extensie. Nu este nevoie sa încarca?i extensii suplimentare pentru a putea utiliza aceste func?ii.

Nota:

By default, all data related to a particular session will be stored in a file in the directory specified by the session.save_path INI option. A file for each session (regardless of if any data is associated with that session) will be created. This is due to the fact that a session is opened (a file is created) but no data is even written to that file. Note that this behavior is a side-effect of the limitations of working with the file system and it is possible that a custom session handler (such as one which uses a database) does not keep track of sessions which store no data.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Session configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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_PERDIR |
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_strict_mode | "0" | PHP_INI_ALL | Available since PHP 5.5.2.
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.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.trans_sid_tags | "a=href,area=href,frame=src,form=" | PHP_INI_ALL | Available since PHP 7.1.0.
session.trans_sid_hosts | $_SERVER['HTTP_HOST'] | PHP_INI_ALL | Available since PHP 7.1.0.
session.sid_length | "32" | PHP_INI_ALL | Available since PHP 7.1.0.
session.sid_bits_per_character | "5" | PHP_INI_ALL | Available since PHP 7.1.0.
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.
session.lazy_write | "1" | PHP_INI_ALL | Available since PHP 7.0.0.
url_rewriter.tags | "a=href,area=href,frame=src,form=" | PHP_INI_ALL | Available since PHP 4.0.4. Since PHP 7.1.0, this INI is no longer used by session.
session.hash_function | "0" | PHP_INI_ALL | Available since PHP 5.0.0. Removed in PHP 7.1.0.
session.hash_bits_per_character | "4" | PHP_INI_ALL | Available since PHP 5.0.0. Removed in PHP 7.1.0.
session.entropy_file | "" | PHP_INI_ALL | Removed in PHP 7.1.0.
session.entropy_length | "0" | PHP_INI_ALL | Removed in PHP 7.1.0
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.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i 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.

The file storage module creates files using mode 600 by default. This default can be changed with the optional MODE argument: N;MODE;/path where MODE is the octal representation of the mode. Setting MODE does not affect the process umask.

Avertizare

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.

Precautie

When using the optional directory level argument N, as described above, note that using a value higher than 1 or 2 is inappropriate for most sites due to the large number of directories required: for example, a value of 3 implies that 64^3 directories exist on the filesystem, which can result in a lot of wasted space and inodes.

Only use N greater than 2 if you are absolutely certain that your site is large enough to require it.

Nota: 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. PHP serialize format (name php_serialize), PHP internal formats (name php and php_binary) and WDDX are supported (name wddx). WDDX is only available, if PHP is compiled with WDDX support. php_serialize is available from PHP 5.5.4. php_serialize uses plain serialize/unserialize function internally and does not have limitations that php and php_binary have. Older serialize handlers cannot store numeric index nor string index contains special characters (| and !) in $_SESSION. Use php_serialize to avoid numeric index or special character errors at script shutdown. 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).

Nota: 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.

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.

Nota: Removed in PHP 7.1.0. As of PHP 5.4.0 session.entropy_file defaults to /dev/urandom or /dev/arandom if it is available. In PHP 5.3.0 this directive is left empty by default.

session.entropy_length integer
session.entropy_length specifies the number of bytes which will be read from the file specified above. Defaults to 32. Removed in PHP 7.1.0.
session.use_strict_mode boolean
session.use_strict_mode specifies whether the module will use strict session id mode. If this mode is enabled, the module does not accept uninitialized session ID. If uninitialized session ID is sent from browser, new session ID is sent to browser. Applications are protected from session fixation via session adoption with strict mode. Defaults to 0 (disabled).

Nota: Enabling session.use_strict_mode is mandatory for general session security. All sites are advised to enable this. See session_create_id() example code for more details.

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().

Nota: 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).

Nota: 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. Since PHP 7.1.0, full URL path, e.g. https://php.net/, is handled by trans sid feature. Previous PHP handled relative URL path only. Rewrite target hosts are defined by session.trans_sid_hosts.

session.trans_sid_tags string
session.trans_sid_tags specifies which HTML tags are rewritten to include session id when transparent sid support is enabled. Defaults to a=href,area=href,frame=src,input=src,form= form is special tag. <input hidden="session_id" name="session_name"> is added as form variable.

Nota: Before PHP 7.1.0, url_rewriter.tags was used for this purpose. Since PHP 7.1.0, fieldset is no longer considered as special tag.

session.trans_sid_hosts string
session.trans_sid_hosts specifies which hosts are rewritten to include session id when transparent sid support is enabled. Defaults to $_SERVER['HTTP_HOST'] Multiple hosts can be specified by ",", no space is allowed between hosts. e.g. php.net,wiki.php.net,bugs.php.net
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.

Nota: Removed in PHP 5.4.0.

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.

Nota: Removed in PHP 5.4.0.

session.sid_length integer
session.sid_length allows you to specify the length of session ID string. Session ID length can be between 22 to 256. The default is 32. If you need compatibility you may specify 32, 40, etc. Longer session ID is harder to guess. At least 32 chars is recommended.

Compatibility Note: Use 32 for
session.hash_func=0 (MD5) and
session.hash_bits_per_character=4,
session.hash_func=1 (SHA1) and
session.hash_bits_per_character=6. Use 26 for
session.hash_func=0 (MD5) and
session.hash_bits_per_character=5. Use 22 for
session.hash_func=0 (MD5) and
session.hash_bits_per_character=6. You must
configure INI values to have at least 128 bits in session ID. Do
not forget set appropriate value to
session.sid_bits_per_character, otherwise you
will have weaker session ID.

Nota: This setting is introduced in PHP 7.1.0.

session.sid_bits_per_character integer
session.sid_per_character allows you to specify the number of bits in encoded session ID character. The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ","). The default is 4. The more bits results in stronger session ID. 5 is recommended value for most environments.

Nota: This setting is introduced in PHP 7.1.0.

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.

Nota: This setting was introduced in PHP 5. Removed in PHP 7.1.0.

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, "-", ",").

Nota: This was introduced in PHP 5. Removed in PHP 7.1.0.

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.

Nota: 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).
session.lazy_write boolean
session.lazy_write, when set to 1, means that session data is only rewritten if it changes. Defaults to 1, enabled.

The 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 more details on this functionality.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

SID (string)
Constant containing either the session name and session ID in the form of "name=ID" or empty string if session ID was set in an appropriate session cookie. This is the same id as the one returned by session_id().
PHP_SESSION_DISABLED (int)
Since PHP 5.4.0. Return value of session_status() if sessions are disabled.
PHP_SESSION_NONE (int)
Since PHP 5.4.0. Return value of session_status() if sessions are enabled, but no session exists.
PHP_SESSION_ACTIVE (int)
Since PHP 5.4.0. Return value of session_status() if sessions are enabled, and a session exists.
Tipurile resurselor
Exemple
Sessions


Exemple

Cuprins

  • Basic usage
  • Passing the Session ID
  • Custom Session Handlers
Constante predefinite
Basic usage
Sessions


Basic usage

Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data. The absence of an ID or session cookie lets PHP know to create a new session, and generate a new session ID.

Sessions follow a simple workflow. When a session is started, PHP will either retrieve an existing session using the ID passed (usually from a session cookie) or if no session is passed it will create a new session. PHP will populate the $_SESSION superglobal with any session data after the session has started. When PHP shuts down, it will automatically take the contents of the $_SESSION superglobal, serialize it, and send it for storage using the session save handler.

By default, PHP uses the internal files save handler which is set by session.save_handler. This saves session data on the server at the location specified by the session.save_path configuration directive.

Sessions can be started manually using the session_start() function. If the session.auto_start directive is set to 1, a session will automatically start on request startup.

Sessions normally shutdown automatically when PHP is finished executing a script, but can be manually shutdown using the session_write_close() function.

Example #1 Registering a variable with $_SESSION.

<?php
session_start();
if (!isset($_SESSION['count'])) {
  $_SESSION['count'] = 0;
} else {
  $_SESSION['count']++;
}
?>

Example #2 Unregistering a variable with $_SESSION.

<?php
session_start();
unset($_SESSION['count']);
?>

Precautie

Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

Avertizare

You can't use references in session variables as there is no feasible way to restore a reference to another variable.

Avertizare

register_globals will overwrite variables in the global scope whose names are shared with session variables. Please see Using Register Globals for details.

Nota:

File based sessions (the default in PHP) lock the session file once a session is opened via session_start() or implicitly via session.auto_start. Once locked, no other script can access the same session file until it has been closed by the first script terminating or calling session_write_close().

This is most likely to be an issue on Web sites that use AJAX heavily and have multiple concurrent requests. The easiest way to deal with it is to call session_write_close() as soon as any required changes to the session have been made, preferably early in the script. Alternatively, a different session backend that does support concurrency could be used.

Exemple
Passing the Session ID
Exemple


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. If the run-time option session.use_trans_sid is enabled, relative URIs will be changed to contain the session id automatically.

Nota:

The arg_separator.output php.ini directive allows to customize the argument separator. 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.

Example #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.

Nota:

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
Exemple


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. As of PHP 5.4.0 you may create session handlers using the SessionHandlerInterface or extend internal PHP handlers by inheriting from SessionHandler.

The callbacks specified in session_set_save_handler() are methods called by PHP during the life-cycle of a session: open, read, write and close and for the housekeeping tasks: destroy for deleting a session and gc for periodic garbage collection.

Therefore, PHP always requires session save handlers. The default is usually the internal 'files' save handler. A custom save handler can be set using session_set_save_handler(). Alternative internal save handlers are also provided by PHP extensions, such as sqlite, memcache and memcached and can be set with session.save_handler.

When the session starts, PHP will internally call the open handler followed by the read callback which should return an encoded string exactly as it was originally passed for storage. Once the read callback returns the encoded string, PHP will decode it and then populate the resulting array into the $_SESSION superglobal.

When PHP shuts down (or when session_write_close() is called), PHP will internally encode the $_SESSION superglobal and pass this along with the session ID to the write callback. After the write callback has finished, PHP will internally invoke the close callback handler.

When a session is specifically destroyed, PHP will call the destroy handler with the session ID.

PHP will call the gc callback from time to time to expire any session records according to the set max lifetime of a session. This routine should delete all records from persistent storage which were last accessed longer than the $lifetime.

Passing the Session ID
Session Upload Progress
Exemple


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 a 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") . $_POST[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 an 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.

Example #1 Example information

Example of the structure of the 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, // Number 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,
  ),
 )
);

Avertizare

The web server's request buffering has to be disabled for this to work properly, else PHP may see the file upload only once fully uploaded. Servers such as Nginx are known to buffer larger requests.

Custom Session Handlers
Sessions and Security
Sessions


Sessions and Security

Cuprins

  • Session Management Basics
  • Securing Session INI Settings

External links: » Session fixation

HTTP session management is core of web security. All of mitigation should be adopted to make sure session security. Developer should enable/use applicable security measures.

Session Upload Progress
Session Management Basics
Sessions


Session Management Basics

Session Security

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 protect the confidentiality 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. e.g. JavaScript injections, session ID in URLs, packet sniffing, physical access to device. 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/TLS on your server and make it mandatory for users. HSTS should be used for better security.

Nota: Even HTTPS cannot protect confidential data in contents sometimes. e.g. CRIME, Beast attack. There are many networks that use HTTPS MITM proxy for audit purpose. Attackers may setup such proxy also.

Non-Adaptive Session Management

PHP's session manager is adaptive by default currently. Adaptive session manger has additional risks.

Since PHP 5.5.2, session.use_strict_mode is available. When it is enabled and session save handler supports it, uninitialized session ID is rejected and new session ID is created. This protects attack that forces users to use known session ID. Attacker may paste links or send mail that contains session ID. e.g. http://example.com/page.php?PHPSESSID=123456789 If session.use_trans_sid is enabled, victim will start session using attacker provided session ID. session.use_strict_mode mitigates the risk.

Avertizare

User defined save handler can also support strict session mode by implementing session ID validation function/method. All user defined save handlers must implement session ID validation function/method.

Session ID cookie could be set with domain, path, httponly, secure attributes. There is precedence defined by browsers. By using the precedence, attacker can set session ID that could be used permanently. Use of session.use_only_cookies will not solve this issue. session.use_strict_mode mitigates this risk. With session.use_strict_mode=On, uninitialized session ID will not be accepted. Session module creates new session ID always when session ID is not initialized by session module.

Nota: Even though session.use_strict_mode mitigates risk of adoptive session management, attacker can force users to use initialized session ID which is created by attacker. e.g. JavaScript injection. This attack could be mitigated by this manual's recommendations. If you follow this manual, you will enable session.use_strict_mode, use time-stamp based session management, and regenerate session ID by session_regenerate_id() with recommended procedure. If you do all of these, attacker generated session ID will eventually deleted. When obsolete session access happened, you should save all active session data for the user. It will be useful for investigation later. Then, force user to logout from all sessions. i.e. Require users to re-authenticate. This way, you can prevent attackers from keep abusing stolen sessions.

Avertizare

Access to obsolete session data does not mean attack always. Unstable network and/or immediate active session deletion will cause legitimate users to use obsolete sessions.

Since PHP 7.1.0, session_create_id() is added. This function could be used to prefix session ID by user ID to access active sessions for a user efficiently. Enabling session.use_strict_mode is very important with this setup. Otherwise, malicious users can set malicious session ID for other users.

Nota: Users prior to PHP 7.1.0 should use CSPRNG, e.g. /dev/urandom, or random_bytes() and hash functions to generate new session ID. session_create_id() has collision detection and generates session ID according to session INI settings. Use of session_create_id() is preferred.

Session ID Regeneration

session.use_strict_mode is good mitigation, but it is not enough mitigation. Developer must use session_regenerate_id() for session security.

Session ID regeneration reduces risk of stolen session ID, thus session_regenerate_id() must be called periodically. e.g. Regenerate session ID for every 15 minutes for security sensitive content. Even when session ID is stolen, either legitimate user or attacker session will be expired. i.e. User or attacker access will generate obsolete session access error.

Session ID must be regenerated when user is authenticated. session_regenerate_id() must be called prior to set authentication information to $_SESSION. (Since PHP 7.0.0, session_regenerate_id() saves current session data automatically in order to save time-stamp/etc to current session.) Make sure only new session contains authenticated flag.

Developer must NOT rely on session ID expiration by session.gc_maxlifetime. Attackers may access victim's session ID periodically to prevent expiration and keep exploiting victim's session ID including authenticated sessions.

Instead, you must implement time-stamp based session data management by yourself.

Avertizare

Although session manager can manage time-stamp transparently, but this feature is not implemented. Old session data must be kept until GC. At the same time, developers must make sure obsolete session data is removed. However, developers must NOT remove active session data immediately. i.e. Never call session_regenerate_id(true); and session_destroy() for active session. This may sound contradictory, but this is the mandatory requirement.

session_regenerate_id() does not delete old session by default. Old authenticated session may be available for use. Developers must prevent old session to be used by anyone, must prohibit access to obsolete session data by themselves using time-stamp.

Avertizare

Immediate active session removal has unwanted side effects. Session could be vanished when there are concurrent connections to web application and/or network is unstable.

Possibly malicious access cannot be detected with immediate active session removal also.

Instead of deleting old session immediately, you must set short term expiration time (time-stamp) in $_SESSION, and prohibit access to the session data by yourself.

You must not prohibit access to old session data immediately after session_regenerate_id(). It must be prohibited a little later. e.g. A few seconds later for stable wired network. A few minutes later for unstable network such as mobile or WiFi.

If user accesses to obsolete session(expired session), deny access to it. It is recommended to remove authenticated status from all of the users' session because it is likely an attack.

Proper use of session.use_only_cookies and session_regenerate_id() could cause personal DoS by undeletable cookies set by attackers. When this is the case, you may ask users to remove cookies and warn users that there could be possible security issues. Attackers may set malicious cookies via vulnerable web application, vulnerable/malicious browser plugins, physically compromised device, etc.

Avertizare

Do not misunderstand the DoS risk. use_strict_mode=On is mandatory for general session ID security! All sites are advised to enable use_strict_mode.

DoS could happen only when the account is under attack by crackers. JavaScript injection vulnerability in application is the most common cause.

Session Data Deletion

Obsolete session data must be inaccessible and deleted. Current session module does not handle this well.

Obsolete session data is better to be removed as soon as possible. However, active sessions MUST NOT be removed immediately. To satisfy these requirements, you MUST implement time-stamp based session data management by yourself.

Set and manage expiration time-stamp in $_SESSION. Prohibit access to obsolete session data. When obsolete session data access is detected, it is advised to remove all authenticated status from the user's sessions and force them to re-authenticated. Obsolete session data access could be an attack. To do this, you must keep track active sessions per user.

Nota: Access to obsolete session could happen by unstable network and/or concurrent access to web site also. Server tried to set new session ID via cookie, but Set-Cookie packet may not be reached to client due to lost connection. One connection may issue new session ID by session_regenerate_id(), but another conncurrent connection may not get the new session ID yet. Therefore, you must prohibit access to obsolete session a while later. i.e. Time-stamp based session management is mandatory.

In short, do not destroy session data by session_regenerate_id() nor session_destroy(), but use time-stamp to control access to session data. Let session_gc() to remove obsolete data from session data storage.

Session and Locking

Session data is locked to avoid races by default. Locking is mandatory to keep session data consistent across requests.

However, locking can be abused by attacker to perform DoS attacks. To mitigate risks of DoS by session lock, minimize lock. Use read only sessions when session data update is not required. Use 'read_and_close' option with session_start(). session_start(['read_and_close'=>1]); Close session as soon as you finish updating $_SESSION by using session_commit().

Current session module does not detect $_SESSION modification while session is inactive. It is your responsibility not to modify $_SESSION when session is inactive.

Active Sessions

Developers should keep track active sessions per user and notify the user how many active sessions, from which IP (and area), how long is active, etc. PHP does not keep track these. You are supposed to do so.

There are number of ways for the implementation. You may setup a database that keeps track required data and store information to it. Since session data is GCed, you have to take care of GCed data to maintain the active session database consistency.

One of the simplest implementation is "User ID prefixed session ID" and store required information to $_SESSION. Many databases have good performance for selecting string prefix. You can use session_regenerate_id() and session_create_id() for this.

Avertizare

Never use confidential data as prefix. If user ID is confidential, consider to use hash_hmac().

Avertizare

Enabling session.use_strict_mode is mandatory for this setup. Make sure it is enabled, otherwise active session database can be compromised.

Time-stamp based session management is mandatory to detect obsolete session access. When access to obsolete session is detected, you should remove authentication flags from all of active sessions for the user. This prevents attackers to keep exploiting stolen session.

Session and Auto Login

Developers must NOT use long life session ID for auto login because it increases risk of stolen session. Auto login should be implemented by developer.

Use secure one time hash key as auto login key using setcookie(). Use secure hash stronger than SHA-2. e.g. SHA-256 or greater with random data from random_bytes() or /dev/urandom.

If user is not authenticated, check the one time auto login key is valid or not. If key is valid, authenticate user and set new secure one time hash key. Auto login key must be able to be used only once. i.e. Never reuse auto login key, generate new auto login key always.

Auto login key is long life authentication key, this key should be protected as much as possible. Use path/httponly/secure cookie attributes to protect. i.e. Never transmit auto login key unless it is required.

Developer must implement feature that disables auto login and removes unneeded auto login key cookie.

CSRF(Cross Site Request Forgeries)

Session and authentication does not protect against CSRF attack. Developers must implement CSRF protection by themselves.

output_add_rewrite_var() can be used for CSRF protection. Refer to the manual page for details.

Nota: PHP prior to 7.2.0 uses the same output buffer and INI setting as trans sid. Therefore, use of output_add_rewrite_var() with PHP prior to 7.2.0 is not recommended.

Most web application frameworks support CSRF protection. Refer to your web application framwork manual for detials.

Sessions and Security
Securing Session INI Settings
Sessions and Security


Securing Session INI Settings

By securing session related INI settings, you can improve session security. Some of important INI settings do not have recommended settings. You are responsible to hardening session settings.

  • session.cookie_lifetime=0

    0 have special meaning. It tells browsers not to store cookie to permanent storage. Therefore, when browser is terminated, session ID cookie is deleted immediately. If developer set other than 0, it may allow other users to use the session ID. Most applications should use "0" for this.

    If auto login feature is required, implement your own secure auto login feature. Do not use long life session ID for it.

  • session.use_cookies=On

    session.use_only_cookies=On

    Although HTTP cookie has some problems, cookie is preferred way to manage session ID. Use only cookies for session ID management when it is possible. Most applications should use cookie for session ID.

    If session.use_only_cookies=Off, session module will use session ID values set by GET/POST/URL is used when session ID cookie is not initialized already.

  • session.use_strict_mode=On

    Although, enabling session.use_strict_mode is mandatory. It is not enabled by default.

    This prevents session module to use uninitialized session ID. In other word, session module only accepts valid session ID generated by session module. It rejects session ID supplied by users.

    Because of cookie spec, attackers are able to set undeletable session ID cookies via locally setting cookie database or JavaScript injections. session.use_strict_mode can prevent attacker initialized session ID being used.

    Nota:

    Attackers may initialize session ID by their device and may set the session ID to victim. They must keep the session ID active to abuse. Attackers require additional steps to perform attack with this attack scenario. Therefore, session.use_strict_mode works as the mitigation.

  • session.cookie_httponly=On

    Disallow access to session cookie by JavaScript. This setting prevents cookies stolen by JavaScript injection.

    It is possible to use session ID as CSRF protection key, but this is not recommended. For example, HTML source may be saved and sent to other users. Developer should not write session ID in web pages for better security. Almost all applications must use httponly attribute for session ID cookie.

    Nota:

    CSRF protection token should be renewed periodically just like session ID

  • session.cookie_secure=On

    Allows access to session ID cookie only when protocol is HTTPS. If your web site is HTTPS only web site, you must enable this setting.

    HSTS should be considered for HTTPS only web site.

  • session.gc_maxlifetime=[choose smallest possible]

    session.gc_maxlifetime is setting for deleting obsolete session ID. Reliance on this setting is NOT recommend. You should manage session life time by time-stamp by yourself.

    Session GC(garbage collection) is better to be performed by session_gc(). session_gc() function is better to be executed by task managers. e.g. cron on UNIX like systems.

    GC is performed by probability by default. This setting does not guarantee old session deletion. Although developer cannot rely on this setting, setting this to smallest possible value is recommended. Adjust session.gc_probability and session.gc_divisor so that obsolete sessions are deleted by appropriate frequency. If auto login feature is required, implement your own secure auto login feature. Never use long life session ID for it.

    Nota:

    Some session save handler modules do not use this setting for probability based expiration . e.g. memcached, memcache. Refer to session save handler documentation for details.

  • session.use_trans_sid=Off

    Use of transparent session ID management is not prohibited. You may use it when it is needed. However, disabling transparent session ID management would improve general session ID security by removing possibility of session ID injection and session ID leak.

    Nota:

    Session ID may leak from bookmarked URL, e-mailed URL, saved HTML source.

  • session.trans_sid_tags=[limitted tags]

    (PHP 7.1.0 >=) You should not rewrite unneeded HTML tags. Default would be good enough for most usage. Older PHP uses url_rewriter.tags for this.

  • session.trans_sid_hosts=[limitted hosts]

    (PHP 7.1.0 >=) This INI defines whitelist hosts that allows trans sid rewrite. Never add untrusted host. Session module allow only $_SERVER['HTTP_HOST'] when this setting is empty.

  • session.referer_check=[your originating URL]

    When session.use_trans_sid is enabled, use of this setting is recommended. It reduces risk of session ID injection. If your site is http://example.com/, set http://example.com/ to it. Note that when HTTPS is used, browser will not send referrer header. Browser may not send referrer header by configuration. Therefore, this setting is not reliable security measure.

  • session.cache_limiter=nocache

    Make sure HTTP contents are not cached for authenticated session. Allow caching only when contents is not private. Otherwise, contents may be exposed. "private" may be used if HTTP content does not include security sensitive data. Note that "private" may leave private data cached by shared clients. "public" may be used only when HTTP content does not contain any private data at all.

  • session.sid_length="48"

    (PHP 7.1.0 >=) Longer session ID results in stronger session ID. Developer should consider session ID length 32 chars or more. At least 26 chars is required when session.sid_bits_per_character="5".

  • session.sid_bits_per_character="6"

    (PHP 7.1.0 >=) The more bits in a session ID char, session module generates stronger session ID for the same session ID length.

  • session.hash_function="sha256"

    (PHP 7.1.0 <) Stronger hash function will generates stronger session ID. Although hash collision is unlikely even with MD5 hash, developers should use SHA-2 or stronger hash functions for the task. Developers may use stronger hashes like sha384 and sha512. Make sure you feed long enough entropy for the hash function used.

Session Management Basics
Func?ii de sesiuni
Sessions and Security


Func?ii de sesiuni

Cuprins

  • session_abort — Discard session array changes and finish session
  • session_cache_expire — Return current cache expire
  • session_cache_limiter — Get and/or set the current cache limiter
  • session_commit — Pseudonim pentru session_write_close
  • session_create_id — Create new session id
  • session_decode — Decodes session data from a session encoded string
  • session_destroy — Destroys all data registered to a session
  • session_encode — Encodes the current session data as a session encoded string
  • session_gc — Perform session data garbage collection
  • session_get_cookie_params — Get the session cookie parameters
  • session_id — Get and/or set the current session id
  • session_is_registered — Find out whether a global variable is registered in a session
  • session_module_name — Get and/or set the current session module
  • session_name — Get and/or set the current session name
  • session_regenerate_id — Update the current session id with a newly generated one
  • session_register_shutdown — Session shutdown function
  • session_register — Register one or more global variables with the current session
  • session_reset — Re-initialize session array with original values
  • session_save_path — Get and/or set the current session save path
  • session_set_cookie_params — Set the session cookie parameters
  • session_set_save_handler — Sets user-level session storage functions
  • session_start — Start new or resume existing session
  • session_status — Returns the current session status
  • session_unregister — Unregister a global variable from the current session
  • session_unset — Free all session variables
  • session_write_close — Write session data and end session
Securing Session INI Settings
session_abort
Sessions


Discard session array changes and finish session

Func?ii de sesiuni
session_cache_expire
Func?ii de sesiuni
PHP Manual

session_abort

(PHP 5 >= 5.6.0, PHP 7)

session_abort — Discard session array changes and finish session

Descrierea

void session_abort ( void )

session_abort() finishes session without saving data. Thus the original values in session data are kept.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • $_SESSION
  • The session.auto_start configuration directive
  • session_start() - Start new or resume existing session
  • session_reset() - Re-initialize session array with original values
  • session_commit() - Pseudonim pentru session_write_close

Func?ii de sesiuni
session_cache_expire
Func?ii de sesiuni


Return current cache expire

session_abort
session_cache_limiter
Func?ii de sesiuni
PHP Manual

session_cache_expire

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

session_cache_expire — Return current cache expire

Descrierea

int session_cache_expire ([ string $new_cache_expire ] )

session_cache_expire() returns the current setting of session.cache_expire.

The cache expire is reset to the default value of 180 stored in session.cache_expire at request startup time. Thus, you need to call session_cache_expire() for every request (and before session_start() is called).

Parametri

new_cache_expire

If new_cache_expire is given, the current cache expire is replaced with new_cache_expire.

Nota: Setting new_cache_expire is of value only, if session.cache_limiter is set to a value different from nocache.

Valorile întoarse

Returns the current setting of session.cache_expire. The value returned should be read in minutes, defaults to 180.

Exemple

Example #1 session_cache_expire() example

<?php

/* set the cache limiter to 'private' */

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

/* set the cache expire to 30 minutes */
session_cache_expire(30);
$cache_expire = session_cache_expire();

/* start the session */

session_start();

echo "The cache limiter is now set to $cache_limiter<br />";
echo "The cached session pages expire after $cache_expire minutes";
?>

A se vedea ?i

  • session.cache_expire
  • session.cache_limiter
  • session_cache_limiter() - Get and/or set the current cache limiter

session_abort
session_cache_limiter
Func?ii de sesiuni


Get and/or set the current cache limiter

session_cache_expire
session_commit
Func?ii de sesiuni
PHP Manual

session_cache_limiter

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

session_cache_limiter — Get and/or set the current cache limiter

Descrierea

string session_cache_limiter ([ string $cache_limiter ] )

session_cache_limiter() returns the name of the current cache limiter.

The cache limiter defines which cache control HTTP headers are sent to the client. These headers determine the rules by which the page content may be cached by the client and intermediate proxies. Setting the cache limiter to nocache disallows any client/proxy caching. A value of public permits caching by proxies and the client, whereas private disallows caching by proxies and permits the client to cache the contents.

In private mode, the Expire header sent to the client may cause confusion for some browsers, including Mozilla. You can avoid this problem by using private_no_expire mode. The Expire header is never sent to the client in this mode.

Setting the cache limiter to '' will turn off automatic sending of cache headers entirely.

The cache limiter is reset to the default value stored in session.cache_limiter at request startup time. Thus, you need to call session_cache_limiter() for every request (and before session_start() is called).

Parametri

cache_limiter

If cache_limiter is specified, the name of the current cache limiter is changed to the new value.

Possible values
Value Headers sent
public
Expires: (sometime in the future, according session.cache_expire)
Cache-Control: public, max-age=(sometime in the future, according to session.cache_expire)
Last-Modified: (the timestamp of when the session was last saved)
private_no_expire
Cache-Control: private, max-age=(session.cache_expire in the future), pre-check=(session.cache_expire in the future)
Last-Modified: (the timestamp of when the session was last saved)
private
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: private, max-age=(session.cache_expire in the future), pre-check=(session.cache_expire in the future)
Last-Modified: (the timestamp of when the session was last saved)
nocache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

Valorile întoarse

Returns the name of the current cache limiter.

Exemple

Example #1 session_cache_limiter() example

<?php

/* set the cache limiter to 'private' */

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

echo "The cache limiter is now set to $cache_limiter<br />";
?>

A se vedea ?i

  • session.cache_limiter

session_cache_expire
session_commit
Func?ii de sesiuni


Pseudonim pentru session_write_close

session_cache_limiter
session_create_id
Func?ii de sesiuni
PHP Manual

session_commit

(PHP 4 >= 4.4.0, PHP 5, PHP 7)

session_commit — Pseudonim pentru session_write_close()

Descrierea

Aceasta func?ie este pseudonim pentru: session_write_close().

session_cache_limiter
session_create_id
Func?ii de sesiuni


Create new session id

session_commit
session_decode
Func?ii de sesiuni
PHP Manual

session_create_id

(PHP 7 >= 7.1.0)

session_create_id — Create new session id

Descrierea

string session_create_id ([ string $prefix ] )

session_create_id() is used to create new session id for the current session. It returns collision free session id.

If session is not active, collision check is omitted.

Session ID is created according to php.ini settings.

It is important to use the same user ID of your web server for GC task script. Otherwise, you may have permission problems especially with files save handler.

Parametri

prefix

If prefix is specified, new session id is prefixed by prefix. Not all characters are allowed within the session id. Characters in the range a-z A-Z 0-9 , (comma) and - (minus) are allowed.

Valorile întoarse

session_create_id() returns new collision free session id for the current session. If it is used without active session, it omits collision check.

Exemple

Example #1 session_create_id() example with session_regenerate_id()

<?php
// My session start function support timestamp management
function my_session_start() {
    session_start();
    // Do not allow to use too old session ID
    if (!empty($_SESSION['deleted_time']) && $_SESSION['deleted_time'] < time() - 180) {
        session_destroy();
        session_start();
    }
}

// My session regenerate id function
function my_session_regenerate_id() {
    // Call session_create_id() while session is active to
    // make sure collision free.
    if (session_status() != PHP_SESSION_ACTIVE) {
        session_start();
    }
    // WARNING: Never use confidential strings for prefix!
    $newid = session_create_id('myprefix-');
    // Set deleted timestamp. Session data must not be deleted immediately for reasons.
    $_SESSION['deleted_time'] = time();
    // Finish session
    session_commit();
    // Make sure to accept user defined session ID
    // NOTE: You must enable use_strict_mode for normal operations.
    ini_set('session.use_strict_mode', 0);
    // Set new custome session ID
    session_id($newid);
    // Start with custome session ID
    session_start();
}

// Make sure use_strict_mode is enabled.
// use_strict_mode is mandatory for security reasons.
ini_set('session.use_strict_mode', 1);
my_session_start();

// Session ID must be regenerated when
//  - User logged in
//  - User logged out
//  - Certain period has passed
my_session_regenerate_id();

// Write useful codes
?>

A se vedea ?i

  • session_regenerate_id() - Update the current session id with a newly generated one
  • session_start() - Start new or resume existing session
  • session.use_strict_mode

session_commit
session_decode
Func?ii de sesiuni


Decodes session data from a session encoded string

session_create_id
session_destroy
Func?ii de sesiuni
PHP Manual

session_decode

(PHP 4, PHP 5, PHP 7)

session_decode — Decodes session data from a session encoded string

Descrierea

bool session_decode ( string $data )

session_decode() decodes the serialized session data provided in $data, and populates the $_SESSION superglobal with the result.

By default, the unserialization method used is internal to PHP, and is not the same as unserialize(). The serialization method can be set using session.serialize_handler.

Parametri

data

The encoded data to be stored.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • session_encode() - Encodes the current session data as a session encoded string
  • session.serialize_handler

session_create_id
session_destroy
Func?ii de sesiuni


Destroys all data registered to a session

session_decode
session_encode
Func?ii de sesiuni
PHP Manual

session_destroy

(PHP 4, PHP 5, PHP 7)

session_destroy — Destroys all data registered to a session

Descrierea

bool session_destroy ( void )

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

Nota: You do not have to call session_destroy() from usual code. Cleanup $_SESSION array rather than destroying session data.

In order to kill the session altogether, the session ID must also be unset. If a cookie is used to propagate the session ID (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

When session.use_strict_mode is enabled. You do not have to remove obsolete session ID cookie because session module will not accept session ID cookie when there is no data associated to the session ID and set new session ID cookie. Enabling session.use_strict_mode is recommended for all sites.

Avertizare

Immediate session deletion may cause unwanted results. When there is concurrent requests, other connections may see sudden session data loss. e.g. Requests from JavaScript and/or requests from URL links.

Although current session module does not accept empty session ID cookie, but immediate session deletion may result in empty session ID cookie due to client(browser) side race condition. This will result that the client creates many session ID needlessly.

To avoid these, you must set deletion time-stamp to $_SESSION and reject access while later. Or make sure your application does not have concurrent requests. This applies to session_regenerate_id() also.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Destroying a session with $_SESSION

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

Note

Nota:

Only use session_unset() for older deprecated code that does not use $_SESSION.

A se vedea ?i

  • session.use_strict_mode
  • session_reset() - Re-initialize session array with original values
  • session_regenerate_id() - Update the current session id with a newly generated one
  • unset() - Elimina o variabila data
  • setcookie() - Send a cookie

session_decode
session_encode
Func?ii de sesiuni


Encodes the current session data as a session encoded string

session_destroy
session_gc
Func?ii de sesiuni
PHP Manual

session_encode

(PHP 4, PHP 5, PHP 7)

session_encode — Encodes the current session data as a session encoded string

Descrierea

string session_encode ( void )

session_encode() returns a serialized string of the contents of the current session data stored in the $_SESSION superglobal.

By default, the serialization method used is internal to PHP, and is not the same as serialize(). The serialization method can be set using session.serialize_handler.

Valorile întoarse

Returns the contents of the current session encoded.

Note

Avertizare

Must call session_start() before using session_encode().

A se vedea ?i

  • session_decode() - Decodes session data from a session encoded string
  • session.serialize_handler

session_destroy
session_gc
Func?ii de sesiuni


Perform session data garbage collection

session_encode
session_get_cookie_params
Func?ii de sesiuni
PHP Manual

session_gc

(No version information available, might only be in Git)

session_gc — Perform session data garbage collection

Descrierea

int session_gc ( void )

session_gc() is used to perform session data GC(garbage collection). PHP does probability based session GC by default.

Probability based GC works somewhat but it has few problems. 1) Low traffic site's session data may not be deleted within preferred duration. 2) High traffic site's may have too frequent GC. 3) GC is performed on the user's request and the user will experience GC delay.

Therefore, it is recommended to execute GC periodically for production systems. e.g. Use "cron" for UNIX like systems. Make sure to disable probability based GC by setting session.gc_probability to 0.

Valorile întoarse

session_gc() returns number of deleted session data for success, FALSE for failure.

Old save handlers do not return number of deleted session data, but only success/failure flag. If this is the case, number of deleted session data became 1 regardless of actually deleted data.

Exemple

Example #1 session_gc() example for task managers like cron

<?php
// Note: This script should be executed by the same user of web server process.

// Need active session to initialize session data storage access.
session_start();

// Executes GC immediately
session_gc();

// Clean up session ID created by session_gc()
session_destroy();
?>

Example #2 session_gc() example for user accessible script

<?php
// Note: session_gc() is recommended to be used by task manager script, but
// it may be used as follows.

// Used for last GC time check
$gc_time = '/tmp/php_session_last_gc';
$gc_period = 1800;

session_start();
// Execute GC only when GC period elapsed.
// i.e. Calling session_gc() every request is waste of resources.
if (file_exists($gc_time)) {
    if (filemtime($gc_time) < time() - $gc_period) {
        session_gc();
        touch($gc_time);
    }
} else {
    touch($gc_time);
}
?>

A se vedea ?i

  • session_start() - Start new or resume existing session
  • session_destroy() - Destroys all data registered to a session
  • session.gc_probability

session_encode
session_get_cookie_params
Func?ii de sesiuni


Get the session cookie parameters

session_gc
session_id
Func?ii de sesiuni
PHP Manual

session_get_cookie_params

(PHP 4, PHP 5, PHP 7)

session_get_cookie_params — Get the session cookie parameters

Descrierea

array session_get_cookie_params ( void )

Gets the session cookie parameters.

Valorile întoarse

Returns an array with the current session cookie information, the array contains the following items:

  • "lifetime" - The lifetime of the cookie in seconds.
  • "path" - The path where information is stored.
  • "domain" - The domain of the cookie.
  • "secure" - The cookie should only be sent over secure connections.
  • "httponly" - The cookie can only be accessed through the HTTP protocol.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | The "httponly" entry was added in the returned array.

A se vedea ?i

  • session.cookie_lifetime
  • session.cookie_path
  • session.cookie_domain
  • session.cookie_secure
  • session.cookie_httponly
  • session_set_cookie_params() - Set the session cookie parameters

session_gc
session_id
Func?ii de sesiuni


Get and/or set the current session id

session_get_cookie_params
session_is_registered
Func?ii de sesiuni
PHP Manual

session_id

(PHP 4, PHP 5, PHP 7)

session_id — Get and/or set the current session id

Descrierea

string session_id ([ string $id ] )

session_id() is used to get or set the session id for the current session.

The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs. See also Session handling.

Parametri

id

If id is specified, it will replace the current session id. session_id() needs to be called before session_start() for that purpose. Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus)!

Nota: When using session cookies, specifying an id for session_id() will always send a new cookie when session_start() is called, regardless if the current session id is identical to the one being set.

Valorile întoarse

session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).

A se vedea ?i

  • session_regenerate_id() - Update the current session id with a newly generated one
  • session_start() - Start new or resume existing session
  • session_set_save_handler() - Sets user-level session storage functions
  • session.save_handler

session_get_cookie_params
session_is_registered
Func?ii de sesiuni


Find out whether a global variable is registered in a session

session_id
session_module_name
Func?ii de sesiuni
PHP Manual

session_is_registered

(PHP 4, PHP 5 < 5.4.0)

session_is_registered — Find out whether a global variable is registered in a session

Descrierea

bool session_is_registered ( string $name )

Finds out whether a global variable is registered in a session.

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

Parametri

name

The variable name.

Valorile întoarse

session_is_registered() returns TRUE if there is a global variable with the name name registered in the current session, FALSE otherwise.

Note

Nota:

If $_SESSION is used, use isset() to check a variable is registered in $_SESSION.

Precautie

If you are using $_SESSION
(or $HTTP_SESSION_VARS), do not use
session_register(),
session_is_registered() and
session_unregister().

session_id
session_module_name
Func?ii de sesiuni


Get and/or set the current session module

session_is_registered
session_name
Func?ii de sesiuni
PHP Manual

session_module_name

(PHP 4, PHP 5, PHP 7)

session_module_name — Get and/or set the current session module

Descrierea

string session_module_name ([ string $module ] )

session_module_name() gets the name of the current session module.

Parametri

module

If module is specified, that module will be used instead.

Valorile întoarse

Returns the name of the current session module.

session_is_registered
session_name
Func?ii de sesiuni


Get and/or set the current session name

session_module_name
session_regenerate_id
Func?ii de sesiuni
PHP Manual

session_name

(PHP 4, PHP 5, PHP 7)

session_name — Get and/or set the current session name

Descrierea

string session_name ([ string $name ] )

session_name() returns the name of the current session. If name is given, session_name() will update the session name and return the old session name.

The session name is reset to the default value stored in session.name at request startup time. Thus, you need to call session_name() for every request (and before session_start() or session_register() are called).

Parametri

name

The session name references the name of the session, which is used in cookies and URLs (e.g. PHPSESSID). It should contain only alphanumeric characters; it should be short and descriptive (i.e. for users with enabled cookie warnings). If name is specified, the name of the current session is changed to its value.

Avertizare

The session name can't consist of digits only, at least one letter must be present. Otherwise a new session id is generated every time.

Valorile întoarse

Returns the name of the current session. If name is given and function updates the session name, name of the old session is returned.

Exemple

Example #1 session_name() example

<?php

/* set the session name to WebsiteID */

$previous_name = session_name("WebsiteID");

echo "The previous session name was $previous_name<br />";
?>

A se vedea ?i

  • The session.name configuration directive

session_module_name
session_regenerate_id
Func?ii de sesiuni


Update the current session id with a newly generated one

session_name
session_register_shutdown
Func?ii de sesiuni
PHP Manual

session_regenerate_id

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

session_regenerate_id — Update the current session id with a newly generated one

Descrierea

bool session_regenerate_id ([ bool $delete_old_session = false ] )

session_regenerate_id() will replace the current session id with a new one, and keep the current session information.

When session.use_trans_sid is enabled, output must be started after session_regenerate_id() call. Otherwise, old session ID is used.

Avertizare

Current session_regenerate_id does not handle unstable network well. e.g. Mobile and WiFi network. Therefore, you may experience lost session by calling session_regenerate_id.

You should not destroy old session data immediately, but should use destroy time-stamp and control access to old session ID. Otherwise, concurrent access to page may result in inconsistent state, or you may have lost session, or it may cause client(browser) side race condition and may create many session ID needlessly. Immediate session data deletion disables session hijack attack detection and prevention also.

Parametri

delete_old_session

Whether to delete the old associated session file or not. You should not delete old session if you need to avoid races caused by deletion or detect/avoid session hijack attacks.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | session_regenerate_id() saves old session data before closing.
5.1.0 | Added the delete_old_session parameter.
4.3.3 | Since then, if session cookies are enabled, use of session_regenerate_id() will also submit a new session cookie with the new session id.

Exemple

Example #1 A session_regenerate_id() example

<?php
// NOTE: This code is not fully working code, but an example!

session_start();

// Check destroyed time-stamp
if (isset($_SESSION['destroyed'])
    && $_SESSION['destroyed'] < time() - 300) {
    // Should not happen usually. This could be attack or due to unstable network.
    // Remove all authentication status of this users session.
    remove_all_authentication_flag_from_active_sessions($_SESSION['userid']);
    throw(new DestroyedSessionAccessException);
}

$old_sessionid = session_id();

// Set destroyed timestamp
$_SESSION['destroyed'] = time(); // Since PHP 7.0.0 and up, session_regenerate_id() saves old session data

// Simply calling session_regenerate_id() may result in lost session, etc.
// See next example.
session_regenerate_id();

// New session does not need destroyed timestamp
unset($_SESSION['destroyed']);

$new_sessionid = session_id();

echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";

print_r($_SESSION);
?>

Current session module does not handle unstable network well. You should manage session ID to avoid lost session by session_regenerate_id.

Example #2 Avoiding lost session by session_regenerate_id()

<?php
// NOTE: This code is not fully working code, but an example!
// my_session_start() and my_session_regenerate_id() avoid lost sessions by
// unstable network. In addition, this code may prevent exploiting stolen
// session by attackers.

function my_session_start() {
    session_start();
    if (isset($_SESSION['destroyed'])) {
       if ($_SESSION['destroyed'] < time()-300) {
           // Should not happen usually. This could be attack or due to unstable network.
           // Remove all authentication status of this users session.
           remove_all_authentication_flag_from_active_sessions($_SESSION['userid']);
           throw(new DestroyedSessionAccessException);
       }
       if (isset($_SESSION['new_session_id'])) {
           // Not fully expired yet. Could be lost cookie by unstable network.
           // Try again to set proper session ID cookie.
           // NOTE: Do not try to set session ID again if you would like to remove
           // authentication flag.
           session_commit();
           session_id($_SESSION['new_session_id']);
           // New session ID should exist
           settion_start();
           return;
       }
   }
}

function my_session_regenerate_id() {
    // New session ID is required to set proper session ID
    // when session ID is not set due to unstable network.
    $new_session_id = session_create_id();
    $_SESSION['new_session_id'] = $new_session_id;

    // Set destroy timestamp
    $_SESSION['destroyed'] = time();

    // Write and close current session;
    session_commit();

    // Start session with new session ID
    session_id($new_session_id);
    ini_set('session.use_strict_mode', 0);
    session_start();
    ini_set('session.use_strict_mode', 1);

    // New session does not need them
    unset($_SESSION['destroyed']);
    unset($_SESSION['new_session_id']);
}
?>

A se vedea ?i

  • session_id() - Get and/or set the current session id
  • session_create_id() - Create new session id
  • session_start() - Start new or resume existing session
  • session_destroy() - Destroys all data registered to a session
  • session_reset() - Re-initialize session array with original values
  • session_name() - Get and/or set the current session name

session_name
session_register_shutdown
Func?ii de sesiuni


Session shutdown function

session_regenerate_id
session_register
Func?ii de sesiuni
PHP Manual

session_register_shutdown

(PHP >=5.4.0)

session_register_shutdown — Session shutdown function

Descrierea

void session_register_shutdown ( void )

Registers session_write_close() as a shutdown function.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Emits E_WARNING if registering the shutdown function fails.

session_regenerate_id
session_register
Func?ii de sesiuni


Register one or more global variables with the current session

session_register_shutdown
session_reset
Func?ii de sesiuni
PHP Manual

session_register

(PHP 4, PHP 5 < 5.4.0)

session_register — Register one or more global variables with the current session

Descrierea

bool session_register ( mixed $name [, mixed $... ] )

session_register() accepts a variable number of arguments, any of which can be either a string holding the name of a variable or an array consisting of variable names or other arrays. For each name, session_register() registers the global variable with that name in the current session.

You can also create a session variable by simply setting the appropriate member of the $_SESSION array.

<?php
// Use of session_register() is deprecated
$barney = "A big purple dinosaur.";
session_register("barney");

// Use of $_SESSION is preferred
$_SESSION["zim"] = "An invader from another planet.";
?>

If session_start() was not called before this function is called, an implicit call to session_start() with no parameters will be made. $_SESSION does not mimic this behavior and requires session_start() before use.

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

Parametri

name

A string holding the name of a variable or an array consisting of variable names or other arrays.

...

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Precautie

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

Nota: register_globals: nota importanta

Începând cu PHP 4.2.0, valoarea implicita pentru directiva PHP register_globals este off. Comunitatea PHP îi încurajeaza pe to?i programatorii sa nu se bazeze pe aceasta directiva, dar sa utilizeze alte mijloace, cum ar fi superglobals.

Precautie

This registers a global variable. If you want to register a session variable from within a function, you need to make sure to make it global using the global keyword or the $GLOBALS[] array, or use the special session arrays as noted below.

Precautie

If you are using $_SESSION, do not use
session_register(),
session_is_registered(), and
session_unregister().

Nota:

It is currently impossible to register resource variables in a session. For example, you cannot create a connection to a database and store the connection id as a session variable and expect the connection to still be valid the next time the session is restored. PHP functions that return a resource are identified by having a return type of resource in their function definition. A list of functions that return resources are available in the resource types appendix.

If $_SESSION is used, assign values to $_SESSION. For example: $_SESSION['var'] = 'ABC';

A se vedea ?i

  • session_is_registered() - Find out whether a global variable is registered in a session
  • session_unregister() - Unregister a global variable from the current session
  • $_SESSION

session_register_shutdown
session_reset
Func?ii de sesiuni


Re-initialize session array with original values

session_register
session_save_path
Func?ii de sesiuni
PHP Manual

session_reset

(PHP 5 >= 5.6.0, PHP 7)

session_reset — Re-initialize session array with original values

Descrierea

void session_reset ( void )

session_reset() reinitializes a session with original values stored in session storage. This function requires an active session and discards changes in $_SESSION.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • $_SESSION
  • The session.auto_start configuration directive
  • session_start() - Start new or resume existing session
  • session_abort() - Discard session array changes and finish session
  • session_commit() - Pseudonim pentru session_write_close

session_register
session_save_path
Func?ii de sesiuni


Get and/or set the current session save path

session_reset
session_set_cookie_params
Func?ii de sesiuni
PHP Manual

session_save_path

(PHP 4, PHP 5, PHP 7)

session_save_path — Get and/or set the current session save path

Descrierea

string session_save_path ([ string $path ] )

session_save_path() returns the path of the current directory used to save session data.

Parametri

path

Session data path. If specified, the path to which data is saved will be changed. session_save_path() needs to be called before session_start() for that purpose.

Nota:

On some operating systems, you may want to specify a path on a filesystem that handles lots of small files efficiently. For example, on Linux, reiserfs may provide better performance than ext2fs.

Valorile întoarse

Returns the path of the current directory used for data storage.

A se vedea ?i

  • The session.save_path configuration directive

session_reset
session_set_cookie_params
Func?ii de sesiuni


Set the session cookie parameters

session_save_path
session_set_save_handler
Func?ii de sesiuni
PHP Manual

session_set_cookie_params

(PHP 4, PHP 5, PHP 7)

session_set_cookie_params — Set the session cookie parameters

Descrierea

void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )

Set cookie parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script. Thus, you need to call session_set_cookie_params() for every request and before session_start() is called.

This function updates the runtime ini values of the corresponding PHP ini configuration keys which can be retrieved with the ini_get().

Parametri

lifetime

Lifetime of the session cookie, defined in seconds.

path

Path on the domain where the cookie will work. Use a single slash ('/') for all paths on the domain.

domain

Cookie domain, for example 'www.php.net'. To make cookies visible on all subdomains then the domain must be prefixed with a dot like '.php.net'.

secure

If TRUE cookie will only be sent over secure connections.

httponly

If set to TRUE then PHP will attempt to send the httponly flag when setting the session cookie.

Valorile întoarse

Nu este întoarsa nici o valoare.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | The httponly parameter was added.

A se vedea ?i

  • session.cookie_lifetime
  • session.cookie_path
  • session.cookie_domain
  • session.cookie_secure
  • session.cookie_httponly
  • session_get_cookie_params() - Get the session cookie parameters

session_save_path
session_set_save_handler
Func?ii de sesiuni


Sets user-level session storage functions

session_set_cookie_params
session_start
Func?ii de sesiuni
PHP Manual

session_set_save_handler

(PHP 4, PHP 5, PHP 7)

session_set_save_handler — Sets user-level session storage functions

Descrierea

bool session_set_save_handler ( callable $open , callable $close , callable $read , callable $write , callable $destroy , callable $gc [, callable $create_sid [, callable $validate_sid [, callable $update_timestamp ]]] )

Since PHP 5.4 it is possible to register the following prototype:

bool session_set_save_handler ( SessionHandlerInterface $sessionhandler [, bool $register_shutdown = true ] )

session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred, e.g. storing the session data in a local database.

Parametri

This function has two prototypes.

sessionhandler

An instance of a class implementing SessionHandlerInterface, such as SessionHandler, to register as the session handler. Since PHP 5.4 only.

register_shutdown

Register session_write_close() as a register_shutdown_function() function.

or
open(string $savePath, string $sessionName)

The open callback works like a constructor in classes and is executed when the session is being opened. It is the first callback function executed when the session is started automatically or manually with session_start(). Return value is TRUE for success, FALSE for failure.

close()

The close callback works like a destructor in classes and is executed after the session write callback has been called. It is also invoked when session_write_close() is called. Return value should be TRUE for success, FALSE for failure.

read(string $sessionId)

The read callback must always return a session encoded (serialized) string, or an empty string if there is no data to read.

This callback is called internally by PHP when the session starts or when session_start() is called. Before this callback is invoked PHP will invoke the open callback.

The value this callback returns must be in exactly the same serialized format that was originally passed for storage to the write callback. The value returned will be unserialized automatically by PHP and used to populate the $_SESSION superglobal. While the data looks similar to serialize() please note it is a different format which is speficied in the session.serialize_handler ini setting.

write(string $sessionId, string $data)

The write callback is called when the session needs to be saved and closed. This callback receives the current session ID a serialized version the $_SESSION superglobal. The serialization method used internally by PHP is specified in the session.serialize_handler ini setting.

The serialized session data passed to this callback should be stored against the passed session ID. When retrieving this data, the read callback must return the exact value that was originally passed to the write callback.

This callback is invoked when PHP shuts down or explicitly when session_write_close() is called. Note that after executing this function PHP will internally execute the close callback.

Nota:

The "write" handler is not executed until after the output stream is closed. Thus, output from debugging statements in the "write" handler will never be seen in the browser. If debugging output is necessary, it is suggested that the debug output be written to a file instead.

destroy($sessionId)

This callback is executed when a session is destroyed with session_destroy() or with session_regenerate_id() with the destroy parameter set to TRUE. Return value should be TRUE for success, FALSE for failure.

gc($lifetime)

The garbage collector callback is invoked internally by PHP periodically in order to purge old session data. The frequency is controlled by session.gc_probability and session.gc_divisor. The value of lifetime which is passed to this callback can be set in session.gc_maxlifetime. Return value should be TRUE for success, FALSE for failure.

create_sid()

This callback is executed when a new session ID is required. No parameters are provided, and the return value should be a string that is a valid session ID for your handler.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Custom session handler: see full code in SessionHandlerInterface synposis.

The following code is for PHP version 5.4.0 and above. We just show the invokation here, the full example can be seen in the SessionHandlerInterface synposis linked above.

Note we use the OOP prototype with session_set_save_handler() and register the shutdown function using the function's parameter flag. This is generally advised when registering objects as session save handlers.

<?php
class MySessionHandler implements SessionHandlerInterface
{
    // implement interfaces here
}

$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();

// proceed to set and retrieve values by key from $_SESSION

Example #2 Custom session save handler using objects

The following code is for PHP versions less than 5.4.0.

The following example provides file based session storage similar to the PHP sessions default save handler files. This example could easily be extended to cover database storage using your favorite PHP supported database engine.

Note we additionally register the shutdown function session_write_close() using register_shutdown_function() under PHP less than 5.4.0. This is generally advised when registering objects as session save handlers under PHP less than 5.4.0.

<?php
class FileSessionHandler
{
    private $savePath;

    function open($savePath, $sessionName)
    {
        $this->savePath = $savePath;
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath, 0777);
        }

        return true;
    }

    function close()
    {
        return true;
    }

    function read($id)
    {
        return (string)@file_get_contents("$this->savePath/sess_$id");
    }

    function write($id, $data)
    {
        return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
    }

    function destroy($id)
    {
        $file = "$this->savePath/sess_$id";
        if (file_exists($file)) {
            unlink($file);
        }

        return true;
    }

    function gc($maxlifetime)
    {
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }
}

$handler = new FileSessionHandler();
session_set_save_handler(
    array($handler, 'open'),
    array($handler, 'close'),
    array($handler, 'read'),
    array($handler, 'write'),
    array($handler, 'destroy'),
    array($handler, 'gc')
    );

// the following prevents unexpected effects when using objects as save handlers
register_shutdown_function('session_write_close');

session_start();
// proceed to set and retrieve values by key from $_SESSION

Note

Avertizare

When using objects as session save handlers, it is important to register the shutdown function with PHP to avoid unexpected side-effects from the way PHP internally destroys objects on shutdown and may prevent the write and close from being called. Typically you should register 'session_write_close' using the register_shutdown_function() function.

As of PHP 5.4.0 you can use session_register_shutdown() or simply use the 'register shutdown' flag when invoking session_set_save_handler() using the OOP method and passing an instance that implements SessionHandlerInterface.

Avertizare

As of PHP 5.0.5 the write and close handlers are called after object destruction and therefore cannot use objects or throw exceptions. Exceptions are not able to be caught since will not be caught nor will any exception trace be displayed and the execution will just cease unexpectedly. The object destructors can however use sessions.

It is possible to call session_write_close() from the destructor to solve this chicken and egg problem but the most reliable way is to register the shutdown function as described above.

Avertizare

Current working directory is changed with some SAPIs if session is closed in the script termination. It is possible to close the session earlier with session_write_close().

Istoricul schimbarilor

Versiune | Descriere
5.5.1 | Added the optional create_sid parameter.
5.4.0 | Added SessionHandlerInterface for implementing session handlers and SessionHandler to expose internal PHP session handlers.

A se vedea ?i

  • The session.save_handler configuration directive
  • The session.serialize_handler configuration directive.
  • The register_shutdown_function() - Register a function for execution on shutdown
  • The session_register_shutdown() - Session shutdown function for PHP 5.4.0+
  • Refer to » save_handler.inc for a full procedural reference implementation

session_set_cookie_params
session_start
Func?ii de sesiuni


Start new or resume existing session

session_set_save_handler
session_status
Func?ii de sesiuni
PHP Manual

session_start

(PHP 4, PHP 5, PHP 7)

session_start — Start new or resume existing session

Descrierea

bool session_start ([ array $options = [] ] )

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by session_set_save_handler(). The read callback will retrieve any existing session data (stored in a special serialized format) and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling.

To use a named session, call session_name() before calling session_start().

When session.use_trans_sid is enabled, the session_start() function will register an internal output handler for URL rewriting.

If a user uses ob_gzhandler or similar with ob_start(), the function order is important for proper output. For example, ob_gzhandler must be registered before starting the session.

Parametri

options

If provided, this is an associative array of options that will override the currently set session configuration directives. The keys should not include the session. prefix.

In addition to the normal set of configuration directives, a read_and_close option may also be provided. If set to TRUE, this will result in the session being closed immediately after being read, thereby avoiding unnecessary locking if the session data won't be changed.

Valorile întoarse

This function returns TRUE if a session was successfully started, otherwise FALSE.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | The options parameter was added.
5.3.0 | If a session fails to start, then FALSE is returned. Previously TRUE was returned.
4.3.3 | As of PHP 4.3.3, calling session_start() after the session was previously started will result in an error of level E_NOTICE. Also, the second session start will simply be ignored.

Exemple

A basic session example

Example #1 page1.php

<?php
// page1.php

session_start();

echo 'Welcome to page #1';

$_SESSION['favcolor'] = 'green';
$_SESSION['animal']   = 'cat';
$_SESSION['time']     = time();

// Works if session cookie was accepted
echo '<br /><a href="page2.php">page 2</a>';

// Or maybe pass along the session id, if needed
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
?>

After viewing page1.php, the second page page2.php will magically contain the session data. Read the session reference for information on propagating session ids as it, for example, explains what the constant SID is all about.

Example #2 page2.php

<?php
// page2.php

session_start();

echo 'Welcome to page #2<br />';

echo $_SESSION['favcolor']; // green
echo $_SESSION['animal'];   // cat
echo date('Y m d H:i:s', $_SESSION['time']);

// You may want to use SID here, like we did in page1.php
echo '<br /><a href="page1.php">page 1</a>';
?>

Providing options to session_start()

Example #3 Overriding the cookie lifetime

<?php
// This sends a persistent cookie that lasts a day.
session_start([
    'cookie_lifetime' => 86400,
]);
?>

Example #4 Reading the session and closing it

<?php
// If we know we don't need to change anything in the
// session, we can just read and close rightaway to avoid
// locking the session file and blocking other pages
session_start([
    'cookie_lifetime' => 86400,
    'read_and_close'  => true,
]);

Note

Nota:

To use cookie-based sessions, session_start() must be called before outputing anything to the browser.

Nota:

Use of zlib.output_compression is recommended instead of ob_gzhandler()

Nota:

This function sends out several HTTP headers depending on the configuration. See session_cache_limiter() to customize these headers.

A se vedea ?i

  • $_SESSION
  • The session.auto_start configuration directive
  • session_id() - Get and/or set the current session id

session_set_save_handler
session_status
Func?ii de sesiuni


Returns the current session status

session_start
session_unregister
Func?ii de sesiuni
PHP Manual

session_status

(PHP >=5.4.0)

session_status — Returns the current session status

Descrierea

int session_status ( void )

session_status() is used to return the current session status.

Valorile întoarse

  • 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.

A se vedea ?i

  • session_start() - Start new or resume existing session
session_start
session_unregister
Func?ii de sesiuni


Unregister a global variable from the current session

session_status
session_unset
Func?ii de sesiuni
PHP Manual

session_unregister

(PHP 4, PHP 5 < 5.4.0)

session_unregister — Unregister a global variable from the current session

Descrierea

bool session_unregister ( string $name )

session_unregister() unregisters the global variable named name from the current session.

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

Parametri

name

The variable name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Note

Nota:

If $_SESSION is used, use unset() to unregister a session variable. Do not unset() $_SESSION itself as this will disable the special function of the $_SESSION superglobal.

Precautie

This function does not unset the corresponding global variable for name, it only prevents the variable from being saved as part of the session. You must call unset() to remove the corresponding global variable.

Precautie

If you are using $_SESSION (or
$HTTP_SESSION_VARS), do not use
session_register(),
session_is_registered() and
session_unregister().

session_status
session_unset
Func?ii de sesiuni


Free all session variables

session_unregister
session_write_close
Func?ii de sesiuni
PHP Manual

session_unset

(PHP 4, PHP 5, PHP 7)

session_unset — Free all session variables

Descrierea

void session_unset ( void )

The session_unset() function frees all session variables currently registered.

Valorile întoarse

Nu este întoarsa nici o valoare.

Note

Nota:

If $_SESSION is used, use unset() to unregister a session variable, i.e. unset ($_SESSION['varname']);.

Precautie

Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

session_unregister
session_write_close
Func?ii de sesiuni


Write session data and end session

session_unset
SessionHandler
Func?ii de sesiuni
PHP Manual

session_write_close

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

session_write_close — Write session data and end session

Descrierea

void session_write_close ( void )

End the current session and store session data.

Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • The session_register_shutdown() - Session shutdown function

session_unset
SessionHandler
Func?ii de sesiuni


The SessionHandler class

(PHP 5 >= 5.4.0, PHP 7)

Introducere

SessionHandler is a special class that can be used to expose the current internal PHP session save handler by inheritance. There are seven methods which wrap the seven internal session save handler callbacks (open, close, read, write, destroy, gc and create_sid). By default, this class will wrap whatever internal save handler is set as defined by the session.save_handler configuration directive which is usually files by default. Other internal session save handlers are provided by PHP extensions such as SQLite (as sqlite), Memcache (as memcache), and Memcached (as memcached).

When a plain instance of SessionHandler is set as the save handler using session_set_save_handler() it will wrap the current save handlers. A class extending from SessionHandler allows you to override the methods or intercept or filter them by calls the parent class methods which ultimately wrap the interal PHP session handlers.

This allows you, for example, to intercept the read and write methods to encrypt/decrypt the session data and then pass the result to and from the parent class. Alternatively one might chose to entirely override a method like the garbage collection callback gc.

Because the SessionHandler wraps the current internal save handler methods, the above example of encryption can be applied to any internal save handler without having to know the internals of the handlers.

To use this class, first set the save handler you wish to expose using session.save_handler and then pass an instance of SessionHandler or one extending it to session_set_save_handler().

Please note the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code. The return values are equally processed internally by PHP. For more information on the session workflow, please refer session_set_save_handler().

Sinopsisul clasei

SessionHandler implements SessionHandlerInterface {
/* Metode */
public bool close ( void )
public string create_sid ( void )
public bool destroy ( string $session_id )
public bool gc ( int $maxlifetime )
public bool open ( string $save_path , string $session_name )
public string read ( string $session_id )
public bool write ( string $session_id , string $session_data )
}
Avertizare

This class is designed to expose the current internal PHP session save handler, if you want to write your own custom save handlers, please implement the SessionHandlerInterface interface instead of extending from SessionHandler.

Istoricul schimbarilor

Versiune | Descriere
5.5.1 | Added SessionHandler::create_sid().

Example #1 Using SessionHandler to add encryption to internal PHP save handlers.

<?php

 /**
  * decrypt AES 256
  *
  * @param data $edata
  * @param string $password
  * @return decrypted data
  */
function decrypt($edata, $password) {
    $data = base64_decode($edata);
    $salt = substr($data, 0, 16);
    $ct = substr($data, 16);

    $rounds = 3; // depends on key length
    $data00 = $password.$salt;
    $hash = array();
    $hash[0] = hash('sha256', $data00, true);
    $result = $hash[0];
    for ($i = 1; $i < $rounds; $i++) {
        $hash[$i] = hash('sha256', $hash[$i - 1].$data00, true);
        $result .= $hash[$i];
    }
    $key = substr($result, 0, 32);
    $iv  = substr($result, 32,16);

    return openssl_decrypt($ct, 'AES-256-CBC', $key, true, $iv);
  }

/**
 * crypt AES 256
 *
 * @param data $data
 * @param string $password
 * @return base64 encrypted data
 */
function encrypt($data, $password) {
    // Set a random salt
    $salt = openssl_random_pseudo_bytes(16);

    $salted = '';
    $dx = '';
    // Salt the key(32) and iv(16) = 48
    while (strlen($salted) < 48) {
      $dx = hash('sha256', $dx.$password.$salt, true);
      $salted .= $dx;
    }

    $key = substr($salted, 0, 32);
    $iv  = substr($salted, 32,16);

    $encrypted_data = openssl_encrypt($data, 'AES-256-CBC', $key, true, $iv);
    return base64_encode($salt . $encrypted_data);
}

class EncryptedSessionHandler extends SessionHandler
{
    private $key;

    public function __construct($key)
    {
        $this->key = $key;
    }

    public function read($id)
    {
        $data = parent::read($id);

        if (!$data) {
            return "";
        } else {
            return decrypt($data, $this->key);
        }
    }

    public function write($id, $data)
    {
        $data = encrypt($data, $this->key);

        return parent::write($id, $data);
    }
}

// we'll intercept the native 'files' handler, but will equally work
// with other internal native handlers like 'sqlite', 'memcache' or 'memcached'
// which are provided by PHP extensions.
ini_set('session.save_handler', 'files');

$key = 'secret_string';
$handler = new EncryptedSessionHandler($key);
session_set_save_handler($handler, true);
session_start();

// proceed to set and retrieve values by key from $_SESSION

Nota:

Since this class' methods are designed to be called internally by PHP as part of the normal session workflow, child class calls to parent methods (i.e. the actual internal native handlers) will return FALSE unless the session has actually been started (either automatically, or by explicit session_start(). This is important to consider when writing unit tests where the class methods might be invoked manually.

Cuprins

  • SessionHandler::close — Close the session
  • SessionHandler::create_sid — Return a new session ID
  • SessionHandler::destroy — Destroy a session
  • SessionHandler::gc — Cleanup old sessions
  • SessionHandler::open — Initialize session
  • SessionHandler::read — Read session data
  • SessionHandler::write — Write session data
session_write_close
SessionHandler::close
Sessions


Close the session

SessionHandler
SessionHandler::create_sid
SessionHandler
PHP Manual

SessionHandler::close

(PHP 5 >= 5.4.0, PHP 7)

SessionHandler::close — Close the session

Descrierea

public bool SessionHandler::close ( void )

Closes the current session. This method is automatically executed internally by PHP when closing the session, or explicitly via session_write_close() (which first calls the SessionHandler::write()).

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was activated by session_set_save_handler().

If this class is extended by inheritiance, calling the parent close method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows the method to be overidden and or intercepted.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::close().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Valoarea întoarsa (de regula TRUE în caz de succes, FALSE în caz de e?ec). Nota: aceasta valoare este întoarsa intern catre PHP pentru procesare.

SessionHandler
SessionHandler::create_sid
SessionHandler


Return a new session ID

SessionHandler::close
SessionHandler::destroy
SessionHandler
PHP Manual

SessionHandler::create_sid

(PHP 5 >= 5.5.1, PHP 7)

SessionHandler::create_sid — Return a new session ID

Descrierea

public string SessionHandler::create_sid ( void )

Generates and returns a new session ID.

Valorile întoarse

A session ID valid for the default session handler.

A se vedea ?i

  • session_id() - Get and/or set the current session id

SessionHandler::close
SessionHandler::destroy
SessionHandler


Destroy a session

SessionHandler::create_sid
SessionHandler::gc
SessionHandler
PHP Manual

SessionHandler::destroy

(PHP 5 >= 5.4.0, PHP 7)

SessionHandler::destroy — Destroy a session

Descrierea

public bool SessionHandler::destroy ( string $session_id )

Destroys a session. Called internally by PHP with session_regenerate_id() (assuming the $destroy is set to TRUE, by session_destroy() or when session_decode() fails.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent destroy method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows this method to be overidden and or intercepted and filtered.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::destroy().

Parametri

session_id

The session ID being destroyed.

Valorile întoarse

Valoarea întoarsa (de regula TRUE în caz de succes, FALSE în caz de e?ec). Nota: aceasta valoare este întoarsa intern catre PHP pentru procesare.

SessionHandler::create_sid
SessionHandler::gc
SessionHandler


Cleanup old sessions

SessionHandler::destroy
SessionHandler::open
SessionHandler
PHP Manual

SessionHandler::gc

(PHP 5 >= 5.4.0, PHP 7)

SessionHandler::gc — Cleanup old sessions

Descrierea

public bool SessionHandler::gc ( int $maxlifetime )

Cleans up expired sessions. Called randomly by PHP internally when a session starts or when session_start() is invoked. The frequency this is called is based on the session.gc_divisor and session.gc_probability configuration directives.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent gc method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows this method to be overidden and or intercepted and filtered.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::gc().

Parametri

maxlifetime

Sessions that have not updated for the last maxlifetime seconds will be removed.

Valorile întoarse

Valoarea întoarsa (de regula TRUE în caz de succes, FALSE în caz de e?ec). Nota: aceasta valoare este întoarsa intern catre PHP pentru procesare.

SessionHandler::destroy
SessionHandler::open
SessionHandler


Initialize session

SessionHandler::gc
SessionHandler::read
SessionHandler
PHP Manual

SessionHandler::open

(PHP 5 >= 5.4.0, PHP 7)

SessionHandler::open — Initialize session

Descrierea

public bool SessionHandler::open ( string $save_path , string $session_name )

Create new session, or re-initialize existing session. Called internally by PHP when a session starts either automatically or when session_start() is invoked.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent open method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows this method to be overidden and or intercepted and filtered.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::open().

Parametri

save_path

The path where to store/retrieve the session.

session_name

The session name.

Valorile întoarse

Valoarea întoarsa (de regula TRUE în caz de succes, FALSE în caz de e?ec). Nota: aceasta valoare este întoarsa intern catre PHP pentru procesare.

A se vedea ?i

  • The session.auto-start configuration directive.

SessionHandler::gc
SessionHandler::read
SessionHandler


Read session data

SessionHandler::open
SessionHandler::write
SessionHandler
PHP Manual

SessionHandler::read

(PHP 5 >= 5.4.0, PHP 7)

SessionHandler::read — Read session data

Descrierea

public string SessionHandler::read ( string $session_id )

Reads the session data from the session storage, and returns the result back to PHP for internal processing. This method is called automatically by PHP when a session is started (either automatically or explicity with session_start() and is preceeded by an internal call to the SessionHandler::open().

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent read method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows the method to be overidden and or intercepted and filtered (for example, decrypting $data value returned by the parent read method).

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::read().

Parametri

session_id

The session id to read data for.

Valorile întoarse

Returns an encoded string of the read data. If nothing was read, it must return an empty string. Note this value is returned internally to PHP for processing.

A se vedea ?i

  • The session.serialize_handler configuration directive.

SessionHandler::open
SessionHandler::write
SessionHandler


Write session data

SessionHandler::read
SessionHandlerInterface
SessionHandler
PHP Manual

SessionHandler::write

(PHP 5 >= 5.4.0, PHP 7)

SessionHandler::write — Write session data

Descrierea

public bool SessionHandler::write ( string $session_id , string $session_data )

Writes the session data to the session storage. Called by normal PHP shutdown, by session_write_close(), or when session_register_shutdown() fails. PHP will call SessionHandler::close() immediately after this method returns.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent write method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows this method to be overidden and or intercepted and filtered (for example, encrypting the $data value before sending it to the parent write method).

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::write().

Parametri

session_id

The session id.

session_data

The encoded session data. This data is the result of the PHP internally encoding the $_SESSION superglobal to a serialized string and passing it as this parameter. Please note sessions use an alternative serialization method.

Valorile întoarse

Valoarea întoarsa (de regula TRUE în caz de succes, FALSE în caz de e?ec). Nota: aceasta valoare este întoarsa intern catre PHP pentru procesare.

A se vedea ?i

  • The session.serialize_handler configuration directive.

SessionHandler::read
SessionHandlerInterface
SessionHandler


The SessionHandlerInterface class

(PHP 5 >= 5.4.0, PHP 7)

Introducere

SessionHandlerInterface is an interface which defines a prototype for creating a custom session handler. In order to pass a custom session handler to session_set_save_handler() using its OOP invocation, the class must implement this interface.

Please note the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code.

Sinopsisul clasei

SessionHandlerInterface {
/* Metode */
abstract public bool close ( void )
abstract public bool destroy ( string $session_id )
abstract public bool gc ( int $maxlifetime )
abstract public bool open ( string $save_path , string $session_name )
abstract public string read ( string $session_id )
abstract public bool write ( string $session_id , string $session_data )
}

Example #1 Example using SessionHandlerInterface

The following example provides file based session storage similar to the PHP sessions default save handler files. This example could easily be extended to cover database storage using your favorite PHP supported database engine.

Note we use the OOP prototype with session_set_save_handler() and register the shutdown function using the function's parameter flag. This is generally advised when registering objects as session save handlers.

<?php
class MySessionHandler implements SessionHandlerInterface
{
    private $savePath;

    public function open($savePath, $sessionName)
    {
        $this->savePath = $savePath;
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath, 0777);
        }

        return true;
    }

    public function close()
    {
        return true;
    }

    public function read($id)
    {
        return (string)@file_get_contents("$this->savePath/sess_$id");
    }

    public function write($id, $data)
    {
        return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
    }

    public function destroy($id)
    {
        $file = "$this->savePath/sess_$id";
        if (file_exists($file)) {
            unlink($file);
        }

        return true;
    }

    public function gc($maxlifetime)
    {
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }
}

$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();

// proceed to set and retrieve values by key from $_SESSION

Cuprins

  • SessionHandlerInterface::close — Close the session
  • SessionHandlerInterface::destroy — Destroy a session
  • SessionHandlerInterface::gc — Cleanup old sessions
  • SessionHandlerInterface::open — Initialize session
  • SessionHandlerInterface::read — Read session data
  • SessionHandlerInterface::write — Write session data
SessionHandler::write
SessionHandlerInterface::close
Sessions


Close the session

SessionHandlerInterface
SessionHandlerInterface::destroy
SessionHandlerInterface
PHP Manual

SessionHandlerInterface::close

(PHP 5 >= 5.4.0, PHP 7)

SessionHandlerInterface::close — Close the session

Descrierea

abstract public bool SessionHandlerInterface::close ( void )

Closes the current session. This function is automatically executed when closing the session, or explicitly via session_write_close().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Valoarea întoarsa (de regula TRUE în caz de succes, FALSE în caz de e?ec). Nota: aceasta valoare este întoarsa intern catre PHP pentru procesare.

SessionHandlerInterface
SessionHandlerInterface::destroy
SessionHandlerInterface


Destroy a session

SessionHandlerInterface::close
SessionHandlerInterface::gc
SessionHandlerInterface
PHP Manual

SessionHandlerInterface::destroy

(PHP 5 >= 5.4.0, PHP 7)

SessionHandlerInterface::destroy — Destroy a session

Descrierea

abstract public bool SessionHandlerInterface::destroy ( string $session_id )

Destroys a session. Called by session_regenerate_id() (with $destroy = TRUE), session_destroy() and when session_decode() fails.

Parametri

session_id

The session ID being destroyed.

Valorile întoarse

Valoarea întoarsa (de regula TRUE în caz de succes, FALSE în caz de e?ec). Nota: aceasta valoare este întoarsa intern catre PHP pentru procesare.

SessionHandlerInterface::close
SessionHandlerInterface::gc
SessionHandlerInterface


Cleanup old sessions

SessionHandlerInterface::destroy
SessionHandlerInterface::open
SessionHandlerInterface
PHP Manual

SessionHandlerInterface::gc

(PHP 5 >= 5.4.0, PHP 7)

SessionHandlerInterface::gc — Cleanup old sessions

Descrierea

abstract public bool SessionHandlerInterface::gc ( int $maxlifetime )

Cleans up expired sessions. Called by session_start(), based on session.gc_divisor, session.gc_probability and session.gc_maxlifetime settings.

Parametri

maxlifetime

Sessions that have not updated for the last maxlifetime seconds will be removed.

Valorile întoarse

Valoarea întoarsa (de regula TRUE în caz de succes, FALSE în caz de e?ec). Nota: aceasta valoare este întoarsa intern catre PHP pentru procesare.

SessionHandlerInterface::destroy
SessionHandlerInterface::open
SessionHandlerInterface


Initialize session

SessionHandlerInterface::gc
SessionHandlerInterface::read
SessionHandlerInterface
PHP Manual

SessionHandlerInterface::open

(PHP 5 >= 5.4.0, PHP 7)

SessionHandlerInterface::open — Initialize session

Descrierea

abstract public bool SessionHandlerInterface::open ( string $save_path , string $session_name )

Re-initialize existing session, or creates a new one. Called when a session starts or when session_start() is invoked.

Parametri

save_path

The path where to store/retrieve the session.

session_name

The session name.

Valorile întoarse

Valoarea întoarsa (de regula TRUE în caz de succes, FALSE în caz de e?ec). Nota: aceasta valoare este întoarsa intern catre PHP pentru procesare.

A se vedea ?i

  • session_name() - Get and/or set the current session name
  • The session.auto-start configuration directive.

SessionHandlerInterface::gc
SessionHandlerInterface::read
SessionHandlerInterface


Read session data

SessionHandlerInterface::open
SessionHandlerInterface::write
SessionHandlerInterface
PHP Manual

SessionHandlerInterface::read

(PHP 5 >= 5.4.0, PHP 7)

SessionHandlerInterface::read — Read session data

Descrierea

abstract public string SessionHandlerInterface::read ( string $session_id )

Reads the session data from the session storage, and returns the results. Called right after the session starts or when session_start() is called. Please note that before this method is called SessionHandlerInterface::open() is invoked.

This method is called by PHP itself when the session is started. This method should retrieve the session data from storage by the session ID provided. The string returned by this method must be in the same serialized format as when originally passed to the SessionHandlerInterface::write() If the record was not found, return an empty string.

The data returned by this method will be decoded internally by PHP using the unserialization method specified in session.serialize_handler. The resulting data will be used to populate the $_SESSION superglobal.

Note that the serialization scheme is not the same as unserialize() and can be accessed by session_decode().

Parametri

session_id

The session id.

Valorile întoarse

Returns an encoded string of the read data. If nothing was read, it must return an empty string. Note this value is returned internally to PHP for processing.

A se vedea ?i

  • The session.serialize_handler configuration directive.

SessionHandlerInterface::open
SessionHandlerInterface::write
SessionHandlerInterface


Write session data

SessionHandlerInterface::read
Session PgSQL
SessionHandlerInterface
PHP Manual

SessionHandlerInterface::write

(PHP 5 >= 5.4.0, PHP 7)

SessionHandlerInterface::write — Write session data

Descrierea

abstract public bool SessionHandlerInterface::write ( string $session_id , string $session_data )

Writes the session data to the session storage. Called by session_write_close(), when session_register_shutdown() fails, or during a normal shutdown. Note: SessionHandlerInterface::close() is called immediately after this function.

PHP will call this method when the session is ready to be saved and closed. It encodes the session data from the $_SESSION superglobal to a serialized string and passes this along with the session ID to this method for storage. The serialization method used is specified in the session.serialize_handler setting.

Note this method is normally called by PHP after the output buffers have been closed unless explicitly called by session_write_close()

Parametri

session_id

The session id.

session_data

The encoded session data. This data is the result of the PHP internally encoding the $_SESSION superglobal to a serialized string and passing it as this parameter. Please note sessions use an alternative serialization method.

Valorile întoarse

Valoarea întoarsa (de regula TRUE în caz de succes, FALSE în caz de e?ec). Nota: aceasta valoare este întoarsa intern catre PHP pentru procesare.

A se vedea ?i

  • The session.serialize_handler configuration directive.

SessionHandlerInterface::read
Session PgSQL
SessionHandlerInterface


PostgreSQL Session Save Handler

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Table definitions
  • Constante predefinite
  • Session PgSQL Func?ii
    • 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
SessionHandlerInterface::write
Introducere
Extensii de lucru cu sesiuni


Introducere

Nota: Aceasta extensie nu este disponibila pe platformele 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
Instalarea / configurarea
Session PgSQL


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Session PgSQL


Necesita?i

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).

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie este considerata ne-între?inuta ?i moarta. Oricum însa codul-sursa al acestei extensii este înca disponibil în PECL SVN aici: » http://svn.php.net/viewvc/pecl/session_pgsql.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Identificatorul salvarii sesiunii PostgreSQL este deocamdata în curs de dezvoltare. Referi?i-va la fi?ierul README din distributivul cu cod-sursa pentru a afla detalii despre configurare.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
Table definitions
Instalarea / configurarea


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);

Avertizare

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
);

Tipurile resurselor
Constante predefinite
Session PgSQL


Constante predefinite

Aceasta extensie nu are constante definite.

Table definitions
Session PgSQL Func?ii
Session PgSQL


Session PgSQL Func?ii

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.

Cuprins

  • 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
Constante predefinite
session_pgsql_add_error
Session PgSQL


Increments error counts and sets last error message

Session PgSQL Func?ii
session_pgsql_get_error
Session PgSQL Func?ii
PHP Manual

session_pgsql_add_error

(PECL session_pgsql SVN)

session_pgsql_add_error — Increments error counts and sets last error message

Descrierea

bool session_pgsql_add_error ( int $error_level [, string $error_message ] )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

error_level

error_message

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • session_pgsql_get_error() - Returns number of errors and last error message

Session PgSQL Func?ii
session_pgsql_get_error
Session PgSQL Func?ii


Returns number of errors and last error message

session_pgsql_add_error
session_pgsql_get_field
Session PgSQL Func?ii
PHP Manual

session_pgsql_get_error

(PECL session_pgsql SVN)

session_pgsql_get_error — Returns number of errors and last error message

Descrierea

array session_pgsql_get_error ([ bool $with_error_message = false ] )

Get the number of errors and optional the error messages.

Parametri

with_error_message

Set to TRUE the literal error message for each error is also returned.

Valorile întoarse

The number of errors are returned as array.

A se vedea ?i

  • session_pgsql_add_error() - Increments error counts and sets last error message

session_pgsql_add_error
session_pgsql_get_field
Session PgSQL Func?ii


Get custom field value

session_pgsql_get_error
session_pgsql_reset
Session PgSQL Func?ii
PHP Manual

session_pgsql_get_field

(PECL session_pgsql SVN)

session_pgsql_get_field — Get custom field value

Descrierea

string session_pgsql_get_field ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

A se vedea ?i

  • session_pgsql_set_field() - Set custom field value

session_pgsql_get_error
session_pgsql_reset
Session PgSQL Func?ii


Reset connection to session database servers

session_pgsql_get_field
session_pgsql_set_field
Session PgSQL Func?ii
PHP Manual

session_pgsql_reset

(PECL session_pgsql SVN)

session_pgsql_reset — Reset connection to session database servers

Descrierea

bool session_pgsql_reset ( void )

Reset the connection to the session database servers.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

session_pgsql_get_field
session_pgsql_set_field
Session PgSQL Func?ii


Set custom field value

session_pgsql_reset
session_pgsql_status
Session PgSQL Func?ii
PHP Manual

session_pgsql_set_field

(PECL session_pgsql SVN)

session_pgsql_set_field — Set custom field value

Descrierea

bool session_pgsql_set_field ( string $value )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

value

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • session_pgsql_get_field() - Get custom field value

session_pgsql_reset
session_pgsql_status
Session PgSQL Func?ii


Get current save handler status

session_pgsql_set_field
Procesarea textului
Session PgSQL Func?ii
PHP Manual

session_pgsql_status

(PECL session_pgsql SVN)

session_pgsql_status — Get current save handler status

Descrierea

array session_pgsql_status ( void )
Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

session_pgsql_set_field
Procesarea textului
Session PgSQL Func?ii


Procesarea textului

  • BBCode — Bulletin Board Code
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii BBCode
  • PCRE — Regular Expressions (Perl-Compatible)
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • ?abloane PCRE
    • Func?ii PCRE
  • POSIX Regex — Regular Expression (POSIX Extended)
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii Regex POSIX
  • ssdeep — ssdeep Fuzzy Hashing
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii ssdeep
  • Strings
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii cu ?iruri de caractere
    • Jurnalul modificarilor
session_pgsql_status
BBCode
Informa?ii de referin?a despre func?ii


Bulletin Board Code

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii 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
Procesarea textului
Introducere
Procesarea textului


Introducere

This extension aims to help parse BBCode text in order to convert it to HTML or another markup language. It uses one pass parsing and provides great speed improvement over the common approach based on regular expressions. Further more, it helps provide valid HTML by reordering open / close tags and by automatically closing unclosed tags.

Since 0.10.1 It supports argument quoting with single quotes, double quotes and HTML escaped double quotes.

BBCode
Instalarea / configurarea
BBCode


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
BBCode


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/bbcode

O solu?ie alternativa elaborata în PHP este pachetul PEAR » HTML_BBCodeParser.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

Un tip de resursa este utilizat în extensia BBCode: un BBCode_Container întors de bbcode_create().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
Func?ii BBCode
BBCode


Func?ii BBCode

Cuprins

  • 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
Constante predefinite
bbcode_add_element
BBCode


Adds a bbcode element

Func?ii BBCode
bbcode_add_smiley
Func?ii BBCode
PHP Manual

bbcode_add_element

(PECL bbcode >= 0.9.0)

bbcode_add_element — Adds a bbcode element

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Func?ii BBCode
bbcode_add_smiley
Func?ii BBCode


Adds a smiley to the parser

bbcode_add_element
bbcode_create
Func?ii BBCode
PHP Manual

bbcode_add_smiley

(PECL bbcode >= 0.10.2)

bbcode_add_smiley — Adds a smiley to the parser

Descrierea

bool bbcode_add_smiley ( resource $bbcode_container , string $smiley , string $replace_by )

Adds a smiley to the parser

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

<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
Func?ii BBCode


Create a BBCode Resource

bbcode_add_smiley
bbcode_destroy
Func?ii BBCode
PHP Manual

bbcode_create

(PECL bbcode >= 0.9.0)

bbcode_create — Create a BBCode Resource

Descrierea

resource bbcode_create ([ array $bbcode_initial_tags = NULL ] )

This function returns a new BBCode Resource used to parse BBCode strings.

Parametri

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.

Valorile întoarse

Returns a BBCode_Container

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

<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
Func?ii BBCode


Close BBCode_container resource

bbcode_create
bbcode_parse
Func?ii BBCode
PHP Manual

bbcode_destroy

(PECL bbcode >= 0.9.0)

bbcode_destroy — Close BBCode_container resource

Descrierea

bool bbcode_destroy ( resource $bbcode_container )

This function closes the resource opened by bbcode_create().

Parametri

bbcode_container

BBCode_Container resource returned by bbcode_create().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

bbcode_create
bbcode_parse
Func?ii BBCode


Parse a string following a given rule set

bbcode_destroy
bbcode_set_arg_parser
Func?ii BBCode
PHP Manual

bbcode_parse

(PECL bbcode >= 0.9.0)

bbcode_parse — Parse a string following a given rule set

Descrierea

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()

Parametri

bbcode_container

BBCode_Container resource returned by bbcode_create().

to_parse

The string we need to parse.

Valorile întoarse

Returns the parsed string, sau FALSE în cazul e?ecului.

bbcode_destroy
bbcode_set_arg_parser
Func?ii BBCode


Attach another parser in order to use another rule set for argument parsing

bbcode_parse
bbcode_set_flags
Func?ii 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

Descrierea

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.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

<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
Func?ii BBCode


Set or alter parser options

bbcode_set_arg_parser
PCRE
Func?ii BBCode
PHP Manual

bbcode_set_flags

(PECL bbcode >= 0.10.2)

bbcode_set_flags — Set or alter parser options

Descrierea

bool bbcode_set_flags ( resource $bbcode_container , int $flags [, int $mode = BBCODE_SET_FLAGS_SET ] )

Set or alter parser options

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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 automatically 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);
?>

Exemplul de mai sus va afi?a:

<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
Func?ii BBCode


Regular Expressions (Perl-Compatible)

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • ?abloane PCRE
    • PCRE regex syntax — Pattern Syntax
    • Possible modifiers in regex patterns — Pattern Modifiers
    • Differences From Perl — Perl Differences
    • Differences from POSIX regex
  • Func?ii PCRE
    • 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_array — Perform a regular expression search and replace using callbacks
    • 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
Introducere
Procesarea textului


Introducere

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.

Nota:

This extension maintains a global per-thread cache of compiled regular expressions (up to 4096).

Avertizare

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
Instalarea / configurarea
PCRE


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
PCRE


Instalarea

The PCRE extension is a core PHP extension, so it is always enabled. By default, this extension is compiled using the bundled PCRE library. Alternatively, an external PCRE library can be used by passing in the --with-pcre-regex=DIR configuration option where DIR is the location of PCRE's include and library files. It is recommended to use PCRE 8.10 or newer for PHP 5.6 and 7.0.

As of PHP 7.0.0 PCRE's just-in-time compilation is supported by default, which can be disabled with the --without-pcre-jit configuration option as of PHP 7.0.12.

Versiunea PHP pentru Windows sus?ine implicit aceasta extensie. Nu este nevoie sa încarca?i extensii suplimentare pentru a putea utiliza aceste func?ii.

Nota:

Before PHP 5.3.0, this extension could be disabled by passing in the --without-pcre-regex configuration option.

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 Versiune | Updated PCRE Versiune | Notes
7.0.3 / 5.6.18 / 5.5.32 | 8.38 | See CVE-2015-8383, CVE-2015-8386, CVE-2015-8387, CVE-2015-8389, CVE-2015-8390, CVE-2015-8391, CVE-2015-8393, CVE-2015-8394
7.0.0 / 5.6.9 / 5.5.26 / 5.4.41 | 8.37 | See CVE-2015-2325, CVE-2015-2326
5.6.0 / 5.5.10 | 8.34 |
5.5.0 / 5.4.14 / 5.3.24 | 8.32 |
5.4.9 / 5.3.19 | 8.31 |
5.3.7 | 8.12 |
5.3.6 | 8.11 |
5.3.4 | 8.10 |
5.3.3 / 5.2.14 | 8.02 |
5.3.2 | 8.00 |
5.3.0 / 5.2.13 | 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.3 | 6.6 |
5.1.0 | 6.2 |
5.0.5 | 5.0 |
5.0.0 | 4.5 |
4.4.7 | 7.7 |

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

PCRE Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.
pcre.jit | "1" | PHP_INI_ALL | Available since PHP 7.0.0.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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).

pcre.jit boolean

Whether PCRE's just-in-time compilation is going to be used.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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
PREG_JIT_STACKLIMIT_ERROR | Returned by preg_last_error() if the last PCRE function failed due to limited JIT stack space. | 7.0.0
PCRE_VERSION | PCRE version and release date (e.g. "7.0 18-Dec-2006"). | 5.2.4
Tipurile resurselor
Exemple
PCRE


Exemple

Example #1 Examples of valid patterns

  • /<\/\w+>/
  • |(\d{3})-\d+|Sm
  • /^(?i)php[34]/
  • {^\s+(\s+)?$}

Example #2 Examples of invalid patterns

  • /href='(.*)' - missing ending delimiter
  • /\w+\s*\w+/J - unknown modifier 'J'
  • 1-\d3-\d3-\d4| - missing starting delimiter

Constante predefinite
?abloane PCRE
PCRE


?abloane PCRE

Cuprins

  • PCRE regex syntax
  • Possible modifiers in regex patterns
  • Differences From Perl
  • Differences from POSIX regex
Exemple
PCRE regex syntax
PCRE


Pattern Syntax

Cuprins

  • 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
?abloane PCRE
Introduction
?abloane PCRE


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_-]%

It is also possible to use bracket style delimiters where the opening and closing brackets are the starting and ending delimiter, respectively. (), {}, [] and <> are all valid bracket style delimiter pairs.

(this [is] a (pattern))
{this [is] a (pattern)}
[this [is] a (pattern)]
<this [is] a (pattern)>
Bracket style delimiters do not need to be escaped when they are used as meta characters within the pattern, but as with other delimiters they must be escaped when they are used as literal characters.

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.

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:

Meta-characters outside square brackets
Meta-character | Description
\ | general escape character with several uses
^ | assert start of subject (or line, in multiline mode)
$ | assert end of subject or before a terminating newline (or end of 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:
Meta-characters inside square brackets (character classes)
Meta-character | Description
\ | general escape character
^ | negate the class, but only if the first character
- | indicates character range
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 "\\".

Nota:

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)
\R
line break: matches \n, \r and \r\n
\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.

The "whitespace" characters are HT (9), LF (10), FF (12), CR (13), and space (32). However, if locale-specific matching is happening, characters with code points in the range 128-255 may also be considered as whitespace characters, for instance, NBSP (A0).

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 in anchors ) 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 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.

Sets of Unicode characters are defined as belonging to certain scripts. A character from one of these sets can be matched using a script name. For example:

  • \p{Greek}
  • \P{Han}

Those that are not part of an identified script are lumped together as Common. The current list of scripts is:

Supported scripts
Arabic | Armenian | Avestan | Balinese | Bamum
Batak | Bengali | Bopomofo | Brahmi | Braille
Buginese | Buhid | Canadian_Aboriginal | Carian | Chakma
Cham | Cherokee | Common | Coptic | Cuneiform
Cypriot | Cyrillic | Deseret | Devanagari | Egyptian_Hieroglyphs
Ethiopic | Georgian | Glagolitic | Gothic | Greek
Gujarati | Gurmukhi | Han | Hangul | Hanunoo
Hebrew | Hiragana | Imperial_Aramaic | Inherited | Inscriptional_Pahlavi
Inscriptional_Parthian | Javanese | Kaithi | Kannada | Katakana
Kayah_Li | Kharoshthi | Khmer | Lao | Latin
Lepcha | Limbu | Linear_B | Lisu | Lycian
Lydian | Malayalam | Mandaic | Meetei_Mayek | Meroitic_Cursive
Meroitic_Hieroglyphs | Miao | Mongolian | Myanmar | New_Tai_Lue
Nko | Ogham | Old_Italic | Old_Persian | Old_South_Arabian
Old_Turkic | Ol_Chiki | Oriya | Osmanya | Phags_Pa
Phoenician | Rejang | Runic | Samaritan | Saurashtra
Sharada | Shavian | Sinhala | Sora_Sompeng | Sundanese
Syloti_Nagri | Syriac | Tagalog | Tagbanwa | Tai_Le
Tai_Tham | Tai_Viet | Takri | Tamil | Telugu
Thaana | Thai | Tibetan | Tifinagh | Ugaritic
Vai | Yi |  |  |

The \X escape matches a Unicode extended grapheme cluster. An extended grapheme cluster is one or more Unicode characters that combine to form a single glyph. In effect, this can be thought of as the Unicode equivalent of . as it will match one composed character, regardless of how many individual characters are actually used to render it.

In versions of PCRE older than 8.32 (which corresponds to PHP versions before 5.4.14 when using the bundled PCRE library), \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. As of PHP 5.3.0 and libpcre 8.10 some character classes are changed to use Unicode character properties, in which case the mentioned restriction does not apply. Refer to the » PCRE(3) manual for details.

Unicode character properties can appear inside a character class. They can not be part of a range. The minus (hyphen) character after a Unicode character class will match literally. Trying to end a range with a Unicode character property will result in a warning.

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 65535. It may not be possible to compile such large patterns, however, depending on the configuration options of libpcre.

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}, and PHP 5.2.7 for \g<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 in escape sequences. 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 (?&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 commentary 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)
Avertizare

Aceasta facilitate este ÎNVECHITA începând cu PHP 5.5.0 ?i ELIMINATA începând cu PHP 7.0.0.

If this deprecated 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.
Precautie

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.

Precautie

Make sure that replacement constitutes a valid PHP code string, otherwise PHP will complain about a parse error at the line containing preg_replace().

Precautie

Use of this modifier is discouraged, as it can easily introduce security vulnerabilites:

<?php
$html = $_POST['html'];

// uppercase headings
$html = preg_replace(
    '(<h([1-6])>(.*?)</h\1>)e',
    '"<h$1>" . strtoupper("$2") . "</h$1>"',
    $html
);

The above example code can be easily exploited by passing in a string such as <h1>{${eval($_GET[php_code])}}</h1>. This gives the attacker the ability to execute arbitrary PHP code and as such gives him nearly complete access to your server.

To prevent this kind of remote code execution vulnerability the preg_replace_callback() function should be used instead:

<?php
$html = $_POST['html'];

// uppercase headings
$html = preg_replace_callback(
    '(<h([1-6])>(.*?)</h\1>)',
    function ($m) {
        return "<h$m[1]>" . strtoupper($m[2]) . "</h$m[1]>";
    },
    $html
);

Nota:

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. .*?).

Nota:

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 (PCRE_UTF8)
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern and subject strings are treated as UTF-8. An invalid subject will cause the preg_* function to match nothing; an invalid pattern will trigger an error of level E_WARNING. Five and six octet UTF-8 sequences are regarded as invalid since PHP 5.3.4 (resp. PCRE 7.3 2007-08-28); formerly those have been regarded as valid UTF-8.

Performance
Differences From Perl
?abloane PCRE


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
?abloane PCRE


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.
  4. The POSIX definition of a "character class" differs from that of PCRE. Simple bracket expressions to match a set of explicit characters are supported in the form of PCRE character classes but POSIX collating elements, character classes and character equivalents are not supported. Supplying an expression with a character class that both starts and ends with :, . or = characters to PCRE is interpreted as an attempt to use one of these unsupported features and causes a compilation error.

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
Func?ii PCRE
?abloane PCRE


Func?ii PCRE

Cuprins

  • 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_array — Perform a regular expression search and replace using callbacks
  • 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

Func?ii PCRE
preg_grep
Func?ii PCRE
PHP Manual

preg_filter

(PHP 5 >= 5.3.0, PHP 7)

preg_filter — Perform a regular expression search and replace

Descrierea

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.

Valorile întoarse

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.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

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
)

A se vedea ?i

  • PCRE Patterns
  • 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_grep() - Return array entries that match the pattern
  • preg_last_error() - Returns the error code of the last PCRE regex execution

Func?ii PCRE
preg_grep
Func?ii PCRE


Return array entries that match the pattern

preg_filter
preg_last_error
Func?ii PCRE
PHP Manual

preg_grep

(PHP 4, PHP 5, PHP 7)

preg_grep — Return array entries that match the pattern

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns an array indexed using the keys from the input array.

Exemple

Example #1 preg_grep() example

<?php
// return all array elements
// containing floating point numbers
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $array);
?>

A se vedea ?i

  • PCRE Patterns
  • preg_quote() - Quote regular expression characters
  • 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
Func?ii PCRE


Returns the error code of the last PCRE regex execution

preg_grep
preg_match_all
Func?ii PCRE
PHP Manual

preg_last_error

(PHP 5 >= 5.2.0, PHP 7)

preg_last_error — Returns the error code of the last PCRE regex execution

Descrierea

int preg_last_error ( void )

Returns the error code of the last PCRE regex execution.

Example #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!';
}

?>

Exemplul de mai sus va afi?a:

Backtrack limit was exhausted!

Valorile întoarse

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_JIT_STACKLIMIT_ERROR (since PHP 7.0.0)

preg_grep
preg_match_all
Func?ii PCRE


Perform a global regular expression match

preg_last_error
preg_match
Func?ii PCRE
PHP Manual

preg_match_all

(PHP 4, PHP 5, PHP 7)

preg_match_all — Perform a global regular expression match

Descrierea

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.

Parametri

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";
?>

Exemplul de mai sus va afi?a:

<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.

If the pattern contains named subpatterns, $matches additionally contains entries for keys with the subpattern name.

If the pattern contains duplicate named subpatterns, only the rightmost subpattern is stored in $matches[NAME].

<?php
preg_match_all(
    '/(?J)(?<match>foo)|(?<match>bar)/',
    'foo bar',
    $matches,
    PREG_PATTERN_ORDER
);
print_r($matches['match']);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] =>
    [1] => bar
)

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";
?>

Exemplul de mai sus va afi?a:

<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 of arrays where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

<?php
preg_match_all('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => foobarbaz
                    [1] => 0
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => foo
                    [1] => 0
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [0] => bar
                    [1] => 3
                )

        )

    [3] => Array
        (
            [0] => Array
                (
                    [0] => baz
                    [1] => 6
                )

        )

)

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).

Nota:

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.

Valorile întoarse

Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.

Istoricul schimbarilor

Versiune | Descriere
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>).

Exemple

Example #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);
?>

Example #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";
}
?>

Exemplul de mai sus va afi?a:

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>

Example #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);

?>

Exemplul de mai sus va afi?a:

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
        )

)

A se vedea ?i

  • PCRE Patterns
  • preg_quote() - Quote regular expression characters
  • 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
Func?ii PCRE


Perform a regular expression match

preg_match_all
preg_quote
Func?ii PCRE
PHP Manual

preg_match

(PHP 4, PHP 5, PHP 7)

preg_match — Perform a regular expression match

Descrierea

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.

Parametri

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.

<?php
preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => Array
        (
            [0] => foobarbaz
            [1] => 0
        )

    [1] => Array
        (
            [0] => foo
            [1] => 0
        )

    [2] => Array
        (
            [0] => bar
            [1] => 3
        )

    [3] => Array
        (
            [0] => baz
            [1] => 6
        )

)

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).

Nota:

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);
?>

Exemplul de mai sus va afi?a:

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
        )

)

Valorile întoarse

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Istoricul schimbarilor

Versiune | Descriere
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>).

Exemple

Example #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.";
}
?>

Example #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.";
}
?>

Example #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";
?>

Exemplul de mai sus va afi?a:

domain name is: php.net

Example #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);

?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)

Note

Sfat

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() instead as it will be faster.

A se vedea ?i

  • PCRE Patterns
  • preg_quote() - Quote regular expression characters
  • 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
Func?ii PCRE


Quote regular expression characters

preg_match
preg_replace_callback_array
Func?ii PCRE
PHP Manual

preg_quote

(PHP 4, PHP 5, PHP 7)

preg_quote — Quote regular expression characters

Descrierea

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: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

Note that / is not a special regular expression character.

Nota:

Note that preg_quote() is not meant to be applied to the $replacement string(s) of preg_replace() etc.

Parametri

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.

Valorile întoarse

Returns the quoted (escaped) string.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | The - character is now quoted

Exemple

Example #1 preg_quote() example

<?php
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
echo $keywords; // returns \$40 for a g3\/400
?>

Example #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);
?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • PCRE Patterns
  • escapeshellcmd() - Escape shell metacharacters

preg_match
preg_replace_callback_array
Func?ii PCRE


Perform a regular expression search and replace using callbacks

preg_quote
preg_replace_callback
Func?ii PCRE
PHP Manual

preg_replace_callback_array

(PHP 7)

preg_replace_callback_array — Perform a regular expression search and replace using callbacks

Descrierea

mixed preg_replace_callback_array ( array $patterns_and_callbacks , mixed $subject [, int $limit = -1 [, int &$count ]] )

The behavior of this function is similar to preg_replace_callback(), except that callbacks are executed on a per-pattern basis.

Parametri

patterns_and_callbacks

An associative array mapping patterns (keys) to callbacks (values).

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.

Valorile întoarse

preg_replace_callback_array() 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.

Exemple

Example #1 preg_replace_callback_array() example

<?php
$subject = 'Aaaaaa Bbb';

preg_replace_callback_array(
    [
        '~[a]+~i' => function ($match) {
            echo strlen($match[0]), ' matches for "a" found', PHP_EOL;
        },
        '~[b]+~i' => function ($match) {
            echo strlen($match[0]), ' matches for "b" found', PHP_EOL;
        }
    ],
    $subject
);
?>

Exemplul de mai sus va afi?a:

6 matches for "a" found
3 matches for "b" found

A se vedea ?i

  • PCRE Patterns
  • preg_replace_callback() - Perform a regular expression search and replace using a callback
  • preg_quote() - Quote regular expression characters
  • preg_replace() - Perform a regular expression search and replace
  • preg_last_error() - Returns the error code of the last PCRE regex execution
  • Anonymous functions
  • informa?ie despre tipul callback

preg_quote
preg_replace_callback
Func?ii PCRE


Perform a regular expression search and replace using a callback

preg_replace_callback_array
preg_replace
Func?ii PCRE
PHP Manual

preg_replace_callback

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

preg_replace_callback — Perform a regular expression search and replace using a callback

Descrierea

mixed preg_replace_callback ( mixed $pattern , callable $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.

Parametri

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. This is the callback signature:

string handler ( array $matches )

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 to declare the 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.

Example #1 preg_replace_callback() and anonymous 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|',
        function ($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.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | The count parameter was added

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

April fools day is 04/01/2003
Last christmas was 12/24/2002

Example #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;
?>

A se vedea ?i

  • PCRE Patterns
  • preg_replace_callback_array() - Perform a regular expression search and replace using callbacks
  • preg_quote() - Quote regular expression characters
  • preg_replace() - Perform a regular expression search and replace
  • preg_last_error() - Returns the error code of the last PCRE regex execution
  • Anonymous functions
  • informa?ie despre tipul callback

preg_replace_callback_array
preg_replace
Func?ii PCRE


Perform a regular expression search and replace

preg_replace_callback
preg_split
Func?ii PCRE
PHP Manual

preg_replace

(PHP 4, PHP 5, PHP 7)

preg_replace — Perform a regular expression search and replace

Descrierea

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.

Parametri

pattern

The pattern to search for. It can be either a string or an array with strings.

Several PCRE modifiers are also available.

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 $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 deprecated 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.

Valorile întoarse

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.

Erori/Excep?ii

As of PHP 5.5.0 E_DEPRECATED level error is emitted when passing in the "\e" modifier. As of PHP 7.0.0 E_WARNING is emitted in this case and "\e" modifier has no effect.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | Support for the /e modifier has been removed. Use preg_replace_callback() instead.
5.5.0 | The /e modifier is deprecated. Use preg_replace_callback() instead. See the PREG_REPLACE_EVAL documentation for additional information about security risks.
5.1.0 | Added the count parameter

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

April1,2003

Example #2 Using indexed arrays with preg_replace()

<?php
$string = 'The quick brown fox jumps 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);
?>

Exemplul de mai sus va afi?a:

The bear black slow jumps 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);
?>

Exemplul de mai sus va afi?a:

The slow black bear jumps over the lazy dog.

Example #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');
?>

Exemplul de mai sus va afi?a:

$startDate = 5/27/1999

Example #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;
?>

Example #5 Using the count parameter

<?php
$count = 0;

echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count);
echo $count; //3
?>

Exemplul de mai sus va afi?a:

xp***to
3

Note

Nota:

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().

A se vedea ?i

  • PCRE Patterns
  • preg_quote() - Quote regular expression characters
  • 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
Func?ii PCRE


Split string by a regular expression

preg_replace
POSIX Regex
Func?ii PCRE
PHP Manual

preg_split

(PHP 4, PHP 5, PHP 7)

preg_split — Split string by a regular expression

Descrierea

array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )

Split the given string by a regular expression.

Parametri

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.

Valorile întoarse

Returns an array containing substrings of subject split along boundaries matched by pattern, sau FALSE în cazul e?ecului.

Exemple

Example #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");
print_r($keywords);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => hypertext
    [1] => language
    [2] => programming
)

Example #2 Splitting a string into component characters

<?php
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => s
    [1] => t
    [2] => r
    [3] => i
    [4] => n
    [5] => g
)

Example #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);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => Array
        (
            [0] => hypertext
            [1] => 0
        )

    [1] => Array
        (
            [0] => language
            [1] => 10
        )

    [2] => Array
        (
            [0] => programming
            [1] => 19
        )

)

Note

Sfat

If you don't need the power of regular expressions, you can choose faster (albeit simpler) alternatives like explode() or str_split().

Sfat

If matching fails, an array with a single element containing the input string will be returned.

A se vedea ?i

  • PCRE Patterns
  • preg_quote() - Quote regular expression characters
  • 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
Func?ii PCRE


Regular Expression (POSIX Extended)

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii Regex POSIX
    • 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
Introducere
Procesarea textului


Introducere

Avertizare

Aceasta facilitate este ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta facilitate sunt:

  • PCRE (for full regular expression support)
  • fnmatch() (for simpler shell style wildcard pattern matching)
Sfat

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.

Avertizare

These regular expression functions are not binary-safe. The PCRE functions are.

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
Instalarea / configurarea
POSIX Regex


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
POSIX Regex


Instalarea

Avertizare

Nu modifica?i TYPE, doar daca ?ti?i ce face?i.

Pentru a activa sus?inerea regexp configura?i op?iunea PHP --with-regex[=TYPE] . TYPE poate avea una din urmatoarele valori: system, apache, php. Valoarea implicita este php.

Versiunea PHP pentru Windows sus?ine implicit aceasta extensie. Nu este nevoie sa încarca?i extensii suplimentare pentru a putea utiliza aceste func?ii.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
POSIX Regex


Exemple

Example #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);
?>

Constante predefinite
Func?ii Regex POSIX
POSIX Regex


Func?ii Regex POSIX

A se vedea ?i

Avertizare

Aceasta facilitate este ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta facilitate sunt:

  • PCRE (pentru sus?inerea deplina a expresiilor regulare)
  • fnmatch() (pentru o mai simpla potrivire a ?abloanelor de tip shell wildcard)

Cuprins

  • 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
Exemple
ereg_replace
POSIX Regex


Replace regular expression

Func?ii Regex POSIX
ereg
Func?ii Regex POSIX
PHP Manual

ereg_replace

(PHP 4, PHP 5)

ereg_replace — Replace regular expression

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • preg_replace()

Descrierea

string ereg_replace ( string $pattern , string $replacement , string $string )

This function scans string for matches to pattern, then replaces the matched text with replacement.

Parametri

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.

Valorile întoarse

The modified string is returned. If no matches are found in string, then it will be returned unchanged.

Exemple

For example, the following code snippet prints "This was a test" three times:

Example #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:

Example #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.' */
?>

Example #3 Replace URLs with links

<?php
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
                     '<a href="\\0">\\0</a>', $text);
?>

A se vedea ?i

  • 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
  • quotemeta() - Quote meta characters

Func?ii Regex POSIX
ereg
Func?ii Regex POSIX


Regular expression match

ereg_replace
eregi_replace
Func?ii Regex POSIX
PHP Manual

ereg

(PHP 4, PHP 5)

ereg — Regular expression match

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • preg_match()

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
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().

Exemple

Example #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";
}
?>

A se vedea ?i

  • 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
Func?ii Regex POSIX


Replace regular expression case insensitive

ereg
eregi
Func?ii Regex POSIX
PHP Manual

eregi_replace

(PHP 4, PHP 5)

eregi_replace — Replace regular expression case insensitive

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • preg_replace() (with the i (PCRE_CASELESS) modifier)

Descrierea

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.

Parametri

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.

Valorile întoarse

The modified string is returned. If no matches are found in string, then it will be returned unchanged.

Exemple

Example #1 Highlight search results

<?php
$pattern = '(>[^<]*)('. quotemeta($_GET['search']) .')';
$replacement = '\\1<span class="search">\\2</span>';
$body = eregi_replace($pattern, $replacement, $body);
?>

A se vedea ?i

  • ereg() - Regular expression match
  • eregi() - Case insensitive regular expression match
  • ereg_replace() - Replace regular expression
  • preg_replace() - Perform a regular expression search and replace
  • quotemeta() - Quote meta characters

ereg
eregi
Func?ii Regex POSIX


Case insensitive regular expression match

eregi_replace
split
Func?ii Regex POSIX
PHP Manual

eregi

(PHP 4, PHP 5)

eregi — Case insensitive regular expression match

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • preg_match() (with the i (PCRE_CASELESS) modifier)

Descrierea

int eregi ( string $pattern , string $string [, array &$regs ] )

This function is identical to ereg() except that it ignores case distinction when matching alphabetic characters.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #1 eregi() example

<?php
$string = 'XYZ';
if (eregi('z', $string)) {
    echo "'$string' contains a 'z' or 'Z'!";
}
?>

A se vedea ?i

  • 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
  • quotemeta() - Quote meta characters

eregi_replace
split
Func?ii Regex POSIX


Split string into array by regular expression

eregi
spliti
Func?ii Regex POSIX
PHP Manual

split

(PHP 4, PHP 5)

split — Split string into array by regular expression

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • preg_split()
  • explode()
  • str_split()

Descrierea

array split ( string $pattern , string $string [, int $limit = -1 ] )

Splits a string into array by regular expression.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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);
?>

Example #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";
?>

Note

Sfat

split() is deprecated as of PHP 5.3.0. preg_split() is the suggested alternative to this function. 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.

Sfat

For users looking for a way to emulate Perl's @chars = split('', $str) behaviour, please see the examples for preg_split() or str_split().

A se vedea ?i

  • 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() - Wraps a string to a given number of characters

eregi
spliti
Func?ii Regex POSIX


Split string into array by regular expression case insensitive

split
sql_regcase
Func?ii Regex POSIX
PHP Manual

spliti

(PHP 4 >= 4.0.1, PHP 5)

spliti — Split string into array by regular expression case insensitive

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • preg_split() (with the i (PCRE_CASELESS) modifier)

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

This example splits a string using 'a' as the separator :

Example #1 spliti() example

<?php
$string = "aBBBaCCCADDDaEEEaGGGA";
$chunks = spliti ("a", $string, 5);
print_r($chunks);
?>

Exemplul de mai sus va afi?a:

Array
(
  [0] =>
  [1] => BBB
  [2] => CCC
  [3] => DDD
  [4] => EEEaGGGA
)

A se vedea ?i

  • 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
Func?ii Regex POSIX


Make regular expression for case insensitive match

spliti
ssdeep
Func?ii Regex POSIX
PHP Manual

sql_regcase

(PHP 4, PHP 5)

sql_regcase — Make regular expression for case insensitive match

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • preg_match()
  • preg_quote()

Descrierea

string sql_regcase ( string $string )

Creates a regular expression for a case insensitive match.

Parametri

string

The input string.

Valorile întoarse

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.

Exemple

Example #1 sql_regcase() example

<?php
echo sql_regcase("Foo - bar.");
?>

Exemplul de mai sus va afi?a:

[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.

spliti
ssdeep
Func?ii Regex POSIX


ssdeep Fuzzy Hashing

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii ssdeep
    • 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
Introducere
Procesarea textului


Introducere

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
Instalarea / configurarea
ssdeep


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
ssdeep


Necesita?i

This extension requires the » ssdeep library.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/ssdeep.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii ssdeep
ssdeep


Func?ii ssdeep

Cuprins

  • 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
Constante predefinite
ssdeep_fuzzy_compare
ssdeep


Calculates the match score between two fuzzy hash signatures

Func?ii ssdeep
ssdeep_fuzzy_hash_filename
Func?ii ssdeep
PHP Manual

ssdeep_fuzzy_compare

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures

Descrierea

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.

Parametri

signature1

The first fuzzy hash signature string.

signature2

The second fuzzy hash signature string.

Valorile întoarse

Returns an integer from 0 to 100 on success, FALSE otherwise.

Func?ii ssdeep
ssdeep_fuzzy_hash_filename
Func?ii ssdeep


Create a fuzzy hash from a file

ssdeep_fuzzy_compare
ssdeep_fuzzy_hash
Func?ii ssdeep
PHP Manual

ssdeep_fuzzy_hash_filename

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file

Descrierea

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.

Parametri

file_name

The filename of the file to hash.

Valorile întoarse

Returns a string on success, FALSE otherwise.

ssdeep_fuzzy_compare
ssdeep_fuzzy_hash
Func?ii ssdeep


Create a fuzzy hash from a string

ssdeep_fuzzy_hash_filename
Strings
Func?ii ssdeep
PHP Manual

ssdeep_fuzzy_hash

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_hash — Create a fuzzy hash from a string

Descrierea

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.

Parametri

to_hash

The input string.

Valorile întoarse

Returns a string on success, FALSE otherwise.

ssdeep_fuzzy_hash_filename
Strings
Func?ii ssdeep


Strings

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii cu ?iruri de caractere
    • addcslashes — Quote string with slashes in a C style
    • addslashes — Quote string with slashes
    • bin2hex — Convert binary data into hexadecimal representation
    • chop — Pseudonim pentru 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 — Decodes a hexadecimally encoded binary string
    • 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 — Pseudonim pentru 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 — Format a number with grouped thousands
    • 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 — Pseudonim pentru 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 — Find the last occurrence of a character in a string
    • strrev — Reverse a string
    • strripos — Find the position of the last occurrence of a case-insensitive substring in a string
    • strrpos — Find the position of the last occurrence of a substring in a string
    • 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 — Make a string lowercase
    • strtoupper — Make a string uppercase
    • 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 — Replace text within a portion of a string
    • 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 — Wraps a string to a given number of characters
  • Jurnalul modificarilor
ssdeep_fuzzy_hash
Introducere
Procesarea textului


Introducere

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
Instalarea / configurarea
Strings


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Strings


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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)
ENT_IGNORE (integer)
ENT_SUBSTITUTE (integer)
ENT_DISALLOWED (integer)
ENT_HTML401 (integer)
ENT_XML1 (integer)
ENT_XHTML (integer)
ENT_HTML5 (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)
Tipurile resurselor
Func?ii cu ?iruri de caractere
Strings


Func?ii cu ?iruri de caractere

A se vedea ?i

Pentru manipulari înca mai avansate cu ?iruri de caractere, accesa?i Func?iile POSIX de lucru cu expresiile regulare ?i Func?iile compatibile Perl de lucru cu expresiile regulare.

Cuprins

  • addcslashes — Quote string with slashes in a C style
  • addslashes — Quote string with slashes
  • bin2hex — Convert binary data into hexadecimal representation
  • chop — Pseudonim pentru 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 — Decodes a hexadecimally encoded binary string
  • 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 — Pseudonim pentru 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 — Format a number with grouped thousands
  • 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 — Pseudonim pentru 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 — Find the last occurrence of a character in a string
  • strrev — Reverse a string
  • strripos — Find the position of the last occurrence of a case-insensitive substring in a string
  • strrpos — Find the position of the last occurrence of a substring in a string
  • 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 — Make a string lowercase
  • strtoupper — Make a string uppercase
  • 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 — Replace text within a portion of a string
  • 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 — Wraps a string to a given number of characters
Constante predefinite
addcslashes
Strings


Quote string with slashes in a C style

Func?ii cu ?iruri de caractere
addslashes
Func?ii cu ?iruri de caractere
PHP Manual

addcslashes

(PHP 4, PHP 5, PHP 7)

addcslashes — Quote string with slashes in a C style

Descrierea

string addcslashes ( string $str , string $charlist )

Returns a string with backslashes before characters that are listed in charlist parameter.

Parametri

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, all of which are predefined escape sequences in C. Many of these sequences are also defined in other C-derived languages, including PHP, meaning that you may not get the desired result if you use the output of addcslashes() to generate code in those languages with these characters defined in charlist.

Valorile întoarse

Returns the escaped string.

Istoricul schimbarilor

Versiune | Descriere
5.2.5 | The escape sequences \v and \f were added.

Exemple

charlist like "\0..\37", which would escape all characters with ASCII code between 0 and 31.

Example #1 addcslashes() example

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?>

A se vedea ?i

  • 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

Func?ii cu ?iruri de caractere
addslashes
Func?ii cu ?iruri de caractere


Quote string with slashes

addcslashes
bin2hex
Func?ii cu ?iruri de caractere
PHP Manual

addslashes

(PHP 4, PHP 5, PHP 7)

addslashes — Quote string with slashes

Descrierea

string addslashes ( string $str )

Returns a string with backslashes before characters that need to be escaped. 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 string that is evaluated by PHP. For example, O'Reilly is stored in $str, you need to escape $str. (e.g. eval("echo '".addslashes($str)."';"); )

To escape database parameters, DBMS specific escape function (e.g. mysqli_real_escape_string() for MySQL or pg_escape_literal(), pg_escape_string() for PostgreSQL) should be used for security reasons. DBMSes have differect escape specification for identifiers (e.g. Table name, field name) than parameters. Some DBMS such as PostgreSQL provides identifier escape function, pg_escape_identifier(), but not all DBMS provides identifier escape API. If this is the case, refer to your database system manual for proper escaping method.

If your DBMS doesn't have an escape function and the DBMS uses \ to escape special chars, you might be able to use this function only when this escape method is adequate for your database. Please note that use of addslashes() for database parameter escaping can be cause of security issues on most databases.

The PHP directive magic_quotes_gpc was on by default before PHP 5.4, and it essentially ran 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.

Parametri

str

The string to be escaped.

Valorile întoarse

Returns the escaped string.

Exemple

Example #1 An addslashes() example

<?php
$str = "Is your name O'Reilly?";

// Outputs: Is your name O\'Reilly?
echo addslashes($str);
?>

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Convert binary data into hexadecimal representation

addslashes
chop
Func?ii cu ?iruri de caractere
PHP Manual

bin2hex

(PHP 4, PHP 5, PHP 7)

bin2hex — Convert binary data into hexadecimal representation

Descrierea

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.

Parametri

str

A string.

Valorile întoarse

Returns the hexadecimal representation of the given string.

A se vedea ?i

  • hex2bin() - Decodes a hexadecimally encoded binary string
  • pack() - Pack data into binary string

addslashes
chop
Func?ii cu ?iruri de caractere


Pseudonim pentru rtrim

bin2hex
chr
Func?ii cu ?iruri de caractere
PHP Manual

chop

(PHP 4, PHP 5, PHP 7)

chop — Pseudonim pentru rtrim()

Descrierea

Aceasta func?ie este pseudonim pentru: rtrim().

Note

Nota:

chop() is different than the Perl chop() function, which removes the last character in the string.

bin2hex
chr
Func?ii cu ?iruri de caractere


Return a specific character

chop
chunk_split
Func?ii cu ?iruri de caractere
PHP Manual

chr

(PHP 4, PHP 5, PHP 7)

chr — Return a specific character

Descrierea

string chr ( int $ascii )

Returns a one-character string containing the character specified by ascii.

This function complements ord().

Parametri

ascii

The extended ASCII code.

Values outside the valid range (0..255) will be bitwise and'ed with 255, which is equivalent to the following algorithm:

while ($ascii < 0) {
    $ascii += 256;
}
$ascii %= 256;

Valorile întoarse

Returns the specified character.

Exemple

Example #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);
?>

Example #2 Overflow behavior

<?php
echo chr(-159), chr(833), PHP_EOL;
?>

Exemplul de mai sus va afi?a:

aA

A se vedea ?i

  • sprintf() - Return a formatted string with a format string of %c
  • ord()
  • An » ASCII-table

chop
chunk_split
Func?ii cu ?iruri de caractere


Split a string into smaller chunks

chr
convert_cyr_string
Func?ii cu ?iruri de caractere
PHP Manual

chunk_split

(PHP 4, PHP 5, PHP 7)

chunk_split — Split a string into smaller chunks

Descrierea

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.

Parametri

body

The string to be chunked.

chunklen

The chunk length.

end

The line ending sequence.

Valorile întoarse

Returns the chunked string.

Exemple

Example #1 chunk_split() example

<?php
// format $data using RFC 2045 semantics
$new_string = chunk_split(base64_encode($data));
?>

A se vedea ?i

  • str_split() - Convert a string to an array
  • explode() - Split a string by string
  • split() - Split string into array by regular expression
  • wordwrap() - Wraps a string to a given number of characters
  • » RFC 2045

chr
convert_cyr_string
Func?ii cu ?iruri de caractere


Convert from one Cyrillic character set to another

chunk_split
convert_uudecode
Func?ii cu ?iruri de caractere
PHP Manual

convert_cyr_string

(PHP 4, PHP 5, PHP 7)

convert_cyr_string — Convert from one Cyrillic character set to another

Descrierea

string convert_cyr_string ( string $str , string $from , string $to )

Converts from one Cyrillic character set to another.

Parametri

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

Valorile întoarse

Returns the converted string.

Note

Nota: Aceasta func?ie accepta ?i date binare.

chunk_split
convert_uudecode
Func?ii cu ?iruri de caractere


Decode a uuencoded string

convert_cyr_string
convert_uuencode
Func?ii cu ?iruri de caractere
PHP Manual

convert_uudecode

(PHP 5, PHP 7)

convert_uudecode — Decode a uuencoded string

Descrierea

string convert_uudecode ( string $data )

convert_uudecode() decodes a uuencoded string.

Parametri

data

The uuencoded data.

Valorile întoarse

Returns the decoded data as a string sau FALSE în cazul e?ecului.

Exemple

Example #1 convert_uudecode() example

<?php
/* Can you imagine what this will print? :) */
echo convert_uudecode("+22!L;W9E(%!(4\"$`\n`");
?>

A se vedea ?i

  • convert_uuencode() - Uuencode a string

convert_cyr_string
convert_uuencode
Func?ii cu ?iruri de caractere


Uuencode a string

convert_uudecode
count_chars
Func?ii cu ?iruri de caractere
PHP Manual

convert_uuencode

(PHP 5, PHP 7)

convert_uuencode — Uuencode a string

Descrierea

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.

Parametri

data

The data to be encoded.

Valorile întoarse

Returns the uuencoded data sau FALSE în cazul e?ecului.

Exemple

Example #1 convert_uuencode() example

<?php
$some_string = "test\ntext text\r\n";

echo convert_uuencode($some_string);
?>

A se vedea ?i

  • convert_uudecode() - Decode a uuencoded string
  • base64_encode() - Encodes data with MIME base64

convert_uudecode
count_chars
Func?ii cu ?iruri de caractere


Return information about characters used in a string

convert_uuencode
crc32
Func?ii cu ?iruri de caractere
PHP Manual

count_chars

(PHP 4, PHP 5, PHP 7)

count_chars — Return information about characters used in a string

Descrierea

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.

Parametri

string

The examined string.

mode

See return values.

Valorile întoarse

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.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Calculates the crc32 polynomial of a string

count_chars
crypt
Func?ii cu ?iruri de caractere
PHP Manual

crc32

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

crc32 — Calculates the crc32 polynomial of a string

Descrierea

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.

Avertizare

Because PHP's integer type is signed many crc32 checksums will result in negative integers on 32bit platforms. On 64bit installations all crc32() results will be positive integers though.

So you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned crc32() checksum in decimal format.

For a hexadecimal representation of the checksum you can either use the "%x" formatter of sprintf() or printf() or the dechex() conversion functions, both of these also take care of converting the crc32() result to an unsigned integer.

Having 64bit installations also return negative integers for higher result values was considered but would break the hexadecimal conversion as negatives would get an extra 0xFFFFFFFF######## offset then. As hexadecimal representation seems to be the most common use case we decided to not break this even if it breaks direct decimal comparisons in about 50% of the cases when moving from 32 to 64bits.

In retrospect having the function return an integer maybe wasn't the best idea and returning a hex string representation right away (as e.g. md5() does) might have been a better plan to begin with.

For a more portable solution you may also consider the generic hash(). hash("crc32b", $str) will return the same string as str_pad(dechex(crc32($str)), 8, '0', STR_PAD_LEFT).

Parametri

str

The data.

Valorile întoarse

Returns the crc32 checksum of str as an integer.

Exemple

Example #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);
?>

A se vedea ?i

  • hash() - Generate a hash value (message digest)
  • md5() - Calculate the md5 hash of a string
  • sha1() - Calculate the sha1 hash of a string

count_chars
crypt
Func?ii cu ?iruri de caractere


One-way string hashing

crc32
echo
Func?ii cu ?iruri de caractere
PHP Manual

crypt

(PHP 4, PHP 5, PHP 7)

crypt — One-way string hashing

Descrierea

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.

The salt parameter is optional. However, crypt() creates a weak password without the salt. PHP 5.6 or later raise an E_NOTICE error without it. Make sure to specify a strong enough salt for better security.

password_hash() uses a strong hash, generates a strong salt, and applies proper rounds automatically. password_hash() is a simple crypt() wrapper and compatible with existing password hashes. Use of password_hash() is encouraged.

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$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters 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. Versions of PHP before 5.3.7 only support "$2a$" as the salt prefix: PHP 5.3.7 introduced the new prefixes to fix a security weakness in the Blowfish implementation. Please refer to » this document for full details of the security fix, but to summarise, developers targeting only PHP 5.3.7 and later should use "$2y$" in preference to "$2a$".
  • 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.

Nota:

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.

Parametri

str

The string to be hashed.

Precautie

Using the CRYPT_BLOWFISH algorithm, will result in the str parameter being truncated to a maximum length of 72 characters.

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.

Valorile întoarse

Returns the hashed string or a string that is shorter than 13 characters and is guaranteed to differ from the salt on failure.

Avertizare

When validating passwords, a string comparison function that isn't vulnerable to timing attacks should be used to compare the output of crypt() to the previously known hash. PHP 5.6 onwards provides hash_equals() for this purpose.

Istoricul schimbarilor

Versiune | Descriere
5.6.5 | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.6 would incorrectly return a DES hash.
5.6.0 | Raise E_NOTICE security warning if salt is omitted.
5.5.21 | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.5 (and earlier branches) would incorrectly return a DES hash.
5.3.7 | Added $2x$ and $2y$ Blowfish modes to deal with potential high-bit attacks.
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.

Exemple

Example #1 crypt() examples

<?php
$hashed_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 (hash_equals($hashed_password, crypt($user_input, $hashed_password))) {
   echo "Password verified!";
}
?>

Example #2 Using crypt() with htpasswd

<?php
// Set the password
$password = 'mypassword';

// Get the hash, letting the salt be automatically generated
$hash = crypt($password);
?>

Example #3 Using crypt() with different hash types

<?php
/* These salts are examples only, and should not be used verbatim in your code.
   You should generate a distinct, correctly-formatted salt for each password.
*/
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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Note

Nota: There is no decrypt function, since crypt() uses a one-way algorithm.

A se vedea ?i

  • hash_equals() - Timing attack safe string comparison
  • password_hash() - Creates a password hash
  • md5() - Calculate the md5 hash of a string
  • The Mcrypt extension
  • The Unix man page for your crypt function for more information

crc32
echo
Func?ii cu ?iruri de caractere


Output one or more strings

crypt
explode
Func?ii cu ?iruri de caractere
PHP Manual

echo

(PHP 4, PHP 5, PHP 7)

echo — Output one or more strings

Descrierea

void echo ( string $arg1 [, string $... ] )

Outputs all parameters. No additional newline is appended.

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. Prior to PHP 5.4.0, this short syntax only works with the short_open_tag configuration setting enabled.

I have <?=$foo?> foo.

The only difference to print is that echo accepts an argument list.

Parametri

arg1

The parameter to output.

...

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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

// Strings can either be passed individually as multiple arguments or
// concatenated together and passed as a single argument
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
?>

Note

Nota: Deoarece aceasta este o construc?ie a limbajului ?i nu o func?ie, ea nu poate fi apelata utilizând func?ii de operare cu variabile .

Sfat

A benefit to passing in multiple arguments over using concatenation in echo regards the precedence of the period operator in PHP. If multiple arguments are passed in, then parentheses will not be required to enforce precedence:

<?php
echo "Sum: ", 1 + 2;
echo "Hello ", isset($name) ? $name : "John Doe", "!";

With concatenation, the period operator has a higher precedence than both the addition and ternary operators, and so parentheses must be used for the correct behaviour:

<?php
echo 'Sum: ' . (1 + 2);
echo 'Hello ' . (isset($name) ? $name : 'John Doe') . '!';

A se vedea ?i

  • print - Output a string
  • printf() - Output a formatted string
  • flush() - Flush system output buffer
  • Heredoc syntax

crypt
explode
Func?ii cu ?iruri de caractere


Split a string by string

echo
fprintf
Func?ii cu ?iruri de caractere
PHP Manual

explode

(PHP 4, PHP 5, PHP 7)

explode — Split a string by string

Descrierea

array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

Parametri

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.

Nota:

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.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Support for negative limits was added

Exemple

Example #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; // *

?>

Example #2 explode() return examples

<?php
/*
   A string that doesn't contain the delimiter will simply
   return a one-length array of the original string.
*/
$input1 = "hello";
$input2 = "hello,there";
$input3 = ',';
var_dump( explode( ',', $input1 ) );
var_dump( explode( ',', $input2 ) );
var_dump( explode( ',', $input3 ) );

?>

Exemplul de mai sus va afi?a:

array(1)
(
    [0] => string(5) "hello"
)
array(2)
(
    [0] => string(5) "hello"
    [1] => string(5) "there"
)
array(2)
(
    [0] => string(0) ""
    [1] => string(0) ""
)

Example #3 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));
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => one
    [1] => two|three|four
)
Array
(
    [0] => one
    [1] => two
    [2] => three
)

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Write a formatted string to a stream

explode
get_html_translation_table
Func?ii cu ?iruri de caractere
PHP Manual

fprintf

(PHP 5, PHP 7)

fprintf — Write a formatted string to a stream

Descrierea

int fprintf ( resource $handle , string $format [, mixed $args [, mixed $... ]] )

Write a string produced according to format to the stream resource specified by handle.

Parametri

handle

O resursa de tip indicator în sistemul de fi?iere care este în mod tipic creata utilizând fopen().

format

See sprintf() for a description of format.

args

...

Valorile întoarse

Returns the length of the string written.

Exemple

Example #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
?>

Example #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
?>

A se vedea ?i

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • vsprintf() - Return a formatted string
  • number_format() - Format a number with grouped thousands

explode
get_html_translation_table
Func?ii cu ?iruri de caractere


Returns the translation table used by htmlspecialchars and htmlentities

fprintf
hebrev
Func?ii cu ?iruri de caractere
PHP Manual

get_html_translation_table

(PHP 4, PHP 5, PHP 7)

get_html_translation_table — Returns the translation table used by htmlspecialchars() and htmlentities()

Descrierea

array get_html_translation_table ([ int $table = HTML_SPECIALCHARS [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = "UTF-8" ]]] )

get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities().

Nota:

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().

Parametri

table

Which table to return. Either HTML_ENTITIES or HTML_SPECIALCHARS.

flags

A bitmask of one or more of the following flags, which specify which quotes the table will contain as well as which document type the table is for. The default is ENT_COMPAT | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Table will contain entities for double-quotes, but not for single-quotes.
ENT_QUOTES | Table will contain entities for both double and single quotes.
ENT_NOQUOTES | Table will neither contain entities for single quotes nor for double quotes.
ENT_HTML401 | Table for HTML 4.01.
ENT_XML1 | Table for XML 1.
ENT_XHTML | Table for XHTML.
ENT_HTML5 | Table for HTML 5.

encoding

Encoding to use. If omitted, the default value for this argument is ISO-8859-1 in versions of PHP prior to 5.4.0, and UTF-8 from PHP 5.4.0 onwards.

The following character sets are supported:

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1.
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
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.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian.
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, SJIS-win, cp932, 932 | Japanese
EUC-JP | EUCJP, eucJP-win | Japanese
MacRoman | Charset that was used by Mac OS.
'' 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.

Nota: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

Valorile întoarse

Returns the translation table as an array, with the original characters as keys and entities as values.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | The default value for the encoding parameter was changed to UTF-8.
5.4.0 | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
5.3.4 | The encoding parameter was added.

Exemple

Example #1 Translation Table Example

<?php
var_dump(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5));
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1510) {
  ["
"]=>
  string(9) "&NewLine;"
  ["!"]=>
  string(6) "&excl;"
  ["""]=>
  string(6) "&quot;"
  ["#"]=>
  string(5) "&num;"
  ["$"]=>
  string(8) "&dollar;"
  ["%"]=>
  string(8) "&percnt;"
  ["&"]=>
  string(5) "&amp;"
  ["'"]=>
  string(6) "&apos;"
  // ...
}

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Convert logical Hebrew text to visual text

get_html_translation_table
hebrevc
Func?ii cu ?iruri de caractere
PHP Manual

hebrev

(PHP 4, PHP 5, PHP 7)

hebrev — Convert logical Hebrew text to visual text

Descrierea

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.

Parametri

hebrew_text

A Hebrew input string.

max_chars_per_line

This optional parameter indicates maximum number of characters per line that will be returned.

Valorile întoarse

Returns the visual string.

A se vedea ?i

  • hebrevc() - Convert logical Hebrew text to visual text with newline conversion

get_html_translation_table
hebrevc
Func?ii cu ?iruri de caractere


Convert logical Hebrew text to visual text with newline conversion

hebrev
hex2bin
Func?ii cu ?iruri de caractere
PHP Manual

hebrevc

(PHP 4, PHP 5, PHP 7)

hebrevc — Convert logical Hebrew text to visual text with newline conversion

Descrierea

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.

Parametri

hebrew_text

A Hebrew input string.

max_chars_per_line

This optional parameter indicates maximum number of characters per line that will be returned.

Valorile întoarse

Returns the visual string.

A se vedea ?i

  • hebrev() - Convert logical Hebrew text to visual text

hebrev
hex2bin
Func?ii cu ?iruri de caractere


Decodes a hexadecimally encoded binary string

hebrevc
html_entity_decode
Func?ii cu ?iruri de caractere
PHP Manual

hex2bin

(PHP >= 5.4.0)

hex2bin — Decodes a hexadecimally encoded binary string

Descrierea

string hex2bin ( string $data )

Decodes a hexadecimally encoded binary string.

Precautie

This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function.

Parametri

data

Hexadecimal representation of data.

Valorile întoarse

Returns the binary representation of the given data sau FALSE în cazul e?ecului.

Erori/Excep?ii

If the hexadecimal input string is of odd length or invalid hexadecimal string an E_WARNING level error is thrown.

Istoricul schimbarilor

Versiune | Descriere
5.5.1 | A warning is thrown if the input string is invalid hexadecimal string.
5.4.4 | A warning is thrown if the input string is of odd length. In PHP 5.4.0 the string was silently accepted, but the last byte was truncated.

Exemple

Example #1 hex2bin() example

<?php
$hex = hex2bin("6578616d706c65206865782064617461");
var_dump($hex);
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(16) "example hex data"

A se vedea ?i

  • bin2hex() - Convert binary data into hexadecimal representation
  • unpack() - Unpack data from binary string

hebrevc
html_entity_decode
Func?ii cu ?iruri de caractere


Convert all HTML entities to their applicable characters

hex2bin
htmlentities
Func?ii cu ?iruri de caractere
PHP Manual

html_entity_decode

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

html_entity_decode — Convert all HTML entities to their applicable characters

Descrierea

string html_entity_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") ]] )

html_entity_decode() is the opposite of htmlentities() in that it converts all HTML entities in the string to their applicable characters.

More precisely, this function decodes all the entities (including all numeric entities) that a) are necessarily valid for the chosen document type — i.e., for XML, this function does not decode named entities that might be defined in some DTD — and b) whose character or characters are in the coded character set associated with the chosen encoding and are permitted in the chosen document type. All other entities are left as is.

Parametri

string

The input string.

flags

A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. 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_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.

encoding

Un argument op?ional ce define?te codarea folosita la convertirea caracterelor.

Daca este omisa, valoarea implicita a argumentului encoding variaza în dependen?a de versiunea PHP utilizata. În PHP 5.6 ?i ulterior, valoarea op?iunii de configurare default_charset este utilizata implicit. PHP 5.4 ?i 5.5 vor utiliza implicit UTF-8. Versiunile anterioare ale PHP utilizau ISO-8859-1.

Cu toate ca acest argument este op?ional, tehnic vorbind, va îndemnam sa specifica?i valoarea corecta pentru codul dvs. daca utiliza?i PHP 5.5 sau anterior, sau daca op?iunea de configurare default_charset poate sa nu fie setata corect pentru intrarile date.

The following character sets are supported:

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1.
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
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.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian.
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, SJIS-win, cp932, 932 | Japanese
EUC-JP | EUCJP, eucJP-win | Japanese
MacRoman | Charset that was used by Mac OS.
'' 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.

Nota: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

Valorile întoarse

Returns the decoded string.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Valoarea implicita a parametrului encoding a fost schimbata pentru a coincide cu valoarea op?iunii de configurare default_charset.
5.4.0 | Default encoding changed from ISO-8859-1 to UTF-8.
5.4.0 | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.

Exemple

Example #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
?>

Note

Nota:

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 encoding.

A se vedea ?i

  • 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() - Decodes URL-encoded string

hex2bin
htmlentities
Func?ii cu ?iruri de caractere


Convert all applicable characters to HTML entities

html_entity_decode
htmlspecialchars_decode
Func?ii cu ?iruri de caractere
PHP Manual

htmlentities

(PHP 4, PHP 5, PHP 7)

htmlentities — Convert all applicable characters to HTML entities

Descrierea

string htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_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 want to decode instead (the reverse) you can use html_entity_decode().

Parametri

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. Using this flag is discouraged 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 invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of leaving them as is. This may be useful, for instance, to ensure the well-formedness of XML documents with embedded external content.
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.

encoding

Un argument op?ional ce define?te codarea folosita la convertirea caracterelor.

Daca este omisa, valoarea implicita a argumentului encoding variaza în dependen?a de versiunea PHP utilizata. În PHP 5.6 ?i ulterior, valoarea op?iunii de configurare default_charset este utilizata implicit. PHP 5.4 ?i 5.5 vor utiliza implicit UTF-8. Versiunile anterioare ale PHP utilizau ISO-8859-1.

Cu toate ca acest argument este op?ional, tehnic vorbind, va îndemnam sa specifica?i valoarea corecta pentru codul dvs. daca utiliza?i PHP 5.5 sau anterior, sau daca op?iunea de configurare default_charset poate sa nu fie setata corect pentru intrarile date.

The following character sets are supported:

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1.
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
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.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian.
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, SJIS-win, cp932, 932 | Japanese
EUC-JP | EUCJP, eucJP-win | Japanese
MacRoman | Charset that was used by Mac OS.
'' 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.

Nota: 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.

Valorile întoarse

Returns the encoded string.

If the input string contains an invalid code unit sequence within the given encoding an empty string will be returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Valoarea implicita a parametrului encoding a fost schimbata pentru a coincide cu valoarea op?iunii de configurare default_charset.
5.4.0 | The default value for the encoding parameter was changed to UTF-8.
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.

Exemple

Example #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);
?>

Example #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");
?>

A se vedea ?i

  • 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() - URL-encodes string

html_entity_decode
htmlspecialchars_decode
Func?ii cu ?iruri de caractere


Convert special HTML entities back to characters

htmlentities
htmlspecialchars
Func?ii cu ?iruri de caractere
PHP Manual

htmlspecialchars_decode

(PHP 5 >= 5.1.0, PHP 7)

htmlspecialchars_decode — Convert special HTML entities back to characters

Descrierea

string htmlspecialchars_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 ] )

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;.

Parametri

string

The string to decode.

flags

A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. 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_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.

Valorile întoarse

Returns the decoded string.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.

Exemple

Example #1 A htmlspecialchars_decode() example

<?php
$str = "<p>this -&gt; &quot;</p>\n";

echo htmlspecialchars_decode($str);

// note that here the quotes aren't converted
echo htmlspecialchars_decode($str, ENT_NOQUOTES);
?>

Exemplul de mai sus va afi?a:

<p>this -> "</p>
<p>this -> &quot;</p>

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Convert special characters to HTML entities

htmlspecialchars_decode
implode
Func?ii cu ?iruri de caractere
PHP Manual

htmlspecialchars

(PHP 4, PHP 5, PHP 7)

htmlspecialchars — Convert special characters to HTML entities

Descrierea

string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_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 these conversions made. If you require all input substrings that have associated named entities to be translated, use htmlentities() instead.

If the input string passed to this function and the final document share the same character set, this function is sufficient to prepare input for inclusion in most contexts of an HTML document. If, however, the input can represent characters that are not coded in the final document character set and you wish to retain those characters (as numeric or named entities), both this function and htmlentities() (which only encodes substrings that have named entity equivalents) may be insufficient. You may have to use mb_encode_numericentity() instead.

Performed translations
Character | Replacement
& (ampersand) | &amp;
" (double quote) | &quot;, unless ENT_NOQUOTES is set
' (single quote) | &#039; (for ENT_HTML401) or &apos; (for ENT_XML1, ENT_XHTML or ENT_HTML5), but only when ENT_QUOTES is set
< (less than) | &lt;
> (greater than) | &gt;

Parametri

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. Using this flag is discouraged as it » may have security implications.
ENT_SUBSTITUTE | Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#xFFFD; (otherwise) instead of returning an empty string.
ENT_DISALLOWED | Replace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#xFFFD; (otherwise) instead of leaving them as is. This may be useful, for instance, to ensure the well-formedness of XML documents with embedded external content.
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.

encoding

Un argument op?ional ce define?te codarea folosita la convertirea caracterelor.

Daca este omisa, valoarea implicita a argumentului encoding variaza în dependen?a de versiunea PHP utilizata. În PHP 5.6 ?i ulterior, valoarea op?iunii de configurare default_charset este utilizata implicit. PHP 5.4 ?i 5.5 vor utiliza implicit UTF-8. Versiunile anterioare ale PHP utilizau ISO-8859-1.

Cu toate ca acest argument este op?ional, tehnic vorbind, va îndemnam sa specifica?i valoarea corecta pentru codul dvs. daca utiliza?i PHP 5.5 sau anterior, sau daca op?iunea de configurare default_charset poate sa nu fie setata corect pentru intrarile date.

For the purposes of this function, the encodings 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 encoding, as the characters affected by htmlspecialchars() occupy the same positions in all of these encodings.

The following character sets are supported:

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1.
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
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.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian.
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, SJIS-win, cp932, 932 | Japanese
EUC-JP | EUCJP, eucJP-win | Japanese
MacRoman | Charset that was used by Mac OS.
'' 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.

Nota: 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.

Valorile întoarse

The converted string.

If the input string contains an invalid code unit sequence within the given encoding an empty string will be returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | Valoarea implicita a parametrului encoding a fost schimbata pentru a coincide cu valoarea op?iunii de configurare default_charset.
5.4.0 | The default value for the encoding parameter was changed to UTF-8.
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.

Exemple

Example #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;
?>

Note

Nota:

Note that this function does not translate anything beyond what is listed above. For full entity translation, see htmlentities().

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Join array elements with a string

htmlspecialchars
join
Func?ii cu ?iruri de caractere
PHP Manual

implode

(PHP 4, PHP 5, PHP 7)

implode — Join array elements with a string

Descrierea

string implode ( string $glue , array $pieces )
string implode ( array $pieces )

Join array elements with a glue string.

Nota:

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.

Parametri

glue

Defaults to an empty string.

pieces

The array of strings to implode.

Valorile întoarse

Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

Exemple

Example #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) ""

?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • explode() - Split a string by string
  • preg_split() - Split string by a regular expression
  • http_build_query() - Generate URL-encoded query string

htmlspecialchars
join
Func?ii cu ?iruri de caractere


Pseudonim pentru implode

implode
lcfirst
Func?ii cu ?iruri de caractere
PHP Manual

join

(PHP 4, PHP 5, PHP 7)

join — Pseudonim pentru implode()

Descrierea

Aceasta func?ie este pseudonim pentru: implode().

implode
lcfirst
Func?ii cu ?iruri de caractere


Make a string's first character lowercase

join
levenshtein
Func?ii cu ?iruri de caractere
PHP Manual

lcfirst

(PHP 5 >= 5.3.0, PHP 7)

lcfirst — Make a string's first character lowercase

Descrierea

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.

Parametri

str

The input string.

Valorile întoarse

Returns the resulting string.

Exemple

Example #1 lcfirst() example

<?php
$foo = 'HelloWorld';
$foo = lcfirst($foo);             // helloWorld

$bar = 'HELLO WORLD!';
$bar = lcfirst($bar);             // hELLO WORLD!
$bar = lcfirst(strtoupper($bar)); // hELLO WORLD!
?>

A se vedea ?i

  • ucfirst() - Make a string's first character uppercase
  • strtolower() - Make a string lowercase
  • strtoupper() - Make a string uppercase
  • ucwords() - Uppercase the first character of each word in a string

join
levenshtein
Func?ii cu ?iruri de caractere


Calculate Levenshtein distance between two strings

lcfirst
localeconv
Func?ii cu ?iruri de caractere
PHP Manual

levenshtein

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

levenshtein — Calculate Levenshtein distance between two strings

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a:

Input word: carrrot
Did you mean: carrot?

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Get numeric formatting information

levenshtein
ltrim
Func?ii cu ?iruri de caractere
PHP Manual

localeconv

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

localeconv — Get numeric formatting information

Descrierea

array localeconv ( void )

Returns an associative array containing localized numeric and monetary formatting information.

Valorile întoarse

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.

Exemple

Example #1 localeconv() example

<?php
if (false !== setlocale(LC_ALL, 'nl_NL.UTF-8@euro')) {
    $locale_info = localeconv();
    print_r($locale_info);
}
?>

Exemplul de mai sus va afi?a:

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
        )

)

A se vedea ?i

  • setlocale() - Set locale information

levenshtein
ltrim
Func?ii cu ?iruri de caractere


Strip whitespace (or other characters) from the beginning of a string

localeconv
md5_file
Func?ii cu ?iruri de caractere
PHP Manual

ltrim

(PHP 4, PHP 5, PHP 7)

ltrim — Strip whitespace (or other characters) from the beginning of a string

Descrierea

string ltrim ( string $str [, string $character_mask ] )

Strip whitespace (or other characters) from the beginning of a string.

Parametri

str

The input string.

character_mask

You can also specify the characters you want to strip, by means of the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Valorile întoarse

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.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

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
"

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Calculates the md5 hash of a given file

ltrim
md5
Func?ii cu ?iruri de caractere
PHP Manual

md5_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

md5_file — Calculates the md5 hash of a given file

Descrierea

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.

Parametri

filename

The filename

raw_output

When TRUE, returns the digest in raw binary format with a length of 16.

Valorile întoarse

Returns a string on success, FALSE otherwise.

Istoricul schimbarilor

Versiune | Descriere
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/..')

Exemple

Example #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);
?>

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Calculate the md5 hash of a string

md5_file
metaphone
Func?ii cu ?iruri de caractere
PHP Manual

md5

(PHP 4, PHP 5, PHP 7)

md5 — Calculate the md5 hash of a string

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the hash as a 32-character hexadecimal number.

Exemple

Example #1 A md5() example

<?php
$str = 'apple';

if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
    echo "Would you like a green or red apple?";
}
?>

Note

Nota: Hashing-ul securizat al parolelor

Nu este recomandabila utilizatea acestei func?ii pentru a securiza parole din motivul rapidita?ii acestui algoritm de hashing. Vede?i aici pentru detalii.

A se vedea ?i

  • 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)
  • crypt() - One-way string hashing
  • password_hash() - Creates a password hash

md5_file
metaphone
Func?ii cu ?iruri de caractere


Calculate the metaphone key of a string

md5
money_format
Func?ii cu ?iruri de caractere
PHP Manual

metaphone

(PHP 4, PHP 5, PHP 7)

metaphone — Calculate the metaphone key of a string

Descrierea

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].

Parametri

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.

Valorile întoarse

Returns the metaphone key as a string, sau FALSE în cazul e?ecului.

Exemple

Example #1 metaphone() basic example

<?php
var_dump(metaphone('programming'));
var_dump(metaphone('programmer'));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(7) "PRKRMNK"
string(6) "PRKRMR"

Example #2 Using the phonemes parameter

<?php
var_dump(metaphone('programming', 5));
var_dump(metaphone('programmer', 5));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(5) "PRKRM"
string(5) "PRKRM"

md5
money_format
Func?ii cu ?iruri de caractere


Formats a number as a currency string

metaphone
nl_langinfo
Func?ii cu ?iruri de caractere
PHP Manual

money_format

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

money_format — Formats a number as a currency string

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Note

Nota:

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.

Nota:

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.

Exemple

Example #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)

?>

A se vedea ?i

  • 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() - Format a number with grouped thousands

metaphone
nl_langinfo
Func?ii cu ?iruri de caractere


Query language and locale information

money_format
nl2br
Func?ii cu ?iruri de caractere
PHP Manual

nl_langinfo

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

nl_langinfo — Query language and locale information

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns the element as a string, or FALSE if item is not valid.

Note

Nota: Aceasta func?ie nu este implementata pe platformele Windows.

A se vedea ?i

  • setlocale() - Set locale information
  • localeconv() - Get numeric formatting information

money_format
nl2br
Func?ii cu ?iruri de caractere


Inserts HTML line breaks before all newlines in a string

nl_langinfo
number_format
Func?ii cu ?iruri de caractere
PHP Manual

nl2br

(PHP 4, PHP 5, PHP 7)

nl2br — Inserts HTML line breaks before all newlines in a string

Descrierea

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).

Parametri

string

The input string.

is_xhtml

Whether to use XHTML compatible line breaks or not.

Valorile întoarse

Returns the altered string.

Exemple

Example #1 Using nl2br()

<?php
echo nl2br("foo isn't\n bar");
?>

Exemplul de mai sus va afi?a:

foo isn't<br />
 bar

Example #2 Generating valid HTML markup using the is_xhtml parameter

<?php
echo nl2br("Welcome\r\nThis is my HTML document", false);
?>

Exemplul de mai sus va afi?a:

Welcome<br>
This is my HTML document

Example #3 Various newline separators

<?php
$string = "This\r\nis\n\ra\nstring\r";
echo nl2br($string);
?>

Exemplul de mai sus va afi?a:

This<br />
is<br />
a<br />
string<br />

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Added the optional is_xhtml parameter. Before this version '<br />' was always inserted.

A se vedea ?i

  • htmlspecialchars() - Convert special characters to HTML entities
  • htmlentities() - Convert all applicable characters to HTML entities
  • wordwrap() - Wraps a string to a given number of characters
  • str_replace() - Replace all occurrences of the search string with the replacement string

nl_langinfo
number_format
Func?ii cu ?iruri de caractere


Format a number with grouped thousands

nl2br
ord
Func?ii cu ?iruri de caractere
PHP Manual

number_format

(PHP 4, PHP 5, PHP 7)

number_format — Format a number with grouped thousands

Descrierea

string number_format ( float $number [, int $decimals = 0 ] )
string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )

This function accepts either one, two, or four parameters (not three):

If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.

If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.

If all four parameters are given, number will be formatted with decimals decimals, dec_point instead of a dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of thousands.

Parametri

number

The number being formatted.

decimals

Sets the number of decimal points.

dec_point

Sets the separator for the decimal point.

thousands_sep

Sets the thousands separator.

Valorile întoarse

A formatted version of number.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions.

Exemple

Example #1 number_format() Example

For instance, French notation usually use two decimals, comma (',') as decimal separator, and space (' ') as thousand separator. This is achieved with this line :

<?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

A se vedea ?i

  • money_format() - Formats a number as a currency string
  • sprintf() - Return a formatted string
  • printf() - Output a formatted string
  • sscanf() - Parses input from a string according to a format

nl2br
ord
Func?ii cu ?iruri de caractere


Return ASCII value of character

number_format
parse_str
Func?ii cu ?iruri de caractere
PHP Manual

ord

(PHP 4, PHP 5, PHP 7)

ord — Return ASCII value of character

Descrierea

int ord ( string $string )

Returns the ASCII value of the first character of string.

This function complements chr().

Parametri

string

A character.

Valorile întoarse

Returns the ASCII value as an integer.

Exemple

Example #1 ord() example

<?php
$str = "\n";
if (ord($str) == 10) {
    echo "The first character of \$str is a line feed.\n";
}
?>

A se vedea ?i

  • chr() - Return a specific character
  • An » ASCII-table

number_format
parse_str
Func?ii cu ?iruri de caractere


Parses the string into variables

ord
print
Func?ii cu ?iruri de caractere
PHP Manual

parse_str

(PHP 4, PHP 5, PHP 7)

parse_str — Parses the string into variables

Descrierea

void parse_str ( string $encoded_string [, array &$result ] )

Parses encoded_string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).

Parametri

encoded_string

The input string.

result

If the second parameter result is present, variables are stored in this variable as array elements instead.

Avertizare

Using this function without second parameter is DISCOURAGED. Dynamically setting variables in function's scope suffers from exactly same problems as register_globals.

Read section on security of Using Register Globals explaining why it is dangerous.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Using parse_str()

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";

// Recommended
parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

// DISCOURAGED
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
?>

Because variables in PHP can't have dots and spaces in their names, those are converted to underscores. Same applies to naming of respective key names in case of using this function with result parameter.

Example #2 parse_str() name mangling

<?php
parse_str($"My Value=Something");
echo $My_Value; // Something

parse_str($"My Value=Something", $output);
echo $output['My_Value']; // Something
?>

Note

Nota:

All variables created (or values returned into array if second parameter is set) are already urldecode()d.

Nota:

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.

Nota:

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.

A se vedea ?i

  • parse_url() - Parse a URL and return its components
  • pathinfo() - Returns information about a file path
  • http_build_query() - Generate URL-encoded query string
  • urldecode() - Decodes URL-encoded string

ord
print
Func?ii cu ?iruri de caractere


Output a string

parse_str
printf
Func?ii cu ?iruri de caractere
PHP Manual

print

(PHP 4, PHP 5, PHP 7)

print — Output a string

Descrierea

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.

The only difference to echo is that print only accepts a single argument.

Parametri

arg

The input data.

Valorile întoarse

Returns 1, always.

Exemple

Example #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;
?>

Note

Nota: Deoarece aceasta este o construc?ie a limbajului ?i nu o func?ie, ea nu poate fi apelata utilizând func?ii de operare cu variabile .

A se vedea ?i

  • echo - Output one or more strings
  • printf() - Output a formatted string
  • flush() - Flush system output buffer
  • Heredoc syntax

parse_str
printf
Func?ii cu ?iruri de caractere


Output a formatted string

print
quoted_printable_decode
Func?ii cu ?iruri de caractere
PHP Manual

printf

(PHP 4, PHP 5, PHP 7)

printf — Output a formatted string

Descrierea

int printf ( string $format [, mixed $args [, mixed $... ]] )

Produces output according to format.

Parametri

format

See sprintf() for a description of format.

args

...

Valorile întoarse

Returns the length of the outputted string.

A se vedea ?i

  • 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() - Parses input from a file according to a format
  • flush() - Flush system output buffer

print
quoted_printable_decode
Func?ii cu ?iruri de caractere


Convert a quoted-printable string to an 8 bit string

printf
quoted_printable_encode
Func?ii cu ?iruri de caractere
PHP Manual

quoted_printable_decode

(PHP 4, PHP 5, PHP 7)

quoted_printable_decode — Convert a quoted-printable string to an 8 bit string

Descrierea

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.

Parametri

str

The input string.

Valorile întoarse

Returns the 8-bit binary string.

A se vedea ?i

  • quoted_printable_encode() - Convert a 8 bit string to a quoted-printable string

printf
quoted_printable_encode
Func?ii cu ?iruri de caractere


Convert a 8 bit string to a quoted-printable string

quoted_printable_decode
quotemeta
Func?ii cu ?iruri de caractere
PHP Manual

quoted_printable_encode

(PHP 5 >= 5.3.0, PHP 7)

quoted_printable_encode — Convert a 8 bit string to a quoted-printable string

Descrierea

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.

Parametri

str

The input string.

Valorile întoarse

Returns the encoded string.

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Quote meta characters

quoted_printable_encode
rtrim
Func?ii cu ?iruri de caractere
PHP Manual

quotemeta

(PHP 4, PHP 5, PHP 7)

quotemeta — Quote meta characters

Descrierea

string quotemeta ( string $str )

Returns a version of str with a backslash character (\) before every character that is among these:

. \ + * ? [ ^ ] ( $ )

Parametri

str

The input string.

Valorile întoarse

Returns the string with meta characters quoted, or FALSE if an empty string is given as str.

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • 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
  • ereg() - Regular expression match
  • preg_quote() - Quote regular expression characters

quoted_printable_encode
rtrim
Func?ii cu ?iruri de caractere


Strip whitespace (or other characters) from the end of a string

quotemeta
setlocale
Func?ii cu ?iruri de caractere
PHP Manual

rtrim

(PHP 4, PHP 5, PHP 7)

rtrim — Strip whitespace (or other characters) from the end of a string

Descrierea

string rtrim ( string $str [, string $character_mask ] )

This function returns a string with whitespace (or other characters) 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 NULL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Parametri

str

The input string.

character_mask

You can also specify the characters you want to strip, by means of the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Valorile întoarse

Returns the modified string.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

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"

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Set locale information

rtrim
sha1_file
Func?ii cu ?iruri de caractere
PHP Manual

setlocale

(PHP 4, PHP 5, PHP 7)

setlocale — Set locale information

Descrierea

string setlocale ( int $category , string $locale [, string $... ] )
string setlocale ( int $category , array $locale )

Sets locale information.

Parametri

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.)

Nota:

On Windows, setlocale(LC_ALL, '') sets the locale names from the system's regional/language settings (accessible via Control Panel).

Valorile întoarse

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.

Nota:

The return value of setlocale() depends on the system that PHP is running. It returns exactly what the system setlocale function returns.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | Support for the category parameter passed as a string has been removed. Only LC_* constants can be used as of this version.
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.

Exemple

Example #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 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
echo "Preferred locale for german on this system is '$loc_de'";
?>

Example #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 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo "Preferred locale for german on this system is '$loc_de'";
?>

Note

Avertizare

The locale information is maintained per process, not per thread. If you are running PHP on a multithreaded server API like IIS, HHVM 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().

Sfat

Windows users will find useful information about locale strings at Microsoft's MSDN website. Supported language strings can be found in the » language strings documentation and supported country/region strings in the » country/region strings documentation.

rtrim
sha1_file
Func?ii cu ?iruri de caractere


Calculate the sha1 hash of a file

setlocale
sha1
Func?ii cu ?iruri de caractere
PHP Manual

sha1_file

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

sha1_file — Calculate the sha1 hash of a file

Descrierea

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.

Parametri

filename

The filename of the file to hash.

raw_output

When TRUE, returns the digest in raw binary format with a length of 20.

Valorile întoarse

Returns a string on success, FALSE otherwise.

Exemple

Example #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;
}
?>

Istoricul schimbarilor

Versiune | Descriere
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/..')

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Calculate the sha1 hash of a string

sha1_file
similar_text
Func?ii cu ?iruri de caractere
PHP Manual

sha1

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

sha1 — Calculate the sha1 hash of a string

Descrierea

string sha1 ( string $str [, bool $raw_output = false ] )

Calculates the sha1 hash of str using the » US Secure Hash Algorithm 1.

Parametri

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.

Valorile întoarse

Returns the sha1 hash as a string.

Exemple

Example #1 A sha1() example

<?php
$str = 'apple';

if (sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
    echo "Would you like a green or red apple?";
}
?>

Note

Nota: Hashing-ul securizat al parolelor

Nu este recomandabila utilizatea acestei func?ii pentru a securiza parole din motivul rapidita?ii acestui algoritm de hashing. Vede?i aici pentru detalii.

A se vedea ?i

  • 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)
  • crypt() - One-way string hashing
  • password_hash() - Creates a password hash

sha1_file
similar_text
Func?ii cu ?iruri de caractere


Calculate the similarity between two strings

sha1
soundex
Func?ii cu ?iruri de caractere
PHP Manual

similar_text

(PHP 4, PHP 5, PHP 7)

similar_text — Calculate the similarity between two strings

Descrierea

int similar_text ( string $first , string $second [, float &$percent ] )

This calculates the similarity between two strings as described in Programming Classics: Implementing the World's Best Algorithms by Oliver (ISBN 0-131-00413-1). 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.

Parametri

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.

Valorile întoarse

Returns the number of matching chars in both strings.

A se vedea ?i

  • levenshtein() - Calculate Levenshtein distance between two strings
  • soundex() - Calculate the soundex key of a string

sha1
soundex
Func?ii cu ?iruri de caractere


Calculate the soundex key of a string

similar_text
sprintf
Func?ii cu ?iruri de caractere
PHP Manual

soundex

(PHP 4, PHP 5, PHP 7)

soundex — Calculate the soundex key of a string

Descrierea

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.

Parametri

str

The input string.

Valorile întoarse

Returns the soundex key as a string.

Exemple

Example #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
?>

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Return a formatted string

soundex
sscanf
Func?ii cu ?iruri de caractere
PHP Manual

sprintf

(PHP 4, PHP 5, PHP 7)

sprintf — Return a formatted string

Descrierea

string sprintf ( string $format [, mixed $args [, mixed $... ]] )

Returns a string produced according to the formatting string format.

Parametri

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.
  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. Additionally, the character to use when padding a number may optionally be specified between the period and the digit.

  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).
    • 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 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.
    • u - the argument is treated as an integer, and presented as an unsigned decimal number.
    • 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).

Variables will be co-erced to a suitable type for the specifier:

Type Handling
Type | Specifiers
string | s
integer | d, u, c, o, x, X, b
double | g, G, e, E, f, F

Avertizare

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

The format string supports argument numbering/swapping. Here is an example:

Example #1 Argument swapping

<?php
$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
echo sprintf($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:

Example #2 Argument swapping

<?php
$format = 'The %s contains %d monkeys';
echo sprintf($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:

Example #3 Argument swapping

<?php
$format = 'The %2$s contains %1$d monkeys';
echo sprintf($format, $num, $location);
?>
An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example:

Example #4 Argument swapping

<?php
$format = 'The %2$s contains %1$d monkeys.
           That\'s a nice %2$s full of %1$d monkeys.';
echo sprintf($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.

Example #5 Specifying padding character

<?php
echo sprintf("%'.9d\n", 123);
echo sprintf("%'.09d\n", 123);
?>

Exemplul de mai sus va afi?a:

......123
000000123

Example #6 Position specifier with other specifiers

<?php
$format = 'The %2$s contains %1$04d monkeys';
echo sprintf($format, $num, $location);
?>

Exemplul de mai sus va afi?a:

The tree contains 0005 monkeys

Nota:

Attempting to use a position specifier greater than PHP_INT_MAX will result in sprintf() generating warnings.

Avertizare

The c type specifier ignores padding and width

args

...

Valorile întoarse

Returns a string produced according to the formatting string format, sau FALSE în cazul e?ecului.

Exemple

Example #7 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
?>

Exemplul de mai sus va afi?a:

%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'

Example #8 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
?>

Exemplul de mai sus va afi?a:

[monkey]
[    monkey]
[monkey    ]
[0000monkey]
[####monkey]
[many monke]

Example #9 sprintf(): zero-padded integers

<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

Example #10 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"
?>

Example #11 sprintf(): scientific notation

<?php
$number = 362525200;

echo sprintf("%.3e", $number); // outputs 3.625e+8
?>

A se vedea ?i

  • printf() - Output a formatted string
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • vsprintf() - Return a formatted string
  • number_format() - Format a number with grouped thousands
  • date() - Formateaza o ora/data

soundex
sscanf
Func?ii cu ?iruri de caractere


Parses input from a string according to a format

sprintf
str_getcsv
Func?ii cu ?iruri de caractere
PHP Manual

sscanf

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

sscanf — Parses input from a string according to a format

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

If there are more substrings expected in the format than there are available within str, -1 will be returned.

Exemple

Example #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.

Example #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";
?>

A se vedea ?i

  • fscanf() - Parses input from a file according to a format
  • printf() - Output a formatted string
  • sprintf() - Return a formatted string

sprintf
str_getcsv
Func?ii cu ?iruri de caractere


Parse a CSV string into an array

sscanf
str_ireplace
Func?ii cu ?iruri de caractere
PHP Manual

str_getcsv

(PHP 5 >= 5.3.0, PHP 7)

str_getcsv — Parse a CSV string into an array

Descrierea

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.

Parametri

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 (\)

Valorile întoarse

Returns an indexed array containing the fields read.

A se vedea ?i

  • fgetcsv() - Gets line from file pointer and parse for CSV fields

sscanf
str_ireplace
Func?ii cu ?iruri de caractere


Case-insensitive version of str_replace.

str_getcsv
str_pad
Func?ii cu ?iruri de caractere
PHP Manual

str_ireplace

(PHP 5, PHP 7)

str_ireplace — Case-insensitive version of str_replace().

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a string or an array of replacements.

Exemple

Example #1 str_ireplace() example

<?php
$bodytag = str_ireplace("%body%", "black", "<body text=%BODY%>");
echo $bodytag; // <body text=black>
?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

Precautie

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.

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Pad a string to a certain length with another string

str_ireplace
str_repeat
Func?ii cu ?iruri de caractere
PHP Manual

str_pad

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

str_pad — Pad a string to a certain length with another string

Descrierea

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.

Parametri

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, and input will be returned.

pad_string

Nota:

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.

Valorile întoarse

Returns the padded string.

Exemple

Example #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_"
echo str_pad($input,  3, "*");                 // produces "Alien"
?>

str_ireplace
str_repeat
Func?ii cu ?iruri de caractere


Repeat a string

str_pad
str_replace
Func?ii cu ?iruri de caractere
PHP Manual

str_repeat

(PHP 4, PHP 5, PHP 7)

str_repeat — Repeat a string

Descrierea

string str_repeat ( string $input , int $multiplier )

Returns input repeated multiplier times.

Parametri

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.

Valorile întoarse

Returns the repeated string.

Exemple

Example #1 str_repeat() example

<?php
echo str_repeat("-=", 10);
?>

Exemplul de mai sus va afi?a:

-=-=-=-=-=-=-=-=-=-=

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Replace all occurrences of the search string with the replacement string

str_repeat
str_rot13
Func?ii cu ?iruri de caractere
PHP Manual

str_replace

(PHP 4, PHP 5, PHP 7)

str_replace — Replace all occurrences of the search string with the replacement string

Descrierea

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().

Parametri

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.

Valorile întoarse

This function returns a string or an array with the replaced values.

Exemple

Example #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;
?>

Example #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;
?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

Precautie

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.

Nota:

This function is case-sensitive. Use str_ireplace() for case-insensitive replace.

A se vedea ?i

  • str_ireplace() - Case-insensitive version of str_replace.
  • substr_replace() - Replace text within a portion of a string
  • preg_replace() - Perform a regular expression search and replace
  • strtr() - Translate characters or replace substrings

str_repeat
str_rot13
Func?ii cu ?iruri de caractere


Perform the rot13 transform on a string

str_replace
str_shuffle
Func?ii cu ?iruri de caractere
PHP Manual

str_rot13

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

str_rot13 — Perform the rot13 transform on a string

Descrierea

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.

Parametri

str

The input string.

Valorile întoarse

Returns the ROT13 version of the given string.

Exemple

Example #1 str_rot13() example

<?php

echo str_rot13('PHP 4.3.0'); // CUC 4.3.0

?>

str_replace
str_shuffle
Func?ii cu ?iruri de caractere


Randomly shuffles a string

str_rot13
str_split
Func?ii cu ?iruri de caractere
PHP Manual

str_shuffle

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

str_shuffle — Randomly shuffles a string

Descrierea

string str_shuffle ( string $str )

str_shuffle() shuffles a string. One permutation of all possible is created.

Precautie

Aceasta func?ie nu genereaza valori securizate din punct de vedere criptografic ?i deci nu trebuie utilizata pentru scopuri criptografice. Daca ave?i nevoie de o valoare securizata din punct de vedere criptografic considera?i utilizarea random_int(), random_bytes() sau openssl_random_pseudo_bytes() în schimb.

Parametri

str

The input string.

Valorile întoarse

Returns the shuffled string.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | The internal randomization algorithm has been changed to use the » Mersenne Twister Random Number Generator instead of the libc rand function.

Exemple

Example #1 str_shuffle() example

<?php
$str = 'abcdef';
$shuffled = str_shuffle($str);

// This will echo something like: bfdaec
echo $shuffled;
?>

A se vedea ?i

  • shuffle() - Shuffle an array
  • rand() - Generate a random integer

str_rot13
str_split
Func?ii cu ?iruri de caractere


Convert a string to an array

str_shuffle
str_word_count
Func?ii cu ?iruri de caractere
PHP Manual

str_split

(PHP 5, PHP 7)

str_split — Convert a string to an array

Descrierea

array str_split ( string $string [, int $split_length = 1 ] )

Converts a string to an array.

Parametri

string

The input string.

split_length

Maximum length of the chunk.

Valorile întoarse

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.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

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
)

Note

Nota:

str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string.

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Return information about words used in a string

str_split
strcasecmp
Func?ii cu ?iruri de caractere
PHP Manual

str_word_count

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

str_word_count — Return information about words used in a string

Descrierea

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.

Parametri

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'

Valorile întoarse

Returns an array or an integer, depending on the format chosen.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Added the charlist parameter

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Binary safe case-insensitive string comparison

str_word_count
strchr
Func?ii cu ?iruri de caractere
PHP Manual

strcasecmp

(PHP 4, PHP 5, PHP 7)

strcasecmp — Binary safe case-insensitive string comparison

Descrierea

int strcasecmp ( string $str1 , string $str2 )

Binary safe case-insensitive string comparison.

Parametri

str1

The first string

str2

The second string

Valorile întoarse

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Exemple

Example #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';
}
?>

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Pseudonim pentru strstr

strcasecmp
strcmp
Func?ii cu ?iruri de caractere
PHP Manual

strchr

(PHP 4, PHP 5, PHP 7)

strchr — Pseudonim pentru strstr()

Descrierea

Aceasta func?ie este pseudonim pentru: strstr().

strcasecmp
strcmp
Func?ii cu ?iruri de caractere


Binary safe string comparison

strchr
strcoll
Func?ii cu ?iruri de caractere
PHP Manual

strcmp

(PHP 4, PHP 5, PHP 7)

strcmp — Binary safe string comparison

Descrierea

int strcmp ( string $str1 , string $str2 )

Note that this comparison is case sensitive.

Parametri

str1

The first string.

str2

The second string.

Valorile întoarse

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Exemple

Example #1 strcmp() example

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcmp($var1, $var2) !== 0) {
    echo '$var1 is not equal to $var2 in a case sensitive string comparison';
}
?>

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Locale based string comparison

strcmp
strcspn
Func?ii cu ?iruri de caractere
PHP Manual

strcoll

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

strcoll — Locale based string comparison

Descrierea

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().

Parametri

str1

The first string.

str2

The second string.

Valorile întoarse

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Istoricul schimbarilor

Versiune | Descriere
4.2.3 | This function now works on win32.

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Find length of initial segment not matching mask

strcoll
strip_tags
Func?ii cu ?iruri de caractere
PHP Manual

strcspn

(PHP 4, PHP 5, PHP 7)

strcspn — Find length of initial segment not matching mask

Descrierea

int strcspn ( string $subject , string $mask [, int $start [, int $length ]] )

Returns the length of the initial segment of subject which does not contain any of the characters in 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 strcspn(substr($subject, $start, $length), $mask) (see substr for more information).

Parametri

subject

The string to examine.

mask

The string containing every disallowed character.

start

The position in subject to start searching.

If start is given and is non-negative, then strcspn() 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 strcspn() 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 length is given and is negative, then subject will be examined from the starting position up to length characters from the end of subject.

Valorile întoarse

Returns the length of the initial segment of subject which consists entirely of characters not in mask.

Nota:

When a start parameter is set, the returned length is counted starting from this position, not from the beginning of subject.

Exemple

Example #1 strcspn() example

<?php
$a = strcspn('abcd',  'apple');
$b = strcspn('abcd',  'banana');
$c = strcspn('hello', 'l');
$d = strcspn('hello', 'world');
$e = strcspn('abcdhelloabcd', 'abcd', -9);
$f = strcspn('abcdhelloabcd', 'abcd', -9, -5);

var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($e);
var_dump($f);
?>

Exemplul de mai sus va afi?a:

int(0)
int(0)
int(2)
int(2)
int(5)
int(4)

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • strspn() - Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.

strcoll
strip_tags
Func?ii cu ?iruri de caractere


Strip HTML and PHP tags from a string

strcspn
stripcslashes
Func?ii cu ?iruri de caractere
PHP Manual

strip_tags

(PHP 4, PHP 5, PHP 7)

strip_tags — Strip HTML and PHP tags from a string

Descrierea

string strip_tags ( string $str [, string $allowable_tags ] )

This function tries to return a string with all NULL bytes, HTML and PHP tags stripped from a given str. It uses the same tag stripping state machine as the fgetss() function.

Parametri

str

The input string.

allowable_tags

You can use the optional second parameter to specify tags which should not be stripped.

Nota:

HTML comments and PHP tags are also stripped. This is hardcoded and can not be changed with allowable_tags.

Nota:

In PHP 5.3.4 and later, self-closing XHTML tags are ignored and only non-self-closing tags should be used in allowable_tags. For example, to allow both <br> and <br/>, you should use:

<?php
strip_tags($input, '<br>');
?>

Valorile întoarse

Returns the stripped string.

Istoricul schimbarilor

Versiune | Descriere
5.3.4 | strip_tags() ignores self-closing XHTML tags in allowable_tags.
5.0.0 | strip_tags() is now binary safe.

Exemple

Example #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>');
?>

Exemplul de mai sus va afi?a:

Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>

Note

Avertizare

Because strip_tags() does not actually validate the HTML, partial or broken tags can result in the removal of more text/data than expected.

Avertizare

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.

Nota:

Tag names within the input HTML that are greater than 1023 bytes in length will be treated as though they are invalid, regardless of the allowable_tags parameter.

A se vedea ?i

  • htmlspecialchars() - Convert special characters to HTML entities

strcspn
stripcslashes
Func?ii cu ?iruri de caractere


Un-quote string quoted with addcslashes

strip_tags
stripos
Func?ii cu ?iruri de caractere
PHP Manual

stripcslashes

(PHP 4, PHP 5, PHP 7)

stripcslashes — Un-quote string quoted with addcslashes()

Descrierea

string stripcslashes ( string $str )

Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation.

Parametri

str

The string to be unescaped.

Valorile întoarse

Returns the unescaped string.

A se vedea ?i

  • addcslashes() - Quote string with slashes in a C style

strip_tags
stripos
Func?ii cu ?iruri de caractere


Find the position of the first occurrence of a case-insensitive substring in a string

stripcslashes
stripslashes
Func?ii cu ?iruri de caractere
PHP Manual

stripos

(PHP 5, PHP 7)

stripos — Find the position of the first occurrence of a case-insensitive substring in a string

Descrierea

mixed 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.

Parametri

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. If the offset is negative, the search will start this number of characters counted from the end of the string.

Valorile întoarse

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.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Support for negative offsets has been added.

Exemple

Example #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";
}
?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • mb_stripos() - Finds position of first occurrence of a string within another, case insensitive
  • strpos() - Find the position of the first occurrence of a substring in a string
  • strrpos() - Find the position of the last occurrence of a substring in a string
  • 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
Func?ii cu ?iruri de caractere


Un-quotes a quoted string

stripos
stristr
Func?ii cu ?iruri de caractere
PHP Manual

stripslashes

(PHP 4, PHP 5, PHP 7)

stripslashes — Un-quotes a quoted string

Descrierea

string stripslashes ( string $str )

Un-quotes a quoted string.

Nota:

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 was on by default before PHP 5.4), 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.

Parametri

str

The input string.

Valorile întoarse

Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).

Exemple

Example #1 A stripslashes() example

<?php
$str = "Is your name O\'reilly?";

// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>

Nota:

stripslashes() is not recursive. If you want to apply this function to a multi-dimensional array, you need to use a recursive function.

Example #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);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => f'oo
    [1] => b'ar
    [2] => Array
        (
            [0] => fo'o
            [1] => b'ar
        )

)

A se vedea ?i

  • addslashes() - Quote string with slashes
  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc

stripos
stristr
Func?ii cu ?iruri de caractere


Case-insensitive strstr

stripslashes
strlen
Func?ii cu ?iruri de caractere
PHP Manual

stristr

(PHP 4, PHP 5, PHP 7)

stristr — Case-insensitive strstr()

Descrierea

string stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

Returns all of haystack starting from and including the first occurrence of needle to the end.

Parametri

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 (excluding needle).

needle and haystack are examined in a case-insensitive manner.

Valorile întoarse

Returns the matched substring. If needle is not found, returns FALSE.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Added the optional parameter before_needle.
4.3.0 | stristr() was made binary safe.

Exemple

Example #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
?>

Example #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
?>

Example #3 Using a non "string" needle

<?php
  $string = 'APPLE';
  echo stristr($string, 97); // 97 = lowercase a
// outputs: APPLE
?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • strstr() - Find the first occurrence of a string
  • strrchr() - Find the last occurrence of a character in a string
  • 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
Func?ii cu ?iruri de caractere


Get string length

stristr
strnatcasecmp
Func?ii cu ?iruri de caractere
PHP Manual

strlen

(PHP 4, PHP 5, PHP 7)

strlen — Get string length

Descrierea

int strlen ( string $string )

Returns the length of the given string.

Parametri

string

The string being measured for length.

Valorile întoarse

The length of the string on success, and 0 if the string is empty.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #1 A strlen() example

<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
?>

Note

Nota:

strlen() returns the number of bytes rather than the number of characters in a string.

Nota:

strlen() returns NULL when executed on arrays, and an E_WARNING level error is emitted.

A se vedea ?i

  • count() - Count all elements in an array, or something in an object
  • grapheme_strlen() - Get string length in grapheme units
  • iconv_strlen() - Returns the character count of string
  • mb_strlen() - Get string length

stristr
strnatcasecmp
Func?ii cu ?iruri de caractere


Case insensitive string comparisons using a "natural order" algorithm

strlen
strnatcmp
Func?ii cu ?iruri de caractere
PHP Manual

strnatcasecmp

(PHP 4, PHP 5, PHP 7)

strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm

Descrierea

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.

Parametri

str1

The first string.

str2

The second string.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


String comparisons using a "natural order" algorithm

strnatcasecmp
strncasecmp
Func?ii cu ?iruri de caractere
PHP Manual

strnatcmp

(PHP 4, PHP 5, PHP 7)

strnatcmp — String comparisons using a "natural order" algorithm

Descrierea

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.

Parametri

str1

The first string.

str2

The second string.

Valorile întoarse

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.

Exemple

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);
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • 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() - Sort an array using a "natural order" algorithm
  • natcasesort() - Sort an array using a case insensitive "natural order" algorithm

strnatcasecmp
strncasecmp
Func?ii cu ?iruri de caractere


Binary safe case-insensitive string comparison of the first n characters

strnatcmp
strncmp
Func?ii cu ?iruri de caractere
PHP Manual

strncasecmp

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

strncasecmp — Binary safe case-insensitive string comparison of the first n characters

Descrierea

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.

Parametri

str1

The first string.

str2

The second string.

len

The length of strings to be used in the comparison.

Valorile întoarse

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Binary safe string comparison of the first n characters

strncasecmp
strpbrk
Func?ii cu ?iruri de caractere
PHP Manual

strncmp

(PHP 4, PHP 5, PHP 7)

strncmp — Binary safe string comparison of the first n characters

Descrierea

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.

Parametri

str1

The first string.

str2

The second string.

len

Number of characters to use in the comparison.

Valorile întoarse

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Search a string for any of a set of characters

strncmp
strpos
Func?ii cu ?iruri de caractere
PHP Manual

strpbrk

(PHP 5, PHP 7)

strpbrk — Search a string for any of a set of characters

Descrierea

string strpbrk ( string $haystack , string $char_list )

strpbrk() searches the haystack string for a char_list.

Parametri

haystack

The string where char_list is looked for.

char_list

This parameter is case sensitive.

Valorile întoarse

Returns a string starting from the character found, or FALSE if it is not found.

Exemple

Example #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');
?>

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Find the position of the first occurrence of a substring in a string

strpbrk
strrchr
Func?ii cu ?iruri de caractere
PHP Manual

strpos

(PHP 4, PHP 5, PHP 7)

strpos — Find the position of the first occurrence of a substring in a string

Descrierea

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

Find the numeric position of the first occurrence of needle in the haystack string.

Parametri

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 offset is negative, the search will start this number of characters counted from the end of the string.

Valorile întoarse

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.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Support for negative offsets has been added.

Exemple

Example #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";
}
?>

Example #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'";
}
?>

Example #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
?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strrpos() - Find the position of the last occurrence of a substring in a string
  • 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
Func?ii cu ?iruri de caractere


Find the last occurrence of a character in a string

strpos
strrev
Func?ii cu ?iruri de caractere
PHP Manual

strrchr

(PHP 4, PHP 5, PHP 7)

strrchr — Find the last occurrence of a character in a string

Descrierea

string strrchr ( string $haystack , mixed $needle )

This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.

Parametri

haystack

The string to search in

needle

If needle contains more than one character, only the first is used. This behavior is different from that of strstr().

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Valorile întoarse

This function returns the portion of string, or FALSE if needle is not found.

Istoricul schimbarilor

Versiune | Descriere
4.3.0 | This function is now binary safe.

Exemple

Example #1 strrchr() example

<?php
// get last directory in $PATH
$dir = substr(strrchr($PATH, ":"), 1);

// get everything after last newline
$text = "Line 1\nLine 2\nLine 3";
$last = substr(strrchr($text, 10), 1 );
?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • strstr() - Find the first occurrence of a string
  • strrpos() - Find the position of the last occurrence of a substring in a string

strpos
strrev
Func?ii cu ?iruri de caractere


Reverse a string

strrchr
strripos
Func?ii cu ?iruri de caractere
PHP Manual

strrev

(PHP 4, PHP 5, PHP 7)

strrev — Reverse a string

Descrierea

string strrev ( string $string )

Returns string, reversed.

Parametri

string

The string to be reversed.

Valorile întoarse

Returns the reversed string.

Exemple

Example #1 Reversing a string with strrev()

<?php
echo strrev("Hello world!"); // outputs "!dlrow olleH"
?>

strrchr
strripos
Func?ii cu ?iruri de caractere


Find the position of the last occurrence of a case-insensitive substring in a string

strrev
strrpos
Func?ii cu ?iruri de caractere
PHP Manual

strripos

(PHP 5, PHP 7)

strripos — Find the position of the last occurrence of a case-insensitive substring in a string

Descrierea

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.

Parametri

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.

Valorile întoarse

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.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Exemple

Example #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)";
}
?>

Exemplul de mai sus va afi?a:

   Congratulations!
   We found the last (aB) in (ababcd) at position (2)

A se vedea ?i

  • 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() - Find the position of the last occurrence of a substring in a string
  • strrchr() - Find the last occurrence of a character in a string
  • stristr() - Case-insensitive strstr
  • substr() - Return part of a string

strrev
strrpos
Func?ii cu ?iruri de caractere


Find the position of the last occurrence of a substring in a string

strripos
strspn
Func?ii cu ?iruri de caractere
PHP Manual

strrpos

(PHP 4, PHP 5, PHP 7)

strrpos — Find the position of the last occurrence of a substring in a string

Descrierea

int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

Find the numeric position of the last occurrence of needle in the haystack string.

Parametri

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.

Valorile întoarse

Returns the position where the needle exists relative to the beginning 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.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Istoricul schimbarilor

Versiune | Descriere
5.0.0 | The needle may now be a string of more than one character.

Exemple

Example #1 Checking if a needle is in the haystack

It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference:

<?php

$pos = strrpos($mystring, "b");
if ($pos === false) { // note: three equal signs
    // not found...
}

?>

Example #2 Searching with offsets

<?php
$foo = "0123456789a123456789b123456789c";

var_dump(strrpos($foo, '7', -5));  // Starts looking backwards five positions
                                   // from the end. Result: int(17)

var_dump(strrpos($foo, '7', 20));  // Starts searching 20 positions into the
                                   // string. Result: int(27)

var_dump(strrpos($foo, '7', 28));  // Result: bool(false)
?>

A se vedea ?i

  • 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
  • strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
  • strrchr() - Find the last occurrence of a character in a string
  • substr() - Return part of a string

strripos
strspn
Func?ii cu ?iruri de caractere


Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.

strrpos
strstr
Func?ii cu ?iruri de caractere
PHP Manual

strspn

(PHP 4, PHP 5, PHP 7)

strspn — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.

Descrierea

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".

Parametri

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 length is given and is negative, then subject will be examined from the starting position up to length characters from the end of subject.

Valorile întoarse

Returns the length of the initial segment of subject which consists entirely of characters in mask.

Nota:

When a start parameter is set, the returned length is counted starting from this position, not from the beginning of subject.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

int(0)
int(2)
int(1)

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • strcspn() - Find length of initial segment not matching mask

strrpos
strstr
Func?ii cu ?iruri de caractere


Find the first occurrence of a string

strspn
strtok
Func?ii cu ?iruri de caractere
PHP Manual

strstr

(PHP 4, PHP 5, PHP 7)

strstr — Find the first occurrence of a string

Descrierea

string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.

Nota:

This function is case-sensitive. For case-insensitive searches, use stristr().

Nota:

If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.

Parametri

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 (excluding the needle).

Valorile întoarse

Returns the portion of string, or FALSE if needle is not found.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Added the optional parameter before_needle.
4.3.0 | strstr() was made binary safe.

Exemple

Example #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
?>

A se vedea ?i

  • stristr() - Case-insensitive strstr
  • strrchr() - Find the last occurrence of a character in a string
  • 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
Func?ii cu ?iruri de caractere


Tokenize string

strstr
strtolower
Func?ii cu ?iruri de caractere
PHP Manual

strtok

(PHP 4, PHP 5, PHP 7)

strtok — Tokenize string

Descrierea

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 is found.

Parametri

str

The string being split up into smaller strings (tokens).

token

The delimiter used when splitting up str.

Valorile întoarse

A string token.

Exemple

Example #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");
}
?>

Example #2 strtok() behavior on empty part found

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

Exemplul de mai sus va afi?a:

    string(9) "something"
    bool(false)

Note

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

A se vedea ?i

  • split() - Split string into array by regular expression
  • explode() - Split a string by string

strstr
strtolower
Func?ii cu ?iruri de caractere


Make a string lowercase

strtok
strtoupper
Func?ii cu ?iruri de caractere
PHP Manual

strtolower

(PHP 4, PHP 5, PHP 7)

strtolower — Make a string lowercase

Descrierea

string strtolower ( string $string )

Returns string with all alphabetic characters converted to lowercase.

Note that 'alphabetic' is determined by the current locale. This means that e.g. in the default "C" locale, characters such as umlaut-A (Ä) will not be converted.

Parametri

string

The input string.

Valorile întoarse

Returns the lowercased string.

Exemple

Example #1 strtolower() example

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
echo $str; // Prints mary had a little lamb and she loved it so
?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • strtoupper() - Make a string uppercase
  • ucfirst() - Make a string's first character uppercase
  • ucwords() - Uppercase the first character of each word in a string
  • mb_strtolower() - Make a string lowercase

strtok
strtoupper
Func?ii cu ?iruri de caractere


Make a string uppercase

strtolower
strtr
Func?ii cu ?iruri de caractere
PHP Manual

strtoupper

(PHP 4, PHP 5, PHP 7)

strtoupper — Make a string uppercase

Descrierea

string strtoupper ( string $string )

Returns string with all alphabetic characters converted to uppercase.

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.

Parametri

string

The input string.

Valorile întoarse

Returns the uppercased string.

Exemple

Example #1 strtoupper() example

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtoupper($str);
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • strtolower() - Make a string lowercase
  • ucfirst() - Make a string's first character uppercase
  • ucwords() - Uppercase the first character of each word in a string
  • mb_strtoupper() - Make a string uppercase

strtolower
strtr
Func?ii cu ?iruri de caractere


Translate characters or replace substrings

strtoupper
substr_compare
Func?ii cu ?iruri de caractere
PHP Manual

strtr

(PHP 4, PHP 5, PHP 7)

strtr — Translate characters or replace substrings

Descrierea

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; additionally, 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.

Parametri

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', ...).

Valorile întoarse

Returns the translated string.

If replace_pairs contains a key which is an empty string (""), FALSE will be returned. If the str is not a scalar then it is not typecasted into a string, instead a warning is raised and NULL is returned.

Exemple

Example #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.

Example #2 strtr() example with two arguments

<?php
$trans = array("h" => "-", "hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>

Exemplul de mai sus va afi?a:

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.

Example #3 strtr() behavior comparison

<?php
echo strtr("baab", "ab", "01"),"\n";

$trans = array("ab" => "01");
echo strtr("baab", $trans);
?>

Exemplul de mai sus va afi?a:

1001
ba01

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Binary safe comparison of two strings from an offset, up to length characters

strtr
substr_count
Func?ii cu ?iruri de caractere
PHP Manual

substr_compare

(PHP 5, PHP 7)

substr_compare — Binary safe comparison of two strings from an offset, up to length characters

Descrierea

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.

Parametri

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.

Valorile întoarse

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 the length is set and is less than 1 (prior to PHP 5.6), substr_compare() prints a warning and returns FALSE.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | length may now be 0.
5.1.0 | Added the possibility to use a negative offset.

Exemple

Example #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
?>

A se vedea ?i

  • strncmp() - Binary safe string comparison of the first n characters

strtr
substr_count
Func?ii cu ?iruri de caractere


Count the number of substring occurrences

substr_compare
substr_replace
Func?ii cu ?iruri de caractere
PHP Manual

substr_count

(PHP 4, PHP 5, PHP 7)

substr_count — Count the number of substring occurrences

Descrierea

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.

Nota:

This function doesn't count overlapped substrings. See the example below!

Parametri

haystack

The string to search in

needle

The substring to search for

offset

The offset where to start counting. If the offset is negative, counting starts from the end of the string.

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. A negative length counts from the end of haystack.

Valorile întoarse

This function returns an integer.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | Support for negative offsets and lengths has been added.
5.1.0 | Added the offset and the length parameters

Exemple

Example #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');
?>

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Replace text within a portion of a string

substr_count
substr
Func?ii cu ?iruri de caractere
PHP Manual

substr_replace

(PHP 4, PHP 5, PHP 7)

substr_replace — Replace text within a portion of a string

Descrierea

mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )

substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.

Parametri

string

The input string.

An array of strings can be provided, in which case the replacements will occur on each string in turn. In this case, the replacement, start and length parameters may be provided either as scalar values to be applied to each input string in turn, or as arrays, in which case the corresponding array element will be used for each input string.

replacement

The replacement string.

start

If start is positive, the replacing will begin at the start'th offset into string.

If start is negative, the replacing will begin at the start'th character from the end of string.

length

If given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string. Of course, if length is zero then this function will have the effect of inserting replacement into string at the given start offset.

Valorile întoarse

The result string is returned. If string is an array then array is returned.

Exemple

Example #1 Simple substr_replace() examples

<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<hr />\n";

/* These two examples replace all of $var with 'bob'. */
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";

/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";

/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo substr_replace($var, 'bob', -7, -1) . "<br />\n";

/* Delete 'MNRPQR' from $var. */
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>

Example #2 Using substr_replace() to replace multiple strings at once

<?php
$input = array('A: XXX', 'B: XXX', 'C: XXX');

// A simple case: replace XXX in each string with YYY.
echo implode('; ', substr_replace($input, 'YYY', 3, 3))."\n";

// A more complicated case where each replacement is different.
$replace = array('AAA', 'BBB', 'CCC');
echo implode('; ', substr_replace($input, $replace, 3, 3))."\n";

// Replace a different number of characters each time.
$length = array(1, 2, 3);
echo implode('; ', substr_replace($input, $replace, 3, $length))."\n";
?>

Exemplul de mai sus va afi?a:

A: YYY; B: YYY; C: YYY
A: AAA; B: BBB; C: CCC
A: AAAXX; B: BBBX; C: CCC

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • str_replace() - Replace all occurrences of the search string with the replacement string
  • substr() - Return part of a string
  • String access and modification by character

substr_count
substr
Func?ii cu ?iruri de caractere


Return part of a string

substr_replace
trim
Func?ii cu ?iruri de caractere
PHP Manual

substr

(PHP 4, PHP 5, PHP 7)

substr — Return part of a string

Descrierea

string substr ( string $string , int $start [, int $length ] )

Returns the portion of string specified by the start and length parameters.

Parametri

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 start characters long, FALSE will be returned.

Example #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.

Example #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"
?>

Valorile întoarse

Returns the extracted part of string; sau FALSE în cazul e?ecului, or an empty string.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | If string is equal to start characters long, an empty string will be returned. Prior to this version, FALSE was returned in this case.
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.

Exemple

Example #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

?>

Example #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;
?>

Exemplul de mai sus va afi?a în PHP 7:

1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) ''
6) ''
7) '1200'

Exemplul de mai sus va afi?a în PHP 5:

1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) false
6) false
7) '1200'

Erori/Excep?ii

Returns FALSE on error.

<?php
var_dump(substr('a', 2)); // bool(false)
?>

A se vedea ?i

  • strrchr() - Find the last occurrence of a character in a string
  • substr_replace() - Replace text within a portion of a string
  • 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() - Wraps a string to a given number of characters
  • String access and modification by character

substr_replace
trim
Func?ii cu ?iruri de caractere


Strip whitespace (or other characters) from the beginning and end of a string

substr
ucfirst
Func?ii cu ?iruri de caractere
PHP Manual

trim

(PHP 4, PHP 5, PHP 7)

trim — Strip whitespace (or other characters) from the beginning and end of a string

Descrierea

string trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] )

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.

Parametri

str

The string that will be trimmed.

character_mask

Optionally, the stripped characters can also be specified using the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Valorile întoarse

The trimmed string.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

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"

Example #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);

?>

Exemplul de mai sus va afi?a:

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"
}

Note

Nota: 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.

A se vedea ?i

  • 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
Func?ii cu ?iruri de caractere


Make a string's first character uppercase

trim
ucwords
Func?ii cu ?iruri de caractere
PHP Manual

ucfirst

(PHP 4, PHP 5, PHP 7)

ucfirst — Make a string's first character uppercase

Descrierea

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.

Parametri

str

The input string.

Valorile întoarse

Returns the resulting string.

Exemple

Example #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!
?>

A se vedea ?i

  • lcfirst() - Make a string's first character lowercase
  • strtolower() - Make a string lowercase
  • strtoupper() - Make a string uppercase
  • ucwords() - Uppercase the first character of each word in a string

trim
ucwords
Func?ii cu ?iruri de caractere


Uppercase the first character of each word in a string

ucfirst
vfprintf
Func?ii cu ?iruri de caractere
PHP Manual

ucwords

(PHP 4, PHP 5, PHP 7)

ucwords — Uppercase the first character of each word in a string

Descrierea

string ucwords ( string $str [, string $delimiters = " \t\r\n\f\v" ] )

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 any character listed in the delimiters parameter (By default these are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).

Parametri

str

The input string.

delimiters

The optional delimiters contains the word separator characters.

Valorile întoarse

Returns the modified string.

Istoricul schimbarilor

Versiune | Descriere
5.4.32, 5.5.16 | Added the delimiters parameter.

Exemple

Example #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!
?>

Example #2 ucwords() example with custom delimiter

<?php
$foo = 'hello|world!';
$bar = ucwords($foo);             // Hello|world!

$baz = ucwords($foo, "|");        // Hello|World!
?>

Note

Nota: Aceasta func?ie accepta ?i date binare.

A se vedea ?i

  • strtoupper() - Make a string uppercase
  • strtolower() - Make a string lowercase
  • ucfirst() - Make a string's first character uppercase
  • mb_convert_case() - Perform case folding on a string

ucfirst
vfprintf
Func?ii cu ?iruri de caractere


Write a formatted string to a stream

ucwords
vprintf
Func?ii cu ?iruri de caractere
PHP Manual

vfprintf

(PHP 5, PHP 7)

vfprintf — Write a formatted string to a stream

Descrierea

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.

Parametri

handle

format

See sprintf() for a description of format.

args

Valorile întoarse

Returns the length of the outputted string.

Exemple

Example #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
?>

A se vedea ?i

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • vsprintf() - Return a formatted string
  • number_format() - Format a number with grouped thousands

ucwords
vprintf
Func?ii cu ?iruri de caractere


Output a formatted string

vfprintf
vsprintf
Func?ii cu ?iruri de caractere
PHP Manual

vprintf

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

vprintf — Output a formatted string

Descrierea

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.

Parametri

format

See sprintf() for a description of format.

args

Valorile întoarse

Returns the length of the outputted string.

Exemple

Example #1 vprintf(): zero-padded integers

<?php
vprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01
?>

A se vedea ?i

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • vsprintf() - Return a formatted string

vfprintf
vsprintf
Func?ii cu ?iruri de caractere


Return a formatted string

vprintf
wordwrap
Func?ii cu ?iruri de caractere
PHP Manual

vsprintf

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

vsprintf — Return a formatted string

Descrierea

string vsprintf ( string $format , array $args )

Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.

Parametri

format

See sprintf() for a description of format.

args

Valorile întoarse

Return array values as a formatted string according to format (which is described in the documentation for sprintf()).

Exemple

Example #1 vsprintf(): zero-padded integers

<?php
print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01
?>

A se vedea ?i

  • sprintf() - Return a formatted string
  • vprintf() - Output a formatted string

vprintf
wordwrap
Func?ii cu ?iruri de caractere


Wraps a string to a given number of characters

vsprintf
Jurnalul modificarilor
Func?ii cu ?iruri de caractere
PHP Manual

wordwrap

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

wordwrap — Wraps a string to a given number of characters

Descrierea

string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )

Wraps a string to a given number of characters using a string break character.

Parametri

str

The input string.

width

The number of characters at which the string will be wrapped.

break

The line is broken using the optional break parameter.

cut

If the cut is set to TRUE, the string is always wrapped at or before the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example). When FALSE the function does not split the word even if the width is smaller than the word width.

Valorile întoarse

Returns the given string wrapped at the specified length.

Exemple

Example #1 wordwrap() example

<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");

echo $newtext;
?>

Exemplul de mai sus va afi?a:

The quick brown fox<br />
jumped over the lazy<br />
dog.

Example #2 wordwrap() example

<?php
$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "\n", true);

echo "$newtext\n";
?>

Exemplul de mai sus va afi?a:

A very
long
wooooooo
ooooord.

Example #3 wordwrap() example

<?php
$text = "A very long woooooooooooooooooord. and something";
$newtext = wordwrap($text, 8, "\n", false);

echo "$newtext\n";
?>

Exemplul de mai sus va afi?a:

A very
long
woooooooooooooooooord.
and
something

A se vedea ?i

  • nl2br() - Inserts HTML line breaks before all newlines in a string
  • chunk_split() - Split a string into smaller chunks

vsprintf
Jurnalul modificarilor
Func?ii cu ?iruri de caractere


Jurnalul modificarilor

Au fost efectuate urmatoarele modificari ale claselor/func?iilor/metodelor acestei extensii.

Version | Function | Description
7.1.0 | str_shuffle | The internal randomization algorithm has been changed to use the Mersenne Twister Random Number Generator instead of the libc rand function.
 | stripos | Support for negative offsets has been added.
 | strpos | Support for negative offsets has been added.
 | substr_count | Support for negative offsets and lengths has been added.
7.0.0 | setlocale | Support for the category parameter passed as a string has been removed. Only LC_* constants can be used as of this version.
 | substr | If string is equal to start characters long, an empty string will be returned. Prior to this version, FALSE was returned in this case.
5.6.5 | crypt | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.6 would incorrectly return a DES hash.
5.6.0 | crypt | Raise E_NOTICE security warning if salt is omitted.
 | html_entity_decode | Valoarea implicita a parametrului encoding a fost schimbata pentru a coincide cu valoarea op?iunii de configurare default_charset.
 | htmlentities | Valoarea implicita a parametrului encoding a fost schimbata pentru a coincide cu valoarea op?iunii de configurare default_charset.
 | htmlspecialchars | Valoarea implicita a parametrului encoding a fost schimbata pentru a coincide cu valoarea op?iunii de configurare default_charset.
 | substr_compare | length may now be 0.
5.5.21 | crypt | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.5 (and earlier branches) would incorrectly return a DES hash.
5.5.1 | hex2bin | A warning is thrown if the input string is invalid hexadecimal string.
5.4.32, 5.5.16 | ucwords | Added the delimiters parameter.
5.4.4 | hex2bin | A warning is thrown if the input string is of odd length. In PHP 5.4.0 the string was silently accepted, but the last byte was truncated.
5.4.0 | get_html_translation_table | The default value for the encoding parameter was changed to UTF-8.
 | get_html_translation_table | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | html_entity_decode | Default encoding changed from ISO-8859-1 to UTF-8.
 | html_entity_decode | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | htmlentities | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | htmlentities | The default value for the encoding parameter was changed to UTF-8.
 | htmlspecialchars | The default value for the encoding parameter was changed to UTF-8.
 | htmlspecialchars | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | htmlspecialchars_decode | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | number_format | This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions.
5.3.7 | crypt | Added $2x$ and $2y$ Blowfish modes to deal with potential high-bit attacks.
5.3.4 | get_html_translation_table | The encoding parameter was added.
 | strip_tags | strip_tags ignores self-closing XHTML tags in allowable_tags.
5.3.2 | crypt | Added SHA-256 and SHA-512 crypt based on Ulrich Drepper's implementation.
 | crypt | Fixed Blowfish behaviour on invalid rounds to return "failure" string ("*0" or "*1"), instead of falling back to DES.
5.3.0 | crypt | 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.
 | htmlentities | The constant ENT_IGNORE was added.
 | htmlspecialchars | The constant ENT_IGNORE was added.
 | nl2br | Added the optional is_xhtml parameter. Before this version '<br />' was always inserted.
 | setlocale | This function now throws an E_DEPRECATED notice if a string is passed to the category parameter instead of one of the LC_* constants.
 | stristr | Added the optional parameter before_needle.
 | strlen | Prior versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error.
 | strstr | Added the optional parameter before_needle.
5.2.5 | addcslashes | The escape sequences \v and \f were added.
5.2.3 | htmlentities | The double_encode parameter was added.
 | htmlspecialchars | The double_encode parameter was added.
5.2.2 - 5.2.6 | substr | If the start parameter indicates the position of a negative truncation or beyond, false is returned. Other versions get the string from start.
5.1.0 | explode | Support for negative limits was added
 | md5_file | Changed the function to use the streams API. It means that you can use it with wrappers, like md5_file('http://example.com/..')
 | sha1_file | Changed the function to use the streams API. It means that you can use it with wrappers, like sha1_file('http://example.com/..')
 | str_word_count | Added the charlist parameter
 | substr_compare | Added the possibility to use a negative offset.
 | substr_count | Added the offset and the length parameters
5.0.0 | strip_tags | strip_tags is now binary safe.
 | strrpos | The needle may now be a string of more than one character.
4.3.0 | stristr | stristr was made binary safe.
 | strrchr | This function is now binary safe.
 | strstr | strstr was made binary safe.
4.2.3 | strcoll | This function now works on win32.
wordwrap
Extensii referitoare la variabile ?i tipuri
Strings


Extensii referitoare la variabile ?i tipuri

  • Arrays
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Sorting Arrays
    • Func?ii ale tablourilor (Array)
  • Classes/Objects — Class/Object Information
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii ale claselor/obiectelor
  • Classkit
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Classkit
  • Ctype — Character type checking
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii Ctype
  • Data Structures
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Collection — The Collection interface
    • Hashable — The Hashable interface
    • Sequence — The Sequence interface
    • Vector — The Vector class
    • Deque — The Deque class
    • Map — The Map class
    • Pair — The Pair class
    • Set — The Set class
    • Stack — The Stack class
    • Queue — The Queue class
    • PriorityQueue — The PriorityQueue class
  • Filter — Data Filtering
    • Introducere
    • Instalarea / configurarea
    • Types of filters
    • Constante predefinite
    • Exemple
    • Func?ii de filtrare
  • Manipularea func?iilor
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii de manipulare a func?iilor
  • Quickhash
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • QuickHashIntSet — The QuickHashIntSet class
    • QuickHashIntHash — The QuickHashIntHash class
    • QuickHashStringIntHash — The QuickHashStringIntHash class
    • QuickHashIntStringHash — The QuickHashIntStringHash class
  • Reflection
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • 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
    • ReflectionType — The ReflectionType class
    • ReflectionGenerator — The ReflectionGenerator class
    • Reflector — The Reflector interface
    • ReflectionException — The ReflectionException class
  • Manipularea variabilelor
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii de gestionare a variabilelor
Jurnalul modificarilor
Arrays
Informa?ii de referin?a despre func?ii


Arrays

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Sorting Arrays
  • Func?ii ale tablourilor (Array)
    • array_change_key_case — Modifica caracterele (minuscule/majuscule) tuturor cheilor unui tablou
    • array_chunk — Desparte un tablou în por?iuni
    • array_column — Return the values from a single column in the input array
    • array_combine — Creates an array by using one array for keys and another for its values
    • array_count_values — Numara toate valorile unui tablou
    • array_diff_assoc — Computes the difference of arrays with additional index check
    • array_diff_key — Computes the difference of arrays using keys for comparison
    • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
    • array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
    • array_diff — Calculeaza diferen?a dintre tablouri
    • array_fill_keys — Fill an array with values, specifying keys
    • array_fill — Completeaza un tablou cu valori
    • array_filter — Filtreaza elementele unui tablou utilizând o func?ie de apel invers
    • array_flip — Exchanges all keys with their associated values in an array
    • array_intersect_assoc — Computes the intersection of arrays with additional index check
    • 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 — Computes the intersection of arrays
    • array_key_exists — Checks if the given key or index exists in the array
    • array_keys — Return all the keys or a subset of the keys of an array
    • array_map — Applies the callback to the elements of the given arrays
    • array_merge_recursive — Merge two or more arrays recursively
    • array_merge — Merge one or more arrays
    • array_multisort — Sort multiple or multi-dimensional arrays
    • array_pad — Pad array to the specified length with a value
    • array_pop — Pop the element off the end of array
    • array_product — Calculate the product of values in an array
    • array_push — Push one or more elements onto the end of array
    • array_rand — Pick one or more random entries out of an array
    • array_reduce — Iteratively reduce the array to a single value using a callback function
    • 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 — Return an array with elements in reverse order
    • array_search — Searches the array for a given value and returns the first corresponding key if successful
    • array_shift — Shift an element off the beginning of array
    • array_slice — Extract a slice of the array
    • array_splice — Remove a portion of the array and replace it with something else
    • array_sum — Calculate the sum of values in an array
    • 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 — Computes the intersection of arrays with additional index check, compares data by a callback function
    • array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
    • array_uintersect — Computes the intersection of arrays, compares data by a callback function
    • array_unique — Removes duplicate values from an array
    • array_unshift — Prepend one or more elements to the beginning of an array
    • array_values — Return all the values of an array
    • array_walk_recursive — Apply a user function recursively to every member of an array
    • array_walk — Apply a user supplied function to every member of an array
    • array — Creeaza un tablou
    • arsort — Sort an array in reverse order and maintain index association
    • asort — Sort an array and maintain index association
    • compact — Create array containing variables and their values
    • count — Count all elements in an array, or something in an object
    • current — Return the current element in an array
    • each — Return the current key and value pair from an array and advance the array cursor
    • end — Set the internal pointer of an array to its last element
    • extract — Import variables into the current symbol table from an array
    • in_array — Checks if a value exists in an array
    • key_exists — Pseudonim pentru array_key_exists
    • key — Fetch a key from an array
    • krsort — Sort an array by key in reverse order
    • ksort — Sort an array by key
    • list — Assign variables as if they were an array
    • natcasesort — Sort an array using a case insensitive "natural order" algorithm
    • natsort — Sort an array using a "natural order" algorithm
    • next — Advance the internal array pointer of an array
    • pos — Pseudonim pentru current
    • prev — Rewind the internal array pointer
    • range — Create an array containing a range of elements
    • reset — Set the internal pointer of an array to its first element
    • rsort — Sort an array in reverse order
    • shuffle — Shuffle an array
    • sizeof — Pseudonim pentru count
    • sort — Sort an array
    • uasort — Sort an array with a user-defined comparison function and maintain index association
    • uksort — Sort an array by keys using a user-defined comparison function
    • usort — Sort an array by values using a user-defined comparison function
Extensii referitoare la variabile ?i tipuri
Introducere
Extensii referitoare la variabile ?i tipuri


Introducere

These functions allow you to interact with and manipulate arrays in various ways. Arrays are essential for storing, managing, and operating on sets of variables.

Simple and multi-dimensional arrays are supported, and may be either user created or created by another function. There are specific database handling functions for populating arrays from database queries, and several functions return arrays.

Please see the Arrays section of the manual for a detailed explanation of how arrays are implemented and used in PHP. See also Array operators for other ways how to manipulate the arrays.

Arrays
Instalarea / configurarea
Arrays


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Arrays


Constante predefinite

Constantele de mai jos sunt întotdeauna disponibile ca parte componenta a nucleului PHP.

CASE_LOWER (integer)
CASE_LOWER is used with array_change_key_case() and is used to convert array keys to lower case. This is also the default case for array_change_key_case().
CASE_UPPER (integer)
CASE_UPPER is used with array_change_key_case() and is used to convert array keys to upper case.

Sorting order flags:

SORT_ASC (integer)
SORT_ASC is used with array_multisort() to sort in ascending order.
SORT_DESC (integer)
SORT_DESC is used with array_multisort() to sort in descending order.

Sorting type flags: used by various sort functions

SORT_REGULAR (integer)
SORT_REGULAR is used to compare items normally.
SORT_NUMERIC (integer)
SORT_NUMERIC is used to compare items numerically.
SORT_STRING (integer)
SORT_STRING is used to compare items as strings.
SORT_LOCALE_STRING (integer)
SORT_LOCALE_STRING is used to compare items as strings, based on the current locale. Added in PHP 5.0.2.
SORT_NATURAL (integer)
SORT_NATURAL is used to compare items as strings using "natural ordering" like natsort(). Added in PHP 5.4.0.
SORT_FLAG_CASE (integer)
SORT_FLAG_CASE can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively. Added in PHP 5.4.0.

Filter flags:

ARRAY_FILTER_USE_KEY (integer)
ARRAY_FILTER_USE_KEY is used with array_filter() to pass each key as the first argument to the given callback function. Added in PHP 5.6.0.
ARRAY_FILTER_USE_BOTH (integer)
ARRAY_FILTER_USE_BOTH is used with array_filter() to pass both value and key to the given callback function. Added in PHP 5.6.0.

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)
Tipurile resurselor
Sorting Arrays
Arrays


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()

Constante predefinite
Func?ii ale tablourilor (Array)
Arrays


Func?ii ale tablourilor (Array)

A se vedea ?i

Accesa?i de asemenea is_array(),
explode(), implode(),
split(), preg_split() ?i
unset().

Cuprins

  • array_change_key_case — Modifica caracterele (minuscule/majuscule) tuturor cheilor unui tablou
  • array_chunk — Desparte un tablou în por?iuni
  • array_column — Return the values from a single column in the input array
  • array_combine — Creates an array by using one array for keys and another for its values
  • array_count_values — Numara toate valorile unui tablou
  • array_diff_assoc — Computes the difference of arrays with additional index check
  • array_diff_key — Computes the difference of arrays using keys for comparison
  • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
  • array_diff — Calculeaza diferen?a dintre tablouri
  • array_fill_keys — Fill an array with values, specifying keys
  • array_fill — Completeaza un tablou cu valori
  • array_filter — Filtreaza elementele unui tablou utilizând o func?ie de apel invers
  • array_flip — Exchanges all keys with their associated values in an array
  • array_intersect_assoc — Computes the intersection of arrays with additional index check
  • 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 — Computes the intersection of arrays
  • array_key_exists — Checks if the given key or index exists in the array
  • array_keys — Return all the keys or a subset of the keys of an array
  • array_map — Applies the callback to the elements of the given arrays
  • array_merge_recursive — Merge two or more arrays recursively
  • array_merge — Merge one or more arrays
  • array_multisort — Sort multiple or multi-dimensional arrays
  • array_pad — Pad array to the specified length with a value
  • array_pop — Pop the element off the end of array
  • array_product — Calculate the product of values in an array
  • array_push — Push one or more elements onto the end of array
  • array_rand — Pick one or more random entries out of an array
  • array_reduce — Iteratively reduce the array to a single value using a callback function
  • 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 — Return an array with elements in reverse order
  • array_search — Searches the array for a given value and returns the first corresponding key if successful
  • array_shift — Shift an element off the beginning of array
  • array_slice — Extract a slice of the array
  • array_splice — Remove a portion of the array and replace it with something else
  • array_sum — Calculate the sum of values in an array
  • 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 — Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
  • array_uintersect — Computes the intersection of arrays, compares data by a callback function
  • array_unique — Removes duplicate values from an array
  • array_unshift — Prepend one or more elements to the beginning of an array
  • array_values — Return all the values of an array
  • array_walk_recursive — Apply a user function recursively to every member of an array
  • array_walk — Apply a user supplied function to every member of an array
  • array — Creeaza un tablou
  • arsort — Sort an array in reverse order and maintain index association
  • asort — Sort an array and maintain index association
  • compact — Create array containing variables and their values
  • count — Count all elements in an array, or something in an object
  • current — Return the current element in an array
  • each — Return the current key and value pair from an array and advance the array cursor
  • end — Set the internal pointer of an array to its last element
  • extract — Import variables into the current symbol table from an array
  • in_array — Checks if a value exists in an array
  • key_exists — Pseudonim pentru array_key_exists
  • key — Fetch a key from an array
  • krsort — Sort an array by key in reverse order
  • ksort — Sort an array by key
  • list — Assign variables as if they were an array
  • natcasesort — Sort an array using a case insensitive "natural order" algorithm
  • natsort — Sort an array using a "natural order" algorithm
  • next — Advance the internal array pointer of an array
  • pos — Pseudonim pentru current
  • prev — Rewind the internal array pointer
  • range — Create an array containing a range of elements
  • reset — Set the internal pointer of an array to its first element
  • rsort — Sort an array in reverse order
  • shuffle — Shuffle an array
  • sizeof — Pseudonim pentru count
  • sort — Sort an array
  • uasort — Sort an array with a user-defined comparison function and maintain index association
  • uksort — Sort an array by keys using a user-defined comparison function
  • usort — Sort an array by values using a user-defined comparison function
Sorting Arrays
array_change_key_case
Arrays


Modifica caracterele (minuscule/majuscule) tuturor cheilor unui tablou

Func?ii ale tablourilor (Array)
array_chunk
Func?ii ale tablourilor (Array)
PHP Manual

array_change_key_case

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

array_change_key_case — Modifica caracterele (minuscule/majuscule) tuturor cheilor unui tablou

Descrierea

array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )

Întoarce un tablou cu toate cheile din array transferate în caractere minuscule sau majuscule. Indicii-numere ramân precum sunt.

Parametri

array

Tabloul asupra caruia se lucreaza

case

Poate lua valoarea CASE_UPPER sau CASE_LOWER (implicit)

Valorile întoarse

Întoarce un tablou cu cheile transferate în caractere minuscule sau majuscule, sau FALSE daca array nu este un tablou.

Erori/Excep?ii

Arunca E_WARNING daca array nu este un tablou.

Exemple

Example #1 Exemplu array_change_key_case()

<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>

Exemplul de mai sus va afi?a:

Array
(
    [FIRST] => 1
    [SECOND] => 4
)

Note

Nota:

Daca un tablou are indici care vor deveni la fel odata ce se va rula aceasta func?ie (de ex. "keY" ?i "kEY"), valoarea cea mai de pe urma din tablou se va suprapune peste ceilal?i indici.

Func?ii ale tablourilor (Array)
array_chunk
Func?ii ale tablourilor (Array)


Desparte un tablou în por?iuni

array_change_key_case
array_column
Func?ii ale tablourilor (Array)
PHP Manual

array_chunk

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

array_chunk — Desparte un tablou în por?iuni

Descrierea

array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )

Desparte un tablou în por?iuni de dimensiunea size. Ultima por?iune poate sa con?ina mai pu?ine elemente decât size.

Parametri

array

Tabloul cu care se lucreaza

size

Dimensiunea fiecarei por?iuni

preserve_keys

Când este stabilit în TRUE cheile vor fi pastrate. Implicit sete FALSE, ceea ce va reindexa numeric por?iunea

Valorile întoarse

Întoarce un tablou multidimensional indexat numeric, începând cu zero, fiecare dimensiune con?inând size elemente.

Erori/Excep?ii

Daca size este mai mic decât 1 va fi emisa o eroare E_WARNING ?i se va întoarce NULL.

Exemple

Example #1 Exemplu array_chunk()

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>

Exemplul de mai sus va afi?a:

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
        )

)

A se vedea ?i

  • array_slice() - Extract a slice of the array

array_change_key_case
array_column
Func?ii ale tablourilor (Array)


Return the values from a single column in the input array

array_chunk
array_combine
Func?ii ale tablourilor (Array)
PHP Manual

array_column

(PHP 5 >= 5.5.0, PHP 7)

array_column — Return the values from a single column in the input array

Descrierea

array array_column ( array $input , mixed $column_key [, mixed $index_key = null ] )

array_column() returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.

Parametri

input

A multi-dimensional array or an array of objects from which to pull a column of values from. If an array of objects is provided, then public properties can be directly pulled. In order for protected or private properties to be pulled, the class must implement both the __get() and __isset() magic methods.

column_key

The column of values to return. This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an associative array or property name. It may also be NULL to return complete arrays or objects (this is useful together with index_key to reindex the array).

index_key

The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name.

Valorile întoarse

Returns an array of values representing a single column from the input array.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | Added the ability for the input parameter to be an array of objects.

Exemple

Example #1 Get the column of first names from a recordset

<?php
// Array representing a possible record set returned from a database
$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);

$first_names = array_column($records, 'first_name');
print_r($first_names);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)

Example #2 Get the column of last names from a recordset, indexed by the "id" column

<?php
// Using the $records array from Example #1
$last_names = array_column($records, 'last_name', 'id');
print_r($last_names);
?>

Exemplul de mai sus va afi?a:

Array
(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)

Example #3 Get the column of usernames from the public "username" property of an object

<?php

class User
{
    public $username;

    public function __construct(string $username)
    {
        $this->username = $username;
    }
}

$users = [
    new User('user 1'),
    new User('user 2'),
    new User('user 3'),
];

print_r(array_column($users, 'username'));
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => user 1
    [1] => user 2
    [2] => user 3
)

Example #4 Get the column of names from the private "name" property of an object using the magic __get() method.

<?php

class Person
{
    private $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function __get($prop)
    {
        return $this->$prop;
    }

    public function __isset($prop) : bool
    {
        return isset($this->$prop);
    }
}

$people = [
    new Person('Fred'),
    new Person('Jane'),
    new Person('John'),
];

print_r(array_column($people, 'name'));
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => Fred
    [1] => Jane
    [2] => John
)
If __isset() is not provided, then an empty array will be returned.

A se vedea ?i

  • » Recommended userland implementation for PHP lower than 5.5

array_chunk
array_combine
Func?ii ale tablourilor (Array)


Creates an array by using one array for keys and another for its values

array_column
array_count_values
Func?ii ale tablourilor (Array)
PHP Manual

array_combine

(PHP 5, PHP 7)

array_combine — Creates an array by using one array for keys and another for its values

Descrierea

array array_combine ( array $keys , array $values )

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

Parametri

keys

Array of keys to be used. Illegal values for key will be converted to string.

values

Array of values to be used

Valorile întoarse

Returns the combined array, FALSE if the number of elements for each array isn't equal.

Erori/Excep?ii

Throws E_WARNING if the number of elements in keys and values does not match.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Previous versions issued E_WARNING and returned FALSE for empty arrays.

Exemple

Example #1 A simple array_combine() example

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

Exemplul de mai sus va afi?a:

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

A se vedea ?i

  • array_merge() - Merge one or more arrays
  • array_walk() - Apply a user supplied function to every member of an array
  • array_values() - Return all the values of an array

array_column
array_count_values
Func?ii ale tablourilor (Array)


Numara toate valorile unui tablou

array_combine
array_diff_assoc
Func?ii ale tablourilor (Array)
PHP Manual

array_count_values

(PHP 4, PHP 5, PHP 7)

array_count_values — Numara toate valorile unui tablou

Descrierea

array array_count_values ( array $array )

array_count_values() întoarce un tablou utilizând valorile tabloului array în calitate de chei ?i frecven?a apari?iei lor în array în calitate de valori.

Parametri

array

Tabloul valorilor ce vor fi numarate

Valorile întoarse

Întoarce un tablou asociativ de valori din array în calitate de chei ?i numarul lor în calitate de valori.

Erori/Excep?ii

Produce un E_WARNING pentru fiecare element care nu este string sau integer.

Exemple

Example #1 Exemplu array_count_values()

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

Exemplul de mai sus va afi?a:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

A se vedea ?i

  • count() - Count all elements in an array, or something in an object
  • array_unique() - Removes duplicate values from an array
  • array_values() - Return all the values of an array
  • count_chars() - Return information about characters used in a string

array_combine
array_diff_assoc
Func?ii ale tablourilor (Array)


Computes the difference of arrays with additional index check

array_count_values
array_diff_key
Func?ii ale tablourilor (Array)
PHP Manual

array_diff_assoc

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

array_diff_assoc — Computes the difference of arrays with additional index check

Descrierea

array array_diff_assoc ( array $array1 , array $array2 [, array $... ] )

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are also used in the comparison.

Parametri

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

Valorile întoarse

Returns an array containing all the values from array1 that are not present in any of the other arrays.

Exemple

Example #1 array_diff_assoc() example

In this example you see the "a" => "green" pair is present in both arrays and thus it is not in the output from the function. Unlike this, the pair 0 => "red" is in the output because in the second argument "red" has key which is 1.

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

Exemplul de mai sus va afi?a:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

Example #2 array_diff_assoc() example

Two values from key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict check takes place so the string representations must be the same.

<?php
$array1 = array(0, 1, 2);
$array2 = array("00", "01", "2");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => 0
    [1] => 1
    )

Note

Nota: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_assoc($array1[0], $array2[0]);.

Nota: Ensure you pass arguments in the correct order when comparing similar arrays with more keys. The new array should be the first in the list.

A se vedea ?i

  • array_diff() - Calculeaza diferen?a dintre tablouri
  • 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() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check

array_count_values
array_diff_key
Func?ii ale tablourilor (Array)


Computes the difference of arrays using keys for comparison

array_diff_assoc
array_diff_uassoc
Func?ii ale tablourilor (Array)
PHP Manual

array_diff_key

(PHP 5 >= 5.1.0, PHP 7)

array_diff_key — Computes the difference of arrays using keys for comparison

Descrierea

array array_diff_key ( array $array1 , array $array2 [, array $... ] )

Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.

Parametri

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

Valorile întoarse

Returns an array containing all the entries from array1 whose keys are not present in any of the other arrays.

Exemple

Example #1 array_diff_key() example

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.

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_key($array1, $array2));
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

Note

Nota:

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_key($array1[0], $array2[0]);.

A se vedea ?i

  • array_diff() - Calculeaza diferen?a dintre tablouri
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • 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_ukey() - Computes the difference of arrays using a callback function on the keys for comparison
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • 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_ukey() - Computes the intersection of arrays using a callback function on the keys for comparison

array_diff_assoc
array_diff_uassoc
Func?ii ale tablourilor (Array)


Computes the difference of arrays with additional index check which is performed by a user supplied callback function

array_diff_key
array_diff_ukey
Func?ii ale tablourilor (Array)
PHP Manual

array_diff_uassoc

(PHP 5, PHP 7)

array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function

Descrierea

array array_diff_uassoc ( array $array1 , array $array2 [, array $... ], callable $key_compare_func )

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the comparison.

Unlike array_diff_assoc() a user supplied callback function is used for the indices comparison, not internal function.

Parametri

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

key_compare_func

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )

Valorile întoarse

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Exemple

Example #1 array_diff_uassoc() example

The "a" => "green" pair is present in both arrays and thus it is not in the output from the function. Unlike this, the pair 0 => "red" is in the output because in the second argument "red" has key which is 1.

<?php
function key_compare_func($a, $b)
{
    if ($a === $b) {
        return 0;
    }
    return ($a > $b)? 1:-1;
}

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);
?>

Exemplul de mai sus va afi?a:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

The equality of 2 indices is checked by the user supplied callback function.

Note

Nota:

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_uassoc($array1[0], $array2[0], "key_compare_func");.

A se vedea ?i

  • array_diff() - Calculeaza diferen?a dintre tablouri
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • 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_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions

array_diff_key
array_diff_ukey
Func?ii ale tablourilor (Array)


Computes the difference of arrays using a callback function on the keys for comparison

array_diff_uassoc
array_diff
Func?ii ale tablourilor (Array)
PHP Manual

array_diff_ukey

(PHP 5 >= 5.1.0, PHP 7)

array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison

Descrierea

array array_diff_ukey ( array $array1 , array $array2 [, array $... ], callable $key_compare_func )

Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.

Unlike array_diff_key() a user supplied callback function is used for the indices comparison, not internal function.

Parametri

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

key_compare_func

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )

Valorile întoarse

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Exemple

Example #1 array_diff_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_diff_ukey($array1, $array2, 'key_compare_func'));
?>

Exemplul de mai sus va afi?a:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

Note

Nota:

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_ukey($array1[0], $array2[0], 'callback_func');.

A se vedea ?i

  • array_diff() - Calculeaza diferen?a dintre tablouri
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • 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() - Computes the difference of arrays using keys for comparison
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • 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_ukey() - Computes the intersection of arrays using a callback function on the keys for comparison

array_diff_uassoc
array_diff
Func?ii ale tablourilor (Array)


Calculeaza diferen?a dintre tablouri

array_diff_ukey
array_fill_keys
Func?ii ale tablourilor (Array)
PHP Manual

array_diff

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

array_diff — Calculeaza diferen?a dintre tablouri

Descrierea

array array_diff ( array $array1 , array $array2 [, array $... ] )

Compara array1 cu unul sau mai multe tablouri ?i întoarce valorile din array1 care nu sunt prezente în celelalte tablouri.

Parametri

array1

Tabloul de referin?a

array2

Tabloul care se compara

...

Mai multe tablouri pentru a se compara

Valorile întoarse

Întoarce un array ce con?ine toate înregistrarile din array1 care nu sunt prezente nici în unul din celelalte tablouri.

Exemple

Example #1 Exemplu array_diff()

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Apari?iile multiple în $array1 sunt toate tratate în acela?i mod. Aceasta va afi?a :

Array
(
    [1] => blue
)

Note

Nota:

Doua elemente sunt considerate egale daca ?i numai daca (string) $elem1 === (string) $elem2. În cuvinte: daca reprezentarea lor ca ?iruri de caractere este aceea?i.

Nota:

Aceasta func?ie verifica numai o dimensiune a unui tablou n-dimensional. Desigur ca pute?i sa verifica?i dimensiunile mai adânci utilizând array_diff($array1[0], $array2[0]);.

A se vedea ?i

  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check

array_diff_ukey
array_fill_keys
Func?ii ale tablourilor (Array)


Fill an array with values, specifying keys

array_diff
array_fill
Func?ii ale tablourilor (Array)
PHP Manual

array_fill_keys

(PHP 5 >= 5.2.0, PHP 7)

array_fill_keys — Fill an array with values, specifying keys

Descrierea

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.

Parametri

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

Valorile întoarse

Returns the filled array

Exemple

Example #1 array_fill_keys() example

<?php
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);
?>

Exemplul de mai sus va afi?a:

Array
(
    [foo] => banana
    [5] => banana
    [10] => banana
    [bar] => banana
)

A se vedea ?i

  • array_fill() - Completeaza un tablou cu valori
  • array_combine() - Creates an array by using one array for keys and another for its values

array_diff
array_fill
Func?ii ale tablourilor (Array)


Completeaza un tablou cu valori

array_fill_keys
array_filter
Func?ii ale tablourilor (Array)
PHP Manual

array_fill

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

array_fill — Completeaza un tablou cu valori

Descrierea

array array_fill ( int $start_index , int $num , mixed $value )

Completeaza un tablou cu num înregistrari cu valoarea parametrului value, cheile începând de la valoarea parametrului start_index.

Parametri

start_index

Primul indice al tabloului întors.

Daca start_index este negativ, primul indice al tabloului întors va fi start_index ?i urmatorii indici vor începe de la zero (vede?i exemplul).

num

Numarul elementelor pentru a fi inserate. Trebuie sa fie mai mare decât sau egal cu zero.

value

Valoarea utilizata pentru a completa tabloul

Valorile întoarse

Întoarce tabloul completat

Erori/Excep?ii

Emite o E_WARNING daca num este mai mic decât zero.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | num nu poate fi zero. Anterior num trebuia sa fie mai mare decât zero.

Exemple

Example #1 Exemplu array_fill()

<?php
$a = array_fill(5, 6, 'banana');
$b = array_fill(-2, 4, 'pear');
print_r($a);
print_r($b);
?>

Exemplul de mai sus va afi?a:

Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)
Array
(
    [-2] => pear
    [0] => pear
    [1] => pear
    [2] => pear
)

Note

Accesa?i de asemenea sec?iunea manualului referitoare la Tablouri pentru o explica?ie detaliata a cheilor negative.

A se vedea ?i

  • array_fill_keys() - Fill an array with values, specifying keys
  • str_repeat() - Repeat a string
  • range() - Create an array containing a range of elements

array_fill_keys
array_filter
Func?ii ale tablourilor (Array)


Filtreaza elementele unui tablou utilizând o func?ie de apel invers

array_fill
array_flip
Func?ii ale tablourilor (Array)
PHP Manual

array_filter

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

array_filter — Filtreaza elementele unui tablou utilizând o func?ie de apel invers

Descrierea

array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )

Itereaza prin fiecare valoare în tabloul array transmi?ând-o func?iei callback. Daca func?ia callback întoarce true, valoarea curenta din array este întoarsa în tabloul rezultant. Cheile tabloului sunt pastrate.

Parametri

array

Tabloul în care se itereaza

callback

Func?ia de apel invers utilizata

Daca nu este furnizata nici o func?ie callback, toate înregistrarile din array egale cu FALSE (vede?i convertarea în boolean) vor fi eliminate.

flag

Fanionul ce determina ce argumente sunt transmise catre callback:

  • ARRAY_FILTER_USE_KEY - transmite cheia ca unic argument pentru callback în loc de valoare
  • ARRAY_FILTER_USE_BOTH - transmite ambele - valoarea ?i cheia - ca argumente pentru callback, ?i nu doar valoarea

Valorile întoarse

Întoarce tabloul filtrat.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | A fost adaugat parametrul op?ional flag ?i constantele ARRAY_FILTER_USE_KEY ?i ARRAY_FILTER_USE_BOTH

Exemple

Example #1 Exemplu array_filter()

<?php
function odd($var)
{
    // întoarce true daca numarul întreg transmis este impar
    return($var & 1);
}

function even($var)
{
    // întoarce true daca numarul întreg transmis este par
    return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?>

Exemplul de mai sus va afi?a:

Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Even:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

Example #2 array_filter() fara callback

<?php

$entry = array(
             0 => 'foo',
             1 => false,
             2 => -1,
             3 => null,
             4 => ''
          );

print_r(array_filter($entry));
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => foo
    [2] => -1
)

Example #3 array_filter() cu flag

<?php

$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];

var_dump(array_filter($arr, function($k) {
    return $k == 'b';
}, ARRAY_FILTER_USE_KEY));

var_dump(array_filter($arr, function($v, $k) {
    return $k == 'b' || $v == 4;
}, ARRAY_FILTER_USE_BOTH));
?>

Exemplul de mai sus va afi?a:

array(1) {
  ["b"]=>
  int(2)
}
array(2) {
  ["b"]=>
  int(2)
  ["d"]=>
  int(4)
}

Note

Precautie

Daca tabloul este modificat în func?ia de apel invers (de ex. un element este adaugat, eliminat sau desetat) comportamentul acestei func?ii este nedefinit.

A se vedea ?i

  • array_map() - Applies the callback to the elements of the given arrays
  • array_reduce() - Iteratively reduce the array to a single value using a callback function
  • array_walk() - Apply a user supplied function to every member of an array

array_fill
array_flip
Func?ii ale tablourilor (Array)


Exchanges all keys with their associated values in an array

array_filter
array_intersect_assoc
Func?ii ale tablourilor (Array)
PHP Manual

array_flip

(PHP 4, PHP 5, PHP 7)

array_flip — Exchanges all keys with their associated values in an array

Descrierea

array array_flip ( array $array )

array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys.

Note that the values of array need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be included in the result.

If a value has several occurrences, the latest key will be used as its value, and all others will be lost.

Parametri

array

An array of key/value pairs to be flipped.

Valorile întoarse

Returns the flipped array on success and NULL on failure.

Exemple

Example #1 array_flip() example

<?php
$input = array("oranges", "apples", "pears");
$flipped = array_flip($input);

print_r($flipped);
?>

Exemplul de mai sus va afi?a:

Array
(
    [oranges] => 0
    [apples] => 1
    [pears] => 2
)

Example #2 array_flip() example : collision

<?php
$input = array("a" => 1, "b" => 1, "c" => 2);
$flipped = array_flip($input);

print_r($flipped);
?>

Exemplul de mai sus va afi?a:

Array
(
    [1] => b
    [2] => c
)

A se vedea ?i

  • array_values() - Return all the values of an array
  • array_keys() - Return all the keys or a subset of the keys of an array
  • array_reverse() - Return an array with elements in reverse order

array_filter
array_intersect_assoc
Func?ii ale tablourilor (Array)


Computes the intersection of arrays with additional index check

array_flip
array_intersect_key
Func?ii ale tablourilor (Array)
PHP Manual

array_intersect_assoc

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

array_intersect_assoc — Computes the intersection of arrays with additional index check

Descrierea

array array_intersect_assoc ( array $array1 , array $array2 [, array $... ] )

array_intersect_assoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are also used in the comparison unlike in array_intersect().

Parametri

array1

The array with master values to check.

array2

An array to compare values against.

...

A variable list of arrays to compare.

Valorile întoarse

Returns an associative array containing all the values in array1 that are present in all of the arguments.

Exemple

Example #1 array_intersect_assoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "b" => "yellow", "blue", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
?>

Exemplul de mai sus va afi?a:

Array
(
    [a] => green
)

In our example you see that only the pair "a" => "green" is present in both arrays and thus is returned. The value "red" is not returned because in $array1 its key is 0 while the key of "red" in $array2 is 1, and the key "b" is not returned because its values are different in each array.

The two values from the key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict type check is executed so the string representation must be the same.

A se vedea ?i

  • array_intersect() - Computes the intersection of arrays
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
  • array_diff() - Calculeaza diferen?a dintre tablouri
  • array_diff_assoc() - Computes the difference of arrays with additional index check
array_flip
array_intersect_key
Func?ii ale tablourilor (Array)


Computes the intersection of arrays using keys for comparison

array_intersect_assoc
array_intersect_uassoc
Func?ii ale tablourilor (Array)
PHP Manual

array_intersect_key

(PHP 5 >= 5.1.0, PHP 7)

array_intersect_key — Computes the intersection of arrays using keys for comparison

Descrierea

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.

Parametri

array1

The array with master keys to check.

array2

An array to compare keys against.

...

A variable list of arrays to compare.

Valorile întoarse

Returns an associative array containing all the entries of array1 which have keys that are present in all arguments.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • array_diff() - Calculeaza diferen?a dintre tablouri
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • 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() - Computes the difference of arrays using keys for comparison
  • array_diff_ukey() - Computes the difference of arrays using a callback function on the keys for comparison
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • 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
Func?ii ale tablourilor (Array)


Computes the intersection of arrays with additional index check, compares indexes by a callback function

array_intersect_key
array_intersect_ukey
Func?ii ale tablourilor (Array)
PHP Manual

array_intersect_uassoc

(PHP 5, PHP 7)

array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function

Descrierea

array array_intersect_uassoc ( array $array1 , array $array2 [, array $... ], callable $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().

Parametri

array1

Initial array for comparison of the arrays.

array2

First array to compare keys against.

...

Variable list of array arguments to compare values against.

key_compare_func

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )

Valorile întoarse

Returns the values of array1 whose values exist in all of the arguments.

Exemple

Example #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"));
?>

Exemplul de mai sus va afi?a:

Array
(
    [b] => brown
)

A se vedea ?i

  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate 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
Func?ii ale tablourilor (Array)


Computes the intersection of arrays using a callback function on the keys for comparison

array_intersect_uassoc
array_intersect
Func?ii ale tablourilor (Array)
PHP Manual

array_intersect_ukey

(PHP 5 >= 5.1.0, PHP 7)

array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison

Descrierea

array array_intersect_ukey ( array $array1 , array $array2 [, array $... ], callable $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.

Parametri

array1

Initial array for comparison of the arrays.

array2

First array to compare keys against.

...

Variable list of array arguments to compare keys against.

key_compare_func

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )

Valorile întoarse

Returns the values of array1 whose keys exist in all the arguments.

Exemple

Example #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'));
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • array_diff() - Calculeaza diferen?a dintre tablouri
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • 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() - Computes the difference of arrays using keys for comparison
  • array_diff_ukey() - Computes the difference of arrays using a callback function on the keys for comparison
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • 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
Func?ii ale tablourilor (Array)


Computes the intersection of arrays

array_intersect_ukey
array_key_exists
Func?ii ale tablourilor (Array)
PHP Manual

array_intersect

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

array_intersect — Computes the intersection of arrays

Descrierea

array array_intersect ( array $array1 , array $array2 [, array $... ] )

array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.

Parametri

array1

The array with master values to check.

array2

An array to compare values against.

...

A variable list of arrays to compare.

Valorile întoarse

Returns an array containing all of the values in array1 whose values exist in all of the parameters.

Exemple

Example #1 array_intersect() example

<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>

Exemplul de mai sus va afi?a:

Array
(
    [a] => green
    [0] => red
)

Note

Nota: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

A se vedea ?i

  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_diff() - Calculeaza diferen?a dintre tablouri
  • array_diff_assoc() - Computes the difference of arrays with additional index check

array_intersect_ukey
array_key_exists
Func?ii ale tablourilor (Array)


Checks if the given key or index exists in the array

array_intersect
array_keys
Func?ii ale tablourilor (Array)
PHP Manual

array_key_exists

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

array_key_exists — Checks if the given key or index exists in the array

Descrierea

bool array_key_exists ( mixed $key , array $array )

array_key_exists() returns TRUE if the given key is set in the array. key can be any value possible for an array index.

Parametri

key

Value to check.

array

An array with keys to check.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Nota:

array_key_exists() will search for the keys in the first dimension only. Nested keys in multidimensional arrays will not be found.

Exemple

Example #1 array_key_exists() example

<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?>

Example #2 array_key_exists() vs isset()

isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.

<?php
$search_array = array('first' => null, 'second' => 4);

// returns false
isset($search_array['first']);

// returns true
array_key_exists('first', $search_array);
?>

Note

Nota:

For backward compatibility reasons, array_key_exists() will also return TRUE if key is a property defined within an object given as array. This behaviour should not be relied upon, and care should be taken to ensure that array is an array.

To check whether a property exists in an object, use property_exists().

A se vedea ?i

  • isset() - Determina daca o variabla este stabilita ?i nu este NULL
  • array_keys() - Return all the keys or a subset of the keys of an array
  • in_array() - Checks if a value exists in an array
  • property_exists() - Checks if the object or class has a property

array_intersect
array_keys
Func?ii ale tablourilor (Array)


Return all the keys or a subset of the keys of an array

array_key_exists
array_map
Func?ii ale tablourilor (Array)
PHP Manual

array_keys

(PHP 4, PHP 5, PHP 7)

array_keys — Return all the keys or a subset of the keys of an array

Descrierea

array array_keys ( array $array [, mixed $search_value = null [, bool $strict = false ]] )

array_keys() returns the keys, numeric and string, from the array.

If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

Parametri

array

An array containing keys to return.

search_value

If specified, then only keys containing these values are returned.

strict

Determines if strict comparison (===) should be used during the search.

Valorile întoarse

Returns an array of all the keys in array.

Exemple

Example #1 array_keys() example

<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

$array = array("color" => array("blue", "red", "green"),
               "size"  => array("small", "medium", "large"));
print_r(array_keys($array));
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => 0
    [1] => color
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => color
    [1] => size
)

A se vedea ?i

  • array_values() - Return all the values of an array
  • array_combine() - Creates an array by using one array for keys and another for its values
  • array_key_exists() - Checks if the given key or index exists in the array
  • array_search() - Searches the array for a given value and returns the first corresponding key if successful

array_key_exists
array_map
Func?ii ale tablourilor (Array)


Applies the callback to the elements of the given arrays

array_keys
array_merge_recursive
Func?ii ale tablourilor (Array)
PHP Manual

array_map

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

array_map — Applies the callback to the elements of the given arrays

Descrierea

array array_map ( callable $callback , array $array1 [, array $... ] )

array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()

Parametri

callback

Callback function to run for each element in each array.

array1

An array to run through the callback function.

...

Variable list of array arguments to run through the callback function.

Valorile întoarse

Returns an array containing all the elements of array1 after applying the callback function to each one.

Exemple

Example #1 array_map() example

<?php
function cube($n)
{
    return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>

This makes $b have:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

Example #2 array_map() using a lambda function (as of PHP 5.3.0)

<?php
$func = function($value) {
    return $value * 2;
};

print_r(array_map($func, range(1, 5)));
?>
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)

Example #3 array_map() - using more arrays

<?php
function show_Spanish($n, $m)
{
    return("The number $n is called $m in Spanish");
}

function map_Spanish($n, $m)
{
    return(array($n => $m));
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");

$c = array_map("show_Spanish", $a, $b);
print_r($c);

$d = array_map("map_Spanish", $a , $b);
print_r($d);
?>

Exemplul de mai sus va afi?a:

// printout of $c
Array
(
    [0] => The number 1 is called uno in Spanish
    [1] => The number 2 is called dos in Spanish
    [2] => The number 3 is called tres in Spanish
    [3] => The number 4 is called cuatro in Spanish
    [4] => The number 5 is called cinco in Spanish
)

// printout of $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

    [1] => Array
        (
            [2] => dos
        )

    [2] => Array
        (
            [3] => tres
        )

    [3] => Array
        (
            [4] => cuatro
        )

    [4] => Array
        (
            [5] => cinco
        )

)

Usually when using two or more arrays, they should be of equal length because the callback function is applied in parallel to the corresponding elements. If the arrays are of unequal length, shorter ones will be extended with empty elements to match the length of the longest.

An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function

Example #4 Creating an array of arrays

<?php
$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");

$d = array_map(null, $a, $b, $c);
print_r($d);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => four
            [2] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => five
            [2] => cinco
        )

)

The returned array will preserve the keys of the array argument if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys.

Example #5 array_map() - with string keys

<?php
$arr = array("stringkey" => "value");
function cb1($a) {
    return array ($a);
}
function cb2($a, $b) {
    return array ($a, $b);
}
var_dump(array_map("cb1", $arr));
var_dump(array_map("cb2", $arr, $arr));
var_dump(array_map(null,  $arr));
var_dump(array_map(null, $arr, $arr));
?>

Exemplul de mai sus va afi?a:

array(1) {
  ["stringkey"]=>
  array(1) {
    [0]=>
    string(5) "value"
  }
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}
array(1) {
  ["stringkey"]=>
  string(5) "value"
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}

A se vedea ?i

  • array_filter() - Filtreaza elementele unui tablou utilizând o func?ie de apel invers
  • array_reduce() - Iteratively reduce the array to a single value using a callback function
  • array_walk() - Apply a user supplied function to every member of an array
  • informa?ie despre tipul callback

array_keys
array_merge_recursive
Func?ii ale tablourilor (Array)


Merge two or more arrays recursively

array_map
array_merge
Func?ii ale tablourilor (Array)
PHP Manual

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

array_merge_recursive — Merge two or more arrays recursively

Descrierea

array array_merge_recursive ( array $array1 [, array $... ] )

array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

Parametri

array1

Initial array to merge.

...

Variable list of arrays to recursively merge.

Valorile întoarse

An array of values resulted from merging the arguments together.

Exemple

Example #1 array_merge_recursive() example

<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

Exemplul de mai sus va afi?a:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

A se vedea ?i

  • array_merge() - Merge one or more arrays
  • array_replace_recursive() - Replaces elements from passed arrays into the first array recursively

array_map
array_merge
Func?ii ale tablourilor (Array)


Merge one or more arrays

array_merge_recursive
array_multisort
Func?ii ale tablourilor (Array)
PHP Manual

array_merge

(PHP 4, PHP 5, PHP 7)

array_merge — Merge one or more arrays

Descrierea

array array_merge ( array $array1 [, array $... ] )

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Parametri

array1

Initial array to merge.

...

Variable list of arrays to merge.

Valorile întoarse

Returns the resulting array.

Exemple

Example #1 array_merge() example

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

Exemplul de mai sus va afi?a:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

Example #2 Simple array_merge() example

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>

Don't forget that numeric keys will be renumbered!

Array
(
    [0] => data
)

If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>

The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.

array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}

Example #3 array_merge() with non-array types

<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

Exemplul de mai sus va afi?a:

    Array
    (
        [0] => foo
        [1] => bar
    )

A se vedea ?i

  • array_merge_recursive() - Merge two or more arrays recursively
  • array_replace() - Replaces elements from passed arrays into the first array
  • array_combine() - Creates an array by using one array for keys and another for its values
  • array operators

array_merge_recursive
array_multisort
Func?ii ale tablourilor (Array)


Sort multiple or multi-dimensional arrays

array_merge
array_pad
Func?ii ale tablourilor (Array)
PHP Manual

array_multisort

(PHP 4, PHP 5, PHP 7)

array_multisort — Sort multiple or multi-dimensional arrays

Descrierea

bool array_multisort ( array &$array1 [, mixed $array1_sort_order = SORT_ASC [, mixed $array1_sort_flags = SORT_REGULAR [, mixed $... ]]] )

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions.

Associative (string) keys will be maintained, but numeric keys will be re-indexed.

Nota:

If two members compare as equal, their relative order in the sorted array is undefined.

Parametri

array1

An array being sorted.

array1_sort_order

The order used to sort the previous array argument. Either SORT_ASC to sort ascendingly or SORT_DESC to sort descendingly.

This argument can be swapped with array1_sort_flags or omitted entirely, in which case SORT_ASC is assumed.

array1_sort_flags

Sort options for the previous array argument:

Sorting type flags:

  • SORT_REGULAR - compare items normally (don't change types)
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()
  • SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
  • SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

This argument can be swapped with array1_sort_order or omitted entirely, in which case SORT_REGULAR is assumed.

...

More arrays, optionally followed by sort order and flags. Only elements corresponding to equivalent elements in previous arrays are compared. In other words, the sort is lexicographical.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | The SORT_NATURAL and SORT_FLAG_CASE were added to array1_sort_flags as possible sort flags.
5.3.0 | The SORT_LOCALE_STRING was added to array1_sort_flags as possible sort flags.

Exemple

Example #1 Sorting multiple arrays

<?php
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?>

In this example, after sorting, the first array will contain 0, 10, 100, 100. The second array will contain 4, 1, 2, 3. The entries in the second array corresponding to the identical entries in the first array (100 and 100) were sorted as well.

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)
}

Example #2 Sorting multi-dimensional array

<?php
$ar = array(
       array("10", 11, 100, 100, "a"),
       array(   1,  2, "2",   3,   1)
      );
array_multisort($ar[0], SORT_ASC, SORT_STRING,
                $ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>

In this example, after sorting, the first array will transform to "10", 100, 100, 11, "a" (it was sorted as strings in ascending order). The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order).

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)
  }
}

Example #3 Sorting database results

For this example, each element in the data array represents one row in a table. This type of dataset is typical of database records.

Example data:

volume | edition
-------+--------
    67 |       2
    86 |       1
    85 |       6
    98 |       2
    86 |       6
    67 |       7

The data as an array, called data. This would usually, for example, be obtained by looping with mysqli_fetch_assoc().

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?>

In this example, we will order by volume descending, edition ascending.

We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.

<?php
// Obtain a list of columns
foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>

The dataset is now sorted, and will look like this:

volume | edition
-------+--------
    98 |       2
    86 |       1
    86 |       6
    85 |       6
    67 |       2
    67 |       7

Example #4 Case insensitive sorting

Both SORT_STRING and SORT_REGULAR are case sensitive, strings starting with a capital letter will come before strings starting with a lowercase letter.

To perform a case insensitive sort, force the sorting order to be determined by a lowercase copy of the original array.

<?php
$array = array('Alpha', 'atomic', 'Beta', 'bank');
$array_lowercase = array_map('strtolower', $array);

array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);

print_r($array);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => Alpha
    [1] => atomic
    [2] => bank
    [3] => Beta
)

A se vedea ?i

  • usort() - Sort an array by values using a user-defined comparison function
  • Compara?ia func?iilor de sortare a tablourilor

array_merge
array_pad
Func?ii ale tablourilor (Array)


Pad array to the specified length with a value

array_multisort
array_pop
Func?ii ale tablourilor (Array)
PHP Manual

array_pad

(PHP 4, PHP 5, PHP 7)

array_pad — Pad array to the specified length with a value

Descrierea

array array_pad ( array $array , int $size , mixed $value )

array_pad() returns a copy of the array padded to size specified by size with value value. If size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of size is less than or equal to the length of the array then no padding takes place. It is possible to add at most 1048576 elements at a time.

Parametri

array

Initial array of values to pad.

size

New size of the array.

value

Value to pad if array is less than size.

Valorile întoarse

Returns a copy of the array padded to size specified by size with value value. If size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of size is less than or equal to the length of the array then no padding takes place.

Exemple

Example #1 array_pad() example

<?php
$input = array(12, 10, 9);

$result = array_pad($input, 5, 0);
// result is array(12, 10, 9, 0, 0)

$result = array_pad($input, -7, -1);
// result is array(-1, -1, -1, -1, 12, 10, 9)

$result = array_pad($input, 2, "noop");
// not padded
?>

A se vedea ?i

  • array_fill() - Completeaza un tablou cu valori
  • range() - Create an array containing a range of elements

array_multisort
array_pop
Func?ii ale tablourilor (Array)


Pop the element off the end of array

array_pad
array_product
Func?ii ale tablourilor (Array)
PHP Manual

array_pop

(PHP 4, PHP 5, PHP 7)

array_pop — Pop the element off the end of array

Descrierea

mixed array_pop ( array &$array )

array_pop() pops and returns the last value of the array, shortening the array by one element.

Nota: Aceasta func?ie va reseta (reset()) indicatorul tabloului (array) de intrare dupa utilizare.

Parametri

array

The array to get the value from.

Valorile întoarse

Returns the last value of array. If array is empty (or is not an array), NULL will be returned.

Erori/Excep?ii

This function will produce an error of level E_WARNING when called on a non-array.

Exemple

Example #1 array_pop() example

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>

After this, $stack will have only 3 elements:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)

and raspberry will be assigned to $fruit.

A se vedea ?i

  • array_push() - Push one or more elements onto the end of array
  • array_shift() - Shift an element off the beginning of array
  • array_unshift() - Prepend one or more elements to the beginning of an array

array_pad
array_product
Func?ii ale tablourilor (Array)


Calculate the product of values in an array

array_pop
array_push
Func?ii ale tablourilor (Array)
PHP Manual

array_product

(PHP 5 >= 5.1.0, PHP 7)

array_product — Calculate the product of values in an array

Descrierea

number array_product ( array $array )

array_product() returns the product of values in an array.

Parametri

array

The array.

Valorile întoarse

Returns the product as an integer or float.

Istoricul schimbarilor

Versiune | Descriere
5.3.6 | The product of an empty array is now 1, when before this function would return 0 for an empty array.

Exemple

Example #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";

?>

Exemplul de mai sus va afi?a:

product(a) = 384
product(array()) = 1

array_pop
array_push
Func?ii ale tablourilor (Array)


Push one or more elements onto the end of array

array_product
array_rand
Func?ii ale tablourilor (Array)
PHP Manual

array_push

(PHP 4, PHP 5, PHP 7)

array_push — Push one or more elements onto the end of array

Descrierea

int array_push ( array &$array , mixed $value1 [, mixed $... ] )

array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:

<?php
$array[] = $var;
?>
repeated for each passed value.

Nota: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

Nota: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.

Parametri

array

The input array.

value1

The first value to push onto the end of the array.

Valorile întoarse

Returns the new number of elements in the array.

Exemple

Example #1 array_push() example

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

A se vedea ?i

  • array_pop() - Pop the element off the end of array
  • array_shift() - Shift an element off the beginning of array
  • array_unshift() - Prepend one or more elements to the beginning of an array

array_product
array_rand
Func?ii ale tablourilor (Array)


Pick one or more random entries out of an array

array_push
array_reduce
Func?ii ale tablourilor (Array)
PHP Manual

array_rand

(PHP 4, PHP 5, PHP 7)

array_rand — Pick one or more random entries out of an array

Descrierea

mixed array_rand ( array $array [, int $num = 1 ] )

Picks one or more random entries out of an array, and returns the key (or keys) of the random entries. It uses a pseudo random number generator that is not suitable for cryptographic purposes.

Parametri

array

The input array.

num

Specifies how many entries should be picked.

Valorile întoarse

When picking only one entry, array_rand() returns the key for a random entry. Otherwise, an array of keys for the random entries is returned. This is done so that random keys can be picked from the array as well as random values. Trying to pick more elements than there are in the array will result in an E_WARNING level error, and NULL will be returned.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | The internal randomization algorithm has been changed to use the » Mersenne Twister Random Number Generator instead of the libc rand function.
5.2.10 | The resulting array of keys is no longer shuffled.

Exemple

Example #1 array_rand() example

<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>

A se vedea ?i

  • shuffle() - Shuffle an array

array_push
array_reduce
Func?ii ale tablourilor (Array)


Iteratively reduce the array to a single value using a callback function

array_rand
array_replace_recursive
Func?ii ale tablourilor (Array)
PHP Manual

array_reduce

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

array_reduce — Iteratively reduce the array to a single value using a callback function

Descrierea

mixed array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] )

array_reduce() applies iteratively the callback function to the elements of the array, so as to reduce the array to a single value.

Parametri

array

The input array.

callback
mixed callback ( mixed $carry , mixed $item )
carry

Holds the return value of the previous iteration; in the case of the first iteration it instead holds the value of initial.

item

Holds the value of the current iteration.

initial

If the optional initial is available, it will be used at the beginning of the process, or as a final result in case the array is empty.

Valorile întoarse

Returns the resulting value.

If the array is empty and initial is not passed, array_reduce() returns NULL.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Changed initial to allow mixed, previously integer.

Exemple

Example #1 array_reduce() example

<?php
function sum($carry, $item)
{
    $carry += $item;
    return $carry;
}

function product($carry, $item)
{
    $carry *= $item;
    return $carry;
}

$a = array(1, 2, 3, 4, 5);
$x = array();

var_dump(array_reduce($a, "sum")); // int(15)
var_dump(array_reduce($a, "product", 10)); // int(1200), because: 10*1*2*3*4*5
var_dump(array_reduce($x, "sum", "No data to reduce")); // string(17) "No data to reduce"
?>

A se vedea ?i

  • array_filter() - Filtreaza elementele unui tablou utilizând o func?ie de apel invers
  • array_map() - Applies the callback to the elements of the given arrays
  • array_unique() - Removes duplicate values from an array
  • array_count_values() - Numara toate valorile unui tablou

array_rand
array_replace_recursive
Func?ii ale tablourilor (Array)


Replaces elements from passed arrays into the first array recursively

array_reduce
array_replace
Func?ii ale tablourilor (Array)
PHP Manual

array_replace_recursive

(PHP 5 >= 5.3.0, PHP 7)

array_replace_recursive — Replaces elements from passed arrays into the first array recursively

Descrierea

array array_replace_recursive ( array $array1 , array $array2 [, array $... ] )

array_replace_recursive() replaces the values of array1 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 array1 is scalar, it will be replaced by the value in array2, may it be scalar or array. When the value in array1 and array2 are both arrays, array_replace_recursive() will replace their respective value recursively.

Parametri

array1

The array in which elements are replaced.

array2

The array from which elements will be extracted.

...

Optional. More arrays from which elements will be extracted.

Valorile întoarse

Returns an array, or NULL if an error occurs.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

)
Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
        )

)

Example #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);

?>

Exemplul de mai sus va afi?a:

Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

    [others] => litchis
)

A se vedea ?i

  • array_replace() - Replaces elements from passed arrays into the first array
  • array_merge_recursive() - Merge two or more arrays recursively

array_reduce
array_replace
Func?ii ale tablourilor (Array)


Replaces elements from passed arrays into the first array

array_replace_recursive
array_reverse
Func?ii ale tablourilor (Array)
PHP Manual

array_replace

(PHP 5 >= 5.3.0, PHP 7)

array_replace — Replaces elements from passed arrays into the first array

Descrierea

array array_replace ( array $array1 , array $array2 [, array $... ] )

array_replace() replaces the values of array1 with values having the same keys in each of 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.

Parametri

array1

The array in which elements are replaced.

array2

The array from which elements will be extracted.

...

More arrays from which elements will be extracted. Values from later arrays overwrite the previous values.

Valorile întoarse

Returns an array, or NULL if an error occurs.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

A se vedea ?i

  • array_replace_recursive() - Replaces elements from passed arrays into the first array recursively
  • array_merge() - Merge one or more arrays

array_replace_recursive
array_reverse
Func?ii ale tablourilor (Array)


Return an array with elements in reverse order

array_replace
array_search
Func?ii ale tablourilor (Array)
PHP Manual

array_reverse

(PHP 4, PHP 5, PHP 7)

array_reverse — Return an array with elements in reverse order

Descrierea

array array_reverse ( array $array [, bool $preserve_keys = false ] )

Takes an input array and returns a new array with the order of the elements reversed.

Parametri

array

The input array.

preserve_keys

If set to TRUE numeric keys are preserved. Non-numeric keys are not affected by this setting and will always be preserved.

Valorile întoarse

Returns the reversed array.

Exemple

Example #1 array_reverse() example

<?php
$input  = array("php", 4.0, array("green", "red"));
$reversed = array_reverse($input);
$preserved = array_reverse($input, true);

print_r($input);
print_r($reversed);
print_r($preserved);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => php
    [1] => 4
    [2] => Array
        (
            [0] => green
            [1] => red
        )

)
Array
(
    [0] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [0] => php
)

A se vedea ?i

  • array_flip() - Exchanges all keys with their associated values in an array

array_replace
array_search
Func?ii ale tablourilor (Array)


Searches the array for a given value and returns the first corresponding key if successful

array_reverse
array_shift
Func?ii ale tablourilor (Array)
PHP Manual

array_search

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

array_search — Searches the array for a given value and returns the first corresponding key if successful

Descrierea

mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

Searches haystack for needle.

Parametri

needle

The searched value.

Nota:

If needle is a string, the comparison is done in a case-sensitive manner.

haystack

The array.

strict

If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also perform a strict type comparison of the needle in the haystack, and objects must be the same instance.

Valorile întoarse

Returns the key for needle if it is found in the array, FALSE otherwise.

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | As with all internal PHP functions as of 5.3.0, array_search() returns NULL if invalid parameters are passed to it.

Exemple

Example #1 array_search() example

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

A se vedea ?i

  • array_keys() - Return all the keys or a subset of the keys of an array
  • array_values() - Return all the values of an array
  • array_key_exists() - Checks if the given key or index exists in the array
  • in_array() - Checks if a value exists in an array

array_reverse
array_shift
Func?ii ale tablourilor (Array)


Shift an element off the beginning of array

array_search
array_slice
Func?ii ale tablourilor (Array)
PHP Manual

array_shift

(PHP 4, PHP 5, PHP 7)

array_shift — Shift an element off the beginning of array

Descrierea

mixed array_shift ( array &$array )

array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

Nota: Aceasta func?ie va reseta (reset()) indicatorul tabloului (array) de intrare dupa utilizare.

Parametri

array

The input array.

Valorile întoarse

Returns the shifted value, or NULL if array is empty or is not an array.

Exemple

Example #1 array_shift() example

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)

and orange will be assigned to $fruit.

A se vedea ?i

  • array_unshift() - Prepend one or more elements to the beginning of an array
  • array_push() - Push one or more elements onto the end of array
  • array_pop() - Pop the element off the end of array

array_search
array_slice
Func?ii ale tablourilor (Array)


Extract a slice of the array

array_shift
array_splice
Func?ii ale tablourilor (Array)
PHP Manual

array_slice

(PHP 4, PHP 5, PHP 7)

array_slice — Extract a slice of the array

Descrierea

array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )

array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.

Parametri

array

The input array.

offset

If offset is non-negative, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.

length

If length is given and is positive, then the sequence will have up to that many elements in it. If the array is shorter than the length, then only the available array elements will be present. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.

preserve_keys

Note that array_slice() will reorder and reset the numeric array indices by default. You can change this behaviour by setting preserve_keys to TRUE.

Valorile întoarse

Returns the slice. If the offset is larger than the size of the array then returns an empty array.

Istoricul schimbarilor

Versiune | Descriere
5.2.4 | The default value of the length parameter was changed to NULL. A NULL length now tells the function to use the length of array. Prior to this version, a NULL length was taken to mean a zero length (nothing will be returned).
5.0.2 | The optional preserve_keys parameter was added.

Exemple

Example #1 array_slice() examples

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)

A se vedea ?i

  • array_splice() - Remove a portion of the array and replace it with something else
  • unset() - Elimina o variabila data
  • array_chunk() - Desparte un tablou în por?iuni

array_shift
array_splice
Func?ii ale tablourilor (Array)


Remove a portion of the array and replace it with something else

array_slice
array_sum
Func?ii ale tablourilor (Array)
PHP Manual

array_splice

(PHP 4, PHP 5, PHP 7)

array_splice — Remove a portion of the array and replace it with something else

Descrierea

array array_splice ( array &$input , int $offset [, int $length = count($input) [, mixed $replacement = array() ]] )

Removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied.

Note that numeric keys in input are not preserved.

Nota: If replacement is not an array, it will be typecast to one (i.e. (array) $replacement). This may result in unexpected behavior when using an object or NULL replacement.

Parametri

input

The input array.

offset

If offset is positive then the start of removed portion is at that offset from the beginning of the input array. If offset is negative then it starts that far from the end of the input array.

length

If length is omitted, removes everything from offset to the end of the array. If length is specified and is positive, then that many elements will be removed. If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array. If length is specified and is zero, no elements will be removed. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length.

replacement

If replacement array is specified, then the removed elements are replaced with elements from this array.

If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specified by the offset. Note that keys in replacement array are not preserved.

If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL.

Valorile întoarse

Returns an array consisting of the extracted elements.

Exemple

Example #1 array_splice() examples

<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green",
//          "blue", "black", "maroon")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
//          "blue", "purple", "yellow");
?>

Example #2 array_splice() examples

The following statements change the values of $input the same way:

<?php
array_push($input, $x, $y);
array_splice($input, count($input), 0, array($x, $y));
array_pop($input);
array_splice($input, -1);
array_shift($input);
array_splice($input, 0, 1);
array_unshift($input, $x, $y);
array_splice($input, 0, 0, array($x, $y));
$input[$x] = $y; // for arrays where key equals offset
array_splice($input, $x, 1, $y);
?>

A se vedea ?i

  • array_slice() - Extract a slice of the array
  • unset() - Elimina o variabila data
  • array_merge() - Merge one or more arrays

array_slice
array_sum
Func?ii ale tablourilor (Array)


Calculate the sum of values in an array

array_splice
array_udiff_assoc
Func?ii ale tablourilor (Array)
PHP Manual

array_sum

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

array_sum — Calculate the sum of values in an array

Descrierea

number array_sum ( array $array )

array_sum() returns the sum of values in an array.

Parametri

array

The input array.

Valorile întoarse

Returns the sum of values as an integer or float; 0 if the array is empty.

Exemple

Example #1 array_sum() examples

<?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";
?>

Exemplul de mai sus va afi?a:

sum(a) = 20
sum(b) = 6.9

array_splice
array_udiff_assoc
Func?ii ale tablourilor (Array)


Computes the difference of arrays with additional index check, compares data by a callback function

array_sum
array_udiff_uassoc
Func?ii ale tablourilor (Array)
PHP Manual

array_udiff_assoc

(PHP 5, PHP 7)

array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function

Descrierea

array array_udiff_assoc ( array $array1 , array $array2 [, array $... ], callable $value_compare_func )

Computes the difference of arrays with additional index check, compares data by a callback function.

Nota: 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");.

Parametri

array1

The first array.

array2

The second array.

value_compare_func

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )

Valorile întoarse

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.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • array_diff() - Calculeaza diferen?a dintre tablouri
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • 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() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions

array_sum
array_udiff_uassoc
Func?ii ale tablourilor (Array)


Computes the difference of arrays with additional index check, compares data and indexes by a callback function

array_udiff_assoc
array_udiff
Func?ii ale tablourilor (Array)
PHP Manual

array_udiff_uassoc

(PHP 5, PHP 7)

array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function

Descrierea

array array_udiff_uassoc ( array $array1 , array $array2 [, array $... ], callable $value_compare_func , callable $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().

Parametri

array1

The first array.

array2

The second array.

value_compare_func

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
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.

Valorile întoarse

Returns an array containing all the values from array1 that are not present in any of the other arguments.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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.

Note

Nota: 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");.

A se vedea ?i

  • array_diff() - Calculeaza diferen?a dintre tablouri
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • 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() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions

array_udiff_assoc
array_udiff
Func?ii ale tablourilor (Array)


Computes the difference of arrays by using a callback function for data comparison

array_udiff_uassoc
array_uintersect_assoc
Func?ii ale tablourilor (Array)
PHP Manual

array_udiff

(PHP 5, PHP 7)

array_udiff — Computes the difference of arrays by using a callback function for data comparison

Descrierea

array array_udiff ( array $array1 , array $array2 [, array $... ], callable $value_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.

Parametri

array1

The first array.

array2

The second array.

value_compare_func

The callback comparison function.

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )

Valorile întoarse

Returns an array containing all the values of array1 that are not present in any of the other arguments.

Exemple

Example #1 array_udiff() example using stdClass Objects

<?php
// Arrays to compare
$array1 = array(new stdclass, new stdclass,
                new stdclass, new stdclass,
               );

$array2 = array(
                new stdclass, new stdclass,
               );

// Set some properties for each object
$array1[0]->width = 11; $array1[0]->height = 3;
$array1[1]->width = 7;  $array1[1]->height = 1;
$array1[2]->width = 2;  $array1[2]->height = 9;
$array1[3]->width = 5;  $array1[3]->height = 7;

$array2[0]->width = 7;  $array2[0]->height = 5;
$array2[1]->width = 9;  $array2[1]->height = 2;

function compare_by_area($a, $b) {
    $areaA = $a->width * $a->height;
    $areaB = $b->width * $b->height;

    if ($areaA < $areaB) {
        return -1;
    } elseif ($areaA > $areaB) {
        return 1;
    } else {
        return 0;
    }
}

print_r(array_udiff($array1, $array2, 'compare_by_area'));
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => stdClass Object
        (
            [width] => 11
            [height] => 3
        )

    [1] => stdClass Object
        (
            [width] => 7
            [height] => 1
        )

)

Example #2 array_udiff() example using DateTime Objects

<?php
class MyCalendar {
    public $free = array();
    public $booked = array();

    public function __construct($week = 'now') {
        $start = new DateTime($week);
        $start->modify('Monday this week midnight');
        $end = clone $start;
        $end->modify('Friday this week midnight');
        $interval = new DateInterval('P1D');
        foreach (new DatePeriod($start, $interval, $end) as $freeTime) {
            $this->free[] = $freeTime;
        }
    }

    public function bookAppointment(DateTime $date, $note) {
        $this->booked[] = array('date' => $date->modify('midnight'), 'note' => $note);
    }

    public function checkAvailability() {
        return array_udiff($this->free, $this->booked, array($this, 'customCompare'));
    }

    public function customCompare($free, $booked) {
        if (is_array($free)) $a = $free['date'];
        else $a = $free;
        if (is_array($booked)) $b = $booked['date'];
        else $b = $booked;
        if ($a == $b) {
            return 0;
        } elseif ($a > $b) {
            return 1;
        } else {
            return -1;
        }
    }
}

// Create a calendar for weekly appointments
$myCalendar = new MyCalendar;

// Book some appointments for this week
$myCalendar->bookAppointment(new DateTime('Monday this week'), "Cleaning GoogleGuy's apartment.");
$myCalendar->bookAppointment(new DateTime('Wednesday this week'), "Going on a snowboarding trip.");
$myCalendar->bookAppointment(new DateTime('Friday this week'), "Fixing buggy code.");

// Check availability of days by comparing $booked dates against $free dates
echo "I'm available on the following days this week...\n\n";
foreach ($myCalendar->checkAvailability() as $free) {
    echo $free->format('l'), "\n";
}
echo "\n\n";
echo "I'm busy on the following days this week...\n\n";
foreach ($myCalendar->booked as $booked) {
    echo $booked['date']->format('l'), ": ", $booked['note'], "\n";
}
?>

Exemplul de mai sus va afi?a:

I'm available on the following days this week...

Tuesday
Thursday

I'm busy on the following days this week...

Monday: Cleaning GoogleGuy's apartment.
Wednesday: Going on a snowboarding trip.
Friday: Fixing buggy code.

Note

Nota: 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");.

A se vedea ?i

  • array_diff() - Calculeaza diferen?a dintre tablouri
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • 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() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions

array_udiff_uassoc
array_uintersect_assoc
Func?ii ale tablourilor (Array)


Computes the intersection of arrays with additional index check, compares data by a callback function

array_udiff
array_uintersect_uassoc
Func?ii ale tablourilor (Array)
PHP Manual

array_uintersect_assoc

(PHP 5, PHP 7)

array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function

Descrierea

array array_uintersect_assoc ( array $array1 , array $array2 [, array $... ], callable $value_compare_func )

Computes the intersection of arrays with additional index check, compares data by a callback function.

Note that the keys are used in the comparison unlike in array_uintersect(). The data is compared by using a callback function.

Parametri

array1

The first array.

array2

The second array.

value_compare_func

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )

Valorile întoarse

Returns an array containing all the values of array1 that are present in all the arguments.

Exemple

Example #1 array_uintersect_assoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_assoc($array1, $array2, "strcasecmp"));
?>

Exemplul de mai sus va afi?a:

Array
(
    [a] => green
)

A se vedea ?i

  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions

array_udiff
array_uintersect_uassoc
Func?ii ale tablourilor (Array)


Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions

array_uintersect_assoc
array_uintersect
Func?ii ale tablourilor (Array)
PHP Manual

array_uintersect_uassoc

(PHP 5, PHP 7)

array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions

Descrierea

array array_uintersect_uassoc ( array $array1 , array $array2 [, array $... ], callable $value_compare_func , callable $key_compare_func )

Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions.

Parametri

array1

The first array.

array2

The second array.

value_compare_func

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
key_compare_func

Key comparison callback function.

Valorile întoarse

Returns an array containing all the values of array1 that are present in all the arguments.

Exemple

Example #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"));
?>

Exemplul de mai sus va afi?a:

Array
(
    [a] => green
    [b] => brown
)

A se vedea ?i

  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function

array_uintersect_assoc
array_uintersect
Func?ii ale tablourilor (Array)


Computes the intersection of arrays, compares data by a callback function

array_uintersect_uassoc
array_unique
Func?ii ale tablourilor (Array)
PHP Manual

array_uintersect

(PHP 5, PHP 7)

array_uintersect — Computes the intersection of arrays, compares data by a callback function

Descrierea

array array_uintersect ( array $array1 , array $array2 [, array $... ], callable $value_compare_func )

Computes the intersection of arrays, compares data by a callback function.

Parametri

array1

The first array.

array2

The second array.

value_compare_func

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )

Valorile întoarse

Returns an array containing all the values of array1 that are present in all the arguments.

Exemple

Example #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"));
?>

Exemplul de mai sus va afi?a:

Array
(
    [a] => green
    [b] => brown
    [0] => red
)

A se vedea ?i

  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions

array_uintersect_uassoc
array_unique
Func?ii ale tablourilor (Array)


Removes duplicate values from an array

array_uintersect
array_unshift
Func?ii ale tablourilor (Array)
PHP Manual

array_unique

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

array_unique — Removes duplicate values from an array

Descrierea

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

Takes an input array and returns a new array without duplicate values.

Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.

Nota: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2 i.e. when the string representation is the same, the first element will be used.

Parametri

array

The input array.

sort_flags

The optional second parameter sort_flags may be used to modify the sorting behavior using these values:

Sorting type flags:

  • SORT_REGULAR - compare items normally (don't change types)
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale.

Valorile întoarse

Returns the filtered array.

Istoricul schimbarilor

Versiune | Descriere
5.2.10 | Changed the default value of sort_flags back to SORT_STRING.
5.2.9 | Added the optional sort_flags defaulting to SORT_REGULAR. Prior to 5.2.9, this function used to sort the array with SORT_STRING internally.

Exemple

Example #1 array_unique() example

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

Exemplul de mai sus va afi?a:

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

Example #2 array_unique() and types

<?php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?>

Exemplul de mai sus va afi?a:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

A se vedea ?i

  • array_count_values() - Numara toate valorile unui tablou

Note

Nota: Note that array_unique() is not intended to work on multi dimensional arrays.

array_uintersect
array_unshift
Func?ii ale tablourilor (Array)


Prepend one or more elements to the beginning of an array

array_unique
array_values
Func?ii ale tablourilor (Array)
PHP Manual

array_unshift

(PHP 4, PHP 5, PHP 7)

array_unshift — Prepend one or more elements to the beginning of an array

Descrierea

int array_unshift ( array &$array , mixed $value1 [, mixed $... ] )

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be changed.

Parametri

array

The input array.

value1

First value to prepend.

Valorile întoarse

Returns the new number of elements in the array.

Exemple

Example #1 array_unshift() example

<?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => apple
    [1] => raspberry
    [2] => orange
    [3] => banana
)

A se vedea ?i

  • array_shift() - Shift an element off the beginning of array
  • array_push() - Push one or more elements onto the end of array
  • array_pop() - Pop the element off the end of array

array_unique
array_values
Func?ii ale tablourilor (Array)


Return all the values of an array

array_unshift
array_walk_recursive
Func?ii ale tablourilor (Array)
PHP Manual

array_values

(PHP 4, PHP 5, PHP 7)

array_values — Return all the values of an array

Descrierea

array array_values ( array $array )

array_values() returns all the values from the array and indexes the array numerically.

Parametri

array

The array.

Valorile întoarse

Returns an indexed array of values.

Exemple

Example #1 array_values() example

<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => XL
    [1] => gold
)

A se vedea ?i

  • array_keys() - Return all the keys or a subset of the keys of an array
  • array_combine() - Creates an array by using one array for keys and another for its values

array_unshift
array_walk_recursive
Func?ii ale tablourilor (Array)


Apply a user function recursively to every member of an array

array_values
array_walk
Func?ii ale tablourilor (Array)
PHP Manual

array_walk_recursive

(PHP 5, PHP 7)

array_walk_recursive — Apply a user function recursively to every member of an array

Descrierea

bool array_walk_recursive ( array &$array , callable $callback [, mixed $userdata = NULL ] )

Applies the user-defined callback function to each element of the array. This function will recurse into deeper arrays.

Parametri

array

The input array.

callback

Typically, callback takes on two parameters. The array parameter's value being the first, and the key/index second.

Nota:

If callback needs to be working with the actual values of the array, specify the first parameter of callback 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • array_walk() - Apply a user supplied function to every member of an array
  • informa?ie despre tipul callback

array_values
array_walk
Func?ii ale tablourilor (Array)


Apply a user supplied function to every member of an array

array_walk_recursive
array
Func?ii ale tablourilor (Array)
PHP Manual

array_walk

(PHP 4, PHP 5, PHP 7)

array_walk — Apply a user supplied function to every member of an array

Descrierea

bool array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] )

Applies the user-defined callback function to each element of the array array.

array_walk() is not affected by the internal array pointer of array. array_walk() will walk through the entire array regardless of pointer position.

Parametri

array

The input array.

callback

Typically, callback takes on two parameters. The array parameter's value being the first, and the key/index second.

Nota:

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

Nota:

Many internal functions (for example strtolower()) will throw a warning if more than the expected number of argument are passed in and are not usable directly as a callback.

Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

userdata

If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

If function callback requires more parameters than given to it, an error of level E_WARNING will be generated each time array_walk() calls callback.

Exemple

Example #1 array_walk() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2<br />\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');
?>

Exemplul de mai sus va afi?a:

Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple

A se vedea ?i

  • array_walk_recursive() - Apply a user function recursively to every member of an array
  • iterator_apply() - Call a function for every element in an iterator
  • list() - Assign variables as if they were an array
  • each() - Return the current key and value pair from an array and advance the array cursor
  • call_user_func_array() - Call a callback with an array of parameters
  • array_map() - Applies the callback to the elements of the given arrays
  • informa?ie despre tipul callback
  • foreach

array_walk_recursive
array
Func?ii ale tablourilor (Array)


Creeaza un tablou

array_walk
arsort
Func?ii ale tablourilor (Array)
PHP Manual

array

(PHP 4, PHP 5, PHP 7)

array — Creeaza un tablou

Descrierea

array array ([ mixed $... ] )

Creeaza un tablou. Citi?i sec?iunea despre tipul array pentru informa?ii suplimentare despre ce este un tablou.

Parametri

...

Sintaxa "indice => valori", separate prin virgule, definesc indicii ?i valorile. Indicele poate fi de tip string sau integer. Când indicele este omis, este generat automat un indice de tip integer, începând cu 0. Daca indicele este de tip integer, urmatorul indice generat va fi cel mai mare indice întreg + 1. Observa?i ca atunci când sunt defini?i doi indici identici, ultima defini?ie se suprapune peste prima.

Plasarea unei virgule dupa ultima înregistrare definita în tablou este o sintaxa valida, cu toate ca este neobi?niuta.

Valorile întoarse

Întoarce un tablou al parametrilor. Parametrilor le poate fi asociat un indice cu ajutorul operatorului =>. Citi?i sec?iunea despre tipul array pentru informa?ii suplimentare despre ce este un tablou.

Exemple

Urmatorul exemplu demonstreaza cum se creeaza un tablou bidimensional, cum se specifica cheile pentru tablourile asociative ?i cum se sare peste indicii numerici în tablouri obi?nuite.

Example #1 Exemplu array()

<?php
$diverse = array (
    "fructe"  => array("a" => "portocala", "b" => "banana", "c" => "mar"),
    "numere" => array(1, 2, 3, 4, 5, 6),
    "gauri"   => array("prima", 5 => "a doua", "a treia")
);
?>

Example #2 Indexarea automata cu array()

<?php
$array = array(1, 1, 1, 1,  1, 8 => 1,  4 => 1, 19, 3 => 13);
print_r($array);
?>

Exemplul de mai sus va afi?a:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

Observa?i ca indicele '3' este definit de doua ori ?i î?i pastreaza valoarea finala 13. Indicele '4' este definit dupa indicele '8' ?i urmatorul indice generat (valoarea 19) este '9', deoarece cel mai mare indice a fost '8'.

Acest exemplu creeaza un tablou cu indicele începând cu 1.

Example #3 Indicele începând cu 1 cu ajutorul array()

<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

Exemplul de mai sus va afi?a:

Array
(
    [1] => January
    [2] => February
    [3] => March
)

Ca ?i în Perl, pute?i accesa o valoare din tablou între ghilimele duble. Însa cu PHP va trebui sa introduce?i tabloul între paranteze figurate.

Example #4 Accesarea unui tablou între ghilimele duble

<?php

$foo = array('bar' => 'baz');
echo "Salut, {$foo['bar']}!"; // Salut, baz!

?>

Note

Nota:

array() este o construc?ie a limbajului utilizata pentru a reprezenta tablouri literale, ?i nu o func?ie obi?nuita.

A se vedea ?i

  • array_pad() - Pad array to the specified length with a value
  • list() - Assign variables as if they were an array
  • count() - Count all elements in an array, or something in an object
  • range() - Create an array containing a range of elements
  • foreach
  • Tipul array

array_walk
arsort
Func?ii ale tablourilor (Array)


Sort an array in reverse order and maintain index association

array
asort
Func?ii ale tablourilor (Array)
PHP Manual

arsort

(PHP 4, PHP 5, PHP 7)

arsort — Sort an array in reverse order and maintain index association

Descrierea

bool arsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

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.

Nota:

If two members compare as equal, their relative order in the sorted array is undefined.

Parametri

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 arsort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

Exemplul de mai sus va afi?a:

a = orange
d = lemon
b = banana
c = apple

The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained.

A se vedea ?i

  • asort() - Sort an array and maintain index association
  • Compara?ia func?iilor de sortare a tablourilor

array
asort
Func?ii ale tablourilor (Array)


Sort an array and maintain index association

arsort
compact
Func?ii ale tablourilor (Array)
PHP Manual

asort

(PHP 4, PHP 5, PHP 7)

asort — Sort an array and maintain index association

Descrierea

bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

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.

Nota:

If two members compare as equal, their relative order in the sorted array is undefined.

Parametri

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 asort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

Exemplul de mai sus va afi?a:

c = apple
b = banana
d = lemon
a = orange

The fruits have been sorted in alphabetical order, and the index associated with each element has been maintained.

A se vedea ?i

  • arsort() - Sort an array in reverse order and maintain index association
  • Compara?ia func?iilor de sortare a tablourilor

arsort
compact
Func?ii ale tablourilor (Array)


Create array containing variables and their values

asort
count
Func?ii ale tablourilor (Array)
PHP Manual

compact

(PHP 4, PHP 5, PHP 7)

compact — Create array containing variables and their values

Descrierea

array compact ( mixed $varname1 [, mixed $... ] )

Creates an array containing variables and their values.

For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract().

Any strings that are not set will simply be skipped.

Parametri

varname1

compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively.

Valorile întoarse

Returns the output array with all the variables added to it.

Exemple

Example #1 compact() example

<?php
$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", "nothing_here", $location_vars);
print_r($result);
?>

Exemplul de mai sus va afi?a:

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)

Note

Nota: Gotcha

Because variable variables may not be used with PHP's Superglobal arrays within functions, the Superglobal arrays may not be passed into compact().

A se vedea ?i

  • extract() - Import variables into the current symbol table from an array

asort
count
Func?ii ale tablourilor (Array)


Count all elements in an array, or something in an object

compact
current
Func?ii ale tablourilor (Array)
PHP Manual

count

(PHP 4, PHP 5, PHP 7)

count — Count all elements in an array, or something in an object

Descrierea

int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

Counts all elements in an array, or something in an object.

For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, Countable::count(), which returns the return value for the count() function.

Please see the Array section of the manual for a detailed explanation of how arrays are implemented and used in PHP.

Parametri

array_or_countable

An array or Countable object.

mode

If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.

Precautie

count() can detect recursion to avoid an infinite loop, but will emit an E_WARNING every time it does (in case the array contains itself more than once) and return a count higher than may be expected.

Valorile întoarse

Returns the number of elements in array_or_countable. If the parameter is not an array or not an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable is NULL, 0 will be returned.

Precautie

count() may return 0 for a variable that isn't set, but it may also return 0 for a variable that has been initialized with an empty array. Use isset() to test if a variable is set.

Exemple

Example #1 count() example

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3

$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
$result = count($b);
// $result == 3

$result = count(null);
// $result == 0

$result = count(false);
// $result == 1
?>

Example #2 Recursive count() example

<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));

// recursive count
echo count($food, COUNT_RECURSIVE); // output 8

// normal count
echo count($food); // output 2

?>

A se vedea ?i

  • is_array() - Determina daca o variabila este un array
  • isset() - Determina daca o variabla este stabilita ?i nu este NULL
  • empty() - Determina daca o variabila este vida
  • strlen() - Get string length

compact
current
Func?ii ale tablourilor (Array)


Return the current element in an array

count
each
Func?ii ale tablourilor (Array)
PHP Manual

current

(PHP 4, PHP 5, PHP 7)

current — Return the current element in an array

Descrierea

mixed current ( array &$array )

Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.

Parametri

array

The array.

Valorile întoarse

The current() function simply returns the value of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, current() returns FALSE.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Exemple

Example #1 Example use of current() and friends

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport);    // $mode = 'foot';
$mode = end($transport);     // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';

$arr = array();
var_dump(current($arr)); // bool(false)

$arr = array(array());
var_dump(current($arr)); // array(0) { }
?>

Note

Nota: You won't be able to distinguish the end of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.

A se vedea ?i

  • end() - Set the internal pointer of an array to its last element
  • key() - Fetch a key from an array
  • each() - Return the current key and value pair from an array and advance the array cursor
  • prev() - Rewind the internal array pointer
  • reset() - Set the internal pointer of an array to its first element
  • next() - Advance the internal array pointer of an array

count
each
Func?ii ale tablourilor (Array)


Return the current key and value pair from an array and advance the array cursor

current
end
Func?ii ale tablourilor (Array)
PHP Manual

each

(PHP 4, PHP 5, PHP 7)

each — Return the current key and value pair from an array and advance the array cursor

Descrierea

array each ( array &$array )

Return the current key and value pair from an array and advance the array cursor.

After each() has executed, the array cursor will be left on the next element of the array, or past the last element if it hits the end of the array. You have to use reset() if you want to traverse the array again using each.

Parametri

array

The input array.

Valorile întoarse

Returns the current key and value pair from the array array. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data.

If the internal pointer for the array points past the end of the array contents, each() returns FALSE.

Exemple

Example #1 each() examples

<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>

$bar now contains the following key/value pairs:

Array
(
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
)

<?php
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?>

$bar now contains the following key/value pairs:

Array
(
    [1] => Bob
    [value] => Bob
    [0] => Robert
    [key] => Robert
)

each() is typically used in conjunction with list() to traverse an array, here's an example:

Example #2 Traversing an array with each()

<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while (list($key, $val) = each($fruit)) {
    echo "$key => $val\n";
}
?>

Exemplul de mai sus va afi?a:

a => apple
b => banana
c => cranberry

Precautie

Because assigning an array to another variable resets the original array's pointer, our example above would cause an endless loop had we assigned $fruit to another variable inside the loop.

Avertizare

each() will also accept objects, but may return unexpected results. It's therefore not recommended to iterate though object properties with each().

A se vedea ?i

  • key() - Fetch a key from an array
  • list() - Assign variables as if they were an array
  • current() - Return the current element in an array
  • reset() - Set the internal pointer of an array to its first element
  • next() - Advance the internal array pointer of an array
  • prev() - Rewind the internal array pointer
  • foreach
  • Object Iteration

current
end
Func?ii ale tablourilor (Array)


Set the internal pointer of an array to its last element

each
extract
Func?ii ale tablourilor (Array)
PHP Manual

end

(PHP 4, PHP 5, PHP 7)

end — Set the internal pointer of an array to its last element

Descrierea

mixed end ( array &$array )

end() advances array's internal pointer to the last element, and returns its value.

Parametri

array

The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.

Valorile întoarse

Returns the value of the last element or FALSE for empty array.

Exemple

Example #1 end() example

<?php

$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry

?>

A se vedea ?i

  • current() - Return the current element in an array
  • each() - Return the current key and value pair from an array and advance the array cursor
  • prev() - Rewind the internal array pointer
  • reset() - Set the internal pointer of an array to its first element
  • next() - Advance the internal array pointer of an array

each
extract
Func?ii ale tablourilor (Array)


Import variables into the current symbol table from an array

end
in_array
Func?ii ale tablourilor (Array)
PHP Manual

extract

(PHP 4, PHP 5, PHP 7)

extract — Import variables into the current symbol table from an array

Descrierea

int extract ( array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = NULL ]] )

Import variables from an array into the current symbol table.

Checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table.

Parametri

array

An associative array. This function treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to flags and prefix parameters.

You must use an associative array; a numerically indexed array will not produce results unless you use EXTR_PREFIX_ALL or EXTR_PREFIX_INVALID.

flags

The way invalid/numeric keys and collisions are treated is determined by the extraction flags. It can be one of the following values:

EXTR_OVERWRITE
If there is a collision, overwrite the existing variable.
EXTR_SKIP
If there is a collision, don't overwrite the existing variable.
EXTR_PREFIX_SAME
If there is a collision, prefix the variable name with prefix.
EXTR_PREFIX_ALL
Prefix all variable names with prefix.
EXTR_PREFIX_INVALID
Only prefix invalid/numeric variable names with prefix.
EXTR_IF_EXISTS
Only overwrite the variable if it already exists in the current symbol table, otherwise do nothing. This is useful for defining a list of valid variables and then extracting only those variables you have defined out of $_REQUEST, for example.
EXTR_PREFIX_IF_EXISTS
Only create prefixed variable names if the non-prefixed version of the same variable exists in the current symbol table.
EXTR_REFS
Extracts variables as references. This effectively means that the values of the imported variables are still referencing the values of the array parameter. You can use this flag on its own or combine it with any other flag by OR'ing the flags.

If flags is not specified, it is assumed to be EXTR_OVERWRITE.

prefix

Note that prefix is only required if flags is EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS. If the prefixed result is not a valid variable name, it is not imported into the symbol table. Prefixes are automatically separated from the array key by an underscore character.

Valorile întoarse

Returns the number of variables successfully imported into the symbol table.

Exemple

Example #1 extract() example

A possible use for extract() is to import into the symbol table variables contained in an associative array returned by wddx_deserialize().

<?php

/* Suppose that $var_array is an array returned from
   wddx_deserialize */

$size = "large";
$var_array = array("color" => "blue",
                   "size"  => "medium",
                   "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape, $wddx_size\n";

?>

Exemplul de mai sus va afi?a:

blue, large, sphere, medium

The $size wasn't overwritten because we specified EXTR_PREFIX_SAME, which resulted in $wddx_size being created. If EXTR_SKIP was specified, then $wddx_size wouldn't even have been created. EXTR_OVERWRITE would have caused $size to have value "medium", and EXTR_PREFIX_ALL would result in new variables being named $wddx_color, $wddx_size, and $wddx_shape.

Note

Avertizare

Do not use extract() on untrusted data, like user input (i.e. $_GET, $_FILES, etc.). If you do, for example if you want to temporarily run old code that relied on register_globals, make sure you use one of the non-overwriting flags values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.

Nota:

If you still have register_globals and it is turned on, if you use extract() on $_FILES and specify EXTR_SKIP, you may be surprised at the results.

Avertizare

This is not recommended practice and is only documented here for completeness. The use of register_globals is deprecated and calling extract() on untrusted data such as $_FILES is, as noted above, a potential security risk. If you encounter this issue, it means that you are using at least two poor coding practices.

<?php

/* Suppose that $testfile is the name of a file upload input
   and that register_globals is turned on. */

var_dump($testfile);
extract($_FILES, EXTR_SKIP);
var_dump($testfile);
var_dump($testfile['tmp_name']);

?>
You might expect to see something like the following:
string(14) "/tmp/phpgCCPX8"
array(5) {
  ["name"]=>
  string(10) "somefile.txt"
  ["type"]=>
  string(24) "application/octet-stream"
  ["tmp_name"]=>
  string(14) "/tmp/phpgCCPX8"
  ["error"]=>
  int(0)
  ["size"]=>
  int(4208)
}
string(14) "/tmp/phpgCCPX8"
However, you would instead see something like this:
string(14) "/tmp/phpgCCPX8"
string(14) "/tmp/phpgCCPX8"
string(1) "/"

This is due to the fact that since register_globals is turned on, $testfile already exists in the global scope when extract() is called. And since EXTR_SKIP is specified, $testfile is not overwritten with the contents of the $_FILES array so $testfile remains a string. Because strings may be accessed using array syntax and the non-numeric string tmp_name is interpreted as 0, PHP sees $testfile['tmp_name'] as $testfile[0].

A se vedea ?i

  • compact() - Create array containing variables and their values
  • list() - Assign variables as if they were an array

end
in_array
Func?ii ale tablourilor (Array)


Checks if a value exists in an array

extract
key_exists
Func?ii ale tablourilor (Array)
PHP Manual

in_array

(PHP 4, PHP 5, PHP 7)

in_array — Checks if a value exists in an array

Descrierea

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

Searches haystack for needle using loose comparison unless strict is set.

Parametri

needle

The searched value.

Nota:

If needle is a string, the comparison is done in a case-sensitive manner.

haystack

The array.

strict

If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.

Valorile întoarse

Returns TRUE if needle is found in the array, FALSE otherwise.

Exemple

Example #1 in_array() example

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}
if (in_array("mac", $os)) {
    echo "Got mac";
}
?>

The second condition fails because in_array() is case-sensitive, so the program above will display:

Got Irix

Example #2 in_array() with strict example

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, true)) {
    echo "'12.4' found with strict check\n";
}

if (in_array(1.13, $a, true)) {
    echo "1.13 found with strict check\n";
}
?>

Exemplul de mai sus va afi?a:

1.13 found with strict check

Example #3 in_array() with an array as needle

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was found\n";
}

if (in_array(array('f', 'i'), $a)) {
    echo "'fi' was found\n";
}

if (in_array('o', $a)) {
    echo "'o' was found\n";
}
?>

Exemplul de mai sus va afi?a:

  'ph' was found
  'o' was found

A se vedea ?i

  • array_search() - Searches the array for a given value and returns the first corresponding key if successful
  • isset() - Determina daca o variabla este stabilita ?i nu este NULL
  • array_key_exists() - Checks if the given key or index exists in the array

extract
key_exists
Func?ii ale tablourilor (Array)


Pseudonim pentru array_key_exists

in_array
key
Func?ii ale tablourilor (Array)
PHP Manual

key_exists

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

key_exists — Pseudonim pentru array_key_exists()

Descrierea

Aceasta func?ie este pseudonim pentru: array_key_exists().

in_array
key
Func?ii ale tablourilor (Array)


Fetch a key from an array

key_exists
krsort
Func?ii ale tablourilor (Array)
PHP Manual

key

(PHP 4, PHP 5, PHP 7)

key — Fetch a key from an array

Descrierea

mixed key ( array &$array )

key() returns the index element of the current array position.

Parametri

array

The array.

Valorile întoarse

The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.

Exemple

Example #1 key() example

<?php
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => 'grape',
    'fruit4' => 'apple',
    'fruit5' => 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array).'<br />';
    }
    next($array);
}
?>

Exemplul de mai sus va afi?a:

fruit1<br />
fruit4<br />
fruit5<br />

A se vedea ?i

  • current() - Return the current element in an array
  • next() - Advance the internal array pointer of an array
  • foreach

key_exists
krsort
Func?ii ale tablourilor (Array)


Sort an array by key in reverse order

key
ksort
Func?ii ale tablourilor (Array)
PHP Manual

krsort

(PHP 4, PHP 5, PHP 7)

krsort — Sort an array by key in reverse order

Descrierea

bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.

Parametri

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 krsort() example

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

Exemplul de mai sus va afi?a:

d = lemon
c = apple
b = banana
a = orange

A se vedea ?i

  • arsort() - Sort an array in reverse order and maintain index association
  • ksort() - Sort an array by key
  • Compara?ia func?iilor de sortare a tablourilor

key
ksort
Func?ii ale tablourilor (Array)


Sort an array by key

krsort
list
Func?ii ale tablourilor (Array)
PHP Manual

ksort

(PHP 4, PHP 5, PHP 7)

ksort — Sort an array by key

Descrierea

bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.

Parametri

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ksort() example

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

Exemplul de mai sus va afi?a:

a = orange
b = banana
c = apple
d = lemon

A se vedea ?i

  • asort() - Sort an array and maintain index association
  • Compara?ia func?iilor de sortare a tablourilor

krsort
list
Func?ii ale tablourilor (Array)


Assign variables as if they were an array

ksort
natcasesort
Func?ii ale tablourilor (Array)
PHP Manual

list

(PHP 4, PHP 5, PHP 7)

list — Assign variables as if they were an array

Descrierea

array list ( mixed $var1 [, mixed $... ] )

Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.

Nota:

list() only works on numerical arrays and assumes the numerical indices start at 0.

Avertizare

In PHP 5, list() assigns the values starting with the right-most parameter. In PHP 7, list() starts with the left-most parameter.

If you are using plain variables, you don't have to worry about this. But if you are using arrays with indices you usually expect the order of the indices in the array the same you wrote in the list() from left to right, which is not the case in PHP 5, as it's assigned in the reverse order.

Generally speaking, it is advisable to avoid relying on a specific order of operation, as this may change again in the future.

Avertizare

Modification of the array during list() execution (e.g. using list($a, $b) = $b) results in undefined behavior.

Parametri

var1

A variable.

Valorile întoarse

Returns the assigned array.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | The order that the assignment operations are performed in has changed.
7.0.0 | list() expressions can no longer be completely empty.
7.0.0 | Strings can no longer be unpacked.

Exemple

Example #1 list() examples

<?php

$info = array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";

// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";

// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
?>

Example #2 An example use of list()

<table>
 <tr>
  <th>Employee name</th>
  <th>Salary</th>
 </tr>

<?php
$result = $pdo->query("SELECT id, name, salary FROM employees");
while (list($id, $name, $salary) = $result->fetch(PDO::FETCH_NUM)) {
    echo " <tr>\n" .
          "  <td><a href=\"info.php?id=$id\">$name</a></td>\n" .
          "  <td>$salary</td>\n" .
          " </tr>\n";
}

?>

</table>

Example #3 Using nested list()

<?php

list($a, list($b, $c)) = array(1, array(2, 3));

var_dump($a, $b, $c);

?>
int(1)
int(2)
int(3)

Example #4 Using list() with array indices

<?php

$info = array('coffee', 'brown', 'caffeine');

list($a[0], $a[1], $a[2]) = $info;

var_dump($a);

?>

Gives the following output (note the order of the elements compared in which order they were written in the list() syntax):

Exemplul de mai sus va afi?a în PHP 7:

array(3) {
  [0]=>
  string(6) "coffee"
  [1]=>
  string(5) "brown"
  [2]=>
  string(8) "caffeine"
}

Exemplul de mai sus va afi?a în PHP 5:

array(3) {
  [2]=>
  string(8) "caffeine"
  [1]=>
  string(5) "brown"
  [0]=>
  string(6) "coffee"
}

Example #5 list() and order of index definitions

The order in which the indices of the array to be consumed by list() are defined is irrelevant.

<?php
$foo = array(2 => 'a', 'foo' => 'b', 0 => 'c');
$foo[1] = 'd';
list($x, $y, $z) = $foo;
var_dump($foo, $x, $y, $z);

Gives the following output (note the order of the elements compared in which order they were written in the list() syntax):

array(4) {
  [2]=>
  string(1) "a"
  ["foo"]=>
  string(1) "b"
  [0]=>
  string(1) "c"
  [1]=>
  string(1) "d"
}
string(1) "c"
string(1) "d"
string(1) "a"

A se vedea ?i

  • each() - Return the current key and value pair from an array and advance the array cursor
  • array() - Creeaza un tablou
  • extract() - Import variables into the current symbol table from an array

ksort
natcasesort
Func?ii ale tablourilor (Array)


Sort an array using a case insensitive "natural order" algorithm

list
natsort
Func?ii ale tablourilor (Array)
PHP Manual

natcasesort

(PHP 4, PHP 5, PHP 7)

natcasesort — Sort an array using a case insensitive "natural order" algorithm

Descrierea

bool natcasesort ( array &$array )

natcasesort() is a case insensitive version of natsort().

This function 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".

Nota:

If two members compare as equal, their relative order in the sorted array is undefined.

Parametri

array

The input array.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 natcasesort() example

<?php
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

sort($array1);
echo "Standard sorting\n";
print_r($array1);

natcasesort($array2);
echo "\nNatural order sorting (case-insensitive)\n";
print_r($array2);
?>

Exemplul de mai sus va afi?a:

Standard sorting
Array
(
    [0] => IMG0.png
    [1] => IMG3.png
    [2] => img1.png
    [3] => img10.png
    [4] => img12.png
    [5] => img2.png
)

Natural order sorting (case-insensitive)
Array
(
    [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.

A se vedea ?i

  • natsort() - Sort an array using a "natural order" algorithm
  • Compara?ia func?iilor de sortare a tablourilor
  • strnatcmp() - String comparisons using a "natural order" algorithm
  • strnatcasecmp() - Case insensitive string comparisons using a "natural order" algorithm

list
natsort
Func?ii ale tablourilor (Array)


Sort an array using a "natural order" algorithm

natcasesort
next
Func?ii ale tablourilor (Array)
PHP Manual

natsort

(PHP 4, PHP 5, PHP 7)

natsort — Sort an array using a "natural order" algorithm

Descrierea

bool natsort ( array &$array )

This function 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 sort()) can be seen in the example below.

Nota:

If two members compare as equal, their relative order in the sorted array is undefined.

Parametri

array

The input array.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.2.10 | Zero padded numeric strings (e.g., '00005') now essentially ignore the 0 padding.

Exemple

Example #1 natsort() examples demonstrating basic usage

<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

asort($array1);
echo "Standard sorting\n";
print_r($array1);

natsort($array2);
echo "\nNatural order sorting\n";
print_r($array2);
?>

Exemplul de mai sus va afi?a:

Standard sorting
Array
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

Example #2 natsort() examples demonstrating potential gotchas

<?php
echo "Negative numbers\n";
$negative = array('-5','3','-2','0','-1000','9','1');
print_r($negative);
natsort($negative);
print_r($negative);

echo "Zero padding\n";
$zeros = array('09', '8', '10', '009', '011', '0');
print_r($zeros);
natsort($zeros);
print_r($zeros);
?>

Exemplul de mai sus va afi?a:

Negative numbers
Array
(
    [0] => -5
    [1] => 3
    [2] => -2
    [3] => 0
    [4] => -1000
    [5] => 9
    [6] => 1
)
Array
(
    [2] => -2
    [0] => -5
    [4] => -1000
    [3] => 0
    [6] => 1
    [1] => 3
    [5] => 9
)

Zero padding
Array
(
    [0] => 09
    [1] => 8
    [2] => 10
    [3] => 009
    [4] => 011
    [5] => 0
)
Array
(
    [5] => 0
    [1] => 8
    [3] => 009
    [0] => 09
    [2] => 10
    [4] => 011
)

A se vedea ?i

  • natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • Compara?ia func?iilor de sortare a tablourilor
  • strnatcmp() - String comparisons using a "natural order" algorithm
  • strnatcasecmp() - Case insensitive string comparisons using a "natural order" algorithm

natcasesort
next
Func?ii ale tablourilor (Array)


Advance the internal array pointer of an array

natsort
pos
Func?ii ale tablourilor (Array)
PHP Manual

next

(PHP 4, PHP 5, PHP 7)

next — Advance the internal array pointer of an array

Descrierea

mixed next ( array &$array )

next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element value. That means it returns the next array value and advances the internal array pointer by one.

Parametri

array

The array being affected.

Valorile întoarse

Returns the array value in the next place that's pointed to by the internal array pointer, or FALSE if there are no more elements.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Exemple

Example #1 Example use of next() and friends

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
?>

Note

Nota: You won't be able to distinguish the end of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.

A se vedea ?i

  • current() - Return the current element in an array
  • end() - Set the internal pointer of an array to its last element
  • prev() - Rewind the internal array pointer
  • reset() - Set the internal pointer of an array to its first element
  • each() - Return the current key and value pair from an array and advance the array cursor

natsort
pos
Func?ii ale tablourilor (Array)


Pseudonim pentru current

next
prev
Func?ii ale tablourilor (Array)
PHP Manual

pos

(PHP 4, PHP 5, PHP 7)

pos — Pseudonim pentru current()

Descrierea

Aceasta func?ie este pseudonim pentru: current()

next
prev
Func?ii ale tablourilor (Array)


Rewind the internal array pointer

pos
range
Func?ii ale tablourilor (Array)
PHP Manual

prev

(PHP 4, PHP 5, PHP 7)

prev — Rewind the internal array pointer

Descrierea

mixed prev ( array &$array )

Rewind the internal array pointer.

prev() behaves just like next(), except it rewinds the internal array pointer one place instead of advancing it.

Parametri

array

The input array.

Valorile întoarse

Returns the array value in the previous place that's pointed to by the internal array pointer, or FALSE if there are no more elements.

Exemple

Example #1 Example use of prev() and friends

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
?>

Note

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Nota: You won't be able to distinguish the beginning of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.

A se vedea ?i

  • current() - Return the current element in an array
  • end() - Set the internal pointer of an array to its last element
  • next() - Advance the internal array pointer of an array
  • reset() - Set the internal pointer of an array to its first element
  • each() - Return the current key and value pair from an array and advance the array cursor

pos
range
Func?ii ale tablourilor (Array)


Create an array containing a range of elements

prev
reset
Func?ii ale tablourilor (Array)
PHP Manual

range

(PHP 4, PHP 5, PHP 7)

range — Create an array containing a range of elements

Descrierea

array range ( mixed $start , mixed $end [, number $step = 1 ] )

Create an array containing a range of elements.

Parametri

start

First value of the sequence.

end

The sequence is ended upon reaching the end value.

step

If a step value is given, it will be used as the increment between elements in the sequence. step should be given as a positive number. If not specified, step will default to 1.

Valorile întoarse

Returns an array of elements from start to end, inclusive.

Exemple

Example #1 range() examples

<?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $number) {
    echo $number;
}

// The step parameter
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $number) {
    echo $number;
}

// Usage of character sequences
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $letter) {
    echo $letter;
}
// array('c', 'b', 'a');
foreach (range('c', 'a') as $letter) {
    echo $letter;
}
?>

Note

Nota:

Character sequence values are limited to a length of one. If a length greater than one is entered, only the first character is used.

A se vedea ?i

  • shuffle() - Shuffle an array
  • array_fill() - Completeaza un tablou cu valori
  • foreach

prev
reset
Func?ii ale tablourilor (Array)


Set the internal pointer of an array to its first element

range
rsort
Func?ii ale tablourilor (Array)
PHP Manual

reset

(PHP 4, PHP 5, PHP 7)

reset — Set the internal pointer of an array to its first element

Descrierea

mixed reset ( array &$array )

reset() rewinds array's internal pointer to the first element and returns the value of the first array element.

Parametri

array

The input array.

Valorile întoarse

Returns the value of the first array element, or FALSE if the array is empty.

Exemple

Example #1 reset() example

<?php

$array = array('step one', 'step two', 'step three', 'step four');

// by default, the pointer is on the first element
echo current($array) . "<br />\n"; // "step one"

// skip two steps
next($array);
next($array);
echo current($array) . "<br />\n"; // "step three"

// reset pointer, start again on step one
reset($array);
echo current($array) . "<br />\n"; // "step one"

?>

A se vedea ?i

  • current() - Return the current element in an array
  • each() - Return the current key and value pair from an array and advance the array cursor
  • end() - Set the internal pointer of an array to its last element
  • next() - Advance the internal array pointer of an array
  • prev() - Rewind the internal array pointer

range
rsort
Func?ii ale tablourilor (Array)


Sort an array in reverse order

reset
shuffle
Func?ii ale tablourilor (Array)
PHP Manual

rsort

(PHP 4, PHP 5, PHP 7)

rsort — Sort an array in reverse order

Descrierea

bool rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

This function sorts an array in reverse order (highest to lowest).

Nota:

If two members compare as equal, their relative order in the sorted array is undefined.

Parametri

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 rsort() example

<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

Exemplul de mai sus va afi?a:

0 = orange
1 = lemon
2 = banana
3 = apple

The fruits have been sorted in reverse alphabetical order.

Note

Nota: Aceasta func?ie atribuie chei noi elementelor din array. Ea va elimina cheile existente, care posibil au fost atribuite, în loc doar sa rearanjeze cheile.

A se vedea ?i

  • arsort() - Sort an array in reverse order and maintain index association
  • krsort() - Sort an array by key in reverse order
  • Compara?ia func?iilor de sortare a tablourilor

reset
shuffle
Func?ii ale tablourilor (Array)


Shuffle an array

rsort
sizeof
Func?ii ale tablourilor (Array)
PHP Manual

shuffle

(PHP 4, PHP 5, PHP 7)

shuffle — Shuffle an array

Descrierea

bool shuffle ( array &$array )

This function shuffles (randomizes the order of the elements in) an array. It uses a pseudo random number generator that is not suitable for cryptographic purposes.

Nota:

If two members compare as equal, their relative order in the sorted array is undefined.

Parametri

array

The array.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
7.1.0 | The internal randomization algorithm has been changed to use the » Mersenne Twister Random Number Generator instead of the libc rand function.

Exemple

Example #1 shuffle() example

<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
    echo "$number ";
}
?>

Note

Nota: Aceasta func?ie atribuie chei noi elementelor din array. Ea va elimina cheile existente, care posibil au fost atribuite, în loc doar sa rearanjeze cheile.

A se vedea ?i

  • array_rand() - Pick one or more random entries out of an array
  • Compara?ia func?iilor de sortare a tablourilor

rsort
sizeof
Func?ii ale tablourilor (Array)


Pseudonim pentru count

shuffle
sort
Func?ii ale tablourilor (Array)
PHP Manual

sizeof

(PHP 4, PHP 5, PHP 7)

sizeof — Pseudonim pentru count()

Descrierea

Aceasta func?ie este pseudonim pentru: count().

shuffle
sort
Func?ii ale tablourilor (Array)


Sort an array

sizeof
uasort
Func?ii ale tablourilor (Array)
PHP Manual

sort

(PHP 4, PHP 5, PHP 7)

sort — Sort an array

Descrierea

bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.

Nota:

If two members compare as equal, their relative order in the sorted array is undefined.

Parametri

array

The input array.

sort_flags

The optional second parameter sort_flags may be used to modify the sorting behavior using these values:

Sorting type flags:

  • SORT_REGULAR - compare items normally (don't change types)
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()
  • SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
  • SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added support for SORT_NATURAL and SORT_FLAG_CASE as sort_flags
5.0.2 | Added SORT_LOCALE_STRING

Exemple

Example #1 sort() example

<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

Exemplul de mai sus va afi?a:

fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

The fruits have been sorted in alphabetical order.

Example #2 sort() example using case-insensitive natural ordering

<?php

$fruits = array(
    "Orange1", "orange2", "Orange3", "orange20"
);
sort($fruits, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

Exemplul de mai sus va afi?a:

fruits[0] = Orange1
fruits[1] = orange2
fruits[2] = Orange3
fruits[3] = orange20

The fruits have been sorted like natcasesort().

Note

Nota: Aceasta func?ie atribuie chei noi elementelor din array. Ea va elimina cheile existente, care posibil au fost atribuite, în loc doar sa rearanjeze cheile.

Nota: Like most PHP sorting functions, sort() uses an implementation of » Quicksort. The pivot is chosen in the middle of the partition resulting in an optimal time for already sorted arrays. This is however an implementation detail you shouldn't rely on.

Avertizare

Be careful when sorting arrays with mixed types values because sort() can produce unpredictable results.

A se vedea ?i

  • asort() - Sort an array and maintain index association
  • Compara?ia func?iilor de sortare a tablourilor

sizeof
uasort
Func?ii ale tablourilor (Array)


Sort an array with a user-defined comparison function and maintain index association

sort
uksort
Func?ii ale tablourilor (Array)
PHP Manual

uasort

(PHP 4, PHP 5, PHP 7)

uasort — Sort an array with a user-defined comparison function and maintain index association

Descrierea

bool uasort ( array &$array , callable $value_compare_func )

This function sorts an array such that array indices maintain their correlation with the array elements 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.

Nota:

If two members compare as equal, their relative order in the sorted array is undefined.

Parametri

array

The input array.

value_compare_func

See usort() and uksort() for examples of user-defined comparison functions.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Basic 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);
print_r($array);

// Sort and print the resulting array
uasort($array, 'cmp');
print_r($array);
?>

Exemplul de mai sus va afi?a:

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
)

A se vedea ?i

  • usort() - Sort an array by values using a user-defined comparison function
  • Compara?ia func?iilor de sortare a tablourilor

sort
uksort
Func?ii ale tablourilor (Array)


Sort an array by keys using a user-defined comparison function

uasort
usort
Func?ii ale tablourilor (Array)
PHP Manual

uksort

(PHP 4, PHP 5, PHP 7)

uksort — Sort an array by keys using a user-defined comparison function

Descrierea

bool uksort ( array &$array , callable $key_compare_func )

uksort() will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

Nota:

If two members compare as equal, their relative order in the sorted array is undefined.

Parametri

array

The input array.

key_compare_func

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 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);
}

$a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);

uksort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
?>

Exemplul de mai sus va afi?a:

an apple: 3
a banana: 4
the Earth: 2
John: 1

A se vedea ?i

  • usort() - Sort an array by values using a user-defined comparison function
  • Compara?ia func?iilor de sortare a tablourilor

uasort
usort
Func?ii ale tablourilor (Array)


Sort an array by values using a user-defined comparison function

uksort
Classes/Objects
Func?ii ale tablourilor (Array)
PHP Manual

usort

(PHP 4, PHP 5, PHP 7)

usort — Sort an array by values using a user-defined comparison function

Descrierea

bool usort ( array &$array , callable $value_compare_func )

This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

Nota:

If two members compare as equal, their relative order in the sorted array is undefined.

Nota: Aceasta func?ie atribuie chei noi elementelor din array. Ea va elimina cheile existente, care posibil au fost atribuite, în loc doar sa rearanjeze cheile.

Parametri

array

The input array.

value_compare_func

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
Precautie

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 usort() example

<?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 => $value) {
    echo "$key: $value\n";
}
?>

Exemplul de mai sus va afi?a:

0: 1
1: 2
2: 3
3: 5
4: 6

Nota:

Obviously in this trivial case the sort() function would be more appropriate.

Example #2 usort() example using multi-dimensional array

<?php
function cmp($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

while (list($key, $value) = each($fruits)) {
    echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>

When sorting a multi-dimensional array, $a and $b contain references to the first index of the array.

Exemplul de mai sus va afi?a:

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

Example #3 usort() example using a member function of an object

<?php
class TestObj {
    var $name;

    function TestObj($name)
    {
        $this->name = $name;
    }

    /* This is the static comparing function: */
    static 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");

usort($a, array("TestObj", "cmp_obj"));

foreach ($a as $item) {
    echo $item->name . "\n";
}
?>

Exemplul de mai sus va afi?a:

b
c
d

Example #4 usort() example using a closure to sort a multi-dimensional array

<?php
$array[0] = array('key_a' => 'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}

usort($array, build_sorter('key_b'));

foreach ($array as $item) {
    echo $item['key_a'] . ', ' . $item['key_b'] . "\n";
}
?>

Exemplul de mai sus va afi?a:

y, a
x, b
z, c

A se vedea ?i

  • uasort() - Sort an array with a user-defined comparison function and maintain index association
  • Compara?ia func?iilor de sortare a tablourilor

uksort
Classes/Objects
Func?ii ale tablourilor (Array)


Class/Object Information

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Func?ii ale claselor/obiectelor
    • __autoload — Attempt to load undefined class
    • call_user_method_array — Call a user method given with an array of parameters
    • call_user_method — Call a user method on an specific object
    • class_alias — Creates an alias for a class
    • class_exists — Verifica daca clasa a fost definita
    • get_called_class — the "Late Static Binding" class name
    • get_class_methods — Gets the class methods' names
    • get_class_vars — Get the default properties of the class
    • get_class — Returns the name of the class of an object
    • get_declared_classes — Returns an array with the name of the defined classes
    • get_declared_interfaces — Returns an array of all declared interfaces
    • get_declared_traits — Returns an array of all declared traits
    • get_object_vars — Gets the properties of the given object
    • get_parent_class — Retrieves the parent class name for object or class
    • interface_exists — Checks if the interface has been defined
    • is_a — Checks if the object is of this class or has this class as one of its parents
    • is_subclass_of — Checks if the object has this class as one of its parents or implements it.
    • method_exists — Checks if the class method exists
    • property_exists — Checks if the object or class has a property
    • trait_exists — Checks if the trait exists
usort
Introducere
Extensii referitoare la variabile ?i tipuri


Introducere

These functions allow you to obtain information about classes and instance objects. You can obtain the name of the class to which an object belongs, as well as its member properties and methods. Using these functions, you can find out not only the class membership of an object, but also its parentage (i.e. what class is the object class extending).

Please see the Objects section of the manual for a detailed explanation of how classes and objects are implemented and used in PHP.

Classes/Objects
Instalarea / configurarea
Classes/Objects


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Classes/Objects


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
Classes/Objects


Exemple

In this example, we first define a base class and an extension of the class. The base class describes a general vegetable, whether it is edible or not and what is its color. The subclass Spinach adds a method to cook it and another to find out if it is cooked.

Example #1 classes.inc

<?php

// base class with member properties and methods
class Vegetable {

   var $edible;
   var $color;

   function __construct($edible, $color="green")
   {
       $this->edible = $edible;
       $this->color = $color;
   }

   function is_edible()
   {
       return $this->edible;
   }

   function what_color()
   {
       return $this->color;
   }

} // end of class Vegetable

// extends the base class
class Spinach extends Vegetable {

   var $cooked = false;

   function __construct()
   {
       parent::__construct(true, "green");
   }

   function cook_it()
   {
       $this->cooked = true;
   }

   function is_cooked()
   {
       return $this->cooked;
   }

} // end of class Spinach

?>

We then instantiate 2 objects from these classes and print out information about them, including their class parentage. We also define some utility functions, mainly to have a nice printout of the variables.

Example #2 test_script.php

<pre>
<?php

include "classes.inc";

// utility functions

function print_vars($obj)
{
foreach (get_object_vars($obj) as $prop => $val) {
    echo "\t$prop = $val\n";
}
}

function print_methods($obj)
{
$arr = get_class_methods(get_class($obj));
foreach ($arr as $method) {
    echo "\tfunction $method()\n";
}
}

function class_parentage($obj, $class)
{
if (is_subclass_of($GLOBALS[$obj], $class)) {
    echo "Object $obj belongs to class " . get_class($GLOBALS[$obj]);
    echo ", a subclass of $class\n";
} else {
    echo "Object $obj does not belong to a subclass of $class\n";
}
}

// instantiate 2 objects

$veggie = new Vegetable(true, "blue");
$leafy = new Spinach();

// print out information about objects
echo "veggie: CLASS " . get_class($veggie) . "\n";
echo "leafy: CLASS " . get_class($leafy);
echo ", PARENT " . get_parent_class($leafy) . "\n";

// show veggie properties
echo "\nveggie: Properties\n";
print_vars($veggie);

// and leafy methods
echo "\nleafy: Methods\n";
print_methods($leafy);

echo "\nParentage:\n";
class_parentage("leafy", "Spinach");
class_parentage("leafy", "Vegetable");
?>
</pre>

One important thing to note in the example above is that the object $leafy is an instance of the class Spinach which is a subclass of Vegetable, therefore the last part of the script above will output:

   [...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach, a subclass of Vegetable

Constante predefinite
Func?ii ale claselor/obiectelor
Classes/Objects


Func?ii ale claselor/obiectelor

Cuprins

  • __autoload — Attempt to load undefined class
  • call_user_method_array — Call a user method given with an array of parameters
  • call_user_method — Call a user method on an specific object
  • class_alias — Creates an alias for a class
  • class_exists — Verifica daca clasa a fost definita
  • get_called_class — the "Late Static Binding" class name
  • get_class_methods — Gets the class methods' names
  • get_class_vars — Get the default properties of the class
  • get_class — Returns the name of the class of an object
  • get_declared_classes — Returns an array with the name of the defined classes
  • get_declared_interfaces — Returns an array of all declared interfaces
  • get_declared_traits — Returns an array of all declared traits
  • get_object_vars — Gets the properties of the given object
  • get_parent_class — Retrieves the parent class name for object or class
  • interface_exists — Checks if the interface has been defined
  • is_a — Checks if the object is of this class or has this class as one of its parents
  • is_subclass_of — Checks if the object has this class as one of its parents or implements it.
  • method_exists — Checks if the class method exists
  • property_exists — Checks if the object or class has a property
  • trait_exists — Checks if the trait exists
Exemple
__autoload
Classes/Objects


Attempt to load undefined class

Func?ii ale claselor/obiectelor
call_user_method_array
Func?ii ale claselor/obiectelor
PHP Manual

__autoload

(PHP 5, PHP 7)

__autoload — Attempt to load undefined class

Descrierea

void __autoload ( string $class )

You can define this function to enable classes autoloading.

Parametri

class

Name of the class to load

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • spl_autoload_register() - Register given function as __autoload() implementation

Func?ii ale claselor/obiectelor
call_user_method_array
Func?ii ale claselor/obiectelor


Call a user method given with an array of parameters

__autoload
call_user_method
Func?ii ale claselor/obiectelor
PHP Manual

call_user_method_array

(PHP 4 >= 4.0.5, PHP 5)

call_user_method_array — Call a user method given with an array of parameters

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 4.1.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • call_user_func_array()

Descrierea

mixed call_user_method_array ( string $method_name , object &$obj , array $params )

Parametri

method_name

The method name being called.

obj

The object that method_name is being called on.

params

An array of parameters.

Exemple

Example #1 call_user_method_array() alternative

<?php
call_user_func_array(array($obj, $method_name), $params);
?>

A se vedea ?i

  • 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
Func?ii ale claselor/obiectelor


Call a user method on an specific object

call_user_method_array
class_alias
Func?ii ale claselor/obiectelor
PHP Manual

call_user_method

(PHP 4, PHP 5)

call_user_method — Call a user method on an specific object

Avertizare

Aceasta func?ie este ÎNVECHITA începând cu PHP 4.1.0 ?i ELIMINATA în PHP 7.0.0.

Variante alternative pentru aceasta func?ie sunt:

  • call_user_func()

Descrierea

mixed call_user_method ( string $method_name , object &$obj [, mixed $parameter [, mixed $... ]] )

Parametri

method_name

The method name being called.

obj

The object that method_name is being called on.

parameter ...

The optional parameters.

Exemple

Example #1 call_user_method() alternative

<?php
call_user_func(array($obj, $method_name), $parameter /* , ... */);
?>

A se vedea ?i

  • 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
Func?ii ale claselor/obiectelor


Creates an alias for a class

call_user_method
class_exists
Func?ii ale claselor/obiectelor
PHP Manual

class_alias

(PHP 5 >= 5.3.0, PHP 7)

class_alias — Creates an alias for a class

Descrierea

bool class_alias ( string $original , string $alias [, bool $autoload = TRUE ] )

Creates an alias named alias based on the user defined class original. The aliased class is exactly the same as the original class.

Parametri

original

The original class.

alias

The alias name for the class.

autoload

Whether to autoload if the original class is not found.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

A se vedea ?i

  • get_parent_class() - Retrieves the parent class name for object or class
  • is_subclass_of() - Checks if the object has this class as one of its parents or implements it.

call_user_method
class_exists
Func?ii ale claselor/obiectelor


Verifica daca clasa a fost definita

class_alias
get_called_class
Func?ii ale claselor/obiectelor
PHP Manual

class_exists

(PHP 4, PHP 5, PHP 7)

class_exists — Verifica daca clasa a fost definita

Descrierea

bool class_exists ( string $class_name [, bool $autoload = true ] )

Aceasta func?ie verifica daca clasa data ca parametru a fost definita sau nu.

Parametri

class_name

Numele clasei. Numele este cautat în maniera case-insensitive (ignora capitalizarea literelor).

autoload

Indica daca __autoload trebuie sa fie apelat implicit.

Valorile întoarse

Întoarce TRUE daca class_name e o clasa definita, FALSE în caz contrar.

Istoricul schimbarilor

Versiune | Descriere
5.0.2 | Nu mai întoarce TRUE pentru interfe?e definite. Folosi?i interface_exists().

Exemple

Example #1 Exemplu class_exists()

<?php
// Check that the class exists before trying to use it
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>

Example #2 Exemplu cu parametrul autoload

<?php
function __autoload($class)
{
    include($class . '.php');

    // Check to see whether the include declared the class
    if (!class_exists($class, false)) {
        trigger_error("Unable to load class: $class", E_USER_WARNING);
    }
}

if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>

A se vedea ?i

  • function_exists() - Return TRUE if the given function has been defined
  • interface_exists() - Checks if the interface has been defined
  • get_declared_classes() - Returns an array with the name of the defined classes

class_alias
get_called_class
Func?ii ale claselor/obiectelor


the "Late Static Binding" class name

class_exists
get_class_methods
Func?ii ale claselor/obiectelor
PHP Manual

get_called_class

(PHP 5 >= 5.3.0, PHP 7)

get_called_class — the "Late Static Binding" class name

Descrierea

string get_called_class ( void )

Gets the name of the class the static method is called in.

Valorile întoarse

Returns the class name. Returns FALSE if called from outside a class.

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a:

string(3) "foo"
string(3) "bar"

A se vedea ?i

  • get_parent_class() - Retrieves the parent class name for object or class
  • get_class() - Returns the name of the class of an object
  • is_subclass_of() - Checks if the object has this class as one of its parents or implements it.

class_exists
get_class_methods
Func?ii ale claselor/obiectelor


Gets the class methods' names

get_called_class
get_class_vars
Func?ii ale claselor/obiectelor
PHP Manual

get_class_methods

(PHP 4, PHP 5, PHP 7)

get_class_methods — Gets the class methods' names

Descrierea

array get_class_methods ( mixed $class_name )

Gets the class methods names.

Parametri

class_name

The class name or an object instance

Valorile întoarse

Returns an array of method names defined for the class specified by class_name. In case of an error, it returns NULL.

Exemple

Example #1 get_class_methods() example

<?php

class myclass {
    // constructor
    function myclass()
    {
        return(true);
    }

    // method 1
    function myfunc1()
    {
        return(true);
    }

    // method 2
    function myfunc2()
    {
        return(true);
    }
}

$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());

foreach ($class_methods as $method_name) {
    echo "$method_name\n";
}

?>

Exemplul de mai sus va afi?a:

myclass
myfunc1
myfunc2

A se vedea ?i

  • get_class() - Returns the name of the class of an object
  • get_class_vars() - Get the default properties of the class
  • get_object_vars() - Gets the properties of the given object

get_called_class
get_class_vars
Func?ii ale claselor/obiectelor


Get the default properties of the class

get_class_methods
get_class
Func?ii ale claselor/obiectelor
PHP Manual

get_class_vars

(PHP 4, PHP 5, PHP 7)

get_class_vars — Get the default properties of the class

Descrierea

array get_class_vars ( string $class_name )

Get the default properties of the given class.

Parametri

class_name

The class name

Valorile întoarse

Returns an associative array of declared properties visible from the current scope, with their default value. The resulting array elements are in the form of varname => value. In case of an error, it returns FALSE.

Istoricul schimbarilor

Versiune | Descriere
5.0.3 | get_class_vars() will only return the properties that can be accessed from the current scope.
5.0.2 | Calling get_class_vars() will now expose all the properties as an array, unlike previous behaviour where protected and private properties were prefixed with nul bytes.
5.0.1 | Calling get_class_vars() will expose all properties, as when converting an object to a class.

Exemple

Example #1 get_class_vars() example

<?php

class myclass {

    var $var1; // this has no default value...
    var $var2 = "xyz";
    var $var3 = 100;
    private $var4;

    // constructor
    function __construct() {
        // change some properties
        $this->var1 = "foo";
        $this->var2 = "bar";
        return true;
    }

}

$my_class = new myclass();

$class_vars = get_class_vars(get_class($my_class));

foreach ($class_vars as $name => $value) {
    echo "$name : $value\n";
}

?>

Exemplul de mai sus va afi?a:

var1 :
var2 : xyz
var3 : 100

Example #2 get_class_vars() and scoping behaviour

<?php
function format($array)
{
    return implode('|', array_keys($array)) . "\r\n";
}

class TestCase
{
    public $a    = 1;
    protected $b = 2;
    private $c   = 3;

    public static function expose()
    {
        echo format(get_class_vars(__CLASS__));
    }
}

TestCase::expose();
echo format(get_class_vars('TestCase'));
?>

Exemplul de mai sus va afi?a:

// 5.0.0
a| * b| TestCase c
a| * b| TestCase c

// 5.0.1 - 5.0.2
a|b|c
a|b|c

// 5.0.3 +
a|b|c
a

A se vedea ?i

  • get_class_methods() - Gets the class methods' names
  • get_object_vars() - Gets the properties of the given object

get_class_methods
get_class
Func?ii ale claselor/obiectelor


Returns the name of the class of an object

get_class_vars
get_declared_classes
Func?ii ale claselor/obiectelor
PHP Manual

get_class

(PHP 4, PHP 5, PHP 7)

get_class — Returns the name of the class of an object

Descrierea

string get_class ([ object $object = NULL ] )

Gets the name of the class of the given object.

Parametri

object

The tested object. This parameter may be omitted when inside a class.

Valorile întoarse

Returns the name of the class of which object is an instance. Returns FALSE if object is not an object.

If object is omitted when inside a class, the name of that class is returned.

If the object is an instance of a class which exists in a namespace, the qualified namespaced name of that class is returned.

Erori/Excep?ii

If get_class() is called with anything other than an object, an E_WARNING level error is raised.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | NULL became the default value for object, so passing NULL to object now has the same result as not passing any value.

Exemple

Example #1 Using get_class()

<?php

class foo {
    function name()
    {
        echo "My name is " , get_class($this) , "\n";
    }
}

// create an object
$bar = new foo();

// external call
echo "Its name is " , get_class($bar) , "\n";

// internal call
$bar->name();

?>

Exemplul de mai sus va afi?a:

Its name is foo
My name is foo

Example #2 Using get_class() in superclass

<?php

abstract class bar {
    public function __construct()
    {
        var_dump(get_class($this));
        var_dump(get_class());
    }
}

class foo extends bar {
}

new foo;

?>

Exemplul de mai sus va afi?a:

string(3) "foo"
string(3) "bar"

Example #3 Using get_class() with namespaced classes

<?php

namespace Foo\Bar;

class Baz {
    public function __construct()
    {

    }
}

$baz = new \Foo\Bar\Baz;

var_dump(get_class($baz));
?>

Exemplul de mai sus va afi?a:

string(11) "Foo\Bar\Baz"

A se vedea ?i

  • get_called_class() - the "Late Static Binding" class name
  • get_parent_class() - Retrieves the parent class name for object or class
  • gettype() - Ob?ine tipul unei variabile
  • is_subclass_of() - Checks if the object has this class as one of its parents or implements it.

get_class_vars
get_declared_classes
Func?ii ale claselor/obiectelor


Returns an array with the name of the defined classes

get_class
get_declared_interfaces
Func?ii ale claselor/obiectelor
PHP Manual

get_declared_classes

(PHP 4, PHP 5, PHP 7)

get_declared_classes — Returns an array with the name of the defined classes

Descrierea

array get_declared_classes ( void )

Gets the declared classes.

Valorile întoarse

Returns an array of the names of the declared classes in the current script.

Nota:

Note that depending on what extensions you have compiled or loaded into PHP, additional classes could be present. This means that you will not be able to define your own classes using these names. There is a list of predefined classes in the Predefined Classes section of the appendices.

Exemple

Example #1 get_declared_classes() example

<?php
print_r(get_declared_classes());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => stdClass
    [1] => __PHP_Incomplete_Class
    [2] => Directory
)

A se vedea ?i

  • class_exists() - Verifica daca clasa a fost definita
  • get_declared_interfaces() - Returns an array of all declared interfaces
  • get_defined_functions() - Returns an array of all defined functions

get_class
get_declared_interfaces
Func?ii ale claselor/obiectelor


Returns an array of all declared interfaces

get_declared_classes
get_declared_traits
Func?ii ale claselor/obiectelor
PHP Manual

get_declared_interfaces

(PHP 5, PHP 7)

get_declared_interfaces — Returns an array of all declared interfaces

Descrierea

array get_declared_interfaces ( void )

Gets the declared interfaces.

Valorile întoarse

Returns an array of the names of the declared interfaces in the current script.

Exemple

Example #1 get_declared_interfaces() example

<?php
print_r(get_declared_interfaces());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => Traversable
    [1] => IteratorAggregate
    [2] => Iterator
    [3] => ArrayAccess
    [4] => reflector
    [5] => RecursiveIterator
    [6] => SeekableIterator
)

A se vedea ?i

  • interface_exists() - Checks if the interface has been defined
  • get_declared_classes() - Returns an array with the name of the defined classes
  • class_implements() - Return the interfaces which are implemented by the given class or interface

get_declared_classes
get_declared_traits
Func?ii ale claselor/obiectelor


Returns an array of all declared traits

get_declared_interfaces
get_object_vars
Func?ii ale claselor/obiectelor
PHP Manual

get_declared_traits

(PHP 5 >= 5.4.0, PHP 7)

get_declared_traits — Returns an array of all declared traits

Descrierea

array get_declared_traits ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array with names of all declared traits in values. Returns NULL in case of a failure.

A se vedea ?i

  • class_uses() - Return the traits used by the given class

get_declared_interfaces
get_object_vars
Func?ii ale claselor/obiectelor


Gets the properties of the given object

get_declared_traits
get_parent_class
Func?ii ale claselor/obiectelor
PHP Manual

get_object_vars

(PHP 4, PHP 5, PHP 7)

get_object_vars — Gets the properties of the given object

Descrierea

array get_object_vars ( object $object )

Gets the accessible non-static properties of the given object according to scope.

Parametri

object

An object instance.

Valorile întoarse

Returns an associative array of defined object accessible non-static properties for the specified object in scope. If a property has not been assigned a value, it will be returned with a NULL value.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function now returns NULL if the object isn't an object. Previously FALSE was returned.

Exemple

Example #1 Use of get_object_vars()

<?php

class foo {
    private $a;
    public $b = 1;
    public $c;
    private $d;
    static $e;

    public function test() {
        var_dump(get_object_vars($this));
    }
}

$test = new foo;
var_dump(get_object_vars($test));

$test->test();

?>

Exemplul de mai sus va afi?a:

array(2) {
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
}
array(4) {
  ["a"]=>
  NULL
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
  ["d"]=>
  NULL
}

A se vedea ?i

  • get_class_methods() - Gets the class methods' names
  • get_class_vars() - Get the default properties of the class

get_declared_traits
get_parent_class
Func?ii ale claselor/obiectelor


Retrieves the parent class name for object or class

get_object_vars
interface_exists
Func?ii ale claselor/obiectelor
PHP Manual

get_parent_class

(PHP 4, PHP 5, PHP 7)

get_parent_class — Retrieves the parent class name for object or class

Descrierea

string get_parent_class ([ mixed $object ] )

Retrieves the parent class name for object or class.

Parametri

object

The tested object or class name. This parameter is optional if called from the object's method.

Valorile întoarse

Returns the name of the parent class of the class of which object is an instance or the name.

Nota:

If the object does not have a parent or the class given does not exist FALSE will be returned.

If called without parameter outside object, this function returns FALSE.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | If called without parameter outside object, this function would have returned NULL with a warning, but now returns FALSE.

Exemple

Example #1 Using get_parent_class()

<?php

class dad {
    function dad()
    {
    // implements some logic
    }
}

class child extends dad {
    function child()
    {
        echo "I'm " , get_parent_class($this) , "'s son\n";
    }
}

class child2 extends dad {
    function child2()
    {
        echo "I'm " , get_parent_class('child2') , "'s son too\n";
    }
}

$foo = new child();
$bar = new child2();

?>

Exemplul de mai sus va afi?a:

I'm dad's son
I'm dad's son too

A se vedea ?i

  • get_class() - Returns the name of the class of an object
  • is_subclass_of() - Checks if the object has this class as one of its parents or implements it.

get_object_vars
interface_exists
Func?ii ale claselor/obiectelor


Checks if the interface has been defined

get_parent_class
is_a
Func?ii ale claselor/obiectelor
PHP Manual

interface_exists

(PHP 5 >= 5.0.2, PHP 7)

interface_exists — Checks if the interface has been defined

Descrierea

bool interface_exists ( string $interface_name [, bool $autoload = true ] )

Checks if the given interface has been defined.

Parametri

interface_name

The interface name

autoload

Whether to call __autoload or not by default.

Valorile întoarse

Returns TRUE if the interface given by interface_name has been defined, FALSE otherwise.

Exemple

Example #1 interface_exists() example

<?php
// Check the interface exists before trying to use it
if (interface_exists('MyInterface')) {
    class MyClass implements MyInterface
    {
        // Methods
    }
}

?>

A se vedea ?i

  • get_declared_interfaces() - Returns an array of all declared interfaces
  • class_implements() - Return the interfaces which are implemented by the given class or interface
  • class_exists() - Verifica daca clasa a fost definita

get_parent_class
is_a
Func?ii ale claselor/obiectelor


Checks if the object is of this class or has this class as one of its parents

interface_exists
is_subclass_of
Func?ii ale claselor/obiectelor
PHP Manual

is_a

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

is_a — Checks if the object is of this class or has this class as one of its parents

Descrierea

bool is_a ( object $object , string $class_name [, bool $allow_string = FALSE ] )

Checks if the given object is of this class or has this class as one of its parents.

Parametri

object

The tested object

class_name

The class name

allow_string

If this parameter set to FALSE, string class name as object is not allowed. This also prevents from calling autoloader if the class doesn't exist.

Valorile întoarse

Returns TRUE if the object is of this class or has this class as one of its parents, FALSE otherwise.

Istoricul schimbarilor

Versiune | Descriere
5.3.9 | Added allow_string parameter
5.3.0 | This function is no longer deprecated, and will therefore no longer throw E_STRICT warnings.
5.0.0 | This function became deprecated in favour of the instanceof operator. Calling this function will result in an E_STRICT warning.

Exemple

Example #1 is_a() example

<?php
// define a class
class WidgetFactory
{
  var $oink = 'moo';
}

// create a new object
$WF = new WidgetFactory();

if (is_a($WF, 'WidgetFactory')) {
  echo "yes, \$WF is still a WidgetFactory\n";
}
?>

Example #2 Using the instanceof operator in PHP 5

<?php
if ($WF instanceof WidgetFactory) {
    echo 'Yes, $WF is a WidgetFactory';
}
?>

A se vedea ?i

  • get_class() - Returns the name of the class of an object
  • get_parent_class() - Retrieves the parent class name for object or class
  • is_subclass_of() - Checks if the object has this class as one of its parents or implements it.

interface_exists
is_subclass_of
Func?ii ale claselor/obiectelor


Checks if the object has this class as one of its parents or implements it.

is_a
method_exists
Func?ii ale claselor/obiectelor
PHP Manual

is_subclass_of

(PHP 4, PHP 5, PHP 7)

is_subclass_of — Checks if the object has this class as one of its parents or implements it.

Descrierea

bool is_subclass_of ( mixed $object , string $class_name [, bool $allow_string = TRUE ] )

Checks if the given object has the class class_name as one of its parents or implements it.

Parametri

object

A class name or an object instance. No error is generated if the class does not exist.

class_name

The class name

allow_string

If this parameter set to false, string class name as object is not allowed. This also prevents from calling autoloader if the class doesn't exist.

Valorile întoarse

This function returns TRUE if the object object, belongs to a class which is a subclass of class_name, FALSE otherwise.

Istoricul schimbarilor

Versiune | Descriere
5.3.9 | Added allow_string parameter
5.3.7 | Added support for class_name to work with interfaces
5.0.3 | You may also specify the object parameter as a string (the name of the class)

Exemple

Example #1 is_subclass_of() example

<?php
// define a class
class WidgetFactory
{
  var $oink = 'moo';
}

// define a child class
class WidgetFactory_Child extends WidgetFactory
{
  var $oink = 'oink';
}

// create a new object
$WF = new WidgetFactory();
$WFC = new WidgetFactory_Child();

if (is_subclass_of($WFC, 'WidgetFactory')) {
  echo "yes, \$WFC is a subclass of WidgetFactory\n";
} else {
  echo "no, \$WFC is not a subclass of WidgetFactory\n";
}

if (is_subclass_of($WF, 'WidgetFactory')) {
  echo "yes, \$WF is a subclass of WidgetFactory\n";
} else {
  echo "no, \$WF is not a subclass of WidgetFactory\n";
}

// usable only since PHP 5.0.3
if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) {
  echo "yes, WidgetFactory_Child is a subclass of WidgetFactory\n";
} else {
  echo "no, WidgetFactory_Child is not a subclass of WidgetFactory\n";
}
?>

Exemplul de mai sus va afi?a:

yes, $WFC is a subclass of WidgetFactory
no, $WF is not a subclass of WidgetFactory
yes, WidgetFactory_Child is a subclass of WidgetFactory

Example #2 is_subclass_of() using interface example

<?php
// Define the Interface
interface MyInterface
{
  public function MyFunction();
}

// Define the class implementation of the interface
class MyClass implements MyInterface
{
  public function MyFunction()
  {
    return "MyClass Implements MyInterface!";
  }
}

// Instantiate the object
$my_object = new MyClass;

// Works since 5.3.7

// Test using the object instance of the class
if (is_subclass_of($my_object, 'MyInterface')) {
  echo "Yes, \$my_object is a subclass of MyInterface\n";
} else {
  echo "No, \$my_object is not a subclass of MyInterface\n";
}

// Test using a string of the class name
if (is_subclass_of('MyClass', 'MyInterface')) {
  echo "Yes, MyClass is a subclass of MyInterface\n";
} else {
  echo "No, MyClass is not a subclass of MyInterface\n";
}
?>

Exemplul de mai sus va afi?a:

Yes, $my_object is a subclass of MyInterface
Yes, MyClass is a subclass of MyInterface

Note

Nota:

Utilizarea acestei func?ii va duce la utilizarea oricarui autoîncarcator înregistrat daca clasa nu este cunoscuta deja.

A se vedea ?i

  • get_class() - Returns the name of the class of an object
  • get_parent_class() - Retrieves the parent class name for object or class
  • is_a() - Checks if the object is of this class or has this class as one of its parents
  • class_parents() - Return the parent classes of the given class

is_a
method_exists
Func?ii ale claselor/obiectelor


Checks if the class method exists

is_subclass_of
property_exists
Func?ii ale claselor/obiectelor
PHP Manual

method_exists

(PHP 4, PHP 5, PHP 7)

method_exists — Checks if the class method exists

Descrierea

bool method_exists ( mixed $object , string $method_name )

Checks if the class method exists in the given object.

Parametri

object

An object instance or a class name

method_name

The method name

Valorile întoarse

Returns TRUE if the method given by method_name has been defined for the given object, FALSE otherwise.

Note

Nota:

Utilizarea acestei func?ii va duce la utilizarea oricarui autoîncarcator înregistrat daca clasa nu este cunoscuta deja.

Exemple

Example #1 method_exists() example

<?php
$directory = new Directory('.');
var_dump(method_exists($directory,'read'));
?>

Exemplul de mai sus va afi?a:

bool(true)

Example #2 Static method_exists() example

<?php
var_dump(method_exists('Directory','read'));
?>

Exemplul de mai sus va afi?a:

bool(true)

A se vedea ?i

  • function_exists() - Return TRUE if the given function has been defined
  • is_callable() - Verifica daca con?inutul unei variabile poate fi apelat în calitate de func?ie
  • class_exists() - Verifica daca clasa a fost definita

is_subclass_of
property_exists
Func?ii ale claselor/obiectelor


Checks if the object or class has a property

method_exists
trait_exists
Func?ii ale claselor/obiectelor
PHP Manual

property_exists

(PHP 5 >= 5.1.0, PHP 7)

property_exists — Checks if the object or class has a property

Descrierea

bool property_exists ( mixed $class , string $property )

This function checks if the given property exists in the specified class.

Nota:

As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.

Parametri

class

The class name or an object of the class to test for

property

The name of the property

Valorile întoarse

Returns TRUE if the property exists, FALSE if it doesn't exist or NULL in case of an error.

Note

Nota:

Utilizarea acestei func?ii va duce la utilizarea oricarui autoîncarcator înregistrat daca clasa nu este cunoscuta deja.

Nota:

The property_exists() function cannot detect properties that are magically accessible using the __get magic method.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | This function checks the existence of a property independent of accessibility.

Exemple

Example #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();

?>

A se vedea ?i

  • method_exists() - Checks if the class method exists

method_exists
trait_exists
Func?ii ale claselor/obiectelor


Checks if the trait exists

property_exists
Classkit
Func?ii ale claselor/obiectelor
PHP Manual

trait_exists

(PHP 5 >= 5.4.0, PHP 7)

trait_exists — Checks if the trait exists

Descrierea

bool trait_exists ( string $traitname [, bool $autoload ] )

Parametri

traitname

Name of the trait to check

autoload

Whether to autoload if not already loaded.

Valorile întoarse

Returns TRUE if trait exists, FALSE if not, NULL in case of an error.

property_exists
Classkit
Func?ii ale claselor/obiectelor


Classkit

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Classkit
    • 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
Introducere
Extensii referitoare la variabile ?i tipuri


Introducere

These functions allow the dynamic manipulation of PHP classes, at runtime.

Nota:

This extension has been replaced by runkit, which is not limited to class manipulation but has function manipulation, as well.

Classkit
Instalarea / configurarea
Classkit


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Classkit


Instalarea

Aceasta extensie este considerata ne-între?inuta ?i moarta. Oricum însa codul-sursa al acestei extensii este înca disponibil în PECL SVN aici: » http://svn.php.net/viewvc/pecl/classkit.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

CLASSKIT_ACC_PRIVATE (int)
Marks the method private
CLASSKIT_ACC_PROTECTED (int)
Marks the method protected
CLASSKIT_ACC_PUBLIC (int)
Marks the method public

Tipurile resurselor
Func?ii Classkit
Classkit


Func?ii Classkit

Cuprins

  • 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
Constante predefinite
classkit_import
Classkit


Import new class method definitions from a file

Func?ii Classkit
classkit_method_add
Func?ii Classkit
PHP Manual

classkit_import

(PECL classkit >= 0.3)

classkit_import — Import new class method definitions from a file

Descrierea

array classkit_import ( string $filename )

Nota: Aceasta func?ie nu poate fi utilizata pentru a manipula metoda care la moment ruleaza, sau este înlan?uita.

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

filename

The filename of the class method definitions to import

Valorile întoarse

Associative array of imported methods

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a:

foo!
bar!

A se vedea ?i

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_copy() - Copies a method from class to another

Func?ii Classkit
classkit_method_add
Func?ii Classkit


Dynamically adds a new method to a given class

classkit_import
classkit_method_copy
Func?ii Classkit
PHP Manual

classkit_method_add

(PECL classkit >= 0.1)

classkit_method_add — Dynamically adds a new method to a given class

Descrierea

bool classkit_method_add ( string $classname , string $methodname , string $args , string $code [, int $flags = CLASSKIT_ACC_PUBLIC ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

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

Nota:

This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

16

A se vedea ?i

  • 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
Func?ii Classkit


Copies a method from class to another

classkit_method_add
classkit_method_redefine
Func?ii Classkit
PHP Manual

classkit_method_copy

(PECL classkit >= 0.2)

classkit_method_copy — Copies a method from class to another

Descrierea

bool classkit_method_copy ( string $dClass , string $dMethod , string $sClass [, string $sMethod ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

foo!

A se vedea ?i

  • 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
Func?ii Classkit


Dynamically changes the code of the given method

classkit_method_copy
classkit_method_remove
Func?ii Classkit
PHP Manual

classkit_method_redefine

(PECL classkit >= 0.1)

classkit_method_redefine — Dynamically changes the code of the given method

Descrierea

bool classkit_method_redefine ( string $classname , string $methodname , string $args , string $code [, int $flags = CLASSKIT_ACC_PUBLIC ] )

Nota: Aceasta func?ie nu poate fi utilizata pentru a manipula metoda care la moment ruleaza, sau este înlan?uita.

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

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

Nota:

This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

Before: foo!
After: bar!

A se vedea ?i

  • 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
Func?ii Classkit


Dynamically removes the given method

classkit_method_redefine
classkit_method_rename
Func?ii Classkit
PHP Manual

classkit_method_remove

(PECL classkit >= 0.1)

classkit_method_remove — Dynamically removes the given method

Descrierea

bool classkit_method_remove ( string $classname , string $methodname )

Nota: Aceasta func?ie nu poate fi utilizata pentru a manipula metoda care la moment ruleaza, sau este înlan?uita.

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

classname

The class in which to remove the method

methodname

The name of the method to remove

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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'));

?>

Exemplul de mai sus va afi?a:

bar

A se vedea ?i

  • 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
Func?ii Classkit


Dynamically changes the name of the given method

classkit_method_remove
Ctype
Func?ii Classkit
PHP Manual

classkit_method_rename

(PECL classkit >= 0.1)

classkit_method_rename — Dynamically changes the name of the given method

Descrierea

bool classkit_method_rename ( string $classname , string $methodname , string $newname )

Nota: Aceasta func?ie nu poate fi utilizata pentru a manipula metoda care la moment ruleaza, sau este înlan?uita.

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

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

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

foo!

A se vedea ?i

  • 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
Func?ii Classkit


Character type checking

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii Ctype
    • 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
Introducere
Extensii referitoare la variabile ?i tipuri


Introducere

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.

Nota:

These functions are not related to the Python "ctypes" library at all. The extension name stems from the ctype.h C header file that their C equivalents are defined in.

This extension also predates Python "ctypes" so any confusion caused by this naming is hardly our fault ...

Ctype
Instalarea / configurarea
Ctype


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Ctype


Necesita?i

Nimic, în afara de func?iile din biblioteca standarda C, care sunt întotdeauna disponibile.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Începând cu PHP 4.2.0 aceste func?ii sunt activate implicit. Pentru versiuni mai vechi trebuie sa configura?i ?i sa compila?i PHP cu op?iunea --enable-ctype . Pute?i dezactiva sus?inerea ctype la compilare cu op?iunea --disable-ctype .

Versiunea PHP pentru Windows sus?ine implicit aceasta extensie. Nu este nevoie sa încarca?i extensii suplimentare pentru a putea utiliza aceste func?ii.

Nota: Sus?inerea ctype este încorporata în PHP începând cu versiunea 4.3.0.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii Ctype
Ctype


Func?ii Ctype

Cuprins

  • 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
Constante predefinite
ctype_alnum
Ctype


Check for alphanumeric character(s)

Func?ii Ctype
ctype_alpha
Func?ii Ctype
PHP Manual

ctype_alnum

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_alnum — Check for alphanumeric character(s)

Descrierea

bool ctype_alnum ( string $text )

Checks if all of the characters in the provided string, text, are alphanumeric.

Parametri

text

The tested string.

Valorile întoarse

Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

The string AbCd1zyZ9 consists of all letters or digits.
The string foo!#$bar does not consist of all letters or digits.

Note

Nota:

Daca e furnizat un integer cu valoarea între -128 ?i 255 inclusiv, el este interpretat ca o valoare ASCII a unui singur caracter (valorilor negative li se adauga 256 pentru a permite caractere din domeniul ASCII extins). Orice alt întreg este interpretat ca un string con?inând cifrele zecimale ale întregului.

A se vedea ?i

  • ctype_alpha() - Check for alphabetic character(s)
  • ctype_digit() - Check for numeric character(s)
  • setlocale() - Set locale information

Func?ii Ctype
ctype_alpha
Func?ii Ctype


Check for alphabetic character(s)

ctype_alnum
ctype_cntrl
Func?ii Ctype
PHP Manual

ctype_alpha

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_alpha — Check for alphabetic character(s)

Descrierea

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.

Parametri

text

The tested string.

Valorile întoarse

Returns TRUE if every character in text is a letter from the current locale, FALSE otherwise.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

The string KjgWZC consists of all letters.
The string arf12 does not consist of all letters.

Note

Nota:

Daca e furnizat un integer cu valoarea între -128 ?i 255 inclusiv, el este interpretat ca o valoare ASCII a unui singur caracter (valorilor negative li se adauga 256 pentru a permite caractere din domeniul ASCII extins). Orice alt întreg este interpretat ca un string con?inând cifrele zecimale ale întregului.

A se vedea ?i

  • ctype_upper() - Check for uppercase character(s)
  • ctype_lower() - Check for lowercase character(s)
  • setlocale() - Set locale information

ctype_alnum
ctype_cntrl
Func?ii Ctype


Check for control character(s)

ctype_alpha
ctype_digit
Func?ii Ctype
PHP Manual

ctype_cntrl

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_cntrl — Check for control character(s)

Descrierea

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.

Parametri

text

The tested string.

Valorile întoarse

Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

The string 'string1' consists of all control characters.
The string 'string2' does not consist of all control characters.

Note

Nota:

Daca e furnizat un integer cu valoarea între -128 ?i 255 inclusiv, el este interpretat ca o valoare ASCII a unui singur caracter (valorilor negative li se adauga 256 pentru a permite caractere din domeniul ASCII extins). Orice alt întreg este interpretat ca un string con?inând cifrele zecimale ale întregului.

A se vedea ?i

  • ctype_print() - Check for printable character(s)

ctype_alpha
ctype_digit
Func?ii Ctype


Check for numeric character(s)

ctype_cntrl
ctype_graph
Func?ii Ctype
PHP Manual

ctype_digit

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_digit — Check for numeric character(s)

Descrierea

bool ctype_digit ( string $text )

Checks if all of the characters in the provided string, text, are numerical.

Parametri

text

The tested string.

Valorile întoarse

Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Before PHP 5.1.0, this function returned TRUE when text was an empty string.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

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.

Example #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
?>

Note

Nota:

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.

Nota:

Daca e furnizat un integer cu valoarea între -128 ?i 255 inclusiv, el este interpretat ca o valoare ASCII a unui singur caracter (valorilor negative li se adauga 256 pentru a permite caractere din domeniul ASCII extins). Orice alt întreg este interpretat ca un string con?inând cifrele zecimale ale întregului.

A se vedea ?i

  • ctype_alnum() - Check for alphanumeric character(s)
  • ctype_xdigit() - Check for character(s) representing a hexadecimal digit
  • is_numeric() - Determina daca o variabila este un numar sau un string numeric
  • is_int() - Determina daca tipul unei variabile este integer
  • is_string() - Determina daca tipul variabilei este string

ctype_cntrl
ctype_graph
Func?ii Ctype


Check for any printable character(s) except space

ctype_digit
ctype_lower
Func?ii Ctype
PHP Manual

ctype_graph

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_graph — Check for any printable character(s) except space

Descrierea

bool ctype_graph ( string $text )

Checks if all of the characters in the provided string, text, creates visible output.

Parametri

text

The tested string.

Valorile întoarse

Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

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.

Note

Nota:

Daca e furnizat un integer cu valoarea între -128 ?i 255 inclusiv, el este interpretat ca o valoare ASCII a unui singur caracter (valorilor negative li se adauga 256 pentru a permite caractere din domeniul ASCII extins). Orice alt întreg este interpretat ca un string con?inând cifrele zecimale ale întregului.

A se vedea ?i

  • 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
Func?ii Ctype


Check for lowercase character(s)

ctype_graph
ctype_print
Func?ii Ctype
PHP Manual

ctype_lower

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_lower — Check for lowercase character(s)

Descrierea

bool ctype_lower ( string $text )

Checks if all of the characters in the provided string, text, are lowercase letters.

Parametri

text

The tested string.

Valorile întoarse

Returns TRUE if every character in text is a lowercase letter in the current locale.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

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.

Note

Nota:

Daca e furnizat un integer cu valoarea între -128 ?i 255 inclusiv, el este interpretat ca o valoare ASCII a unui singur caracter (valorilor negative li se adauga 256 pentru a permite caractere din domeniul ASCII extins). Orice alt întreg este interpretat ca un string con?inând cifrele zecimale ale întregului.

A se vedea ?i

  • ctype_alpha() - Check for alphabetic character(s)
  • ctype_upper() - Check for uppercase character(s)
  • setlocale() - Set locale information

ctype_graph
ctype_print
Func?ii Ctype


Check for printable character(s)

ctype_lower
ctype_punct
Func?ii Ctype
PHP Manual

ctype_print

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_print — Check for printable character(s)

Descrierea

bool ctype_print ( string $text )

Checks if all of the characters in the provided string, text, are printable.

Parametri

text

The tested string.

Valorile întoarse

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.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

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.

Note

Nota:

Daca e furnizat un integer cu valoarea între -128 ?i 255 inclusiv, el este interpretat ca o valoare ASCII a unui singur caracter (valorilor negative li se adauga 256 pentru a permite caractere din domeniul ASCII extins). Orice alt întreg este interpretat ca un string con?inând cifrele zecimale ale întregului.

A se vedea ?i

  • 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
Func?ii Ctype


Check for any printable character which is not whitespace or an alphanumeric character

ctype_print
ctype_space
Func?ii Ctype
PHP Manual

ctype_punct

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character

Descrierea

bool ctype_punct ( string $text )

Checks if all of the characters in the provided string, text, are punctuation character.

Parametri

text

The tested string.

Valorile întoarse

Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

The string ABasdk!@!$# does not consist of all punctuation.
The string !@ # $ does not consist of all punctuation.
The string *&$() consists of all punctuation.

Note

Nota:

Daca e furnizat un integer cu valoarea între -128 ?i 255 inclusiv, el este interpretat ca o valoare ASCII a unui singur caracter (valorilor negative li se adauga 256 pentru a permite caractere din domeniul ASCII extins). Orice alt întreg este interpretat ca un string con?inând cifrele zecimale ale întregului.

A se vedea ?i

  • ctype_cntrl() - Check for control character(s)
  • ctype_graph() - Check for any printable character(s) except space

ctype_print
ctype_space
Func?ii Ctype


Check for whitespace character(s)

ctype_punct
ctype_upper
Func?ii Ctype
PHP Manual

ctype_space

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_space — Check for whitespace character(s)

Descrierea

bool ctype_space ( string $text )

Checks if all of the characters in the provided string, text, creates whitespace.

Parametri

text

The tested string.

Valorile întoarse

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.

Exemple

Example #1 A ctype_space() example

<?php
$strings = array(
    'string1' => "\n\r\t",
    'string2' => "\narf12",
    'string3' => '\n\r\t' // note the single quotes
);
foreach ($strings as $name => $testcase) {
    if (ctype_space($testcase)) {
        echo "The string '$name' consists of whitespace characters only.\n";
    } else {
        echo "The string '$name' contains non-whitespace characters.\n";
    }
}
?>

Exemplul de mai sus va afi?a:

The string 'string1' consists of whitespace characters only.
The string 'string2' contains non-whitespace characters.
The string 'string3' contains non-whitespace characters.

Note

Nota:

Daca e furnizat un integer cu valoarea între -128 ?i 255 inclusiv, el este interpretat ca o valoare ASCII a unui singur caracter (valorilor negative li se adauga 256 pentru a permite caractere din domeniul ASCII extins). Orice alt întreg este interpretat ca un string con?inând cifrele zecimale ale întregului.

A se vedea ?i

  • 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
Func?ii Ctype


Check for uppercase character(s)

ctype_space
ctype_xdigit
Func?ii Ctype
PHP Manual

ctype_upper

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_upper — Check for uppercase character(s)

Descrierea

bool ctype_upper ( string $text )

Checks if all of the characters in the provided string, text, are uppercase characters.

Parametri

text

The tested string.

Valorile întoarse

Returns TRUE if every character in text is an uppercase letter in the current locale.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

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.

Note

Nota:

Daca e furnizat un integer cu valoarea între -128 ?i 255 inclusiv, el este interpretat ca o valoare ASCII a unui singur caracter (valorilor negative li se adauga 256 pentru a permite caractere din domeniul ASCII extins). Orice alt întreg este interpretat ca un string con?inând cifrele zecimale ale întregului.

A se vedea ?i

  • ctype_alpha() - Check for alphabetic character(s)
  • ctype_lower() - Check for lowercase character(s)
  • setlocale() - Set locale information

ctype_space
ctype_xdigit
Func?ii Ctype


Check for character(s) representing a hexadecimal digit

ctype_upper
Data Structures
Func?ii Ctype
PHP Manual

ctype_xdigit

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_xdigit — Check for character(s) representing a hexadecimal digit

Descrierea

bool ctype_xdigit ( string $text )

Checks if all of the characters in the provided string, text, are hexadecimal 'digits'.

Parametri

text

The tested string.

Valorile întoarse

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.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

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.

Note

Nota:

Daca e furnizat un integer cu valoarea între -128 ?i 255 inclusiv, el este interpretat ca o valoare ASCII a unui singur caracter (valorilor negative li se adauga 256 pentru a permite caractere din domeniul ASCII extins). Orice alt întreg este interpretat ca un string con?inând cifrele zecimale ale întregului.

A se vedea ?i

  • ctype_digit() - Check for numeric character(s)

ctype_upper
Data Structures
Func?ii Ctype


Data Structures

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
  • Constante predefinite
  • Exemple
  • Collection — The Collection interface
    • Ds\Collection::clear — Removes all values.
    • Ds\Collection::copy — Returns a shallow copy of the collection.
    • Ds\Collection::isEmpty — Returns whether the collection is empty
    • Ds\Collection::toArray — Converts the collection to an array.
  • Hashable — The Hashable interface
    • Ds\Hashable::equals — Determines whether an object is equal to the current instance.
    • Ds\Hashable::hash — Returns a scalar value to be used as a hash value.
  • Sequence — The Sequence interface
    • Ds\Sequence::allocate — Allocates enough memory for a required capacity.
    • Ds\Sequence::apply — Updates all values by applying a callback function to each value.
    • Ds\Sequence::capacity — Returns the current capacity.
    • Ds\Sequence::contains — Determines if the sequence contains given values.
    • Ds\Sequence::filter — Creates a new sequence using a callable to determine which values to include.
    • Ds\Sequence::find — Attempts to find a value's index.
    • Ds\Sequence::first — Returns the first value in the sequence.
    • Ds\Sequence::get — Returns the value at a given index.
    • Ds\Sequence::insert — Inserts values at a given index.
    • Ds\Sequence::join — Joins all values together as a string.
    • Ds\Sequence::last — Returns the last value.
    • Ds\Sequence::map — Returns the result of applying a callback to each value.
    • Ds\Sequence::merge — Returns the result of adding all given values to the sequence.
    • Ds\Sequence::pop — Removes and returns the last value.
    • Ds\Sequence::push — Adds values to the end of the sequence.
    • Ds\Sequence::reduce — Reduces the sequence to a single value using a callback function.
    • Ds\Sequence::remove — Removes and returns a value by index.
    • Ds\Sequence::reverse — Reverses the sequence in-place.
    • Ds\Sequence::reversed — Returns a reversed copy.
    • Ds\Sequence::rotate — Rotates the sequence by a given number of rotations.
    • Ds\Sequence::set — Updates a value at a given index.
    • Ds\Sequence::shift — Removes and returns the first value.
    • Ds\Sequence::slice — Returns a sub-sequence of a given range.
    • Ds\Sequence::sort — Sorts the sequence in-place.
    • Ds\Sequence::sorted — Returns a sorted copy.
    • Ds\Sequence::sum — Returns the sum of all values in the sequence.
    • Ds\Sequence::unshift — Adds values to the front of the sequence.
  • Vector — The Vector class
    • Ds\Vector::allocate — Allocates enough memory for a required capacity.
    • Ds\Vector::apply — Updates all values by applying a callback function to each value.
    • Ds\Vector::capacity — Returns the current capacity.
    • Ds\Vector::clear — Removes all values.
    • Ds\Vector::__construct — Creates a new instance.
    • Ds\Vector::contains — Determines if the vector contains given values.
    • Ds\Vector::copy — Returns a shallow copy of the vector.
    • Ds\Vector::count — Returns the number of values in the collection.
    • Ds\Vector::filter — Creates a new vector using a callable to determine which values to include.
    • Ds\Vector::find — Attempts to find a value's index.
    • Ds\Vector::first — Returns the first value in the vector.
    • Ds\Vector::get — Returns the value at a given index.
    • Ds\Vector::insert — Inserts values at a given index.
    • Ds\Vector::isEmpty — Returns whether the vector is empty
    • Ds\Vector::join — Joins all values together as a string.
    • Ds\Vector::jsonSerialize — Returns a representation that can be converted to JSON.
    • Ds\Vector::last — Returns the last value.
    • Ds\Vector::map — Returns the result of applying a callback to each value.
    • Ds\Vector::merge — Returns the result of adding all given values to the vector.
    • Ds\Vector::pop — Removes and returns the last value.
    • Ds\Vector::push — Adds values to the end of the vector.
    • Ds\Vector::reduce — Reduces the vector to a single value using a callback function.
    • Ds\Vector::remove — Removes and returns a value by index.
    • Ds\Vector::reverse — Reverses the vector in-place.
    • Ds\Vector::reversed — Returns a reversed copy.
    • Ds\Vector::rotate — Rotates the vector by a given number of rotations.
    • Ds\Vector::set — Updates a value at a given index.
    • Ds\Vector::shift — Removes and returns the first value.
    • Ds\Vector::slice — Returns a sub-vector of a given range.
    • Ds\Vector::sort — Sorts the vector in-place.
    • Ds\Vector::sorted — Returns a sorted copy.
    • Ds\Vector::sum — Returns the sum of all values in the vector.
    • Ds\Vector::toArray — Converts the vector to an array.
    • Ds\Vector::unshift — Adds values to the front of the vector.
  • Deque — The Deque class
    • Ds\Deque::allocate — Allocates enough memory for a required capacity.
    • Ds\Deque::apply — Updates all values by applying a callback function to each value.
    • Ds\Deque::capacity — Returns the current capacity.
    • Ds\Deque::clear — Removes all values from the deque.
    • Ds\Deque::__construct — Creates a new instance.
    • Ds\Deque::contains — Determines if the deque contains given values.
    • Ds\Deque::copy — Returns a shallow copy of the deque.
    • Ds\Deque::count — Returns the number of values in the collection.
    • Ds\Deque::filter — Creates a new deque using a callable to determine which values to include.
    • Ds\Deque::find — Attempts to find a value's index.
    • Ds\Deque::first — Returns the first value in the deque.
    • Ds\Deque::get — Returns the value at a given index.
    • Ds\Deque::insert — Inserts values at a given index.
    • Ds\Deque::isEmpty — Returns whether the deque is empty
    • Ds\Deque::join — Joins all values together as a string.
    • Ds\Deque::jsonSerialize — Returns a representation that can be converted to JSON.
    • Ds\Deque::last — Returns the last value.
    • Ds\Deque::map — Returns the result of applying a callback to each value.
    • Ds\Deque::merge — Returns the result of adding all given values to the deque.
    • Ds\Deque::pop — Removes and returns the last value.
    • Ds\Deque::push — Adds values to the end of the deque.
    • Ds\Deque::reduce — Reduces the deque to a single value using a callback function.
    • Ds\Deque::remove — Removes and returns a value by index.
    • Ds\Deque::reverse — Reverses the deque in-place.
    • Ds\Deque::reversed — Returns a reversed copy.
    • Ds\Deque::rotate — Rotates the deque by a given number of rotations.
    • Ds\Deque::set — Updates a value at a given index.
    • Ds\Deque::shift — Removes and returns the first value.
    • Ds\Deque::slice — Returns a sub-deque of a given range.
    • Ds\Deque::sort — Sorts the deque in-place.
    • Ds\Deque::sorted — Returns a sorted copy.
    • Ds\Deque::sum — Returns the sum of all values in the deque.
    • Ds\Deque::toArray — Converts the deque to an array.
    • Ds\Deque::unshift — Adds values to the front of the deque.
  • Map — The Map class
    • Ds\Map::allocate — Allocates enough memory for a required capacity.
    • Ds\Map::apply — Updates all values by applying a callback function to each value.
    • Ds\Map::capacity — Returns the current capacity.
    • Ds\Map::clear — Removes all values.
    • Ds\Map::__construct — Creates a new instance.
    • Ds\Map::copy — Returns a shallow copy of the map.
    • Ds\Map::count — Returns the number of values in the map.
    • Ds\Map::diff — Creates a new map using keys that aren't in another map.
    • Ds\Map::filter — Creates a new map using a callable to determine which pairs to include.
    • Ds\Map::first — Returns the first pair in the map.
    • Ds\Map::get — Returns the value for a given key.
    • Ds\Map::hasKey — Determines whether the map contains a given key.
    • Ds\Map::hasValue — Determines whether the map contains a given value.
    • Ds\Map::intersect — Creates a new map by intersecting keys with another map.
    • Ds\Map::isEmpty — Returns whether the map is empty
    • Ds\Map::jsonSerialize — Returns a representation that can be converted to JSON.
    • Ds\Map::keys — Returns a set of the map's keys.
    • Ds\Map::ksort — Sorts the map in-place by key.
    • Ds\Map::ksorted — Returns a copy, sorted by key.
    • Ds\Map::last — Returns the last pair of the map.
    • Ds\Map::map — Returns the result of applying a callback to each value.
    • Ds\Map::merge — Returns the result of adding all given associations.
    • Ds\Map::pairs — Returns a sequence containing all the pairs of the map.
    • Ds\Map::put — Associates a key with a value.
    • Ds\Map::putAll — Associates all key-value pairs of a traversable object or array.
    • Ds\Map::reduce — Reduces the map to a single value using a callback function.
    • Ds\Map::remove — Removes and returns a value by key.
    • Ds\Map::reverse — Reverses the map in-place.
    • Ds\Map::reversed — Returns a reversed copy.
    • Ds\Map::skip — Returns the pair at a given positional index.
    • Ds\Map::slice — Returns a subset of the map defined by a starting index and length.
    • Ds\Map::sort — Sorts the map in-place by value.
    • Ds\Map::sorted — Returns a copy, sorted by value.
    • Ds\Map::sum — Returns the sum of all values in the map.
    • Ds\Map::toArray — Converts the map to an array.
    • Ds\Map::union — Creates a new map using values from the current instance and another map.
    • Ds\Map::values — Returns a sequence of the map's values.
    • Ds\Map::xor — Creates a new map using keys of either the current instance or of another map, but not of both.
  • Pair — The Pair class
    • Ds\Pair::clear — Removes all values.
    • Ds\Pair::__construct — Creates a new instance.
    • Ds\Pair::copy — Returns a shallow copy of the pair.
    • Ds\Pair::isEmpty — Returns whether the pair is empty
    • Ds\Pair::jsonSerialize — Returns a representation that can be converted to JSON.
    • Ds\Pair::toArray — Converts the pair to an array.
  • Set — The Set class
    • Ds\Set::add — Adds values to the set.
    • Ds\Set::allocate — Allocates enough memory for a required capacity.
    • Ds\Set::capacity — Returns the current capacity.
    • Ds\Set::clear — Removes all values.
    • Ds\Set::__construct — Creates a new instance.
    • Ds\Set::contains — Determines if the set contains all values.
    • Ds\Set::copy — Returns a shallow copy of the set.
    • Ds\Set::count — Returns the number of values in the set.
    • Ds\Set::diff — Creates a new set using values that aren't in another set.
    • Ds\Set::filter — Creates a new set using a callable to determine which values to include.
    • Ds\Set::first — Returns the first value in the set.
    • Ds\Set::get — Returns the value at a given index.
    • Ds\Set::intersect — Creates a new set by intersecting values with another set.
    • Ds\Set::isEmpty — Returns whether the set is empty
    • Ds\Set::join — Joins all values together as a string.
    • Ds\Set::jsonSerialize — Returns a representation that can be converted to JSON.
    • Ds\Set::last — Returns the last value in the set.
    • Ds\Set::merge — Returns the result of adding all given values to the set.
    • Ds\Set::reduce — Reduces the set to a single value using a callback function.
    • Ds\Set::remove — Removes all given values from the set.
    • Ds\Set::reverse — Reverses the set in-place.
    • Ds\Set::reversed — Returns a reversed copy.
    • Ds\Set::slice — Returns a sub-set of a given range.
    • Ds\Set::sort — Sorts the set in-place.
    • Ds\Set::sorted — Returns a sorted copy.
    • Ds\Set::sum — Returns the sum of all values in the set.
    • Ds\Set::toArray — Converts the set to an array.
    • Ds\Set::union — Creates a new set using values from the current instance and another set.
    • Ds\Set::xor — Creates a new set using values in either the current instance or in another set, but not in both.
  • Stack — The Stack class
    • Ds\Stack::allocate — Allocates enough memory for a required capacity.
    • Ds\Stack::capacity — Returns the current capacity.
    • Ds\Stack::clear — Removes all values.
    • Ds\Stack::__construct — Creates a new instance.
    • Ds\Stack::copy — Returns a shallow copy of the stack.
    • Ds\Stack::count — Returns the number of values in the stack.
    • Ds\Stack::isEmpty — Returns whether the stack is empty
    • Ds\Stack::jsonSerialize — Returns a representation that can be converted to JSON.
    • Ds\Stack::peek — Returns the value at the top of the stack.
    • Ds\Stack::pop — Removes and returns the value at the top of the stack.
    • Ds\Stack::push — Pushes values onto the stack.
    • Ds\Stack::toArray — Converts the stack to an array.
  • Queue — The Queue class
    • Ds\Queue::allocate — Allocates enough memory for a required capacity.
    • Ds\Queue::capacity — Returns the current capacity.
    • Ds\Queue::clear — Removes all values.
    • Ds\Queue::__construct — Creates a new instance.
    • Ds\Queue::copy — Returns a shallow copy of the queue.
    • Ds\Queue::count — Returns the number of values in the queue.
    • Ds\Queue::isEmpty — Returns whether the queue is empty
    • Ds\Queue::jsonSerialize — Returns a representation that can be converted to JSON.
    • Ds\Queue::peek — Returns the value at the front of the queue.
    • Ds\Queue::pop — Removes and returns the value at the front of the queue.
    • Ds\Queue::push — Pushes values into the queue.
    • Ds\Queue::toArray — Converts the queue to an array.
  • PriorityQueue — The PriorityQueue class
    • Ds\PriorityQueue::allocate — Allocates enough memory for a required capacity.
    • Ds\PriorityQueue::capacity — Returns the current capacity.
    • Ds\PriorityQueue::clear — Removes all values.
    • Ds\PriorityQueue::__construct — Creates a new instance.
    • Ds\PriorityQueue::copy — Returns a shallow copy of the queue.
    • Ds\PriorityQueue::count — Returns the number of values in the queue.
    • Ds\PriorityQueue::isEmpty — Returns whether the queue is empty
    • Ds\PriorityQueue::jsonSerialize — Returns a representation that can be converted to JSON.
    • Ds\PriorityQueue::peek — Returns the value at the front of the queue.
    • Ds\PriorityQueue::pop — Removes and returns the value with the highest priority.
    • Ds\PriorityQueue::push — Pushes values into the queue.
    • Ds\PriorityQueue::toArray — Converts the queue to an array.
ctype_xdigit
Introducere
Extensii referitoare la variabile ?i tipuri


Introducere

Efficient data structures for PHP 7, provided as an alternative to the array.

See » this blog post for benchmarks, discussion and frequently asked questions.

Data Structures
Instalarea / configurarea
Data Structures


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
Introducere
Necesita?i
Data Structures


Necesita?i

PHP 7 is required by both the extension and the compatibility polyfill.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

The easiest way to install the extension is via » PECL

pecl install ds

You can also build directly from source:

# Dependencies you might need to install
# sudo apt-get install git build-essential php7.0-dev

git clone https://github.com/php-ds/extension "php-ds"
cd php-ds

# Build and install the extension
phpize
./configure
make
make install

# Clean up the build files
make clean
phpize --clean

If you're on Windows, you can » download a compiled .dll on PECL

Nota:

If you're using Composer, it's highly recommended that you include » php-ds/php-ds in your project so that your code is still functional in an environment where the extension is not installed. The extension will take priority if installed.

Necesita?i
Constante predefinite
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Instalarea
Exemple
Data Structures


Exemple

Example #1 Vector

<?php

$vector = new \Ds\Vector();

$vector->push('a');
$vector->push('b', 'c');

$vector[] = 'd';

print_r($vector);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

Example #2 Map

<?php

$map = new \Ds\Map();

$map->put('a', 1);
$map->put('b', 2);

$map['c'] = 3;

print_r($map);

?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)
Constante predefinite
Collection
Data Structures


The Collection interface

(No version information available, might only be in Git)

Introducere

Collection is the base interface which covers functionality common to all the data structures in this library. It guarantees that all structures are traversable, countable, and can be converted to json using json_encode().

Descrierea succinta a interfe?ei

Ds\Collection implements Traversable , Countable , JsonSerializable {
/* Metode */
abstract public void clear ( void )
abstract public Ds\Collection copy ( void )
abstract public bool isEmpty ( void )
abstract public array toArray ( void )
}

Cuprins

  • Ds\Collection::clear — Removes all values.
  • Ds\Collection::copy — Returns a shallow copy of the collection.
  • Ds\Collection::isEmpty — Returns whether the collection is empty
  • Ds\Collection::toArray — Converts the collection to an array.
Exemple
Ds\Collection::clear
Data Structures


Removes all values.

Collection
Ds\Collection::copy
Collection
PHP Manual

Ds\Collection::clear

(PECL ds >= 1.0.0)

Ds\Collection::clear — Removes all values.

Descrierea

abstract public void Ds\Collection::clear ( void )

Removes all values from the collection.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Collection::clear() example

<?php
$collection = new \Ds\Vector([1, 2, 3]);
print_r($collection);

$collection->clear();
print_r($collection);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Vector Object
(
)
Collection
Ds\Collection::copy
Collection


Returns a shallow copy of the collection.

Ds\Collection::clear
Ds\Collection::isEmpty
Collection
PHP Manual

Ds\Collection::copy

(PECL ds >= 1.0.0)

Ds\Collection::copy — Returns a shallow copy of the collection.

Descrierea

abstract public Ds\Collection Ds\Collection::copy ( void )

Returns a shallow copy of the collection.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a shallow copy of the collection.

Exemple

Example #1 Ds\Collection::copy() example

<?php
$a = new \Ds\Vector([1, 2, 3]);
$b = $a->copy();

$b->push(4);

print_r($a);
print_r($b);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
Ds\Collection::clear
Ds\Collection::isEmpty
Collection


Returns whether the collection is empty

Ds\Collection::copy
Ds\Collection::toArray
Collection
PHP Manual

Ds\Collection::isEmpty

(PECL ds >= 1.0.0)

Ds\Collection::isEmpty — Returns whether the collection is empty

Descrierea

abstract public bool Ds\Collection::isEmpty ( void )

Returns whether the collection is empty.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the collection is empty, FALSE otherwise.

Exemple

Example #1 Ds\Collection::isEmpty() example

<?php
$a = new \Ds\Vector([1, 2, 3]);
$b = new \Ds\Vector();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
bool(true)
Ds\Collection::copy
Ds\Collection::toArray
Collection


Converts the collection to an array.

Ds\Collection::isEmpty
Hashable
Collection
PHP Manual

Ds\Collection::toArray

(PECL ds >= 1.0.0)

Ds\Collection::toArray — Converts the collection to an array.

Descrierea

abstract public array Ds\Collection::toArray ( void )

Converts the collection to an array.

Nota:

Casting to an array is not supported yet.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array containing all the values in the same order as the collection.

Exemple

Example #1 Ds\Collection::toArray() example

<?php
$collection = new \Ds\Vector([1, 2, 3]);

var_dump($collection->toArray());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Collection::isEmpty
Hashable
Collection


The Hashable interface

(No version information available, might only be in Git)

Introducere

Hashable is an interface which allows objects to be used as keys. It’s an alternative to spl_object_hash(), which determines an object’s hash based on its handle: this means that two objects that are considered equal by an implicit definition would not treated as equal because they are not the same instance.

hash() is used to return a scalar value to be used as the object's hash value, which determines where it goes in the hash table. While this value does not have to be unique, objects which are equal must have the same hash value.

equals() is used to determine if two objects are equal. It's guaranteed that the comparing object will be an instance of the same class as the subject.

Descrierea succinta a interfe?ei

Ds\Hashable {
/* Metode */
abstract public bool equals ( object $obj )
abstract public mixed hash ( void )
}

Cuprins

  • Ds\Hashable::equals — Determines whether an object is equal to the current instance.
  • Ds\Hashable::hash — Returns a scalar value to be used as a hash value.
Ds\Collection::toArray
Ds\Hashable::equals
Data Structures


Determines whether an object is equal to the current instance.

Hashable
Ds\Hashable::hash
Hashable
PHP Manual

Ds\Hashable::equals

(PECL ds >= 1.0.0)

Ds\Hashable::equals — Determines whether an object is equal to the current instance.

Descrierea

abstract public bool Ds\Hashable::equals ( object $obj )

Determines whether another object is equal to the current instance.

This method allows objects to be used as keys in structures such as Ds\Map and Ds\Set, or any other lookup structure that honors this interface.

Nota:

It's guaranteed that obj is an instance of the same class.

Precautie

It's important that objects which are equal also have the same hash value. See Ds\Hashable::hash().

Parametri

obj

The object to compare the current instance to, which is always an instance of the same class.

Valorile întoarse

TRUE if equal, FALSE otherwise.

Hashable
Ds\Hashable::hash
Hashable


Returns a scalar value to be used as a hash value.

Ds\Hashable::equals
Sequence
Hashable
PHP Manual

Ds\Hashable::hash

(PECL ds >= 1.0.0)

Ds\Hashable::hash — Returns a scalar value to be used as a hash value.

Descrierea

abstract public mixed Ds\Hashable::hash ( void )

Returns a scalar value to be used as the hash value of the objects.

While the hash value does not define equality, all objects that are equal according to Ds\Hashable::equals() must have the same hash value. Hash values of equal objects don't have to be unique, for example you could just return TRUE for all objects and nothing would break - the only implication would be that hash tables then turn into linked lists because all your objects will be hashed to the same bucket. It's therefore very important that you pick a good hash value, such as an ID or email address.

This method allows objects to be used as keys in structures such as Ds\Map and Ds\Set, or any other lookup structure that honors this interface.

Precautie

Do not pick a value that might change within the object, such as a public property. Hash table lookups would fail because the hash has changed.

Precautie

All objects that are equal must have the same hash value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A scalar value to be used as this object's hash value.

Exemple

Example #1 Ds\Hashable::hash() example

<?php
class HashableObject implements \Ds\Hashable
{
    private $name;
    private $email;

    public function __construct($name, $email)
    {
        $this->name  = $name;
        $this->email = $email;
    }

    /**
     * Should return the same value for all equal objects, but doesn't have to
     * be unique. This value will not be used to determine equality.
     */
    public function hash()
    {
        return $this->email;
    }

    /**
     * This determines equality, usually during a hash table lookup to determine
     * if the bucket's key matches the lookup key. The hash has to be equal if
     * the objects are equal, otherwise this determination wouldn't be reached.
     */
    public function equals($obj): bool
    {
        return $this->name  === $obj->name
            && $this->email === $obj->email;
    }
}
?>
Ds\Hashable::equals
Sequence
Hashable


The Sequence interface

(No version information available, might only be in Git)

Introducere

A Sequence describes the behaviour of values arranged in a single, linear dimension. Some languages refer to this as a "List". It’s similar to an array that uses incremental integer keys, with the exception of a few characteristics:

  • Values will always be indexed as [0, 1, 2, …, size - 1].
  • Only allowed to access values by index in the range [0, size - 1].

Use cases:

  • Wherever you would use an array as a list (not concerned with keys).
  • A more efficient alternative to SplDoublyLinkedList and SplFixedArray.

Descrierea succinta a interfe?ei

Ds\Sequence implements Ds\Collection {
/* Metode */
abstract public void allocate ( int $capacity )
abstract public void apply ( callable $callback )
abstract public int capacity ( void )
abstract public bool contains ([ mixed $...values ] )
abstract public Ds\Sequence filter ([ callable $callback ] )
abstract public mixed find ( mixed $value )
abstract public mixed first ( void )
abstract public mixed get ( int $index )
abstract public void insert ( int $index [, mixed $...values ] )
abstract public string join ([ string $glue ] )
abstract public mixed last ( void )
abstract public Ds\Sequence map ( callable $callback )
abstract public Ds\Sequence merge ( mixed $values )
abstract public mixed pop ( void )
abstract public void push ([ mixed $...values ] )
abstract public mixed reduce ( callable $callback [, mixed $initial ] )
abstract public mixed remove ( int $index )
abstract public void reverse ( void )
abstract public Ds\Sequence reversed ( void )
abstract public void rotate ( int $rotations )
abstract public void set ( int $index , mixed $value )
abstract public mixed shift ( void )
abstract public Ds\Sequence slice ( int $index [, int $length ] )
abstract public void sort ([ callable $comparator ] )
abstract public Ds\Sequence sorted ([ callable $comparator ] )
abstract public number sum ( void )
abstract public void unshift ([ mixed $values ] )
}

Cuprins

  • Ds\Sequence::allocate — Allocates enough memory for a required capacity.
  • Ds\Sequence::apply — Updates all values by applying a callback function to each value.
  • Ds\Sequence::capacity — Returns the current capacity.
  • Ds\Sequence::contains — Determines if the sequence contains given values.
  • Ds\Sequence::filter — Creates a new sequence using a callable to determine which values to include.
  • Ds\Sequence::find — Attempts to find a value's index.
  • Ds\Sequence::first — Returns the first value in the sequence.
  • Ds\Sequence::get — Returns the value at a given index.
  • Ds\Sequence::insert — Inserts values at a given index.
  • Ds\Sequence::join — Joins all values together as a string.
  • Ds\Sequence::last — Returns the last value.
  • Ds\Sequence::map — Returns the result of applying a callback to each value.
  • Ds\Sequence::merge — Returns the result of adding all given values to the sequence.
  • Ds\Sequence::pop — Removes and returns the last value.
  • Ds\Sequence::push — Adds values to the end of the sequence.
  • Ds\Sequence::reduce — Reduces the sequence to a single value using a callback function.
  • Ds\Sequence::remove — Removes and returns a value by index.
  • Ds\Sequence::reverse — Reverses the sequence in-place.
  • Ds\Sequence::reversed — Returns a reversed copy.
  • Ds\Sequence::rotate — Rotates the sequence by a given number of rotations.
  • Ds\Sequence::set — Updates a value at a given index.
  • Ds\Sequence::shift — Removes and returns the first value.
  • Ds\Sequence::slice — Returns a sub-sequence of a given range.
  • Ds\Sequence::sort — Sorts the sequence in-place.
  • Ds\Sequence::sorted — Returns a sorted copy.
  • Ds\Sequence::sum — Returns the sum of all values in the sequence.
  • Ds\Sequence::unshift — Adds values to the front of the sequence.
Ds\Hashable::hash
Ds\Sequence::allocate
Data Structures


Allocates enough memory for a required capacity.

Sequence
Ds\Sequence::apply
Sequence
PHP Manual

Ds\Sequence::allocate

(PECL ds >= 1.0.0)

Ds\Sequence::allocate — Allocates enough memory for a required capacity.

Descrierea

abstract public void Ds\Sequence::allocate ( int $capacity )

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

Parametri

capacity

The number of values for which capacity should be allocated.

Nota:

Capacity will stay the same if this value is less than or equal to the current capacity.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Sequence::allocate() example

<?php
$sequence = new \Ds\Vector();
var_dump($sequence->capacity());

$vector->allocate(100);
var_dump($sequence->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(10)
int(100)
Sequence
Ds\Sequence::apply
Sequence


Updates all values by applying a callback function to each value.

Ds\Sequence::allocate
Ds\Sequence::capacity
Sequence
PHP Manual

Ds\Sequence::apply

(PECL ds >= 1.0.0)

Ds\Sequence::apply — Updates all values by applying a callback function to each value.

Descrierea

abstract public void Ds\Sequence::apply ( callable $callback )

Updates all values by applying a callback function to each value in the sequence.

Parametri

callback

mixed callback ( mixed $value )

A callable to apply to each value in the sequence.

The callback should return what the value should be replaced by.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Sequence::apply() example

<?php
$sequence = new \Ds\Sequence([1, 2, 3]);
$sequence->apply(function($value) { return $value * 2; });

print_r($sequence);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)
Ds\Sequence::allocate
Ds\Sequence::capacity
Sequence


Returns the current capacity.

Ds\Sequence::apply
Ds\Sequence::contains
Sequence
PHP Manual

Ds\Sequence::capacity

(PECL ds >= 1.0.0)

Ds\Sequence::capacity — Returns the current capacity.

Descrierea

abstract public int Ds\Sequence::capacity ( void )

Returns the current capacity.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current capacity.

Exemple

Example #1 Ds\Sequence::capacity() example

<?php
$sequence = new \Ds\Vector();
var_dump($sequence->capacity());

$sequence->push(...range(1, 50));
var_dump($sequence->capacity());

$sequence[] = "a";
var_dump($sequence->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(10)
int(50)
int(75)
Ds\Sequence::apply
Ds\Sequence::contains
Sequence


Determines if the sequence contains given values.

Ds\Sequence::capacity
Ds\Sequence::filter
Sequence
PHP Manual

Ds\Sequence::contains

(PECL ds >= 1.0.0)

Ds\Sequence::contains — Determines if the sequence contains given values.

Descrierea

abstract public bool Ds\Sequence::contains ([ mixed $...values ] )

Determines if the sequence contains all values.

Parametri

values

Values to check.

Valorile întoarse

FALSE if any of the provided values are not in the sequence, TRUE otherwise.

Exemple

Example #1 Ds\Sequence::contains() example

<?php
$sequence = new \Ds\Vector(['a', 'b', 'c', 1, 2, 3]);

var_dump($sequence->contains('a'));                // true
var_dump($sequence->contains('a', 'b'));           // true
var_dump($sequence->contains('c', 'd'));           // false

var_dump($sequence->contains(...['c', 'b', 'a'])); // true

// Always strict
var_dump($sequence->contains(1));                  // true
var_dump($sequence->contains('1'));                // false

var_dump($sequece->contains(...[]));               // true
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
Ds\Sequence::capacity
Ds\Sequence::filter
Sequence


Creates a new sequence using a callable to determine which values to include.

Ds\Sequence::contains
Ds\Sequence::find
Sequence
PHP Manual

Ds\Sequence::filter

(PECL ds >= 1.0.0)

Ds\Sequence::filter — Creates a new sequence using a callable to determine which values to include.

Descrierea

abstract public Ds\Sequence Ds\Sequence::filter ([ callable $callback ] )

Creates a new sequence using a callable to determine which values to include.

Parametri

callback

bool callback ( mixed $value )

Optional callable which returns TRUE if the value should be included, FALSE otherwise.

If a callback is not provided, only values which are TRUE (see converting to boolean) will be included.

Valorile întoarse

A new sequence containing all the values for which either the callback returned TRUE, or all values that convert to TRUE if a callback was not provided.

Exemple

Example #1 Ds\Sequence::filter() example using callback function

<?php
$sequence = new \Ds\Vector([1, 2, 3, 4, 5]);

var_dump($sequence->filter(function($value) {
    return $value % 2 == 0;
}));
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Vector)#3 (2) {
  [0]=>
  int(2)
  [1]=>
  int(4)
}

Example #2 Ds\Sequence::filter() example without a callback function

<?php
$sequence = new \Ds\Vector([0, 1, 'a', true, false]);

var_dump($sequence->filter());
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Vector)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}
Ds\Sequence::contains
Ds\Sequence::find
Sequence


Attempts to find a value's index.

Ds\Sequence::filter
Ds\Sequence::first
Sequence
PHP Manual

Ds\Sequence::find

(PECL ds >= 1.0.0)

Ds\Sequence::find — Attempts to find a value's index.

Descrierea

abstract public mixed Ds\Sequence::find ( mixed $value )

Returns the index of the value, or FALSE if not found.

Parametri

value

The value to find.

Valorile întoarse

The index of the value, or FALSE if not found.

Nota:

Values will be compared by value and by type.

Exemple

Example #1 Ds\Sequence::find() example

<?php
$sequence = new \Ds\Vector(["a", 1, true]);

var_dump($sequence->find("a")); // 0
var_dump($sequence->find("b")); // false
var_dump($sequence->find("1")); // false
var_dump($sequence->find(1));   // 1
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(0)
bool(false)
bool(false)
int(1)
Ds\Sequence::filter
Ds\Sequence::first
Sequence


Returns the first value in the sequence.

Ds\Sequence::find
Ds\Sequence::get
Sequence
PHP Manual

Ds\Sequence::first

(PECL ds >= 1.0.0)

Ds\Sequence::first — Returns the first value in the sequence.

Descrierea

abstract public mixed Ds\Sequence::first ( void )

Returns the first value in the sequence.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The first value in the sequence.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Sequence::first() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);
var_dump($sequence->first());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(1)
Ds\Sequence::find
Ds\Sequence::get
Sequence


Returns the value at a given index.

Ds\Sequence::first
Ds\Sequence::insert
Sequence
PHP Manual

Ds\Sequence::get

(PECL ds >= 1.0.0)

Ds\Sequence::get — Returns the value at a given index.

Descrierea

abstract public mixed Ds\Sequence::get ( int $index )

Returns the value at a given index.

Parametri

index

The index to access, starting at 0.

Valorile întoarse

The value at the requested index.

Erori/Excep?ii

OutOfRangeException if the index is not valid.

Exemple

Example #1 Ds\Sequence::get() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

var_dump($sequence->get(0));
var_dump($sequence->get(1));
var_dump($sequence->get(2));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
string(1) "b"
string(1) "c"

Example #2 Ds\Sequence::get() example using array syntax

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

var_dump($sequence[0]);
var_dump($sequence[1]);
var_dump($sequence[2]);
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
string(1) "b"
string(1) "c"
Ds\Sequence::first
Ds\Sequence::insert
Sequence


Inserts values at a given index.

Ds\Sequence::get
Ds\Sequence::join
Sequence
PHP Manual

Ds\Sequence::insert

(PECL ds >= 1.0.0)

Ds\Sequence::insert — Inserts values at a given index.

Descrierea

abstract public void Ds\Sequence::insert ( int $index [, mixed $...values ] )

Inserts values into the sequence at a given index.

Parametri

index

The index at which to insert. 0 <= index <= count

Nota:

You can insert at the index equal to the number of values.

values

The value or values to insert.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

OutOfRangeException if the index is not valid.

Exemple

Example #1 Ds\Sequence::insert() example

<?php
$sequence = new \Ds\Vector();

$sequence->insert(0, "e");             // [e]
$sequence->insert(1, "f");             // [e, f]
$sequence->insert(2, "g");             // [e, f, g]
$sequence->insert(0, "a", "b");        // [a, b, e, f, g]
$sequence->insert(2, ...["c", "d"]);   // [a, b, c, d, e, f, g]

var_dump($sequence);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Vector)#1 (7) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
  [6]=>
  string(1) "g"
}
Ds\Sequence::get
Ds\Sequence::join
Sequence


Joins all values together as a string.

Ds\Sequence::insert
Ds\Sequence::last
Sequence
PHP Manual

Ds\Sequence::join

(PECL ds >= 1.0.0)

Ds\Sequence::join — Joins all values together as a string.

Descrierea

abstract public string Ds\Sequence::join ([ string $glue ] )

Joins all values together as a string using an optional separator between each value.

Parametri

glue

An optional string to separate each value.

Valorile întoarse

All values of the sequence joined together as a string.

Exemple

Example #1 Ds\Sequence::join() example using a separator string

<?php
$sequence = new \Ds\Vector(["a", "b", "c", 1, 2, 3]);

var_dump($sequence->join("|"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(11) "a|b|c|1|2|3"

Example #2 Ds\Sequence::join() example without a separator string

<?php
$sequence = new \Ds\Vector(["a", "b", "c", 1, 2, 3]);

var_dump($sequence->join());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(11) "abc123"
Ds\Sequence::insert
Ds\Sequence::last
Sequence


Returns the last value.

Ds\Sequence::join
Ds\Sequence::map
Sequence
PHP Manual

Ds\Sequence::last

(PECL ds >= 1.0.0)

Ds\Sequence::last — Returns the last value.

Descrierea

abstract public mixed Ds\Sequence::last ( void )

Returns the last value in the sequence.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The last value in the sequence.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Sequence::last() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);
var_dump($sequence->last());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)
Ds\Sequence::join
Ds\Sequence::map
Sequence


Returns the result of applying a callback to each value.

Ds\Sequence::last
Ds\Sequence::merge
Sequence
PHP Manual

Ds\Sequence::map

(PECL ds >= 1.0.0)

Ds\Sequence::map — Returns the result of applying a callback to each value.

Descrierea

abstract public Ds\Sequence Ds\Sequence::map ( callable $callback )

Returns the result of applying a callback function to each value in the sequence.

Parametri

callback

mixed callback ( mixed $value )

A callable to apply to each value in the sequence.

The callable should return what the new value will be in the new sequence.

Valorile întoarse

The result of applying a callback to each value in the sequence.

Nota:

The values of the current instance won't be affected.

Exemple

Example #1 Ds\Sequence::map() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

print_r($sequence->map(function($value) { return $value * 2; }));
print_r($sequence);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Sequence::last
Ds\Sequence::merge
Sequence


Returns the result of adding all given values to the sequence.

Ds\Sequence::map
Ds\Sequence::pop
Sequence
PHP Manual

Ds\Sequence::merge

(PECL ds >= 1.0.0)

Ds\Sequence::merge — Returns the result of adding all given values to the sequence.

Descrierea

abstract public Ds\Sequence Ds\Sequence::merge ( mixed $values )

Returns the result of adding all given values to the sequence.

Parametri

values

A traversable object or an array.

Valorile întoarse

The result of adding all given values to the sequence, effectively the same as adding the values to a copy, then returning that copy.

Nota:

The current instance won't be affected.

Exemple

Example #1 Ds\Sequence::merge() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

var_dump($sequence->merge([4, 5, 6]));
var_dump($sequence);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Vector)#2 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}
object(Ds\Vector)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Sequence::map
Ds\Sequence::pop
Sequence


Removes and returns the last value.

Ds\Sequence::merge
Ds\Sequence::push
Sequence
PHP Manual

Ds\Sequence::pop

(PECL ds >= 1.0.0)

Ds\Sequence::pop — Removes and returns the last value.

Descrierea

abstract public mixed Ds\Sequence::pop ( void )

Removes and returns the last value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The removed last value.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Sequence::pop() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

var_dump($sequence->pop());
var_dump($sequence->pop());
var_dump($sequence->pop());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)
int(2)
int(1)
Ds\Sequence::merge
Ds\Sequence::push
Sequence


Adds values to the end of the sequence.

Ds\Sequence::pop
Ds\Sequence::reduce
Sequence
PHP Manual

Ds\Sequence::push

(PECL ds >= 1.0.0)

Ds\Sequence::push — Adds values to the end of the sequence.

Descrierea

abstract public void Ds\Sequence::push ([ mixed $...values ] )

Adds values to the end of the sequence.

Parametri

values

The values to add.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Sequence::push() example

<?php
$sequence = new \Ds\Vector();

$sequence->push("a");
$sequence->push("b");
$sequence->push("c", "d");
$sequence->push(...["e", "f"]);

print_r($sequence);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)
Ds\Sequence::pop
Ds\Sequence::reduce
Sequence


Reduces the sequence to a single value using a callback function.

Ds\Sequence::push
Ds\Sequence::remove
Sequence
PHP Manual

Ds\Sequence::reduce

(PECL ds >= 1.0.0)

Ds\Sequence::reduce — Reduces the sequence to a single value using a callback function.

Descrierea

abstract public mixed Ds\Sequence::reduce ( callable $callback [, mixed $initial ] )

Reduces the sequence to a single value using a callback function.

Parametri

callback
mixed callback ( mixed $carry , mixed $value )
carry

The return value of the previous callback, or initial if it's the first iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be NULL.

Valorile întoarse

The return value of the final callback.

Exemple

Example #1 Ds\Sequence::reduce() with initial value example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

$callback = function($carry, $value) {
    return $carry * $value;
};

var_dump($sequence->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 =  5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(30)

Example #2 Ds\Sequence::reduce() without an initial value example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

var_dump($sequence->reduce(function($carry, $value) {
    return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 =  6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(21)
Ds\Sequence::push
Ds\Sequence::remove
Sequence


Removes and returns a value by index.

Ds\Sequence::reduce
Ds\Sequence::reverse
Sequence
PHP Manual

Ds\Sequence::remove

(PECL ds >= 1.0.0)

Ds\Sequence::remove — Removes and returns a value by index.

Descrierea

abstract public mixed Ds\Sequence::remove ( int $index )

Removes and returns a value by index.

Parametri

index

The index of the value to remove.

Valorile întoarse

The value that was removed.

Erori/Excep?ii

OutOfRangeException if the index is not valid.

Exemple

Example #1 Ds\Sequence::remove() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

var_dump($sequence->remove(1));
var_dump($sequence->remove(0));
var_dump($sequence->remove(0));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "b"
string(1) "a"
string(1) "c"
Ds\Sequence::reduce
Ds\Sequence::reverse
Sequence


Reverses the sequence in-place.

Ds\Sequence::remove
Ds\Sequence::reversed
Sequence
PHP Manual

Ds\Sequence::reverse

(PECL ds >= 1.0.0)

Ds\Sequence::reverse — Reverses the sequence in-place.

Descrierea

abstract public void Ds\Sequence::reverse ( void )

Reverses the sequence in-place.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Sequence::reverse() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);
$sequence->reverse();

print_r($sequence);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Sequence::remove
Ds\Sequence::reversed
Sequence


Returns a reversed copy.

Ds\Sequence::reverse
Ds\Sequence::rotate
Sequence
PHP Manual

Ds\Sequence::reversed

(PECL ds >= 1.0.0)

Ds\Sequence::reversed — Returns a reversed copy.

Descrierea

abstract public Ds\Sequence Ds\Sequence::reversed ( void )

Returns a reversed copy of the sequence.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A reversed copy of the sequence.

Nota:

The current instance is not affected.

Exemple

Example #1 Ds\Sequence::reversed() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

print_r($sequence->reversed());
print_r($sequence);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
)
Ds\Sequence::reverse
Ds\Sequence::rotate
Sequence


Rotates the sequence by a given number of rotations.

Ds\Sequence::reversed
Ds\Sequence::set
Sequence
PHP Manual

Ds\Sequence::rotate

(PECL ds >= 1.0.0)

Ds\Sequence::rotate — Rotates the sequence by a given number of rotations.

Descrierea

abstract public void Ds\Sequence::rotate ( int $rotations )

Rotates the sequence by a given number of rotations, which is equivalent to successively calling $sequence->push($sequence->shift()) if the number of rotations is positive, or $sequence->unshift($sequence->pop()) if negative.

Parametri

rotations

The number of times the sequence should be rotated.

Valorile întoarse

Nu este întoarsa nici o valoare.. The sequence of the current instance will be rotated.

Exemple

Example #1 Ds\Sequence::rotate() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c", "d"]);

$sequence->rotate(1);  // "a" is shifted, then pushed.
print_r($sequence);

$sequence->rotate(2);  // "b" and "c" are both shifted, the pushed.
print_r($sequence);
?>

Exemplul de mai sus va afi?a ceva similar cu:

(
    [0] => b
    [1] => c
    [2] => d
    [3] => a
)
Ds\Vector Object
(
    [0] => d
    [1] => a
    [2] => b
    [3] => c
)
Ds\Sequence::reversed
Ds\Sequence::set
Sequence


Updates a value at a given index.

Ds\Sequence::rotate
Ds\Sequence::shift
Sequence
PHP Manual

Ds\Sequence::set

(PECL ds >= 1.0.0)

Ds\Sequence::set — Updates a value at a given index.

Descrierea

abstract public void Ds\Sequence::set ( int $index , mixed $value )

Updates a value at a given index.

Parametri

index

The index of the value to update.

value

The new value.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

OutOfRangeException if the index is not valid.

Exemple

Example #1 Ds\Sequence::set() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

$sequence->set(1, "_");
print_r($sequence);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => a
    [1] => _
    [2] => c
)

Example #2 Ds\Sequence::set() example using array syntax

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

$sequence[1] = "_";
print_r($sequence);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => a
    [1] => _
    [2] => c
)
Ds\Sequence::rotate
Ds\Sequence::shift
Sequence


Removes and returns the first value.

Ds\Sequence::set
Ds\Sequence::slice
Sequence
PHP Manual

Ds\Sequence::shift

(PECL ds >= 1.0.0)

Ds\Sequence::shift — Removes and returns the first value.

Descrierea

abstract public mixed Ds\Sequence::shift ( void )

Removes and returns the first value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The first value, which was removed.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Sequence::shift() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

var_dump($sequence->shift());
var_dump($sequence->shift());
var_dump($sequence->shift());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
string(1) "b"
string(1) "c"
Ds\Sequence::set
Ds\Sequence::slice
Sequence


Returns a sub-sequence of a given range.

Ds\Sequence::shift
Ds\Sequence::sort
Sequence
PHP Manual

Ds\Sequence::slice

(PECL ds >= 1.0.0)

Ds\Sequence::slice — Returns a sub-sequence of a given range.

Descrierea

abstract public Ds\Sequence Ds\Sequence::slice ( int $index [, int $length ] )

Creates a sub-sequence of a given range.

Parametri

index

The index at which the sub-sequence starts.

If positive, the sequence will start at that index in the sequence. If negative, the sequence will start that far from the end.

length

If a length is given and is positive, the resulting sequence will have up to that many values in it. If the length results in an overflow, only values up to the end of the sequence will be included. If a length is given and is negative, the sequence will stop that many values from the end. If a length is not provided, the resulting sequence will contain all values between the index and the end of the sequence.

Valorile întoarse

A sub-sequence of the given range.

Exemple

Example #1 Ds\Sequence::slice() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c", "d", "e"]);

// Slice from 2 onwards
print_r($sequence->slice(2));

// Slice from 1, for a length of 3
print_r($sequence->slice(1, 3));

// Slice from 1 onwards
print_r($sequence->slice(1));

// Slice from 2 from the end onwards
print_r($sequence->slice(-2));

// Slice from 1 to 1 from the end
print_r($sequence->slice(1, -1));
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => c
    [1] => d
    [2] => e
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)
Ds\Vector Object
(
    [0] => d
    [1] => e
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Sequence::shift
Ds\Sequence::sort
Sequence


Sorts the sequence in-place.

Ds\Sequence::slice
Ds\Sequence::sorted
Sequence
PHP Manual

Ds\Sequence::sort

(PECL ds >= 1.0.0)

Ds\Sequence::sort — Sorts the sequence in-place.

Descrierea

abstract public void Ds\Sequence::sort ([ callable $comparator ] )

Sorts the sequence in-place, using an optional comparator function.

Parametri

comparator

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
Precautie

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Sequence::sort() example

<?php
$sequence = new \Ds\Vector([4, 5, 1, 3, 2]);
$sequence->sort();

print_r($sequence);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Sequence::sort() example using a comparator

<?php
$sequence = new \Ds\Vector([4, 5, 1, 3, 2]);

$sequence->sort(function($a, $b) {
    return $b <=> $a;
});

print_r($sequence);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)
Ds\Sequence::slice
Ds\Sequence::sorted
Sequence


Returns a sorted copy.

Ds\Sequence::sort
Ds\Sequence::sum
Sequence
PHP Manual

Ds\Sequence::sorted

(PECL ds >= 1.0.0)

Ds\Sequence::sorted — Returns a sorted copy.

Descrierea

abstract public Ds\Sequence Ds\Sequence::sorted ([ callable $comparator ] )

Returns a sorted copy, using an optional comparator function.

Parametri

comparator

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
Precautie

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valorile întoarse

Returns a sorted copy of the sequence.

Exemple

Example #1 Ds\Sequence::sorted() example

<?php
$sequence = new \Ds\Vector([4, 5, 1, 3, 2]);

print_r($sequence->sorted());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Sequence::sorted() example using a comparator

<?php
$sequence = new \Ds\Vector([4, 5, 1, 3, 2]);

$sorted = $sequence->sorted(function($a, $b) {
    return $b <=> $a;
});

print_r($sorted);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)
Ds\Sequence::sort
Ds\Sequence::sum
Sequence


Returns the sum of all values in the sequence.

Ds\Sequence::sorted
Ds\Sequence::unshift
Sequence
PHP Manual

Ds\Sequence::sum

(PECL ds >= 1.0.0)

Ds\Sequence::sum — Returns the sum of all values in the sequence.

Descrierea

abstract public number Ds\Sequence::sum ( void )

Returns the sum of all values in the sequence.

Nota:

Arrays and objects are considered equal to zero when calculating the sum.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The sum of all the values in the sequence as either a float or int depending on the values in the sequence.

Exemple

Example #1 Ds\Sequence::sum() integer example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);
var_dump($sequence->sum());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(6)

Example #2 Ds\Sequence::sum() float example

<?php
$sequence = new \Ds\Vector([1, 2.5, 3]);
var_dump($sequence->sum());
?>

Exemplul de mai sus va afi?a ceva similar cu:

float(6.5)
Ds\Sequence::sorted
Ds\Sequence::unshift
Sequence


Adds values to the front of the sequence.

Ds\Sequence::sum
Vector
Sequence
PHP Manual

Ds\Sequence::unshift

(PECL ds >= 1.0.0)

Ds\Sequence::unshift — Adds values to the front of the sequence.

Descrierea

abstract public void Ds\Sequence::unshift ([ mixed $values ] )

Adds values to the front of the sequence, moving all the current values forward to make room for the new values.

Parametri

values

The values to add to the front of the sequence.

Nota:

Multiple values will be added in the same order that they are passed.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Sequence::unshift() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

$sequence->unshift("a");
$sequence->unshift("b", "c");

print_r($sequence);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => a
    [3] => 1
    [4] => 2
    [5] => 3
)
Ds\Sequence::sum
Vector
Sequence


The Vector class

(No version information available, might only be in Git)

Introducere

A Vector is a sequence of values in a contiguous buffer that grows and shrinks automatically. It’s the most efficient sequential structure because a value’s index is a direct mapping to its index in the buffer, and the growth factor isn't bound to a specific multiple or exponent.

Strengths

  • Supports array syntax (square brackets).
  • Uses less overall memory than an array for the same number of values.
  • Automatically frees allocated memory when its size drops low enough.
  • Capacity does not have to be a power of 2.
  • get(),
set(),
push(),
pop() are all O(1).

Weaknesses

  • shift(),
unshift(),
insert() and
remove() are all O(n).

Sinopsisul clasei

Ds\Vector implements Ds\Sequence {
/* Constants */
const int MIN_CAPACITY = 10 ;
/* Metode */
public void allocate ( int $capacity )
public void apply ( callable $callback )
public int capacity ( void )
public void clear ( void )
public bool contains ([ mixed $...values ] )
public Ds\Vector copy ( void )
public Ds\Vector filter ([ callable $callback ] )
public mixed find ( mixed $value )
public mixed first ( void )
public mixed get ( int $index )
public void insert ( int $index [, mixed $...values ] )
public bool isEmpty ( void )
public string join ([ string $glue ] )
public mixed last ( void )
public Ds\Vector map ( callable $callback )
public Ds\Vector merge ( mixed $values )
public mixed pop ( void )
public void push ([ mixed $...values ] )
public mixed reduce ( callable $callback [, mixed $initial ] )
public mixed remove ( int $index )
public void reverse ( void )
public Ds\Vector reversed ( void )
public void rotate ( int $rotations )
public void set ( int $index , mixed $value )
public mixed shift ( void )
public Ds\Vector slice ( int $index [, int $length ] )
public void sort ([ callable $comparator ] )
public Ds\Vector sorted ([ callable $comparator ] )
public number sum ( void )
public array toArray ( void )
public void unshift ([ mixed $values ] )
}

Constante predefinite

Ds\Vector::MIN_CAPACITY

Cuprins

  • Ds\Vector::allocate — Allocates enough memory for a required capacity.
  • Ds\Vector::apply — Updates all values by applying a callback function to each value.
  • Ds\Vector::capacity — Returns the current capacity.
  • Ds\Vector::clear — Removes all values.
  • Ds\Vector::__construct — Creates a new instance.
  • Ds\Vector::contains — Determines if the vector contains given values.
  • Ds\Vector::copy — Returns a shallow copy of the vector.
  • Ds\Vector::count — Returns the number of values in the collection.
  • Ds\Vector::filter — Creates a new vector using a callable to determine which values to include.
  • Ds\Vector::find — Attempts to find a value's index.
  • Ds\Vector::first — Returns the first value in the vector.
  • Ds\Vector::get — Returns the value at a given index.
  • Ds\Vector::insert — Inserts values at a given index.
  • Ds\Vector::isEmpty — Returns whether the vector is empty
  • Ds\Vector::join — Joins all values together as a string.
  • Ds\Vector::jsonSerialize — Returns a representation that can be converted to JSON.
  • Ds\Vector::last — Returns the last value.
  • Ds\Vector::map — Returns the result of applying a callback to each value.
  • Ds\Vector::merge — Returns the result of adding all given values to the vector.
  • Ds\Vector::pop — Removes and returns the last value.
  • Ds\Vector::push — Adds values to the end of the vector.
  • Ds\Vector::reduce — Reduces the vector to a single value using a callback function.
  • Ds\Vector::remove — Removes and returns a value by index.
  • Ds\Vector::reverse — Reverses the vector in-place.
  • Ds\Vector::reversed — Returns a reversed copy.
  • Ds\Vector::rotate — Rotates the vector by a given number of rotations.
  • Ds\Vector::set — Updates a value at a given index.
  • Ds\Vector::shift — Removes and returns the first value.
  • Ds\Vector::slice — Returns a sub-vector of a given range.
  • Ds\Vector::sort — Sorts the vector in-place.
  • Ds\Vector::sorted — Returns a sorted copy.
  • Ds\Vector::sum — Returns the sum of all values in the vector.
  • Ds\Vector::toArray — Converts the vector to an array.
  • Ds\Vector::unshift — Adds values to the front of the vector.
Ds\Sequence::unshift
Ds\Vector::allocate
Data Structures


Allocates enough memory for a required capacity.

Vector
Ds\Vector::apply
Vector
PHP Manual

Ds\Vector::allocate

(PECL ds >= 1.0.0)

Ds\Vector::allocate — Allocates enough memory for a required capacity.

Descrierea

public void Ds\Vector::allocate ( int $capacity )

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

Parametri

capacity

The number of values for which capacity should be allocated.

Nota:

Capacity will stay the same if this value is less than or equal to the current capacity.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Vector::allocate() example

<?php
$vector = new \Ds\Vector();
var_dump($vector->capacity());

$vector->allocate(100);
var_dump($vector->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(10)
int(100)
Vector
Ds\Vector::apply
Vector


Updates all values by applying a callback function to each value.

Ds\Vector::allocate
Ds\Vector::capacity
Vector
PHP Manual

Ds\Vector::apply

(PECL ds >= 1.0.0)

Ds\Vector::apply — Updates all values by applying a callback function to each value.

Descrierea

public void Ds\Vector::apply ( callable $callback )

Updates all values by applying a callback function to each value in the vector.

Parametri

callback

mixed callback ( mixed $value )

A callable to apply to each value in the vector.

The callback should return what the value should be replaced by.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Vector::apply() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
$vector->apply(function($value) { return $value * 2; });

print_r($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)
Ds\Vector::allocate
Ds\Vector::capacity
Vector


Returns the current capacity.

Ds\Vector::apply
Ds\Vector::clear
Vector
PHP Manual

Ds\Vector::capacity

(PECL ds >= 1.0.0)

Ds\Vector::capacity — Returns the current capacity.

Descrierea

public int Ds\Vector::capacity ( void )

Returns the current capacity.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current capacity.

Exemple

Example #1 Ds\Vector::capacity() example

<?php
$vector = new \Ds\Vector();
var_dump($vector->capacity());

$vector->push(...range(1, 50));
var_dump($vector->capacity());

$vector[] = "a";
var_dump($vector->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(10)
int(50)
int(75)
Ds\Vector::apply
Ds\Vector::clear
Vector


Removes all values.

Ds\Vector::capacity
Ds\Vector::__construct
Vector
PHP Manual

Ds\Vector::clear

(PECL ds >= 1.0.0)

Ds\Vector::clear — Removes all values.

Descrierea

public void Ds\Vector::clear ( void )

Removes all values from the vector.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Vector::clear() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
print_r($vector);

$vector->clear();
print_r($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Vector Object
(
)
Ds\Vector::capacity
Ds\Vector::__construct
Vector


Creates a new instance.

Ds\Vector::clear
Ds\Vector::contains
Vector
PHP Manual

Ds\Vector::__construct

(PECL ds >= 1.0.0)

Ds\Vector::__construct — Creates a new instance.

Descrierea

public Ds\Vector::__construct ([ mixed $values ] )

Creates a new instance, using either a traversable object or an array for the initial values.

Parametri

values

A traversable object or an array to use for the initial values.

Exemple

Example #1 Ds\Vector::__construct() example

<?php
$vector = new \Ds\Vector();
var_dump($vector);

$vector = new \Ds\Vector([1, 2, 3]);
var_dump($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Vector)#2 (0) {
}
object(Ds\Vector)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Vector::clear
Ds\Vector::contains
Vector


Determines if the vector contains given values.

Ds\Vector::__construct
Ds\Vector::copy
Vector
PHP Manual

Ds\Vector::contains

(PECL ds >= 1.0.0)

Ds\Vector::contains — Determines if the vector contains given values.

Descrierea

public bool Ds\Vector::contains ([ mixed $...values ] )

Determines if the vector contains all values.

Parametri

values

Values to check.

Valorile întoarse

FALSE if any of the provided values are not in the vector, TRUE otherwise.

Exemple

Example #1 Ds\Vector::contains() example

<?php
$vector = new \Ds\Vector(['a', 'b', 'c', 1, 2, 3]);

var_dump($vector->contains('a'));                // true
var_dump($vector->contains('a', 'b'));           // true
var_dump($vector->contains('c', 'd'));           // false

var_dump($vector->contains(...['c', 'b', 'a'])); // true

// Always strict
var_dump($vector->contains(1));                  // true
var_dump($vector->contains('1'));                // false

var_dump($sequece->contains(...[]));               // true
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
Ds\Vector::__construct
Ds\Vector::copy
Vector


Returns a shallow copy of the vector.

Ds\Vector::contains
Ds\Vector::count
Vector
PHP Manual

Ds\Vector::copy

(PECL ds >= 1.0.0)

Ds\Vector::copy — Returns a shallow copy of the vector.

Descrierea

public Ds\Vector Ds\Vector::copy ( void )

Returns a shallow copy of the vector.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a shallow copy of the vector.

Exemple

Example #1 Ds\Vector::copy() example

<?php
$a = new \Ds\Vector([1, 2, 3]);
$b = $a->copy();

// Updating the copy doesn't affect the original
$b->push(4);

print_r($a);
print_r($b);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
Ds\Vector::contains
Ds\Vector::count
Vector


Returns the number of values in the collection.

Ds\Vector::copy
Ds\Vector::filter
Vector
PHP Manual

Ds\Vector::count

(PECL ds >= 1.0.0)

Ds\Vector::count — Returns the number of values in the collection.

See Countable::count()

Ds\Vector::copy
Ds\Vector::filter
Vector


Creates a new vector using a callable to determine which values to include.

Ds\Vector::count
Ds\Vector::find
Vector
PHP Manual

Ds\Vector::filter

(PECL ds >= 1.0.0)

Ds\Vector::filter — Creates a new vector using a callable to determine which values to include.

Descrierea

public Ds\Vector Ds\Vector::filter ([ callable $callback ] )

Creates a new vector using a callable to determine which values to include.

Parametri

callback

bool callback ( mixed $value )

Optional callable which returns TRUE if the value should be included, FALSE otherwise.

If a callback is not provided, only values which are TRUE (see converting to boolean) will be included.

Valorile întoarse

A new vector containing all the values for which either the callback returned TRUE, or all values that convert to TRUE if a callback was not provided.

Exemple

Example #1 Ds\Vector::filter() example using callback function

<?php
$vector = new \Ds\Vector([1, 2, 3, 4, 5]);

var_dump($vector->filter(function($value) {
    return $value % 2 == 0;
}));
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Vector)#3 (2) {
  [0]=>
  int(2)
  [1]=>
  int(4)
}

Example #2 Ds\Vector::filter() example without a callback function

<?php
$vector = new \Ds\Vector([0, 1, 'a', true, false]);

var_dump($vector->filter());
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Vector)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}
Ds\Vector::count
Ds\Vector::find
Vector


Attempts to find a value's index.

Ds\Vector::filter
Ds\Vector::first
Vector
PHP Manual

Ds\Vector::find

(PECL ds >= 1.0.0)

Ds\Vector::find — Attempts to find a value's index.

Descrierea

public mixed Ds\Vector::find ( mixed $value )

Returns the index of the value, or FALSE if not found.

Parametri

value

The value to find.

Valorile întoarse

The index of the value, or FALSE if not found.

Nota:

Values will be compared by value and by type.

Exemple

Example #1 Ds\Vector::find() example

<?php
$vector = new \Ds\Vector(["a", 1, true]);

var_dump($vector->find("a")); // 0
var_dump($vector->find("b")); // false
var_dump($vector->find("1")); // false
var_dump($vector->find(1));   // 1
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(0)
bool(false)
bool(false)
int(1)
Ds\Vector::filter
Ds\Vector::first
Vector


Returns the first value in the vector.

Ds\Vector::find
Ds\Vector::get
Vector
PHP Manual

Ds\Vector::first

(PECL ds >= 1.0.0)

Ds\Vector::first — Returns the first value in the vector.

Descrierea

public mixed Ds\Vector::first ( void )

Returns the first value in the vector.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The first value in the vector.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Vector::first() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
var_dump($vector->first());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(1)
Ds\Vector::find
Ds\Vector::get
Vector


Returns the value at a given index.

Ds\Vector::first
Ds\Vector::insert
Vector
PHP Manual

Ds\Vector::get

(PECL ds >= 1.0.0)

Ds\Vector::get — Returns the value at a given index.

Descrierea

public mixed Ds\Vector::get ( int $index )

Returns the value at a given index.

Parametri

index

The index to access, starting at 0.

Valorile întoarse

The value at the requested index.

Erori/Excep?ii

OutOfRangeException if the index is not valid.

Exemple

Example #1 Ds\Vector::get() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

var_dump($vector->get(0));
var_dump($vector->get(1));
var_dump($vector->get(2));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
string(1) "b"
string(1) "c"

Example #2 Ds\Vector::get() example using array syntax

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

var_dump($vector[0]);
var_dump($vector[1]);
var_dump($vector[2]);
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
string(1) "b"
string(1) "c"
Ds\Vector::first
Ds\Vector::insert
Vector


Inserts values at a given index.

Ds\Vector::get
Ds\Vector::isEmpty
Vector
PHP Manual

Ds\Vector::insert

(PECL ds >= 1.0.0)

Ds\Vector::insert — Inserts values at a given index.

Descrierea

public void Ds\Vector::insert ( int $index [, mixed $...values ] )

Inserts values into the vector at a given index.

Parametri

index

The index at which to insert. 0 <= index <= count

Nota:

You can insert at the index equal to the number of values.

values

The value or values to insert.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

OutOfRangeException if the index is not valid.

Exemple

Example #1 Ds\Vector::insert() example

<?php
$vector = new \Ds\Vector();

$vector->insert(0, "e");             // [e]
$vector->insert(1, "f");             // [e, f]
$vector->insert(2, "g");             // [e, f, g]
$vector->insert(0, "a", "b");        // [a, b, e, f, g]
$vector->insert(2, ...["c", "d"]);   // [a, b, c, d, e, f, g]

var_dump($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Vector)#1 (7) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
  [6]=>
  string(1) "g"
}
Ds\Vector::get
Ds\Vector::isEmpty
Vector


Returns whether the vector is empty

Ds\Vector::insert
Ds\Vector::join
Vector
PHP Manual

Ds\Vector::isEmpty

(PECL ds >= 1.0.0)

Ds\Vector::isEmpty — Returns whether the vector is empty

Descrierea

public bool Ds\Vector::isEmpty ( void )

Returns whether the vector is empty.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the vector is empty, FALSE otherwise.

Exemple

Example #1 Ds\Vector::isEmpty() example

<?php
$a = new \Ds\Vector([1, 2, 3]);
$b = new \Ds\Vector();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
bool(true)
Ds\Vector::insert
Ds\Vector::join
Vector


Joins all values together as a string.

Ds\Vector::isEmpty
Ds\Vector::jsonSerialize
Vector
PHP Manual

Ds\Vector::join

(PECL ds >= 1.0.0)

Ds\Vector::join — Joins all values together as a string.

Descrierea

public string Ds\Vector::join ([ string $glue ] )

Joins all values together as a string using an optional separator between each value.

Parametri

glue

An optional string to separate each value.

Valorile întoarse

All values of the vector joined together as a string.

Exemple

Example #1 Ds\Vector::join() example using a separator string

<?php
$vector = new \Ds\Vector(["a", "b", "c", 1, 2, 3]);

var_dump($vector->join("|"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(11) "a|b|c|1|2|3"

Example #2 Ds\Vector::join() example without a separator string

<?php
$vector = new \Ds\Vector(["a", "b", "c", 1, 2, 3]);

var_dump($vector->join());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(11) "abc123"
Ds\Vector::isEmpty
Ds\Vector::jsonSerialize
Vector


Returns a representation that can be converted to JSON.

Ds\Vector::join
Ds\Vector::last
Vector
PHP Manual

Ds\Vector::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Vector::jsonSerialize — Returns a representation that can be converted to JSON.

See JsonSerializable::jsonSerialize()

Nota:

You should never need to call this directly.

Ds\Vector::join
Ds\Vector::last
Vector


Returns the last value.

Ds\Vector::jsonSerialize
Ds\Vector::map
Vector
PHP Manual

Ds\Vector::last

(PECL ds >= 1.0.0)

Ds\Vector::last — Returns the last value.

Descrierea

public mixed Ds\Vector::last ( void )

Returns the last value in the vector.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The last value in the vector.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Vector::last() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
var_dump($vector->last());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)
Ds\Vector::jsonSerialize
Ds\Vector::map
Vector


Returns the result of applying a callback to each value.

Ds\Vector::last
Ds\Vector::merge
Vector
PHP Manual

Ds\Vector::map

(PECL ds >= 1.0.0)

Ds\Vector::map — Returns the result of applying a callback to each value.

Descrierea

public Ds\Vector Ds\Vector::map ( callable $callback )

Returns the result of applying a callback function to each value in the vector.

Parametri

callback

mixed callback ( mixed $value )

A callable to apply to each value in the vector.

The callable should return what the new value will be in the new vector.

Valorile întoarse

The result of applying a callback to each value in the vector.

Nota:

The values of the current instance won't be affected.

Exemple

Example #1 Ds\Vector::map() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

print_r($vector->map(function($value) { return $value * 2; }));
print_r($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Vector::last
Ds\Vector::merge
Vector


Returns the result of adding all given values to the vector.

Ds\Vector::map
Ds\Vector::pop
Vector
PHP Manual

Ds\Vector::merge

(PECL ds >= 1.0.0)

Ds\Vector::merge — Returns the result of adding all given values to the vector.

Descrierea

public Ds\Vector Ds\Vector::merge ( mixed $values )

Returns the result of adding all given values to the vector.

Parametri

values

A traversable object or an array.

Valorile întoarse

The result of adding all given values to the vector, effectively the same as adding the values to a copy, then returning that copy.

Nota:

The current instance won't be affected.

Exemple

Example #1 Ds\Vector::merge() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

var_dump($vector->merge([4, 5, 6]));
var_dump($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Vector)#2 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}
object(Ds\Vector)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Vector::map
Ds\Vector::pop
Vector


Removes and returns the last value.

Ds\Vector::merge
Ds\Vector::push
Vector
PHP Manual

Ds\Vector::pop

(PECL ds >= 1.0.0)

Ds\Vector::pop — Removes and returns the last value.

Descrierea

public mixed Ds\Vector::pop ( void )

Removes and returns the last value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The removed last value.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Vector::pop() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

var_dump($vector->pop());
var_dump($vector->pop());
var_dump($vector->pop());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)
int(2)
int(1)
Ds\Vector::merge
Ds\Vector::push
Vector


Adds values to the end of the vector.

Ds\Vector::pop
Ds\Vector::reduce
Vector
PHP Manual

Ds\Vector::push

(PECL ds >= 1.0.0)

Ds\Vector::push — Adds values to the end of the vector.

Descrierea

public void Ds\Vector::push ([ mixed $...values ] )

Adds values to the end of the vector.

Parametri

values

The values to add.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Vector::push() example

<?php
$vector = new \Ds\Vector();

$vector->push("a");
$vector->push("b");
$vector->push("c", "d");
$vector->push(...["e", "f"]);

print_r($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)
Ds\Vector::pop
Ds\Vector::reduce
Vector


Reduces the vector to a single value using a callback function.

Ds\Vector::push
Ds\Vector::remove
Vector
PHP Manual

Ds\Vector::reduce

(PECL ds >= 1.0.0)

Ds\Vector::reduce — Reduces the vector to a single value using a callback function.

Descrierea

public mixed Ds\Vector::reduce ( callable $callback [, mixed $initial ] )

Reduces the vector to a single value using a callback function.

Parametri

callback
mixed callback ( mixed $carry , mixed $value )
carry

The return value of the previous callback, or initial if it's the first iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be NULL.

Valorile întoarse

The return value of the final callback.

Exemple

Example #1 Ds\Vector::reduce() with initial value example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

$callback = function($carry, $value) {
    return $carry * $value;
};

var_dump($vector->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 =  5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(30)

Example #2 Ds\Vector::reduce() without an initial value example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

var_dump($vector->reduce(function($carry, $value) {
    return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 =  6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(21)
Ds\Vector::push
Ds\Vector::remove
Vector


Removes and returns a value by index.

Ds\Vector::reduce
Ds\Vector::reverse
Vector
PHP Manual

Ds\Vector::remove

(PECL ds >= 1.0.0)

Ds\Vector::remove — Removes and returns a value by index.

Descrierea

public mixed Ds\Vector::remove ( int $index )

Removes and returns a value by index.

Parametri

index

The index of the value to remove.

Valorile întoarse

The value that was removed.

Erori/Excep?ii

OutOfRangeException if the index is not valid.

Exemple

Example #1 Ds\Vector::remove() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

var_dump($vector->remove(1));
var_dump($vector->remove(0));
var_dump($vector->remove(0));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "b"
string(1) "a"
string(1) "c"
Ds\Vector::reduce
Ds\Vector::reverse
Vector


Reverses the vector in-place.

Ds\Vector::remove
Ds\Vector::reversed
Vector
PHP Manual

Ds\Vector::reverse

(PECL ds >= 1.0.0)

Ds\Vector::reverse — Reverses the vector in-place.

Descrierea

public void Ds\Vector::reverse ( void )

Reverses the vector in-place.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Vector::reverse() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);
$vector->reverse();

print_r($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Vector::remove
Ds\Vector::reversed
Vector


Returns a reversed copy.

Ds\Vector::reverse
Ds\Vector::rotate
Vector
PHP Manual

Ds\Vector::reversed

(PECL ds >= 1.0.0)

Ds\Vector::reversed — Returns a reversed copy.

Descrierea

public Ds\Vector Ds\Vector::reversed ( void )

Returns a reversed copy of the vector.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A reversed copy of the vector.

Nota:

The current instance is not affected.

Exemple

Example #1 Ds\Vector::reversed() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

print_r($vector->reversed());
print_r($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
)
Ds\Vector::reverse
Ds\Vector::rotate
Vector


Rotates the vector by a given number of rotations.

Ds\Vector::reversed
Ds\Vector::set
Vector
PHP Manual

Ds\Vector::rotate

(PECL ds >= 1.0.0)

Ds\Vector::rotate — Rotates the vector by a given number of rotations.

Descrierea

public void Ds\Vector::rotate ( int $rotations )

Rotates the vector by a given number of rotations, which is equivalent to successively calling $vector->push($vector->shift()) if the number of rotations is positive, or $vector->unshift($vector->pop()) if negative.

Parametri

rotations

The number of times the vector should be rotated.

Valorile întoarse

Nu este întoarsa nici o valoare.. The vector of the current instance will be rotated.

Exemple

Example #1 Ds\Vector::rotate() example

<?php
$vector = new \Ds\Vector(["a", "b", "c", "d"]);

$vector->rotate(1);  // "a" is shifted, then pushed.
print_r($vector);

$vector->rotate(2);  // "b" and "c" are both shifted, the pushed.
print_r($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

(
    [0] => b
    [1] => c
    [2] => d
    [3] => a
)
Ds\Vector Object
(
    [0] => d
    [1] => a
    [2] => b
    [3] => c
)
Ds\Vector::reversed
Ds\Vector::set
Vector


Updates a value at a given index.

Ds\Vector::rotate
Ds\Vector::shift
Vector
PHP Manual

Ds\Vector::set

(PECL ds >= 1.0.0)

Ds\Vector::set — Updates a value at a given index.

Descrierea

public void Ds\Vector::set ( int $index , mixed $value )

Updates a value at a given index.

Parametri

index

The index of the value to update.

value

The new value.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

OutOfRangeException if the index is not valid.

Exemple

Example #1 Ds\Vector::set() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

$vector->set(1, "_");
print_r($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => a
    [1] => _
    [2] => c
)

Example #2 Ds\Vector::set() example using array syntax

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

$vector[1] = "_";
print_r($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => a
    [1] => _
    [2] => c
)
Ds\Vector::rotate
Ds\Vector::shift
Vector


Removes and returns the first value.

Ds\Vector::set
Ds\Vector::slice
Vector
PHP Manual

Ds\Vector::shift

(PECL ds >= 1.0.0)

Ds\Vector::shift — Removes and returns the first value.

Descrierea

public mixed Ds\Vector::shift ( void )

Removes and returns the first value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The first value, which was removed.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Vector::shift() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

var_dump($vector->shift());
var_dump($vector->shift());
var_dump($vector->shift());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
string(1) "b"
string(1) "c"
Ds\Vector::set
Ds\Vector::slice
Vector


Returns a sub-vector of a given range.

Ds\Vector::shift
Ds\Vector::sort
Vector
PHP Manual

Ds\Vector::slice

(PECL ds >= 1.0.0)

Ds\Vector::slice — Returns a sub-vector of a given range.

Descrierea

public Ds\Vector Ds\Vector::slice ( int $index [, int $length ] )

Creates a sub-vector of a given range.

Parametri

index

The index at which the sub-vector starts.

If positive, the vector will start at that index in the vector. If negative, the vector will start that far from the end.

length

If a length is given and is positive, the resulting vector will have up to that many values in it. If the length results in an overflow, only values up to the end of the vector will be included. If a length is given and is negative, the vector will stop that many values from the end. If a length is not provided, the resulting vector will contain all values between the index and the end of the vector.

Valorile întoarse

A sub-vector of the given range.

Exemple

Example #1 Ds\Vector::slice() example

<?php
$vector = new \Ds\Vector(["a", "b", "c", "d", "e"]);

// Slice from 2 onwards
print_r($vector->slice(2));

// Slice from 1, for a length of 3
print_r($vector->slice(1, 3));

// Slice from 1 onwards
print_r($vector->slice(1));

// Slice from 2 from the end onwards
print_r($vector->slice(-2));

// Slice from 1 to 1 from the end
print_r($vector->slice(1, -1));
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => c
    [1] => d
    [2] => e
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)
Ds\Vector Object
(
    [0] => d
    [1] => e
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Vector::shift
Ds\Vector::sort
Vector


Sorts the vector in-place.

Ds\Vector::slice
Ds\Vector::sorted
Vector
PHP Manual

Ds\Vector::sort

(PECL ds >= 1.0.0)

Ds\Vector::sort — Sorts the vector in-place.

Descrierea

public void Ds\Vector::sort ([ callable $comparator ] )

Sorts the vector in-place, using an optional comparator function.

Parametri

comparator

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
Precautie

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Vector::sort() example

<?php
$vector = new \Ds\Vector([4, 5, 1, 3, 2]);
$vector->sort();

print_r($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Vector::sort() example using a comparator

<?php
$vector = new \Ds\Vector([4, 5, 1, 3, 2]);

$vector->sort(function($a, $b) {
    return $b <=> $a;
});

print_r($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)
Ds\Vector::slice
Ds\Vector::sorted
Vector


Returns a sorted copy.

Ds\Vector::sort
Ds\Vector::sum
Vector
PHP Manual

Ds\Vector::sorted

(PECL ds >= 1.0.0)

Ds\Vector::sorted — Returns a sorted copy.

Descrierea

public Ds\Vector Ds\Vector::sorted ([ callable $comparator ] )

Returns a sorted copy, using an optional comparator function.

Parametri

comparator

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
Precautie

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valorile întoarse

Returns a sorted copy of the vector.

Exemple

Example #1 Ds\Vector::sorted() example

<?php
$vector = new \Ds\Vector([4, 5, 1, 3, 2]);

print_r($vector->sorted());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Vector::sorted() example using a comparator

<?php
$vector = new \Ds\Vector([4, 5, 1, 3, 2]);

$sorted = $vector->sorted(function($a, $b) {
    return $b <=> $a;
});

print_r($sorted);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)
Ds\Vector::sort
Ds\Vector::sum
Vector


Returns the sum of all values in the vector.

Ds\Vector::sorted
Ds\Vector::toArray
Vector
PHP Manual

Ds\Vector::sum

(PECL ds >= 1.0.0)

Ds\Vector::sum — Returns the sum of all values in the vector.

Descrierea

public number Ds\Vector::sum ( void )

Returns the sum of all values in the vector.

Nota:

Arrays and objects are considered equal to zero when calculating the sum.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The sum of all the values in the vector as either a float or int depending on the values in the vector.

Exemple

Example #1 Ds\Vector::sum() integer example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
var_dump($vector->sum());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(6)

Example #2 Ds\Vector::sum() float example

<?php
$vector = new \Ds\Vector([1, 2.5, 3]);
var_dump($vector->sum());
?>

Exemplul de mai sus va afi?a ceva similar cu:

float(6.5)
Ds\Vector::sorted
Ds\Vector::toArray
Vector


Converts the vector to an array.

Ds\Vector::sum
Ds\Vector::unshift
Vector
PHP Manual

Ds\Vector::toArray

(PECL ds >= 1.0.0)

Ds\Vector::toArray — Converts the vector to an array.

Descrierea

public array Ds\Vector::toArray ( void )

Converts the vector to an array.

Nota:

Casting to an array is not supported yet.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array containing all the values in the same order as the vector.

Exemple

Example #1 Ds\Vector::toArray() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

var_dump($vector->toArray());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Vector::sum
Ds\Vector::unshift
Vector


Adds values to the front of the vector.

Ds\Vector::toArray
Deque
Vector
PHP Manual

Ds\Vector::unshift

(PECL ds >= 1.0.0)

Ds\Vector::unshift — Adds values to the front of the vector.

Descrierea

public void Ds\Vector::unshift ([ mixed $values ] )

Adds values to the front of the vector, moving all the current values forward to make room for the new values.

Parametri

values

The values to add to the front of the vector.

Nota:

Multiple values will be added in the same order that they are passed.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Vector::unshift() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

$vector->unshift("a");
$vector->unshift("b", "c");

print_r($vector);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => a
    [3] => 1
    [4] => 2
    [5] => 3
)
Ds\Vector::toArray
Deque
Vector


The Deque class

(No version information available, might only be in Git)

Introducere

A Deque (pronounced “deck”) is a sequence of values in a contiguous buffer that grows and shrinks automatically. The name is a common abbreviation of “double-ended queue” and is used internally by Ds\Queue.

Two pointers are used to keep track of a head and a tail. The pointers can “wrap around” the end of the buffer, which avoids the need to move other values around to make room. This makes shift and unshift very fast?—? something a Ds\Vector can’t compete with.

Accessing a value by index requires a translation between the index and its corresponding position in the buffer: ((head + position) % capacity).

Strengths

  • Supports array syntax (square brackets).
  • Uses less overall memory than an array for the same number of values.
  • Automatically frees allocated memory when its size drops low enough.
  • get(),
set(),
push(),
pop(),
shift(), and
unshift() are all O(1).

Weaknesses

  • Capacity must be a power of 2.
  • insert() and remove() are O(n).

Sinopsisul clasei

Ds\Deque implements Ds\Sequence {
/* Constants */
const int MIN_CAPACITY = 8 ;
/* Metode */
public void allocate ( int $capacity )
public void apply ( callable $callback )
public int capacity ( void )
public void clear ( void )
public bool contains ([ mixed $...values ] )
public Ds\Deque copy ( void )
public Ds\Deque filter ([ callable $callback ] )
public mixed find ( mixed $value )
public mixed first ( void )
public mixed get ( int $index )
public void insert ( int $index [, mixed $...values ] )
public bool isEmpty ( void )
public string join ([ string $glue ] )
public mixed last ( void )
public Ds\Deque map ( callable $callback )
public Ds\Deque merge ( mixed $values )
public mixed pop ( void )
public void push ([ mixed $...values ] )
public mixed reduce ( callable $callback [, mixed $initial ] )
public mixed remove ( int $index )
public void reverse ( void )
public Ds\Deque reversed ( void )
public void rotate ( int $rotations )
public void set ( int $index , mixed $value )
public mixed shift ( void )
public Ds\Deque slice ( int $index [, int $length ] )
public void sort ([ callable $comparator ] )
public Ds\Deque sorted ([ callable $comparator ] )
public number sum ( void )
public array toArray ( void )
public void unshift ([ mixed $values ] )
}

Constante predefinite

Ds\Deque::MIN_CAPACITY

Cuprins

  • Ds\Deque::allocate — Allocates enough memory for a required capacity.
  • Ds\Deque::apply — Updates all values by applying a callback function to each value.
  • Ds\Deque::capacity — Returns the current capacity.
  • Ds\Deque::clear — Removes all values from the deque.
  • Ds\Deque::__construct — Creates a new instance.
  • Ds\Deque::contains — Determines if the deque contains given values.
  • Ds\Deque::copy — Returns a shallow copy of the deque.
  • Ds\Deque::count — Returns the number of values in the collection.
  • Ds\Deque::filter — Creates a new deque using a callable to determine which values to include.
  • Ds\Deque::find — Attempts to find a value's index.
  • Ds\Deque::first — Returns the first value in the deque.
  • Ds\Deque::get — Returns the value at a given index.
  • Ds\Deque::insert — Inserts values at a given index.
  • Ds\Deque::isEmpty — Returns whether the deque is empty
  • Ds\Deque::join — Joins all values together as a string.
  • Ds\Deque::jsonSerialize — Returns a representation that can be converted to JSON.
  • Ds\Deque::last — Returns the last value.
  • Ds\Deque::map — Returns the result of applying a callback to each value.
  • Ds\Deque::merge — Returns the result of adding all given values to the deque.
  • Ds\Deque::pop — Removes and returns the last value.
  • Ds\Deque::push — Adds values to the end of the deque.
  • Ds\Deque::reduce — Reduces the deque to a single value using a callback function.
  • Ds\Deque::remove — Removes and returns a value by index.
  • Ds\Deque::reverse — Reverses the deque in-place.
  • Ds\Deque::reversed — Returns a reversed copy.
  • Ds\Deque::rotate — Rotates the deque by a given number of rotations.
  • Ds\Deque::set — Updates a value at a given index.
  • Ds\Deque::shift — Removes and returns the first value.
  • Ds\Deque::slice — Returns a sub-deque of a given range.
  • Ds\Deque::sort — Sorts the deque in-place.
  • Ds\Deque::sorted — Returns a sorted copy.
  • Ds\Deque::sum — Returns the sum of all values in the deque.
  • Ds\Deque::toArray — Converts the deque to an array.
  • Ds\Deque::unshift — Adds values to the front of the deque.
Ds\Vector::unshift
Ds\Deque::allocate
Data Structures


Allocates enough memory for a required capacity.

Deque
Ds\Deque::apply
Deque
PHP Manual

Ds\Deque::allocate

(PECL ds >= 1.0.0)

Ds\Deque::allocate — Allocates enough memory for a required capacity.

Descrierea

public void Ds\Deque::allocate ( int $capacity )

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

Parametri

capacity

The number of values for which capacity should be allocated.

Nota:

Capacity will stay the same if this value is less than or equal to the current capacity.

Nota:

Capacity will always be rounded up to the nearest power of 2.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Deque::allocate() example

<?php
$deque = new \Ds\Deque();
var_dump($deque->capacity());

$deque->allocate(100);
var_dump($deque->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(8)
int(128)
Deque
Ds\Deque::apply
Deque


Updates all values by applying a callback function to each value.

Ds\Deque::allocate
Ds\Deque::capacity
Deque
PHP Manual

Ds\Deque::apply

(PECL ds >= 1.0.0)

Ds\Deque::apply — Updates all values by applying a callback function to each value.

Descrierea

public void Ds\Deque::apply ( callable $callback )

Updates all values by applying a callback function to each value in the deque.

Parametri

callback

mixed callback ( mixed $value )

A callable to apply to each value in the deque.

The callback should return what the value should be replaced by.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Deque::apply() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
$deque->apply(function($value) { return $value * 2; });

print_r($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)
Ds\Deque::allocate
Ds\Deque::capacity
Deque


Returns the current capacity.

Ds\Deque::apply
Ds\Deque::clear
Deque
PHP Manual

Ds\Deque::capacity

(PECL ds >= 1.0.0)

Ds\Deque::capacity — Returns the current capacity.

Descrierea

public int Ds\Deque::capacity ( void )

Returns the current capacity.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current capacity.

Exemple

Example #1 Ds\Deque::capacity() example

<?php
$deque = new \Ds\Deque();
var_dump($deque->capacity());

$deque->push(...range(1, 50));
var_dump($deque->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(8)
int(64)
Ds\Deque::apply
Ds\Deque::clear
Deque


Removes all values from the deque.

Ds\Deque::capacity
Ds\Deque::__construct
Deque
PHP Manual

Ds\Deque::clear

(PECL ds >= 1.0.0)

Ds\Deque::clear — Removes all values from the deque.

Descrierea

public void Ds\Deque::clear ( void )

Removes all values from the deque.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Deque::clear() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
print_r($deque);

$deque->clear();
print_r($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Deque Object
(
)
Ds\Deque::capacity
Ds\Deque::__construct
Deque


Creates a new instance.

Ds\Deque::clear
Ds\Deque::contains
Deque
PHP Manual

Ds\Deque::__construct

(PECL ds >= 1.0.0)

Ds\Deque::__construct — Creates a new instance.

Descrierea

public Ds\Deque::__construct ([ mixed $values ] )

Creates a new instance, using either a traversable object or an array for the initial values.

Parametri

values

A traversable object or an array to use for the initial values.

Exemple

Example #1 Ds\Deque::__construct() example

<?php
$deque = new \Ds\Deque();
var_dump($deque);

$deque = new \Ds\Deque([1, 2, 3]);
var_dump($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Deque)#2 (0) {
}
object(Ds\Deque)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Deque::clear
Ds\Deque::contains
Deque


Determines if the deque contains given values.

Ds\Deque::__construct
Ds\Deque::copy
Deque
PHP Manual

Ds\Deque::contains

(PECL ds >= 1.0.0)

Ds\Deque::contains — Determines if the deque contains given values.

Descrierea

public bool Ds\Deque::contains ([ mixed $...values ] )

Determines if the deque contains all values.

Parametri

values

Values to check.

Valorile întoarse

FALSE if any of the provided values are not in the deque, TRUE otherwise.

Exemple

Example #1 Ds\Deque::contains() example

<?php
$deque = new \Ds\Deque(['a', 'b', 'c', 1, 2, 3]);

var_dump($deque->contains('a'));                // true
var_dump($deque->contains('a', 'b'));           // true
var_dump($deque->contains('c', 'd'));           // false

var_dump($deque->contains(...['c', 'b', 'a'])); // true

// Always strict
var_dump($deque->contains(1));                  // true
var_dump($deque->contains('1'));                // false

var_dump($sequece->contains(...[]));               // true
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
Ds\Deque::__construct
Ds\Deque::copy
Deque


Returns a shallow copy of the deque.

Ds\Deque::contains
Ds\Deque::count
Deque
PHP Manual

Ds\Deque::copy

(PECL ds >= 1.0.0)

Ds\Deque::copy — Returns a shallow copy of the deque.

Descrierea

public Ds\Deque Ds\Deque::copy ( void )

Returns a shallow copy of the deque.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A shallow copy of the deque.

Exemple

Example #1 Ds\Deque::copy() example

<?php
$a = new \Ds\Deque([1, 2, 3]);
$b = $a->copy();

$b->push(4);

print_r($a);
print_r($b);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
Ds\Deque::contains
Ds\Deque::count
Deque


Returns the number of values in the collection.

Ds\Deque::copy
Ds\Deque::filter
Deque
PHP Manual

Ds\Deque::count

(PECL ds >= 1.0.0)

Ds\Deque::count — Returns the number of values in the collection.

See Countable::count()

Ds\Deque::copy
Ds\Deque::filter
Deque


Creates a new deque using a callable to determine which values to include.

Ds\Deque::count
Ds\Deque::find
Deque
PHP Manual

Ds\Deque::filter

(PECL ds >= 1.0.0)

Ds\Deque::filter — Creates a new deque using a callable to determine which values to include.

Descrierea

public Ds\Deque Ds\Deque::filter ([ callable $callback ] )

Creates a new deque using a callable to determine which values to include.

Parametri

callback

bool callback ( mixed $value )

Optional callable which returns TRUE if the value should be included, FALSE otherwise.

If a callback is not provided, only values which are TRUE (see converting to boolean) will be included.

Valorile întoarse

A new deque containing all the values for which either the callback returned TRUE, or all values that convert to TRUE if a callback was not provided.

Exemple

Example #1 Ds\Deque::filter() example using callback function

<?php
$deque = new \Ds\Deque([1, 2, 3, 4, 5]);

var_dump($deque->filter(function($value) {
    return $value % 2 == 0;
}));
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Deque)#3 (2) {
  [0]=>
  int(2)
  [1]=>
  int(4)
}

Example #2 Ds\Deque::filter() example without a callback function

<?php
$deque = new \Ds\Deque([0, 1, 'a', true, false]);

var_dump($deque->filter());
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Deque)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}
Ds\Deque::count
Ds\Deque::find
Deque


Attempts to find a value's index.

Ds\Deque::filter
Ds\Deque::first
Deque
PHP Manual

Ds\Deque::find

(PECL ds >= 1.0.0)

Ds\Deque::find — Attempts to find a value's index.

Descrierea

public mixed Ds\Deque::find ( mixed $value )

Returns the index of the value, or FALSE if not found.

Parametri

value

The value to find.

Valorile întoarse

The index of the value, or FALSE if not found.

Nota:

Values will be compared by value and by type.

Exemple

Example #1 Ds\Deque::find() example

<?php
$deque = new \Ds\Deque(["a", 1, true]);

var_dump($deque->find("a")); // 0
var_dump($deque->find("b")); // false
var_dump($deque->find("1")); // false
var_dump($deque->find(1));   // 1
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(0)
bool(false)
bool(false)
int(1)
Ds\Deque::filter
Ds\Deque::first
Deque


Returns the first value in the deque.

Ds\Deque::find
Ds\Deque::get
Deque
PHP Manual

Ds\Deque::first

(PECL ds >= 1.0.0)

Ds\Deque::first — Returns the first value in the deque.

Descrierea

public mixed Ds\Deque::first ( void )

Returns the first value in the deque.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The first value in the deque.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Deque::first() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
var_dump($deque->first());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(1)
Ds\Deque::find
Ds\Deque::get
Deque


Returns the value at a given index.

Ds\Deque::first
Ds\Deque::insert
Deque
PHP Manual

Ds\Deque::get

(PECL ds >= 1.0.0)

Ds\Deque::get — Returns the value at a given index.

Descrierea

public mixed Ds\Deque::get ( int $index )

Returns the value at a given index.

Parametri

index

The index to access, starting at 0.

Valorile întoarse

The value at the requested index.

Erori/Excep?ii

OutOfRangeException if the index is not valid.

Exemple

Example #1 Ds\Deque::get() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

var_dump($deque->get(0));
var_dump($deque->get(1));
var_dump($deque->get(2));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
string(1) "b"
string(1) "c"

Example #2 Ds\Deque::get() example using array syntax

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

var_dump($deque[0]);
var_dump($deque[1]);
var_dump($deque[2]);
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
string(1) "b"
string(1) "c"
Ds\Deque::first
Ds\Deque::insert
Deque


Inserts values at a given index.

Ds\Deque::get
Ds\Deque::isEmpty
Deque
PHP Manual

Ds\Deque::insert

(PECL ds >= 1.0.0)

Ds\Deque::insert — Inserts values at a given index.

Descrierea

public void Ds\Deque::insert ( int $index [, mixed $...values ] )

Inserts values into the deque at a given index.

Parametri

index

The index at which to insert. 0 <= index <= count

Nota:

You can insert at the index equal to the number of values.

values

The value or values to insert.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

OutOfRangeException if the index is not valid.

Exemple

Example #1 Ds\Deque::insert() example

<?php
$deque = new \Ds\Deque();

$deque->insert(0, "e");             // [e]
$deque->insert(1, "f");             // [e, f]
$deque->insert(2, "g");             // [e, f, g]
$deque->insert(0, "a", "b");        // [a, b, e, f, g]
$deque->insert(2, ...["c", "d"]);   // [a, b, c, d, e, f, g]

var_dump($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Deque)#1 (7) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
  [6]=>
  string(1) "g"
}
Ds\Deque::get
Ds\Deque::isEmpty
Deque


Returns whether the deque is empty

Ds\Deque::insert
Ds\Deque::join
Deque
PHP Manual

Ds\Deque::isEmpty

(PECL ds >= 1.0.0)

Ds\Deque::isEmpty — Returns whether the deque is empty

Descrierea

public bool Ds\Deque::isEmpty ( void )

Returns whether the deque is empty.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the deque is empty, FALSE otherwise.

Exemple

Example #1 Ds\Deque::isEmpty() example

<?php
$a = new \Ds\Deque([1, 2, 3]);
$b = new \Ds\Deque();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
bool(true)
Ds\Deque::insert
Ds\Deque::join
Deque


Joins all values together as a string.

Ds\Deque::isEmpty
Ds\Deque::jsonSerialize
Deque
PHP Manual

Ds\Deque::join

(PECL ds >= 1.0.0)

Ds\Deque::join — Joins all values together as a string.

Descrierea

public string Ds\Deque::join ([ string $glue ] )

Joins all values together as a string using an optional separator between each value.

Parametri

glue

An optional string to separate each value.

Valorile întoarse

All values of the deque joined together as a string.

Exemple

Example #1 Ds\Deque::join() example using a separator string

<?php
$deque = new \Ds\Deque(["a", "b", "c", 1, 2, 3]);

var_dump($deque->join("|"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(11) "a|b|c|1|2|3"

Example #2 Ds\Deque::join() example without a separator string

<?php
$deque = new \Ds\Deque(["a", "b", "c", 1, 2, 3]);

var_dump($deque->join());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(11) "abc123"
Ds\Deque::isEmpty
Ds\Deque::jsonSerialize
Deque


Returns a representation that can be converted to JSON.

Ds\Deque::join
Ds\Deque::last
Deque
PHP Manual

Ds\Deque::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Deque::jsonSerialize — Returns a representation that can be converted to JSON.

See JsonSerializable::jsonSerialize()

Nota:

You should never need to call this directly.

Ds\Deque::join
Ds\Deque::last
Deque


Returns the last value.

Ds\Deque::jsonSerialize
Ds\Deque::map
Deque
PHP Manual

Ds\Deque::last

(PECL ds >= 1.0.0)

Ds\Deque::last — Returns the last value.

Descrierea

public mixed Ds\Deque::last ( void )

Returns the last value in the deque.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The last value in the deque.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Deque::last() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
var_dump($deque->last());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)
Ds\Deque::jsonSerialize
Ds\Deque::map
Deque


Returns the result of applying a callback to each value.

Ds\Deque::last
Ds\Deque::merge
Deque
PHP Manual

Ds\Deque::map

(PECL ds >= 1.0.0)

Ds\Deque::map — Returns the result of applying a callback to each value.

Descrierea

public Ds\Deque Ds\Deque::map ( callable $callback )

Returns the result of applying a callback function to each value in the deque.

Parametri

callback

mixed callback ( mixed $value )

A callable to apply to each value in the deque.

The callable should return what the new value will be in the new deque.

Valorile întoarse

The result of applying a callback to each value in the deque.

Nota:

The values of the current instance won't be affected.

Exemple

Example #1 Ds\Deque::map() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

print_r($deque->map(function($value) { return $value * 2; }));
print_r($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Deque::last
Ds\Deque::merge
Deque


Returns the result of adding all given values to the deque.

Ds\Deque::map
Ds\Deque::pop
Deque
PHP Manual

Ds\Deque::merge

(PECL ds >= 1.0.0)

Ds\Deque::merge — Returns the result of adding all given values to the deque.

Descrierea

public Ds\Deque Ds\Deque::merge ( mixed $values )

Returns the result of adding all given values to the deque.

Parametri

values

A traversable object or an array.

Valorile întoarse

The result of adding all given values to the deque, effectively the same as adding the values to a copy, then returning that copy.

Nota:

The current instance won't be affected.

Exemple

Example #1 Ds\Deque::merge() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

var_dump($deque->merge([4, 5, 6]));
var_dump($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Deque)#2 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}
object(Ds\Deque)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Deque::map
Ds\Deque::pop
Deque


Removes and returns the last value.

Ds\Deque::merge
Ds\Deque::push
Deque
PHP Manual

Ds\Deque::pop

(PECL ds >= 1.0.0)

Ds\Deque::pop — Removes and returns the last value.

Descrierea

public mixed Ds\Deque::pop ( void )

Removes and returns the last value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The removed last value.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Deque::pop() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

var_dump($deque->pop());
var_dump($deque->pop());
var_dump($deque->pop());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)
int(2)
int(1)
Ds\Deque::merge
Ds\Deque::push
Deque


Adds values to the end of the deque.

Ds\Deque::pop
Ds\Deque::reduce
Deque
PHP Manual

Ds\Deque::push

(PECL ds >= 1.0.0)

Ds\Deque::push — Adds values to the end of the deque.

Descrierea

public void Ds\Deque::push ([ mixed $...values ] )

Adds values to the end of the deque.

Parametri

values

The values to add.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Deque::push() example

<?php
$deque = new \Ds\Deque();

$deque->push("a");
$deque->push("b");
$deque->push("c", "d");
$deque->push(...["e", "f"]);

print_r($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)
Ds\Deque::pop
Ds\Deque::reduce
Deque


Reduces the deque to a single value using a callback function.

Ds\Deque::push
Ds\Deque::remove
Deque
PHP Manual

Ds\Deque::reduce

(PECL ds >= 1.0.0)

Ds\Deque::reduce — Reduces the deque to a single value using a callback function.

Descrierea

public mixed Ds\Deque::reduce ( callable $callback [, mixed $initial ] )

Reduces the deque to a single value using a callback function.

Parametri

callback
mixed callback ( mixed $carry , mixed $value )
carry

The return value of the previous callback, or initial if it's the first iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be NULL.

Valorile întoarse

The return value of the final callback.

Exemple

Example #1 Ds\Deque::reduce() with initial value example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

$callback = function($carry, $value) {
    return $carry * $value;
};

var_dump($deque->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 =  5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(30)

Example #2 Ds\Deque::reduce() without an initial value example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

var_dump($deque->reduce(function($carry, $value) {
    return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 =  6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(21)
Ds\Deque::push
Ds\Deque::remove
Deque


Removes and returns a value by index.

Ds\Deque::reduce
Ds\Deque::reverse
Deque
PHP Manual

Ds\Deque::remove

(PECL ds >= 1.0.0)

Ds\Deque::remove — Removes and returns a value by index.

Descrierea

public mixed Ds\Deque::remove ( int $index )

Removes and returns a value by index.

Parametri

index

The index of the value to remove.

Valorile întoarse

The value that was removed.

Erori/Excep?ii

OutOfRangeException if the index is not valid.

Exemple

Example #1 Ds\Deque::remove() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

var_dump($deque->remove(1));
var_dump($deque->remove(0));
var_dump($deque->remove(0));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "b"
string(1) "a"
string(1) "c"
Ds\Deque::reduce
Ds\Deque::reverse
Deque


Reverses the deque in-place.

Ds\Deque::remove
Ds\Deque::reversed
Deque
PHP Manual

Ds\Deque::reverse

(PECL ds >= 1.0.0)

Ds\Deque::reverse — Reverses the deque in-place.

Descrierea

public void Ds\Deque::reverse ( void )

Reverses the deque in-place.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Deque::reverse() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);
$deque->reverse();

print_r($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Deque::remove
Ds\Deque::reversed
Deque


Returns a reversed copy.

Ds\Deque::reverse
Ds\Deque::rotate
Deque
PHP Manual

Ds\Deque::reversed

(PECL ds >= 1.0.0)

Ds\Deque::reversed — Returns a reversed copy.

Descrierea

public Ds\Deque Ds\Deque::reversed ( void )

Returns a reversed copy of the deque.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A reversed copy of the deque.

Nota:

The current instance is not affected.

Exemple

Example #1 Ds\Deque::reversed() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

print_r($deque->reversed());
print_r($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Deque Object
(
    [0] => a
    [1] => b
    [2] => c
)
Ds\Deque::reverse
Ds\Deque::rotate
Deque


Rotates the deque by a given number of rotations.

Ds\Deque::reversed
Ds\Deque::set
Deque
PHP Manual

Ds\Deque::rotate

(PECL ds >= 1.0.0)

Ds\Deque::rotate — Rotates the deque by a given number of rotations.

Descrierea

public void Ds\Deque::rotate ( int $rotations )

Rotates the deque by a given number of rotations, which is equivalent to successively calling $deque->push($deque->shift()) if the number of rotations is positive, or $deque->unshift($deque->pop()) if negative.

Parametri

rotations

The number of times the deque should be rotated.

Valorile întoarse

Nu este întoarsa nici o valoare.. The deque of the current instance will be rotated.

Exemple

Example #1 Ds\Deque::rotate() example

<?php
$deque = new \Ds\Deque(["a", "b", "c", "d"]);

$deque->rotate(1);  // "a" is shifted, then pushed.
print_r($deque);

$deque->rotate(2);  // "b" and "c" are both shifted, the pushed.
print_r($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

(
    [0] => b
    [1] => c
    [2] => d
    [3] => a
)
Ds\Deque Object
(
    [0] => d
    [1] => a
    [2] => b
    [3] => c
)
Ds\Deque::reversed
Ds\Deque::set
Deque


Updates a value at a given index.

Ds\Deque::rotate
Ds\Deque::shift
Deque
PHP Manual

Ds\Deque::set

(PECL ds >= 1.0.0)

Ds\Deque::set — Updates a value at a given index.

Descrierea

public void Ds\Deque::set ( int $index , mixed $value )

Updates a value at a given index.

Parametri

index

The index of the value to update.

value

The new value.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

OutOfRangeException if the index is not valid.

Exemple

Example #1 Ds\Deque::set() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

$deque->set(1, "_");
print_r($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => a
    [1] => _
    [2] => c
)

Example #2 Ds\Deque::set() example using array syntax

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

$deque[1] = "_";
print_r($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => a
    [1] => _
    [2] => c
)
Ds\Deque::rotate
Ds\Deque::shift
Deque


Removes and returns the first value.

Ds\Deque::set
Ds\Deque::slice
Deque
PHP Manual

Ds\Deque::shift

(PECL ds >= 1.0.0)

Ds\Deque::shift — Removes and returns the first value.

Descrierea

public mixed Ds\Deque::shift ( void )

Removes and returns the first value.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The first value, which was removed.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Deque::shift() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

var_dump($deque->shift());
var_dump($deque->shift());
var_dump($deque->shift());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
string(1) "b"
string(1) "c"
Ds\Deque::set
Ds\Deque::slice
Deque


Returns a sub-deque of a given range.

Ds\Deque::shift
Ds\Deque::sort
Deque
PHP Manual

Ds\Deque::slice

(PECL ds >= 1.0.0)

Ds\Deque::slice — Returns a sub-deque of a given range.

Descrierea

public Ds\Deque Ds\Deque::slice ( int $index [, int $length ] )

Creates a sub-deque of a given range.

Parametri

index

The index at which the sub-deque starts.

If positive, the deque will start at that index in the deque. If negative, the deque will start that far from the end.

length

If a length is given and is positive, the resulting deque will have up to that many values in it. If the length results in an overflow, only values up to the end of the deque will be included. If a length is given and is negative, the deque will stop that many values from the end. If a length is not provided, the resulting deque will contain all values between the index and the end of the deque.

Valorile întoarse

A sub-deque of the given range.

Exemple

Example #1 Ds\Deque::slice() example

<?php
$deque = new \Ds\Deque(["a", "b", "c", "d", "e"]);

// Slice from 2 onwards
print_r($deque->slice(2));

// Slice from 1, for a length of 3
print_r($deque->slice(1, 3));

// Slice from 1 onwards
print_r($deque->slice(1));

// Slice from 2 from the end onwards
print_r($deque->slice(-2));

// Slice from 1 to 1 from the end
print_r($deque->slice(1, -1));
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => c
    [1] => d
    [2] => e
)
Ds\Deque Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Deque Object
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)
Ds\Deque Object
(
    [0] => d
    [1] => e
)
Ds\Deque Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Deque::shift
Ds\Deque::sort
Deque


Sorts the deque in-place.

Ds\Deque::slice
Ds\Deque::sorted
Deque
PHP Manual

Ds\Deque::sort

(PECL ds >= 1.0.0)

Ds\Deque::sort — Sorts the deque in-place.

Descrierea

public void Ds\Deque::sort ([ callable $comparator ] )

Sorts the deque in-place, using an optional comparator function.

Parametri

comparator

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
Precautie

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Deque::sort() example

<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);
$deque->sort();

print_r($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Deque::sort() example using a comparator

<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);

$deque->sort(function($a, $b) {
    return $b <=> $a;
});

print_r($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)
Ds\Deque::slice
Ds\Deque::sorted
Deque


Returns a sorted copy.

Ds\Deque::sort
Ds\Deque::sum
Deque
PHP Manual

Ds\Deque::sorted

(PECL ds >= 1.0.0)

Ds\Deque::sorted — Returns a sorted copy.

Descrierea

public Ds\Deque Ds\Deque::sorted ([ callable $comparator ] )

Returns a sorted copy, using an optional comparator function.

Parametri

comparator

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
Precautie

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valorile întoarse

Returns a sorted copy of the deque.

Exemple

Example #1 Ds\Deque::sorted() example

<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);

print_r($deque->sorted());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Deque::sorted() example using a comparator

<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);

$sorted = $deque->sorted(function($a, $b) {
    return $b <=> $a;
});

print_r($sorted);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)
Ds\Deque::sort
Ds\Deque::sum
Deque


Returns the sum of all values in the deque.

Ds\Deque::sorted
Ds\Deque::toArray
Deque
PHP Manual

Ds\Deque::sum

(PECL ds >= 1.0.0)

Ds\Deque::sum — Returns the sum of all values in the deque.

Descrierea

public number Ds\Deque::sum ( void )

Returns the sum of all values in the deque.

Nota:

Arrays and objects are considered equal to zero when calculating the sum.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The sum of all the values in the deque as either a float or int depending on the values in the deque.

Exemple

Example #1 Ds\Deque::sum() integer example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
var_dump($deque->sum());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(6)

Example #2 Ds\Deque::sum() float example

<?php
$deque = new \Ds\Deque([1, 2.5, 3]);
var_dump($deque->sum());
?>

Exemplul de mai sus va afi?a ceva similar cu:

float(6.5)
Ds\Deque::sorted
Ds\Deque::toArray
Deque


Converts the deque to an array.

Ds\Deque::sum
Ds\Deque::unshift
Deque
PHP Manual

Ds\Deque::toArray

(PECL ds >= 1.0.0)

Ds\Deque::toArray — Converts the deque to an array.

Descrierea

public array Ds\Deque::toArray ( void )

Converts the deque to an array.

Nota:

Casting to an array is not supported yet.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array containing all the values in the same order as the deque.

Exemple

Example #1 Ds\Deque::toArray() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

var_dump($deque->toArray());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Deque::sum
Ds\Deque::unshift
Deque


Adds values to the front of the deque.

Ds\Deque::toArray
Map
Deque
PHP Manual

Ds\Deque::unshift

(PECL ds >= 1.0.0)

Ds\Deque::unshift — Adds values to the front of the deque.

Descrierea

public void Ds\Deque::unshift ([ mixed $values ] )

Adds values to the front of the deque, moving all the current values forward to make room for the new values.

Parametri

values

The values to add to the front of the deque.

Nota:

Multiple values will be added in the same order that they are passed.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Deque::unshift() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

$deque->unshift("a");
$deque->unshift("b", "c");

print_r($deque);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Deque Object
(
    [0] => b
    [1] => c
    [2] => a
    [3] => 1
    [4] => 2
    [5] => 3
)
Ds\Deque::toArray
Map
Deque


The Map class

(No version information available, might only be in Git)

Introducere

A Map is a sequential collection of key-value pairs, almost identical to an array used in a similar context. Keys can be any type, but must be unique. Values are replaced if added to the map using the same key.

Strengths

  • Keys and values can be any type, including objects.
  • Supports array syntax (square brackets).
  • Insertion order is preserved.
  • Performance and memory efficiency is very similar to an array.
  • Automatically frees allocated memory when its size drops low enough.

Weaknesses

  • Can’t be converted to an array when objects are used as keys.

Sinopsisul clasei

Ds\Map implements Ds\Collection {
/* Constants */
const int MIN_CAPACITY = 16 ;
/* Metode */
public void allocate ( int $capacity )
public void apply ( callable $callback )
public int capacity ( void )
public void clear ( void )
public Ds\Map copy ( void )
public Ds\Map diff ( Ds\Map $map )
public Ds\Map filter ([ callable $callback ] )
public Ds\Pair first ( void )
public mixed get ( mixed $key [, mixed $default ] )
public bool hasKey ( mixed $key )
public bool hasValue ( mixed $value )
public Ds\Map intersect ( Ds\Map $map )
public bool isEmpty ( void )
public Ds\Set keys ( void )
public void ksort ([ callable $comparator ] )
public Ds\Map ksorted ([ callable $comparator ] )
public Ds\Pair last ( void )
public Ds\Map map ( callable $callback )
public Ds\Map merge ( mixed $values )
public Ds\Sequence pairs ( void )
public void put ( mixed $key , mixed $value )
public void putAll ( mixed $pairs )
public mixed reduce ( callable $callback [, mixed $initial ] )
public mixed remove ( mixed $key [, mixed $default ] )
public void reverse ( void )
public Ds\Map reversed ( void )
public Ds\Pair skip ( int $position )
public Ds\Map slice ( int $index [, int $length ] )
public void sort ([ callable $comparator ] )
public Ds\Map sorted ([ callable $comparator ] )
public number sum ( void )
public array toArray ( void )
public Ds\Map union ( Ds\Map $map )
public Ds\Sequence values ( void )
public Ds\Map xor ( Ds\Map $map )
}

Constante predefinite

Ds\Map::MIN_CAPACITY

Cuprins

  • Ds\Map::allocate — Allocates enough memory for a required capacity.
  • Ds\Map::apply — Updates all values by applying a callback function to each value.
  • Ds\Map::capacity — Returns the current capacity.
  • Ds\Map::clear — Removes all values.
  • Ds\Map::__construct — Creates a new instance.
  • Ds\Map::copy — Returns a shallow copy of the map.
  • Ds\Map::count — Returns the number of values in the map.
  • Ds\Map::diff — Creates a new map using keys that aren't in another map.
  • Ds\Map::filter — Creates a new map using a callable to determine which pairs to include.
  • Ds\Map::first — Returns the first pair in the map.
  • Ds\Map::get — Returns the value for a given key.
  • Ds\Map::hasKey — Determines whether the map contains a given key.
  • Ds\Map::hasValue — Determines whether the map contains a given value.
  • Ds\Map::intersect — Creates a new map by intersecting keys with another map.
  • Ds\Map::isEmpty — Returns whether the map is empty
  • Ds\Map::jsonSerialize — Returns a representation that can be converted to JSON.
  • Ds\Map::keys — Returns a set of the map's keys.
  • Ds\Map::ksort — Sorts the map in-place by key.
  • Ds\Map::ksorted — Returns a copy, sorted by key.
  • Ds\Map::last — Returns the last pair of the map.
  • Ds\Map::map — Returns the result of applying a callback to each value.
  • Ds\Map::merge — Returns the result of adding all given associations.
  • Ds\Map::pairs — Returns a sequence containing all the pairs of the map.
  • Ds\Map::put — Associates a key with a value.
  • Ds\Map::putAll — Associates all key-value pairs of a traversable object or array.
  • Ds\Map::reduce — Reduces the map to a single value using a callback function.
  • Ds\Map::remove — Removes and returns a value by key.
  • Ds\Map::reverse — Reverses the map in-place.
  • Ds\Map::reversed — Returns a reversed copy.
  • Ds\Map::skip — Returns the pair at a given positional index.
  • Ds\Map::slice — Returns a subset of the map defined by a starting index and length.
  • Ds\Map::sort — Sorts the map in-place by value.
  • Ds\Map::sorted — Returns a copy, sorted by value.
  • Ds\Map::sum — Returns the sum of all values in the map.
  • Ds\Map::toArray — Converts the map to an array.
  • Ds\Map::union — Creates a new map using values from the current instance and another map.
  • Ds\Map::values — Returns a sequence of the map's values.
  • Ds\Map::xor — Creates a new map using keys of either the current instance or of another map, but not of both.
Ds\Deque::unshift
Ds\Map::allocate
Data Structures


Allocates enough memory for a required capacity.

Map
Ds\Map::apply
Map
PHP Manual

Ds\Map::allocate

(PECL ds >= 1.0.0)

Ds\Map::allocate — Allocates enough memory for a required capacity.

Descrierea

public void Ds\Map::allocate ( int $capacity )

Allocates enough memory for a required capacity.

Parametri

capacity

The number of values for which capacity should be allocated.

Nota:

Capacity will stay the same if this value is less than or equal to the current capacity.

Nota:

Capacity will always be rounded up to the nearest power of 2.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Map::allocate() example

<?php
$map = new \Ds\Map();
var_dump($map->capacity());

$map->allocate(100);
var_dump($map->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(16)
int(128)
Map
Ds\Map::apply
Map


Updates all values by applying a callback function to each value.

Ds\Map::allocate
Ds\Map::capacity
Map
PHP Manual

Ds\Map::apply

(PECL ds >= 1.0.0)

Ds\Map::apply — Updates all values by applying a callback function to each value.

Descrierea

public void Ds\Map::apply ( callable $callback )

Updates all values by applying a callback function to each value in the map.

Parametri

callback

mixed callback ( mixed $key , mixed $value )

A callable to apply to each value in the map.

The callback should return what the value should be replaced by.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Map::apply() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$map->apply(function($key, $value) { return $value * 2; });

print_r($map);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 4
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 6
        )

)
Ds\Map::allocate
Ds\Map::capacity
Map


Returns the current capacity.

Ds\Map::apply
Ds\Map::clear
Map
PHP Manual

Ds\Map::capacity

(PECL ds >= 1.0.0)

Ds\Map::capacity — Returns the current capacity.

Descrierea

public int Ds\Map::capacity ( void )

Returns the current capacity.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current capacity.

Exemple

Example #1 Ds\Map::capacity() example

<?php
$map = new \Ds\Map();
var_dump($map->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(16)
Ds\Map::apply
Ds\Map::clear
Map


Removes all values.

Ds\Map::capacity
Ds\Map::__construct
Map
PHP Manual

Ds\Map::clear

(PECL ds >= 1.0.0)

Ds\Map::clear — Removes all values.

Descrierea

public void Ds\Map::clear ( void )

Removes all values from the map.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Map::clear() example

<?php
$map = new \Ds\Map([
    "a" => 1,
    "b" => 2,
    "c" => 3,
]);
print_r($map);

$map->clear();
print_r($map);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)
Ds\Map Object
(
)
Ds\Map::capacity
Ds\Map::__construct
Map


Creates a new instance.

Ds\Map::clear
Ds\Map::copy
Map
PHP Manual

Ds\Map::__construct

(PECL ds >= 1.0.0)

Ds\Map::__construct — Creates a new instance.

Descrierea

public Ds\Map::__construct ([ mixed $...values ] )

Creates a new instance, using either a traversable object or an array for the initial values.

Parametri

values

A traversable object or an array to use for the initial values.

Exemple

Example #1 Ds\Map::__construct() example

<?php
$map = new \Ds\Map();
var_dump($map);

$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Map)#1 (0) {
}
object(Ds\Map)#2 (3) {
  [0]=>
  object(Ds\Pair)#1 (2) {
    ["key"]=>
    string(1) "a"
    ["value"]=>
    int(1)
  }
  [1]=>
  object(Ds\Pair)#3 (2) {
    ["key"]=>
    string(1) "b"
    ["value"]=>
    int(2)
  }
  [2]=>
  object(Ds\Pair)#4 (2) {
    ["key"]=>
    string(1) "c"
    ["value"]=>
    int(3)
  }
}
Ds\Map::clear
Ds\Map::copy
Map


Returns a shallow copy of the map.

Ds\Map::__construct
Ds\Map::count
Map
PHP Manual

Ds\Map::copy

(PECL ds >= 1.0.0)

Ds\Map::copy — Returns a shallow copy of the map.

Descrierea

public Ds\Map Ds\Map::copy ( void )

Returns a shallow copy of the map.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a shallow copy of the map.

Exemple

Example #1 Ds\Map::copy() example

<?php
$map = new \Ds\Map([
    "a" => 1,
    "b" => 2,
    "c" => 3,
]);

print_r($map->copy());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)
Ds\Map::__construct
Ds\Map::count
Map


Returns the number of values in the map.

Ds\Map::copy
Ds\Map::diff
Map
PHP Manual

Ds\Map::count

(PECL ds >= 1.0.0)

Ds\Map::count — Returns the number of values in the map.

See Countable::count()

Ds\Map::copy
Ds\Map::diff
Map


Creates a new map using keys that aren't in another map.

Ds\Map::count
Ds\Map::filter
Map
PHP Manual

Ds\Map::diff

(PECL ds >= 1.0.0)

Ds\Map::diff — Creates a new map using keys that aren't in another map.

Descrierea

public Ds\Map Ds\Map::diff ( Ds\Map $map )

Returns the result of removing all keys from the current instance that are present in a given map.

A \ B = {x ? A | x ? B}

Parametri

map

The map containing the keys to exclude in the resulting map.

Valorile întoarse

The result of removing all keys from the current instance that are present in a given map.

See Also

  • » Compliment on Wikipedia

Exemple

Example #1 Ds\Map::diff() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map(["b" => 4, "c" => 5, "d" => 6]);

var_dump($a->diff($b));
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Map)#3 (1) {
  [0]=>
  object(Ds\Pair)#4 (2) {
    ["key"]=>
    string(1) "a"
    ["value"]=>
    int(1)
  }
}
Ds\Map::count
Ds\Map::filter
Map


Creates a new map using a callable to determine which pairs to include.

Ds\Map::diff
Ds\Map::first
Map
PHP Manual

Ds\Map::filter

(PECL ds >= 1.0.0)

Ds\Map::filter — Creates a new map using a callable to determine which pairs to include.

Descrierea

public Ds\Map Ds\Map::filter ([ callable $callback ] )

Creates a new map using a callable to determine which pairs to include.

Parametri

callback

bool callback ( mixed $key , mixed $value )

Optional callable which returns TRUE if the pair should be included, FALSE otherwise.

If a callback is not provided, only values which are TRUE (see converting to boolean) will be included.

Valorile întoarse

A new map containing all the pairs for which either the callback returned TRUE, or all values that convert to TRUE if a callback was not provided.

Exemple

Example #1 Ds\Map::filter() example using callback function

<?php
$map = new \Ds\Map(["a", "b", "c", "d", "e"]);

var_dump($map->filter(function($key, $value) {
    return $key % 2 == 0;
}));
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Map)#3 (3) {
  [0]=>
  object(Ds\Pair)#2 (2) {
    ["key"]=>
    int(0)
    ["value"]=>
    string(1) "a"
  }
  [1]=>
  object(Ds\Pair)#4 (2) {
    ["key"]=>
    int(2)
    ["value"]=>
    string(1) "c"
  }
  [2]=>
  object(Ds\Pair)#5 (2) {
    ["key"]=>
    int(4)
    ["value"]=>
    string(1) "e"
  }
}

Example #2 Ds\Map::filter() example without a callback function

<?php
$map = new \Ds\Map(["a" => 0, "b" => 1, "c" => true, "d" => false]);

var_dump($map->filter());
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Map)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}
Ds\Map::diff
Ds\Map::first
Map


Returns the first pair in the map.

Ds\Map::filter
Ds\Map::get
Map
PHP Manual

Ds\Map::first

(PECL ds >= 1.0.0)

Ds\Map::first — Returns the first pair in the map.

Descrierea

public Ds\Pair Ds\Map::first ( void )

Returns the first pair in the map.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The first pair in the map.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Map::first() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->first());
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Pair)#2 (2) {
  ["key"]=>
  string(1) "a"
  ["value"]=>
  int(1)
}
Ds\Map::filter
Ds\Map::get
Map


Returns the value for a given key.

Ds\Map::first
Ds\Map::hasKey
Map
PHP Manual

Ds\Map::get

(PECL ds >= 1.0.0)

Ds\Map::get — Returns the value for a given key.

Descrierea

public mixed Ds\Map::get ( mixed $key [, mixed $default ] )

Returns the value for a given key, or an optional default value if the key could not be found.

Nota:

Keys of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Nota:

You can also use array syntax to access values by key, eg. $map["key"].

Precautie

Be careful when using array syntax. Scalar keys will be coerced to integers by the engine. For example, $map["1"] will attempt to access int(1), while $map->get("1") will correctly look up the string key.

See Arrays.

Parametri

key

The key to look up.

default

The optional default value, returned if the key could not be found.

Valorile întoarse

The value mapped to the given key, or the default value if provided and the key could not be found in the map.

Erori/Excep?ii

OutOfBoundsException if the key could not be found and a default value was not provided.

Exemple

Example #1 Ds\Map::get() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->get("a"));       // 1
var_dump($map->get("d", 10));   // 10 (default used)
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(1)
int(10)

Example #2 Ds\Map::get() example using array syntax

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map["a"])); // 1
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(1)
Ds\Map::first
Ds\Map::hasKey
Map


Determines whether the map contains a given key.

Ds\Map::get
Ds\Map::hasValue
Map
PHP Manual

Ds\Map::hasKey

(PECL ds >= 1.0.0)

Ds\Map::hasKey — Determines whether the map contains a given key.

Descrierea

public bool Ds\Map::hasKey ( mixed $key )

Determines whether the map contains a given key.

Parametri

key

The key to look for.

Valorile întoarse

Returns TRUE if the key could found, FALSE otherwise.

Exemple

Example #1 Ds\Map::hasKey() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->hasKey("a")); // true
var_dump($map->hasKey("e")); // false
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(false)
Ds\Map::get
Ds\Map::hasValue
Map


Determines whether the map contains a given value.

Ds\Map::hasKey
Ds\Map::intersect
Map
PHP Manual

Ds\Map::hasValue

(PECL ds >= 1.0.0)

Ds\Map::hasValue — Determines whether the map contains a given value.

Descrierea

public bool Ds\Map::hasValue ( mixed $value )

Determines whether the map contains a given value.

Parametri

value

The value to look for.

Valorile întoarse

Returns TRUE if the value could found, FALSE otherwise.

Exemple

Example #1 Ds\Map::hasValue() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->hasValue(1)); // true
var_dump($map->hasValue(4)); // false
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(false)
Ds\Map::hasKey
Ds\Map::intersect
Map


Creates a new map by intersecting keys with another map.

Ds\Map::hasValue
Ds\Map::isEmpty
Map
PHP Manual

Ds\Map::intersect

(PECL ds >= 1.0.0)

Ds\Map::intersect — Creates a new map by intersecting keys with another map.

Descrierea

public Ds\Map Ds\Map::intersect ( Ds\Map $map )

Creates a new map containing the pairs of the current instance whose keys are also present in the given map. In other words, returns a copy of the current instance with all keys removed that are not also in the other map.

A n B = {x : x ? A ? x ? B}

Nota:

Values from the current instance will be kept.

Parametri

map

The other map, containing the keys to intersect with.

Valorile întoarse

The key intersection of the current instance and another map.

See Also

  • » Intersection on Wikipedia

Exemple

Example #1 Ds\Map::intersect() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map(["b" => 4, "c" => 5, "d" => 6]);

var_dump($a->intersect($b));
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Map)#3 (2) {
  [0]=>
  object(Ds\Pair)#4 (2) {
    ["key"]=>
    string(1) "b"
    ["value"]=>
    int(2)
  }
  [1]=>
  object(Ds\Pair)#5 (2) {
    ["key"]=>
    string(1) "c"
    ["value"]=>
    int(3)
  }
}
Ds\Map::hasValue
Ds\Map::isEmpty
Map


Returns whether the map is empty

Ds\Map::intersect
Ds\Map::jsonSerialize
Map
PHP Manual

Ds\Map::isEmpty

(PECL ds >= 1.0.0)

Ds\Map::isEmpty — Returns whether the map is empty

Descrierea

public bool Ds\Map::isEmpty ( void )

Returns whether the map is empty.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the map is empty, FALSE otherwise.

Exemple

Example #1 Ds\Map::isEmpty() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
bool(true)
Ds\Map::intersect
Ds\Map::jsonSerialize
Map


Returns a representation that can be converted to JSON.

Ds\Map::isEmpty
Ds\Map::keys
Map
PHP Manual

Ds\Map::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Map::jsonSerialize — Returns a representation that can be converted to JSON.

See JsonSerializable::jsonSerialize()

Nota:

You should never need to call this directly.

Ds\Map::isEmpty
Ds\Map::keys
Map


Returns a set of the map's keys.

Ds\Map::jsonSerialize
Ds\Map::ksort
Map
PHP Manual

Ds\Map::keys

(PECL ds >= 1.0.0)

Ds\Map::keys — Returns a set of the map's keys.

Descrierea

public Ds\Set Ds\Map::keys ( void )

Returns a set containing all the keys of the map, in the same order.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A Ds\Set containing all the keys of the map.

Exemple

Example #1 Ds\Map::keys() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->keys());
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Set)#2 (3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
}
Ds\Map::jsonSerialize
Ds\Map::ksort
Map


Sorts the map in-place by key.

Ds\Map::keys
Ds\Map::ksorted
Map
PHP Manual

Ds\Map::ksort

(PECL ds >= 1.0.0)

Ds\Map::ksort — Sorts the map in-place by key.

Descrierea

public void Ds\Map::ksort ([ callable $comparator ] )

Sorts the map in-place by key, using an optional comparator function.

Parametri

comparator

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
Precautie

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Map::ksort() example

<?php
$map = new \Ds\Map(["b" => 2, "c" => 3, "a" => 1]);
$map->ksort();

print_r($map);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)

Example #2 Ds\Map::ksort() example using a comparator

<?php
$map = new \Ds\Map([1 => "x", 2 => "y", 0 => "z"]);

// Reverse
$map->ksort(function($a, $b) {
    return $b <=> $a;
});

print_r($map);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 2
            [value] => y
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => x
        )

    [2] => Ds\Pair Object
        (
            [key] => 0
            [value] => z
        )

)
Ds\Map::keys
Ds\Map::ksorted
Map


Returns a copy, sorted by key.

Ds\Map::ksort
Ds\Map::last
Map
PHP Manual

Ds\Map::ksorted

(No version information available, might only be in Git)

Ds\Map::ksorted — Returns a copy, sorted by key.

Descrierea

public Ds\Map Ds\Map::ksorted ([ callable $comparator ] )

Returns a copy sorted by key, using an optional comparator function.

Parametri

comparator

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
Precautie

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valorile întoarse

Returns a copy of the map, sorted by key.

Exemple

Example #1 Ds\Map::ksorted() example

<?php
$map = new \Ds\Map(["b" => 2, "c" => 3, "a" => 1]);

print_r($map->ksorted());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)

Example #2 Ds\Map::ksorted() example using a comparator

<?php
$map = new \Ds\Map([1 => "x", 2 => "y", 0 => "z"]);

// Reverse
$sorted = $map->ksorted(function($a, $b) {
    return $b <=> $a;
});

print_r($sorted);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 2
            [value] => y
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => x
        )

    [2] => Ds\Pair Object
        (
            [key] => 0
            [value] => z
        )

)
Ds\Map::ksort
Ds\Map::last
Map


Returns the last pair of the map.

Ds\Map::ksorted
Ds\Map::map
Map
PHP Manual

Ds\Map::last

(PECL ds >= 1.0.0)

Ds\Map::last — Returns the last pair of the map.

Descrierea

public Ds\Pair Ds\Map::last ( void )

Returns the last pair of the map.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The last pair of the map.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Map::last() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->last());
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Pair)#2 (2) {
  ["key"]=>
  string(1) "c"
  ["value"]=>
  int(3)
}
Ds\Map::ksorted
Ds\Map::map
Map


Returns the result of applying a callback to each value.

Ds\Map::last
Ds\Map::merge
Map
PHP Manual

Ds\Map::map

(PECL ds >= 1.0.0)

Ds\Map::map — Returns the result of applying a callback to each value.

Descrierea

public Ds\Map Ds\Map::map ( callable $callback )

Returns the result of applying a callback function to each value of the map.

Parametri

callback

mixed callback ( mixed $key , mixed $value )

A callable to apply to each value in the map.

The callable should return what the key will be mapped to in the resulting map.

Valorile întoarse

The result of applying a callback to each value in the map.

Nota:

The keys and values of the current instance won't be affected.

Exemple

Example #1 Ds\Map::map() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

print_r($map->map(function($key, $value) { return $value * 2; }));
print_r($map);
?>

Exemplul de mai sus va afi?a ceva similar cu:

(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 4
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 6
        )

)
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)
Ds\Map::last
Ds\Map::merge
Map


Returns the result of adding all given associations.

Ds\Map::map
Ds\Map::pairs
Map
PHP Manual

Ds\Map::merge

(PECL ds >= 1.0.0)

Ds\Map::merge — Returns the result of adding all given associations.

Descrierea

public Ds\Map Ds\Map::merge ( mixed $values )

Returns the result of associating all keys of a given traversable object or array with their corresponding values, combined with the current instance.

Nota:

Values of the current instance will be overwritten by those provided where keys are equal.

Parametri

values

A traversable object or an array.

Valorile întoarse

The result of associating all keys of a given traversable object or array with their corresponding values, combined with the current instance.

Nota:

The current instance won't be affected.

Exemple

Example #1 Ds\Map::merge() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

print_r($map->merge(["a" => 10, "e" => 50]));
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 10
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

    [3] => Ds\Pair Object
        (
            [key] => e
            [value] => 50
        )

)
Ds\Map::map
Ds\Map::pairs
Map


Returns a sequence containing all the pairs of the map.

Ds\Map::merge
Ds\Map::put
Map
PHP Manual

Ds\Map::pairs

(PECL ds >= 1.0.0)

Ds\Map::pairs — Returns a sequence containing all the pairs of the map.

Descrierea

public Ds\Sequence Ds\Map::pairs ( void )

Returns a Ds\Sequence containing all the pairs of the map.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Ds\Sequence containing all the pairs of the map.

Exemple

Example #1 Ds\Map::pairs() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->pairs());
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Map)#8 (3) {
  [0]=>
  object(Ds\Pair)#5 (2) {
    ["key"]=>
    string(1) "a"
    ["value"]=>
    int(1)
  }
  [1]=>
  object(Ds\Pair)#6 (2) {
    ["key"]=>
    string(1) "b"
    ["value"]=>
    int(2)
  }
  [2]=>
  object(Ds\Pair)#7 (2) {
    ["key"]=>
    string(1) "c"
    ["value"]=>
    int(3)
  }
}
p
Ds\Map::merge
Ds\Map::put
Map


Associates a key with a value.

Ds\Map::pairs
Ds\Map::putAll
Map
PHP Manual

Ds\Map::put

(PECL ds >= 1.0.0)

Ds\Map::put — Associates a key with a value.

Descrierea

public void Ds\Map::put ( mixed $key , mixed $value )

Associates a key with a value, overwriting a previous association if one exists.

Nota:

Keys of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Nota:

You can also use array syntax to associate values by key, eg. $map["key"] = $value.

Precautie

Be careful when using array syntax. Scalar keys will be coerced to integers by the engine. For example, $map["1"] will attempt to access int(1), while $map->get("1") will correctly look up the string key.

See Arrays.

Parametri

key

The key to associate the value with.

value

The value to be associated with the key.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Map::put() example

<?php
$map = new \Ds\Map();

$map->put("a", 1);
$map->put("b", 2);
$map->put("c", 3);

print_r($map);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)

Example #2 Ds\Map::put() example using objects as keys

<?php
class HashableObject implements \Ds\Hashable
{
    /**
     * An arbitrary value to use as the hash value. Does not define equality.
     */
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function hash()
    {
        return $this->value;
    }

    public function equals($obj): bool
    {
        return $this->value === $obj->value;
    }
}

$map = new \Ds\Map();

$obj = new \ArrayIterator([]);

// Using the same instance multiple times will overwrite the previous value.
$map->put($obj, 1);
$map->put($obj, 2);

// Using multiple instances of the same object will create new associations.
$map->put(new \stdClass(), 3);
$map->put(new \stdClass(), 4);

// Using multiple instances of equal hashable objects will overwrite previous values.
$map->put(new \HashableObject(1), 5);
$map->put(new \HashableObject(1), 6);
$map->put(new \HashableObject(2), 7);
$map->put(new \HashableObject(2), 8);

var_dump($map);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Map)#1 (5) {
  [0]=>
  object(Ds\Pair)#7 (2) {
    ["key"]=>
    object(ArrayIterator)#2 (1) {
      ["storage":"ArrayIterator":private]=>
      array(0) {
      }
    }
    ["value"]=>
    int(2)
  }
  [1]=>
  object(Ds\Pair)#8 (2) {
    ["key"]=>
    object(stdClass)#3 (0) {
    }
    ["value"]=>
    int(3)
  }
  [2]=>
  object(Ds\Pair)#9 (2) {
    ["key"]=>
    object(stdClass)#4 (0) {
    }
    ["value"]=>
    int(4)
  }
  [3]=>
  object(Ds\Pair)#10 (2) {
    ["key"]=>
    object(HashableObject)#5 (1) {
      ["value":"HashableObject":private]=>
      int(1)
    }
    ["value"]=>
    int(6)
  }
  [4]=>
  object(Ds\Pair)#11 (2) {
    ["key"]=>
    object(HashableObject)#6 (1) {
      ["value":"HashableObject":private]=>
      int(2)
    }
    ["value"]=>
    int(8)
  }
}
Ds\Map::pairs
Ds\Map::putAll
Map


Associates all key-value pairs of a traversable object or array.

Ds\Map::put
Ds\Map::reduce
Map
PHP Manual

Ds\Map::putAll

(PECL ds >= 1.0.2)

Ds\Map::putAll — Associates all key-value pairs of a traversable object or array.

Descrierea

public void Ds\Map::putAll ( mixed $pairs )

Associates all key-value pairs of a traversable object or array.

Nota:

Keys of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Parametri

pairs

traversable object or array.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Map::putAll() example

<?php
$map = new \Ds\Map();

$map->putAll([
    "a" => 1,
    "b" => 2,
    "c" => 3,
]);

print_r($map);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)
Ds\Map::put
Ds\Map::reduce
Map


Reduces the map to a single value using a callback function.

Ds\Map::putAll
Ds\Map::remove
Map
PHP Manual

Ds\Map::reduce

(PECL ds >= 1.0.0)

Ds\Map::reduce — Reduces the map to a single value using a callback function.

Descrierea

public mixed Ds\Map::reduce ( callable $callback [, mixed $initial ] )

Reduces the map to a single value using a callback function.

Parametri

callback
mixed callback ( mixed $carry , mixed $key , mixed $value )
carry

The return value of the previous callback, or initial if it's the first iteration.

key

The key of the current iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be NULL.

Valorile întoarse

The return value of the final callback.

Exemple

Example #1 Ds\Map::reduce() with initial value example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

$callback = function($carry, $key, $value) {
    return $carry * $value;
};

var_dump($map->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 =  5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(30)

Example #2 Ds\Map::reduce() without an initial value example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->reduce(function($carry, $key, $value) {
    return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 =  6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(21)
Ds\Map::putAll
Ds\Map::remove
Map


Removes and returns a value by key.

Ds\Map::reduce
Ds\Map::reverse
Map
PHP Manual

Ds\Map::remove

(PECL ds >= 1.0.0)

Ds\Map::remove — Removes and returns a value by key.

Descrierea

public mixed Ds\Map::remove ( mixed $key [, mixed $default ] )

Removes and returns a value by key, or return an optional default value if the key could not be found.

Nota:

Keys of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Nota:

You can also use array syntax to access values by key, eg. $map["key"].

Precautie

Be careful when using array syntax. Scalar keys will be coerced to integers by the engine. For example, $map["1"] will attempt to access int(1), while $map->get("1") will correctly look up the string key.

See Arrays.

Parametri

key

The key to remove.

default

The optional default value, returned if the key could not be found.

Valorile întoarse

The value that was removed, or the default value if provided and the key could not be found in the map.

Erori/Excep?ii

OutOfBoundsException if the key could not be found and a default value was not provided.

Exemple

Example #1 Ds\Map::remove() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->remove("a"));      //  1
var_dump($map->remove("e", 10));  // 10 (default used)
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(1)
int(10)
Ds\Map::reduce
Ds\Map::reverse
Map


Reverses the map in-place.

Ds\Map::remove
Ds\Map::reversed
Map
PHP Manual

Ds\Map::reverse

(PECL ds >= 1.0.0)

Ds\Map::reverse — Reverses the map in-place.

Descrierea

public void Ds\Map::reverse ( void )

Reverses the map in-place.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Map::reverse() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$map->reverse();

print_r($map);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

)
Ds\Map::remove
Ds\Map::reversed
Map


Returns a reversed copy.

Ds\Map::reverse
Ds\Map::skip
Map
PHP Manual

Ds\Map::reversed

(PECL ds >= 1.0.0)

Ds\Map::reversed — Returns a reversed copy.

Descrierea

public Ds\Map Ds\Map::reversed ( void )

Returns a reversed copy of the map.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A reversed copy of the map.

Nota:

The current instance is not affected.

Exemple

Example #1 Ds\Map::reversed() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

print_r($map->reversed());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

)
Ds\Map::reverse
Ds\Map::skip
Map


Returns the pair at a given positional index.

Ds\Map::reversed
Ds\Map::slice
Map
PHP Manual

Ds\Map::skip

(PECL ds >= 1.0.0)

Ds\Map::skip — Returns the pair at a given positional index.

Descrierea

public Ds\Pair Ds\Map::skip ( int $position )

Returns the pair at a given zero-based position.

Parametri

position

The zero-based positional index to return.

Valorile întoarse

Returns the Ds\Pair at the given position.

Erori/Excep?ii

OutOfRangeException if the position is not valid.

Exemple

Example #1 Ds\Map::skip() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->skip(1));
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Pair)#2 (2) {
  ["key"]=>
  string(1) "b"
  ["value"]=>
  int(2)
}
Ds\Map::reversed
Ds\Map::slice
Map


Returns a subset of the map defined by a starting index and length.

Ds\Map::skip
Ds\Map::sort
Map
PHP Manual

Ds\Map::slice

(PECL ds >= 1.0.0)

Ds\Map::slice — Returns a subset of the map defined by a starting index and length.

Descrierea

public Ds\Map Ds\Map::slice ( int $index [, int $length ] )

Returns a subset of the map defined by a starting index and length.

Parametri

index

The index at which the range starts.

If positive, the range will start at that index in the map. If negative, the range will start that far from the end.

length

If a length is given and is positive, the resulting map will have up to that many pairs in it. If a length is given and is negative, the range will stop that many pairs from the end. If the length results in an overflow, only pairs up to the end of the map will be included. If a length is not provided, the resulting map will contain all pairs between the index and the end of the map.

Valorile întoarse

A subset of the map defined by a starting index and length.

Exemple

Example #1 Ds\Map::slice() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5]);

// Slice from 2 onwards
print_r($map->slice(2)->toArray());

// Slice from 1, for a length of 3
print_r($map->slice(1, 3)->toArray());

// Slice from 1 onwards
print_r($map->slice(1)->toArray());

// Slice from 2 from the end onwards
print_r($map->slice(-2)->toArray());

// Slice from 1 to 1 from the end
print_r($map->slice(1, -1)->toArray());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [c] => 3
    [d] => 4
    [e] => 5
)
Array
(
    [b] => 2
    [c] => 3
    [d] => 4
)
Array
(
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
)
Array
(
    [d] => 4
    [e] => 5
)
Array
(
    [b] => 2
    [c] => 3
    [d] => 4
)
Ds\Map::skip
Ds\Map::sort
Map


Sorts the map in-place by value.

Ds\Map::slice
Ds\Map::sorted
Map
PHP Manual

Ds\Map::sort

(PECL ds >= 1.0.0)

Ds\Map::sort — Sorts the map in-place by value.

Descrierea

public void Ds\Map::sort ([ callable $comparator ] )

Sorts the map in-place by value, using an optional comparator function.

Parametri

comparator

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
Precautie

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Map::sort() example

<?php
$map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]);
$map->sort();

print_r($map);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => c
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

)

Example #2 Ds\Map::sort() example using a comparator

<?php
$map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]);

$map->sort(function($a, $b) {
    return $b <=> $a;
});

print_r($map);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

    [1] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 1
        )

)
Ds\Map::slice
Ds\Map::sorted
Map


Returns a copy, sorted by value.

Ds\Map::sort
Ds\Map::sum
Map
PHP Manual

Ds\Map::sorted

(PECL ds >= 1.0.0)

Ds\Map::sorted — Returns a copy, sorted by value.

Descrierea

public Ds\Map Ds\Map::sorted ([ callable $comparator ] )

Returns a copy, sorted by value using an optional comparator function.

Parametri

comparator

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
Precautie

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valorile întoarse

Returns a copy of the map, sorted by value.

Exemple

Example #1 Ds\Map::sort() example

<?php
$map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]);

print_r($map->sorted());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => c
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

)

Example #2 Ds\Map::sort() example using a comparator

<?php
$map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]);

// Reverse
$sorted = $map->sorted(function($a, $b) {
    return $b <=> $a;
});

print_r($sorted);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

    [1] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 1
        )

)
Ds\Map::sort
Ds\Map::sum
Map


Returns the sum of all values in the map.

Ds\Map::sorted
Ds\Map::toArray
Map
PHP Manual

Ds\Map::sum

(No version information available, might only be in Git)

Ds\Map::sum — Returns the sum of all values in the map.

Descrierea

public number Ds\Map::sum ( void )

Returns the sum of all values in the map.

Nota:

Arrays and objects are considered equal to zero when calculating the sum.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The sum of all the values in the map as either a float or int depending on the values in the map.

Exemple

Example #1 Ds\Map::sum() integer example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->sum());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(6)

Example #2 Ds\Map::sum() float example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2.5, "c" => 3]);
var_dump($map->sum());
?>

Exemplul de mai sus va afi?a ceva similar cu:

float(6.5)
Ds\Map::sorted
Ds\Map::toArray
Map


Converts the map to an array.

Ds\Map::sum
Ds\Map::union
Map
PHP Manual

Ds\Map::toArray

(PECL ds >= 1.0.0)

Ds\Map::toArray — Converts the map to an array.

Descrierea

public array Ds\Map::toArray ( void )

Converts the map to an array.

Precautie

Maps where non-scalar keys are can't be converted to an array.

Precautie

An array will treat all numeric keys as integers, eg. "1" and 1 as keys in the map will only result in 1 being included in the array.

Nota:

Casting to an array is not supported yet.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array containing all the values in the same order as the map.

Exemple

Example #1 Ds\Map::toArray() example

<?php
$map = new \Ds\Map([
    "a" => 1,
    "b" => 2,
    "c" => 3,
]);

var_dump($map->toArray());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(2)
  ["c"]=>
  int(3)
}
Ds\Map::sum
Ds\Map::union
Map


Creates a new map using values from the current instance and another map.

Ds\Map::toArray
Ds\Map::values
Map
PHP Manual

Ds\Map::union

(PECL ds >= 1.0.0)

Ds\Map::union — Creates a new map using values from the current instance and another map.

Descrierea

public Ds\Map Ds\Map::union ( Ds\Map $map )

Creates a new map that contains the pairs of the current instance as well as the pairs of another map.

A ? B = {x: x ? A ? x ? B}

Nota:

Values of the current instance will be overwritten by those provided where keys are equal.

Parametri

map

The other map, to combine with the current instance.

Valorile întoarse

A new map containing all the pairs of the current instance as well as another map.

See Also

  • » Union on Wikipedia

Exemple

Example #1 Ds\Map::union() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map(["b" => 3, "c" => 4, "d" => 5]);

print_r($a->union($b));
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 4
        )

    [3] => Ds\Pair Object
        (
            [key] => d
            [value] => 5
        )

)
Ds\Map::toArray
Ds\Map::values
Map


Returns a sequence of the map's values.

Ds\Map::union
Ds\Map::xor
Map
PHP Manual

Ds\Map::values

(PECL ds >= 1.0.0)

Ds\Map::values — Returns a sequence of the map's values.

Descrierea

public Ds\Sequence Ds\Map::values ( void )

Returns a sequence containing all the values of the map, in the same order.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A Ds\Sequence containing all the values of the map.

Exemple

Example #1 Ds\Map::values() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->values());
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Map)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Map::union
Ds\Map::xor
Map


Creates a new map using keys of either the current instance or of another map, but not of both.

Ds\Map::values
Pair
Map
PHP Manual

Ds\Map::xor

(PECL ds >= 1.0.0)

Ds\Map::xor — Creates a new map using keys of either the current instance or of another map, but not of both.

Descrierea

public Ds\Map Ds\Map::xor ( Ds\Map $map )

Creates a new map containing keys of the current instance as well as another map, but not of both.

A ? B = {x : x ? (A \ B) ? (B \ A)}

Parametri

map

The other map.

Valorile întoarse

A new map containing keys in the current instance as well as another map, but not in both.

See Also

  • » Symmetric Difference on Wikipedia

Exemple

Example #1 Ds\Map::xor() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map(["b" => 4, "c" => 5, "d" => 6]);

print_r($a->xor($b));
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => d
            [value] => 6
        )

)
Ds\Map::values
Pair
Map


The Pair class

(No version information available, might only be in Git)

Introducere

A pair is used by Ds\Map to pair keys with values.

Sinopsisul clasei

Ds\Pair implements JsonSerializable {
/* Metode */
public __construct ([ mixed $key [, mixed $value ]] )
}

Cuprins

  • Ds\Pair::clear — Removes all values.
  • Ds\Pair::__construct — Creates a new instance.
  • Ds\Pair::copy — Returns a shallow copy of the pair.
  • Ds\Pair::isEmpty — Returns whether the pair is empty
  • Ds\Pair::jsonSerialize — Returns a representation that can be converted to JSON.
  • Ds\Pair::toArray — Converts the pair to an array.
Ds\Map::xor
Ds\Pair::clear
Data Structures


Removes all values.

Pair
Ds\Pair::__construct
Pair
PHP Manual

Ds\Pair::clear

(No version information available, might only be in Git)

Ds\Pair::clear — Removes all values.

Descrierea

public void Ds\Pair::clear ( void )

Removes all values from the pair.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Pair::clear() example

<?php
$pair = new \Ds\Pair("a", 1);
print_r($pair);

$pair->clear();
print_r($pair);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Pair Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Pair Object
(
)
Pair
Ds\Pair::__construct
Pair


Creates a new instance.

Ds\Pair::clear
Ds\Pair::copy
Pair
PHP Manual

Ds\Pair::__construct

(PECL ds >= 1.0.0)

Ds\Pair::__construct — Creates a new instance.

Descrierea

public Ds\Pair::__construct ([ mixed $key [, mixed $value ]] )

Creates a new instance using a given key and value.

Parametri

key

The key.

value

The value.

Ds\Pair::clear
Ds\Pair::copy
Pair


Returns a shallow copy of the pair.

Ds\Pair::__construct
Ds\Pair::isEmpty
Pair
PHP Manual

Ds\Pair::copy

(No version information available, might only be in Git)

Ds\Pair::copy — Returns a shallow copy of the pair.

Descrierea

public Ds\Pair Ds\Pair::copy ( void )

Returns a shallow copy of the pair.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a shallow copy of the pair.

Exemple

Example #1 Ds\Pair::copy() example

<?php
$a = new \Ds\Pair("a", 1);
$b = $a->copy();

$a->key = "x";

print_r($a);
print_r($b);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Pair Object
(
    [key] => x
    [value] => 1
)
Ds\Pair Object
(
    [key] => a
    [value] => 1
)
Ds\Pair::__construct
Ds\Pair::isEmpty
Pair


Returns whether the pair is empty

Ds\Pair::copy
Ds\Pair::jsonSerialize
Pair
PHP Manual

Ds\Pair::isEmpty

(No version information available, might only be in Git)

Ds\Pair::isEmpty — Returns whether the pair is empty

Descrierea

public bool Ds\Pair::isEmpty ( void )

Returns whether the pair is empty.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the pair is empty, FALSE otherwise.

Exemple

Example #1 Ds\Pair::isEmpty() example

<?php
$a = new \Ds\Pair("a", 1);
$b = new \Ds\Pair();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
bool(true)
Ds\Pair::copy
Ds\Pair::jsonSerialize
Pair


Returns a representation that can be converted to JSON.

Ds\Pair::isEmpty
Ds\Pair::toArray
Pair
PHP Manual

Ds\Pair::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Pair::jsonSerialize — Returns a representation that can be converted to JSON.

See JsonSerializable::jsonSerialize()

Nota:

You should never need to call this directly.

Ds\Pair::isEmpty
Ds\Pair::toArray
Pair


Converts the pair to an array.

Ds\Pair::jsonSerialize
Set
Pair
PHP Manual

Ds\Pair::toArray

(PECL ds >= 1.0.0)

Ds\Pair::toArray — Converts the pair to an array.

Descrierea

public array Ds\Pair::toArray ( void )

Converts the pair to an array.

Nota:

Casting to an array is not supported yet.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array containing all the values in the same order as the pair.

Exemple

Example #1 Ds\Pair::toArray() example

<?php
$pair = new \Ds\Pair("a", 1);

var_dump($pair->toArray());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  ["key"]=>
  string(1) "a"
  ["value"]=>
  int(1)
}
Ds\Pair::jsonSerialize
Set
Pair


The Set class

(No version information available, might only be in Git)

Introducere

A Set is a sequence of unique values. This implementation uses the same hash table as Ds\Map, where values are used as keys and the mapped value is ignored.

Strengths

  • Values can be any type, including objects.
  • Supports array syntax (square brackets).
  • Insertion order is preserved.
  • Automatically frees allocated memory when its size drops low enough.
  • add(),
remove() and
contains() are all O(1).

Weaknesses

  • Doesn’t support
                push(),
                pop(),
                insert(),
                shift(), or
                unshift().
  • get() is O(n) if there are deleted values in the buffer before the accessed index, O(1) otherwise.

Sinopsisul clasei

Ds\Set implements Ds\Collection {
/* Constants */
const int MIN_CAPACITY = 16 ;
/* Metode */
public void add ([ mixed $...values ] )
public void allocate ( int $capacity )
public int capacity ( void )
public void clear ( void )
public bool contains ([ mixed $...values ] )
public Ds\Set copy ( void )
public Ds\Set diff ( Ds\Set $set )
public Ds\Set filter ([ callable $callback ] )
public void first ( void )
public mixed get ( int $index )
public Ds\Set intersect ( Ds\Set $set )
public bool isEmpty ( void )
public string join ([ string $glue ] )
public void last ( void )
public Ds\Set merge ( mixed $values )
public mixed reduce ( callable $callback [, mixed $initial ] )
public void remove ([ mixed $...values ] )
public void reverse ( void )
public Ds\Set reversed ( void )
public Ds\Set slice ( int $index [, int $length ] )
public void sort ([ callable $comparator ] )
public Ds\Set sorted ([ callable $comparator ] )
public number sum ( void )
public array toArray ( void )
public Ds\Set union ( Ds\Set $set )
public Ds\Set xor ( Ds\Set $set )
}

Constante predefinite

Ds\Set::MIN_CAPACITY

Cuprins

  • Ds\Set::add — Adds values to the set.
  • Ds\Set::allocate — Allocates enough memory for a required capacity.
  • Ds\Set::capacity — Returns the current capacity.
  • Ds\Set::clear — Removes all values.
  • Ds\Set::__construct — Creates a new instance.
  • Ds\Set::contains — Determines if the set contains all values.
  • Ds\Set::copy — Returns a shallow copy of the set.
  • Ds\Set::count — Returns the number of values in the set.
  • Ds\Set::diff — Creates a new set using values that aren't in another set.
  • Ds\Set::filter — Creates a new set using a callable to determine which values to include.
  • Ds\Set::first — Returns the first value in the set.
  • Ds\Set::get — Returns the value at a given index.
  • Ds\Set::intersect — Creates a new set by intersecting values with another set.
  • Ds\Set::isEmpty — Returns whether the set is empty
  • Ds\Set::join — Joins all values together as a string.
  • Ds\Set::jsonSerialize — Returns a representation that can be converted to JSON.
  • Ds\Set::last — Returns the last value in the set.
  • Ds\Set::merge — Returns the result of adding all given values to the set.
  • Ds\Set::reduce — Reduces the set to a single value using a callback function.
  • Ds\Set::remove — Removes all given values from the set.
  • Ds\Set::reverse — Reverses the set in-place.
  • Ds\Set::reversed — Returns a reversed copy.
  • Ds\Set::slice — Returns a sub-set of a given range.
  • Ds\Set::sort — Sorts the set in-place.
  • Ds\Set::sorted — Returns a sorted copy.
  • Ds\Set::sum — Returns the sum of all values in the set.
  • Ds\Set::toArray — Converts the set to an array.
  • Ds\Set::union — Creates a new set using values from the current instance and another set.
  • Ds\Set::xor — Creates a new set using values in either the current instance or in another set, but not in both.
Ds\Pair::toArray
Ds\Set::add
Data Structures


Adds values to the set.

Set
Ds\Set::allocate
Set
PHP Manual

Ds\Set::add

(PECL ds >= 1.0.0)

Ds\Set::add — Adds values to the set.

Descrierea

public void Ds\Set::add ([ mixed $...values ] )

Adds all given values to the set that haven't already been added.

Nota:

Values of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Precautie

All comparisons are strict (type and value).

Parametri

values

Values to add to the set.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Set::add() example using integers

<?php
$set = new \Ds\Set();

$set->add(1);
$set->add(1);
$set->add(2);
$set->add(3);

// Strict comparison would not treat these the same as int(1)
$set->add("1");
$set->add(true);

var_dump($set);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Set)#1 (5) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  string(1) "1"
  [4]=>
  bool(true)
}

Example #2 Ds\Set::add() example using objects

<?php
class HashableObject implements \Ds\Hashable
{
    /**
     * An arbitrary value to use as the hash value. Does not define equality.
     */
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function hash()
    {
        return $this->value;
    }

    public function equals($obj): bool
    {
        return $this->value === $obj->value;
    }
}

$set = new \Ds\Set();

$obj = new \ArrayIterator([]);

// Adding the same instance multiple times will only add the first.
$set->add($obj);
$set->add($obj);

// Adding multiple instances of the same object will add them all.
$set->add(new \stdClass());
$set->add(new \stdClass());

// Adding multiple instances of equal hashable objects will only add the first.
$set->add(new \HashableObject(1));
$set->add(new \HashableObject(1));
$set->add(new \HashableObject(2));
$set->add(new \HashableObject(2));

var_dump($set);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Set)#1 (5) {
  [0]=>
  object(ArrayIterator)#2 (1) {
    ["storage":"ArrayIterator":private]=>
    array(0) {
    }
  }
  [1]=>
  object(stdClass)#3 (0) {
  }
  [2]=>
  object(stdClass)#4 (0) {
  }
  [3]=>
  object(HashableObject)#5 (1) {
    ["value":"HashableObject":private]=>
    int(1)
  }
  [4]=>
  object(HashableObject)#6 (1) {
    ["value":"HashableObject":private]=>
    int(2)
  }
}
Set
Ds\Set::allocate
Set


Allocates enough memory for a required capacity.

Ds\Set::add
Ds\Set::capacity
Set
PHP Manual

Ds\Set::allocate

(PECL ds >= 1.0.0)

Ds\Set::allocate — Allocates enough memory for a required capacity.

Descrierea

public void Ds\Set::allocate ( int $capacity )

Allocates enough memory for a required capacity.

Parametri

capacity

The number of values for which capacity should be allocated.

Nota:

Capacity will stay the same if this value is less than or equal to the current capacity.

Nota:

Capacity will always be rounded up to the nearest power of 2.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Set::allocate() example

<?php
$set = new \Ds\Set();
var_dump($set->capacity());

$set->allocate(100);
var_dump($set->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(16)
int(128)
Ds\Set::add
Ds\Set::capacity
Set


Returns the current capacity.

Ds\Set::allocate
Ds\Set::clear
Set
PHP Manual

Ds\Set::capacity

(PECL ds >= 1.0.0)

Ds\Set::capacity — Returns the current capacity.

Descrierea

public int Ds\Set::capacity ( void )

Returns the current capacity.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current capacity.

Exemple

Example #1 Ds\Set::capacity() example

<?php
$set = new \Ds\Set();
var_dump($set->capacity());

$set->push(...range(1, 50));
var_dump($set->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(16)
int(64)
Ds\Set::allocate
Ds\Set::clear
Set


Removes all values.

Ds\Set::capacity
Ds\Set::__construct
Set
PHP Manual

Ds\Set::clear

(PECL ds >= 1.0.0)

Ds\Set::clear — Removes all values.

Descrierea

public void Ds\Set::clear ( void )

Removes all values from the set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Set::clear() example

<?php
$set = new \Ds\Set([1, 2, 3]);
print_r($set);

$set->clear();
print_r($set);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Set Object
(
)
Ds\Set::capacity
Ds\Set::__construct
Set


Creates a new instance.

Ds\Set::clear
Ds\Set::contains
Set
PHP Manual

Ds\Set::__construct

(PECL ds >= 1.0.0)

Ds\Set::__construct — Creates a new instance.

Descrierea

public Ds\Set::__construct ([ mixed $...values ] )

Creates a new instance, using either a traversable object or an array for the initial values.

Parametri

values

A traversable object or an array to use for the initial values.

Exemple

Example #1 Ds\Set::__construct() example

<?php
$set = new \Ds\Set();
var_dump($set);

$set = new \Ds\Set([1, 2, 3]);
var_dump($set);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Set)#1 (0) {
}
object(Ds\Set)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Set::clear
Ds\Set::contains
Set


Determines if the set contains all values.

Ds\Set::__construct
Ds\Set::copy
Set
PHP Manual

Ds\Set::contains

(PECL ds >= 1.0.0)

Ds\Set::contains — Determines if the set contains all values.

Descrierea

public bool Ds\Set::contains ([ mixed $...values ] )

Determines if the set contains all values.

Nota:

Values of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Precautie

All comparisons are strict (type and value).

Parametri

values

Values to check.

Valorile întoarse

FALSE if any of the provided values are not in the set, TRUE otherwise.

Exemple

Example #1 Ds\Set::contains() example

<?php
$set = new \Ds\Set([1, 2, 3]);

var_dump($set->contains(1));                // true
var_dump($set->contains(1, 2));             // true
var_dump($set->contains(...[1, 2]));        // true

var_dump($set->contains("1"));              // false
var_dump($set->contains(...[1, 2, 3, 4]));  // false

var_dump($set->contains(...[]));            // true
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(true)
bool(true)
bool(false)
bool(false)
bool(true)
Ds\Set::__construct
Ds\Set::copy
Set


Returns a shallow copy of the set.

Ds\Set::contains
Ds\Set::count
Set
PHP Manual

Ds\Set::copy

(PECL ds >= 1.0.0)

Ds\Set::copy — Returns a shallow copy of the set.

Descrierea

public Ds\Set Ds\Set::copy ( void )

Returns a shallow copy of the set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a shallow copy of the set.

Exemple

Example #1 Ds\Set::copy() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = $a->copy();

// Updating the copy doesn't affect the original
$b->add(4);

print_r($a);
print_r($b);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
Ds\Set::contains
Ds\Set::count
Set


Returns the number of values in the set.

Ds\Set::copy
Ds\Set::diff
Set
PHP Manual

Ds\Set::count

(PECL ds >= 1.0.0)

Ds\Set::count — Returns the number of values in the set.

See Countable::count()

Ds\Set::copy
Ds\Set::diff
Set


Creates a new set using values that aren't in another set.

Ds\Set::count
Ds\Set::filter
Set
PHP Manual

Ds\Set::diff

(PECL ds >= 1.0.0)

Ds\Set::diff — Creates a new set using values that aren't in another set.

Descrierea

public Ds\Set Ds\Set::diff ( Ds\Set $set )

Creates a new set using values that aren't in another set.

A \ B = {x ? A | x ? B}

Parametri

set

Set containing the values to exclude.

Valorile întoarse

A new set containing all values that were not in the other set.

See Also

  • » Compliment on Wikipedia

Exemple

Example #1 Ds\Set::diff() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set([3, 4, 5]);

var_dump($a->diff($b));
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Set)#3 (2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}
Ds\Set::count
Ds\Set::filter
Set


Creates a new set using a callable to determine which values to include.

Ds\Set::diff
Ds\Set::first
Set
PHP Manual

Ds\Set::filter

(PECL ds >= 1.0.0)

Ds\Set::filter — Creates a new set using a callable to determine which values to include.

Descrierea

public Ds\Set Ds\Set::filter ([ callable $callback ] )

Creates a new set using a callable to determine which values to include.

Parametri

callback

bool callback ( mixed $value )

Optional callable which returns TRUE if the value should be included, FALSE otherwise.

If a callback is not provided, only values which are TRUE (see converting to boolean) will be included.

Valorile întoarse

A new set containing all the values for which either the callback returned TRUE, or all values that convert to TRUE if a callback was not provided.

Exemple

Example #1 Ds\Set::filter() example using callback function

<?php
$set = new \Ds\Set([1, 2, 3, 4, 5]);

var_dump($set->filter(function($value) {
    return $value % 2 == 0;
}));
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Set)#3 (2) {
  [0]=>
  int(2)
  [1]=>
  int(4)
}

Example #2 Ds\Set::filter() example without a callback function

<?php
$set = new \Ds\Set([0, 1, 'a', true, false]);

var_dump($set->filter());
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Set)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}
Ds\Set::diff
Ds\Set::first
Set


Returns the first value in the set.

Ds\Set::filter
Ds\Set::get
Set
PHP Manual

Ds\Set::first

(PECL ds >= 1.0.0)

Ds\Set::first — Returns the first value in the set.

Descrierea

public void Ds\Set::first ( void )

Returns the first value in the set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The first value in the set.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Set::first() example

<?php
$set = new \Ds\Set([1, 2, 3]);
var_dump($set->first());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(1)
Ds\Set::filter
Ds\Set::get
Set


Returns the value at a given index.

Ds\Set::first
Ds\Set::intersect
Set
PHP Manual

Ds\Set::get

(PECL ds >= 1.0.0)

Ds\Set::get — Returns the value at a given index.

Descrierea

public mixed Ds\Set::get ( int $index )

Returns the value at a given index.

Parametri

index

The index to access, starting at 0.

Valorile întoarse

The value at the requested index.

Erori/Excep?ii

OutOfRangeException if the index is not valid.

Exemple

Example #1 Ds\Set::get() example

<?php
$set = new \Ds\Set(["a", "b", "c"]);

var_dump($set->get(0));
var_dump($set->get(1));
var_dump($set->get(2));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
string(1) "b"
string(1) "c"

Example #2 Ds\Set::get() example using array syntax

<?php
$set = new \Ds\Set(["a", "b", "c"]);

var_dump($set[0]);
var_dump($set[1]);
var_dump($set[2]);
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
string(1) "b"
string(1) "c"
Ds\Set::first
Ds\Set::intersect
Set


Creates a new set by intersecting values with another set.

Ds\Set::get
Ds\Set::isEmpty
Set
PHP Manual

Ds\Set::intersect

(PECL ds >= 1.0.0)

Ds\Set::intersect — Creates a new set by intersecting values with another set.

Descrierea

public Ds\Set Ds\Set::intersect ( Ds\Set $set )

Creates a new set using values common to both the current instance and another set. In other words, returns a copy of the current instance with all values removed that are not in the other set.

A n B = {x : x ? A ? x ? B}

Parametri

set

The other set.

Valorile întoarse

The intersection of the current instance and another set.

See Also

  • » Intersection on Wikipedia

Exemple

Example #1 Ds\Set::intersect() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set([3, 4, 5]);

var_dump($a->intersect($b));
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Set)#3 (1) {
  [0]=>
  int(3)
}
Ds\Set::get
Ds\Set::isEmpty
Set


Returns whether the set is empty

Ds\Set::intersect
Ds\Set::join
Set
PHP Manual

Ds\Set::isEmpty

(PECL ds >= 1.0.0)

Ds\Set::isEmpty — Returns whether the set is empty

Descrierea

public bool Ds\Set::isEmpty ( void )

Returns whether the set is empty.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the set is empty, FALSE otherwise.

Exemple

Example #1 Ds\Set::isEmpty() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
bool(true)
Ds\Set::intersect
Ds\Set::join
Set


Joins all values together as a string.

Ds\Set::isEmpty
Ds\Set::jsonSerialize
Set
PHP Manual

Ds\Set::join

(PECL ds >= 1.0.0)

Ds\Set::join — Joins all values together as a string.

Descrierea

public string Ds\Set::join ([ string $glue ] )

Joins all values together as a string using an optional separator between each value.

Parametri

glue

An optional string to separate each value.

Valorile întoarse

All values of the set joined together as a string.

Exemple

Example #1 Ds\Set::join() example using a separator string

<?php
$set = new \Ds\Set(["a", "b", "c", 1, 2, 3]);

var_dump($set->join("|"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(11) "a|b|c|1|2|3"

Example #2 Ds\Set::join() example without a separator string

<?php
$set = new \Ds\Set(["a", "b", "c", 1, 2, 3]);

var_dump($set->join());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(11) "abc123"
Ds\Set::isEmpty
Ds\Set::jsonSerialize
Set


Returns a representation that can be converted to JSON.

Ds\Set::join
Ds\Set::last
Set
PHP Manual

Ds\Set::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Set::jsonSerialize — Returns a representation that can be converted to JSON.

See JsonSerializable::jsonSerialize()

Nota:

You should never need to call this directly.

Ds\Set::join
Ds\Set::last
Set


Returns the last value in the set.

Ds\Set::jsonSerialize
Ds\Set::merge
Set
PHP Manual

Ds\Set::last

(PECL ds >= 1.0.0)

Ds\Set::last — Returns the last value in the set.

Descrierea

public void Ds\Set::last ( void )

Returns the last value in the set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The last value in the set.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Set::last() example

<?php
$set = new \Ds\Set([1, 2, 3]);
var_dump($set->last());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)
Ds\Set::jsonSerialize
Ds\Set::merge
Set


Returns the result of adding all given values to the set.

Ds\Set::last
Ds\Set::reduce
Set
PHP Manual

Ds\Set::merge

(PECL ds >= 1.0.3)

Ds\Set::merge — Returns the result of adding all given values to the set.

Descrierea

public Ds\Set Ds\Set::merge ( mixed $values )

Returns the result of adding all given values to the set.

Parametri

values

A traversable object or an array.

Valorile întoarse

The result of adding all given values to the set, effectively the same as adding the values to a copy, then returning that copy.

Nota:

The current instance won't be affected.

Exemple

Example #1 Ds\Set::merge() example

<?php
$set = new \Ds\Set([1, 2, 3]);

var_dump($set->merge([3, 4, 5]));
var_dump($set);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Set)#2 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
}
object(Ds\Set)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Set::last
Ds\Set::reduce
Set


Reduces the set to a single value using a callback function.

Ds\Set::merge
Ds\Set::remove
Set
PHP Manual

Ds\Set::reduce

(PECL ds >= 1.0.0)

Ds\Set::reduce — Reduces the set to a single value using a callback function.

Descrierea

public mixed Ds\Set::reduce ( callable $callback [, mixed $initial ] )

Reduces the set to a single value using a callback function.

Parametri

callback
mixed callback ( mixed $carry , mixed $value )
carry

The return value of the previous callback, or initial if it's the first iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be NULL.

Valorile întoarse

The return value of the final callback.

Exemple

Example #1 Ds\Set::reduce() with initial value example

<?php
$set = new \Ds\Set([1, 2, 3]);

$callback = function($carry, $value) {
    return $carry * $value;
};

var_dump($set->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 =  5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(30)

Example #2 Ds\Set::reduce() without an initial value example

<?php
$set = new \Ds\Set([1, 2, 3]);

var_dump($set->reduce(function($carry, $value) {
    return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 =  6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(21)
Ds\Set::merge
Ds\Set::remove
Set


Removes all given values from the set.

Ds\Set::reduce
Ds\Set::reverse
Set
PHP Manual

Ds\Set::remove

(PECL ds >= 1.0.0)

Ds\Set::remove — Removes all given values from the set.

Descrierea

public void Ds\Set::remove ([ mixed $...values ] )

Removes all given values from the set, ignoring any that are not in the set.

Parametri

values

The values to remove.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Set::remove() example

<?php
$set = new \Ds\Set([1, 2, 3, 4, 5]);

$set->remove(1);            // Remove 1
$set->remove(1, 2);         // Can't find 1, but remove 2
$set->remove(...[3, 4]);    // Remove 3 and 4

var_dump($set);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Set)#1 (1) {
  [0]=>
  int(5)
}
Ds\Set::reduce
Ds\Set::reverse
Set


Reverses the set in-place.

Ds\Set::remove
Ds\Set::reversed
Set
PHP Manual

Ds\Set::reverse

(PECL ds >= 1.0.0)

Ds\Set::reverse — Reverses the set in-place.

Descrierea

public void Ds\Set::reverse ( void )

Reverses the set in-place.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Set::reverse() example

<?php
$set = new \Ds\Set(["a", "b", "c"]);
$set->reverse();

print_r($set);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Set Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Set::remove
Ds\Set::reversed
Set


Returns a reversed copy.

Ds\Set::reverse
Ds\Set::slice
Set
PHP Manual

Ds\Set::reversed

(PECL ds >= 1.0.0)

Ds\Set::reversed — Returns a reversed copy.

Descrierea

public Ds\Set Ds\Set::reversed ( void )

Returns a reversed copy of the set.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A reversed copy of the set.

Nota:

The current instance is not affected.

Exemple

Example #1 Ds\Set::reversed() example

<?php
$set = new \Ds\Set(["a", "b", "c"]);

print_r($set->reversed());
print_r($set);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Set Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Set Object
(
    [0] => a
    [1] => b
    [2] => c
)
Ds\Set::reverse
Ds\Set::slice
Set


Returns a sub-set of a given range.

Ds\Set::reversed
Ds\Set::sort
Set
PHP Manual

Ds\Set::slice

(PECL ds >= 1.0.0)

Ds\Set::slice — Returns a sub-set of a given range.

Descrierea

public Ds\Set Ds\Set::slice ( int $index [, int $length ] )

Creates a sub-set of a given range.

Parametri

index

The index at which the sub-set starts.

If positive, the set will start at that index in the set. If negative, the set will start that far from the end.

length

If a length is given and is positive, the resulting set will have up to that many values in it. If the length results in an overflow, only values up to the end of the set will be included. If a length is given and is negative, the set will stop that many values from the end. If a length is not provided, the resulting set will contain all values between the index and the end of the set.

Valorile întoarse

A sub-set of the given range.

Exemple

Example #1 Ds\Set::slice() example

<?php
$set = new \Ds\Set(["a", "b", "c", "d", "e"]);

// Slice from 2 onwards
print_r($set->slice(2));

// Slice from 1, for a length of 3
print_r($set->slice(1, 3));

// Slice from 1 onwards
print_r($set->slice(1));

// Slice from 2 from the end onwards
print_r($set->slice(-2));

// Slice from 1 to 1 from the end
print_r($set->slice(1, -1));
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Set Object
(
    [0] => c
    [1] => d
    [2] => e
)
Ds\Set Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Set Object
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)
Ds\Set Object
(
    [0] => d
    [1] => e
)
Ds\Set Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Set::reversed
Ds\Set::sort
Set


Sorts the set in-place.

Ds\Set::slice
Ds\Set::sorted
Set
PHP Manual

Ds\Set::sort

(PECL ds >= 1.0.0)

Ds\Set::sort — Sorts the set in-place.

Descrierea

public void Ds\Set::sort ([ callable $comparator ] )

Sorts the set in-place, using an optional comparator function.

Parametri

comparator

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
Precautie

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Set::sort() example

<?php
$set = new \Ds\Set([4, 5, 1, 3, 2]);
$set->sort();

print_r($set);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Set::sort() example using a comparator

<?php
$set = new \Ds\Set([4, 5, 1, 3, 2]);

$set->sort(function($a, $b) {
    return $b <=> $a;
});

print_r($set);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Set Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)
Ds\Set::slice
Ds\Set::sorted
Set


Returns a sorted copy.

Ds\Set::sort
Ds\Set::sum
Set
PHP Manual

Ds\Set::sorted

(PECL ds >= 1.0.0)

Ds\Set::sorted — Returns a sorted copy.

Descrierea

public Ds\Set Ds\Set::sorted ([ callable $comparator ] )

Returns a sorted copy, using an optional comparator function.

Parametri

comparator

Func?ia de comparare trebuie sa întoarca un întreg mai mic, egal cu sau mai mare decât zero daca primul argument este considerat respectiv mai mic, egal cu sau mai mare decât al doilea argument.

int callback ( mixed $a, mixed $b )
Precautie

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Valorile întoarse

Returns a sorted copy of the set.

Exemple

Example #1 Ds\Set::sorted() example

<?php
$set = new \Ds\Set([4, 5, 1, 3, 2]);

print_r($set->sorted());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Set::sorted() example using a comparator

<?php
$set = new \Ds\Set([4, 5, 1, 3, 2]);

$sorted = $set->sorted(function($a, $b) {
    return $b <=> $a;
});

print_r($sorted);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Set Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)
Ds\Set::sort
Ds\Set::sum
Set


Returns the sum of all values in the set.

Ds\Set::sorted
Ds\Set::toArray
Set
PHP Manual

Ds\Set::sum

(PECL ds >= 1.0.0)

Ds\Set::sum — Returns the sum of all values in the set.

Descrierea

public number Ds\Set::sum ( void )

Returns the sum of all values in the set.

Nota:

Arrays and objects are considered equal to zero when calculating the sum.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The sum of all the values in the set as either a float or int depending on the values in the set.

Exemple

Example #1 Ds\Set::sum() integer example

<?php
$set = new \Ds\Set([1, 2, 3]);
var_dump($set->sum());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(6)

Example #2 Ds\Set::sum() float example

<?php
$set = new \Ds\Set([1, 2.5, 3]);
var_dump($set->sum());
?>

Exemplul de mai sus va afi?a ceva similar cu:

float(6.5)
Ds\Set::sorted
Ds\Set::toArray
Set


Converts the set to an array.

Ds\Set::sum
Ds\Set::union
Set
PHP Manual

Ds\Set::toArray

(PECL ds >= 1.0.0)

Ds\Set::toArray — Converts the set to an array.

Descrierea

public array Ds\Set::toArray ( void )

Converts the set to an array.

Nota:

Casting to an array is not supported yet.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array containing all the values in the same order as the set.

Exemple

Example #1 Ds\Set::toArray() example

<?php
$set = new \Ds\Set([1, 2, 3]);

var_dump($set->toArray());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Set::sum
Ds\Set::union
Set


Creates a new set using values from the current instance and another set.

Ds\Set::toArray
Ds\Set::xor
Set
PHP Manual

Ds\Set::union

(PECL ds >= 1.0.0)

Ds\Set::union — Creates a new set using values from the current instance and another set.

Descrierea

public Ds\Set Ds\Set::union ( Ds\Set $set )

Creates a new set that contains the values of the current instance as well as the values of another set.

A ? B = {x: x ? A ? x ? B}

Parametri

set

The other set, to combine with the current instance.

Valorile întoarse

A new set containing all the values of the current instance as well as another set.

See Also

  • » Union on Wikipedia

Exemple

Example #1 Ds\Set::union() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set([3, 4, 5]);

var_dump($a->union($b));
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Set)#3 (5) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
}
Ds\Set::toArray
Ds\Set::xor
Set


Creates a new set using values in either the current instance or in another set, but not in both.

Ds\Set::union
Stack
Set
PHP Manual

Ds\Set::xor

(PECL ds >= 1.0.0)

Ds\Set::xor — Creates a new set using values in either the current instance or in another set, but not in both.

Descrierea

public Ds\Set Ds\Set::xor ( Ds\Set $set )

Creates a new set containing values in the current instance as well as another set, but not in both.

A ? B = {x : x ? (A \ B) ? (B \ A)}

Parametri

set

The other set.

Valorile întoarse

A new set containing values in the current instance as well as another set, but not in both.

See Also

  • » Symmetric Difference on Wikipedia

Exemple

Example #1 Ds\Set::xor() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set([3, 4, 5]);

var_dump($a->xor($b));
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Set)#3 (4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(4)
  [3]=>
  int(5)
}
Ds\Set::union
Stack
Set


The Stack class

(No version information available, might only be in Git)

Introducere

A Stack is a “last in, first out” or “LIFO” collection that only allows access to the value at the top of the structure and iterates in that order, destructively.

Uses a Ds\Vector internally.

Sinopsisul clasei

Ds\Stack implements Ds\Collection {
/* Metode */
public void allocate ( int $capacity )
public int capacity ( void )
public void clear ( void )
public Ds\Stack copy ( void )
public bool isEmpty ( void )
public mixed peek ( void )
public mixed pop ( void )
public void push ([ mixed $...values ] )
public array toArray ( void )
}

Cuprins

  • Ds\Stack::allocate — Allocates enough memory for a required capacity.
  • Ds\Stack::capacity — Returns the current capacity.
  • Ds\Stack::clear — Removes all values.
  • Ds\Stack::__construct — Creates a new instance.
  • Ds\Stack::copy — Returns a shallow copy of the stack.
  • Ds\Stack::count — Returns the number of values in the stack.
  • Ds\Stack::isEmpty — Returns whether the stack is empty
  • Ds\Stack::jsonSerialize — Returns a representation that can be converted to JSON.
  • Ds\Stack::peek — Returns the value at the top of the stack.
  • Ds\Stack::pop — Removes and returns the value at the top of the stack.
  • Ds\Stack::push — Pushes values onto the stack.
  • Ds\Stack::toArray — Converts the stack to an array.
Ds\Set::xor
Ds\Stack::allocate
Data Structures


Allocates enough memory for a required capacity.

Stack
Ds\Stack::capacity
Stack
PHP Manual

Ds\Stack::allocate

(PECL ds >= 1.0.0)

Ds\Stack::allocate — Allocates enough memory for a required capacity.

Descrierea

public void Ds\Stack::allocate ( int $capacity )

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

Parametri

capacity

The number of values for which capacity should be allocated.

Nota:

Capacity will stay the same if this value is less than or equal to the current capacity.

Valorile întoarse

Nu este întoarsa nici o valoare.

Stack
Ds\Stack::capacity
Stack


Returns the current capacity.

Ds\Stack::allocate
Ds\Stack::clear
Stack
PHP Manual

Ds\Stack::capacity

(PECL ds >= 1.0.0)

Ds\Stack::capacity — Returns the current capacity.

Descrierea

public int Ds\Stack::capacity ( void )

Returns the current capacity.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current capacity.

Ds\Stack::allocate
Ds\Stack::clear
Stack


Removes all values.

Ds\Stack::capacity
Ds\Stack::__construct
Stack
PHP Manual

Ds\Stack::clear

(PECL ds >= 1.0.0)

Ds\Stack::clear — Removes all values.

Descrierea

public void Ds\Stack::clear ( void )

Removes all values from the stack.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Stack::clear() example

<?php
$stack = new \Ds\Stack([1, 2, 3]);
print_r($stack);

$stack->clear();
print_r($stack);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Stack Object
(
    [0] => 3
    [1] => 2
    [2] => 1
)
Ds\Stack Object
(
)
Ds\Stack::capacity
Ds\Stack::__construct
Stack


Creates a new instance.

Ds\Stack::clear
Ds\Stack::copy
Stack
PHP Manual

Ds\Stack::__construct

(PECL ds >= 1.0.0)

Ds\Stack::__construct — Creates a new instance.

Descrierea

public Ds\Stack::__construct ([ mixed $values ] )

Creates a new instance, using either a traversable object or an array for the initial values.

Parametri

values

A traversable object or an array to use for the initial values.

Exemple

Example #1 Ds\Stack::__construct() example

<?php
$stack = new \Ds\Stack();
print_r($stack);

$stack = new \Ds\Stack([1, 2, 3]);
print_r($stack);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Stack Object
(
)
Ds\Stack Object
(
    [0] => 3
    [1] => 2
    [2] => 1
)
Ds\Stack::clear
Ds\Stack::copy
Stack


Returns a shallow copy of the stack.

Ds\Stack::__construct
Ds\Stack::count
Stack
PHP Manual

Ds\Stack::copy

(PECL ds >= 1.0.0)

Ds\Stack::copy — Returns a shallow copy of the stack.

Descrierea

public Ds\Stack Ds\Stack::copy ( void )

Returns a shallow copy of the stack.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a shallow copy of the stack.

Exemple

Example #1 Ds\Stack::copy() example

<?php
$a = new \Ds\Stack([1, 2, 3]);
$b = $a->copy();

// Updating the copy doesn't affect the original
$b->push(4);

print_r($a);
print_r($b);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Stack Object
(
    [0] => 3
    [1] => 2
    [2] => 1
)
Ds\Stack Object
(
    [0] => 4
    [1] => 3
    [2] => 2
    [3] => 1
)
Ds\Stack::__construct
Ds\Stack::count
Stack


Returns the number of values in the stack.

Ds\Stack::copy
Ds\Stack::isEmpty
Stack
PHP Manual

Ds\Stack::count

(PECL ds >= 1.0.0)

Ds\Stack::count — Returns the number of values in the stack.

See Countable::count()

Ds\Stack::copy
Ds\Stack::isEmpty
Stack


Returns whether the stack is empty

Ds\Stack::count
Ds\Stack::jsonSerialize
Stack
PHP Manual

Ds\Stack::isEmpty

(PECL ds >= 1.0.0)

Ds\Stack::isEmpty — Returns whether the stack is empty

Descrierea

public bool Ds\Stack::isEmpty ( void )

Returns whether the stack is empty.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the stack is empty, FALSE otherwise.

Exemple

Example #1 Ds\Stack::isEmpty() example

<?php
$a = new \Ds\Stack([1, 2, 3]);
$b = new \Ds\Stack();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
bool(true)
Ds\Stack::count
Ds\Stack::jsonSerialize
Stack


Returns a representation that can be converted to JSON.

Ds\Stack::isEmpty
Ds\Stack::peek
Stack
PHP Manual

Ds\Stack::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Stack::jsonSerialize — Returns a representation that can be converted to JSON.

See JsonSerializable::jsonSerialize()

Nota:

You should never need to call this directly.

Ds\Stack::isEmpty
Ds\Stack::peek
Stack


Returns the value at the top of the stack.

Ds\Stack::jsonSerialize
Ds\Stack::pop
Stack
PHP Manual

Ds\Stack::peek

(PECL ds >= 1.0.0)

Ds\Stack::peek — Returns the value at the top of the stack.

Descrierea

public mixed Ds\Stack::peek ( void )

Returns the value at the top of the stack, but does not remove it.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The value at the top of the stack.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Stack::peek() example

<?php
$stack = new \Ds\Stack();

$stack->push("a");
$stack->push("b");
$stack->push("c");

var_dump($stack->peek());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "c"
Ds\Stack::jsonSerialize
Ds\Stack::pop
Stack


Removes and returns the value at the top of the stack.

Ds\Stack::peek
Ds\Stack::push
Stack
PHP Manual

Ds\Stack::pop

(PECL ds >= 1.0.0)

Ds\Stack::pop — Removes and returns the value at the top of the stack.

Descrierea

public mixed Ds\Stack::pop ( void )

Removes and returns the value at the top of the stack.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The removed value which was at the top of the stack.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Stack::pop() example

<?php
$stack = new \Ds\Stack();

$stack->push("a");
$stack->push("b");
$stack->push("c");

var_dump($stack->pop());
var_dump($stack->pop());
var_dump($stack->pop());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "c"
string(1) "b"
string(1) "a"
Ds\Stack::peek
Ds\Stack::push
Stack


Pushes values onto the stack.

Ds\Stack::pop
Ds\Stack::toArray
Stack
PHP Manual

Ds\Stack::push

(PECL ds >= 1.0.0)

Ds\Stack::push — Pushes values onto the stack.

Descrierea

public void Ds\Stack::push ([ mixed $...values ] )

Pushes values onto the stack.

Parametri

values

The values to push onto the stack.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Stack::push() example

<?php
$stack = new \Ds\Stack();

$stack->push("a");
$stack->push("b");
$stack->push("c", "d");
$stack->push(...["e", "f"]);

print_r($stack);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Stack Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)
Ds\Stack::pop
Ds\Stack::toArray
Stack


Converts the stack to an array.

Ds\Stack::push
Queue
Stack
PHP Manual

Ds\Stack::toArray

(PECL ds >= 1.0.0)

Ds\Stack::toArray — Converts the stack to an array.

Descrierea

public array Ds\Stack::toArray ( void )

Converts the stack to an array.

Nota:

Casting to an array is not supported yet.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array containing all the values in the same order as the stack.

Exemple

Example #1 Ds\Stack::toArray() example

<?php
$stack = new \Ds\Stack([1, 2, 3]);

var_dump($stack->toArray());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  [0]=>
  int(3)
  [1]=>
  int(2)
  [2]=>
  int(1)
}
Ds\Stack::push
Queue
Stack


The Queue class

(No version information available, might only be in Git)

Introducere

A Queue is a “first in, first out” or “FIFO” collection that only allows access to the value at the front of the queue and iterates in that order, destructively.

Sinopsisul clasei

Ds\Queue implements Ds\Collection {
/* Constants */
const int MIN_CAPACITY = 8 ;
/* Metode */
public void allocate ( int $capacity )
public int capacity ( void )
public void clear ( void )
public Ds\Queue copy ( void )
public bool isEmpty ( void )
public mixed peek ( void )
public mixed pop ( void )
public void push ([ mixed $...values ] )
public array toArray ( void )
}

Constante predefinite

Ds\Queue::MIN_CAPACITY

Cuprins

  • Ds\Queue::allocate — Allocates enough memory for a required capacity.
  • Ds\Queue::capacity — Returns the current capacity.
  • Ds\Queue::clear — Removes all values.
  • Ds\Queue::__construct — Creates a new instance.
  • Ds\Queue::copy — Returns a shallow copy of the queue.
  • Ds\Queue::count — Returns the number of values in the queue.
  • Ds\Queue::isEmpty — Returns whether the queue is empty
  • Ds\Queue::jsonSerialize — Returns a representation that can be converted to JSON.
  • Ds\Queue::peek — Returns the value at the front of the queue.
  • Ds\Queue::pop — Removes and returns the value at the front of the queue.
  • Ds\Queue::push — Pushes values into the queue.
  • Ds\Queue::toArray — Converts the queue to an array.
Ds\Stack::toArray
Ds\Queue::allocate
Data Structures


Allocates enough memory for a required capacity.

Queue
Ds\Queue::capacity
Queue
PHP Manual

Ds\Queue::allocate

(PECL ds >= 1.0.0)

Ds\Queue::allocate — Allocates enough memory for a required capacity.

Descrierea

public void Ds\Queue::allocate ( int $capacity )

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

Nota:

Capacity will always be rounded up to the nearest power of 2.

Parametri

capacity

The number of values for which capacity should be allocated.

Nota:

Capacity will stay the same if this value is less than or equal to the current capacity.

Nota:

Capacity will always be rounded up to the nearest power of 2.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Queue::allocate() example

<?php
$queue = new \Ds\Queue();
var_dump($queue->capacity());

$queue->allocate(100);
var_dump($queue->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(8)
int(128)
Queue
Ds\Queue::capacity
Queue


Returns the current capacity.

Ds\Queue::allocate
Ds\Queue::clear
Queue
PHP Manual

Ds\Queue::capacity

(PECL ds >= 1.0.0)

Ds\Queue::capacity — Returns the current capacity.

Descrierea

public int Ds\Queue::capacity ( void )

Returns the current capacity.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current capacity.

Exemple

Example #1 Ds\Queue::capacity() example

<?php
$queue = new \Ds\Queue();
var_dump($queue->capacity());

$queue->push(...range(1, 50));
var_dump($queue->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(8)
int(64)
Ds\Queue::allocate
Ds\Queue::clear
Queue


Removes all values.

Ds\Queue::capacity
Ds\Queue::__construct
Queue
PHP Manual

Ds\Queue::clear

(PECL ds >= 1.0.0)

Ds\Queue::clear — Removes all values.

Descrierea

public void Ds\Queue::clear ( void )

Removes all values from the queue.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Queue::clear() example

<?php
$queue = new \Ds\Queue([1, 2, 3]);
print_r($queue);

$queue->clear();
print_r($queue);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Queue Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Queue Object
(
)
Ds\Queue::capacity
Ds\Queue::__construct
Queue


Creates a new instance.

Ds\Queue::clear
Ds\Queue::copy
Queue
PHP Manual

Ds\Queue::__construct

(PECL ds >= 1.0.0)

Ds\Queue::__construct — Creates a new instance.

Descrierea

public Ds\Queue::__construct ([ mixed $values ] )

Creates a new instance, using either a traversable object or an array for the initial values.

Parametri

values

A traversable object or an array to use for the initial values.

Exemple

Example #1 Ds\Queue::__construct() example

<?php
$queue = new \Ds\Queue();
var_dump($queue);

$queue = new \Ds\Queue([1, 2, 3]);
var_dump($queue);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\Queue)#2 (0) {
}
object(Ds\Queue)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Queue::clear
Ds\Queue::copy
Queue


Returns a shallow copy of the queue.

Ds\Queue::__construct
Ds\Queue::count
Queue
PHP Manual

Ds\Queue::copy

(PECL ds >= 1.0.0)

Ds\Queue::copy — Returns a shallow copy of the queue.

Descrierea

public Ds\Queue Ds\Queue::copy ( void )

Returns a shallow copy of the queue.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a shallow copy of the queue.

Exemple

Example #1 Ds\Queue::copy() example

<?php
$a = new \Ds\Queue([1, 2, 3]);
$b = $a->copy();

// Updating the copy doesn't affect the original
$b->push(4);

print_r($a);
print_r($b);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Queue Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Queue Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
Ds\Queue::__construct
Ds\Queue::count
Queue


Returns the number of values in the queue.

Ds\Queue::copy
Ds\Queue::isEmpty
Queue
PHP Manual

Ds\Queue::count

(PECL ds >= 1.0.0)

Ds\Queue::count — Returns the number of values in the queue.

See Countable::count()

Ds\Queue::copy
Ds\Queue::isEmpty
Queue


Returns whether the queue is empty

Ds\Queue::count
Ds\Queue::jsonSerialize
Queue
PHP Manual

Ds\Queue::isEmpty

(PECL ds >= 1.0.0)

Ds\Queue::isEmpty — Returns whether the queue is empty

Descrierea

public bool Ds\Queue::isEmpty ( void )

Returns whether the queue is empty.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the queue is empty, FALSE otherwise.

Exemple

Example #1 Ds\Queue::isEmpty() example

<?php
$a = new \Ds\Queue([1, 2, 3]);
$b = new \Ds\Queue();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
bool(true)
Ds\Queue::count
Ds\Queue::jsonSerialize
Queue


Returns a representation that can be converted to JSON.

Ds\Queue::isEmpty
Ds\Queue::peek
Queue
PHP Manual

Ds\Queue::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Queue::jsonSerialize — Returns a representation that can be converted to JSON.

See JsonSerializable::jsonSerialize()

Nota:

You should never need to call this directly.

Ds\Queue::isEmpty
Ds\Queue::peek
Queue


Returns the value at the front of the queue.

Ds\Queue::jsonSerialize
Ds\Queue::pop
Queue
PHP Manual

Ds\Queue::peek

(PECL ds >= 1.0.0)

Ds\Queue::peek — Returns the value at the front of the queue.

Descrierea

public mixed Ds\Queue::peek ( void )

Returns the value at the front of the queue, but does not remove it.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The value at the front of the queue.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Queue::peek() example

<?php
$queue = new \Ds\Queue();

$queue->push("a");
$queue->push("b");
$queue->push("c");

var_dump($queue->peek());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
Ds\Queue::jsonSerialize
Ds\Queue::pop
Queue


Removes and returns the value at the front of the queue.

Ds\Queue::peek
Ds\Queue::push
Queue
PHP Manual

Ds\Queue::pop

(PECL ds >= 1.0.0)

Ds\Queue::pop — Removes and returns the value at the front of the queue.

Descrierea

public mixed Ds\Queue::pop ( void )

Removes and returns the value at the front of the queue.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The removed value which was at the front of the queue.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\Queue::pop() example

<?php
$queue = new \Ds\Queue();

$queue->push("a");
$queue->push("b");
$queue->push("c");

var_dump($queue->pop());
var_dump($queue->pop());
var_dump($queue->pop());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
string(1) "b"
string(1) "c"
Ds\Queue::peek
Ds\Queue::push
Queue


Pushes values into the queue.

Ds\Queue::pop
Ds\Queue::toArray
Queue
PHP Manual

Ds\Queue::push

(PECL ds >= 1.0.0)

Ds\Queue::push — Pushes values into the queue.

Descrierea

public void Ds\Queue::push ([ mixed $...values ] )

Pushes values into the queue.

Parametri

values

The values to push into the queue.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\Queue::push() example

<?php
$queue = new \Ds\Queue();

$queue->push("a");
$queue->push("b");
$queue->push("c", "d");
$queue->push(...["e", "f"]);

print_r($queue);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\Queue Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)
Ds\Queue::pop
Ds\Queue::toArray
Queue


Converts the queue to an array.

Ds\Queue::push
PriorityQueue
Queue
PHP Manual

Ds\Queue::toArray

(PECL ds >= 1.0.0)

Ds\Queue::toArray — Converts the queue to an array.

Descrierea

public array Ds\Queue::toArray ( void )

Converts the queue to an array.

Nota:

Casting to an array is not supported yet.

Nota:

This method is not destructive.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array containing all the values in the same order as the queue.

Exemple

Example #1 Ds\Queue::toArray() example

<?php
$queue = new \Ds\Queue([1, 2, 3]);

var_dump($queue->toArray());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Ds\Queue::push
PriorityQueue
Queue


The PriorityQueue class

(No version information available, might only be in Git)

Introducere

A PriorityQueue is very similar to a Queue. Values are pushed into the queue with an assigned priority, and the value with the highest priority will always be at the front of the queue.

Implemented using a max heap.

Nota:

"First in, first out" ordering is preserved for values with the same priority.

Nota:

Iterating over a PriorityQueue is destructive, equivalent to successive pop operations until the queue is empty.

Sinopsisul clasei

Ds\PriorityQueue implements Ds\Collection {
/* Constants */
const int MIN_CAPACITY = 8 ;
/* Metode */
public void allocate ( int $capacity )
public int capacity ( void )
public void clear ( void )
public Ds\PriorityQueue copy ( void )
public bool isEmpty ( void )
public mixed peek ( void )
public mixed pop ( void )
public void push ( mixed $value , int $priority )
public array toArray ( void )
}

Constante predefinite

Ds\PriorityQueue::MIN_CAPACITY

Cuprins

  • Ds\PriorityQueue::allocate — Allocates enough memory for a required capacity.
  • Ds\PriorityQueue::capacity — Returns the current capacity.
  • Ds\PriorityQueue::clear — Removes all values.
  • Ds\PriorityQueue::__construct — Creates a new instance.
  • Ds\PriorityQueue::copy — Returns a shallow copy of the queue.
  • Ds\PriorityQueue::count — Returns the number of values in the queue.
  • Ds\PriorityQueue::isEmpty — Returns whether the queue is empty
  • Ds\PriorityQueue::jsonSerialize — Returns a representation that can be converted to JSON.
  • Ds\PriorityQueue::peek — Returns the value at the front of the queue.
  • Ds\PriorityQueue::pop — Removes and returns the value with the highest priority.
  • Ds\PriorityQueue::push — Pushes values into the queue.
  • Ds\PriorityQueue::toArray — Converts the queue to an array.
Ds\Queue::toArray
Ds\PriorityQueue::allocate
Data Structures


Allocates enough memory for a required capacity.

PriorityQueue
Ds\PriorityQueue::capacity
PriorityQueue
PHP Manual

Ds\PriorityQueue::allocate

(PECL ds >= 1.0.0)

Ds\PriorityQueue::allocate — Allocates enough memory for a required capacity.

Descrierea

public void Ds\PriorityQueue::allocate ( int $capacity )

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

Parametri

capacity

The number of values for which capacity should be allocated.

Nota:

Capacity will stay the same if this value is less than or equal to the current capacity.

Nota:

Capacity will always be rounded up to the nearest power of 2.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\PriorityQueue::allocate() example

<?php
$queue = new \Ds\PriorityQueue();
var_dump($queue->capacity());

$queue->allocate(100);
var_dump($queue->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(8)
int(128)
PriorityQueue
Ds\PriorityQueue::capacity
PriorityQueue


Returns the current capacity.

Ds\PriorityQueue::allocate
Ds\PriorityQueue::clear
PriorityQueue
PHP Manual

Ds\PriorityQueue::capacity

(PECL ds >= 1.0.0)

Ds\PriorityQueue::capacity — Returns the current capacity.

Descrierea

public int Ds\PriorityQueue::capacity ( void )

Returns the current capacity.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current capacity.

Exemple

Example #1 Ds\PriorityQueue::capacity() example

<?php
$queue = new \Ds\PriorityQueue();
var_dump($queue->capacity());
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(8)
Ds\PriorityQueue::allocate
Ds\PriorityQueue::clear
PriorityQueue


Removes all values.

Ds\PriorityQueue::capacity
Ds\PriorityQueue::__construct
PriorityQueue
PHP Manual

Ds\PriorityQueue::clear

(PECL ds >= 1.0.0)

Ds\PriorityQueue::clear — Removes all values.

Descrierea

public void Ds\PriorityQueue::clear ( void )

Removes all values from the queue.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\PriorityQueue::clear() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a",  5);
$queue->push("b", 15);
$queue->push("c", 10);

$queue->clear();
print_r($queue);
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\PriorityQueue Object
(
)
Ds\PriorityQueue::capacity
Ds\PriorityQueue::__construct
PriorityQueue


Creates a new instance.

Ds\PriorityQueue::clear
Ds\PriorityQueue::copy
PriorityQueue
PHP Manual

Ds\PriorityQueue::__construct

(PECL ds >= 1.0.0)

Ds\PriorityQueue::__construct — Creates a new instance.

Descrierea

public Ds\PriorityQueue::__construct ( void )

Creates a new instance.

Exemple

Example #1 Ds\PriorityQueue::__construct() example

<?php
$queue = new \Ds\PriorityQueue();
var_dump($queue);
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(Ds\PriorityQueue)#1 (0) {
}
Ds\PriorityQueue::clear
Ds\PriorityQueue::copy
PriorityQueue


Returns a shallow copy of the queue.

Ds\PriorityQueue::__construct
Ds\PriorityQueue::count
PriorityQueue
PHP Manual

Ds\PriorityQueue::copy

(PECL ds >= 1.0.0)

Ds\PriorityQueue::copy — Returns a shallow copy of the queue.

Descrierea

public Ds\PriorityQueue Ds\PriorityQueue::copy ( void )

Returns a shallow copy of the queue.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a shallow copy of the queue.

Exemple

Example #1 Ds\PriorityQueue::copy() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a",  5);
$queue->push("b", 15);
$queue->push("c", 10);

print_r($queue->copy());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Ds\PriorityQueue Object
(
    [0] => b
    [1] => c
    [2] => a
)
Ds\PriorityQueue::__construct
Ds\PriorityQueue::count
PriorityQueue


Returns the number of values in the queue.

Ds\PriorityQueue::copy
Ds\PriorityQueue::isEmpty
PriorityQueue
PHP Manual

Ds\PriorityQueue::count

(PECL ds >= 1.0.0)

Ds\PriorityQueue::count — Returns the number of values in the queue.

See Countable::count()

Ds\PriorityQueue::copy
Ds\PriorityQueue::isEmpty
PriorityQueue


Returns whether the queue is empty

Ds\PriorityQueue::count
Ds\PriorityQueue::jsonSerialize
PriorityQueue
PHP Manual

Ds\PriorityQueue::isEmpty

(PECL ds >= 1.0.0)

Ds\PriorityQueue::isEmpty — Returns whether the queue is empty

Descrierea

public bool Ds\PriorityQueue::isEmpty ( void )

Returns whether the queue is empty.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the queue is empty, FALSE otherwise.

Exemple

Example #1 Ds\PriorityQueue::isEmpty() example

<?php
$a = new \Ds\PriorityQueue();
$b = new \Ds\PriorityQueue();

$a->push("a",  5);
$a->push("b", 15);
$a->push("c", 10);

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
bool(true)
Ds\PriorityQueue::count
Ds\PriorityQueue::jsonSerialize
PriorityQueue


Returns a representation that can be converted to JSON.

Ds\PriorityQueue::isEmpty
Ds\PriorityQueue::peek
PriorityQueue
PHP Manual

Ds\PriorityQueue::jsonSerialize

(PECL ds >= 1.0.0)

Ds\PriorityQueue::jsonSerialize — Returns a representation that can be converted to JSON.

See JsonSerializable::jsonSerialize()

Nota:

You should never need to call this directly.

Ds\PriorityQueue::isEmpty
Ds\PriorityQueue::peek
PriorityQueue


Returns the value at the front of the queue.

Ds\PriorityQueue::jsonSerialize
Ds\PriorityQueue::pop
PriorityQueue
PHP Manual

Ds\PriorityQueue::peek

(PECL ds >= 1.0.0)

Ds\PriorityQueue::peek — Returns the value at the front of the queue.

Descrierea

public mixed Ds\PriorityQueue::peek ( void )

Returns the value at the front of the queue, but does not remove it.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The value at the front of the queue.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\PriorityQueue::peek() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a",  5);
$queue->push("b", 15);
$queue->push("c", 10);

var_dump($queue->peek());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "b"
Ds\PriorityQueue::jsonSerialize
Ds\PriorityQueue::pop
PriorityQueue


Removes and returns the value with the highest priority.

Ds\PriorityQueue::peek
Ds\PriorityQueue::push
PriorityQueue
PHP Manual

Ds\PriorityQueue::pop

(PECL ds >= 1.0.0)

Ds\PriorityQueue::pop — Removes and returns the value with the highest priority.

Descrierea

public mixed Ds\PriorityQueue::pop ( void )

Removes and returns the value at the front of the queue, ie. the value with the highest priority.

Nota:

Values with equal priority fall back to FIFO (first in first out).

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The removed value which was at the front of the queue.

Erori/Excep?ii

UnderflowException if empty.

Exemple

Example #1 Ds\PriorityQueue::pop() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a",  5);
$queue->push("b", 15);
$queue->push("c", 10);

print_r($queue->pop());
print_r($queue->pop());
print_r($queue->pop());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "a"
string(1) "b"
string(1) "c"
Ds\PriorityQueue::peek
Ds\PriorityQueue::push
PriorityQueue


Pushes values into the queue.

Ds\PriorityQueue::pop
Ds\PriorityQueue::toArray
PriorityQueue
PHP Manual

Ds\PriorityQueue::push

(PECL ds >= 1.0.0)

Ds\PriorityQueue::push — Pushes values into the queue.

Descrierea

public void Ds\PriorityQueue::push ( mixed $value , int $priority )

Pushes a value with a given priority into the queue.

Parametri

value

The value to push into the queue.

priority

The priority associated with the value.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Ds\PriorityQueue::push() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a",  5);
$queue->push("b", 15);
$queue->push("c", 10);

print_r($queue->pop());
print_r($queue->pop());
print_r($queue->pop());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(1) "b"
string(1) "c"
string(1) "a"
Ds\PriorityQueue::pop
Ds\PriorityQueue::toArray
PriorityQueue


Converts the queue to an array.

Ds\PriorityQueue::push
Filter
PriorityQueue
PHP Manual

Ds\PriorityQueue::toArray

(PECL ds >= 1.0.0)

Ds\PriorityQueue::toArray — Converts the queue to an array.

Descrierea

public array Ds\PriorityQueue::toArray ( void )

Converts the queue to an array.

Nota:

This method is not destructive.

Nota:

Casting to an array is not supported yet.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array containing all the values in the same order as the queue.

Exemple

Example #1 Ds\PriorityQueue::toArray() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a",  5);
$queue->push("b", 15);
$queue->push("c", 10);

var_dump($queue->toArray());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(3) {
  [0]=>
  string(1) "b"
  [1]=>
  string(1) "c"
  [2]=>
  string(1) "a"
}
Ds\PriorityQueue::push
Filter
PriorityQueue


Data Filtering

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Types of filters
    • Validate filters
    • Sanitize filters
    • Other filters
    • Filter flags
  • Constante predefinite
  • Exemple
    • Validation
    • Sanitization
  • Func?ii de filtrare
    • 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
Ds\PriorityQueue::toArray
Introducere
Extensii referitoare la variabile ?i tipuri


Introducere

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
Instalarea / configurarea
Filter


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Filter


Instalarea

Extensia filter este activata implicit începând cu PHP 5.2.0. Anterior era utilizata o extensie PECL experimentala. Acum însa versiunea PECL nu mai este recomandata sau reînnoita.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Filter Configuration Options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Nota:

Be careful about the default flags for the default filters. You should explicitly set them to the value you want. For example, to configure the default filter to behave exactly like htmlspecialchars() you need to set them default flags to 0 as shown below.

Example #1 Configuring the default filter to act like htmlspecialchars

filter.default = full_special_chars
filter.default_flags = 0

filter.default_flags integer

Default flags to apply when the default filter is set. This is set to FILTER_FLAG_NO_ENCODE_QUOTES by default for backwards compatibility reasons. See the flag list for the list of all the flag names.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
Types of filters
Instalarea / configurarea


Types of filters

Cuprins

  • Validate filters
  • Sanitize filters
  • Other filters
  • Filter flags
Tipurile resurselor
Validate filters
Filter


Validate filters

Listing of filters for validation
ID | Name | Options | Flags | Description
FILTER_VALIDATE_BOOLEAN | "boolean" | default | 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" | default | FILTER_FLAG_EMAIL_UNICODE | Validates whether the value is a valid e-mail address. In general, this validates e-mail addresses against the syntax in RFC 822, with the exceptions that comments and whitespace folding and dotless domain names are not supported.
FILTER_VALIDATE_FLOAT | "float" | default, decimal | FILTER_FLAG_ALLOW_THOUSAND | Validates value as float, and converts to float on success.
FILTER_VALIDATE_INT | "int" | default, min_range, max_range | FILTER_FLAG_ALLOW_OCTAL, FILTER_FLAG_ALLOW_HEX | Validates value as integer, optionally from the specified range, and converts to int on success.
FILTER_VALIDATE_IP | "validate_ip" | default | 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_MAC | "validate_mac_address" | default |  | Validates value as MAC address.
FILTER_VALIDATE_REGEXP | "validate_regexp" | default, regexp |  | Validates value against regexp, a Perl-compatible regular expression.
FILTER_VALIDATE_URL | "validate_url" | default | FILTER_FLAG_SCHEME_REQUIRED, FILTER_FLAG_HOST_REQUIRED, FILTER_FLAG_PATH_REQUIRED, FILTER_FLAG_QUERY_REQUIRED | Validates value as URL (according to » http://www.faqs.org/rfcs/rfc2396), optionally with required components. Beware a valid URL may not specify the HTTP protocol http:// so further validation may be required to determine the URL uses an expected protocol, e.g. ssh:// or mailto:. Note that the function will only find ASCII URLs to be valid; internationalized domain names (containing non-ASCII characters) will fail.

Nota:

As of PHP 5.4.11, the numbers +0 and -0 validate as both integers as well as floats (using FILTER_VALIDATE_FLOAT and FILTER_VALIDATE_INT). Before PHP 5.4.11 they only validated as floats (using FILTER_VALIDATE_FLOAT).

When default is set to option, default's value is used if value is not validated.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | Added FILTER_VALIDATE_MAC
5.2.1 | FILTER_VALIDATE_URL now defaults to FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED.

Types of filters
Sanitize filters
Types of filters


Sanitize filters

List of filters for sanitization
ID | Name | 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_STRIP_BACKTICK, 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_STRIP_BACKTICK, 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. When using this filter as a default filter, see the warning below about setting the default flags to 0.
FILTER_SANITIZE_STRING | "string" | FILTER_FLAG_NO_ENCODE_QUOTES, FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_STRIP_BACKTICK, 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_STRIP_BACKTICK, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | Do nothing, optionally strip or encode special characters. This filter is also aliased to FILTER_DEFAULT.

Avertizare

When using one of these filters as a default filter either through your ini file or through your web server's configuration, the default flags is set to FILTER_FLAG_NO_ENCODE_QUOTES. You need to explicitly set filter.default_flags to 0 to have quotes encoded by default. Like this:

Example #1 Configuring the default filter to act like htmlspecialchars

filter.default = full_special_chars
filter.default_flags = 0

Istoricul schimbarilor

Versiune | Descriere
5.2.11/5.3.1 | Slashes (/) are removed by FILTER_SANITIZE_EMAIL. Prior they were retained.

Validate filters
Other filters
Types of filters


Other filters

List of miscellaneous filters
ID | Name | Options | Flags | Description
FILTER_CALLBACK | "callback" | callable 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 have a numerical value <32.
FILTER_FLAG_STRIP_HIGH | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Strips characters that have a numerical value >127.
FILTER_FLAG_STRIP_BACKTICK | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Strips backtick characters.
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_EMAIL_UNICODE | FILTER_VALIDATE_EMAIL | Allows the local part of the email address to contain Unicode characters.
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, 127.0.0.0/8 and 240.0.0.0/4. Fails validation for the following reserved IPv6 ranges: ::1/128, ::/128, ::ffff:0:0/96 and fe80::/10.
FILTER_FLAG_SCHEME_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a scheme part.
FILTER_FLAG_HOST_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a host part.
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.
FILTER_REQUIRE_SCALAR |  | Requires the value to be scalar.
FILTER_REQUIRE_ARRAY |  | Requires the value to be an array.
FILTER_FORCE_ARRAY |  | If the value is a scalar, it is treated as array with the scalar value as only element.

Istoricul schimbarilor

Versiune | Descriere
5.3.2 | FILTER_FLAG_STRIP_BACKTICK has been added.
5.2.10 | FILTER_FLAG_NO_RES_RANGE supports also IPv6 addresses.

Other filters
Constante predefinite
Types of filters


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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_VALIDATE_MAC (integer)
ID of "validate_mac_address" filter. (Available as of PHP 5.5.0)
FILTER_DEFAULT (integer)
ID of default ("unsafe_raw") filter. This is equivalent to FILTER_UNSAFE_RAW.
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_FLAG_EMAIL_UNICODE (integer)
Accepts Unicode characters in the local part in "validate_email" filter. (Available as of PHP 7.1.0)
Filter flags
Exemple
Filter


Exemple

Cuprins

  • Validation
  • Sanitization
Constante predefinite
Validation
Filter


Validation

Example #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.\n";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_b) email address is considered valid.\n";
} else {
    echo "This ($email_b) email address is considered invalid.\n";
}
?>

Exemplul de mai sus va afi?a:

This (joe@example.com) email address is considered valid.
This (bogus) email address is considered invalid.

Example #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.";
}
?>

Exemplul de mai sus va afi?a:

This (ip_a) IP address is considered valid.

Example #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.";
}
?>

Exemplul de mai sus va afi?a:

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.

Exemple
Sanitization
Exemple


Sanitization

Example #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";
}
?>

Exemplul de mai sus va afi?a:

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

Example #2 Configuring a default filter

filter.default = full_special_chars
filter.default_flags = 0

Validation
Func?ii de filtrare
Exemple


Func?ii de filtrare

Cuprins

  • 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

Func?ii de filtrare
filter_id
Func?ii de filtrare
PHP Manual

filter_has_var

(PHP 5 >= 5.2.0, PHP 7)

filter_has_var — Checks if variable of specified type exists

Descrierea

bool filter_has_var ( int $type , string $variable_name )

Parametri

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

variable_name

Name of a variable to check.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Func?ii de filtrare
filter_id
Func?ii de filtrare


Returns the filter ID belonging to a named filter

filter_has_var
filter_input_array
Func?ii de filtrare
PHP Manual

filter_id

(PHP 5 >= 5.2.0, PHP 7)

filter_id — Returns the filter ID belonging to a named filter

Descrierea

int filter_id ( string $filtername )

Parametri

filtername

Name of a filter to get.

Valorile întoarse

ID of a filter on success or FALSE if filter doesn't exist.

A se vedea ?i

  • filter_list() - Returns a list of all supported filters

filter_has_var
filter_input_array
Func?ii de filtrare


Gets external variables and optionally filters them

filter_id
filter_input
Func?ii de filtrare
PHP Manual

filter_input_array

(PHP 5 >= 5.2.0, PHP 7)

filter_input_array — Gets external variables and optionally filters them

Descrierea

mixed filter_input_array ( int $type [, mixed $definition [, bool $add_empty = true ]] )

This function is useful for retrieving many values without repetitively calling filter_input().

Parametri

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.

add_empty

Add missing keys as NULL to the return value.

Valorile întoarse

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.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

array(6) {
  ["product_id"]=>
  string(17) "libgd%3Cscript%3E"
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  string(6) "2.0.33"
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added add_empty parameter.

Note

Nota:

There is no REQUEST_TIME key in INPUT_SERVER array because it is inserted into the $_SERVER later.

A se vedea ?i

  • 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
Func?ii de filtrare


Gets a specific external variable by name and optionally filters it

filter_input_array
filter_list
Func?ii de filtrare
PHP Manual

filter_input

(PHP 5 >= 5.2.0, PHP 7)

filter_input — Gets a specific external variable by name and optionally filters it

Descrierea

mixed filter_input ( int $type , string $variable_name [, int $filter = FILTER_DEFAULT [, mixed $options ]] )

Parametri

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

variable_name

Name of a variable to get.

filter

Identificatorul ID al filtrului ce va fi aplicat. Pagina manualului pentru Types of filters afi?eaza filtrele disponibile.

Daca parametrul este omis, se va utiliza FILTER_DEFAULT, ceea ce este echivalent cu FILTER_UNSAFE_RAW. Aceasta va duce la neaplicarea filtrarii în mod implicit.

options

Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array.

Valorile întoarse

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.

Exemple

Example #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>";
?>

Exemplul de mai sus va afi?a ceva similar cu:

You have searched for Me &#38; son.
<a href='?search=Me%20%26%20son'>Search again.</a>

A se vedea ?i

  • 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
Func?ii de filtrare


Returns a list of all supported filters

filter_input
filter_var_array
Func?ii de filtrare
PHP Manual

filter_list

(PHP 5 >= 5.2.0, PHP 7)

filter_list — Returns a list of all supported filters

Descrierea

array filter_list ( void )

Valorile întoarse

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.

Exemple

Example #1 A filter_list() example

<?php
print_r(filter_list());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
Func?ii de filtrare


Gets multiple variables and optionally filters them

filter_list
filter_var
Func?ii de filtrare
PHP Manual

filter_var_array

(PHP 5 >= 5.2.0, PHP 7)

filter_var_array — Gets multiple variables and optionally filters them

Descrierea

mixed filter_var_array ( array $data [, mixed $definition [, bool $add_empty = true ]] )

This function is useful for retrieving many values without repetitively calling filter_var().

Parametri

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.

add_empty

Add missing keys as NULL to the return value.

Valorile întoarse

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.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a:

array(6) {
  ["product_id"]=>
  string(17) "libgd%3Cscript%3E"
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  string(6) "2.0.33"
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added add_empty parameter.

A se vedea ?i

  • 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
Func?ii de filtrare


Filters a variable with a specified filter

filter_var_array
Manipularea func?iilor
Func?ii de filtrare
PHP Manual

filter_var

(PHP 5 >= 5.2.0, PHP 7)

filter_var — Filters a variable with a specified filter

Descrierea

mixed filter_var ( mixed $variable [, int $filter = FILTER_DEFAULT [, mixed $options ]] )

Parametri

variable

Value to filter. Note that scalar values are converted to string internally before they are filtered.

filter

Identificatorul ID al filtrului ce va fi aplicat. Pagina manualului pentru Types of filters afi?eaza filtrele disponibile.

Daca parametrul este omis, se va utiliza FILTER_DEFAULT, ceea ce este echivalent cu FILTER_UNSAFE_RAW. Aceasta va duce la neaplicarea filtrarii în mod implicit.

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, callable 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'));
?>

Valorile întoarse

Returns the filtered data, or FALSE if the filter fails.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

string(15) "bob@example.com"
bool(false)

A se vedea ?i

  • 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
  • informa?ie despre tipul callback

filter_var_array
Manipularea func?iilor
Func?ii de filtrare


Manipularea func?iilor

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii de manipulare a func?iilor
    • 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
Introducere
Extensii referitoare la variabile ?i tipuri


Introducere

Aceste func?ii efectueaza diverse opera?iuni de manipulare a func?iilor.

Manipularea func?iilor
Instalarea / configurarea
Manipularea func?iilor


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Manipularea func?iilor


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii de manipulare a func?iilor
Manipularea func?iilor


Func?ii de manipulare a func?iilor

Cuprins

  • 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
Constante predefinite
call_user_func_array
Manipularea func?iilor


Call a callback with an array of parameters

Func?ii de manipulare a func?iilor
call_user_func
Func?ii de manipulare a func?iilor
PHP Manual

call_user_func_array

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

call_user_func_array — Call a callback with an array of parameters

Descrierea

mixed call_user_func_array ( callable $callback , array $param_arr )

Calls the callback given by the first parameter with the parameters in param_arr.

Parametri

callback

The callable to be called.

param_arr

The parameters to be passed to the callback, as an indexed array.

Valorile întoarse

Returns the return value of the callback, or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #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"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

foobar got one and two
foo::bar got three and four

Example #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'));

?>

Exemplul de mai sus va afi?a ceva similar cu:

Hello Hannes!
Hello Philip!

Example #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 */

?>

Exemplul de mai sus va afi?a:

int(8)

Example #4 Passing values by reference

<?php

function mega(&$a){
    $a = 55;
    echo "function mega \$a=$a\n";
}
$bar = 77;
call_user_func_array('mega',array(&$bar));
echo "global \$bar=$bar\n";

?>

Exemplul de mai sus va afi?a:

function mega $a=55
global $bar=55

Note

Nota:

Before PHP 5.4, 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 has been removed in PHP 5.4. 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 (there is, however, an exception for passed values with reference count = 1, such as in literals, as these can be turned into references without ill effects — but also without writes to that value having any effect —; do not rely in this behavior, though, as the reference count is an implementation detail and the soundness of this behavior is questionable).

Nota:

Func?iile de apel invers înregistrate cu astfel de func?ii ca call_user_func() ?i call_user_func_array() nu vor fi apelate daca exista o excep?ie neinterceptata emisa într-un apel precedent.

A se vedea ?i

  • call_user_func() - Call the callback given by the first parameter
  • informa?ie despre tipul callback
  • ReflectionFunction::invokeArgs() - Invokes function args
  • ReflectionMethod::invokeArgs() - Invoke args

Func?ii de manipulare a func?iilor
call_user_func
Func?ii de manipulare a func?iilor


Call the callback given by the first parameter

call_user_func_array
create_function
Func?ii de manipulare a func?iilor
PHP Manual

call_user_func

(PHP 4, PHP 5, PHP 7)

call_user_func — Call the callback given by the first parameter

Descrierea

mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] )

Calls the callback given by the first parameter and passes the remaining parameters as arguments.

Parametri

callback

The callable to be called.

parameter

Zero or more parameters to be passed to the callback.

Nota:

Note that the parameters for call_user_func() are not passed by reference.

Example #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";

// You can use this instead
call_user_func_array('increment', array(&$a));
echo $a."\n";
?>

Exemplul de mai sus va afi?a:

0
1

Valorile întoarse

Returns the return value of the callback.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #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");
?>

Exemplul de mai sus va afi?a:

You wanted a mushroom haircut, no problem
You wanted a shave haircut, no problem

Example #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

?>

Exemplul de mai sus va afi?a:

Hello world!
Hello world!

Example #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'));

?>

Exemplul de mai sus va afi?a:

Hello!
Hello!
Hello!

Example #5 Using lambda function with call_user_func()

<?php
call_user_func(function($arg) { print "[$arg]\n"; }, 'test'); /* As of PHP 5.3.0 */
?>

Exemplul de mai sus va afi?a:

[test]

Note

Nota:

Func?iile de apel invers înregistrate cu astfel de func?ii ca call_user_func() ?i call_user_func_array() nu vor fi apelate daca exista o excep?ie neinterceptata emisa într-un apel precedent.

A se vedea ?i

  • call_user_func_array() - Call a callback with an array of parameters
  • is_callable() - Verifica daca con?inutul unei variabile poate fi apelat în calitate de func?ie
  • informa?ie despre tipul callback
  • ReflectionFunction::invoke() - Invokes function
  • ReflectionMethod::invoke() - Invoke

call_user_func_array
create_function
Func?ii de manipulare a func?iilor


Create an anonymous (lambda-style) function

call_user_func
forward_static_call_array
Func?ii de manipulare a func?iilor
PHP Manual

create_function

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

create_function — Create an anonymous (lambda-style) function

Descrierea

string create_function ( string $args , string $code )

Creates an anonymous function from the parameters passed, and returns a unique name for it.

Precautie

This function internally performs an eval() and as such has the same security issues as eval(). Additionally it has bad performance and memory usage characteristics.

If you are using PHP 5.3.0 or newer a native anonymous function should be used instead.

Parametri

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.

Valorile întoarse

Returns a unique function name as a string, or FALSE on error.

Exemple

Example #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:

Example #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);
?>

Exemplul de mai sus va afi?a:

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()

Example #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);
?>

Exemplul de mai sus va afi?a:

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);

?>

Exemplul de mai sus va afi?a:

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);

?>

Exemplul de mai sus va afi?a:

Array
(
  [0] => it is a string thing
  [1] => a big string
  [2] => larger
  [3] => small
)

A se vedea ?i

  • Anonymous functions

call_user_func
forward_static_call_array
Func?ii de manipulare a func?iilor


Call a static method and pass the arguments as array

create_function
forward_static_call
Func?ii de manipulare a func?iilor
PHP Manual

forward_static_call_array

(PHP 5 >= 5.3.0, PHP 7)

forward_static_call_array — Call a static method and pass the arguments as array

Descrierea

mixed forward_static_call_array ( callable $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().

Parametri

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.

Nota:

Note that the parameters for forward_static_call_array() are not passed by reference.

Valorile întoarse

Returns the function result, or FALSE on error.

Exemple

Example #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";
    }

?>

Exemplul de mai sus va afi?a:

B
B more,args
C other,args

A se vedea ?i

  • 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() - Verifica daca con?inutul unei variabile poate fi apelat în calitate de func?ie
  • informa?ie despre tipul callback

create_function
forward_static_call
Func?ii de manipulare a func?iilor


Call a static method

forward_static_call_array
func_get_arg
Func?ii de manipulare a func?iilor
PHP Manual

forward_static_call

(PHP 5 >= 5.3.0, PHP 7)

forward_static_call — Call a static method

Descrierea

mixed forward_static_call ( callable $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.

Parametri

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.

Valorile întoarse

Returns the function result, or FALSE on error.

Exemple

Example #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";
    }

?>

Exemplul de mai sus va afi?a:

B
B more,args
C other,args

A se vedea ?i

  • 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() - Verifica daca con?inutul unei variabile poate fi apelat în calitate de func?ie
  • informa?ie despre tipul callback

forward_static_call_array
func_get_arg
Func?ii de manipulare a func?iilor


Return an item from the argument list

forward_static_call
func_get_args
Func?ii de manipulare a func?iilor
PHP Manual

func_get_arg

(PHP 4, PHP 5, PHP 7)

func_get_arg — Return an item from the argument list

Descrierea

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.

Parametri

arg_num

The argument offset. Function arguments are counted starting from zero.

Valorile întoarse

Returns the specified argument, or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
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.

Erori/Excep?ii

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.

Exemple

Example #1 func_get_arg() example

<?php
function foo()
{
     $numargs = func_num_args();
     echo "Number of arguments: $numargs\n";
     if ($numargs >= 2) {
         echo "Second argument is: " . func_get_arg(1) . "\n";
     }
}

foo(1, 2, 3);
?>

Exemplul de mai sus va afi?a:

Number of arguments: 3
Second argument is: 2

Example #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.inc
<?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

Example #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);
?>

Exemplul de mai sus va afi?a în PHP 7:

As passed : 'bar'
After change : 'baz'
As passed : 'bar'
After change : 'baz'

Exemplul de mai sus va afi?a în PHP 5:

As passed : 'bar'
After change : 'bar'
As passed : 'bar'
After change : 'baz'

Note

Nota:

Deoarece aceasta func?ie î?i determina detaliile parametrilor în dependen?a de circumstan?a, ea nu poate fi utilizata în calitate de parametru-func?ie în versiunile anterioare 5.3.0. Daca trebuie transmisa aceasta valoare, atunci rezultatele trebuie atribuite unei variabile, ?i aceasta variabila trebuie transmisa.

Nota:

Daca argumentele sunt transmise prin referin?a atunci orice schimbare a lor va fi reflectata în valorile întoarse de aceasta func?ie. Începând cu PHP 7 valorile curente vor fi întoarse de asemenea ?i atunci când argumentele sunt transmise prin valoare.

Nota: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.

A se vedea ?i

  • ... syntax in PHP 5.6+
  • func_get_args()
  • func_num_args()

forward_static_call
func_get_args
Func?ii de manipulare a func?iilor


Returns an array comprising a function's argument list

func_get_arg
func_num_args
Func?ii de manipulare a func?iilor
PHP Manual

func_get_args

(PHP 4, PHP 5, PHP 7)

func_get_args — Returns an array comprising a function's argument list

Descrierea

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.

Valorile întoarse

Returns an array in which each element is a copy of the corresponding member of the current user-defined function's argument list.

Istoricul schimbarilor

Versiune | Descriere
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.

Erori/Excep?ii

Generates a warning if called from outside of a user-defined function.

Exemple

Example #1 func_get_args() example

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs \n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "\n";
    }
}

foo(1, 2, 3);
?>

Exemplul de mai sus va afi?a:

Number of arguments: 3
Second argument is: 2
Argument 0 is: 1
Argument 1 is: 2
Argument 2 is: 3

Example #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

Example #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);
?>

Exemplul de mai sus va afi?a în PHP 7:

As passed : array (
0 => 'bar',
)
After change : array (
0 => 'baz',
)
As passed : array (
0 => 'bar',
)
After change : array (
0 => 'baz',
)

Exemplul de mai sus va afi?a în PHP 5:

As passed : array (
0 => 'bar',
)
After change : array (
0 => 'bar',
)
As passed : array (
0 => 'bar',
)
After change : array (
0 => 'baz',
)

Note

Nota:

Deoarece aceasta func?ie î?i determina detaliile parametrilor în dependen?a de circumstan?a, ea nu poate fi utilizata în calitate de parametru-func?ie în versiunile anterioare 5.3.0. Daca trebuie transmisa aceasta valoare, atunci rezultatele trebuie atribuite unei variabile, ?i aceasta variabila trebuie transmisa.

Nota:

Daca argumentele sunt transmise prin referin?a atunci orice schimbare a lor va fi reflectata în valorile întoarse de aceasta func?ie. Începând cu PHP 7 valorile curente vor fi întoarse de asemenea ?i atunci când argumentele sunt transmise prin valoare.

Nota: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.

A se vedea ?i

  • ... syntax in PHP 5.6+
  • func_get_arg()
  • func_num_args()
  • ReflectionFunctionAbstract::getParameters()

func_get_arg
func_num_args
Func?ii de manipulare a func?iilor


Returns the number of arguments passed to the function

func_get_args
function_exists
Func?ii de manipulare a func?iilor
PHP Manual

func_num_args

(PHP 4, PHP 5, PHP 7)

func_num_args — Returns the number of arguments passed to the function

Descrierea

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.

Valorile întoarse

Returns the number of arguments passed into the current user-defined function.

Istoricul schimbarilor

Versiune | Descriere
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.

Erori/Excep?ii

Generates a warning if called from outside of a user-defined function.

Exemple

Example #1 func_num_args() example

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs\n";
}

foo(1, 2, 3);
?>

Exemplul de mai sus va afi?a:

Number of arguments: 3

Example #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

Note

Nota:

Deoarece aceasta func?ie î?i determina detaliile parametrilor în dependen?a de circumstan?a, ea nu poate fi utilizata în calitate de parametru-func?ie în versiunile anterioare 5.3.0. Daca trebuie transmisa aceasta valoare, atunci rezultatele trebuie atribuite unei variabile, ?i aceasta variabila trebuie transmisa.

A se vedea ?i

  • ... syntax in PHP 5.6+
  • func_get_arg()
  • func_get_args()
  • ReflectionFunctionAbstract::getNumberOfParameters()

func_get_args
function_exists
Func?ii de manipulare a func?iilor


Return TRUE if the given function has been defined

func_num_args
get_defined_functions
Func?ii de manipulare a func?iilor
PHP Manual

function_exists

(PHP 4, PHP 5, PHP 7)

function_exists — Return TRUE if the given function has been defined

Descrierea

bool function_exists ( string $function_name )

Checks the list of defined functions, both built-in (internal) and user-defined, for function_name.

Parametri

function_name

The function name, as a string.

Valorile întoarse

Returns TRUE if function_name exists and is a function, FALSE otherwise.

Nota:

This function will return FALSE for constructs, such as include_once and echo.

Exemple

Example #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";
}
?>

Note

Nota:

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).

A se vedea ?i

  • method_exists() - Checks if the class method exists
  • is_callable() - Verifica daca con?inutul unei variabile poate fi apelat în calitate de func?ie
  • get_defined_functions() - Returns an array of all defined functions
  • class_exists() - Verifica daca clasa a fost definita
  • extension_loaded() - Find out whether an extension is loaded

func_num_args
get_defined_functions
Func?ii de manipulare a func?iilor


Returns an array of all defined functions

function_exists
register_shutdown_function
Func?ii de manipulare a func?iilor
PHP Manual

get_defined_functions

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

get_defined_functions — Returns an array of all defined functions

Descrierea

array get_defined_functions ([ bool $exclude_disabled = FALSE ] )

Gets an array of all defined functions.

Parametri

exclude_disabled

Whether disabled functions should be excluded from the return value.

Valorile întoarse

Returns a 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).

Istoricul schimbarilor

Versiune | Descriere
PHP 7.0.15, PHP 7.1.1 | The exclude_disabled parameter has been added.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

)

A se vedea ?i

  • function_exists() - Return TRUE if the given function has been defined
  • get_defined_vars() - Întoarce un msiv cu toate variabilele definite
  • get_defined_constants() - Returns an associative array with the names of all the constants and their values
  • get_declared_classes() - Returns an array with the name of the defined classes

function_exists
register_shutdown_function
Func?ii de manipulare a func?iilor


Register a function for execution on shutdown

get_defined_functions
register_tick_function
Func?ii de manipulare a func?iilor
PHP Manual

register_shutdown_function

(PHP 4, PHP 5, PHP 7)

register_shutdown_function — Register a function for execution on shutdown

Descrierea

void register_shutdown_function ( callable $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.

Parametri

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.

...

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

If the passed callback is not callable a E_WARNING level error will be generated.

Exemple

Example #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');
?>

Note

Nota:

Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache.

Nota:

Shutdown functions will not be executed if the process is killed with a SIGTERM or SIGKILL signal. While you cannot intercept a SIGKILL, you can use pcntl_signal() to install a handler for a SIGTERM which uses exit() to end cleanly.

A se vedea ?i

  • auto_append_file
  • exit() - Output a message and terminate the current script
  • The section on connection handling

get_defined_functions
register_tick_function
Func?ii de manipulare a func?iilor


Register a function for execution on each tick

register_shutdown_function
unregister_tick_function
Func?ii de manipulare a func?iilor
PHP Manual

register_tick_function

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

register_tick_function — Register a function for execution on each tick

Descrierea

bool register_tick_function ( callable $function [, mixed $arg [, mixed $... ]] )

Registers the given function to be executed when a tick is called.

Parametri

function

The function name as a string, or an array consisting of an object and a method.

arg

...

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | Ticks are now supported on threaded web server modules.

Note

Avertizare

register_tick_function() should not be used with threaded web server modules with PHP 5.2 or lower.

A se vedea ?i

  • declare
  • unregister_tick_function() - De-register a function for execution on each tick

register_shutdown_function
unregister_tick_function
Func?ii de manipulare a func?iilor


De-register a function for execution on each tick

register_tick_function
Quickhash
Func?ii de manipulare a func?iilor
PHP Manual

unregister_tick_function

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

unregister_tick_function — De-register a function for execution on each tick

Descrierea

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.

Parametri

function_name

The function name, as a string.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • register_tick_function() - Register a function for execution on each tick

register_tick_function
Quickhash
Func?ii de manipulare a func?iilor


Quickhash

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
  • Constante predefinite
  • Exemple
  • 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
unregister_tick_function
Introducere
Extensii referitoare la variabile ?i tipuri


Introducere

The quickhash extension contains a set of specific strongly-typed classes to deal with specific set and hash implementations.

Quickhash
Instalarea / configurarea
Quickhash


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
Introducere
Necesita?i
Quickhash


Necesita?i

This extension requires no additional libraries.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/quickhash

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Configura?ia la rulare
Exemple
Quickhash


Exemple

Example #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 ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(false)
bool(true)
bool(false)

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
1415926

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

5 => -4234
4 => 712314
1 => 145926
2 => 1415926
3 => 72

Example #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" );

foreach( $hash as $key => $value )
{
    echo $key, ' => ', $value, "\n";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

1 => one million four hundred fifteen thousand nine hundred twenty six
2 => one more
Constante predefinite
QuickHashIntSet
Quickhash


The QuickHashIntSet class

(PECL quickhash >= Unknown)

Introducere

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.

Sinopsisul clasei

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 )
}

Constante predefinite

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.

Cuprins

  • 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
Exemple
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

Descrierea

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.

Parametri

key

The key of the entry to add.

Valorile întoarse

TRUE when the entry was added, and FALSE if the entry was not added.

Exemple

Example #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 ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a new QuickHashIntSet object.

Exemple

Example #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

Descrierea

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.

Parametri

key

The key of the entry to delete.

Valorile întoarse

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Exemple

Example #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 ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

public bool QuickHashIntSet::exists ( int $key )

This method checks whether an entry with the provided key exists in the set.

Parametri

key

The key of the entry to check for whether it exists in the set.

Valorile întoarse

Returns TRUE when the entry was found, or FALSE when the entry is not found.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

publicint QuickHashIntSet::getSize ( void )

Returns the number of elements in the set.

Parametri

key

The key of the entry to add.

Valorile întoarse

The number of elements in the set.

Exemple

Example #1 QuickHashIntSet::getSize() example

<?php
$set = new QuickHashIntSet( 8 );
var_dump( $set->add( 2 ) );
var_dump( $set->add( 3 ) );
var_dump( $set->getSize() );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a new QuickHashIntSet.

Exemple

Example #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'
    );
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a new QuickHashIntSet.

Exemple

Example #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'
    );
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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.

Parametri

filename

The filename of the file to store the hash in.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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

Descrierea

public string QuickHashIntSet::saveToString ( void )

This method returns a serialized version of the set in the same format that loadFromString() can read.

Valorile întoarse

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.

Exemple

Example #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

(PECL quickhash >= Unknown)

Introducere

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.

Sinopsisul clasei

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 )
}

Constante predefinite

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.

Cuprins

  • 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

Descrierea

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.

Parametri

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.

Valorile întoarse

TRUE when the entry was added, and FALSE if the entry was not added.

Exemple

Example #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 ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a new QuickHashIntHash object.

Exemple

Example #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

Descrierea

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.

Parametri

key

The key of the entry to delete.

Valorile întoarse

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Exemple

Example #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 ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

public bool QuickHashIntHash::exists ( int $key )

This method checks whether an entry with the provided key exists in the hash.

Parametri

key

The key of the entry to check for whether it exists in the hash.

Valorile întoarse

Returns TRUE when the entry was found, or FALSE when the entry is not found.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

public int QuickHashIntHash::get ( int $key )

This method retrieves a value from the hash by its key.

Parametri

key

The key of the entry to add.

Valorile întoarse

The value if the key exists, or NULL if the key wasn't part of the hash.

Exemple

Example #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 ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

public int QuickHashIntHash::getSize ( void )

Returns the number of elements in the hash.

Parametri

key

The key of the entry to add.

Valorile întoarse

The number of elements in the hash.

Exemple

Example #1 QuickHashIntHash::getSize() example

<?php
$hash = new QuickHashIntHash( 8 );
var_dump( $hash->add( 2 ) );
var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->getSize() );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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:

Example #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

Example #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

Parametri

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.

Valorile întoarse

Returns a new QuickHashIntHash.

Exemple

Example #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'
    );
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a new QuickHashIntHash.

Exemple

Example #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'
    );
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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.

Parametri

filename

The filename of the file to store the hash in.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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

Descrierea

public string QuickHashIntHash::saveToString ( void )

This method returns a serialized version of the hash in the same format that loadFromString() can read.

Valorile întoarse

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.

Exemple

Example #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

Descrierea

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.

Parametri

key

The key of the entry to add or update.

value

The new value to set the entry with.

Valorile întoarse

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

Exemple

Example #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 ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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.

Parametri

key

The key of the entry to add.

value

The new value to update the entry with.

Valorile întoarse

TRUE when the entry was found and updated, and FALSE if the entry was not part of the hash already.

Exemple

Example #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 ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(true)
int(223606)

QuickHashIntHash::set
QuickHashStringIntHash
QuickHashIntHash


The QuickHashStringIntHash class

(No version information available, might only be in Git)

Introducere

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.

Sinopsisul clasei

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 )
}

Constante predefinite

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.

Cuprins

  • 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 Git)

QuickHashStringIntHash::add — This method adds a new entry to the hash

Descrierea

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.

Parametri

key

The key of the entry to add.

value

The value of the entry to add.

Valorile întoarse

TRUE when the entry was added, and FALSE if the entry was not added.

Exemple

Example #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 ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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 Git)

QuickHashStringIntHash::__construct — Creates a new QuickHashStringIntHash object

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a new QuickHashStringIntHash object.

Exemple

Example #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 Git)

QuickHashStringIntHash::delete — This method deletes am entry from the hash

Descrierea

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.

Parametri

key

The key of the entry to delete.

Valorile întoarse

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Exemple

Example #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' ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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 Git)

QuickHashStringIntHash::exists — This method checks whether a key is part of the hash

Descrierea

public bool QuickHashStringIntHash::exists ( string $key )

This method checks whether an entry with the provided key exists in the hash.

Parametri

key

The key of the entry to check for whether it exists in the hash.

Valorile întoarse

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 Git)

QuickHashStringIntHash::get — This method retrieves a value from the hash by its key

Descrierea

public mixed QuickHashStringIntHash::get ( string $key )

This method retrieves a value from the hash by its key.

Parametri

key

The key of the entry to add.

Valorile întoarse

The value if the key exists, or NULL if the key wasn't part of the hash.

Exemple

Example #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" ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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 Git)

QuickHashStringIntHash::getSize — Returns the number of elements in the hash

Descrierea

public int QuickHashStringIntHash::getSize ( void )

Returns the number of elements in the hash.

Parametri

key

The key of the entry to add.

Valorile întoarse

The number of elements in the hash.

Exemple

Example #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() );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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 Git)

QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file

Descrierea

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:

Example #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

Example #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

Parametri

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.)

Valorile întoarse

Returns a new QuickHashStringIntHash.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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 Git)

QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string

Descrierea

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".

Parametri

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.

Valorile întoarse

Returns a new QuickHashStringIntHash.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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 Git)

QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk

Descrierea

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.

Parametri

filename

The filename of the file to store the hash in.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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 Git)

QuickHashStringIntHash::saveToString — This method returns a serialized version of the hash

Descrierea

public string QuickHashStringIntHash::saveToString ( void )

This method returns a serialized version of the hash in the same format that loadFromString() can read.

Valorile întoarse

This method returns a serialized format of an existing hash, in the same format that loadFromString() can read.

Exemple

Example #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 Git)

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

Descrierea

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.

Parametri

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.

Valorile întoarse

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

Exemple

Example #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" ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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 Git)

QuickHashStringIntHash::update — This method updates an entry in the hash with a new value

Descrierea

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.

Parametri

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.

Valorile întoarse

TRUE when the entry was found and updated, and FALSE if the entry was not part of the hash already.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

314159265
314159265
bool(true)
bool(false)
314159265
314159266

QuickHashStringIntHash::set
QuickHashIntStringHash
QuickHashStringIntHash


The QuickHashIntStringHash class

(PECL quickhash >= Unknown)

Introducere

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.

Sinopsisul clasei

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 )
}

Constante predefinite

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.

Cuprins

  • 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

Descrierea

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.

Parametri

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.

Valorile întoarse

TRUE when the entry was added, and FALSE if the entry was not added.

Exemple

Example #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" ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a new QuickHashIntStringHash object.

Exemple

Example #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

Descrierea

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.

Parametri

key

The key of the entry to delete.

Valorile întoarse

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Exemple

Example #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 ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

public bool QuickHashIntStringHash::exists ( int $key )

This method checks whether an entry with the provided key exists in the hash.

Parametri

key

The key of the entry to check for whether it exists in the hash.

Valorile întoarse

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

Descrierea

public mixed QuickHashIntStringHash::get ( int $key )

This method retrieves a value from the hash by its key.

Parametri

key

The key of the entry to add.

Valorile întoarse

The value if the key exists, or NULL if the key wasn't part of the hash.

Exemple

Example #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 ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

public int QuickHashIntStringHash::getSize ( void )

Returns the number of elements in the hash.

Valorile întoarse

The number of elements in the hash.

Exemple

Example #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() );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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 element data string. An example could be:

Example #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

Example #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

Parametri

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.

Valorile întoarse

Returns a new QuickHashIntStringHash.

Exemple

Example #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'
    );
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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".

Parametri

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.

Valorile întoarse

Returns a new QuickHashIntStringHash.

Exemple

Example #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'
    );
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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.

Parametri

filename

The filename of the file to store the hash in.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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

Descrierea

public string QuickHashIntStringHash::saveToString ( void )

This method returns a serialized version of the hash in the same format that loadFromString() can read.

Valorile întoarse

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.

Exemple

Example #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

Descrierea

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.

Parametri

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.

Valorile întoarse

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

Exemple

Example #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 ) );
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

Descrierea

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.

Parametri

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.

Valorile întoarse

TRUE when the entry was found and updated, and FALSE if the entry was not part of the hash already.

Exemple

Example #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";
?>

Exemplul de mai sus va afi?a ceva similar cu:

--
a lot
bool(true)
bool(false)
--
a lot plus one

QuickHashIntStringHash::set
Reflection
QuickHashIntStringHash


Reflection

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Extending
  • Reflection — The Reflection class
    • Reflection::export — Exports
    • Reflection::getModifierNames — Gets modifier names
  • ReflectionClass — The ReflectionClass class
    • ReflectionClass::__construct — Constructs a ReflectionClass
    • ReflectionClass::export — Exports a class
    • ReflectionClass::getConstant — Gets defined constant
    • ReflectionClass::getConstants — Gets constants
    • ReflectionClass::getConstructor — Gets the constructor of the class
    • ReflectionClass::getDefaultProperties — Gets default properties
    • ReflectionClass::getDocComment — Gets doc comments
    • ReflectionClass::getEndLine — Gets end line
    • ReflectionClass::getExtension — Gets a ReflectionExtension object for the extension which defined the class
    • ReflectionClass::getExtensionName — Gets the name of the extension which defined the class
    • 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 for a class method.
    • ReflectionClass::getMethods — Gets an array 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 a ReflectionProperty for a class's 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::isAnonymous — Checks if class is anonymous
    • 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 the class is instantiable
    • ReflectionClass::isInterface — Checks if the class is an interface
    • ReflectionClass::isInternal — Checks if class is defined internally by an extension, or the core
    • 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::getClosureScopeClass — Returns the scope associated to the closure
    • 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::getReturnType — Gets the specified return type of a function
    • ReflectionFunctionAbstract::getShortName — Gets function short name
    • ReflectionFunctionAbstract::getStartLine — Gets starting line number
    • ReflectionFunctionAbstract::getStaticVariables — Gets static variables
    • ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type
    • ReflectionFunctionAbstract::inNamespace — Checks if function in namespace
    • ReflectionFunctionAbstract::isClosure — Checks if closure
    • ReflectionFunctionAbstract::isDeprecated — Checks if deprecated
    • ReflectionFunctionAbstract::isGenerator — Returns whether this function is a generator
    • ReflectionFunctionAbstract::isInternal — Checks if is internal
    • ReflectionFunctionAbstract::isUserDefined — Checks if user defined
    • ReflectionFunctionAbstract::isVariadic — Checks if the function is variadic
    • 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 the type hinted class
    • ReflectionParameter::getDeclaringClass — Gets declaring class
    • ReflectionParameter::getDeclaringFunction — Gets declaring function
    • ReflectionParameter::getDefaultValue — Gets default parameter value
    • ReflectionParameter::getDefaultValueConstantName — Returns the default value's constant name if default value is constant or null
    • ReflectionParameter::getName — Gets parameter name
    • ReflectionParameter::getPosition — Gets parameter position
    • ReflectionParameter::getType — Gets a parameter's type
    • ReflectionParameter::hasType — Checks if parameter has a type
    • ReflectionParameter::isArray — Checks if parameter expects an array
    • ReflectionParameter::isCallable — Returns whether parameter MUST be callable
    • ReflectionParameter::isDefaultValueAvailable — Checks if a default value is available
    • ReflectionParameter::isDefaultValueConstant — Returns whether the default value of this parameter is constant
    • ReflectionParameter::isOptional — Checks if optional
    • ReflectionParameter::isPassedByReference — Checks if passed by reference
    • ReflectionParameter::isVariadic — Checks if the parameter is variadic
    • 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 the property doc comment
    • ReflectionProperty::getModifiers — Gets modifiers
    • ReflectionProperty::getName — Gets property name
    • ReflectionProperty::getValue — Gets value
    • ReflectionProperty::isDefault — Checks if property is a default property
    • 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
  • ReflectionType — The ReflectionType class
    • ReflectionType::allowsNull — Checks if null is allowed
    • ReflectionType::isBuiltin — Checks if it is a built-in type
    • ReflectionType::__toString — To string
  • ReflectionGenerator — The ReflectionGenerator class
    • ReflectionGenerator::__construct — Constructs a ReflectionGenerator object
    • ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator
    • ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object
    • ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator
    • ReflectionGenerator::getFunction — Gets the function name of the generator
    • ReflectionGenerator::getThis — Gets the $this value of the generator
    • ReflectionGenerator::getTrace — Gets the trace of the executing generator
  • Reflector — The Reflector interface
    • Reflector::export — Exports
    • Reflector::__toString — To string
  • ReflectionException — The ReflectionException class
QuickHashIntStringHash::update
Introducere
Extensii referitoare la variabile ?i tipuri


Introducere

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
Instalarea / configurarea
Reflection


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Reflection


Constante predefinite

Fiecare clasa descrie propriile constante.

Tipurile resurselor
Exemple
Reflection


Exemple

Many examples exist within the Reflection documentation, typically within the __construct documentation for each class.

Example #1 Reflection Example from Shell (a Terminal)

$ php --rf strlen
$ php --rc finfo
$ php --re json
$ php --ri dom

Exemplul de mai sus va afi?a ceva similar cu:

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
Constante predefinite
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.

Example #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'));
?>

Exemplul de mai sus va afi?a ceva similar cu:

object(My_Reflection_Method)#1 (3) {
  ["visibility"]=>
  array(1) {
    [0]=>
    string(6) "public"
  }
  ["name"]=>
  string(1) "x"
  ["class"]=>
  string(1) "U"
}
Precautie

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

Exemple
Reflection
Reflection


The Reflection class

(PHP 5, PHP 7)

Introducere

The reflection class.

Sinopsisul clasei

Reflection {
/* Metode */
public static string export ( Reflector $reflector [, bool $return = false ] )
public static array getModifierNames ( int $modifiers )
}

Cuprins

  • Reflection::export — Exports
  • Reflection::getModifierNames — Gets modifier names
Extending
Reflection::export
Reflection


Exports

Reflection
Reflection::getModifierNames
Reflection
PHP Manual

Reflection::export

(PHP 5, PHP 7)

Reflection::export — Exports

Descrierea

public static string Reflection::export ( Reflector $reflector [, bool $return = false ] )

Exports a reflection.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

reflector

Reflec?ia ce va fi exportata.

return

Stabilirea valorii TRUE va duce la întoarcerea valorii exportate, ?i nu la emiterea ei. Stabilirea în FALSE (valoarea implicita) va efectua opera?ia opusa.

Valorile întoarse

Daca parametrul return este stabilit în TRUE, atunci valoarea exportata este întoarsa ca un string, în caz contrar este întors NULL.

A se vedea ?i

  • Reflection::getModifierNames() - Gets modifier names

Reflection
Reflection::getModifierNames
Reflection


Gets modifier names

Reflection::export
ReflectionClass
Reflection
PHP Manual

Reflection::getModifierNames

(PHP 5, PHP 7)

Reflection::getModifierNames — Gets modifier names

Descrierea

public static array Reflection::getModifierNames ( int $modifiers )

Gets modifier names.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

modifiers

The modifiers to get, which is from a numeric value.

Valorile întoarse

An array of modifier names.

A se vedea ?i

  • Reflection::export() - Exports

Reflection::export
ReflectionClass
Reflection


The ReflectionClass class

(PHP 5, PHP 7)

Introducere

The ReflectionClass class reports information about a class.

Sinopsisul clasei

ReflectionClass implements Reflector {
/* Constante */
const integer IS_IMPLICIT_ABSTRACT = 16 ;
const integer IS_EXPLICIT_ABSTRACT = 32 ;
const integer IS_FINAL = 64 ;
/* Proprieta?i */
public $name ;
/* Metode */
public __construct ( mixed $argument )
public static string export ( mixed $argument [, bool $return = false ] )
public mixed getConstant ( string $name )
public array getConstants ( void )
public ReflectionMethod 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 ([ int $filter ] )
public int getModifiers ( void )
public string getName ( void )
public string getNamespaceName ( void )
public ReflectionClass 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 [, mixed &$def_value ] )
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 isAnonymous ( 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 )
}

Proprieta?i

name

Name of the class. Read-only, throws ReflectionException in attempt to write.

Constante predefinite

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.

Cuprins

  • ReflectionClass::__construct — Constructs a ReflectionClass
  • ReflectionClass::export — Exports a class
  • ReflectionClass::getConstant — Gets defined constant
  • ReflectionClass::getConstants — Gets constants
  • ReflectionClass::getConstructor — Gets the constructor of the class
  • ReflectionClass::getDefaultProperties — Gets default properties
  • ReflectionClass::getDocComment — Gets doc comments
  • ReflectionClass::getEndLine — Gets end line
  • ReflectionClass::getExtension — Gets a ReflectionExtension object for the extension which defined the class
  • ReflectionClass::getExtensionName — Gets the name of the extension which defined the class
  • 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 for a class method.
  • ReflectionClass::getMethods — Gets an array 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 a ReflectionProperty for a class's 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::isAnonymous — Checks if class is anonymous
  • 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 the class is instantiable
  • ReflectionClass::isInterface — Checks if the class is an interface
  • ReflectionClass::isInternal — Checks if class is defined internally by an extension, or the core
  • 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::__construct
Reflection


Constructs a ReflectionClass

ReflectionClass
ReflectionClass::export
ReflectionClass
PHP Manual

ReflectionClass::__construct

(PHP 5, PHP 7)

ReflectionClass::__construct — Constructs a ReflectionClass

Descrierea

public ReflectionClass::__construct ( mixed $argument )

Constructs a new ReflectionClass object.

Parametri

argument

Either a string containing the name of the class to reflect, or an object.

Valorile întoarse

Returns constructed ReflectionClass instance.

Erori/Excep?ii

Throws ReflectionException if the class to reflect does not exist.

Exemple

Example #1 Basic usage ReflectionClass

<?php
Reflection::export(new ReflectionClass('Exception'));
?>

Exemplul de mai sus va afi?a ceva similar cu:

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 ] {
    }
  }
}

A se vedea ?i

  • ReflectionObject::__construct() - Constructs a ReflectionObject
  • Constructors

ReflectionClass
ReflectionClass::export
ReflectionClass


Exports a class

ReflectionClass::__construct
ReflectionClass::getConstant
ReflectionClass
PHP Manual

ReflectionClass::export

(PHP 5, PHP 7)

ReflectionClass::export — Exports a class

Descrierea

public static string ReflectionClass::export ( mixed $argument [, bool $return = false ] )

Exports a reflected class.

Parametri

argument

Reflec?ia ce va fi exportata.

return

Stabilirea valorii TRUE va duce la întoarcerea valorii exportate, ?i nu la emiterea ei. Stabilirea în FALSE (valoarea implicita) va efectua opera?ia opusa.

Valorile întoarse

Daca parametrul return este stabilit în TRUE, atunci valoarea exportata este întoarsa ca un string, în caz contrar este întors NULL.

Exemple

Example #1 Basic usage of ReflectionClass::export()

<?php
class Apple {
    public $var1;
    public $var2 = 'Orange';

    public function type() {
        return 'Apple';
    }
}
ReflectionClass::export('Apple');
?>

Exemplul de mai sus va afi?a ceva similar cu:

Class [ <user> class Apple ] {
  @@ php shell code 1-8

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [2] {
    Property [ <default> public $var1 ]
    Property [ <default> public $var2 ]
  }

  - Methods [1] {
    Method [ <user> public method type ] {
      @@ php shell code 5 - 7
    }
  }
}

A se vedea ?i

  • ReflectionClass::getName() - Gets class name

ReflectionClass::__construct
ReflectionClass::getConstant
ReflectionClass


Gets defined constant

ReflectionClass::export
ReflectionClass::getConstants
ReflectionClass
PHP Manual

ReflectionClass::getConstant

(PHP 5, PHP 7)

ReflectionClass::getConstant — Gets defined constant

Descrierea

public mixed ReflectionClass::getConstant ( string $name )

Gets the defined constant.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Name of the constant.

Valorile întoarse

Value of the constant.

A se vedea ?i

  • ReflectionClass::getConstants() - Gets constants

ReflectionClass::export
ReflectionClass::getConstants
ReflectionClass


Gets constants

ReflectionClass::getConstant
ReflectionClass::getConstructor
ReflectionClass
PHP Manual

ReflectionClass::getConstants

(PHP 5, PHP 7)

ReflectionClass::getConstants — Gets constants

Descrierea

public array ReflectionClass::getConstants ( void )

Gets defined constants from a class.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array of constants. Constant name in key, constant value in value.

A se vedea ?i

  • ReflectionClass::getConstant() - Gets defined constant

ReflectionClass::getConstant
ReflectionClass::getConstructor
ReflectionClass


Gets the constructor of the class

ReflectionClass::getConstants
ReflectionClass::getDefaultProperties
ReflectionClass
PHP Manual

ReflectionClass::getConstructor

(PHP 5, PHP 7)

ReflectionClass::getConstructor — Gets the constructor of the class

Descrierea

public ReflectionMethod ReflectionClass::getConstructor ( void )

Gets the constructor of the reflected class.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A ReflectionMethod object reflecting the class' constructor, or NULL if the class has no constructor.

Exemple

Example #1 Basic usage of ReflectionClass::getConstructor()

<?php
$class = new ReflectionClass('ReflectionClass');
$constructor = $class->getConstructor();
var_dump($constructor);
?>

Exemplul de mai sus va afi?a:

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(11) "__construct"
  ["class"]=>
  string(15) "ReflectionClass"
}

A se vedea ?i

  • ReflectionClass::getName() - Gets class name

ReflectionClass::getConstants
ReflectionClass::getDefaultProperties
ReflectionClass


Gets default properties

ReflectionClass::getConstructor
ReflectionClass::getDocComment
ReflectionClass
PHP Manual

ReflectionClass::getDefaultProperties

(PHP 5, PHP 7)

ReflectionClass::getDefaultProperties — Gets default properties

Descrierea

public array ReflectionClass::getDefaultProperties ( void )

Gets default properties from a class (including inherited properties).

Nota:

This method only works for static properties when used on internal classes. The default value of a static class property can not be tracked when using this method on user defined classes.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

array(5) {
   ["staticProperty"]=>
   string(14) "staticProperty"
   ["property"]=>
   string(15) "propertyDefault"
   ["privateProperty"]=>
   string(22) "privatePropertyDefault"
   ["defaultlessProperty"]=>
   NULL
   ["inheritedProperty"]=>
   string(16) "inheritedDefault"
}

A se vedea ?i

  • ReflectionClass::getProperties() - Gets properties
  • ReflectionClass::getStaticProperties() - Gets static properties
  • ReflectionClass::getProperty() - Gets a ReflectionProperty for a class's property

ReflectionClass::getConstructor
ReflectionClass::getDocComment
ReflectionClass


Gets doc comments

ReflectionClass::getDefaultProperties
ReflectionClass::getEndLine
ReflectionClass
PHP Manual

ReflectionClass::getDocComment

(PHP 5 >= 5.1.0, PHP 7)

ReflectionClass::getDocComment — Gets doc comments

Descrierea

public string ReflectionClass::getDocComment ( void )

Gets doc comments from a class.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The doc comment if it exists, otherwise FALSE

Exemple

Example #1 ReflectionClass::getDocComment() example

<?php
/**
* A test class
*
* @param  foo bar
* @return baz
*/
class TestClass { }

$rc = new ReflectionClass('TestClass');
var_dump($rc->getDocComment())
?>

Exemplul de mai sus va afi?a:

string(55) "/**
* A test class
*
* @param  foo bar
* @return baz
*/"

A se vedea ?i

  • ReflectionClass::getName() - Gets class name

ReflectionClass::getDefaultProperties
ReflectionClass::getEndLine
ReflectionClass


Gets end line

ReflectionClass::getDocComment
ReflectionClass::getExtension
ReflectionClass
PHP Manual

ReflectionClass::getEndLine

(PHP 5, PHP 7)

ReflectionClass::getEndLine — Gets end line

Descrierea

public int ReflectionClass::getEndLine ( void )

Gets end line number from a user-defined class definition.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The ending line number of the user defined class, or FALSE if unknown.

Exemple

Example #1 ReflectionClass::getEndLine() example

<?php
// Test Class
class TestClass { }

$rc = new ReflectionClass('TestClass');

echo $rc->getEndLine();
?>

Exemplul de mai sus va afi?a:

3

A se vedea ?i

  • ReflectionClass::getStartLine() - Gets starting line number

ReflectionClass::getDocComment
ReflectionClass::getExtension
ReflectionClass


Gets a ReflectionExtension object for the extension which defined the class

ReflectionClass::getEndLine
ReflectionClass::getExtensionName
ReflectionClass
PHP Manual

ReflectionClass::getExtension

(PHP 5, PHP 7)

ReflectionClass::getExtension — Gets a ReflectionExtension object for the extension which defined the class

Descrierea

public ReflectionExtension ReflectionClass::getExtension ( void )

Gets a ReflectionExtension object for the extension which defined the class.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A ReflectionExtension object representing the extension which defined the class, or NULL for user-defined classes.

Exemple

Example #1 Basic usage of ReflectionClass::getExtension()

<?php
$class = new ReflectionClass('ReflectionClass');
$extension = $class->getExtension();
var_dump($extension);
?>

Exemplul de mai sus va afi?a:

object(ReflectionExtension)#2 (1) {
  ["name"]=>
  string(10) "Reflection"
}

A se vedea ?i

  • ReflectionClass::getExtensionName() - Gets the name of the extension which defined the class

ReflectionClass::getEndLine
ReflectionClass::getExtensionName
ReflectionClass


Gets the name of the extension which defined the class

ReflectionClass::getExtension
ReflectionClass::getFileName
ReflectionClass
PHP Manual

ReflectionClass::getExtensionName

(PHP 5, PHP 7)

ReflectionClass::getExtensionName — Gets the name of the extension which defined the class

Descrierea

public string ReflectionClass::getExtensionName ( void )

Gets the name of the extension which defined the class.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The name of the extension which defined the class, or FALSE for user-defined classes.

Exemple

Example #1 Basic usage of ReflectionClass::getExtensionName()

<?php
$class = new ReflectionClass('ReflectionClass');
$extension = $class->getExtensionName();
var_dump($extension);
?>

Exemplul de mai sus va afi?a:

string(10) "Reflection"

A se vedea ?i

  • ReflectionClass::getExtension() - Gets a ReflectionExtension object for the extension which defined the class

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, PHP 7)

ReflectionClass::getFileName — Gets the filename of the file in which the class has been defined

Descrierea

public string ReflectionClass::getFileName ( void )

Gets the filename of the file in which the class has been defined.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

A se vedea ?i

  • ReflectionClass::getExtensionName() - Gets the name of the extension which defined the class

ReflectionClass::getExtensionName
ReflectionClass::getInterfaceNames
ReflectionClass


Gets the interface names

ReflectionClass::getFileName
ReflectionClass::getInterfaces
ReflectionClass
PHP Manual

ReflectionClass::getInterfaceNames

(PHP 5 >= 5.2.0, PHP 7)

ReflectionClass::getInterfaceNames — Gets the interface names

Descrierea

public array ReflectionClass::getInterfaceNames ( void )

Get the interface names.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A numerical array with interface names as the values.

Exemple

Example #1 ReflectionClass::getInterfaceNames() example

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

print_r($rc1->getInterfaceNames());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [0] => Foo
    [1] => Bar
)

A se vedea ?i

  • ReflectionClass::getInterfaces() - Gets the interfaces

ReflectionClass::getFileName
ReflectionClass::getInterfaces
ReflectionClass


Gets the interfaces

ReflectionClass::getInterfaceNames
ReflectionClass::getMethod
ReflectionClass
PHP Manual

ReflectionClass::getInterfaces

(PHP 5, PHP 7)

ReflectionClass::getInterfaces — Gets the interfaces

Descrierea

public array ReflectionClass::getInterfaces ( void )

Gets the interfaces.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An associative array of interfaces, with keys as interface names and the array values as ReflectionClass objects.

Exemple

Example #1 ReflectionClass::getInterfaces() example

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

print_r($rc1->getInterfaces());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [Foo] => ReflectionClass Object
        (
            [name] => Foo
        )

    [Bar] => ReflectionClass Object
        (
            [name] => Bar
        )

)

A se vedea ?i

  • ReflectionClass::getInterfaceNames() - Gets the interface names

ReflectionClass::getInterfaceNames
ReflectionClass::getMethod
ReflectionClass


Gets a ReflectionMethod for a class method.

ReflectionClass::getInterfaces
ReflectionClass::getMethods
ReflectionClass
PHP Manual

ReflectionClass::getMethod

(PHP 5, PHP 7)

ReflectionClass::getMethod — Gets a ReflectionMethod for a class method.

Descrierea

public ReflectionMethod ReflectionClass::getMethod ( string $name )

Gets a ReflectionMethod for a class method.

Parametri

name

The method name to reflect.

Valorile întoarse

A ReflectionMethod.

Erori/Excep?ii

A ReflectionException if the method does not exist.

Exemple

Example #1 Basic usage of ReflectionClass::getMethod()

<?php
$class = new ReflectionClass('ReflectionClass');
$method = $class->getMethod('getMethod');
var_dump($method);
?>

Exemplul de mai sus va afi?a:

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(9) "getMethod"
  ["class"]=>
  string(15) "ReflectionClass"
}

A se vedea ?i

  • ReflectionClass::getMethods() - Gets an array of methods

ReflectionClass::getInterfaces
ReflectionClass::getMethods
ReflectionClass


Gets an array of methods

ReflectionClass::getMethod
ReflectionClass::getModifiers
ReflectionClass
PHP Manual

ReflectionClass::getMethods

(PHP 5, PHP 7)

ReflectionClass::getMethods — Gets an array of methods

Descrierea

public array ReflectionClass::getMethods ([ int $filter ] )

Gets an array of methods for the class.

Parametri

filter

Filter the results to include only methods with certain attributes. Defaults to no filtering.

Any bitwise disjunction of ReflectionMethod::IS_STATIC,
ReflectionMethod::IS_PUBLIC,
ReflectionMethod::IS_PROTECTED,
ReflectionMethod::IS_PRIVATE,
ReflectionMethod::IS_ABSTRACT,
ReflectionMethod::IS_FINAL,
so that all methods with any of the given
attributes will be returned.

Nota: Note that other bitwise operations, for instance ~ will not work as expected. In other words, it is not possible to retrieve all non-static methods, for example.

Valorile întoarse

An array of ReflectionMethod objects reflecting each method.

Exemple

Example #1 Basic usage of ReflectionClass::getMethods()

<?php
class Apple {
    public function firstMethod() { }
    final protected function secondMethod() { }
    private static function thirdMethod() { }
}

$class = new ReflectionClass('Apple');
$methods = $class->getMethods();
var_dump($methods);
?>

Exemplul de mai sus va afi?a:

array(3) {
  [0]=>
  &object(ReflectionMethod)#2 (2) {
    ["name"]=>
    string(11) "firstMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [1]=>
  &object(ReflectionMethod)#3 (2) {
    ["name"]=>
    string(12) "secondMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [2]=>
  &object(ReflectionMethod)#4 (2) {
    ["name"]=>
    string(11) "thirdMethod"
    ["class"]=>
    string(5) "Apple"
  }
}

Example #2 Filtering results from ReflectionClass::getMethods()

<?php
class Apple {
    public function firstMethod() { }
    final protected function secondMethod() { }
    private static function thirdMethod() { }
}

$class = new ReflectionClass('Apple');
$methods = $class->getMethods(ReflectionMethod::IS_STATIC | ReflectionMethod::IS_FINAL);
var_dump($methods);
?>

Exemplul de mai sus va afi?a:

array(2) {
  [0]=>
  &object(ReflectionMethod)#2 (2) {
    ["name"]=>
    string(12) "secondMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [1]=>
  &object(ReflectionMethod)#3 (2) {
    ["name"]=>
    string(11) "thirdMethod"
    ["class"]=>
    string(5) "Apple"
  }
}

A se vedea ?i

  • ReflectionClass::getMethod() - Gets a ReflectionMethod for a class method.
  • get_class_methods() - Gets the class methods' names

ReflectionClass::getMethod
ReflectionClass::getModifiers
ReflectionClass


Gets modifiers

ReflectionClass::getMethods
ReflectionClass::getName
ReflectionClass
PHP Manual

ReflectionClass::getModifiers

(PHP 5, PHP 7)

ReflectionClass::getModifiers — Gets modifiers

Descrierea

public int ReflectionClass::getModifiers ( void )

Returns a bitfield of the access modifiers for this class.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns bitmask of modifier constants.

A se vedea ?i

  • ReflectionClass::getProperties() - Gets properties

ReflectionClass::getMethods
ReflectionClass::getName
ReflectionClass


Gets class name

ReflectionClass::getModifiers
ReflectionClass::getNamespaceName
ReflectionClass
PHP Manual

ReflectionClass::getName

(PHP 5, PHP 7)

ReflectionClass::getName — Gets class name

Descrierea

public string ReflectionClass::getName ( void )

Gets the class name.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The class name.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::getNamespaceName — Gets namespace name

Descrierea

public string ReflectionClass::getNamespaceName ( void )

Gets the namespace name.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The namespace name.

Exemple

Example #1 ReflectionClass::getNamespaceName() example

<?php
namespace A\B;

class Foo { }

$class = new \ReflectionClass('stdClass');

var_dump($class->inNamespace());
var_dump($class->getName());
var_dump($class->getNamespaceName());
var_dump($class->getShortName());

$class = new \ReflectionClass('A\\B\\Foo');

var_dump($class->inNamespace());
var_dump($class->getName());
var_dump($class->getNamespaceName());
var_dump($class->getShortName());
?>

Exemplul de mai sus va afi?a:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::getParentClass — Gets parent class

Descrierea

public ReflectionClass ReflectionClass::getParentClass ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A ReflectionClass.

A se vedea ?i

  • ReflectionClass::__construct() - Constructs a ReflectionClass

ReflectionClass::getNamespaceName
ReflectionClass::getProperties
ReflectionClass


Gets properties

ReflectionClass::getParentClass
ReflectionClass::getProperty
ReflectionClass
PHP Manual

ReflectionClass::getProperties

(PHP 5, PHP 7)

ReflectionClass::getProperties — Gets properties

Descrierea

public array ReflectionClass::getProperties ([ int $filter ] )

Retrieves reflected properties.

Parametri

filter

The optional filter, for filtering desired property types. It's configured using the ReflectionProperty constants, and defaults to all property types.

Valorile întoarse

An array of ReflectionProperty objects.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a ceva similar cu:

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"
  }
}

A se vedea ?i

  • ReflectionClass::getProperty() - Gets a ReflectionProperty for a class's property
  • ReflectionProperty
  • ReflectionProperty modifier constants

ReflectionClass::getParentClass
ReflectionClass::getProperty
ReflectionClass


Gets a ReflectionProperty for a class's property

ReflectionClass::getProperties
ReflectionClass::getShortName
ReflectionClass
PHP Manual

ReflectionClass::getProperty

(PHP 5, PHP 7)

ReflectionClass::getProperty — Gets a ReflectionProperty for a class's property

Descrierea

public ReflectionProperty ReflectionClass::getProperty ( string $name )

Gets a ReflectionProperty for a class's property.

Parametri

name

The property name.

Valorile întoarse

A ReflectionProperty.

Exemple

Example #1 Basic usage of ReflectionClass::getProperty()

<?php
$class = new ReflectionClass('ReflectionClass');
$property = $class->getProperty('name');
var_dump($property);
?>

Exemplul de mai sus va afi?a:

object(ReflectionProperty)#2 (2) {
  ["name"]=>
  string(4) "name"
  ["class"]=>
  string(15) "ReflectionClass"
}

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::getShortName — Gets short name

Descrierea

public string ReflectionClass::getShortName ( void )

Gets the short name of the class, the part without the namespace.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The class short name.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::getStartLine — Gets starting line number

Descrierea

public int ReflectionClass::getStartLine ( void )

Get the starting line number.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The starting line number, as an integer.

A se vedea ?i

  • ReflectionClass::getEndLine() - Gets end line

ReflectionClass::getShortName
ReflectionClass::getStaticProperties
ReflectionClass


Gets static properties

ReflectionClass::getStartLine
ReflectionClass::getStaticPropertyValue
ReflectionClass
PHP Manual

ReflectionClass::getStaticProperties

(PHP 5, PHP 7)

ReflectionClass::getStaticProperties — Gets static properties

Descrierea

public array ReflectionClass::getStaticProperties ( void )

Get the static properties.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The static properties, as an array.

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::getStaticPropertyValue — Gets static property value

Descrierea

public mixed ReflectionClass::getStaticPropertyValue ( string $name [, mixed &$def_value ] )

Gets the value of a static property on this class.

Parametri

name

The name of the static property for which to return a value.

def_value

A default value to return in case the class does not declare a static property with the given name. If the property does not exist and this argument is omitted, a ReflectionException is thrown.

Valorile întoarse

The value of the static property.

Exemple

Example #1 Basic usage of ReflectionClass::getStaticPropertyValue()

<?php
class Apple {
    public static $color = 'Red';
}

$class = new ReflectionClass('Apple');
var_dump($class->getStaticPropertyValue('color'));
?>

Exemplul de mai sus va afi?a:

string(3) "Red"

A se vedea ?i

  • 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

Descrierea

public array ReflectionClass::getTraitAliases ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public array ReflectionClass::getTraitNames ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public array ReflectionClass::getTraits ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

ReflectionClass::hasConstant — Checks if constant is defined

Descrierea

public bool ReflectionClass::hasConstant ( string $name )

Checks whether the class has a specific constant defined or not.

Parametri

name

The name of the constant being checked for.

Valorile întoarse

TRUE if the constant is defined, otherwise FALSE.

Exemple

Example #1 ReflectionClass::hasConstant() example

<?php
class Foo {
    const c1 = 1;
}

$class = new ReflectionClass("Foo");

var_dump($class->hasConstant("c1"));
var_dump($class->hasConstant("c2"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(false)

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::hasMethod — Checks if method is defined

Descrierea

public bool ReflectionClass::hasMethod ( string $name )

Checks whether a specific method is defined in a class.

Parametri

name

Name of the method being checked for.

Valorile întoarse

TRUE if it has the method, otherwise FALSE

Exemple

Example #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'));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::hasProperty — Checks if property is defined

Descrierea

public bool ReflectionClass::hasProperty ( string $name )

Checks whether the specified property is defined.

Parametri

name

Name of the property being checked for.

Valorile întoarse

TRUE if it has the property, otherwise FALSE

Exemple

Example #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"));
?>

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(true)
bool(true)
bool(false)

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::implementsInterface — Implements interface

Descrierea

public bool ReflectionClass::implementsInterface ( string $interface )

Checks whether it implements an interface.

Parametri

interface

The interface name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ReflectionClass::isInterface() - Checks if the class is an interface
  • ReflectionClass::isSubclassOf() - Checks if a subclass
  • 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, PHP 7)

ReflectionClass::inNamespace — Checks if in namespace

Descrierea

public bool ReflectionClass::inNamespace ( void )

Checks if this class is defined in a namespace.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

A se vedea ?i

  • ReflectionClass::getNamespaceName() - Gets namespace name
  • PHP Namespaces

ReflectionClass::implementsInterface
ReflectionClass::isAbstract
ReflectionClass


Checks if class is abstract

ReflectionClass::inNamespace
ReflectionClass::isAnonymous
ReflectionClass
PHP Manual

ReflectionClass::isAbstract

(PHP 5, PHP 7)

ReflectionClass::isAbstract — Checks if class is abstract

Descrierea

public bool ReflectionClass::isAbstract ( void )

Checks if the class is abstract.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

A se vedea ?i

  • ReflectionClass::isInterface() - Checks if the class is an interface
  • Class Abstraction

ReflectionClass::inNamespace
ReflectionClass::isAnonymous
ReflectionClass


Checks if class is anonymous

ReflectionClass::isAbstract
ReflectionClass::isCloneable
ReflectionClass
PHP Manual

ReflectionClass::isAnonymous

(PHP 7)

ReflectionClass::isAnonymous — Checks if class is anonymous

Descrierea

public bool ReflectionClass::isAnonymous ( void )

Checks if a class is an anonymous class.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ReflectionClass::isAnonymous() example

<?php
class TestClass {}
$anonClass = new class {};

$normalClass = new ReflectionClass('TestClass');
$anonClass  = new ReflectionClass($anonClass);

var_dump($normalClass->isAnonymous());
var_dump($anonClass->isAnonymous());

?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

A se vedea ?i

  • ReflectionClass::isFinal() - Checks if class is final

ReflectionClass::isAbstract
ReflectionClass::isCloneable
ReflectionClass


Returns whether this class is cloneable

ReflectionClass::isAnonymous
ReflectionClass::isFinal
ReflectionClass
PHP Manual

ReflectionClass::isCloneable

(PHP >= 5.4.0)

ReflectionClass::isCloneable — Returns whether this class is cloneable

Descrierea

public bool ReflectionClass::isCloneable ( void )

Returns whether this class is cloneable.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the class is cloneable, FALSE otherwise.

Exemple

Example #1 Basic usage of ReflectionClass::isCloneable()

<?php
class NotCloneable {
    public $var1;

    private function __clone() {
    }
}

class Cloneable {
    public $var1;
}

$notCloneable = new ReflectionClass('NotCloneable');
$cloneable = new ReflectionClass('Cloneable');

var_dump($notCloneable->isCloneable());
var_dump($cloneable->isCloneable());
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

ReflectionClass::isAnonymous
ReflectionClass::isFinal
ReflectionClass


Checks if class is final

ReflectionClass::isCloneable
ReflectionClass::isInstance
ReflectionClass
PHP Manual

ReflectionClass::isFinal

(PHP 5, PHP 7)

ReflectionClass::isFinal — Checks if class is final

Descrierea

public bool ReflectionClass::isFinal ( void )

Checks if a class is final.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 ReflectionClass::isFinal() example

<?php
class       TestClass { }
final class TestFinalClass { }

$normalClass = new ReflectionClass('TestClass');
$finalClass  = new ReflectionClass('TestFinalClass');

var_dump($normalClass->isFinal());
var_dump($finalClass->isFinal());

?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::isInstance — Checks class for instance

Descrierea

public bool ReflectionClass::isInstance ( object $object )

Checks if an object is an instance of a class.

Parametri

object

The object being compared to.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Yes
Yes
Yes

A se vedea ?i

  • ReflectionClass::isInterface() - Checks if the class is an interface
  • Type operators (instanceof)
  • Object Interfaces
  • is_a() - Checks if the object is of this class or has this class as one of its parents

ReflectionClass::isFinal
ReflectionClass::isInstantiable
ReflectionClass


Checks if the class is instantiable

ReflectionClass::isInstance
ReflectionClass::isInterface
ReflectionClass
PHP Manual

ReflectionClass::isInstantiable

(PHP 5, PHP 7)

ReflectionClass::isInstantiable — Checks if the class is instantiable

Descrierea

public bool ReflectionClass::isInstantiable ( void )

Checks if the class is instantiable.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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() { }
}

class privateConstructor {
    private function __construct() { }
}

$classes = array(
    "C",
    "iface",
    "ifaceImpl",
    "abstractClass",
    "D",
    "privateConstructor",
);

foreach($classes  as $class ) {
    $reflectionClass = new ReflectionClass($class);
    echo "Is $class instantiable?  ";
    var_dump($reflectionClass->IsInstantiable());
}

?>

Exemplul de mai sus va afi?a:

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)
Is privateConstructor instantiable?  bool(false)

A se vedea ?i

  • ReflectionClass::isInstance() - Checks class for instance

ReflectionClass::isInstance
ReflectionClass::isInterface
ReflectionClass


Checks if the class is an interface

ReflectionClass::isInstantiable
ReflectionClass::isInternal
ReflectionClass
PHP Manual

ReflectionClass::isInterface

(PHP 5, PHP 7)

ReflectionClass::isInterface — Checks if the class is an interface

Descrierea

public bool ReflectionClass::isInterface ( void )

Checks whether the class is an interface.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Basic usage of ReflectionClass::isInterface()

<?php
interface SomeInterface {
    public function interfaceMethod();
}

$class = new ReflectionClass('SomeInterface');
var_dump($class->isInterface());
?>

Exemplul de mai sus va afi?a:

bool(true)

A se vedea ?i

  • ReflectionClass::isInstance() - Checks class for instance

ReflectionClass::isInstantiable
ReflectionClass::isInternal
ReflectionClass


Checks if class is defined internally by an extension, or the core

ReflectionClass::isInterface
ReflectionClass::isIterateable
ReflectionClass
PHP Manual

ReflectionClass::isInternal

(PHP 5, PHP 7)

ReflectionClass::isInternal — Checks if class is defined internally by an extension, or the core

Descrierea

public bool ReflectionClass::isInternal ( void )

Checks if the class is defined internally by an extension, or the core, as opposed to user-defined.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Basic usage of ReflectionClass::isInternal()

<?php
$internalclass = new ReflectionClass('ReflectionClass');

class Apple {}
$userclass = new ReflectionClass('Apple');

var_dump($internalclass->isInternal());
var_dump($userclass->isInternal());
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::isIterateable — Checks if iterateable

Descrierea

public bool ReflectionClass::isIterateable ( void )

Checks whether the class is iterateable.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
}
?>

Exemplul de mai sus va afi?a:

Is ArrayObject iterateable? bool(true)
Is IteratorClass iterateable? bool(true)
Is DerivedClass iterateable? bool(true)
Is NonIterator iterateable? bool(false)

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::isSubclassOf — Checks if a subclass

Descrierea

public bool ReflectionClass::isSubclassOf ( string $class )

Checks if the class is a subclass of a specified class or implements a specified interface.

Parametri

class

The class name being checked against.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ReflectionClass::isInterface() - Checks if the class is an interface
  • ReflectionClass::implementsInterface() - Implements interface
  • is_subclass_of() - Checks if the object has this class as one of its parents or implements it.
  • get_parent_class() - Retrieves the parent class name for object or class

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

Descrierea

public bool ReflectionClass::isTrait ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

ReflectionClass::isUserDefined — Checks if user defined

Descrierea

public bool ReflectionClass::isUserDefined ( void )

Checks whether the class is user-defined, as opposed to internal.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • ReflectionClass::isInternal() - Checks if class is defined internally by an extension, or the core

ReflectionClass::isTrait
ReflectionClass::newInstance
ReflectionClass


Creates a new class instance from given arguments.

ReflectionClass::isUserDefined
ReflectionClass::newInstanceArgs
ReflectionClass
PHP Manual

ReflectionClass::newInstance

(PHP 5, PHP 7)

ReflectionClass::newInstance — Creates a new class instance from given arguments.

Descrierea

public object ReflectionClass::newInstance ( mixed $args [, mixed $... ] )

Creates a new instance of the class. The given arguments are passed to the class constructor.

Parametri

args

Accepts a variable number of arguments which are passed to the class constructor, much like call_user_func().

Valorile întoarse

Erori/Excep?ii

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.

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::newInstanceArgs — Creates a new class instance from given arguments.

Descrierea

public object ReflectionClass::newInstanceArgs ([ array $args ] )

Creates a new instance of the class, the given arguments are passed to the class constructor.

Parametri

args

The parameters to be passed to the class constructor as an array.

Valorile întoarse

Returns a new instance of the class.

Exemple

Example #1 Basic usage of ReflectionClass::newInstanceArgs()

<?php
$class = new ReflectionClass('ReflectionFunction');
$instance = $class->newInstanceArgs(array('substr'));
var_dump($instance);
?>

Exemplul de mai sus va afi?a:

object(ReflectionFunction)#2 (1) {
  ["name"]=>
  string(6) "substr"
}

Erori/Excep?ii

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.

A se vedea ?i

  • 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.

Descrierea

public object ReflectionClass::newInstanceWithoutConstructor ( void )

Creates a new instance of the class without invoking the constructor.

Parametri

Valorile întoarse

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | All internal classes can now be instantiated except for those declared final.

Erori/Excep?ii

A ReflectionException if the class is an internal class that cannot be instantiated without invoking the constructor. In PHP 5.6.0 onwards, this exception is limited only to internal classes that are final.

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::setStaticPropertyValue — Sets static property value

Descrierea

public void ReflectionClass::setStaticPropertyValue ( string $name , string $value )

Sets static property value.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Property name.

value

New property value.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

ReflectionClass::__toString — Returns the string representation of the ReflectionClass object.

Descrierea

public string ReflectionClass::__toString ( void )

Returns the string representation of the ReflectionClass object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A string representation of this ReflectionClass instance.

Exemple

Example #1 ReflectionClass::__toString() example

<?php
$reflectionClass = new ReflectionClass('Exception');
echo $reflectionClass->__toString();
?>

Exemplul de mai sus va afi?a:

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 ] {
    }
  }
}

A se vedea ?i

  • ReflectionClass::export() - Exports a class
  • __toString()

ReflectionClass::setStaticPropertyValue
ReflectionZendExtension
ReflectionClass


The ReflectionZendExtension class

(PHP >= 5.4.0)

Introducere

Sinopsisul clasei

ReflectionZendExtension implements Reflector {
/* Proprieta?i */
public $name ;
/* Metode */
final private void __clone ( void )
public __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 )
}

Proprieta?i

name

Name of the extension. Read-only, throws ReflectionException in attempt to write.

Cuprins

  • 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

Descrierea

final private void ReflectionZendExtension::__clone ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ReflectionZendExtension
ReflectionZendExtension::__construct
ReflectionZendExtension


Constructor

ReflectionZendExtension::__clone
ReflectionZendExtension::export
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::__construct

(PHP >= 5.4.0)

ReflectionZendExtension::__construct — Constructor

Descrierea

public ReflectionZendExtension::__construct ( string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

Valorile întoarse

ReflectionZendExtension::__clone
ReflectionZendExtension::export
ReflectionZendExtension


Export

ReflectionZendExtension::__construct
ReflectionZendExtension::getAuthor
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::export

(PHP >= 5.4.0)

ReflectionZendExtension::export — Export

Descrierea

public static string ReflectionZendExtension::export ( string $name [, string $return ] )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

name

return

Valorile întoarse

ReflectionZendExtension::__construct
ReflectionZendExtension::getAuthor
ReflectionZendExtension


Gets author

ReflectionZendExtension::export
ReflectionZendExtension::getCopyright
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getAuthor

(PHP >= 5.4.0)

ReflectionZendExtension::getAuthor — Gets author

Descrierea

public string ReflectionZendExtension::getAuthor ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ReflectionZendExtension::export
ReflectionZendExtension::getCopyright
ReflectionZendExtension


Gets copyright

ReflectionZendExtension::getAuthor
ReflectionZendExtension::getName
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getCopyright

(PHP >= 5.4.0)

ReflectionZendExtension::getCopyright — Gets copyright

Descrierea

public string ReflectionZendExtension::getCopyright ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ReflectionZendExtension::getAuthor
ReflectionZendExtension::getName
ReflectionZendExtension


Gets name

ReflectionZendExtension::getCopyright
ReflectionZendExtension::getURL
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getName

(PHP >= 5.4.0)

ReflectionZendExtension::getName — Gets name

Descrierea

public string ReflectionZendExtension::getName ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ReflectionZendExtension::getCopyright
ReflectionZendExtension::getURL
ReflectionZendExtension


Gets URL

ReflectionZendExtension::getName
ReflectionZendExtension::getVersion
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getURL

(PHP >= 5.4.0)

ReflectionZendExtension::getURL — Gets URL

Descrierea

public string ReflectionZendExtension::getURL ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ReflectionZendExtension::getName
ReflectionZendExtension::getVersion
ReflectionZendExtension


Gets version

ReflectionZendExtension::getURL
ReflectionZendExtension::__toString
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getVersion

(PHP >= 5.4.0)

ReflectionZendExtension::getVersion — Gets version

Descrierea

public string ReflectionZendExtension::getVersion ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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

Descrierea

public string ReflectionZendExtension::__toString ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

ReflectionZendExtension::getVersion
ReflectionExtension
ReflectionZendExtension


The ReflectionExtension class

(PHP 5, PHP 7)

Introducere

The ReflectionExtension class reports information about an extension.

Sinopsisul clasei

ReflectionExtension implements Reflector {
/* Proprieta?i */
public $name ;
/* Metode */
final private void __clone ( void )
public __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 )
}

Proprieta?i

name

Name of the extension, same as calling the ReflectionExtension::getName() method.

Cuprins

  • 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, PHP 7)

ReflectionExtension::__clone — Clones

Descrierea

final private void ReflectionExtension::__clone ( void )

The clone method prevents an object from being cloned. Reflection objects cannot be cloned.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

No value is returned, if called a fatal error will occur.

A se vedea ?i

  • 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, PHP 7)

ReflectionExtension::__construct — Constructs a ReflectionExtension

Descrierea

public ReflectionExtension::__construct ( string $name )

Construct a ReflectionExtension object.

Parametri

name

Name of the extension.

Valorile întoarse

A ReflectionExtension object.

Exemple

Example #1 ReflectionExtension example

<?php
$ext = new ReflectionExtension('Reflection');

printf('Extension: %s (version: %s)', $ext->getName(), $ext->getVersion());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Extension: Reflection (version: $Revision: 330543 $)

A se vedea ?i

  • ReflectionExtension::info() - Print extension info
  • Constructors

ReflectionExtension::__clone
ReflectionExtension::export
ReflectionExtension


Export

ReflectionExtension::__construct
ReflectionExtension::getClasses
ReflectionExtension
PHP Manual

ReflectionExtension::export

(PHP 5, PHP 7)

ReflectionExtension::export — Export

Descrierea

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].

Parametri

name

Reflec?ia ce va fi exportata.

return

Stabilirea valorii TRUE va duce la întoarcerea valorii exportate, ?i nu la emiterea ei. Stabilirea în FALSE (valoarea implicita) va efectua opera?ia opusa.

Valorile întoarse

Daca parametrul return este stabilit în TRUE, atunci valoarea exportata este întoarsa ca un string, în caz contrar este întors NULL.

A se vedea ?i

  • ReflectionExtension::info() - Print extension info

ReflectionExtension::__construct
ReflectionExtension::getClasses
ReflectionExtension


Gets classes

ReflectionExtension::export
ReflectionExtension::getClassNames
ReflectionExtension
PHP Manual

ReflectionExtension::getClasses

(PHP 5, PHP 7)

ReflectionExtension::getClasses — Gets classes

Descrierea

public array ReflectionExtension::getClasses ( void )

Gets a list of classes from an extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array of ReflectionClass objects, one for each class within the extension. If no classes are defined, an empty array is returned.

Exemple

Example #1 ReflectionExtension::getClasses() example

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClasses());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  ["XMLWriter"]=>
  &object(ReflectionClass)#2 (1) {
    ["name"]=>
    string(9) "XMLWriter"
  }
}

A se vedea ?i

  • ReflectionExtension::getClassNames() - Gets class names

ReflectionExtension::export
ReflectionExtension::getClassNames
ReflectionExtension


Gets class names

ReflectionExtension::getClasses
ReflectionExtension::getConstants
ReflectionExtension
PHP Manual

ReflectionExtension::getClassNames

(PHP 5, PHP 7)

ReflectionExtension::getClassNames — Gets class names

Descrierea

public array ReflectionExtension::getClassNames ( void )

Gets a listing of class names as defined in the extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array of class names, as defined in the extension. If no classes are defined, an empty array is returned.

Exemple

Example #1 ReflectionExtension::getClassNames() example

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClassNames());
?>

Exemplul de mai sus va afi?a ceva similar cu:

array(1) {
  [0]=>
  string(9) "XMLWriter"
}

A se vedea ?i

  • 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, PHP 7)

ReflectionExtension::getConstants — Gets constants

Descrierea

public array ReflectionExtension::getConstants ( void )

Get defined constants from an extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An associative array with constant names as keys.

Exemple

Example #1 ReflectionExtension::getConstants() example

<?php
$ext = new ReflectionExtension('DOM');

print_r($ext->getConstants());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • ReflectionExtension::getINIEntries() - Gets extension ini entries

ReflectionExtension::getClassNames
ReflectionExtension::getDependencies
ReflectionExtension


Gets dependencies

ReflectionExtension::getConstants
ReflectionExtension::getFunctions
ReflectionExtension
PHP Manual

ReflectionExtension::getDependencies

(PHP 5, PHP 7)

ReflectionExtension::getDependencies — Gets dependencies

Descrierea

public array ReflectionExtension::getDependencies ( void )

Gets dependencies, by listing both required and conflicting dependencies.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An associative array with dependencies as keys and either Required, Optional or Conflicts as the values.

Exemple

Example #1 ReflectionExtension::getDependencies() example

<?php
$dom = new ReflectionExtension('dom');

print_r($dom->getDependencies());
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [libxml] => Required
    [domxml] => Conflicts
)

A se vedea ?i

  • ReflectionClass::getVersion()

ReflectionExtension::getConstants
ReflectionExtension::getFunctions
ReflectionExtension


Gets extension functions

ReflectionExtension::getDependencies
ReflectionExtension::getINIEntries
ReflectionExtension
PHP Manual

ReflectionExtension::getFunctions

(PHP 5, PHP 7)

ReflectionExtension::getFunctions — Gets extension functions

Descrierea

public array ReflectionExtension::getFunctions ( void )

Get defined functions from an extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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.

Exemple

Example #1 ReflectionExtension::getFunctions() example

<?php
$dom = new ReflectionExtension('SimpleXML');

print_r($dom->getFunctions());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
        )

)

A se vedea ?i

  • ReflectionExtension::getClasses() - Gets classes
  • get_extension_funcs() - Returns an array with the names of the functions of a module

ReflectionExtension::getDependencies
ReflectionExtension::getINIEntries
ReflectionExtension


Gets extension ini entries

ReflectionExtension::getFunctions
ReflectionExtension::getName
ReflectionExtension
PHP Manual

ReflectionExtension::getINIEntries

(PHP 5, PHP 7)

ReflectionExtension::getINIEntries — Gets extension ini entries

Descrierea

public array ReflectionExtension::getINIEntries ( void )

Get the ini entries for an extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An associative array with the ini entries as keys, with their defined values as values.

Exemple

Example #1 ReflectionExtension::getINIEntries() example

<?php
$ext = new ReflectionExtension('mysql');

print_r($ext->getINIEntries());
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
)

A se vedea ?i

  • ini_get_all() - Gets all configuration options
  • ReflectionExtension::getConstants() - Gets constants

ReflectionExtension::getFunctions
ReflectionExtension::getName
ReflectionExtension


Gets extension name

ReflectionExtension::getINIEntries
ReflectionExtension::getVersion
ReflectionExtension
PHP Manual

ReflectionExtension::getName

(PHP 5, PHP 7)

ReflectionExtension::getName — Gets extension name

Descrierea

public string ReflectionExtension::getName ( void )

Gets the extensions name.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The extensions name.

Exemple

Example #1 ReflectionExtension::getName() example

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getName());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(6) "mysqli"

A se vedea ?i

  • ReflectionExtension::getClassNames() - Gets class names

ReflectionExtension::getINIEntries
ReflectionExtension::getVersion
ReflectionExtension


Gets extension version

ReflectionExtension::getName
ReflectionExtension::info
ReflectionExtension
PHP Manual

ReflectionExtension::getVersion

(PHP 5, PHP 7)

ReflectionExtension::getVersion — Gets extension version

Descrierea

public string ReflectionExtension::getVersion ( void )

Gets the version of the extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The version of the extension.

Exemple

Example #1 ReflectionExtension::getVersion() example

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getVersion());
?>

Exemplul de mai sus va afi?a ceva similar cu:

string(3) "0.1"

A se vedea ?i

  • ReflectionExtension::info() - Print extension info

ReflectionExtension::getName
ReflectionExtension::info
ReflectionExtension


Print extension info

ReflectionExtension::getVersion
ReflectionExtension::isPersistent
ReflectionExtension
PHP Manual

ReflectionExtension::info

(PHP 5, PHP 7)

ReflectionExtension::info — Print extension info

Descrierea

public void ReflectionExtension::info ( void )

Prints out the "phpinfo()" snippet for the given extension.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Information about the extension.

Exemple

Example #1 ReflectionExtension::info() example

<?php
$ext = new ReflectionExtension('mysqli');
$ext->info();
?>

Exemplul de mai sus va afi?a ceva similar cu:

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

A se vedea ?i

  • 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

Descrierea

public void ReflectionExtension::isPersistent ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE for extensions loaded by extension, FALSE otherwise.

A se vedea ?i

  • 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

Descrierea

public void ReflectionExtension::isTemporary ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE for extensions loaded by dl(), FALSE otherwise.

A se vedea ?i

  • 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, PHP 7)

ReflectionExtension::__toString — To string

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the exported extension as a string, in the same way as the ReflectionExtension::export().

A se vedea ?i

  • ReflectionExtension::__construct() - Constructs a ReflectionExtension
  • ReflectionExtension::export() - Export
  • __toString()

ReflectionExtension::isTemporary
ReflectionFunction
ReflectionExtension


The ReflectionFunction class

(PHP 5, PHP 7)

Introducere

The ReflectionFunction class reports information about a function.

Sinopsisul clasei

ReflectionFunction extends ReflectionFunctionAbstract implements Reflector {
/* Constante */
const integer IS_DEPRECATED = 262144 ;
/* Proprieta?i */
public $name ;
/* Metode */
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 )
/* Metode mo?tenite */
final private void ReflectionFunctionAbstract::__clone ( void )
public ReflectionClass ReflectionFunctionAbstract::getClosureScopeClass ( 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 ReflectionType ReflectionFunctionAbstract::getReturnType ( void )
public string ReflectionFunctionAbstract::getShortName ( void )
public int ReflectionFunctionAbstract::getStartLine ( void )
public array ReflectionFunctionAbstract::getStaticVariables ( void )
public bool ReflectionFunctionAbstract::hasReturnType ( void )
public bool ReflectionFunctionAbstract::inNamespace ( void )
public bool ReflectionFunctionAbstract::isClosure ( void )
public bool ReflectionFunctionAbstract::isDeprecated ( void )
public bool ReflectionFunctionAbstract::isGenerator ( void )
public bool ReflectionFunctionAbstract::isInternal ( void )
public bool ReflectionFunctionAbstract::isUserDefined ( void )
public bool ReflectionFunctionAbstract::isVariadic ( void )
public bool ReflectionFunctionAbstract::returnsReference ( void )
abstract public void ReflectionFunctionAbstract::__toString ( void )
}

Proprieta?i

name

Name of the function. Read-only, throws ReflectionException in attempt to write.

Constante predefinite

ReflectionFunction Modifiers

ReflectionFunction::IS_DEPRECATED

Indicates deprecated functions.

Cuprins

  • 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, PHP 7)

ReflectionFunction::__construct — Constructs a ReflectionFunction object

Descrierea

public ReflectionFunction::__construct ( mixed $name )

Constructs a ReflectionFunction object.

Parametri

name

The name of the function to reflect or a closure.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

A ReflectionException if the name parameter does not contain a valid function.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | name can now be a closure.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

===> 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,
)

A se vedea ?i

  • ReflectionMethod::__construct() - Constructs a ReflectionMethod
  • Constructors

ReflectionFunction
ReflectionFunction::export
ReflectionFunction


Exports function

ReflectionFunction::__construct
ReflectionFunction::getClosure
ReflectionFunction
PHP Manual

ReflectionFunction::export

(PHP 5, PHP 7)

ReflectionFunction::export — Exports function

Descrierea

public static string ReflectionFunction::export ( string $name [, string $return ] )

Exports a Reflected function.

Parametri

name

Reflec?ia ce va fi exportata.

return

Stabilirea valorii TRUE va duce la întoarcerea valorii exportate, ?i nu la emiterea ei. Stabilirea în FALSE (valoarea implicita) va efectua opera?ia opusa.

Valorile întoarse

Daca parametrul return este stabilit în TRUE, atunci valoarea exportata este întoarsa ca un string, în caz contrar este întors NULL.

A se vedea ?i

  • 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

(PHP >= 5.4.0)

ReflectionFunction::getClosure — Returns a dynamically created closure for the function

Descrierea

public Closure ReflectionFunction::getClosure ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

ReflectionFunction::invoke — Invokes function

Descrierea

public mixed ReflectionFunction::invoke ([ mixed $parameter [, mixed $... ]] )

Invokes a reflected function.

Parametri

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.

Valorile întoarse

Returns the result of the invoked function call.

Exemple

Example #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');
?>

Exemplul de mai sus va afi?a:

Dr. Phil

Note

Nota:

Daca func?ia are argumente ce trebuie sa fie referin?e, atunci ele trebuie sa fie ca referin?e ?i în lista argumentelor transmise.

A se vedea ?i

  • 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, PHP 7)

ReflectionFunction::invokeArgs — Invokes function args

Descrierea

public mixed ReflectionFunction::invokeArgs ( array $args )

Invokes the function and pass its arguments as array.

Parametri

args

The passed arguments to the function as an array, much like call_user_func_array() works.

Valorile întoarse

Returns the result of the invoked function

Exemple

Example #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'));
?>

Exemplul de mai sus va afi?a:

Dr. Phil

Example #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);
?>

Exemplul de mai sus va afi?a:

array(2) {
  [0]=>
  bool(false)
  [1]=>
  int(0)
}

Note

Nota:

Daca func?ia are argumente ce trebuie sa fie referin?e, atunci ele trebuie sa fie ca referin?e ?i în lista argumentelor transmise.

A se vedea ?i

  • 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, PHP 7)

ReflectionFunction::isDisabled — Checks if function is disabled

Descrierea

public bool ReflectionFunction::isDisabled ( void )

Checks if the function is disabled, via the disable_functions directive.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if it's disable, otherwise FALSE

A se vedea ?i

  • 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, PHP 7)

ReflectionFunction::__toString — To string

Descrierea

public string ReflectionFunction::__toString ( void )

To string.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns ReflectionFunction::export()-like output for the function.

Exemple

Example #1 ReflectionFunction::__toString() example

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

echo new ReflectionFunction('title');
?>

Exemplul de mai sus va afi?a ceva similar cu:

Function [ <user> function title ] {
  @@ Command line code 1 - 1

  - Parameters [2] {
    Parameter #0 [ <required> $title ]
    Parameter #1 [ <required> $name ]
  }
}

A se vedea ?i

  • ReflectionFunction::export() - Exports function
  • ReflectionClass::clone()
  • __toString()

ReflectionFunction::isDisabled
ReflectionFunctionAbstract
ReflectionFunction


The ReflectionFunctionAbstract class

(PHP 5, PHP 7)

Introducere

A parent class to ReflectionFunction, read its description for details.

Sinopsisul clasei

ReflectionFunctionAbstract implements Reflector {
/* Proprieta?i */
public $name ;
/* Metode */
final private void __clone ( void )
public ReflectionClass getClosureScopeClass ( 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 ReflectionType getReturnType ( void )
public string getShortName ( void )
public int getStartLine ( void )
public array getStaticVariables ( void )
public bool hasReturnType ( void )
public bool inNamespace ( void )
public bool isClosure ( void )
public bool isDeprecated ( void )
public bool isGenerator ( void )
public bool isInternal ( void )
public bool isUserDefined ( void )
public bool isVariadic ( void )
public bool returnsReference ( void )
abstract public void __toString ( void )
}

Proprieta?i

name

Name of the function. Read-only, throws ReflectionException in attempt to write.

Cuprins

  • ReflectionFunctionAbstract::__clone — Clones function
  • ReflectionFunctionAbstract::getClosureScopeClass — Returns the scope associated to the closure
  • 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::getReturnType — Gets the specified return type of a function
  • ReflectionFunctionAbstract::getShortName — Gets function short name
  • ReflectionFunctionAbstract::getStartLine — Gets starting line number
  • ReflectionFunctionAbstract::getStaticVariables — Gets static variables
  • ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type
  • ReflectionFunctionAbstract::inNamespace — Checks if function in namespace
  • ReflectionFunctionAbstract::isClosure — Checks if closure
  • ReflectionFunctionAbstract::isDeprecated — Checks if deprecated
  • ReflectionFunctionAbstract::isGenerator — Returns whether this function is a generator
  • ReflectionFunctionAbstract::isInternal — Checks if is internal
  • ReflectionFunctionAbstract::isUserDefined — Checks if user defined
  • ReflectionFunctionAbstract::isVariadic — Checks if the function is variadic
  • ReflectionFunctionAbstract::returnsReference — Checks if returns reference
  • ReflectionFunctionAbstract::__toString — To string
ReflectionFunction::__toString
ReflectionFunctionAbstract::__clone
Reflection


Clones function

ReflectionFunctionAbstract
ReflectionFunctionAbstract::getClosureScopeClass
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::__clone

(PHP 5, PHP 7)

ReflectionFunctionAbstract::__clone — Clones function

Descrierea

final private void ReflectionFunctionAbstract::__clone ( void )

Clones a function.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • Object cloning

ReflectionFunctionAbstract
ReflectionFunctionAbstract::getClosureScopeClass
ReflectionFunctionAbstract


Returns the scope associated to the closure

ReflectionFunctionAbstract::__clone
ReflectionFunctionAbstract::getClosureThis
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getClosureScopeClass

(PHP >= 5.4.0)

ReflectionFunctionAbstract::getClosureScopeClass — Returns the scope associated to the closure

Descrierea

public ReflectionClass ReflectionFunctionAbstract::getClosureScopeClass ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the class on success or NULL on failure.

ReflectionFunctionAbstract::__clone
ReflectionFunctionAbstract::getClosureThis
ReflectionFunctionAbstract


Returns this pointer bound to closure

ReflectionFunctionAbstract::getClosureScopeClass
ReflectionFunctionAbstract::getDocComment
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getClosureThis

(PHP >= 5.4.0)

ReflectionFunctionAbstract::getClosureThis — Returns this pointer bound to closure

Descrierea

public object ReflectionFunctionAbstract::getClosureThis ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns $this pointer. Returns NULL in case of an error.

ReflectionFunctionAbstract::getClosureScopeClass
ReflectionFunctionAbstract::getDocComment
ReflectionFunctionAbstract


Gets doc comment

ReflectionFunctionAbstract::getClosureThis
ReflectionFunctionAbstract::getEndLine
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getDocComment

(PHP 5 >= 5.1.0, PHP 7)

ReflectionFunctionAbstract::getDocComment — Gets doc comment

Descrierea

public string ReflectionFunctionAbstract::getDocComment ( void )

Get a Doc comment from a function.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The doc comment if it exists, otherwise FALSE

A se vedea ?i

  • 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, PHP 7)

ReflectionFunctionAbstract::getEndLine — Gets end line number

Descrierea

public int ReflectionFunctionAbstract::getEndLine ( void )

Get the ending line number.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The ending line number of the user defined function, or FALSE if unknown.

A se vedea ?i

  • 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, PHP 7)

ReflectionFunctionAbstract::getExtension — Gets extension info

Descrierea

public ReflectionExtension ReflectionFunctionAbstract::getExtension ( void )

Get the extension information of a function.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The extension information, as a ReflectionExtension object.

A se vedea ?i

  • ReflectionFunctionAbstract::getExtensionName() - Gets extension name

ReflectionFunctionAbstract::getEndLine
ReflectionFunctionAbstract::getExtensionName
ReflectionFunctionAbstract


Gets extension name

ReflectionFunctionAbstract::getExtension
ReflectionFunctionAbstract::getFileName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getExtensionName

(PHP 5, PHP 7)

ReflectionFunctionAbstract::getExtensionName — Gets extension name

Descrierea

public string ReflectionFunctionAbstract::getExtensionName ( void )

Get the extensions name.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The extensions name.

A se vedea ?i

  • ReflectionFunctionAbstract::getExtension() - Gets extension info

ReflectionFunctionAbstract::getExtension
ReflectionFunctionAbstract::getFileName
ReflectionFunctionAbstract


Gets file name

ReflectionFunctionAbstract::getExtensionName
ReflectionFunctionAbstract::getName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getFileName

(PHP 5, PHP 7)

ReflectionFunctionAbstract::getFileName — Gets file name

Descrierea

public string ReflectionFunctionAbstract::getFileName ( void )

Gets the file name from a user-defined function.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The file name.

A se vedea ?i

  • ReflectionFunctionAbstract::getNamespaceName() - Gets namespace name

ReflectionFunctionAbstract::getExtensionName
ReflectionFunctionAbstract::getName
ReflectionFunctionAbstract


Gets function name

ReflectionFunctionAbstract::getFileName
ReflectionFunctionAbstract::getNamespaceName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getName

(PHP 5, PHP 7)

ReflectionFunctionAbstract::getName — Gets function name

Descrierea

public string ReflectionFunctionAbstract::getName ( void )

Get the name of the function.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The name of the function.

A se vedea ?i

  • 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, PHP 7)

ReflectionFunctionAbstract::getNamespaceName — Gets namespace name

Descrierea

public string ReflectionFunctionAbstract::getNamespaceName ( void )

Get the namespace name where the class is defined.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The namespace name.

A se vedea ?i

  • 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, PHP 7)

ReflectionFunctionAbstract::getNumberOfParameters — Gets number of parameters

Descrierea

public int ReflectionFunctionAbstract::getNumberOfParameters ( void )

Get the number of parameters that a function defines, both optional and required.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The number of parameters.

A se vedea ?i

  • 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, PHP 7)

ReflectionFunctionAbstract::getNumberOfRequiredParameters — Gets number of required parameters

Descrierea

public int ReflectionFunctionAbstract::getNumberOfRequiredParameters ( void )

Get the number of required parameters that a function defines.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The number of required parameters.

A se vedea ?i

  • ReflectionFunctionAbstract::getNumberOfParameters() - Gets number of parameters

ReflectionFunctionAbstract::getNumberOfParameters
ReflectionFunctionAbstract::getParameters
ReflectionFunctionAbstract


Gets parameters

ReflectionFunctionAbstract::getNumberOfRequiredParameters
ReflectionFunctionAbstract::getReturnType
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getParameters

(PHP 5, PHP 7)

ReflectionFunctionAbstract::getParameters — Gets parameters

Descrierea

public array ReflectionFunctionAbstract::getParameters ( void )

Get the parameters as an array of ReflectionParameter.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The parameters, as a ReflectionParameter object.

A se vedea ?i

  • ReflectionFunctionAbstract::getNumberOfParameters() - Gets number of parameters
  • func_get_args() - Returns an array comprising a function's argument list

ReflectionFunctionAbstract::getNumberOfRequiredParameters
ReflectionFunctionAbstract::getReturnType
ReflectionFunctionAbstract


Gets the specified return type of a function

ReflectionFunctionAbstract::getParameters
ReflectionFunctionAbstract::getShortName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getReturnType

(PHP 7)

ReflectionFunctionAbstract::getReturnType — Gets the specified return type of a function

Descrierea

public ReflectionType ReflectionFunctionAbstract::getReturnType ( void )

Gets the specified return type of a reflected function.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a ReflectionType object if a return type is specified, NULL otherwise.

Exemple

Example #1 ReflectionFunctionAbstract::getReturnType() example

<?php

function to_int($param) : int {
    return (int) $param;
}

$reflection1 = new ReflectionFunction('to_int');
echo $reflection1->getReturnType();

Exemplul de mai sus va afi?a:

int

Example #2 Usage on built-in functions

<?php

$reflection2 = new ReflectionFunction('array_merge');

var_dump($reflection2->getReturnType());

Exemplul de mai sus va afi?a:

null

This is because many internal functions do not have types specified for their parameters or return values. It is therefore best to avoid using this method on built-in functions.

A se vedea ?i

  • ReflectionFunctionAbstract::hasReturnType() - Checks if the function has a specified return type
  • ReflectionType::__toString() - To string

ReflectionFunctionAbstract::getParameters
ReflectionFunctionAbstract::getShortName
ReflectionFunctionAbstract


Gets function short name

ReflectionFunctionAbstract::getReturnType
ReflectionFunctionAbstract::getStartLine
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getShortName

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::getShortName — Gets function short name

Descrierea

public string ReflectionFunctionAbstract::getShortName ( void )

Get the short name of the function (without the namespace part).

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The short name of the function.

A se vedea ?i

  • ReflectionFunctionAbstract::getNamespaceName() - Gets namespace name
  • namespaces

ReflectionFunctionAbstract::getReturnType
ReflectionFunctionAbstract::getStartLine
ReflectionFunctionAbstract


Gets starting line number

ReflectionFunctionAbstract::getShortName
ReflectionFunctionAbstract::getStaticVariables
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getStartLine

(PHP 5, PHP 7)

ReflectionFunctionAbstract::getStartLine — Gets starting line number

Descrierea

public int ReflectionFunctionAbstract::getStartLine ( void )

Gets the starting line number of the function.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The starting line number.

A se vedea ?i

  • ReflectionFunctionAbstract::getEndLine() - Gets end line number

ReflectionFunctionAbstract::getShortName
ReflectionFunctionAbstract::getStaticVariables
ReflectionFunctionAbstract


Gets static variables

ReflectionFunctionAbstract::getStartLine
ReflectionFunctionAbstract::hasReturnType
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getStaticVariables

(PHP 5, PHP 7)

ReflectionFunctionAbstract::getStaticVariables — Gets static variables

Descrierea

public array ReflectionFunctionAbstract::getStaticVariables ( void )

Get the static variables.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array of static variables.

A se vedea ?i

  • ReflectionFunctionAbstract::getParameters() - Gets parameters

ReflectionFunctionAbstract::getStartLine
ReflectionFunctionAbstract::hasReturnType
ReflectionFunctionAbstract


Checks if the function has a specified return type

ReflectionFunctionAbstract::getStaticVariables
ReflectionFunctionAbstract::inNamespace
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::hasReturnType

(PHP 7)

ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type

Descrierea

public bool ReflectionFunctionAbstract::hasReturnType ( void )

Checks whether the reflected function has a return type specified.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the function is a specified return type, otherwise FALSE.

Exemple

Example #1 ReflectionFunctionAbstract::hasReturnType() example

<?php

function to_int($param) : int {
    return (int) $param;
}

$reflection1 = new ReflectionFunction('to_int');
var_dump($reflection1->hasReturnType());

Exemplul de mai sus va afi?a:

bool(true)

Example #2 Usage on built-in functions

<?php

$reflection2 = new ReflectionFunction('array_merge');

var_dump($reflection2->hasReturnType());

Exemplul de mai sus va afi?a:

bool(false)

This is because many internal functions do not have types specified for their parameters or return values. It is therefore best to avoid using this method on built-in functions.

A se vedea ?i

  • ReflectionFunctionAbstract::getReturnType() - Gets the specified return type of a function

ReflectionFunctionAbstract::getStaticVariables
ReflectionFunctionAbstract::inNamespace
ReflectionFunctionAbstract


Checks if function in namespace

ReflectionFunctionAbstract::hasReturnType
ReflectionFunctionAbstract::isClosure
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::inNamespace

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::inNamespace — Checks if function in namespace

Descrierea

public bool ReflectionFunctionAbstract::inNamespace ( void )

Checks whether a function is defined in a namespace.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if it's in a namespace, otherwise FALSE

A se vedea ?i

  • ReflectionFunctionAbstract::getNamespaceName() - Gets namespace name
  • namespaces

ReflectionFunctionAbstract::hasReturnType
ReflectionFunctionAbstract::isClosure
ReflectionFunctionAbstract


Checks if closure

ReflectionFunctionAbstract::inNamespace
ReflectionFunctionAbstract::isDeprecated
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isClosure

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::isClosure — Checks if closure

Descrierea

public bool ReflectionFunctionAbstract::isClosure ( void )

Checks whether the reflected function is a Closure.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the function is a Closure, otherwise FALSE.

Exemple

Example #1 ReflectionFunctionAbstract::isClosure() example

<?php
// Non-closure
$function1 = 'str_replace';
$reflection1 = new ReflectionFunction($function1);
var_dump($reflection1->isClosure());

// Closure
$function2 = function () {};
$reflection2 = new ReflectionFunction($function2);
var_dump($reflection2->isClosure());
?>

Exemplul de mai sus va afi?a:

bool(false)
bool(true)

A se vedea ?i

  • ReflectionFunctionAbstract::isGenerator() - Returns whether this function is a generator

ReflectionFunctionAbstract::inNamespace
ReflectionFunctionAbstract::isDeprecated
ReflectionFunctionAbstract


Checks if deprecated

ReflectionFunctionAbstract::isClosure
ReflectionFunctionAbstract::isGenerator
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isDeprecated

(PHP 5, PHP 7)

ReflectionFunctionAbstract::isDeprecated — Checks if deprecated

Descrierea

public bool ReflectionFunctionAbstract::isDeprecated ( void )

Checks whether the function is deprecated.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if it's deprecated, otherwise FALSE

Exemple

Example #1 ReflectionFunctionAbstract::isDeprecated() example

<?php
$rf = new ReflectionFunction('ereg');
var_dump($rf->isDeprecated());
?>

Exemplul de mai sus va afi?a:

bool(true)

A se vedea ?i

  • ReflectionFunctionAbstract::getDocComment() - Gets doc comment

ReflectionFunctionAbstract::isClosure
ReflectionFunctionAbstract::isGenerator
ReflectionFunctionAbstract


Returns whether this function is a generator

ReflectionFunctionAbstract::isDeprecated
ReflectionFunctionAbstract::isInternal
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isGenerator

(PHP 5 >= 5.5.0, PHP 7)

ReflectionFunctionAbstract::isGenerator — Returns whether this function is a generator

Descrierea

public bool ReflectionFunctionAbstract::isGenerator ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the function is generator, FALSE if it is not or NULL on failure.

ReflectionFunctionAbstract::isDeprecated
ReflectionFunctionAbstract::isInternal
ReflectionFunctionAbstract


Checks if is internal

ReflectionFunctionAbstract::isGenerator
ReflectionFunctionAbstract::isUserDefined
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isInternal

(PHP 5, PHP 7)

ReflectionFunctionAbstract::isInternal — Checks if is internal

Descrierea

public bool ReflectionFunctionAbstract::isInternal ( void )

Checks whether the function is internal, as opposed to user-defined.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if it's internal, otherwise FALSE

A se vedea ?i

  • ReflectionFunctionAbstract::isUserDefined() - Checks if user defined

ReflectionFunctionAbstract::isGenerator
ReflectionFunctionAbstract::isUserDefined
ReflectionFunctionAbstract


Checks if user defined

ReflectionFunctionAbstract::isInternal
ReflectionFunctionAbstract::isVariadic
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isUserDefined

(PHP 5, PHP 7)

ReflectionFunctionAbstract::isUserDefined — Checks if user defined

Descrierea

public bool ReflectionFunctionAbstract::isUserDefined ( void )

Checks whether the function is user-defined, as opposed to internal.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if it's user-defined, otherwise false;

A se vedea ?i

  • ReflectionFunctionAbstract::isInternal() - Checks if is internal

ReflectionFunctionAbstract::isInternal
ReflectionFunctionAbstract::isVariadic
ReflectionFunctionAbstract


Checks if the function is variadic

ReflectionFunctionAbstract::isUserDefined
ReflectionFunctionAbstract::returnsReference
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isVariadic

(PHP 5 >= 5.6.0, PHP 7)

ReflectionFunctionAbstract::isVariadic — Checks if the function is variadic

Descrierea

public bool ReflectionFunctionAbstract::isVariadic ( void )

Checks if the function is variadic.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the function is variadic, otherwise FALSE.

ReflectionFunctionAbstract::isUserDefined
ReflectionFunctionAbstract::returnsReference
ReflectionFunctionAbstract


Checks if returns reference

ReflectionFunctionAbstract::isVariadic
ReflectionFunctionAbstract::__toString
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::returnsReference

(PHP 5, PHP 7)

ReflectionFunctionAbstract::returnsReference — Checks if returns reference

Descrierea

public bool ReflectionFunctionAbstract::returnsReference ( void )

Checks whether the function returns a reference.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if it returns a reference, otherwise FALSE

A se vedea ?i

  • ReflectionFunctionAbstract::isClosure() - Checks if closure

ReflectionFunctionAbstract::isVariadic
ReflectionFunctionAbstract::__toString
ReflectionFunctionAbstract


To string

ReflectionFunctionAbstract::returnsReference
ReflectionMethod
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::__toString

(PHP 5, PHP 7)

ReflectionFunctionAbstract::__toString — To string

Descrierea

abstract public void ReflectionFunctionAbstract::__toString ( void )

To string.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The string.

A se vedea ?i

  • ReflectionClass::clone()
  • __toString()

ReflectionFunctionAbstract::returnsReference
ReflectionMethod
ReflectionFunctionAbstract


The ReflectionMethod class

(PHP 5, PHP 7)

Introducere

The ReflectionMethod class reports information about a method.

Sinopsisul clasei

ReflectionMethod extends ReflectionFunctionAbstract implements Reflector {
/* Constante */
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 ;
/* Proprieta?i */
public $name ;
public $class ;
/* Metode */
public __construct ( mixed $class , string $name )
public static string export ( string $class , string $name [, bool $return = false ] )
public Closure getClosure ( object $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 )
/* Metode mo?tenite */
final private void ReflectionFunctionAbstract::__clone ( void )
public ReflectionClass ReflectionFunctionAbstract::getClosureScopeClass ( 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 ReflectionType ReflectionFunctionAbstract::getReturnType ( void )
public string ReflectionFunctionAbstract::getShortName ( void )
public int ReflectionFunctionAbstract::getStartLine ( void )
public array ReflectionFunctionAbstract::getStaticVariables ( void )
public bool ReflectionFunctionAbstract::hasReturnType ( void )
public bool ReflectionFunctionAbstract::inNamespace ( void )
public bool ReflectionFunctionAbstract::isClosure ( void )
public bool ReflectionFunctionAbstract::isDeprecated ( void )
public bool ReflectionFunctionAbstract::isGenerator ( void )
public bool ReflectionFunctionAbstract::isInternal ( void )
public bool ReflectionFunctionAbstract::isUserDefined ( void )
public bool ReflectionFunctionAbstract::isVariadic ( void )
public bool ReflectionFunctionAbstract::returnsReference ( void )
abstract public void ReflectionFunctionAbstract::__toString ( void )
}

Proprieta?i

name

Method name

class

Class name

Constante predefinite

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.

Cuprins

  • 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, PHP 7)

ReflectionMethod::__construct — Constructs a ReflectionMethod

Descrierea

public ReflectionMethod::__construct ( mixed $class , string $name )
public ReflectionMethod::__construct ( string $class_method )

Constructs a new ReflectionMethod.

Parametri

class

Classname or object (instance of the class) that contains the method.

name

Name of the method.

class_method

Class name and method name delimited by ::.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

A ReflectionException is thrown if the given method does not exist.

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a ceva similar cu:

===> 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)

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::export — Export a reflection method.

Descrierea

public static string ReflectionMethod::export ( string $class , string $name [, bool $return = false ] )

Exports a ReflectionMethod.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

class

The class name.

name

The name of the method.

return

Stabilirea valorii TRUE va duce la întoarcerea valorii exportate, ?i nu la emiterea ei. Stabilirea în FALSE (valoarea implicita) va efectua opera?ia opusa.

Valorile întoarse

Daca parametrul return este stabilit în TRUE, atunci valoarea exportata este întoarsa ca un string, în caz contrar este întors NULL.

A se vedea ?i

  • 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

Descrierea

public Closure ReflectionMethod::getClosure ( object $object )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

object

Forbidden for static methods, required for other methods.

Valorile întoarse

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, PHP 7)

ReflectionMethod::getDeclaringClass — Gets declaring class for the reflected method.

Descrierea

public ReflectionClass ReflectionMethod::getDeclaringClass ( void )

Gets the declaring class for the reflected method.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A ReflectionClass object of the class that the reflected method is part of.

Exemple

Example #1 ReflectionMethod::getDeclaringClass() example

<?php
class HelloWorld {

    protected function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod(new HelloWorld(), 'sayHelloTo');
var_dump($reflectionMethod->getDeclaringClass());
?>

Exemplul de mai sus va afi?a:

object(ReflectionClass)#2 (1) {
  ["name"]=>
  string(10) "HelloWorld"
}

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::getModifiers — Gets the method modifiers

Descrierea

public int ReflectionMethod::getModifiers ( void )

Returns a bitfield of the access modifiers for this method.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A numeric representation of the modifiers. The modifiers are listed below. The actual meanings of these modifiers are described in the predefined constants.

Exemple

Example #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()));
?>

Exemplul de mai sus va afi?a ceva similar cu:

Modifiers for method foo():
261
final public static
Modifiers for method bar():
65792
public

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::getPrototype — Gets the method prototype (if there is one).

Descrierea

public ReflectionMethod ReflectionMethod::getPrototype ( void )

Returns the methods prototype.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A ReflectionMethod instance of the method prototype.

Erori/Excep?ii

A ReflectionException exception is thrown if the method does not have a prototype.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(10) "sayHelloTo"
  ["class"]=>
  string(5) "Hello"
}

A se vedea ?i

  • ReflectionMethod::getModifiers() - Gets the method modifiers

ReflectionMethod::getModifiers
ReflectionMethod::invoke
ReflectionMethod


Invoke

ReflectionMethod::getPrototype
ReflectionMethod::invokeArgs
ReflectionMethod
PHP Manual

ReflectionMethod::invoke

(PHP 5, PHP 7)

ReflectionMethod::invoke — Invoke

Descrierea

public mixed ReflectionMethod::invoke ( object $object [, mixed $parameter [, mixed $... ]] )

Invokes a reflected method.

Parametri

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.

Valorile întoarse

Returns the method result.

Erori/Excep?ii

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.

Exemple

Example #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');
?>

Exemplul de mai sus va afi?a:

Hello Mike

Note

Nota:

Daca func?ia are argumente ce trebuie sa fie referin?e, atunci ele trebuie sa fie ca referin?e ?i în lista argumentelor transmise.

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::invokeArgs — Invoke args

Descrierea

public mixed ReflectionMethod::invokeArgs ( object $object , array $args )

Invokes the reflected method and pass its arguments as array.

Parametri

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.

Valorile întoarse

Returns the method result.

Erori/Excep?ii

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.

Exemple

Example #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'));
?>

Exemplul de mai sus va afi?a:

Hello Mike

Note

Nota:

Daca func?ia are argumente ce trebuie sa fie referin?e, atunci ele trebuie sa fie ca referin?e ?i în lista argumentelor transmise.

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::isAbstract — Checks if method is abstract

Descrierea

public bool ReflectionMethod::isAbstract ( void )

Checks if the method is abstract.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the method is abstract, otherwise FALSE

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::isConstructor — Checks if method is a constructor

Descrierea

public bool ReflectionMethod::isConstructor ( void )

Checks if the method is a constructor.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the method is a constructor, otherwise FALSE

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::isDestructor — Checks if method is a destructor

Descrierea

public bool ReflectionMethod::isDestructor ( void )

Checks if the method is a destructor.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the method is a destructor, otherwise FALSE

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::isFinal — Checks if method is final

Descrierea

public bool ReflectionMethod::isFinal ( void )

Checks if the method is final.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the method is final, otherwise FALSE

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::isPrivate — Checks if method is private

Descrierea

public bool ReflectionMethod::isPrivate ( void )

Checks if the method is private.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the method is private, otherwise FALSE

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::isProtected — Checks if method is protected

Descrierea

public bool ReflectionMethod::isProtected ( void )

Checks if the method is protected.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the method is protected, otherwise FALSE

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::isPublic — Checks if method is public

Descrierea

public bool ReflectionMethod::isPublic ( void )

Checks if the method is public.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the method is public, otherwise FALSE

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::isStatic — Checks if method is static

Descrierea

public bool ReflectionMethod::isStatic ( void )

Checks if the method is static.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the method is static, otherwise FALSE

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::setAccessible — Set method accessibility

Descrierea

public void ReflectionMethod::setAccessible ( bool $accessible )

Sets a method to be accessible. For example, it may allow protected and private methods to be invoked.

Parametri

accessible

TRUE to allow accessibility, or FALSE.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

ReflectionMethod::__toString — Returns the string representation of the Reflection method object.

Descrierea

public string ReflectionMethod::__toString ( void )

Returns the string representation of the Reflection method object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A string representation of this ReflectionMethod instance.

Exemple

Example #1 ReflectionMethod::__toString() example

<?php
class HelloWorld {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod(new HelloWorld(), 'sayHelloTo');
echo $reflectionMethod;
?>

Exemplul de mai sus va afi?a:

Method [ <user> public method sayHelloTo ] {
  @@ /var/www/examples/reflection.php 16 - 18

  - Parameters [1] {
    Parameter #0 [ <required> $name ]
  }
}

A se vedea ?i

  • ReflectionMethod::export() - Export a reflection method.
  • __toString()

ReflectionMethod::setAccessible
ReflectionObject
ReflectionMethod


The ReflectionObject class

(PHP 5, PHP 7)

Introducere

The ReflectionObject class reports information about an object.

Sinopsisul clasei

ReflectionObject extends ReflectionClass implements Reflector {
/* Constante */
const integer IS_IMPLICIT_ABSTRACT = 16 ;
const integer IS_EXPLICIT_ABSTRACT = 32 ;
const integer IS_FINAL = 64 ;
/* Proprieta?i */
public $name ;
/* Metode */
public __construct ( object $argument )
public static string export ( string $argument [, bool $return ] )
/* Metode mo?tenite */
public 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 ReflectionMethod 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 ([ int $filter ] )
public int ReflectionClass::getModifiers ( void )
public string ReflectionClass::getName ( void )
public string ReflectionClass::getNamespaceName ( void )
public ReflectionClass 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 [, mixed &$def_value ] )
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::isAnonymous ( 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 )
}

Proprieta?i

name

Name of the object's class. Read-only, throws ReflectionException in attempt to write.

Cuprins

  • 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, PHP 7)

ReflectionObject::__construct — Constructs a ReflectionObject

Descrierea

public ReflectionObject::__construct ( object $argument )

Constructs a ReflectionObject.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

argument

An object instance.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • ReflectionObject::export() - Export
  • Constructors

ReflectionObject
ReflectionObject::export
ReflectionObject


Export

ReflectionObject::__construct
ReflectionParameter
ReflectionObject
PHP Manual

ReflectionObject::export

(PHP 5, PHP 7)

ReflectionObject::export — Export

Descrierea

public static string ReflectionObject::export ( string $argument [, bool $return ] )

Exports a reflection.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

argument

Reflec?ia ce va fi exportata.

return

Stabilirea valorii TRUE va duce la întoarcerea valorii exportate, ?i nu la emiterea ei. Stabilirea în FALSE (valoarea implicita) va efectua opera?ia opusa.

Valorile întoarse

Daca parametrul return este stabilit în TRUE, atunci valoarea exportata este întoarsa ca un string, în caz contrar este întors NULL.

A se vedea ?i

  • ReflectionObject::__construct() - Constructs a ReflectionObject

ReflectionObject::__construct
ReflectionParameter
ReflectionObject


The ReflectionParameter class

(PHP 5, PHP 7)

Introducere

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.

Sinopsisul clasei

ReflectionParameter implements Reflector {
/* Proprieta?i */
public $name ;
/* Metode */
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 ReflectionFunctionAbstract getDeclaringFunction ( void )
public mixed getDefaultValue ( void )
public string getDefaultValueConstantName ( void )
public string getName ( void )
public int getPosition ( void )
public ReflectionType getType ( void )
public bool hasType ( void )
public bool isArray ( void )
public bool isCallable ( void )
public bool isDefaultValueAvailable ( void )
public bool isDefaultValueConstant ( void )
public bool isOptional ( void )
public bool isPassedByReference ( void )
public bool isVariadic ( void )
public string __toString ( void )
}

Proprieta?i

name

Name of the parameter. Read-only, throws ReflectionException in attempt to write.

Cuprins

  • 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 the type hinted class
  • ReflectionParameter::getDeclaringClass — Gets declaring class
  • ReflectionParameter::getDeclaringFunction — Gets declaring function
  • ReflectionParameter::getDefaultValue — Gets default parameter value
  • ReflectionParameter::getDefaultValueConstantName — Returns the default value's constant name if default value is constant or null
  • ReflectionParameter::getName — Gets parameter name
  • ReflectionParameter::getPosition — Gets parameter position
  • ReflectionParameter::getType — Gets a parameter's type
  • ReflectionParameter::hasType — Checks if parameter has a type
  • ReflectionParameter::isArray — Checks if parameter expects an array
  • ReflectionParameter::isCallable — Returns whether parameter MUST be callable
  • ReflectionParameter::isDefaultValueAvailable — Checks if a default value is available
  • ReflectionParameter::isDefaultValueConstant — Returns whether the default value of this parameter is constant
  • ReflectionParameter::isOptional — Checks if optional
  • ReflectionParameter::isPassedByReference — Checks if passed by reference
  • ReflectionParameter::isVariadic — Checks if the parameter is variadic
  • ReflectionParameter::__toString — To string
ReflectionObject::export
ReflectionParameter::allowsNull
Reflection


Checks if null is allowed

ReflectionParameter
ReflectionParameter::canBePassedByValue
ReflectionParameter
PHP Manual

ReflectionParameter::allowsNull

(PHP 5, PHP 7)

ReflectionParameter::allowsNull — Checks if null is allowed

Descrierea

public bool ReflectionParameter::allowsNull ( void )

Checks whether the parameter allows NULL.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if NULL is allowed, otherwise FALSE

A se vedea ?i

  • 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

Descrierea

public bool ReflectionParameter::canBePassedByValue ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

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, PHP 7)

ReflectionParameter::__clone — Clone

Descrierea

final private void ReflectionParameter::__clone ( void )

Clones.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • ReflectionParameter::toString()
  • Object cloning

ReflectionParameter::canBePassedByValue
ReflectionParameter::__construct
ReflectionParameter


Construct

ReflectionParameter::__clone
ReflectionParameter::export
ReflectionParameter
PHP Manual

ReflectionParameter::__construct

(PHP 5, PHP 7)

ReflectionParameter::__construct — Construct

Descrierea

public ReflectionParameter::__construct ( string $function , string $parameter )

Constructs a ReflectionParameter class.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

function

The function to reflect parameters from.

parameter

The parameter.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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'
    );
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

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
}

A se vedea ?i

  • 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, PHP 7)

ReflectionParameter::export — Exports

Descrierea

public static string ReflectionParameter::export ( string $function , string $parameter [, bool $return ] )

Exports.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

function

The function name.

parameter

The parameter name.

return

Stabilirea valorii TRUE va duce la întoarcerea valorii exportate, ?i nu la emiterea ei. Stabilirea în FALSE (valoarea implicita) va efectua opera?ia opusa.

Valorile întoarse

The exported reflection.

A se vedea ?i

  • ReflectionParameter::toString()

ReflectionParameter::__construct
ReflectionParameter::getClass
ReflectionParameter


Get the type hinted class

ReflectionParameter::export
ReflectionParameter::getDeclaringClass
ReflectionParameter
PHP Manual

ReflectionParameter::getClass

(PHP 5, PHP 7)

ReflectionParameter::getClass — Get the type hinted class

Descrierea

public ReflectionClass ReflectionParameter::getClass ( void )

Gets the class type hinted for the parameter as a ReflectionClass object.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A ReflectionClass object.

Exemple

Example #1 Using the ReflectionParameter class

<?php
function foo(Exception $a) { }

$functionReflection = new ReflectionFunction('foo');
$parameters = $functionReflection->getParameters();
$aParameter = $parameters[0];

echo $aParameter->getClass()->name;
?>

Exemplul de mai sus va afi?a:

Exception

A se vedea ?i

  • ReflectionParameter::getDeclaringClass() - Gets declaring class

ReflectionParameter::export
ReflectionParameter::getDeclaringClass
ReflectionParameter


Gets declaring class

ReflectionParameter::getClass
ReflectionParameter::getDeclaringFunction
ReflectionParameter
PHP Manual

ReflectionParameter::getDeclaringClass

(PHP 5, PHP 7)

ReflectionParameter::getDeclaringClass — Gets declaring class

Descrierea

public ReflectionClass ReflectionParameter::getDeclaringClass ( void )

Gets the declaring class.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A ReflectionClass object.

Exemple

Example #1 Getting the class that declared the method

<?php
class Foo
{
    public function bar(\DateTime $datetime)
    {
    }
}

class Baz extends Foo
{
}

$param = new \ReflectionParameter(['Baz', 'bar'], 0);

var_dump($param->getDeclaringClass());

Exemplul de mai sus va afi?a:

object(ReflectionClass)#2 (1) {
  ["name"]=>
  string(3) "Foo"
}

A se vedea ?i

  • ReflectionParameter::getClass() - Get the type hinted class

ReflectionParameter::getClass
ReflectionParameter::getDeclaringFunction
ReflectionParameter


Gets declaring function

ReflectionParameter::getDeclaringClass
ReflectionParameter::getDefaultValue
ReflectionParameter
PHP Manual

ReflectionParameter::getDeclaringFunction

(PHP 5 >= 5.2.3, PHP 7)

ReflectionParameter::getDeclaringFunction — Gets declaring function

Descrierea

public ReflectionFunctionAbstract ReflectionParameter::getDeclaringFunction ( void )

Gets the declaring function.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A ReflectionFunction object.

A se vedea ?i

  • ReflectionParameter::getDeclaringClass() - Gets declaring class

ReflectionParameter::getDeclaringClass
ReflectionParameter::getDefaultValue
ReflectionParameter


Gets default parameter value

ReflectionParameter::getDeclaringFunction
ReflectionParameter::getDefaultValueConstantName
ReflectionParameter
PHP Manual

ReflectionParameter::getDefaultValue

(PHP 5 >= 5.0.3, PHP 7)

ReflectionParameter::getDefaultValue — Gets default parameter value

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The parameters default value.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

Name: test

Name: bar
Default value: baz

Note

Nota:

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.

A se vedea ?i

  • ReflectionParameter::isOptional() - Checks if optional
  • ReflectionParameter::isPassedByReference() - Checks if passed by reference

ReflectionParameter::getDeclaringFunction
ReflectionParameter::getDefaultValueConstantName
ReflectionParameter


Returns the default value's constant name if default value is constant or null

ReflectionParameter::getDefaultValue
ReflectionParameter::getName
ReflectionParameter
PHP Manual

ReflectionParameter::getDefaultValueConstantName

(PHP 5 >= 5.4.6, PHP 7)

ReflectionParameter::getDefaultValueConstantName — Returns the default value's constant name if default value is constant or null

Descrierea

public string ReflectionParameter::getDefaultValueConstantName ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns string on success or NULL on failure.

ReflectionParameter::getDefaultValue
ReflectionParameter::getName
ReflectionParameter


Gets parameter name

ReflectionParameter::getDefaultValueConstantName
ReflectionParameter::getPosition
ReflectionParameter
PHP Manual

ReflectionParameter::getName

(PHP 5, PHP 7)

ReflectionParameter::getName — Gets parameter name

Descrierea

public string ReflectionParameter::getName ( void )

Gets the name of the parameter.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The name of the reflected parameter.

A se vedea ?i

  • ReflectionParameter::getValue()

ReflectionParameter::getDefaultValueConstantName
ReflectionParameter::getPosition
ReflectionParameter


Gets parameter position

ReflectionParameter::getName
ReflectionParameter::getType
ReflectionParameter
PHP Manual

ReflectionParameter::getPosition

(PHP 5 >= 5.2.3, PHP 7)

ReflectionParameter::getPosition — Gets parameter position

Descrierea

public int ReflectionParameter::getPosition ( void )

Gets the position of the parameter.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The position of the parameter, left to right, starting at position #0.

A se vedea ?i

  • ReflectionParameter::getName() - Gets parameter name

ReflectionParameter::getName
ReflectionParameter::getType
ReflectionParameter


Gets a parameter's type

ReflectionParameter::getPosition
ReflectionParameter::hasType
ReflectionParameter
PHP Manual

ReflectionParameter::getType

(PHP 7)

ReflectionParameter::getType — Gets a parameter's type

Descrierea

public ReflectionType ReflectionParameter::getType ( void )

Gets the associated type of a parameter.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a ReflectionType object if a parameter type is specified, NULL otherwise.

Exemple

Example #1 ReflectionParameter::getType() example

<?php
function someFunction(int $param, $param2) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
$reflectionType2 = $reflectionParams[1]->getType();

echo $reflectionType1;
var_dump($reflectionType2);

Exemplul de mai sus va afi?a ceva similar cu:

int
null

A se vedea ?i

  • ReflectionParameter::hasType() - Checks if parameter has a type
  • ReflectionType::__toString() - To string

ReflectionParameter::getPosition
ReflectionParameter::hasType
ReflectionParameter


Checks if parameter has a type

ReflectionParameter::getType
ReflectionParameter::isArray
ReflectionParameter
PHP Manual

ReflectionParameter::hasType

(PHP 7)

ReflectionParameter::hasType — Checks if parameter has a type

Descrierea

public bool ReflectionParameter::hasType ( void )

Checks if the parameter has a type associated with it.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if a type is specified, FALSE otherwise.

Exemple

Example #1 ReflectionParameter::hasType() example

<?php
function someFunction(string $param, $param2 = null) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->hasType());
var_dump($reflectionParams[1]->hasType());

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(false)

A se vedea ?i

  • ReflectionParameter::getType() - Gets a parameter's type

ReflectionParameter::getType
ReflectionParameter::isArray
ReflectionParameter


Checks if parameter expects an array

ReflectionParameter::hasType
ReflectionParameter::isCallable
ReflectionParameter
PHP Manual

ReflectionParameter::isArray

(PHP 5 >= 5.1.0, PHP 7)

ReflectionParameter::isArray — Checks if parameter expects an array

Descrierea

public bool ReflectionParameter::isArray ( void )

Checks if the parameter expects an array.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if an array is expected, FALSE otherwise.

A se vedea ?i

  • ReflectionParameter::isOptional() - Checks if optional

ReflectionParameter::hasType
ReflectionParameter::isCallable
ReflectionParameter


Returns whether parameter MUST be callable

ReflectionParameter::isArray
ReflectionParameter::isDefaultValueAvailable
ReflectionParameter
PHP Manual

ReflectionParameter::isCallable

(PHP 5 >= 5.4.0, PHP 7)

ReflectionParameter::isCallable — Returns whether parameter MUST be callable

Descrierea

public bool ReflectionParameter::isCallable ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the parameter is callable, FALSE if it is not or NULL on failure.

ReflectionParameter::isArray
ReflectionParameter::isDefaultValueAvailable
ReflectionParameter


Checks if a default value is available

ReflectionParameter::isCallable
ReflectionParameter::isDefaultValueConstant
ReflectionParameter
PHP Manual

ReflectionParameter::isDefaultValueAvailable

(PHP 5 >= 5.0.3, PHP 7)

ReflectionParameter::isDefaultValueAvailable — Checks if a default value is available

Descrierea

public bool ReflectionParameter::isDefaultValueAvailable ( void )

Checks if a default value for the parameter is available.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if a default value is available, otherwise FALSE

A se vedea ?i

  • ReflectionParameter::getDefaultValue() - Gets default parameter value
  • ReflectionParameter::getName() - Gets parameter name

ReflectionParameter::isCallable
ReflectionParameter::isDefaultValueConstant
ReflectionParameter


Returns whether the default value of this parameter is constant

ReflectionParameter::isDefaultValueAvailable
ReflectionParameter::isOptional
ReflectionParameter
PHP Manual

ReflectionParameter::isDefaultValueConstant

(PHP 5 >= 5.4.6, PHP 7)

ReflectionParameter::isDefaultValueConstant — Returns whether the default value of this parameter is constant

Descrierea

public bool ReflectionParameter::isDefaultValueConstant ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the default value is constant, FALSE if it is not or NULL on failure.

ReflectionParameter::isDefaultValueAvailable
ReflectionParameter::isOptional
ReflectionParameter


Checks if optional

ReflectionParameter::isDefaultValueConstant
ReflectionParameter::isPassedByReference
ReflectionParameter
PHP Manual

ReflectionParameter::isOptional

(PHP 5 >= 5.0.3, PHP 7)

ReflectionParameter::isOptional — Checks if optional

Descrierea

public bool ReflectionParameter::isOptional ( void )

Checks if the parameter is optional.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the parameter is optional, otherwise FALSE

A se vedea ?i

  • ReflectionParameter::getName() - Gets parameter name

ReflectionParameter::isDefaultValueConstant
ReflectionParameter::isPassedByReference
ReflectionParameter


Checks if passed by reference

ReflectionParameter::isOptional
ReflectionParameter::isVariadic
ReflectionParameter
PHP Manual

ReflectionParameter::isPassedByReference

(PHP 5, PHP 7)

ReflectionParameter::isPassedByReference — Checks if passed by reference

Descrierea

public bool ReflectionParameter::isPassedByReference ( void )

Checks if the parameter is passed in by reference.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the parameter is passed in by reference, otherwise FALSE

A se vedea ?i

  • ReflectionParameter::getName() - Gets parameter name

ReflectionParameter::isOptional
ReflectionParameter::isVariadic
ReflectionParameter


Checks if the parameter is variadic

ReflectionParameter::isPassedByReference
ReflectionParameter::__toString
ReflectionParameter
PHP Manual

ReflectionParameter::isVariadic

(PHP 5 >= 5.6.0, PHP 7)

ReflectionParameter::isVariadic — Checks if the parameter is variadic

Descrierea

public bool ReflectionParameter::isVariadic ( void )

Checks if the parameter was declared as a variadic parameter.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the parameter is variadic, otherwise FALSE.

ReflectionParameter::isPassedByReference
ReflectionParameter::__toString
ReflectionParameter


To string

ReflectionParameter::isVariadic
ReflectionProperty
ReflectionParameter
PHP Manual

ReflectionParameter::__toString

(PHP 5, PHP 7)

ReflectionParameter::__toString — To string

Descrierea

public string ReflectionParameter::__toString ( void )

To string.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • ReflectionParameter::export() - Exports
  • __toString()

ReflectionParameter::isVariadic
ReflectionProperty
ReflectionParameter


The ReflectionProperty class

(PHP 5, PHP 7)

Introducere

The ReflectionProperty class reports information about classes properties.

Sinopsisul clasei

ReflectionProperty implements Reflector {
/* Constante */
const integer IS_STATIC = 1 ;
const integer IS_PUBLIC = 256 ;
const integer IS_PROTECTED = 512 ;
const integer IS_PRIVATE = 1024 ;
/* Proprieta?i */
public $name ;
public $class ;
/* Metode */
final private void __clone ( void )
public __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 )
}

Proprieta?i

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.

Constante predefinite

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.

Cuprins

  • ReflectionProperty::__clone — Clone
  • ReflectionProperty::__construct — Construct a ReflectionProperty object
  • ReflectionProperty::export — Export
  • ReflectionProperty::getDeclaringClass — Gets declaring class
  • ReflectionProperty::getDocComment — Gets the property doc comment
  • ReflectionProperty::getModifiers — Gets modifiers
  • ReflectionProperty::getName — Gets property name
  • ReflectionProperty::getValue — Gets value
  • ReflectionProperty::isDefault — Checks if property is a default property
  • 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, PHP 7)

ReflectionProperty::__clone — Clone

Descrierea

final private void ReflectionProperty::__clone ( void )

Clones.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • ReflectionProperty::export() - Export
  • Object cloning

ReflectionProperty
ReflectionProperty::__construct
ReflectionProperty


Construct a ReflectionProperty object

ReflectionProperty::__clone
ReflectionProperty::export
ReflectionProperty
PHP Manual

ReflectionProperty::__construct

(PHP 5, PHP 7)

ReflectionProperty::__construct — Construct a ReflectionProperty object

Descrierea

public ReflectionProperty::__construct ( mixed $class , string $name )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

class

The class name, that contains the property.

name

The name of the property being reflected.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Trying to get or set private or protected class property's values will result in an exception being thrown.

Exemple

Example #1 ReflectionProperty::__construct() example

<?php
class Str
{
    public $length  = 5;
}

// Create an instance of the ReflectionProperty class
$prop = new ReflectionProperty('Str', '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 Str
$obj= new Str();

// 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);
?>

Exemplul de mai sus va afi?a ceva similar cu:

===> 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(Str)#2 (1) {
  ["length"]=>
  int(10)
}

Example #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)

?>

Exemplul de mai sus va afi?a ceva similar cu:

int(2)
int(3)

A se vedea ?i

  • ReflectionProperty::getName() - Gets property name
  • Constructors

ReflectionProperty::__clone
ReflectionProperty::export
ReflectionProperty


Export

ReflectionProperty::__construct
ReflectionProperty::getDeclaringClass
ReflectionProperty
PHP Manual

ReflectionProperty::export

(PHP 5, PHP 7)

ReflectionProperty::export — Export

Descrierea

public static string ReflectionProperty::export ( mixed $class , string $name [, bool $return ] )

Exports a reflection.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

argument

Reflec?ia ce va fi exportata.

name

The property name.

return

Stabilirea valorii TRUE va duce la întoarcerea valorii exportate, ?i nu la emiterea ei. Stabilirea în FALSE (valoarea implicita) va efectua opera?ia opusa.

Valorile întoarse

A se vedea ?i

  • ReflectionProperty::toString()

ReflectionProperty::__construct
ReflectionProperty::getDeclaringClass
ReflectionProperty


Gets declaring class

ReflectionProperty::export
ReflectionProperty::getDocComment
ReflectionProperty
PHP Manual

ReflectionProperty::getDeclaringClass

(PHP 5, PHP 7)

ReflectionProperty::getDeclaringClass — Gets declaring class

Descrierea

public ReflectionClass ReflectionProperty::getDeclaringClass ( void )

Gets the declaring class.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A ReflectionClass object.

A se vedea ?i

  • ReflectionProperty::getName() - Gets property name

ReflectionProperty::export
ReflectionProperty::getDocComment
ReflectionProperty


Gets the property doc comment

ReflectionProperty::getDeclaringClass
ReflectionProperty::getModifiers
ReflectionProperty
PHP Manual

ReflectionProperty::getDocComment

(PHP 5 >= 5.1.0, PHP 7)

ReflectionProperty::getDocComment — Gets the property doc comment

Descrierea

public string ReflectionProperty::getDocComment ( void )

Gets the doc comment for a property.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The property doc comment.

Exemple

Example #1 ReflectionProperty::getDocComment() example

<?php
class Str
{
    /**
     * @var int  The length of the string
     */
    public $length = 5;
}

$prop = new ReflectionProperty('Str', 'length');

var_dump($prop->getDocComment());

?>

Exemplul de mai sus va afi?a ceva similar cu:

string(53) "/**
     * @var int  The length of the string
     */"

A se vedea ?i

  • ReflectionProperty::getModifiers() - Gets modifiers
  • ReflectionProperty::getName() - Gets property name
  • ReflectionProperty::getValue() - Gets value

ReflectionProperty::getDeclaringClass
ReflectionProperty::getModifiers
ReflectionProperty


Gets modifiers

ReflectionProperty::getDocComment
ReflectionProperty::getName
ReflectionProperty
PHP Manual

ReflectionProperty::getModifiers

(PHP 5, PHP 7)

ReflectionProperty::getModifiers — Gets modifiers

Descrierea

public int ReflectionProperty::getModifiers ( void )

Gets the modifiers.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A numeric representation of the modifiers.

A se vedea ?i

  • 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, PHP 7)

ReflectionProperty::getName — Gets property name

Descrierea

public string ReflectionProperty::getName ( void )

Gets the properties name.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The name of the reflected property.

A se vedea ?i

  • ReflectionProperty::getValue() - Gets value

ReflectionProperty::getModifiers
ReflectionProperty::getValue
ReflectionProperty


Gets value

ReflectionProperty::getName
ReflectionProperty::isDefault
ReflectionProperty
PHP Manual

ReflectionProperty::getValue

(PHP 5, PHP 7)

ReflectionProperty::getValue — Gets value

Descrierea

public mixed ReflectionProperty::getValue ([ object $object ] )

Gets the property's value.

Parametri

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.

Valorile întoarse

The current value of the property.

Erori/Excep?ii

Throws a ReflectionException if the property is inaccessible. You can make a protected or private property accessible using ReflectionProperty::setAccessible().

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

string(6) "foobar"
string(6) "barfoo"
string(6) "foofoo"

A se vedea ?i

  • 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 property is a default property

ReflectionProperty::getValue
ReflectionProperty::isPrivate
ReflectionProperty
PHP Manual

ReflectionProperty::isDefault

(PHP 5, PHP 7)

ReflectionProperty::isDefault — Checks if property is a default property

Descrierea

public bool ReflectionProperty::isDefault ( void )

Checks whether the property was declared at compile-time, or whether the property was dynamically declared at run-time.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the property was declared at compile-time, or FALSE if it was created at run-time.

Exemple

Example #1 ReflectionClass::isDefault() example

<?php
class Foo {
    public $bar;
}

$o = new Foo();
$o->bar = 42;
$o->baz = 42;

$ro = new ReflectionObject($o);
var_dump($ro->getProperty('bar')->isDefault());
var_dump($ro->getProperty('baz')->isDefault());
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)

A se vedea ?i

  • 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, PHP 7)

ReflectionProperty::isPrivate — Checks if property is private

Descrierea

public bool ReflectionProperty::isPrivate ( void )

Checks whether the property is private.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the property is private, FALSE otherwise.

A se vedea ?i

  • ReflectionProperty::isPublic() - Checks if property is public
  • ReflectionProperty::isProtected() - Checks if property is protected
  • ReflectionProperty::isStatic() - Checks if property is static

ReflectionProperty::isDefault
ReflectionProperty::isProtected
ReflectionProperty


Checks if property is protected

ReflectionProperty::isPrivate
ReflectionProperty::isPublic
ReflectionProperty
PHP Manual

ReflectionProperty::isProtected

(PHP 5, PHP 7)

ReflectionProperty::isProtected — Checks if property is protected

Descrierea

public bool ReflectionProperty::isProtected ( void )

Checks whether the property is protected.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the property is protected, FALSE otherwise.

A se vedea ?i

  • ReflectionProperty::isPublic() - Checks if property is public
  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isStatic() - Checks if property is static

ReflectionProperty::isPrivate
ReflectionProperty::isPublic
ReflectionProperty


Checks if property is public

ReflectionProperty::isProtected
ReflectionProperty::isStatic
ReflectionProperty
PHP Manual

ReflectionProperty::isPublic

(PHP 5, PHP 7)

ReflectionProperty::isPublic — Checks if property is public

Descrierea

public bool ReflectionProperty::isPublic ( void )

Checks whether the property is public.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the property is public, FALSE otherwise.

A se vedea ?i

  • ReflectionProperty::isProtected() - Checks if property is protected
  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isStatic() - Checks if property is static

ReflectionProperty::isProtected
ReflectionProperty::isStatic
ReflectionProperty


Checks if property is static

ReflectionProperty::isPublic
ReflectionProperty::setAccessible
ReflectionProperty
PHP Manual

ReflectionProperty::isStatic

(PHP 5, PHP 7)

ReflectionProperty::isStatic — Checks if property is static

Descrierea

public bool ReflectionProperty::isStatic ( void )

Checks whether the property is static.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the property is static, FALSE otherwise.

A se vedea ?i

  • ReflectionProperty::isPublic() - Checks if property is public
  • ReflectionProperty::isProtected() - Checks if property is protected
  • 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, PHP 7)

ReflectionProperty::setAccessible — Set property accessibility

Descrierea

public void ReflectionProperty::setAccessible ( bool $accessible )

Sets a property to be accessible. For example, it may allow protected and private properties to be accessed.

Parametri

accessible

TRUE to allow accessibility, or FALSE.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

ReflectionProperty::setValue — Set property value

Descrierea

public void ReflectionProperty::setValue ( object $object , mixed $value )
public void ReflectionProperty::setValue ( mixed $value )

Sets (changes) the property's value.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Throws a ReflectionException if the property is inaccessible. You can make a protected or private property accessible using ReflectionProperty::setAccessible().

Exemple

Example #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));
?>

Exemplul de mai sus va afi?a:

string(3) "foo"
string(3) "bar"
string(6) "foobar"

A se vedea ?i

  • ReflectionProperty::getValue() - Gets value
  • ReflectionProperty::setAccessible() - Set property accessibility
  • ReflectionClass::setStaticPropertyValue() - Sets static property value

ReflectionProperty::setAccessible
ReflectionProperty::__toString
ReflectionProperty


To string

ReflectionProperty::setValue
ReflectionType
ReflectionProperty
PHP Manual

ReflectionProperty::__toString

(PHP 5, PHP 7)

ReflectionProperty::__toString — To string

Descrierea

public string ReflectionProperty::__toString ( void )

To string.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • __toString()

ReflectionProperty::setValue
ReflectionType
ReflectionProperty


The ReflectionType class

(PHP 7)

Introducere

The ReflectionType class reports information about a function's return type.

Sinopsisul clasei

ReflectionType {
/* Metode */
public bool allowsNull ( void )
public bool isBuiltin ( void )
public string __toString ( void )
}

Cuprins

  • ReflectionType::allowsNull — Checks if null is allowed
  • ReflectionType::isBuiltin — Checks if it is a built-in type
  • ReflectionType::__toString — To string
ReflectionProperty::__toString
ReflectionType::allowsNull
Reflection


Checks if null is allowed

ReflectionType
ReflectionType::isBuiltin
ReflectionType
PHP Manual

ReflectionType::allowsNull

(PHP 7)

ReflectionType::allowsNull — Checks if null is allowed

Descrierea

public bool ReflectionType::allowsNull ( void )

Checks whether the parameter allows NULL.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if NULL is allowed, otherwise FALSE

Exemple

Example #1 ReflectionType::allowsNull() example

<?php
function someFunction(string $param, StdClass $param2 = null) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->getType()->allowsNull());
var_dump($reflectionParams[1]->getType()->allowsNull());

Exemplul de mai sus va afi?a ceva similar cu:

bool(false)
bool(true)

A se vedea ?i

  • ReflectionType::isBuiltin() - Checks if it is a built-in type
  • ReflectionType::__toString() - To string
  • ReflectionParameter::getType() - Gets a parameter's type

ReflectionType
ReflectionType::isBuiltin
ReflectionType


Checks if it is a built-in type

ReflectionType::allowsNull
ReflectionType::__toString
ReflectionType
PHP Manual

ReflectionType::isBuiltin

(PHP 7)

ReflectionType::isBuiltin — Checks if it is a built-in type

Descrierea

public bool ReflectionType::isBuiltin ( void )

Checks if the type is a built-in type in PHP.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if it's a built-in type, otherwise FALSE

Exemple

Example #1 ReflectionType::isBuiltin() example

<?php
class SomeClass {}

function someFunction(string $param, SomeClass $param2, StdClass $param3) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->getType()->isBuiltin());
var_dump($reflectionParams[1]->getType()->isBuiltin());
var_dump($reflectionParams[2]->getType()->isBuiltin());

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
bool(false)
bool(false)

Note that the ReflectionType::isBuiltin() method does not distinguish between internal and custom classes. To make this distinction, the ReflectionClass::isInternal() method should be used on the returned class name.

A se vedea ?i

  • ReflectionType::allowsNull() - Checks if null is allowed
  • ReflectionType::__toString() - To string
  • ReflectionClass::isInternal() - Checks if class is defined internally by an extension, or the core
  • ReflectionParameter::getType() - Gets a parameter's type

ReflectionType::allowsNull
ReflectionType::__toString
ReflectionType


To string

ReflectionType::isBuiltin
ReflectionGenerator
ReflectionType
PHP Manual

ReflectionType::__toString

(PHP 7)

ReflectionType::__toString — To string

Descrierea

public string ReflectionType::__toString ( void )

Gets the parameter type name.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the type of the parameter.

Exemple

Example #1 ReflectionType::__toString() example

<?php
function someFunction(string $param) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParam = $reflectionFunc->getParameters()[0];

echo $reflectionParam->getType();

Exemplul de mai sus va afi?a ceva similar cu:

string

A se vedea ?i

  • ReflectionType::allowsNull() - Checks if null is allowed
  • ReflectionType::isBuiltin() - Checks if it is a built-in type
  • ReflectionParameter::getType() - Gets a parameter's type

ReflectionType::isBuiltin
ReflectionGenerator
ReflectionType


The ReflectionGenerator class

(PHP 7)

Introducere

The ReflectionGenerator class reports information about a generator.

Sinopsisul clasei

ReflectionGenerator {
/* Metode */
public __construct ( Generator $generator )
public string getExecutingFile ( void )
public Generator getExecutingGenerator ( void )
public int getExecutingLine ( void )
public ReflectionFunctionAbstract getFunction ( void )
public object getThis ( void )
public array getTrace ([ int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT ] )
}

Cuprins

  • ReflectionGenerator::__construct — Constructs a ReflectionGenerator object
  • ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator
  • ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object
  • ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator
  • ReflectionGenerator::getFunction — Gets the function name of the generator
  • ReflectionGenerator::getThis — Gets the $this value of the generator
  • ReflectionGenerator::getTrace — Gets the trace of the executing generator
ReflectionType::__toString
ReflectionGenerator::__construct
Reflection


Constructs a ReflectionGenerator object

ReflectionGenerator
ReflectionGenerator::getExecutingFile
ReflectionGenerator
PHP Manual

ReflectionGenerator::__construct

(PHP 7)

ReflectionGenerator::__construct — Constructs a ReflectionGenerator object

Descrierea

public ReflectionGenerator::__construct ( Generator $generator )

Constructs a ReflectionGenerator object.

Parametri

generator

A generator object.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 ReflectionGenerator::__construct() example

<?php

function gen()
{
    yield 1;
}

$gen = gen();

$reflectionGen = new ReflectionGenerator($gen);

echo <<< output
{$reflectionGen->getFunction()->name}
Line: {$reflectionGen->getExecutingLine()}
File: {$reflectionGen->getExecutingFile()}
output;

Exemplul de mai sus va afi?a ceva similar cu:

gen
Line: 5
File: /path/to/file/example.php

A se vedea ?i

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator

ReflectionGenerator
ReflectionGenerator::getExecutingFile
ReflectionGenerator


Gets the file name of the currently executing generator

ReflectionGenerator::__construct
ReflectionGenerator::getExecutingGenerator
ReflectionGenerator
PHP Manual

ReflectionGenerator::getExecutingFile

(PHP 7)

ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator

Descrierea

public string ReflectionGenerator::getExecutingFile ( void )

Get the full path and file name of the currently executing generator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the full path and file name of the currently executing generator.

Exemple

Example #1 ReflectionGenerator::getExecutingFile() example

<?php

class GenExample
{
    public function gen()
    {
        yield 1;
    }
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

echo "File: {$reflectionGen->getExecutingFile()}";

Exemplul de mai sus va afi?a ceva similar cu:

File: /path/to/file/example.php

A se vedea ?i

  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingGenerator() - Gets the executing Generator object

ReflectionGenerator::__construct
ReflectionGenerator::getExecutingGenerator
ReflectionGenerator


Gets the executing Generator object

ReflectionGenerator::getExecutingFile
ReflectionGenerator::getExecutingLine
ReflectionGenerator
PHP Manual

ReflectionGenerator::getExecutingGenerator

(PHP 7)

ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object

Descrierea

public Generator ReflectionGenerator::getExecutingGenerator ( void )

Get the executing Generator object

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the currently executing Generator object.

Exemple

Example #1 ReflectionGenerator::getExecutingGenerator() example

<?php

class GenExample
{
    public function gen()
    {
        yield 1;
    }
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

$gen2 = $reflectionGen->getExecutingGenerator();

var_dump($gen2 === $gen);
var_dump($gen2->current());

Exemplul de mai sus va afi?a ceva similar cu:

bool(true)
int(1);

A se vedea ?i

  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator

ReflectionGenerator::getExecutingFile
ReflectionGenerator::getExecutingLine
ReflectionGenerator


Gets the currently executing line of the generator

ReflectionGenerator::getExecutingGenerator
ReflectionGenerator::getFunction
ReflectionGenerator
PHP Manual

ReflectionGenerator::getExecutingLine

(PHP 7)

ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator

Descrierea

public int ReflectionGenerator::getExecutingLine ( void )

Get the currently executing line number of the generator.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the line number of the currently executing statement in the generator.

Exemple

Example #1 ReflectionGenerator::getExecutingLine() example

<?php

class GenExample
{
    public function gen()
    {
        yield 1;
    }
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

echo "Line: {$reflectionGen->getExecutingLine()}";

Exemplul de mai sus va afi?a ceva similar cu:

Line: 7

A se vedea ?i

  • ReflectionGenerator::getExecutingGenerator() - Gets the executing Generator object
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator

ReflectionGenerator::getExecutingGenerator
ReflectionGenerator::getFunction
ReflectionGenerator


Gets the function name of the generator

ReflectionGenerator::getExecutingLine
ReflectionGenerator::getThis
ReflectionGenerator
PHP Manual

ReflectionGenerator::getFunction

(PHP 7)

ReflectionGenerator::getFunction — Gets the function name of the generator

Descrierea

public ReflectionFunctionAbstract ReflectionGenerator::getFunction ( void )

Enables the function name of the generator to be obtained by returning a class derived from ReflectionFunctionAbstract.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a ReflectionFunctionAbstract class. This will be ReflectionFunction for functions, or ReflectionMethod for methods.

Exemple

Example #1 ReflectionGenerator::getFunction() example

<?php

function gen()
{
    yield 1;
}

$gen = gen();

$reflectionGen = new ReflectionGenerator($gen);

var_dump($reflectionGen->getFunction());

Exemplul de mai sus va afi?a ceva similar cu:

object(ReflectionFunction)#3 (1) {
  ["name"]=>
  string(3) "gen"
}

A se vedea ?i

  • ReflectionGenerator::getThis() - Gets the $this value of the generator
  • ReflectionGenerator::getTrace() - Gets the trace of the executing generator

ReflectionGenerator::getExecutingLine
ReflectionGenerator::getThis
ReflectionGenerator


Gets the $this value of the generator

ReflectionGenerator::getFunction
ReflectionGenerator::getTrace
ReflectionGenerator
PHP Manual

ReflectionGenerator::getThis

(PHP 7)

ReflectionGenerator::getThis — Gets the $this value of the generator

Descrierea

public object ReflectionGenerator::getThis ( void )

Get the $this value that the generator has access to.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the $this value, or NULL if the generator was not created in a class context.

Exemple

Example #1 ReflectionGenerator::getThis() example

<?php

class GenExample
{
    public function gen()
    {
        yield 1;
    }
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

var_dump($reflectionGen->getThis());

Exemplul de mai sus va afi?a ceva similar cu:

object(GenExample)#3 (0) {
}

A se vedea ?i

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getTrace() - Gets the trace of the executing generator

ReflectionGenerator::getFunction
ReflectionGenerator::getTrace
ReflectionGenerator


Gets the trace of the executing generator

ReflectionGenerator::getThis
Reflector
ReflectionGenerator
PHP Manual

ReflectionGenerator::getTrace

(PHP 7)

ReflectionGenerator::getTrace — Gets the trace of the executing generator

Descrierea

public array ReflectionGenerator::getTrace ([ int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT ] )

Get the trace of the currently executing generator.

Parametri

options

The value of options can be any of the following the following flags.

Available options
Option | Description
DEBUG_BACKTRACE_PROVIDE_OBJECT | Default.
DEBUG_BACKTRACE_IGNORE_ARGS | Don't include the argument information for functions in the stack trace.

Valorile întoarse

Returns the trace of the currently executing generator.

Exemple

Example #1 ReflectionGenerator::getTrace() example

<?php
function foo() {
    yield 1;
}

function bar()
{
    yield from foo();
}

function baz()
{
    yield from bar();
}

$gen = baz();
$gen->valid(); // start the generator

var_dump((new ReflectionGenerator($gen))->getTrace());

Exemplul de mai sus va afi?a ceva similar cu:

array(2) {
  [0]=>
  array(4) {
    ["file"]=>
    string(18) "example.php"
    ["line"]=>
    int(8)
    ["function"]=>
    string(3) "foo"
    ["args"]=>
    array(0) {
    }
  }
  [1]=>
  array(4) {
    ["file"]=>
    string(18) "example.php"
    ["line"]=>
    int(12)
    ["function"]=>
    string(3) "bar"
    ["args"]=>
    array(0) {
    }
  }
}

A se vedea ?i

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getThis() - Gets the $this value of the generator

ReflectionGenerator::getThis
Reflector
ReflectionGenerator


The Reflector interface

(PHP 5, PHP 7)

Introducere

Reflector is an interface implemented by all exportable Reflection classes.

Sinopsisul clasei

Reflector {
/* Metode */
public static string export ( void )
public string __toString ( void )
}

Cuprins

  • Reflector::export — Exports
  • Reflector::__toString — To string
ReflectionGenerator::getTrace
Reflector::export
Reflection


Exports

Reflector
Reflector::__toString
Reflector
PHP Manual

Reflector::export

(PHP 5, PHP 7)

Reflector::export — Exports

Descrierea

public static string Reflector::export ( void )

Exports.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • Reflection::__toString()

Reflector
Reflector::__toString
Reflector


To string

Reflector::export
ReflectionException
Reflector
PHP Manual

Reflector::__toString

(PHP 5, PHP 7)

Reflector::__toString — To string

Descrierea

public string Reflector::__toString ( void )

To string.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A se vedea ?i

  • ReflectionProperty::export() - Export
  • __toString()

Reflector::export
ReflectionException
Reflector


The ReflectionException class

(PHP 5, PHP 7)

Introducere

The ReflectionException class.

Sinopsisul clasei

ReflectionException extends Exception {
/* Proprieta?i */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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
Manipularea variabilelor
Reflection


Manipularea variabilelor

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii de gestionare a variabilelor
    • boolval — Get the boolean value of a variable
    • debug_zval_dump — Dumps a string representation of an internal zend value to output
    • doubleval — Pseudonim pentru floatval
    • empty — Determina daca o variabila este vida
    • floatval — Ob?ine valoarea float a unei variabile
    • get_defined_vars — Întoarce un msiv cu toate variabilele definite
    • get_resource_type — Întoarce tipul resursei
    • gettype — Ob?ine tipul unei variabile
    • import_request_variables — Importa variabilele GET/POST/Cookie în circumstan?a globala
    • intval — Ob?ine valoarea întreaga a unei variabile
    • is_array — Determina daca o variabila este un array
    • is_bool — Determina daca o variabla este un boolean
    • is_callable — Verifica daca con?inutul unei variabile poate fi apelat în calitate de func?ie
    • is_double — Pseudonim pentru is_float
    • is_float — Determina daca tipul unei variabile este float
    • is_int — Determina daca tipul unei variabile este integer
    • is_integer — Pseudonim pentru is_int
    • is_long — Pseudonim pentru is_int
    • is_null — Determina daca o variabila este NULL
    • is_numeric — Determina daca o variabila este un numar sau un string numeric
    • is_object — Determina daca o variabila este un obiect
    • is_real — Pseudonim pentru is_float
    • is_resource — Determina daca o variabila este o resursa
    • is_scalar — Determina daca o variabila este un scalar
    • is_string — Determina daca tipul variabilei este string
    • isset — Determina daca o variabla este stabilita ?i nu este NULL
    • print_r — Afi?eaza informa?ie lizibila de om despre o variabila
    • serialize — Genereaza o reprezentare ce poate fi stocata a unei valori
    • settype — Stabile?te tipul unei variabile
    • strval — Ob?ine valoarea string a unei variabile
    • unserialize — Creeaza o valoare PHP dintr-o reprezentare stocata
    • unset — Elimina o variabila data
    • var_dump — Afi?eaza informa?ia despre o variabila
    • var_export — Afi?eaza sau întoarce o reprezentare string, ce poate fi prelucrata, a unei variabile
ReflectionException
Introducere
Extensii referitoare la variabile ?i tipuri


Introducere

Pentru informa?ii despre cum se comporta variabilele, accesa?i înregistrarea Variabile din sec?iunea Descrierea limbajului a manualului.

Manipularea variabilelor
Instalarea / configurarea
Manipularea variabilelor


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Manipularea variabilelor


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Op?iuni de configurare a variabilelor
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
unserialize_callback_func | NULL | PHP_INI_ALL | Disponibila începând cu PHP 4.2.0.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

unserialize_callback_func string

Func?ia de apel invers specificata este apelata în cazul când unserialize() încearca sa utilizeze o clasa nedefinita. Va aparea o avertizare daca func?ia de apel invers specificata nu este definita, sau daca func?ia de apel invers nu reu?e?te sa defineasca clasa ce lipse?te.

Accesa?i de asemenea unserialize() ?i Autoîncarcarea obiectelor.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii de gestionare a variabilelor
Manipularea variabilelor


Func?ii de gestionare a variabilelor

Cuprins

  • boolval — Get the boolean value of a variable
  • debug_zval_dump — Dumps a string representation of an internal zend value to output
  • doubleval — Pseudonim pentru floatval
  • empty — Determina daca o variabila este vida
  • floatval — Ob?ine valoarea float a unei variabile
  • get_defined_vars — Întoarce un msiv cu toate variabilele definite
  • get_resource_type — Întoarce tipul resursei
  • gettype — Ob?ine tipul unei variabile
  • import_request_variables — Importa variabilele GET/POST/Cookie în circumstan?a globala
  • intval — Ob?ine valoarea întreaga a unei variabile
  • is_array — Determina daca o variabila este un array
  • is_bool — Determina daca o variabla este un boolean
  • is_callable — Verifica daca con?inutul unei variabile poate fi apelat în calitate de func?ie
  • is_double — Pseudonim pentru is_float
  • is_float — Determina daca tipul unei variabile este float
  • is_int — Determina daca tipul unei variabile este integer
  • is_integer — Pseudonim pentru is_int
  • is_long — Pseudonim pentru is_int
  • is_null — Determina daca o variabila este NULL
  • is_numeric — Determina daca o variabila este un numar sau un string numeric
  • is_object — Determina daca o variabila este un obiect
  • is_real — Pseudonim pentru is_float
  • is_resource — Determina daca o variabila este o resursa
  • is_scalar — Determina daca o variabila este un scalar
  • is_string — Determina daca tipul variabilei este string
  • isset — Determina daca o variabla este stabilita ?i nu este NULL
  • print_r — Afi?eaza informa?ie lizibila de om despre o variabila
  • serialize — Genereaza o reprezentare ce poate fi stocata a unei valori
  • settype — Stabile?te tipul unei variabile
  • strval — Ob?ine valoarea string a unei variabile
  • unserialize — Creeaza o valoare PHP dintr-o reprezentare stocata
  • unset — Elimina o variabila data
  • var_dump — Afi?eaza informa?ia despre o variabila
  • var_export — Afi?eaza sau întoarce o reprezentare string, ce poate fi prelucrata, a unei variabile
Constante predefinite
boolval
Manipularea variabilelor


Get the boolean value of a variable

Func?ii de gestionare a variabilelor
debug_zval_dump
Func?ii de gestionare a variabilelor
PHP Manual

boolval

(PHP 5 >= 5.5.0, PHP 7)

boolval — Get the boolean value of a variable

Descrierea

boolean boolval ( mixed $var )

Returns the boolean value of var.

Parametri

var

The scalar value being converted to a boolean.

Valorile întoarse

The boolean value of var.

Exemple

Example #1 boolval() examples

<?php
echo '0:        '.(boolval(0) ? 'true' : 'false')."\n";
echo '42:       '.(boolval(42) ? 'true' : 'false')."\n";
echo '0.0:      '.(boolval(0.0) ? 'true' : 'false')."\n";
echo '4.2:      '.(boolval(4.2) ? 'true' : 'false')."\n";
echo '"":       '.(boolval("") ? 'true' : 'false')."\n";
echo '"string": '.(boolval("string") ? 'true' : 'false')."\n";
echo '"0":      '.(boolval("0") ? 'true' : 'false')."\n";
echo '"1":      '.(boolval("1") ? 'true' : 'false')."\n";
echo '[1, 2]:   '.(boolval([1, 2]) ? 'true' : 'false')."\n";
echo '[]:       '.(boolval([]) ? 'true' : 'false')."\n";
echo 'stdClass: '.(boolval(new stdClass) ? 'true' : 'false')."\n";
?>

Exemplul de mai sus va afi?a:

0:        false
42:       true
0.0:      false
4.2:      true
"":       false
"string": true
"0":      false
"1":      true
[1, 2]:   true
[]:       false
stdClass: true

A se vedea ?i

  • floatval() - Ob?ine valoarea float a unei variabile
  • intval() - Ob?ine valoarea întreaga a unei variabile
  • strval() - Ob?ine valoarea string a unei variabile
  • settype() - Stabile?te tipul unei variabile
  • is_bool() - Determina daca o variabla este un boolean
  • Type juggling

Func?ii de gestionare a variabilelor
debug_zval_dump
Func?ii de gestionare a variabilelor


Dumps a string representation of an internal zend value to output

boolval
doubleval
Func?ii de gestionare a variabilelor
PHP Manual

debug_zval_dump

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

debug_zval_dump — Dumps a string representation of an internal zend value to output

Descrierea

void debug_zval_dump ( mixed $variable [, mixed $... ] )

Dumps a string representation of an internal zend value to output.

Parametri

variable

The variable being evaluated.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 debug_zval_dump() example

<?php
$var1 = 'Hello World';
$var2 = '';

$var2 =& $var1;

debug_zval_dump(&$var1);
?>

Exemplul de mai sus va afi?a:

&string(11) "Hello World" refcount(3)

Nota: 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
?>

Exemplul de mai sus va afi?a:

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);
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • var_dump() - Afi?eaza informa?ia despre o variabila
  • debug_backtrace() - Generates a backtrace
  • References Explained
  • » References Explained (by Derick Rethans)

boolval
doubleval
Func?ii de gestionare a variabilelor


Pseudonim pentru floatval

debug_zval_dump
empty
Func?ii de gestionare a variabilelor
PHP Manual

doubleval

(PHP 4, PHP 5, PHP 7)

doubleval — Pseudonim pentru floatval()

Descrierea

Aceasta func?ie este pseudonim pentru: floatval().

debug_zval_dump
empty
Func?ii de gestionare a variabilelor


Determina daca o variabila este vida

doubleval
floatval
Func?ii de gestionare a variabilelor
PHP Manual

empty

(PHP 4, PHP 5, PHP 7)

empty — Determina daca o variabila este vida

Descrierea

bool empty ( mixed $var )

Determina daca o variabila este considerata vida. O variabila este considerata vida daca ea nu exista, sau daca valoarea ei este egala cu FALSE. Func?ia empty() nu genereaza o avertizare daca variabila nu exista.

Parametri

var

Variabla pentru a fi verificata

Nota:

Anterior versiunii PHP 5.5, empty() sus?ine doar variabile; orice altceva va duce la o eroare de interpretare. Cu alte cuvinte, urmatoarea comanda nu va func?iona: empty(trim($name)). În loc, utiliza?i trim($name) == false.

Nici o avertizare nu este generata daca variabila nu exista. Aceasta înseamna ca empty() este în esen?a varianta prescurtata a !isset($var) || $var == false.

Valorile întoarse

Întoarce FALSE daca var are o valoare nevida ?i neegala cu zero. În caz contrar, întoarce TRUE.

Urmatoarele entita?i sunt considerate a fi vide:

  • "" (un string vid)
  • 0 (0 în calitate de integer)
  • 0.0 (0 în calitate de float)
  • "0" (0 în calitate de string)
  • NULL
  • FALSE
  • array() (un tablou vid)
  • $var; (o variabila declarata, dar fara o valoare)

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | empty() acum sus?ine ?i expresii, nu doar variabile.
5.4.0 | Verificarea deplasamentelor non-numerice ale ?irurilor de caractere întoarce TRUE.

Exemple

Example #1 O simpla conpara?ie între empty() / isset().

<?php
$var = 0;

// Evalueaza în true, deoarece $var este vida
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}

// Evalueaza în true, deoarece $var este stabilita
if (isset($var)) {
    echo '$var is set even though it is empty';
}
?>

Example #2 empty() cu deplasamente în ?iruri de caractere

PHP 5.4 schimba modul în care func?ioneaza empty() când îi sunt transmise deplasamente în ?iruri de caractere.

<?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']));
?>

Exemplul de mai sus va afi?a în PHP 5.3:

bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)

Exemplul de mai sus va afi?a în PHP 5.4:

bool(true)
bool(false)
bool(false)
bool(false)
bool(true)
bool(true)

Note

Nota: Deoarece aceasta este o construc?ie a limbajului ?i nu o func?ie, ea nu poate fi apelata utilizând func?ii de operare cu variabile .

Nota:

La utilizarea empty() asupra proprieta?ilor inaccesibile ale obiectelor, va fi apelata metoda de supraîncarcare __isset(), daca este declarata.

A se vedea ?i

  • isset() - Determina daca o variabla este stabilita ?i nu este NULL
  • __isset()
  • unset() - Elimina o variabila data
  • array_key_exists() - Checks if the given key or index exists in the array
  • count() - Count all elements in an array, or something in an object
  • strlen() - Get string length
  • Tabelele de comparare a tipurilor

doubleval
floatval
Func?ii de gestionare a variabilelor


Ob?ine valoarea float a unei variabile

empty
get_defined_vars
Func?ii de gestionare a variabilelor
PHP Manual

floatval

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

floatval — Ob?ine valoarea float a unei variabile

Descrierea

float floatval ( mixed $var )

Ob?ine valoarea float a var.

Parametri

var

Poate fi orice tip scalar. floatval() nu trebuie utilizat asupra obiectelor, deoarece aceasta va provoca o eroare de nivel E_NOTICE ?i va întoarce 1.

Valorile întoarse

Valoarea float a variabilei date. În cazul tablourilor vide va fi întors 0, iar în cazul tablourilor nevide va fi întors 1.

?irurile de caractere cel mai probabil vor întoarce 0, cu toate ca aceasta depinde de cele mai din stânga caractere ale string-ului. Aici se aplica regulile generale de float casting.

Exemple

Example #1 Exemplu floatval()

<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>

Example #2 Exemplu floatval() cu cele mai din stânga caractere non-numerice

<?php
$var = 'The122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 0
?>

A se vedea ?i

  • boolval() - Get the boolean value of a variable
  • intval() - Ob?ine valoarea întreaga a unei variabile
  • strval() - Ob?ine valoarea string a unei variabile
  • settype() - Stabile?te tipul unei variabile
  • Manipularea tipurilor

empty
get_defined_vars
Func?ii de gestionare a variabilelor


Întoarce un msiv cu toate variabilele definite

floatval
get_resource_type
Func?ii de gestionare a variabilelor
PHP Manual

get_defined_vars

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

get_defined_vars — Întoarce un msiv cu toate variabilele definite

Descrierea

array get_defined_vars ( void )

Aceasta func?ie întoarce un tablou multidimensional ce con?ine lista tuturor variabilelor definite de mediu, de server sau de utilizator, în cadrul circumstan?ei în care este apelata func?ia get_defined_vars().

Valorile întoarse

Un tablou multidimensional cu toate variabilele.

Exemple

Example #1 Exemplu get_defined_vars()

<?php
$b = array(1, 1, 2, 3, 5, 8);

$arr = get_defined_vars();

// print $b
print_r($arr["b"]);

/* Afi?eaza calea catre interpretorul PHP (daca e utilizat ca CGI)
 * de ex. /usr/local/bin/php */
echo $arr["_"];

// Afi?eaza parametrii din linia de comanda, daca ace?tia exista
print_r($arr["argv"]);

// Afi?eaza toate variabilele de server
print_r($arr["_SERVER"]);

// Afi?eaza toate cheile disponibile pentru tablourile de variabile
print_r(array_keys(get_defined_vars()));
?>

A se vedea ?i

  • isset() - Determina daca o variabla este stabilita ?i nu este 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
Func?ii de gestionare a variabilelor


Întoarce tipul resursei

get_defined_vars
gettype
Func?ii de gestionare a variabilelor
PHP Manual

get_resource_type

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

get_resource_type — Întoarce tipul resursei

Descrierea

string get_resource_type ( resource $handle )

Aceasta func?ie ob?ine tipul unei resurse date.

Parametri

handle

Handle-ul resursei în cauza.

Valorile întoarse

Daca handle-ul furnizat este o resursa, aceasta func?ie va întoarce un string reprezentând tipul sau. Daca func?ia nu poate identifica tipul, valoarea întoarsa va fi string-ul Unknown.

Aceasta func?ie va întoarce FALSE ?i va genera o eroare daca handle nu este o resource.

Exemple

Example #1 Exemplu get_resource_type()

<?php
// Afi?eaza: mysql link
$c = mysql_connect();
echo get_resource_type($c) . "\n";

// Afi?eaza: stream
$fp = fopen("foo", "w");
echo get_resource_type($fp) . "\n";

// Afi?eaza: domxml document
$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc) . "\n";
?>

get_defined_vars
gettype
Func?ii de gestionare a variabilelor


Ob?ine tipul unei variabile

get_resource_type
import_request_variables
Func?ii de gestionare a variabilelor
PHP Manual

gettype

(PHP 4, PHP 5, PHP 7)

gettype — Ob?ine tipul unei variabile

Descrierea

string gettype ( mixed $var )

Întoarce tipul variabilei PHP var. Pentru verificarea tipului, utiliza?i func?iile is_*.

Parametri

var

Variabila, tipul careia se verifica.

Valorile întoarse

Valorile posibile pentru string-ul întors sunt:

  • "boolean"
  • "integer"
  • "double" (din motive istorice se întoarce "double" în cazul unui float, ?i nu pur ?i simplu "float")
  • "string"
  • "array"
  • "object"
  • "resource"
  • "NULL"
  • "unknown type"

Exemple

Example #1 Exemplu gettype()

<?php

$data = array(1, 1., NULL, new stdClass, 'foo');

foreach ($data as $value) {
    echo gettype($value), "\n";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

integer
double
NULL
object
string

A se vedea ?i

  • settype() - Stabile?te tipul unei variabile
  • get_class() - Returns the name of the class of an object
  • is_array() - Determina daca o variabila este un array
  • is_bool() - Determina daca o variabla este un boolean
  • is_callable() - Verifica daca con?inutul unei variabile poate fi apelat în calitate de func?ie
  • is_float() - Determina daca tipul unei variabile este float
  • is_int() - Determina daca tipul unei variabile este integer
  • is_null() - Determina daca o variabila este NULL
  • is_numeric() - Determina daca o variabila este un numar sau un string numeric
  • is_object() - Determina daca o variabila este un obiect
  • is_resource() - Determina daca o variabila este o resursa
  • is_scalar() - Determina daca o variabila este un scalar
  • is_string() - Determina daca tipul variabilei este string
  • function_exists() - Return TRUE if the given function has been defined
  • method_exists() - Checks if the class method exists

get_resource_type
import_request_variables
Func?ii de gestionare a variabilelor


Importa variabilele GET/POST/Cookie în circumstan?a globala

gettype
intval
Func?ii de gestionare a variabilelor
PHP Manual

import_request_variables

(PHP 4 >= 4.1.0, PHP 5 < 5.4.0)

import_request_variables — Importa variabilele GET/POST/Cookie în circumstan?a globala

Descrierea

bool import_request_variables ( string $types [, string $prefix ] )

Importa variabilele GET/POST/Cookie în circumstan?a globala. Aceasta func?ie este utila daca a?i dezactivat register_globals, însa dori?i sa ave?i acces la unele variabile din circumstan?a globala.

Daca va intereseaza importul altor variabile în circumstan?a globala, cum ar fi $_SERVER, considera?i utilizarea extract().

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

Parametri

types

Utilizând parametrul types pute?i specifica care variabile de interpelare vor fi importate. Pute?i utiliza caracterele 'G', 'P' ?i 'C' respectiv pentru GET, POST ?i Cookie. Nu importa daca caracterele sunt majuscule sau minuscule, de aceea pute?i utiliza orice combina?ie cu 'g', 'p' ?i 'c'. POST include ?i informa?ia despre fi?ierele încarcate prin metoda POST.

Nota:

Observa?i ca ordinea literelor conteaza, de aceea la utilizarea "GP" variabilele POST vor acoperi variabilele GET cu acela?i nume. Orice alte litere decât GPC sunt ignorate.

prefix

Prefixul denumirilor variabilelor, plasat înaintea denumirilor tuturor variabilelor importate în circumstan?a globala. Deci daca ave?i o valoare GET denumita "userid" ?i indica?i prefixul "pref_", atunci ve?i ob?ine o variabila globala denumita $pref_userid.

Nota:

Cu toate ca parametrul prefix este op?ional, ve?i ob?ine o eroare de nivel E_NOTICE daca nu specifica?i un prefix, sau specifica?i un string vid în calitate de prefix. Acesta probabil ca nu este un pericol de securitate. Erorile de nivel notice nu sunt afi?ate la nivelul de raportare al erorilor implicit.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Exemplu import_request_variables()

<?php
// Aceasta va importa variabilele GET ?i POST
// ?i le va prefixa cu "rvar_"
import_request_variables("gp", "rvar_");

echo $rvar_foo;
?>

A se vedea ?i

  • $_REQUEST
  • register_globals
  • Variabilele predefinite
  • extract() - Import variables into the current symbol table from an array

gettype
intval
Func?ii de gestionare a variabilelor


Ob?ine valoarea întreaga a unei variabile

import_request_variables
is_array
Func?ii de gestionare a variabilelor
PHP Manual

intval

(PHP 4, PHP 5, PHP 7)

intval — Ob?ine valoarea întreaga a unei variabile

Descrierea

int intval ( mixed $var [, int $base = 10 ] )

Întoarce valoarea de tip integer a parametrului var, utilizând baza base specificata pentru a efectua conversia (baza implicita este 10). intval() nu trebuie utilizat asupra obiectelor, deoarece aceasta va provoca o eroare de nivel E_NOTICE ?i va întoarce 1.

Parametri

var

Valoarea scalara ce va fi convertita într-un integer

base

Baza pentru efectuarea conversiei

Nota:

Daca base este 0, atunci baza utilizata este determinata cu ajutorul formatului var:

  • daca ?irul con?ine prefixul "0x" (sau "0X"), baza este considerata 16 (hexazecimala); în caz contrar,
  • daca ?irul începe cu "0", baza este considerata 8 (octala); în caz contrar,
  • baza este considerata 10 (zecimala).

Valorile întoarse

Valoarea întreaga a var în cazul succesului sau 0 în caz de e?ec. Tablourile vide întorc 0, tablourile nevide întorc 1.

Valoarea maximala depinde de sistem. Sistemele pe 32 bi?i au diapazonul maxim al numerelor întregi cu semn de la -2147483648 pâna la 2147483647. Deci, de exemplu, pe un a?a sistem intval('1000000000000') va întoarce 2147483647. Valoarea maxima pentru numerele întregi cu semn pe sistemele pe 64 bi?i este 9223372036854775807.

String-urile cel mai probabil vor întoarce 0, cu toate ca aceasta depinde de caracterul cel mai din stânga din string. Regulile obi?nuite pentru transformarile integer se aplica în acest caz.

Exemple

Example #1 Exemple intval()

Urmatoarele exemple se bazeaza pe un sistem de 32 de bi?i.

<?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
?>

Note

Nota:

Parametrul base are efect numai daca parametrul var este un string.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Emite E_NOTICE ?i întoarce 1, când un obiect este transmis catre var.

A se vedea ?i

  • boolval() - Get the boolean value of a variable
  • floatval() - Ob?ine valoarea float a unei variabile
  • strval() - Ob?ine valoarea string a unei variabile
  • settype() - Stabile?te tipul unei variabile
  • is_numeric() - Determina daca o variabila este un numar sau un string numeric
  • Manipularea tipurilor
  • Func?iile matematice de precizie arbitrara BCMath

import_request_variables
is_array
Func?ii de gestionare a variabilelor


Determina daca o variabila este un array

intval
is_bool
Func?ii de gestionare a variabilelor
PHP Manual

is_array

(PHP 4, PHP 5, PHP 7)

is_array — Determina daca o variabila este un array

Descrierea

bool is_array ( mixed $var )

Determina daca variabila data este un array.

Parametri

var

Variabila ce este evaluata.

Valorile întoarse

Întoarce TRUE daca var este un array, FALSE în caz contrar.

Exemple

Example #1 Verifica daca variabla este un 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';
?>

Exemplul de mai sus va afi?a:

Array
not an Array

A se vedea ?i

  • is_float() - Determina daca tipul unei variabile este float
  • is_int() - Determina daca tipul unei variabile este integer
  • is_string() - Determina daca tipul variabilei este string
  • is_object() - Determina daca o variabila este un obiect

intval
is_bool
Func?ii de gestionare a variabilelor


Determina daca o variabla este un boolean

is_array
is_callable
Func?ii de gestionare a variabilelor
PHP Manual

is_bool

(PHP 4, PHP 5, PHP 7)

is_bool — Determina daca o variabla este un boolean

Descrierea

bool is_bool ( mixed $var )

Determina daca variabila data este un boolean.

Parametri

var

Variabila ce este evaluata.

Valorile întoarse

Întoarce TRUE daca var este un boolean, FALSE în caz contrar.

Exemple

Example #1 Exemple is_bool()

<?php
$a = false;
$b = 0;

// Deoarece $a este un boolean, func?ia va întoarce true
if (is_bool($a) === true) {
    echo "Da, acesta este un boolean";
}

// Deoarece $b nu este un boolean, func?ia va întoarce false
if (is_bool($b) === false) {
    echo "Nu, acesta nu este un boolean";
}
?>

A se vedea ?i

  • is_float() - Determina daca tipul unei variabile este float
  • is_int() - Determina daca tipul unei variabile este integer
  • is_string() - Determina daca tipul variabilei este string
  • is_object() - Determina daca o variabila este un obiect
  • is_array() - Determina daca o variabila este un array

is_array
is_callable
Func?ii de gestionare a variabilelor


Verifica daca con?inutul unei variabile poate fi apelat în calitate de func?ie

is_bool
is_double
Func?ii de gestionare a variabilelor
PHP Manual

is_callable

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

is_callable — Verifica daca con?inutul unei variabile poate fi apelat în calitate de func?ie

Descrierea

bool is_callable ( mixed $var [, bool $syntax_only = false [, string &$callable_name ]] )

Verifica daca con?inutul unei variabile poate fi apelat în calitate de func?ie. Aceasta poate verifica daca o variabila simpla con?ine denumirea unei func?ii valide, sau daca un tablou con?ine un obiect ?i denumirea unei func?ii codificate în mod corespunzator.

Parametri

var

Valoarea spre a fi verificata.

syntax_only

Daca este stabilit în TRUE atunci func?ia verifica numai daca name poate fi o func?ie sau o metoda. Ea doar va respinge variabilele simple care nu sunt stringuri, sau tablourile care nu au structuri valide pentru a fi utilizate în calitate de func?ie de apel invers. Cele valide trebuie sa aiba doar 2 înregistrari, prima dintre care este un obiect sau un string, ?i a doua - un string.

callable_name

Prime?te "denumirea apelabila". În exemplul de mai jos aceasta este "someClass::someMethod". Observa?i însa ca în ciuda faptului ca someClass::SomeMethod() este o metoda apelabila static, acesta nu este cazul.

Valorile întoarse

Întoarce TRUE daca var este apelabila, FALSE în caz contrar.

Exemple

Example #1 Exemplu is_callable()

<?php
//  Cum de verificat o variabila daca ea poate fi apelata în calitate de
//  func?ie

//
//  O variabila simpla ce con?ine o func?ie
//

function someFunction()
{
}

$functionVariable = 'someFunction';

var_dump(is_callable($functionVariable, false, $callable_name));  // bool(true)

echo $callable_name, "\n";  // someFunction

//
//  Tablou con?inând o metoda
//

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

?>

Example #2 is_callable() ?i constructori

Începând cu PHP 5.3.0 is_callable() raporteaza constructorii ca nefiind apelabili. Aceasta afecteaza constructorii de stil PHP 5 (__construct), precum ?i constructorii de stil PHP 4 (de ex. metode cu aceea?i denumire ca ?i clasa). Anterior ambele cazuri erau considerate apelabile.

<?php

class Foo
{
    public function __construct() {}
    public function foo() {}
}

var_dump(
    is_callable(array('Foo', '__construct')),
    is_callable(array('Foo', 'foo'))
);

Exemplul de mai sus va afi?a:

bool(false)
bool(false)

A se vedea ?i

  • function_exists() - Return TRUE if the given function has been defined
  • method_exists() - Checks if the class method exists

is_bool
is_double
Func?ii de gestionare a variabilelor


Pseudonim pentru is_float

is_callable
is_float
Func?ii de gestionare a variabilelor
PHP Manual

is_double

(PHP 4, PHP 5, PHP 7)

is_double — Pseudonim pentru is_float()

Descrierea

Aceasta func?ie este pseudonim pentru: is_float().

is_callable
is_float
Func?ii de gestionare a variabilelor


Determina daca tipul unei variabile este float

is_double
is_int
Func?ii de gestionare a variabilelor
PHP Manual

is_float

(PHP 4, PHP 5, PHP 7)

is_float — Determina daca tipul unei variabile este float

Descrierea

bool is_float ( mixed $var )

Determina daca tipul variabilei date este float.

Nota:

Pentru a verifica daca o variabila este un numar sau un string numeric (ca în cazul datelor introduse, care întotdeauna este un string), trebuie sa utiliza?i is_numeric().

Parametri

var

Variabila ce este evaluata.

Valorile întoarse

Întoarce TRUE daca var este un float, FALSE în caz contrar.

Exemple

Example #1 Exemplu is_float()

<?php
if (is_float(27.25)) {
    echo "este float\n";
} else {
    echo "nu este float\n";
}
var_dump(is_float('abc'));
var_dump(is_float(23));
var_dump(is_float(23.5));
var_dump(is_float(1e7));  // Notarea ?tiin?ifica a numarului
var_dump(is_float(true));
?>

Exemplul de mai sus va afi?a:

este float
bool(false)
bool(false)
bool(true)
bool(true)
bool(false)

A se vedea ?i

  • is_bool() - Determina daca o variabla este un boolean
  • is_int() - Determina daca tipul unei variabile este integer
  • is_numeric() - Determina daca o variabila este un numar sau un string numeric
  • is_string() - Determina daca tipul variabilei este string
  • is_array() - Determina daca o variabila este un array
  • is_object() - Determina daca o variabila este un obiect

is_double
is_int
Func?ii de gestionare a variabilelor


Determina daca tipul unei variabile este integer

is_float
is_integer
Func?ii de gestionare a variabilelor
PHP Manual

is_int

(PHP 4, PHP 5, PHP 7)

is_int — Determina daca tipul unei variabile este integer

Descrierea

bool is_int ( mixed $var )

Determina daca tipul variabilei date este integer.

Nota:

Pentru a verifica daca o variabila este un numar sau un string numeric (ca în cazul datelor introduse, care întotdeauna este un string), trebuie sa utiliza?i is_numeric().

Parametri

var

Variabila ce este evaluata.

Valorile întoarse

Întoarce TRUE daca var este un integer, FALSE în caz contrar.

Exemple

Example #1 is_int() example

<?php
$values = array(23, "23", 23.5, "23.5", null, true, false);
foreach ($values as $value) {
    echo "is_int(";
    var_export($value);
    echo ") = ";
    var_dump(is_int($value));
}
?>

Exemplul de mai sus va afi?a:

is_int(23) = bool(true)
is_int('23') = bool(false)
is_int(23.5) = bool(false)
is_int('23.5') = bool(false)
is_int(NULL) = bool(false)
is_int(true) = bool(false)
is_int(false) = bool(false)

A se vedea ?i

  • is_bool() - Determina daca o variabla este un boolean
  • is_float() - Determina daca tipul unei variabile este float
  • is_numeric() - Determina daca o variabila este un numar sau un string numeric
  • is_string() - Determina daca tipul variabilei este string
  • is_array() - Determina daca o variabila este un array
  • is_object() - Determina daca o variabila este un obiect

is_float
is_integer
Func?ii de gestionare a variabilelor


Pseudonim pentru is_int

is_int
is_long
Func?ii de gestionare a variabilelor
PHP Manual

is_integer

(PHP 4, PHP 5, PHP 7)

is_integer — Pseudonim pentru is_int()

Descrierea

Aceasta func?ie este pseudonim pentru: is_int().

is_int
is_long
Func?ii de gestionare a variabilelor


Pseudonim pentru is_int

is_integer
is_null
Func?ii de gestionare a variabilelor
PHP Manual

is_long

(PHP 4, PHP 5, PHP 7)

is_long — Pseudonim pentru is_int()

Descrierea

Aceasta func?ie este pseudonim pentru: is_int().

is_integer
is_null
Func?ii de gestionare a variabilelor


Determina daca o variabila este NULL

is_long
is_numeric
Func?ii de gestionare a variabilelor
PHP Manual

is_null

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

is_null — Determina daca o variabila este NULL

Descrierea

bool is_null ( mixed $var )

Determina daca tipul variabilei date este NULL.

Parametri

var

Variabila ce este evaluata.

Valorile întoarse

Întoarce TRUE daca var este null, FALSE în caz contrar.

Exemple

Example #1 Exemplu is_null()

<?php

error_reporting(E_ALL);

$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));

?>
Notice: Undefined variable: inexistent in ...
bool(true)
bool(true)

A se vedea ?i

  • Tipul NULL
  • isset() - Determina daca o variabla este stabilita ?i nu este NULL
  • is_bool() - Determina daca o variabla este un boolean
  • is_numeric() - Determina daca o variabila este un numar sau un string numeric
  • is_float() - Determina daca tipul unei variabile este float
  • is_int() - Determina daca tipul unei variabile este integer
  • is_string() - Determina daca tipul variabilei este string
  • is_object() - Determina daca o variabila este un obiect
  • is_array() - Determina daca o variabila este un array

is_long
is_numeric
Func?ii de gestionare a variabilelor


Determina daca o variabila este un numar sau un string numeric

is_null
is_object
Func?ii de gestionare a variabilelor
PHP Manual

is_numeric

(PHP 4, PHP 5, PHP 7)

is_numeric — Determina daca o variabila este un numar sau un string numeric

Descrierea

bool is_numeric ( mixed $var )

Determina daca variabila data este numerica. String-urile numerice constau din semnul op?ional, orice numar de cifre, partea decimala op?ionala ?i partea exponen?iala op?ionala. Astfel +0123.45e6 este o valoare numerica valida. Notarea hexadecimala (de ex. 0xf4c3b00c) sau binara (de ex. 0b10100111001), nu este permisa.

Parametri

var

Variabila ce este evaluata.

Valorile întoarse

Întoarce TRUE daca var este un numar sau un string numeric, FALSE în caz contrar.

Exemple

Example #1 Exemple is_numeric()

<?php
$tests = array(
    "42",
    1337,
    0x539,
    02471,
    0b10100111001,
    1337e0,
    "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;
    }
}
?>

Exemplul de mai sus va afi?a:

'42' is numeric
'1337' is numeric
'1337' is numeric
'1337' is numeric
'1337' is numeric
'1337' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | ?iruri în nota?ie hexadecimala (de ex. 0xf4c3b00c) nu mai sunt privite ca ?iruri numerice, în consecin?a is_numeric() acum întoarce FALSE.

A se vedea ?i

  • ctype_digit() - Check for numeric character(s)
  • is_bool() - Determina daca o variabla este un boolean
  • is_null() - Determina daca o variabila este NULL
  • is_float() - Determina daca tipul unei variabile este float
  • is_int() - Determina daca tipul unei variabile este integer
  • is_string() - Determina daca tipul variabilei este string
  • is_object() - Determina daca o variabila este un obiect
  • is_array() - Determina daca o variabila este un array

is_null
is_object
Func?ii de gestionare a variabilelor


Determina daca o variabila este un obiect

is_numeric
is_real
Func?ii de gestionare a variabilelor
PHP Manual

is_object

(PHP 4, PHP 5, PHP 7)

is_object — Determina daca o variabila este un obiect

Descrierea

bool is_object ( mixed $var )

Determina daca variabila data este un obiect.

Parametri

var

Variabila ce este evaluata.

Valorile întoarse

Întoarce TRUE daca var este un object, FALSE în caz contrar.

Exemple

Example #1 Exemplu is_object()

<?php
// Declara o func?ie simpla ce întoarce un tablou
// din obiectul nostru
function get_students($obj)
{
    if (!is_object($obj)) {
        return false;
    }

    return $obj->students;
}

// Declara o noua instan?a a clasei ?i completeaza
// unele valori
$obj = new stdClass();
$obj->students = array('Kalle', 'Ross', 'Felipe');

var_dump(get_students(null));
var_dump(get_students($obj));
?>

Note

Nota:

Aceasta func?ie va întoarce FALSE daca este utilizata cu un obiect neserializat, unde defini?ia clasei nu este prezenta (cu toate ca gettype() întoarce object).

A se vedea ?i

  • is_bool() - Determina daca o variabla este un boolean
  • is_int() - Determina daca tipul unei variabile este integer
  • is_float() - Determina daca tipul unei variabile este float
  • is_string() - Determina daca tipul variabilei este string
  • is_array() - Determina daca o variabila este un array

is_numeric
is_real
Func?ii de gestionare a variabilelor


Pseudonim pentru is_float

is_object
is_resource
Func?ii de gestionare a variabilelor
PHP Manual

is_real

(PHP 4, PHP 5, PHP 7)

is_real — Pseudonim pentru is_float()

Descrierea

Aceasta func?ie este pseudonim pentru: is_float().

is_object
is_resource
Func?ii de gestionare a variabilelor


Determina daca o variabila este o resursa

is_real
is_scalar
Func?ii de gestionare a variabilelor
PHP Manual

is_resource

(PHP 4, PHP 5, PHP 7)

is_resource — Determina daca o variabila este o resursa

Descrierea

bool is_resource ( mixed $var )

Determina daca variabila data este o resursa.

Parametri

var

Variabila ce este evaluata.

Valorile întoarse

Întoarce TRUE daca var este o resource, FALSE în caz contrar.

Exemple

Example #1 Exemplu is_resource()

<?php

$db_link = @mysql_connect('localhost', 'mysql_user', 'mysql_pass');
if (!is_resource($db_link)) {
    die('Can\'t connect : ' . mysql_error());
}

?>

Note

Nota:

is_resource() nu este o metoda stricta de verificare a tipului: ea va întoarce FALSE daca var este o variabila cu resursa care a fost închisa.

A se vedea ?i

  • Documenta?ia despre tipul resursa
  • get_resource_type() - Întoarce tipul resursei

is_real
is_scalar
Func?ii de gestionare a variabilelor


Determina daca o variabila este un scalar

is_resource
is_string
Func?ii de gestionare a variabilelor
PHP Manual

is_scalar

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

is_scalar — Determina daca o variabila este un scalar

Descrierea

bool is_scalar ( mixed $var )

Determina daca variabila data este un scalar.

Variabilele scalare sunt acelea ce con?in un integer, float, string sau boolean. Tipurile array, object ?i resource nu sunt scalare.

Nota:

is_scalar() nu considera valorile de tip resource a fi scalare deoarece resursele sunt tipuri de date abstracte care în prezent se bazeaza pe numere întregi. Nu trebuie de bazat pe acest detaliu de implementare, deoarece poate fi schimbat în viitor.

Nota:

is_scalar() nu considera NULL ca scalar.

Parametri

var

Variabila ce este evaluata.

Valorile întoarse

Întoarce TRUE daca var este un scalar, FALSE în caz contrar.

Exemple

Example #1 Exemplu is_scalar()

<?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)

?>

Exemplul de mai sus va afi?a:

3.1416
array(3) {
  [0]=>
  string(10) "hemoglobin"
  [1]=>
  string(20) "cytochrome c oxidase"
  [2]=>
  string(10) "ferredoxin"
}

A se vedea ?i

  • is_float() - Determina daca tipul unei variabile este float
  • is_int() - Determina daca tipul unei variabile este integer
  • is_numeric() - Determina daca o variabila este un numar sau un string numeric
  • is_real() - Pseudonim pentru is_float
  • is_string() - Determina daca tipul variabilei este string
  • is_bool() - Determina daca o variabla este un boolean
  • is_object() - Determina daca o variabila este un obiect
  • is_array() - Determina daca o variabila este un array

is_resource
is_string
Func?ii de gestionare a variabilelor


Determina daca tipul variabilei este string

is_scalar
isset
Func?ii de gestionare a variabilelor
PHP Manual

is_string

(PHP 4, PHP 5, PHP 7)

is_string — Determina daca tipul variabilei este string

Descrierea

bool is_string ( mixed $var )

Determina daca tipul variabilei date este string.

Parametri

var

Variabila care este evaluata.

Valorile întoarse

Întoarce TRUE daca var este de tip string, FALSE în caz contrar.

Exemple

Example #1 Exemplu is_string()

<?php
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
    echo "is_string(";
    var_export($value);
    echo ") = ";
    echo var_dump(is_string($value));
}
?>

Exemplul de mai sus va afi?a:

is_string(false) = bool(false)
is_string(true) = bool(false)
is_string(NULL) = bool(false)
is_string('abc') = bool(true)
is_string('23') = bool(true)
is_string(23) = bool(false)
is_string('23.5') = bool(true)
is_string(23.5) = bool(false)
is_string('') = bool(true)
is_string(' ') = bool(true)
is_string('0') = bool(true)
is_string(0) = bool(false)

A se vedea ?i

  • is_float() - Determina daca tipul unei variabile este float
  • is_int() - Determina daca tipul unei variabile este integer
  • is_bool() - Determina daca o variabla este un boolean
  • is_object() - Determina daca o variabila este un obiect
  • is_array() - Determina daca o variabila este un array

is_scalar
isset
Func?ii de gestionare a variabilelor


Determina daca o variabla este stabilita ?i nu este NULL

is_string
print_r
Func?ii de gestionare a variabilelor
PHP Manual

isset

(PHP 4, PHP 5, PHP 7)

isset — Determina daca o variabla este stabilita ?i nu este NULL

Descrierea

bool isset ( mixed $var [, mixed $... ] )

Determina daca o variabla este stabilita ?i nu este NULL.

Daca o variabila a fost eliminata cu unset(), ea nu va mai fi stabilita. isset() va întoarce FALSE la testarea unei variabile care a fost stabilita în NULL. De asemenea observa?i ca caracterul nul ("\0") nu este echivalent cu constanta PHP NULL.

Daca se furnizeaza mai mul?i parametri, atunci isset() va întoarce TRUE numai daca to?i parametrii sunt stabili?i. Evaluarea se petrece de la stânga spre dreapta ?i se încheie de îndata ce se întâlne?te o variabila "ne-stabilita".

Parametri

var

Variabila ce va fi verificata.

...

O alta variabila ...

Valorile întoarse

Întoarce TRUE daca var exista ?i are o valoare diferita de NULL. FALSE în caz contrar.

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Verificarea deplasamentelor non-numerice în ?iruri de caractere acum întoarce FALSE.

Exemple

Example #1 Ecemple isset()

<?php

$var = '';

// Aceasta va evalua în TRUE, de aceea textul va fi afi?at.
if (isset($var)) {
    echo "This var is set so I will print.";
}

// În urmatoarele exemple vom utiliza var_dump pentru a afi?a
// valoarea întoarsa de 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

?>

Aceasta de asemenea func?ioneaza ?i pentru elemente din tablouri:

<?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

// Cheia 'hello' este egala cu NULL, de aceea este considerata nesetata
// Daca dori?i sa verifica?i cheile cu valori NULL, atunci încerca?i:
var_dump(array_key_exists('hello', $a)); // TRUE

// Verificarea valorilor la nivele mai adânci în tablou
var_dump(isset($a['pie']['a']));        // TRUE
var_dump(isset($a['pie']['b']));        // FALSE
var_dump(isset($a['cake']['a']['b']));  // FALSE

?>

Example #2 isset() cu deplasamente în ?iruri de caractere

PHP 5.4 modifica modul cum func?ioneaza isset() când îi sunt transmise deplasamente în ?iruri de caractere.

<?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']));
?>

Exemplul de mai sus va afi?a în PHP 5.3:

bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

Exemplul de mai sus va afi?a în PHP 5.4:

bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)

Note

Avertizare

isset() func?ioneaza numai cu variabile, deoarece la furnizarea a orice altceva se va genera o eroare de interpretare. Pentru a verifica daca constantele sunt stabilite utiliza?i func?ia defined().

Nota: Deoarece aceasta este o construc?ie a limbajului ?i nu o func?ie, ea nu poate fi apelata utilizând func?ii de operare cu variabile .

Nota:

La utilizarea isset() asupra proprieta?ilor inaccesibile ale obiectelor, va fi apelata metoda de supraîncarcare __isset(), daca este declarata.

A se vedea ?i

  • empty() - Determina daca o variabila este vida
  • __isset()
  • unset() - Elimina o variabila data
  • defined() - Checks whether a given named constant exists
  • tabelele de comparare a tipurilor
  • array_key_exists() - Checks if the given key or index exists in the array
  • is_null() - Determina daca o variabila este NULL
  • operatorul de control al erorilor @

is_string
print_r
Func?ii de gestionare a variabilelor


Afi?eaza informa?ie lizibila de om despre o variabila

isset
serialize
Func?ii de gestionare a variabilelor
PHP Manual

print_r

(PHP 4, PHP 5, PHP 7)

print_r — Afi?eaza informa?ie lizibila de om despre o variabila

Descrierea

mixed print_r ( mixed $expression [, bool $return = false ] )

print_r() afi?eaza informa?ia despre o variabila într-un mod care poate fi citit de oameni.

print_r(), var_dump() ?i var_export() de asemenea vor afi?a proprieta?ile protejate ?i private ale obiectelor în PHP 5. Membrii statici ai claselor nu vor fi afi?a?i.

Parametri

expression

Expresia pentru a fi afi?ata.

return

Daca dori?i sa capta?i ceea ce afi?eaza print_r(), utiliza?i parametrul return. Când acest parametru este stabilit în TRUE, print_r() va întoarce informa?ia, în loc sa o afi?eze.

Valorile întoarse

Daca se furnizeaza un string, integer sau float, însa?i valoarea va fi afi?ata. Daca este furnizat un array, valorile vor fi prezentate într-un format care arata cheile ?i elementele. O notare similara este utilizata pentru tipuri object.

Când parametrul return este stabilit în TRUE, aceasta func?ie va întoarce un string. În caz contrar, valoarea întoarsa este TRUE.

Note

Nota:

Când este utilizat parametrul return, aceasta func?ie efectueaza buferizarea interna a ie?irilor, de aceea nu poate fi utilizata în interiorul func?iei de apel invers (callback) ob_start().

Exemple

Example #1 Exemplu print_r()

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

Exemplul de mai sus va afi?a:

<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

Example #2 Exemplu cu parametrul return

<?php
$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results acum con?ine ceea ce afi?eaza print_r
?>

A se vedea ?i

  • ob_start() - Turn on output buffering
  • var_dump() - Afi?eaza informa?ia despre o variabila
  • var_export() - Afi?eaza sau întoarce o reprezentare string, ce poate fi prelucrata, a unei variabile

isset
serialize
Func?ii de gestionare a variabilelor


Genereaza o reprezentare ce poate fi stocata a unei valori

print_r
settype
Func?ii de gestionare a variabilelor
PHP Manual

serialize

(PHP 4, PHP 5, PHP 7)

serialize — Genereaza o reprezentare ce poate fi stocata a unei valori

Descrierea

string serialize ( mixed $value )

Genereaza o reprezentare ce poate fi stocata a unei valori.

Aceasta este utila pentru pastrarea sau interpretarea valorilor PHP fara a pierde tipul sau structura lor.

Pentru a transforma invers un string serializat într-o valoare PHP, utiliza?i unserialize().

Parametri

value

Valoarea ce trebuie serializata. serialize() prelucreaza toate tipurile, cu excep?ia resource. Pute?i chiar aplica serialize() asupra tablourilor ce con?in referin?e la sine însele. Referin?ele circulare din interiorul tabloului/obiectului pe care îl serializa?i de asemenea vor fi stocate. Orice alta referin?a va fi pierduta.

La serializarea obiectelor, PHP va încerca sa apeleze func?ia-membru __sleep() înainte de serializare. Aceasta se efectueaza pentru a-i permite obiectului sa efectueze orice cura?iri, etc. înainte de a fi serializat. La fel, când obiectul este restabilit cu ajutorul unserialize() func?ia-membru __wakeup() este apelata.

Nota:

Membrii priva?i ai obiectului au denumirea clasei prefixata la denumirea membrului; membrii priva?i au un '*' prefixat la denumirea membrului. Aceste valori prefixate au câte un octet nul din ambele par?i.

Valorile întoarse

Întoarce un string con?inând reprezentarea value sub forma de byte-stream care poate fi stocata oriunde.

Atrage?i aten?ia ca acesta este un ?ir de caractere binar, ce poate include octe?i null, de aceea trebuie stocat ?i manipulat ca atare. De exemplu, rezultatele func?iei serialize() la general ar trebui stocate într-un câmp BLOB într-o baza de date, ?i nu într-un câmp CHAR sau TEXT.

Exemple

Example #1 Exemplu serialize()

<?php
// $session_data con?ine un tablou multi-dimensional cu informa?ie despre
// sesiune pentru utilizatorul curent. Vom utiliza serialize() pentru a
// stoca aceasta informa?ie într-o baza de date dupa încheierea interpelarii.

$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)) {
        /* Ceva nu este în regula.. */
    }
}
?>

Note

Nota:

Atrage?i aten?ia ca multe obiecte PHP încorporate nu pot fi serializate. Însa cele ce permit acest lucru implementeaza interfa?a Serializable sau metodele magice __sleep() ?i __wakeup(). Daca o clasa interna nu îndepline?te cel pu?in una dintre aceste cerin?e, ea nu poate fi serializata cu siguran?a.

Exista unele excep?ii istorice de la aceasta regula, când unele obiecte interne pot fi serializate fara a implementa interfa?a sau a expune metodele. Cel mai elocvent exemplu este ArrayObject în versiunile anterioare PHP 5.2.0.

Avertizare

Când serialize() serializeaza obiecte, primul backslash din denumirea clasei, în cazul claselor cu spa?ii de nume, este exclus pentru a maximiza compatibilitatea.

A se vedea ?i

  • unserialize() - Creeaza o valoare PHP dintr-o reprezentare stocata
  • var_export() - Afi?eaza sau întoarce o reprezentare string, ce poate fi prelucrata, a unei variabile
  • json_encode() - Întoarce o reprezentare JSON pentru valoarea data
  • Serializarea Obiectelor
  • __sleep()
  • __wakeup()

print_r
settype
Func?ii de gestionare a variabilelor


Stabile?te tipul unei variabile

serialize
strval
Func?ii de gestionare a variabilelor
PHP Manual

settype

(PHP 4, PHP 5, PHP 7)

settype — Stabile?te tipul unei variabile

Descrierea

bool settype ( mixed &$var , string $type )

Stabile?te tipul variabilei var în type.

Parametri

var

Variabila ce este convertita.

type

Valorile posibile ale type sunt:

  • "boolean" (sau, începând cu PHP 4.2.0, "bool")
  • "integer" (sau, începând cu PHP 4.2.0, "int")
  • "float" (posibil numai începând cu PHP 4.2.0, pentru versiunile anterioare utiliza?i varianta învechita "double")
  • "string"
  • "array"
  • "object"
  • "null" (începând cu PHP 4.2.0)

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Exemplu settype()

<?php
$foo = "5bar"; // string
$bar = true;   // boolean

settype($foo, "integer"); // $foo este acum 5   (integer)
settype($bar, "string");  // $bar este acum "1" (string)
?>

Note

Nota:

Valoarea maxima pentru "int" este PHP_INT_MAX.

A se vedea ?i

  • gettype() - Ob?ine tipul unei variabile
  • Transformarea tipurilor
  • Manipularea tipurilor

serialize
strval
Func?ii de gestionare a variabilelor


Ob?ine valoarea string a unei variabile

settype
unserialize
Func?ii de gestionare a variabilelor
PHP Manual

strval

(PHP 4, PHP 5, PHP 7)

strval — Ob?ine valoarea string a unei variabile

Descrierea

string strval ( mixed $var )

Ob?ine valoarea string a unei variabile. Accesa?i documenta?ia tipului string pentru a ob?ine mai multe informa?ii despre convertirea în string.

Aceasta func?ie nu formateaza în vre-un careva mod valoarea întoarsa. Daca cauta?i un mod de a formata o valoare numerica ca string, vede?i sprintf() sau number_format().

Parametri

var

Variabila ce este convertita în string.

var poate fi de orice tip scalar sau un obiect ce implementeaza metoda __toString(). Nu pute?i utiliza strval() cu tablouri sau cu obiecte ce nu implementeaza metoda __toString().

Valorile întoarse

Valoarea string a var.

Exemple

Example #1 Exemplu strval() cu utilizarea metodei magice a PHP 5 __toString().

<?php
class StrValTest
{
    public function __toString()
    {
        return __CLASS__;
    }
}

// Afi?eaza 'StrValTest'
echo strval(new StrValTest);
?>

A se vedea ?i

  • boolval() - Get the boolean value of a variable
  • floatval() - Ob?ine valoarea float a unei variabile
  • intval() - Ob?ine valoarea întreaga a unei variabile
  • settype() - Stabile?te tipul unei variabile
  • sprintf() - Return a formatted string
  • number_format() - Format a number with grouped thousands
  • Manipularea tipurilor
  • __toString()

settype
unserialize
Func?ii de gestionare a variabilelor


Creeaza o valoare PHP dintr-o reprezentare stocata

strval
unset
Func?ii de gestionare a variabilelor
PHP Manual

unserialize

(PHP 4, PHP 5, PHP 7)

unserialize — Creeaza o valoare PHP dintr-o reprezentare stocata

Descrierea

mixed unserialize ( string $str [, array $options ] )

unserialize() preia o singura variabila serializata ?i o converte?te invers într-o valoare PHP.

Avertizare

Nu transmite?i date ale utilizatorilor, de care nu sunte?i sigur, func?iei unserialize(). Deserializarea poate rezulta în încarcarea ?i executarea codului datorita instan?ierii ?i autoîncarcarii obiectelor, ?i un utilizator rau-inten?ionat poate sa exploateze aceasta posibilitate. Utiliza?i un format securizat, standard de schimb de date, cum ar fi JSON (cu ajutorul json_decode() ?i json_encode()) daca ave?i nevoie sa transmite?i date serializate utilizatorului.

Daca ave?i nevoie sa deserializa?i date serializate stocate extern, considera?i utilizarea hash_hmac() pentru validarea datelor. Asigura?i-va ca datele nu au fost modificate de altcineva.

Parametri

str

String-ul serializat.

Daca variabila ce se deserializeaza este un obiect, dupa ce se reconstituie cu succes, PHP automat va încerca sa apeleze func?ia-membru __wakeup() (daca aceasta exista).

Nota: directiva unserialize_callback_func

Este posibil de a stabili o func?ie de apel invers ce se va apela când o clasa nedefinita trebuie instan?iata în timpul deserializarii. (pentru a preveni ob?inerea unui object incomplet "__PHP_Incomplete_Class".) Utiliza?i php.ini, ini_set() sau .htaccess pentru a defini 'unserialize_callback_func'. De fiecare data când o clasa nedefinita va trebui instan?iata, aceasta func?ie va fi apelata. Pentru a dezactiva aceasta facilitate lasa?i aceasta op?iune vida.

options

Orice op?iuni ce trebuie transmise unserialize(), ca tablou asociativ.

Op?iuni valide
Nume | Tip | Descriere
allowed_classes | mixed | Poate fi un array cu denumiri de clase, ce trebuie sa fie acceptate, FALSE pentru a nu accepta clase sau TRUE pentru a accepta toate clasele. Daca aceasta op?iune e definita ?i unserialize() întâlne?te un obiect al unei clase ce nu trebuie acceptata, atunci obiectul va fi instan?iat ca __PHP_Incomplete_Class. Omiterea acestei op?iuni are acela?i efect ca ?i definirea sa în TRUE: PHP va încerca sa instan?ieze obiecte de orice clasa.

Valorile întoarse

Valoarea convertita este întoarsa, ?i poate fi de tip boolean, integer, float, string, array sau object.

În caz ca string-ul furnizat nu poate fi deserializat se va întoarce FALSE ?i se va emite o eroare E_NOTICE.

Istoricul schimbarilor

Versiune | Descriere
7.0.0 | Parametrul options a fost adaugat.
5.6.0 | Manipularea datelor serialiate prin înlocuirea C: cu O: pentru a for?a instan?ierea obiectului fara a apela constructorul acum va e?ua.

Exemple

Example #1 Exemplu unserialize()

<?php
// Aici vom utiliza unserialize() pentru a încarca datele sesiunii în tabloul
// $session_data din string-ul selectat dintr-o baza de date.
// Acest exemplu îl complementeaza pe cel descris în func?ia 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)) {
    // daca execute sau fetch e?ueaza, se ini?ializeaza un tablou vid
    $session_data = array();
} else {
    // acum trebuie sa avem datele serializate în $tmp[0].
    $session_data = unserialize($tmp[0]);
    if (!is_array($session_data)) {
        // ceva nu este în regula, ini?ializeaza într-un tablou vid
        $session_data = array();
    }
}
?>

Example #2 Exemplu unserialize_callback_func

<?php
$serialized_object='O:1:"a":1:{s:5:"value";s:3:"100";}';

// directiva unserialize_callback_func este disponibila începând cu PHP 4.2.0
ini_set('unserialize_callback_func', 'mycallback'); // stabile?te func?ia de apel invers

function mycallback($classname)
{
    // doar include?i un fi?ier ce con?ine defini?ia clasei
    // ve?i lasa ca $classname sa-?i dea seama care defini?ie a clasei este necesara
}
?>

Note

Avertizare

FALSE este întors atât în cazul unei erori, cât ?i în cazul deserializarii unei valori FALSE serializate. Este posibil de a intercepta acest caz special comparând str cu serialize(false) sau interceptând eroarea E_NOTICE emisa.

A se vedea ?i

  • json_encode() - Întoarce o reprezentare JSON pentru valoarea data
  • json_decode() - Converte?te într-o variabila un ?ir reprezentat JSON
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • serialize() - Genereaza o reprezentare ce poate fi stocata a unei valori
  • Autoîncarcarea claselor
  • unserialize_callback_func
  • __wakeup()

strval
unset
Func?ii de gestionare a variabilelor


Elimina o variabila data

unserialize
var_dump
Func?ii de gestionare a variabilelor
PHP Manual

unset

(PHP 4, PHP 5, PHP 7)

unset — Elimina o variabila data

Descrierea

void unset ( mixed $var [, mixed $... ] )

unset() distruge variabila specificata.

Comportamentul unset() în interiorul unei func?ii poate varia în dependen?a de tipul variabilei pe care încerca?i sa o distruge?i.

Daca este aplicat unset() asupra unei variabile globale în interiorul unei func?ii, numai variabila locala va fi distrusa. Variabila din mediul apelant î?i va pastra aceea?i valoare ca ?i pâna la apelul unset().

<?php
function destroy_foo()
{
    global $foo;
    unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;
?>

Exemplul de mai sus va afi?a:

bar

Daca dori?i sa aplica?i unset() asupra unei variabile globale din interiorul unei func?ii, pute?i utiliza tabloul $GLOBALS pentru aceasta:

<?php
function foo()
{
    unset($GLOBALS['bar']);
}

$bar = "ceva";
foo();
?>

Daca se aplica unset() în interiorul unei func?ii asupra unei variabile care este transmisa PRIN REFERIN?A, numai variabila locala va fi distrusa. Variabila din mediul apelant î?i va pastra aceea?i valoare ca ?i pâna la apelul unset().

<?php
function foo(&$bar)
{
    unset($bar);
    $bar = "blah";
}

$bar = 'ceva';
echo "$bar\n";

foo($bar);
echo "$bar\n";
?>

Exemplul de mai sus va afi?a:

ceva
ceva

Daca se aplica unset() asupra unei variabile statice în interiorul unei func?ii, unset() distruge variabila numai în contextul restului func?iei. Apelurile urmatoare vor restabili valoarea precedenta a variabilei.

<?php
function foo()
{
    static $bar;
    $bar++;
    echo "Înainte de unset: $bar, ";
    unset($bar);
    $bar = 23;
    echo "dupa unset: $bar\n";
}

foo();
foo();
foo();
?>

Exemplul de mai sus va afi?a:

Înainte de unset: 1, dupa unset: 23
Înainte de unset: 2, dupa unset: 23
Înainte de unset: 3, dupa unset: 23

Parametri

var

Variabila ce va fi eliminata.

...

O alta variabila ...

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Exemplu unset()

<?php
// distruge o singura variabila
unset($foo);

// distruge un singur element din tablou
unset($bar['quux']);

// distruge mai multe variabile
unset($foo1, $foo2, $foo3);
?>

Example #2 Utilizarea modificatorului (unset)

Utilizarea modificatorului (unset) este deseori confundata cu func?ia unset(). Modificarea cu ajutorul (unset) serve?te doar pentru transformarea într-un tip NULL, pentru a asigura completitudinea. El nu modifica variabla careia îi modifica tipul.

<?php
$name = 'Felipe';

var_dump((unset) $name);
var_dump($name);
?>

Exemplul de mai sus va afi?a:

NULL
string(6) "Felipe"

Note

Nota: Deoarece aceasta este o construc?ie a limbajului ?i nu o func?ie, ea nu poate fi apelata utilizând func?ii de operare cu variabile .

Nota:

Este posibil de a elimina chiar ?i proprieta?i ale obiectelor vizibile în contextul curent.

Nota:

Nu este posibil de a elimina $this în interiorul unei metode a unui obiect începând cu PHP 5.

Nota:

La utilizarea unset() asupra proprieta?ilor inaccesibile ale obiectelor, va fi apelata metoda de supraîncarcare __unset(), daca este declarata.

A se vedea ?i

  • isset() - Determina daca o variabla este stabilita ?i nu este NULL
  • empty() - Determina daca o variabila este vida
  • __unset()
  • array_splice() - Remove a portion of the array and replace it with something else

unserialize
var_dump
Func?ii de gestionare a variabilelor


Afi?eaza informa?ia despre o variabila

unset
var_export
Func?ii de gestionare a variabilelor
PHP Manual

var_dump

(PHP 4, PHP 5, PHP 7)

var_dump — Afi?eaza informa?ia despre o variabila

Descrierea

void var_dump ( mixed $expression [, mixed $... ] )

Aceasta func?ie afi?eaza informa?ia structurata despre una sau mai multe expresii, ce include tipul ?i valoarea sa. Tablourile ?i obiectele sunt traversate recursiv ?i valorile sunt amplasate vizual astfel încât sa reflecte structura.

Toate proprieta?ile publice, private ?i protejate ale obiectelor vor fi afi?ate, doar daca obiectul nu implementeaa metoda __debugInfo() (implementata în PHP 5.6.0).

Sfat

La fel ca ?i orice program/script ce afi?eaza rezultatele direct în browser, func?iile de control al ie?irilor pot fi utilizate pentru a capta ie?irea acestei func?ii ?i de a o salva într-un string (spre exemplu).

Parametri

expression

Variabila, pe care dori?i sa o afi?a?i.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Exemple var_dump()

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

Exemplul de mai sus va afi?a:

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);

?>

Exemplul de mai sus va afi?a:

float(3.1)
bool(true)

A se vedea ?i

  • print_r() - Afi?eaza informa?ie lizibila de om despre o variabila
  • debug_zval_dump() - Dumps a string representation of an internal zend value to output
  • var_export() - Afi?eaza sau întoarce o reprezentare string, ce poate fi prelucrata, a unei variabile
  • __debugInfo()

unset
var_export
Func?ii de gestionare a variabilelor


Afi?eaza sau întoarce o reprezentare string, ce poate fi prelucrata, a unei variabile

var_dump
Servicii Web
Func?ii de gestionare a variabilelor
PHP Manual

var_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

var_export — Afi?eaza sau întoarce o reprezentare string, ce poate fi prelucrata, a unei variabile

Descrierea

mixed var_export ( mixed $expression [, bool $return = false ] )

var_export() poate ob?ine informa?ia structurata despre variabila data. Este similara cu var_dump() cu o singura excep?ie: reprezentarea întoarsa este cod PHP valid.

Parametri

expression

Variabila pe care dori?i sa o exporta?i.

return

Daca este utilizat ?i stabilit în TRUE, var_export() va întoarce reprezentarea variabilei în loc sa o afi?eze.

Valorile întoarse

Întoarce reprezentarea variabilei când parametrul return este utilizat ?i evalueaza în TRUE. În caz contrar, aceasta func?ie va întoarce NULL.

Note

Nota:

Când este utilizat parametrul return, aceasta func?ie efectueaza buferizarea interna a ie?irilor, de aceea nu poate fi utilizata în interiorul func?iei de apel invers (callback) ob_start().

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Posibilitatea de a exporta clase ?i tablouri con?inând clase utilizând metoda magica __set_state().

Exemple

Example #1 Exemple var_export()

<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?>

Exemplul de mai sus va afi?a:

array (
  0 => 1,
  1 => 2,
  2 =>
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
<?php

$b = 3.1;
$v = var_export($b, true);
echo $v;

?>

Exemplul de mai sus va afi?a:

3.1

Example #2 Exportarea claselor începând cu PHP 5.1.0

<?php
class A { public $var; }
$a = new A;
$a->var = 5;
var_export($a);
?>

Exemplul de mai sus va afi?a:

A::__set_state(array(
   'var' => 5,
))

Example #3 Utilizarea __set_state() (începând cu 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);
?>

Exemplul de mai sus va afi?a:

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

Note

Nota:

Variabile de tip resource nu pot fi exportate cu aceasta func?ie.

Nota:

var_export() nu prelucreaza referin?e circulare, deoarece ar fi aproape imposibil de a genera cod PHP prelucrabil în acest caz. Daca dori?i sa face?i ceva cu reprezentarea deplina a unui tablou sau obiect, utiliza?i serialize().

Avertizare

Când var_export() exporta obiecte, în denumirea clasei nu se include backslash-ul din fa?a (pentru clasele cu spa?ii de nume), pentru a maximiza compatibilitatea.

Nota:

Pentru a putea evalua codul PHP generat de var_export(), toate obiectele procesate trebuie sa implementeze metoda magica __set_state. Observa?i ca StdClass nu implementeaza __set_state().

A se vedea ?i

  • print_r() - Afi?eaza informa?ie lizibila de om despre o variabila
  • serialize() - Genereaza o reprezentare ce poate fi stocata a unei valori
  • var_dump() - Afi?eaza informa?ia despre o variabila

var_dump
Servicii Web
Func?ii de gestionare a variabilelor


Servicii Web

  • OAuth
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii OAuth
    • OAuth — The OAuth class
    • OAuthProvider — The OAuthProvider class
    • OAuthException — OAuthException class
  • SCA
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • SCA Func?ii
  • SOAP
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii SOAP
    • SoapClient — The SoapClient class
    • SoapServer — The SoapServer class
    • SoapFault — The SoapFault class
    • SoapHeader — The SoapHeader class
    • SoapParam — The SoapParam class
    • SoapVar — The SoapVar class
  • Yar — Yet Another RPC Framework
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Yar_Server — The Yar_Server class
    • Yar_Client — The Yar_Client class
    • Yar_Concurrent_Client — The Yar_Concurrent_Client class
    • Yar_Server_Exception — The Yar_Server_Exception class
    • Yar_Client_Exception — The Yar_Client_Exception class
  • XML-RPC
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii XML-RPC
var_export
OAuth
Informa?ii de referin?a despre func?ii


OAuth

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • FireEagle
  • Func?ii OAuth
    • 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
Servicii Web
Introducere
Servicii Web


Introducere

This extension provides OAuth 1.0a 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
Instalarea / configurarea
OAuth


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
OAuth


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pear.php.net/package/oauth

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.

Tipurile resurselor
Exemple
OAuth


Exemple

Cuprins

  • FireEagle
Constante predefinite
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);
}
?>

Exemple
Func?ii OAuth
Exemple


Func?ii OAuth

Cuprins

  • 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

Func?ii OAuth
oauth_urlencode
Func?ii OAuth
PHP Manual

oauth_get_sbs

(PECL OAuth >=0.99.7)

oauth_get_sbs — Generate a Signature Base String

Descrierea

string oauth_get_sbs ( string $http_method , string $uri [, array $request_parameters ] )

Generates a Signature Base String according to pecl/oauth.

Parametri

http_method

The HTTP method.

uri

URI to encode.

request_parameters

Array of request parameters.

Valorile întoarse

Returns a Signature Base String.

Func?ii OAuth
oauth_urlencode
Func?ii OAuth


Encode a URI to RFC 3986

oauth_get_sbs
OAuth
Func?ii OAuth
PHP Manual

oauth_urlencode

(PECL OAuth >=0.99.2)

oauth_urlencode — Encode a URI to RFC 3986

Descrierea

string oauth_urlencode ( string $uri )

Encodes a URI to » RFC 3986.

Parametri

uri

URI to encode.

Valorile întoarse

Returns an » RFC 3986 encoded string.

oauth_get_sbs
OAuth
Func?ii OAuth


The OAuth class

(PECL OAuth >= 0.99.1)

Introducere

The OAuth extension provides a simple interface to interact with data providers using the OAuth HTTP specification to protect private resources.

Sinopsisul clasei

OAuth {
/* Proprieta?i */
public $debug ;
public $sslChecks ;
public $debugInfo ;
/* Metode */
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 [, string $http_method ]]] )
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 [, string $http_method ]] )
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 )
}

Proprieta?i

debug

sslChecks

debugInfo

Cuprins

  • 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

Descrierea

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

Parametri

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

Descrierea

public void OAuth::__destruct ( void )

The destructor.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE

Istoricul schimbarilor

Versiune | Descriere
0.99.8 | The related debug property was added.

A se vedea ?i

  • 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

Descrierea

public bool OAuth::disableRedirects ( void )

Disable redirects from being followed automatically, thus allowing the request to be manually redirected.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE

Istoricul schimbarilor

Versiune | Descriere
0.99.8 | The sslChecks member was added

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE

Istoricul schimbarilor

Versiune | Descriere
0.99.8 | The debug and debugInfo members were added

A se vedea ?i

  • 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

Descrierea

public bool OAuth::enableRedirects ( void )

Follow and sign redirects automatically, which is enabled by default.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE

A se vedea ?i

  • 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

Descrierea

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.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE

Istoricul schimbarilor

Versiune | Descriere
0.99.8 | The sslChecks member was added

A se vedea ?i

  • 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

Descrierea

public mixed OAuth::fetch ( string $protected_resource_url [, array $extra_parameters [, string $http_method [, array $http_headers ]]] )

Fetch a resource.

Parametri

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.)

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
1.0.0 | Anterior întorcea NULL în caz de e?ec, în loc de FALSE.
0.99.5 | The http_method parameter was added
0.99.8 | The http_headers parameter was added

Exemple

Example #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";
}
?>

A se vedea ?i

  • 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 Git)

OAuth::generateSignature — Generate a signature

Descrierea

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.

Parametri

http_method

HTTP method for request

url

URL for request

extra_parameters

String or array of additional parameters.

Valorile întoarse

A string containing the generated signature sau FALSE în cazul e?ecului

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

Descrierea

public array OAuth::getAccessToken ( string $access_token_url [, string $auth_session_handle [, string $verifier_token [, string $http_method ]]] )

Fetch an access token, secret and any additional response parameters from the service provider.

Parametri

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.

http_method

HTTP method to use, e.g. GET or POST.

Valorile întoarse

Returns an array containing the parsed OAuth response on success or FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
1.0.0 | Anterior întorcea NULL în caz de e?ec, în loc de FALSE.
0.99.9 | The verifier_token parameter was added

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

A se vedea ?i

  • 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

Descrierea

public array OAuth::getCAPath ( void )

Gets the Certificate Authority information, which includes the ca_path and ca_info set by OAuth::setCaPath().

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array of Certificate Authority information, specifically as ca_path and ca_info keys within the returned associative array.

A se vedea ?i

  • 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

Descrierea

public string OAuth::getLastResponse ( void )

Get the raw response of the most recent request.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string containing the last response.

A se vedea ?i

  • 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 Git)

OAuth::getLastResponseHeaders — Get headers for last response

Descrierea

public string OAuth::getLastResponseHeaders ( void )

Get headers for last response.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A string containing the last response's headers sau FALSE în cazul e?ecului

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

Descrierea

public array OAuth::getLastResponseInfo ( void )

Get HTTP information about the last response.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns an array containing the response information for the last request. Constants from curl_getinfo() may be used.

A se vedea ?i

  • 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 Git)

OAuth::getRequestHeader — Generate OAuth header string signature

Descrierea

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

Parametri

http_method

HTTP method for request.

url

URL for request.

extra_parameters

String or array of additional parameters.

Valorile întoarse

A string containing the generated request header sau FALSE în cazul e?ecului

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

Descrierea

public array OAuth::getRequestToken ( string $request_token_url [, string $callback_url [, string $http_method ]] )

Fetch a request token, secret and any additional response parameters from the service provider.

Parametri

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.

http_method

HTTP method to use, e.g. GET or POST.

Valorile întoarse

Returns an array containing the parsed OAuth response on success or FALSE on failure.

Istoricul schimbarilor

Versiune | Descriere
1.0.0 | Anterior întorcea NULL în caz de e?ec, în loc de FALSE.
0.99.9 | The callback_url parameter was added

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a ceva similar cu:

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

A se vedea ?i

  • 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

Descrierea

public mixed OAuth::setAuthType ( int $auth_type )

Set where the OAuth parameters should be passed.

Parametri

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.

Valorile întoarse

Returns TRUE if a parameter is correctly set, otherwise FALSE (e.g., if an invalid auth_type is passed in.)

Istoricul schimbarilor

Versiune | Descriere
1.0.0 | Anterior întorcea NULL în caz de e?ec, în loc de 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

Descrierea

public mixed OAuth::setCAPath ([ string $ca_path [, string $ca_info ]] )

Sets the Certificate Authority (CA), both for path and info.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

ca_path

The CA Path being set.

ca_info

The CA Info being set.

Valorile întoarse

Returns TRUE on success, or FALSE if either ca_path or ca_info are considered invalid.

Istoricul schimbarilor

Versiune | Descriere
1.0.0 | Anterior întorcea NULL în caz de e?ec, în loc de FALSE.

A se vedea ?i

  • 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

Descrierea

public mixed OAuth::setNonce ( string $nonce )

Sets the nonce for all subsequent requests.

Parametri

nonce

The value for oauth_nonce.

Valorile întoarse

Returns TRUE on success, or FALSE if the nonce is considered invalid.

Istoricul schimbarilor

Versiune | Descriere
1.0.0 | Anterior întorcea NULL în caz de e?ec, în loc de FALSE.

A se vedea ?i

  • 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

Descrierea

public void OAuth::setRequestEngine ( int $reqengine )

Sets the Request Engine, that will be sending the HTTP requests.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

reqengine

The desired request engine. Set to OAUTH_REQENGINE_STREAMS to use PHP Streams, or OAUTH_REQENGINE_CURL to use Curl.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Emits an OAuthException exception if an invalid request engine is chosen.

Exemple

Example #1 OAuth::setRequestEngine() example

<?php
$consumer = new OAuth();

$consumer->setRequestEngine(OAUTH_REQENGINE_STREAMS);
?>

A se vedea ?i

  • 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

Descrierea

public mixed OAuth::setRSACertificate ( string $cert )

Sets the RSA certificate.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

cert

The RSA certificate.

Valorile întoarse

Returns TRUE on success, or FALSE on failure (e.g., the RSA certificate cannot be parsed.)

Istoricul schimbarilor

Versiune | Descriere
1.0.0 | Anterior întorcea NULL în caz de e?ec, în loc de FALSE.

Exemple

Example #1 An OAuth::setRsaCertificate() example

<?php
$consume = new OAuth('1234', '', OAUTH_SIG_METHOD_RSASHA1);

$consume->setRSACertificate(file_get_contents('test.pem'));
?>

A se vedea ?i

  • 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 Git)

OAuth::setSSLChecks — Tweak specific SSL checks for requests.

Descrierea

public bool OAuth::setSSLChecks ( int $sslcheck )

Tweak specific SSL checks for requests.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

sslcheck

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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

Descrierea

public mixed OAuth::setTimestamp ( string $timestamp )

Sets the OAuth timestamp for subsequent requests.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

timestamp

The timestamp.

Valorile întoarse

Returns TRUE, unless the timestamp is invalid, in which case FALSE is returned.

Istoricul schimbarilor

Versiune | Descriere
1.0.0 | Anterior întorcea NULL în caz de e?ec, în loc de FALSE.

A se vedea ?i

  • 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

Descrierea

public bool OAuth::setToken ( string $token , string $token_secret )

Set the token and secret for subsequent requests.

Parametri

token

The OAuth token.

token_secret

The OAuth token secret.

Valorile întoarse

TRUE

Exemple

Example #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

Descrierea

public bool OAuth::setVersion ( string $version )

Sets the OAuth version for subsequent requests

Parametri

version

OAuth version, default value is always "1.0"

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

OAuth::setToken
OAuthProvider
OAuth


The OAuthProvider class

(PECL OAuth >= 1.0.0)

Introducere

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.

Sinopsisul clasei

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 ( callable $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 ( callable $callback_function )
public void tokenHandler ( callable $callback_function )
}

Cuprins

  • 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

Descrierea

final public bool OAuthProvider::addRequiredParameter ( string $req_params )

Add required oauth provider parameters.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

req_params

The required parameters.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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 Git)

OAuthProvider::callconsumerHandler — Calls the consumerNonceHandler callback

Descrierea

public void OAuthProvider::callconsumerHandler ( void )

Calls the registered consumer handler callback function, which is set with OAuthProvider::consumerHandler().

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Emite o eroare de nivel E_ERROR daca func?ia de apel invers nu poate fi apelata, sau nu a fost specificata.

A se vedea ?i

  • 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

Descrierea

public void OAuthProvider::callTimestampNonceHandler ( void )

Calls the registered timestamp handler callback function, which is set with OAuthProvider::timestampNonceHandler().

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Emite o eroare de nivel E_ERROR daca func?ia de apel invers nu poate fi apelata, sau nu a fost specificata.

A se vedea ?i

  • 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

Descrierea

public void OAuthProvider::calltokenHandler ( void )

Calls the registered token handler callback function, which is set with OAuthProvider::tokenHandler().

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Emite o eroare de nivel E_ERROR daca func?ia de apel invers nu poate fi apelata, sau nu a fost specificata.

A se vedea ?i

  • 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

Descrierea

public void OAuthProvider::checkOAuthRequest ([ string $uri [, string $method ]] )

Checks an OAuth request.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

uri

The optional URI, or endpoint.

method

The HTTP method. Optionally pass in one of the OAUTH_HTTP_METHOD_* OAuth constants.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

Emits an E_ERROR level error if the HTTP method cannot be detected.

A se vedea ?i

  • 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

Descrierea

public OAuthProvider::__construct ([ array $params_array ] )

Initiates a new OAuthProvider object.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

params_array

Setting these optional parameters is limited to the CLI SAPI.

Valorile întoarse

An OAuthProvider object.

Exemple

Example #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);
}
?>

A se vedea ?i

  • 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

Descrierea

public void OAuthProvider::consumerHandler ( callable $callback_function )

Sets the consumer handler callback, which will later be called with OAuthProvider::callConsumerHandler().

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

callback_function

The callable functions name.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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;
}
?>

A se vedea ?i

  • 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

Descrierea

final public static string OAuthProvider::generateToken ( int $size [, bool $strong = false ] )

Generates a string of pseudo-random bytes.

Parametri

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.

Valorile întoarse

The generated token, as a string of bytes.

Erori/Excep?ii

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).

Exemple

Example #1 OAuthProvider::generateToken() example

<?php
$p = new OAuthProvider();

$t = $p->generateToken(4);

echo strlen($t),  PHP_EOL;
echo bin2hex($t), PHP_EOL;

?>

Exemplul de mai sus va afi?a ceva similar cu:

4
b6a82c27

Note

Nota:

When not enough random data is available to the system, this function will fill the remaining random bytes using the internal PHP rand() implementation.

A se vedea ?i

  • 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

Descrierea

public void OAuthProvider::is2LeggedEndpoint ( mixed $params_array )

The 2-legged flow, or request signing. It does not require a token.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

params_array

Valorile întoarse

An OAuthProvider object.

Exemple

Example #1 OAuthProvider::is2LeggedEndpoint() example

<?php

$provider = new OAuthProvider();

$provider->is2LeggedEndpoint(true);

?>

A se vedea ?i

  • 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

Descrierea

public void OAuthProvider::isRequestTokenEndpoint ( bool $will_issue_request_token )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

will_issue_request_token

Sets whether or not it will issue a request token, thus determining if OAuthProvider::tokenHandler() needs to be called.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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

Descrierea

final public bool OAuthProvider::removeRequiredParameter ( string $req_params )

Removes a required parameter.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

req_params

The required parameter to be removed.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

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.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

oauthexception

The OAuthException.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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

Descrierea

final public bool OAuthProvider::setParam ( string $param_key [, mixed $param_val ] )

Sets a parameter.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

param_key

The parameter key.

param_val

The optional parameter value.

To exclude a parameter from signature verification, set its value to NULL.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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

Descrierea

final public bool OAuthProvider::setRequestTokenPath ( string $path )

Sets the request tokens path.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

path

The path.

Valorile întoarse

TRUE

A se vedea ?i

  • 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

Descrierea

public void OAuthProvider::timestampNonceHandler ( callable $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.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

callback_function

The callable functions name.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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;
}
?>

A se vedea ?i

  • 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

Descrierea

public void OAuthProvider::tokenHandler ( callable $callback_function )

Sets the token handler callback, which will later be called with OAuthProvider::callTokenHandler().

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

callback_function

The callable functions name.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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;
}
?>

A se vedea ?i

  • OAuthProvider::callTokenHandler() - Calls the tokenNonceHandler callback
OAuthProvider::timestampNonceHandler
OAuthException
OAuthProvider


OAuthException class

(PECL OAuth >= 0.99.1)

Introducere

This exception is thrown when exceptional errors occur while using the OAuth extension and contains useful debugging information.

Sinopsisul clasei

OAuthException extends Exception {
/* Proprieta?i */
public $lastResponse ;
public $debugInfo ;
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Proprieta?i

lastResponse

The response of the exception which occurred, if any

debugInfo

OAuthProvider::tokenHandler
SCA
OAuth


SCA

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • 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 Func?ii
    • 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
Introducere
Servicii Web


Introducere

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

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.

Example #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
Instalarea / configurarea
SCA


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SCA


Necesita?i

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

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/sca.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
SCA


Exemple

Cuprins

  • 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.

Constante predefinite
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.

Precautie

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

Example #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

}
?>

Exemple
Obtaining a proxy for another Service Component
Exemple


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.

Example #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:

Example #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
Exemple


Calling another Service Component

The ConvertedStockQuote example also calls the proxies for the two components to which it refers.

Example #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
Exemple


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:

Example #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.

Example #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
Exemple


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.

Example #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:

Example #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
Exemple


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
Exemple


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.

Example #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
Exemple


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:

Example #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:

Example #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:

Example #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').

Precautie

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
Exemple


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.

Example #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
Exemple


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 Func?ii
Exemple


Error handling
SCA::createDataObject
SCA
PHP Manual

SCA Func?ii

Clase predefinite

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.

Metode

  • 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.

Metode

  • 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.

Metode

  • createDataObject - create an SDO

Cuprins

  • 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 Func?ii
SCA::getService
SCA Func?ii
PHP Manual

SCA::createDataObject

(PECL SDO >= 0.5.0)

SCA::createDataObject — create an SDO

Descrierea

SDO_DataObject SCA::createDataObject ( string $type_namespace_uri , string $type_name )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Valorile întoarse

Returns the newly created SDO_DataObject.

Erori/Excep?ii

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 Func?ii
SCA::getService
SCA Func?ii


Obtain a proxy for a service

SCA::createDataObject
SCA_LocalProxy::createDataObject
SCA Func?ii
PHP Manual

SCA::getService

(PECL SDO >= 0.5.0)

SCA::getService — Obtain a proxy for a service

Descrierea

mixed SCA::getService ( string $target [, string $binding [, array $config ]] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

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.

Valorile întoarse

The SCA_LocalProxy or SCA_SoapProxy.

Exemple

Example #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(...);
?>

Exemplul de mai sus va afi?a:

SCA::createDataObject
SCA_LocalProxy::createDataObject
SCA Func?ii


create an SDO

SCA::getService
SCA_SoapProxy::createDataObject
SCA Func?ii
PHP Manual

SCA_LocalProxy::createDataObject

(PECL SDO >= 0.5.0)

SCA_LocalProxy::createDataObject — create an SDO

Descrierea

SDO_DataObject SCA_LocalProxy::createDataObject ( string $type_namespace_uri , string $type_name )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Valorile întoarse

Returns the newly created SDO_DataObject.

Erori/Excep?ii

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 Func?ii


create an SDO

SCA_LocalProxy::createDataObject
SOAP
SCA Func?ii
PHP Manual

SCA_SoapProxy::createDataObject

(PECL SDO >= 0.5.0)

SCA_SoapProxy::createDataObject — create an SDO

Descrierea

SDO_DataObject SCA_SoapProxy::createDataObject ( string $type_namespace_uri , string $type_name )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Valorile întoarse

Returns the newly created SDO_DataObject.

Erori/Excep?ii

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 Func?ii


SOAP

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii SOAP
    • 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
Introducere
Servicii Web


Introducere

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
Instalarea / configurarea
SOAP


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SOAP


Necesita?i

Aceasta extensie necesita extensia PHP libxml. Aceasta înseamna ca e necesara de asemenea ?i indicarea op?iunii --enable-libxml , cu toate ca aceasta este realizat în mod implicit deoarece libxml este activata implicit.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Pentru a activa sus?inerea SOAP, configura?i PHP cu op?iunea --enable-soap .

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

SOAP Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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 |

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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 |
SOAP_SSL_METHOD_TLS (integer) | 0 | Since PHP 5.5.0.
SOAP_SSL_METHOD_SSLv2 (integer) | 1 | Since PHP 5.5.0.
SOAP_SSL_METHOD_SSLv3 (integer) | 2 | Since PHP 5.5.0.
SOAP_SSL_METHOD_SSLv23 (integer) | 3 | Since PHP 5.5.0.
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 |
Tipurile resurselor
Func?ii SOAP
SOAP


Func?ii SOAP

Cuprins

  • is_soap_fault — Checks if a SOAP call has failed
  • use_soap_error_handler — Set whether to use the SOAP error handler
Constante predefinite
is_soap_fault
SOAP


Checks if a SOAP call has failed

Func?ii SOAP
use_soap_error_handler
Func?ii SOAP
PHP Manual

is_soap_fault

(Unknown)

is_soap_fault — Checks if a SOAP call has failed

Descrierea

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.

Parametri

object

The object to test.

Valorile întoarse

This will return TRUE on error, and FALSE otherwise.

Exemple

Example #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);
}
?>

Example #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);
}
?>

A se vedea ?i

  • SoapClient::SoapClient() - SoapClient constructor
  • SoapFault::SoapFault() - SoapFault constructor

Func?ii SOAP
use_soap_error_handler
Func?ii SOAP


Set whether to use the SOAP error handler

is_soap_fault
SoapClient
Func?ii SOAP
PHP Manual

use_soap_error_handler

(Unknown)

use_soap_error_handler — Set whether to use the SOAP error handler

Descrierea

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 client as a SOAP fault message. If FALSE, the standard PHP error handler is used. The default is to send error to the client as SOAP fault message.

Parametri

handler

Set to TRUE to send error details to clients.

Valorile întoarse

Returns the original value.

A se vedea ?i

  • set_error_handler() - Stabile?te o func?ie definita de utilizator pentru prelucrarea erorilor
  • set_exception_handler() - Sets a user-defined exception handler function

is_soap_fault
SoapClient
Func?ii SOAP


The SoapClient class

(PHP 5 >= 5.0.1, PHP 7)

Introducere

The SoapClient class provides a client for » SOAP 1.1, » SOAP 1.2 servers. It can be used in WSDL or non-WSDL mode.

Sinopsisul clasei

SoapClient {
/* Metode */
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 ] )
}

Cuprins

  • 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, PHP 7)

SoapClient::__call — Calls a SOAP function (deprecated)

Descrierea

public mixed SoapClient::__call ( string $function_name , string $arguments )

Calling this method directly is deprecated. Usually, SOAP functions can be called as methods of the SoapClient object; in situations where this is not possible or additional options are needed, use SoapClient::__soapCall().

SoapClient
SoapClient::__construct
SoapClient


SoapClient constructor

SoapClient::__call
SoapClient::__doRequest
SoapClient
PHP Manual

SoapClient::__construct

(PHP 5 >= 5.0.1, PHP 7)

SoapClient::__construct — SoapClient constructor

Descrierea

public SoapClient::SoapClient ( mixed $wsdl [, array $options ] )

Aceasta func?ie este pseudonim pentru: 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, PHP 7)

SoapClient::__doRequest — Performs a SOAP request

Descrierea

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.

Parametri

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.

Valorile întoarse

The XML SOAP response.

Istoricul schimbarilor

Versiune | Descriere
5.1.3 | The one_way parameter was added.

Exemple

Example #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, PHP 7)

SoapClient::__getFunctions — Returns list of available SOAP functions

Descrierea

public array SoapClient::__getFunctions ( void )

Returns an array of functions described in the WSDL for the Web service.

Nota:

Aceasta func?ie func?ioneaza doar în modul WSDL.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The array of SOAP function prototypes, detailing the return type, the function name and type-hinted parameters.

Exemple

Example #1 SoapClient::__getFunctions() example

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getFunctions());
?>

Exemplul de mai sus va afi?a:

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)"
}

A se vedea ?i

  • 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, PHP 7)

SoapClient::__getLastRequest — Returns last SOAP request

Descrierea

public string SoapClient::__getLastRequest ( void )

Returns the XML sent in the last SOAP request.

Nota:

This method works only if the SoapClient object was created with the trace option set to TRUE.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The last SOAP request, as an XML string.

Exemple

Example #1 SoapClient::__getLastRequest() example

<?php
$client = new SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
?>

A se vedea ?i

  • 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, PHP 7)

SoapClient::__getLastRequestHeaders — Returns the SOAP headers from the last request

Descrierea

public string SoapClient::__getLastRequestHeaders ( void )

Returns the SOAP headers from the last request.

Nota:

This function only works if the SoapClient object was created with the trace option set to TRUE.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The last SOAP request headers.

Exemple

Example #1 SoapClient::__getLastRequestHeaders() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST HEADERS:\n" . $client->__getLastRequestHeaders() . "\n";
?>

A se vedea ?i

  • 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, PHP 7)

SoapClient::__getLastResponse — Returns last SOAP response

Descrierea

public string SoapClient::__getLastResponse ( void )

Returns the XML received in the last SOAP response.

Nota:

This method works only if the SoapClient object was created with the trace option set to TRUE.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The last SOAP response, as an XML string.

Exemple

Example #1 SoapClient::__getLastResponse() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "Response:\n" . $client->__getLastResponse() . "\n";
?>

A se vedea ?i

  • 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, PHP 7)

SoapClient::__getLastResponseHeaders — Returns the SOAP headers from the last response

Descrierea

public string SoapClient::__getLastResponseHeaders ( void )

Returns the SOAP headers from the last response.

Nota:

This function only works if the SoapClient object was created with the trace option set to TRUE.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The last SOAP response headers.

Exemple

Example #1 SoapClient::__getLastResponse() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "RESPONSE HEADERS:\n" . $client->__getLastResponseHeaders() . "\n";
?>

A se vedea ?i

  • 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, PHP 7)

SoapClient::__getTypes — Returns a list of SOAP types

Descrierea

public array SoapClient::__getTypes ( void )

Returns an array of types described in the WSDL for the Web service.

Nota:

Aceasta func?ie func?ioneaza doar în modul WSDL.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The array of SOAP types, detailing all structures and types.

Exemple

Example #1 SoapClient::__getTypes() example

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getTypes());
?>

Exemplul de mai sus va afi?a:

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;
}"
}

A se vedea ?i

  • 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, PHP 7)

SoapClient::__setCookie — The __setCookie purpose

Descrierea

public void SoapClient::__setCookie ( string $name [, string $value ] )

Defines a cookie to be sent along with the SOAP requests.

Nota:

Calling this method will affect all following calls to SoapClient methods.

Parametri

name

The name of the cookie.

value

The value of the cookie. If not specified, the cookie will be deleted.

Valorile întoarse

Nu este întoarsa nici o valoare.

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, PHP 7)

SoapClient::__setLocation — Sets the location of the Web service to use

Descrierea

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.

Nota:

Calling this method is optional. The SoapClient uses the endpoint from the WSDL file by default.

Parametri

new_location

The new endpoint URL.

Valorile întoarse

The old endpoint URL.

Exemple

Example #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;

?>

Exemplul de mai sus va afi?a ceva similar cu:

http://www.somethirdparty.com

A se vedea ?i

  • 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, PHP 7)

SoapClient::__setSoapHeaders — Sets SOAP headers for subsequent calls

Descrierea

public bool SoapClient::__setSoapHeaders ([ mixed $soapheaders ] )

Defines headers to be sent along with the SOAP requests.

Nota:

Calling this method will replace any previous values.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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);
?>

Example #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, PHP 7)

SoapClient::__soapCall — Calls a SOAP function

Descrierea

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().

Parametri

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. Note that most SOAP servers require parameter names to be provided, in which case this must be 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.

Valorile întoarse

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 exceptions option set to FALSE, a SoapFault object will be returned.

Exemple

Example #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'));
?>

A se vedea ?i

  • 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, PHP 7)

SoapClient::SoapClient — SoapClient constructor

Descrierea

public SoapClient::SoapClient ( mixed $wsdl [, array $options ] )

This constructor creates SoapClient objects in WSDL or non-WSDL mode.

Parametri

wsdl

URI of the WSDL file or NULL if working in non-WSDL mode.

Nota:

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 should be one of either SOAP_1_1 or SOAP_1_2 to select SOAP 1.1 or 1.2, respectively. If omitted, 1.1 is used.

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.

The ssl_method option is one of SOAP_SSL_METHOD_TLS, SOAP_SSL_METHOD_SSLv2, SOAP_SSL_METHOD_SSLv3 or SOAP_SSL_METHOD_SSLv23.

Erori/Excep?ii

SoapClient::SoapClient() will generate an E_ERROR error if the location and uri options aren't provided in non-WSDL mode.

A SoapFault exception will be thrown if the wsdl URI cannot be loaded.

Istoricul schimbarilor

Versiune | Descriere
5.5.0 | New ssl_method option.
5.4.0 | New keep_alive option.

Exemple

Example #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));

$client = new SoapClient("some.wsdl", array('encoding'=>'ISO-8859-1'));

class MyBook {
    public $title;
    public $author;
}

$client = new SoapClient("books.wsdl", array('classmap' => array('book' => "MyBook")));

?>

SoapClient::__soapCall
SoapServer
SoapClient


The SoapServer class

(PHP 5 >= 5.0.1, PHP 7)

Introducere

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.

Sinopsisul clasei

SoapServer {
/* Metode */
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 ] )
}

Cuprins

  • 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, PHP 7)

SoapServer::addFunction — Adds one or more functions to handle SOAP requests

Descrierea

public void SoapServer::addFunction ( mixed $functions )

Exports one or more functions for remote clients

Parametri

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.

Nota:

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);

?>

A se vedea ?i

  • 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, PHP 7)

SoapServer::addSoapHeader — Add a SOAP header to the response

Descrierea

public void SoapServer::addSoapHeader ( SoapHeader $object )

Adds a SOAP header to be returned with the response to the current request.

Parametri

object

The header to be returned.

Valorile întoarse

Nu este întoarsa nici o valoare.

SoapServer::addFunction
SoapServer::__construct
SoapServer


SoapServer constructor

SoapServer::addSoapHeader
SoapServer::fault
SoapServer
PHP Manual

SoapServer::__construct

(PHP 5 >= 5.0.1, PHP 7)

SoapServer::__construct — SoapServer constructor

Descrierea

public SoapServer::__construct ( mixed $wsdl [, array $options ] )

Aceasta func?ie este pseudonim pentru: 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, PHP 7)

SoapServer::fault — Issue SoapServer fault indicating an error

Descrierea

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.

Nota:

This can only be called when handling a request.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

SoapServer::getFunctions — Returns list of defined functions

Descrierea

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().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

An array of the defined functions.

Exemple

Example #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";
  }
}
?>

A se vedea ?i

  • 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, PHP 7)

SoapServer::handle — Handles a SOAP request

Descrierea

public void SoapServer::handle ([ string $soap_request ] )

Processes a SOAP request, calls necessary functions, and sends a response back.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 SoapServer::handle() example

<?php
function test($x)
{
    return $x;
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

A se vedea ?i

  • 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, PHP 7)

SoapServer::setClass — Sets the class which handles SOAP requests

Descrierea

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.

Parametri

class_name

The name of the exported class.

args

These optional parameters will be passed to the default class constructor during object creation.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

SoapServer::setObject — Sets the object which will be used to handle SOAP requests

Descrierea

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().

Parametri

object

The object to handle the requests.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

SoapServer::setPersistence — Sets SoapServer persistence mode

Descrierea

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().

Nota:

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.

Nota:

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.

Parametri

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 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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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());
 }
?>

A se vedea ?i

  • 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, PHP 7)

SoapServer::SoapServer — SoapServer constructor

Descrierea

public SoapServer::SoapServer ( mixed $wsdl [, array $options ] )

This constructor allows the creation of SoapServer objects in WSDL or non-WSDL mode.

Parametri

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.

The send_errors option can be set to FALSE to sent a generic error message ("Internal error") instead of the specific error message sent otherwise.

Exemple

Example #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")));

?>

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | Added the typemap option.

A se vedea ?i

  • SoapClient::SoapClient() - SoapClient constructor

SoapServer::setPersistence
SoapFault
SoapServer


The SoapFault class

(PHP 5 >= 5.0.1, PHP 7)

Introducere

Represents a SOAP fault.

Sinopsisul clasei

SoapFault extends Exception {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode */
__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 )
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Cuprins

  • 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, PHP 7)

SoapFault::__construct — SoapFault constructor

Descrierea

SoapFault::__construct ( string $faultcode , string $faultstring [, string $faultactor [, string $detail [, string $faultname [, string $headerfault ]]]] )

Aceasta func?ie este pseudonim pentru: SoapFault::SoapFault()

SoapFault
SoapFault::SoapFault
SoapFault


SoapFault constructor

SoapFault::__construct
SoapFault::__toString
SoapFault
PHP Manual

SoapFault::SoapFault

(PHP 5 >= 5.0.1, PHP 7)

SoapFault::SoapFault — SoapFault constructor

Descrierea

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.

Parametri

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.

Exemple

Example #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.

Example #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();
?>

A se vedea ?i

  • 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, PHP 7)

SoapFault::__toString — Obtain a string representation of a SoapFault

Descrierea

public string SoapFault::__toString ( void )

Returns a string representation of the SoapFault.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A string describing the SoapFault.

SoapFault::SoapFault
SoapHeader
SoapFault


The SoapHeader class

(PHP 5 >= 5.0.1, PHP 7)

Introducere

Represents a SOAP header.

Sinopsisul clasei

SoapHeader {
/* Metode */
__construct ( string $namespace , string $name [, mixed $data [, bool $mustunderstand [, string $actor ]]] )
SoapHeader ( string $namespace , string $name [, mixed $data [, bool $mustunderstand = false [, string $actor ]]] )
}

Cuprins

  • 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, PHP 7)

SoapHeader::__construct — SoapHeader constructor

Descrierea

SoapHeader::__construct ( string $namespace , string $name [, mixed $data [, bool $mustunderstand [, string $actor ]]] )

Aceasta func?ie este pseudonim pentru: SoapHeader::SoapHeader()

SoapHeader
SoapHeader::SoapHeader
SoapHeader


SoapHeader constructor

SoapHeader::__construct
SoapParam
SoapHeader
PHP Manual

SoapHeader::SoapHeader

(PHP 5 >= 5.0.1, PHP 7)

SoapHeader::SoapHeader — SoapHeader constructor

Descrierea

SoapHeader::SoapHeader ( string $namespace , string $name [, mixed $data [, bool $mustunderstand = false [, string $actor ]]] )

Constructs a new SoapHeader object.

Parametri

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.

Exemple

Example #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'));
?>

A se vedea ?i

  • 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

(PHP 5 >= 5.0.1, PHP 7)

Introducere

Represents parameter to a SOAP call.

Sinopsisul clasei

SoapParam {
/* Metode */
__construct ( mixed $data , string $name )
SoapParam ( mixed $data , string $name )
}

Cuprins

  • 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, PHP 7)

SoapParam::__construct — SoapParam constructor

Descrierea

SoapParam::__construct ( mixed $data , string $name )

Aceasta func?ie este pseudonim pentru: SoapParam::SoapParam()

SoapParam
SoapParam::SoapParam
SoapParam


SoapParam constructor

SoapParam::__construct
SoapVar
SoapParam
PHP Manual

SoapParam::SoapParam

(PHP 5 >= 5.0.1, PHP 7)

SoapParam::SoapParam — SoapParam constructor

Descrierea

SoapParam::SoapParam ( mixed $data , string $name )

Constructs a new SoapParam object.

Parametri

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.

Exemple

Example #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"));
?>

A se vedea ?i

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapVar::SoapVar() - SoapVar constructor

SoapParam::__construct
SoapVar
SoapParam


The SoapVar class

(PHP 5 >= 5.0.1, PHP 7)

Introducere

A class representing a variable or object for use with SOAP services.

Sinopsisul clasei

SoapVar {
/* Metode */
__construct ( mixed $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 ]]]] )
}

Cuprins

  • 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, PHP 7)

SoapVar::__construct — SoapVar constructor

Descrierea

SoapVar::__construct ( mixed $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )

Aceasta func?ie este pseudonim pentru: SoapVar::SoapVar()

SoapVar
SoapVar::SoapVar
SoapVar


SoapVar constructor

SoapVar::__construct
Yar
SoapVar
PHP Manual

SoapVar::SoapVar

(PHP 5 >= 5.0.1, PHP 7)

SoapVar::SoapVar — SoapVar constructor

Descrierea

SoapVar::SoapVar ( mixed $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )

Constructs a new SoapVar object.

Parametri

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.

Exemple

Example #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"));
?>

A se vedea ?i

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapParam::SoapParam() - SoapParam constructor

SoapVar::__construct
Yar
SoapVar


Yet Another RPC Framework

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • Yar_Server — The Yar_Server class
    • Yar_Server::__construct — Register a server
    • Yar_Server::handle — Start RPC Server
  • Yar_Client — The Yar_Client class
    • Yar_Client::__call — Call service
    • Yar_Client::__construct — Create a client
    • Yar_Client::setOpt — Set calling contexts
  • Yar_Concurrent_Client — The Yar_Concurrent_Client class
    • Yar_Concurrent_Client::call — Register a concurrent call
    • Yar_Concurrent_Client::loop — Send all calls
    • Yar_Concurrent_Client::reset — Clean all registered calls
  • Yar_Server_Exception — The Yar_Server_Exception class
    • Yar_Server_Exception::getType — The getType purpose
  • Yar_Client_Exception — The Yar_Client_Exception class
    • Yar_Client_Exception::getType — The getType purpose
SoapVar::SoapVar
Introducere
Servicii Web


Introducere

Yar is a RPC framework which aims to provide a simple and easy way to do communication between PHP applications It has the ability to concurrently call multiple remote services.

Yar
Instalarea / configurarea
Yar


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
Yar


Necesita?i

if you want to use msgpack as packager, you need compile Yar by your self with ./configure --enable-msgpack

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/yar.

O biblioteca DLL pentru aceasta extensie PECL nu este disponibila în prezent. Accesa?i de asemenea ?i sec?iunea compilarea în Windows.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Yar Op?iuni de configurare pentru
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
yar.packager | php | PHP_INI_SYSTEM |
yar.debug | Off | PHP_INI_ALL |
yar.connect_timeout | 1000 | PHP_INI_ALL |
yar.timeout | 5000 | PHP_INI_ALL |
yar.expose_info | On | PHP_INI_SYS |

Iata o explica?ie pe scurt a directivelor de configurare.

yar.packager string

it could be php, json, and msgpack(require built with msgpack support)

yar.debug string

yar.connect_timeout integer

timeout in ms

yar.timeout integer

timeout in ms

yar.expose_info bool

whether expose the service info(when access the server via GET)

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

YAR_VERSION (string)
YAR_CLIENT_PROTOCOL_HTTP (integer)
YAR_CLIENT_OPT_PACKAGER (integer)
YAR_CLIENT_OPT_TIMEOUT (integer)
YAR_CLIENT_OPT_CONNECT_TIMEOUT (integer)
YAR_PACKAGER_PHP (string)
YAR_PACKAGER_JSON (string)
YAR_ERR_OKEY (integer)
YAR_ERR_OUTPUT (integer)
YAR_ERR_TRANSPORT (integer)
YAR_ERR_REQUEST (integer)
YAR_ERR_PROTOCOL (integer)
YAR_ERR_PACKAGER (integer)
YAR_ERR_EXCEPTION (integer)

Tipurile resurselor
Exemple
Yar


Exemple

Example #1 Yar Server Example

<?php

/* assume this page can be accessed by http://example.com/operator.php */

class Operator {

    /**
     * Add two operands
     * @param interge
     * @return interge
     */
    public function add($a, $b) {
        return $this->_add($a, $b);
    }

    /**
     * Sub
     */
    public function sub($a, $b) {
        return $a - $b;
    }

    /**
     * Mul
     */
    public function mul($a, $b) {
        return $a * $b;
    }

    /**
     * Protected methods will not be exposed
     * @param interge
     * @return interge
     */
    protected function _add($a, $b) {
        return $a + $b;
    }
}

$server = new Yar_Server(new Operator());
$server->handle();
?>

Example #2 Access the server in borwser(GET request)

Exemplul de mai sus va afi?a ceva similar cu:

Yar Server Info

Example #3 Yar Client Example

<?php
$client = new yar_client("http://example.com/operator.php");

/* call directly */
var_dump($client->add(1, 2));

/* call via call */
var_dump($client->call("add", array(3, 2)));

/* __add can not be called */
var_dump($client->_add(1, 2));
?>

Exemplul de mai sus va afi?a ceva similar cu:

int(3)
int(5)
PHP Fatal error:  Uncaught exception 'Yar_Server_Exception' with message 'call to api Operator::_add() failed' in *

Example #4 Yar Concurrent Client Example

<?php
function callback($ret, $callinfo) {
    echo $callinfo['method'] , " result: ", $ret , "\n";
}

/* register async call to remote services */
Yar_Concurrent_Client::call("http://example.com/operator.php", "add", array(1, 2), "callback");
Yar_Concurrent_Client::call("http://example.com/operator.php", "sub", array(2, 1), "callback");
Yar_Concurrent_Client::call("http://example.com/operator.php", "mul", array(2, 2), "callback");

/* sent all request and wait for response */
Yar_Concurrent_Client::loop();
?>

Exemplul de mai sus va afi?a ceva similar cu:

mul result: 4
sub result: 1
add result: 3
Constante predefinite
Yar_Server
Yar


The Yar_Server class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

Yar_Server {
/* Proprieta?i */
protected $_executor ;
/* Metode */
final public __construct ( Object $obj )
public boolean handle ( void )
}

Proprieta?i

_executor

Cuprins

  • Yar_Server::__construct — Register a server
  • Yar_Server::handle — Start RPC Server
Exemple
Yar_Server::__construct
Yar


Register a server

Yar_Server
Yar_Server::handle
Yar_Server
PHP Manual

Yar_Server::__construct

(PECL yar >= 1.0.0)

Yar_Server::__construct — Register a server

Descrierea

final public Yar_Server::__construct ( Object $obj )

Set up a Yar HTTP RPC Server, All the public methods of $obj will be register as a RPC service.

Parametri

obj

An Object, all public methods of its will be registered as RPC services.

Valorile întoarse

An instance of Yar_Server.

Exemple

Example #1 Yar_Server::__construct() example

<?php
class API {
    /**
     * the doc info will be generated automatically into service info page.
     * @params
     * @return
     */
    public function some_method($parameter, $option = "foo") {
         return "some_method";
    }

    protected function client_can_not_see() {
    }
}

$service = new Yar_Server(new API());
$service->handle();
?>

Exemplul de mai sus va afi?a ceva similar cu:

A se vedea ?i

  • Yar_Server::handle() - Start RPC Server
    •

Yar_Server

Yar_Server::handle

Yar_Server


Start RPC Server

Yar_Server::__construct
Yar_Client
Yar_Server
PHP Manual

Yar_Server::handle

(PECL yar >= 1.0.0)

Yar_Server::handle — Start RPC Server

Descrierea

public boolean Yar_Server::handle ( void )

Start a RPC HTTP server, and ready for accpet RPC requests.

Nota:

Usual RPC calls will be issued as HTTP POST requests. If a HTTP GET request is issued to the uri, the service information (commented section above) will be printed on the page

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

boolean

Exemple

Example #1 Yar_Server::handle() example

<?php
class API {
    /**
     * the doc info will be generated automatically into service info page.
     * @params
     * @return
     */
    public function some_method($parameter, $option = "foo") {
    }

    protected function client_can_not_see() {
    }
}

$service = new Yar_Server(new API());
$service->handle();
?>

Exemplul de mai sus va afi?a ceva similar cu:

A se vedea ?i

  • Yar_Server::__construct() - Register a server
    •

Yar_Server::__construct

Yar_Client

Yar_Server


The Yar_Client class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

Yar_Client {
/* Proprieta?i */
protected $_protocol ;
protected $_uri ;
protected $_options ;
protected $_running ;
/* Metode */
public void __call ( string $method , array $parameters )
final public __construct ( string $url )
public boolean setOpt ( number $name , mixed $value )
}

Proprieta?i

_protocol

_uri

_options

_running

Cuprins

  • Yar_Client::__call — Call service
  • Yar_Client::__construct — Create a client
  • Yar_Client::setOpt — Set calling contexts
Yar_Server::handle
Yar_Client::__call
Yar


Call service

Yar_Client
Yar_Client::__construct
Yar_Client
PHP Manual

Yar_Client::__call

(PECL yar >= 1.0.0)

Yar_Client::__call — Call service

Descrierea

public void Yar_Client::__call ( string $method , array $parameters )

Issue a call to remote RPC method.

Parametri

method

Remote RPC method name.

parameters

Parameters.

Valorile întoarse

Exemple

Example #1 Yar_Client::__call() example

<?php

$client = new Yar_Client("http://host/api/");

/* call remote service */
$result = $client->some_method("parameter");
?>

Exemplul de mai sus va afi?a ceva similar cu:

A se vedea ?i

  • Yar_Client::setOpt() - Set calling contexts
    •

Yar_Client

Yar_Client::__construct

Yar_Client


Create a client

Yar_Client::__call
Yar_Client::setOpt
Yar_Client
PHP Manual

Yar_Client::__construct

(PECL yar >= 1.0.0)

Yar_Client::__construct — Create a client

Descrierea

final public Yar_Client::__construct ( string $url )

Create a Yar_Client to a Yar_Server.

Parametri

url

Yar Server URL.

Valorile întoarse

Yar_Client instance.

Exemple

Example #1 Yar_Client::__construct() example

<?php
$client = new Yar_Client("http://host/api/");
?>

Exemplul de mai sus va afi?a ceva similar cu:

A se vedea ?i

  • Yar_Client::__call() - Call service
    •

  • Yar_Client::setOpt() - Set calling contexts
    •

Yar_Client::__call

Yar_Client::setOpt

Yar_Client


Set calling contexts

Yar_Client::__construct
Yar_Concurrent_Client
Yar_Client
PHP Manual

Yar_Client::setOpt

(PECL yar >= 1.0.0)

Yar_Client::setOpt — Set calling contexts

Descrierea

public boolean Yar_Client::setOpt ( number $name , mixed $value )

Parametri

name

it can be: YAR_OPT_PACKAGER, YAR_OPT_PERSISTENT (Need server support), YAR_OPT_TIMEOUT, YAR_OPT_CONNECT_TIMEOUT

value

Valorile întoarse

Exemple

Example #1 Yar_Client::setOpt() example

<?php

$cient = new Yar_Client("http://host/api/");

//Set timeout to 1s
$client->SetOpt(YAR_OPT_CONNECT_TIMEOUT, 1000);

//Set packager to JSON
$client->SetOpt(YAR_OPT_PACKAGER, "json");

/* call remote service */
$result = $client->some_method("parameter");
?>

Exemplul de mai sus va afi?a ceva similar cu:

A se vedea ?i

  • Yar_Client::__call() - Call service
    •

Yar_Client::__construct

Yar_Concurrent_Client

Yar_Client


The Yar_Concurrent_Client class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

Yar_Concurrent_Client {
/* Proprieta?i */
static $_callstack ;
static $_callback ;
static $_error_callback ;
/* Metode */
public static int call ( string $uri , string $method , array $parameters [, callable $callback ] )
public static boolean loop ([ callable $callback [, callable $error_callback ]] )
public static boolean reset ( void )
}

Proprieta?i

_callstack

_callback

_error_callback

Cuprins

  • Yar_Concurrent_Client::call — Register a concurrent call
  • Yar_Concurrent_Client::loop — Send all calls
  • Yar_Concurrent_Client::reset — Clean all registered calls
Yar_Client::setOpt
Yar_Concurrent_Client::call
Yar


Register a concurrent call

Yar_Concurrent_Client
Yar_Concurrent_Client::loop
Yar_Concurrent_Client
PHP Manual

Yar_Concurrent_Client::call

(PECL yar >= 1.0.0)

Yar_Concurrent_Client::call — Register a concurrent call

Descrierea

public static int Yar_Concurrent_Client::call ( string $uri , string $method , array $parameters [, callable $callback ] )

Register a RPC call, but won't sent it immediately, it will be send while further call to Yar_Concurrent_Client::loop()

Parametri

uri

The RPC server URI(http, tcp)

method

Service name(aka the method name)

parameters

Parameters

callback

A function callback, which will be called while the response return.

Valorile întoarse

An unique id, can be used to identified which call it is.

Exemple

Example #1 Yar_Concurrent_Client::call() example

<?php
function callback($retval, $callinfo) {
     var_dump($retval);
}

function error_callback($type, $error, $callinfo) {
    error_log($error);
}

Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback");
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"));   // if the callback is not specificed,
                                                                               // callback in loop will be used
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_PACKAGER => "json"));
                                                                               //this server accept json packager
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_TIMEOUT=>1));
                                                                               //custom timeout

//The requests are not sent yet
?>

Exemplul de mai sus va afi?a ceva similar cu:

A se vedea ?i

  • Yar_Concurrent_Client::loop() - Send all calls
    •

  • Yar_Concurrent_Client::reset() - Clean all registered calls
    •

  • Yar_Server::__construct() - Register a server
    •

  • Yar_Server::handle() - Start RPC Server
    •

Yar_Concurrent_Client

Yar_Concurrent_Client::loop

Yar_Concurrent_Client


Send all calls

Yar_Concurrent_Client::call
Yar_Concurrent_Client::reset
Yar_Concurrent_Client
PHP Manual

Yar_Concurrent_Client::loop

(PECL yar >= 1.0.0)

Yar_Concurrent_Client::loop — Send all calls

Descrierea

public static boolean Yar_Concurrent_Client::loop ([ callable $callback [, callable $error_callback ]] )

Send all registed remote RPC calls.

Parametri

callback

If this callback is set, then Yar will call this callback after all calls are sent and before any response return, with a $callinfo NULL.

Then, if user didn't specify callback when registering concurrent call, this callback will be used to handle response, otherwise, the callback specified while registering will be used.

error_callback

If this callback is set, then Yar will call this callback while error occurred.

Valorile întoarse

Exemple

Example #1 Yar_Concurrent_Client::loop() example

<?php
function callback($retval, $callinfo) {
     if ($callinfo == NULL) {
        echo "Now, all requests are sent, and no any response available\n";
     } else {
        echo "This is a remote call response, the method name is", $callinfo["method"],
             ". calling sequence is " , $callinfo["sequence"] , "\n";
        var_dump($retval);
     }
}

function error_callback($type, $error, $callinfo) {
    error_log($error);
}

Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback");
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"));   // if the callback is not specificed,
                                                                               // callback in loop will be used
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_PACKAGER => "json"));
                                                                               //this server accept json packager
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_TIMEOUT=>1));
                                                                               //custom timeout

Yar_Concurrent_Client::loop("callback", "error_callback"); //send the requests,
                                                           //the error_callback is optional
?>

Exemplul de mai sus va afi?a ceva similar cu:

Now, all requests are sent, and no any response available
This is a remote call response, the method name issome_method. calling sequence is 4
string(11) "some_method"
This is a remote call response, the method name issome_method. calling sequence is 1
string(11) "some_method"
This is a remote call response, the method name issome_method. calling sequence is 2
string(11) "some_method"
This is a remote call response, the method name issome_method. calling sequence is 3
string(11) "some_method"

A se vedea ?i

  • Yar_Concurrent_Client::call() - Register a concurrent call
  • Yar_Concurrent_Client::reset() - Clean all registered calls
  • Yar_Server::__construct() - Register a server
  • Yar_Server::handle() - Start RPC Server
Yar_Concurrent_Client::call
Yar_Concurrent_Client::reset
Yar_Concurrent_Client


Clean all registered calls

Yar_Concurrent_Client::loop
Yar_Server_Exception
Yar_Concurrent_Client
PHP Manual

Yar_Concurrent_Client::reset

(No version information available, might only be in Git)

Yar_Concurrent_Client::reset — Clean all registered calls

Descrierea

public static boolean Yar_Concurrent_Client::reset ( void )

Clean all registered calls

Parametri

Valorile întoarse

Exemple

Example #1 Yar_Concurrent_Client::reset() example

Exemplul de mai sus va afi?a ceva similar cu:

A se vedea ?i

  • Yar_Concurrent_Client::call() - Register a concurrent call
    •

  • Yar_Concurrent_Client::loop() - Send all calls
    •

  • Yar_Server::__construct() - Register a server
    •

  • Yar_Server::handle() - Start RPC Server
    •

Yar_Concurrent_Client::loop

Yar_Server_Exception

Yar_Concurrent_Client


The Yar_Server_Exception class

(No version information available, might only be in Git)

Introducere

If service threw exceptions, A Yar_Server_Exception will be threw in client side.

Sinopsisul clasei

Yar_Server_Exception extends Exception {
/* Proprieta?i */
protected $_type ;
/* Metode */
public string getType ( void )
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Proprieta?i

message

code

file

line

_type

Cuprins

  • Yar_Server_Exception::getType — The getType purpose
Yar_Concurrent_Client::reset
Yar_Server_Exception::getType
Yar


The getType purpose

Yar_Server_Exception
Yar_Client_Exception
Yar_Server_Exception
PHP Manual

Yar_Server_Exception::getType

(PECL yar >= 1.0.0)

Yar_Server_Exception::getType — The getType purpose

Descrierea

public string Yar_Server_Exception::getType ( void )

Get the exception original type threw by server

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

string

Exemple

Example #1 Yar_Server_Exception::getType() example

//Server.php
<?php
class Custom_Exception extends Exception {};

class API {
    public function throw_exception($name) {
        throw new Custom_Exception($name);
    }
}

$service = new Yar_Server(new API());
$service->handle();
?>

//Client.php
<?php
$client = new Yar_Client("http://host/api.php");

try {
    $client->throw_exception("client");
} catch (Yar_Server_Exception $e) {
    var_dump($e->getType());
    var_dump($e->getMessage());
}

Exemplul de mai sus va afi?a ceva similar cu:

string(16) "Custom_Exception"
string(6) "client"

A se vedea ?i

Yar_Server_Exception
Yar_Client_Exception
Yar_Server_Exception


The Yar_Client_Exception class

(No version information available, might only be in Git)

Introducere

Sinopsisul clasei

Yar_Client_Exception extends Exception {
/* Proprieta?i */
/* Metode */
public void getType ( void )
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Proprieta?i

message

code

file

line

Cuprins

  • Yar_Client_Exception::getType — The getType purpose
Yar_Server_Exception::getType
Yar_Client_Exception::getType
Yar


The getType purpose

Yar_Client_Exception
XML-RPC
Yar_Client_Exception
PHP Manual

Yar_Client_Exception::getType

(PECL yar >= 1.0.0)

Yar_Client_Exception::getType — The getType purpose

Descrierea

public void Yar_Client_Exception::getType ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Exemple

Example #1 Yar_Client_Exception::getType() example

<?php

/* ... */

?>

Exemplul de mai sus va afi?a ceva similar cu:

...

A se vedea ?i

Yar_Client_Exception
XML-RPC
Yar_Client_Exception


XML-RPC

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii XML-RPC
    • xmlrpc_decode_request — Decodifica XML în tipuri PHP indigene
    • xmlrpc_decode — Decodifica XML în tipuri indigene PHP
    • xmlrpc_encode_request — Genereaza XML pentru o cerere de metoda
    • xmlrpc_encode — Genereaza XML pentru o valoare PHP
    • xmlrpc_get_type — Ob?ine tipul xmlrpc pentru o valoare PHP
    • xmlrpc_is_fault — Determina daca o valoare din array reprezinta o gre?eala XMLRPC
    • xmlrpc_parse_method_descriptions — Decodifica XML într-o lista de descrieri ale metodelor
    • xmlrpc_server_add_introspection_data — Adauga documenta?ia de introspec?ie
    • xmlrpc_server_call_method — Prelucreaza interpelarile ?i metodele de apel XML
    • xmlrpc_server_create — Creeaza un server xmlrpc
    • xmlrpc_server_destroy — Destroys server resources
    • xmlrpc_server_register_introspection_callback — Înregistreaza o func?ie PHP pentru a genera documenta?ie
    • xmlrpc_server_register_method — Înregistreaza o func?ie PHP unei metode de resursa ce corespunde method_name
    • xmlrpc_set_type — Stabile?te tipul xmlrpc, base64 sau datetime, pentru o valoare string PHP
Yar_Client_Exception::getType
Introducere
Servicii Web


Introducere

Aceste func?ii pot fi utilizate pentru a scrie servere ?i clien?i XML-RPC. Pute?i gasi mai multe informa?ii despre XML-RPC la » http://www.xmlrpc.com/, ?i mai multa documenta?ie despre aceasta extensie ?i func?iile sale la » http://xmlrpc-epi.sourceforge.net/.

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

XML-RPC
Instalarea / configurarea
XML-RPC


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
XML-RPC


Instalarea

Sus?inerea XML-RPC în PHP nu este activata implicit. Va trebui sa utiliza?i op?iunea de configurare --with-xmlrpc[=DIR] la compilarea PHP pentru a activa sus?inerea XML-RPC. Aceasta extensie este încorporata în PHP începând cu versiunea 4.1.0.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie define?te o resursa server XML-RPC întoarsa de xmlrpc_server_create().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii XML-RPC
XML-RPC


Func?ii XML-RPC

Cuprins

  • xmlrpc_decode_request — Decodifica XML în tipuri PHP indigene
  • xmlrpc_decode — Decodifica XML în tipuri indigene PHP
  • xmlrpc_encode_request — Genereaza XML pentru o cerere de metoda
  • xmlrpc_encode — Genereaza XML pentru o valoare PHP
  • xmlrpc_get_type — Ob?ine tipul xmlrpc pentru o valoare PHP
  • xmlrpc_is_fault — Determina daca o valoare din array reprezinta o gre?eala XMLRPC
  • xmlrpc_parse_method_descriptions — Decodifica XML într-o lista de descrieri ale metodelor
  • xmlrpc_server_add_introspection_data — Adauga documenta?ia de introspec?ie
  • xmlrpc_server_call_method — Prelucreaza interpelarile ?i metodele de apel XML
  • xmlrpc_server_create — Creeaza un server xmlrpc
  • xmlrpc_server_destroy — Destroys server resources
  • xmlrpc_server_register_introspection_callback — Înregistreaza o func?ie PHP pentru a genera documenta?ie
  • xmlrpc_server_register_method — Înregistreaza o func?ie PHP unei metode de resursa ce corespunde method_name
  • xmlrpc_set_type — Stabile?te tipul xmlrpc, base64 sau datetime, pentru o valoare string PHP
Constante predefinite
xmlrpc_decode_request
XML-RPC


Decodifica XML în tipuri PHP indigene

Func?ii XML-RPC
xmlrpc_decode
Func?ii XML-RPC
PHP Manual

xmlrpc_decode_request

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_decode_request — Decodifica XML în tipuri PHP indigene

Descrierea

mixed xmlrpc_decode_request ( string $xml , string &$method [, string $encoding ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Func?ii XML-RPC
xmlrpc_decode
Func?ii XML-RPC


Decodifica XML în tipuri indigene PHP

xmlrpc_decode_request
xmlrpc_encode_request
Func?ii XML-RPC
PHP Manual

xmlrpc_decode

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_decode — Decodifica XML în tipuri indigene PHP

Descrierea

mixed xmlrpc_decode ( string $xml [, string $encoding = "iso-8859-1" ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

xml

Raspunsul XML întors de metoda XMLRPC.

encoding

Codificarea întrarii sus?inuta de iconv.

Valorile întoarse

Întoarce un array, un integer, un string sau un boolean în dependen?a de raspunsul întors de metoda XMLRPC.

Exemple

Accesa?i exemplul din xmlrpc_encode_request().

A se vedea ?i

  • xmlrpc_encode_request() - Genereaza XML pentru o cerere de metoda
  • xmlrpc_is_fault() - Determina daca o valoare din array reprezinta o gre?eala XMLRPC

xmlrpc_decode_request
xmlrpc_encode_request
Func?ii XML-RPC


Genereaza XML pentru o cerere de metoda

xmlrpc_decode
xmlrpc_encode
Func?ii XML-RPC
PHP Manual

xmlrpc_encode_request

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_encode_request — Genereaza XML pentru o cerere de metoda

Descrierea

string xmlrpc_encode_request ( string $method , mixed $params [, array $output_options ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

method

Denumirea metodei pentru a fi apelata.

params

Parametrii metodei, compatibili cu semnatura metodei.

output_options

Tabloul ce specifica op?iunile de ie?ire posibile (valorile implicite sunt accentuate):

  • output_type: php, xml

  • verbosity: no_white_space, newlines_only, pretty

  • escaping: cdata, non-ascii, non-print, markup (poate fi un string cu o valoare sau un array cu valori multiple)

  • version: simple, xmlrpc, soap 1.1, auto

  • encoding: iso-8859-1, alte seturi de caractere sus?inute de iconv

Valorile întoarse

Întoarce un string con?inând reprezentarea XML a cererii.

Exemple

Example #1 Exemplu al func?iilor client XMLRPC

<?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);
}
?>

A se vedea ?i

  • stream_context_create() - Creates a stream context
  • file_get_contents() - Reads entire file into a string
  • xmlrpc_decode() - Decodifica XML în tipuri indigene PHP

xmlrpc_decode
xmlrpc_encode
Func?ii XML-RPC


Genereaza XML pentru o valoare PHP

xmlrpc_encode_request
xmlrpc_get_type
Func?ii XML-RPC
PHP Manual

xmlrpc_encode

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_encode — Genereaza XML pentru o valoare PHP

Descrierea

string xmlrpc_encode ( mixed $value )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

xmlrpc_encode_request
xmlrpc_get_type
Func?ii XML-RPC


Ob?ine tipul xmlrpc pentru o valoare PHP

xmlrpc_encode
xmlrpc_is_fault
Func?ii XML-RPC
PHP Manual

xmlrpc_get_type

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_get_type — Ob?ine tipul xmlrpc pentru o valoare PHP

Descrierea

string xmlrpc_get_type ( mixed $value )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Aceasta func?ie este utila în special pentru string-uri base64 ?i datetime.

Parametri

value

Valoarea PHP

Valorile întoarse

Întoarce tipul XML-RPC.

Exemple

Example #1 Exemplu cu tip XML-RPC

<?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
?>

A se vedea ?i

  • xmlrpc_set_type() - Stabile?te tipul xmlrpc, base64 sau datetime, pentru o valoare string PHP

xmlrpc_encode
xmlrpc_is_fault
Func?ii XML-RPC


Determina daca o valoare din array reprezinta o gre?eala XMLRPC

xmlrpc_get_type
xmlrpc_parse_method_descriptions
Func?ii XML-RPC
PHP Manual

xmlrpc_is_fault

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

xmlrpc_is_fault — Determina daca o valoare din array reprezinta o gre?eala XMLRPC

Descrierea

bool xmlrpc_is_fault ( array $arg )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

arg

Tabloul întors de xmlrpc_decode().

Valorile întoarse

Întoarce TRUE daca argumentul exprima o gre?eala, FALSE în caz contrar. Descrierea erorii este disponibila în $arg["faultString"], codul gre?elii este în $arg["faultCode"].

Exemple

Accesa?i exemplul din xmlrpc_encode_request().

A se vedea ?i

  • xmlrpc_decode() - Decodifica XML în tipuri indigene PHP

xmlrpc_get_type
xmlrpc_parse_method_descriptions
Func?ii XML-RPC


Decodifica XML într-o lista de descrieri ale metodelor

xmlrpc_is_fault
xmlrpc_server_add_introspection_data
Func?ii XML-RPC
PHP Manual

xmlrpc_parse_method_descriptions

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_parse_method_descriptions — Decodifica XML într-o lista de descrieri ale metodelor

Descrierea

array xmlrpc_parse_method_descriptions ( string $xml )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

xmlrpc_is_fault
xmlrpc_server_add_introspection_data
Func?ii XML-RPC


Adauga documenta?ia de introspec?ie

xmlrpc_parse_method_descriptions
xmlrpc_server_call_method
Func?ii XML-RPC
PHP Manual

xmlrpc_server_add_introspection_data

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_add_introspection_data — Adauga documenta?ia de introspec?ie

Descrierea

int xmlrpc_server_add_introspection_data ( resource $server , array $desc )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

xmlrpc_parse_method_descriptions
xmlrpc_server_call_method
Func?ii XML-RPC


Prelucreaza interpelarile ?i metodele de apel XML

xmlrpc_server_add_introspection_data
xmlrpc_server_create
Func?ii XML-RPC
PHP Manual

xmlrpc_server_call_method

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_call_method — Prelucreaza interpelarile ?i metodele de apel XML

Descrierea

string xmlrpc_server_call_method ( resource $server , string $xml , mixed $user_data [, array $output_options ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

xmlrpc_server_add_introspection_data
xmlrpc_server_create
Func?ii XML-RPC


Creeaza un server xmlrpc

xmlrpc_server_call_method
xmlrpc_server_destroy
Func?ii XML-RPC
PHP Manual

xmlrpc_server_create

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_create — Creeaza un server xmlrpc

Descrierea

resource xmlrpc_server_create ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

xmlrpc_server_call_method
xmlrpc_server_destroy
Func?ii XML-RPC


Destroys server resources

xmlrpc_server_create
xmlrpc_server_register_introspection_callback
Func?ii XML-RPC
PHP Manual

xmlrpc_server_destroy

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_destroy — Destroys server resources

Descrierea

int xmlrpc_server_destroy ( resource $server )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

xmlrpc_server_create
xmlrpc_server_register_introspection_callback
Func?ii XML-RPC


Înregistreaza o func?ie PHP pentru a genera documenta?ie

xmlrpc_server_destroy
xmlrpc_server_register_method
Func?ii XML-RPC
PHP Manual

xmlrpc_server_register_introspection_callback

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_register_introspection_callback — Înregistreaza o func?ie PHP pentru a genera documenta?ie

Descrierea

bool xmlrpc_server_register_introspection_callback ( resource $server , string $function )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

xmlrpc_server_destroy
xmlrpc_server_register_method
Func?ii XML-RPC


Înregistreaza o func?ie PHP unei metode de resursa ce corespunde method_name

xmlrpc_server_register_introspection_callback
xmlrpc_set_type
Func?ii XML-RPC
PHP Manual

xmlrpc_server_register_method

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_register_method — Înregistreaza o func?ie PHP unei metode de resursa ce corespunde method_name

Descrierea

bool xmlrpc_server_register_method ( resource $server , string $method_name , string $function )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

xmlrpc_server_register_introspection_callback
xmlrpc_set_type
Func?ii XML-RPC


Stabile?te tipul xmlrpc, base64 sau datetime, pentru o valoare string PHP

xmlrpc_server_register_method
Extensii doar pentru Windows
Func?ii XML-RPC
PHP Manual

xmlrpc_set_type

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_set_type — Stabile?te tipul xmlrpc, base64 sau datetime, pentru o valoare string PHP

Descrierea

bool xmlrpc_set_type ( string &$value , string $type )

Stabile?te tipul xmlrpc, base64 sau datetime, pentru o valoare-?ir PHP.

Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Parametri

value

Valoarea în care se stabile?te tipul

type

'base64' sau 'datetime'

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. În cazul succesului, value este transformat într-un obiect.

Exemple

Example #1 Un exemplu xmlrpc_set_type()

<?php

$params = date("Ymd\TH:i:s", time());
xmlrpc_set_type($params, 'datetime');
echo xmlrpc_encode($params);

?>

Exemplul de mai sus va afi?a ceva similar cu:

<?xml version="1.0" encoding="utf-8"?>
<params>
<param>
 <value>
  <dateTime.iso8601>20090322T23:43:03</dateTime.iso8601>
 </value>
</param>
</params>

Erori/Excep?ii

Emite un E_WARNING cu tipul nesus?inut de XMLRPC.

xmlrpc_server_register_method
Extensii doar pentru Windows
Func?ii XML-RPC


Extensii doar pentru Windows

  • COM — COM and .Net (Windows)
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Erorile ?i prelucrarea lor
    • Exemple
    • COM — The COM class
    • DOTNET — The DOTNET class
    • VARIANT — VARIANT class
    • COM Func?ii
  • win32ps
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii win32ps
  • win32service
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii win32service
xmlrpc_set_type
COM
Informa?ii de referin?a despre func?ii


COM and .Net (Windows)

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Erorile ?i prelucrarea lor
  • Exemple
    • For Each
    • Arrays and Array-style COM properties
  • COM — The COM class
  • DOTNET — The DOTNET class
  • VARIANT — VARIANT class
  • COM Func?ii
    • 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_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
    • 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
Extensii doar pentru Windows
Introducere
Extensii doar pentru Windows


Introducere

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 been 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
Instalarea / configurarea
COM


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
COM


Necesita?i

COM functions are only available for the Windows version of PHP.

.Net support requires PHP 5 and the .Net runtime.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

As of PHP 5.3.15 / 5.4.5, this extension requires php_com_dotnet.dll to be enabled inside of php.ini in order to use these functions. Previous versions of PHP enabled these extensions by default.

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în php.ini.

Com configuration options
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
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.
Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i Where a configuration setting may be set.

Iata o explica?ie pe scurt a directivelor de configurare.

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.

Nota: 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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

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).

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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. |
Tipurile resurselor
Erorile ?i prelucrarea lor
COM


Erorile ?i prelucrarea lor

Excep?ii (PHP 5)

Aceasta extensie va emite instan?e ale clasei com_exception de fiecare data când COM raporteaza o eroare poten?ial fatala. Toate excep?iile COM poseda o proprietate code bine definita care corespunde cu valoarea HRESULT întoarsa de diferite opera?ii COM. Pute?i utiliza acest cod pentru a lua decizii în program în privin?a prelucrarii excep?iei.

Constante predefinite
Exemple
COM


Exemple

Cuprins

  • For Each
  • Arrays and Array-style COM properties
Erorile ?i prelucrarea lor
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.

Example #1 For Each in ASP

<%
Set domainObject = GetObject("WinNT://Domain")
For Each obj in domainObject
  Response.Write obj.Name & "<br />"
Next
%>

Example #2 foreach in PHP

<?php
$domainObject = new COM("WinNT://Domain");
foreach ($domainObject as $obj) {
   echo $obj->Name . "<br />";
}
?>

Exemple
Arrays and Array-style COM properties
Exemple


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
Exemple


The COM class

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

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::__construct ( 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.

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.

Avertizare

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.

Avertizare

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

Example #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;
?>

Example #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, PHP 7)

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::__construct ( 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.

Example #1 DOTNET example

<?php
 $stack = new DOTNET("mscorlib", "System.Collections.Stack");
 $stack->Push(".Net");
 $stack->Push("Hello ");
 echo $stack->Pop() . $stack->Pop();
?>

Nota:

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, PHP 7)

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::__construct ([ 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 Constante predefinite. 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:

Example #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/>";
?>

Example #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.

Nota:

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 printing 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 Func?ii
COM


COM Func?ii

A se vedea ?i

For further information on COM read the » COM specification. 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.

Cuprins

  • 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_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
  • 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_create_guid
COM


Generate a globally unique identifier (GUID)

COM Func?ii
com_event_sink
COM Func?ii
PHP Manual

com_create_guid

(PHP 5, PHP 7)

com_create_guid — Generate a globally unique identifier (GUID)

Descrierea

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.

Valorile întoarse

Returns the GUID as a string.

A se vedea ?i

  • uuid_create() in the PECL uuid extension

COM Func?ii
com_event_sink
COM Func?ii


Connect events from a COM object to a PHP object

com_create_guid
com_get_active_object
COM Func?ii
PHP Manual

com_event_sink

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

com_event_sink — Connect events from a COM object to a PHP object

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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;
?>

A se vedea ?i

  • 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 Func?ii


Returns a handle to an already running instance of a COM object

com_event_sink
com_load_typelib
COM Func?ii
PHP Manual

com_get_active_object

(PHP 5, PHP 7)

com_get_active_object — Returns a handle to an already running instance of a COM object

Descrierea

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.

Parametri

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.

Valorile întoarse

If the requested object is running, it will be returned to your script just like any other COM object.

Erori/Excep?ii

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.

Note

Avertizare

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_load_typelib
COM Func?ii


Loads a Typelib

com_get_active_object
com_message_pump
COM Func?ii
PHP Manual

com_load_typelib

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

com_load_typelib — Loads a Typelib

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

com_get_active_object
com_message_pump
COM Func?ii


Process COM messages, sleeping for up to timeoutms milliseconds

com_load_typelib
com_print_typeinfo
COM Func?ii
PHP Manual

com_message_pump

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds

Descrierea

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.

Parametri

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.

Valorile întoarse

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_typelib
com_print_typeinfo
COM Func?ii


Print out a PHP class definition for a dispatchable interface

com_message_pump
variant_abs
COM Func?ii
PHP Manual

com_print_typeinfo

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

com_print_typeinfo — Print out a PHP class definition for a dispatchable interface

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • com_event_sink() - Connect events from a COM object to a PHP object
  • com_load_typelib() - Loads a Typelib

com_message_pump
variant_abs
COM Func?ii


Returns the absolute value of a variant

com_print_typeinfo
variant_add
COM Func?ii
PHP Manual

variant_abs

(PHP 5, PHP 7)

variant_abs — Returns the absolute value of a variant

Descrierea

mixed variant_abs ( mixed $val )

Returns the absolute value of a variant.

Parametri

val

The variant.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

Returns the absolute value of val.

A se vedea ?i

  • abs() - Absolute value

com_print_typeinfo
variant_add
COM Func?ii


"Adds" two variant values together and returns the result

variant_abs
variant_and
COM Func?ii
PHP Manual

variant_add

(PHP 5, PHP 7)

variant_add — "Adds" two variant values together and returns the result

Descrierea

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

Parametri

left

The left operand.

right

The right operand.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

Returns the result.

A se vedea ?i

  • variant_sub() - Subtracts the value of the right variant from the left variant value

variant_abs
variant_and
COM Func?ii


Performs a bitwise AND operation between two variants

variant_add
variant_cast
COM Func?ii
PHP Manual

variant_and

(PHP 5, PHP 7)

variant_and — Performs a bitwise AND operation between two variants

Descrierea

mixed variant_and ( mixed $left , mixed $right )

Performs a bitwise AND operation. Note that this is slightly different from a regular AND operation.

Parametri

left

The left operand.

right

The right operand.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

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

A se vedea ?i

  • variant_or() - Performs a logical disjunction on two variants

variant_add
variant_cast
COM Func?ii


Convert a variant into a new variant object of another type

variant_and
variant_cat
COM Func?ii
PHP Manual

variant_cast

(PHP 5, PHP 7)

variant_cast — Convert a variant into a new variant object of another type

Descrierea

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.

Parametri

variant

The variant.

type

type should be one of the VT_XXX constants.

Valorile întoarse

Returns a variant of given type.

A se vedea ?i

  • variant_set_type() - Convert a variant into another type "in-place"

variant_and
variant_cat
COM Func?ii


concatenates two variant values together and returns the result

variant_cast
variant_cmp
COM Func?ii
PHP Manual

variant_cat

(PHP 5, PHP 7)

variant_cat — concatenates two variant values together and returns the result

Descrierea

mixed variant_cat ( mixed $left , mixed $right )

Concatenates left with right and returns the result.

This function is notionally equivalent to $left . $right.

Parametri

left

The left operand.

right

The right operand.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

Returns the result of the concatenation.

A se vedea ?i

  • String Operators for the string concatenation operator

variant_cast
variant_cmp
COM Func?ii


Compares two variants

variant_cat
variant_date_from_timestamp
COM Func?ii
PHP Manual

variant_cmp

(PHP 5, PHP 7)

variant_cmp — Compares two variants

Descrierea

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.

Parametri

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

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

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 Func?ii


Returns a variant date representation of a Unix timestamp

variant_cmp
variant_date_to_timestamp
COM Func?ii
PHP Manual

variant_date_from_timestamp

(PHP 5, PHP 7)

variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp

Descrierea

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.

Parametri

timestamp

A unix timestamp.

Valorile întoarse

Returns a VT_DATE variant.

A se vedea ?i

  • variant_date_to_timestamp() - Converts a variant date/time value to Unix timestamp
  • mktime() - Ob?ine timestamp-ul Unix pentru o data ?i ora
  • time() - Întoarce timpul curent Unix

variant_cmp
variant_date_to_timestamp
COM Func?ii


Converts a variant date/time value to Unix timestamp

variant_date_from_timestamp
variant_div
COM Func?ii
PHP Manual

variant_date_to_timestamp

(PHP 5, PHP 7)

variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp

Descrierea

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.

Parametri

variant

The variant.

Valorile întoarse

Returns a unix timestamp.

A se vedea ?i

  • variant_date_from_timestamp() - Returns a variant date representation of a Unix timestamp
  • date() - Formateaza o ora/data
  • strftime() - Formateaza o ora/data locala în conformitate cu setarile locale

variant_date_from_timestamp
variant_div
COM Func?ii


Returns the result from dividing two variants

variant_date_to_timestamp
variant_eqv
COM Func?ii
PHP Manual

variant_div

(PHP 5, PHP 7)

variant_div — Returns the result from dividing two variants

Descrierea

mixed variant_div ( mixed $left , mixed $right )

Divides left by right and returns the result.

Parametri

left

The left operand.

right

The right operand.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

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

A se vedea ?i

  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

variant_date_to_timestamp
variant_eqv
COM Func?ii


Performs a bitwise equivalence on two variants

variant_div
variant_fix
COM Func?ii
PHP Manual

variant_eqv

(PHP 5, PHP 7)

variant_eqv — Performs a bitwise equivalence on two variants

Descrierea

mixed variant_eqv ( mixed $left , mixed $right )

Performs a bitwise equivalence on two variants.

Parametri

left

The left operand.

right

The right operand.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

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 Func?ii


Returns the integer portion of a variant

variant_eqv
variant_get_type
COM Func?ii
PHP Manual

variant_fix

(PHP 5, PHP 7)

variant_fix — Returns the integer portion of a variant

Descrierea

mixed variant_fix ( mixed $variant )

Gets the integer portion of a variant.

Parametri

variant

The variant.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

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.

Note

Avertizare

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.

A se vedea ?i

  • variant_int() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - Round fractions down
  • ceil() - Round fractions up
  • round() - Rounds a float

variant_eqv
variant_get_type
COM Func?ii


Returns the type of a variant object

variant_fix
variant_idiv
COM Func?ii
PHP Manual

variant_get_type

(PHP 5, PHP 7)

variant_get_type — Returns the type of a variant object

Descrierea

int variant_get_type ( variant $variant )

Returns the type of a variant object.

Parametri

variant

The variant object.

Valorile întoarse

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 Func?ii


Converts variants to integers and then returns the result from dividing them

variant_get_type
variant_imp
COM Func?ii
PHP Manual

variant_idiv

(PHP 5, PHP 7)

variant_idiv — Converts variants to integers and then returns the result from dividing them

Descrierea

mixed variant_idiv ( mixed $left , mixed $right )

Converts left and right to integer values, and then performs integer division.

Parametri

left

The left operand.

right

The right operand.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

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

A se vedea ?i

  • variant_div() - Returns the result from dividing two variants

variant_get_type
variant_imp
COM Func?ii


Performs a bitwise implication on two variants

variant_idiv
variant_int
COM Func?ii
PHP Manual

variant_imp

(PHP 5, PHP 7)

variant_imp — Performs a bitwise implication on two variants

Descrierea

mixed variant_imp ( mixed $left , mixed $right )

Performs a bitwise implication operation.

Parametri

left

The left operand.

right

The right operand.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

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 Func?ii


Returns the integer portion of a variant

variant_imp
variant_mod
COM Func?ii
PHP Manual

variant_int

(PHP 5, PHP 7)

variant_int — Returns the integer portion of a variant

Descrierea

mixed variant_int ( mixed $variant )

Gets the integer portion of a variant.

Parametri

variant

The variant.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

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.

A se vedea ?i

  • variant_fix() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - Round fractions down
  • ceil() - Round fractions up
  • round() - Rounds a float

variant_imp
variant_mod
COM Func?ii


Divides two variants and returns only the remainder

variant_int
variant_mul
COM Func?ii
PHP Manual

variant_mod

(PHP 5, PHP 7)

variant_mod — Divides two variants and returns only the remainder

Descrierea

mixed variant_mod ( mixed $left , mixed $right )

Divides left by right and returns the remainder.

Parametri

left

The left operand.

right

The right operand.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

Returns the remainder of the division.

A se vedea ?i

  • 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 Func?ii


Multiplies the values of the two variants

variant_mod
variant_neg
COM Func?ii
PHP Manual

variant_mul

(PHP 5, PHP 7)

variant_mul — Multiplies the values of the two variants

Descrierea

mixed variant_mul ( mixed $left , mixed $right )

Multiplies left by right.

Parametri

left

The left operand.

right

The right operand.

Boolean values are converted to -1 for FALSE and 0 for TRUE.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

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

A se vedea ?i

  • 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 Func?ii


Performs logical negation on a variant

variant_mul
variant_not
COM Func?ii
PHP Manual

variant_neg

(PHP 5, PHP 7)

variant_neg — Performs logical negation on a variant

Descrierea

mixed variant_neg ( mixed $variant )

Performs logical negation of variant.

Parametri

variant

The variant.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

Returns the result of the logical negation.

variant_mul
variant_not
COM Func?ii


Performs bitwise not negation on a variant

variant_neg
variant_or
COM Func?ii
PHP Manual

variant_not

(PHP 5, PHP 7)

variant_not — Performs bitwise not negation on a variant

Descrierea

mixed variant_not ( mixed $variant )

Performs bitwise not negation on variant and returns the result.

Parametri

variant

The variant.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

Returns the bitwise not negation. If variant is NULL, the result will also be NULL.

variant_neg
variant_or
COM Func?ii


Performs a logical disjunction on two variants

variant_not
variant_pow
COM Func?ii
PHP Manual

variant_or

(PHP 5, PHP 7)

variant_or — Performs a logical disjunction on two variants

Descrierea

mixed variant_or ( mixed $left , mixed $right )

Performs a bitwise OR operation. Note that this is slightly different from a regular OR operation.

Parametri

left

The left operand.

right

The right operand.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

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

A se vedea ?i

  • variant_and() - Performs a bitwise AND operation between two variants
  • variant_xor() - Performs a logical exclusion on two variants

variant_not
variant_pow
COM Func?ii


Returns the result of performing the power function with two variants

variant_or
variant_round
COM Func?ii
PHP Manual

variant_pow

(PHP 5, PHP 7)

variant_pow — Returns the result of performing the power function with two variants

Descrierea

mixed variant_pow ( mixed $left , mixed $right )

Returns the result of left to the power of right.

Parametri

left

The left operand.

right

The right operand.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

Returns the result of left to the power of right.

A se vedea ?i

  • pow() - Exponential expression

variant_or
variant_round
COM Func?ii


Rounds a variant to the specified number of decimal places

variant_pow
variant_set_type
COM Func?ii
PHP Manual

variant_round

(PHP 5, PHP 7)

variant_round — Rounds a variant to the specified number of decimal places

Descrierea

mixed variant_round ( mixed $variant , int $decimals )

Returns the value of variant rounded to decimals decimal places.

Parametri

variant

The variant.

decimals

Number of decimal places.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

Returns the rounded value.

A se vedea ?i

  • round() - Rounds a float

variant_pow
variant_set_type
COM Func?ii


Convert a variant into another type "in-place"

variant_round
variant_set
COM Func?ii
PHP Manual

variant_set_type

(PHP 5, PHP 7)

variant_set_type — Convert a variant into another type "in-place"

Descrierea

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().

Parametri

variant

The variant.

type

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • variant_cast() - Convert a variant into a new variant object of another type

variant_round
variant_set
COM Func?ii


Assigns a new value for a variant object

variant_set_type
variant_sub
COM Func?ii
PHP Manual

variant_set

(PHP 5, PHP 7)

variant_set — Assigns a new value for a variant object

Descrierea

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.

Parametri

variant

The variant.

value

Valorile întoarse

Nu este întoarsa nici o valoare.

variant_set_type
variant_sub
COM Func?ii


Subtracts the value of the right variant from the left variant value

variant_set
variant_xor
COM Func?ii
PHP Manual

variant_sub

(PHP 5, PHP 7)

variant_sub — Subtracts the value of the right variant from the left variant value

Descrierea

mixed variant_sub ( mixed $left , mixed $right )

Subtracts right from left.

Parametri

left

The left operand.

right

The right operand.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

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

A se vedea ?i

  • variant_add() - "Adds" two variant values together and returns the result

variant_set
variant_xor
COM Func?ii


Performs a logical exclusion on two variants

variant_sub
win32ps
COM Func?ii
PHP Manual

variant_xor

(PHP 5, PHP 7)

variant_xor — Performs a logical exclusion on two variants

Descrierea

mixed variant_xor ( mixed $left , mixed $right )

Performs a logical exclusion.

Parametri

left

The left operand.

right

The right operand.

Nota:

Ca ?i în cazul tuturor func?iilor aritmetice de variante, parametrii pentru aceasta func?ie pot fi sau de un tip PHP indigen (integer, string, floating point, boolean sau NULL), sau o instan?a a claselor COM, VARIANT sau DOTNET. Tipurile PHP indigene vor fi convertite în variante utilizând acelea?i reguli ca ?i cele din constructorul VARIANT clasei. De la obiectele COM ?i DOTNET se va lua valoarea proprieta?ii lor implicite ?i va fi utilizata ca valoare a variantei.

Func?iile aritmetice ale variantelor sunt ni?te înveli?uri ale func?iilor denumite similar în biblioteca COM; pentru informa?ii suplimentare despre aceste func?ii consulta?i biblioteca MSDN. Func?iile PHP sunt denumite un pic diferit; spre exemplu, variant_add() din PHP corespunde cu VarAdd() în documenta?ia MSDN.

Valorile întoarse

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

A se vedea ?i

  • variant_or() - Performs a logical disjunction on two variants
  • variant_and() - Performs a bitwise AND operation between two variants

variant_sub
win32ps
COM Func?ii


win32ps

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Win32ps examples
  • Func?ii win32ps
    • win32_ps_list_procs — List running processes
    • win32_ps_stat_mem — Stat memory utilization
    • win32_ps_stat_proc — Stat process
variant_xor
Introducere
Extensii doar pentru Windows


Introducere

The win32ps extension is a Windows specific extension that allows PHP retrieve statistics about process and memory utilization.

win32ps
Instalarea / configurarea
win32ps


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
win32ps


Necesita?i

Windows NT, Windows 2000, Windows XP or Windows Server 2003. Any version of Windows derived from Windows NT should be compatible.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/win32ps.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
win32ps


Exemple

Cuprins

  • Win32ps examples
Constante predefinite
Win32ps examples
win32ps


Win32ps examples

Example #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
            )

    )
*/
?>

Example #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
    )
*/
?>

Exemple
Func?ii win32ps
Exemple


Func?ii win32ps

Cuprins

  • 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

Func?ii win32ps
win32_ps_stat_mem
Func?ii win32ps
PHP Manual

win32_ps_list_procs

(PECL win32ps >= 1.0.1)

win32_ps_list_procs — List running processes

Descrierea

array win32_ps_list_procs ( void )

Retrieves statistics about all running processes.

Valorile întoarse

Returns FALSE on failure, or an array consisting of process statistics like win32_ps_stat_proc() returns for all running processes on success.

A se vedea ?i

  • win32_ps_stat_proc() - Stat process

Func?ii win32ps
win32_ps_stat_mem
Func?ii win32ps


Stat memory utilization

win32_ps_list_procs
win32_ps_stat_proc
Func?ii win32ps
PHP Manual

win32_ps_stat_mem

(PECL win32ps >= 1.0.1)

win32_ps_stat_mem — Stat memory utilization

Descrierea

array win32_ps_stat_mem ( void )

Retrieves statistics about the global memory utilization.

Valorile întoarse

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
Func?ii win32ps


Stat process

win32_ps_stat_mem
win32service
Func?ii win32ps
PHP Manual

win32_ps_stat_proc

(PECL win32ps >= 1.0.1)

win32_ps_stat_proc — Stat process

Descrierea

array win32_ps_stat_proc ([ int $pid = 0 ] )

Retrieves statistics about the process with the process id pid.

Parametri

pid

The process id of the process to stat. If omitted, the id of the current process.

Valorile întoarse

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.

A se vedea ?i

  • win32_ps_list_procs() - List running processes

win32_ps_stat_mem
win32service
Func?ii win32ps


win32service

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
    • 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
  • Exemple
  • Func?ii win32service
    • 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
Introducere
Extensii doar pentru Windows


Introducere

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
Instalarea / configurarea
win32service


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
win32service


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/win32service

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Cuprins

  • 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

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

Tipurile resurselor
Win32Service Service Type Bitmasks
win32service


Win32Service Service Type Bitmasks

Constante predefinite
Win32Service Service Status Constants
Constante predefinite
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.
Constante predefinite
Win32Service Service Status Constants
Constante predefinite


Win32Service Service Status Constants

Win32Service Service Type Bitmasks
Win32Service Service Control Message Constants
Constante predefinite
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
Constante predefinite


Win32Service Service Control Message Constants

Win32Service Service Status Constants
Win32Service Service Control Message Accepted Bitmasks
Constante predefinite
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
Constante predefinite


Win32Service Service Control Message Accepted Bitmasks

Win32Service Service Control Message Constants
Win32Service Service Start Type Constants
Constante predefinite
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
Constante predefinite


Win32Service Service Start Type Constants

Win32Service Service Control Message Accepted Bitmasks
Win32Service Service Error Control Constants
Constante predefinite
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
Constante predefinite


Win32Service Service Error Control Constants

Win32Service Service Start Type Constants
Win32Service Service Flag Constants
Constante predefinite
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
Constante predefinite


Win32Service Service Flag Constants

Win32Service Service Error Control Constants
Win32 Error Codes
Constante predefinite
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
Constante predefinite


Win32 Error Codes

Win32Service Service Flag Constants
Win32 Base Priority Classes
Constante predefinite
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
Constante predefinite


Win32 Base Priority Classes

Win32 Error Codes
Exemple
Constante predefinite
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
Exemple
Constante predefinite


Exemple

Example #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
));
?>

Example #2 Unregistering a service

<?php
win32_delete_service('dummyphp');
?>

Example #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
Func?ii win32service
win32service


Func?ii win32service

Cuprins

  • 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
Exemple
win32_continue_service
win32service


Resumes a paused service

Func?ii win32service
win32_create_service
Func?ii win32service
PHP Manual

win32_continue_service

(PECL win32service SVN)

win32_continue_service — Resumes a paused service

Descrierea

int win32_continue_service ( string $servicename [, string $machine ] )

Resumes a paused, named service. Requires administrative privileges.

Parametri

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Valorile întoarse

Întoarce WIN32_NO_ERROR în caz de succes, FALSE în caz ca este vre-o problema cu parametrii, sau un Cod de Eroare Win32 în caz de e?ec.

A se vedea ?i

  • win32_start_service() - Starts a service
  • Win32 Error Codes

Func?ii win32service
win32_create_service
Func?ii win32service


Creates a new service entry in the SCM database

win32_continue_service
win32_delete_service
Func?ii win32service
PHP Manual

win32_create_service

(PECL win32service SVN)

win32_create_service — Creates a new service entry in the SCM database

Descrierea

mixed win32_create_service ( array $details [, string $machine ] )

Parametri

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.

Valorile întoarse

Întoarce WIN32_NO_ERROR în caz de succes, FALSE în caz ca este vre-o problema cu parametrii, sau un Cod de Eroare Win32 în caz de e?ec.

Exemple

Example #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);
?>

A se vedea ?i

  • win32_delete_service() - Deletes a service entry from the SCM database
  • Win32 Base Priority Classes
  • Win32 Error Codes

win32_continue_service
win32_delete_service
Func?ii win32service


Deletes a service entry from the SCM database

win32_create_service
win32_get_last_control_message
Func?ii win32service
PHP Manual

win32_delete_service

(PECL win32service SVN)

win32_delete_service — Deletes a service entry from the SCM database

Descrierea

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.

Parametri

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Valorile întoarse

Întoarce WIN32_NO_ERROR în caz de succes, FALSE în caz ca este vre-o problema cu parametrii, sau un Cod de Eroare Win32 în caz de e?ec.

Exemple

Example #1 A win32_delete_service() example

Deletes the dummyphp service.

<?php
win32_delete_service('dummyphp');
?>

A se vedea ?i

  • win32_create_service() - Creates a new service entry in the SCM database
  • Win32 Error Codes

win32_create_service
win32_get_last_control_message
Func?ii win32service


Returns the last control message that was sent to this service

win32_delete_service
win32_pause_service
Func?ii win32service
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

Descrierea

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.

Valorile întoarse

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.

A se vedea ?i

  • 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
Func?ii win32service


Pauses a service

win32_get_last_control_message
win32_query_service_status
Func?ii win32service
PHP Manual

win32_pause_service

(PECL win32service SVN)

win32_pause_service — Pauses a service

Descrierea

int win32_pause_service ( string $servicename [, string $machine ] )

Pauses a named service. Requires administrative privileges.

Parametri

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Valorile întoarse

Întoarce WIN32_NO_ERROR în caz de succes, FALSE în caz ca este vre-o problema cu parametrii, sau un Cod de Eroare Win32 în caz de e?ec.

A se vedea ?i

  • win32_start_service() - Starts a service
  • Win32 Error Codes

win32_get_last_control_message
win32_query_service_status
Func?ii win32service


Queries the status of a service

win32_pause_service
win32_set_service_status
Func?ii win32service
PHP Manual

win32_query_service_status

(PECL win32service SVN)

win32_query_service_status — Queries the status of a service

Descrierea

mixed win32_query_service_status ( string $servicename [, string $machine ] )

Queries the current status for a service, returning an array of information.

Parametri

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Valorile întoarse

Returns an array consisting of the following information on success, FALSE în caz ca este vre-o problema cu parametrii, sau un Cod de Eroare Win32 în caz de e?ec.

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.

A se vedea ?i

  • Win32Service Predefined Constants

win32_pause_service
win32_set_service_status
Func?ii win32service


Update the service status

win32_query_service_status
win32_start_service_ctrl_dispatcher
Func?ii win32service
PHP Manual

win32_set_service_status

(PECL win32service SVN)

win32_set_service_status — Update the service status

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce TRUE în caz de succes, FALSE în caz ca este vre-o problema cu parametrii, sau un Cod de Eroare Win32 în caz de e?ec.

A se vedea ?i

  • 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
Func?ii win32service


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
Func?ii win32service
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

Descrierea

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.

Parametri

name

The short-name of the service, as registered by win32_create_service().

Valorile întoarse

Întoarce TRUE în caz de succes, FALSE în caz ca este vre-o problema cu parametrii, sau un Cod de Eroare Win32 în caz de e?ec.

Exemple

Example #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
}
?>

A se vedea ?i

  • 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
Func?ii win32service


Starts a service

win32_start_service_ctrl_dispatcher
win32_stop_service
Func?ii win32service
PHP Manual

win32_start_service

(PECL win32service SVN)

win32_start_service — Starts a service

Descrierea

int win32_start_service ( string $servicename [, string $machine ] )

Attempts to start the named service. Usually requires administrative privileges.

Parametri

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Valorile întoarse

Întoarce WIN32_NO_ERROR în caz de succes, FALSE în caz ca este vre-o problema cu parametrii, sau un Cod de Eroare Win32 în caz de e?ec.

A se vedea ?i

  • win32_stop_service() - Stops a service
  • Win32 Error Codes

win32_start_service_ctrl_dispatcher
win32_stop_service
Func?ii win32service


Stops a service

win32_start_service
Manipularea XML
Func?ii win32service
PHP Manual

win32_stop_service

(PECL win32service SVN)

win32_stop_service — Stops a service

Descrierea

int win32_stop_service ( string $servicename [, string $machine ] )

Stops a named service. Requires administrative privileges.

Parametri

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Valorile întoarse

Întoarce WIN32_NO_ERROR în caz de succes, FALSE în caz ca este vre-o problema cu parametrii, sau un Cod de Eroare Win32 în caz de e?ec.

A se vedea ?i

  • win32_start_service() - Starts a service
  • Win32 Error Codes

win32_start_service
Manipularea XML
Func?ii win32service


Manipularea XML

  • DOM — Document Object Model
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • 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 Func?ii
  • libxml
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • libXMLError — The libXMLError class
    • Func?ii libxml
  • SDO — Service Data Objects
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Limitations
    • Exemple
    • SDO Func?ii
  • SDO-DAS-Relational — SDO Relational Data Access Service
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Limitations
    • SDO-DAS-Relational Func?ii
  • SDO DAS XML — SDO XML Data Access Service
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • SDO DAS XML Func?ii
  • SimpleXML
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • SimpleXMLElement — The SimpleXMLElement class
    • SimpleXMLIterator — The SimpleXMLIterator class
    • Func?ii SimpleXML
  • WDDX
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • Func?ii WDDX
  • XMLDiff — XML diff and merge
    • Introducere
    • Instalarea / configurarea
    • XMLDiff\Base — The XMLDiff\Base class
    • XMLDiff\DOM — The XMLDiff\DOM class
    • XMLDiff\Memory — The XMLDiff\Memory class
    • XMLDiff\File — The XMLDiff\File class
  • XML Parser
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Event Handlers
    • Case Folding
    • Error Codes
    • Character Encoding
    • Exemple
    • Func?ii ale interpretatorului XML
  • XMLReader
    • Introducere
    • Instalarea / configurarea
    • XMLReader — The XMLReader class
  • XMLWriter
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Func?ii XMLWriter
  • XSL
    • Introducere
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • XSLTProcessor — The XSLTProcessor class
win32_stop_service
DOM
Informa?ii de referin?a despre func?ii


Document Object Model

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • 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 — Creeaza un obiect nou DOMImplementation
    • 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 Func?ii
    • dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object
Manipularea XML
Introducere
Manipularea XML


Introducere

The DOM extension allows you to operate on XML documents through the DOM API with PHP.

Nota:

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
Instalarea / configurarea
DOM


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
DOM


Instalarea

Aceasta extensie este activata în mod implicit. Ea poate fi dezactivata utilizând urmatoarea op?iune la compilare: --disable-dom

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
Exemple
DOM


Exemple

Many examples in this reference require an XML file. We will use book.xml that contains the following:

Example #1 book.xml

<?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>
 <chapter id="books">
  <title>My books</title>
  <para>
   <informaltable>
    <tgroup cols="4">
     <thead>
      <row>
       <entry>Title</entry>
       <entry>Author</entry>
       <entry>Language</entry>
       <entry>ISBN</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
      <row>
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
      <row>
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
      <!-- TODO: I have a lot of remaining books to add.. -->
     </tbody>
    </tgroup>
   </informaltable>
  </para>
 </chapter>
</book>

Constante predefinite
DOMAttr
DOM


The DOMAttr class

(PHP 5, PHP 7)

Introducere

DOMAttr represents an attribute in the DOMElement object.

Sinopsisul clasei

DOMAttr extends DOMNode {
/* Proprieta?i */
public readonly string $name ;
public readonly DOMElement $ownerElement ;
public readonly bool $schemaTypeInfo ;
public readonly bool $specified ;
public string $value ;
/* Metode */
public __construct ( string $name [, string $value ] )
public bool isId ( void )
/* Metode mo?tenite */
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 )
}

Proprieta?i

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

A se vedea ?i

  • » W3C specification of Attr

Cuprins

  • DOMAttr::__construct — Creates a new DOMAttr object
  • DOMAttr::isId — Checks if attribute is a defined ID
Exemple
DOMAttr::__construct
DOM


Creates a new DOMAttr object

DOMAttr
DOMAttr::isId
DOMAttr
PHP Manual

DOMAttr::__construct

(PHP 5, PHP 7)

DOMAttr::__construct — Creates a new DOMAttr object

Descrierea

public 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.

Parametri

name

The tag name of the attribute.

value

The value of the attribute.

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a:

<?xml version="1.0" encoding="utf-8"?>
<root attr="attrvalue" />

A se vedea ?i

  • 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, PHP 7)

DOMAttr::isId — Checks if attribute is a defined ID

Descrierea

public 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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, PHP 7)

Introducere

The DOMCdataSection inherits from DOMText for textural representation of CData constructs.

Sinopsisul clasei

DOMCdataSection extends DOMText {
/* Methods */
public __construct ( string $value )
/* Inherited methods */
public bool DOMText::isWhitespaceInElementContent ( void )
public DOMText DOMText::splitText ( int $offset )
}

Cuprins

  • 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, PHP 7)

DOMCdataSection::__construct — Constructs a new DOMCdataSection object

Descrierea

public DOMCdataSection::__construct ( string $value )

Constructs a new CDATA node. This works like the DOMText class.

Parametri

value

The value of the CDATA node. If not supplied, an empty CDATA node is created.

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a:

<?xml version="1.0" encoding="utf-8"?>
<root><![CDATA[root value]]></root>

A se vedea ?i

  • DOMText::__construct() - Creates a new DOMText object
  • DOMDocument::createTextNode() - Create new text node

DOMCdataSection
DOMCharacterData
DOMCdataSection


The DOMCharacterData class

(PHP 5, PHP 7)

Introducere

Represents nodes with character data. No nodes directly correspond to this class, but other nodes do inherit from it.

Sinopsisul clasei

DOMCharacterData extends DOMNode {
/* Proprieta?i */
public string $data ;
readonly public int $length ;
/* Metode */
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 )
/* Metode mo?tenite */
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 )
}

Proprieta?i

data

The contents of the node.

length

The length of the contents.

A se vedea ?i

  • » W3C specification of CharacterData

Cuprins

  • 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, PHP 7)

DOMCharacterData::appendData — Append the string to the end of the character data of the node

Descrierea

void DOMCharacterData::appendData ( string $data )

Append the string data to the end of the character data of the node.

Parametri

data

The string to append.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • 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, PHP 7)

DOMCharacterData::deleteData — Remove a range of characters from the node

Descrierea

void DOMCharacterData::deleteData ( int $offset , int $count )

Deletes count characters starting from position offset.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

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.

A se vedea ?i

  • 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, PHP 7)

DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset

Descrierea

void DOMCharacterData::insertData ( int $offset , string $data )

Inserts string data at position offset.

Parametri

offset

The character offset at which to insert.

data

The string to insert.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data.

A se vedea ?i

  • 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, PHP 7)

DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node

Descrierea

void DOMCharacterData::replaceData ( int $offset , int $count , string $data )

Replace count characters starting from position offset with data.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

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.

A se vedea ?i

  • 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, PHP 7)

DOMCharacterData::substringData — Extracts a range of data from the node

Descrierea

string DOMCharacterData::substringData ( int $offset , int $count )

Returns the specified substring.

Parametri

offset

Start offset of substring to extract.

count

The number of characters to extract.

Valorile întoarse

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.

Erori/Excep?ii

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.

A se vedea ?i

  • 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, PHP 7)

Introducere

Represents comment nodes, characters delimited by <!-- and -->.

Sinopsisul clasei

DOMComment extends DOMCharacterData {
/* Metode */
public __construct ([ string $value ] )
/* Metode mo?tenite */
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 )
}

A se vedea ?i

  • » W3C specification of Comment

Cuprins

  • 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, PHP 7)

DOMComment::__construct — Creates a new DOMComment object

Descrierea

public 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.

Parametri

value

The value of the comment.

Exemple

Example #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> */

?>

A se vedea ?i

  • DOMDocument::createComment() - Create new comment node

DOMComment
DOMDocument
DOMComment


The DOMDocument class

(PHP 5, PHP 7)

Introducere

Represents an entire HTML or XML document; serves as the root of the document tree.

Sinopsisul clasei

DOMDocument extends DOMNode {
/* Proprieta?i */
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 ;
/* Metode */
public __construct ([ string $version [, string $encoding ]] )
public DOMAttr createAttribute ( string $name )
public DOMAttr createAttributeNS ( string $namespaceURI , string $qualifiedName )
public DOMCDATASection createCDATASection ( string $data )
public DOMComment createComment ( string $data )
public DOMDocumentFragment createDocumentFragment ( void )
public DOMElement createElement ( string $name [, string $value ] )
public DOMElement createElementNS ( string $namespaceURI , string $qualifiedName [, string $value ] )
public DOMEntityReference createEntityReference ( string $name )
public DOMProcessingInstruction createProcessingInstruction ( string $target [, string $data ] )
public DOMText createTextNode ( string $content )
public DOMElement getElementById ( string $elementId )
public DOMNodeList getElementsByTagName ( string $name )
public DOMNodeList getElementsByTagNameNS ( string $namespaceURI , string $localName )
public DOMNode importNode ( DOMNode $importedNode [, bool $deep ] )
public mixed load ( string $filename [, int $options = 0 ] )
public bool loadHTML ( string $source [, int $options = 0 ] )
public bool loadHTMLFile ( string $filename [, int $options = 0 ] )
public mixed loadXML ( string $source [, int $options = 0 ] )
public void normalizeDocument ( void )
public bool registerNodeClass ( string $baseclass , string $extendedclass )
public bool relaxNGValidate ( string $filename )
public bool relaxNGValidateSource ( string $source )
public int save ( string $filename [, int $options ] )
public string saveHTML ([ DOMNode $node = NULL ] )
public int saveHTMLFile ( string $filename )
public string saveXML ([ DOMNode $node [, int $options ]] )
public bool schemaValidate ( string $filename [, int $flags ] )
public bool schemaValidateSource ( string $source [, int $flags ] )
public bool validate ( void )
public int xinclude ([ int $options ] )
/* Metode mo?tenite */
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 )
}

Proprieta?i

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".

Note

Nota:

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.

A se vedea ?i

  • » W3C specification for Document

Cuprins

  • 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, PHP 7)

DOMDocument::__construct — Creates a new DOMDocument object

Descrierea

public DOMDocument::__construct ([ string $version [, string $encoding ]] )

Creates a new DOMDocument object.

Parametri

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.

Exemple

Example #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"?> */

?>

A se vedea ?i

  • 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, PHP 7)

DOMDocument::createAttribute — Create new attribute

Descrierea

public DOMAttr DOMDocument::createAttribute ( string $name )

This function creates a new instance of class DOMAttr. Acest nod nu va aparea în document daca nu este inserat cu DOMNode::appendChild() de exemplu.

Parametri

name

The name of the attribute.

Valorile întoarse

The new DOMAttr or FALSE if an error occurred.

Erori/Excep?ii

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

A se vedea ?i

  • 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, PHP 7)

DOMDocument::createAttributeNS — Create new attribute node with an associated namespace

Descrierea

public DOMAttr DOMDocument::createAttributeNS ( string $namespaceURI , string $qualifiedName )

This function creates a new instance of class DOMAttr. Acest nod nu va aparea în document daca nu este inserat cu DOMNode::appendChild() de exemplu.

Parametri

namespaceURI

The URI of the namespace.

qualifiedName

The tag name and prefix of the attribute, as prefix:tagname.

Valorile întoarse

The new DOMAttr or FALSE if an error occurred.

Erori/Excep?ii

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.

A se vedea ?i

  • 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, PHP 7)

DOMDocument::createCDATASection — Create new cdata node

Descrierea

public DOMCDATASection DOMDocument::createCDATASection ( string $data )

This function creates a new instance of class DOMCDATASection. Acest nod nu va aparea în document daca nu este inserat cu DOMNode::appendChild() de exemplu.

Parametri

data

The content of the cdata.

Valorile întoarse

The new DOMCDATASection or FALSE if an error occurred.

A se vedea ?i

  • 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, PHP 7)

DOMDocument::createComment — Create new comment node

Descrierea

public DOMComment DOMDocument::createComment ( string $data )

This function creates a new instance of class DOMComment. Acest nod nu va aparea în document daca nu este inserat cu DOMNode::appendChild() de exemplu.

Parametri

data

The content of the comment.

Valorile întoarse

The new DOMComment or FALSE if an error occurred.

A se vedea ?i

  • 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, PHP 7)

DOMDocument::createDocumentFragment — Create new document fragment

Descrierea

public DOMDocumentFragment DOMDocument::createDocumentFragment ( void )

This function creates a new instance of class DOMDocumentFragment. Acest nod nu va aparea în document daca nu este inserat cu DOMNode::appendChild() de exemplu.

Valorile întoarse

The new DOMDocumentFragment or FALSE if an error occurred.

A se vedea ?i

  • 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, PHP 7)

DOMDocument::createElement — Create new element node

Descrierea

public DOMElement DOMDocument::createElement ( string $name [, string $value ] )

This function creates a new instance of class DOMElement. Acest nod nu va aparea în document daca nu este inserat cu DOMNode::appendChild() de exemplu.

Parametri

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.

The value is used verbatim except that the < and > entity references will escaped. Note that & has to be manually escaped; otherwise it is regarded as starting an entity reference. Also " won't be escaped.

Valorile întoarse

Returns a new instance of class DOMElement or FALSE if an error occurred.

Erori/Excep?ii

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

<?xml version="1.0" encoding="utf-8"?>
<test>This is the root element!</test>

Example #2 Passing text containing an unescaped & as value

<?php
$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->createElement('foo', 'me & you');
$dom->appendChild($element);
echo $dom->saveXML();
?>

Exemplul de mai sus va afi?a ceva similar cu:

Warning: DOMDocument::createElement(): unterminated entity reference             you in /in/BjTCg on line 4
<?xml version="1.0" encoding="utf-8"?>
<foo/>

Note

Nota:

The value will not be escaped. Use DOMDocument::createTextNode() to create a text node with escaping support.

A se vedea ?i

  • 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, PHP 7)

DOMDocument::createElementNS — Create new element node with an associated namespace

Descrierea

public DOMElement DOMDocument::createElementNS ( string $namespaceURI , string $qualifiedName [, string $value ] )

This function creates a new element node with an associated namespace. Acest nod nu va aparea în document daca nu este inserat cu DOMNode::appendChild() de exemplu.

Parametri

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.

Valorile întoarse

The new DOMElement or FALSE if an error occurred.

Erori/Excep?ii

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a maformed qualified name.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

<?xml version="1.0" encoding="utf-8"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>

Example #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
?>

Exemplul de mai sus va afi?a:

<?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

A se vedea ?i

  • 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, PHP 7)

DOMDocument::createEntityReference — Create new entity reference node

Descrierea

public DOMEntityReference DOMDocument::createEntityReference ( string $name )

This function creates a new instance of class DOMEntityReference. Acest nod nu va aparea în document daca nu este inserat cu DOMNode::appendChild() de exemplu.

Parametri

name

The content of the entity reference, e.g. the entity reference minus the leading & and the trailing ; characters.

Valorile întoarse

The new DOMEntityReference or FALSE if an error occurred.

Erori/Excep?ii

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

A se vedea ?i

  • 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, PHP 7)

DOMDocument::createProcessingInstruction — Creates new PI node

Descrierea

public DOMProcessingInstruction DOMDocument::createProcessingInstruction ( string $target [, string $data ] )

This function creates a new instance of class DOMProcessingInstruction. Acest nod nu va aparea în document daca nu este inserat cu DOMNode::appendChild() de exemplu.

Parametri

target

The target of the processing instruction.

data

The content of the processing instruction.

Valorile întoarse

The new DOMProcessingInstruction or FALSE if an error occurred.

Erori/Excep?ii

DOM_INVALID_CHARACTER_ERR

Raised if target contains an invalid character.

A se vedea ?i

  • 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, PHP 7)

DOMDocument::createTextNode — Create new text node

Descrierea

public DOMText DOMDocument::createTextNode ( string $content )

This function creates a new instance of class DOMText. Acest nod nu va aparea în document daca nu este inserat cu DOMNode::appendChild() de exemplu.

Parametri

content

The content of the text.

Valorile întoarse

The new DOMText or FALSE if an error occurred.

A se vedea ?i

  • 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, PHP 7)

DOMDocument::getElementById — Searches for an element with a certain id

Descrierea

public 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.

Parametri

elementId

The unique id value for an element.

Valorile întoarse

Returns the DOMElement or NULL if the element is not found.

Exemple

Example #1 DOMDocument::getElementById() Example

Urmatoarele exemple utilizeaza book.xml ce con?ine urmatoarele:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books [
  <!ELEMENT books   (book+)>
  <!ELEMENT book    (title, author+, xhtml:blurb?)>
  <!ELEMENT title   (#PCDATA)>
  <!ELEMENT blurb   (#PCDATA)>
  <!ELEMENT author  (#PCDATA)>
  <!ATTLIST books   xmlns        CDATA  #IMPLIED>
  <!ATTLIST books   xmlns:xhtml  CDATA  #IMPLIED>
  <!ATTLIST book    id           ID     #IMPLIED>
  <!ATTLIST author  email        CDATA  #IMPLIED>
]>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<books xmlns="http://books.php/" xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <book id="php-basics">
    <title>PHP Basics</title>
    <author email="jim.smith@basics.php">Jim Smith</author>
    <author email="jane.smith@basics.php">Jane Smith</author>
    <xhtml:blurb><![CDATA[
<p><em>PHP Basics</em> provides an introduction to PHP.</p>
]]></xhtml:blurb>
  </book>
  <book id="php-advanced">
    <title>PHP Advanced Programming</title>
    <author email="jon.doe@advanced.php">Jon Doe</author>
  </book>
</books>
<?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 'php-basics' is: " . $doc->getElementById('php-basics')->tagName . "\n";

?>

Exemplul de mai sus va afi?a:

The element whose id is 'php-basics' is: book

A se vedea ?i

  • 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, PHP 7)

DOMDocument::getElementsByTagName — Searches for all elements with given local tag name

Descrierea

public DOMNodeList DOMDocument::getElementsByTagName ( string $name )

This function returns a new instance of class DOMNodeList containing all the elements with a given local tag name.

Parametri

name

The local name (without namespace) of the tag to match on. The special value * matches all tags.

Valorile întoarse

A new DOMNodeList object containing all the matched elements.

Exemple

Example #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;
}
?>

Exemplul de mai sus va afi?a:

Patterns of Enterprise Application Architecture
Design Patterns: Elements of Reusable Software Design
Clean Code

A se vedea ?i

  • 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, PHP 7)

DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace

Descrierea

public DOMNodeList DOMDocument::getElementsByTagNameNS ( string $namespaceURI , string $localName )

Returns a DOMNodeList of all elements with a given local name and a namespace URI.

Parametri

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.

Valorile întoarse

A new DOMNodeList object containing all the matched elements.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

local name: include, prefix: xi
local name: fallback, prefix: xi

A se vedea ?i

  • 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, PHP 7)

DOMDocument::importNode — Import node into current document

Descrierea

public DOMNode DOMDocument::importNode ( DOMNode $importedNode [, bool $deep ] )

This function returns a copy of the node to import and associates it with the current document.

Parametri

importedNode

The node to import.

deep

If set to TRUE, this method will recursively import the subtree under the importedNode.

Nota:

To copy the nodes attributes deep needs to be set to TRUE

Valorile întoarse

The copied node or FALSE, if it cannot be copied.

Erori/Excep?ii

DOMException is thrown if node cannot be imported.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

DOMDocument::load — Load XML from a file

Descrierea

public mixed DOMDocument::load ( string $filename [, int $options = 0 ] )

Loads an XML document from a file.

Avertizare

Unix style paths with forward slashes can cause significant performance degradation on Windows systems; be sure to call realpath() in such a case.

Parametri

filename

The path to the XML document.

options

Bitwise OR of the libxml option constants.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. If called statically, returns a DOMDocument sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Aceasta metoda poate fi apelata în mod static, dar va emite o eroare E_STRICT.

Exemple

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

A se vedea ?i

  • 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, PHP 7)

DOMDocument::loadHTML — Load HTML from a string

Descrierea

public bool DOMDocument::loadHTML ( string $source [, int $options = 0 ] )

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.

Parametri

source

The HTML string.

options

Since PHP 5.4.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. If called statically, returns a DOMDocument sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Aceasta metoda poate fi apelata în mod static, dar va emite o eroare E_STRICT.

Cu toate ca codul HTML deteriorat ar trebui sa se încarce cu succes, aceasta func?ie poate sa genereze erori de tip E_WARNING atunci când întâlne?te un marcaj gre?it. Func?iile de gestiune a erorilor libxml pot fi utilizate pentru a prelucra aceste erori.

Exemple

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
echo $doc->saveHTML();
?>

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added options parameter.

A se vedea ?i

  • 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, PHP 7)

DOMDocument::loadHTMLFile — Load HTML from a file

Descrierea

public bool DOMDocument::loadHTMLFile ( string $filename [, int $options = 0 ] )

The function parses the HTML document in the file named filename. Unlike loading XML, HTML does not have to be well-formed to load.

Parametri

filename

The path to the HTML file.

options

Since PHP 5.4.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. If called statically, returns a DOMDocument sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Aceasta metoda poate fi apelata în mod static, dar va emite o eroare E_STRICT.

Cu toate ca codul HTML deteriorat ar trebui sa se încarce cu succes, aceasta func?ie poate sa genereze erori de tip E_WARNING atunci când întâlne?te un marcaj gre?it. Func?iile de gestiune a erorilor libxml pot fi utilizate pentru a prelucra aceste erori.

Exemple

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
echo $doc->saveHTML();
?>

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added options parameter.

A se vedea ?i

  • 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, PHP 7)

DOMDocument::loadXML — Load XML from a string

Descrierea

public mixed DOMDocument::loadXML ( string $source [, int $options = 0 ] )

Loads an XML document from a string.

Parametri

source

The string containing the XML.

options

Bitwise OR of the libxml option constants.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. If called statically, returns a DOMDocument sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

Aceasta metoda poate fi apelata în mod static, dar va emite o eroare E_STRICT.

Exemple

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

Example #2 Static invocation of loadXML

<?php
// Issues an E_STRICT error
$doc = DOMDocument::loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

A se vedea ?i

  • 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, PHP 7)

DOMDocument::normalizeDocument — Normalizes the document

Descrierea

public void DOMDocument::normalizeDocument ( void )

This method acts as if you saved and then loaded the document, putting the document in a "normal" form.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • » 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, PHP 7)

DOMDocument::registerNodeClass — Register extended class used to create base node type

Descrierea

public 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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
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.

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a:

<?xml version="1.0"?>
<root><child foo="bar"/></root>

Example #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;
?>

Exemplul de mai sus va afi?a:

string(9) "myElement"
text in child

Example #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));
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

DOMDocument::relaxNGValidate — Performs relaxNG validation on the document

Descrierea

public bool DOMDocument::relaxNGValidate ( string $filename )

Performs » relaxNG validation on the document based on the given RNG schema.

Parametri

filename

The RNG file.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document

Descrierea

public bool DOMDocument::relaxNGValidateSource ( string $source )

Performs » relaxNG validation on the document based on the given RNG source.

Parametri

source

A string containing the RNG schema.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

DOMDocument::save — Dumps the internal XML tree back into a file

Descrierea

public 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.

Parametri

filename

The path to the saved XML document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

Valorile întoarse

Returns the number of bytes written or FALSE if an error occurred.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Added the options parameter

Exemple

Example #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

?>

A se vedea ?i

  • 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, PHP 7)

DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting

Descrierea

public 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.

Parametri

node

Optional parameter to output a subset of the document.

Valorile întoarse

Returns the HTML, or FALSE if an error occurred.

Istoricul schimbarilor

Versiune | Descriere
5.3.6 | The node parameter was added.

Exemple

Example #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();

?>

A se vedea ?i

  • 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, PHP 7)

DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting

Descrierea

public 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.

Parametri

filename

The path to the saved HTML document.

Valorile întoarse

Returns the number of bytes written or FALSE if an error occurred.

Exemple

Example #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

?>

A se vedea ?i

  • 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, PHP 7)

DOMDocument::saveXML — Dumps the internal XML tree back into a string

Descrierea

public 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.

Parametri

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.

Valorile întoarse

Returns the XML, or FALSE if an error occurred.

Erori/Excep?ii

DOM_WRONG_DOCUMENT_ERR

Raised if node is from another document.

Istoricul schimbarilor

Versiune | Descriere
5.1.0 | Added the options parameter

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

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>

A se vedea ?i

  • 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, PHP 7)

DOMDocument::schemaValidate — Validates a document based on a schema

Descrierea

public bool DOMDocument::schemaValidate ( string $filename [, int $flags ] )

Validates a document based on the given schema file.

Parametri

filename

The path to the schema.

flags

A bitmask of Libxml schema validation flags. Currently the only supported value is LIBXML_SCHEMA_CREATE. Available since PHP 5.5.2 and Libxml 2.6.14.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.2 | Added the flags parameter

A se vedea ?i

  • 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, PHP 7)

DOMDocument::schemaValidateSource — Validates a document based on a schema

Descrierea

public bool DOMDocument::schemaValidateSource ( string $source [, int $flags ] )

Validates a document based on a schema defined in the given string.

Parametri

source

A string containing the schema.

flags

A bitmask of Libxml schema validation flags. Currently the only supported value is LIBXML_SCHEMA_CREATE. Available since PHP 5.5.2 and Libxml 2.6.14.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.5.2 | Added the flags parameter

A se vedea ?i

  • 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, PHP 7)

DOMDocument::validate — Validates the document based on its DTD

Descrierea

public 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. If the document have no DTD attached, this method will return FALSE.

Exemple

Example #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');
?>

A se vedea ?i

  • 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, PHP 7)

DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object

Descrierea

public int DOMDocument::xinclude ([ int $options ] )

This method substitutes » XIncludes in a DOMDocument object.

Nota:

Due to libxml2 automatically resolving entities, this method will produce unexpected results if the included XML file have an attached DTD.

Parametri

options

libxml parameters. Available since PHP 5.1.0 and Libxml 2.6.7.

Valorile întoarse

Returns the number of XIncludes in the document, -1 if some processing failed, or FALSE if there were no substitutions.

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a ceva similar cu:

<?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, PHP 7)

Sinopsisul clasei

DOMDocumentFragment extends DOMNode {
/* Proprieta?i */
/* Metode */
public bool appendXML ( string $data )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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, PHP 7)

DOMDocumentFragment::appendXML — Append raw XML data

Descrierea

public 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.

Parametri

data

XML to append.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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();
?>

Exemplul de mai sus va afi?a:

<?xml version="1.0"?>
<root><foo>text</foo><bar>text2</bar></root>

DOMDocumentFragment
DOMDocumentType
DOMDocumentFragment


The DOMDocumentType class

(PHP 5, PHP 7)

Introducere

Each DOMDocument has a doctype attribute whose value is either NULL or a DOMDocumentType object.

Sinopsisul clasei

DOMDocumentType extends DOMNode {
/* Proprieta?i */
readonly public string $publicId ;
readonly public string $systemId ;
readonly public string $name ;
readonly public DOMNamedNodeMap $entities ;
readonly public DOMNamedNodeMap $notations ;
readonly public string $internalSubset ;
/* Metode mo?tenite */
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 )
}

Proprieta?i

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 does not contain the delimiting square brackets.

DOMDocumentFragment::appendXML
DOMElement
DOM


The DOMElement class

(PHP 5, PHP 7)

Sinopsisul clasei

DOMElement extends DOMNode {
/* Proprieta?i */
readonly public bool $schemaTypeInfo ;
readonly public string $tagName ;
/* Metode */
public __construct ( string $name [, string $value [, string $namespaceURI ]] )
public string getAttribute ( string $name )
public DOMAttr getAttributeNode ( string $name )
public DOMAttr getAttributeNodeNS ( string $namespaceURI , string $localName )
public string getAttributeNS ( string $namespaceURI , string $localName )
public DOMNodeList getElementsByTagName ( string $name )
public DOMNodeList getElementsByTagNameNS ( string $namespaceURI , string $localName )
public bool hasAttribute ( string $name )
public bool hasAttributeNS ( string $namespaceURI , string $localName )
public bool removeAttribute ( string $name )
public bool removeAttributeNode ( DOMAttr $oldnode )
public bool removeAttributeNS ( string $namespaceURI , string $localName )
public DOMAttr setAttribute ( string $name , string $value )
public DOMAttr setAttributeNode ( DOMAttr $attr )
public DOMAttr setAttributeNodeNS ( DOMAttr $attr )
public void setAttributeNS ( string $namespaceURI , string $qualifiedName , string $value )
public void setIdAttribute ( string $name , bool $isId )
public void setIdAttributeNode ( DOMAttr $attr , bool $isId )
public void setIdAttributeNS ( string $namespaceURI , string $localName , bool $isId )
/* Metode mo?tenite */
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 )
}

Proprieta?i

schemaTypeInfo

Not implemented yet, always return NULL

tagName

The element name

Note

Nota:

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.

Cuprins

  • 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, PHP 7)

DOMElement::__construct — Creates a new DOMElement object

Descrierea

public 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.

Parametri

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.

Exemple

Example #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> */

?>

A se vedea ?i

  • 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, PHP 7)

DOMElement::getAttribute — Returns value of attribute

Descrierea

public string DOMElement::getAttribute ( string $name )

Gets the value of the attribute with name name for the current node.

Parametri

name

The name of the attribute.

Valorile întoarse

The value of the attribute, or an empty string if no attribute with the given name is found.

A se vedea ?i

  • 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, PHP 7)

DOMElement::getAttributeNode — Returns attribute node

Descrierea

public DOMAttr DOMElement::getAttributeNode ( string $name )

Returns the attribute node with name name for the current element.

Parametri

name

The name of the attribute.

Valorile întoarse

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr.

A se vedea ?i

  • 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, PHP 7)

DOMElement::getAttributeNodeNS — Returns attribute node

Descrierea

public DOMAttr DOMElement::getAttributeNodeNS ( string $namespaceURI , string $localName )

Returns the attribute node in namespace namespaceURI with local name localName for the current node.

Parametri

namespaceURI

The namespace URI.

localName

The local name.

Valorile întoarse

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr.

A se vedea ?i

  • 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, PHP 7)

DOMElement::getAttributeNS — Returns value of attribute

Descrierea

public string DOMElement::getAttributeNS ( string $namespaceURI , string $localName )

Gets the value of the attribute in namespace namespaceURI with local name localName for the current node.

Parametri

namespaceURI

The namespace URI.

localName

The local name.

Valorile întoarse

The value of the attribute, or an empty string if no attribute with the given localName and namespaceURI is found.

A se vedea ?i

  • 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, PHP 7)

DOMElement::getElementsByTagName — Gets elements by tagname

Descrierea

public 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.

Parametri

name

The tag name. Use * to return all elements within the element tree.

Valorile întoarse

This function returns a new instance of the class DOMNodeList of all matched elements.

A se vedea ?i

  • 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, PHP 7)

DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName

Descrierea

public DOMNodeList DOMElement::getElementsByTagNameNS ( string $namespaceURI , string $localName )

This function fetch all the descendant elements with a given localName and namespaceURI.

Parametri

namespaceURI

The namespace URI.

localName

The local name. Use * to return all elements within the element tree.

Valorile întoarse

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.

A se vedea ?i

  • 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, PHP 7)

DOMElement::hasAttribute — Checks to see if attribute exists

Descrierea

public bool DOMElement::hasAttribute ( string $name )

Indicates whether attribute named name exists as a member of the element.

Parametri

name

The attribute name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

DOMElement::hasAttributeNS — Checks to see if attribute exists

Descrierea

public bool DOMElement::hasAttributeNS ( string $namespaceURI , string $localName )

Indicates whether attribute in namespace namespaceURI named localName exists as a member of the element.

Parametri

namespaceURI

The namespace URI.

localName

The local name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

DOMElement::removeAttribute — Removes attribute

Descrierea

public bool DOMElement::removeAttribute ( string $name )

Removes attribute named name from the element.

Parametri

name

The name of the attribute.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

A se vedea ?i

  • 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, PHP 7)

DOMElement::removeAttributeNode — Removes attribute

Descrierea

public bool DOMElement::removeAttributeNode ( DOMAttr $oldnode )

Removes attribute oldnode from the element.

Parametri

oldnode

The attribute node.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

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.

A se vedea ?i

  • 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, PHP 7)

DOMElement::removeAttributeNS — Removes attribute

Descrierea

public bool DOMElement::removeAttributeNS ( string $namespaceURI , string $localName )

Removes attribute is namespace namespaceURI named localName from the element.

Parametri

namespaceURI

The namespace URI.

localName

The local name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

A se vedea ?i

  • 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, PHP 7)

DOMElement::setAttribute — Adds new attribute

Descrierea

public 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.

Parametri

name

The name of the attribute.

value

The value of the attribute.

Valorile întoarse

The new DOMAttr or FALSE if an error occurred.

Erori/Excep?ii

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Exemple

Example #1 Setting an attribute

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

A se vedea ?i

  • 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, PHP 7)

DOMElement::setAttributeNode — Adds new attribute node to element

Descrierea

public DOMAttr DOMElement::setAttributeNode ( DOMAttr $attr )

Adds new attribute node attr to element.

Parametri

attr

The attribute node.

Valorile întoarse

Returns old node if the attribute has been replaced or NULL.

Erori/Excep?ii

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

A se vedea ?i

  • 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, PHP 7)

DOMElement::setAttributeNodeNS — Adds new attribute node to element

Descrierea

public DOMAttr DOMElement::setAttributeNodeNS ( DOMAttr $attr )

Adds new attribute node attr to element.

Parametri

attr

The attribute node.

Valorile întoarse

Returns the old node if the attribute has been replaced.

Erori/Excep?ii

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

A se vedea ?i

  • 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, PHP 7)

DOMElement::setAttributeNS — Adds new attribute

Descrierea

public 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.

Parametri

namespaceURI

The namespace URI.

qualifiedName

The qualified name of the attribute, as prefix:tagname.

value

The value of the attribute.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

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.

A se vedea ?i

  • 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, PHP 7)

DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID

Descrierea

public void DOMElement::setIdAttribute ( string $name , bool $isId )

Declares the attribute name to be of type ID.

Parametri

name

The name of the attribute.

isId

Set it to TRUE if you want name to be of type ID, FALSE otherwise.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

A se vedea ?i

  • 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, PHP 7)

DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID

Descrierea

public void DOMElement::setIdAttributeNode ( DOMAttr $attr , bool $isId )

Declares the attribute specified by attr to be of type ID.

Parametri

attr

The attribute node.

isId

Set it to TRUE if you want name to be of type ID, FALSE otherwise.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

A se vedea ?i

  • 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, PHP 7)

DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID

Descrierea

public void DOMElement::setIdAttributeNS ( string $namespaceURI , string $localName , bool $isId )

Declares the attribute specified by localName and namespaceURI to be of type ID.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Erori/Excep?ii

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

A se vedea ?i

  • 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, PHP 7)

Introducere

This interface represents a known entity, either parsed or unparsed, in an XML document.

Sinopsisul clasei

DOMEntity extends DOMNode {
/* Proprieta?i */
readonly public string $publicId ;
readonly public string $systemId ;
readonly public string $notationName ;
public string $actualEncoding ;
readonly public string $encoding ;
readonly public string $version ;
/* Metode mo?tenite */
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 )
}

Proprieta?i

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, PHP 7)

Sinopsisul clasei

DOMEntityReference extends DOMNode {
/* Proprieta?i */
/* Metode */
public __construct ( string $name )
/* Metode mo?tenite */
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 )
}

Cuprins

  • 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, PHP 7)

DOMEntityReference::__construct — Creates a new DOMEntityReference object

Descrierea

public DOMEntityReference::__construct ( string $name )

Creates a new DOMEntityReference object.

Parametri

name

The name of the entity reference.

Exemple

Example #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> */

?>

A se vedea ?i

  • DOMDocument::createEntityReference() - Create new entity reference node

DOMEntityReference
DOMException
DOMEntityReference


The DOMException class

(PHP 5, PHP 7)

Introducere

DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.

See also Exceptions.

Sinopsisul clasei

DOMException extends Exception {
/* Proprieta?i */
readonly public int $code ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}

Proprieta?i

code

An integer indicating the type of error generated

DOMEntityReference::__construct
DOMImplementation
DOM


The DOMImplementation class

(PHP 5, PHP 7)

Introducere

The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.

Sinopsisul clasei

DOMImplementation {
/* Proprieta?i */
/* Metode */
__construct ( void )
public DOMDocument createDocument ([ string $namespaceURI = NULL [, string $qualifiedName = NULL [, DOMDocumentType $doctype = NULL ]]] )
public DOMDocumentType createDocumentType ([ string $qualifiedName = NULL [, string $publicId = NULL [, string $systemId = NULL ]]] )
public bool hasFeature ( string $feature , string $version )
}

Cuprins

  • DOMImplementation::__construct — Creeaza un obiect nou DOMImplementation
  • 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


Creeaza un obiect nou DOMImplementation

DOMImplementation
DOMImplementation::createDocument
DOMImplementation
PHP Manual

DOMImplementation::__construct

(PHP 5, PHP 7)

DOMImplementation::__construct — Creeaza un obiect nou DOMImplementation

Descrierea

DOMImplementation::__construct ( void )

Creeaza un obiect nou DOMImplementation.

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, PHP 7)

DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element

Descrierea

public DOMDocument DOMImplementation::createDocument ([ string $namespaceURI = NULL [, string $qualifiedName = NULL [, DOMDocumentType $doctype = NULL ]]] )

Creates a DOMDocument object of the specified type with its document element.

Parametri

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.

Valorile întoarse

A new DOMDocument object. If namespaceURI, qualifiedName, and doctype are null, the returned DOMDocument is empty with no document element

Erori/Excep?ii

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.

Aceasta metoda poate fi apelata în mod static, dar va emite o eroare E_STRICT.

A se vedea ?i

  • 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, PHP 7)

DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object

Descrierea

public 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.

Parametri

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

Valorile întoarse

A new DOMDocumentType node with its ownerDocument set to NULL.

Erori/Excep?ii

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by qualifiedName.

Aceasta metoda poate fi apelata în mod static, dar va emite o eroare E_STRICT.

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

A se vedea ?i

  • 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, PHP 7)

DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature

Descrierea

public 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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Aceasta metoda poate fi apelata în mod static, dar va emite o eroare E_STRICT.

Exemple

Example #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";
  }
}

?>

A se vedea ?i

  • DOMNode::isSupported() - Checks if feature is supported for specified version

DOMImplementation::createDocumentType
DOMNamedNodeMap
DOMImplementation


The DOMNamedNodeMap class

(PHP 5, PHP 7)

Sinopsisul clasei

DOMNamedNodeMap implements Traversable {
/* Proprieta?i */
readonly public int $length ;
/* Metode */
DOMNode getNamedItem ( string $name )
DOMNode getNamedItemNS ( string $namespaceURI , string $localName )
DOMNode item ( int $index )
}

Proprieta?i

length

The number of nodes in the map. The range of valid child node indices is 0 to length - 1 inclusive.

Cuprins

  • 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, PHP 7)

DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name

Descrierea

DOMNode DOMNamedNodeMap::getNamedItem ( string $name )

Retrieves a node specified by its nodeName.

Parametri

name

The nodeName of the node to retrieve.

Valorile întoarse

A node (of any type) with the specified nodeName, or NULL if no node is found.

A se vedea ?i

  • 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, PHP 7)

DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI

Descrierea

DOMNode DOMNamedNodeMap::getNamedItemNS ( string $namespaceURI , string $localName )

Retrieves a node specified by localName and namespaceURI.

Parametri

namespaceURI

The namespace URI of the node to retrieve.

localName

The local name of the node to retrieve.

Valorile întoarse

A node (of any type) with the specified local name and namespace URI, or NULL if no node is found.

A se vedea ?i

  • 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, PHP 7)

DOMNamedNodeMap::item — Retrieves a node specified by index

Descrierea

DOMNode DOMNamedNodeMap::item ( int $index )

Retrieves a node specified by index within the DOMNamedNodeMap object.

Parametri

index

Index into this map.

Valorile întoarse

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, PHP 7)

Sinopsisul clasei

DOMNode {
/* Proprieta?i */
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 ;
/* Metode */
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 )
}

Proprieta?i

nodeName

Returns the most accurate name for the current node type

nodeValue

The value of this node, depending on its type. Contrary to the W3C specification, the node value of DOMElement nodes is equal to DOMNode::textContent instead of NULL.

nodeType

Gets the type of the node. One of the predefined XML_xxx_NODE constants

parentNode

The parent of this node. If there is no such node, this returns NULL.

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

The text content of this node and its descendants.

Note

Nota:

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.

Istoricul schimbarilor

Versiune | Descriere
5.6.1 | The textContent property has been made writable (formerly it has been readonly).

A se vedea ?i

  • » W3C specification of Node

Cuprins

  • 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, PHP 7)

DOMNode::appendChild — Adds new child at the end of the children

Descrierea

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.

Parametri

newnode

The appended child.

Valorile întoarse

The node added.

Erori/Excep?ii

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.

Exemple

The following example will add a new element node to a fresh document.

Example #1 Adding a child

<?php

$doc = new DOMDocument;

$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);

echo $doc->saveXML();
?>

A se vedea ?i

  • DOMNode::insertBefore() - Adds a new child before a reference node
  • 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, PHP 7)

DOMNode::C14N — Canonicalize nodes to a string

Descrierea

public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )

Canonicalize nodes to a string

Parametri

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.

Valorile întoarse

Returns canonicalized nodes as a string sau FALSE în cazul e?ecului

A se vedea ?i

  • 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, PHP 7)

DOMNode::C14NFile — Canonicalize nodes to a file

Descrierea

public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )

Canonicalize nodes to a file.

Parametri

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.

Valorile întoarse

Number of bytes written sau FALSE în cazul e?ecului

A se vedea ?i

  • 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, PHP 7)

DOMNode::cloneNode — Clones a node

Descrierea

public DOMNode DOMNode::cloneNode ([ bool $deep ] )

Creates a copy of the node.

Parametri

deep

Indicates whether to copy all descendant nodes. This parameter is defaulted to FALSE.

Valorile întoarse

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, PHP 7)

DOMNode::getLineNo — Get line number for a node

Descrierea

public int DOMNode::getLineNo ( void )

Gets line number for where the node is defined.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Always returns the line number where the node was defined in.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

DOMNode::getNodePath — Get an XPath for a node

Descrierea

public string DOMNode::getNodePath ( void )

Gets an XPath location path for the node.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a string containing the XPath, or NULL in case of an error.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

/fruits
/fruits/apples
/fruits/apples/apple[1]
/fruits/apples/apple[2]
/fruits/pears
/fruits/pears/pear

A se vedea ?i

  • DOMXPath

DOMNode::getLineNo
DOMNode::hasAttributes
DOMNode


Checks if node has attributes

DOMNode::getNodePath
DOMNode::hasChildNodes
DOMNode
PHP Manual

DOMNode::hasAttributes

(PHP 5, PHP 7)

DOMNode::hasAttributes — Checks if node has attributes

Descrierea

public bool DOMNode::hasAttributes ( void )

This method checks if the node has attributes. The tested node has to be an XML_ELEMENT_NODE.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

DOMNode::hasChildNodes — Checks if node has children

Descrierea

public bool DOMNode::hasChildNodes ( void )

This function checks if the node has children.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

DOMNode::insertBefore — Adds a new child before a reference node

Descrierea

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.

Parametri

newnode

The new node.

refnode

The reference node. If not supplied, newnode is appended to the children.

Valorile întoarse

The inserted node.

Erori/Excep?ii

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.

A se vedea ?i

  • DOMNode::appendChild() - Adds new child at the end of the children

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, PHP 7)

DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not

Descrierea

public bool DOMNode::isDefaultNamespace ( string $namespaceURI )

Tells whether namespaceURI is the default namespace.

Parametri

namespaceURI

The namespace URI to look for.

Valorile întoarse

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, PHP 7)

DOMNode::isSameNode — Indicates if two nodes are the same node

Descrierea

public bool DOMNode::isSameNode ( DOMNode $node )

This function indicates if two nodes are the same node. The comparison is not based on content

Parametri

node

The compared node.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

DOMNode::isDefaultNamespace
DOMNode::isSupported
DOMNode


Checks if feature is supported for specified version

DOMNode::isSameNode
DOMNode::lookupNamespaceURI
DOMNode
PHP Manual

DOMNode::isSupported

(PHP 5, PHP 7)

DOMNode::isSupported — Checks if feature is supported for specified version

Descrierea

public bool DOMNode::isSupported ( string $feature , string $version )

Checks if the asked feature is supported for the specified version.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

DOMNode::lookupNamespaceURI — Gets the namespace URI of the node based on the prefix

Descrierea

public string DOMNode::lookupNamespaceURI ( string $prefix )

Gets the namespace URI of the node based on the prefix.

Parametri

prefix

The prefix of the namespace.

Valorile întoarse

The namespace URI of the node.

A se vedea ?i

  • 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, PHP 7)

DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI

Descrierea

public string DOMNode::lookupPrefix ( string $namespaceURI )

Gets the namespace prefix of the node based on the namespace URI.

Parametri

namespaceURI

The namespace URI.

Valorile întoarse

The prefix of the namespace.

A se vedea ?i

  • 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, PHP 7)

DOMNode::normalize — Normalizes the node

Descrierea

public void DOMNode::normalize ( void )

Remove empty text nodes and merge adjacent text nodes in this node and all its children.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • » 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, PHP 7)

DOMNode::removeChild — Removes child from list of children

Descrierea

public DOMNode DOMNode::removeChild ( DOMNode $oldnode )

This functions removes a child from a list of children.

Parametri

oldnode

The removed child.

Valorile întoarse

If the child could be removed the function returns the old child.

Erori/Excep?ii

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly.

DOM_NOT_FOUND

Raised if oldnode is not a child of this node.

Exemple

The following example will delete the chapter element of our XML document.

Example #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();
?>

Exemplul de mai sus va afi?a:

<?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>

A se vedea ?i

  • 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, PHP 7)

DOMNode::replaceChild — Replaces a child

Descrierea

public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )

This function replaces the child oldnode with the passed new node. If the newnode is already a child it will not be added a second time. If the replacement succeeds the old node is returned.

Parametri

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.

Valorile întoarse

The old node or FALSE if an error occur.

Erori/Excep?ii

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.

A se vedea ?i

  • 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, PHP 7)

Sinopsisul clasei

DOMNodeList implements Traversable {
/* Proprieta?i */
readonly public int $length ;
/* Metode */
DOMElement DOMNodelist::item ( int $index )
}

Proprieta?i

length

The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

A se vedea ?i

  • » W3C specification of NodeList

Cuprins

  • 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, PHP 7)

DOMNodelist::item — Retrieves a node specified by index

Descrierea

DOMElement DOMNodelist::item ( int $index )

Retrieves a node specified by index within the DOMNodeList object.

Sfat

If you need to know the number of nodes in the collection, use the length property of the DOMNodeList object.

Parametri

index

Index of the node into the collection.

Valorile întoarse

The node at the indexth position in the DOMNodeList, or NULL if that is not a valid index.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a:

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, PHP 7)

Sinopsisul clasei

DOMNotation extends DOMNode {
/* Proprieta?i */
readonly public string $publicId ;
readonly public string $systemId ;
/* Metode mo?tenite */
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 )
}

Proprieta?i

publicId

systemId

DOMNodelist::item
DOMProcessingInstruction
DOM


The DOMProcessingInstruction class

(PHP 5, PHP 7)

Sinopsisul clasei

DOMProcessingInstruction extends DOMNode {
/* Proprieta?i */
readonly public string $target ;
public string $data ;
/* Metode */
public __construct ( string $name [, string $value ] )
/* Metode mo?tenite */
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 )
}

Proprieta?i

target

data

Cuprins

  • 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, PHP 7)

DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object

Descrierea

public 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.

Parametri

name

The tag name of the processing instruction.

value

The value of the processing instruction.

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a:

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Hello World"; ?></body></html>

A se vedea ?i

  • DOMDocument::createProcessingInstruction() - Creates new PI node

DOMProcessingInstruction
DOMText
DOMProcessingInstruction


The DOMText class

(PHP 5, PHP 7)

Introducere

The DOMText class inherits from DOMCharacterData and represents the textual content of a DOMElement or DOMAttr.

Sinopsisul clasei

DOMText extends DOMCharacterData {
/* Proprieta?i */
readonly public string $wholeText ;
/* Metode */
public __construct ([ string $value ] )
public bool isWhitespaceInElementContent ( void )
public DOMText splitText ( int $offset )
/* Metode mo?tenite */
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 )
}

Proprieta?i

wholeText

Holds all the text of logically-adjacent (not separated by Element, Comment or Processing Instruction) Text nodes.

Cuprins

  • 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, PHP 7)

DOMText::__construct — Creates a new DOMText object

Descrierea

public DOMText::__construct ([ string $value ] )

Creates a new DOMText object.

Parametri

value

The value of the text node. If not supplied an empty text node is created.

Exemple

Example #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> */

?>

A se vedea ?i

  • 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, PHP 7)

DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace

Descrierea

public bool DOMText::isWhitespaceInElementContent ( void )

Indicates whether this text node contains only whitespace or it is empty. The text node is determined to contain whitespace in element content during the load of the document.

Valorile întoarse

Returns TRUE if node contains zero or more whitespace characters and nothing else. Returns FALSE otherwise.

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, PHP 7)

DOMText::splitText — Breaks this node into two nodes at the specified offset

Descrierea

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.

Parametri

offset

The offset at which to split, starting from 0.

Valorile întoarse

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, PHP 7)

Introducere

Supports XPath 1.0

Sinopsisul clasei

DOMXPath {
/* Proprieta?i */
public DOMDocument $document ;
/* Metode */
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 ] )
}

Proprieta?i

document

Cuprins

  • 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, PHP 7)

DOMXPath::__construct — Creates a new DOMXPath object

Descrierea

public DOMXPath::__construct ( DOMDocument $doc )

Creates a new DOMXPath object.

Parametri

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, PHP 7)

DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible

Descrierea

public mixed DOMXPath::evaluate ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true ]] )

Executes the given XPath expression and returns a typed result if possible.

Parametri

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.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
5.3.3 | The registerNodeNS parameter was added.

Exemple

Example #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";

?>

Exemplul de mai sus va afi?a:

There are 2 english books

A se vedea ?i

  • 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, PHP 7)

DOMXPath::query — Evaluates the given XPath expression

Descrierea

public DOMNodeList DOMXPath::query ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true ]] )

Executes the given XPath expression.

Parametri

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.

Valorile întoarse

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.

Istoricul schimbarilor

Versiune | Descriere
5.3.3 | The registerNodeNS parameter was added.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

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";
}
?>

A se vedea ?i

  • 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, PHP 7)

DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object

Descrierea

public bool DOMXPath::registerNamespace ( string $prefix , string $namespaceURI )

Registers the namespaceURI and prefix with the DOMXPath object.

Parametri

prefix

The prefix.

namespaceURI

The URI of the namespace.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

DOMXPath::query
DOMXPath::registerPhpFunctions
DOMXPath


Register PHP functions as XPath functions

DOMXPath::registerNamespace
DOM Func?ii
DOMXPath
PHP Manual

DOMXPath::registerPhpFunctions

(PHP 5 >= 5.3.0, PHP 7)

DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions

Descrierea

public void DOMXPath::registerPhpFunctions ([ mixed $restrict ] )

This method enables the ability to use PHP functions within XPath expressions.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

The following examples use book.xml which contains the following:

Example #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>

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

Found 2 books starting with 'PHP':
PHP Basics by Jim Smith
PHP Secrets by Jenny Smythe

Example #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";
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

Books with multiple authors:
PHP Basics

A se vedea ?i

  • 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 Func?ii
DOMXPath


DOM Func?ii

Cuprins

  • 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 Func?ii
libxml
DOM Func?ii
PHP Manual

dom_import_simplexml

(PHP 5, PHP 7)

dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

Descrierea

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.

Parametri

node

The SimpleXMLElement node.

Valorile întoarse

The DOMElement node added or FALSE if any errors occur.

Exemple

Example #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();

?>

A se vedea ?i

  • simplexml_import_dom() - Get a SimpleXMLElement object from a DOM node.

DOM Func?ii
libxml
DOM Func?ii


libxml

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • libXMLError — The libXMLError class
  • Func?ii libxml
    • 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_external_entity_loader — Changes the default external entity loader
    • 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
dom_import_simplexml
Introducere
Manipularea XML


Introducere

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, XML, XMLReader, XMLRPC ?i XMLWriter.

libxml
Instalarea / configurarea
libxml


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
libxml


Necesita?i

This extension requires » libxml >= 2.6.0.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

LIBXML_BIGLINES (integer)
Allows line numbers greater than 65535 to be reported correctly.

Nota:

Only available as of PHP 7.0.0 with Libxml >= 2.9.0

LIBXML_COMPACT (integer)
Activate small nodes allocation optimization. This may speed up your application without needing to change the code.

Nota:

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_HTML_NOIMPLIED (integer)
Sets HTML_PARSE_NOIMPLIED flag, which turns off the automatic adding of implied html/body... elements.

Nota:

Only available in Libxml >= 2.7.7 (as of PHP >= 5.4.0)

LIBXML_HTML_NODEFDTD (integer)
Sets HTML_PARSE_NODEFDTD flag, which prevents a default doctype being added when one is not found.

Nota:

Only available in Libxml >= 2.7.8 (as of PHP >= 5.4.0)

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>)

Nota:

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

Nota:

Only available in Libxml >= 2.6.21

LIBXML_NSCLEAN (integer)
Remove redundant namespace 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.

Nota:

Only available in Libxml >= 2.7.0 (as of PHP >= 5.3.2 and PHP >= 5.2.12)

LIBXML_PEDANTIC (integer)
Sets XML_PARSE_PEDANTIC flag, which enables pedantic error reporting.

Nota:

Available as of PHP >= 5.4.0

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
LIBXML_SCHEMA_CREATE (integer)
Create default/fixed value nodes during XSD schema validation

Nota:

Only available in Libxml >= 2.6.14 (as of PHP >= 5.5.2)

Tipurile resurselor
libXMLError
libxml


The libXMLError class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

Contains various information about errors thrown by libxml. The error codes are described within the official » xmlError API documentation.

Sinopsisul clasei

libXMLError {
/* Proprieta?i */
public int $level ;
public int $code ;
public int $column ;
public string $message ;
public string $file ;
public int $line ;
}

Proprieta?i

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.

Nota:

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.

Constante predefinite
Func?ii libxml
libxml


Func?ii libxml

Cuprins

  • 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_external_entity_loader — Changes the default external entity loader
  • 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

Func?ii libxml
libxml_disable_entity_loader
Func?ii libxml
PHP Manual

libxml_clear_errors

(PHP 5 >= 5.1.0, PHP 7)

libxml_clear_errors — Clear libxml error buffer

Descrierea

void libxml_clear_errors ( void )

libxml_clear_errors() clears the libxml error buffer.

Valorile întoarse

Nu este întoarsa nici o valoare.

A se vedea ?i

  • libxml_get_errors() - Retrieve array of errors
  • libxml_get_last_error() - Retrieve last error from libxml

Func?ii libxml
libxml_disable_entity_loader
Func?ii libxml


Disable the ability to load external entities

libxml_clear_errors
libxml_get_errors
Func?ii libxml
PHP Manual

libxml_disable_entity_loader

(PHP 5 >= 5.2.11, PHP 7)

libxml_disable_entity_loader — Disable the ability to load external entities

Descrierea

bool libxml_disable_entity_loader ([ bool $disable = true ] )

Disable/enable the ability to load external entities.

Parametri

disable

Disable (TRUE) or enable (FALSE) libxml extensions (such as DOM, XMLWriter and XMLReader) to load external entities.

Valorile întoarse

Returns the previous value.

A se vedea ?i

  • 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
Func?ii libxml


Retrieve array of errors

libxml_disable_entity_loader
libxml_get_last_error
Func?ii libxml
PHP Manual

libxml_get_errors

(PHP 5 >= 5.1.0, PHP 7)

libxml_get_errors — Retrieve array of errors

Descrierea

array libxml_get_errors ( void )

Retrieve array of errors.

Valorile întoarse

Returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.

Exemple

Example #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 === false) {
    $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";
}

?>

Exemplul de mai sus va afi?a:

  <titles>PHP: Behind the Parser</title>
----------------------------------------------^
Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 46

--------------------------------------------

A se vedea ?i

  • libxml_get_last_error() - Retrieve last error from libxml
  • libxml_clear_errors() - Clear libxml error buffer

libxml_disable_entity_loader
libxml_get_last_error
Func?ii libxml


Retrieve last error from libxml

libxml_get_errors
libxml_set_external_entity_loader
Func?ii libxml
PHP Manual

libxml_get_last_error

(PHP 5 >= 5.1.0, PHP 7)

libxml_get_last_error — Retrieve last error from libxml

Descrierea

LibXMLError libxml_get_last_error ( void )

Retrieve last error from libxml.

Valorile întoarse

Returns a LibXMLError object if there is any error in the buffer, FALSE otherwise.

A se vedea ?i

  • libxml_get_errors() - Retrieve array of errors
  • libxml_clear_errors() - Clear libxml error buffer

libxml_get_errors
libxml_set_external_entity_loader
Func?ii libxml


Changes the default external entity loader

libxml_get_last_error
libxml_set_streams_context
Func?ii libxml
PHP Manual

libxml_set_external_entity_loader

(PHP 5 >= 5.4.0, PHP 7)

libxml_set_external_entity_loader — Changes the default external entity loader

Descrierea

void libxml_set_external_entity_loader ( callable $resolver_function )

Changes the default external entity loader.

Parametri

resolver_function

A callable that takes three arguments. Two strings, a public id and system id, and a context (an array with four keys) as the third argument. This callback should return a resource, a string from which a resource can be opened, or NULL.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 libxml_set_external_entity_loader() example

<?php
$xml = <<<XML
<!DOCTYPE foo PUBLIC "-//FOO/BAR" "http://example.com/foobar">
<foo>bar</foo>
XML;

$dtd = <<<DTD
<!ELEMENT foo (#PCDATA)>
DTD;

libxml_set_external_entity_loader(
    function ($public, $system, $context) use($dtd) {
        var_dump($public);
        var_dump($system);
        var_dump($context);
        $f = fopen("php://temp", "r+");
        fwrite($f, $dtd);
        rewind($f);
        return $f;
    }
);

$dd = new DOMDocument;
$r  = $dd->loadXML($xml);

var_dump($dd->validate());
?>

Exemplul de mai sus va afi?a:

string(10) "-//FOO/BAR"
string(25) "http://example.com/foobar"
array(4) {
    ["directory"]    => NULL
    ["intSubName"]   => NULL
    ["extSubURI"]    => NULL
    ["extSubSystem"] => NULL
}
bool(true)

A se vedea ?i

  • libxml_disable_entity_loader() - Disable the ability to load external entities

libxml_get_last_error
libxml_set_streams_context
Func?ii libxml


Set the streams context for the next libxml document load or write

libxml_set_external_entity_loader
libxml_use_internal_errors
Func?ii libxml
PHP Manual

libxml_set_streams_context

(PHP 5, PHP 7)

libxml_set_streams_context — Set the streams context for the next libxml document load or write

Descrierea

void libxml_set_streams_context ( resource $streams_context )

Sets the streams context for the next libxml document load or write.

Parametri

streams_context

The stream context resource (created with stream_context_create())

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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');

?>

A se vedea ?i

  • stream_context_create() - Creates a stream context

libxml_set_external_entity_loader
libxml_use_internal_errors
Func?ii libxml


Disable libxml errors and allow user to fetch error information as needed

libxml_set_streams_context
SDO
Func?ii libxml
PHP Manual

libxml_use_internal_errors

(PHP 5 >= 5.1.0, PHP 7)

libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed

Descrierea

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.

Parametri

use_errors

Enable (TRUE) user error handling or disable (FALSE) user error handling. Disabling will also clear any existing libxml errors.

Valorile întoarse

This function returns the previous value of use_errors.

Exemple

Example #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();
}

?>

Exemplul de mai sus va afi?a:

bool(false)

A se vedea ?i

  • libxml_clear_errors() - Clear libxml error buffer
  • libxml_get_errors() - Retrieve array of errors

libxml_set_streams_context
SDO
Func?ii libxml


Service Data Objects

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Limitations
  • Exemple
    • Basic usage
    • Setting and Getting Property Values
    • Working with Sequenced Data Objects
    • Reflecting on Service Data Objects
  • SDO Func?ii
    • 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
libxml_use_internal_errors
Introducere
Manipularea XML


Introducere

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
Instalarea / configurarea
SDO


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SDO


Necesita?i

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/.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/sca_sdo.

Nota:

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.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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'.
Tipurile resurselor
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.

Constante predefinite
Exemple
SDO


Exemple

Cuprins

  • 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.

Exemple
Setting and Getting Property Values
Exemple


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.

Example #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';
?>

Example #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'];
?>

Example #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.

Example #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;
?>

Example #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];
?>

Example #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.

Example #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'.

Example #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.

Example #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]"];
?>

Example #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;
?>

Example #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);
?>

Example #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]);
?>

Example #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);
  }
?>

Example #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
Exemple


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.

Example #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.

Example #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];
?>

Example #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) {
    // ...
}
?>

Example #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];
?>

Example #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);
?>

Example #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
Exemple


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.

Example #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);
?>

Exemplul de mai sus va afi?a:

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).

Example #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";
        }
    }
?>

Exemplul de mai sus va afi?a:

name
SN
manager

Working with Sequenced Data Objects
SDO Func?ii
Exemple


SDO Func?ii

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.

Clase predefinite

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.

Metode

  • 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.

Metode

  • 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.

Metode

  • 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.

Metode

  • 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.

Metode

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.

Constructorul

  • __construct - construct a new SDO_Model_ReflectionDataObject.

Metode

  • 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.

Metode

  • 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.

Metode

  • 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.

Metode

  • 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.

Metode

  • 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.

Metode

  • 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.

Metode

  • 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

Cuprins

  • 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 Func?ii
SDO_DAS_ChangeSummary::endLogging
SDO Func?ii
PHP Manual

SDO_DAS_ChangeSummary::beginLogging

(^)

SDO_DAS_ChangeSummary::beginLogging — Begin change logging

Descrierea

void SDO_DAS_ChangeSummary::beginLogging ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Begin logging changes made to the SDO_DataObject.

Parametri

None.

Valorile întoarse

None.

SDO Func?ii
SDO_DAS_ChangeSummary::endLogging
SDO Func?ii


End change logging

SDO_DAS_ChangeSummary::beginLogging
SDO_DAS_ChangeSummary::getChangeType
SDO Func?ii
PHP Manual

SDO_DAS_ChangeSummary::endLogging

(^)

SDO_DAS_ChangeSummary::endLogging — End change logging

Descrierea

void SDO_DAS_ChangeSummary::endLogging ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

End logging changes made to an SDO_DataObject.

Parametri

None.

Valorile întoarse

None.

SDO_DAS_ChangeSummary::beginLogging
SDO_DAS_ChangeSummary::getChangeType
SDO Func?ii


Get the type of change made to an SDO_DataObject

SDO_DAS_ChangeSummary::endLogging
SDO_DAS_ChangeSummary::getChangedDataObjects
SDO Func?ii
PHP Manual

SDO_DAS_ChangeSummary::getChangeType

(^)

SDO_DAS_ChangeSummary::getChangeType — Get the type of change made to an SDO_DataObject

Descrierea

int SDO_DAS_ChangeSummary::getChangeType ( SDO_DataObject $dataObject )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Get the type of change which has been made to the supplied SDO_DataObject.

Parametri

dataObject

The SDO_DataObject which has been changed.

Valorile întoarse

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 Func?ii


Get the changed data objects from a change summary

SDO_DAS_ChangeSummary::getChangeType
SDO_DAS_ChangeSummary::getOldContainer
SDO Func?ii
PHP Manual

SDO_DAS_ChangeSummary::getChangedDataObjects

(^)

SDO_DAS_ChangeSummary::getChangedDataObjects — Get the changed data objects from a change summary

Descrierea

SDO_List SDO_DAS_ChangeSummary::getChangedDataObjects ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

Returns an SDO_List of SDO_DataObjects.

SDO_DAS_ChangeSummary::getChangeType
SDO_DAS_ChangeSummary::getOldContainer
SDO Func?ii


Get the old container for a deleted SDO_DataObject

SDO_DAS_ChangeSummary::getChangedDataObjects
SDO_DAS_ChangeSummary::getOldValues
SDO Func?ii
PHP Manual

SDO_DAS_ChangeSummary::getOldContainer

(^)

SDO_DAS_ChangeSummary::getOldContainer — Get the old container for a deleted SDO_DataObject

Descrierea

SDO_DataObject SDO_DAS_ChangeSummary::getOldContainer ( SDO_DataObject $data_object )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Get the old container (SDO_DataObject) for a deleted SDO_DataObject.

Parametri

data_object

The SDO_DataObject which has been deleted and whose container we wish to identify.

Valorile întoarse

The old containing data object of the deleted SDO_DataObject.

SDO_DAS_ChangeSummary::getChangedDataObjects
SDO_DAS_ChangeSummary::getOldValues
SDO Func?ii


Get the old values for a given changed SDO_DataObject

SDO_DAS_ChangeSummary::getOldContainer
SDO_DAS_ChangeSummary::isLogging
SDO Func?ii
PHP Manual

SDO_DAS_ChangeSummary::getOldValues

(^)

SDO_DAS_ChangeSummary::getOldValues — Get the old values for a given changed SDO_DataObject

Descrierea

SDO_List SDO_DAS_ChangeSummary::getOldValues ( SDO_DataObject $data_object )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

data_object

The data object which has been changed.

Valorile întoarse

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 Func?ii


Test to see whether change logging is switched on

SDO_DAS_ChangeSummary::getOldValues
SDO_DAS_DataFactory::addPropertyToType
SDO Func?ii
PHP Manual

SDO_DAS_ChangeSummary::isLogging

(^)

SDO_DAS_ChangeSummary::isLogging — Test to see whether change logging is switched on

Descrierea

bool SDO_DAS_ChangeSummary::isLogging ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Test to see whether change logging is switched on.

Parametri

None.

Valorile întoarse

Returns TRUE if change logging is on, otherwise returns FALSE.

SDO_DAS_ChangeSummary::getOldValues
SDO_DAS_DataFactory::addPropertyToType
SDO Func?ii


Adds a property to a type

SDO_DAS_ChangeSummary::isLogging
SDO_DAS_DataFactory::addType
SDO Func?ii
PHP Manual

SDO_DAS_DataFactory::addPropertyToType

(^)

SDO_DAS_DataFactory::addPropertyToType — Adds a property to a type

Descrierea

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 ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

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).

Valorile întoarse

None.

Istoricul schimbarilor

Versiune | Descriere
0.5.2 | Optional parameters many, readOnly, and containment deprecated in favour of the options array.

Exemple

Example #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 Func?ii


Add a new type to a model

SDO_DAS_DataFactory::addPropertyToType
SDO_DAS_DataFactory::getDataFactory
SDO Func?ii
PHP Manual

SDO_DAS_DataFactory::addType

(^)

SDO_DAS_DataFactory::addType — Add a new type to a model

Descrierea

void SDO_DAS_DataFactory::addType ( string $type_namespace_uri , string $type_name [, array $options ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

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="...">.

Valorile întoarse

None.

Exemple

Example #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 Func?ii


Get a data factory instance

SDO_DAS_DataFactory::addType
SDO_DAS_DataObject::getChangeSummary
SDO Func?ii
PHP Manual

SDO_DAS_DataFactory::getDataFactory

(^)

SDO_DAS_DataFactory::getDataFactory — Get a data factory instance

Descrierea

SDO_DAS_DataFactory SDO_DAS_DataFactory::getDataFactory ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

Returns an SDO_DAS_DataFactory.

SDO_DAS_DataFactory::addType
SDO_DAS_DataObject::getChangeSummary
SDO Func?ii


Get a data object's change summary

SDO_DAS_DataFactory::getDataFactory
SDO_DAS_Setting::getListIndex
SDO Func?ii
PHP Manual

SDO_DAS_DataObject::getChangeSummary

(^)

SDO_DAS_DataObject::getChangeSummary — Get a data object's change summary

Descrierea

SDO_DAS_ChangeSummary SDO_DAS_DataObject::getChangeSummary ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Get the SDO_DAS_ChangeSummary for an SDO_DAS_DataObject, or NULL if it does not have one.

Parametri

None.

Valorile întoarse

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 Func?ii


Get the list index for a changed many-valued property

SDO_DAS_DataObject::getChangeSummary
SDO_DAS_Setting::getPropertyIndex
SDO Func?ii
PHP Manual

SDO_DAS_Setting::getListIndex

(^)

SDO_DAS_Setting::getListIndex — Get the list index for a changed many-valued property

Descrierea

int SDO_DAS_Setting::getListIndex ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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).

Parametri

None.

Valorile întoarse

The list index for the element of the many-valued property which has been changed.

SDO_DAS_DataObject::getChangeSummary
SDO_DAS_Setting::getPropertyIndex
SDO Func?ii


Get the property index for a changed property

SDO_DAS_Setting::getListIndex
SDO_DAS_Setting::getPropertyName
SDO Func?ii
PHP Manual

SDO_DAS_Setting::getPropertyIndex

(^)

SDO_DAS_Setting::getPropertyIndex — Get the property index for a changed property

Descrierea

int SDO_DAS_Setting::getPropertyIndex ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Returns the property index for the changed property. This index identifies the property which was modified in data object.

Parametri

None.

Valorile întoarse

The property index for a changed property.

SDO_DAS_Setting::getListIndex
SDO_DAS_Setting::getPropertyName
SDO Func?ii


Get the property name for a changed property

SDO_DAS_Setting::getPropertyIndex
SDO_DAS_Setting::getValue
SDO Func?ii
PHP Manual

SDO_DAS_Setting::getPropertyName

(^)

SDO_DAS_Setting::getPropertyName — Get the property name for a changed property

Descrierea

string SDO_DAS_Setting::getPropertyName ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Returns the property name for the changed property. This name identifies the property which was modified in data object.

Parametri

None.

Valorile întoarse

The property name for a changed property.

SDO_DAS_Setting::getPropertyIndex
SDO_DAS_Setting::getValue
SDO Func?ii


Get the old value for the changed property

SDO_DAS_Setting::getPropertyName
SDO_DAS_Setting::isSet
SDO Func?ii
PHP Manual

SDO_DAS_Setting::getValue

(^)

SDO_DAS_Setting::getValue — Get the old value for the changed property

Descrierea

mixed SDO_DAS_Setting::getValue ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

Returns the old value of the changed property.

SDO_DAS_Setting::getPropertyName
SDO_DAS_Setting::isSet
SDO Func?ii


Test whether a property was set prior to being modified

SDO_DAS_Setting::getValue
SDO_DataFactory::create
SDO Func?ii
PHP Manual

SDO_DAS_Setting::isSet

(^)

SDO_DAS_Setting::isSet — Test whether a property was set prior to being modified

Descrierea

bool SDO_DAS_Setting::isSet ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

Returns TRUE if the property was set prior to being modified, otherwise returns FALSE.

SDO_DAS_Setting::getValue
SDO_DataFactory::create
SDO Func?ii


Create an SDO_DataObject

SDO_DAS_Setting::isSet
SDO_DataObject::clear
SDO Func?ii
PHP Manual

SDO_DataFactory::create

(^)

SDO_DataFactory::create — Create an SDO_DataObject

Descrierea

void SDO_DataFactory::create ( string $type_namespace_uri , string $type_name )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Create a new SDO_DataObject given the data object's namespace URI and type name.

Parametri

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Valorile întoarse

Returns the newly created SDO_DataObject.

Erori/Excep?ii

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 Func?ii


Clear an SDO_DataObject's properties

SDO_DataFactory::create
SDO_DataObject::createDataObject
SDO Func?ii
PHP Manual

SDO_DataObject::clear

(^)

SDO_DataObject::clear — Clear an SDO_DataObject's properties

Descrierea

void SDO_DataObject::clear ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Clear an SDO_DataObject's properties. Read-only properties are unaffected. Subsequent calls to isset() for the data object will return FALSE.

Parametri

None.

Valorile întoarse

No return values.

SDO_DataFactory::create
SDO_DataObject::createDataObject
SDO Func?ii


Create a child SDO_DataObject

SDO_DataObject::clear
SDO_DataObject::getContainer
SDO Func?ii
PHP Manual

SDO_DataObject::createDataObject

(^)

SDO_DataObject::createDataObject — Create a child SDO_DataObject

Descrierea

SDO_DataObject SDO_DataObject::createDataObject ( mixed $identifier )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

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.

Valorile întoarse

Returns the newly created SDO_DataObject.

Erori/Excep?ii

SDO_PropertyNotFoundException

Thrown if the identifier does not correspond to a property of the data object.

SDO_DataObject::clear
SDO_DataObject::getContainer
SDO Func?ii


Get a data object's container

SDO_DataObject::createDataObject
SDO_DataObject::getSequence
SDO Func?ii
PHP Manual

SDO_DataObject::getContainer

(^)

SDO_DataObject::getContainer — Get a data object's container

Descrierea

SDO_DataObject SDO_DataObject::getContainer ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Get the data object which contains this data object.

Parametri

None.

Valorile întoarse

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 Func?ii


Get the sequence for a data object

SDO_DataObject::getContainer
SDO_DataObject::getTypeName
SDO Func?ii
PHP Manual

SDO_DataObject::getSequence

(^)

SDO_DataObject::getSequence — Get the sequence for a data object

Descrierea

SDO_Sequence SDO_DataObject::getSequence ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

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 Func?ii


Return the name of the type for a data object.

SDO_DataObject::getSequence
SDO_DataObject::getTypeNamespaceURI
SDO Func?ii
PHP Manual

SDO_DataObject::getTypeName

(^)

SDO_DataObject::getTypeName — Return the name of the type for a data object.

Descrierea

string SDO_DataObject::getTypeName ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Return the name of the type for a data object. A convenience method corresponding to SDO_Model_ReflectionDataObject::getType().getName().

Parametri

None.

Valorile întoarse

The name of the type for the data object.

SDO_DataObject::getSequence
SDO_DataObject::getTypeNamespaceURI
SDO Func?ii


Return the namespace URI of the type for a data object.

SDO_DataObject::getTypeName
SDO_Exception::getCause
SDO Func?ii
PHP Manual

SDO_DataObject::getTypeNamespaceURI

(^)

SDO_DataObject::getTypeNamespaceURI — Return the namespace URI of the type for a data object.

Descrierea

string SDO_DataObject::getTypeNamespaceURI ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Return the namespace URI of the type for a data object. A convenience method corresponding to SDO_Model_ReflectionDataObject::getType().getNamespaceURI().

Parametri

None.

Valorile întoarse

The namespace URI of the type for the data object.

SDO_DataObject::getTypeName
SDO_Exception::getCause
SDO Func?ii


Get the cause of the exception.

SDO_DataObject::getTypeNamespaceURI
SDO_List::insert
SDO Func?ii
PHP Manual

SDO_Exception::getCause

(^)

SDO_Exception::getCause — Get the cause of the exception.

Descrierea

mixed SDO_Exception::getCause ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

Returns the cause of this exception or NULL if the cause is nonexistent or unknown.

SDO_DataObject::getTypeNamespaceURI
SDO_List::insert
SDO Func?ii


Insert into a list

SDO_Exception::getCause
SDO_Model_Property::getContainingType
SDO Func?ii
PHP Manual

SDO_List::insert

(^)

SDO_List::insert — Insert into a list

Descrierea

void SDO_List::insert ( mixed $value [, int $index ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Insert a new element at a specified position in the list. All subsequent list items are moved up.

Parametri

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.

Valorile întoarse

None.

Erori/Excep?ii

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 Func?ii


Get the SDO_Model_Type which contains this property

SDO_List::insert
SDO_Model_Property::getDefault
SDO Func?ii
PHP Manual

SDO_Model_Property::getContainingType

(^)

SDO_Model_Property::getContainingType — Get the SDO_Model_Type which contains this property

Descrierea

SDO_Model_Type SDO_Model_Property::getContainingType ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Returns the SDO_Model_Type which contains this property.

Parametri

None.

Valorile întoarse

Returns the SDO_Model_Type which contains this property.

SDO_List::insert
SDO_Model_Property::getDefault
SDO Func?ii


Get the default value for the property

SDO_Model_Property::getContainingType
SDO_Model_Property::getName
SDO Func?ii
PHP Manual

SDO_Model_Property::getDefault

(^)

SDO_Model_Property::getDefault — Get the default value for the property

Descrierea

mixed SDO_Model_Property::getDefault ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Returns the default value for the property. Only primitive data type properties can have default values.

Parametri

None.

Valorile întoarse

Returns the default value for the property.

SDO_Model_Property::getContainingType
SDO_Model_Property::getName
SDO Func?ii


Get the name of the SDO_Model_Property

SDO_Model_Property::getDefault
SDO_Model_Property::getType
SDO Func?ii
PHP Manual

SDO_Model_Property::getName

(^)

SDO_Model_Property::getName — Get the name of the SDO_Model_Property

Descrierea

string SDO_Model_Property::getName ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Returns the name of the SDO_Model_Property.

Parametri

None.

Valorile întoarse

Returns the name of the SDO_Model_Property.

SDO_Model_Property::getDefault
SDO_Model_Property::getType
SDO Func?ii


Get the SDO_Model_Type of the property

SDO_Model_Property::getName
SDO_Model_Property::isContainment
SDO Func?ii
PHP Manual

SDO_Model_Property::getType

(^)

SDO_Model_Property::getType — Get the SDO_Model_Type of the property

Descrierea

SDO_Model_Type SDO_Model_Property::getType ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

Returns the SDO_Model_Type describing the property's type information.

SDO_Model_Property::getName
SDO_Model_Property::isContainment
SDO Func?ii


Test to see if the property defines a containment relationship

SDO_Model_Property::getType
SDO_Model_Property::isMany
SDO Func?ii
PHP Manual

SDO_Model_Property::isContainment

(^)

SDO_Model_Property::isContainment — Test to see if the property defines a containment relationship

Descrierea

bool SDO_Model_Property::isContainment ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

Returns TRUE if the property defines a containment relationship, or FALSE if it is reference.

SDO_Model_Property::getType
SDO_Model_Property::isMany
SDO Func?ii


Test to see if the property is many-valued

SDO_Model_Property::isContainment
SDO_Model_ReflectionDataObject::__construct
SDO Func?ii
PHP Manual

SDO_Model_Property::isMany

(^)

SDO_Model_Property::isMany — Test to see if the property is many-valued

Descrierea

bool SDO_Model_Property::isMany ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Test to see if the property is many-valued. Returns TRUE if this is a many-valued property, otherwise returns FALSE.

Parametri

None.

Valorile întoarse

Returns TRUE if this is a many-valued property, otherwise returns FALSE.

SDO_Model_Property::isContainment
SDO_Model_ReflectionDataObject::__construct
SDO Func?ii


Construct an SDO_Model_ReflectionDataObject

SDO_Model_Property::isMany
SDO_Model_ReflectionDataObject::export
SDO Func?ii
PHP Manual

SDO_Model_ReflectionDataObject::__construct

(^)

SDO_Model_ReflectionDataObject::__construct — Construct an SDO_Model_ReflectionDataObject

Descrierea

SDO_Model_ReflectionDataObject::__construct ( SDO_DataObject $data_object )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

data_object

The SDO_DataObject being reflected upon.

Valorile întoarse

None.

SDO_Model_Property::isMany
SDO_Model_ReflectionDataObject::export
SDO Func?ii


Get a string describing the SDO_DataObject.

SDO_Model_ReflectionDataObject::__construct
SDO_Model_ReflectionDataObject::getContainmentProperty
SDO Func?ii
PHP Manual

SDO_Model_ReflectionDataObject::export

(^)

SDO_Model_ReflectionDataObject::export — Get a string describing the SDO_DataObject.

Descrierea

mixed SDO_Model_ReflectionDataObject::export ( SDO_Model_ReflectionDataObject $rdo [, bool $return ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

rdo

An SDO_Model_ReflectionDataObject.

return

If TRUE, return the output as a string, otherwise print it.

Valorile întoarse

Returns the output if TRUE is specified for return, otherwise NULL.

SDO_Model_ReflectionDataObject::__construct
SDO_Model_ReflectionDataObject::getContainmentProperty
SDO Func?ii


Get the property which defines the containment relationship to the data object

SDO_Model_ReflectionDataObject::export
SDO_Model_ReflectionDataObject::getInstanceProperties
SDO Func?ii
PHP Manual

SDO_Model_ReflectionDataObject::getContainmentProperty

(^)

SDO_Model_ReflectionDataObject::getContainmentProperty — Get the property which defines the containment relationship to the data object

Descrierea

SDO_Model_Property SDO_Model_ReflectionDataObject::getContainmentProperty ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

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 Func?ii


Get the instance properties of the SDO_DataObject

SDO_Model_ReflectionDataObject::getContainmentProperty
SDO_Model_ReflectionDataObject::getType
SDO Func?ii
PHP Manual

SDO_Model_ReflectionDataObject::getInstanceProperties

(^)

SDO_Model_ReflectionDataObject::getInstanceProperties — Get the instance properties of the SDO_DataObject

Descrierea

array SDO_Model_ReflectionDataObject::getInstanceProperties ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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).

Parametri

None.

Valorile întoarse

An array of SDO_Model_Property objects.

SDO_Model_ReflectionDataObject::getContainmentProperty
SDO_Model_ReflectionDataObject::getType
SDO Func?ii


Get the SDO_Model_Type for the SDO_DataObject

SDO_Model_ReflectionDataObject::getInstanceProperties
SDO_Model_Type::getBaseType
SDO Func?ii
PHP Manual

SDO_Model_ReflectionDataObject::getType

(^)

SDO_Model_ReflectionDataObject::getType — Get the SDO_Model_Type for the SDO_DataObject

Descrierea

SDO_Model_Type SDO_Model_ReflectionDataObject::getType ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

Returns the SDO_Model_Type for the SDO_DataObject.

SDO_Model_ReflectionDataObject::getInstanceProperties
SDO_Model_Type::getBaseType
SDO Func?ii


Get the base type for this type

SDO_Model_ReflectionDataObject::getType
SDO_Model_Type::getName
SDO Func?ii
PHP Manual

SDO_Model_Type::getBaseType

(^)

SDO_Model_Type::getBaseType — Get the base type for this type

Descrierea

SDO_Model_Type SDO_Model_Type::getBaseType ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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="...">
.

Parametri

None.

Valorile întoarse

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 Func?ii


Get the name of the type

SDO_Model_Type::getBaseType
SDO_Model_Type::getNamespaceURI
SDO Func?ii
PHP Manual

SDO_Model_Type::getName

(^)

SDO_Model_Type::getName — Get the name of the type

Descrierea

string SDO_Model_Type::getName ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Returns the name of the type. The combination of type name and namespace URI is used to uniquely identify the type.

Parametri

None.

Valorile întoarse

Returns the name of the type.

SDO_Model_Type::getBaseType
SDO_Model_Type::getNamespaceURI
SDO Func?ii


Get the namespace URI of the type

SDO_Model_Type::getName
SDO_Model_Type::getProperties
SDO Func?ii
PHP Manual

SDO_Model_Type::getNamespaceURI

(^)

SDO_Model_Type::getNamespaceURI — Get the namespace URI of the type

Descrierea

string SDO_Model_Type::getNamespaceURI ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Returns the namespace URI of the type. The combination of namespace URI and type name is used to uniquely identify the type.

Parametri

None.

Valorile întoarse

Returns the namespace URI of the type.

SDO_Model_Type::getName
SDO_Model_Type::getProperties
SDO Func?ii


Get the SDO_Model_Property objects defined for the type

SDO_Model_Type::getNamespaceURI
SDO_Model_Type::getProperty
SDO Func?ii
PHP Manual

SDO_Model_Type::getProperties

(^)

SDO_Model_Type::getProperties — Get the SDO_Model_Property objects defined for the type

Descrierea

array SDO_Model_Type::getProperties ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

Returns an array of SDO_Model_Property objects.

SDO_Model_Type::getNamespaceURI
SDO_Model_Type::getProperty
SDO Func?ii


Get an SDO_Model_Property of the type

SDO_Model_Type::getProperties
SDO_Model_Type::isAbstractType
SDO Func?ii
PHP Manual

SDO_Model_Type::getProperty

(^)

SDO_Model_Type::getProperty — Get an SDO_Model_Property of the type

Descrierea

SDO_Model_Property SDO_Model_Type::getProperty ( mixed $identifier )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Get an SDO_Model_Property of the type, identified by its property index or property name.

Parametri

identifier

The property index or property name.

Valorile întoarse

Returns the SDO_Model_Property.

SDO_Model_Type::getProperties
SDO_Model_Type::isAbstractType
SDO Func?ii


Test to see if this SDO_Model_Type is an abstract data type

SDO_Model_Type::getProperty
SDO_Model_Type::isDataType
SDO Func?ii
PHP Manual

SDO_Model_Type::isAbstractType

(^)

SDO_Model_Type::isAbstractType — Test to see if this SDO_Model_Type is an abstract data type

Descrierea

bool SDO_Model_Type::isAbstractType ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

Returns TRUE if this type is an abstract data type, otherwise returns FALSE.

SDO_Model_Type::getProperty
SDO_Model_Type::isDataType
SDO Func?ii


Test to see if this SDO_Model_Type is a primitive data type

SDO_Model_Type::isAbstractType
SDO_Model_Type::isInstance
SDO Func?ii
PHP Manual

SDO_Model_Type::isDataType

(^)

SDO_Model_Type::isDataType — Test to see if this SDO_Model_Type is a primitive data type

Descrierea

bool SDO_Model_Type::isDataType ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

Returns TRUE if this type is a primitive data type, otherwise returns FALSE.

SDO_Model_Type::isAbstractType
SDO_Model_Type::isInstance
SDO Func?ii


Test for an SDO_DataObject being an instance of this SDO_Model_Type

SDO_Model_Type::isDataType
SDO_Model_Type::isOpenType
SDO Func?ii
PHP Manual

SDO_Model_Type::isInstance

(^)

SDO_Model_Type::isInstance — Test for an SDO_DataObject being an instance of this SDO_Model_Type

Descrierea

bool SDO_Model_Type::isInstance ( SDO_DataObject $data_object )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

data_object

The SDO_DataObject to be tested.

Valorile întoarse

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 Func?ii


Test to see if this type is an open type

SDO_Model_Type::isInstance
SDO_Model_Type::isSequencedType
SDO Func?ii
PHP Manual

SDO_Model_Type::isOpenType

(^)

SDO_Model_Type::isOpenType — Test to see if this type is an open type

Descrierea

bool SDO_Model_Type::isOpenType ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

Returns TRUE if this type is open, otherwise returns FALSE.

SDO_Model_Type::isInstance
SDO_Model_Type::isSequencedType
SDO Func?ii


Test to see if this is a sequenced type

SDO_Model_Type::isOpenType
SDO_Sequence::getProperty
SDO Func?ii
PHP Manual

SDO_Model_Type::isSequencedType

(^)

SDO_Model_Type::isSequencedType — Test to see if this is a sequenced type

Descrierea

bool SDO_Model_Type::isSequencedType ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

Returns TRUE if this type is sequence, otherwise return FALSE.

SDO_Model_Type::isOpenType
SDO_Sequence::getProperty
SDO Func?ii


Return the property for the specified sequence index.

SDO_Model_Type::isSequencedType
SDO_Sequence::insert
SDO Func?ii
PHP Manual

SDO_Sequence::getProperty

(^)

SDO_Sequence::getProperty — Return the property for the specified sequence index.

Descrierea

SDO_Model_Property SDO_Sequence::getProperty ( int $sequence_index )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Return the property for the specified sequence index.

Parametri

sequence_index

The position of the element in the sequence.

Valorile întoarse

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.

Erori/Excep?ii

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 Func?ii


Insert into a sequence

SDO_Sequence::getProperty
SDO_Sequence::move
SDO Func?ii
PHP Manual

SDO_Sequence::insert

(^)

SDO_Sequence::insert — Insert into a sequence

Descrierea

void SDO_Sequence::insert ( mixed $value [, int $sequenceIndex [, mixed $propertyIdentifier ]] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Insert a new element at a specified position in the sequence. All subsequent sequence items are moved up.

Parametri

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.

Valorile întoarse

None.

Erori/Excep?ii

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 Func?ii


Move an item to another sequence position

SDO_Sequence::insert
SDO-DAS-Relational
SDO Func?ii
PHP Manual

SDO_Sequence::move

(^)

SDO_Sequence::move — Move an item to another sequence position

Descrierea

void SDO_Sequence::move ( int $toIndex, int $fromIndex )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Modify the position of the item in the sequence, without altering the value of the property in the SDO_DataObject.

Parametri

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.

Valorile întoarse

None.

Erori/Excep?ii

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 Func?ii


SDO Relational Data Access Service

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Creating, retrieving, updating and deleting data
    • Specifying the metadata
    • One-table examples
    • Two-table examples
    • Three-table example
  • Limitations
  • SDO-DAS-Relational Func?ii
    • 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
Introducere
Manipularea XML


Introducere

Avertizare

Aceasta extensie este EXPERIMENTALA. Comportamentul acestei extensii ? - inclusiv denumirile func?iilor sale ?i orice alte aspecte documentate în privin?a acestei extensii ? - pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta extensie la propriul risc.

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
Instalarea / configurarea
SDO-DAS-Relational


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SDO-DAS-Relational


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

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';
?>

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Aceasta extensie nu are directive de configurare definite în 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.

Instalarea
Tipurile resurselor
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

DAS Rela?ional nu introduce careva constante predefinite.

Tipurile resurselor
Exemple
SDO-DAS-Relational


Exemple

Cuprins

  • Creating, retrieving, updating and deleting data
  • Specifying the metadata
  • One-table examples
  • Two-table examples
  • Three-table example
Constante predefinite
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.

Exemple
Specifying the metadata
Exemple


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
Exemple


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.

Example #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);
?>

Example #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";
}
?>

Example #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);
?>

Example #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
Exemple


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.

Example #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);

?>

Example #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);
?>

Example #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
Exemple


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.

Example #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";
?>

Example #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";

?>

Example #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
Exemple


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 Func?ii
SDO-DAS-Relational


SDO-DAS-Relational Func?ii

Clase predefinite

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.

Metode

  • __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.

Cuprins

  • 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 Func?ii
SDO_DAS_Relational::__construct
SDO-DAS-Relational Func?ii
PHP Manual

SDO_DAS_Relational::applyChanges

(^)

SDO_DAS_Relational::applyChanges — Applies the changes made to a data graph back to the database.

Descrierea

void SDO_DAS_Relational::applyChanges ( PDO $database_handle , SDODataObject $root_data_object )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

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.

Valorile întoarse

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.

Erori/Excep?ii

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.

Exemple

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 Func?ii
SDO_DAS_Relational::__construct
SDO-DAS-Relational Func?ii


Creates an instance of a Relational Data Access Service

SDO_DAS_Relational::applyChanges
SDO_DAS_Relational::createRootDataObject
SDO-DAS-Relational Func?ii
PHP Manual

SDO_DAS_Relational::__construct

(^)

SDO_DAS_Relational::__construct — Creates an instance of a Relational Data Access Service

Descrierea

SDO_DAS_Relational::__construct ( array $database_metadata [, string $application_root_type [, array $SDO_containment_references_metadata ]] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

Constructs an instance of a Relational Data Access Service from the passed metadata.

Parametri

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.

Valorile întoarse

Returns an SDO_DAS_Relational object on success.

Erori/Excep?ii

SDO_DAS_Relational::__construct() throws a SDO_DAS_Relational_Exception if any problems are found in the metadata.

Exemple

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 Func?ii


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 Func?ii
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.

Descrierea

SDODataObject SDO_DAS_Relational::createRootDataObject ( void )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

None.

Valorile întoarse

The root object.

Erori/Excep?ii

None.

Exemple

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 Func?ii


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 Func?ii
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.

Descrierea

SDODataObject SDO_DAS_Relational::executePreparedQuery ( PDO $database_handle , PDOStatement $prepared_statement , array $value_list [, array $column_specifier ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

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.

Valorile întoarse

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.

Erori/Excep?ii

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.

Exemple

Example #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 Func?ii


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 Func?ii
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.

Descrierea

SDODataObject SDO_DAS_Relational::executeQuery ( PDO $database_handle , string $SQL_statement [, array $column_specifier ] )
Avertizare

Aceasta func?ie este EXPERIMENTALA. Comportamentul acestei func?ii, denumirea sa ?i orice alte aspecte documentate în privin?a acestei func?ii pot sa fie modificate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceasta func?ie la propriul risc.

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.

Parametri

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.

Valorile întoarse

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.

Erori/Excep?ii

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.

Exemple

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 Func?ii


SDO XML Data Access Service

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
  • SDO DAS XML Func?ii
    • 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
Introducere
Manipularea XML


Introducere

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
Instalarea / configurarea
SDO DAS XML


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SDO DAS XML


Necesita?i

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.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

The XML Data Access Service is packaged and installed as part of the SDO extension. Please Refer SDO installation instructions.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
SDO DAS XML


Exemple

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>

Example #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>

Example #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>

Example #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"?>
.../...

Example #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>

Example #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

Example #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)
Constante predefinite
SDO DAS XML Func?ii
SDO DAS XML


SDO DAS XML Func?ii

Clase predefinite

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,

Metode

  • 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.

Metode

  • 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.

Cuprins

  • 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
Exemple
SDO_DAS_XML::addTypes
SDO DAS XML


To load a second or subsequent schema file to a SDO_DAS_XML object

SDO DAS XML Func?ii
SDO_DAS_XML::create
SDO DAS XML Func?ii
PHP Manual

SDO_DAS_XML::addTypes

(^)

SDO_DAS_XML::addTypes — To load a second or subsequent schema file to a SDO_DAS_XML object

Descrierea

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.

Parametri

xsd_file

Path to XSD Schema file.

Valorile întoarse

None if successful, otherwise throws an exception as described below.

Erori/Excep?ii

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 Func?ii
SDO_DAS_XML::create
SDO DAS XML Func?ii


To create SDO_DAS_XML object for a given schema file

SDO_DAS_XML::addTypes
SDO_DAS_XML::createDataObject
SDO DAS XML Func?ii
PHP Manual

SDO_DAS_XML::create

(^)

SDO_DAS_XML::create — To create SDO_DAS_XML object for a given schema file

Descrierea

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.

Parametri

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

Valorile întoarse

Returns SDO_DAS_XML object on success otherwise throws an exception as described below.

Erori/Excep?ii

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 Func?ii


Creates SDO_DataObject for a given namespace URI and type name

SDO_DAS_XML::create
SDO_DAS_XML::createDocument
SDO DAS XML Func?ii
PHP Manual

SDO_DAS_XML::createDataObject

(^)

SDO_DAS_XML::createDataObject — Creates SDO_DataObject for a given namespace URI and type name

Descrierea

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.

Parametri

namespace_uri

Namespace URI of the type name.

type_name

Type Name.

Valorile întoarse

Returns SDO_DataObject on success.

Erori/Excep?ii

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

SDO_DAS_XML::create
SDO_DAS_XML::createDocument
SDO DAS XML Func?ii


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 Func?ii
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.

Descrierea

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.

Parametri

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

Valorile întoarse

Returns an SDO_XML_DAS_Document object on success.

Erori/Excep?ii

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 Func?ii


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 Func?ii
PHP Manual

SDO_DAS_XML::loadFile

(^)

SDO_DAS_XML::loadFile — Returns SDO_DAS_XML_Document object for a given path to xml instance document

Descrierea

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.

Parametri

xml_file

Path to Instance document. This can be a path to a local file or it can be a URL.

Valorile întoarse

Returns SDO_DAS_XML_Document object on Success or throws exception as described.

Erori/Excep?ii

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 Func?ii


Returns SDO_DAS_XML_Document for a given xml instance string

SDO_DAS_XML::loadFile
SDO_DAS_XML::saveFile
SDO DAS XML Func?ii
PHP Manual

SDO_DAS_XML::loadString

(^)

SDO_DAS_XML::loadString — Returns SDO_DAS_XML_Document for a given xml instance string

Descrierea

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.

Parametri

xml_string

xml string.

Valorile întoarse

Returns SDO_DAS_XML_Document object on Success or throws exception as described.

Erori/Excep?ii

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 Func?ii


Saves the SDO_DAS_XML_Document object to a file

SDO_DAS_XML::loadString
SDO_DAS_XML::saveString
SDO DAS XML Func?ii
PHP Manual

SDO_DAS_XML::saveFile

(^)

SDO_DAS_XML::saveFile — Saves the SDO_DAS_XML_Document object to a file

Descrierea

void SDO_DAS_XML::saveFile ( SDO_XMLDocument $xdoc , string $xml_file [, int $indent ] )

Saves the SDO_DAS_XML_Document object to a file.

Parametri

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.

Valorile întoarse

None.

Erori/Excep?ii

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.

SDO_DAS_XML::loadString
SDO_DAS_XML::saveString
SDO DAS XML Func?ii


Saves the SDO_DAS_XML_Document object to a string

SDO_DAS_XML::saveFile
SDO_DAS_XML_Document::getRootDataObject
SDO DAS XML Func?ii
PHP Manual

SDO_DAS_XML::saveString

(^)

SDO_DAS_XML::saveString — Saves the SDO_DAS_XML_Document object to a string

Descrierea

string SDO_DAS_XML::saveString ( SDO_XMLDocument $xdoc [, int $indent ] )

Saves the SDO_DAS_XML_Document object to string.

Parametri

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.

Valorile întoarse

xml string.

SDO_DAS_XML::saveFile
SDO_DAS_XML_Document::getRootDataObject
SDO DAS XML Func?ii


Returns the root SDO_DataObject

SDO_DAS_XML::saveString
SDO_DAS_XML_Document::getRootElementName
SDO DAS XML Func?ii
PHP Manual

SDO_DAS_XML_Document::getRootDataObject

(^)

SDO_DAS_XML_Document::getRootDataObject — Returns the root SDO_DataObject

Descrierea

SDO_DataObject SDO_DAS_XML_Document::getRootDataObject ( void )

Returns the root SDO_DataObject.

Parametri

Valorile întoarse

Returns the root SDO_DataObject.

SDO_DAS_XML::saveString
SDO_DAS_XML_Document::getRootElementName
SDO DAS XML Func?ii


Returns root element's name

SDO_DAS_XML_Document::getRootDataObject
SDO_DAS_XML_Document::getRootElementURI
SDO DAS XML Func?ii
PHP Manual

SDO_DAS_XML_Document::getRootElementName

(^)

SDO_DAS_XML_Document::getRootElementName — Returns root element's name

Descrierea

string SDO_DAS_XML_Document::getRootElementName ( void )

Returns root element's name.

Parametri

Valorile întoarse

Returns root element's name.

SDO_DAS_XML_Document::getRootDataObject
SDO_DAS_XML_Document::getRootElementURI
SDO DAS XML Func?ii


Returns root element's URI string

SDO_DAS_XML_Document::getRootElementName
SDO_DAS_XML_Document::setEncoding
SDO DAS XML Func?ii
PHP Manual

SDO_DAS_XML_Document::getRootElementURI

(^)

SDO_DAS_XML_Document::getRootElementURI — Returns root element's URI string

Descrierea

string SDO_DAS_XML_Document::getRootElementURI ( void )

Returns root element's URI string.

Parametri

Valorile întoarse

Returns root element's URI string.

SDO_DAS_XML_Document::getRootElementName
SDO_DAS_XML_Document::setEncoding
SDO DAS XML Func?ii


Sets the given string as encoding

SDO_DAS_XML_Document::getRootElementURI
SDO_DAS_XML_Document::setXMLDeclaration
SDO DAS XML Func?ii
PHP Manual

SDO_DAS_XML_Document::setEncoding

(^)

SDO_DAS_XML_Document::setEncoding — Sets the given string as encoding

Descrierea

void SDO_DAS_XML_Document::setEncoding ( string $encoding )

Sets the given string as encoding.

Parametri

encoding

Encoding string.

Valorile întoarse

None.

SDO_DAS_XML_Document::getRootElementURI
SDO_DAS_XML_Document::setXMLDeclaration
SDO DAS XML Func?ii


Sets the xml declaration

SDO_DAS_XML_Document::setEncoding
SDO_DAS_XML_Document::setXMLVersion
SDO DAS XML Func?ii
PHP Manual

SDO_DAS_XML_Document::setXMLDeclaration

(^)

SDO_DAS_XML_Document::setXMLDeclaration — Sets the xml declaration

Descrierea

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.

Parametri

xmlDeclatation

Boolean value to set the XML declaration.

Valorile întoarse

None.

SDO_DAS_XML_Document::setEncoding
SDO_DAS_XML_Document::setXMLVersion
SDO DAS XML Func?ii


Sets the given string as xml version

SDO_DAS_XML_Document::setXMLDeclaration
SimpleXML
SDO DAS XML Func?ii
PHP Manual

SDO_DAS_XML_Document::setXMLVersion

(^)

SDO_DAS_XML_Document::setXMLVersion — Sets the given string as xml version

Descrierea

void SDO_DAS_XML_Document::setXMLVersion ( string $xmlVersion )

Sets the given string as xml version.

Parametri

xmlVersion

xml version string.

Valorile întoarse

None.

SDO_DAS_XML_Document::setXMLDeclaration
SimpleXML
SDO DAS XML Func?ii


SimpleXML

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • 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 — Pseudonim pentru SimpleXMLElement::asXML
    • SimpleXMLElement::__toString — Returns the string content
    • 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
  • Func?ii SimpleXML
    • 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
Introducere
Manipularea XML


Introducere

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
Instalarea / configurarea
SimpleXML


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
SimpleXML


Necesita?i

Aceasta extensie necesita extensia PHP libxml. Aceasta înseamna ca e necesara de asemenea ?i indicarea op?iunii --enable-libxml , cu toate ca aceasta este realizat în mod implicit deoarece libxml este activata implicit.

The SimpleXML extension requires PHP 5.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie este activata în mod implicit. Ea poate fi dezactivata utilizând urmatoarea op?iune la compilare: --disable-simplexml .

Nota: Înainte de PHP 5.1.2, indicarea op?iunii --enable-simplexml era necesara pentru a activa aceasta extensie.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
SimpleXML


Exemple

Cuprins

  • Basic SimpleXML usage
  • Dealing with XML errors
Constante predefinite
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().

Example #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.

Example #2 Getting <plot>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie[0]->plot;
?>

Exemplul de mai sus va afi?a:

   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.

Example #3 Getting <line>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie->{'great-lines'}->line;
?>

Exemplul de mai sus va afi?a:

PHP solves all my web problems

Example #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;
}

?>

Exemplul de mai sus va afi?a:

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Nota:

Properties ($movies->movie in previous example) are not arrays. They are iterable and accessible objects.

Example #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;
    }
}
?>

Exemplul de mai sus va afi?a:

7 thumbs up5 stars

Example #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);
?>

Exemplul de mai sus va afi?a:

My favorite movie.PHP: Behind the Parser

Example #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
?>

Exemplul de mai sus va afi?a:

bool(false)

Example #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.

Exemplul de mai sus va afi?a:

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Example #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();
?>

Exemplul de mai sus va afi?a:

<?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>

Example #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 = $movies->movie[0]->addChild('rating', 'PG');
$rating->addAttribute('type', 'mpaa');

echo $movies->asXML();
?>

Exemplul de mai sus va afi?a:

<?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>

Example #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;
?>

Exemplul de mai sus va afi?a:

blah

Exemple
Dealing with XML errors
Exemple


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.

Example #1 Loading broken XML string

<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if ($sxe === false) {
    echo "Failed loading XML\n";
    foreach(libxml_get_errors() as $error) {
        echo "\t", $error->message;
    }
}
?>

Exemplul de mai sus va afi?a:

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

A se vedea ?i

  • libxml_use_internal_errors()
  • libxml_get_errors()
  • libXMLError

Basic SimpleXML usage
SimpleXMLElement
Exemple


The SimpleXMLElement class

(PHP 5 >= 5.0.1, PHP 7)

Introducere

Represents an element in an XML document.

Sinopsisul clasei

SimpleXMLElement implements Traversable {
/* Metode */
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 [, bool $from_root = true ]] )
public string getName ( void )
public array getNamespaces ([ bool $recursive = false ] )
public bool registerXPathNamespace ( string $prefix , string $ns )
public string __toString ( void )
public array xpath ( string $path )
}

Cuprins

  • 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 — Pseudonim pentru SimpleXMLElement::asXML
  • SimpleXMLElement::__toString — Returns the string content
  • 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, PHP 7)

SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element

Descrierea

public void SimpleXMLElement::addAttribute ( string $name [, string $value [, string $namespace ]] )

Adds an attribute to the SimpleXML element.

Parametri

name

The name of the attribute to add.

value

The value of the attribute.

namespace

If specified, the namespace to which the attribute belongs.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Nota:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #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();

?>

Exemplul de mai sus va afi?a ceva similar cu:

<?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>

A se vedea ?i

  • 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, PHP 7)

SimpleXMLElement::addChild — Adds a child element to the XML node

Descrierea

public SimpleXMLElement SimpleXMLElement::addChild ( string $name [, string $value [, string $namespace ]] )

Adds a child element to the node and returns a SimpleXMLElement of the child.

Parametri

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.

Valorile întoarse

The addChild method returns a SimpleXMLElement object representing the child added to the XML node.

Exemple

Nota:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #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();

?>

Exemplul de mai sus va afi?a ceva similar cu:

<?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>

A se vedea ?i

  • 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, PHP 7)

SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element

Descrierea

public mixed SimpleXMLElement::asXML ([ string $filename ] )

The asXML method formats the parent object's data in XML version 1.0.

Parametri

filename

If specified, the function writes the data to the file rather than returning it.

Valorile întoarse

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.

Exemple

Example #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();

?>

Exemplul de mai sus va afi?a:

<?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:

Example #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();
}
?>

Exemplul de mai sus va afi?a:

<c>text</c><c>stuff</c>

A se vedea ?i

  • SimpleXMLElement::__toString() - Returns the string content
  • 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, PHP 7)

SimpleXMLElement::attributes — Identifies an element's attributes

Descrierea

public SimpleXMLElement SimpleXMLElement::attributes ([ string $ns = NULL [, bool $is_prefix = false ]] )

This function provides the attributes and values defined within an xml tag.

Nota: SimpleXML a creat o regula de a adauga proprieta?i iterative la majoritatea metodelor. Ele nu pot fi vizualizate cu ajutorul var_dump() sau orice altceva ce poate examina obiecte.

Parametri

ns

An optional namespace for the retrieved attributes

is_prefix

Default to FALSE

Valorile întoarse

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.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

name="one"
game="lonely"

A se vedea ?i

  • 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, PHP 7)

SimpleXMLElement::children — Finds children of given node

Descrierea

public SimpleXMLElement SimpleXMLElement::children ([ string $ns [, bool $is_prefix = false ]] )

This method finds the children of an element. The result follows normal iteration rules.

Nota: SimpleXML a creat o regula de a adauga proprieta?i iterative la majoritatea metodelor. Ele nu pot fi vizualizate cu ajutorul var_dump() sau orice altceva ce poate examina obiecte.

Parametri

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.

Valorile întoarse

Returns a SimpleXMLElement element, whether the node has children or not.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | The optional parameter is_prefix was added.

Exemple

Example #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'];
        }
    }
}
?>

Exemplul de mai sus va afi?a:

The person begot a son who begot a daughter; The person
begot a daughter who begot a son; and that son begot a son

Example #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)

Note

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.

A se vedea ?i

  • SimpleXMLElement::count() - Counts the children of an element
  • count() - Count all elements in an array, or something in an object

SimpleXMLElement::attributes
SimpleXMLElement::__construct
SimpleXMLElement


Creates a new SimpleXMLElement object

SimpleXMLElement::children
SimpleXMLElement::count
SimpleXMLElement
PHP Manual

SimpleXMLElement::__construct

(PHP 5 >= 5.0.1, PHP 7)

SimpleXMLElement::__construct — Creates a new SimpleXMLElement object

Descrierea

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.

Parametri

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.

Nota:

It may be necessary to pass LIBXML_PARSEHUGE to be able to process deeply nested XML or very large text nodes.

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.

Valorile întoarse

Returns a SimpleXMLElement object representing data.

Erori/Excep?ii

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.

Sfat

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Exemple

Nota:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Create a SimpleXMLElement object

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->movie[0]->title;

?>

Exemplul de mai sus va afi?a:

PHP: Behind the Parser

Example #2 Create a SimpleXMLElement object from a URL

<?php

$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
echo $sxe->asXML();

?>

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | Added the ns and is_prefix parameters.
5.1.2 | Added the options and data_is_url parameters.

A se vedea ?i

  • 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, PHP 7)

SimpleXMLElement::count — Counts the children of an element

Descrierea

public int SimpleXMLElement::count ( void )

This method counts the number of children of an element.

Valorile întoarse

Returns the number of elements of an element.

Exemple

Example #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());
}
?>

Exemplul de mai sus va afi?a:

Person 1 has got 3 children.
Person 2 has got 5 children.

A se vedea ?i

  • 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, PHP 7)

SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document

Descrierea

public array SimpleXMLElement::getDocNamespaces ([ bool $recursive = false [, bool $from_root = true ]] )

Returns namespaces declared in document

Parametri

recursive

If specified, returns all namespaces declared in parent and child nodes. Otherwise, returns only namespaces declared in root node.

from_root

Allows you to recursively check namespaces under a child node instead of from the root of the XML doc.

Valorile întoarse

The getDocNamespaces method returns an array of namespace names with their associated URIs.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

array(1) {
   ["p"]=>
   string(21) "http://example.org/ns"
}

Example #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);

?>

Exemplul de mai sus va afi?a:

array(3) {
  ["p"]=>
  string(21) "http://example.org/ns"
  ["t"]=>
  string(23) "http://example.org/test"
  ["a"]=>
  string(23) "http://example.org/addr"
}

Istoricul schimbarilor

Versiune | Descriere
5.4.0 | Added from_root parameter.

A se vedea ?i

  • 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, PHP 7)

SimpleXMLElement::getName — Gets the name of the XML element

Descrierea

public string SimpleXMLElement::getName ( void )

Gets the name of the XML element.

Valorile întoarse

The getName method returns as a string the name of the XML tag referenced by the SimpleXMLElement object.

Exemple

Nota:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #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";
}

?>

Exemplul de mai sus va afi?a:

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, PHP 7)

SimpleXMLElement::getNamespaces — Returns namespaces used in document

Descrierea

public array SimpleXMLElement::getNamespaces ([ bool $recursive = false ] )

Returns namespaces used in document

Parametri

recursive

If specified, returns all namespaces used in parent and child nodes. Otherwise, returns only namespaces used in root node.

Valorile întoarse

The getNamespaces method returns an array of namespace names with their associated URIs.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

array(1) {
  ["p"]=>
  string(21) "http://example.org/ns"
}

A se vedea ?i

  • 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, PHP 7)

SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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";
}

?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • 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


Pseudonim pentru SimpleXMLElement::asXML

SimpleXMLElement::registerXPathNamespace
SimpleXMLElement::__toString
SimpleXMLElement
PHP Manual

SimpleXMLElement::saveXML

(PHP 5 >= 5.2.0, PHP 7)

SimpleXMLElement::saveXML — Pseudonim pentru SimpleXMLElement::asXML()

Descrierea

Aceasta metoda este pseudonim pentru: SimpleXMLElement::asXML()

SimpleXMLElement::registerXPathNamespace
SimpleXMLElement::__toString
SimpleXMLElement


Returns the string content

SimpleXMLElement::saveXML
SimpleXMLElement::xpath
SimpleXMLElement
PHP Manual

SimpleXMLElement::__toString

(No version information available, might only be in Git)

SimpleXMLElement::__toString — Returns the string content

Descrierea

public string SimpleXMLElement::__toString ( void )

Returns text content that is directly in this element. Does not return text content that is inside this element's children.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the string content on success or an empty string on failure.

Exemple

Example #1 Get string content

<?php
$xml = new SimpleXMLElement('<a>1 <b>2 </b>3</a>');
echo $xml;
?>

Exemplul de mai sus va afi?a:

1 3

A se vedea ?i

  • SimpleXMLElement::asXML() - Return a well-formed XML string based on SimpleXML element

SimpleXMLElement::saveXML
SimpleXMLElement::xpath
SimpleXMLElement


Runs XPath query on XML data

SimpleXMLElement::__toString
SimpleXMLIterator
SimpleXMLElement
PHP Manual

SimpleXMLElement::xpath

(PHP 5 >= 5.2.0, PHP 7)

SimpleXMLElement::xpath — Runs XPath query on XML data

Descrierea

public array SimpleXMLElement::xpath ( string $path )

The xpath method searches the SimpleXML node for children matching the XPath path.

Parametri

path

An XPath path

Valorile întoarse

Returns an array of SimpleXMLElement objects or FALSE in case of an error.

Exemple

Example #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";
}
?>

Exemplul de mai sus va afi?a:

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

Notice that the two results are equal.

A se vedea ?i

  • 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::__toString
SimpleXMLIterator
SimpleXMLElement


The SimpleXMLIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

The SimpleXMLIterator provides recursive iteration over all nodes of a SimpleXMLElement object.

Sinopsisul clasei

SimpleXMLIterator extends SimpleXMLElement implements RecursiveIterator , Countable {
/* Metode */
public mixed current ( void )
public SimpleXMLIterator getChildren ( void )
public bool hasChildren ( void )
public mixed key ( void )
public void next ( void )
public void rewind ( void )
public bool valid ( void )
/* Metode mo?tenite */
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 [, bool $from_root = true ]] )
public string SimpleXMLElement::getName ( void )
public array SimpleXMLElement::getNamespaces ([ bool $recursive = false ] )
public bool SimpleXMLElement::registerXPathNamespace ( string $prefix , string $ns )
public string SimpleXMLElement::__toString ( void )
public array SimpleXMLElement::xpath ( string $path )
}

Cuprins

  • 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, PHP 7)

SimpleXMLIterator::current — Returns the current element

Descrierea

public mixed SimpleXMLIterator::current ( void )

This method returns the current element as a SimpleXMLIterator object or NULL.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the current element as a SimpleXMLIterator object or NULL on failure.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

NULL
object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "PHP basics"
}

A se vedea ?i

  • 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, PHP 7)

SimpleXMLIterator::getChildren — Returns the sub-elements of the current element

Descrierea

public SimpleXMLIterator SimpleXMLIterator::getChildren ( void )

This method returns a SimpleXMLIterator object containing sub-elements of the current SimpleXMLIterator element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns a SimpleXMLIterator object containing the sub-elements of the current element.

Exemple

Example #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";
    }
}
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

SimpleXMLIterator::hasChildren — Checks whether the current element has sub elements.

Descrierea

public bool SimpleXMLIterator::hasChildren ( void )

This method checks whether the current SimpleXMLIterator element has sub-elements.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

TRUE if the current element has sub-elements, otherwise FALSE

Exemple

Example #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());
    }
}
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

SimpleXMLIterator::key — Return current key

Descrierea

public mixed SimpleXMLIterator::key ( void )

This method gets the XML tag name of the current element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the XML tag name of the element referenced by the current SimpleXMLIterator object or FALSE

Exemple

Example #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());

?>

Exemplul de mai sus va afi?a:

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, PHP 7)

SimpleXMLIterator::next — Move to next element

Descrierea

public void SimpleXMLIterator::next ( void )

This method moves the SimpleXMLIterator to the next element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

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, PHP 7)

SimpleXMLIterator::rewind — Rewind to the first element

Descrierea

public void SimpleXMLIterator::rewind ( void )

This method rewinds the SimpleXMLIterator to the first element.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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());
?>

Exemplul de mai sus va afi?a:

object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "PHP Basics"
}

SimpleXMLIterator::next
SimpleXMLIterator::valid
SimpleXMLIterator


Check whether the current element is valid

SimpleXMLIterator::rewind
Func?ii SimpleXML
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::valid

(PHP 5 >= 5.1.0, PHP 7)

SimpleXMLIterator::valid — Check whether the current element is valid

Descrierea

public bool SimpleXMLIterator::valid ( void )

This method checks if the current element is valid after calls to SimpleXMLIterator::rewind() or SimpleXMLIterator::next().

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns TRUE if the current element is valid, otherwise FALSE

Exemple

Example #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
Func?ii SimpleXML
SimpleXMLIterator


Func?ii SimpleXML

Cuprins

  • 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.

Func?ii SimpleXML
simplexml_load_file
Func?ii SimpleXML
PHP Manual

simplexml_import_dom

(PHP 5, PHP 7)

simplexml_import_dom — Get a SimpleXMLElement object from a DOM node.

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns a SimpleXMLElement sau FALSE în cazul e?ecului.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Exemple

Example #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;
?>

Exemplul de mai sus va afi?a:

blah

A se vedea ?i

  • dom_import_simplexml() - Gets a DOMElement object from a SimpleXMLElement object
  • Basic SimpleXML usage

Func?ii SimpleXML
simplexml_load_file
Func?ii SimpleXML


Interprets an XML file into an object

simplexml_import_dom
simplexml_load_string
Func?ii SimpleXML
PHP Manual

simplexml_load_file

(PHP 5, PHP 7)

simplexml_load_file — Interprets an XML file into an object

Descrierea

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.

Parametri

filename

Path to the XML file

Nota:

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.

Valorile întoarse

Returns an object of class SimpleXMLElement with properties containing the data held within the XML document, sau FALSE în cazul e?ecului.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Erori/Excep?ii

Produces an E_WARNING error message for each error found in the XML data.

Sfat

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Exemple

Example #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.

A se vedea ?i

  • 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
Func?ii SimpleXML


Interprets a string of XML into an object

simplexml_load_file
WDDX
Func?ii SimpleXML
PHP Manual

simplexml_load_string

(PHP 5, PHP 7)

simplexml_load_string — Interprets a string of XML into an object

Descrierea

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.

Parametri

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.

Valorile întoarse

Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, sau FALSE în cazul e?ecului.

Avertizare

Aceasta func?ie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evalueaza în FALSE. Va rugam sa citi?i sec?iunea despre tipul Boolean pentru informa?ii suplimentare. Utiliza?i operatorul === pentru a verifica valoarea întoarsa de aceasta func?ie.

Erori/Excep?ii

Produces an E_WARNING error message for each error found in the XML data.

Sfat

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Exemple

Example #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);
?>

Exemplul de mai sus va afi?a:

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.

A se vedea ?i

  • 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
Func?ii SimpleXML


WDDX

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Exemple wddx
  • Func?ii WDDX
    • wddx_add_vars — Adauga variable la un pachet WDDX cu un ID specificat
    • wddx_deserialize — Deserializeaza un pachet WDDX
    • wddx_packet_end — Sfâr?e?te un pachet WDDX cu un ID specificat
    • wddx_packet_start — Ini?iaza un pachet nou WDDX cu structura sa interna
    • wddx_serialize_value — Serializeaza o singura valoare într-un pachet WDDX
    • wddx_serialize_vars — Serializeaza variabile într-un pachet WDDX
simplexml_load_string
Introducere
Manipularea XML


Introducere

Aceste func?ii sunt destinate pentru lucrul cu » WDDX.

WDDX
Instalarea / configurarea
WDDX


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
WDDX


Necesita?i

Aceasta extensie necesita extensia PHP libxml. Aceasta înseamna ca e necesara de asemenea ?i indicarea op?iunii --enable-libxml , cu toate ca aceasta este realizat în mod implicit deoarece libxml este activata implicit.

Pentru a utiliza WDDX va trebui sa instala?i biblioteca expat (care vine cu Apache 1.3.7 sau ulterior).

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Dupa instalarea bibliotecii expat, care este necesara, compila?i PHP cu op?iunea --enable-wddx ?i utiliza?i --with-libexpat-dir pentru expat.

Versiunea PHP pentru Windows sus?ine implicit aceasta extensie. Nu este nevoie sa încarca?i extensii suplimentare pentru a putea utiliza aceste func?ii.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie define?te un identificator de pachet WDDX întors de wddx_packet_start().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Exemple
WDDX


Exemple

Cuprins

  • Exemple wddx
Constante predefinite
Exemple wddx
WDDX


Exemple wddx

Toate func?iile care serializeaza variabile utilizeaza primul element din array pentru a determina daca array-ul trebuie serializat într-un array, sau într-o structura. Daca primul element are o cheie-string, atunci el este serializat într-o structura, în caz contrar, într-un array.

Example #1 Serializarea unei singure valori cu WDDX

<?php
echo wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

Acest exemplu va produce:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Example #2 Utilizarea pachetelor incrementale cu 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;
?>

Acest exemplu va 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>

Nota:

Daca dori?i sa serializa?i caractere non-ASCII, trebuie mai întâi sa converti?i datele dumneavoastra în UTF-8 (vezi utf8_encode() ?i iconv()).

Exemple
Func?ii WDDX
Exemple


Func?ii WDDX

Cuprins

  • wddx_add_vars — Adauga variable la un pachet WDDX cu un ID specificat
  • wddx_deserialize — Deserializeaza un pachet WDDX
  • wddx_packet_end — Sfâr?e?te un pachet WDDX cu un ID specificat
  • wddx_packet_start — Ini?iaza un pachet nou WDDX cu structura sa interna
  • wddx_serialize_value — Serializeaza o singura valoare într-un pachet WDDX
  • wddx_serialize_vars — Serializeaza variabile într-un pachet WDDX
Exemple wddx
wddx_add_vars
WDDX


Adauga variable la un pachet WDDX cu un ID specificat

Func?ii WDDX
wddx_deserialize
Func?ii WDDX
PHP Manual

wddx_add_vars

(PHP 4, PHP 5, PHP 7)

wddx_add_vars — Adauga variable la un pachet WDDX cu un ID specificat

Descrierea

bool wddx_add_vars ( resource $packet_id , mixed $var_name [, mixed $... ] )

Serializeaza variabilele transmise ?i adauga rezultatul la pachetul dat.

Parametri

Aceasta func?ie preia un numar variabil de parametri.

packet_id

Un pachet WDDX, întors de wddx_packet_start().

var_name

Poate fi sau un string cu denumirea variabilei, sau un array con?inând string-uri cu denumirile variabilelor, sau un alt array, etc.

...

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Func?ii WDDX
wddx_deserialize
Func?ii WDDX


Deserializeaza un pachet WDDX

wddx_add_vars
wddx_packet_end
Func?ii WDDX
PHP Manual

wddx_deserialize

(PHP 4, PHP 5, PHP 7)

wddx_deserialize — Deserializeaza un pachet WDDX

Descrierea

mixed wddx_deserialize ( string $packet )

Deserializeaza un packet WDDX.

Parametri

packet

Un pachet WDDX reprezentat ca string sau stream.

Valorile întoarse

Întoarce valoarea deserializata, care poate fi un string, un numar sau un tablou. Observa?i ca structurile sunt deserializate în tablouri asociative.

Note

Avertizare

Nu transmite?i date introduse de utilizator, în care nu ave?i încredere, spre wddx_deserialize(). Deserializarea poate rezulta în cod ce va fi încarcat ?i executat datorita instan?ierii ?i autoîncarcarii obiectelor, ?i un utilizator malign s-ar putea folosi de aceasta.

wddx_add_vars
wddx_packet_end
Func?ii WDDX


Sfâr?e?te un pachet WDDX cu un ID specificat

wddx_deserialize
wddx_packet_start
Func?ii WDDX
PHP Manual

wddx_packet_end

(PHP 4, PHP 5, PHP 7)

wddx_packet_end — Sfâr?e?te un pachet WDDX cu un ID specificat

Descrierea

string wddx_packet_end ( resource $packet_id )

Sfâr?e?te ?i întoarce pachetul WDDX dat.

Parametri

packet_id

Un pachet WDDX întors de wddx_packet_start().

Valorile întoarse

Întoarce string-ul con?inând pachetul WDDX.

wddx_deserialize
wddx_packet_start
Func?ii WDDX


Ini?iaza un pachet nou WDDX cu structura sa interna

wddx_packet_end
wddx_serialize_value
Func?ii WDDX
PHP Manual

wddx_packet_start

(PHP 4, PHP 5, PHP 7)

wddx_packet_start — Ini?iaza un pachet nou WDDX cu structura sa interna

Descrierea

resource wddx_packet_start ([ string $comment ] )

Ini?iaza un nou pachet WDDX pentru adaugari consecutive de variabile. Func?ia creeaza în mod automat defini?ia structurii din interiorul pachetului pentru ca acesta sa con?ina variabilele.

Parametri

comment

Un string cu comentariu op?ional.

Valorile întoarse

Întoarce un ID al pachetului, pentru a fi utilizat ulterior în func?ii, sau FALSE în caz de eroare.

wddx_packet_end
wddx_serialize_value
Func?ii WDDX


Serializeaza o singura valoare într-un pachet WDDX

wddx_packet_start
wddx_serialize_vars
Func?ii WDDX
PHP Manual

wddx_serialize_value

(PHP 4, PHP 5, PHP 7)

wddx_serialize_value — Serializeaza o singura valoare într-un pachet WDDX

Descrierea

string wddx_serialize_value ( mixed $var [, string $comment ] )

Creeaza un pachet WDDX dintr-o singura valoare transmisa.

Parametri

var

Valoarea pentru a fi serializata

comment

Un string cu comentariu op?ional, care apare în antetul pachetului.

Valorile întoarse

Întoarce pachetul WDDX, sau FALSE în caz de eroare.

wddx_packet_start
wddx_serialize_vars
Func?ii WDDX


Serializeaza variabile într-un pachet WDDX

wddx_serialize_value
XMLDiff
Func?ii WDDX
PHP Manual

wddx_serialize_vars

(PHP 4, PHP 5, PHP 7)

wddx_serialize_vars — Serializeaza variabile într-un pachet WDDX

Descrierea

string wddx_serialize_vars ( mixed $var_name [, mixed $... ] )

Creeaza un pachet WDDX cu o structura ce con?ine reprezentarea serializata a variabilelor transmise.

Parametri

Aceasta func?ie preia un numar variabil de parametri.

var_name

Poate fi sau un string cu denumirea variabilei, sau un array con?inând string-uri cu denumirile variabilelor, sau un alt array, etc.

...

Valorile întoarse

Întoarce pachetul WDDX, sau FALSE în caz de eroare.

Exemple

Example #1 Exemplu wddx_serialize_vars()

<?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";

$clvars = array("c", "d");
echo wddx_serialize_vars("a", "b", $clvars);
?>

Exemplul de mai sus va afi?a:

<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
XMLDiff
Func?ii WDDX


XML diff and merge

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
  • XMLDiff\Base — The XMLDiff\Base class
    • XMLDiff\Base::__construct — Constructor
    • XMLDiff\Base::diff — Produce diff of two XML documents
    • XMLDiff\Base::merge — Produce new XML document based on diff
  • XMLDiff\DOM — The XMLDiff\DOM class
    • XMLDiff\DOM::diff — Diff two DOMDocument objects
    • XMLDiff\DOM::merge — Produce merged DOMDocument
  • XMLDiff\Memory — The XMLDiff\Memory class
    • XMLDiff\Memory::diff — Diff two XML documents
    • XMLDiff\Memory::merge — Produce merged XML document
  • XMLDiff\File — The XMLDiff\File class
    • XMLDiff\File::diff — Diff two XML files
    • XMLDiff\File::merge — Produce merged XML document
wddx_serialize_vars
Introducere
Manipularea XML


Introducere

The extension is able to produce diffs of two XML documents and then to apply the difference to the source document. The diff is a XML document containing copy/insert/delete instruction nodes in human readable format. DOMDocument objects, local files and strings in memory can be processed.

XMLDiff
Instalarea / configurarea
XMLDiff


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
Introducere
Necesita?i
XMLDiff


Necesita?i

libdiffmark - version 0.10 is bundled with the extension. If diffmark is available from your system packages, its usage is strongly encouraged.

libxml extension

DOM extension

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/xmldiff.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/xmldiff/.

Necesita?i
XMLDiff\Base
Instalarea / configurarea


The XMLDiff\Base class

(PECL xmldiff >= 0.8.0)

Introducere

Base abstract class for all the comparsion classes in the extension.

Sinopsisul clasei

XMLDiff\Base {
/* Metode */
public __construct ( string $nsname )
abstract public mixed diff ( mixed $from , mixed $to )
abstract public mixed merge ( mixed $src , mixed $diff )
}

Cuprins

  • XMLDiff\Base::__construct — Constructor
  • XMLDiff\Base::diff — Produce diff of two XML documents
  • XMLDiff\Base::merge — Produce new XML document based on diff
Instalarea
XMLDiff\Base::__construct
XMLDiff


Constructor

XMLDiff\Base
XMLDiff\Base::diff
XMLDiff\Base
PHP Manual

XMLDiff\Base::__construct

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::__construct — Constructor

Descrierea

public XMLDiff\Base::__construct ( string $nsname )

Base constructor for all the worker classes in the xmldiff extension.

Parametri

nsname

Custom namespace name for the diff document. The default namespace is http://www.locus.cz/diffmark and that's enough to avoid namespace conflicts. Use this parameter if you want to change it for some reason.

Valorile întoarse

XMLDiff\Base
XMLDiff\Base::diff
XMLDiff\Base


Produce diff of two XML documents

XMLDiff\Base::__construct
XMLDiff\Base::merge
XMLDiff\Base
PHP Manual

XMLDiff\Base::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::diff — Produce diff of two XML documents

Descrierea

abstract public mixed XMLDiff\Base::diff ( mixed $from , mixed $to )

Abstract diff method to be implemented by inheriting classes.

The basic purpose of this method is to produce diff of the two documents. The param order matters and will produce different output.

Parametri

from

Source XML document.

to

Target XML document.

Valorile întoarse

Implementation dependent.

XMLDiff\Base::__construct
XMLDiff\Base::merge
XMLDiff\Base


Produce new XML document based on diff

XMLDiff\Base::diff
XMLDiff\DOM
XMLDiff\Base
PHP Manual

XMLDiff\Base::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::merge — Produce new XML document based on diff

Descrierea

abstract public mixed XMLDiff\Base::merge ( mixed $src , mixed $diff )

Abstract merge method to be implemented by inheriting classes.

Basically the method purpose is to produce a new XML document based on the diff information.

Parametri

src

Source XML document.

diff

Document produced by the diff method.

Valorile întoarse

Implementation dependent.

XMLDiff\Base::diff
XMLDiff\DOM
XMLDiff\Base


The XMLDiff\DOM class

(PECL xmldiff >= 0.8.0)

Introducere

Sinopsisul clasei

XMLDiff\DOM extends XMLDiff\Base {
/* Metode */
public DOMDocument diff ( DOMDocument $from , DOMDocument $to )
public DOMDocument merge ( DOMDocument $src , DOMDocument $diff )
/* Metode mo?tenite */
public XMLDiff\Base::__construct ( string $nsname )
abstract public mixed XMLDiff\Base::diff ( mixed $from , mixed $to )
abstract public mixed XMLDiff\Base::merge ( mixed $src , mixed $diff )
}

Cuprins

  • XMLDiff\DOM::diff — Diff two DOMDocument objects
  • XMLDiff\DOM::merge — Produce merged DOMDocument
XMLDiff\Base::merge
XMLDiff\DOM::diff
XMLDiff


Diff two DOMDocument objects

XMLDiff\DOM
XMLDiff\DOM::merge
XMLDiff\DOM
PHP Manual

XMLDiff\DOM::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\DOM::diff — Diff two DOMDocument objects

Descrierea

public DOMDocument XMLDiff\DOM::diff ( DOMDocument $from , DOMDocument $to )

Diff two DOMDocument instances and produce the new one containing the diff information.

Parametri

from

Source DOMDocument object.

to

Target DOMDocument object.

Valorile întoarse

DOMDocument with the diff information or NULL.

XMLDiff\DOM
XMLDiff\DOM::merge
XMLDiff\DOM


Produce merged DOMDocument

XMLDiff\DOM::diff
XMLDiff\Memory
XMLDiff\DOM
PHP Manual

XMLDiff\DOM::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\DOM::merge — Produce merged DOMDocument

Descrierea

public DOMDocument XMLDiff\DOM::merge ( DOMDocument $src , DOMDocument $diff )

Create new DOMDocument based on the diff.

Parametri

src

Source DOMDocument object.

diff

DOMDocument object containing the diff information.

Valorile întoarse

Merged DOMDocument or NULL.

XMLDiff\DOM::diff
XMLDiff\Memory
XMLDiff\DOM


The XMLDiff\Memory class

(PECL xmldiff >= 0.8.0)

Introducere

Sinopsisul clasei

XMLDiff\Memory extends XMLDiff\Base {
/* Metode */
public string diff ( string $from , string $to )
public string merge ( string $src , string $diff )
/* Metode mo?tenite */
public XMLDiff\Base::__construct ( string $nsname )
abstract public mixed XMLDiff\Base::diff ( mixed $from , mixed $to )
abstract public mixed XMLDiff\Base::merge ( mixed $src , mixed $diff )
}

Cuprins

  • XMLDiff\Memory::diff — Diff two XML documents
  • XMLDiff\Memory::merge — Produce merged XML document
XMLDiff\DOM::merge
XMLDiff\Memory::diff
XMLDiff


Diff two XML documents

XMLDiff\Memory
XMLDiff\Memory::merge
XMLDiff\Memory
PHP Manual

XMLDiff\Memory::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\Memory::diff — Diff two XML documents

Descrierea

public string XMLDiff\Memory::diff ( string $from , string $to )

Diff two strings containing XML documents and produce the diff information.

Parametri

from

Source XML document.

to

Target XML document.

Valorile întoarse

String with the XML document containing the diff information or NULL.

XMLDiff\Memory
XMLDiff\Memory::merge
XMLDiff\Memory


Produce merged XML document

XMLDiff\Memory::diff
XMLDiff\File
XMLDiff\Memory
PHP Manual

XMLDiff\Memory::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\Memory::merge — Produce merged XML document

Descrierea

public string XMLDiff\Memory::merge ( string $src , string $diff )

Create new XML document based on diffs and source document.

Parametri

src

Source XML document.

diff

XML document containing diff information.

Valorile întoarse

String with the new XML document or NULL.

XMLDiff\Memory::diff
XMLDiff\File
XMLDiff\Memory


The XMLDiff\File class

(PECL xmldiff >= 0.8.0)

Introducere

Sinopsisul clasei

XMLDiff\File extends XMLDiff\Base {
/* Metode */
public string diff ( string $from , string $to )
public string merge ( string $src , string $diff )
/* Metode mo?tenite */
public XMLDiff\Base::__construct ( string $nsname )
abstract public mixed XMLDiff\Base::diff ( mixed $from , mixed $to )
abstract public mixed XMLDiff\Base::merge ( mixed $src , mixed $diff )
}

Cuprins

  • XMLDiff\File::diff — Diff two XML files
  • XMLDiff\File::merge — Produce merged XML document
XMLDiff\Memory::merge
XMLDiff\File::diff
XMLDiff


Diff two XML files

XMLDiff\File
XMLDiff\File::merge
XMLDiff\File
PHP Manual

XMLDiff\File::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\File::diff — Diff two XML files

Descrierea

public string XMLDiff\File::diff ( string $from , string $to )

Diff two local XML files and produce string with the diff information.

Parametri

from

Path to the source document.

to

Path to the target document.

Valorile întoarse

String with the XML document containing the diff information or NULL.

XMLDiff\File
XMLDiff\File::merge
XMLDiff\File


Produce merged XML document

XMLDiff\File::diff
XML Parser
XMLDiff\File
PHP Manual

XMLDiff\File::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\File::merge — Produce merged XML document

Descrierea

public string XMLDiff\File::merge ( string $src , string $diff )

Create new XML document based on diffs and source document.

Parametri

src

Path to the source XML document.

diff

Path to the XML document with the diff information.

Valorile întoarse

String with the new XML document or NULL.

XMLDiff\File::diff
XML Parser
XMLDiff\File


XML Parser

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Event Handlers
  • Case Folding
  • Error Codes
  • Character Encoding
  • Exemple
    • XML Element Structure Example
    • XML Tag Mapping Example
    • XML External Entity Example
  • Func?ii ale interpretatorului XML
    • utf8_decode — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1
    • utf8_encode — Encodes an ISO-8859-1 string to UTF-8
    • xml_error_string — Get XML parser error string
    • xml_get_current_byte_index — Get current byte index for an XML parser
    • xml_get_current_column_number — Get current column number for an XML parser
    • xml_get_current_line_number — Get current line number for an XML parser
    • xml_get_error_code — Get XML parser error code
    • xml_parse_into_struct — Parse XML data into an array structure
    • xml_parse — Start parsing an XML document
    • xml_parser_create_ns — Create an XML parser with namespace support
    • xml_parser_create — Create an XML parser
    • xml_parser_free — Free an XML parser
    • 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 — Set up start and end element handlers
    • 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
XMLDiff\File::merge
Introducere
Manipularea XML


Introducere

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
Instalarea / configurarea
XML Parser


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
XML Parser


Necesita?i

Aceasta extensie necesita extensia PHP libxml. Aceasta înseamna ca e necesara de asemenea ?i indicarea op?iunii --enable-libxml , cu toate ca aceasta este realizat în mod implicit deoarece libxml este activata implicit.

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/.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie este activata în mod implicit. Ea poate fi dezactivata utilizând urmatoarea op?iune la compilare: --disable-xml

These functions are enabled by default, using the bundled expat library. You can disable XML support with --disable-xml . If you compile PHP as a module for Apache 1.3.9 or later, PHP will automatically use the bundled expat library from Apache. If you don't want to use the bundled expat library, configure PHP with --with-expat-dir=DIR , where DIR should point to the base installation directory of expat.

Versiunea PHP pentru Windows sus?ine implicit aceasta extensie. Nu este nevoie sa încarca?i extensii suplimentare pentru a putea utiliza aceste func?ii.

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

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.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
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 triggered by libXML.

Constante predefinite
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
Exemple
XML Parser


Exemple

Cuprins

  • 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.

Example #1 Show XML Element Structure

<?php
$file = "data.xml";
$depth = array();

function startElement($parser, $name, $attrs)
{
    global $depth;

    if (!isset($depth[$parser])) {
        $depth[$parser] = 0;
    }

    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);
?>

Exemple
XML Tag Mapping Example
Exemple


XML Tag Mapping Example

Example #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
Exemple


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.)

Example #1 External Entity Example

<?php
$file = "xmltest.xml";

function trustedFile($file)
{
    // only trust local files owned by ourselves
    if (!preg_match("@^([a-z][a-z0-9+.-]*)\:\/\/@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);

?>

Example #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:

Example #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
Func?ii ale interpretatorului XML
Exemple


Func?ii ale interpretatorului XML

Cuprins

  • utf8_decode — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1
  • utf8_encode — Encodes an ISO-8859-1 string to UTF-8
  • xml_error_string — Get XML parser error string
  • xml_get_current_byte_index — Get current byte index for an XML parser
  • xml_get_current_column_number — Get current column number for an XML parser
  • xml_get_current_line_number — Get current line number for an XML parser
  • xml_get_error_code — Get XML parser error code
  • xml_parse_into_struct — Parse XML data into an array structure
  • xml_parse — Start parsing an XML document
  • xml_parser_create_ns — Create an XML parser with namespace support
  • xml_parser_create — Create an XML parser
  • xml_parser_free — Free an XML parser
  • 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 — Set up start and end element handlers
  • 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


Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1

Func?ii ale interpretatorului XML
utf8_encode
Func?ii ale interpretatorului XML
PHP Manual

utf8_decode

(PHP 4, PHP 5, PHP 7)

utf8_decode — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1

Descrierea

string utf8_decode ( string $data )

This function converts the string data from the UTF-8 encoding to ISO-8859-1. Bytes in the string which are not valid UTF-8, and UTF-8 characters which do not exist in ISO-8859-1 (that is, characters above U+00FF) are replaced with ?.

Nota:

Many web pages marked as using the ISO-8859-1 character encoding actually use the similar Windows-1252 encoding, and web browsers will interpret ISO-8859-1 web pages as Windows-1252. Windows-1252 features additional printable characters, such as the Euro sign (€) and curly quotes (“ ”), instead of certain ISO-8859-1 control characters. This function will not convert such Windows-1252 characters correctly. Use a different function if Windows-1252 conversion is required.

Parametri

data

A UTF-8 encoded string.

Valorile întoarse

Returns the ISO-8859-1 translation of data.

A se vedea ?i

  • utf8_encode() - Encodes an ISO-8859-1 string to UTF-8 - Performs the reverse conversion
  • mb_convert_encoding() - Convert character encoding - Converts between various character encodings, including UTF-8, ISO-8859-1 and Windows-1252
  • iconv() - Convert string to requested character encoding - Converts between various character encodings
  • recode_string() - Recode a string according to a recode request - Converts between various character encodings

Func?ii ale interpretatorului XML
utf8_encode
Func?ii ale interpretatorului XML


Encodes an ISO-8859-1 string to UTF-8

utf8_decode
xml_error_string
Func?ii ale interpretatorului XML
PHP Manual

utf8_encode

(PHP 4, PHP 5, PHP 7)

utf8_encode — Encodes an ISO-8859-1 string to UTF-8

Descrierea

string utf8_encode ( string $data )

This function converts the string data from the ISO-8859-1 encoding to UTF-8.

Nota:

Many web pages marked as using the ISO-8859-1 character encoding actually use the similar Windows-1252 encoding, and web browsers will interpret ISO-8859-1 web pages as Windows-1252. Windows-1252 features additional printable characters, such as the Euro sign (€) and curly quotes (“ ”), instead of certain ISO-8859-1 control characters. This function will not convert such Windows-1252 characters correctly. Use a different function if Windows-1252 conversion is required.

Parametri

data

An ISO-8859-1 string.

Valorile întoarse

Returns the UTF-8 translation of data.

A se vedea ?i

  • utf8_decode() - Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1 - Performs the reverse conversion
  • mb_convert_encoding() - Convert character encoding - Converts between various character encodings, including UTF-8, ISO-8859-1 and Windows-1252
  • iconv() - Convert string to requested character encoding - Converts between various character encodings
  • recode_string() - Recode a string according to a recode request - Converts between various character encodings

utf8_decode
xml_error_string
Func?ii ale interpretatorului XML


Get XML parser error string

utf8_encode
xml_get_current_byte_index
Func?ii ale interpretatorului XML
PHP Manual

xml_error_string

(PHP 4, PHP 5, PHP 7)

xml_error_string — Get XML parser error string

Descrierea

string xml_error_string ( int $code )

Gets the XML parser error string associated with the given code.

Parametri

code

An error code from xml_get_error_code().

Valorile întoarse

Returns a string with a textual description of the error code, or FALSE if no description was found.

A se vedea ?i

  • xml_get_error_code() - Get XML parser error code

utf8_encode
xml_get_current_byte_index
Func?ii ale interpretatorului XML


Get current byte index for an XML parser

xml_error_string
xml_get_current_column_number
Func?ii ale interpretatorului XML
PHP Manual

xml_get_current_byte_index

(PHP 4, PHP 5, PHP 7)

xml_get_current_byte_index — Get current byte index for an XML parser

Descrierea

int xml_get_current_byte_index ( resource $parser )

Gets the current byte index of the given XML parser.

Parametri

parser

A reference to the XML parser to get byte index from.

Valorile întoarse

This function returns FALSE if parser does not refer to a valid parser, or else it returns which byte index the parser is currently at in its data buffer (starting at 0).

Note

Avertizare

This function returns byte index according to UTF-8 encoded text disregarding if input is in another encoding.

A se vedea ?i

  • xml_get_current_column_number() - Get current column number for an XML parser
  • xml_get_current_line_number() - Get current line number for an XML parser

xml_error_string
xml_get_current_column_number
Func?ii ale interpretatorului XML


Get current column number for an XML parser

xml_get_current_byte_index
xml_get_current_line_number
Func?ii ale interpretatorului XML
PHP Manual

xml_get_current_column_number

(PHP 4, PHP 5, PHP 7)

xml_get_current_column_number — Get current column number for an XML parser

Descrierea

int xml_get_current_column_number ( resource $parser )

Gets the current column number of the given XML parser.

Parametri

parser

A reference to the XML parser to get column number from.

Valorile întoarse

This function returns FALSE if parser does not refer to a valid parser, or else it returns which column on the current line (as given by xml_get_current_line_number()) the parser is currently at.

A se vedea ?i

  • xml_get_current_byte_index() - Get current byte index for an XML parser
  • xml_get_current_line_number() - Get current line number for an XML parser

xml_get_current_byte_index
xml_get_current_line_number
Func?ii ale interpretatorului XML


Get current line number for an XML parser

xml_get_current_column_number
xml_get_error_code
Func?ii ale interpretatorului XML
PHP Manual

xml_get_current_line_number

(PHP 4, PHP 5, PHP 7)

xml_get_current_line_number — Get current line number for an XML parser

Descrierea

int xml_get_current_line_number ( resource $parser )

Gets the current line number for the given XML parser.

Parametri

parser

A reference to the XML parser to get line number from.

Valorile întoarse

This function returns FALSE if parser does not refer to a valid parser, or else it returns which line the parser is currently at in its data buffer.

A se vedea ?i

  • xml_get_current_column_number() - Get current column number for an XML parser
  • xml_get_current_byte_index() - Get current byte index for an XML parser

xml_get_current_column_number
xml_get_error_code
Func?ii ale interpretatorului XML


Get XML parser error code

xml_get_current_line_number
xml_parse_into_struct
Func?ii ale interpretatorului XML
PHP Manual

xml_get_error_code

(PHP 4, PHP 5, PHP 7)

xml_get_error_code — Get XML parser error code

Descrierea

int xml_get_error_code ( resource $parser )

Gets the XML parser error code.

Parametri

parser

A reference to the XML parser to get error code from.

Valorile întoarse

This function returns FALSE if parser does not refer to a valid parser, or else it returns one of the error codes listed in the error codes section.

A se vedea ?i

  • xml_error_string() - Get XML parser error string

xml_get_current_line_number
xml_parse_into_struct
Func?ii ale interpretatorului XML


Parse XML data into an array structure

xml_get_error_code
xml_parse
Func?ii ale interpretatorului XML
PHP Manual

xml_parse_into_struct

(PHP 4, PHP 5, PHP 7)

xml_parse_into_struct — Parse XML data into an array structure

Descrierea

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.

Parametri

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.

Valorile întoarse

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 ===.

Exemple

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:

Example #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:

Example #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:

Example #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
Func?ii ale interpretatorului XML


Start parsing an XML document

xml_parse_into_struct
xml_parser_create_ns
Func?ii ale interpretatorului XML
PHP Manual

xml_parse

(PHP 4, PHP 5, PHP 7)

xml_parse — Start parsing an XML document

Descrierea

int xml_parse ( resource $parser , string $data [, bool $is_final = false ] )

xml_parse() parses an XML document. The handlers for the configured events are called as many times as necessary.

Parametri

parser

A reference to the XML parser to use.

data

Chunk of data to parse. A document may be parsed piece-wise by calling xml_parse() several times with new data, as long as the is_final parameter is set and TRUE when the last data is parsed.

is_final

If set and TRUE, data is the last piece of data sent in this parse.

Valorile întoarse

Returns 1 on success or 0 on failure.

For unsuccessful parses, error information can be retrieved with
xml_get_error_code(),
xml_error_string(),
xml_get_current_line_number(),
xml_get_current_column_number() and
xml_get_current_byte_index().

Nota:

Entity errors are reported at the end of the data thus only if is_final is set and TRUE.

xml_parse_into_struct
xml_parser_create_ns
Func?ii ale interpretatorului XML


Create an XML parser with namespace support

xml_parse
xml_parser_create
Func?ii ale interpretatorului XML
PHP Manual

xml_parser_create_ns

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

xml_parser_create_ns — Create an XML parser with namespace support

Descrierea

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.

Parametri

encoding

The input encoding is automatically detected, so that the encoding parameter specifies only the output encoding. 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 separator.

Valorile întoarse

Returns a resource handle for the new XML parser.

A se vedea ?i

  • xml_parser_create() - Create an XML parser
  • xml_parser_free() - Free an XML parser

xml_parse
xml_parser_create
Func?ii ale interpretatorului XML


Create an XML parser

xml_parser_create_ns
xml_parser_free
Func?ii ale interpretatorului XML
PHP Manual

xml_parser_create

(PHP 4, PHP 5, PHP 7)

xml_parser_create — Create an XML parser

Descrierea

resource xml_parser_create ([ string $encoding ] )

xml_parser_create() creates a new XML parser and returns a resource handle referencing it to be used by the other XML functions.

Parametri

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. If empty string is passed, the parser attempts to identify which encoding the document is encoded in by looking at the heading 3 or 4 bytes. 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.

Valorile întoarse

Returns a resource handle for the new XML parser.

A se vedea ?i

  • xml_parser_create_ns() - Create an XML parser with namespace support
  • xml_parser_free() - Free an XML parser

xml_parser_create_ns
xml_parser_free
Func?ii ale interpretatorului XML


Free an XML parser

xml_parser_create
xml_parser_get_option
Func?ii ale interpretatorului XML
PHP Manual

xml_parser_free

(PHP 4, PHP 5, PHP 7)

xml_parser_free — Free an XML parser

Descrierea

bool xml_parser_free ( resource $parser )

Frees the given XML parser.

Parametri

parser
A reference to the XML parser to free.

Valorile întoarse

This function returns FALSE if parser does not refer to a valid parser, or else it frees the parser and returns TRUE.

xml_parser_create
xml_parser_get_option
Func?ii ale interpretatorului XML


Get options from an XML parser

xml_parser_free
xml_parser_set_option
Func?ii ale interpretatorului XML
PHP Manual

xml_parser_get_option

(PHP 4, PHP 5, PHP 7)

xml_parser_get_option — Get options from an XML parser

Descrierea

mixed xml_parser_get_option ( resource $parser , int $option )

Gets an option value from an XML parser.

Parametri

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.

Valorile întoarse

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
Func?ii ale interpretatorului XML


Set options in an XML parser

xml_parser_get_option
xml_set_character_data_handler
Func?ii ale interpretatorului XML
PHP Manual

xml_parser_set_option

(PHP 4, PHP 5, PHP 7)

xml_parser_set_option — Set options in an XML parser

Descrierea

bool xml_parser_set_option ( resource $parser , int $option , mixed $value )

Sets an option in an XML parser.

Parametri

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.

Valorile întoarse

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
Func?ii ale interpretatorului XML


Set up character data handler

xml_parser_set_option
xml_set_default_handler
Func?ii ale interpretatorului XML
PHP Manual

xml_set_character_data_handler

(PHP 4, PHP 5, PHP 7)

xml_set_character_data_handler — Set up character data handler

Descrierea

bool xml_set_character_data_handler ( resource $parser , callable $handler )

Sets the character data handler function for the XML parser parser.

Parametri

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.

Nota: În locul denumirii func?iei poate fi indicat un tablou con?inând o referin?a la obiect ?i o denumire a metodei.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

xml_parser_set_option
xml_set_default_handler
Func?ii ale interpretatorului XML


Set up default handler

xml_set_character_data_handler
xml_set_element_handler
Func?ii ale interpretatorului XML
PHP Manual

xml_set_default_handler

(PHP 4, PHP 5, PHP 7)

xml_set_default_handler — Set up default handler

Descrierea

bool xml_set_default_handler ( resource $parser , callable $handler )

Sets the default handler function for the XML parser parser.

Parametri

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.

Nota: În locul denumirii func?iei poate fi indicat un tablou con?inând o referin?a la obiect ?i o denumire a metodei.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

xml_set_character_data_handler
xml_set_element_handler
Func?ii ale interpretatorului XML


Set up start and end element handlers

xml_set_default_handler
xml_set_end_namespace_decl_handler
Func?ii ale interpretatorului XML
PHP Manual

xml_set_element_handler

(PHP 4, PHP 5, PHP 7)

xml_set_element_handler — Set up start and end element handlers

Descrierea

bool xml_set_element_handler ( resource $parser , callable $start_element_handler , callable $end_element_handler )

Sets the element handler functions for the XML parser. start_element_handler and end_element_handler are strings containing the names of functions that must exist when xml_parse() is called for parser.

Parametri

parser

A reference to the XML parser to set up start and end element handler functions.

start_element_handler

The function named by start_element_handler must accept three parameters:

start_element_handler ( resource $parser , string $name , array $attribs )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
name
The second parameter, name, contains the name of the element for which this handler is called.If case-folding is in effect for this parser, the element name will be in uppercase letters.
attribs
The third parameter, attribs, contains an associative array with the element's attributes (if any).The keys of this array are the attribute names, the values are the attribute values.Attribute names are case-folded on the same criteria as element names.Attribute values are not case-folded. The original order of the attributes can be retrieved by walking through attribs the normal way, using each().The first key in the array was the first attribute, and so on.

Nota: În locul denumirii func?iei poate fi indicat un tablou con?inând o referin?a la obiect ?i o denumire a metodei.

end_element_handler

The function named by end_element_handler must accept two parameters:

end_element_handler ( resource $parser , string $name )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
name
The second parameter, name, contains the name of the element for which this handler is called.If case-folding is in effect for this parser, the element name will be in uppercase letters.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

xml_set_default_handler
xml_set_end_namespace_decl_handler
Func?ii ale interpretatorului XML


Set up end namespace declaration handler

xml_set_element_handler
xml_set_external_entity_ref_handler
Func?ii ale interpretatorului XML
PHP Manual

xml_set_end_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

xml_set_end_namespace_decl_handler — Set up end namespace declaration handler

Descrierea

bool xml_set_end_namespace_decl_handler ( resource $parser , callable $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.

Precautie

This event is not supported under libXML, so a registered handler wouldn't be called.

Parametri

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.

Nota: În locul denumirii func?iei poate fi indicat un tablou con?inând o referin?a la obiect ?i o denumire a metodei.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • xml_set_start_namespace_decl_handler() - Set up start namespace declaration handler

xml_set_element_handler
xml_set_external_entity_ref_handler
Func?ii ale interpretatorului XML


Set up external entity reference handler

xml_set_end_namespace_decl_handler
xml_set_notation_decl_handler
Func?ii ale interpretatorului XML
PHP Manual

xml_set_external_entity_ref_handler

(PHP 4, PHP 5, PHP 7)

xml_set_external_entity_ref_handler — Set up external entity reference handler

Descrierea

bool xml_set_external_entity_ref_handler ( resource $parser , callable $handler )

Sets the external entity reference handler function for the XML parser parser.

Parametri

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.

Nota: În locul denumirii func?iei poate fi indicat un tablou con?inând o referin?a la obiect ?i o denumire a metodei.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

xml_set_end_namespace_decl_handler
xml_set_notation_decl_handler
Func?ii ale interpretatorului XML


Set up notation declaration handler

xml_set_external_entity_ref_handler
xml_set_object
Func?ii ale interpretatorului XML
PHP Manual

xml_set_notation_decl_handler

(PHP 4, PHP 5, PHP 7)

xml_set_notation_decl_handler — Set up notation declaration handler

Descrierea

bool xml_set_notation_decl_handler ( resource $parser , callable $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.

Parametri

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.

Nota: În locul denumirii func?iei poate fi indicat un tablou con?inând o referin?a la obiect ?i o denumire a metodei.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

xml_set_external_entity_ref_handler
xml_set_object
Func?ii ale interpretatorului XML


Use XML Parser within an object

xml_set_notation_decl_handler
xml_set_processing_instruction_handler
Func?ii ale interpretatorului XML
PHP Manual

xml_set_object

(PHP 4, PHP 5, PHP 7)

xml_set_object — Use XML Parser within an object

Descrierea

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.

Precautie

In addition to calling xml_parser_free() when the parsing is finished, as of PHP 7.0.0 it is necessary to also explicitly unset the reference to parser to avoid memory leaks.

Parametri

parser

A reference to the XML parser to use inside the object.

object

The object where to use the XML parser.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 xml_set_object() example

<?php
class XMLParser
{
    private $parser;

    function __construct()
    {
        $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 __destruct()
    {
        xml_parser_free($this->parser);
        unset($this->parser);
    }

    function parse($data)
    {
        xml_parse($this->parser, $data);
    }

    function tag_open($parser, $tag, $attributes)
    {
        var_dump($tag, $attributes);
    }

    function cdata($parser, $cdata)
    {
        var_dump($cdata);
    }

    function tag_close($parser, $tag)
    {
        var_dump($tag);
    }
}

$xml_parser = new XMLParser();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
?>

Exemplul de mai sus va afi?a:

string(1) "A"
array(1) {
  ["ID"]=>
  string(5) "hallo"
}
string(3) "PHP"
string(1) "A"

xml_set_notation_decl_handler
xml_set_processing_instruction_handler
Func?ii ale interpretatorului XML


Set up processing instruction (PI) handler

xml_set_object
xml_set_start_namespace_decl_handler
Func?ii ale interpretatorului XML
PHP Manual

xml_set_processing_instruction_handler

(PHP 4, PHP 5, PHP 7)

xml_set_processing_instruction_handler — Set up processing instruction (PI) handler

Descrierea

bool xml_set_processing_instruction_handler ( resource $parser , callable $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.

Parametri

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.

Nota: În locul denumirii func?iei poate fi indicat un tablou con?inând o referin?a la obiect ?i o denumire a metodei.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

xml_set_object
xml_set_start_namespace_decl_handler
Func?ii ale interpretatorului XML


Set up start namespace declaration handler

xml_set_processing_instruction_handler
xml_set_unparsed_entity_decl_handler
Func?ii ale interpretatorului XML
PHP Manual

xml_set_start_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

xml_set_start_namespace_decl_handler — Set up start namespace declaration handler

Descrierea

bool xml_set_start_namespace_decl_handler ( resource $parser , callable $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.

Parametri

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.

Nota: În locul denumirii func?iei poate fi indicat un tablou con?inând o referin?a la obiect ?i o denumire a metodei.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • xml_set_end_namespace_decl_handler() - Set up end namespace declaration handler

xml_set_processing_instruction_handler
xml_set_unparsed_entity_decl_handler
Func?ii ale interpretatorului XML


Set up unparsed entity declaration handler

xml_set_start_namespace_decl_handler
XMLReader
Func?ii ale interpretatorului XML
PHP Manual

xml_set_unparsed_entity_decl_handler

(PHP 4, PHP 5, PHP 7)

xml_set_unparsed_entity_decl_handler — Set up unparsed entity declaration handler

Descrierea

bool xml_set_unparsed_entity_decl_handler ( resource $parser , callable $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.

Parametri

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.

Nota: În locul denumirii func?iei poate fi indicat un tablou con?inând o referin?a la obiect ?i o denumire a metodei.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

xml_set_start_namespace_decl_handler
XMLReader
Func?ii ale interpretatorului XML


XMLReader

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • 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 itself
    • 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
Introducere
Manipularea XML


Introducere

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.

Codificarea

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
Instalarea / configurarea
XMLReader


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
XMLReader


Instalarea

The XMLReader extension was initially a PECL extension for PHP 5. It was later moved to the PHP source (bundled) as of PHP 5.1.0, and later enabled by default as of PHP 5.1.2.

Aceasta extensie este activata în mod implicit. Ea poate fi dezactivata utilizând urmatoarea op?iune la compilare: --disable-xmlreader

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

Aceasta extensie nu are tipuri de resurse definite.

Configura?ia la rulare
XMLReader
Instalarea / configurarea


The XMLReader class

(PHP 5 >= 5.1.0, PHP 7)

Introducere

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.

Sinopsisul clasei

XMLReader {
/* Constante */
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 ;
/* Proprieta?i */
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 ;
/* Metode */
public bool close ( void )
public DOMNode expand ([ DOMNode $basenode ] )
public string getAttribute ( string $name )
public string getAttributeNo ( int $index )
public string getAttributeNs ( string $localName , string $namespaceURI )
public bool getParserProperty ( int $property )
public bool isValid ( void )
public string lookupNamespace ( string $prefix )
public bool moveToAttribute ( string $name )
public bool moveToAttributeNo ( int $index )
public bool moveToAttributeNs ( string $localName , string $namespaceURI )
public bool moveToElement ( void )
public bool moveToFirstAttribute ( void )
public bool moveToNextAttribute ( void )
public bool next ([ string $localname ] )
public bool open ( string $URI [, string $encoding [, int $options = 0 ]] )
public bool read ( void )
public string readInnerXML ( void )
public string readOuterXML ( void )
public string readString ( void )
public bool setParserProperty ( int $property , bool $value )
public bool setRelaxNGSchema ( string $filename )
public bool setRelaxNGSchemaSource ( string $source )
public bool setSchema ( string $filename )
public bool xml ( string $source [, string $encoding [, int $options = 0 ]] )
}

Proprieta?i

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

Constante predefinite

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

Cuprins

  • 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 itself
  • 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
Tipurile resurselor
XMLReader::close
XMLReader


Close the XMLReader input

XMLReader
XMLReader::expand
XMLReader
PHP Manual

XMLReader::close

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::close — Close the XMLReader input

Descrierea

public bool XMLReader::close ( void )

Closes the input the XMLReader object is currently parsing.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::expand — Returns a copy of the current node as a DOM object

Descrierea

public DOMNode XMLReader::expand ([ DOMNode $basenode ] )

This method copies the current node and returns the appropriate DOM object.

Parametri

basenode

A DOMNode defining the target DOMDocument for the created DOM object.

Valorile întoarse

The resulting DOMNode or FALSE on error.

Istoricul schimbarilor

Versiune | Descriere
5.3.0 | The parameter basenode was added.

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.0, PHP 7)

XMLReader::getAttribute — Get the value of a named attribute

Descrierea

public 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.

Parametri

name

The name of the attribute.

Valorile întoarse

The value of the attribute, or NULL if no attribute with the given name is found or not positioned on an element node.

Istoricul schimbarilor

Versiune | Descriere
5.1.3 | Return NULL if no attribute found. Previously, returned an empty string.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::getAttributeNo — Get the value of an attribute by index

Descrierea

public 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.

Parametri

index

The position of the attribute.

Valorile întoarse

The value of the attribute, or an empty string (before PHP 5.6) or NULL (from PHP 5.6 onwards) if no attribute exists at index or is not positioned on the element.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | XMLReader::getAttributeNo() now returns NULL if the attribute doesn't exist.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::getAttributeNs — Get the value of an attribute by localname and URI

Descrierea

public 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.

Parametri

localName

The local name.

namespaceURI

The namespace URI.

Valorile întoarse

The value of the attribute, or an empty string (before PHP 5.6) or NULL (from PHP 5.6 onwards) if no attribute with the given localName and namespaceURI is found or not positioned of element.

Istoricul schimbarilor

Versiune | Descriere
5.6.0 | XMLReader::getAttributeNS() now returns NULL if the attribute doesn't exist.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::getParserProperty — Indicates if specified property has been set

Descrierea

public bool XMLReader::getParserProperty ( int $property )

Indicates if specified property has been set.

Parametri

property

One of the parser option constants.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::isValid — Indicates if the parsed document is valid

Descrierea

public bool XMLReader::isValid ( void )

Returns a boolean indicating if the document being parsed is currently valid.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Validating XML

<?php
$xml = XMLReader::open('test.xml');

// The validate parser option must be enabled for
// this method to work properly
$xml->setParserProperty(XMLReader::VALIDATE, true);

var_dump($xml->isValid());
?>

Note

Nota: This checks the current node, not the entire document.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::lookupNamespace — Lookup namespace for a prefix

Descrierea

public string XMLReader::lookupNamespace ( string $prefix )

Lookup in scope namespace for a given prefix.

Parametri

prefix

String containing the prefix.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

XMLReader::isValid
XMLReader::moveToAttribute
XMLReader


Move cursor to a named attribute

XMLReader::lookupNamespace
XMLReader::moveToAttributeNo
XMLReader
PHP Manual

XMLReader::moveToAttribute

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::moveToAttribute — Move cursor to a named attribute

Descrierea

public bool XMLReader::moveToAttribute ( string $name )

Positions cursor on the named attribute.

Parametri

name

The name of the attribute.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::moveToAttributeNo — Move cursor to an attribute by index

Descrierea

public bool XMLReader::moveToAttributeNo ( int $index )

Positions cursor on attribute based on its position.

Parametri

index

The position of the attribute.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::moveToAttributeNs — Move cursor to a named attribute

Descrierea

public bool XMLReader::moveToAttributeNs ( string $localName , string $namespaceURI )

Positions cursor on the named attribute in specified namespace.

Parametri

localName

The local name.

namespaceURI

The namespace URI.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::moveToElement — Position cursor on the parent Element of current Attribute

Descrierea

public bool XMLReader::moveToElement ( void )

Moves cursor to the parent Element of current Attribute.

Valorile întoarse

Returns TRUE if successful and FALSE if it fails or not positioned on Attribute when this method is called.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::moveToFirstAttribute — Position cursor on the first Attribute

Descrierea

public bool XMLReader::moveToFirstAttribute ( void )

Moves cursor to the first Attribute.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::moveToNextAttribute — Position cursor on the next Attribute

Descrierea

public 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::next — Move cursor to next node skipping all subtrees

Descrierea

public bool XMLReader::next ([ string $localname ] )

Positions cursor on the next node skipping all subtrees.

Parametri

localname

The name of the next node to move to.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::open — Set the URI containing the XML to parse

Descrierea

public bool XMLReader::open ( string $URI [, string $encoding [, int $options = 0 ]] )

Set the URI containing the XML document to be parsed.

Parametri

URI

URI pointing to the document.

encoding

The document encoding or NULL.

options

A bitmask of the LIBXML_* constants.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. If called statically, returns an XMLReader sau FALSE în cazul e?ecului.

Erori/Excep?ii

Aceasta metoda poate fi apelata în mod static, dar va emite o eroare E_STRICT.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | encoding and options were added.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::read — Move to next node in document

Descrierea

public bool XMLReader::read ( void )

Moves cursor to the next node in the document.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

XMLReader::readInnerXML — Retrieve XML from current node

Descrierea

public string XMLReader::readInnerXML ( void )

Reads the contents of the current node, including child nodes and markup.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the contents of the current node as a string. Empty string on failure.

Note

Precautie

Aceasta func?ie este disponibila numai când PHP este compilat cu libxml 20620 sau ulterioara.

A se vedea ?i

  • XMLReader::readString() - Reads the contents of the current node as a string
  • XMLReader::readOuterXML() - Retrieve XML from current node, including itself
  • XMLReader::expand() - Returns a copy of the current node as a DOM object

XMLReader::read
XMLReader::readOuterXML
XMLReader


Retrieve XML from current node, including itself

XMLReader::readInnerXML
XMLReader::readString
XMLReader
PHP Manual

XMLReader::readOuterXML

(PHP 5 >= 5.2.0, PHP 7)

XMLReader::readOuterXML — Retrieve XML from current node, including itself

Descrierea

public string XMLReader::readOuterXML ( void )

Reads the contents of the current node, including the node itself.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the contents of current node, including itself, as a string. Empty string on failure.

Note

Precautie

Aceasta func?ie este disponibila numai când PHP este compilat cu libxml 20620 sau ulterioara.

A se vedea ?i

  • 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, PHP 7)

XMLReader::readString — Reads the contents of the current node as a string

Descrierea

public string XMLReader::readString ( void )

Reads the contents of the current node as a string.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the content of the current node as a string. Empty string on failure.

Note

Precautie

Aceasta func?ie este disponibila numai când PHP este compilat cu libxml 20620 sau ulterioara.

A se vedea ?i

  • XMLReader::readOuterXML() - Retrieve XML from current node, including itself
  • 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.0, PHP 7)

XMLReader::setParserProperty — Set parser options

Descrierea

public 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.

Parametri

property

One of the parser option constants.

value

If set to TRUE the option will be enabled otherwise will be disabled.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

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, PHP 7)

XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema

Descrierea

public bool XMLReader::setRelaxNGSchema ( string $filename )

Set the filename or URI for the RelaxNG Schema to use for validation.

Parametri

filename

filename or URI pointing to a RelaxNG Schema.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema

Descrierea

public bool XMLReader::setRelaxNGSchemaSource ( string $source )

Set the data containing a RelaxNG Schema to use for validation.

Parametri

source

String containing the RelaxNG Schema.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

XMLReader::setSchema — Validate document against XSD

Descrierea

public 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().

Parametri

filename

The filename of the XSD schema.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Erori/Excep?ii

Issues E_WARNING if libxml was built without schema support, the schema contains errors or if XMLReader::read() has already been called.

Note

Precautie

Aceasta func?ie este disponibila numai când PHP este compilat cu libxml 20620 sau ulterioara.

A se vedea ?i

  • 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.0, PHP 7)

XMLReader::XML — Set the data containing the XML to parse

Descrierea

public bool XMLReader::xml ( string $source [, string $encoding [, int $options = 0 ]] )

Set the data containing the XML to parse.

Parametri

source

String containing the XML to be parsed.

encoding

The document encoding or NULL.

options

A bitmask of the LIBXML_* constants.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului. If called statically, returns an XMLReader sau FALSE în cazul e?ecului.

Erori/Excep?ii

Aceasta metoda poate fi apelata în mod static, dar va emite o eroare E_STRICT.

Istoricul schimbarilor

Versiune | Descriere
5.2.0 | encoding and options were added.

A se vedea ?i

  • XMLReader::open() - Set the URI containing the XML to parse
  • XMLReader::close() - Close the XMLReader input

XMLReader::setSchema
XMLWriter
XMLReader


XMLWriter

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Func?ii XMLWriter
    • 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
Introducere
Manipularea XML


Introducere

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
Instalarea / configurarea
XMLWriter


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
XMLWriter


Instalarea

The XMLWriter extension was initially a PECL extension for PHP 5. It was later added to the PHP source (bundled) as of PHP 5.1.2. This extension is enabled by default.

Aceasta extensie este activata în mod implicit. Ea poate fi dezactivata utilizând urmatoarea op?iune la compilare: --disable-xmlwriter

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Tipurile resurselor

There is one resource used by the procedural version of the XMLWriter extension: returned by xmlwriter_open_memory() or xmlwriter_open_uri().

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Aceasta extensie nu are constante definite.

Tipurile resurselor
Func?ii XMLWriter
XMLWriter


Func?ii XMLWriter

Cuprins

  • 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
Constante predefinite
XMLWriter::endAttribute
XMLWriter


End attribute

Func?ii XMLWriter
XMLWriter::endCData
Func?ii XMLWriter
PHP Manual

XMLWriter::endAttribute

xmlwriter_end_attribute

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endAttribute -- xmlwriter_end_attribute — End attribute

Descrierea

Stil obiect-orientat

bool XMLWriter::endAttribute ( void )

Stil procedural

bool xmlwriter_end_attribute ( resource $xmlwriter )

Ends the current attribute.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNS() - Create start namespaced attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNS() - Write full namespaced attribute

Func?ii XMLWriter
XMLWriter::endCData
Func?ii XMLWriter


End current CDATA

XMLWriter::endAttribute
XMLWriter::endComment
Func?ii XMLWriter
PHP Manual

XMLWriter::endCData

xmlwriter_end_cdata

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endCData -- xmlwriter_end_cdata — End current CDATA

Descrierea

Stil obiect-orientat

bool XMLWriter::endCData ( void )

Stil procedural

bool xmlwriter_end_cdata ( resource $xmlwriter )

Ends the current CDATA section.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startCData() - Create start CDATA tag
  • XMLWriter::writeCData() - Write full CDATA tag

XMLWriter::endAttribute
XMLWriter::endComment
Func?ii XMLWriter


Create end comment

XMLWriter::endCData
XMLWriter::endDocument
Func?ii XMLWriter
PHP Manual

XMLWriter::endComment

xmlwriter_end_comment

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 1.0.0)

XMLWriter::endComment -- xmlwriter_end_comment — Create end comment

Descrierea

Stil obiect-orientat

bool XMLWriter::endComment ( void )

Stil procedural

bool xmlwriter_end_comment ( resource $xmlwriter )

Ends the current comment.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::writeComment() - Write full comment tag

XMLWriter::endCData
XMLWriter::endDocument
Func?ii XMLWriter


End current document

XMLWriter::endComment
XMLWriter::endDTDAttlist
Func?ii XMLWriter
PHP Manual

XMLWriter::endDocument

xmlwriter_end_document

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endDocument -- xmlwriter_end_document — End current document

Descrierea

Stil obiect-orientat

bool XMLWriter::endDocument ( void )

Stil procedural

bool xmlwriter_end_document ( resource $xmlwriter )

Ends the current document.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startDocument() - Create document tag

XMLWriter::endComment
XMLWriter::endDTDAttlist
Func?ii XMLWriter


End current DTD AttList

XMLWriter::endDocument
XMLWriter::endDTDElement
Func?ii XMLWriter
PHP Manual

XMLWriter::endDTDAttlist

xmlwriter_end_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endDTDAttlist -- xmlwriter_end_dtd_attlist — End current DTD AttList

Descrierea

Stil obiect-orientat

bool XMLWriter::endDTDAttlist ( void )

Stil procedural

bool xmlwriter_end_dtd_attlist ( resource $xmlwriter )

Ends the current DTD attribute list.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startDTDAttlist() - Create start DTD AttList
  • XMLWriter::writeDTDAttlist() - Write full DTD AttList tag

XMLWriter::endDocument
XMLWriter::endDTDElement
Func?ii XMLWriter


End current DTD element

XMLWriter::endDTDAttlist
XMLWriter::endDTDEntity
Func?ii XMLWriter
PHP Manual

XMLWriter::endDTDElement

xmlwriter_end_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endDTDElement -- xmlwriter_end_dtd_element — End current DTD element

Descrierea

Stil obiect-orientat

bool XMLWriter::endDTDElement ( void )

Stil procedural

bool xmlwriter_end_dtd_element ( resource $xmlwriter )

Ends the current DTD element.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startDTDElement() - Create start DTD element
  • XMLWriter::writeDTDElement() - Write full DTD element tag

XMLWriter::endDTDAttlist
XMLWriter::endDTDEntity
Func?ii XMLWriter


End current DTD Entity

XMLWriter::endDTDElement
XMLWriter::endDTD
Func?ii XMLWriter
PHP Manual

XMLWriter::endDTDEntity

xmlwriter_end_dtd_entity

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endDTDEntity -- xmlwriter_end_dtd_entity — End current DTD Entity

Descrierea

Stil obiect-orientat

bool XMLWriter::endDTDEntity ( void )

Stil procedural

bool xmlwriter_end_dtd_entity ( resource $xmlwriter )

Ends the current DTD entity.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startDTDEntity() - Create start DTD Entity
  • XMLWriter::writeDTDEntity() - Write full DTD Entity tag

XMLWriter::endDTDElement
XMLWriter::endDTD
Func?ii XMLWriter


End current DTD

XMLWriter::endDTDEntity
XMLWriter::endElement
Func?ii XMLWriter
PHP Manual

XMLWriter::endDTD

xmlwriter_end_dtd

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endDTD -- xmlwriter_end_dtd — End current DTD

Descrierea

Stil obiect-orientat

bool XMLWriter::endDTD ( void )

Stil procedural

bool xmlwriter_end_dtd ( resource $xmlwriter )

Ends the DTD of the document.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startDTD() - Create start DTD tag
  • XMLWriter::writeDTD() - Write full DTD tag

XMLWriter::endDTDEntity
XMLWriter::endElement
Func?ii XMLWriter


End current element

XMLWriter::endDTD
XMLWriter::endPI
Func?ii XMLWriter
PHP Manual

XMLWriter::endElement

xmlwriter_end_element

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endElement -- xmlwriter_end_element — End current element

Descrierea

Stil obiect-orientat

bool XMLWriter::endElement ( void )

Stil procedural

bool xmlwriter_end_element ( resource $xmlwriter )

Ends the current element.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::writeElement() - Write full element tag

XMLWriter::endDTD
XMLWriter::endPI
Func?ii XMLWriter


End current PI

XMLWriter::endElement
XMLWriter::flush
Func?ii XMLWriter
PHP Manual

XMLWriter::endPI

xmlwriter_end_pi

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endPI -- xmlwriter_end_pi — End current PI

Descrierea

Stil obiect-orientat

bool XMLWriter::endPI ( void )

Stil procedural

bool xmlwriter_end_pi ( resource $xmlwriter )

Ends the current processing instruction.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startPI() - Create start PI tag
  • XMLWriter::writePI() - Writes a PI

XMLWriter::endElement
XMLWriter::flush
Func?ii XMLWriter


Flush current buffer

XMLWriter::endPI
XMLWriter::fullEndElement
Func?ii XMLWriter
PHP Manual

XMLWriter::flush

xmlwriter_flush

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 1.0.0)

XMLWriter::flush -- xmlwriter_flush — Flush current buffer

Descrierea

Stil obiect-orientat

mixed XMLWriter::flush ([ bool $empty = true ] )

Stil procedural

mixed xmlwriter_flush ( resource $xmlwriter [, bool $empty = true ] )

Flushes the current buffer.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

empty

Whether to empty the buffer or not. Default is TRUE.

Valorile întoarse

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
Func?ii XMLWriter


End current element

XMLWriter::flush
XMLWriter::openMemory
Func?ii XMLWriter
PHP Manual

XMLWriter::fullEndElement

xmlwriter_full_end_element

(PHP 5 >= 5.2.0, PHP 7, PECL xmlwriter >= 2.0.4)

XMLWriter::fullEndElement -- xmlwriter_full_end_element — End current element

Descrierea

Stil obiect-orientat

bool XMLWriter::fullEndElement ( void )

Stil procedural

bool xmlwriter_full_end_element ( resource $xmlwriter )

End the current xml element. Writes an end tag even if the element is empty.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::endElement() - End current element

XMLWriter::flush
XMLWriter::openMemory
Func?ii XMLWriter


Create new xmlwriter using memory for string output

XMLWriter::fullEndElement
XMLWriter::openURI
Func?ii XMLWriter
PHP Manual

XMLWriter::openMemory

xmlwriter_open_memory

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::openMemory -- xmlwriter_open_memory — Create new xmlwriter using memory for string output

Descrierea

Stil obiect-orientat

bool XMLWriter::openMemory ( void )

Stil procedural

resource xmlwriter_open_memory ( void )

Creates a new XMLWriter using memory for string output.

Parametri

Valorile întoarse

Stil obiect-orientat: Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Stil procedural: Returns a new xmlwriter resource for later use with the xmlwriter functions on success, FALSE on error.

A se vedea ?i

  • XMLWriter::openURI() - Create new xmlwriter using source uri for output

XMLWriter::fullEndElement
XMLWriter::openURI
Func?ii XMLWriter


Create new xmlwriter using source uri for output

XMLWriter::openMemory
XMLWriter::outputMemory
Func?ii XMLWriter
PHP Manual

XMLWriter::openURI

xmlwriter_open_uri

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::openURI -- xmlwriter_open_uri — Create new xmlwriter using source uri for output

Descrierea

Stil obiect-orientat

bool XMLWriter::openURI ( string $uri )

Stil procedural

resource xmlwriter_open_uri ( string $uri )

Creates a new XMLWriter using uri for the output.

Parametri

uri

The URI of the resource for the output.

Valorile întoarse

Stil obiect-orientat: Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Stil procedural: Returns a new xmlwriter resource for later use with the xmlwriter functions on success, FALSE on error.

A se vedea ?i

  • XMLWriter::openMemory() - Create new xmlwriter using memory for string output

XMLWriter::openMemory
XMLWriter::outputMemory
Func?ii XMLWriter


Returns current buffer

XMLWriter::openURI
XMLWriter::setIndentString
Func?ii XMLWriter
PHP Manual

XMLWriter::outputMemory

xmlwriter_output_memory

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::outputMemory -- xmlwriter_output_memory — Returns current buffer

Descrierea

Stil obiect-orientat

string XMLWriter::outputMemory ([ bool $flush = true ] )

Stil procedural

string xmlwriter_output_memory ( resource $xmlwriter [, bool $flush = true ] )

Returns the current buffer.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

flush

Whether to flush the output buffer or not. Default is TRUE.

Valorile întoarse

Returns the current buffer as a string.

A se vedea ?i

  • XMLWriter::flush() - Flush current buffer

XMLWriter::openURI
XMLWriter::setIndentString
Func?ii XMLWriter


Set string used for indenting

XMLWriter::outputMemory
XMLWriter::setIndent
Func?ii XMLWriter
PHP Manual

XMLWriter::setIndentString

xmlwriter_set_indent_string

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndentString -- xmlwriter_set_indent_string — Set string used for indenting

Descrierea

Stil obiect-orientat

bool XMLWriter::setIndentString ( string $indentString )

Stil procedural

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.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

indentString

The indentation string.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::setIndent() - Toggle indentation on/off

XMLWriter::outputMemory
XMLWriter::setIndent
Func?ii XMLWriter


Toggle indentation on/off

XMLWriter::setIndentString
XMLWriter::startAttributeNS
Func?ii XMLWriter
PHP Manual

XMLWriter::setIndent

xmlwriter_set_indent

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndent -- xmlwriter_set_indent — Toggle indentation on/off

Descrierea

Stil obiect-orientat

bool XMLWriter::setIndent ( bool $indent )

Stil procedural

bool xmlwriter_set_indent ( resource $xmlwriter , bool $indent )

Toggles indentation on or off.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

indent

Whether indentation is enabled.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::setIndentString() - Set string used for indenting

XMLWriter::setIndentString
XMLWriter::startAttributeNS
Func?ii XMLWriter


Create start namespaced attribute

XMLWriter::setIndent
XMLWriter::startAttribute
Func?ii XMLWriter
PHP Manual

XMLWriter::startAttributeNS

xmlwriter_start_attribute_ns

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttributeNS -- xmlwriter_start_attribute_ns — Create start namespaced attribute

Descrierea

Stil obiect-orientat

bool XMLWriter::startAttributeNS ( string $prefix , string $name , string $uri )

Stil procedural

bool xmlwriter_start_attribute_ns ( resource $xmlwriter , string $prefix , string $name , string $uri )

Starts a namespaced attribute.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

prefix

The namespace prefix.

name

The attribute name.

uri

The namespace URI.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::endAttribute() - End attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNS() - Write full namespaced attribute

XMLWriter::setIndent
XMLWriter::startAttribute
Func?ii XMLWriter


Create start attribute

XMLWriter::startAttributeNS
XMLWriter::startCData
Func?ii XMLWriter
PHP Manual

XMLWriter::startAttribute

xmlwriter_start_attribute

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttribute -- xmlwriter_start_attribute — Create start attribute

Descrierea

Stil obiect-orientat

bool XMLWriter::startAttribute ( string $name )

Stil procedural

bool xmlwriter_start_attribute ( resource $xmlwriter , string $name )

Starts an attribute.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

name

The attribute name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii XMLWriter


Create start CDATA tag

XMLWriter::startAttribute
XMLWriter::startComment
Func?ii XMLWriter
PHP Manual

XMLWriter::startCData

xmlwriter_start_cdata

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startCData -- xmlwriter_start_cdata — Create start CDATA tag

Descrierea

Stil obiect-orientat

bool XMLWriter::startCData ( void )

Stil procedural

bool xmlwriter_start_cdata ( resource $xmlwriter )

Starts a CDATA.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::endCData() - End current CDATA
  • XMLWriter::writeCData() - Write full CDATA tag

XMLWriter::startAttribute
XMLWriter::startComment
Func?ii XMLWriter


Create start comment

XMLWriter::startCData
XMLWriter::startDocument
Func?ii XMLWriter
PHP Manual

XMLWriter::startComment

xmlwriter_start_comment

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 1.0.0)

XMLWriter::startComment -- xmlwriter_start_comment — Create start comment

Descrierea

Stil obiect-orientat

bool XMLWriter::startComment ( void )

Stil procedural

bool xmlwriter_start_comment ( resource $xmlwriter )

Starts a comment.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::endComment() - Create end comment
  • XMLWriter::writeComment() - Write full comment tag

XMLWriter::startCData
XMLWriter::startDocument
Func?ii XMLWriter


Create document tag

XMLWriter::startComment
XMLWriter::startDTDAttlist
Func?ii XMLWriter
PHP Manual

XMLWriter::startDocument

xmlwriter_start_document

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startDocument -- xmlwriter_start_document — Create document tag

Descrierea

Stil obiect-orientat

bool XMLWriter::startDocument ([ string $version = 1.0 [, string $encoding = NULL [, string $standalone ]]] )

Stil procedural

bool xmlwriter_start_document ( resource $xmlwriter [, string $version = 1.0 [, string $encoding = NULL [, string $standalone ]]] )

Starts a document.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

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.

standalone

yes or no.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::endDocument() - End current document

XMLWriter::startComment
XMLWriter::startDTDAttlist
Func?ii XMLWriter


Create start DTD AttList

XMLWriter::startDocument
XMLWriter::startDTDElement
Func?ii XMLWriter
PHP Manual

XMLWriter::startDTDAttlist

xmlwriter_start_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startDTDAttlist -- xmlwriter_start_dtd_attlist — Create start DTD AttList

Descrierea

Stil obiect-orientat

bool XMLWriter::startDTDAttlist ( string $name )

Stil procedural

bool xmlwriter_start_dtd_attlist ( resource $xmlwriter , string $name )

Starts a DTD attribute list.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

name

The attribute list name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::endDTDAttlist() - End current DTD AttList
  • XMLWriter::writeDTDAttlist() - Write full DTD AttList tag

XMLWriter::startDocument
XMLWriter::startDTDElement
Func?ii XMLWriter


Create start DTD element

XMLWriter::startDTDAttlist
XMLWriter::startDTDEntity
Func?ii XMLWriter
PHP Manual

XMLWriter::startDTDElement

xmlwriter_start_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startDTDElement -- xmlwriter_start_dtd_element — Create start DTD element

Descrierea

Stil obiect-orientat

bool XMLWriter::startDTDElement ( string $qualifiedName )

Stil procedural

bool xmlwriter_start_dtd_element ( resource $xmlwriter , string $qualifiedName )

Starts a DTD element.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

qualifiedName

The qualified name of the document type to create.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::endDTDElement() - End current DTD element
  • XMLWriter::writeDTDElement() - Write full DTD element tag

XMLWriter::startDTDAttlist
XMLWriter::startDTDEntity
Func?ii XMLWriter


Create start DTD Entity

XMLWriter::startDTDElement
XMLWriter::startDTD
Func?ii XMLWriter
PHP Manual

XMLWriter::startDTDEntity

xmlwriter_start_dtd_entity

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startDTDEntity -- xmlwriter_start_dtd_entity — Create start DTD Entity

Descrierea

Stil obiect-orientat

bool XMLWriter::startDTDEntity ( string $name , bool $isparam )

Stil procedural

bool xmlwriter_start_dtd_entity ( resource $xmlwriter , string $name , bool $isparam )

Starts a DTD entity.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

name

The name of the entity.

isparam

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::endDTDEntity() - End current DTD Entity
  • XMLWriter::writeDTDEntity() - Write full DTD Entity tag

XMLWriter::startDTDElement
XMLWriter::startDTD
Func?ii XMLWriter


Create start DTD tag

XMLWriter::startDTDEntity
XMLWriter::startElementNS
Func?ii XMLWriter
PHP Manual

XMLWriter::startDTD

xmlwriter_start_dtd

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startDTD -- xmlwriter_start_dtd — Create start DTD tag

Descrierea

Stil obiect-orientat

bool XMLWriter::startDTD ( string $qualifiedName [, string $publicId [, string $systemId ]] )

Stil procedural

bool xmlwriter_start_dtd ( resource $xmlwriter , string $qualifiedName [, string $publicId [, string $systemId ]] )

Starts a DTD.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::endDTD() - End current DTD
  • XMLWriter::writeDTD() - Write full DTD tag

XMLWriter::startDTDEntity
XMLWriter::startElementNS
Func?ii XMLWriter


Create start namespaced element tag

XMLWriter::startDTD
XMLWriter::startElement
Func?ii XMLWriter
PHP Manual

XMLWriter::startElementNS

xmlwriter_start_element_ns

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startElementNS -- xmlwriter_start_element_ns — Create start namespaced element tag

Descrierea

Stil obiect-orientat

bool XMLWriter::startElementNS ( string $prefix , string $name , string $uri )

Stil procedural

bool xmlwriter_start_element_ns ( resource $xmlwriter , string $prefix , string $name , string $uri )

Starts a namespaced element.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

prefix

The namespace prefix.

name

The element name.

uri

The namespace URI.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNS() - Write full namespaced element tag

XMLWriter::startDTD
XMLWriter::startElement
Func?ii XMLWriter


Create start element tag

XMLWriter::startElementNS
XMLWriter::startPI
Func?ii XMLWriter
PHP Manual

XMLWriter::startElement

xmlwriter_start_element

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startElement -- xmlwriter_start_element — Create start element tag

Descrierea

Stil obiect-orientat

bool XMLWriter::startElement ( string $name )

Stil procedural

bool xmlwriter_start_element ( resource $xmlwriter , string $name )

Starts an element.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

name

The element name.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag

XMLWriter::startElementNS
XMLWriter::startPI
Func?ii XMLWriter


Create start PI tag

XMLWriter::startElement
XMLWriter::text
Func?ii XMLWriter
PHP Manual

XMLWriter::startPI

xmlwriter_start_pi

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startPI -- xmlwriter_start_pi — Create start PI tag

Descrierea

Stil obiect-orientat

bool XMLWriter::startPI ( string $target )

Stil procedural

bool xmlwriter_start_pi ( resource $xmlwriter , string $target )

Starts a processing instruction tag.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

target

The target of the processing instruction.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::endPI() - End current PI
  • XMLWriter::writePI() - Writes a PI

XMLWriter::startElement
XMLWriter::text
Func?ii XMLWriter


Write text

XMLWriter::startPI
XMLWriter::writeAttributeNS
Func?ii XMLWriter
PHP Manual

XMLWriter::text

xmlwriter_text

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::text -- xmlwriter_text — Write text

Descrierea

Stil obiect-orientat

bool XMLWriter::text ( string $content )

Stil procedural

bool xmlwriter_text ( resource $xmlwriter , string $content )

Writes a text.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

content

The contents of the text.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

XMLWriter::startPI
XMLWriter::writeAttributeNS
Func?ii XMLWriter


Write full namespaced attribute

XMLWriter::text
XMLWriter::writeAttribute
Func?ii XMLWriter
PHP Manual

XMLWriter::writeAttributeNS

xmlwriter_write_attribute_ns

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttributeNS -- xmlwriter_write_attribute_ns — Write full namespaced attribute

Descrierea

Stil obiect-orientat

bool XMLWriter::writeAttributeNS ( string $prefix , string $name , string $uri , string $content )

Stil procedural

bool xmlwriter_write_attribute_ns ( resource $xmlwriter , string $prefix , string $name , string $uri , string $content )

Writes a full namespaced attribute.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

prefix

The namespace prefix.

name

The attribute name.

uri

The namespace URI.

content

The attribute value.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNS() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute

XMLWriter::text
XMLWriter::writeAttribute
Func?ii XMLWriter


Write full attribute

XMLWriter::writeAttributeNS
XMLWriter::writeCData
Func?ii XMLWriter
PHP Manual

XMLWriter::writeAttribute

xmlwriter_write_attribute

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttribute -- xmlwriter_write_attribute — Write full attribute

Descrierea

Stil obiect-orientat

bool XMLWriter::writeAttribute ( string $name , string $value )

Stil procedural

bool xmlwriter_write_attribute ( resource $xmlwriter , string $name , string $value )

Writes a full attribute.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

name

The name of the attribute.

value

The value of the attribute.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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
Func?ii XMLWriter


Write full CDATA tag

XMLWriter::writeAttribute
XMLWriter::writeComment
Func?ii XMLWriter
PHP Manual

XMLWriter::writeCData

xmlwriter_write_cdata

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeCData -- xmlwriter_write_cdata — Write full CDATA tag

Descrierea

Stil obiect-orientat

bool XMLWriter::writeCData ( string $content )

Stil procedural

bool xmlwriter_write_cdata ( resource $xmlwriter , string $content )

Writes a full CDATA.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

content

The contents of the CDATA.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startCData() - Create start CDATA tag
  • XMLWriter::endCData() - End current CDATA

XMLWriter::writeAttribute
XMLWriter::writeComment
Func?ii XMLWriter


Write full comment tag

XMLWriter::writeCData
XMLWriter::writeDTDAttlist
Func?ii XMLWriter
PHP Manual

XMLWriter::writeComment

xmlwriter_write_comment

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeComment -- xmlwriter_write_comment — Write full comment tag

Descrierea

Stil obiect-orientat

bool XMLWriter::writeComment ( string $content )

Stil procedural

bool xmlwriter_write_comment ( resource $xmlwriter , string $content )

Writes a full comment.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

content

The contents of the comment.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::endComment() - Create end comment

XMLWriter::writeCData
XMLWriter::writeDTDAttlist
Func?ii XMLWriter


Write full DTD AttList tag

XMLWriter::writeComment
XMLWriter::writeDTDElement
Func?ii XMLWriter
PHP Manual

XMLWriter::writeDTDAttlist

xmlwriter_write_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDTDAttlist -- xmlwriter_write_dtd_attlist — Write full DTD AttList tag

Descrierea

Stil obiect-orientat

bool XMLWriter::writeDTDAttlist ( string $name , string $content )

Stil procedural

bool xmlwriter_write_dtd_attlist ( resource $xmlwriter , string $name , string $content )

Writes a DTD attribute list.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

name

The name of the DTD attribute list.

content

The content of the DTD attribute list.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startDTDAttlist() - Create start DTD AttList
  • XMLWriter::endDTDAttlist() - End current DTD AttList

XMLWriter::writeComment
XMLWriter::writeDTDElement
Func?ii XMLWriter


Write full DTD element tag

XMLWriter::writeDTDAttlist
XMLWriter::writeDTDEntity
Func?ii XMLWriter
PHP Manual

XMLWriter::writeDTDElement

xmlwriter_write_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDTDElement -- xmlwriter_write_dtd_element — Write full DTD element tag

Descrierea

Stil obiect-orientat

bool XMLWriter::writeDTDElement ( string $name , string $content )

Stil procedural

bool xmlwriter_write_dtd_element ( resource $xmlwriter , string $name , string $content )

Writes a full DTD element.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

name

The name of the DTD element.

content

The content of the element.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startDTDElement() - Create start DTD element
  • XMLWriter::endDTDElement() - End current DTD element

XMLWriter::writeDTDAttlist
XMLWriter::writeDTDEntity
Func?ii XMLWriter


Write full DTD Entity tag

XMLWriter::writeDTDElement
XMLWriter::writeDTD
Func?ii XMLWriter
PHP Manual

XMLWriter::writeDTDEntity

xmlwriter_write_dtd_entity

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDTDEntity -- xmlwriter_write_dtd_entity — Write full DTD Entity tag

Descrierea

Stil obiect-orientat

bool XMLWriter::writeDTDEntity ( string $name , string $content , bool $pe , string $pubid , string $sysid , string $ndataid )

Stil procedural

bool xmlwriter_write_dtd_entity ( resource $xmlwriter , string $name , string $content , bool $pe , string $pubid , string $sysid , string $ndataid )

Writes a full DTD entity.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

name

The name of the entity.

content

The content of the entity.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startDTDEntity() - Create start DTD Entity
  • XMLWriter::endDTDEntity() - End current DTD Entity

XMLWriter::writeDTDElement
XMLWriter::writeDTD
Func?ii XMLWriter


Write full DTD tag

XMLWriter::writeDTDEntity
XMLWriter::writeElementNS
Func?ii XMLWriter
PHP Manual

XMLWriter::writeDTD

xmlwriter_write_dtd

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDTD -- xmlwriter_write_dtd — Write full DTD tag

Descrierea

Stil obiect-orientat

bool XMLWriter::writeDTD ( string $name [, string $publicId [, string $systemId [, string $subset ]]] )

Stil procedural

bool xmlwriter_write_dtd ( resource $xmlwriter , string $name [, string $publicId [, string $systemId [, string $subset ]]] )

Writes a full DTD.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau 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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startDTD() - Create start DTD tag
  • XMLWriter::endDTD() - End current DTD

XMLWriter::writeDTDEntity
XMLWriter::writeElementNS
Func?ii XMLWriter


Write full namespaced element tag

XMLWriter::writeDTD
XMLWriter::writeElement
Func?ii XMLWriter
PHP Manual

XMLWriter::writeElementNS

xmlwriter_write_element_ns

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElementNS -- xmlwriter_write_element_ns — Write full namespaced element tag

Descrierea

Stil obiect-orientat

bool XMLWriter::writeElementNS ( string $prefix , string $name , string $uri [, string $content ] )

Stil procedural

bool xmlwriter_write_element_ns ( resource $xmlwriter , string $prefix , string $name , string $uri [, string $content ] )

Writes a full namespaced element tag.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

prefix

The namespace prefix.

name

The element name.

uri

The namespace URI.

content

The element contents.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.2.3 | The content parameter became optional.

A se vedea ?i

  • XMLWriter::startElementNS() - Create start namespaced element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag

XMLWriter::writeDTD
XMLWriter::writeElement
Func?ii XMLWriter


Write full element tag

XMLWriter::writeElementNS
XMLWriter::writePI
Func?ii XMLWriter
PHP Manual

XMLWriter::writeElement

xmlwriter_write_element

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElement -- xmlwriter_write_element — Write full element tag

Descrierea

Stil obiect-orientat

bool XMLWriter::writeElement ( string $name [, string $content ] )

Stil procedural

bool xmlwriter_write_element ( resource $xmlwriter , string $name [, string $content ] )

Writes a full element tag.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

name

The element name.

content

The element contents.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
5.2.3 | The content parameter became optional.

A se vedea ?i

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNS() - Write full namespaced element tag

XMLWriter::writeElementNS
XMLWriter::writePI
Func?ii XMLWriter


Writes a PI

XMLWriter::writeElement
XMLWriter::writeRaw
Func?ii XMLWriter
PHP Manual

XMLWriter::writePI

xmlwriter_write_pi

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writePI -- xmlwriter_write_pi — Writes a PI

Descrierea

Stil obiect-orientat

bool XMLWriter::writePI ( string $target , string $content )

Stil procedural

bool xmlwriter_write_pi ( resource $xmlwriter , string $target , string $content )

Writes a processing instruction.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

target

The target of the processing instruction.

content

The content of the processing instruction.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::startPI() - Create start PI tag
  • XMLWriter::endPI() - End current PI

XMLWriter::writeElement
XMLWriter::writeRaw
Func?ii XMLWriter


Write a raw XML text

XMLWriter::writePI
XSL
Func?ii XMLWriter
PHP Manual

XMLWriter::writeRaw

xmlwriter_write_raw

(PHP 5 >= 5.2.0, PHP 7, PECL xmlwriter >= 2.0.4)

XMLWriter::writeRaw -- xmlwriter_write_raw — Write a raw XML text

Descrierea

Stil obiect-orientat

bool XMLWriter::writeRaw ( string $content )

Stil procedural

bool xmlwriter_write_raw ( resource $xmlwriter , string $content )

Writes a raw xml text.

Parametri

xmlwriter

Numai pentru apelurile procedurale. Resursa XMLWriter care este modificata. Aceasta resursa se ob?ine în urma apelarii xmlwriter_open_uri() sau xmlwriter_open_memory ().

content

The text string to write.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • XMLWriter::text() - Write text

XMLWriter::writePI
XSL
Func?ii XMLWriter


XSL

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
    • Configura?ia la rulare
    • Tipurile resurselor
  • Constante predefinite
  • Exemple
    • Example collection.xml and collection.xsl files
    • Error handling with libxml error handling functions
  • XSLTProcessor — The XSLTProcessor class
    • XSLTProcessor::__construct — Creates a new XSLTProcessor object
    • XSLTProcessor::getParameter — Get value of a parameter
    • XsltProcessor::getSecurityPrefs — Get security preferences
    • 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::setSecurityPrefs — Set security preferences
    • XSLTProcessor::transformToDoc — Transform to a DOMDocument
    • XSLTProcessor::transformToUri — Transform to URI
    • XSLTProcessor::transformToXML — Transform to XML
XMLWriter::writeRaw
Introducere
Manipularea XML


Introducere

The XSL extension implements the XSL standard, performing » XSLT transformations using the » libxslt library

XSL
Instalarea / configurarea
XSL


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
  • Configura?ia la rulare
  • Tipurile resurselor
Introducere
Necesita?i
XSL


Necesita?i

Aceasta extensie necesita extensia PHP libxml. Aceasta înseamna ca e necesara de asemenea ?i indicarea op?iunii --enable-libxml , cu toate ca aceasta este realizat în mod implicit deoarece libxml este activata implicit.

This extension uses libxslt which can be found at » http://xmlsoft.org/XSLT/. libxslt version 1.1.0 or greater is required.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

PHP 5 include extensia XSL în mod implicit ?i aceasta poate fi activata adaugând argumentul --with-xsl[=DIR] la linia de configurare (DIR fiind directorul de instalare al libxslt).

Necesita?i
Configura?ia la rulare
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
XSL_SECPREF_NONE (integer)
Deactivate all security restrictions.
XSL_SECPREF_READ_FILE (integer)
Disallows reading files.
XSL_SECPREF_WRITE_FILE (integer)
Disallows writing files.
XSL_SECPREF_CREATE_DIRECTORY (integer)
Disallows creating directories.
XSL_SECPREF_READ_NETWORK (integer)
Disallows reading network files.
XSL_SECPREF_WRITE_NETWORK (integer)
Disallows writing network files.
XSL_SECPREF_DEFAULT (integer)
Disallows all write access, i.e. a bitmask of XSL_SECPREF_WRITE_NETWORK | XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE.
Tipurile resurselor
Exemple
XSL


Exemple

Cuprins

  • Example collection.xml and collection.xsl files
  • Error handling with libxml error handling functions
Constante predefinite
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:

Example #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>

Example #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>

Exemple
Error handling with libxml error handling functions
Exemple


Error handling with libxml error handling functions

libxml offers a number of functions for handling errors, which can be employed to capture and deal with errors in XSLT processing.

Example #1 fruits.xml

A valid XML file.

<fruits>
 <fruit>Apple</fruit>
 <fruit>Banana</fruit>
 <fruit>Cherry</fruit>
</fruits>

Example #2 fruits.xsl

Contains an invalid select expression.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="html" encoding="utf-8" indent="no"/>
 <xsl:template match="fruits">
  <ul>
   <xsl:apply-templates/>
  </ul>
 </xsl:template>
 <xsl:template match="fruit">
  <li><xsl:value-of select="THIS IS A DELIBERATE ERROR!"/></li>
 </xsl:template>
</xsl:stylesheet>

Example #3 Collating and printing errors

The example below captures and displays libxml errors raised when calling XSLTProcessor::importStyleSheet() with a stylesheet containing an error.

<?php

$xmldoc = new DOMDocument();
$xsldoc = new DOMDocument();
$xsl = new XSLTProcessor();

$xmldoc->loadXML('fruits.xml');
$xsldoc->loadXML('fruits.xsl');

libxml_use_internal_errors(true);
$result = $xsl->importStyleSheet($xsldoc);
if (!$result) {
    foreach (libxml_get_errors() as $error) {
        echo "Libxml error: {$error->message}\n";
    }
}
libxml_use_internal_errors(false);

if ($result) {
    echo $xsl->transformToXML($xmldoc);
}

?>

Exemplul de mai sus va afi?a ceva similar cu:

Libxml error: Invalid expression

Libxml error: compilation error: file fruits.xsl line 9 element value-of
Libxml error: xsl:value-of : could not compile select expression 'THIS IS A DELIBERATE ERROR!'

Example collection.xml and collection.xsl files
XSLTProcessor
Exemple


The XSLTProcessor class

(PHP 5, PHP 7)

Introducere

Sinopsisul clasei

XSLTProcessor {
/* Metode */
string getParameter ( string $namespaceURI , string $localName )
public int XsltProcessor::getSecurityPrefs ( void )
bool hasExsltSupport ( void )
public bool 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 )
public int XsltProcessor::setSecurityPrefs ( int $securityPrefs )
DOMDocument transformToDoc ( DOMNode $doc )
int transformToURI ( DOMDocument $doc , string $uri )
string transformToXML ( object $doc )
}

Cuprins

  • XSLTProcessor::__construct — Creates a new XSLTProcessor object
  • XSLTProcessor::getParameter — Get value of a parameter
  • XsltProcessor::getSecurityPrefs — Get security preferences
  • 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::setSecurityPrefs — Set security preferences
  • XSLTProcessor::transformToDoc — Transform to a DOMDocument
  • XSLTProcessor::transformToUri — Transform to URI
  • XSLTProcessor::transformToXML — Transform to XML
Error handling with libxml error handling functions
XSLTProcessor::__construct
XSL


Creates a new XSLTProcessor object

XSLTProcessor
XSLTProcessor::getParameter
XSLTProcessor
PHP Manual

XSLTProcessor::__construct

(PHP 5, PHP 7)

XSLTProcessor::__construct — Creates a new XSLTProcessor object

Descrierea

XSLTProcessor::__construct ( void )

Creates a new XSLTProcessor object.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #1 Creating an XSLTProcessor

<?php

$xsldoc = new DOMDocument();
$xsldoc->load($xsl_filename);

$xmldoc = new DOMDocument();
$xmldoc->load($xml_filename);

$xsl = new XSLTProcessor();
$xsl->importStyleSheet($xsldoc);
echo $xsl->transformToXML($xmldoc);

?>

XSLTProcessor
XSLTProcessor::getParameter
XSLTProcessor


Get value of a parameter

XSLTProcessor::__construct
XsltProcessor::getSecurityPrefs
XSLTProcessor
PHP Manual

XSLTProcessor::getParameter

(PHP 5, PHP 7)

XSLTProcessor::getParameter — Get value of a parameter

Descrierea

string XSLTProcessor::getParameter ( string $namespaceURI , string $localName )

Gets a parameter if previously set by XSLTProcessor::setParameter().

Parametri

namespaceURI

The namespace URI of the XSLT parameter.

localName

The local name of the XSLT parameter.

Valorile întoarse

The value of the parameter (as a string), or FALSE if it's not set.

A se vedea ?i

  • XSLTProcessor::setParameter() - Set value for a parameter
  • XSLTProcessor::removeParameter() - Remove parameter

XSLTProcessor::__construct
XsltProcessor::getSecurityPrefs
XSLTProcessor


Get security preferences

XSLTProcessor::getParameter
XSLTProcessor::hasExsltSupport
XSLTProcessor
PHP Manual

XsltProcessor::getSecurityPrefs

(PHP >= 5.4.0)

XsltProcessor::getSecurityPrefs — Get security preferences

Descrierea

public int XsltProcessor::getSecurityPrefs ( void )

Gets the security preferences.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

A bitmask consisting of XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK, XSL_SECPREF_WRITE_NETWORK.

XSLTProcessor::getParameter
XSLTProcessor::hasExsltSupport
XSLTProcessor


Determine if PHP has EXSLT support

XsltProcessor::getSecurityPrefs
XSLTProcessor::importStylesheet
XSLTProcessor
PHP Manual

XSLTProcessor::hasExsltSupport

(PHP 5 >= 5.0.4, PHP 7)

XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support

Descrierea

bool XSLTProcessor::hasExsltSupport ( void )

This method determines if PHP was built with the » EXSLT library.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #1 Testing EXSLT support

<?php

$proc = new XSLTProcessor;
if (!$proc->hasExsltSupport()) {
    die('EXSLT support not available');
}

// do EXSLT stuff here ..

?>

XsltProcessor::getSecurityPrefs
XSLTProcessor::importStylesheet
XSLTProcessor


Import stylesheet

XSLTProcessor::hasExsltSupport
XSLTProcessor::registerPHPFunctions
XSLTProcessor
PHP Manual

XSLTProcessor::importStylesheet

(PHP 5, PHP 7)

XSLTProcessor::importStylesheet — Import stylesheet

Descrierea

public bool XSLTProcessor::importStylesheet ( object $stylesheet )

This method imports the stylesheet into the XSLTProcessor for transformations.

Parametri

stylesheet

The imported style sheet as a DOMDocument or SimpleXMLElement object.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Istoricul schimbarilor

Versiune | Descriere
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, PHP 7)

XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions

Descrierea

void XSLTProcessor::registerPHPFunctions ([ mixed $restrict ] )

This method enables the ability to use PHP functions as XSLT functions within XSL stylesheets.

Parametri

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.

Valorile întoarse

Nu este întoarsa nici o valoare.

Exemple

Example #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);
?>

Istoricul schimbarilor

Versiune | Descriere
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, PHP 7)

XSLTProcessor::removeParameter — Remove parameter

Descrierea

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.

Parametri

namespaceURI

The namespace URI of the XSLT parameter.

localName

The local name of the XSLT parameter.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

A se vedea ?i

  • 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, PHP 7)

XSLTProcessor::setParameter — Set value for a parameter

Descrierea

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.

Parametri

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.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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');
}

?>

A se vedea ?i

  • XSLTProcessor::getParameter() - Get value of a parameter
  • XSLTProcessor::removeParameter() - Remove parameter

XSLTProcessor::removeParameter
XSLTProcessor::setProfiling
XSLTProcessor


Sets profiling output file

XSLTProcessor::setParameter
XsltProcessor::setSecurityPrefs
XSLTProcessor
PHP Manual

XSLTProcessor::setProfiling

(PHP >= 5.3.0)

XSLTProcessor::setProfiling — Sets profiling output file

Descrierea

bool XSLTProcessor::setProfiling ( string $filename )

Sets the file to output profiling information when processing a stylesheet.

Parametri

filename

Path to the file to dump profiling information.

Valorile întoarse

Întoarce valoarea TRUE în cazul succesului sau FALSE în cazul e?ecului.

Exemple

Example #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::setSecurityPrefs
XSLTProcessor


Set security preferences

XSLTProcessor::setProfiling
XSLTProcessor::transformToDoc
XSLTProcessor
PHP Manual

XsltProcessor::setSecurityPrefs

(PHP >= 5.4.0)

XsltProcessor::setSecurityPrefs — Set security preferences

Descrierea

public int XsltProcessor::setSecurityPrefs ( int $securityPrefs )

Sets the security preferences.

Parametri

securityPrefs

The new security preferences. The following constants can be ORed: XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK, XSL_SECPREF_WRITE_NETWORK. Alternatively, XSL_SECPREF_NONE or XSL_SECPREF_DEFAULT can be passed.

Valorile întoarse

Returns the old security preferences.

XSLTProcessor::setProfiling
XSLTProcessor::transformToDoc
XSLTProcessor


Transform to a DOMDocument

XsltProcessor::setSecurityPrefs
XSLTProcessor::transformToUri
XSLTProcessor
PHP Manual

XSLTProcessor::transformToDoc

(PHP 5, PHP 7)

XSLTProcessor::transformToDoc — Transform to a DOMDocument

Descrierea

DOMDocument XSLTProcessor::transformToDoc ( DOMNode $doc )

Transforms the source node to a DOMDocument applying the stylesheet given by the XSLTProcessor::importStylesheet() method.

Parametri

doc

The node to be transformed.

Valorile întoarse

The resulting DOMDocument or FALSE on error.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

A se vedea ?i

  • XSLTProcessor::transformToUri() - Transform to URI
  • XSLTProcessor::transformToXml() - Transform to XML

XsltProcessor::setSecurityPrefs
XSLTProcessor::transformToUri
XSLTProcessor


Transform to URI

XSLTProcessor::transformToDoc
XSLTProcessor::transformToXML
XSLTProcessor
PHP Manual

XSLTProcessor::transformToUri

(PHP 5, PHP 7)

XSLTProcessor::transformToUri — Transform to URI

Descrierea

int XSLTProcessor::transformToURI ( DOMDocument $doc , string $uri )

Transforms the source node to an URI applying the stylesheet given by the XSLTProcessor::importStylesheet() method.

Parametri

doc

The document to transform.

uri

The target URI for the transformation.

Valorile întoarse

Returns the number of bytes written or FALSE if an error occurred.

Exemple

Example #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');

?>

A se vedea ?i

  • XSLTProcessor::transformToDoc() - Transform to a DOMDocument
  • XSLTProcessor::transformToXml() - Transform to XML

XSLTProcessor::transformToDoc
XSLTProcessor::transformToXML
XSLTProcessor


Transform to XML

XSLTProcessor::transformToUri
Extensii GUI
XSLTProcessor
PHP Manual

XSLTProcessor::transformToXML

(PHP 5, PHP 7)

XSLTProcessor::transformToXML — Transform to XML

Descrierea

string XSLTProcessor::transformToXML ( object $doc )

Transforms the source node to a string applying the stylesheet given by the xsltprocessor::importStylesheet() method.

Parametri

doc

The DOMDocument or SimpleXMLElement object to be transformed.

Valorile întoarse

The result of the transformation as a string or FALSE on error.

Exemple

Example #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);

?>

Exemplul de mai sus va afi?a:

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>

A se vedea ?i

  • XSLTProcessor::transformToDoc() - Transform to a DOMDocument
  • XSLTProcessor::transformToUri() - Transform to URI

XSLTProcessor::transformToUri
Extensii GUI
XSLTProcessor


Extensii GUI

  • UI
    • Introducere
    • Instalarea / configurarea
    • UI\Point — Represents a position (x,y)
    • UI\Size — Represents dimenstions (width, height)
    • UI\Window — Window
    • UI\Control — Control
    • UI\Menu — Menu
    • UI\MenuItem — Menu Item
    • UI\Area — Area
    • UI\Executor — Execution Scheduler
    • UI\Controls\Tab — Tab Control
    • UI\Controls\Check — Check Control
    • UI\Controls\Button — Button Control
    • UI\Controls\ColorButton — ColorButton Control
    • UI\Controls\Label — Label Control
    • UI\Controls\Entry — Entry Control
    • UI\Controls\MultilineEntry — MultilineEntry Control
    • UI\Controls\Spin — Spin Control
    • UI\Controls\Slider — Slider Control
    • UI\Controls\Progress — Progress Control
    • UI\Controls\Separator — Control Separator
    • UI\Controls\Combo — Combo Control
    • UI\Controls\EditableCombo — EdiableCombo Control
    • UI\Controls\Radio — Radio Control
    • UI\Controls\Picker — Picker Control
    • UI\Controls\Form — Control Form (Arrangement)
    • UI\Controls\Grid — Control Grid (Arrangement)
    • UI\Controls\Group — Control Group (Arrangement)
    • UI\Controls\Box — Control Box (Arrangement)
    • UI\Draw\Pen — Draw Pen
    • UI\Draw\Path — Draw Path
    • UI\Draw\Matrix — Draw Matrix
    • UI\Draw\Color — Color Representation
    • UI\Draw\Stroke — Draw Stroke
    • UI\Draw\Brush — Brushes
    • UI\Draw\Brush\Gradient — Gradient Brushes
    • UI\Draw\Brush\LinearGradient — Linear Gradient
    • UI\Draw\Brush\RadialGradient — Radial Gradient
    • UI\Draw\Text\Layout — Represents Text Layout
    • UI\Draw\Text\Font — Represents a Font
    • UI\Draw\Text\Font\Descriptor — Font Descriptor
    • UI Func?ii
    • UI\Draw\Text\Font\Weight — Font Weight Settings
    • UI\Draw\Text\Font\Italic — Italic Font Settings
    • UI\Draw\Text\Font\Stretch — Font Stretch Settings
    • UI\Draw\Line\Cap — Line Cap Settings
    • UI\Draw\Line\Join — Line Join Settings
    • UI\Key — Key Identifiers
    • UI\Exception\InvalidArgumentException — InvalidArgumentException
    • UI\Exception\RuntimeException — RuntimeException
XSLTProcessor::transformToXML
UI
Informa?ii de referin?a despre func?ii


UI

  • Introducere
  • Instalarea / configurarea
    • Necesita?i
    • Instalarea
  • UI\Point — Represents a position (x,y)
    • UI\Point::at — Size Coercion
    • UI\Point::__construct — Construct a new Point
    • UI\Point::getX — Retrieves X
    • UI\Point::getY — Retrieves Y
    • UI\Point::setX — Set X
    • UI\Point::setY — Set Y
  • UI\Size — Represents dimenstions (width, height)
    • UI\Size::__construct — Construct a new Size
    • UI\Size::getHeight — Retrieves Height
    • UI\Size::getWidth — Retrives Width
    • UI\Size::of — Point Coercion
    • UI\Size::setHeight — Set Height
    • UI\Size::setWidth — Set Width
  • UI\Window — Window
    • UI\Window::add — Add a Control
    • UI\Window::__construct — Construct a new Window
    • UI\Window::error — Show Error Box
    • UI\Window::getSize — Get Window Size
    • UI\Window::getTitle — Get Title
    • UI\Window::hasBorders — Border Detection
    • UI\Window::hasMargin — Margin Detection
    • UI\Window::isFullScreen — Full Screen Detection
    • UI\Window::msg — Show Message Box
    • UI\Window::onClosing — Closing Callback
    • UI\Window::open — Open Dialog
    • UI\Window::save — Save Dialog
    • UI\Window::setBorders — Border Use
    • UI\Window::setFullScreen — Full Screen Use
    • UI\Window::setMargin — Margin Use
    • UI\Window::setSize — Set Size
    • UI\Window::setTitle — Window Title
  • UI\Control — Control
    • UI\Control::destroy — Destroy Control
    • UI\Control::disable — Disable Control
    • UI\Control::enable — Enable Control
    • UI\Control::getParent — Get Parent Control
    • UI\Control::getTopLevel — Get Top Level
    • UI\Control::hide — Hide Control
    • UI\Control::isEnabled — Determine if Control is enabled
    • UI\Control::isVisible — Determine if Control is visible
    • UI\Control::setParent — Set Parent Control
    • UI\Control::show — Control Show
  • UI\Menu — Menu
    • UI\Menu::append — Append Menu Item
    • UI\Menu::appendAbout — Append About Menu Item
    • UI\Menu::appendCheck — Append Checkable Menu Item
    • UI\Menu::appendPreferences — Append Preferences Menu Item
    • UI\Menu::appendQuit — Append Quit Menu Item
    • UI\Menu::appendSeparator — Append Menu Item Separator
    • UI\Menu::__construct — Construct a new Menu
  • UI\MenuItem — Menu Item
    • UI\MenuItem::disable — Disable Menu Item
    • UI\MenuItem::enable — Enable Menu Item
    • UI\MenuItem::isChecked — Detect Checked
    • UI\MenuItem::onClick — On Click Callback
    • UI\MenuItem::setChecked — Set Checked
  • UI\Area — Area
    • UI\Area::onDraw — Draw Callback
    • UI\Area::onKey — Key Callback
    • UI\Area::onMouse — Mouse Callback
    • UI\Area::redraw — Redraw Area
    • UI\Area::scrollTo — Area Scroll
    • UI\Area::setSize — Set Size
  • UI\Executor — Execution Scheduler
    • UI\Executor::__construct — Construct a new Executor
    • UI\Executor::kill — Stop Executor
    • UI\Executor::onExecute — Execution Callback
    • UI\Executor::setInterval — Interval Manipulation
  • UI\Controls\Tab — Tab Control
    • UI\Controls\Tab::append — Append Page
    • UI\Controls\Tab::delete — Delete Page
    • UI\Controls\Tab::hasMargin — Margin Detection
    • UI\Controls\Tab::insertAt — Insert Page
    • UI\Controls\Tab::pages — Page Count
    • UI\Controls\Tab::setMargin — Set Margin
  • UI\Controls\Check — Check Control
    • UI\Controls\Check::__construct — Construct a new Check
    • UI\Controls\Check::getText — Get Text
    • UI\Controls\Check::isChecked — Checked Detection
    • UI\Controls\Check::onToggle — Toggle Callback
    • UI\Controls\Check::setChecked — Set Checked
    • UI\Controls\Check::setText — Set Text
  • UI\Controls\Button — Button Control
    • UI\Controls\Button::__construct — Construct a new Button
    • UI\Controls\Button::getText — Get Text
    • UI\Controls\Button::onClick — Click Handler
    • UI\Controls\Button::setText — Set Text
  • UI\Controls\ColorButton — ColorButton Control
    • UI\Controls\ColorButton::getColor — Get Color
    • UI\Controls\ColorButton::onChange — Change Handler
    • UI\Controls\ColorButton::setColor — Set Color
  • UI\Controls\Label — Label Control
    • UI\Controls\Label::__construct — Construct a new Label
    • UI\Controls\Label::getText — Get Text
    • UI\Controls\Label::setText — Set Text
  • UI\Controls\Entry — Entry Control
    • UI\Controls\Entry::__construct — Construct a new Entry
    • UI\Controls\Entry::getText — Get Text
    • UI\Controls\Entry::isReadOnly — Detect Read Only
    • UI\Controls\Entry::onChange — Change Handler
    • UI\Controls\Entry::setReadOnly — Set Read Only
    • UI\Controls\Entry::setText — Set Text
  • UI\Controls\MultilineEntry — MultilineEntry Control
    • UI\Controls\MultilineEntry::append — Append Text
    • UI\Controls\MultilineEntry::__construct — Construct a new Multiline Entry
    • UI\Controls\MultilineEntry::getText — Get Text
    • UI\Controls\MultilineEntry::isReadOnly — Read Only Detection
    • UI\Controls\MultilineEntry::onChange — Change Handler
    • UI\Controls\MultilineEntry::setReadOnly — Set Read Only
    • UI\Controls\MultilineEntry::setText — Set Text
  • UI\Controls\Spin — Spin Control
    • UI\Controls\Spin::__construct — Construct a new Spin
    • UI\Controls\Spin::getValue — Get Value
    • UI\Controls\Spin::onChange — Change Handler
    • UI\Controls\Spin::setValue — Set Value
  • UI\Controls\Slider — Slider Control
    • UI\Controls\Slider::__construct — Construct a new Slider
    • UI\Controls\Slider::getValue — Get Value
    • UI\Controls\Slider::onChange — Change Handler
    • UI\Controls\Slider::setValue — Set Value
  • UI\Controls\Progress — Progress Control
    • UI\Controls\Progress::getValue — Get Value
    • UI\Controls\Progress::setValue — Set Value
  • UI\Controls\Separator — Control Separator
    • UI\Controls\Separator::__construct — Construct a new Separator
  • UI\Controls\Combo — Combo Control
    • UI\Controls\Combo::append — Append Option
    • UI\Controls\Combo::getSelected — Get Selected Option
    • UI\Controls\Combo::onSelected — Selected Handler
    • UI\Controls\Combo::setSelected — Set Selected Option
  • UI\Controls\EditableCombo — EdiableCombo Control
    • UI\Controls\EditableCombo::append — Append Option
    • UI\Controls\EditableCombo::getText — Get Text
    • UI\Controls\EditableCombo::onChange — Change Handler
    • UI\Controls\EditableCombo::setText — Set Text
  • UI\Controls\Radio — Radio Control
    • UI\Controls\Radio::append — Append Option
    • UI\Controls\Radio::getSelected — Get Selected Option
    • UI\Controls\Radio::onSelected — Selected Handler
    • UI\Controls\Radio::setSelected — Set Selected Option
  • UI\Controls\Picker — Picker Control
    • UI\Controls\Picker::__construct — Construct a new Picker
  • UI\Controls\Form — Control Form (Arrangement)
    • UI\Controls\Form::append — Append Control
    • UI\Controls\Form::delete — Delete Control
    • UI\Controls\Form::isPadded — Padding Detection
    • UI\Controls\Form::setPadded — Set Padding
  • UI\Controls\Grid — Control Grid (Arrangement)
    • UI\Controls\Grid::append — Append Control
    • UI\Controls\Grid::isPadded — Padding Detection
    • UI\Controls\Grid::setPadded — Set Padding
  • UI\Controls\Group — Control Group (Arrangement)
    • UI\Controls\Group::append — Append Control
    • UI\Controls\Group::__construct — Construct a new Group
    • UI\Controls\Group::getTitle — Get Title
    • UI\Controls\Group::hasMargin — Margin Detection
    • UI\Controls\Group::setMargin — Set Margin
    • UI\Controls\Group::setTitle — Set Title
  • UI\Controls\Box — Control Box (Arrangement)
    • UI\Controls\Box::append — Append Control
    • UI\Controls\Box::__construct — Construct a new Box
    • UI\Controls\Box::delete — Delete Control
    • UI\Controls\Box::getOrientation — Get Orientation
    • UI\Controls\Box::isPadded — Padding Detection
    • UI\Controls\Box::setPadded — Set Padding
  • UI\Draw\Pen — Draw Pen
    • UI\Draw\Pen::clip — Clip a Path
    • UI\Draw\Pen::fill — Fill a Path
    • UI\Draw\Pen::restore — Restore
    • UI\Draw\Pen::save — Save
    • UI\Draw\Pen::stroke — Stroke a Path
    • UI\Draw\Pen::transform — Matrix Transform
    • UI\Draw\Pen::write — Draw Text at Point
  • UI\Draw\Path — Draw Path
    • UI\Draw\Path::addRectangle — Draw a Rectangle
    • UI\Draw\Path::arcTo — Draw an Arc
    • UI\Draw\Path::bezierTo — Draw Bezier Curve
    • UI\Draw\Path::closeFigure — Close Figure
    • UI\Draw\Path::__construct — Construct a new Path
    • UI\Draw\Path::end — Finalize Path
    • UI\Draw\Path::lineTo — Draw a Line
    • UI\Draw\Path::newFigure — Draw Figure
    • UI\Draw\Path::newFigureWithArc — Draw Figure with Arc
  • UI\Draw\Matrix — Draw Matrix
    • UI\Draw\Matrix::invert — Invert Matrix
    • UI\Draw\Matrix::isInvertible — Invertible Detection
    • UI\Draw\Matrix::multiply — Multiply Matrix
    • UI\Draw\Matrix::rotate — Rotate Matrix
    • UI\Draw\Matrix::scale — Scale Matrix
    • UI\Draw\Matrix::skew — Skew Matrix
    • UI\Draw\Matrix::translate — Translate Matrix
  • UI\Draw\Color — Color Representation
    • UI\Draw\Color::__construct — Construct new Color
    • UI\Draw\Color::getChannel — Color Manipulation
    • UI\Draw\Color::setChannel — Color Manipulation
  • UI\Draw\Stroke — Draw Stroke
    • UI\Draw\Stroke::__construct — Construct a new Stroke
    • UI\Draw\Stroke::getCap — Get Line Cap
    • UI\Draw\Stroke::getJoin — Get Line Join
    • UI\Draw\Stroke::getMiterLimit — Get Miter Limit
    • UI\Draw\Stroke::getThickness — Get Thickness
    • UI\Draw\Stroke::setCap — Set Line Cap
    • UI\Draw\Stroke::setJoin — Set Line Join
    • UI\Draw\Stroke::setMiterLimit — Set Miter Limit
    • UI\Draw\Stroke::setThickness — Set Thickness
  • UI\Draw\Brush — Brushes
    • UI\Draw\Brush::__construct — Construct a new Brush
    • UI\Draw\Brush::getColor — Get Color
    • UI\Draw\Brush::setColor — Set Color
  • UI\Draw\Brush\Gradient — Gradient Brushes
    • UI\Draw\Brush\Gradient::addStop — Stop Manipulation
    • UI\Draw\Brush\Gradient::delStop — Stop Manipulation
    • UI\Draw\Brush\Gradient::setStop — Stop Manipulation
  • UI\Draw\Brush\LinearGradient — Linear Gradient
    • UI\Draw\Brush\LinearGradient::__construct — Construct a Linear Gradient
  • UI\Draw\Brush\RadialGradient — Radial Gradient
    • UI\Draw\Brush\RadialGradient::__construct — Construct a new Radial Gradient
  • UI\Draw\Text\Layout — Represents Text Layout
    • UI\Draw\Text\Layout::__construct — Construct a new Text Layout
    • UI\Draw\Text\Layout::setColor — Set Color
    • UI\Draw\Text\Layout::setWidth — Set Width
  • UI\Draw\Text\Font — Represents a Font
    • UI\Draw\Text\Font::__construct — Construct a new Font
    • UI\Draw\Text\Font::getAscent — Font Metrics
    • UI\Draw\Text\Font::getDescent — Font Metrics
    • UI\Draw\Text\Font::getLeading — Font Metrics
    • UI\Draw\Text\Font::getUnderlinePosition — Font Metrics
    • UI\Draw\Text\Font::getUnderlineThickness — Font Metrics
  • UI\Draw\Text\Font\Descriptor — Font Descriptor
    • UI\Draw\Text\Font\Descriptor::__construct — Construct a new Font Descriptor
    • UI\Draw\Text\Font\Descriptor::getFamily — Get Font Family
    • UI\Draw\Text\Font\Descriptor::getItalic — Style Detection
    • UI\Draw\Text\Font\Descriptor::getSize — Size Detection
    • UI\Draw\Text\Font\Descriptor::getStretch — Style Detection
    • UI\Draw\Text\Font\Descriptor::getWeight — Weight Detection
  • UI Func?ii
    • UI\Draw\Text\Font\fontFamilies — Retrieve Font Families
    • UI\quit — Quit UI Loop
    • UI\run — Enter UI Loop
  • UI\Draw\Text\Font\Weight — Font Weight Settings
  • UI\Draw\Text\Font\Italic — Italic Font Settings
  • UI\Draw\Text\Font\Stretch — Font Stretch Settings
  • UI\Draw\Line\Cap — Line Cap Settings
  • UI\Draw\Line\Join — Line Join Settings
  • UI\Key — Key Identifiers
  • UI\Exception\InvalidArgumentException — InvalidArgumentException
  • UI\Exception\RuntimeException — RuntimeException
Extensii GUI
Introducere
Extensii GUI


Introducere

This extension wraps libui to provide an OO API for the cross platform development of native look-and-feel user interfaces .

UI
Instalarea / configurarea
UI


Instalarea / configurarea

Cuprins

  • Necesita?i
  • Instalarea
Introducere
Necesita?i
UI


Necesita?i

Installation requires the libui library, and PHP 7 or newer.

This extension requires the » libui library version 0.1.0 or higher to be installed. See the libui documentation for a list of prerequisites.

Instalarea / configurarea
Instalarea
Instalarea / configurarea


Instalarea

Aceasta extensie » PECL nu este încorporata în PHP.

Informa?ie despre instalarea acestei extensii PECL poate fi gasita în capitolul manualului, întitulat Instalarea extensiilor PECL. Informa?ii adi?ionale, cum ar fi lansari noi, descarcari, fi?iere-sursa, informa?ii despre persoana care între?ine extensia ?i istoria schimbarilor poate fi localizata aici: » http://pecl.php.net/package/ui.

Windows binaries (DLL files) for this PECL extension are available from the PECL website.

Necesita?i
UI\Point
Instalarea / configurarea


Represents a position (x,y)

(PHP 7, UI 0.9.9)

Introducere

Points are used throughout UI to represent co-ordinates on a screen, control, or area.

Sinopsisul clasei

final UI\Point {
/* Proprieta?i */
public $x ;
public $y ;
/* Constructor */
public __construct ( float $x , float $y )
/* Metode */
public static UI\Point at ( float $point )
public static UI\Point at ( UI\Size $size )
public float getX ( void )
public float getY ( void )
public setX ( float $point )
public setY ( float $point )
}

Proprieta?i

x

Holds the X co-ordinate, can be read/written directly

y

Holds the Y co-ordinate, can be read/written directly

Cuprins

  • UI\Point::at — Size Coercion
  • UI\Point::__construct — Construct a new Point
  • UI\Point::getX — Retrieves X
  • UI\Point::getY — Retrieves Y
  • UI\Point::setX — Set X
  • UI\Point::setY — Set Y
Instalarea
UI\Point::at
UI


Size Coercion

UI\Point
UI\Point::__construct
UI\Point
PHP Manual

UI\Point::at

(PHP 7, UI 1.0.2)

UI\Point::at — Size Coercion

Descrierea

public static UI\Point UI\Point::at ( float $point )
public static UI\Point UI\Point::at ( UI\Size $size )

Shall return a UI\Point object where x and y are equal to those supplied, either in float or UI\Size form

Parametri

point

The value for x and y

size

The Size to convert

Valorile întoarse

The resulting Point

UI\Point
UI\Point::__construct
UI\Point


Construct a new Point

UI\Point::at
UI\Point::getX
UI\Point
PHP Manual

UI\Point::__construct

(PHP 7, UI 0.9.9)

UI\Point::__construct — Construct a new Point

Descrierea

public UI\Point::__construct ( float $x , float $y )

Construct a new Point using new co-ordinates

Parametri

x

The new X co-ordinate

y

The new Y co-ordinate

UI\Point::at
UI\Point::getX
UI\Point


Retrieves X

UI\Point::__construct
UI\Point::getY
UI\Point
PHP Manual

UI\Point::getX

(PHP 7, UI 0.9.9)

UI\Point::getX — Retrieves X

Descrierea

public float UI\Point::getX ( void )

Retrieves the X co-ordinate

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current X co-ordinate

UI\Point::__construct
UI\Point::getY
UI\Point


Retrieves Y

UI\Point::getX
UI\Point::setX
UI\Point
PHP Manual

UI\Point::getY

(PHP 7, UI 0.9.9)

UI\Point::getY — Retrieves Y

Descrierea

public float UI\Point::getY ( void )

Retrieves the Y co-ordinate

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current Y co-ordinate

UI\Point::getX
UI\Point::setX
UI\Point


Set X

UI\Point::getY
UI\Point::setY
UI\Point
PHP Manual

UI\Point::setX

(PHP 7, UI 0.9.9)

UI\Point::setX — Set X

Descrierea

public UI\Point::setX ( float $point )

Set the X co-ordinate

Parametri

point

The new X co-ordinate

Valorile întoarse

UI\Point::getY
UI\Point::setY
UI\Point


Set Y

UI\Point::setX
UI\Size
UI\Point
PHP Manual

UI\Point::setY

(PHP 7, UI 0.9.9)

UI\Point::setY — Set Y

Descrierea

public UI\Point::setY ( float $point )

Set the Y co-ordinate

Parametri

point

The new Y co-ordinate

Valorile întoarse

UI\Point::setX
UI\Size
UI\Point


Represents dimenstions (width, height)

(PHP 7, UI 0.9.9)

Introducere

Sizes are used throughout UI to represent the size of a screen, control, or area.

Sinopsisul clasei

final UI\Size {
/* Proprieta?i */
public $width ;
public $height ;
/* Constructor */
public __construct ( float $width , float $height )
/* Metode */
public float getHeight ( void )
public float getWidth ( void )
public static UI\Size of ( float $size )
public static UI\Size of ( UI\Point $point )
public setHeight ( float $size )
public setWidth ( float $size )
}

Proprieta?i

width

Holds the width, can be read/written directly

height

Holds the height, can be read/written directly

Cuprins

  • UI\Size::__construct — Construct a new Size
  • UI\Size::getHeight — Retrieves Height
  • UI\Size::getWidth — Retrives Width
  • UI\Size::of — Point Coercion
  • UI\Size::setHeight — Set Height
  • UI\Size::setWidth — Set Width
UI\Point::setY
UI\Size::__construct
UI


Construct a new Size

UI\Size
UI\Size::getHeight
UI\Size
PHP Manual

UI\Size::__construct

(PHP 7, UI 0.9.9)

UI\Size::__construct — Construct a new Size

Descrierea

public UI\Size::__construct ( float $width , float $height )

Construct a new Size using new width and height

Parametri

width

The new width

height

The new height

UI\Size
UI\Size::getHeight
UI\Size


Retrieves Height

UI\Size::__construct
UI\Size::getWidth
UI\Size
PHP Manual

UI\Size::getHeight

(PHP 7, UI 0.9.9)

UI\Size::getHeight — Retrieves Height

Descrierea

public float UI\Size::getHeight ( void )

Retrieves the Height

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current Height

UI\Size::__construct
UI\Size::getWidth
UI\Size


Retrives Width

UI\Size::getHeight
UI\Size::of
UI\Size
PHP Manual

UI\Size::getWidth

(PHP 7, UI 0.9.9)

UI\Size::getWidth — Retrives Width

Descrierea

public float UI\Size::getWidth ( void )

Retrieves the Width

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current Width

UI\Size::getHeight
UI\Size::of
UI\Size


Point Coercion

UI\Size::getWidth
UI\Size::setHeight
UI\Size
PHP Manual

UI\Size::of

(PHP 7, UI 1.0.2)

UI\Size::of — Point Coercion

Descrierea

public static UI\Size UI\Size::of ( float $size )
public static UI\Size UI\Size::of ( UI\Point $point )

Shall return a UI\Size object where width and height are equal to those supplied, either in float or UI\Point form

Parametri

size

The value for width and height

point

The Point to convert

Valorile întoarse

The resulting Size

UI\Size::getWidth
UI\Size::setHeight
UI\Size


Set Height

UI\Size::of
UI\Size::setWidth
UI\Size
PHP Manual

UI\Size::setHeight

(PHP 7, UI 0.9.9)

UI\Size::setHeight — Set Height

Descrierea

public UI\Size::setHeight ( float $size )

Set new Height

Parametri

size

The new Height

Valorile întoarse

UI\Size::of
UI\Size::setWidth
UI\Size


Set Width

UI\Size::setHeight
UI\Window
UI\Size
PHP Manual

UI\Size::setWidth

(PHP 7, UI 0.9.9)

UI\Size::setWidth — Set Width

Descrierea

public UI\Size::setWidth ( float $size )

Set new Width

Parametri

size

The new Width

Valorile întoarse

UI\Size::setHeight
UI\Window
UI\Size


Window

(PHP 7, UI 0.9.9)

Introducere

Represents a UI Window

Sinopsisul clasei

UI\Window extends UI\Control {
/* Proprieta?i */
protected $controls ;
/* Constructor */
public __construct ( string $title , Size $size [, boolean $menu = false ] )
/* Metode */
public add ( UI\Control $control )
public error ( string $title , string $msg )
public UI\Size getSize ( void )
public string getTitle ( void )
public bool hasBorders ( void )
public bool hasMargin ( void )
public bool isFullScreen ( void )
public msg ( string $title , string $msg )
protected int onClosing ( void )
public string open ( void )
public string save ( void )
public setBorders ( boolean $borders )
public setFullScreen ( boolean $full )
public setMargin ( boolean $margin )
public setSize ( UI\Size $size )
public setTitle ( string $title )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Proprieta?i

controls

Contains controls, should not be manipulated directly

Cuprins

  • UI\Window::add — Add a Control
  • UI\Window::__construct — Construct a new Window
  • UI\Window::error — Show Error Box
  • UI\Window::getSize — Get Window Size
  • UI\Window::getTitle — Get Title
  • UI\Window::hasBorders — Border Detection
  • UI\Window::hasMargin — Margin Detection
  • UI\Window::isFullScreen — Full Screen Detection
  • UI\Window::msg — Show Message Box
  • UI\Window::onClosing — Closing Callback
  • UI\Window::open — Open Dialog
  • UI\Window::save — Save Dialog
  • UI\Window::setBorders — Border Use
  • UI\Window::setFullScreen — Full Screen Use
  • UI\Window::setMargin — Margin Use
  • UI\Window::setSize — Set Size
  • UI\Window::setTitle — Window Title
UI\Size::setWidth
UI\Window::add
UI


Add a Control

UI\Window
UI\Window::__construct
UI\Window
PHP Manual

UI\Window::add

(PHP 7, UI 0.9.9)

UI\Window::add — Add a Control

Descrierea

public UI\Window::add ( UI\Control $control )

Shall add a Control to this Window

Parametri

control

The Control to add

Valorile întoarse

UI\Window
UI\Window::__construct
UI\Window


Construct a new Window

UI\Window::add
UI\Window::error
UI\Window
PHP Manual

UI\Window::__construct

(PHP 7, UI 0.9.9)

UI\Window::__construct — Construct a new Window

Descrierea

public UI\Window::__construct ( string $title , Size $size [, boolean $menu = false ] )

Shall construct a new Window

Parametri

title

The title of the Window

size

The size of the Window

menu

Menu switch

UI\Window::add
UI\Window::error
UI\Window


Show Error Box

UI\Window::__construct
UI\Window::getSize
UI\Window
PHP Manual

UI\Window::error

(PHP 7, UI 0.9.9)

UI\Window::error — Show Error Box

Descrierea

public UI\Window::error ( string $title , string $msg )

Shall show an error box

Parametri

title

The title of the error box

msg

The message for the error box

UI\Window::__construct
UI\Window::getSize
UI\Window


Get Window Size

UI\Window::error
UI\Window::getTitle
UI\Window
PHP Manual

UI\Window::getSize

(PHP 7, UI 0.9.9)

UI\Window::getSize — Get Window Size

Descrierea

public UI\Size UI\Window::getSize ( void )

Shall return the size of this Window

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Window::error
UI\Window::getTitle
UI\Window


Get Title

UI\Window::getSize
UI\Window::hasBorders
UI\Window
PHP Manual

UI\Window::getTitle

(PHP 7, UI 0.9.9)

UI\Window::getTitle — Get Title

Descrierea

public string UI\Window::getTitle ( void )

Shall retrieve the title of this Window

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Window::getSize
UI\Window::hasBorders
UI\Window


Border Detection

UI\Window::getTitle
UI\Window::hasMargin
UI\Window
PHP Manual

UI\Window::hasBorders

(PHP 7, UI 0.9.9)

UI\Window::hasBorders — Border Detection

Descrierea

public bool UI\Window::hasBorders ( void )

Shall detect if borders are used on this Window

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Window::getTitle
UI\Window::hasMargin
UI\Window


Margin Detection

UI\Window::hasBorders
UI\Window::isFullScreen
UI\Window
PHP Manual

UI\Window::hasMargin

(PHP 7, UI 0.9.9)

UI\Window::hasMargin — Margin Detection

Descrierea

public bool UI\Window::hasMargin ( void )

Shall detect if margins are used on this Window

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Window::hasBorders
UI\Window::isFullScreen
UI\Window


Full Screen Detection

UI\Window::hasMargin
UI\Window::msg
UI\Window
PHP Manual

UI\Window::isFullScreen

(PHP 7, UI 0.9.9)

UI\Window::isFullScreen — Full Screen Detection

Descrierea

public bool UI\Window::isFullScreen ( void )

Shall detect if this Window us using the whole screen

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Window::hasMargin
UI\Window::msg
UI\Window


Show Message Box

UI\Window::isFullScreen
UI\Window::onClosing
UI\Window
PHP Manual

UI\Window::msg

(PHP 7, UI 0.9.9)

UI\Window::msg — Show Message Box

Descrierea

public UI\Window::msg ( string $title , string $msg )

Shall show a message box

Parametri

title

The title of the message box

msg

The message

UI\Window::isFullScreen
UI\Window::onClosing
UI\Window


Closing Callback

UI\Window::msg
UI\Window::open
UI\Window
PHP Manual

UI\Window::onClosing

(PHP 7, UI 0.9.9)

UI\Window::onClosing — Closing Callback

Descrierea

protected int UI\Window::onClosing ( void )

Should gracefully destroy this Window

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Window::msg
UI\Window::open
UI\Window


Open Dialog

UI\Window::onClosing
UI\Window::save
UI\Window
PHP Manual

UI\Window::open

(PHP 7, UI 0.9.9)

UI\Window::open — Open Dialog

Descrierea

public string UI\Window::open ( void )

Shall show an open file dialog

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the name of the file selected for opening

UI\Window::onClosing
UI\Window::save
UI\Window


Save Dialog

UI\Window::open
UI\Window::setBorders
UI\Window
PHP Manual

UI\Window::save

(PHP 7, UI 0.9.9)

UI\Window::save — Save Dialog

Descrierea

public string UI\Window::save ( void )

Shall show a save dialog

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

Returns the file name selecting for saving

UI\Window::open
UI\Window::setBorders
UI\Window


Border Use

UI\Window::save
UI\Window::setFullScreen
UI\Window
PHP Manual

UI\Window::setBorders

(PHP 7, UI 0.9.9)

UI\Window::setBorders — Border Use

Descrierea

public UI\Window::setBorders ( boolean $borders )

Shall enable or disable the use of borders on this Window

Parametri

borders

UI\Window::save
UI\Window::setFullScreen
UI\Window


Full Screen Use

UI\Window::setBorders
UI\Window::setMargin
UI\Window
PHP Manual

UI\Window::setFullScreen

(PHP 7, UI 0.9.9)

UI\Window::setFullScreen — Full Screen Use

Descrierea

public UI\Window::setFullScreen ( boolean $full )

Shall enable or disable the use of the full screen for this Window

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

full

UI\Window::setBorders
UI\Window::setMargin
UI\Window


Margin Use

UI\Window::setFullScreen
UI\Window::setSize
UI\Window
PHP Manual

UI\Window::setMargin

(PHP 7, UI 0.9.9)

UI\Window::setMargin — Margin Use

Descrierea

public UI\Window::setMargin ( boolean $margin )

Shall enable or disable the use of margins for this Window

Parametri

margin

UI\Window::setFullScreen
UI\Window::setSize
UI\Window


Set Size

UI\Window::setMargin
UI\Window::setTitle
UI\Window
PHP Manual

UI\Window::setSize

(PHP 7, UI 0.9.9)

UI\Window::setSize — Set Size

Descrierea

public UI\Window::setSize ( UI\Size $size )

Shall set the size of this Window

Parametri

size

Valorile întoarse

UI\Window::setMargin
UI\Window::setTitle
UI\Window


Window Title

UI\Window::setSize
UI\Control
UI\Window
PHP Manual

UI\Window::setTitle

(PHP 7, UI 0.9.9)

UI\Window::setTitle — Window Title

Descrierea

public UI\Window::setTitle ( string $title )

Shall set the title for this Window

Parametri

title

The new title

UI\Window::setSize
UI\Control
UI\Window


Control

(PHP 7, UI 0.9.9)

Introducere

This is the closed base class for all UI Controls.

Sinopsisul clasei

final UI\Control {
/* Metode */
public destroy ( void )
public disable ( void )
public enable ( void )
public UI\Control getParent ( void )
public int getTopLevel ( void )
public hide ( void )
public bool isEnabled ( void )
public bool isVisible ( void )
public setParent ( UI\Control $parent )
public show ( void )
}

Cuprins

  • UI\Control::destroy — Destroy Control
  • UI\Control::disable — Disable Control
  • UI\Control::enable — Enable Control
  • UI\Control::getParent — Get Parent Control
  • UI\Control::getTopLevel — Get Top Level
  • UI\Control::hide — Hide Control
  • UI\Control::isEnabled — Determine if Control is enabled
  • UI\Control::isVisible — Determine if Control is visible
  • UI\Control::setParent — Set Parent Control
  • UI\Control::show — Control Show
UI\Window::setTitle
UI\Control::destroy
UI


Destroy Control

UI\Control
UI\Control::disable
UI\Control
PHP Manual

UI\Control::destroy

(PHP 7, UI 0.9.9)

UI\Control::destroy — Destroy Control

Descrierea

public UI\Control::destroy ( void )

Shall destroy this Control

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Control
UI\Control::disable
UI\Control


Disable Control

UI\Control::destroy
UI\Control::enable
UI\Control
PHP Manual

UI\Control::disable

(PHP 7, UI 0.9.9)

UI\Control::disable — Disable Control

Descrierea

public UI\Control::disable ( void )

Shall disable this Control

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Control::destroy
UI\Control::enable
UI\Control


Enable Control

UI\Control::disable
UI\Control::getParent
UI\Control
PHP Manual

UI\Control::enable

(PHP 7, UI 0.9.9)

UI\Control::enable — Enable Control

Descrierea

public UI\Control::enable ( void )

Shall enable this Control

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Control::disable
UI\Control::getParent
UI\Control


Get Parent Control

UI\Control::enable
UI\Control::getTopLevel
UI\Control
PHP Manual

UI\Control::getParent

(PHP 7, UI 0.9.9)

UI\Control::getParent — Get Parent Control

Descrierea

public UI\Control UI\Control::getParent ( void )

Shall return the parent Control

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Control::enable
UI\Control::getTopLevel
UI\Control


Get Top Level

UI\Control::getParent
UI\Control::hide
UI\Control
PHP Manual

UI\Control::getTopLevel

(PHP 7, UI 0.9.9)

UI\Control::getTopLevel — Get Top Level

Descrierea

public int UI\Control::getTopLevel ( void )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Control::getParent
UI\Control::hide
UI\Control


Hide Control

UI\Control::getTopLevel
UI\Control::isEnabled
UI\Control
PHP Manual

UI\Control::hide

(PHP 7, UI 0.9.9)

UI\Control::hide — Hide Control

Descrierea

public UI\Control::hide ( void )

Shall hide this Control

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Control::getTopLevel
UI\Control::isEnabled
UI\Control


Determine if Control is enabled

UI\Control::hide
UI\Control::isVisible
UI\Control
PHP Manual

UI\Control::isEnabled

(PHP 7, UI 0.9.9)

UI\Control::isEnabled — Determine if Control is enabled

Descrierea

public bool UI\Control::isEnabled ( void )

Shall detect if this Control is enabled

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Control::hide
UI\Control::isVisible
UI\Control


Determine if Control is visible

UI\Control::isEnabled
UI\Control::setParent
UI\Control
PHP Manual

UI\Control::isVisible

(PHP 7, UI 0.9.9)

UI\Control::isVisible — Determine if Control is visible

Descrierea

public bool UI\Control::isVisible ( void )

Shall detect if this Control is visible

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Control::isEnabled
UI\Control::setParent
UI\Control


Set Parent Control

UI\Control::isVisible
UI\Control::show
UI\Control
PHP Manual

UI\Control::setParent

(PHP 7, UI 0.9.9)

UI\Control::setParent — Set Parent Control

Descrierea

public UI\Control::setParent ( UI\Control $parent )

Shall set the parent Control of this Control

Parametri

parent

The parent Control

Valorile întoarse

UI\Control::isVisible
UI\Control::show
UI\Control


Control Show

UI\Control::setParent
UI\Menu
UI\Control
PHP Manual

UI\Control::show

(PHP 7, UI 0.9.9)

UI\Control::show — Control Show

Descrierea

public UI\Control::show ( void )

Shall show this Control

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Control::setParent
UI\Menu
UI\Control


Menu

(PHP 7, UI 0.9.9)

Introducere

Menus must be constructed before the first Window, and can be shown on any Window

Sinopsisul clasei

UI\Menu {
/* Constructor */
public __construct ( string $name )
/* Metode */
public UI\MenuItem append ( string $name [, string $type = UI\MenuItem::class ] )
public UI\MenuItem appendAbout ([ string $type = UI\MenuItem::class ] )
public UI\MenuItem appendCheck ( string $name [, string $type = UI\MenuItem::class ] )
public UI\MenuItem appendPreferences ([ string $type = UI\MenuItem::class ] )
public UI\MenuItem appendQuit ([ string $type = UI\MenuItem::class ] )
public appendSeparator ( void )
}

Cuprins

  • UI\Menu::append — Append Menu Item
  • UI\Menu::appendAbout — Append About Menu Item
  • UI\Menu::appendCheck — Append Checkable Menu Item
  • UI\Menu::appendPreferences — Append Preferences Menu Item
  • UI\Menu::appendQuit — Append Quit Menu Item
  • UI\Menu::appendSeparator — Append Menu Item Separator
  • UI\Menu::__construct — Construct a new Menu
UI\Control::show
UI\Menu::append
UI


Append Menu Item

UI\Menu
UI\Menu::appendAbout
UI\Menu
PHP Manual

UI\Menu::append

(PHP 7, UI 0.9.9)

UI\Menu::append — Append Menu Item

Descrierea

public UI\MenuItem UI\Menu::append ( string $name [, string $type = UI\MenuItem::class ] )

Shall append a new Menu Item

Parametri

name

The name (text) for the new item

type

The type for the new item

Valorile întoarse

A constructed object of the given type

UI\Menu
UI\Menu::appendAbout
UI\Menu


Append About Menu Item

UI\Menu::append
UI\Menu::appendCheck
UI\Menu
PHP Manual

UI\Menu::appendAbout

(PHP 7, UI 0.9.9)

UI\Menu::appendAbout — Append About Menu Item

Descrierea

public UI\MenuItem UI\Menu::appendAbout ([ string $type = UI\MenuItem::class ] )

Shall append an About menu item

Parametri

type

The type for the new item

Valorile întoarse

A constructed About menu item of the given type

UI\Menu::append
UI\Menu::appendCheck
UI\Menu


Append Checkable Menu Item

UI\Menu::appendAbout
UI\Menu::appendPreferences
UI\Menu
PHP Manual

UI\Menu::appendCheck

(PHP 7, UI 0.9.9)

UI\Menu::appendCheck — Append Checkable Menu Item

Descrierea

public UI\MenuItem UI\Menu::appendCheck ( string $name [, string $type = UI\MenuItem::class ] )

Shall append a checkable menu item

Parametri

name

The name (text) for the new item

type

The type for the new item

Valorile întoarse

A constructed checkable menu item of the given type

UI\Menu::appendAbout
UI\Menu::appendPreferences
UI\Menu


Append Preferences Menu Item

UI\Menu::appendCheck
UI\Menu::appendQuit
UI\Menu
PHP Manual

UI\Menu::appendPreferences

(PHP 7, UI 0.9.9)

UI\Menu::appendPreferences — Append Preferences Menu Item

Descrierea

public UI\MenuItem UI\Menu::appendPreferences ([ string $type = UI\MenuItem::class ] )

Shall append a Preferences menu item

Parametri

type

The type for the new item

Valorile întoarse

A constructed Preferences menu item of the given type

UI\Menu::appendCheck
UI\Menu::appendQuit
UI\Menu


Append Quit Menu Item

UI\Menu::appendPreferences
UI\Menu::appendSeparator
UI\Menu
PHP Manual

UI\Menu::appendQuit

(PHP 7, UI 0.9.9)

UI\Menu::appendQuit — Append Quit Menu Item

Descrierea

public UI\MenuItem UI\Menu::appendQuit ([ string $type = UI\MenuItem::class ] )

Shall append a Quit menu item

Parametri

type

The type for the new item

Valorile întoarse

A constructed Quit menu item of the given type

UI\Menu::appendPreferences
UI\Menu::appendSeparator
UI\Menu


Append Menu Item Separator

UI\Menu::appendQuit
UI\Menu::__construct
UI\Menu
PHP Manual

UI\Menu::appendSeparator

(PHP 7, UI 0.9.9)

UI\Menu::appendSeparator — Append Menu Item Separator

Descrierea

public UI\Menu::appendSeparator ( void )

Shall append a separator

Parametri

Aceasta func?ie nu are parametri.

UI\Menu::appendQuit
UI\Menu::__construct
UI\Menu


Construct a new Menu

UI\Menu::appendSeparator
UI\MenuItem
UI\Menu
PHP Manual

UI\Menu::__construct

(PHP 7, UI 0.9.9)

UI\Menu::__construct — Construct a new Menu

Descrierea

public UI\Menu::__construct ( string $name )

Shall construct a new Menu

Parametri

name

The name (text) for the menu

UI\Menu::appendSeparator
UI\MenuItem
UI\Menu


Menu Item

(PHP 7, UI 0.9.9)

Introducere

Menu Items should only be created by the Menu

Sinopsisul clasei

UI\MenuItem {
/* Metode */
public disable ( void )
public enable ( void )
public bool isChecked ( void )
protected onClick ( void )
public setChecked ( boolean $checked )
}

Cuprins

  • UI\MenuItem::disable — Disable Menu Item
  • UI\MenuItem::enable — Enable Menu Item
  • UI\MenuItem::isChecked — Detect Checked
  • UI\MenuItem::onClick — On Click Callback
  • UI\MenuItem::setChecked — Set Checked
UI\Menu::__construct
UI\MenuItem::disable
UI


Disable Menu Item

UI\MenuItem
UI\MenuItem::enable
UI\MenuItem
PHP Manual

UI\MenuItem::disable

(PHP 7, UI 0.9.9)

UI\MenuItem::disable — Disable Menu Item

Descrierea

public UI\MenuItem::disable ( void )

Shall disable this Menu Item

Parametri

Aceasta func?ie nu are parametri.

UI\MenuItem
UI\MenuItem::enable
UI\MenuItem


Enable Menu Item

UI\MenuItem::disable
UI\MenuItem::isChecked
UI\MenuItem
PHP Manual

UI\MenuItem::enable

(PHP 7, UI 0.9.9)

UI\MenuItem::enable — Enable Menu Item

Descrierea

public UI\MenuItem::enable ( void )

Shall enable this Menu Item

Parametri

Aceasta func?ie nu are parametri.

UI\MenuItem::disable
UI\MenuItem::isChecked
UI\MenuItem


Detect Checked

UI\MenuItem::enable
UI\MenuItem::onClick
UI\MenuItem
PHP Manual

UI\MenuItem::isChecked

(PHP 7, UI 0.9.9)

UI\MenuItem::isChecked — Detect Checked

Descrierea

public bool UI\MenuItem::isChecked ( void )

Shall detect if this Menu Item is checked

Parametri

Aceasta func?ie nu are parametri.

UI\MenuItem::enable
UI\MenuItem::onClick
UI\MenuItem


On Click Callback

UI\MenuItem::isChecked
UI\MenuItem::setChecked
UI\MenuItem
PHP Manual

UI\MenuItem::onClick

(PHP 7, UI 0.9.9)

UI\MenuItem::onClick — On Click Callback

Descrierea

protected UI\MenuItem::onClick ( void )

Shall be executed when this Menu Item is clicked

Parametri

Aceasta func?ie nu are parametri.

UI\MenuItem::isChecked
UI\MenuItem::setChecked
UI\MenuItem


Set Checked

UI\MenuItem::onClick
UI\Area
UI\MenuItem
PHP Manual

UI\MenuItem::setChecked

(PHP 7, UI 0.9.9)

UI\MenuItem::setChecked — Set Checked

Descrierea

public UI\MenuItem::setChecked ( boolean $checked )

Shall set the checked status of this Menu Item

Parametri

checked

The new status

UI\MenuItem::onClick
UI\Area
UI\MenuItem


Area

(PHP 7, UI 0.9.9)

Introducere

An Area represents a canvas which can be used to draw, and respond to mouse and key events.

Sinopsisul clasei

UI\Area extends UI\Control {
/* Constants */
const integer Ctrl ;
const integer Alt ;
const integer Shift ;
const integer Super ;
const integer Down ;
const integer Up ;
/* Metode */
protected onDraw ( UI\Draw\Pen $pen , UI\Size $areaSize , UI\Point $clipPoint , UI\Size $clipSize )
protected onKey ( string $key , integer $ext , integer $flags )
protected onMouse ( UI\Point $areaPoint , UI\Size $areaSize , integer $flags )
public redraw ( void )
public scrollTo ( UI\Point $point , UI\Size $size )
public setSize ( UI\Size $size )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Constante predefinite

UI\Area::Ctrl

Shall be set in the modifiers passed to key and mouse events when the CTRL key is active

UI\Area::Alt

Shall be set in the modifiers passed to key and mouse events when the ALT key is active

UI\Area::Shift

Shall be set in the modifiers passed to key and mouse events when the SHIFT key is active

UI\Area::Super

UI\Area::Down

Shall be set in the modifiers passed to key and mouse events

UI\Area::Up

Shall be set in the modifiers passed to key and mouse events

Cuprins

  • UI\Area::onDraw — Draw Callback
  • UI\Area::onKey — Key Callback
  • UI\Area::onMouse — Mouse Callback
  • UI\Area::redraw — Redraw Area
  • UI\Area::scrollTo — Area Scroll
  • UI\Area::setSize — Set Size
UI\MenuItem::setChecked
UI\Area::onDraw
UI


Draw Callback

UI\Area
UI\Area::onKey
UI\Area
PHP Manual

UI\Area::onDraw

(PHP 7, UI 0.9.9)

UI\Area::onDraw — Draw Callback

Descrierea

protected UI\Area::onDraw ( UI\Draw\Pen $pen , UI\Size $areaSize , UI\Point $clipPoint , UI\Size $clipSize )

Shall be invoked when this Area requires redrawing

Parametri

pen

A Pen suitable for drawing in this Area

areaSize

The size of the Area

clipPoint

The clip point of the Area

clipSize

The clip size of the Area

UI\Area
UI\Area::onKey
UI\Area


Key Callback

UI\Area::onDraw
UI\Area::onMouse
UI\Area
PHP Manual

UI\Area::onKey

(PHP 7, UI 0.9.9)

UI\Area::onKey — Key Callback

Descrierea

protected UI\Area::onKey ( string $key , integer $ext , integer $flags )

Shall be executed on key events

Parametri

key

The key pressed

ext

The extended key pressed

flags

Event modifiers

Valorile întoarse

UI\Area::onDraw
UI\Area::onMouse
UI\Area


Mouse Callback

UI\Area::onKey
UI\Area::redraw
UI\Area
PHP Manual

UI\Area::onMouse

(PHP 7, UI 0.9.9)

UI\Area::onMouse — Mouse Callback

Descrierea

protected UI\Area::onMouse ( UI\Point $areaPoint , UI\Size $areaSize , integer $flags )

Shall be executed on mouse events

Parametri

areaPoint

The co-ordinates of the event

areaSize

The size of the area of the event

flags

Event modifiers

UI\Area::onKey
UI\Area::redraw
UI\Area


Redraw Area

UI\Area::onMouse
UI\Area::scrollTo
UI\Area
PHP Manual

UI\Area::redraw

(PHP 7, UI 0.9.9)

UI\Area::redraw — Redraw Area

Descrierea

public UI\Area::redraw ( void )

Requests that this Area is redrawn

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Area::onMouse
UI\Area::scrollTo
UI\Area


Area Scroll

UI\Area::redraw
UI\Area::setSize
UI\Area
PHP Manual

UI\Area::scrollTo

(PHP 7, UI 0.9.9)

UI\Area::scrollTo — Area Scroll

Descrierea

public UI\Area::scrollTo ( UI\Point $point , UI\Size $size )

Scroll this Area

Parametri

point

The point to scroll to

size

The size of the scroll pane

UI\Area::redraw
UI\Area::setSize
UI\Area


Set Size

UI\Area::scrollTo
UI\Executor
UI\Area
PHP Manual

UI\Area::setSize

(PHP 7, UI 0.9.9)

UI\Area::setSize — Set Size

Descrierea

public UI\Area::setSize ( UI\Size $size )

Sets the size of this Area

Parametri

size

The new size

UI\Area::scrollTo
UI\Executor
UI\Area


Execution Scheduler

(PHP 7, UI 2.0.0)

Introducere

This facility schedules repetitive execution of a callback, useful for animations and other such activities.

Sinopsisul clasei

abstract UI\Executor {
/* Constructor */
public __construct ( void )
public __construct ( integer $microseconds )
public __construct ( integer $seconds , integer $microseconds )
/* Metode */
public void kill ( void )
abstract protected void onExecute ( void )
public bool setInterval ( integer $microseconds )
public bool setInterval ( integer $seconds , integer $microseconds )
}

Cuprins

  • UI\Executor::__construct — Construct a new Executor
  • UI\Executor::kill — Stop Executor
  • UI\Executor::onExecute — Execution Callback
  • UI\Executor::setInterval — Interval Manipulation
UI\Area::setSize
UI\Executor::__construct
UI


Construct a new Executor

UI\Executor
UI\Executor::kill
UI\Executor
PHP Manual

UI\Executor::__construct

(PHP 7, UI 2.0.0)

UI\Executor::__construct — Construct a new Executor

Descrierea

public UI\Executor::__construct ( void )
public UI\Executor::__construct ( integer $microseconds )
public UI\Executor::__construct ( integer $seconds , integer $microseconds )

Shall construct an executor with the given interval, will not start executing until main loop is entered

Parametri

seconds

Seconds between executions

microseconds

Microseconds between executions

UI\Executor
UI\Executor::kill
UI\Executor


Stop Executor

UI\Executor::__construct
UI\Executor::onExecute
UI\Executor
PHP Manual

UI\Executor::kill

(PHP 7, UI 2.0.0)

UI\Executor::kill — Stop Executor

Descrierea

public void UI\Executor::kill ( void )

Shall stop an executor, the executor cannot be restarted

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Executor::__construct
UI\Executor::onExecute
UI\Executor


Execution Callback

UI\Executor::kill
UI\Executor::setInterval
UI\Executor
PHP Manual

UI\Executor::onExecute

(PHP 7, UI 2.0.0)

UI\Executor::onExecute — Execution Callback

Descrierea

abstract protected void UI\Executor::onExecute ( void )

Shall be repetitively queued for execution in the main thread

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Executor::kill
UI\Executor::setInterval
UI\Executor


Interval Manipulation

UI\Executor::onExecute
UI\Controls\Tab
UI\Executor
PHP Manual

UI\Executor::setInterval

(PHP 7, UI 2.0.0)

UI\Executor::setInterval — Interval Manipulation

Descrierea

public bool UI\Executor::setInterval ( integer $microseconds )
public bool UI\Executor::setInterval ( integer $seconds , integer $microseconds )

Shall set the new interval. An interval of 0 will pause the executor until a new interval has been set

Parametri

seconds

microseconds

Valorile întoarse

Indication of success

UI\Executor::onExecute
UI\Controls\Tab
UI\Executor


Tab Control

(PHP 7, UI 0.9.9)

Introducere

A Tab can contain many pages of Controls, each with a title, each selectable by the user.

Sinopsisul clasei

UI\Controls\Tab extends UI\Control {
/* Proprieta?i */
protected $controls ;
/* Metode */
public integer append ( string $name , UI\Control $control )
public boolean delete ( integer $index )
public bool hasMargin ( integer $page )
public insertAt ( string $name , integer $page , UI\Control $control )
public integer pages ( void )
public setMargin ( integer $page , boolean $margin )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Proprieta?i

controls

Contains controls, should not be manipulated directly

Cuprins

  • UI\Controls\Tab::append — Append Page
  • UI\Controls\Tab::delete — Delete Page
  • UI\Controls\Tab::hasMargin — Margin Detection
  • UI\Controls\Tab::insertAt — Insert Page
  • UI\Controls\Tab::pages — Page Count
  • UI\Controls\Tab::setMargin — Set Margin
UI\Executor::setInterval
UI\Controls\Tab::append
UI


Append Page

UI\Controls\Tab
UI\Controls\Tab::delete
UI\Controls\Tab
PHP Manual

UI\Controls\Tab::append

(PHP 7, UI 0.9.9)

UI\Controls\Tab::append — Append Page

Descrierea

public integer UI\Controls\Tab::append ( string $name , UI\Control $control )

Append a new page to this Tab

Parametri

name

The name for the new page

control

The control for the new page

Valorile întoarse

Shall return the index of the appended control, may be 0

UI\Controls\Tab
UI\Controls\Tab::delete
UI\Controls\Tab


Delete Page

UI\Controls\Tab::append
UI\Controls\Tab::hasMargin
UI\Controls\Tab
PHP Manual

UI\Controls\Tab::delete

(PHP 7, UI 0.9.9)

UI\Controls\Tab::delete — Delete Page

Descrierea

public boolean UI\Controls\Tab::delete ( integer $index )

Shall remove the selected page from this Tab

Parametri

index

The index of the page to remove

Valorile întoarse

Indication of success

UI\Controls\Tab::append
UI\Controls\Tab::hasMargin
UI\Controls\Tab


Margin Detection

UI\Controls\Tab::delete
UI\Controls\Tab::insertAt
UI\Controls\Tab
PHP Manual

UI\Controls\Tab::hasMargin

(PHP 7, UI 0.9.9)

UI\Controls\Tab::hasMargin — Margin Detection

Descrierea

public bool UI\Controls\Tab::hasMargin ( integer $page )

Shall detect if the given page has a margin.

Parametri

page

The index of the page

Valorile întoarse

UI\Controls\Tab::delete
UI\Controls\Tab::insertAt
UI\Controls\Tab


Insert Page

UI\Controls\Tab::hasMargin
UI\Controls\Tab::pages
UI\Controls\Tab
PHP Manual

UI\Controls\Tab::insertAt

(PHP 7, UI 0.9.9)

UI\Controls\Tab::insertAt — Insert Page

Descrierea

public UI\Controls\Tab::insertAt ( string $name , integer $page , UI\Control $control )

Shall insert a new page into this Tab

Parametri

name

The name for the new page

page

The index to perform the insertion before

control

The control for the new page

UI\Controls\Tab::hasMargin
UI\Controls\Tab::pages
UI\Controls\Tab


Page Count

UI\Controls\Tab::insertAt
UI\Controls\Tab::setMargin
UI\Controls\Tab
PHP Manual

UI\Controls\Tab::pages

(PHP 7, UI 0.9.9)

UI\Controls\Tab::pages — Page Count

Descrierea

public integer UI\Controls\Tab::pages ( void )

Shall return the number of pages in this Tab

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The number of pages in this Tab

UI\Controls\Tab::insertAt
UI\Controls\Tab::setMargin
UI\Controls\Tab


Set Margin

UI\Controls\Tab::pages
UI\Controls\Check
UI\Controls\Tab
PHP Manual

UI\Controls\Tab::setMargin

(PHP 7, UI 0.9.9)

UI\Controls\Tab::setMargin — Set Margin

Descrierea

public UI\Controls\Tab::setMargin ( integer $page , boolean $margin )

Shall enable or disable margins on the selected page

Parametri

page

The page to select

margin

Margin switch

UI\Controls\Tab::pages
UI\Controls\Check
UI\Controls\Tab


Check Control

(PHP 7, UI 0.9.9)

Introducere

A Check is a labelled checkable box

Sinopsisul clasei

UI\Controls\Check extends UI\Control {
/* Constructor */
public __construct ( string $text )
/* Metode */
public string getText ( void )
public bool isChecked ( void )
protected onToggle ( void )
public setChecked ( boolean $checked )
public setText ( string $text )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Cuprins

  • UI\Controls\Check::__construct — Construct a new Check
  • UI\Controls\Check::getText — Get Text
  • UI\Controls\Check::isChecked — Checked Detection
  • UI\Controls\Check::onToggle — Toggle Callback
  • UI\Controls\Check::setChecked — Set Checked
  • UI\Controls\Check::setText — Set Text
UI\Controls\Tab::setMargin
UI\Controls\Check::__construct
UI


Construct a new Check

UI\Controls\Check
UI\Controls\Check::getText
UI\Controls\Check
PHP Manual

UI\Controls\Check::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Check::__construct — Construct a new Check

Descrierea

public UI\Controls\Check::__construct ( string $text )

Shall construct a new Check

Parametri

text

The text (label) for the Check box

UI\Controls\Check
UI\Controls\Check::getText
UI\Controls\Check


Get Text

UI\Controls\Check::__construct
UI\Controls\Check::isChecked
UI\Controls\Check
PHP Manual

UI\Controls\Check::getText

(PHP 7, UI 0.9.9)

UI\Controls\Check::getText — Get Text

Descrierea

public string UI\Controls\Check::getText ( void )

Shall return the text (label) for this Check

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current text (label)

UI\Controls\Check::__construct
UI\Controls\Check::isChecked
UI\Controls\Check


Checked Detection

UI\Controls\Check::getText
UI\Controls\Check::onToggle
UI\Controls\Check
PHP Manual

UI\Controls\Check::isChecked

(PHP 7, UI 0.9.9)

UI\Controls\Check::isChecked — Checked Detection

Descrierea

public bool UI\Controls\Check::isChecked ( void )

Shall detect the status of this Check

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Check::getText
UI\Controls\Check::onToggle
UI\Controls\Check


Toggle Callback

UI\Controls\Check::isChecked
UI\Controls\Check::setChecked
UI\Controls\Check
PHP Manual

UI\Controls\Check::onToggle

(PHP 7, UI 0.9.9)

UI\Controls\Check::onToggle — Toggle Callback

Descrierea

protected UI\Controls\Check::onToggle ( void )

Shall be executed when the status of this Check is changed

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Check::isChecked
UI\Controls\Check::setChecked
UI\Controls\Check


Set Checked

UI\Controls\Check::onToggle
UI\Controls\Check::setText
UI\Controls\Check
PHP Manual

UI\Controls\Check::setChecked

(PHP 7, UI 0.9.9)

UI\Controls\Check::setChecked — Set Checked

Descrierea

public UI\Controls\Check::setChecked ( boolean $checked )

Shall change the status of this Check

Parametri

checked

The new status

UI\Controls\Check::onToggle
UI\Controls\Check::setText
UI\Controls\Check


Set Text

UI\Controls\Check::setChecked
UI\Controls\Button
UI\Controls\Check
PHP Manual

UI\Controls\Check::setText

(PHP 7, UI 0.9.9)

UI\Controls\Check::setText — Set Text

Descrierea

public UI\Controls\Check::setText ( string $text )

Shall set the text (label) for this Check

Parametri

text

The new text (label)

UI\Controls\Check::setChecked
UI\Controls\Button
UI\Controls\Check


Button Control

(PHP 7, UI 0.9.9)

Introducere

Represents a labelled clickable button

Sinopsisul clasei

UI\Controls\Button extends UI\Control {
/* Constructor */
public __construct ( string $text )
/* Metode */
public string getText ( void )
protected onClick ( void )
public setText ( string $text )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Cuprins

  • UI\Controls\Button::__construct — Construct a new Button
  • UI\Controls\Button::getText — Get Text
  • UI\Controls\Button::onClick — Click Handler
  • UI\Controls\Button::setText — Set Text
UI\Controls\Check::setText
UI\Controls\Button::__construct
UI


Construct a new Button

UI\Controls\Button
UI\Controls\Button::getText
UI\Controls\Button
PHP Manual

UI\Controls\Button::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Button::__construct — Construct a new Button

Descrierea

public UI\Controls\Button::__construct ( string $text )

Shall construct a new Button

Parametri

text

The text (label) for this Button

UI\Controls\Button
UI\Controls\Button::getText
UI\Controls\Button


Get Text

UI\Controls\Button::__construct
UI\Controls\Button::onClick
UI\Controls\Button
PHP Manual

UI\Controls\Button::getText

(PHP 7, UI 0.9.9)

UI\Controls\Button::getText — Get Text

Descrierea

public string UI\Controls\Button::getText ( void )

Shall retrieve the text (label) for this Button

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current text (label)

UI\Controls\Button::__construct
UI\Controls\Button::onClick
UI\Controls\Button


Click Handler

UI\Controls\Button::getText
UI\Controls\Button::setText
UI\Controls\Button
PHP Manual

UI\Controls\Button::onClick

(PHP 7, UI 0.9.9)

UI\Controls\Button::onClick — Click Handler

Descrierea

protected UI\Controls\Button::onClick ( void )

Shall be executed when this Button is clicked

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Button::getText
UI\Controls\Button::setText
UI\Controls\Button


Set Text

UI\Controls\Button::onClick
UI\Controls\ColorButton
UI\Controls\Button
PHP Manual

UI\Controls\Button::setText

(PHP 7, UI 0.9.9)

UI\Controls\Button::setText — Set Text

Descrierea

public UI\Controls\Button::setText ( string $text )

Shall set the text (label) for this Button

Parametri

text

The new text (label)

UI\Controls\Button::onClick
UI\Controls\ColorButton
UI\Controls\Button


ColorButton Control

(PHP 7, UI 0.9.9)

Introducere

A Color Button is a button which displays a color picker when clicked

Sinopsisul clasei

UI\Controls\ColorButton extends UI\Control {
/* Metode */
public UI\Color getColor ( void )
protected onChange ( void )
public setColor ( UI\Draw\Color $color )
public setColor ( integer $color )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Cuprins

  • UI\Controls\ColorButton::getColor — Get Color
  • UI\Controls\ColorButton::onChange — Change Handler
  • UI\Controls\ColorButton::setColor — Set Color
UI\Controls\Button::setText
UI\Controls\ColorButton::getColor
UI


Get Color

UI\Controls\ColorButton
UI\Controls\ColorButton::onChange
UI\Controls\ColorButton
PHP Manual

UI\Controls\ColorButton::getColor

(PHP 7, UI 0.9.9)

UI\Controls\ColorButton::getColor — Get Color

Descrierea

public UI\Color UI\Controls\ColorButton::getColor ( void )

Shall retrieve the currently selected Color

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Controls\ColorButton
UI\Controls\ColorButton::onChange
UI\Controls\ColorButton


Change Handler

UI\Controls\ColorButton::getColor
UI\Controls\ColorButton::setColor
UI\Controls\ColorButton
PHP Manual

UI\Controls\ColorButton::onChange

(PHP 7, UI 0.9.9)

UI\Controls\ColorButton::onChange — Change Handler

Descrierea

protected UI\Controls\ColorButton::onChange ( void )

Shall be executed when the selected Color is changed

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\ColorButton::getColor
UI\Controls\ColorButton::setColor
UI\Controls\ColorButton


Set Color

UI\Controls\ColorButton::onChange
UI\Controls\Label
UI\Controls\ColorButton
PHP Manual

UI\Controls\ColorButton::setColor

(PHP 7, UI 0.9.9)

UI\Controls\ColorButton::setColor — Set Color

Descrierea

public UI\Controls\ColorButton::setColor ( UI\Draw\Color $color )
public UI\Controls\ColorButton::setColor ( integer $color )

Shall set the currently selected Color

Parametri

color

The new color

UI\Controls\ColorButton::onChange
UI\Controls\Label
UI\Controls\ColorButton


Label Control

(PHP 7, UI 0.9.9)

Introducere

A Label is a single line of text, meant to identify, for the user, some element of the interface.

Sinopsisul clasei

UI\Controls\Label extends UI\Control {
/* Constructor */
public __construct ( string $text )
/* Metode */
public string getText ( void )
public setText ( string $text )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Cuprins

  • UI\Controls\Label::__construct — Construct a new Label
  • UI\Controls\Label::getText — Get Text
  • UI\Controls\Label::setText — Set Text
UI\Controls\ColorButton::setColor
UI\Controls\Label::__construct
UI


Construct a new Label

UI\Controls\Label
UI\Controls\Label::getText
UI\Controls\Label
PHP Manual

UI\Controls\Label::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Label::__construct — Construct a new Label

Descrierea

public UI\Controls\Label::__construct ( string $text )

Shall construct a new Label

Parametri

text

The text for this label

UI\Controls\Label
UI\Controls\Label::getText
UI\Controls\Label


Get Text

UI\Controls\Label::__construct
UI\Controls\Label::setText
UI\Controls\Label
PHP Manual

UI\Controls\Label::getText

(PHP 7, UI 0.9.9)

UI\Controls\Label::getText — Get Text

Descrierea

public string UI\Controls\Label::getText ( void )

Shall return the current text for this Label

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Controls\Label::__construct
UI\Controls\Label::setText
UI\Controls\Label


Set Text

UI\Controls\Label::getText
UI\Controls\Entry
UI\Controls\Label
PHP Manual

UI\Controls\Label::setText

(PHP 7, UI 0.9.9)

UI\Controls\Label::setText — Set Text

Descrierea

public UI\Controls\Label::setText ( string $text )

Shall set the text for this Label

Parametri

text

The new text

UI\Controls\Label::getText
UI\Controls\Entry
UI\Controls\Label


Entry Control

(PHP 7, UI 0.9.9)

Introducere

An Entry is a text entry control, suitable for entering plain text, passwords, or search terms.

Sinopsisul clasei

UI\Controls\Entry extends UI\Control {
/* Constants */
const integer Normal ;
const integer Password ;
const integer Search ;
/* Constructor */
public __construct ([ integer $type = UI\Controls\Entry::Normal ] )
/* Metode */
public string getText ( void )
public bool isReadOnly ( void )
protected onChange ( void )
public setReadOnly ( boolean $readOnly )
public setText ( string $text )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Constante predefinite

UI\Controls\Entry::Normal

A normal single line entry

UI\Controls\Entry::Password

A password entry

UI\Controls\Entry::Search

A search entry

Cuprins

  • UI\Controls\Entry::__construct — Construct a new Entry
  • UI\Controls\Entry::getText — Get Text
  • UI\Controls\Entry::isReadOnly — Detect Read Only
  • UI\Controls\Entry::onChange — Change Handler
  • UI\Controls\Entry::setReadOnly — Set Read Only
  • UI\Controls\Entry::setText — Set Text
UI\Controls\Label::setText
UI\Controls\Entry::__construct
UI


Construct a new Entry

UI\Controls\Entry
UI\Controls\Entry::getText
UI\Controls\Entry
PHP Manual

UI\Controls\Entry::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Entry::__construct — Construct a new Entry

Descrierea

public UI\Controls\Entry::__construct ([ integer $type = UI\Controls\Entry::Normal ] )

Construct a new entry of the given type

Parametri

type

Entry::Normal, Entry::Password, or Entry::Search

UI\Controls\Entry
UI\Controls\Entry::getText
UI\Controls\Entry


Get Text

UI\Controls\Entry::__construct
UI\Controls\Entry::isReadOnly
UI\Controls\Entry
PHP Manual

UI\Controls\Entry::getText

(PHP 7, UI 0.9.9)

UI\Controls\Entry::getText — Get Text

Descrierea

public string UI\Controls\Entry::getText ( void )

Shall return the current text from this Entry

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current text

UI\Controls\Entry::__construct
UI\Controls\Entry::isReadOnly
UI\Controls\Entry


Detect Read Only

UI\Controls\Entry::getText
UI\Controls\Entry::onChange
UI\Controls\Entry
PHP Manual

UI\Controls\Entry::isReadOnly

(PHP 7, UI 0.9.9)

UI\Controls\Entry::isReadOnly — Detect Read Only

Descrierea

public bool UI\Controls\Entry::isReadOnly ( void )

Shall detect if this Entry is read only

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Controls\Entry::getText
UI\Controls\Entry::onChange
UI\Controls\Entry


Change Handler

UI\Controls\Entry::isReadOnly
UI\Controls\Entry::setReadOnly
UI\Controls\Entry
PHP Manual

UI\Controls\Entry::onChange

(PHP 7, UI 0.9.9)

UI\Controls\Entry::onChange — Change Handler

Descrierea

protected UI\Controls\Entry::onChange ( void )

Shall be executed when the text in this Entry changes

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Entry::isReadOnly
UI\Controls\Entry::setReadOnly
UI\Controls\Entry


Set Read Only

UI\Controls\Entry::onChange
UI\Controls\Entry::setText
UI\Controls\Entry
PHP Manual

UI\Controls\Entry::setReadOnly

(PHP 7, UI 0.9.9)

UI\Controls\Entry::setReadOnly — Set Read Only

Descrierea

public UI\Controls\Entry::setReadOnly ( boolean $readOnly )

Shall enable or disable read only for this Entry

Parametri

readOnly

UI\Controls\Entry::onChange
UI\Controls\Entry::setText
UI\Controls\Entry


Set Text

UI\Controls\Entry::setReadOnly
UI\Controls\MultilineEntry
UI\Controls\Entry
PHP Manual

UI\Controls\Entry::setText

(PHP 7, UI 0.9.9)

UI\Controls\Entry::setText — Set Text

Descrierea

public UI\Controls\Entry::setText ( string $text )

Shall set the text for this Entry

Parametri

text

The new text

UI\Controls\Entry::setReadOnly
UI\Controls\MultilineEntry
UI\Controls\Entry


MultilineEntry Control

(PHP 7, UI 0.9.9)

Introducere

A Multiline Entry is a text entry control able to hold multiple lines of text, with or without wrapping.

Sinopsisul clasei

UI\Controls\MultilineEntry extends UI\Control {
/* Constants */
const integer Wrap ;
const integer NoWrap ;
/* Constructor */
public __construct ([ integer $type ] )
/* Metode */
public append ( string $text )
public string getText ( void )
public bool isReadOnly ( void )
protected onChange ( void )
public setReadOnly ( boolean $readOnly )
public setText ( string $text )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Constante predefinite

UI\Controls\MultilineEntry::Wrap

Allow lines to wrap

UI\Controls\MultilineEntry::NoWrap

Do not allow lines to wrap

Cuprins

  • UI\Controls\MultilineEntry::append — Append Text
  • UI\Controls\MultilineEntry::__construct — Construct a new Multiline Entry
  • UI\Controls\MultilineEntry::getText — Get Text
  • UI\Controls\MultilineEntry::isReadOnly — Read Only Detection
  • UI\Controls\MultilineEntry::onChange — Change Handler
  • UI\Controls\MultilineEntry::setReadOnly — Set Read Only
  • UI\Controls\MultilineEntry::setText — Set Text
UI\Controls\Entry::setText
UI\Controls\MultilineEntry::append
UI


Append Text

UI\Controls\MultilineEntry
UI\Controls\MultilineEntry::__construct
UI\Controls\MultilineEntry
PHP Manual

UI\Controls\MultilineEntry::append

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::append — Append Text

Descrierea

public UI\Controls\MultilineEntry::append ( string $text )

Shall append the given text to the text in this Multiline Entry

Parametri

text

The text to append

UI\Controls\MultilineEntry
UI\Controls\MultilineEntry::__construct
UI\Controls\MultilineEntry


Construct a new Multiline Entry

UI\Controls\MultilineEntry::append
UI\Controls\MultilineEntry::getText
UI\Controls\MultilineEntry
PHP Manual

UI\Controls\MultilineEntry::__construct

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::__construct — Construct a new Multiline Entry

Descrierea

public UI\Controls\MultilineEntry::__construct ([ integer $type ] )

Shall construct a new Multiline Entry of the given type

Parametri

type

MultilineEntry::Wrap or MultilineEntry::NoWrap

UI\Controls\MultilineEntry::append
UI\Controls\MultilineEntry::getText
UI\Controls\MultilineEntry


Get Text

UI\Controls\MultilineEntry::__construct
UI\Controls\MultilineEntry::isReadOnly
UI\Controls\MultilineEntry
PHP Manual

UI\Controls\MultilineEntry::getText

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::getText — Get Text

Descrierea

public string UI\Controls\MultilineEntry::getText ( void )

Shall return the text in this Multiline Entry

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\MultilineEntry::__construct
UI\Controls\MultilineEntry::isReadOnly
UI\Controls\MultilineEntry


Read Only Detection

UI\Controls\MultilineEntry::getText
UI\Controls\MultilineEntry::onChange
UI\Controls\MultilineEntry
PHP Manual

UI\Controls\MultilineEntry::isReadOnly

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::isReadOnly — Read Only Detection

Descrierea

public bool UI\Controls\MultilineEntry::isReadOnly ( void )

Shall detect if this Multiline Entry is read only

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\MultilineEntry::getText
UI\Controls\MultilineEntry::onChange
UI\Controls\MultilineEntry


Change Handler

UI\Controls\MultilineEntry::isReadOnly
UI\Controls\MultilineEntry::setReadOnly
UI\Controls\MultilineEntry
PHP Manual

UI\Controls\MultilineEntry::onChange

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::onChange — Change Handler

Descrierea

protected UI\Controls\MultilineEntry::onChange ( void )

Shall be executed when the text in this Multiline Entry is changed

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\MultilineEntry::isReadOnly
UI\Controls\MultilineEntry::setReadOnly
UI\Controls\MultilineEntry


Set Read Only

UI\Controls\MultilineEntry::onChange
UI\Controls\MultilineEntry::setText
UI\Controls\MultilineEntry
PHP Manual

UI\Controls\MultilineEntry::setReadOnly

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::setReadOnly — Set Read Only

Descrierea

public UI\Controls\MultilineEntry::setReadOnly ( boolean $readOnly )

Shall enable or disable read only on this Multiline Entry

Parametri

readOnly

UI\Controls\MultilineEntry::onChange
UI\Controls\MultilineEntry::setText
UI\Controls\MultilineEntry


Set Text

UI\Controls\MultilineEntry::setReadOnly
UI\Controls\Spin
UI\Controls\MultilineEntry
PHP Manual

UI\Controls\MultilineEntry::setText

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::setText — Set Text

Descrierea

public UI\Controls\MultilineEntry::setText ( string $text )

Shall set the text in this Multiline Entry

Parametri

text

The new text

UI\Controls\MultilineEntry::setReadOnly
UI\Controls\Spin
UI\Controls\MultilineEntry


Spin Control

(PHP 7, UI 0.9.9)

Introducere

A Spin box is a text box with an up-down control which changes the integer value in the box, within a defined range

Sinopsisul clasei

UI\Controls\Spin extends UI\Control {
/* Constructor */
public __construct ( integer $min , integer $max )
/* Metode */
public int getValue ( void )
protected onChange ( void )
public setValue ( integer $value )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Cuprins

  • UI\Controls\Spin::__construct — Construct a new Spin
  • UI\Controls\Spin::getValue — Get Value
  • UI\Controls\Spin::onChange — Change Handler
  • UI\Controls\Spin::setValue — Set Value
UI\Controls\MultilineEntry::setText
UI\Controls\Spin::__construct
UI


Construct a new Spin

UI\Controls\Spin
UI\Controls\Spin::getValue
UI\Controls\Spin
PHP Manual

UI\Controls\Spin::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Spin::__construct — Construct a new Spin

Descrierea

public UI\Controls\Spin::__construct ( integer $min , integer $max )

Constructs a new Spin with the given range

Parametri

min

The minimum value allowed

max

The maximum value allowed

UI\Controls\Spin
UI\Controls\Spin::getValue
UI\Controls\Spin


Get Value

UI\Controls\Spin::__construct
UI\Controls\Spin::onChange
UI\Controls\Spin
PHP Manual

UI\Controls\Spin::getValue

(PHP 7, UI 0.9.9)

UI\Controls\Spin::getValue — Get Value

Descrierea

public int UI\Controls\Spin::getValue ( void )

Get the value in this Spin

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Spin::__construct
UI\Controls\Spin::onChange
UI\Controls\Spin


Change Handler

UI\Controls\Spin::getValue
UI\Controls\Spin::setValue
UI\Controls\Spin
PHP Manual

UI\Controls\Spin::onChange

(PHP 7, UI 0.9.9)

UI\Controls\Spin::onChange — Change Handler

Descrierea

protected UI\Controls\Spin::onChange ( void )

Shall be executed when the value in this Spin changes

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Spin::getValue
UI\Controls\Spin::setValue
UI\Controls\Spin


Set Value

UI\Controls\Spin::onChange
UI\Controls\Slider
UI\Controls\Spin
PHP Manual

UI\Controls\Spin::setValue

(PHP 7, UI 0.9.9)

UI\Controls\Spin::setValue — Set Value

Descrierea

public UI\Controls\Spin::setValue ( integer $value )

Set the value in this Spin

Parametri

value

The new value

UI\Controls\Spin::onChange
UI\Controls\Slider
UI\Controls\Spin


Slider Control

(PHP 7, UI 0.9.9)

Introducere

A Slider is a control which represents a range, and a current value in the range. The sliding element of the control (sometimes called the "thumb") reflects the value, and can be adjusted within the range.

Sinopsisul clasei

UI\Controls\Slider extends UI\Control {
/* Constructor */
public __construct ( integer $min , integer $max )
/* Metode */
public integer getValue ( void )
protected onChange ( void )
public setValue ( integer $value )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Cuprins

  • UI\Controls\Slider::__construct — Construct a new Slider
  • UI\Controls\Slider::getValue — Get Value
  • UI\Controls\Slider::onChange — Change Handler
  • UI\Controls\Slider::setValue — Set Value
UI\Controls\Spin::setValue
UI\Controls\Slider::__construct
UI


Construct a new Slider

UI\Controls\Slider
UI\Controls\Slider::getValue
UI\Controls\Slider
PHP Manual

UI\Controls\Slider::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Slider::__construct — Construct a new Slider

Descrierea

public UI\Controls\Slider::__construct ( integer $min , integer $max )

Construct a new Slider with the given range

Parametri

min

The minimum allowed value

max

The maximum allowed value

UI\Controls\Slider
UI\Controls\Slider::getValue
UI\Controls\Slider


Get Value

UI\Controls\Slider::__construct
UI\Controls\Slider::onChange
UI\Controls\Slider
PHP Manual

UI\Controls\Slider::getValue

(PHP 7, UI 0.9.9)

UI\Controls\Slider::getValue — Get Value

Descrierea

public integer UI\Controls\Slider::getValue ( void )

Get the value from this Slider

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Slider::__construct
UI\Controls\Slider::onChange
UI\Controls\Slider


Change Handler

UI\Controls\Slider::getValue
UI\Controls\Slider::setValue
UI\Controls\Slider
PHP Manual

UI\Controls\Slider::onChange

(PHP 7, UI 0.9.9)

UI\Controls\Slider::onChange — Change Handler

Descrierea

protected UI\Controls\Slider::onChange ( void )

Shall be executed when the value of this Slider changes

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Slider::getValue
UI\Controls\Slider::setValue
UI\Controls\Slider


Set Value

UI\Controls\Slider::onChange
UI\Controls\Progress
UI\Controls\Slider
PHP Manual

UI\Controls\Slider::setValue

(PHP 7, UI 0.9.9)

UI\Controls\Slider::setValue — Set Value

Descrierea

public UI\Controls\Slider::setValue ( integer $value )

Shall set the value for this Slider

Parametri

value

The new value

UI\Controls\Slider::onChange
UI\Controls\Progress
UI\Controls\Slider


Progress Control

(PHP 7, UI 0.9.9)

Introducere

A Progress control is a familiar Progress bar: It represents progress as a percentage, with a possible range of 0 to 100 (inclusive).

Sinopsisul clasei

UI\Controls\Progress extends UI\Control {
/* Metode */
public int getValue ( void )
public setValue ( integer $value )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Cuprins

  • UI\Controls\Progress::getValue — Get Value
  • UI\Controls\Progress::setValue — Set Value
UI\Controls\Slider::setValue
UI\Controls\Progress::getValue
UI


Get Value

UI\Controls\Progress
UI\Controls\Progress::setValue
UI\Controls\Progress
PHP Manual

UI\Controls\Progress::getValue

(PHP 7, UI 0.9.9)

UI\Controls\Progress::getValue — Get Value

Descrierea

public int UI\Controls\Progress::getValue ( void )

Shall retrieve the current value of this Progress bar

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Progress
UI\Controls\Progress::setValue
UI\Controls\Progress


Set Value

UI\Controls\Progress::getValue
UI\Controls\Separator
UI\Controls\Progress
PHP Manual

UI\Controls\Progress::setValue

(PHP 7, UI 0.9.9)

UI\Controls\Progress::setValue — Set Value

Descrierea

public UI\Controls\Progress::setValue ( integer $value )

Shall set the value for this Progress bar

Parametri

value

An integer between 0 and 100 (inclusive)

UI\Controls\Progress::getValue
UI\Controls\Separator
UI\Controls\Progress


Control Separator

(PHP 7, UI 0.9.9)

Introducere

A Separator represents a control separator, it has no other function.

Sinopsisul clasei

UI\Controls\Separator extends UI\Control {
/* Constants */
const integer Horizontal ;
const integer Vertical ;
/* Constructor */
public __construct ([ integer $type = UI\Controls\Separator::Horizontal ] )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Constante predefinite

UI\Controls\Separator::Horizontal

A Horizontal Separator

UI\Controls\Separator::Vertical

A Vertical Separator

Cuprins

  • UI\Controls\Separator::__construct — Construct a new Separator
UI\Controls\Progress::setValue
UI\Controls\Separator::__construct
UI


Construct a new Separator

UI\Controls\Separator
UI\Controls\Combo
UI\Controls\Separator
PHP Manual

UI\Controls\Separator::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Separator::__construct — Construct a new Separator

Descrierea

public UI\Controls\Separator::__construct ([ integer $type = UI\Controls\Separator::Horizontal ] )

Shall construct a new Separator of the given type

Parametri

type

Separator::Horizonal or Separator::Vertical

UI\Controls\Separator
UI\Controls\Combo
UI\Controls\Separator


Combo Control

(PHP 7, UI 0.9.9)

Introducere

A Combo control represents a list of options, like the familiar select HTML element.

Sinopsisul clasei

UI\Controls\Combo extends UI\Control {
/* Metode */
public append ( string $text )
public integer getSelected ( void )
protected onSelected ( void )
public setSelected ( integer $index )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Cuprins

  • UI\Controls\Combo::append — Append Option
  • UI\Controls\Combo::getSelected — Get Selected Option
  • UI\Controls\Combo::onSelected — Selected Handler
  • UI\Controls\Combo::setSelected — Set Selected Option
UI\Controls\Separator::__construct
UI\Controls\Combo::append
UI


Append Option

UI\Controls\Combo
UI\Controls\Combo::getSelected
UI\Controls\Combo
PHP Manual

UI\Controls\Combo::append

(PHP 7, UI 0.9.9)

UI\Controls\Combo::append — Append Option

Descrierea

public UI\Controls\Combo::append ( string $text )

Append an option to this Combo

Parametri

text

The text for the new option

UI\Controls\Combo
UI\Controls\Combo::getSelected
UI\Controls\Combo


Get Selected Option

UI\Controls\Combo::append
UI\Controls\Combo::onSelected
UI\Controls\Combo
PHP Manual

UI\Controls\Combo::getSelected

(PHP 7, UI 0.9.9)

UI\Controls\Combo::getSelected — Get Selected Option

Descrierea

public integer UI\Controls\Combo::getSelected ( void )

Shall retrieve the index of the option selected in this Combo

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Combo::append
UI\Controls\Combo::onSelected
UI\Controls\Combo


Selected Handler

UI\Controls\Combo::getSelected
UI\Controls\Combo::setSelected
UI\Controls\Combo
PHP Manual

UI\Controls\Combo::onSelected

(PHP 7, UI 0.9.9)

UI\Controls\Combo::onSelected — Selected Handler

Descrierea

protected UI\Controls\Combo::onSelected ( void )

Shall be executed when an option is selected in this Combo

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Combo::getSelected
UI\Controls\Combo::setSelected
UI\Controls\Combo


Set Selected Option

UI\Controls\Combo::onSelected
UI\Controls\EditableCombo
UI\Controls\Combo
PHP Manual

UI\Controls\Combo::setSelected

(PHP 7, UI 0.9.9)

UI\Controls\Combo::setSelected — Set Selected Option

Descrierea

public UI\Controls\Combo::setSelected ( integer $index )

Shall set the currently selected option in this Combo

Parametri

index

The index of the option to select

UI\Controls\Combo::onSelected
UI\Controls\EditableCombo
UI\Controls\Combo


EdiableCombo Control

(PHP 7, UI 0.9.9)

Introducere

An Editable Combo is a Combo which allows the user to enter custom options

Sinopsisul clasei

UI\Controls\EditableCombo extends UI\Control {
/* Metode */
public append ( string $text )
public string getText ( void )
protected onChange ( void )
public setText ( string $text )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Cuprins

  • UI\Controls\EditableCombo::append — Append Option
  • UI\Controls\EditableCombo::getText — Get Text
  • UI\Controls\EditableCombo::onChange — Change Handler
  • UI\Controls\EditableCombo::setText — Set Text
UI\Controls\Combo::setSelected
UI\Controls\EditableCombo::append
UI


Append Option

UI\Controls\EditableCombo
UI\Controls\EditableCombo::getText
UI\Controls\EditableCombo
PHP Manual

UI\Controls\EditableCombo::append

(PHP 7, UI 0.9.9)

UI\Controls\EditableCombo::append — Append Option

Descrierea

public UI\Controls\EditableCombo::append ( string $text )

Shall append a new option to this Editable Combo

Parametri

text

The text for the new option

UI\Controls\EditableCombo
UI\Controls\EditableCombo::getText
UI\Controls\EditableCombo


Get Text

UI\Controls\EditableCombo::append
UI\Controls\EditableCombo::onChange
UI\Controls\EditableCombo
PHP Manual

UI\Controls\EditableCombo::getText

(PHP 7, UI 0.9.9)

UI\Controls\EditableCombo::getText — Get Text

Descrierea

public string UI\Controls\EditableCombo::getText ( void )

Get the value of the currently selected option in this Editable Combo

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\EditableCombo::append
UI\Controls\EditableCombo::onChange
UI\Controls\EditableCombo


Change Handler

UI\Controls\EditableCombo::getText
UI\Controls\EditableCombo::setText
UI\Controls\EditableCombo
PHP Manual

UI\Controls\EditableCombo::onChange

(PHP 7, UI 0.9.9)

UI\Controls\EditableCombo::onChange — Change Handler

Descrierea

protected UI\Controls\EditableCombo::onChange ( void )

Shall be executed when the value of this Editable Combobox changes

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\EditableCombo::getText
UI\Controls\EditableCombo::setText
UI\Controls\EditableCombo


Set Text

UI\Controls\EditableCombo::onChange
UI\Controls\Radio
UI\Controls\EditableCombo
PHP Manual

UI\Controls\EditableCombo::setText

(PHP 7, UI 0.9.9)

UI\Controls\EditableCombo::setText — Set Text

Descrierea

public UI\Controls\EditableCombo::setText ( string $text )

Shall set the text of the currently selected option in this Editable Combo

Parametri

text

The new text

UI\Controls\EditableCombo::onChange
UI\Controls\Radio
UI\Controls\EditableCombo


Radio Control

(PHP 7, UI 0.9.9)

Introducere

A Radio is similar to the radio input type familiar from HTML

Sinopsisul clasei

UI\Controls\Radio extends UI\Control {
/* Metode */
public append ( string $text )
public integer getSelected ( void )
protected onSelected ( void )
public setSelected ( integer $index )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Cuprins

  • UI\Controls\Radio::append — Append Option
  • UI\Controls\Radio::getSelected — Get Selected Option
  • UI\Controls\Radio::onSelected — Selected Handler
  • UI\Controls\Radio::setSelected — Set Selected Option
UI\Controls\EditableCombo::setText
UI\Controls\Radio::append
UI


Append Option

UI\Controls\Radio
UI\Controls\Radio::getSelected
UI\Controls\Radio
PHP Manual

UI\Controls\Radio::append

(PHP 7, UI 0.9.9)

UI\Controls\Radio::append — Append Option

Descrierea

public UI\Controls\Radio::append ( string $text )

Shall append a new option to this Radio

Parametri

text

The text (label) for the option

UI\Controls\Radio
UI\Controls\Radio::getSelected
UI\Controls\Radio


Get Selected Option

UI\Controls\Radio::append
UI\Controls\Radio::onSelected
UI\Controls\Radio
PHP Manual

UI\Controls\Radio::getSelected

(PHP 7, UI 0.9.9)

UI\Controls\Radio::getSelected — Get Selected Option

Descrierea

public integer UI\Controls\Radio::getSelected ( void )

Shall retrieve the index of the currently selected option in this Radio

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Radio::append
UI\Controls\Radio::onSelected
UI\Controls\Radio


Selected Handler

UI\Controls\Radio::getSelected
UI\Controls\Radio::setSelected
UI\Controls\Radio
PHP Manual

UI\Controls\Radio::onSelected

(PHP 7, UI 0.9.9)

UI\Controls\Radio::onSelected — Selected Handler

Descrierea

protected UI\Controls\Radio::onSelected ( void )

Shall be executed when the option selected in this Radio changes

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Radio::getSelected
UI\Controls\Radio::setSelected
UI\Controls\Radio


Set Selected Option

UI\Controls\Radio::onSelected
UI\Controls\Picker
UI\Controls\Radio
PHP Manual

UI\Controls\Radio::setSelected

(PHP 7, UI 0.9.9)

UI\Controls\Radio::setSelected — Set Selected Option

Descrierea

public UI\Controls\Radio::setSelected ( integer $index )

Shall set the currently selected option in this Radio

Parametri

index

The index of the option to select

UI\Controls\Radio::onSelected
UI\Controls\Picker
UI\Controls\Radio


Picker Control

(PHP 7, UI 0.9.9)

Introducere

A Picker represents a button which when clicked presents a native Date/Time/DateTime Picker interface to the user.

Sinopsisul clasei

UI\Controls\Picker extends UI\Control {
/* Constants */
const integer Date ;
const integer Time ;
const integer DateTime ;
/* Constructor */
public __construct ([ integer $type = UI\Controls\Picker::Date ] )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Constante predefinite

UI\Controls\Picker::Date

A Date Picker

UI\Controls\Picker::Time

A Time Picker

UI\Controls\Picker::DateTime

A Date and Time Picker

Cuprins

  • UI\Controls\Picker::__construct — Construct a new Picker
UI\Controls\Radio::setSelected
UI\Controls\Picker::__construct
UI


Construct a new Picker

UI\Controls\Picker
UI\Controls\Form
UI\Controls\Picker
PHP Manual

UI\Controls\Picker::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Picker::__construct — Construct a new Picker

Descrierea

public UI\Controls\Picker::__construct ([ integer $type = UI\Controls\Picker::Date ] )

Construct a new Picker of the given type

Parametri

type

Picker::Date, Picker::Time, or Picker::DateTime

UI\Controls\Picker
UI\Controls\Form
UI\Controls\Picker


Control Form (Arrangement)

(PHP 7, UI 0.9.9)

Introducere

A Form is a control which allows the arrangement of other controls into a familiar layout (the form).

Sinopsisul clasei

UI\Controls\Form extends UI\Control {
/* Proprieta?i */
protected $controls ;
/* Metode */
public integer append ( string $label , UI\Control $control [, boolean $stretchy = false ] )
public boolean delete ( integer $index )
public bool isPadded ( void )
public setPadded ( boolean $padded )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Proprieta?i

controls

Contains controls, should not be manipulated directly

Cuprins

  • UI\Controls\Form::append — Append Control
  • UI\Controls\Form::delete — Delete Control
  • UI\Controls\Form::isPadded — Padding Detection
  • UI\Controls\Form::setPadded — Set Padding
UI\Controls\Picker::__construct
UI\Controls\Form::append
UI


Append Control

UI\Controls\Form
UI\Controls\Form::delete
UI\Controls\Form
PHP Manual

UI\Controls\Form::append

(PHP 7, UI 0.9.9)

UI\Controls\Form::append — Append Control

Descrierea

public integer UI\Controls\Form::append ( string $label , UI\Control $control [, boolean $stretchy = false ] )

Shall append the control to the form, and set the label

Parametri

label

The text for the label

control

A control

stretchy

Should be set true to stretch the control

Valorile întoarse

Shall return the index of the appended control, may be 0

UI\Controls\Form
UI\Controls\Form::delete
UI\Controls\Form


Delete Control

UI\Controls\Form::append
UI\Controls\Form::isPadded
UI\Controls\Form
PHP Manual

UI\Controls\Form::delete

(PHP 7, UI 0.9.9)

UI\Controls\Form::delete — Delete Control

Descrierea

public boolean UI\Controls\Form::delete ( integer $index )

Shall delete the control at the given index in this Form

Parametri

index

The index of the control to remove

Valorile întoarse

Indication of succcess

UI\Controls\Form::append
UI\Controls\Form::isPadded
UI\Controls\Form


Padding Detection

UI\Controls\Form::delete
UI\Controls\Form::setPadded
UI\Controls\Form
PHP Manual

UI\Controls\Form::isPadded

(PHP 7, UI 0.9.9)

UI\Controls\Form::isPadded — Padding Detection

Descrierea

public bool UI\Controls\Form::isPadded ( void )

Shall detect if padding is enabled on this Form

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Form::delete
UI\Controls\Form::setPadded
UI\Controls\Form


Set Padding

UI\Controls\Form::isPadded
UI\Controls\Grid
UI\Controls\Form
PHP Manual

UI\Controls\Form::setPadded

(PHP 7, UI 0.9.9)

UI\Controls\Form::setPadded — Set Padding

Descrierea

public UI\Controls\Form::setPadded ( boolean $padded )

Shall enable or disable padding on this Form

Parametri

padded

UI\Controls\Form::isPadded
UI\Controls\Grid
UI\Controls\Form


Control Grid (Arrangement)

(PHP 7, UI 0.9.9)

Introducere

A Grid is a control which is allows the arrangement of children into a grid

Sinopsisul clasei

UI\Controls\Grid extends UI\Control {
/* Constants */
const integer Fill ;
const integer Start ;
const integer Center ;
const integer End ;
const integer Leading ;
const integer Top ;
const integer Trailing ;
const integer Bottom ;
/* Proprieta?i */
protected $controls ;
/* Metode */
public append ( UI\Control $control , integer $left , integer $top , integer $xspan , integer $yspan , boolean $hexpand , integer $halign , boolean $vexpand , integer $valign )
public bool isPadded ( void )
public setPadded ( boolean $padding )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Constante predefinite

UI\Controls\Grid::Fill

UI\Controls\Grid::Start

UI\Controls\Grid::Center

UI\Controls\Grid::End

UI\Controls\Grid::Leading

UI\Controls\Grid::Top

UI\Controls\Grid::Trailing

UI\Controls\Grid::Bottom

Proprieta?i

controls

Contains controls, should not be manipulated directly

Cuprins

  • UI\Controls\Grid::append — Append Control
  • UI\Controls\Grid::isPadded — Padding Detection
  • UI\Controls\Grid::setPadded — Set Padding
UI\Controls\Form::setPadded
UI\Controls\Grid::append
UI


Append Control

UI\Controls\Grid
UI\Controls\Grid::isPadded
UI\Controls\Grid
PHP Manual

UI\Controls\Grid::append

(PHP 7, UI 0.9.9)

UI\Controls\Grid::append — Append Control

Descrierea

public UI\Controls\Grid::append ( UI\Control $control , integer $left , integer $top , integer $xspan , integer $yspan , boolean $hexpand , integer $halign , boolean $vexpand , integer $valign )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

control

The Control to append

left

top

xspan

yspan

hexpand

halign

vexpand

valign

Valorile întoarse

UI\Controls\Grid
UI\Controls\Grid::isPadded
UI\Controls\Grid


Padding Detection

UI\Controls\Grid::append
UI\Controls\Grid::setPadded
UI\Controls\Grid
PHP Manual

UI\Controls\Grid::isPadded

(PHP 7, UI 0.9.9)

UI\Controls\Grid::isPadded — Padding Detection

Descrierea

public bool UI\Controls\Grid::isPadded ( void )

Shall detect if padding is enabled on this Grid

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Grid::append
UI\Controls\Grid::setPadded
UI\Controls\Grid


Set Padding

UI\Controls\Grid::isPadded
UI\Controls\Group
UI\Controls\Grid
PHP Manual

UI\Controls\Grid::setPadded

(PHP 7, UI 0.9.9)

UI\Controls\Grid::setPadded — Set Padding

Descrierea

public UI\Controls\Grid::setPadded ( boolean $padding )

Shall enable or disable padding for this Grid

Parametri

padding

UI\Controls\Grid::isPadded
UI\Controls\Group
UI\Controls\Grid


Control Group (Arrangement)

(PHP 7, UI 0.9.9)

Introducere

A Group is a titled container for child controls

Sinopsisul clasei

UI\Controls\Group extends UI\Control {
/* Proprieta?i */
protected $controls ;
/* Constructor */
public __construct ( string $title )
/* Metode */
public append ( UI\Control $control )
public string getTitle ( void )
public bool hasMargin ( void )
public setMargin ( boolean $margin )
public setTitle ( string $title )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Proprieta?i

controls

Contains controls, should not be manipulated directly

Cuprins

  • UI\Controls\Group::append — Append Control
  • UI\Controls\Group::__construct — Construct a new Group
  • UI\Controls\Group::getTitle — Get Title
  • UI\Controls\Group::hasMargin — Margin Detection
  • UI\Controls\Group::setMargin — Set Margin
  • UI\Controls\Group::setTitle — Set Title
UI\Controls\Grid::setPadded
UI\Controls\Group::append
UI


Append Control

UI\Controls\Group
UI\Controls\Group::__construct
UI\Controls\Group
PHP Manual

UI\Controls\Group::append

(No version information available, might only be in Git)

UI\Controls\Group::append — Append Control

Descrierea

public UI\Controls\Group::append ( UI\Control $control )

Shall append a control to this Group

Parametri

control

The control to append

UI\Controls\Group
UI\Controls\Group::__construct
UI\Controls\Group


Construct a new Group

UI\Controls\Group::append
UI\Controls\Group::getTitle
UI\Controls\Group
PHP Manual

UI\Controls\Group::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Group::__construct — Construct a new Group

Descrierea

public UI\Controls\Group::__construct ( string $title )

Shall construct a new Group with the given title

Parametri

title

The text for the title label

UI\Controls\Group::append
UI\Controls\Group::getTitle
UI\Controls\Group


Get Title

UI\Controls\Group::__construct
UI\Controls\Group::hasMargin
UI\Controls\Group
PHP Manual

UI\Controls\Group::getTitle

(PHP 7, UI 0.9.9)

UI\Controls\Group::getTitle — Get Title

Descrierea

public string UI\Controls\Group::getTitle ( void )

Shall return the current title for this Group

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current title

UI\Controls\Group::__construct
UI\Controls\Group::hasMargin
UI\Controls\Group


Margin Detection

UI\Controls\Group::getTitle
UI\Controls\Group::setMargin
UI\Controls\Group
PHP Manual

UI\Controls\Group::hasMargin

(PHP 7, UI 0.9.9)

UI\Controls\Group::hasMargin — Margin Detection

Descrierea

public bool UI\Controls\Group::hasMargin ( void )

Shall detect if this Group has a margin

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Group::getTitle
UI\Controls\Group::setMargin
UI\Controls\Group


Set Margin

UI\Controls\Group::hasMargin
UI\Controls\Group::setTitle
UI\Controls\Group
PHP Manual

UI\Controls\Group::setMargin

(PHP 7, UI 0.9.9)

UI\Controls\Group::setMargin — Set Margin

Descrierea

public UI\Controls\Group::setMargin ( boolean $margin )

Shall enable or disable margins for this Group

Parametri

margin

UI\Controls\Group::hasMargin
UI\Controls\Group::setTitle
UI\Controls\Group


Set Title

UI\Controls\Group::setMargin
UI\Controls\Box
UI\Controls\Group
PHP Manual

UI\Controls\Group::setTitle

(PHP 7, UI 0.9.9)

UI\Controls\Group::setTitle — Set Title

Descrierea

public UI\Controls\Group::setTitle ( string $title )

Shall set the title for this Group

Parametri

title

The text for the new title

UI\Controls\Group::setMargin
UI\Controls\Box
UI\Controls\Group


Control Box (Arrangement)

(PHP 7, UI 0.9.9)

Introducere

A Box allows the arrangement of other controls

Sinopsisul clasei

UI\Controls\Box extends UI\Control {
/* Constants */
const integer Vertical ;
const integer Horizontal ;
/* Proprieta?i */
protected $controls ;
/* Constructor */
public __construct ([ integer $orientation = UI\Controls\Box::Horizontal ] )
/* Metode */
public integer append ( Control $control [, boolean $stretchy = false ] )
public boolean delete ( integer $index )
public integer getOrientation ( void )
public bool isPadded ( void )
public setPadded ( boolean $padded )
/* Metode mo?tenite */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control UI\Control::getParent ( void )
public int UI\Control::getTopLevel ( void )
public UI\Control::hide ( void )
public bool UI\Control::isEnabled ( void )
public bool UI\Control::isVisible ( void )
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Proprieta?i

controls

Contains controls, should not be manipulated directly

Constante predefinite

UI\Controls\Box::Vertical

UI\Controls\Box::Horizontal

Cuprins

  • UI\Controls\Box::append — Append Control
  • UI\Controls\Box::__construct — Construct a new Box
  • UI\Controls\Box::delete — Delete Control
  • UI\Controls\Box::getOrientation — Get Orientation
  • UI\Controls\Box::isPadded — Padding Detection
  • UI\Controls\Box::setPadded — Set Padding
UI\Controls\Group::setTitle
UI\Controls\Box::append
UI


Append Control

UI\Controls\Box
UI\Controls\Box::__construct
UI\Controls\Box
PHP Manual

UI\Controls\Box::append

(PHP 7, UI 0.9.9)

UI\Controls\Box::append — Append Control

Descrierea

public integer UI\Controls\Box::append ( Control $control [, boolean $stretchy = false ] )

Shall append the given control to this Box

Parametri

control

The control to append

stretchy

Set true to stretch the control

Valorile întoarse

Shall return the index of the appended control, may be 0

UI\Controls\Box
UI\Controls\Box::__construct
UI\Controls\Box


Construct a new Box

UI\Controls\Box::append
UI\Controls\Box::delete
UI\Controls\Box
PHP Manual

UI\Controls\Box::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Box::__construct — Construct a new Box

Descrierea

public UI\Controls\Box::__construct ([ integer $orientation = UI\Controls\Box::Horizontal ] )

Shall construct a new box

Parametri

orientation

Box::Horizontal or Box::Vertical

UI\Controls\Box::append
UI\Controls\Box::delete
UI\Controls\Box


Delete Control

UI\Controls\Box::__construct
UI\Controls\Box::getOrientation
UI\Controls\Box
PHP Manual

UI\Controls\Box::delete

(PHP 7, UI 0.9.9)

UI\Controls\Box::delete — Delete Control

Descrierea

public boolean UI\Controls\Box::delete ( integer $index )

Shall delete the control at the given index from this Box

Parametri

index

The index of the control to delete

Valorile întoarse

Indication of success

UI\Controls\Box::__construct
UI\Controls\Box::getOrientation
UI\Controls\Box


Get Orientation

UI\Controls\Box::delete
UI\Controls\Box::isPadded
UI\Controls\Box
PHP Manual

UI\Controls\Box::getOrientation

(PHP 7, UI 0.9.9)

UI\Controls\Box::getOrientation — Get Orientation

Descrierea

public integer UI\Controls\Box::getOrientation ( void )

Shall retrieve the orientation of this Box

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Box::delete
UI\Controls\Box::isPadded
UI\Controls\Box


Padding Detection

UI\Controls\Box::getOrientation
UI\Controls\Box::setPadded
UI\Controls\Box
PHP Manual

UI\Controls\Box::isPadded

(PHP 7, UI 0.9.9)

UI\Controls\Box::isPadded — Padding Detection

Descrierea

public bool UI\Controls\Box::isPadded ( void )

Shall detect if padding is enabled on this Box

Parametri

Aceasta func?ie nu are parametri.

UI\Controls\Box::getOrientation
UI\Controls\Box::setPadded
UI\Controls\Box


Set Padding

UI\Controls\Box::isPadded
UI\Draw\Pen
UI\Controls\Box
PHP Manual

UI\Controls\Box::setPadded

(PHP 7, UI 0.9.9)

UI\Controls\Box::setPadded — Set Padding

Descrierea

public UI\Controls\Box::setPadded ( boolean $padded )

Shall enable or disable padding on this Box

Parametri

padded

UI\Controls\Box::isPadded
UI\Draw\Pen
UI\Controls\Box


Draw Pen

(PHP 7, UI 0.9.9)

Introducere

The Pen is passed to the Area Draw event handler, it is used for clipping, filling, stroking, and writing to Draw Paths.

Sinopsisul clasei

final UI\Draw\Pen {
/* Metode */
public clip ( UI\Draw\Path $path )
public fill ( UI\Draw\Path $path , UI\Draw\Brush $with )
public fill ( UI\Draw\Path $path , UI\Draw\Color $with )
public fill ( UI\Draw\Path $path , integer $with )
public restore ( void )
public save ( void )
public stroke ( UI\Draw\Path $path , UI\Draw\Brush $with , UI\Draw\Stroke $stroke )
public stroke ( UI\Draw\Path $path , UI\Draw\Color $with , UI\Draw\Stroke $stroke )
public stroke ( UI\Draw\Path $path , integer $with , UI\Draw\Stroke $stroke )
public transform ( UI\Draw\Matrix $matrix )
public write ( UI\Point $point , UI\Draw\Text\Layout $layout )
}

Cuprins

  • UI\Draw\Pen::clip — Clip a Path
  • UI\Draw\Pen::fill — Fill a Path
  • UI\Draw\Pen::restore — Restore
  • UI\Draw\Pen::save — Save
  • UI\Draw\Pen::stroke — Stroke a Path
  • UI\Draw\Pen::transform — Matrix Transform
  • UI\Draw\Pen::write — Draw Text at Point
UI\Controls\Box::setPadded
UI\Draw\Pen::clip
UI


Clip a Path

UI\Draw\Pen
UI\Draw\Pen::fill
UI\Draw\Pen
PHP Manual

UI\Draw\Pen::clip

(PHP 7, UI 0.9.9)

UI\Draw\Pen::clip — Clip a Path

Descrierea

public UI\Draw\Pen::clip ( UI\Draw\Path $path )

Shall clip the given Path

Parametri

path

The path to clip

UI\Draw\Pen
UI\Draw\Pen::fill
UI\Draw\Pen


Fill a Path

UI\Draw\Pen::clip
UI\Draw\Pen::restore
UI\Draw\Pen
PHP Manual

UI\Draw\Pen::fill

(PHP 7, UI 0.9.9)

UI\Draw\Pen::fill — Fill a Path

Descrierea

public UI\Draw\Pen::fill ( UI\Draw\Path $path , UI\Draw\Brush $with )
public UI\Draw\Pen::fill ( UI\Draw\Path $path , UI\Draw\Color $with )
public UI\Draw\Pen::fill ( UI\Draw\Path $path , integer $with )

Shall fill the given path

Parametri

path

The path to fill

with

The color or brush to fill with

UI\Draw\Pen::clip
UI\Draw\Pen::restore
UI\Draw\Pen


Restore

UI\Draw\Pen::fill
UI\Draw\Pen::save
UI\Draw\Pen
PHP Manual

UI\Draw\Pen::restore

(PHP 7, UI 0.9.9)

UI\Draw\Pen::restore — Restore

Descrierea

public UI\Draw\Pen::restore ( void )

Shall restore a previously saved Pen

Parametri

Aceasta func?ie nu are parametri.

UI\Draw\Pen::fill
UI\Draw\Pen::save
UI\Draw\Pen


Save

UI\Draw\Pen::restore
UI\Draw\Pen::stroke
UI\Draw\Pen
PHP Manual

UI\Draw\Pen::save

(PHP 7, UI 0.9.9)

UI\Draw\Pen::save — Save

Descrierea

public UI\Draw\Pen::save ( void )

Shall save the Pen

Parametri

Aceasta func?ie nu are parametri.

UI\Draw\Pen::restore
UI\Draw\Pen::stroke
UI\Draw\Pen


Stroke a Path

UI\Draw\Pen::save
UI\Draw\Pen::transform
UI\Draw\Pen
PHP Manual

UI\Draw\Pen::stroke

(PHP 7, UI 0.9.9)

UI\Draw\Pen::stroke — Stroke a Path

Descrierea

public UI\Draw\Pen::stroke ( UI\Draw\Path $path , UI\Draw\Brush $with , UI\Draw\Stroke $stroke )
public UI\Draw\Pen::stroke ( UI\Draw\Path $path , UI\Draw\Color $with , UI\Draw\Stroke $stroke )
public UI\Draw\Pen::stroke ( UI\Draw\Path $path , integer $with , UI\Draw\Stroke $stroke )

Shall stroke the given path

Parametri

path

The path to stroke

with

The color or brush to stroke with

stroke

The configuration of the stroke

UI\Draw\Pen::save
UI\Draw\Pen::transform
UI\Draw\Pen


Matrix Transform

UI\Draw\Pen::stroke
UI\Draw\Pen::write
UI\Draw\Pen
PHP Manual

UI\Draw\Pen::transform

(PHP 7, UI 0.9.9)

UI\Draw\Pen::transform — Matrix Transform

Descrierea

public UI\Draw\Pen::transform ( UI\Draw\Matrix $matrix )

Shall perform matrix transformation

Parametri

matrix

The matrix to use

UI\Draw\Pen::stroke
UI\Draw\Pen::write
UI\Draw\Pen


Draw Text at Point

UI\Draw\Pen::transform
UI\Draw\Path
UI\Draw\Pen
PHP Manual

UI\Draw\Pen::write

(PHP 7, UI 0.9.9)

UI\Draw\Pen::write — Draw Text at Point

Descrierea

public UI\Draw\Pen::write ( UI\Point $point , UI\Draw\Text\Layout $layout )

Shall draw the given text layout at the given point

Parametri

point

The point to perform the drawing

layout

The layout of the text to draw

UI\Draw\Pen::transform
UI\Draw\Path
UI\Draw\Pen


Draw Path

(PHP 7, UI 0.9.9)

Introducere

A Draw Path guides a Draw Pen, telling the Pen where to draw on an Area.

Sinopsisul clasei

UI\Draw\Path {
/* Constants */
const integer Winding ;
const integer Alternate ;
/* Constructor */
public __construct ([ integer $mode = UI\Draw\Path::Winding ] )
/* Metode */
public addRectangle ( UI\Point $point , UI\Size $size )
public arcTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )
public bezierTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )
public closeFigure ( void )
public end ( void )
public lineTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )
public newFigure ( UI\Point $point )
public newFigureWithArc ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )
}

Constante predefinite

UI\Draw\Path::Winding

This is the default draw path mode

UI\Draw\Path::Alternate

This is the alternate draw path mode

Cuprins

  • UI\Draw\Path::addRectangle — Draw a Rectangle
  • UI\Draw\Path::arcTo — Draw an Arc
  • UI\Draw\Path::bezierTo — Draw Bezier Curve
  • UI\Draw\Path::closeFigure — Close Figure
  • UI\Draw\Path::__construct — Construct a new Path
  • UI\Draw\Path::end — Finalize Path
  • UI\Draw\Path::lineTo — Draw a Line
  • UI\Draw\Path::newFigure — Draw Figure
  • UI\Draw\Path::newFigureWithArc — Draw Figure with Arc
UI\Draw\Pen::write
UI\Draw\Path::addRectangle
UI


Draw a Rectangle

UI\Draw\Path
UI\Draw\Path::arcTo
UI\Draw\Path
PHP Manual

UI\Draw\Path::addRectangle

(PHP 7, UI 0.9.9)

UI\Draw\Path::addRectangle — Draw a Rectangle

Descrierea

public UI\Draw\Path::addRectangle ( UI\Point $point , UI\Size $size )

Shall map the path of a rectangle of the given size, at the given point

Parametri

point

The point to begin the shape

size

The size of the rectangle

UI\Draw\Path
UI\Draw\Path::arcTo
UI\Draw\Path


Draw an Arc

UI\Draw\Path::addRectangle
UI\Draw\Path::bezierTo
UI\Draw\Path
PHP Manual

UI\Draw\Path::arcTo

(PHP 7, UI 0.9.9)

UI\Draw\Path::arcTo — Draw an Arc

Descrierea

public UI\Draw\Path::arcTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Shall map the path for an arc

Parametri

point

The point to begin mapping

radius

The radius of the arc

angle

The angle of the arc

sweep

The sweep of the arc

negative

Valorile întoarse

UI\Draw\Path::addRectangle
UI\Draw\Path::bezierTo
UI\Draw\Path


Draw Bezier Curve

UI\Draw\Path::arcTo
UI\Draw\Path::closeFigure
UI\Draw\Path
PHP Manual

UI\Draw\Path::bezierTo

(PHP 7, UI 0.9.9)

UI\Draw\Path::bezierTo — Draw Bezier Curve

Descrierea

public UI\Draw\Path::bezierTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Shall draw a bezier curve

Parametri

point

The point at which to begin mapping

radius

The radius of the curve

angle

The angle of the curve

sweep

The sweep of the curve

negative

UI\Draw\Path::arcTo
UI\Draw\Path::closeFigure
UI\Draw\Path


Close Figure

UI\Draw\Path::bezierTo
UI\Draw\Path::__construct
UI\Draw\Path
PHP Manual

UI\Draw\Path::closeFigure

(PHP 7, UI 0.9.9)

UI\Draw\Path::closeFigure — Close Figure

Descrierea

public UI\Draw\Path::closeFigure ( void )

Shall close the current figure

Parametri

Aceasta func?ie nu are parametri.

UI\Draw\Path::bezierTo
UI\Draw\Path::__construct
UI\Draw\Path


Construct a new Path

UI\Draw\Path::closeFigure
UI\Draw\Path::end
UI\Draw\Path
PHP Manual

UI\Draw\Path::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Path::__construct — Construct a new Path

Descrierea

public UI\Draw\Path::__construct ([ integer $mode = UI\Draw\Path::Winding ] )

Shall construct a new path in the given mode

Parametri

mode

Path::Winding or Path::Alternate

UI\Draw\Path::closeFigure
UI\Draw\Path::end
UI\Draw\Path


Finalize Path

UI\Draw\Path::__construct
UI\Draw\Path::lineTo
UI\Draw\Path
PHP Manual

UI\Draw\Path::end

(PHP 7, UI 0.9.9)

UI\Draw\Path::end — Finalize Path

Descrierea

public UI\Draw\Path::end ( void )

Shall finalize this Path

Parametri

Aceasta func?ie nu are parametri.

UI\Draw\Path::__construct
UI\Draw\Path::lineTo
UI\Draw\Path


Draw a Line

UI\Draw\Path::end
UI\Draw\Path::newFigure
UI\Draw\Path
PHP Manual

UI\Draw\Path::lineTo

(PHP 7, UI 0.9.9)

UI\Draw\Path::lineTo — Draw a Line

Descrierea

public UI\Draw\Path::lineTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Shall map the path for a line

Parametri

point

The point to begin mapping

radius

angle

sweep

negative

Valorile întoarse

UI\Draw\Path::end
UI\Draw\Path::newFigure
UI\Draw\Path


Draw Figure

UI\Draw\Path::lineTo
UI\Draw\Path::newFigureWithArc
UI\Draw\Path
PHP Manual

UI\Draw\Path::newFigure

(PHP 7, UI 0.9.9)

UI\Draw\Path::newFigure — Draw Figure

Descrierea

public UI\Draw\Path::newFigure ( UI\Point $point )

Shall map a new figure at the given point

Parametri

point

The point to begin mapping

UI\Draw\Path::lineTo
UI\Draw\Path::newFigureWithArc
UI\Draw\Path


Draw Figure with Arc

UI\Draw\Path::newFigure
UI\Draw\Matrix
UI\Draw\Path
PHP Manual

UI\Draw\Path::newFigureWithArc

(PHP 7, UI 0.9.9)

UI\Draw\Path::newFigureWithArc — Draw Figure with Arc

Descrierea

public UI\Draw\Path::newFigureWithArc ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Parametri

point

radius

angle

sweep

negative

Valorile întoarse

UI\Draw\Path::newFigure
UI\Draw\Matrix
UI\Draw\Path


Draw Matrix

(PHP 7, UI 0.9.9)

Introducere

Sinopsisul clasei

UI\Draw\Matrix {
/* Metode */
public invert ( void )
public bool isInvertible ( void )
public UI\Draw\Matrix multiply ( UI\Draw\Matrix $matrix )
public rotate ( UI\Point $point , float $amount )
public scale ( UI\Point $center , UI\Point $point )
public skew ( UI\Point $point , UI\Point $amount )
public translate ( UI\Point $point )
}

Cuprins

  • UI\Draw\Matrix::invert — Invert Matrix
  • UI\Draw\Matrix::isInvertible — Invertible Detection
  • UI\Draw\Matrix::multiply — Multiply Matrix
  • UI\Draw\Matrix::rotate — Rotate Matrix
  • UI\Draw\Matrix::scale — Scale Matrix
  • UI\Draw\Matrix::skew — Skew Matrix
  • UI\Draw\Matrix::translate — Translate Matrix
UI\Draw\Path::newFigureWithArc
UI\Draw\Matrix::invert
UI


Invert Matrix

UI\Draw\Matrix
UI\Draw\Matrix::isInvertible
UI\Draw\Matrix
PHP Manual

UI\Draw\Matrix::invert

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::invert — Invert Matrix

Descrierea

public UI\Draw\Matrix::invert ( void )

Shall invert this matrix

Parametri

Aceasta func?ie nu are parametri.

UI\Draw\Matrix
UI\Draw\Matrix::isInvertible
UI\Draw\Matrix


Invertible Detection

UI\Draw\Matrix::invert
UI\Draw\Matrix::multiply
UI\Draw\Matrix
PHP Manual

UI\Draw\Matrix::isInvertible

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::isInvertible — Invertible Detection

Descrierea

public bool UI\Draw\Matrix::isInvertible ( void )

Shall detect if this Matrix may be inverted

Parametri

Aceasta func?ie nu are parametri.

UI\Draw\Matrix::invert
UI\Draw\Matrix::multiply
UI\Draw\Matrix


Multiply Matrix

UI\Draw\Matrix::isInvertible
UI\Draw\Matrix::rotate
UI\Draw\Matrix
PHP Manual

UI\Draw\Matrix::multiply

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::multiply — Multiply Matrix

Descrierea

public UI\Draw\Matrix UI\Draw\Matrix::multiply ( UI\Draw\Matrix $matrix )

Shall multiply this matrix with the given matrix

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The new Matrix

UI\Draw\Matrix::isInvertible
UI\Draw\Matrix::rotate
UI\Draw\Matrix


Rotate Matrix

UI\Draw\Matrix::multiply
UI\Draw\Matrix::scale
UI\Draw\Matrix
PHP Manual

UI\Draw\Matrix::rotate

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::rotate — Rotate Matrix

Descrierea

public UI\Draw\Matrix::rotate ( UI\Point $point , float $amount )

Shall rotate this Matrix

Parametri

point

amount

UI\Draw\Matrix::multiply
UI\Draw\Matrix::scale
UI\Draw\Matrix


Scale Matrix

UI\Draw\Matrix::rotate
UI\Draw\Matrix::skew
UI\Draw\Matrix
PHP Manual

UI\Draw\Matrix::scale

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::scale — Scale Matrix

Descrierea

public UI\Draw\Matrix::scale ( UI\Point $center , UI\Point $point )

Shall scale this Matrix

Parametri

center

point

UI\Draw\Matrix::rotate
UI\Draw\Matrix::skew
UI\Draw\Matrix


Skew Matrix

UI\Draw\Matrix::scale
UI\Draw\Matrix::translate
UI\Draw\Matrix
PHP Manual

UI\Draw\Matrix::skew

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::skew — Skew Matrix

Descrierea

public UI\Draw\Matrix::skew ( UI\Point $point , UI\Point $amount )

Shall skew this Matrix

Parametri

point

amount

UI\Draw\Matrix::scale
UI\Draw\Matrix::translate
UI\Draw\Matrix


Translate Matrix

UI\Draw\Matrix::skew
UI\Draw\Color
UI\Draw\Matrix
PHP Manual

UI\Draw\Matrix::translate

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::translate — Translate Matrix

Descrierea

public UI\Draw\Matrix::translate ( UI\Point $point )

Shall translate this Matrix

Parametri

point

UI\Draw\Matrix::skew
UI\Draw\Color
UI\Draw\Matrix


Color Representation

(PHP 7, UI 0.9.9)

Introducere

Represents RGBA colours, individual channels are accessible via public properties.

Sinopsisul clasei

UI\Draw\Color {
/* Constants */
const integer Red ;
const integer Green ;
const integer Blue ;
const integer Alpha ;
/* Proprieta?i */
public $r ;
public $g ;
public $b ;
public $a ;
/* Constructor */
public __construct ([ UI\Draw\Color $color ] )
public __construct ([ integer $color ] )
/* Metode */
public float getChannel ( integer $channel )
public void setChannel ( integer $channel , float $value )
}

Proprieta?i

r

Provides access to the red channel

g

Provides access to the green channel

b

Provides access to the blue channel

a

Provides access to the alpha channel

Constante predefinite

UI\Draw\Color::Red

Identifies the red channel

UI\Draw\Color::Green

Identifies the green channel

UI\Draw\Color::Blue

Identifies the blue channel

UI\Draw\Color::Alpha

Identifies the alpha channel

Cuprins

  • UI\Draw\Color::__construct — Construct new Color
  • UI\Draw\Color::getChannel — Color Manipulation
  • UI\Draw\Color::setChannel — Color Manipulation
UI\Draw\Matrix::translate
UI\Draw\Color::__construct
UI


Construct new Color

UI\Draw\Color
UI\Draw\Color::getChannel
UI\Draw\Color
PHP Manual

UI\Draw\Color::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Color::__construct — Construct new Color

Descrierea

public UI\Draw\Color::__construct ([ UI\Draw\Color $color ] )
public UI\Draw\Color::__construct ([ integer $color ] )

Shall construct a new color

Parametri

color

May be UI\Draw\Color or RRGGBBAA

UI\Draw\Color
UI\Draw\Color::getChannel
UI\Draw\Color


Color Manipulation

UI\Draw\Color::__construct
UI\Draw\Color::setChannel
UI\Draw\Color
PHP Manual

UI\Draw\Color::getChannel

(PHP 7, UI 0.9.9)

UI\Draw\Color::getChannel — Color Manipulation

Descrierea

public float UI\Draw\Color::getChannel ( integer $channel )

Shall retrieve the value for a channel

Parametri

channel

Constant channel identity

Valorile întoarse

The current value of the requested channel

UI\Draw\Color::__construct
UI\Draw\Color::setChannel
UI\Draw\Color


Color Manipulation

UI\Draw\Color::getChannel
UI\Draw\Stroke
UI\Draw\Color
PHP Manual

UI\Draw\Color::setChannel

(PHP 7, UI 0.9.9)

UI\Draw\Color::setChannel — Color Manipulation

Descrierea

public void UI\Draw\Color::setChannel ( integer $channel , float $value )

Shall set the selected channel to the given value

Parametri

channel

Constant channel identity

value

The new value for the selected channel

Valorile întoarse

UI\Draw\Color::getChannel
UI\Draw\Stroke
UI\Draw\Color


Draw Stroke

(PHP 7, UI 0.9.9)

Introducere

Holds the configuration for the Pen to perform a stroke

Sinopsisul clasei

UI\Draw\Stroke {
/* Constructor */
public __construct ([ integer $cap = UI\Draw\Line\Cap::Flat [, integer $join = UI\Draw\Line\Join::Miter [, float $thickness = 1 [, float $miterLimit = 10 ]]]] )
/* Metode */
public integer getCap ( void )
public integer getJoin ( void )
public float getMiterLimit ( void )
public float getThickness ( void )
public setCap ( integer $cap )
public setJoin ( integer $join )
public setMiterLimit ( float $limit )
public setThickness ( float $thickness )
}

Cuprins

  • UI\Draw\Stroke::__construct — Construct a new Stroke
  • UI\Draw\Stroke::getCap — Get Line Cap
  • UI\Draw\Stroke::getJoin — Get Line Join
  • UI\Draw\Stroke::getMiterLimit — Get Miter Limit
  • UI\Draw\Stroke::getThickness — Get Thickness
  • UI\Draw\Stroke::setCap — Set Line Cap
  • UI\Draw\Stroke::setJoin — Set Line Join
  • UI\Draw\Stroke::setMiterLimit — Set Miter Limit
  • UI\Draw\Stroke::setThickness — Set Thickness
UI\Draw\Color::setChannel
UI\Draw\Stroke::__construct
UI


Construct a new Stroke

UI\Draw\Stroke
UI\Draw\Stroke::getCap
UI\Draw\Stroke
PHP Manual

UI\Draw\Stroke::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::__construct — Construct a new Stroke

Descrierea

public UI\Draw\Stroke::__construct ([ integer $cap = UI\Draw\Line\Cap::Flat [, integer $join = UI\Draw\Line\Join::Miter [, float $thickness = 1 [, float $miterLimit = 10 ]]]] )

Shall construct a new Stroke

Parametri

cap

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

thickness

The thickness of the stroke

miterLimit

Miter limit (default is sensible for all supported platforms)

UI\Draw\Stroke
UI\Draw\Stroke::getCap
UI\Draw\Stroke


Get Line Cap

UI\Draw\Stroke::__construct
UI\Draw\Stroke::getJoin
UI\Draw\Stroke
PHP Manual

UI\Draw\Stroke::getCap

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::getCap — Get Line Cap

Descrierea

public integer UI\Draw\Stroke::getCap ( void )

Shall retrieve the line cap setting of this Stroke

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square

UI\Draw\Stroke::__construct
UI\Draw\Stroke::getJoin
UI\Draw\Stroke


Get Line Join

UI\Draw\Stroke::getCap
UI\Draw\Stroke::getMiterLimit
UI\Draw\Stroke
PHP Manual

UI\Draw\Stroke::getJoin

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::getJoin — Get Line Join

Descrierea

public integer UI\Draw\Stroke::getJoin ( void )

Shall retrieve the line join setting of this Stroke

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

UI\Draw\Stroke::getCap
UI\Draw\Stroke::getMiterLimit
UI\Draw\Stroke


Get Miter Limit

UI\Draw\Stroke::getJoin
UI\Draw\Stroke::getThickness
UI\Draw\Stroke
PHP Manual

UI\Draw\Stroke::getMiterLimit

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::getMiterLimit — Get Miter Limit

Descrierea

public float UI\Draw\Stroke::getMiterLimit ( void )

Shall retrieve the miter limit of this Stroke

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current miter limit

UI\Draw\Stroke::getJoin
UI\Draw\Stroke::getThickness
UI\Draw\Stroke


Get Thickness

UI\Draw\Stroke::getMiterLimit
UI\Draw\Stroke::setCap
UI\Draw\Stroke
PHP Manual

UI\Draw\Stroke::getThickness

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::getThickness — Get Thickness

Descrierea

public float UI\Draw\Stroke::getThickness ( void )

Shall retrieve the thickness of this Stroke

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current thickness

UI\Draw\Stroke::getMiterLimit
UI\Draw\Stroke::setCap
UI\Draw\Stroke


Set Line Cap

UI\Draw\Stroke::getThickness
UI\Draw\Stroke::setJoin
UI\Draw\Stroke
PHP Manual

UI\Draw\Stroke::setCap

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::setCap — Set Line Cap

Descrierea

public UI\Draw\Stroke::setCap ( integer $cap )

Shall set the line cap setting for this Stroke

Parametri

cap

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square

UI\Draw\Stroke::getThickness
UI\Draw\Stroke::setJoin
UI\Draw\Stroke


Set Line Join

UI\Draw\Stroke::setCap
UI\Draw\Stroke::setMiterLimit
UI\Draw\Stroke
PHP Manual

UI\Draw\Stroke::setJoin

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::setJoin — Set Line Join

Descrierea

public UI\Draw\Stroke::setJoin ( integer $join )

Shall set the line join setting for this Stroke

Parametri

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

Valorile întoarse

UI\Draw\Stroke::setCap
UI\Draw\Stroke::setMiterLimit
UI\Draw\Stroke


Set Miter Limit

UI\Draw\Stroke::setJoin
UI\Draw\Stroke::setThickness
UI\Draw\Stroke
PHP Manual

UI\Draw\Stroke::setMiterLimit

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::setMiterLimit — Set Miter Limit

Descrierea

public UI\Draw\Stroke::setMiterLimit ( float $limit )

Set the miter limit for this Stroke

Parametri

limit

The new limit

UI\Draw\Stroke::setJoin
UI\Draw\Stroke::setThickness
UI\Draw\Stroke


Set Thickness

UI\Draw\Stroke::setMiterLimit
UI\Draw\Brush
UI\Draw\Stroke
PHP Manual

UI\Draw\Stroke::setThickness

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::setThickness — Set Thickness

Descrierea

public UI\Draw\Stroke::setThickness ( float $thickness )

Shall set the thickness for this Stroke

Parametri

thickness

The new thickness

UI\Draw\Stroke::setMiterLimit
UI\Draw\Brush
UI\Draw\Stroke


Brushes

(PHP 7, UI 0.9.9)

Introducere

Represents a solid color brush

Sinopsisul clasei

UI\Draw\Brush {
/* Constructor */
public __construct ( UI\Draw\Color $color )
public __construct ( integer $color )
/* Metode */
public UI\Draw\Color getColor ( void )
public void setColor ( UI\Draw\Color $color )
public void setColor ( integer $color )
}

Cuprins

  • UI\Draw\Brush::__construct — Construct a new Brush
  • UI\Draw\Brush::getColor — Get Color
  • UI\Draw\Brush::setColor — Set Color
UI\Draw\Stroke::setThickness
UI\Draw\Brush::__construct
UI


Construct a new Brush

UI\Draw\Brush
UI\Draw\Brush::getColor
UI\Draw\Brush
PHP Manual

UI\Draw\Brush::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Brush::__construct — Construct a new Brush

Descrierea

public UI\Draw\Brush::__construct ( UI\Draw\Color $color )
public UI\Draw\Brush::__construct ( integer $color )

Shall construct a solid brush using the given color

Parametri

color

Can be a UI\Draw\Color or RRGGBBAA

UI\Draw\Brush
UI\Draw\Brush::getColor
UI\Draw\Brush


Get Color

UI\Draw\Brush::__construct
UI\Draw\Brush::setColor
UI\Draw\Brush
PHP Manual

UI\Draw\Brush::getColor

(PHP 7, UI 0.9.9)

UI\Draw\Brush::getColor — Get Color

Descrierea

public UI\Draw\Color UI\Draw\Brush::getColor ( void )

Shall return a UI\Draw\Color for this brush

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

The current color of the brush

UI\Draw\Brush::__construct
UI\Draw\Brush::setColor
UI\Draw\Brush


Set Color

UI\Draw\Brush::getColor
UI\Draw\Brush\Gradient
UI\Draw\Brush
PHP Manual

UI\Draw\Brush::setColor

(PHP 7, UI 0.9.9)

UI\Draw\Brush::setColor — Set Color

Descrierea

public void UI\Draw\Brush::setColor ( UI\Draw\Color $color )
public void UI\Draw\Brush::setColor ( integer $color )

Shall set the color of this brush to the color provided

Parametri

color

Can be a UI\Draw\Color or RRGGBBAA

Valorile întoarse

UI\Draw\Brush::getColor
UI\Draw\Brush\Gradient
UI\Draw\Brush


Gradient Brushes

(PHP 7, UI 2.0.0)

Introducere

Abstract for gradient brushes

Sinopsisul clasei

abstract UI\Draw\Brush\Gradient extends UI\Draw\Brush {
/* Metode */
public integer addStop ( float $position , UI\Draw\Color $color )
public integer addStop ( float $position , integer $color )
public integer delStop ( integer $index )
public boolean setStop ( integer $index , float $position , UI\Draw\Color $color )
public boolean setStop ( integer $index , float $position , integer $color )
/* Metode mo?tenite */
public UI\Draw\Color UI\Draw\Brush::getColor ( void )
public void UI\Draw\Brush::setColor ( UI\Draw\Color $color )
public void UI\Draw\Brush::setColor ( integer $color )
}

Cuprins

  • UI\Draw\Brush\Gradient::addStop — Stop Manipulation
  • UI\Draw\Brush\Gradient::delStop — Stop Manipulation
  • UI\Draw\Brush\Gradient::setStop — Stop Manipulation
UI\Draw\Brush::setColor
UI\Draw\Brush\Gradient::addStop
UI


Stop Manipulation

UI\Draw\Brush\Gradient
UI\Draw\Brush\Gradient::delStop
UI\Draw\Brush\Gradient
PHP Manual

UI\Draw\Brush\Gradient::addStop

(PHP 7, UI 2.0.0)

UI\Draw\Brush\Gradient::addStop — Stop Manipulation

Descrierea

public integer UI\Draw\Brush\Gradient::addStop ( float $position , UI\Draw\Color $color )
public integer UI\Draw\Brush\Gradient::addStop ( float $position , integer $color )

Shall at a stop of the given color at the given position

Parametri

position

The position for the new stop

color

The color for the new stop, may be UI\Draw\Color or RRGGBBAA

Valorile întoarse

Total number of stops

UI\Draw\Brush\Gradient
UI\Draw\Brush\Gradient::delStop
UI\Draw\Brush\Gradient


Stop Manipulation

UI\Draw\Brush\Gradient::addStop
UI\Draw\Brush\Gradient::setStop
UI\Draw\Brush\Gradient
PHP Manual

UI\Draw\Brush\Gradient::delStop

(PHP 7, UI 2.0.0)

UI\Draw\Brush\Gradient::delStop — Stop Manipulation

Descrierea

public integer UI\Draw\Brush\Gradient::delStop ( integer $index )

Avertizare

Aceasta func?ie nu este documentata în prezent; este disponibila numai lista sa de argumente.

Parametri

index

Valorile întoarse

Total number of stops

UI\Draw\Brush\Gradient::addStop
UI\Draw\Brush\Gradient::setStop
UI\Draw\Brush\Gradient


Stop Manipulation

UI\Draw\Brush\Gradient::delStop
UI\Draw\Brush\LinearGradient
UI\Draw\Brush\Gradient
PHP Manual

UI\Draw\Brush\Gradient::setStop

(PHP 7, UI 2.0.0)

UI\Draw\Brush\Gradient::setStop — Stop Manipulation

Descrierea

public boolean UI\Draw\Brush\Gradient::setStop ( integer $index , float $position , UI\Draw\Color $color )
public boolean UI\Draw\Brush\Gradient::setStop ( integer $index , float $position , integer $color )

Parametri

index

The index of the stop to set

position

The position for the stop

color

The color for the stop, may be UI\Draw\Color or RRGGBBAA

Valorile întoarse

Indication of success

UI\Draw\Brush\Gradient::delStop
UI\Draw\Brush\LinearGradient
UI\Draw\Brush\Gradient


Linear Gradient

(PHP 7, UI 2.0.0)

Introducere

Sinopsisul clasei

UI\Draw\Brush\LinearGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct ( UI\Point $start , UI\Point $end )
/* Metode mo?tenite */
public integer UI\Draw\Brush\Gradient::addStop ( float $position , UI\Draw\Color $color )
public integer UI\Draw\Brush\Gradient::addStop ( float $position , integer $color )
public integer UI\Draw\Brush\Gradient::delStop ( integer $index )
public boolean UI\Draw\Brush\Gradient::setStop ( integer $index , float $position , UI\Draw\Color $color )
public boolean UI\Draw\Brush\Gradient::setStop ( integer $index , float $position , integer $color )
}

Cuprins

  • UI\Draw\Brush\LinearGradient::__construct — Construct a Linear Gradient
UI\Draw\Brush\Gradient::setStop
UI\Draw\Brush\LinearGradient::__construct
UI


Construct a Linear Gradient

UI\Draw\Brush\LinearGradient
UI\Draw\Brush\RadialGradient
UI\Draw\Brush\LinearGradient
PHP Manual

UI\Draw\Brush\LinearGradient::__construct

(PHP 7, UI 2.0.0)

UI\Draw\Brush\LinearGradient::__construct — Construct a Linear Gradient

Descrierea

public UI\Draw\Brush\LinearGradient::__construct ( UI\Point $start , UI\Point $end )

Shall construct a new linear gradient

Parametri

start

end

UI\Draw\Brush\LinearGradient
UI\Draw\Brush\RadialGradient
UI\Draw\Brush\LinearGradient


Radial Gradient

(PHP 7, UI 2.0.0)

Introducere

Sinopsisul clasei

UI\Draw\Brush\RadialGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct ( UI\Point $start , UI\Point $outer , float $radius )
/* Metode mo?tenite */
public integer UI\Draw\Brush\Gradient::addStop ( float $position , UI\Draw\Color $color )
public integer UI\Draw\Brush\Gradient::addStop ( float $position , integer $color )
public integer UI\Draw\Brush\Gradient::delStop ( integer $index )
public boolean UI\Draw\Brush\Gradient::setStop ( integer $index , float $position , UI\Draw\Color $color )
public boolean UI\Draw\Brush\Gradient::setStop ( integer $index , float $position , integer $color )
}

Cuprins

  • UI\Draw\Brush\RadialGradient::__construct — Construct a new Radial Gradient
UI\Draw\Brush\LinearGradient::__construct
UI\Draw\Brush\RadialGradient::__construct
UI


Construct a new Radial Gradient

UI\Draw\Brush\RadialGradient
UI\Draw\Text\Layout
UI\Draw\Brush\RadialGradient
PHP Manual

UI\Draw\Brush\RadialGradient::__construct

(PHP 7, UI 2.0.0)

UI\Draw\Brush\RadialGradient::__construct — Construct a new Radial Gradient

Descrierea

public UI\Draw\Brush\RadialGradient::__construct ( UI\Point $start , UI\Point $outer , float $radius )

Shall construct a new radial gradient

Parametri

start

outer

radius

UI\Draw\Brush\RadialGradient
UI\Draw\Text\Layout
UI\Draw\Brush\RadialGradient


Represents Text Layout

(PHP 7, UI 0.9.9)

Introducere

A Text Layout represents the layout of text which will be drawn by the Pen

Sinopsisul clasei

UI\Draw\Text\Layout {
/* Constructor */
public __construct ( string $text , UI\Draw\Text\Font $font , float $width )
/* Metode */
public setColor ( UI\Draw\Color $color [, integer $start = 0 [, integer $end ]] )
public setColor ( integer $color [, integer $start = 0 [, integer $end ]] )
public setWidth ( float $width )
}

Cuprins

  • UI\Draw\Text\Layout::__construct — Construct a new Text Layout
  • UI\Draw\Text\Layout::setColor — Set Color
  • UI\Draw\Text\Layout::setWidth — Set Width
UI\Draw\Brush\RadialGradient::__construct
UI\Draw\Text\Layout::__construct
UI


Construct a new Text Layout

UI\Draw\Text\Layout
UI\Draw\Text\Layout::setColor
UI\Draw\Text\Layout
PHP Manual

UI\Draw\Text\Layout::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Text\Layout::__construct — Construct a new Text Layout

Descrierea

public UI\Draw\Text\Layout::__construct ( string $text , UI\Draw\Text\Font $font , float $width )

Shall construct a new Text Layout

Parametri

text

The text for the layout

font

The font to use for writing

width

The width of the layout

UI\Draw\Text\Layout
UI\Draw\Text\Layout::setColor
UI\Draw\Text\Layout


Set Color

UI\Draw\Text\Layout::__construct
UI\Draw\Text\Layout::setWidth
UI\Draw\Text\Layout
PHP Manual

UI\Draw\Text\Layout::setColor

(PHP 7, UI 0.9.9)

UI\Draw\Text\Layout::setColor — Set Color

Descrierea

public UI\Draw\Text\Layout::setColor ( UI\Draw\Color $color [, integer $start = 0 [, integer $end ]] )
public UI\Draw\Text\Layout::setColor ( integer $color [, integer $start = 0 [, integer $end ]] )

Shall set the Color for all of, or a range of the text in the Layout

Parametri

color

The color to use

start

The starting character

end

The ending character, by default the end of the string

UI\Draw\Text\Layout::__construct
UI\Draw\Text\Layout::setWidth
UI\Draw\Text\Layout


Set Width

UI\Draw\Text\Layout::setColor
UI\Draw\Text\Font
UI\Draw\Text\Layout
PHP Manual

UI\Draw\Text\Layout::setWidth

(PHP 7, UI 0.9.9)

UI\Draw\Text\Layout::setWidth — Set Width

Descrierea

public UI\Draw\Text\Layout::setWidth ( float $width )

Shall set the width of this Text Layout

Parametri

width

The new width

UI\Draw\Text\Layout::setColor
UI\Draw\Text\Font
UI\Draw\Text\Layout


Represents a Font

(PHP 7, UI 0.9.9)

Introducere

Loads a described font

Sinopsisul clasei

UI\Draw\Text\Font {
/* Constructor */
public __construct ( UI\Draw\Text\Font\Descriptor $descriptor )
/* Metode */
public float getAscent ( void )
public float getDescent ( void )
public float getLeading ( void )
public float getUnderlinePosition ( void )
public float getUnderlineThickness ( void )
}

Cuprins

  • UI\Draw\Text\Font::__construct — Construct a new Font
  • UI\Draw\Text\Font::getAscent — Font Metrics
  • UI\Draw\Text\Font::getDescent — Font Metrics
  • UI\Draw\Text\Font::getLeading — Font Metrics
  • UI\Draw\Text\Font::getUnderlinePosition — Font Metrics
  • UI\Draw\Text\Font::getUnderlineThickness — Font Metrics
UI\Draw\Text\Layout::setWidth
UI\Draw\Text\Font::__construct
UI


Construct a new Font

UI\Draw\Text\Font
UI\Draw\Text\Font::getAscent
UI\Draw\Text\Font
PHP Manual

UI\Draw\Text\Font::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Text\Font::__construct — Construct a new Font

Descrierea

public UI\Draw\Text\Font::__construct ( UI\Draw\Text\Font\Descriptor $descriptor )

Shall construct a new Font using the given descriptor

Parametri

descriptor

The descriptor for the Font

UI\Draw\Text\Font
UI\Draw\Text\Font::getAscent
UI\Draw\Text\Font


Font Metrics

UI\Draw\Text\Font::__construct
UI\Draw\Text\Font::getDescent
UI\Draw\Text\Font
PHP Manual

UI\Draw\Text\Font::getAscent

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font::getAscent — Font Metrics

Descrierea

public float UI\Draw\Text\Font::getAscent ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Draw\Text\Font::__construct
UI\Draw\Text\Font::getDescent
UI\Draw\Text\Font


Font Metrics

UI\Draw\Text\Font::getAscent
UI\Draw\Text\Font::getLeading
UI\Draw\Text\Font
PHP Manual

UI\Draw\Text\Font::getDescent

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font::getDescent — Font Metrics

Descrierea

public float UI\Draw\Text\Font::getDescent ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Draw\Text\Font::getAscent
UI\Draw\Text\Font::getLeading
UI\Draw\Text\Font


Font Metrics

UI\Draw\Text\Font::getDescent
UI\Draw\Text\Font::getUnderlinePosition
UI\Draw\Text\Font
PHP Manual

UI\Draw\Text\Font::getLeading

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font::getLeading — Font Metrics

Descrierea

public float UI\Draw\Text\Font::getLeading ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Draw\Text\Font::getDescent
UI\Draw\Text\Font::getUnderlinePosition
UI\Draw\Text\Font


Font Metrics

UI\Draw\Text\Font::getLeading
UI\Draw\Text\Font::getUnderlineThickness
UI\Draw\Text\Font
PHP Manual

UI\Draw\Text\Font::getUnderlinePosition

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font::getUnderlinePosition — Font Metrics

Descrierea

public float UI\Draw\Text\Font::getUnderlinePosition ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Draw\Text\Font::getLeading
UI\Draw\Text\Font::getUnderlineThickness
UI\Draw\Text\Font


Font Metrics

UI\Draw\Text\Font::getUnderlinePosition
UI\Draw\Text\Font\Descriptor
UI\Draw\Text\Font
PHP Manual

UI\Draw\Text\Font::getUnderlineThickness

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font::getUnderlineThickness — Font Metrics

Descrierea

public float UI\Draw\Text\Font::getUnderlineThickness ( void )

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Draw\Text\Font::getUnderlinePosition
UI\Draw\Text\Font\Descriptor
UI\Draw\Text\Font


Font Descriptor

(PHP 7, UI 0.9.9)

Introducere

Describes a font

Sinopsisul clasei

UI\Draw\Text\Font\Descriptor {
/* Constructor */
public __construct ( string $family , float $size [, integer $weight = UI\Draw\Text\Font\Weight::Normal [, integer $italic = UI\Draw\Text\Font\Italic::Normal [, integer $stretch = UI\Draw\Text\Font\Stretch::Normal ]]] )
/* Metode */
public string getFamily ( void )
public int getItalic ( void )
public float getSize ( void )
public int getStretch ( void )
public int getWeight ( void )
}

Cuprins

  • UI\Draw\Text\Font\Descriptor::__construct — Construct a new Font Descriptor
  • UI\Draw\Text\Font\Descriptor::getFamily — Get Font Family
  • UI\Draw\Text\Font\Descriptor::getItalic — Style Detection
  • UI\Draw\Text\Font\Descriptor::getSize — Size Detection
  • UI\Draw\Text\Font\Descriptor::getStretch — Style Detection
  • UI\Draw\Text\Font\Descriptor::getWeight — Weight Detection
UI\Draw\Text\Font::getUnderlineThickness
UI\Draw\Text\Font\Descriptor::__construct
UI


Construct a new Font Descriptor

UI\Draw\Text\Font\Descriptor
UI\Draw\Text\Font\Descriptor::getFamily
UI\Draw\Text\Font\Descriptor
PHP Manual

UI\Draw\Text\Font\Descriptor::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Text\Font\Descriptor::__construct — Construct a new Font Descriptor

Descrierea

public UI\Draw\Text\Font\Descriptor::__construct ( string $family , float $size [, integer $weight = UI\Draw\Text\Font\Weight::Normal [, integer $italic = UI\Draw\Text\Font\Italic::Normal [, integer $stretch = UI\Draw\Text\Font\Stretch::Normal ]]] )

Shall construct a new Font Descriptor

Parametri

family

The name of a valid family of fonts

size

The preferred size

weight

UI\Draw\Text\Font\Weight constant

italic

UI\Draw\Text\Font\Italic constant

stretch

UI\Draw\Text\Font\Stretch constant

UI\Draw\Text\Font\Descriptor
UI\Draw\Text\Font\Descriptor::getFamily
UI\Draw\Text\Font\Descriptor


Get Font Family

UI\Draw\Text\Font\Descriptor::__construct
UI\Draw\Text\Font\Descriptor::getItalic
UI\Draw\Text\Font\Descriptor
PHP Manual

UI\Draw\Text\Font\Descriptor::getFamily

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getFamily — Get Font Family

Descrierea

public string UI\Draw\Text\Font\Descriptor::getFamily ( void )

Shall return the requested font family

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Draw\Text\Font\Descriptor::__construct
UI\Draw\Text\Font\Descriptor::getItalic
UI\Draw\Text\Font\Descriptor


Style Detection

UI\Draw\Text\Font\Descriptor::getFamily
UI\Draw\Text\Font\Descriptor::getSize
UI\Draw\Text\Font\Descriptor
PHP Manual

UI\Draw\Text\Font\Descriptor::getItalic

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getItalic — Style Detection

Descrierea

public int UI\Draw\Text\Font\Descriptor::getItalic ( void )

Shall return constant setting

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Draw\Text\Font\Descriptor::getFamily
UI\Draw\Text\Font\Descriptor::getSize
UI\Draw\Text\Font\Descriptor


Size Detection

UI\Draw\Text\Font\Descriptor::getItalic
UI\Draw\Text\Font\Descriptor::getStretch
UI\Draw\Text\Font\Descriptor
PHP Manual

UI\Draw\Text\Font\Descriptor::getSize

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getSize — Size Detection

Descrierea

public float UI\Draw\Text\Font\Descriptor::getSize ( void )

Shall return the requested size

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Draw\Text\Font\Descriptor::getItalic
UI\Draw\Text\Font\Descriptor::getStretch
UI\Draw\Text\Font\Descriptor


Style Detection

UI\Draw\Text\Font\Descriptor::getSize
UI\Draw\Text\Font\Descriptor::getWeight
UI\Draw\Text\Font\Descriptor
PHP Manual

UI\Draw\Text\Font\Descriptor::getStretch

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getStretch — Style Detection

Descrierea

public int UI\Draw\Text\Font\Descriptor::getStretch ( void )

Shall return requested stretch

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Draw\Text\Font\Descriptor::getSize
UI\Draw\Text\Font\Descriptor::getWeight
UI\Draw\Text\Font\Descriptor


Weight Detection

UI\Draw\Text\Font\Descriptor::getStretch
UI Func?ii
UI\Draw\Text\Font\Descriptor
PHP Manual

UI\Draw\Text\Font\Descriptor::getWeight

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getWeight — Weight Detection

Descrierea

public int UI\Draw\Text\Font\Descriptor::getWeight ( void )

Shall return requested weight

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Draw\Text\Font\Descriptor::getStretch
UI Func?ii
UI\Draw\Text\Font\Descriptor


UI Func?ii

Cuprins

  • UI\Draw\Text\Font\fontFamilies — Retrieve Font Families
  • UI\quit — Quit UI Loop
  • UI\run — Enter UI Loop
UI\Draw\Text\Font\Descriptor::getWeight
UI\Draw\Text\Font\fontFamilies
UI


Retrieve Font Families

UI Func?ii
UI\quit
UI Func?ii
PHP Manual

UI\Draw\Text\Font\fontFamilies

(PHP 7, UI 0.9.9)

UI\Draw\Text\Font\fontFamilies — Retrieve Font Families

Descrierea

array UI\Draw\Text\Font\fontFamilies ( void )

Returns an array of valid font families for the current system

Parametri

Aceasta func?ie nu are parametri.

UI Func?ii
UI\quit
UI Func?ii


Quit UI Loop

UI\Draw\Text\Font\fontFamilies
UI\run
UI Func?ii
PHP Manual

UI\quit

(PHP 7, UI 2.0.0)

UI\quit — Quit UI Loop

Descrierea

void UI\quit ( void )

Shall cause the main loop to be exited

Parametri

Aceasta func?ie nu are parametri.

Valorile întoarse

UI\Draw\Text\Font\fontFamilies
UI\run
UI Func?ii


Enter UI Loop

UI\quit
UI\Draw\Text\Font\Weight
UI Func?ii
PHP Manual

UI\run

(PHP 7, UI 2.0.0)

UI\run — Enter UI Loop

Descrierea

void UI\run ([ integer $flags ] )

Shall cause PHP to enter into the main loop, by default control will not be returned to the caller

Parametri

flags

Set UI\Loop to return control, and UI\Wait to return control after waiting

Valorile întoarse

UI\quit
UI\Draw\Text\Font\Weight
UI Func?ii


Font Weight Settings

(PHP 7, UI 0.9.9)

Introducere

Sinopsisul clasei

final UI\Draw\Text\Font\Weight {
/* Constants */
const integer Thin ;
const integer UltraLight ;
const integer Light ;
const integer Book ;
const integer Normal ;
const integer Medium ;
const integer SemiBold ;
const integer Bold ;
const integer UltraBold ;
const integer Heavy ;
const integer UltraHeavy ;
}
UI\run
UI\Draw\Text\Font\Italic
UI


Italic Font Settings

(PHP 7, UI 0.9.9)

Introducere

Sinopsisul clasei

final UI\Draw\Text\Font\Italic {
/* Constants */
const integer Normal = 0 ;
const integer Oblique = 1 ;
const integer Italic = 2 ;
}
UI\Draw\Text\Font\Weight
UI\Draw\Text\Font\Stretch
UI


Font Stretch Settings

(PHP 7, UI 0.9.9)

Introducere

Sinopsisul clasei

final UI\Draw\Text\Font\Stretch {
/* Constants */
const integer UltraCondensed = 0 ;
const integer ExtraCondensed = 1 ;
const integer Condensed = 2 ;
const integer SemiCondensed = 3 ;
const integer Normal = 4 ;
const integer SemiExpanded = 5 ;
const integer Expanded = 6 ;
const integer ExtraExpanded = 7 ;
const integer UltraExpanded = 8 ;
}
UI\Draw\Text\Font\Italic
UI\Draw\Line\Cap
UI


Line Cap Settings

(PHP 7, UI 0.9.9)

Introducere

Sinopsisul clasei

final UI\Draw\Line\Cap {
/* Constants */
const integer Flat ;
const integer Round ;
const integer Square ;
}
UI\Draw\Text\Font\Stretch
UI\Draw\Line\Join
UI


Line Join Settings

(PHP 7, UI 0.9.9)

Introducere

Sinopsisul clasei

final UI\Draw\Line\Join {
/* Constants */
const integer Miter ;
const integer Round ;
const integer Bevel ;
}
UI\Draw\Line\Cap
UI\Key
UI


Key Identifiers

(PHP 7, UI 1.0.0)

Introducere

Sinopsisul clasei

final UI\Key {
/* Constants */
const integer Escape ;
const integer Insert ;
const integer Delete ;
const integer Home ;
const integer End ;
const integer PageUp ;
const integer PageDown ;
const integer Up ;
const integer Down ;
const integer Left ;
const integer Right ;
const integer F1 ;
const integer F2 ;
const integer F3 ;
const integer F4 ;
const integer F5 ;
const integer F6 ;
const integer F7 ;
const integer F8 ;
const integer F9 ;
const integer F10 ;
const integer F11 ;
const integer F12 ;
const integer N0 ;
const integer N1 ;
const integer N2 ;
const integer N3 ;
const integer N4 ;
const integer N5 ;
const integer N6 ;
const integer N7 ;
const integer N8 ;
const integer N9 ;
const integer NDot ;
const integer NEnter ;
const integer NAdd ;
const integer NSubtract ;
const integer NMultiply ;
const integer NDivide ;
}
UI\Draw\Line\Join
UI\Exception\InvalidArgumentException
UI


InvalidArgumentException

(PHP 7, UI 1.0.3)

Introducere

Sinopsisul clasei

UI\Exception\InvalidArgumentException extends InvalidArgumentException implements Throwable {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
UI\Key
UI\Exception\RuntimeException
UI


RuntimeException

(PHP 7, UI 1.0.3)

Introducere

Sinopsisul clasei

UI\Exception\RuntimeException extends RuntimeException implements Throwable {
/* Proprieta?i mo?tenite */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metode mo?tenite */
final public string Exception::getMessage ( void )
final public Throwable 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 )
}
UI\Exception\InvalidArgumentException
Nucleul PHP: Ghidul unui hacker
UI


Nucleul PHP: Ghidul unui hacker

  • Preface
  • Memory management
    • Basic memory management
    • Data persistence
    • Thread-Safe Resource Manager
  • Working with Variables
    • Introduction to Variables
    • Working with Arrays
    • Working with HashTable
    • Working with Objects
  • Writing Functions
  • Writing Classes
  • Working with Resources
  • Working with INI settings
  • Working with streams
  • The "counter" Extension - A Continuing Example
    • Instalarea / configurarea
    • Constante predefinite
    • Exemple
    • 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
  • 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 Opcodes
    • Opcode Descriptions and Examples
  • Zend Engine 1
    • Old introduction
    • Streams API for PHP Extension Authors
    • API al Zend: Aprofundare în nucleul PHP
    • TSRM API
UI\Exception\RuntimeException
Preface
Manualul PHP


Preface

This section of the manual is written for the Hacker: someone thinking about getting their hands dirty, someone who wants an understanding of internals in order to advance their PHP skills, or maybe someone looking to write the next best extension. Whatever the reason, this section will seek to provide a good understanding of the internals of PHP, how to write extensions, how to understand existing code containing mystical macros. All of the important internal functionality is documented here, enough anyway to convince you to read the source.

Out of necessity, this section assumes the reader has a working knowledge of the C programming language, and associated tools, like compilers and terminal emulators and the like. You don't need to be the next Alan Turing, but a working knowledge is none the less essential for this section to be of any use. With just that working knowledge, this section should be enough to get you well on the way to earning the title Hacker, and you do have to earn it.

The documentation in this section is current as of PHP 5.3.3, deviations in API functionality are duly noted in the appropriate sections.

Avertizare

This documentation is still under 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.

Nucleul PHP: Ghidul unui hacker
Memory management
Nucleul PHP: Ghidul unui hacker


Memory management

Cuprins

  • 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.

Preface
Basic memory management
Nucleul PHP: Ghidul unui hacker


Basic memory management

The engine's memory management is implemented with features important to a system like PHP. The exact functionality of the engine's memory management and the optimizations performed are out of the scope of this document. However, a good understanding of its functionality provides a basis for a good understanding of the rest of the Hacker's Guide, and introduce you to terminology and functionality used throughout PHP.

The most important of its features for the Hacker, and the first thing to mention is tracking allocations. Tracking allocations allow the memory manager to avoid leaks, a thorn in the side of most Hackers. When PHP is built in debug mode (--enable-debug), detected leaks are reported, in a perfect world they would never get to deployment.

While tracking allocations is an important, and highly useful feature, the Hacker should not become lazy! Always attempt to resolve leaks before deploying your code, a memory leak in a SAPI environment can become a very big problem, very quickly.

Another, perhaps more incidental but still noteworthy, feature is that the memory manager is the part that allows a hard limit on memory usage for each instance of PHP. As we all know, there is no such thing as unlimited. If some code is running out of memory, it is likely to be written wrong, either by the Hacker, or the programmer of PHP. Limiting the memory therefore is not a restriction on the language that is supposed to be experienced in production, it is simply a way from stopping development environments from spiraling out of control when mistakes are made, and equally, when bugs are found in production.

From the Hacker's perspective, the memory management API looks very much like libc's (or whoever the Hacker prefers !) malloc implementation.

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.

Nota: The engines memory management functions do not return NULL upon failure, if memory cannot be allocated at runtime, the engine bails and raises an error.

Precautie

Always use valgrind before deploying code and as a normal part of the Hacker's process. The engine can only report and detect leaks where it has allocated the memory. All of PHP is only a thin wrapper around third parties, those third parties do not use the engines memory management. Additionally, valgrind will catch errors that do not always halt or even have an apparent effect at execution time, it is just as important that there should be no errors, as it is important that avoidable leaks should be avoided.

Nota: Some leaks are unavoidable, some libraries rely on the end of a process to free some of their structures, this is normal under some circumstances and acceptable where it is out of the Hacker's control.

While executing in a debug environment, configured with --enable-debug, the leak function used in the next example is actually implemented by the engine and is available to call in userland.

Example #1 Leak Detection in Action

ZEND_FUNCTION(leak)
{
    long leakbytes = 3;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &leakbytes) == FAILURE) {
        return;
    }

    emalloc(leakbytes);
}

Exemplul de mai sus va afi?a ceva similar cu:

[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 ===

Nota: USE_ZEND_ALLOC=0 in the environment will stop the memory manager from functioning, all allocations fall back on the default system allocators which can be useful for debugging leaks, and should only be used for this purpose.

Memory management
Data persistence
Memory management


Data persistence

In this context, data persistence is taken to mean any data that is intended to survive the current request. The memory management within the engine is very focused on request bound allocations, but this is not always practical or appropriate. Persistent memory is sometimes required in order to satisfy requirements of external libraries, it can also be useful while Hacking.

A common use of persistent memory is to enable persistent SQL server connections, though this practice is frowned upon, it is none the less the most common use of this feature.

Nota: All of the following functions take the additional persistent parameter, should this be false, the engine will use its regular allocators (emalloc) and the memory should not be considered persistent. Where memory is allocated as persistent, system allocators are invoked, under most circumstances they are still not able to return NULL pointers just as the Main memory APIs.

Persistent memory APIs
Prototype | Description
void *pemalloc(size_t size, zend_bool persistent) | Allocate size bytes of memory.
void *pecalloc(size_t nmemb, size_t size, zend_bool persistent) | Allocate a buffer for nmemb elements of size bytes and makes sure it is initialized with zeros.
void *perealloc(void *ptr, size_t size, zend_bool persistent) | Resize the buffer ptr, which was allocated using emalloc to hold size bytes of memory.
void pefree(void *ptr, zend_bool persistent) | Free the buffer pointed by ptr. The buffer had to be allocated by pemalloc.
void *safe_pemalloc(size_t nmemb, size_t size, size_t offset, zend_bool persistent) | Allocate a buffer for holding nmemb blocks of each size bytes and an additional offset bytes. This is similar to pemalloc(nmemb * size + offset) but adds a special protection against overflows.
char *pestrdup(const char *s, zend_bool persistent) | Allocate a buffer that can hold the NULL-terminated string s and copy the s into that buffer.
char *pestrndup(const char *s, unsigned int length, zend_bool persistent) | Similar to pestrdup while the length of the NULL-terminated string is already known.
Precautie

It is important to remember that memory allocated to be persistent is not optimized or tracked by the engine; it is not subject to memory_limit, additionally, all variables that are created by the Hacker for the engine must not use persistent memory.

Basic memory management
Thread-Safe Resource Manager
Memory management


Thread-Safe Resource Manager

When PHP is built with Thread Safety enabled, the engine requires a way to isolate contexts from one another, such that the threads of a process may service individual requests without interference. TSRM is omnipotent within PHP, extension authors have to do very little in order to make sure their extensions can function in both a Thread Safe and Non Thread Safe architecture.

Example #1 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

The snippet above shows how an extension author is expected to define their global accessors. The TSRMG macro takes an identifier, type cast and element name. The identifier is assigned by TSRM during initialization of the module. Declaring global accessors in this way ensures that an extension can operate safely in a Thread Safe and Non Thread Safe architecture using the same logic.

TSRM manages the isolation and safety of all global structures within PHP, from executor globals to extension globals, a pointer to the isolated storage is also passed around with most, or many of the API functions. The macros TSRMLS_C and TSRMLS_CC translate to "thread safe local storage" and "thread safe local storage prefixed with a comma" respectively.

If a function requires a pointer to TSRM, it is declared with the macro TSRMLS_D or TSRMLS_DC in it's prototype, which translates to "thread safe local storage only" and "thread safe local storage prefixed with a comma" respectively. Many macros within the engine reference TSRM, so it is a good idea to declare most things to accept TSRM, such that if they need to call upon TSRM they do not have to fetch a pointer during execution.

Because TSRM is thread local, and some functions (for compatibility reasons) are not able to accept TSRM directly, the macro TSRMLS_FETCH exists, which requests that TSRM fetches the pointer to the thread local storage. This should be avoided wherever it can be, as it is not without cost in a Thread Safe setup.

Nota: While developing extensions, build errors that contain "tsrm_ls is undefined" or errors to that effect stem from the fact that TSRMLS is undefined in the current scope, to fix this, declare the function to accept TSRMLS with the appropriate macro, if the prototype of the function in question cannot be changed, you must call TSRMLS_FETCH within the function body.

The functionality documented hereafter is aimed at advanced use of TSRM. It is not ordinary for extensions to have to interact with TSRM directly, the pecl programmer should use API's above TSRM such as the Module Globals API.

TSRM Internals
Prototype | Description
typedef int ts_rsrc_id | The type definition to represent a resource by numeric identifiers
int tsrm_startup(int expected_threads, int expected_resources, int debug_level, char *debug_filename) | expected_threads and expected_resources are not hard limits. debug_level and debug_filename only have an effect on windows in Debug mode or when TSRM_DEBUG is defined. Called once per process in ZTS mode during server startup.
void tsrm_shutdown(void) | Should be the last thing called in the process to destroy and free all storage TSRM storage in ZTS mode.
ts_rsrc_id ts_allocate_id(ts_rsrc_id *rsrc_id, size_t size, ts_allocate_ctor ctor, ts_allocate_dtor dtor) | Allocates and thread safe pointer of size bytes, calling ctor on the pointer, assigning (and returning) the id to rsrc_id, the dtor is called when the resource is free'd. Module globals are isolated in ZTS mode using this API.
void *ts_resource_ex(ts_rsrc_id id, THREAD_T *th_id) | Fetches a resource by previously allocated id from the entries created by the specified thread identifed by th_id.
void *ts_resource(ts_rsrc_id id) | Fetches a resource by previously allocated id from the entries created by the calling thread.
void ts_free_thread(void) | Destroys and frees the entries for the calling thread, currently this API is only used by ISAPI module.
void ts_free_id(ts_rsrc_id id) | Destroys the resource identified by previously allocated id. Module globals are cleaned up in ZTS mode using this API.

Nota: There are more TSRM API functions to enable the creation and destruction of interpreter contexts, the usage of such functionality is out of the scope of this documentation, please see TSRM/TSRM.h for more information.

TSRM Mutex API
Prototype | Description
MUTEX_T tsrm_mutex_alloc(void) | Allocates and returns a suitable MUTEX_T for the environment.
int tsrm_mutex_lock(MUTEX_T mutexp) | Locks mutexp for the calling thread.
int tsrm_mutex_unlock(MUTEX_T mutexp) | Unlocks mutexp for the calling thread.
void tsrm_mutex_free(MUTEX_T mutexp); | Destroys and frees the (unlocked) and previously allocated mutexp.

Nota: The mutex API is exposed by TSRM. However, its internal usage is far too wide to document usefully here, none the less, basic functionality and prototypes are documented here.

Data persistence
Working with Variables
Memory management


Working with Variables

Cuprins

  • Introduction to Variables
  • Working with Arrays
  • Working with HashTable
  • Working with Objects
Thread-Safe Resource Manager
Introduction to Variables
Nucleul PHP: Ghidul unui hacker


Introduction to Variables

A good understanding of how variables are stored and manipulated is essential to becoming a Hacker. The engine attempts to cover up the complexity of the concept of a variable that can be any type by providing a uniform and intuitive set of macros for accessing the structures various fields. As the Hacker works through this chapter, they should become comfortable with the terminology and concepts involved with Variables in PHP.

Nota:

PHP is a dynamic, loosely typed language, that uses copy-on-write and reference counting.

To clarify what exactly is meant by the statement above: PHP is a high level language, weak typing is implicit of the engines preference to convert, or coerce variables into the required type at execution time. Reference counting is the means by which the engine can deduce when a variable no longer has any references in the users code, and so is able to free the structures associated with the variable.

All variables in PHP are represented by one structure, the zval:

typedef struct _zval_struct {
    zvalue_value value;        /* variable value */
    zend_uint refcount__gc;    /* reference counter */
    zend_uchar type;           /* value type */
    zend_uchar is_ref__gc;     /* reference flag */
} zval;

The zval_value is a union which can represent all types a variable may hold:

typedef union _zvalue_value {
    long lval;                 /* long value */
    double dval;               /* double value */
    struct {
        char *val;
        int len;               /* this will always be set for strings */
    } str;                     /* string (always has length) */
    HashTable *ht;             /* an array */
    zend_object_value obj;     /* stores an object store handle, and handlers */
} zvalue_value;

It should be clear from the structures above that a variable can be of one type, the variable data is represented by the appropriate field in the zval_value union. The zval itself holds the type, reference count and a flag to indicate if a variable is a reference.

Native Type Constants
Constant | Mapping
IS_NULL | no value is set in this case
IS_LONG | lval
IS_DOUBLE | dval
IS_BOOL | lval
IS_RESOURCE | lval
IS_STRING | str
IS_ARRAY | ht
IS_OBJECT | obj

Nota:

There are additional constants that help to identify internal types such as constant arrays and callable objects, their usage is outside the scope of this part of the documentation.

The following table defines the macros exposed by the engine for working with zval values:

Accessor Macros
Prototype | Accesses | Description
zend_uchar Z_TYPE(zval zv) | type | returns the type of the value
long Z_LVAL(zval zv) | value.lval |
zend_bool Z_BVAL(zval zv) | value.lval | cast long value to zend_bool
double Z_DVAL(zval zv) | value.dval |
long Z_RESVAL(zval zv) | value.lval | returns the resource list identifier for value
char* Z_STRVAL(zval zv) | value.str.val | return the string value
int Z_STRLEN(zval zv) | value.str.len | return the length of the string value
HashTable* Z_ARRVAL(zval zv) | value.ht | return the HashTable (array) value
zend_object_value Z_OBJVAL(zval zv) | value.obj | returns object value
uint Z_OBJ_HANDLE(zval zv) | value.obj.handle | returns the object handle for object value
zend_object_handlers* Z_OBJ_HT_P(zval zv) | value.obj.handlers | returns the handler table for object value
zend_class_entry* Z_OBJCE(zval zv) | value.obj | returns the class entry for object value
HashTable* Z_OBJPROP(zval zv) | value.obj | returns the properties of object value
HashTable* Z_OBJPROP(zval zv) | value.obj | returns the properties of object value
HashTable* Z_OBJDEBUG(zval zv) | value.obj | if an object has the get_debug_info handler set, it is called, else Z_OBJPROP is called

Please check the Reference Counting Basics chapter for details how reference counting and references work in detail.

Reference Count Manipulation
Prototype | Description
zend_uint Z_REFCOUNT(zval zv) | returns the reference count of the value
zend_uint Z_SET_REFCOUNT(zval zv) | sets the reference count of the value, returning it
zend_uint Z_ADDREF(zval zv) | pre-increments the reference count of value, returning it
zend_uint Z_DELREF(zval zv) | pre-decrements the reference count of value, returning it
zend_bool Z_ISREF(zval zv) | tells if the zval is a reference
void Z_UNSET_ISREF(zval zv) | set is_ref__gc to 0
void Z_SET_ISREF(zval zv) | set is_ref__gc to 1
void Z_SET_ISREF_TO(zval zv, zend_uchar to) | set is_ref__gc to to

Nota:

The Z_* macros above all take a zval, they are all defined again suffixed with _P to take a pointer to a zval, for example zend_uchar Z_TYPE_P(zval* pzv), and again suffixed with _PP to take a pointer to a pointer to a zval, for example zend_uchar Z_TYPE_PP(zval** ppzv)

Creation, Destruction, Separation and Copying
Prototype | Description
ALLOC_ZVAL(zval* pzval) | emallocs pzval
ALLOC_INIT_ZVAL(zval* pzval) | emallocs pzval, and points pzval at a null typed zval for sanity
MAKE_STD_ZVAL(zval* pzval) | emallocs pzval, setting the refcount to 1
ZVAL_COPY_VALUE(zval* dst, zval* src) | sets the value and type of dst from the value and type of src
INIT_PZVAL_COPY(zval* dst, zval*dst) | performs ZVAL_COPY_VALUE, setting refcount of dst to 1, and setting is_ref__gc to 0
SEPARATE_ZVAL(zval** ppzval) | if the refcount of ppzval is >1, redirects *ppzval to a newly emalloc'd, copied, and constructed zval of the same type and value
SEPARATE_ZVAL_IF_NOT_REF(zval** ppzval) | if *ppzval is not a reference, will perform SEPARATE_ZVAL on ppzval
SEPARATE_ZVAL_TO_MAKE_IS_REF(zval** ppzval) | if *ppzval is not a reference, performs SEPARATE_ZVAL then Z_SET_ISREF_PP on ppzval
COPY_PZVAL_TO_ZVAL(zval dst, zval** src) | results in dst being a copy of src without affecting the refcount of src
MAKE_COPY_ZVAL(zval** src, zval* dst) | performs INIT_PZVAL_COPY, then zval_copy_ctor on the new zval
void zval_copy_ctor(zval** pzval) | performs maintenance of reference counts, used widely throughout the engine
void zval_ptr_dtor(zval* pzval) | decrements the refcount for the variable, if no refcounts remain the variable is destroyed
FREE_ZVAL(zval* pzval) | efrees pzval

Nota:

Objects and Resources have a reference count as part of their respective structures, when zval_ptr_dtor is called on either, their appropriate del_ref method is executed. See Working with Objects and Working with Resources for more information.

If the Hacker only has room to remember two more functions, they should be zval_copy_ctor and zval_ptr_dtor, these are at the basis of the engines reference counting mechanisms and it is important to note that zval_copy_ctor does not actually result in any copying occuring under normal circumstances, it simply increases the reference count. By the same token, zval_ptr_dtor only really destroys a variable when there are no references remaining to it and the refcount is at 0.

PHP is weakly typed, as such the engine provides API functions for converting variables from one type to another.

Type Conversion
Prototype
void convert_to_long(zval* pzval)
void convert_to_double(zval* pzval)
void convert_to_long_base(zval* pzval, int base)
void convert_to_null(zval* pzval)
void convert_to_boolean(zval* pzval)
void convert_to_array(zval* pzval)
void convert_to_object(zval* pzval)
void convert_object_to_type(zval* pzval, convert_func_t converter)

Nota:

convert_func_t functions should have the prototype (void) (zval* pzval)

By now you should have a good understanding of: the types that are native to the engine, how to detect types and read zval values, how to manipulate refcounts, and other zval flags

Working with Variables
Working with Arrays
Working with Variables


Working with Arrays

Arrays are stored in HashTable strucures, and have the zval type IS_ARRAY. The API functions for creating, destroying and manipulating these structures as variables are documented here and can be found in Zend/zend_API.h

HashTable as Variable API
Prototype | Description
void array_init(zval* pzval) | initializes the variable as a HashTable, setting type and appropriate destructor function for the HashTable
void array_init_size(zval* pzval) | initializes the variable as array_init with a minimum of size buckets

Nota:

Do not squint too hard looking for array_destroy: to destroy a variable array you should call zval_ptr_dtor on the variable, if there are no other references to the variable it will result in the array being destroyed.

Indexed Arrays API
Prototype
int add_index_long(zval* pzval, ulong index, long value)
int add_index_null(zval* pzval, ulong index)
int add_index_bool(zval* pzval, ulong index, zend_bool value)
int add_index_bool(zval* pzval, ulong index, zend_bool value)
int add_index_resource(zval* pzval, ulong index, uint value)
int add_index_double(zval* pzval, ulong index, double value)
int add_index_string(zval* pzval, ulong index, char* string, zend_bool duplicate)
int add_index_stringl(zval* pzval, ulong index, char* string, uint length, zend_bool duplicate)
int add_index_zval(zval* pzval, ulong index, zval* value)
int add_next_index_long(zval* pzval, long value)
int add_next_index_null(zval* pzval)
int add_next_index_bool(zval* pzval, zend_bool value)
int add_next_index_resource(zval* pzval, uint value)
int add_next_index_double(zval* pzval, double value)
int add_next_index_string(zval* pzval, const char* string, zend_bool dulpicate)
int add_next_index_stringl(zval* pzval, const char* string, uint length, zend_bool duplicate)
int add_next_index_zval(zval* pzval, zval* value)
Associative Arrays API
Prototype
int add_assoc_long(zval* pzval, const char* key, long value)
int add_assoc_long_ex(zval* pzval, const char* key, uint klen, long value)
int add_assoc_null(zval* pzval, const char* key)
int add_assoc_null_ex(zval* pzval, const char* key, uint klen)
int add_assoc_bool(zval* pzval, const char* key, zend_bool value)
int add_assoc_bool(zval* pzval, const char* key, zend_bool value)
int add_assoc_bool_ex(zval* pzval, const char* key, uint klen, zend_bool value)
int add_assoc_resource(zval* pzval, const char* key, uint value)
int add_assoc_resource_ex(zval* pzval, const char* key, uint klen, uint value)
int add_assoc_double(zval* pzval, const char* key, double value)
int add_assoc_double_ex(zval* pzval, const char* key, uint klen, double value)
int add_assoc_string(zval* pzval, const char* key, const char* value)
int add_assoc_string_ex(zval* pzval, const char* key, uint klen, const char* value)
int add_assoc_stringl(zval* pzval, const char* key, const char* value, uint vlen, zend_bool duplicate)
int add_assoc_stringl_ex(zval* pzval, const char* key, uint klen, const char* value, uint vlen, zend_bool duplicate)
int add_assoc_zval(zval* pzval, const char* key, zval* value)
int add_assoc_zval_ex(zval* pzval, const char* key, uint klen, zval* value)

Nota:

add_*_string functions that accept a parameter named duplicate, will duplicate the string with estrndup when duplicate is true

Nota:

add_*_zval functions do not adjust the refcount of the value parameter

To perform more advanced operations on array variables we must use the HashTable API directly.

Introduction to Variables
Working with HashTable
Working with Variables


Working with HashTable

The HashTable structure serves many purposes in PHP and can be found everywhere, a good understanding of it's functionality is a preqrequisite of being a good Hacker.

The HashTable implemented by the engine is a standard HashTable, that is to say, a key => value based store, where the keys are always strings, whose hashes are calculated with a built in hashing algorithm zend_inline_hash_func(const char* key, uint length), which results in good distribution, and reasonable usage.

The internal structure and exact operation of HashTable is out of the scope of this document, this document serves to inform you of the API's available and how best to use them. For a more detailed picture of the HashTable see Zend/zend_hash.h.

Unless otherwise stated, these functions all return FAILURE if the requested operation fails for any reason, otherwise SUCCESS is returned.

Nota:

It is important to remember that ordinarily HashTable API functions expect key lengths to be the length of the null terminated string, including the null termination, in other words they expect strlen(key) + 1

Below are some typedefs you should know when interacting with HashTable. They are mostly self explanitory and will allow the Hacker to fully understand the prototypes below properly.

typedef ulong (*hash_func_t)(const char *arKey, uint nKeyLength); /* mostly redundant */
typedef int  (*compare_func_t)(const void *, const void * TSRMLS_DC); /* comparison function */
typedef void (*sort_func_t)(void *, size_t, register size_t, compare_func_t TSRMLS_DC); /* sorting function */
typedef void (*dtor_func_t)(void *pDest); /* destructor function */
typedef void (*copy_ctor_func_t)(void *pElement); /* copy constructor */
typedef void (*copy_ctor_param_func_t)(void *pElement, void *pParam); /* copy with argument constructor */
typedef int (*apply_func_t)(void *pDest TSRMLS_DC); /* apply function */
typedef int (*apply_func_arg_t)(void *pDest, void *argument TSRMLS_DC); /* apply with argument function */
typedef int (*apply_func_args_t)(void *pDest TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key); /* apply with multiple arguments function */
HashTable API
int zend_hash_init(HashTable* ht, uint size, hash_func_t hash, dtor_func_t destructor, zend_bool persistent)
Initializes the hash table to hold at least size elements, hash exists for historical reasons and is always ignored, zend_inline_hash_func is always used as the hashing function. destructor may be NULL.
int zend_hash_add(HashTable* ht, const char* key, uint klen, void* data, uint dlen, void** dest)
adds data to the table using the specified key, where the key is length bytes long (and will be copied from key to the table). If the key is set FAILURE will be returned.
int zend_hash_update(HashTable* ht, const char* key, uint klen, void* data, uint dlen, void** dest)
adds data to the table using the specified key, where the key is length bytes long (and will be copied from key to the table). If the key has been set previously the old data has dtor_func_t called on it and the existing data is replaced with data
int zend_hash_find(HashTable* ht, const char* key, uint klen, void** data)
searches the table for key, setting *data and returning SUCCESS if it is found.
zend_bool zend_hash_exists(HashTable* ht, const char* key, uint klen)
returns positively if key is found in ht
int zend_hash_del(HashTable* ht, const char* key, uint klen)
removes the entry identified by key from the table if found
int zend_hash_index_update(HashTable* ht, ulong index, void* data, uint dsize, void** dest)
updates the entry at index in ht, with the data at data
int zend_hash_index_del(HashTable* ht, ulong index)
deletes the entry at index from ht
int zend_hash_index_find(HashTable* ht, ulong index, void** data)
redirects *data to the data identified by index in ht
int zend_hash_index_exists(HashTable* ht, ulong index)
returns positively if index is found in ht
ulong zend_hash_next_free_element(HashTable* ht)
returns the index of the next free element in ht
Precautie

zend_hash_* functions that accept void* data should normally cast it to (void**) (ie, (void**) &data)

Traversing the HashTable is often necessary, to do this you provide a pointer to a HashTable, with an optional HashPosition - a structure internal to the HashTable API that allows traversal not to affect the internal position of HashTable. The following traversal functions are provided, and an example usage found below.

HashTable Traversal API
int zend_hash_internal_pointer_reset(HashTable* ht)
resets the internal pointer of ht to the start
int zend_hash_internal_pointer_reset_ex(HashTable* ht, HashPosition position)
sets position the the start of ht
int zend_hash_get_current_data(HashTable* ht, void* data)
gets the data at the current position in ht, data should be cast to void**, ie: (void**) &data
int zend_hash_get_current_data_ex(HashTable* ht, void* data, HashPosition position)
sets data to the data at position in ht
int zend_hash_get_current_key(HashTable* ht, void* data, char**key, uint klen, ulong index, zend_bool duplicate)
sets key, klen, and index from the key information at the current position. The possible return values HASH_KEY_IS_STRING and HASH_KEY_IS_LONG are indicative of the kind of key found at the current posision.
int zend_hash_get_current_key_ex(HashTable* ht, void* data, char**key, uint klen, ulong index, zend_bool duplicate, HashPosition position)
sets key, klen, and index from the key information at position. The possible return values HASH_KEY_IS_STRING and HASH_KEY_IS_LONG are indicative of the kind of key found at position.
int zend_hash_move_forward(HashTable* ht)
moves the internal pointer of ht to the next entry in ht
int zend_hash_move_forward_ex(HashTable* ht, HashPosition position)
moves position to the next entry in ht

The functions above allow traversal over a HashTable to be much like a normal loop, which will look something like:

HashPosition position;
zval **data = NULL;

for (zend_hash_internal_pointer_reset_ex(ht, &position);
     zend_hash_get_current_data_ex(ht, (void**) &data, &position) == SUCCESS;
     zend_hash_move_forward_ex(ht, &position)) {

     /* by now we have data set and can use Z_ macros for accessing type and variable data */

     char *key = NULL;
     uint  klen;
     ulong index;

     if (zend_hash_get_current_key_ex(ht, &key, &klen, &index, 0, &position) == HASH_KEY_IS_STRING) {
         /* the key is a string, key and klen will be set */
     } else {
         /* we assume the key to be long, index will be set */
     }
}

Nota:

If a HashTable has been passed into the engine, it is a good idea to use the zend_hash_*_ex API to avoid unexpected behaviour in userland.

Nota:

If a duplicate of the key is requested and HAS_KEY_IS_STRING is returned the caller must efree the duplicated key

In addition to traversal, the engine provides API functions for merging, copying, and comparing HashTables. These are all concepts that the Hacker should be familiar with. A concept possibly not in the repertoire of the Hacker is applying, which is lamens terms is functionality of the HashTable API allowing the Hacker to pass a callback function to be executed on every entry in a HashTable.

Copying, Merging and Sorting
void zend_hash_copy(HashTable *target, HashTable *source, copy_ctor_func_t pCopyConstructor, void *tmp, uint size)
Copies the contents of source to target. tmp should be an unallocated temporary pointer of the appropriate type, used during copying. size is the size of each element.
void zend_hash_merge(HashTable *target, HashTable *source, copy_ctor_func_t pCopyConstructor, void *tmp, uint size, zend_bool overwrite)
Merges the contents of source into destination, replacing existing entries only where overwrite is true.
void int zend_hash_sort(HashTable *ht, sort_func_t sort_func, compare_func_t compare_func, int renumber TSRMLS_DC)
renumber controls if indexes should be preserved, see the typedefs at the start of this section for more information

Nota:

When a function accepts a copy_ctor_func_t pCopyConstructor, the function passed with be executed upon creation of every new entry in the HashTable. The most common copy constructor used within the engine is a wrapper around zval_copy_ctor, the macro ZVAL_COPY_CTOR.

Working with Arrays
Working with Objects
Working with Variables


Working with Objects

Working with HashTable
Writing Functions
Working with Variables


Writing Functions

Functions and Methods in PHP take much the same form, a method is simply a function with a specific scope; the scope of their class entry. The Hacker will read about class entries in other sections of the Hacker's guide. The purpose of this section is to introduce the Hacker to the anatomy of a function or method; the Hacker will learn how to define functions, how to accept variables and how to return variables to the programmer of PHP.

The anatomy of a function could not be simpler:

PHP_FUNCTION(hackers_function) {
  /* your accepted arguments here */
  long number;

  /* accepting arguments */
  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &number) != SUCCESS) {
      return;
  }

  /* do some work on the input */
  number *= 2;

  /* set return value */
  RETURN_LONG(number);
}

The PHP_FUNCTION(hackers_function) preprocessor instruction will result in the following declaration:

void zif_hackers_function(INTERNAL_FUNCTION_PARAMETERS)

INTERNAL_FUNCTION_PARAMETERS is defined as a macro and explained in the following table:

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. |

For clarity, the fully expanded declaration for PHP_FUNCTION(hackers_function) looks like:

void zif_hackers_function(int ht, zval* return_value, zval** return_value_ptr, zval* this_ptr, int return_value_used)

The presence of this_ptr may be confusing, classes are covered in detail in later sections, suffice to say that PHP_METHOD(MyClass, hackersFunction) would result in the following declaration:

void zim_MyClass_hackersFunction(INTERNAL_FUNCTION_PARAMETERS)

hackers_function doesn't do anything useful, it accepts a number using the zend_parse_parameters API, doubles it, and returns it to the engine. It is obvious that a normal function would have to do something more complex than double the input, for the purposes of education we are keeping it simple. On entry to the function return_value is allocated and initialized to null, making null the default return value of any function in PHP.

If zend_parse_parameters does not recieve what is specified by the Hacker as the correct arguments, and the arguments recieved cannot be converted to conform with type_spec an error will be raised, and by convention, the Hacker should return immediately.

Nota:

Arrays, Objects, and Resources cannot be converted.

Parsing Parameters Prototypes
int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...)
int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...)
int zend_parse_parameter(int flags, int arg_num TSRMLS_DC, zval **arg, const char *spec, ...)

Nota:

zend_parse_parameter is available from version 5.5, it behaves like zend_parse_parameters_ex except that instead of reading the arguments from the stack, it receives a single zval to convert, which may be changed in place.

Nota:

flags is intended to be a mask, currently only ZEND_PARSE_PARAMS_QUIET will have any impact (supress warnings)

The variable arguments recieved by these API functions are expected to be the address of C variables, and should be considered the output of the zend_parse_parameters API functions.

Type Specifiers
Spec | Type | Locals
a | array | zval*
A | array or object | zval*
b | boolean | zend_bool
C | class | zend_class_entry*
d | double | double
f | function | zend_fcall_info*, zend_fcall_info_cache*
h | array | HashTable*
H | array or object | HashTable*
l | long | long
L | long (limits out-of-range LONG_MAX/LONG_MIN) | long
o | object | zval*
O | object (of specified zend_class_entry) | zval*, zend_class_entry*
p | string (a valid path) | char*, int
r | resource | zval*
s | string | char*, int
z | mixed | zval*
Z | mixed | zval**

Nota:

Where the type specifier is O, the local zend_class_entry* is to be considered input (part of the type spec) to zend_parse_parameter

Advanced Type Specifiers
Spec | Description
* | a variable number of argument of the preceeding type, 0 or more
+ | a variable number of argument of the preceeding type, 1 or more
| | indicates that the remaining parameters are optional
/ | SEPARATE_ZVAL_IF_NOT_REF on the parameter it follows
! | the preceeding parameter can be of the specified type or null For 'b', 'l' and 'd', an extra argument of type zend_bool* must be passed after the corresponding bool*, long* or double* addresses which will be set true if null is recieved.

Nota:

Consult README.PARAMETER_PARSING_API included in source distributions for more information on parsing parameters

Once the Hacker's function has executed whatever it was implemented to execute, it is time to set the return_value for the engine. The RETURN_ and RETVAL_ macros are just wrappers around Z_*_P macros that work with return_value.

Nota:

RETURN_ macros cause execution to leave the function immediately (ie: return;), while RETVAL_ macros allow execution to continue after return_value has been set.

The Hacker should now have a reasonable understanding of the anatomy of a function, and to some degree, the anatomy of a method.

Working with Objects
Writing Classes
Nucleul PHP: Ghidul unui hacker


Writing Classes

Writing Functions
Working with Resources
Nucleul PHP: Ghidul unui hacker


Working with Resources

This section will serve to introduce the Hacker to the concept and usage of Resources in PHP.

Writing Classes
Working with INI settings
Nucleul PHP: Ghidul unui hacker


Working with INI settings

Working with Resources
Working with streams
Nucleul PHP: Ghidul unui hacker


Working with streams

Nota:

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
The "counter" Extension - A Continuing Example
Nucleul PHP: Ghidul unui hacker


The "counter" Extension - A Continuing Example

Cuprins

  • Instalarea / configurarea
  • Constante predefinite
  • Exemple
  • 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.

Nota: "counter" serves no practical purpose whatsoever, as the functionality it provides is far more effectively implemented by appropriate userland code.

Working with streams
Instalarea / configurarea
Nucleul PHP: Ghidul unui hacker


Instalarea / configurarea

Cuprins

  • Introducere
  • Configura?ia la rulare
  • Tipurile resurselor
The "counter" Extension - A Continuing Example
Introducere
The "counter" Extension - A Continuing Example


Introducere

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.

Instalarea / configurarea
Configura?ia la rulare
Instalarea / configurarea


Configura?ia la rulare

Comportamentul acestor func?ii este afectat de parametrii stabili?i în 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 |

Pentru mai multe detalii ?i defini?ii ale modurilor PHP_INI_* accesa?i 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.
Introducere
Tipurile resurselor
Instalarea / configurarea


Tipurile resurselor

The "counter" extension defines one resource type: a counter.

Configura?ia la rulare
Constante predefinite
Instalarea / configurarea


Constante predefinite

Constantele de mai jos sunt definite de aceasta extensie ?i vor fi disponibile doar daca aceasta extensie a fost compilata în interiorul PHP, sau a fost încarcata dinamic în timpul rularii.

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.
Tipurile resurselor
Exemple
The "counter" Extension - A Continuing Example


Exemple

Cuprins

  • Basic interface
  • Extended interface
  • Objective interface
Constante predefinite
Basic interface
The "counter" Extension - A Continuing Example


Basic interface

The basic interface provides three simple functions, illustrated here:

Example #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);
?>

Exemplul de mai sus va afi?a:

  0   1   0

The basic interface also provides a number of INI settings.

Exemple
Extended interface
Exemple


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.

Example #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
Exemple


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.

Example #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
Exemple


The Counter class

Introducere

Represents a single counter object.

Sinopsisul clasei

Counter {
__construct ( string $name [, integer $initial_value [, integer $flags ]] )
integer getValue ( void )
bumpValue ( integer $offset )
voidresetValue ( void )
mixed getMeta ( integer $attribute )
static Counter getNamed ( string $name )
static voidsetCounterClass ( string $name )
}

Cuprins

  • 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.

Descrierea

Counter::__construct ( string $name [, integer $initial_value [, integer $flags ]] )

Creates an instance of a Counter which maintains a single numeric value.

Parametri

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.

Valorile întoarse

Returns a Counter object on success.

Erori/Excep?ii

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.

Descrierea

integer Counter::getValue ( void )

Counter::getValue() returns the current value of a counter.

Valorile întoarse

Counter::getValue() returns an integer.

A se vedea ?i

  • 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.

Descrierea

Counter::bumpValue ( integer $offset )

Counter::bumpValue() updates the current value of a counter.

Parametri

offset
The amount by which to change the counter's value. Can be negative.

A se vedea ?i

  • 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.

Descrierea

voidCounter::resetValue ( void )

Counter::resetValue() resets the current value of a counter to its original initial value.

A se vedea ?i

  • 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.

Descrierea

mixed Counter::getMeta ( integer $attribute )

Counter::getMeta() returns metainformation about a counter.

Parametri

attribute
The metainformation to retrieve.

Valorile întoarse

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.

Descrierea

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.

Parametri

name
The counter name to search for.

Valorile întoarse

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().

Descrierea

static voidCounter::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.

Parametri

name
The name of the class to use.
Counter::getNamed
Basic
Counter


The basic interface

Cuprins

  • 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.

Descrierea

integer counter_get ( void )

counter_get() returns the current value of the basic interface's counter.

Valorile întoarse

counter_get() returns an integer.

A se vedea ?i

  • 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.

Descrierea

voidcounter_bump ( integer $offset )

counter_bump() updates the current value of the basic interface's counter.

Parametri

offset
The amount by which to change the counter's value. Can be negative.

A se vedea ?i

  • 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.

Descrierea

voidcounter_reset ( void )

counter_reset() resets the current value of the basic interface's counter to its original initial value.

A se vedea ?i

  • 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

Cuprins

  • 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.

Descrierea

resource counter_create ( string $name [, integer $initial_value [, integer $flags ]] )

Creates a counter which maintains a single numeric value.

Parametri

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.

Valorile întoarse

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.

Descrierea

integer counter_get_value ( resource $counter )

counter_get_value() returns the current value of a counter resource.

Parametri

counter
The counter resource to operate on.

Valorile întoarse

counter_get_value() returns an integer.

A se vedea ?i

  • 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.

Descrierea

voidcounter_bump_value ( resource $counter , integer $offset )

counter_bump_value() updates the current value of a counter resource.

Parametri

counter
The counter resource to operate on.
offset
The amount by which to change the counter's value. Can be negative.

A se vedea ?i

  • 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.

Descrierea

voidcounter_reset_value ( resource $counter )

counter_reset_value() resets the current value of a counter resource to its original initial value.

Parametri

counter
The counter resource to operate on.

A se vedea ?i

  • 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.

Descrierea

mixed counter_get_meta ( resource $counter , integer $attribute )

counter_get_meta() returns metainformation about a counter resource.

Parametri

counter
The counter resource to operate on.
attribute
The metainformation to retrieve.

Valorile întoarse

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.

Descrierea

resource Counter::getNamed ( string $name )

counter_get_named() returns an existing counter by name if that name exists, or NULL otherwise.

Parametri

name
The counter name to search for.

Valorile întoarse

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

Cuprins

  • 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
Nucleul PHP: Ghidul unui hacker


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 Aspecte generale privind instalarea. 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.

Sfat

The version of autoconf you have installed makes a difference when developing an extension. For PHP 5.3 and earlier, you will have the best results with autoconf version 2.13 but versions up to and including 2.59 will work. For PHP 5.4 and later the oldest autoconf version you can use is 2.59 and you will have better results with later versions.

Example #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.

Example #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
...

Nota:

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.

Example #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.

Example #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.

Example #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

Cuprins

  • 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
Nucleul PHP: Ghidul unui hacker


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:

Example #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:

Nota: 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.

    Nota: 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:

Example #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:

Example #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.

Nota:

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.

Example #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:

Example #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:

Example #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:

Example #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:

Example #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

Nota: 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.

Nota: 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.

Avertizare

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():

Example #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:

Example #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
PDO Driver How-To
Extension structure


PDO Driver How-To

Cuprins

  • 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.

Testing an extension
Prerequisites
Nucleul PHP: Ghidul unui hacker


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.

Example #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.

Nota:

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.

Example #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:

Example #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.

Nota:

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)
Avertizare

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
Nucleul PHP: Ghidul unui hacker


Zend Engine 2 API reference

Extension FAQs
Zend Engine 2 Opcodes
Nucleul PHP: Ghidul unui hacker


Zend Engine 2 Opcodes

Cuprins

  • Opcode Descriptions and Examples

When parsing PHP files, Zend Engine 2 generates a series of operation codes, commonly known as "opcodes", representing the function of the code. This part of the manual details those opcodes and their behaviour.

Opcodes may be dumped for a given PHP file using the vld extension (see » http://pecl.php.net/package/vld).

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 | JMP | yes
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 | CONT | yes
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 | INIT_NS_FCALL_BY_NAME | 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 | GOTO | no
101 | EXT_STMT | yes
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 | RETURN_BY_REF | 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 | DECLARE_CONST | no
144 | ADD_INTERFACE | no
145 | DECLARE_INHERITED_CLASS_DELAYED | 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
154 | ZEND_ADD_TRAIT | no
155 | ZEND_BIND_TRAITS | no
156 | ZEND_SEPARATE | no
157 | ZEND_FETCH_CLASS_NAME | no
158 | ZEND_CALL_TRAMPOLINE | no
159 | ZEND_DISCARD_EXCEPTION | no
160 | ZEND_YIELD | no
161 | ZEND_GENERATOR_RETURN | no
162 | ZEND_FAST_CALL | no
163 | ZEND_FAST_RET | no
164 | ZEND_RECV_VARIADIC | no
165 | ZEND_SEND_UNPACK | no
166 | ZEND_POW | no
167 | ZEND_ASSIGN_POW | no
168 | ZEND_BIND_GLOBAL | no
169 | ZEND_COALESCE | no
170 | ZEND_SPACESHIP | no
171 | ZEND_DECLARE_ANON_CLASS | no
172 | ZEND_DECLARE_ANON_INHERITED_CLASS | no
Zend Engine 2 API reference
Opcode Descriptions and Examples
Nucleul PHP: Ghidul unui hacker


Opcode Descriptions and Examples

Cuprins

  • 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
  • CONT
  • DECLARE_CLASS
  • DECLARE_CONST
  • DECLARE_FUNCTION
  • DECLARE_INHERITED_CLASS
  • DECLARE_INHERITED_CLASS_DELAYED
  • DIV
  • DO_FCALL
  • DO_FCALL_BY_NAME
  • ECHO
  • END_SILENCE
  • EXIT
  • EXT_FCALL_BEGIN
  • EXT_FCALL_END
  • EXT_NOP
  • EXT_STMT
  • FE_FETCH
  • FE_RESET
  • 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
  • FREE
  • GOTO
  • HANDLE_EXCEPTION
  • INCLUDE_OR_EVAL
  • INIT_ARRAY
  • INIT_FCALL_BY_NAME
  • INIT_METHOD_CALL
  • INIT_NS_FCALL_BY_NAME
  • INIT_STATIC_METHOD_CALL
  • INIT_STRING
  • INSTANCEOF
  • IS_EQUAL
  • IS_IDENTICAL
  • IS_NOT_EQUAL
  • IS_NOT_IDENTICAL
  • IS_SMALLER
  • IS_SMALLER_OR_EQUAL
  • ISSET_ISEMPTY_DIM_OBJ
  • ISSET_ISEMPTY_PROP_OBJ
  • ISSET_ISEMPTY_VAR
  • JMP
  • JMPNZ
  • JMPNZ_EX
  • JMPZ
  • JMPZ_EX
  • JMPZNZ
  • 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
  • RETURN_BY_REF
  • 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_DECLARE_LAMBDA_FUNCTION
  • ZEND_JMP_SET
Zend Engine 2 Opcodes
ADD
Zend Engine 2 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 Descriptions and Examples
ADD_ARRAY_ELEMENT
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


ADD_CHAR

PHP code

<?php
/*
 * add regular characters in encapsed string
 * opcode number: 54
 */
echo "$a ";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ADD_VAR |  |  |  | !0
 | 1 | ADD_CHAR |  |  |  | 32
 | 2 | ECHO |  |  |  |
 | 3 | RETURN |  |  |  | 1
ADD_ARRAY_ELEMENT
ADD_INTERFACE
Opcode Descriptions and Examples


ADD_INTERFACE

PHP code

<?php
/*
 * adds an implemented interface to a class declaration
 * opcode number: 144
 */
interface iA {
}

class A implements iA {
}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
 | 1 | DECLARE_CLASS |  |  |  | 'a'
 | 2 | ADD_INTERFACE |  |  |  | 'iA'
 | 3 | VERIFY_ABSTRACT_CLASS |  |  |  |
 | 3 | RETURN |  |  |  | 1
ADD_CHAR
ADD_STRING
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


CAST

PHP code

<?php
/*
 * casts value1 as type value2 (type in extended_value)
 * opcode number: 21
 */
echo (int)1;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | CAST |  | 4 | ~0 | 1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
CASE
CATCH
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
CONT
Opcode Descriptions and Examples


CONT

PHP code

<?php
/*
 * Continue next iteration of current loop level
 * opcode number: 51
 */
$foo = false;
while(!$foo) {
    $foo = true;
    continue;
}
?>

PHP opcodes

Function name: (null)

compiled vars: !0 = $foo

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0, false
7 | 1 | BOOL_NOT |  |  | ~1 | !0
 | 2 | JMPZ |  |  |  | ~1, ->5
8 | 3 | ASSIGN |  |  |  | !0, true
9 | 4 | CONT |  |  |  | 1
10 | 5 | JMP |  |  |  | ->1
12 | 6 | RETURN |  |  |  | 1
CONCAT
DECLARE_CLASS
Opcode Descriptions and Examples


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
CONT
DECLARE_CONST
Opcode Descriptions and Examples


DECLARE_CONST

PHP code

<?php
/*
 *
 * opcode number: 143
 * No sample PHP yet */
?>
DECLARE_CLASS
DECLARE_FUNCTION
Opcode Descriptions and Examples


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_CONST
DECLARE_INHERITED_CLASS
Opcode Descriptions and Examples


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
DECLARE_INHERITED_CLASS_DELAYED
Opcode Descriptions and Examples


DECLARE_INHERITED_CLASS_DELAYED

PHP code

<?php
/*
 *
 * opcode number: 145
 * No sample PHP yet */
?>
DECLARE_INHERITED_CLASS
DIV
Opcode Descriptions and Examples


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_DELAYED
DO_FCALL
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


EXT_FCALL_BEGIN

PHP code

<?php
/*
 *
 * opcode number: 102
 * No sample PHP yet */
?>
EXIT
EXT_FCALL_END
Opcode Descriptions and Examples


EXT_FCALL_END

PHP code

<?php
/*
 *
 * opcode number: 103
 * No sample PHP yet */
?>
EXT_FCALL_BEGIN
EXT_NOP
Opcode Descriptions and Examples


EXT_NOP

PHP code

<?php
/*
 *
 * opcode number: 104
 * No sample PHP yet */
?>
EXT_FCALL_END
EXT_STMT
Opcode Descriptions and Examples


EXT_STMT

PHP code

<?php
/*
 *
 * opcode number: 101
 */
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
7 | 0 | EXT_STMT |  |  |  |
8 | 1 | RETURN |  |  |  | 1
EXT_NOP
FE_FETCH
Opcode Descriptions and Examples


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
EXT_STMT
FE_RESET
Opcode Descriptions and Examples


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
FETCH_CLASS
Opcode Descriptions and Examples


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
FE_RESET
FETCH_CONSTANT
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


FETCH_DIM_IS

PHP code

<?php
/*
 *
 * opcode number: 90
 * No sample PHP yet */
?>
FETCH_DIM_FUNC_ARG
FETCH_DIM_R
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


FETCH_OBJ_IS

PHP code

<?php
/*
 *
 * opcode number: 91
 * No sample PHP yet */
?>
FETCH_OBJ_FUNC_ARG
FETCH_OBJ_R
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


FETCH_OBJ_W

PHP code

<?php
/*
 * Fetch an object from the property of this object and write to the property of the fectched object.
 * opcode number: 85
 */
$foo = new stdclass;
$foo->bar = new stdclass;
$foo->bar->baz = 'quix';
?>

PHP opcodes

Function name: (null)

Compiled variables: !0 = $foo

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  | 4 | :0 | 'stdclass'
 | 1 | NEW |  |  |  | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0
7 | 4 | ZEND_FETCH_CLASS |  | 4 | :5 | 'stdclass'
 | 5 | NEW |  |  |  | :5
 | 6 | DO_FCALL_BY_NAME |  | 0 |  |
 | 7 | ZEND_ASSIGN_OBJ |  |  |  | !0, 'bar'
 | 8 | ZEND_OP_DATA |  |  |  |
8 | 9 | FETCH_OBJ_W |  |  |  | !0, 'bar'
 | 10 | ZEND_ASSIGN_OBJ |  |  |  | 'baz'
 | 11 | ZEND_OP_DATA |  |  |  | 'quix'
9 | 12 | RETURN |  |  |  | 1
FETCH_OBJ_UNSET
FETCH_R
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
FREE
Opcode Descriptions and Examples


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
FETCH_W
GOTO
Opcode Descriptions and Examples


GOTO

PHP code

<?php
/*
 *
 * opcode number: 100
 * No sample PHP yet */
?>
FREE
HANDLE_EXCEPTION
Opcode Descriptions and Examples


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
GOTO
INCLUDE_OR_EVAL
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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_NS_FCALL_BY_NAME
Opcode Descriptions and Examples


INIT_NS_FCALL_BY_NAME

PHP code

<?php
/*
 *
 * opcode number: 69
 * No sample PHP yet */
?>
INIT_METHOD_CALL
INIT_STATIC_METHOD_CALL
Opcode Descriptions and Examples


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_NS_FCALL_BY_NAME
INIT_STRING
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
IS_EQUAL
Opcode Descriptions and Examples


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
INSTANCEOF
IS_IDENTICAL
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


IS_SMALLER_OR_EQUAL

PHP code

<?php
/*
 * compares if value1 is less than or equal to value2
 * opcode number: 20
 */
echo (2 <= 1);
?>

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
ISSET_ISEMPTY_DIM_OBJ
Opcode Descriptions and Examples


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
IS_SMALLER_OR_EQUAL
ISSET_ISEMPTY_PROP_OBJ
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
JMP
Opcode Descriptions and Examples


JMP

PHP code

<?php
/*
 * Unconditonally jump to the address
 * opcode number: 42
 */
$foo = false;
while(!$foo) {
    $foo = true;
}
?>

PHP opcodes

Function name: (null)

compiled vars: !0 = $foo

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0, false
7 | 1 | BOOL_NOT |  |  | ~1 | !0
 | 2 | JMPZ |  |  |  | ~1, ->5
8 | 3 | ASSIGN |  |  |  | !0, true
9 | 4 | JMP |  |  |  | ->1
11 | 5 | RETURN |  |  |  | 1
ISSET_ISEMPTY_VAR
JMPNZ
Opcode Descriptions and Examples


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
JMP
JMPNZ_EX
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
JMPZ_EX
Opcode Descriptions and Examples


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
JMPZ
JMPZNZ
Opcode Descriptions and Examples


JMPZNZ

PHP code

<?php
/*
 * Jump to the address given in the operands if the value is zero;
 * jump to the address given in extended data if nonzero.
 * 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_EX
MOD
Opcode Descriptions and Examples


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
JMPZNZ
MUL
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
RETURN_BY_REF
Opcode Descriptions and Examples


RETURN_BY_REF

PHP code

<?php
/*
 *
 * opcode number: 111
 * No sample PHP yet */
?>
RETURN
SEND_REF
Opcode Descriptions and Examples


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_BY_REF
SEND_VAL
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


SEND_VAR_NO_REF

PHP code

<?php
/*
 *
 * opcode number: 106
 * No sample PHP yet */
?>
SEND_VAR
SL
Opcode Descriptions and Examples


SL

PHP code

<?php
/*
 * Shift bits of value1 to the left value2 steps (each step means "multiply by two")
 * 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
Opcode Descriptions and Examples


SR

PHP code

<?php
/*
 * Shift bits of value1 to the right value2 steps (each step means "divide by two")
 * 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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


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
Opcode Descriptions and Examples


USER_OPCODE

PHP code

<?php
/*
 *
 * opcode number: 150
 * No sample PHP yet */
?>
UNSET_VAR
VERIFY_ABSTRACT_CLASS
Opcode Descriptions and Examples


VERIFY_ABSTRACT_CLASS

PHP code

<?php
/*
 *
 * opcode number: 146
 * No sample PHP yet */
?>
USER_OPCODE
ZEND_DECLARE_LAMBDA_FUNCTION
Opcode Descriptions and Examples


ZEND_DECLARE_LAMBDA_FUNCTION

PHP code

<?php
/*
 *
 * opcode number: 153
 * No sample PHP yet */
?>
VERIFY_ABSTRACT_CLASS
ZEND_JMP_SET
Opcode Descriptions and Examples


ZEND_JMP_SET

PHP code

<?php
/*
 *
 * opcode number: 152
 * No sample PHP yet */
?>
ZEND_DECLARE_LAMBDA_FUNCTION
Zend Engine 1
Opcode Descriptions and Examples


Zend Engine 1

Cuprins

  • Old introduction
  • Streams API for PHP Extension Authors
  • API al Zend: Aprofundare în nucleul 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 the old ZE1 documentation is preserved here exactly as it was.

ZEND_JMP_SET
Old introduction
Nucleul PHP: Ghidul unui hacker


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

Nota:

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:

Example #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:

Example #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();
}

Example #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.

Nota: 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.

Nota: 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
API al Zend: Aprofundare în nucleul PHP
Zend Engine 1


API al Zend: Aprofundare în nucleul 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.

Avertizare

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

Nota:

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.
Avertizare

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.

Nota:

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:

Example #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.

Example #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)
    ZEND_FE_END
};

/* 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.)

Nota:

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.

Avertizare

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.

Example #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..

Example #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)
    ZEND_FE_END
};
You can see that the last entry in the list always has to be ZEND_FE_END. This marker has to be set for Zend to know when the end of the list of exported functions is reached.

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..

Example #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

Nota: 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)

Nota: 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.

Example #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.

Nota:

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..

Example #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..

Example #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.

Example #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.).

Example #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.):

Example #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
}

Example #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.

Nota:

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);
}

Nota:

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)

Nota:

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.

Nota:

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().

Example #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..

Example #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.

Example #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'";
?>

Exemplul de mai sus va afi?a:

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

API al Zend: Aprofundare în nucleul PHP
FAQ
Zend Engine 1


FAQ: Întrebari frecvente

  • Informa?ii generale
  • Mailing lists
  • Obtaining PHP
  • Database issues
  • Installation
  • Build Problems
  • Using PHP
  • Password Hashing — Safe Password Hashing
  • PHP and HTML
  • PHP and COM
  • Miscellaneous Questions
TSRM API
Informa?ii generale
Manualul PHP


Informa?ii generale

Aceasta sec?iune cuprinde cele mai generale întrebari despre PHP: ce este ?i ce face.

  1. Ce este PHP?
  2. De la ce vine PHP?
  3. Care este rela?ia dintre versiuni?
  4. Pot sa rulez mai multe veriuni de PHP in acela?i timp?
  5. Cred ca am gasit un bug! Cui ar trebui sa-i spun?
Ce este PHP?

Din prefa?a manualului:

PHP este un limbaj de scripting care poate fi inclus în HTML. O mare parte din sintaxa acestuia fiind imprumutata din C, Java ?i Perl cu alte câteva caracteristici specifice PHP adaugate în el. Scopul limbajului este sa ajute programatorii web sa scrie repede pagini generate dinamic.

De la ce vine PHP?

PHP vine de la PHP: Hypertext Preprocessor. Aceasta denumire creaza confuzii multora, deoarece primul cuvânt din acronim este însu?i acronimul. Un astfel de acronim se nume?te recursiv. Pentru informa?ii suplimentare, cei curio?i pot vizita » Dic?ionarul liber, on-line de termeni informatici sau » Înregistrarea Wikipedia despre acronime recursive.

Care este rela?ia dintre versiuni?

PHP/FI 2.0 este prima versiune a PHP ?i nu mai este între?inuta în prezent. PHP 3 este succesorul PHP/FI 2.0 ?i e mult mai placut. PHP 5 este genera?ia moderna a PHP, ce folose?te » Zend engine 2 care, printre altele, ofera multe facilita?i suplimentare de programare OOP.

Pot sa rulez mai multe veriuni de PHP in acela?i timp?

Da. Vezi fi?ierul INSTALL, care este inclus în codul sursa distribuit cu PHP.

Cred ca am gasit un bug! Cui ar trebui sa-i spun?

Ar trebui sa accesa?i PHP Bug Database ?i sa va asigura?i ca bug-ul gasit nu este deja cunoscut. Daca nu-l vede?i în baza de date, utiliza?i formularul de raportare pentru a comunica despre bug. Este important sa utiliza?i baza de date a bug-urilor în loc sa transmite?i doar un email catre una din listele po?tale, deoarece în acest fel bug-ului i se va atribui un numar de urmarire ?i apoi ve?i putea reveni pentru a verifica statutul bug-ului. Baza de date a bug-urilor poate fi gasita la » 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, Git, 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.

Informa?ii generale
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 Git 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 Git to get the absolute latest version of the source. For more information, go to » http://www.php.net/git.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?

Nota: Those marked with a * are to the best of our knowledge not thread safe; they are not recommended for use in a multi-threaded environment.

  • » 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 Git repository on my Windows machine, what do I need to compile it?

See the PHP Wiki for the latest instructions: » Step by Step Build Instructions

Where do I find the Browser Capabilities File?

You can find a browscap.ini file at » http://browscap.org/.

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. Why is the MySQL extension (ext/mysql) that I've been using for over 10 years discouraged from use? Is it deprecated? What do I use instead? How can I migrate?
  4. 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 Unix machines you can use PDO_ODBC or the Unified ODBC API.

On Windows machines you can also use PDO_SQLSRV or SQLSRV.

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.

Why is the MySQL extension (ext/mysql) that I've been using for over 10 years discouraged from use? Is it deprecated? What do I use instead? How can I migrate?

There are three MySQL extensions, as described under the Choosing a MySQL API section. The old API should not be used, it is deprecated as of PHP 5.5.0 and has been moved to PECL as of PHP 7.0.0. You are strongly encouraged to write all new code with either mysqli or PDO_MySQL.

Migration scripts are not available at this time, although the mysqli API contains both a procedural and OOP API, with the procedural version being similar to ext/mysql.

It is not possible to mix the extensions. So, for example, passing a mysqli connection to PDO_MySQL or ext/mysql will not work.

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, and almost any web server.

To install PHP, follow the instructions in Installarea ?i configurarea.

  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 7, XP, Vista, 2008, 2012 and up:

  • Go to Control Panel and open the System icon (Start ? Control Panel)

  • 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

Nota: 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 system's 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:

  • Go to Control Panel and open the System icon (Start ? Settings ? Control Panel ? System, or just Start ? Control Panel ? System)

  • 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 Git 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/libmysqlclient/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysqlclient/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 Git 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 Git 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/libmysqlclient/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysqlclient/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.

Nota:

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?
  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;
}
?>

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.

Nota: Nota asupra directivei: magic_quotes_gpc

Directiva magic_quotes_gpc are valoarea implicita on. În esen?a ea executa addslashes() asupra tuturor datelor GET, POST ?i COOKIE. stripslashes() poate fi utilizata pentru a elimina slash-urile suplimentare.

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.

Nota: Nota asupra directivei: magic_quotes_gpc

Directiva magic_quotes_gpc are valoarea implicita on. În esen?a ea executa addslashes() asupra tuturor datelor GET, POST ?i COOKIE. stripslashes() poate fi utilizata pentru a elimina slash-urile suplimentare.

How does the PHP directive register_globals affect me?
Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

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. 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

Nota:

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 affect 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.

Nota: register_globals: nota importanta

Începând cu PHP 4.2.0, valoarea implicita pentru directiva PHP register_globals este off. Comunitatea PHP îi încurajeaza pe to?i programatorii sa nu se bazeze pe aceasta directiva, dar sa utilizeze alte mijloace, cum ar fi 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.

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?

The available options are K (for Kilobytes), M (for Megabytes) and G (for Gigabytes; available since PHP 5.1.0), and are all case-insensitive. Anything else assumes bytes. 1M equals one Megabyte or 1048576 bytes. 1K equals one Kilobyte or 1024 bytes. These shorthand notations may be used in php.ini and in the ini_set() function.

Nota: 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?
  5. How do I store my salts?
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.

PHP 5.5 provides a native password hashing API that safely handles both hashing and verifying passwords in a secure manner. There is also » a pure PHP compatibility library available for PHP 5.3.7 and later.

Another option is the crypt() function, which supports several hashing algorithms in PHP 5.3 and later. 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 suggested algorithm to use when hashing passwords is Blowfish, which is also the default used by the password hashing API, as it is significantly more computationally expensive than MD5 or SHA1, while still being scalable.

Note that if you are using crypt() to verify a password, you will need to take care to prevent timing attacks by using a constant time string comparison. Neither PHP's == and === operators nor strcmp() perform constant time string comparisons. As password_verify() will do this for you, you are strongly encouraged to use the native password hashing API whenever possible.

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.

password_hash() will create a random salt if one isn't provided, and this is generally the easiest and most secure approach.

How do I store my salts?

When using password_hash() or crypt(), the return value includes the salt as part of the generated hash. This value should be stored verbatim in your database, as it includes information about the hash function that was used and can then be given directly to password_verify() or crypt() when verifying passwords.

The following diagram shows the format of a return value from crypt() or password_hash(). As you can see, they are self-contained, with all the information on the algorithm and salt required for future password verification.

The components of the value returned by password_hash and crypt: in order, the chosen algorithm, the algorithm's options, the salt used, and the hashed password.

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.

  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().

Example #1 A hidden HTML form element

<?php
    echo '<input type="hidden" value="' . htmlspecialchars($data) . '" />'."\n";
?>

Nota: 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.

Example #2 Data to be edited by the user

<?php
    echo "<textarea name='mydata'>\n";
    echo htmlspecialchars($data)."\n";
    echo "</textarea>";
?>

Nota: 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.

Example #3 In a URL

<?php
    echo '<a href="' . htmlspecialchars("/nextpage.php?stage=23&data=" .
        urlencode($data)) . '">'."\n";
?>

Nota: In fact you are faking a HTML GET request, therefore it's necessary to manually urlencode() the data.

Nota: 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'].

Nota:

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.

Nota:

Specifying array keys 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 = document.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.

Example #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?

The COM extension throws com_exception exceptions, which you can catch and then inspect the code member to determine what to do next.

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
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.

Example #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();

?>

PHP and COM
Anexe
FAQ


Anexe

  • Istoria PHP ?i a proiectelor asociate
    • Istoria PHP
    • Istoria proiectelor asociate cu PHP
    • Car?i despre PHP
    • Publica?ii despre PHP
  • Migrating from PHP 7.0.x to PHP 7.1.x
    • New features
    • New functions
    • New global constants
    • Backward incompatible changes
    • Deprecated features in PHP 7.1.x
    • Changed functions
    • Other changes
    • Windows Support
  • Migrating from PHP 5.6.x to PHP 7.0.x
    • Schimbari incompatibile în sens invers
    • New features
    • Deprecated features in PHP 7.0.x
    • Changed functions
    • New functions
    • New Classes and Interfaces
    • New Global Constants
    • Changes in SAPI Modules
    • Removed Extensions and SAPIs
    • Other Changes
  • Migrating from PHP 5.5.x to PHP 5.6.x
    • Backward incompatible changes
    • New features
    • Deprecated features in PHP 5.6.x
    • Changed functions
    • New functions
    • OpenSSL changes in PHP 5.6.x
    • Other changes to extensions
    • New global constants
  • Migrating from PHP 5.4.x to PHP 5.5.x
    • What has changed in PHP 5.5.x
    • Backward Incompatible Changes
    • New features
    • Deprecated features in PHP 5.5.x
    • Changed Functions
    • New Functions
    • New Classes and Interfaces
    • New Methods
    • Other changes to extensions
    • New Global Constants
    • Changes to INI file handling
    • Changes to PHP Internals
  • 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 in SAPI modules
    • Deprecated features in PHP 5.4.x
    • Changed Functions
    • New Functions
    • New Classes and Interfaces
    • New Methods
    • Removed Extensions
    • Other changes to extensions
    • 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
  • Migrarea de la PHP 5.1.x la PHP 5.2.x
    • Ce s-a schimbat în PHP 5.2.x
    • Schimbari incompatibile în sens invers
    • Noile mesaje de eroare
    • Schimbarile PHP în sus?inerea func?iilor datetime
    • Parametri noi
    • Func?ii noi
    • Metode noi
    • Extensiile eliminate
    • Extensii noi
    • Clase noi
    • Constante globale noi
    • Constante de clase noi
    • Noile directive de configurare INI
    • Raportarea erorilor
    • Alte îmbunata?iri
  • Migrarea de la PHP 5.0.x la PHP 5.1.x
    • Principalele facilita?i ale PHP 5.1.x
    • Modificari în manipularea referin?elor
    • Citirea []
    • Valorile întregi în parametrii func?iilor
    • Schimbari în clase ?i obiecte
    • Extensiile
    • Sus?inerea Datei/orei
    • Modificari în sus?inerea bazelor de date
    • Verificarea E_STRICT
  • Migrarea de la PHP 4 la PHP 5.0.x
    • Ce s-a schimbat în PHP 5.0.x
    • Schimbari incompatibile în sens invers
    • CLI ?i CGI
    • Migrarea fi?ierelor de configurare
    • Func?ii noi
    • Directive noi
    • Bazele de date
    • Noul Model de Obiecte
    • Raportarea erorilor
  • Depistarea erorilor (debugging) în PHP
    • Despre debugging în PHP
  • Op?iunile de configurare
    • Lista op?iunilor de configurare de baza
  • Directive php.ini
    • Lista directivelor php.ini
    • Lista sec?iunilor php.ini
    • Descrierea directivelor de baza ale php.ini
  • Lista/Categoriile extensiilor
    • În ordine alfabetica
    • Apartenen?a
    • Statutul
  • Lista pseudonimelor func?iilor
  • Lista cuvintelor rezervate
    • Lista cuvintelor-cheie
    • Clase predefinite
    • Constante predefinite
    • Lista altor cuvinte rezervate
  • Lisa tipurilor de resurse
  • Lista filtrelor disponibile
    • Filtrele string-urilor
    • Filtre de conversie
    • Filtrele de compresie
    • Filtrele de criptare
  • Lista transporturilor prin socket-e sus?inute
    • Domeniul Internet: TCP, UDP, SSL ?i TLS
    • Domeniul Unix: Unix ?i UDG
  • Tabelele de compara?ii ale tipurilor PHP
  • Lista semnelor interpretorului
  • Ghidul de stabilire a denumirilor de catre utilizatori
    • Spa?iul global de denumiri
    • Reguli
    • Sfaturi
  • Despre manual
    • Formate
    • Despre adnotarile utilizatorilor
    • Cum se cite?te defini?ia unei func?ii (prototipul)
    • Versiunile PHP documentate în acest manual
    • Cum sa gasim mai multa informa?ie despre PHP
    • Cum sa contribuim la îmbunata?irea documenta?iei
    • Cum generam formatele
    • Traduceri
  • Creative Commons Attribution 3.0
  • Listingul-indice
    • Listingul func?iilor ?i metodelor
    • Listingul exemplelor
  • Jurnalul modificarilor
Miscellaneous Questions
Istoria PHP ?i a proiectelor asociate
Manualul PHP


Istoria PHP ?i a proiectelor asociate

Cuprins

  • Istoria PHP
  • Istoria proiectelor asociate cu PHP
  • Car?i despre PHP
  • Publica?ii despre PHP

PHP a parcurs o cale lunga de la conceperea sa în mijlocul anilor 1990. La început modest, devenind apoi unul din cele mai proeminente limbaje care dirijeaza web-ul, evolu?ia PHP este o poveste pentru tocilari. Or, o astfel de cre?tere exploziva nu a fost o sarcina u?oara. Cei dintre voi interesa?i de a afla pe scurt cum PHP a crescut pâna la ceea ce este el în ziua de azi, citi?i în continuare. Daca dori?i sa atinge?i o parte din istoria Internetului, pute?i gasi versiuni mai vechi ale PHP în » muzeul PHP.

Anexe
Istoria PHP
Anexe


Istoria PHP

Unelte PHP, FI, Construction Kit ?i PHP/FI

PHP cum este cunoscut astazi este, de fapt succesorul unui produs numit PHP/FI. Creat în 1994 de catre Rasmus Lerdorf, prima încarnare a PHP a fost un simplu set de binare Common Gateway Interface (CGI) scrise în limbajul de programare C. Ini?ial folosit pentru urmarirea vizitelor la CV-ul sau on-line, el a numit suita de script-uri "Personal Home Page Tools", mai frecvent men?ionate ca "Unelte PHP". De-a lungul timpului, a aparut dorin?a de a avea mai multe func?ionalita?i, ?i Rasmus a rescris Uneltele PHP, producând o implementare mult mai mare ?i mai bogata. Acest nou model a fost capabil de interac?iune cu baze de date ?i mai mult, oferind un framework cu ajutorul carora utilizatorii puteau dezvolta aplicatii web simple ?i dinamice, cum ar fi car?ile de oaspe?i. În luna iunie a anului 1995, Rasmus » a lansat codul sursa pentru Uneltele PHP catre public, ceea ce a permis dezvoltatorilor sa-l foloseasca dupa cum considerau de cuviin?a. Acest lucru, de asemenea, a permis ?i a încurajat utilizatorii sa ofere remedieri pentru bug-uri în cod, ?i în general sa-l îmbunata?easca.

În luna septembrie a aceluia?i an, Rasmus a extins PHP ?i, pentru o perioada scurta de timp, chiar a renun?at la denumirea PHP. Acum, referindu-se la Unelte ca FI (prescurtarea de la "Forms Interpreter"), noua implementare a inclus o parte din func?ionalitatea de baza a PHP a?a cum o ?tim astazi. Ea a avut variabile ca în Perl, interpretare automata a variabilelor din formulare ?i sintaxa inclusa în HTML. Insa?i sintaxa a fost similara cu cea din Perl, de?i mult mai limitata, simpla, ?i oarecum inconsistenta. De fapt, pentru a încorpora codul într-un fi?ier HTML, dezvoltatorii trebuiau sa utilizeze comentarii HTML. De?i aceasta metoda nu a fost în întregime bine-primita, FI a continuat sa se bucure de o cre?tere ?i de acceptare ca un instrument CGI, dar înca nu chiar ca un limbaj. Cu toate acestea, acest lucru a început sa se schimbe în luna urmatoare; în octombrie 1995, Rasmus a lansat o rescriere completa a codului. Readucând denumirea PHP, a fost acum (pe scurt) numit "Personal Home Page Construction Kit", ?i a fost prima versiune ce s-a laudat cu ceea ce a fost considerat, la momentul respectiv, o interfa?a avansata de scripting. Limbajul a fost în mod inten?ionat conceput sa semene cu structura C, ceea ce facea mai simpla adop?ia sa pentru dezvoltatori familiariza?i cu C, Perl, ?i limbaje similare. Fiind pâna acum limitat doar la sisteme UNIX ?i sisteme compatibile POSIX, a început explorarea poten?ialului pentru o implementare Windows NT.

Codul iara?i a suferit o rescriere completa, ?i în aprilie 1996, combinând denumirile implementarilor din trecut, Rasmus a introdus PHP/FI. Aceasta implementare de genera?ia a doua a început sa evolueze cu adevarat PHP de la o suita de instrumente spre un limbaj de programare cu drepturi depline. Aceasta a inclus sus?inerea încorporata a bazelor de date DBM, mSQL Postgres95, cookies, suport pentru func?ii definite de utilizator, ?i multe altele. În acea luna iunie, lui PHP/FI i-a fost oferit un statut de versiune 2.0. Un fapt interesant despre aceasta este ca a fost doar o singura versiune deplina de PHP 2.0. Când în cele din urma ea a absolvit statutul de versiune beta în noiembrie 1997, motorul de interpretare care statea la baza a fost deja rescris în întregime.

De?i a trait o via?a de dezvoltare scurta, el a continuat sa se bucure de o popularitate în cre?tere în lumea înca tânara a dezvoltarii web. În 1997 ?i 1998, PHP/FI a avut un cult de câ?iva mii de utilizatori în jurul lumii. Un sondaj Netcraft din luna mai, 1998, a indicat ca aproape 60.000 de domenii au raportat prezen?a antetelor care con?in "PHP", indicând faptul ca serverul gazda într-adevar îl avea instalat. Acest numar echivala cu aproximativ 1% din toate domeniile pe Internet existente la momentul respectiv. În ciuda acestor cifre impresionante, maturizarea PHP/FI era condamnata la limitari; în timp ce au existat mai mul?i contribuabili mici, el înca mai era dezvoltat cu precadere de catre un singur individ.

Example #1 Exemplu de cod PHP/FI

<!--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 a fost prima versiune care se aseamana mult cu PHP cum el este astazi. Gasind PHP/FI 2.0 înca ineficient ?i fara func?ionalita?ile de care aveau nevoie pentru a sus?ine o aplica?ie de comer? electronic, pe care o dezvoltau pentru un proiect universitar, Andi Gutmans ?i Zeev Suraski de la Tel Aviv, Israel, au început înca o rescriere completa a interpretorului de baza în 1997. Apropiindu-se de Rasmus on-line, ei au discutat diverse aspecte ale implementarii curente ?i redezvoltarea lor a PHP. Într-un efort de a îmbunata?i motorul ?i a continua dezvoltarea pe baza de utilizatori deja existenta a PHP/FI, Andi, Rasmus, ?i Zeev au decis sa colaboreze în dezvoltarea unui nou limbaj de programare independent. Acest cu totul nou limbaj a fost lansat sub o alta denumire, care a eliminat implicarea uzului pur personal, pe care îl implica denumirea PHP/FI 2.0. Acesta a fost redenumit pur ?i simplu "PHP", semnificând un acronim recursiv - PHP: Hypertext Preprocessor.

Unul dintre cele mai mari avantaje ale PHP 3.0 au fost facilita?ile puternice de extindere. Adi?ional la oferirea utilizatorilor finali a unei interfe?e mature pentru multiple baze de date, protocoale ?i API-uri, u?urin?a de a extinde însu?i limbajul a atras zeci de dezvoltatori care au creat o varietate de module. Probabil aceasta a fost cheia PHP 3.0 catre un succes imens. Alte facilita?i-cheie introduse în PHP 3.0 au inclus sus?inerea programarii orientate pe obiecte ?i o mult mai puternica ?i consistenta sintaxa a limbajului.

În iunie 1998, cu mul?i dezvoltatori noi din întreaga lume aderând la efort, PHP 3.0 a fost anun?at de catre noua Echipa de Dezvoltare PHP ca succesor oficial al PHP/FI 2.0. Dezvoltarea activa a PHP/FI 2.0, care practic încetase în noiembrie a anului precedent, a fost acum încheiata oficial. Dupa aproximativ noua luni de testare publica deschisa, când s-a dat anun?ul despre lansarea oficiala a PHP 3.0, el deja era instalat pe mai mult de 70.000 domenii din întreaga lume, ?i nu mai era limitat la sisteme de operare POSIX compatibile. O pondere relativ mica de domenii, care raportau instalarea PHP, erau gazduite pe servere ce rulau Windows 95, 98, ?i NT, ?i Macintosh. La momentul de vârf, PHP 3.0 a fost instalat pe aproximativ 10% din serverele web din Internet.

PHP 4

Catre iarna anului 1998, la scurt timp dupa ce PHP 3.0 a fost lansat oficial, Andi Gutmans ?i Zeev Suraski au început lucrul asupra rescrierii nucleului PHP. Scopurile reproiectarii erau de a îmbunata?i performan?a aplica?iilor complexe ?i de a îmbunata?i modularitatea bazei de coduri-sursa ale PHP. Astfel de aplica?ii puteau fi realizate datorita noilor facilita?i din PHP 3.0, precum ?i a sus?inerii unei game largi de baze de date ?i interfe?e API ale ter?ilor producatori, însa PHP 3.0 nu fusese proiectat sa lucreze cu astfel de aplica?ii complexe în mod eficient.

Noul nucleu, denumit 'Zend Engine' (compus din numele autorilor, Zeev ?i Andi), a facut fa?a cerin?elor de proiect cu succes, ?i a fost prezentat pentru prima data la mijlocul anului 1999. PHP 4.0, bazat pe acest nucleu ?i în cuplu cu o gama larga de facilita?i noi a fost lansat oficial în mai 2000, aproape doi ani dupa predecesorul sau. Suplimentar la performan?a îmbunata?ita substan?ial în aceasta versiune, PHP 4.0 a inclus alte facilita?i de baza, cum ar fi sus?inerea mult mai multor servere Web, sesiunilor HTTP, buferizarea ie?irii, metode mai securizate de gestionare a datelor introduse de utilizatori ?i câteva construc?ii noi ale limbajului.

PHP 5

PHP 5 a fost lansat în iulie 2004 dupa o lunga perioada de dezvoltare ?i câteva lansari preliminare. El este condus de nucleul sau, Zend Engine 2.0 cu un nou model de obiecte ?i o duzina de alte noi facilita?i.

Echipa de dezvoltare a PHP include zeci de programatori, precum ?i alte zeci de persoane care lucreaza la proiecte PHP conexe ?i de suport, cum ar fi PEAR, PECL ?i documentare, precum ?i o infrastructura de re?ea cu peste o suta servere web individuale pe ?ase din cele ?apte continente ale lumii. De?i este numai o estimare bazata pe statistici din anii anteriori, putem cu siguran?a sa presupunem ca PHP este acum instalat pe zeci sau poate chiar sute de milioane de domenii din întreaga lume.

Istoria PHP ?i a proiectelor asociate
Istoria proiectelor asociate cu PHP
Istoria PHP ?i a proiectelor asociate


Istoria proiectelor asociate cu PHP

PEAR

» PEAR, Repozitoriul de Extensii ?i Aplica?ii PHP (original, Repozitoriul de Extensii ?i Suplimente PHP) este versiunea PHP a claselor fundamentale, care în viitor poate deveni una din modalita?ile cheie de distribuire a extensiilor PHP între programatori.

PEAR s-a nascut din discu?iile purtate la Întrunirea Programatorilor PHP (PHP Developers' Meeting (PDM)), care a avut loc în ianuarie 2000 în Tel Aviv. PEAR a fost creat de catre Stig S. Bakken ?i este dedicat fiicei sale întâi nascute, Malin Bakken.

De la începutul anului 2000, PEAR a ajuns sa devina un proiect mare, semnificativ, cu un numar mare de programatori lucrând asupra implementarii unor func?ionalita?i standarde, reutilizabile, pentru beneficiul întregii comunita?i PHP. În prezent PEAR include o larga varietate de clase fundamentale de infrastructura pentru acces la baze de date, memorizarea con?inutului, calcule matematice, comer? electronic ?i multe altele.

Mai multe informa?ii despre PEAR pot fi gasite în » manual.

Ini?iativa de Asigurare a Calita?ii în PHP

» Ini?iativa de Asigurare a Calita?ii în PHP a fost inaugurata în vara anului 2000 ca raspuns la criticile, precum ca versiunile PHP nu erau suficient testate pentru a putea fi puse în medii de producere. Acum echipa consta dintr-un grup de programatori de baza care poseda o buna în?elegere a codurilor-sursa PHP. Ace?ti programatori î?i petrec o buna parte din timp localizând ?i corectând gre?elile din PHP. În plus, exista mul?i al?i membri ai echipei, care testeaza ?i î?i expun parerea asupra acestor corectari, folosind o larga varietate de platforme.

PHP-GTK

» PHP-GTK este solu?ia PHP pentru scrierea aplica?iilor GUI de partea clientului. Andrei Zmievski î?i aminte?te planificarea ?i procesul de creare a PHP-GTK:

Programarea GUI întotdeauna îmi trezea interes, ?i am aflat ca Gtk+ este un instrumentar foarte frumos, cu excep?ia ca programarea sa în C este un pic anevoioasa. Dupa ce am fost martor la implementarile PyGtk ?i GTK-Perl, am decis sa vad daca PHP ar putea sa conlucreze cu Gtk+, chiar la nivel minim. Începând cu august 2000, eu am început sa am un pic mai mult timp liber ?i deci atunci am început sa experimentez. Orientarea mea de baza a fost implementarea PyGtk deoarece avea un set mai mult sau mai pu?in deplin de facilita?i ?i avea o interfa?a buna obiect-orientata. James Henstridge, autorul PyGtk, mi-a acordat multe sfaturi utile în decursul acelor etape ini?iale.

Scrierea manuala a interfe?elor pentru toate func?iile Gtk+ era în afara oricaror discu?ii, de aceea am precautat ideea unui generator de cod similar celui realizat în PyGtk. Generatorul de cod este un program PHP care cite?te un set de fi?iere .defs con?inând informa?ii despre clasele, constantele ?i metodele Gtk+ ?i genereaza cod C care face posibila interfa?a PHP cu ele. Ceea ce nu poate fi generat în mod automat, poate fi scris cu mâna în fi?iere .overrides.

Lucrul asupra generatorului de cod ?i asupra infrastructurii a durat destul de mult din cauza ca în toamna anului 2000 am avut pu?in timp sa lucrez asupra PHP-GTK. Dupa ce am demonstrat PHP-GTK lui Frank Kromann, el a manifestat interes ?i a început sa-mi ofere ajutor la generatorul de cod ?i la implementarea pentru Win32. Când am scris primul program 'Hello World' ?i l-am lansat, a fost foarte palpitant. A durat înca vre-o doua luni pâna ce am adus proiectul la o stare prezentabila ?i versiunea ini?iala a fost lansata la 1 martie 2001. Noutatea a aparut rapid pe SlashDot.

Sim?ind ca PHP-GTK poate fi costisitor, am pregatit o lista po?tala de distribu?ie ?i CVS separate pentru el, precum ?i web site-ul gtk.php.net cu ajutorul lui Colin Viebrock. Trebuia creata ?i documenta?ia ?i James Moore a venit în ajutor în aceasta privin?a.

PHP-GTK a început sa câ?tige popularitate chiar din momentul lansarii sale. Noi avem propria echipa de documentare, manualul continua sa se îmbunata?easca, oamenii încep sa scrie extensii pentru PHP-GTK ?i tot mai multe aplica?ii interesante cu ajutorul sau.

Istoria PHP
Car?i despre PHP
Istoria PHP ?i a proiectelor asociate


Car?i despre PHP

Odata cu dezvoltarea sa, PHP a început sa fie recunoscut pe plan mondial drept o platforma de dezvoltare foarte populara. Una din cele mai interesante modalita?i de urmarire a acestei tendin?e a fost observarea car?ilor despre PHP, care au aparut pe parcursul anilor.

Din câte cunoa?tem, prima carte dedicata PHP a fost "PHP - tvorba aplikací internetových interaktivních" (PHP - Crearea de aplicatii Internet interactive) - o carte ceha publicata în aprilie 1999, scrisa de Jirka Kosek. În luna urmatoare a urmat o carte germana scrisa de Egon Schmid, Christian Cartus ?i Richard Blume. Prima carte în limba engleza despre PHP a fost publicata la scurt timp dupa aceea, ?i a fost întitulata "Core PHP Programming" de Leon Atkinson. Aceste car?i au abordat PHP 3.0.

În timp ce aceste car?i erau primele de acest gen, ele au fost urmate de un numar mare de car?i de la o serie de autori ?i editori. Exista peste 400 de car?i în limba engleza, peste 100 de car?i în Germana, ?i peste 50 de car?i în limba franceza sau spaniola! În plus, pute?i gasi car?i despre PHP în multe alte limbi, inclusiv coreeana, japoneza ?i ebraica.

În mod cert, acest mare numar de car?i scrise de diferi?i autori, publicate de mul?i editori ?i disponibilitatea lor în atâtea limbi - sunt o marturie incontestabila a succesului PHP la scara mondiala.

Istoria proiectelor asociate cu PHP
Publica?ii despre PHP
Istoria PHP ?i a proiectelor asociate


Publica?ii despre PHP

Din câte cunoa?tem, primul articol despre PHP într-o revista tiparita a fost publicat într-o modificare ceha a revistei Computerworld în primavara anului 1998, ?i cuprindea PHP 3.0. Ca ?i în cazul car?ilor, acesta a fost primul dintr-o serie de articole despre PHP publicate în diverse reviste proeminente.

Articole despre PHP au aparut în Dr. Dobbs, Linux Enterprise, Linux Magazine ?i în multe altele. Articole despre migrarea aplica?iilor bazate pe ASP în PHP pentru Windows apar chiar ?i la Microsoft în propriul lor MSDN!

Car?i despre PHP
Migrating from PHP 7.0.x to PHP 7.1.x
Istoria PHP ?i a proiectelor asociate


Migrating from PHP 7.0.x to PHP 7.1.x

Cuprins

  • New features
  • New functions
  • New global constants
  • Backward incompatible changes
  • Deprecated features in PHP 7.1.x
  • Changed functions
  • Other changes
  • Windows Support

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

Accesa?i de asemenea ghidurile de migrare pentru versiunile PHP 5.0.x, 5.1.x, 5.2.x, 5.3.x, 5.4.x, 5.5.x, 5.6.x and 7.0.x.

Publica?ii despre PHP
New features
Anexe


New features

Nullable types

Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, null can be passed as an argument, or returned as a value, respectively.

<?php

function testReturn(): ?string
{
    return 'elePHPant';
}

var_dump(testReturn());

function testReturn(): ?string
{
    return null;
}

var_dump(testReturn());

function test(?string $name)
{
    var_dump($name);
}

test('elePHPant');
test(null);
test();

Exemplul de mai sus va afi?a:

string(10) "elePHPant"
NULL
string(10) "elePHPant"
NULL
Uncaught Error: Too few arguments to function test(), 0 passed in...

Void functions

A void return type has been introduced. Functions declared with void as their return type must either omit their return statement altogether, or use an empty return statement. null is not a valid return value for a void function.

<?php
function swap(&$left, &$right): void
{
    if ($left === $right) {
        return;
    }

    $tmp = $left;
    $left = $right;
    $right = $tmp;
}

$a = 1;
$b = 2;
var_dump(swap($a, $b), $a, $b);

Exemplul de mai sus va afi?a:

null
int(2)
int(1)

Attempting to use a void function's return value simply evaluates to null, with no warnings emitted. The reason for this is because warnings would implicate the use of generic higher order functions.

Symmetric array destructuring

The shorthand array syntax ([]) may now be used to destructure arrays for assignments (including within foreach), as an alternative to the existing list() syntax, which is still supported.

<?php
$data = [
    [1, 'Tom'],
    [2, 'Fred'],
];

// list() style
list($id1, $name1) = $data[0];

// [] style
[$id1, $name1] = $data[0];

// list() style
foreach ($data as list($id, $name)) {
    // logic here with $id and $name
}

// [] style
foreach ($data as [$id, $name]) {
    // logic here with $id and $name
}

Class constant visibility

Support for specifying the visibility of class constants has been added.

<?php
class ConstDemo
{
    const PUBLIC_CONST_A = 1;
    public const PUBLIC_CONST_B = 2;
    protected const PROTECTED_CONST = 3;
    private const PRIVATE_CONST = 4;
}

iterable pseudo-type

A new pseudo-type (similar to callable) called iterable has been introduced. It may be used in parameter and return types, where it accepts either arrays or objects that implement the Traversable interface. With respect to subtyping, parameter types of child classes may broaden a parent's declaration of array or Traversable to iterable. With return types, child classes may narrow a parent's return type of iterable to array or an object that implements Traversable.

<?php
function iterator(iterable $iter)
{
    foreach ($iter as $val) {
        //
    }
}

Multi catch exception handling

Multiple exceptions per catch block may now be specified using the pipe character (|). This is useful for when different exceptions from different class hierarchies are handled the same.

<?php
try {
    // some code
} catch (FirstException | SecondException $e) {
    // handle first and second exceptions
}

Support for keys in list()

You can now specify keys in list(), or its new shorthand [] syntax. This enables destructuring of arrays with non-integer or non-sequential keys.

<?php
$data = [
    ["id" => 1, "name" => 'Tom'],
    ["id" => 2, "name" => 'Fred'],
];

// list() style
list("id" => $id1, "name" => $name1) = $data[0];

// [] style
["id" => $id1, "name" => $name1] = $data[0];

// list() style
foreach ($data as list("id" => $id, "name" => $name)) {
    // logic here with $id and $name
}

// [] style
foreach ($data as ["id" => $id, "name" => $name]) {
    // logic here with $id and $name
}

Support for negative string offsets

Support for negative string offsets has been added to the string manipulation functions accepting offsets, as well as to string indexing with [] or {}. In such cases, a negative offset is interpreted as being an offset from the end of the string.

<?php
var_dump("abcdef"[-2]);
var_dump(strpos("aabbcc", "b", -3));

Exemplul de mai sus va afi?a:

string (1) "e"
int(3)

Negative string and array offsets are now also supported in the simple variable parsing syntax inside of strings.

<?php
$string = 'bar';
echo "The last character of '$string' is '$string[-1]'.\n";
?>

Exemplul de mai sus va afi?a:

The last character of 'bar' is 'r'.

Support for AEAD in ext/openssl

Support for AEAD (modes GCM and CCM) have been added by extending the openssl_encrypt() and openssl_decrypt() functions with additional parameters.

Convert callables to Closures with Closure::fromCallable()

A new static method has been introduced to the Closure class to allow for callables to be easily converted into Closure objects.

<?php
class Test
{
    public function exposeFunction()
    {
        return Closure::fromCallable([$this, 'privateFunction']);
    }

    private function privateFunction($param)
    {
        var_dump($param);
    }
}

$privFunc = (new Test)->exposeFunction();
$privFunc('some value');

Exemplul de mai sus va afi?a:

string(10) "some value"

Asynchronous signal handling

A new function called pcntl_async_signals() has been introduced to enable asynchronous signal handling without using ticks (which introduce a lot of overhead).

<?php
pcntl_async_signals(true); // turn on async signals

pcntl_signal(SIGHUP,  function($sig) {
    echo "SIGHUP\n";
});

posix_kill(posix_getpid(), SIGHUP);

Exemplul de mai sus va afi?a:

SIGHUP

HTTP/2 server push support in ext/curl

Support for server push has been added to the CURL extension (requires version 7.46 and above). This can be leveraged through the curl_multi_setopt() function with the new CURLMOPT_PUSHFUNCTION constant. The constants CURL_PUSH_OK and CURL_PUSH_DENY have also been added so that the execution of the server push callback can either be approved or denied.

Migrating from PHP 7.0.x to PHP 7.1.x
New functions
Migrating from PHP 7.0.x to PHP 7.1.x


New functions

PHP Core

  • sapi_windows_cp_get()
  • sapi_windows_cp_set()
  • sapi_windows_cp_conv()
  • sapi_windows_cp_is_utf8()

Closure

  • Closure::fromCallable()

CURL

  • curl_multi_errno()
  • curl_share_errno()
  • curl_share_strerror()

Session

  • session_create_id()
  • session_gc()

SPL

  • is_iterable()

PCNTL

  • pcntl_async_signals()
  • pcntl_signal_get_handler()
New features
New global constants
Migrating from PHP 7.0.x to PHP 7.1.x


New global constants

Core Predefined Constants

  • PHP_FD_SETSIZE

CURL

  • CURLMOPT_PUSHFUNCTION
  • CURL_PUSH_OK
  • CURL_PUSH_DENY

Data Filtering

  • FILTER_FLAG_EMAIL_UNICODE

Image Processing and GD

  • IMAGETYPE_WEBP

JSON

  • JSON_UNESCAPED_LINE_TERMINATORS

LDAP

  • LDAP_OPT_X_SASL_NOCANON
  • LDAP_OPT_X_SASL_USERNAME
  • LDAP_OPT_X_TLS_CACERTDIR
  • LDAP_OPT_X_TLS_CACERTFILE
  • LDAP_OPT_X_TLS_CERTFILE
  • LDAP_OPT_X_TLS_CIPHER_SUITE
  • LDAP_OPT_X_TLS_KEYFILE
  • LDAP_OPT_X_TLS_RANDOM_FILE
  • LDAP_OPT_X_TLS_CRLCHECK
  • LDAP_OPT_X_TLS_CRL_NONE
  • LDAP_OPT_X_TLS_CRL_PEER
  • LDAP_OPT_X_TLS_CRL_ALL
  • LDAP_OPT_X_TLS_DHFILE
  • LDAP_OPT_X_TLS_CRLFILE
  • LDAP_OPT_X_TLS_PROTOCOL_MIN
  • LDAP_OPT_X_TLS_PROTOCOL_SSL2
  • LDAP_OPT_X_TLS_PROTOCOL_SSL3
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_0
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_1
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_2
  • LDAP_OPT_X_TLS_PACKAGE
  • LDAP_OPT_X_KEEPALIVE_IDLE
  • LDAP_OPT_X_KEEPALIVE_PROBES
  • LDAP_OPT_X_KEEPALIVE_INTERVAL

PostgreSQL

  • PGSQL_NOTICE_LAST
  • PGSQL_NOTICE_ALL
  • PGSQL_NOTICE_CLEAR

SPL

  • MT_RAND_PHP
New functions
Backward incompatible changes
Migrating from PHP 7.0.x to PHP 7.1.x


Backward incompatible changes

Throw on passing too few function arguments

Previously, a warning would be emitted for invoking user-defined functions with too few arguments. Now, this warning has been promoted to an Error exception. This change only applies to user-defined functions, not internal functions. For example:

<?php
function test($param){}
test();

Exemplul de mai sus va afi?a ceva similar cu:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function test(), 0 passed in %s on line %d and exactly 1 expected in %s:%d

Forbid dynamic calls to scope introspection functions

Dynamic calls for certain functions have been forbidden (in the form of $func() or array_map('extract', ...), etc). These functions either inspect or modify another scope, and present with them ambiguous and unreliable behavior. The functions are as follows:

  • assert() - with a string as the first argument
  • compact()
  • extract()
  • func_get_args()
  • func_get_arg()
  • func_num_args()
  • get_defined_vars()
  • mb_parse_str() - with one arg
  • parse_str() - with one arg
<?php
(function () {
    $func = 'func_num_args';
    $func();
})();

Exemplul de mai sus va afi?a:

Warning: Cannot call func_num_args() dynamically in %s on line %d

Invalid class, interface, and trait names

The following names cannot be used to name classes, interfaces, or traits:

  • void
  • iterable

Numerical string conversions now respect scientific notation

Integer operations and conversions on numerical strings now respect scientific notation. This also includes the (int) cast operation, and the following functions: intval() (where the base is 10), settype(), decbin(), decoct(), and dechex().

Fixes to mt_rand() algorithm

mt_rand() will now default to using the fixed version of the Mersenne Twister algorithm. If deterministic output from mt_srand() was relied upon, then the MT_RAND_PHP with the ability to preserve the old (incorrect) implementation via an additional optional second parameter to mt_srand().

rand() aliased to mt_rand() and srand() aliased to mt_srand()

rand() and srand() have now been made aliases to mt_rand() and mt_srand(), respectively. This means that the output for the following functions have changes: rand(), shuffle(), str_shuffle(), and array_rand().

Disallow the ASCII delete control character in identifiers

The ASCII delete control character (0x7F) can no longer be used in identifiers that are not quoted.

error_log changes with syslog value

If the error_log ini setting is set to syslog, the PHP error levels are mapped to the syslog error levels. This brings finer differentiation in the error logs in contrary to the previous approach where all the errors are logged with the notice level only.

Do not call destructors on incomplete objects

Destructors are now never called for objects that throw an exception during the execution of their constructor. In previous versions this behavior depended on whether the object was referenced outside the construcor (e.g. by an exception backtrace).

call_user_func() handling of reference arguments

call_user_func() will now always generate a warning upon calls to functions that expect references as arguments. Previously this depended on whether the call was fully qualified.

Additionally, call_user_func() and call_user_func_array() will no longer abort the function call in this case. The "expected reference" warning will be emitted, but the call will proceed as usual.

The empty index operator is not supported for strings anymore

Applying the empty index operator to a string (e.g. $str[] = $x) throws a fatal error instead of converting silently to array.

Removed ini directives

The following ini directives have been removed:

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

Array ordering when elements are automatically created during by reference assignments has changed

The order of the elements in an array has changed when those elements have been automatically created by referencing them in a by reference assignment. For example:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Output of the above example in PHP 7.0:

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

Output of the above example in PHP 7.1:

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Sort order of equal elements

The internal sorting algorithm has been improved, what may result in different sort order of elements, which compare as equal, than before.

Nota:

Don't rely on the order of elements which compare as equal; it might change anytime.

Error message for E_RECOVERABLE errors

The error message for E_RECOVERABLE errors has been changed from "Catchable fatal error" to "Recoverable fatal error".

$options parameter of unserialize()

The allowed_classes element of the $options parameter of unserialize() is now strictly typed, i.e. if anything other than an array or a boolean is given, unserialize() returns FALSE and issues an E_WARNING.

DateTime constructor incorporates microseconds

DateTime and DateTimeImmutable now properly incorporate microseconds when constructed from the current time, either explicitly or with a relative string (e.g. "first day of next month"). This means that naive comparisons of two newly created instances will now more likely return FALSE instead of TRUE:

<?php
new DateTime() == new DateTime();
?>

Fatal errors to Error exceptions conversions

In the Date extension, invalid serialization data for DateTime or DatePeriod classes, or timezone initialization failure from serialized data, will now throw an Error exception from the __wakeup() or __set_state() methods, instead of resulting in a fatal error.

In the DBA extension, data modification functions (such as dba_insert()) will now throw an Error exception instead of triggering a catchable fatal error if the key does not contain exactly two elements.

In the DOM extension, invalid schema or RelaxNG validation contexts will now throw an Error exception instead of resulting in a fatal error. Similarly, attempting to register a node class that does not extend the appropriate base class, or attempting to read an invalid property or write to a readonly property, will also now throw an Error exception.

In the IMAP extension, email addresses longer than 16385 bytes will throw an Error exception instead of resulting in a fatal error.

In the Intl extension, failing to call the parent constructor in a class extending Collator before invoking the parent methods will now throw an Error instead of resulting in a recoverable fatal error. Also, cloning a Transliterator object will now throw an Error exception on failure to clone the internal transliterator instead of resulting in a fatal error.

In the LDAP extension, providing an unknown modification type to ldap_batch_modify() will now throw an Error exception instead of resulting in a fatal error.

In the mbstring extension, the mb_ereg() and mb_eregi() functions will now throw a ParseError exception if an invalid PHP expression is provided and the 'e' option is used.

In the Mcrypt extension, the mcrypt_encrypt() and mcrypt_decrypt() will now throw an Error exception instead of resulting in a fatal error if mcrypt cannot be initialized.

In the mysqli extension, attempting to read an invalid property or write to a readonly property will now throw an Error exception instead of resulting in a fatal error.

In the Reflection extension, failing to retrieve a reflection object or retrieve an object property will now throw an Error exception instead of resulting in a fatal error.

In the Session extension, custom session handlers that do not return strings for session IDs will now throw an Error exception instead of resulting in a fatal error when a function is called that must generate a session ID.

In the SimpleXML extension, creating an unnamed or duplicate attribute will now throw an Error exception instead of resulting in a fatal error.

In the SPL extension, attempting to clone an SplDirectory object will now throw an Error exception instead of resulting in a fatal error. Similarly, calling ArrayIterator::append() when iterating over an object will also now throw an Error exception.

In the standard extension, the assert() function, when provided with a string argument as its first parameter, will now throw a ParseError exception instead of resulting in a catchable fatal error if the PHP code is invalid. Similarly, calling forward_static_call() outside of a class scope will now throw an Error exception.

In the Tidy extension, creating a tidyNode manually will now throw an Error exception instead of resulting in a fatal error.

In the WDDX extension, a circular reference when serializing will now throw an Error exception instead of resulting in a fatal error.

In the XML-RPC extension, a circular reference when serializing will now throw an instance of Error exception instead of resulting in a fatal error.

In the Zip extension, the ZipArchive::addGlob() method will now throw an Error exception instead of resulting in a fatal error if glob support is not available.

Lexically bound variables cannot reuse names

Variables bound to a closure via the use construct cannot use the same name as any superglobals, $this, or any parameter. For example, all of these function definition will result in a fatal error:

<?php
$f = function () use ($_SERVER) {};
$f = function () use ($this) {};
$f = function ($param) use ($param) {};

JSON encoding and decoding

The serialize_precision ini setting now controls the serialization precision when encoding doubles.

Decoding an empty key now results in an empty property name, rather than _empty_ as a property name.

<?php
var_dump(json_decode(json_encode(['' => 1])));

Exemplul de mai sus va afi?a ceva similar cu:

object(stdClass)#1 (1) {
  [""]=>
  int(1)
}

When supplying the JSON_UNESCAPED_UNICODE flag to json_encode(), the sequences U+2028 and U+2029 are now escaped.

Changes to mb_ereg() and mb_eregi() parameter semantics

The third paramter to the mb_ereg() and mb_eregi() functions (regs) will now be set to an empty array if nothing was matched. Formely, the parameter would not have been modified.

Drop support for the sslv2 stream

The sslv2 stream has now been dropped in OpenSSL.

New global constants
Deprecated features in PHP 7.1.x
Migrating from PHP 7.0.x to PHP 7.1.x


Deprecated features in PHP 7.1.x

ext/mcrypt

The mcrypt extension has been abandonware for nearly a decade now, and was also fairly complex to use. It has therefore been deprecated in favour of OpenSSL, where it will be removed from the core and into PECL in PHP 7.2.

Eval option for mb_ereg_replace() and mb_eregi_replace()

The e pattern modifier has been deprecated for the mb_ereg_replace() and mb_eregi_replace() functions.

Backward incompatible changes
Changed functions
Migrating from PHP 7.0.x to PHP 7.1.x


Changed functions

PHP Core

  • getopt() has an optional third parameter that exposes the index of the next element in the argument vector list to be processed. This is done via a by-ref parameter.
  • getenv() no longer requires its parameter. If the parameter is omitted, then the current environment variables will be returned as an associative array.
  • get_headers() now has an additional parameter to enable for the passing of custom stream contexts.
  • long2ip() now also accepts an integer as a parameter.
  • output_reset_rewrite_vars() no longer resets session URL rewrite variables.
  • parse_url() is now more restrictive and supports RFC3986.
  • unpack() now accepts an optional third parameter to specify the offset to begin unpacking from.

File System

  • file_get_contents() now accepts a negative seek offset if the stream is seekable.
  • tempnam() now emits a notice when falling back to the system's temp directory.

JSON

  • json_encode() now accepts a new option, JSON_UNESCAPED_LINE_TERMINATORS, to disable the escaping of U+2028 and U+2029 characters when JSON_UNESCAPED_UNICODE is supplied.

Multibyte String

  • mb_ereg() now rejects illegal byte sequences.
  • mb_ereg_replace() now rejects illegal byte sequences.

PDO

  • PDO::lastInsertId() for PostgreSQL will now trigger an error when nextval has not been called for the current session (the postgres connection).

PostgreSQL

  • pg_last_notice() now accepts an optional parameter to specify an operation. This can be done with one of the following new constants: PGSQL_NOTICE_LAST, PGSQL_NOTICE_ALL, or PGSQL_NOTICE_CLEAR.
  • pg_fetch_all() now accepts an optional second parameter to specify the result type (similar to the third parameter of pg_fetch_array()).
  • pg_select() now accepts an optional fourth parameter to specify the result type (similar to the third parameter of pg_fetch_array()).
Deprecated features in PHP 7.1.x
Other changes
Migrating from PHP 7.0.x to PHP 7.1.x


Other changes

Notices and warnings on arithmetic with invalid strings

New E_WARNING and E_NOTICE errors have been introduced when invalid strings are coerced using operators expecting numbers (+ - * / ** % << >> | & ^) or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.

<?php
'1b' + 'something';

Exemplul de mai sus va afi?a:

Notice: A non well formed numeric value encountered in %s on line %d
Warning: A non-numeric value encountered in %s on line %d

Warn on octal escape sequence overflow

Previously, 3-octet octal string escape sequences would overflow silently. Now, they will still overflow, but E_WARNING will be emitted.

<?php
var_dump("\500");

Exemplul de mai sus va afi?a:

Warning: Octal escape sequence overflow \500 is greater than \377 in %s on line %d
string(1) "@"

Inconsistency fixes to $this

Whilst $this is considered a special variable in PHP, it lacked proper checks to ensure it wasn't used as a variable name or reassigned. This has now been rectified to ensure that $this cannot be a user-defined variable, reassigned to a different value, or be globalised.

Session ID generation without hashing

Session IDs will no longer be hashed upon generation. With this change brings about the removal of the following four ini settings:

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

And the addition of the following two ini settings:

  • session.sid_length - defines the length of the session ID, defaulting to 32 characters for backwards compatibility)
  • session.sid_bits_per_character - defines the number of bits to be stored per character (i.e. increases the range of characters that can be used in the session ID), defaulting to 4 for backwards compatibility

Changes to INI file handling

precision

If the value is set to -1, then the dtoa mode 0 is used. The default value is still 14.

serialize_precision

If the value is set to -1, then the dtoa mode 0 is used. The value -1 is now used by default.

gd.jpeg_ignore_warning

The default of this php.ini setting has been changed to 1, so by default libjpeg warnings are ignored.

Session ID generation with a CSPRNG only

Session IDs will now only be generated with a CSPRNG.

More informative TypeError messages when NULL is allowed

TypeError exceptions for arg_info type checks will now provide more informative error messages. If the parameter type or return type accepts NULL (by either having a default value of NULL or being a nullable type), then the error message will now mention this with a message of "must be ... or null" or "must ... or be null."

Changed functions
Windows Support
Migrating from PHP 7.0.x to PHP 7.1.x


Windows Support

readline

The readline extension is supported through the » WinEditLine library. Thereby, the interactive CLI shell is supported as well (php.exe -a).

Other changes
Migrating from PHP 5.6.x to PHP 7.0.x
Migrating from PHP 7.0.x to PHP 7.1.x


Migrating from PHP 5.6.x to PHP 7.0.x

Cuprins

  • Schimbari incompatibile în sens invers
  • New features
  • Deprecated features in PHP 7.0.x
  • Changed functions
  • New functions
  • New Classes and Interfaces
  • New Global Constants
  • Changes in SAPI Modules
  • Removed Extensions and SAPIs
  • Other Changes

Despite the fact that PHP 7.0 is a new major version, efforts have been made to make migration as painless as possible. This release focuses mainly on removing functionality deprecated in previous versions and improving language consistency.

There are a few incompatibilities and new features that should be considered, and code should be tested before switching PHP versions in production environments.

Accesa?i de asemenea ghidurile de migrare pentru versiunile PHP 5.0.x, 5.1.x, 5.2.x, 5.3.x, 5.4.x, 5.5.x and 5.6.x.

Windows Support
Schimbari incompatibile în sens invers
Anexe


Schimbari incompatibile în sens invers

Changes to error and exception handling

Many fatal and recoverable fatal errors have been converted to exceptions in PHP 7. These error exceptions inherit from the Error class, which itself implements the Throwable interface (the new base interface all exceptions inherit).

This means that custom error handlers may no longer be triggered because exceptions may be thrown instead (causing new fatal errors for uncaught Error exceptions).

A fuller description of how errors operate in PHP 7 can be found on the PHP 7 errors page. This migration guide will merely enumerate the changes that affect backward compatibility.

set_exception_handler() is no longer guaranteed to receive Exception objects

Code that implements an exception handler registered with set_exception_handler() using a type declaration of Exception will cause a fatal error when an Error object is thrown.

If the handler needs to work on both PHP 5 and 7, you should remove the type declaration from the handler, while code that is being migrated to work on PHP 7 exclusively can simply replace the Exception type declaration with Throwable instead.

<?php
// PHP 5 era code that will break.
function handler(Exception $e) { ... }
set_exception_handler('handler');

// PHP 5 and 7 compatible.
function handler($e) { ... }

// PHP 7 only.
function handler(Throwable $e) { ... }
?>

Internal constructors always throw exceptions on failure

Previously, some internal classes would return NULL or an unusable object when the constructor failed. All internal classes will now throw an Exception in this case in the same way that user classes already had to.

Parse errors throw ParseError

Parser errors now throw a ParseError object. Error handling for eval() should now include a catch block that can handle this error.

E_STRICT notices severity changes

All of the E_STRICT notices have been reclassified to other levels. E_STRICT constant is retained, so calls like error_reporting(E_ALL|E_STRICT) will not cause an error.

E_STRICT notices severity changes
Situation | New level/behaviour
Indexing by a resource | E_NOTICE
Abstract static methods | Notice removed, triggers no error
"Redefining" a constructor | Notice removed, triggers no error
Signature mismatch during inheritance | E_WARNING
Same (compatible) property in two used traits | Notice removed, triggers no error
Accessing static property non-statically | E_NOTICE
Only variables should be assigned by reference | E_NOTICE
Only variables should be passed by reference | E_NOTICE
Calling non-static methods statically | E_DEPRECATED

Changes to variable handling

PHP 7 now uses an abstract syntax tree when parsing source files. This has permitted many improvements to the language which were previously impossible due to limitations in the parser used in earlier versions of PHP, but has resulted in the removal of a few special cases for consistency reasons, which has resulted in backward compatibility breaks. These cases are detailed in this section.

Changes to the handling of indirect variables, properties, and methods

Indirect access to variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the previous mix of special cases. The table below shows how the order of evaluation has changed.

Old and new evaluation of indirect expressions
Expression | PHP 5 interpretation | PHP 7 interpretation
$$foo['bar']['baz'] | ${$foo['bar']['baz']} | ($$foo)['bar']['baz']
$foo->$bar['baz'] | $foo->{$bar['baz']} | ($foo->$bar)['baz']
$foo->$bar['baz']() | $foo->{$bar['baz']}() | ($foo->$bar)['baz']()
Foo::$bar['baz']() | Foo::{$bar['baz']}() | (Foo::$bar)['baz']()

Code that used the old right-to-left evaluation order must be rewritten to explicitly use that evaluation order with curly braces (see the above middle column). This will make the code both forwards compatible with PHP 7.x and backwards compatible with PHP 5.x.

Changes to list() handling

list() no longer assigns variables in reverse order

list() will now assign values to variables in the order they are defined, rather than reverse order. In general, this only affects the case where list() is being used in conjunction with the array [] operator, as shown below:

<?php
list($a[], $a[], $a[]) = [1, 2, 3];
var_dump($a);
?>

Exemplul de mai sus va afi?a în PHP 5:

array(3) {
  [0]=>
  int(3)
  [1]=>
  int(2)
  [2]=>
  int(1)
}

Exemplul de mai sus va afi?a în PHP 7:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

In general, it is recommended not to rely on the order in which list() assignments occur, as this is an implementation detail that may change again in the future.

Empty list() assignments have been removed

list() constructs can no longer be empty. The following are no longer allowed:

<?php
list() = $a;
list(,,) = $a;
list($x, list(), $y) = $a;
?>
list() cannot unpack strings

list() can no longer unpack string variables. str_split() should be used instead.

Array ordering when elements are automatically created during by reference assignments has changed

The order of the elements in an array has changed when those elements have been automatically created by referencing them in a by reference assignment. For example:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Exemplul de mai sus va afi?a în PHP 5:

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Exemplul de mai sus va afi?a în PHP 7:

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

global only accepts simple variables

Variable variables can no longer be used with the global keyword. The curly brace syntax can be used to emulate the previous behaviour if required:

<?php
function f() {
    // Valid in PHP 5 only.
    global $$foo->bar;

    // Valid in PHP 5 and 7.
    global ${$foo->bar};
}
?>

As a general principle, using anything other than a bare variable with global is discouraged.

Parentheses around function arguments no longer affect behaviour

In PHP 5, using redundant parentheses around a function argument could quiet strict standards warnings when the function argument was passed by reference. The warning will now always be issued.

<?php
function getArray() {
    return [1, 2, 3];
}

function squareArray(array &$a) {
    foreach ($a as &$v) {
        $v **= 2;
    }
}

// Generates a warning in PHP 7.
squareArray((getArray()));
?>

Exemplul de mai sus va afi?a:

Notice: Only variables should be passed by reference in /tmp/test.php on line 13

Changes to foreach

Minor changes have been made to the behaviour of the foreach control structure, primarily around the handling of the internal array pointer and modification of the array being iterated over.

foreach no longer changes the internal array pointer

Prior to PHP 7, the internal array pointer was modified while an array was being iterated over with foreach. This is no longer the case, as shown in the following example:

<?php
$array = [0, 1, 2];
foreach ($array as &$val) {
    var_dump(current($array));
}
?>

Exemplul de mai sus va afi?a în PHP 5:

int(1)
int(2)
bool(false)

Exemplul de mai sus va afi?a în PHP 7:

int(0)
int(0)
int(0)

foreach by-value operates on a copy of the array

When used in the default by-value mode, foreach will now operate on a copy of the array being iterated rather than the array itself. This means that changes to the array made during iteration will not affect the values that are iterated.

foreach by-reference has improved iteration behaviour

When iterating by-reference, foreach will now do a better job of tracking changes to the array made during iteration. For example, appending to an array while iterating will now result in the appended values being iterated over as well:

<?php
$array = [0];
foreach ($array as &$val) {
    var_dump($val);
    $array[1] = 1;
}
?>

Exemplul de mai sus va afi?a în PHP 5:

int(0)

Exemplul de mai sus va afi?a în PHP 7:

int(0)
int(1)

Iteration of non-Traversable objects

Iterating over a non-Traversable object will now have the same behaviour as iterating over by-reference arrays. This results in the improved behaviour when modifying an array during iteration also being applied when properties are added to or removed from the object.

Changes to integer handling

Invalid octal literals

Previously, octal literals that contained invalid numbers were silently truncated (0128 was taken as 012). Now, an invalid octal literal will cause a parse error.

Negative bitshifts

Bitwise shifts by negative numbers will now throw an ArithmeticError:

<?php
var_dump(1 >> -1);
?>

Exemplul de mai sus va afi?a în PHP 5:

int(0)

Exemplul de mai sus va afi?a în PHP 7:

Fatal error: Uncaught ArithmeticError: Bit shift by negative number in /tmp/test.php:2
Stack trace:
#0 {main}
  thrown in /tmp/test.php on line 2

Out of range bitshifts

Bitwise shifts (in either direction) beyond the bit width of an integer will always result in 0. Previously, the behaviour of such shifts was architecture dependent.

Changes to Division By Zero

Previously, when 0 was used as the divisor for either the divide (/) or modulus (%) operators, an E_WARNING would be emitted and false would be returned. Now, the divide operator returns a float as either +INF, -INF, or NAN, as specified by IEEE 754. The modulus operator E_WARNING has been removed and will throw a DivisionByZeroError exception.

<?php
var_dump(3/0);
var_dump(0/0);
var_dump(0%0);
?>

Exemplul de mai sus va afi?a în PHP 5:

Warning: Division by zero in %s on line %d
bool(false)

Warning: Division by zero in %s on line %d
bool(false)

Warning: Division by zero in %s on line %d
bool(false)

Exemplul de mai sus va afi?a în PHP 7:

Warning: Division by zero in %s on line %d
float(INF)

Warning: Division by zero in %s on line %d
float(NAN)

PHP Fatal error:  Uncaught DivisionByZeroError: Modulo by zero in %s line %d

Changes to string handling

Hexadecimal strings are no longer considered numeric

Strings containing hexadecimal numbers are no longer considered to be numeric. For example:

<?php
var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));
?>

Exemplul de mai sus va afi?a în PHP 5:

bool(true)
bool(true)
int(15)
string(2) "oo"

Exemplul de mai sus va afi?a în PHP 7:

bool(false)
bool(false)
int(0)

Notice: A non well formed numeric value encountered in /tmp/test.php on line 5
string(3) "foo"

filter_var() can be used to check if a string contains a hexadecimal number, and also to convert a string of that type to an integer:

<?php
$str = "0xffff";
$int = filter_var($str, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX);
if (false === $int) {
    throw new Exception("Invalid integer!");
}
var_dump($int); // int(65535)
?>

\u{ may cause errors

Due to the addition of the new Unicode codepoint escape syntax, strings containing a literal \u{ followed by an invalid sequence will cause a fatal error. To avoid this, the leading backslash should be escaped.

Removed functions

call_user_method() and call_user_method_array()

These functions were deprecated in PHP 4.1.0 in favour of call_user_func() and call_user_func_array(). You may also want to consider using variable functions and/or the ... operator.

All ereg* functions

All ereg functions were removed. PCRE is a recommended alternative.

mcrypt aliases

The deprecated mcrypt_generic_end() function has been removed in favour of mcrypt_generic_deinit().

Additionally, the deprecated mcrypt_ecb(), mcrypt_cbc(), mcrypt_cfb() and mcrypt_ofb() functions have been removed in favour of using mcrypt_decrypt() with the appropriate MCRYPT_MODE_* constant.

All ext/mysql functions

All ext/mysql functions were removed. For details about choosing a different MySQL API, see Choosing a MySQL API.

All ext/mssql functions

All ext/mssql functions were removed. For a list of alternatives, see the MSSQL Introduction.

intl aliases

The deprecated datefmt_set_timezone_id() and
IntlDateFormatter::setTimeZoneID() aliases have been
removed in favour of datefmt_set_timezone() and
IntlDateFormatter::setTimeZone(), respectively.

set_magic_quotes_runtime()

set_magic_quotes_runtime(), along with its alias magic_quotes_runtime(), have been removed. They were deprecated in PHP 5.3.0, and became effectively non-functional with the removal of magic quotes in PHP 5.4.0.

set_socket_blocking()

The deprecated set_socket_blocking() alias has been removed in favour of stream_set_blocking().

dl() in PHP-FPM

dl() can no longer be used in PHP-FPM. It remains functional in the CLI and embed SAPIs.

GD Type1 functions

Support for PostScript Type1 fonts has been removed from the GD extension, resulting in the removal of the following functions:

  • imagepsbbox()
  • imagepsencodefont()
  • imagepsextendfont()
  • imagepsfreefont()
  • imagepsloadfont()
  • imagepsslantfont()
  • imagepstext()

Using TrueType fonts and their associated functions is recommended instead.

Removed INI directives

Removed features

The following INI directives have been removed as their associated features have also been removed:

  • always_populate_raw_post_data
  • asp_tags

xsl.security_prefs

The xsl.security_prefs directive has been removed. Instead, the XsltProcessor::setSecurityPrefs() method should be called to control the security preferences on a per-processor basis.

Other backward incompatible changes

New objects cannot be assigned by reference

The result of the new statement can no longer be assigned to a variable by reference:

<?php
class C {}
$c =& new C;
?>

Exemplul de mai sus va afi?a în PHP 5:

Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3

Exemplul de mai sus va afi?a în PHP 7:

Parse error: syntax error, unexpected 'new' (T_NEW) in /tmp/test.php on line 3

Invalid class, interface and trait names

The following names cannot be used to name classes, interfaces or traits:

  • bool
  • int
  • float
  • string
  • NULL
  • TRUE
  • FALSE

Furthermore, the following names should not be used. Although they will not generate an error in PHP 7.0, they are reserved for future use and should be considered deprecated.

  • resource
  • object
  • mixed
  • numeric

ASP and script PHP tags removed

Support for using ASP and script tags to delimit PHP code has been removed. The affected tags are:

Removed ASP and script tags
Opening tag | Closing tag
<% | %>
<%= | %>
<script language="php"> | </script>

Calls from incompatible context removed

Previously deprecated in PHP 5.6, static calls made to a non-static method with an incompatible context will now result in the called method having an undefined $this variable and a deprecation warning being issued.

<?php
class A {
    public function test() { var_dump($this); }
}

// Note: Does NOT extend A
class B {
    public function callNonStaticMethodOfA() { A::test(); }
}

(new B)->callNonStaticMethodOfA();
?>

Exemplul de mai sus va afi?a în PHP 5.6:

Deprecated: Non-static method A::test() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8
object(B)#1 (0) {
}

Exemplul de mai sus va afi?a în PHP 7:

Deprecated: Non-static method A::test() should not be called statically in /tmp/test.php on line 8

Notice: Undefined variable: this in /tmp/test.php on line 3
NULL

yield is now a right associative operator

The yield construct no longer requires parentheses, and has been changed to a right associative operator with precedence between print and =>. This can result in changed behaviour:

<?php
echo yield -1;
// Was previously interpreted as
echo (yield) - 1;
// And is now interpreted as
echo yield (-1);

yield $foo or die;
// Was previously interpreted as
yield ($foo or die);
// And is now interpreted as
(yield $foo) or die;
?>

Parentheses can be used to disambiguate those cases.

Functions cannot have multiple parameters with the same name

It is no longer possible to define two or more function parameters with the same name. For example, the following function will trigger an E_COMPILE_ERROR:

<?php
function foo($a, $b, $unused, $unused) {
    //
}
?>

Functions inspecting arguments report the current parameter value

func_get_arg(), func_get_args(), debug_backtrace() and exception backtraces will no longer report the original value that was passed to a parameter, but will instead provide the current value (which might have been modified).

<?php
function foo($x) {
    $x++;
    var_dump(func_get_arg(0));
}
foo(1);?>

Exemplul de mai sus va afi?a în PHP 5:

1

Exemplul de mai sus va afi?a în PHP 7:

2

Switch statements cannot have multiple default blocks

It is no longer possible to define two or more default blocks in a switch statement. For example, the following switch statement will trigger an E_COMPILE_ERROR:

<?php
switch (1) {
    default:
    break;
    default:
    break;
}
?>

$HTTP_RAW_POST_DATA removed

$HTTP_RAW_POST_DATA is no longer available. The php://input stream should be used instead.

# comments in INI files removed

Support for prefixing comments with # in INI files has been removed. ; (semi-colon) should be used instead. This change applies to php.ini, as well as files handled by parse_ini_file() and parse_ini_string().

JSON extension replaced with JSOND

The JSON extension has been replaced with JSOND, causing three minor BC breaks. Firstly, a number must not end in a decimal point (i.e. 34. must be changed to either 34.0 or 34). Secondly, when using scientific notation, the e exponent must not immediately follow a decimal point (i.e. 3.e3 must be changed to either 3.0e3 or 3e3). Finally, an empty string is no longer considered valid JSON.

Internal function failure on overflow

Previously, internal functions would silently truncate numbers produced from float-to-integer coercions when the float was too large to represent as an integer. Now, an E_WARNING will be emitted and NULL will be returned.

Fixes to custom session handler return values

Any predicate functions implemented by custom session handlers that return either FALSE or -1 will be fatal errors. If any value from these functions other than a boolean, -1, or 0 is returned, then it will fail and an E_WARNING will be emitted.

Sort order of equal elements

The internal sorting algorithm has been improved, what may result in different sort order of elements, which compare as equal, than before.

Nota:

Don't rely on the order of elements which compare as equal; it might change anytime.

Migrating from PHP 5.6.x to PHP 7.0.x
New features
Migrating from PHP 5.6.x to PHP 7.0.x


New features

Scalar type declarations

Scalar type declarations come in two flavours: coercive (default) and strict. The following types for parameters can now be enforced (either coercively or strictly): strings (string), integers (int), floating-point numbers (float), and booleans (bool). They augment the other types introduced in PHP 5: class names, interfaces, array and callable.

<?php
// Coercive mode
function sumOfInts(int ...$ints)
{
    return array_sum($ints);
}

var_dump(sumOfInts(2, '3', 4.1));

Exemplul de mai sus va afi?a:

int(9)

To enable strict mode, a single declare directive must be placed at the top of the file. This means that the strictness of typing for scalars is configured on a per-file basis. This directive not only affects the type declarations of parameters, but also a function's return type (see return type declarations, built-in PHP functions, and functions from loaded extensions.

Full documentation and examples of scalar type declarations can be found in the type declaration reference.

Return type declarations

PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of the value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.

<?php

function arraysSum(array ...$arrays): array
{
    return array_map(function(array $array): int {
        return array_sum($array);
    }, $arrays);
}

print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));

Exemplul de mai sus va afi?a:

Array
(
    [0] => 6
    [1] => 15
    [2] => 24
)

Full documentation and examples of return type declarations can be found in the return type declarations. reference.

Null coalescing operator

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

Spaceship operator

The spaceship operator is used for comparing two expressions. It returns -1, 0 or 1 when $a is respectively less than, equal to, or greater than $b. Comparisons are performed according to PHP's usual type comparison rules.

<?php
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
?>

Constant arrays using define()

Array constants can now be defined with define(). In PHP 5.6, they could only be defined with const.

<?php
define('ANIMALS', [
    'dog',
    'cat',
    'bird'
]);

echo ANIMALS[1]; // outputs "cat"
?>

Anonymous classes

Support for anonymous classes has been added via new class. These can be used in place of full class definitions for throwaway objects:

<?php
interface Logger {
    public function log(string $msg);
}

class Application {
    private $logger;

    public function getLogger(): Logger {
         return $this->logger;
    }

    public function setLogger(Logger $logger) {
         $this->logger = $logger;
    }
}

$app = new Application;
$app->setLogger(new class implements Logger {
    public function log(string $msg) {
        echo $msg;
    }
});

var_dump($app->getLogger());
?>

Exemplul de mai sus va afi?a:

object(class@anonymous)#2 (0) {
}

Full documentation can be found in the anonymous class reference.

Unicode codepoint escape syntax

This takes a Unicode codepoint in hexadecimal form, and outputs that codepoint in UTF-8 to a double-quoted string or a heredoc. Any valid codepoint is accepted, with leading 0's being optional.

echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";

Exemplul de mai sus va afi?a:

ª
ª (same as before but with optional leading 0's)
?

Closure::call()

Closure::call() is a more performant, shorthand way of temporarily binding an object scope to a closure and invoking it.

<?php
class A {private $x = 1;}

// Pre PHP 7 code
$getXCB = function() {return $this->x;};
$getX = $getXCB->bindTo(new A, 'A'); // intermediate closure
echo $getX();

// PHP 7+ code
$getX = function() {return $this->x;};
echo $getX->call(new A);

Exemplul de mai sus va afi?a:

1
1

Filtered unserialize()

This feature seeks to provide better security when unserializing objects on untrusted data. It prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.

<?php

// converts all objects into __PHP_Incomplete_Class object
$data = unserialize($foo, ["allowed_classes" => false]);

// converts all objects into __PHP_Incomplete_Class object except those of MyClass and MyClass2
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]]);

// default behaviour (same as omitting the second argument) that accepts all classes
$data = unserialize($foo, ["allowed_classes" => true]);

IntlChar

The new IntlChar class seeks to expose additional ICU functionality. The class itself defines a number of static methods and constants that can be used to manipulate unicode characters.

<?php

printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName('@');
var_dump(IntlChar::ispunct('!'));

Exemplul de mai sus va afi?a:

10ffff
COMMERCIAL AT
bool(true)

In order to use this class, the Intl extension must be installed.

Expectations

Expectations are a backwards compatible enhancement to the older assert() function. They allow for zero-cost assertions in production code, and provide the ability to throw custom exceptions when the assertion fails.

While the old API continues to be maintained for compatibility, assert() is now a language construct, allowing the first parameter to be an expression rather than just a string to be evaluated or a boolean value to be tested.

<?php
ini_set('assert.exception', 1);

class CustomError extends AssertionError {}

assert(false, new CustomError('Some error message'));
?>

Exemplul de mai sus va afi?a:

Fatal error: Uncaught CustomError: Some error message

Full details on this feature, including how to configure it in both development and production environments, can be found in the expectations section of the assert() reference.

Group use declarations

Classes, functions and constants being imported from the same namespace can now be grouped together in a single use statement.

<?php
// Pre PHP 7 code
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;

use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;

// PHP 7+ code
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};
?>

Generator Return Expressions

This feature builds upon the generator functionality introduced into PHP 5.5. It enables for a return statement to be used within a generator to enable for a final expression to be returned (return by reference is not allowed). This value can be fetched using the new Generator::getReturn() method, which may only be used once the generator has finished yielding values.

<?php

$gen = (function() {
    yield 1;
    yield 2;

    return 3;
})();

foreach ($gen as $val) {
    echo $val, PHP_EOL;
}

echo $gen->getReturn(), PHP_EOL;

Exemplul de mai sus va afi?a:

1
2
3

Being able to explicitly return a final value from a generator is a handy ability to have. This is because it enables for a final value to be returned by a generator (from perhaps some form of coroutine computation) that can be specifically handled by the client code executing the generator. This is far simpler than forcing the client code to firstly check whether the final value has been yielded, and then if so, to handle that value specifically.

Generator delegation

Generators can now delegate to another generator, Traversable object or array automatically, without needing to write boilerplate in the outermost generator by using the yield from construct.

<?php
function gen()
{
    yield 1;
    yield 2;
    yield from gen2();
}

function gen2()
{
    yield 3;
    yield 4;
}

foreach (gen() as $val)
{
    echo $val, PHP_EOL;
}
?>

Exemplul de mai sus va afi?a:

1
2
3
4

Integer division with intdiv()

The new intdiv() function performs an integer division of its operands and returns it.

<?php
var_dump(intdiv(10, 3));
?>

Exemplul de mai sus va afi?a:

int(3)

Session options

session_start() now accepts an array of options that override the session configuration directives normally set in php.ini.

These options have also been expanded to support session.lazy_write, which is on by default and causes PHP to only overwrite any session file if the session data has changed, and read_and_close, which is an option that can only be passed to session_start() to indicate that the session data should be read and then the session should immediately be closed unchanged.

For example, to set session.cache_limiter to private and immediately close the session after reading it:

<?php
session_start([
    'cache_limiter' => 'private',
    'read_and_close' => true,
]);
?>

preg_replace_callback_array()

The new preg_replace_callback_array() function enables code to be written more cleanly when using the preg_replace_callback() function. Prior to PHP 7, callbacks that needed to be executed per regular expression required the callback function to be polluted with lots of branching.

Now, callbacks can be registered to each regular expression using an associative array, where the key is a regular expression and the value is a callback.

CSPRNG Functions

Two new functions have been added to generate cryptographically secure integers and strings in a cross platform way: random_bytes() and random_int().

list() can always unpack objects implementing ArrayAccess

Previously, list() was not guaranteed to operate correctly with objects implementing ArrayAccess. This has been fixed.

Other Features

  • Class member access on cloning has been added, e.g. (clone $foo)->bar().
Schimbari incompatibile în sens invers
Deprecated features in PHP 7.0.x
Migrating from PHP 5.6.x to PHP 7.0.x


Deprecated features in PHP 7.0.x

PHP 4 style constructors

PHP 4 style constructors (methods that have the same name as the class they are defined in) are deprecated, and will be removed in the future. PHP 7 will emit E_DEPRECATED if a PHP 4 constructor is the only constructor defined within a class. Classes that implement a __construct() method are unaffected.

<?php
class foo {
    function foo() {
        echo 'I am the constructor';
    }
}
?>

Exemplul de mai sus va afi?a:

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; foo has a deprecated constructor in example.php on line 3

Static calls to non-static methods

Static calls to methods that are not declared static are deprecated, and may be removed in the future.

<?php
class foo {
    function bar() {
        echo 'I am not static!';
    }
}

foo::bar();
?>

Exemplul de mai sus va afi?a:

Deprecated: Non-static method foo::bar() should not be called statically in - on line 8
I am not static!

password_hash() salt option

The salt option for the password_hash() function has been deprecated to prevent developers from generating their own (usually insecure) salts. The function itself generates a cryptographically secure salt when no salt is provided by the developer - therefore custom salt generation should not be needed.

capture_session_meta SSL context option

The capture_session_meta SSL context option has been deprecated. SSL metadata is now available through the stream_get_meta_data() function.

LDAP deprecations

The following function has been deprecated:

  • ldap_sort()
New features
Changed functions
Migrating from PHP 5.6.x to PHP 7.0.x


Changed functions

PHP Core

  • debug_zval_dump() now prints "int" instead of "long", and "float" instead of "double"
  • dirname() now optionally takes a second parameter, depth, to get the name of the directory depth levels up from the current directory.
  • getrusage() is now supported on Windows.
  • mktime() and gmmktime() functions no longer accept is_dst parameter.
  • preg_replace() function no longer supports "\e" (PREG_REPLACE_EVAL). preg_replace_callback() should be used instead.
  • setlocale() function no longer accepts category passed as string. LC_* constants must be used instead.
  • exec(), system() and passthru() functions have NULL byte protection now.
  • shmop_open() now returns a resource instead of an int, which has to be passed to shmop_size(), shmop_write(), shmop_read(), shmop_close() and shmop_delete().
  • substr() and iconv_substr() now return an empty string, if string is equal to start characters long.
  • xml_set_object() now requires to manually unset the $parser when finished, to avoid memory leaks.
Deprecated features in PHP 7.0.x
New functions
Migrating from PHP 5.6.x to PHP 7.0.x


New functions

Closure

  • Closure::call()

CSPRNG

  • random_bytes()
  • random_int()

Error Handling and Logging

  • error_clear_last()

Generator

  • Generator::getReturn()

GNU Multiple Precision

  • gmp_random_seed()

Math

  • intdiv()

PCRE

  • preg_replace_callback_array()

PHP Options/Info

  • gc_mem_caches()
  • get_resources()

POSIX

  • posix_setrlimit()

Reflection

  • ReflectionParameter::getType()
  • ReflectionParameter::hasType()
  • ReflectionFunctionAbstract::getReturnType()
  • ReflectionFunctionAbstract::hasReturnType()

Zip

  • ZipArchive::setCompressionIndex()
  • ZipArchive::setCompressionName()

Zlib Compression

  • inflate_add()
  • deflate_add()
  • inflate_init()
  • deflate_init()
Changed functions
New Classes and Interfaces
Migrating from PHP 5.6.x to PHP 7.0.x


New Classes and Interfaces

Intl

  • IntlChar

Reflection

  • ReflectionGenerator
  • ReflectionType

Session Handling

  • SessionUpdateTimestampHandlerInterface

Exception Hierarchy

  • Throwable
  • Error
  • TypeError
  • ParseError
  • AssertionError
  • ArithmeticError
  • DivisionByZeroError
New functions
New Global Constants
Migrating from PHP 5.6.x to PHP 7.0.x


New Global Constants

Core Predefined Constants

  • PHP_INT_MIN

GD

  • IMG_WEBP (as of PHP 7.0.10)

JSON

  • JSON_ERROR_INVALID_PROPERTY_NAME
  • JSON_ERROR_UTF16

LibXML

  • LIBXML_BIGLINES

PCRE

  • PREG_JIT_STACKLIMIT_ERROR

POSIX

  • POSIX_RLIMIT_AS
  • POSIX_RLIMIT_CORE
  • POSIX_RLIMIT_CPU
  • POSIX_RLIMIT_DATA
  • POSIX_RLIMIT_FSIZE
  • POSIX_RLIMIT_LOCKS
  • POSIX_RLIMIT_MEMLOCK
  • POSIX_RLIMIT_MSGQUEUE
  • POSIX_RLIMIT_NICE
  • POSIX_RLIMIT_NOFILE
  • POSIX_RLIMIT_NPROC
  • POSIX_RLIMIT_RSS
  • POSIX_RLIMIT_RTPRIO
  • POSIX_RLIMIT_RTTIME
  • POSIX_RLIMIT_SIGPENDING
  • POSIX_RLIMIT_STACK
  • POSIX_RLIMIT_INFINITY

Zlib

  • ZLIB_ENCODING_RAW
  • ZLIB_ENCODING_DEFLATE
  • ZLIB_ENCODING_GZIP
  • ZLIB_FILTERED
  • ZLIB_HUFFMAN_ONLY
  • ZLIB_FIXED
  • ZLIB_RLE
  • ZLIB_DEFAULT_STRATEGY
  • ZLIB_BLOCK
  • ZLIB_FINISH
  • ZLIB_FULL_FLUSH
  • ZLIB_NO_FLUSH
  • ZLIB_PARTIAL_FLUSH
  • ZLIB_SYNC_FLUSH
New Classes and Interfaces
Changes in SAPI Modules
Migrating from PHP 5.6.x to PHP 7.0.x


Changes in SAPI Modules

FPM

Unqualified listen ports now listen on both IPv4 and IPv6

In PHP 5, a listen directive with only a port number would listen on all interfaces, but only on IPv4. PHP 7 will now accept requests made via both IPv4 and IPv6.

This does not affect directives which include specific IP addresses; these will continue to only listen on that address and protocol.

New Global Constants
Removed Extensions and SAPIs
Migrating from PHP 5.6.x to PHP 7.0.x


Removed Extensions and SAPIs

Removed Extensions

  • ereg
  • mssql
  • mysql
  • sybase_ct

Removed SAPIs

  • aolserver
  • apache
  • apache_hooks
  • apache2filter
  • caudium
  • continuity
  • isapi
  • milter
  • nsapi
  • phttpd
  • pi3web
  • roxen
  • thttpd
  • tux
  • webjames
Changes in SAPI Modules
Other Changes
Migrating from PHP 5.6.x to PHP 7.0.x


Other Changes

Loosening Reserved Word Restrictions

Globally reserved words as property, constant, and method names within classes, interfaces, and traits are now allowed. This reduces the surface of BC breaks when new keywords are introduced and avoids naming restrictions on APIs.

This is particularly useful when creating internal DSLs with fluent interfaces:

<?php
// 'new', 'private', and 'for' were previously unusable
Project::new('Project Name')->private()->for('purpose here')->with('username here');
?>

The only limitation is that the class keyword still cannot be used as a constant name, otherwise it would conflict with the class name resolution syntax (ClassName::class).

Removal of date.timezone Warning

Previously, a warning was emitted if the date.timezone INI setting had not been set prior to using any date- or time-based functions. Now, this warning has been removed (with date.timezone still defaulting to UTC).

Removed Extensions and SAPIs
Migrating from PHP 5.5.x to PHP 5.6.x
Migrating from PHP 5.6.x to PHP 7.0.x


Migrating from PHP 5.5.x to PHP 5.6.x

Cuprins

  • Backward incompatible changes
  • New features
  • Deprecated features in PHP 5.6.x
  • Changed functions
  • New functions
  • OpenSSL changes in PHP 5.6.x
  • Other changes to extensions
  • New global constants

Most improvements in PHP 5.6.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.

Accesa?i de asemenea ghidurile de migrare pentru versiunile PHP 5.0.x, 5.1.x, 5.2.x, 5.3.x, 5.4.x and 5.5.x.

Other Changes
Backward incompatible changes
Anexe


Backward incompatible changes

Although most existing PHP 5 code should work without changes, please take note of some backward incompatible changes:

Array keys won't be overwritten when defining an array as a property of a class via an array literal

Previously, arrays declared as class properties which mixed explicit and implicit keys could have array elements silently overwritten if an explicit key was the same as a sequential implicit key. For example:

<?php
class C {
    const ONE = 1;
    public $array = [
        self::ONE => 'foo',
        'bar',
        'quux',
    ];
}

var_dump((new C)->array);
?>

Exemplul de mai sus va afi?a în PHP 5.5:

array(2) {
  [0]=>
  string(3) "bar"
  [1]=>
  string(4) "quux"
}

Exemplul de mai sus va afi?a în PHP 5.6:

array(3) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(4) "quux"
}

json_decode() strictness

json_decode() now rejects non-lowercase variants of the JSON literals true, false and null at all times, as per the JSON specification, and sets json_last_error() accordingly. Previously, inputs to json_decode() that consisted solely of one of these values in upper or mixed case were accepted.

This change will only affect cases where invalid JSON was being passed to json_decode(): valid JSON input is unaffected and will continue to be parsed normally.

Stream wrappers now verify peer certificates and host names by default when using SSL/TLS

Toate torentele-client criptate ofera acum implicit verificarea corespondentului. Implicit aceasta va utiliza setul implicit de CA al OpenSSL pentru a verifica certificatul corespondentului. În majoritatea cazurilor nu va fi nevoie de careva schimbari pentru a comunica cu servere cu certificate SSL valide, deoarece distribuitorii de obicei configureaza OpenSSL sa utilizeze seturi valide de CA bine cunoscute.

Setul implicit de CA poate fi înlocuit global stabilind op?iunile de configurare openssl.cafile sau openssl.capath, sau la nivelul interpelarii utilizând op?iunile de context cafile sau capath.

Cu toate ca nu este recomandabil la general, este posibil de a dezactiva verificarea certificatului corespondentului pentru o interpelare stabilind op?iunea de context verify_peer în FALSE, ?i de a dezactiva validarea numelui corespondentului stabilind op?iunea de context verify_peer_name în FALSE.

GMP resources are now objects

GMP resources are now objects. The functional API implemented in the GMP extension has not changed, and code should run unmodified unless it checks explicitly for a resource using is_resource() or similar.

Mcrypt functions now require valid keys and IVs

mcrypt_encrypt(), mcrypt_decrypt(), mcrypt_cbc(), mcrypt_cfb(), mcrypt_ecb(), mcrypt_generic() and mcrypt_ofb() will no longer accept keys or IVs with incorrect sizes, and block cipher modes that require IVs will now fail if an IV isn't provided.

cURL file uploads

Uploads using the @file syntax now require CURLOPT_SAFE_UPLOAD to be set to FALSE. CURLFile should be used instead.

Migrating from PHP 5.5.x to PHP 5.6.x
New features
Migrating from PHP 5.5.x to PHP 5.6.x


New features

Constant expressions

It is now possible to provide a scalar expression involving numeric and string literals and/or constants in contexts where PHP previously expected a static value, such as constant and property declarations and default function arguments.

<?php
const ONE = 1;
const TWO = ONE * 2;

class C {
    const THREE = TWO + 1;
    const ONE_THIRD = ONE / self::THREE;
    const SENTENCE = 'The value of THREE is '.self::THREE;

    public function f($a = ONE + self::THREE) {
        return $a;
    }
}

echo (new C)->f()."\n";
echo C::SENTENCE;
?>

Exemplul de mai sus va afi?a:

4
The value of THREE is 3

It is also now possible to define a constant array using the const keyword:

<?php
const ARR = ['a', 'b'];

echo ARR[0];
?>

Exemplul de mai sus va afi?a:

a

Variadic functions via ...

Variadic functions can now be implemented using the ... operator, instead of relying on func_get_args().

<?php
function f($req, $opt = null, ...$params) {
    // $params is an array containing the remaining arguments.
    printf('$req: %d; $opt: %d; number of params: %d'."\n",
           $req, $opt, count($params));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);
?>

Exemplul de mai sus va afi?a:

$req: 1; $opt: 0; number of params: 0
$req: 1; $opt: 2; number of params: 0
$req: 1; $opt: 2; number of params: 1
$req: 1; $opt: 2; number of params: 2
$req: 1; $opt: 2; number of params: 3

Argument unpacking via ...

Arrays and Traversable objects can be unpacked into argument lists when calling functions by using the ... operator. This is also known as the splat operator in other languages, including Ruby.

<?php
function add($a, $b, $c) {
    return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators);
?>

Exemplul de mai sus va afi?a:

6

Exponentiation via **

A right associative ** operator has been added to support exponentiation, along with a **= shorthand assignment operator.

<?php
printf("2 ** 3 ==      %d\n", 2 ** 3);
printf("2 ** 3 ** 2 == %d\n", 2 ** 3 ** 2);

$a = 2;
$a **= 3;
printf("a ==           %d\n", $a);
?>

Exemplul de mai sus va afi?a:

2 ** 3 ==      8
2 ** 3 ** 2 == 512
a ==           8

use function and use const

The use operator has been extended to support importing functions and constants in addition to classes. This is achieved via the use function and use const constructs, respectively.

<?php
namespace Name\Space {
    const FOO = 42;
    function f() { echo __FUNCTION__."\n"; }
}

namespace {
    use const Name\Space\FOO;
    use function Name\Space\f;

    echo FOO."\n";
    f();
}
?>

Exemplul de mai sus va afi?a:

42
Name\Space\f

phpdbg

PHP now includes an interactive debugger called phpdbg implemented as a SAPI module. For more information, please visit the » phpdbg documentation.

Default character encoding

default_charset is now used as the default character set for the htmlentities(), html_entity_decode() and htmlspecialchars() functions. Note that if the (now deprecated) iconv and mbstring encoding settings are set, they will take precedence over default_charset for iconv and mbstring functions, respectively.

The default value for this setting is UTF-8.

php://input is reusable

php://input may now be reopened and read as many times as required. This work has also resulted in a major reduction in the amount of memory required to deal with POST data.

Large file uploads

Files larger than 2 gigabytes in size are now accepted.

GMP supports operator overloading

GMP objects now support operator overloading and casting to scalar types. This allows for more expressive code using GMP:

<?php
$a = gmp_init(42);
$b = gmp_init(17);

if (version_compare(PHP_VERSION, '5.6', '<')) {
    echo gmp_intval(gmp_add($a, $b)), PHP_EOL;
    echo gmp_intval(gmp_add($a, 17)), PHP_EOL;
    echo gmp_intval(gmp_add(42, $b)), PHP_EOL;
} else {
    echo $a + $b, PHP_EOL;
    echo $a + 17, PHP_EOL;
    echo 42 + $b, PHP_EOL;
}
?>

Exemplul de mai sus va afi?a:

59
59
59

hash_equals() for timing attack safe string comparison

The hash_equals() function has been added to compare two strings in constant time. This should be used to mitigate timing attacks; for instance, when testing crypt() password hashes (assuming that you are unable to use password_hash() and password_verify(), which aren't susceptible to timing attacks).

<?php
$expected  = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correct   = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrect = crypt('1234',  '$2a$07$usesomesillystringforsalt$');

var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));
?>

Exemplul de mai sus va afi?a:

bool(true)
bool(false)

__debugInfo()

The __debugInfo() magic method has been added to allow objects to change the properties and values that are shown when the object is output using var_dump().

<?php
class C {
    private $prop;

    public function __construct($val) {
        $this->prop = $val;
    }

    public function __debugInfo() {
        return [
            'propSquared' => $this->prop ** 2,
        ];
    }
}

var_dump(new C(42));
?>

Exemplul de mai sus va afi?a:

object(C)#1 (1) {
  ["propSquared"]=>
  int(1764)
}

gost-crypto hash algorithm

The gost-crypto hash algorithm has been added. This implements the GOST hash function using the CryptoPro S-box tables as specified by » RFC 4357, section 11.2.

SSL/TLS improvements

A wide range of improvements have been made to the SSL/TLS support in PHP 5.6. These include enabling peer verification by default, supporting certificate fingerprint matching, mitigating against TLS renegotiation attacks, and many new SSL context options to allow more fine grained control over protocol and verification settings when using encrypted streams.

These changes are described in more detail in the OpenSSL changes in PHP 5.6.x section of this migration guide.

pgsql async support

The pgsql extension now supports asynchronous connections and queries, thereby enabling non-blocking behaviour when interacting with PostgreSQL databases. Asynchronous connections may be established via the PGSQL_CONNECT_ASYNC constant, and the new pg_connect_poll(), pg_socket(), pg_consume_input() and pg_flush() functions may be used to handle asynchronous connections and queries.

Backward incompatible changes
Deprecated features in PHP 5.6.x
Migrating from PHP 5.5.x to PHP 5.6.x


Deprecated features in PHP 5.6.x

Calls from incompatible context

Methods called from an incompatible context are now deprecated, and will generate E_DEPRECATED errors when invoked instead of E_STRICT. Support for these calls will be removed in a future version of PHP.

An example of such a call is:

<?php
class A {
    function f() { echo get_class($this); }
}

class B {
    function f() { A::f(); }
}

(new B)->f();
?>

Exemplul de mai sus va afi?a:

Deprecated: Non-static method A::f() should not be called statically, assuming $this from incompatible context in - on line 7
B

$HTTP_RAW_POST_DATA and always_populate_raw_post_data

always_populate_raw_post_data will now generate an E_DEPRECATED error when $HTTP_RAW_POST_DATA is populated. New code should use php://input instead of $HTTP_RAW_POST_DATA, which will be removed in a future release. You can opt in for the new behaviour (in which $HTTP_RAW_POST_DATA is never defined hence no E_DEPRECATED error will be generated) by setting always_populate_raw_post_data to -1.

iconv and mbstring encoding settings

The iconv and mbstring configuration options related to encoding have been deprecated in favour of default_charset. The deprecated options are:

  • iconv.input_encoding
  • iconv.output_encoding
  • iconv.internal_encoding
  • mbstring.http_input
  • mbstring.http_output
  • mbstring.internal_encoding
New features
Changed functions
Migrating from PHP 5.5.x to PHP 5.6.x


Changed functions

PHP Core

  • crypt() will now raise an E_NOTICE error if the salt parameter is omitted.
  • substr_compare() will now accept 0 for its length parameter.
  • unserialize() will now fail if passed serialised data that has been manipulated to attempt to instantiate an object without calling its constructor.

cURL

  • Uploads using the @file syntax are now only supported if the CURLOPT_SAFE_UPLOAD option is set to FALSE. CURLFile should be used instead.

Mcrypt

  • The source parameter of mcrypt_create_iv() now defaults to MCRYPT_DEV_URANDOM instead of MCRYPT_DEV_RANDOM.

OpenSSL

  • stream_socket_enable_crypto() now allows the crypto_type parameter to be optional if the stream's SSL context includes the new crypto_type option.

PostgreSQL

  • pg_insert(), pg_select(), pg_update() and pg_delete() are no longer experimental.
  • pg_send_execute(), pg_send_prepare(), pg_send_query() and pg_send_query_params() will no longer block until query write completion if the underlying socket stream for the database connection is set to non-blocking mode.

Reflection

  • ReflectionClass::newInstanceWithoutConstructor() now allows non-final internal classes to be instantiated.

XMLReader

  • XMLReader::getAttributeNs() and XMLReader::getAttributeNo() now return NULL if the attribute could not be found, like XMLReader::getAttribute().
Deprecated features in PHP 5.6.x
New functions
Migrating from PHP 5.5.x to PHP 5.6.x


New functions

Date and Time

  • DateTimeImmutable::createFromMutable()

GMP

  • gmp_root()
  • gmp_rootrem()

Hash

  • hash_equals()

LDAP

  • ldap_escape()
  • ldap_modify_batch()

MySQLi

  • mysqli_get_links_stats()

OCI8

  • oci_get_implicit_resultset()

OpenSSL

  • openssl_get_cert_locations()
  • openssl_x509_fingerprint()
  • openssl_spki_new()
  • openssl_spki_verify()
  • openssl_spki_export_challenge()
  • openssl_spki_export()

PostgreSQL

  • pg_connect_poll()
  • pg_consume_input()
  • pg_flush()
  • pg_socket()

PDO_PGSQL

  • PDO::pgsqlGetNotify()
  • PDO::pgsqlGetPid()

Session

  • session_abort()
  • session_reset()

Zip

  • ZipArchive::setPassword()
Changed functions
OpenSSL changes in PHP 5.6.x
Migrating from PHP 5.5.x to PHP 5.6.x


OpenSSL changes in PHP 5.6.x

Stream wrappers now verify peer certificates and host names by default when using SSL/TLS

Toate torentele-client criptate ofera acum implicit verificarea corespondentului. Implicit aceasta va utiliza setul implicit de CA al OpenSSL pentru a verifica certificatul corespondentului. În majoritatea cazurilor nu va fi nevoie de careva schimbari pentru a comunica cu servere cu certificate SSL valide, deoarece distribuitorii de obicei configureaza OpenSSL sa utilizeze seturi valide de CA bine cunoscute.

Setul implicit de CA poate fi înlocuit global stabilind op?iunile de configurare openssl.cafile sau openssl.capath, sau la nivelul interpelarii utilizând op?iunile de context cafile sau capath.

Cu toate ca nu este recomandabil la general, este posibil de a dezactiva verificarea certificatului corespondentului pentru o interpelare stabilind op?iunea de context verify_peer în FALSE, ?i de a dezactiva validarea numelui corespondentului stabilind op?iunea de context verify_peer_name în FALSE.

Certificate fingerprints

Support has been added for extracting and verifying certificate fingerprints. openssl_x509_fingerprint() has been added to extract a fingerprint from an X.509 certificate, and two SSL stream context options have been added: capture_peer_cert to capture the peer's X.509 certificate, and peer_fingerprint to assert that the peer's certificate should match the given fingerprint.

Default ciphers updated

The default ciphers used by PHP have been updated to a more secure list based on the » Mozilla cipher recommendations, with two additional exclusions: anonymous Diffie-Hellman ciphers, and RC4.

This list can be accessed via the new OPENSSL_DEFAULT_STREAM_CIPHERS constant, and can be overridden (as in previous PHP versions) by setting the ciphers context option.

Compression disabled by default

SSL/TLS compression has been disabled by default to mitigate the CRIME attack. PHP 5.4.13 added a disable_compression context option to allow compression to be disabled: this is now set to TRUE (that is, compression is disabled) by default.

Allow servers to prefer their cipher order

The honor_cipher_order SSL context option has been added to allow encrypted stream servers to mitigate BEAST vulnerabilities by preferring the server's ciphers to the client's.

Access the negotiated protocol and cipher

The protocol and cipher that were negotiated for an encrypted stream can now be accessed via stream_get_meta_data() or stream_context_get_options() when the capture_session_meta SSL context option is set to TRUE.

<?php
$ctx = stream_context_create(['ssl' => [
    'capture_session_meta' => TRUE
]]);

$html = file_get_contents('https://google.com/', FALSE, $ctx);
$meta = stream_context_get_options($ctx)['ssl']['session_meta'];
var_dump($meta);
?>

Exemplul de mai sus va afi?a:

array(4) {
  ["protocol"]=>
  string(5) "TLSv1"
  ["cipher_name"]=>
  string(20) "ECDHE-RSA-AES128-SHA"
  ["cipher_bits"]=>
  int(128)
  ["cipher_version"]=>
  string(11) "TLSv1/SSLv3"
}

New options for perfect forward secrecy in encrypted stream servers

Encrypted client streams already support perfect forward secrecy, as it is generally controlled by the server. PHP encrypted server streams using certificates capable of perfect forward secrecy do not need to take any additional action to enable PFS; however a number of new SSL context options have been added to allow more control over PFS and deal with any compatibility issues that may arise.

ecdh_curve

This option allows the selection of a specific curve for use with ECDH ciphers. If not specified, prime256v1 will be used.

dh_param

A path to a file containing parametrs for Diffie-Hellman key exchange, such as that created by the following command:

openssl dhparam -out /path/to/my/certs/dh-2048.pem 2048
single_dh_use

If set to TRUE, a new key pair will be created when using Diffie-Hellman parameters, thereby improving forward secrecy.

single_ecdh_use

If set to TRUE, a new key pair will always be generated when ECDH cipher suites are negotiated. This improves forward secrecy.

SSL/TLS version selection

It is now possible to select specific versions of SSL and TLS via the crypto_method SSL context option or by specifying a specific transport when creating a stream wrapper (for example, by calling stream_socket_client() or stream_socket_server()).

The crypto_method SSL context option accepts a bitmask enumerating the protocols that are permitted, as does the crypto_type of stream_socket_enable_crypto().

Selected protocol versions and corresponding options
Protocol(s) | Client flag | Server flag | Transport
Any TLS or SSL version | STREAM_CRYPTO_METHOD_ANY_CLIENT | STREAM_CRYPTO_METHOD_ANY_SERVER | ssl://
Any TLS version | STREAM_CRYPTO_METHOD_TLS_CLIENT | STREAM_CRYPTO_METHOD_TLS_SERVER | tls://
TLS 1.0 | STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_0_SERVER | tlsv1.0://
TLS 1.1 | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_1_SERVER | tlsv1.1://
TLS 1.2 | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_SERVER | tlsv1.2://
SSL 3 | STREAM_CRYPTO_METHOD_SSLv3_CLIENT | STREAM_CRYPTO_METHOD_SSLv3_SERVER | sslv3://
<?php

// Requiring TLS 1.0 or better when using file_get_contents():
$ctx = stream_context_create([
    'ssl' => [
        'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
    ],
]);
$html = file_get_contents('https://google.com/', false, $ctx);

// Requiring TLS 1.1 or 1.2:
$ctx = stream_context_create([
    'ssl' => [
        'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT |
                           STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
    ],
]);
$html = file_get_contents('https://google.com/', false, $ctx);

// Connecting using the tlsv1.2:// stream socket transport.
$sock = stream_socket_client('tlsv1.2://google.com:443/');

?>

openssl_get_cert_locations() added

The openssl_get_cert_locations() function has been added: it returns the default locations PHP will search when looking for CA bundles.

<?php
var_dump(openssl_get_cert_locations());
?>

Exemplul de mai sus va afi?a:

array(8) {
  ["default_cert_file"]=>
  string(21) "/etc/pki/tls/cert.pem"
  ["default_cert_file_env"]=>
  string(13) "SSL_CERT_FILE"
  ["default_cert_dir"]=>
  string(18) "/etc/pki/tls/certs"
  ["default_cert_dir_env"]=>
  string(12) "SSL_CERT_DIR"
  ["default_private_dir"]=>
  string(20) "/etc/pki/tls/private"
  ["default_default_cert_area"]=>
  string(12) "/etc/pki/tls"
  ["ini_cafile"]=>
  string(0) ""
  ["ini_capath"]=>
  string(0) ""
}

SPKI support

Support has been added for generating, extracting and verifying signed public key and challenges (SPKAC). openssl_spki_new(), openssl_spki_verify(), openssl_spki_export_challenge(), and openssl_spki_export() have been added to create, verify export PEM public key and associated challenge from SPKAC's generated from a KeyGen HTML5 element.

openssl_spki_new

Generates a new SPKAC using private key, challenge string and hashing algorithm.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
?>

Exemplul de mai sus va afi?a:

SPKAC=MIIBXjCByDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA3L0IfUijj7+A8CPC8EmhcdNoe5fUAog7OrBdhn7EkxFButUp40P7+LiYiygYG1TmoI/a5EgsLU3s9twEz3hmgY9mYIqb/rb+SF8qlD/K6KVyUORC7Wlz1Df4L8O3DuRGzx6/+3jIW6cPBpfgH1sVuYS1vDBsP/gMMIxwTsKJ4P0CAwEAARYkYjViMzYxMTktNjY5YS00ZDljLWEyYzctMGZjNGFhMjVlMmE2MA0GCSqGSIb3DQEBAwUAA4GBAF7hu0ifzmjonhAak2FhhBRsKFDzXdKIkrWxVNe8e0bZzMrWOxFM/rqBgeH3/gtOUDRS5Fnzyq425UsTYbjfiKzxGeCYCQJb1KJ2V5Ij/mIJHZr53WYEXHQTNMGR8RPm7IxwVXVSHIgAfXsXZ9IXNbFbcaLRiSTr9/N4U+MXUWL7
openssl_spki_verify

Verifies provided SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
var_dump(openssl_spki_verify($spkac));
?>
openssl_spki_export_challenge

Exports associated challenge from provided SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
$challenge = openssl_spki_export_challenge($spkac):
echo $challenge;
?>

Exemplul de mai sus va afi?a:

challenge string
openssl_spki_export

Exports the PEM formatted RSA public key from SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
echo openssl_spki_export($spkac);
?>

Exemplul de mai sus va afi?a:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcvQh9SKOPv4DwI8LwSaFx02h7
l9QCiDs6sF2GfsSTEUG61SnjQ/v4uJiLKBgbVOagj9rkSCwtTez23ATPeGaBj2Zg
ipv+tv5IXyqUP8ropXJQ5ELtbXPUN/gvw7cO5EbPHr/7eMhbpw8Gl+AfWxW5hLW8
MGw/+AwwjHBOwong/QIDAQAB
-----END PUBLIC KEY-----
New functions
Other changes to extensions
Migrating from PHP 5.5.x to PHP 5.6.x


Other changes to extensions

cURL

A number of constants marked obsolete in the cURL library have now been removed:

  • CURLOPT_CLOSEPOLICY
  • CURLCLOSEPOLICY_CALLBACK
  • CURLCLOSEPOLICY_LEAST_RECENTLY_USED
  • CURLCLOSEPOLICY_LEAST_TRAFFIC
  • CURLCLOSEPOLICY_OLDEST
  • CURLCLOSEPOLICY_SLOWEST

OCI8

  • Support for implicit result sets for Oracle Database 12c has been added via the new oci_get_implicit_resultset() function.
  • Using oci_execute($s, OCI_NO_AUTO_COMMIT) for a SELECT no longer unnecessarily initiates an internal ROLLBACK during connection close.
  • Added DTrace probes controlled by the --enable-dtrace configure option.
  • oci_internal_debug() is now a no-op.
  • The phpinfo() output format for OCI8 has changed.

Zip

A --with-libzip configure option has been added to use a system libzip installation. libzip version 0.11 is required, with 0.11.2 or later recommended.

MySQLi

A new mysqli.rollback_on_cached_plink option was added to rollback connections put back into the persistent connection pool.

OpenSSL changes in PHP 5.6.x
New global constants
Migrating from PHP 5.5.x to PHP 5.6.x


New global constants

GD

  • IMG_WEBP (as of PHP 5.6.25)

LDAP

  • LDAP_ESCAPE_DN
  • LDAP_ESCAPE_FILTER

OpenSSL

  • OPENSSL_DEFAULT_STREAM_CIPHERS
  • STREAM_CRYPTO_METHOD_ANY_CLIENT
  • STREAM_CRYPTO_METHOD_ANY_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_0_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_1_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_2_SERVER

PostgreSQL

  • PGSQL_CONNECT_ASYNC
  • PGSQL_CONNECTION_AUTH_OK
  • PGSQL_CONNECTION_AWAITING_RESPONSE
  • PGSQL_CONNECTION_MADE
  • PGSQL_CONNECTION_SETENV
  • PGSQL_CONNECTION_SSL_STARTUP
  • PGSQL_CONNECTION_STARTED
  • PGSQL_DML_ESCAPE
  • PGSQL_POLLING_ACTIVE
  • PGSQL_POLLING_FAILED
  • PGSQL_POLLING_OK
  • PGSQL_POLLING_READING
  • PGSQL_POLLING_WRITING
Other changes to extensions
Migrating from PHP 5.4.x to PHP 5.5.x
Migrating from PHP 5.5.x to PHP 5.6.x


Migrating from PHP 5.4.x to PHP 5.5.x

Cuprins

  • What has changed in PHP 5.5.x
  • Backward Incompatible Changes
  • New features
  • Deprecated features in PHP 5.5.x
  • Changed Functions
  • New Functions
  • New Classes and Interfaces
  • New Methods
  • Other changes to extensions
  • New Global Constants
  • Changes to INI file handling
  • Changes to PHP Internals

Accesa?i de asemenea ghidurile de migrare pentru versiunile PHP 5.0.x, 5.1.x, 5.2.x, 5.3.x, 5.4.x, 5.6.x, and 7.0.x.

New global constants
What has changed in PHP 5.5.x
Anexe


What has changed in PHP 5.5.x

Most improvements in PHP 5.5.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.4.x.
  • 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.4.x to PHP 5.5.x
Backward Incompatible Changes
Migrating from PHP 5.4.x to PHP 5.5.x


Backward Incompatible Changes

Although most existing PHP 5 code should work without changes, please take note of some backward incompatible changes:

Windows XP and 2003 support dropped

Support for Windows XP and 2003 has been dropped. Windows builds of PHP now require Windows Vista or newer.

Case insensitivity no longer locale specific

All case insensitive matching for function, class and constant names is now performed in a locale independent manner according to ASCII rules. This improves support for languages using the Latin alphabet with unusual collating rules, such as Turkish and Azeri.

This may cause issues for code that uses case insensitive matches for non-ASCII characters in multibyte character sets (including UTF-8), such as accented characters in many European languages. If you have a non-English, non-ASCII code base, then you will need to test that you are not inadvertently relying on this behaviour before deploying PHP 5.5 to production systems.

pack() and unpack() changes

Changes were made to pack() and unpack() to make them more compatible with Perl:

  • pack() now supports the "Z" format code, which behaves identically to "a".
  • unpack() now support the "Z" format code for NULL padded strings, and behaves as "a" did in previous versions: it will strip trailing NULL bytes.
  • unpack() now keeps trailing NULL bytes when the "a" format code is used.
  • unpack() now strips all trailing ASCII whitespace when the "A" format code is used.

Writing backward compatible code that uses the "a" format code with unpack() requires the use of version_compare(), due to the backward compatibility break.

For example:

<?php
// Old code:
$data = unpack('a5', $packed);

// New code:
if (version_compare(PHP_VERSION, '5.5.0-dev', '>=')) {
  $data = unpack('Z5', $packed);
} else {
  $data = unpack('a5', $packed);
}
?>

self, parent and static are now always case insensitive

Prior to PHP 5.5, cases existed where the self, parent, and static keywords were treated in a case sensitive fashion. These have now been resolved, and these keywords are always handled case insensitively: SELF::CONSTANT is now treated identically to self::CONSTANT.

PHP logo GUIDs removed

The GUIDs that previously resulted in PHP outputting various logos have been removed. This includes the removal of the functions to return those GUIDs. The removed functions are:

  • php_logo_guid()
  • php_egg_logo_guid()
  • php_real_logo_guid()
  • zend_logo_guid()

Internal execution changes

Extension authors should note that the zend_execute() function can no longer be overridden, and that numerous changes have been made to the execute_data struct and related function and method handling opcodes.

Most extension authors are unlikely to be affected, but those writing extensions that hook deeply into the Zend Engine should read the notes on these changes.

What has changed in PHP 5.5.x
New features
Migrating from PHP 5.4.x to PHP 5.5.x


New features

Generators added

Support for generators has been added via the yield keyword. Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A simple example that reimplements the range() function as a generator (at least for positive step values):

<?php
function xrange($start, $limit, $step = 1) {
    for ($i = $start; $i <= $limit; $i += $step) {
        yield $i;
    }
}

echo 'Single digit odd numbers: ';

/*
 * Note that an array is never created or returned,
 * which saves memory.
 */
foreach (xrange(1, 9, 2) as $number) {
    echo "$number ";
}

echo "\n";
?>

Exemplul de mai sus va afi?a:

Single digit odd numbers: 1 3 5 7 9

finally keyword added

try-catch blocks now support a finally block for code that should be run regardless of whether an exception has been thrown or not.

New password hashing API

A new password hashing API that makes it easier to securely hash and manage passwords using the same underlying library as crypt() in PHP has been added. See the documentation for password_hash() for more detail.

foreach now supports list()

The foreach control structure now supports unpacking nested arrays into separate variables via the list() construct. For example:

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b)) {
    echo "A: $a; B: $b\n";
}
?>

Exemplul de mai sus va afi?a:

A: 1; B: 2
A: 3; B: 4

Further documentation is available on the foreach manual page.

empty() supports arbitrary expressions

Passing an arbitrary expression instead of a variable to empty() is now supported. For example:

<?php
function always_false() {
    return false;
}

if (empty(always_false())) {
    echo "This will be printed.\n";
}

if (empty(true)) {
    echo "This will not be printed.\n";
}
?>

Exemplul de mai sus va afi?a:

This will be printed.

array and string literal dereferencing

Array and string literals can now be dereferenced directly to access individual elements and characters:

<?php
echo 'Array dereferencing: ';
echo [1, 2, 3][0];
echo "\n";

echo 'String dereferencing: ';
echo 'PHP'[0];
echo "\n";
?>

Exemplul de mai sus va afi?a:

Array dereferencing: 1
String dereferencing: P

Class name resolution via ::class

It is possible to use ClassName::class to get a fully qualified name of class ClassName. For example:

<?php
namespace Name\Space;
class ClassName {}

echo ClassName::class;

echo "\n";
?>

Exemplul de mai sus va afi?a:

Name\Space\ClassName

OPcache extension added

The Zend Optimiser+ opcode cache has been added to PHP as the new OPcache extension. OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request. See the installation instructions for more detail on enabling and using OPcache.

foreach now supports non-scalar keys

foreach now supports keys of any type. While non-scalar keys cannot occur in native PHP arrays, it is possible for Iterator::key() to return a value of any type, and this will now be handled correctly.

Apache 2.4 handler supported on Windows

The Apache 2.4 handler SAPI is now supported on Windows.

Improvements to GD

Various improvements have been made to the GD extension, these include:

  • Flipping support using the new imageflip() function.
  • Advanced cropping support using the imagecrop() & imagecropauto() functions.
  • WebP read and write support using imagecreatefromwebp() & imagewebp() respectively.
Backward Incompatible Changes
Deprecated features in PHP 5.5.x
Migrating from PHP 5.4.x to PHP 5.5.x


Deprecated features in PHP 5.5.x

ext/mysql deprecation

The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MySQLi or PDO_MySQL extensions.

preg_replace() /e modifier

The preg_replace() /e modifier is now deprecated. Instead, use the preg_replace_callback() function.

intl deprecations

IntlDateFormatter::setTimeZoneID() and
datefmt_set_timezone_id() are now deprecated. Instead,
use the IntlDateFormatter::setTimeZone() method and
datefmt_set_timezone() function, respectively.

mcrypt deprecations

The following functions have been deprecated:

  • mcrypt_cbc()
  • mcrypt_cfb()
  • mcrypt_ecb()
  • mcrypt_ofb()
New features
Changed Functions
Migrating from PHP 5.4.x to PHP 5.5.x


Changed Functions

PHP Core

  • set_error_handler() can now be called with NULL as an argument to reset the error handler.
  • When called with NULL, set_error_handler() and set_exception_handler() now return the previous error or exception handler, respectively.
  • json_encode() now accepts depth parameter.
  • The behaviour of pack() and unpack() with the "a" and "A" format codes has changed. Detailed notes on these changes are available.

intl

  • MessageFormatter::format() and related functions now accept named arguments and mixed numeric and named arguments when PHP is linked to ICU 4.8 or later.
  • MessageFormatter::format() and related functions no longer error when an insufficient number of arguments have been provided. Instead, the placeholders will not be substituted.
  • MessageFormatter::format() and MessageFormatter::parse() are no longer limited to second precision when dealing with times.
  • IntlDateFormatter::__construct() and datefmt_create() now accept IntlTimeZone and DateTimeZone objects for the timezone argument, and IntlCalendar objects for the calendar argument. Furthermore, if the time zone is omitted and the calendar doesn't specify a time zone, PHP's default time zone from date_default_timezone_get() is now used instead of the default ICU time zone.
  • IntlDateFormatter::getCalendar() and datefmt_get_calendar() return false if the IntlDateFormatter object was created with an IntlCalendar instance instead of one of the IntlDateFormatter constants.
  • IntlDateFormatter::setCalendar() and datefmt_set_calendar() now accept IntlCalendar objects in addition to the IntlDateFormatter constants.
  • IntlDateFormatter::format() and datefmt_format() now accept IntlCalendar objects.
Deprecated features in PHP 5.5.x
New Functions
Migrating from PHP 5.4.x to PHP 5.5.x


New Functions

PHP Core

  • array_column()
  • boolval()
  • json_last_error_msg()
  • password_get_info()
  • password_hash()
  • password_needs_rehash()
  • password_verify()

Hash

  • hash_pbkdf2()

OpenSSL

  • openssl_pbkdf2()

cURL

  • curl_escape()
  • curl_file_create()
  • curl_multi_setopt()
  • curl_multi_strerror()
  • curl_pause()
  • curl_reset()
  • curl_share_close()
  • curl_share_init()
  • curl_share_setopt()
  • curl_strerror()
  • curl_unescape()

GD

  • imageaffinematrixconcat()
  • imageaffinematrixget()
  • imagecrop()
  • imagecropauto()
  • imageflip()
  • imagepalettetotruecolor()
  • imagescale()

MySQLi

  • mysqli_begin_transaction()
  • mysqli_release_savepoint()
  • mysqli_savepoint()

PostgreSQL

  • pg_escape_literal()
  • pg_escape_identifier()

Sockets

  • socket_sendmsg()
  • socket_recvmsg()
  • socket_cmsg_space()

CLI

  • cli_get_process_title()
  • cli_set_process_title()

Intl

  • datefmt_format_object()
  • datefmt_get_calendar_object()
  • datefmt_get_timezone()
  • datefmt_set_timezone()
  • datefmt_get_calendar_object()
  • intlcal_create_instance()
  • intlcal_get_keyword_values_for_locale()
  • intlcal_get_now()
  • intlcal_get_available_locales()
  • intlcal_get()
  • intlcal_get_time()
  • intlcal_set_time()
  • intlcal_add()
  • intlcal_set_time_zone()
  • intlcal_after()
  • intlcal_before()
  • intlcal_set()
  • intlcal_roll()
  • intlcal_clear()
  • intlcal_field_difference()
  • intlcal_get_actual_maximum()
  • intlcal_get_actual_minimum()
  • intlcal_get_day_of_week_type()
  • intlcal_get_first_day_of_week()
  • intlcal_get_greatest_minimum()
  • intlcal_get_least_maximum()
  • intlcal_get_locale()
  • intlcal_get_maximum()
  • intlcal_get_minimal_days_in_first_week()
  • intlcal_get_minimum()
  • intlcal_get_time_zone()
  • intlcal_get_type()
  • intlcal_get_weekend_transition()
  • intlcal_in_daylight_time()
  • intlcal_is_equivalent_to()
  • intlcal_is_lenient()
  • intlcal_is_set()
  • intlcal_is_weekend()
  • intlcal_set_first_day_of_week()
  • intlcal_set_lenient()
  • intlcal_equals()
  • intlcal_get_repeated_wall_time_option()
  • intlcal_get_skipped_wall_time_option()
  • intlcal_set_repeated_wall_time_option()
  • intlcal_set_skipped_wall_time_option()
  • intlcal_from_date_time()
  • intlcal_to_date_time()
  • intlcal_get_error_code()
  • intlcal_get_error_message()
  • intlgregcal_create_instance()
  • intlgregcal_set_gregorian_change()
  • intlgregcal_get_gregorian_change()
  • intlgregcal_is_leap_year()
  • intltz_create_time_zone()
  • intltz_create_default()
  • intltz_get_id()
  • intltz_get_gmt()
  • intltz_get_unknown()
  • intltz_create_enumeration()
  • intltz_count_equivalent_ids()
  • intltz_create_time_zone_id_enumeration()
  • intltz_get_canonical_id()
  • intltz_get_region()
  • intltz_get_tz_data_version()
  • intltz_get_equivalent_id()
  • intltz_use_daylight_time()
  • intltz_get_offset()
  • intltz_get_raw_offset()
  • intltz_has_same_rules()
  • intltz_get_display_name()
  • intltz_get_dst_savings()
  • intltz_from_date_time_zone()
  • intltz_to_date_time_zone()
  • intltz_get_error_code()
  • intltz_get_error_message()

SPL

  • SplFixedArray::__wakeup()
Changed Functions
New Classes and Interfaces
Migrating from PHP 5.4.x to PHP 5.5.x


New Classes and Interfaces

cURL

  • CURLFile

Date and Time

  • DateTimeImmutable
  • DateTimeInterface

Intl

  • IntlCalendar
  • IntlGregorianCalendar
  • IntlTimeZone
  • IntlBreakIterator
  • IntlRuleBasedBreakIterator
  • IntlCodePointBreakIterator
New Functions
New Methods
Migrating from PHP 5.4.x to PHP 5.5.x


New Methods

MySQLi

  • mysqli::begin_transaction()
  • mysqli::release_savepoint()
  • mysqli::savepoint()

Intl

  • IntlDateFormatter::formatObject()
  • IntlDateFormatter::getCalendarObject()
  • IntlDateFormatter::getTimeZone()
  • IntlDateFormatter::setTimeZone()
New Classes and Interfaces
Other changes to extensions
Migrating from PHP 5.4.x to PHP 5.5.x


Other changes to extensions

Intl

The intl extension now requires ICU 4.0 or later.

New Methods
New Global Constants
Migrating from PHP 5.4.x to PHP 5.5.x


New Global Constants

GD

  • IMG_AFFINE_TRANSLATE
  • IMG_AFFINE_SCALE
  • IMG_AFFINE_ROTATE
  • IMG_AFFINE_SHEAR_HORIZONTAL
  • IMG_AFFINE_SHEAR_VERTICAL
  • IMG_CROP_DEFAULT
  • IMG_CROP_TRANSPARENT
  • IMG_CROP_BLACK
  • IMG_CROP_WHITE
  • IMG_CROP_SIDES
  • IMG_FLIP_BOTH
  • IMG_FLIP_HORIZONTAL
  • IMG_FLIP_VERTICAL
  • IMG_BELL
  • IMG_BESSEL
  • IMG_BICUBIC
  • IMG_BICUBIC_FIXED
  • IMG_BLACKMAN
  • IMG_BOX
  • IMG_BSPLINE
  • IMG_CATMULLROM
  • IMG_GAUSSIAN
  • IMG_GENERALIZED_CUBIC
  • IMG_HERMITE
  • IMG_HAMMING
  • IMG_HANNING
  • IMG_MITCHELL
  • IMG_POWER
  • IMG_QUADRATIC
  • IMG_SINC
  • IMG_NEAREST_NEIGHBOUR
  • IMG_WEIGHTED4
  • IMG_TRIANGLE

JSON

  • JSON_ERROR_RECURSION
  • JSON_ERROR_INF_OR_NAN
  • JSON_ERROR_UNSUPPORTED_TYPE

MySQLi

The MYSQLI_SERVER_PUBLIC_KEY option has been added for use with mysqli_options().

Other changes to extensions
Changes to INI file handling
Migrating from PHP 5.4.x to PHP 5.5.x


Changes to INI file handling

Intl

The intl.use_exceptions configuration directive has been added, which controls the behaviour of intl when global errors occur in conjunction with the already extant intl.error_level configuration directive.

MySQLnd

The mysqlnd.sha256_server_public_key configuration directive has been added to allow mysqli to use the new MySQL authentication protocol.

New Global Constants
Changes to PHP Internals
Migrating from PHP 5.4.x to PHP 5.5.x


Changes to PHP Internals

  • Extensions cannot override zend_execute() any more and should override zend_execute_ex() instead. EG(current_execute_data) is already initialized in zend_execute_ex(), so for compatibility extensions may need to use EG(current_execute_data)->prev_execute_data instead.
  • Removed EG(arg_types_stack), EX(fbc), EX(called_scope) and EX(current_object).
  • Added op_array->nested_calls, which is calculated at compile time.
  • Added EX(call_slots), which is an array to store information about syntaticaly nested calls (e.g. foo(bar())) and is preallocated together with execute_data.
  • Added EX(call), which is a pointer to a current calling function, and is an element of EX(call_slots).
  • Opcodes INIT_METHOD_CALL, ZEND_INIT_STATIC_METHOD_CALL, ZEND_INIT_FCALL_BY_NAME and ZEND_INIT_NS_FCALL_BY_NAME use result.num as an index in EX(call_slots).
  • Opcode ZEND_NEW uses extended_value as an index in EX(call_slots).
  • Opcodes ZEND_DO_FCALL and ZEND_DO_FCALL_BY_NAME use op2.num as an index in EX(call_slots).
  • Added op_array->used_stack, which is calculated at compile time; the corresponding stack space is preallocated together with execute_data. As a result, the ZEND_SEND* and ZEND_DO_FCALL* opcodes no longer need to check for stack overflow.
  • Removed execute_data->Ts field. The VM temporary variables are always allocated immediately before the execute_data structure, and are now accessed by their offset from the execute_data base pointer instead of via execute_data->Ts. The compiler stores new offsets in op_array->opcodes[*].op?.num. The EX_TMP_VAR() and EX_TMP_VAR_NUM() macros can be used to access temporary variables by offset or number. You can convert the number to an offset using EX_TMP_VAR_NUM(0, num) or offset to number using (EX_TMP_VAR_NUM(0,0)-EX_TMP_VAR(0,offset)).
  • Removed the execute_data->CVs field. The VM compiled variables are always allocated immediately after the execute_data structure, and are now accessed by the offset from the execute_data base pointer instead of via execute_data->CVs. You can use the EX_CV_NUM() macro to access compiled variables by number.
Changes to INI file handling
Migrating from PHP 5.3.x to PHP 5.4.x
Migrating from PHP 5.4.x to PHP 5.5.x


Migrating from PHP 5.3.x to PHP 5.4.x

Cuprins

  • What has changed in PHP 5.4.x
  • Backward Incompatible Changes
  • New features
  • Changes in SAPI modules
  • Deprecated features in PHP 5.4.x
  • Changed Functions
  • New Functions
  • New Classes and Interfaces
  • New Methods
  • Removed Extensions
  • Other changes to extensions
  • New Global Constants
  • Changes to INI file handling
  • Other changes

Accesa?i de asemenea ghidurile de migrare pentru versiunile PHP 5.0.x, 5.1.x, 5.2.x, 5.3.x, 5.5.x and 5.6.x.

Changes to PHP Internals
What has changed in PHP 5.4.x
Anexe


What has changed in PHP 5.4.x

Most improvements in PHP 5.4.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.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:

  • Safe mode is no longer supported. Any applications that rely on safe mode may need adjustment, in terms of security.
  • Magic quotes has been removed. Applications relying on this feature may need to be updated, to avoid security issues. get_magic_quotes_gpc() and get_magic_quotes_runtime() now always return FALSE. set_magic_quotes_runtime() raises an E_CORE_ERROR level error on trying to enable Magic quotes.
  • The register_globals and register_long_arrays php.ini directives have been removed.
  • The mbstring.script_encoding directive has been removed. Use zend.script_encoding instead.
  • Call-time pass by reference has been removed.
  • The break and continue statements no longer accept variable arguments (e.g., break 1 + foo() * $bar;). Static arguments still work, such as break 2;. As a side effect of this change break 0; and continue 0; are no longer allowed.
  • In the date and time extension, the timezone can no longer be set using the TZ environment variable. Instead you have to specify a timezone using the date.timezone php.ini option or date_default_timezone_set() function. PHP will no longer attempt to guess the timezone, and will instead fall back to "UTC" and issue a E_WARNING.
  • Non-numeric string offsets - e.g. $a['foo'] where $a is a string - now return false on isset() and true on empty(), and produce a E_WARNING if you try to use them. Offsets of types double, bool and null produce a E_NOTICE. Numeric strings (e.g. $a['2']) still work as before. Note that offsets like '12.3' and '5 foobar' are considered non-numeric and produce a E_WARNING, but are converted to 12 and 5 respectively, for backward compatibility reasons. Note: Following code returns different result. $str='abc';var_dump(isset($str['x'])); // false for PHP 5.4 or later, but true for 5.3 or less
  • Converting an array to a string will now generate an E_NOTICE level error, but the result of the cast will still be the string "Array".
  • Turning NULL, FALSE, or an empty string into an object by adding a property will now emit an E_WARNING level error, instead of E_STRICT.
  • Parameter names that shadow super globals now cause a fatal error. This prohibits code like function foo($_GET, $_POST) {}.
  • The Salsa10 and Salsa20 hash algorithms have been removed.
  • array_combine() now returns array() instead of FALSE when two empty arrays are provided as parameters.
  • If you use htmlentities() with asian character sets, it works like htmlspecialchars() - this has always been the case in previous versions of PHP, but now an E_STRICT level error is emitted.
  • The third parameter of ob_start() has changed from boolean erase to integer flags. Note that code that explicitly set erase to FALSE will no longer behave as expected in PHP 5.4: please follow this example to write code that is compatible with PHP 5.3 and 5.4.

The following keywords are now reserved, and may not be used as names by functions, classes, etc.

  • trait
  • callable
  • insteadof

The following functions have been removed from PHP:

  • define_syslog_variables()
  • import_request_variables()
  • session_is_registered(), session_register() and session_unregister().
  • The aliases
mysqli_bind_param(), mysqli_bind_result(),
mysqli_client_encoding(), mysqli_fetch(),
mysqli_param_count(), mysqli_get_metadata(),
mysqli_send_long_data(), mysqli::client_encoding() and mysqli_stmt::stmt().
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.
  • Short array syntax has been added, e.g. $a = [1, 2, 3, 4]; or $a = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];.
  • Function array dereferencing has been added, e.g. foo()[0].
  • Closures now support $this.
  • <?= is now always available, regardless of the short_open_tag php.ini option.
  • Class member access on instantiation has been added, e.g. (new Foo)->bar().
  • Class::{expr}() syntax is now supported.
  • Binary number format has been added, e.g. 0b001001101.
  • Improved parse error messages and improved incompatible arguments warnings.
  • The session extension can now track the upload progress of files.
  • Built-in development web server in CLI mode.
Backward Incompatible Changes
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.
  • Added CLI option --rz which shows information of the named Zend extension.
  • Added shortcut #inisetting=value to change php.ini settings at run-time in interactive readline CLI
  • Added apache compatible functions: apache_child_terminate(),
getallheaders(), apache_request_headers()
and apache_response_headers() for FastCGI SAPI.
  • PHP-FPM: Added the process.max setting, to control the number of processes that FPM can fork.
New features
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

Deprecated functions:

  • mysql_list_dbs()
Changes in SAPI modules
Changed Functions
Migrating from PHP 5.3.x to PHP 5.4.x


Changed Functions

Several functions were given new, optional parameters in PHP 5.4:

PHP Core:

  • Added the optional limit parameter to debug_backtrace() and debug_print_backtrace(), to limit the amount of stack frames returned.
  • is_link() now works properly for symbolic links on Windows Vista or later. Earlier systems do not support symbolic links.
  • parse_url() now recognizes the host when a scheme is omitted, and a leading component separator is present. As of PHP 5.4.7.

OpenSSL:

  • Added a no padding option to the openssl_encrypt() and openssl_decrypt() functions.

Intl:

  • idn_to_ascii() and idn_to_utf8() now take two extra parameters, one indicating the variant (IDNA 2003 or UTS #46) and another, passed by reference, to return details about the operation in case UTS #46 is chosen.
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:

  • hex2bin()
  • http_response_code()
  • get_declared_traits()
  • getimagesizefromstring()
  • stream_set_chunk_size()
  • socket_import_stream()
  • trait_exists()
  • header_register_callback()

SPL:

  • class_uses()

Session:

  • session_status()
  • session_register_shutdown()

Mysqli:

  • mysqli_error_list()
  • mysqli_stmt_error_list()

Libxml:

  • libxml_set_external_entity_loader()

LDAP:

  • ldap_control_paged_result()
  • ldap_control_paged_result_response()

Intl:

  • transliterator_create()
  • transliterator_create_from_rules()
  • transliterator_create_inverse()
  • transliterator_get_error_code()
  • transliterator_get_error_message()
  • transliterator_list_ids()
  • transliterator_transliterate()

Zlib:

  • zlib_decode()
  • zlib_encode()
Changed Functions
New Classes and Interfaces
Migrating from PHP 5.3.x to PHP 5.4.x


New Classes and Interfaces

The following classes were introduced in PHP 5.4.0:

SPL:

  • CallbackFilterIterator
  • RecursiveCallbackFilterIterator

Reflection:

  • ReflectionZendExtension

Json:

  • JsonSerializable

Session:

  • SessionHandler
  • SessionHandlerInterface

Snmp:

  • SNMP

Intl:

  • Transliterator
  • Spoofchecker
New Functions
New Methods
Migrating from PHP 5.3.x to PHP 5.4.x


New Methods

Several new methods were introduced in 5.4.0:

XSL:

  • XsltProcessor::setSecurityPrefs()
  • XsltProcessor::getSecurityPrefs()

SPL:

  • RegexIterator::getRegex()
  • SplObjectStorage::getHash()
  • DirectoryIterator::getExtension()
  • SplDoublyLinkedList::serialize()
  • SplDoublyLinkedList::unserialize()
  • SplFileInfo::getExtension()
  • SplFileObject::fputcsv()
  • SplQueue::serialize()
  • SplQueue::unserialize()
  • SplStack::serialize()
  • SplStack::unserialize()
  • SplTempFileObject::fputcsv()

Reflection:

  • ReflectionExtension::isPersistent()
  • ReflectionExtension::isTemporary()
  • ReflectionClass::isCloneable()

Closure:

  • Closure::bind()
  • Closure::bindTo()

PDO_dblib:

  • PDO::newRowset()

StreamWrapper:

  • StreamWrapper::stream_metadata()
  • StreamWrapper::stream_truncate()
New Classes and Interfaces
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.

  • sqlite - Note that ext/sqlite3 and ext/pdo_sqlite are not affected
New Methods
Other changes to extensions
Migrating from PHP 5.3.x to PHP 5.4.x


Other changes to extensions

Changes in extension behavior, and new features:

  • mysqli - mysqli_result now implements Traversable
  • pdo_mysql - Removed support for linking with MySQL client libraries older than 4.1
  • The MySQL extensions mysql, mysqli and PDO_mysql use mysqlnd as the default library now. It is still possible to use libmysqlclient by specifying a path to the configure options.
  • mysqlnd - Added named pipes support
Removed Extensions
New Global Constants
Migrating from PHP 5.3.x to PHP 5.4.x


New Global Constants

PHP Core:

  • ENT_DISALLOWED
  • ENT_HTML401
  • ENT_HTML5
  • ENT_SUBSTITUTE
  • ENT_XML1
  • ENT_XHTML
  • IPPROTO_IP
  • IPPROTO_IPV6
  • IPV6_MULTICAST_HOPS
  • IPV6_MULTICAST_IF
  • IPV6_MULTICAST_LOOP
  • IP_MULTICAST_IF
  • IP_MULTICAST_LOOP
  • IP_MULTICAST_TTL
  • MCAST_JOIN_GROUP
  • MCAST_LEAVE_GROUP
  • MCAST_BLOCK_SOURCE
  • MCAST_UNBLOCK_SOURCE
  • MCAST_JOIN_SOURCE_GROUP
  • MCAST_LEAVE_SOURCE_GROUP

Curl:

  • CURLOPT_MAX_RECV_SPEED_LARGE
  • CURLOPT_MAX_SEND_SPEED_LARGE

LibXML:

  • LIBXML_HTML_NODEFDTD
  • LIBXML_HTML_NOIMPLIED
  • LIBXML_PEDANTIC

OpenSSL:

  • OPENSSL_CIPHER_AES_128_CBC
  • OPENSSL_CIPHER_AES_192_CBC
  • OPENSSL_CIPHER_AES_256_CBC
  • OPENSSL_RAW_DATA
  • OPENSSL_ZERO_PADDING

Output buffering:

  • PHP_OUTPUT_HANDLER_CLEAN
  • PHP_OUTPUT_HANDLER_CLEANABLE
  • PHP_OUTPUT_HANDLER_DISABLED
  • PHP_OUTPUT_HANDLER_FINAL
  • PHP_OUTPUT_HANDLER_FLUSH
  • PHP_OUTPUT_HANDLER_FLUSHABLE
  • PHP_OUTPUT_HANDLER_REMOVABLE
  • PHP_OUTPUT_HANDLER_STARTED
  • PHP_OUTPUT_HANDLER_STDFLAGS
  • PHP_OUTPUT_HANDLER_WRITE

Sessions:

  • PHP_SESSION_ACTIVE
  • PHP_SESSION_DISABLED
  • PHP_SESSION_NONE

Streams:

  • STREAM_META_ACCESS
  • STREAM_META_GROUP
  • STREAM_META_GROUP_NAME
  • STREAM_META_OWNER
  • STREAM_META_OWNER_NAME
  • STREAM_META_TOUCH

Zlib:

  • ZLIB_ENCODING_DEFLATE
  • ZLIB_ENCODING_GZIP
  • ZLIB_ENCODING_RAW

Intl:

  • U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR
  • IDNA_CHECK_BIDI
  • IDNA_CHECK_CONTEXTJ
  • IDNA_NONTRANSITIONAL_TO_ASCII
  • IDNA_NONTRANSITIONAL_TO_UNICODE
  • INTL_IDNA_VARIANT_2003
  • INTL_IDNA_VARIANT_UTS46
  • IDNA_ERROR_EMPTY_LABEL
  • IDNA_ERROR_LABEL_TOO_LONG
  • IDNA_ERROR_DOMAIN_NAME_TOO_LONG
  • IDNA_ERROR_LEADING_HYPHEN
  • IDNA_ERROR_TRAILING_HYPHEN
  • IDNA_ERROR_HYPHEN_3_4
  • IDNA_ERROR_LEADING_COMBINING_MARK
  • IDNA_ERROR_DISALLOWED
  • IDNA_ERROR_PUNYCODE
  • IDNA_ERROR_LABEL_HAS_DOT
  • IDNA_ERROR_INVALID_ACE_LABEL
  • IDNA_ERROR_BIDI
  • IDNA_ERROR_CONTEXTJ

Json:

  • JSON_PRETTY_PRINT
  • JSON_UNESCAPED_SLASHES
  • JSON_NUMERIC_CHECK
  • JSON_UNESCAPED_UNICODE
  • JSON_BIGINT_AS_STRING
Other changes to extensions
Changes to INI file handling
Migrating from PHP 5.3.x to PHP 5.4.x


Changes to INI file handling

The following php.ini directives have been removed:

  • register_globals and register_long_arrays
  • magic_quotes_gpc, magic_quotes_runtime, and magic_quotes_sybase
  • allow_call_time_pass_reference
  • define_syslog_variables
  • highlight.bg
  • session.bug_compat_42 and session.bug_compat_warn
  • mbstring.script_encoding
  • y2k_compliance
  • safe_mode, safe_mode_gid, safe_mode_include_dir, safe_mode_exec_dir, safe_mode_allowed_env_vars, and safe_mode_protected_env_vars

The following php.ini directives have been added:

  • cli.pager and cli.prompt for CLI SAPI using readline in interactive mode.
  • cli_server.color to enable the built-in development web server to use ANSI color coding in terminal output.
  • max_input_vars - specifies how many GET/POST/COOKIE input variables may be accepted.
  • zend.multibyte - to control the new multibyte support.
  • zend.script_encoding - This value will be used unless a "declare(encoding=...)" directive appears at the top of the script.
  • zend.signal_check - to check for replaced signal handlers on shutdown.
  • session.upload_progress.enabled, session.upload_progress.cleanup, session.upload_progress.prefix, session.upload_progress.name, session.upload_progress.freq, session.upload_progress.min_freq
  • enable_post_data_reading - When it's disabled, the POST data is not read (and processed)
  • windows_show_crt_warning - This directive shows the Windows CRT warnings when enabled. These warnings were displayed by default until now.

The following php.ini. directives have been changed:

  • session.entropy_file now defaults to /dev/random or /dev/urandom depending on what has been guessed at compile time.
  • session.entropy_length now defaults to 32.
New Global Constants
Other changes
Migrating from PHP 5.3.x to PHP 5.4.x


Other changes

  • The default character set for htmlspecialchars() and htmlentities() is now UTF-8, instead of ISO-8859-1. Note that changing your output charset via the default_charset configuration setting does not affect htmlspecialchars/htmlentities unless you are passing "" (an empty string) as the encoding parameter to your htmlspecialchars()/htmlentities() calls. Generally we do not recommend doing this because you should be able to change your output charset without affecting the runtime charset used by these functions. The safest approach is to explicitly set the charset on each call to htmlspecialchars() and htmlentities().
  • E_ALL now includes E_STRICT level errors in the error_reporting configuration directive.
  • SNMP now has an OOP API. Functions now return FALSE on every error condition including SNMP-related (no such instance, end of MIB, etc). Thus, in particular, breaks previous behavior of get/walk functions returning an empty string on SNMP-related errors. Multi OID get/getnext/set queries are now supported. Dropped UCD-SNMP compatibility code, consider upgrading to net-snmp v5.3+, Net-SNMP v5.4+ is required for Windows version. In sake of adding support for IPv6 DNS name resolution of remote SNMP agent (peer) is done by extension now, not by Net-SNMP library anymore.
  • OpenSSL now supports AES.
  • CLI SAPI doesn't terminate any more on fatal errors when using interactive mode with readline support.
  • $_SERVER['REQUEST_TIME_FLOAT'] has been added to include microsecond precision.
  • Added new hash algorithms: fnv132, fnv164, joaat
  • Chained string offsets - e.g. $a[0][0] where $a is a string - now work.
  • Arrays cast from SimpleXMLElement now always contain all nodes instead of just the first matching node. All SimpleXMLElement children are now always printed when using var_dump(), var_export() and print_r().
  • It's now possible to enforce the class' __construct arguments in an abstract constructor in the base class.
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

Cuprins

  • 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

Accesa?i de asemenea ghidurile de migrare pentru versiunile PHP 5.0.x, 5.1.x, 5.2.x, 5.4.x, 5.5.x and 5.6.x.

Other changes
What has changed in PHP 5.3.x
Anexe


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 libmysqlclient 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:
    <?php
    class C {
       public static     $foo = 123;
    }

    $a = "C";
    echo     $a::$foo;
    ?>

    Exemplul de mai sus va afi?a:

    123
  • Exceptions can now be nested:
    <?php
    class MyCustomException extends Exception {}

    try {
        throw new     MyCustomException("Exceptional", 112);
    } catch (    Exception $e) {
            /* Note the use of the third parameter to pass $e
         * into the RuntimeException. */
            throw new RuntimeException("Rethrowing", 911, $e);
    }
    ?>
  • A garbage collector for circular references has been added, and is enabled by default.
  • The mail() function now supports logging of sent email via the mail.log configuration directive. (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 or later 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 Constante predefinite.
Avertizare

Support for the ISAPI module has been dropped. Use the improved FastCGI SAPI module instead.

Nota: 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)
  • mcrypt_generic_end()
  • 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 information 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 libmysqlclient. mysqlnd will be used to build the mysql, mysqli and PDO_MySQL extensions if libmysqlclient isn't found on the system. It may also be used instead of libmysqlclient even when libmysqlclient 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, zend_extension_debug_ts 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.
  • open_basedir restrictions may now be tighted at runtime, and the directive is now PHP_INI_ALL.
  • 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.
  • Two new mail directives: mail.add_x_header and mail.log, have been added.

The following new ini directives have been added:

  • user_ini.filename and user_ini.cache_ttl have been added to control the use of user INI files.
  • exit_on_timeout has been added to force Apache 1.x children to exit if a PHP execution timeout occurs.
  • 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
Migrarea de la PHP 5.1.x la PHP 5.2.x
Migrating from PHP 5.2.x to PHP 5.3.x


Migrarea de la PHP 5.1.x la PHP 5.2.x

Cuprins

  • Ce s-a schimbat în PHP 5.2.x
  • Schimbari incompatibile în sens invers
  • Noile mesaje de eroare
  • Schimbarile PHP în sus?inerea func?iilor datetime
  • Parametri noi
  • Func?ii noi
  • Metode noi
  • Extensiile eliminate
  • Extensii noi
  • Clase noi
  • Constante globale noi
  • Constante de clase noi
  • Noile directive de configurare INI
  • Raportarea erorilor
  • Alte îmbunata?iri

Accesa?i de asemenea ghidurile de migrare pentru versiunile PHP 5.0.x, 5.1.x, 5.3.x, 5.4.x, 5.5.x ?i 5.6.x.

Other changes
Ce s-a schimbat în PHP 5.2.x
Anexe


Ce s-a schimbat în PHP 5.2.x

Majoritatea îmbunata?irilor din PHP 5.2.x nu au nici un impact asupra codului-sursa existent. Sunt însa unele mici incompatibilita?i ?i noi mesaje de eroare care trebuie luate în considerare, iar codul-sursa trebuie testat înainte de a schimba versiunile PHP în mediile de produc?ie.

Daca sistemul este schimbat de la PHP 5.0.x, este necesar de citit ?i sec?iunea manualului întitulata Note la reînnoirea pâna la PHP 5.1.x.

Similar, daca sistemul este schimbat de la PHP 4, trebuie citita ?i sec?iunea manualului întitulata Migrarea de la PHP 4 la PHP 5.

Migrarea de la PHP 5.1.x la PHP 5.2.x
Schimbari incompatibile în sens invers
Migrarea de la PHP 5.1.x la PHP 5.2.x


Schimbari incompatibile în sens invers

Cu toate ca codul-sursa existent în PHP 5 trebuie sa func?ioneze fara schimbari, ar trebui sa atrage?i aten?ia la urmatoarele schimbari incompatibile în sens invers:

  • getrusage() întoarce NULL când îi sunt transmise argumente incompatibile începând cu PHP 5.2.1.
  • ZipArchive::setCommentName() întoarce TRUE în caz de succes începând cu PHP 5.2.1.
  • ZipArchive::setCommentIndex() întoarce TRUE în caz de succes începând cu PHP 5.2.1.
  • SplFileObject::getFilename() întoarce denumirea fi?ierului, ?i nu calea/relativa/spre/fi?ier, începând cu PHP 5.2.1.
  • S-a modificat prioritatea variabilei de mediu PHPRC pe sistemele Win32. Variabila de mediu PHPRC acum are prioritate fa?a de calea stocata în registrul Windows.
  • CLI SAPI nu mai cauta fi?ierele php.ini sau php-cli.ini în directorul curent. În PHP 5.1.x a fost introdusa o facilitate nedocumentata care facea ca binarul CLI sa caute în Directorul de Lucru Curent (DLC) un fi?ier de configurare PHP, ducând poten?ial la un comportament imprevizibil atunci când era citit un fi?ier de configurare nea?teptat. Aceasta func?ionalitate a fost eliminata în versiunea 5.2.0, ?i PHP nu mai cauta în DLC fi?ierele php.ini sau php-cli.ini. Accesa?i de asemenea sec?iunea manualului referitoare la linia de comanda.
  • A fost adaugata o preîntâmpinare la efectuarea opera?iei modulus 0. În versiunile anterioare ale PHP, efectuarea opera?iei "integer % 0" nu emitea nici un mesaj de preîntâmpinare, întorcând, în loc, o valoare nea?teptata FALSE. Începând cu PHP 5.2.0 aceasta opera?ie va emite un E_WARNING, dupa cum e cazul ?i în orice alta situa?ie când se efectueaza împar?irea la zero.
    <?php
    print 10 % 0;
    /* Warning:  Division by zero in filename on line n */
    ?>
  • A fost modificat __toString() pentru a fi apelat oricând este aplicabil. Metoda magica __toString() acum va fi apelata în contextul unui string, adica oriunde un obiect este utilizat ca string. Situa?ia când se întoarce un string care con?ine identificatorul obiectului a fost abandonata în PHP 5.2.0. Aceasta devenise problematica deoarece identificatorul obiectului nu poate fi considerat unic. Aceasta schimbare va însemna ca aplica?ia dumneavoastra este defectuoasa daca v-a?i bazat pe identificatorul obiectului în calitate de valoare întoarsa. Acum încercarea de a utiliza aceasta valoare în calitate de string va rezulta în emiterea unei erori fatale interceptabile.
    <?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 */
    ?>
    Chiar ?i cu __toString() obiectele nu pot fi utilizate ca indici ai tabloului sau chei. S-ar putea sa adaugam ulterior sus?inerea încorporata a hash-urilor pentru aceasta, însa în PHP 5.2.x va trebui sau sa crea?i propria func?ie hash, sau sa utiliza?i noua func?ie SPL spl_object_hash(). Din metodele __toString() nu pot fi aruncate excep?ii.
    <?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) {}
    ?>
  • Au fost abandonate func?iile de clasa statice abstracte. Din cauza unei scapari, PHP 5.0.x ?i 5.1.x permiteau func?ii abstracte statice în clase. Începând cu PHP 5.2.x, numai interfe?ele le pot avea.
    <?php
    abstract class foo {
        abstract static function     bar();
            /* Strict Standards:  Static function foo::bar()
        should not be abstract in filename on line n */
    }
    ?>
  • Extensia Oracle necesita prezen?a a cel pu?in Oracle 10 pe Windows.
  • A fost adaugata sus?inerea RFC2397 (fluxurile data:). Introducerea schemei URL 'data' poate duce la o schimbare în comportament sub Windows. Daca lucra?i cu un sistem de fi?iere NTFS ?i utiliza?i meta-fluxurile în aplica?ia dumneavoastra, ?i daca se întâmpla sa utliza?i un fi?ier cu denumirea 'data:', accesat fara informa?ia despre cale - aceasta nu va mai func?iona. Pentru a corecta aceasta, utiliza?i protocolul 'file:' pentru a-l accesa. Accesa?i de asemenea » 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 */
    ?>
  • Regresul în ?abloanele glob() În versiunea 5.2.4 o corectare a unei probleme de securitate cauza un regres al ?abloanelor de forma "/foo/*/bar/*". Începând cu versiunea 5.2.5 în loc de a emite o preîntâmpinare, func?ia glob() va întoarce FALSE când restric?iile openbase_dir sunt încalcate.
Ce s-a schimbat în PHP 5.2.x
Noile mesaje de eroare
Migrarea de la PHP 5.1.x la PHP 5.2.x


Noile mesaje de eroare

Mai jos sunt enumerate noile mesaje de eroare, care nu au fost discutate în alte sec?iuni din acest document.

Example #1 În nucleul PHP

<?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 */
?>

Example #2 Cod-sursa obiect-orientat în nucleul PHP

<?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 */
?>

Example #3 În extensia bzip2

<?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 */
?>

Example #4 În extensia datetime

<?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 */
?>

Example #5 În extensia dBase

<?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 */
?>

Example #6 În extensia mcrypt

<?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 */
?>

Example #7 În extensia oci8

<?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 */
?>

Example #8 În extensia SPL

<?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 */
?>

Example #9 În extensia Semaphore (sysvmsg)

<?php
/* Warning:  maximum size of the message has to be
   greater then zero in filename on line n */
?>

Example #10 Un exemplu Zip 5.2.1+

<?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 */
?>

Schimbari incompatibile în sens invers
Schimbarile PHP în sus?inerea func?iilor datetime
Migrarea de la PHP 5.1.x la PHP 5.2.x


Schimbarile PHP în sus?inerea func?iilor datetime

Începând cu PHP 5.1.0, exista o extensie denumita date în nucleul PHP. Aceasta este noua implementare a sus?inerii în PHP a func?iilor datetime. Cu toate ca PHP va încerca sa ghiceasca setarile fusului orar ale sistemului, ar trebui sa stabili?i în mod manual fusul orar. Pute?i realiza acest lucru prin oricare dintre urmatoarele trei metode:

  • în fi?ierul php.ini utilizând directiva INI date.timezone
  • în sistemul de operare utilizând variabila de mediu TZ
  • din script utilizând func?ia date_default_timezone_set()

Toate fusele orare sus?inute sunt enumerate în manualul PHP.

Odata cu apari?ia PHP 5.2.x, au aparut reprezentari-obiect ale datei ?i fuselor orare, denumite DateTime ?i DateTimeZone respectiv. Metodele apeleaza func?iile procedurale de date existente.

Noile mesaje de eroare
Parametri noi
Migrarea de la PHP 5.1.x la PHP 5.2.x


Parametri noi

Unor func?ii li s-au dat parametri noi, op?ionali, în PHP 5.2.x:

Nucleul PHP:

  • htmlentities() - s-a adaugat double_encode în PHP 5.2.3.
  • htmlspecialchars() - s-a adaugat double_encode în PHP 5.2.3.
  • base64_decode() - s-a adaugat strict
  • setcookie() - s-a adaugat httponly
  • setrawcookie() - s-a adaugat httponly
  • session_set_cookie_params() - s-a adaugat httponly
  • memory_get_usage() - s-a adaugat real_usage
  • get_loaded_extensions() - s-a adaugat zend_extensions în PHP 5.2.4

curl:

  • curl_multi_info_read() - s-a adaugat msgs_in_queue

datetime

  • date() - s-a adaugat caracterul de formatare "u" (milisecunde) în PHP 5.2.2

imap:

  • imap_open() - s-a adaugat n_retries
  • imap_reopen() - s-a adaugat n_retries

mbstring:

  • mb_strrpos() - s-a adaugat offset
    Avertizare

    Parametrul offset a fost pus în pozi?ia unde se afla parametrul encoding. Compatibilitatea în sens invers a fost realizata permi?ând ca encoding sa fie specificat ca al treilea parametru. Utilizarea acestui mod de compatibilitate inversa nu e recomandat deoarece va fi eliminat într-o versiune ulterioara a PHP.

ming:

  • SWFMovie::streamMP3() - s-a adaugat skip în PHP 5.2.1

openssl:

  • openssl_verify() - s-a adaugat signature_algo

pgsql:

  • pg_escape_bytea() - s-a adaugat connection
  • pg_escape_string() - s-a adaugat connection

simplexml:

  • SimpleXMLElement::__construct() - s-a adaugat is_prefix
  • SimpleXMLElement::attributes() - s-a adaugat is_prefix
  • SimpleXMLElement::children() - s-a adaugat is_prefix
  • simplexml_load_file() - s-a adaugat is_prefix
  • simplexml_load_string() - s-a adaugat is_prefix

spl:

  • array iterator_to_array(Traversable it [, bool use_keys = true]) - s-a adaugat use_keys în PHP 5.2.1

xmlreader:

  • XMLReader::open() - s-au adaugat encoding ?i options
  • XMLReader::XML() - s-au adaugat encoding ?i options

XMLWriter:

  • xmlwriter_write_element() - parametrul content a devenit op?ional în PHP 5.2.3
  • xmlwriter_write_element_ns() - parametrul content a devenit op?ional în PHP 5.2.3
Schimbarile PHP în sus?inerea func?iilor datetime
Func?ii noi
Migrarea de la PHP 5.1.x la PHP 5.2.x


Func?ii noi

În PHP 5.2.x au fost introduse unele noi func?ii:

Nucleul PHP:

  • array_fill_keys() - Creeaza un tablou utilizând elementele primului parametru în calitate de chei, fiecare ini?ializata cu val
  • error_get_last() - Întoarce ultima eroare survenita ca tablou asociativ. Întoarce NULL daca înca nu a survenit nici o eroare
  • image_type_to_extension() - Întoarce extensia fi?ierului pentru tipul-imagine întors de getimagesize(), exif_read_data(), exif_thumbnail(), exif_imagetype()
  • memory_get_peak_usage() - Întoarce maximul de memorie alocat de PHP
  • sys_get_temp_dir() - Întoarce calea directorului utilizat pentru fi?iere temporare. (Adaugat în 5.2.1)
  • timezone_abbreviations_list() - Întoarce un tablou asociativ con?inând DST, deplasamentul ?i denumirea fusului orar
  • timezone_identifiers_list() - Întoarce un tablou numeric indexat cu toate identificatoarele fusurilor orare
  • timezone_name_from_abbr() - Întoarce denumirea fusului orar din abreviere
  • stream_socket_shutdown() - Cauzeaza deconectarea totala sau par?iala a unei conexiuni full-duplex realizata prin intermediul unui socket asociat cu un flux. Începând cu PHP 5.2.1.

Imagini:

  • imagegrabscreen() - Intercepteaza imaginea întregului ecran. Începând cu PHP 5.2.2.
  • imagegrabwindow() - Captureaza o fereastra. Începând cu PHP 5.2.2.

libXML:

  • libxml_disable_entity_loader() - Elimina posibilitatea de a încarca entita?i externe. Începând cu PHP 5.2.11.

mbstring:

  • mb_stripos() - Gase?te pozi?ia primei apari?ii a unui string în cadrul altuia, fara a lua în considera?ie caracterele minuscule/majuscule
  • mb_stristr() - Gase?te prima apari?ie a unui string în cadrul altuia, luând în considera?ie caracterele minuscule/majuscule
  • mb_strrchr() - Gase?te ultima apari?ie a unui caracter dintr-un string în cadrul altui string
  • mb_strrichr() - Gase?te ultima apari?ie a unui caracter dintr-un string în cadrul altui string, luând în considera?ie caracterele minuscule/majuscule
  • mb_strripos() - Gase?te ultima apari?ie a unui caracter dintr-un string în cadrul altui string, fara a lua în considera?ie caracterele minuscule/majuscule
  • mb_strstr() - Gase?te prima apari?ie a unui string în cadrul altuia

ming (Începând cu PHP 5.2.1):

  • void ming_setSWFCompression(int num) - Stabile?te compresia ie?irii
  • void swfmovie::namedanchor(string name) - Creaza o ancora
  • void swfmovie::protect([string password]) - Protejeaza

openssl:

  • openssl_csr_get_public_key() - Extrage cheia publica dintr-un CERT ?i o pregate?te pentru utilizare
  • openssl_csr_get_subject() - Întoarce subiectul unui CERT
  • openssl_pkey_get_details() - Întoarce un tablou cu detaliile cheii (bi?ii, pkey, tipul)

spl:

  • spl_object_hash() - Întoarce id-ul hash-ului pentru un obiect dat
  • int iterator_apply(Traversable it, mixed function [, mixed params]) - Apeleaza o func?ie pentru fiecare element într-un iterator

pcre:

  • preg_last_error() - Întoarce codul erorii a ultimei execu?ii regex

pgsql:

  • pg_field_table() - Întoarce denumirea tabelei careia îi apar?ine câmpul, sau oid-ul tabelei daca oid_only este TRUE

posix:

  • posix_initgroups() - Calculeaza lista de acces a grupului pentru utilizatorul specificat în denumire

gmp:

  • gmp_nextprime() - Calculeaza urmatorul numar prim

xmlwriter:

  • xmlwriter_full_end_element() - Finalizeaza elementul curent - întoarce FALSE la eroare
  • xmlwriter_write_raw() - Înscrie textul - întoarce FALSE la eroare
  • xmlwriter_start_dtd_entity() - Creaza o entitate DTD de start - întoarce FALSE la eroare
  • xmlwriter_end_dtd_entity() - Finalizeaza entitatea DTD curenta - întoarce FALSE la eroare
  • xmlwriter_write_dtd_entity() - Înscrie eticheta entita?ii DTD depline - întoarce FALSE la eroare
Parametri noi
Metode noi
Migrarea de la PHP 5.1.x la PHP 5.2.x


Metode noi

În 5.2.0 au fost introduse metode noi:

dom:

  • DOMDocument::registerNodeClass() - Înregistreaza clasa extinsa utilizata pentru a crea tipul de baza al nodului
  • DOMElement::setIDAttribute() - Declara atributul specificat dupa denumire pentru a fi de tip ID
  • DOMElement::setIDAttributeNode() - Declara atributul specificat dupa nod pentru a fi de tip ID
  • DOMElement::setIDAttributeNS() - Declara atributul specificat dupa numele local ?i spa?iul de nume URI pentru a fi de tip ID
  • DOMNode::C14N()([bool exclusive [, bool with_comments [, array xpath [, array ns_prefixes]]]]) - Efectueaza transformarea canonica a nodurilor într-un string
  • DOMNode::C14NFile()(string uri [, bool exclusive [, bool with_comments [, array xpath [, array ns_prefixes]]]]) - Efectueaza transformarea canonica a nodurilor într-un fi?ier
  • DOMNode::getNodePath()() - Ob?ine un xpath pentru un nod

soap:

  • SoapServer::setObject()(object obj) - Stabile?te obiectul care va gestiona interpelarile SOAP

spl:

  • int ArrayObject::asort()(void) - Sorteaza înregistrarile dupa valori
  • int ArrayObject::ksort()(void) - Sorteaza înregistrarile dupa cheie
  • int ArrayObject::natcasesort()(void) - Sorteaza înregistrarile dupa cheie utilizând algoritmul "ordinii naturale", ce nu diferen?iaza caracterele minuscule / majuscule.
  • int ArrayObject::natsort()(void) - Sorteaza înregistrarile dupa valori utilizând algoritmul "ordinii naturale".
  • int ArrayObject::uasort()(callback cmp_function) - Sorteaza înregistrarile dupa valori utilizând o func?ie definita de utilizator
  • int ArrayObject::uksort()(callback cmp_function) - Sorteaza înregistrarile dupa cheie utilizând o func?ie definita de utilizator
  • ArrayIterator AppendIterator::getArrayIterator()() - Ob?ine acces la ArrayIterator intern
  • int AppendIterator::getIteratorIndex()() - Ob?ine indicele iteratorului
  • bool CachingIterator::getCache()() - Întoarce cache-ul
  • int CachingIterator::getFlags()() - Întoarce fanioanele interne
  • bool CachingIterator::offsetExists()(mixed index) - Întoarce TRUE daca indicele cerut exista
  • string CachingIterator::offsetGet()(mixed index) - Întoarce cache-ul intern daca este utilizat
  • void CachingIterator::offsetSet()(mixed index, mixed newval) - Stabile?te indicele dat în cache
  • void CachingIterator::offsetUnset()(mixed index) - Elimina indicele dat din cache
  • void CachingIterator::setFlags()() - Stabile?te fanioanele interne
  • array("delimiter" =>, "enclosure" =>) SplFileObject::getCsvControl()(void) - Ob?ine caracterele de delimitare ?i încapsulare utilizate în fgetcsv()
  • void SplFileObject::setCsvControl()([string delimiter = ',' [, string enclosure = '"']]) - Stabile?te caracterele de delimitare ?i încapsulare utilizate în fgetcsv()

Tidy

  • tidyNode tidyNode::getParent() - Întoarce nodul-parinte al nodului curent (adaugat în PHP 5.2.2)

XMLReader

  • boolean XMLReader::setSchema() - Utilizeaza schema W3C XSD pentru a valida documentul în timp ce este procesat. Activarea este posibila numai înainte de primul XMLReader::read()

zip:

  • ZipArchive::addEmptyDir()() - Creeaza un director vid în arhiva
Func?ii noi
Extensiile eliminate
Migrarea de la PHP 5.1.x la PHP 5.2.x


Extensiile eliminate

Aceste extensii au fost transferate în PECL ?i nu mai fac parte din distributivul PHP. Versiunile-pachete PECL ale acestor extensii vor fi create conform cerin?elor utilizatorilor.

  • filePro
  • Hyperwave API
Metode noi
Extensii noi
Migrarea de la PHP 5.1.x la PHP 5.2.x


Extensii noi

Urmatoarele sunt extensii noi adaugate (implicit) începând cu PHP 5.2.0:

  • Filtru - valideaza ?i filtreaza datele ?i este proiectat pentru a fi utilizat cu date nesecurizate, cum ar fi cele introduse de utilizator. Aceasta extensie este activata implicit; modul implicit RAW nu ar vre-un impact asupra datelor introduse.
  • JSON - implementeaza formatul de schimb al datelor JavaScript Object Notation (JSON) — Notarea Obiectelor în JavaScript. Aceasta extensie este activata implicit.
  • Zip - va permite sa înscrie?i ?i sa citi?i în mod transparent arhive comprimate ZIP ?i fi?ierele din interiorul lor.
Extensiile eliminate
Clase noi
Migrarea de la PHP 5.1.x la PHP 5.2.x


Clase noi

Urmatoarele clase au fost introduse în PHP 5.2.0:

  • DateTime
  • DateTimeZone
  • RegexIterator - extinde FilterIterator; implementeaza Iterator, Traversable, OuterIterator Constante:
    • RegexIterator::ALL_MATCHES
    • RegexIterator::GET_MATCH
    • RegexIterator::MATCH
    • RegexIterator::REPLACE
    • RegexIterator::SPLIT
    • RegexIterator::USE_KEY
    Proprieta?i:
    • public replacement
    Metode:
    • RegexIterator::__construct(Iterator it, string regex [, int mode [, int flags [, int preg_flags]]]) - Creeaza un RegexIterator dintr-un alt iterator ?i o expresie regulara
    • bool RegexIterator::accept() - Potrive?te (string)current() conform expresiei regulare
    • bool RegexIterator::getFlags() - Întoarce fanioanele opera?ionale curente
    • bool RegexIterator::getMode() - Întoarce modul opera?ional curent
    • bool RegexIterator::getPregFlags() - Întoarce fanioanele PREG curente (daca se utilizeaza) sau NULL
    • bool RegexIterator::setFlags(int new_flags) - Stabile?te fanioanele opera?ionale
    • bool RegexIterator::setMode(int new_mode) - Stabile?te noul mod opera?ional
    • bool RegexIterator::setPregFlags(int new_flags) - Stabile?te fanioanele PREG
  • RecursiveRegexIterator Constante:
    • RecursiveRegexIterator::ALL_MATCHES
    • RecursiveRegexIterator::GET_MATCH
    • RecursiveRegexIterator::MATCH
    • RecursiveRegexIterator::REPLACE
    • RecursiveRegexIterator::SPLIT
    • RecursiveRegexIterator::USE_KEY
    Metode:
    • RecursiveRegexIterator::__construct(RecursiveIterator it, string regex [, int mode [, int flags [, int preg_flags]]]) - Creeaza un RecursiveRegexIterator dintr-un alt iterator recursiv ?i o expresie regulara
    • RecursiveRegexIterator RecursiveRegexIterator::getChildren() - Întoarce fiii iteratorului intern, ce se con?in într-un RecursiveRegexIterator
    • bool RecursiveRegexIterator::hasChildren() - Verifica daca elementul curent al iteratorului intern poseda fii
Extensii noi
Constante globale noi
Migrarea de la PHP 5.1.x la PHP 5.2.x


Constante globale noi

Nucleul PHP:

  • 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 Adaugata în PHP 5.2.1.
  • CURLOPT_TIMEOUT_MS Adaugata în PHP 5.2.3
  • CURLOPT_CONNECTTIMEOUT_MS Adaugata în PHP 5.2.3

GMP:

  • GMP_VERSION Adaugata în 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
Clase noi
Constante de clase noi
Migrarea de la PHP 5.1.x la PHP 5.2.x


Constante de clase noi

pdo:

  • PDO::ATTR_DEFAULT_FETCH_MODE
  • PDO::FETCH_PROPS_LATE
  • PDO::FETCH_KEY_PAIR Transleaza un set de rezultate în 2 coloane într-un tablou asociativ. (Adaugata în PHP 5.2.3)

spl:

  • CachingIterator::FULL_CACHE
  • CachingIterator::TOSTRING_USE_INNER
  • SplFileObject::READ_AHEAD
  • SplFileObject::READ_CSV
  • SplFileObject::SKIP_EMPTY
Constante globale noi
Noile directive de configurare INI
Migrarea de la PHP 5.1.x la PHP 5.2.x


Noile directive de configurare INI

Noi directive ale php.ini au fost introduse în PHP 5.2.0:

  • allow_url_include Aceasta op?iune utila face posibila diferen?ierea dintre opera?iunile standarde asupra fi?ierelor la distan?a ?i includerea fi?ierelor la distan?a. În timp ce prima este de obicei dezirabila, ultima poate fi un risc de securitate daca este utilizata naiv. Începând cu PHP 5.2.0 pute?i permite efectuarea opera?iunilor asupra fi?ierelor la distan?a, interzicând totodata includerea fi?ierelor la distan?a în script-urile locale. De fapt, aceasta este configura?ia implicita.
  • pcre.backtrack_limit Limita de backtracking a PCRE.
  • pcre.recursion_limit Limita de recursie a PCRE. Observa?i ca daca stabili?i aceasta valoare prea mare, pute?i sa consuma?i toata stiva disponibila a procesului ?i eventual sa suspenda?i PHP (din cauza atingerii limitei dimensiunii stivei, impusa de sistemul de operare).
  • session.cookie_httponly Marcheaza prajiturile ca fiind accesibile numai prin intermediul protocolului HTTP. Aceasta înseamna ca prajitura nu va fi accesibila prin intermediul limbajelor de scriptare, cum ar fi JavaScript. Aceasta op?iune poate efectiv ajuta la reducerea furtului de identitate prin atacuri XSS (cu toate ca aceasta nu este sus?inut de toate navigatoarele).

Directive noi în PHP 5.2.2:

  • max_input_nesting_level Limiteaza adâncimea încorporarii variabilelor de intrare, implicit este 64.
Constante de clase noi
Raportarea erorilor
Migrarea de la PHP 5.1.x la PHP 5.2.x


Raportarea erorilor

Unele din condi?iile E_ERROR existente au fost convertite în ceva ce poate fi interceptat cu ajutorul unui handler de erori definit de utilizator. Daca o E_RECOVERABLE_ERROR nu este interceptata, ea se va comporta la fel ca ?i E_ERROR în toate versiunile PHP. Erorile de acest tip sunt înscrise în jurnal ca Eroare fatala interceptabila.

Aceasta schimbare înseamna ca valoarea E_ALL a constantei error_reporting este acum 6143, în timp ce valoarea precedenta era 2047. Deoarece constantele PHP nu au nici o însemnatate în afara PHP, în unele cazuri este utilizata valoarea întreaga, de aceea ea va trebui ajustata. Deci, spre exemplu, stabilind modul error_reporting în fi?ierele httpd.conf sau .htaccess, valoarea trebuie schimbata corespunzator. Acela?i lucru este valabil atunci când valorile numerice sunt utilizate în locul constantelor în script-urile PHP.

Ca efect secundar a unei schimbari efectuate pentru a preveni dublarea mesajelor de eroare atunci când track_errors este On, acum este necesar de a întoarce FALSE din handler-ele de erori definite de utilizator pentru a popula $php_errormsg. Aceasta ofera un control granular asupra nivelelor mesajelor stocate.

Noile directive de configurare INI
Alte îmbunata?iri
Migrarea de la PHP 5.1.x la PHP 5.2.x


Alte îmbunata?iri

  • Managerul îmbunata?it al memoriei ?i limita implicita marita a memoriei. Noul manager al memoriei aloca mai pu?ina memorie ?i lucreaza mai rapid decât încarnarea precedenta. El aloca memorie din sistem în blocuri largi ?i apoi gestioneaza gramada (heap) independent. Valoarea memory_limit din php.ini este verificata nu la fiecare apel emalloc() (ca înainte), dar pentru blocurile de facto cerute de la sistem. Aceasta înseamna ca memory_limit este mult mai exact decât era, deoarece vechiul manager al memoriei nu calcula tot necesarul de memorie utilizat de biblioteca malloc. Datorita acestei precizii ob?inute utilizarea memoriei poate parea sa se fi marit, cu toate ca, de fapt, nu este a?a. Pentru a acomoda aceasta marire aparenta, valoarea implicita a memory_limit de asemenea a fost marita - de la 8 la 16 megaocte?i.
  • S-a adaugat sus?inerea constructorilor în interfe?e pentru a for?a verificarea semnaturilor constructorilor în implementari. Începând cu PHP 5.2.0, interfe?ele pot avea constructori. Însa daca alege?i sa declara?i un constructor într-o interfa?a, fiecare clasa ce va implementa aceasta interfa?a TREBUIE sa includa un constructor cu o semnatura identica cu acea a constructorului din interfa?a de baza. Prin 'semnatura' se în?eleg defini?iile tipurilor parametrilor ?i a valorii întoarse, inclusiv orice fel de indicatori explici?i ai tipurilor ?i faptul daca datele sunt transmise prin referin?a, sau prin valoare.
Raportarea erorilor
Migrarea de la PHP 5.0.x la PHP 5.1.x
Migrarea de la PHP 5.1.x la PHP 5.2.x


Migrarea de la PHP 5.0.x la PHP 5.1.x

Cuprins

  • Principalele facilita?i ale PHP 5.1.x
  • Modificari în manipularea referin?elor
  • Citirea []
  • Valorile întregi în parametrii func?iilor
  • Schimbari în clase ?i obiecte
  • Extensiile
  • Sus?inerea Datei/orei
  • Modificari în sus?inerea bazelor de date
  • Verificarea E_STRICT

Accesa?i de asemenea ghidurile de migrare pentru versiunile PHP 5.0.x, 5.2.x, 5.3.x, 5.4.x, 5.5.x ?i 5.6.x.

Alte îmbunata?iri
Principalele facilita?i ale PHP 5.1.x
Anexe


Principalele facilita?i ale PHP 5.1.x

Unele din principalele facilita?i ale PHP 5.1.x includ:

  • O rescriere completa a codului de prelucrare a datelor, cu o sus?inere îmbunata?ita a zonelor orare.

  • Îmbunata?iri semnificative ale performan?ei în compara?ie cu PHP 5.0.X.

  • Extensia PDO acum este activata implicit.

  • Peste 30 func?ii noi în diferite extensii ?i func?ionalita?i încorporate.

  • Peste 400 diverse erori corectate.

Migrarea de la PHP 5.0.x la PHP 5.1.x
Modificari în manipularea referin?elor
Migrarea de la PHP 5.0.x la PHP 5.1.x


Modificari în manipularea referin?elor

  • Aspecte generale

  • Codul-sursa care lucra în PHP 4.3.x, dar acum e?ueaza

  • Codul-sursa care lucra în PHP 4.3.x, dar acum arunca o eroare

  • Codul-sursa care e?ua în PHP 4.3.x, dar acum lucreaza

  • Codul-sursa care ar fi trebuit sa lucreze în PHP 5.0.x

  • Preîntâmpinari care au aparut ?i au disparut

Aspecte generale

Din punctul de vedere al programatorului script-urilor PHP, schimbarea care cel mai probabil va afecta codul-sursa vechi este modul în care sunt manipulate referin?ele în toate versiunile PHP ce au urmat dupa PHP 4.4.0.

Pâna la, ?i inclusiv în PHP 4.3 era posibil de a transmite, atribui sau întoarce variabile prin referin?a, care ar fi trebuit în mod real sa fie întoarse prin valoare, cum ar fi o constanta, o valoare temporara (de ex. rezultatul unei expresii) sau rezultatul unei func?ii care însa?i a fost întoarsa prin valoare, ca în acest exemplu:

<?php
$foo = "123";

function return_value() {
    global $foo;
    return $foo;
}

$bar = &return_value();
?>

Cu toate ca acest cod-sursa de obicei lucreaza conform a?teptarilor în PHP 4.3, în caz general rezultatul este nedefinit. Motorul Zend nu poate func?iona corect cu aceste valori în calitate de referin?e. Aceasta eroare putea, ?i într-adevar a dus la diverse probleme de alterare a con?inutului memoriei dificile de reprodus, în special acolo unde baza de cod-sursa era foarte mare.

În PHP 4.4.0, PHP 5.0.4 ?i toate versiunile ulterioare ale PHP Motorul a fost corectat pentru a '?ti' când opera?ia de referin?a este utilizata asupra unei valori care nu ar trebui sa fie referita. Acum în aceste cazuri este utilizata valoarea propriu-zisa ?i este emisa o preîntâmpinare. Preîntâmpinarea ia forma unui E_NOTICE în PHP 4.4.0 ?i ulterior, ?i E_STRICT în PHP 5.0.4 ?i ulterior.

Codul-sursa care pote?ial putea sa produca alterarea memoriei acum nu mai poate face aceasta. Însa unele coduri-sursa vechi pot ca rezultat sa func?ioneze în mod diferit.

Codul-sursa care lucra în PHP 4.3, dar acum e?ueaza

<?php
function func(&$arraykey) {
    return $arraykey; // func?ia întoarce rezultatul prin valoare!
}

$array = array('a', 'b', 'c');
foreach (array_keys($array) as $key) {
    $y = &func($array[$key]);
    $z[] =& $y;
}

var_dump($z);
?>
<

Lansând în execu?ie script-ul de mai sus în orice versiune a PHP mai înainte de corectarea referin?elor va produce urmatoarea ie?ire:

array(3) {
  [0]=>
  &string(1) "a"
  [1]=>
  &string(1) "b"
  [2]=>
  &string(1) "c"
}

Dupa corectarea referin?elor acela?i cod-sursa va produce urmatoarele:

array(3) {
  [0]=>
  &string(1) "c"
  [1]=>
  &string(1) "c"
  [2]=>
  &string(1) "c"
}

Aceasta se întâmpla din cauza ca, dupa corectare, func() atribuie prin valoare. Valoarea variabilei $y este re-atribuita ?i legatura prin referin?a este pastrata prin $z. Înainte de corectare valoarea era atribuita prin referin?a, ce ducea la faptul ca $y era realipit la fiecare atribuire. Încercarea de a alipi ceva prin referin?a la o valoare temporara cauza alterarea memoriei.

Un astfel de cod-sursa poate fi facut sa func?ioneze identic în ambele versiuni PHP: înainte de corectare ?i dupa. Semnatura func() poate fi alterata ca sa întoarca valoarea prin referin?a, sau atribuirea prin referin?a poate fi eliminata din rezultatul func().

<?php
function func() {
    return 'function return';
}

$x = 'original value';
$y =& $x;
$y = &func();
echo $x;
?>

În PHP 4.3 $x ar fi fost 'valoarea originara', în timp ce dupa corectari aceasta va fi 'ceea ce întoarce func?ia' - aminti?i-va ca atunci când func?ia nu întoarce valoarea prin referin?a, atribuirea prin referin?a este convertita într-o atribuire obi?nuita. Iara?i, aceasta poate fi adus la un numitor comun prin for?area func() sa întoarca valoarea prin referin?a, sau prin eliminarea atribuirii prin referin?a.

Codul-sursa care lucra în PHP 4.3.x, dar acum arunca o eroare

<?php
class Foo {

    function getThis() {
        return $this;
    }

    function destroyThis() {
        $baz =& $this->getThis();
    }
}

$bar = new Foo();
$bar->destroyThis();
var_dump($bar);
?>

În PHP 5.0.3, $bar evalua în NULL în loc sa întoarca un obiect. Aceasta s-a întâmplat din cauza ca getThis() întoarce prin valoare, dar aici valoarea e atribuita prin referin?a. Cu toate ca acum script-ul func?ioneaza conform a?teptarilor, acesta este de fapt un cod invalid, care va arunca un E_NOTICE sub PHP 4.4, sau un E_STRICT sub PHP 5.0.4 ?i ulterior.

Codul-sursa care e?ua în PHP 4.3.x, dar acum lucreaza

<?php
function &f() {
    $x = "foo";
    var_dump($x);
    print "$x\n";
    return($a);
}

for ($i = 0; $i < 3; $i++) {
    $h = &f();
}
?>

În PHP 4.3 al treilea apel la var_dump() produce NULL, din cauza alterarii memoriei cauzate de întoarcerea unei valori neini?ializate prin referin?a. Acest cod-sursa este valid în PHP 5.0.4 ?i ulterior, dar arunca erori în versiunile anterioare ale PHP.

<?php
$arr = array('a1' => array('alfa' => 'ok'));
$arr =& $arr['a1'];
echo '-'.$arr['alfa']."-\n";
?>

Pâna la PHP 5.0.5, nu era posibil de a atribui valoarea unui element al tabloului prin referin?a, în acest mod. Acum este posibil.

Codul-sursa care ar fi trebuit sa lucreze în PHP 5.0.x

Exista vre-o doua erori raportate în PHP 5.0 înainte de corectarea referin?elor, care acum 'lucreaza'. Însa în ambele cazuri erorile sunt aruncate de PHP 5.1.x, deoarece în primul rând codul-sursa era invalid. Întoarcerea valorilor prin referin?a utilizând self:: acum lucreaza la general, dar arunca o preîntâmpinare E_STRICT, ?i cu toate ca rezultatele variaza de la caz la caz la atribuirea prin referin?a la un obiect supraîncarcat, oricum ve?i vedea un E_ERROR atunci când încerca?i aceasta, chiar ?i acolo unde însa?i atribuirea pare sa func?ioneze.

Preîntâmpinari care au aparut ?i au disparut

Apeluri incluse unul în altul catre func?ii care întorc valoarea prin referin?a sunt exemple de cod-sursa valid în ambele PHP 4.3.x ?i PHP 5.1.x, dar aruncau erori nejustificate E_NOTICE sau E_STRICT în versiunile intermediare ale PHP.

<?php
function & foo() {
    $var = 'ok';
    return $var;
}

function & bar() {
    return foo();
}

$a =& bar();
echo "$a\n";
?>
Principalele facilita?i ale PHP 5.1.x
Citirea []
Migrarea de la PHP 5.0.x la PHP 5.1.x


Citirea []

<?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();
?>

Aceasta întotdeauna ar fi trebuit sa arunce o eroare fatala E_ERROR, din cauza ca [] nu pot fi utilizate pentru citire în PHP. Acesta este cod-sursa invalid în PHP 4.4.2 ?i PHP 5.0.5 ?i ulterior.

Modificari în manipularea referin?elor
Valorile întregi în parametrii func?iilor
Migrarea de la PHP 5.0.x la PHP 5.1.x


Valorile întregi în parametrii func?iilor

Odata cu apari?ia PHP 5.0.x a fost introdus un nou API de prelucrare a parametrilor, care este utilizat de un mare numar de func?ii PHP. În toate versiunile PHP între 5.0.x ?i 5.1.x, manipularea valorilor întregi era foarte stricta ?i erau respinse toate valorile numerice formate incorect atunci când o func?ie PHP e?tepta un întreg. Aceste verificari acum sunt mai legere pentru a sus?ine string-uri numerice formate nu chiar bine, cum ar fi " 123" ?i "123 " ?i acestea nu vor mai e?ua, cum era cazul în PHP 5.0.x. Însa pentru a promova siguran?a în cod ?i validarea intrarilor, func?iile PHP acum emit un E_NOTICE atunci când astfel de string-uri sunt transmise în calitate de întregi.

Citirea []
Schimbari în clase ?i obiecte
Migrarea de la PHP 5.0.x la PHP 5.1.x


Schimbari în clase ?i obiecte

  • instanceof, is_a(), is_subclass_of() ?i catch

  • Metodele private abstracte

  • Modificatorii de acces în interfe?e

  • Schimbari în regulile de mo?tenire

  • Constantele de clasa

instanceof, is_a(), is_subclass_of() ?i catch

În PHP 5.0, is_a() a devenit învechit ?i a fost înlocuit cu operatorul instanceof. Au existat unele probleme cu implementarea ini?iala a instanceof, care se baza pe __autoload() pentru a cauta clasele ce lipsesc. Daca clasa nu era prezenta, instanceof arunca un E_ERROR fatal din cauza e?ecului __autoload() de a descoperi acea clasa. Acela?i comportament îl avea ?i operatorul catch ?i func?ia is_subclass_of(), ambele din acela?i motiv.

Nici una din aceste func?ii sau operatori nu apeleaza __autoload() în PHP 5.1.x, iar utilizarea class_exists() în codul-sursa scris pentru PHP 5.0.x, cu toate ca nu este problematica în nici un fel, nu mai este necesara.

Metodele private abstracte

Metodele private abstracte au fost sus?inute între PHP 5.0.0 ?i PHP 5.0.4, însa apoi au fost interzise în baza faptului ca comportamentele private ?i abstract se excludeau reciproc.

Modificatorii de acces în interfe?e

În PHP 5.0, declara?iile func?iilor în interfe?e erau tratate exact la fel ca ?i declara?iile func?iilor în clase. Aceasta nu mai era adevarat începând cu octombrie 2004, când numai modificatorul de acces public a fost permis în declara?iile func?iilor din interfe?e. Începând cu aprilie 2005 - înainte de apari?ia lansarii PHP 5.0b1 - modificatorul static de asemenea a fost permis. Oricum, modificatorii protected ?i private acum vor arunca un E_ERROR, la fel ca ?i abstract. Observa?i însa ca aceasta schimbare nu ar trebui sa afecteze codul dumneavoastra sursa existent, deoarece nici unul din ace?ti modificatori nu are sens în contextul interfe?elor.

Schimbari în regulile de mo?tenire

În PHP 5.0 era posibil de a avea o declara?ie a func?iei într-o clasa derivata, care nu era corespunzatoare cu declara?ia aceleia?i func?ii în clasa de baza, de ex.

Acest cod-sursa va cauza o eroare E_STRICT emisa în 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;
    }
}
?>

Constantele de clasa

În PHP 5.0.x urmatorul cod-sursa era valid:

În PHP 5.1.x redefinirea unei constante de clasa va arunca o eroare fatala E_ERROR.

<?php
class test {
    const foobar = 'foo';
    const foobar = 'bar';
}

?>
Valorile întregi în parametrii func?iilor
Extensiile
Migrarea de la PHP 5.0.x la PHP 5.1.x


Extensiile

  • Extensiile care au disparut din nucleul PHP

  • Constantele de clasa în extensiile noi din PHP 5.1.x

Extensiile care au disparut din nucleul PHP

Probabil primul lucru pe care îl ve?i observa când ve?i descarca PHP 5.1.x este ca câteva extensii mai vechi au disparut. Acele extensii care deocamdata sunt men?inute activ sunt disponibile în PHP Extension Community Library (PECL) — Biblioteca Comunita?ii de Extensii PHP, la adresa » http://pecl.php.net/.

Extensiile eliminate
Extensia | Alternativa/Starea
ext/cpdf | pecl/pdflib
ext/dbx | pecl/dbx
ext/dio | pecl/dio
ext/fam | Nu este men?inuta activ
ext/ingres_ii | pecl/ingres
ext/ircg | Nu este men?inuta activ
ext/mcve | pecl/mcve
ext/mnogosearch | Nu este men?inuta activ
ext/oracle | ext/oci8 or ext/pdo_oci
ext/ovrimos | Nu este men?inuta activ
ext/pfpro | Nu este men?inuta activ
ext/w32api | » pecl/ffi
ext/yp | Nu este men?inuta activ
ext/activescript | » pecl/activescript

Modulele din PECL care nu sunt men?inute activ (de ex. nu au fost sus?inute de un timp, nu au un men?inator activ ce lucreaza în prezent asupra lor ?i nu au careva lansari de pachete PECL) sunt înca disponibile în SVN la » http://svn.php.net/viewvc/pecl. Însa modulele PHP nelansate sunt dupa natura lor nesus?inute ?i pute?i e?ua la încercarea de a le instala sau utiliza.

Constantele de clasa în extensiile noi ale PHP 5.1.x

Zend Engine 2.1 API le permite programatorilor de extensii sa declare constante de clasa în extensii obiect-orientate. Extensiile noi scrise pentru PHP 5.1.x, inclusiv SPL, PDO, XMLReader ?i date, î?i au constantele în formatul PDO::CLASS_CONSTANT ?i nu în formatul C PDO_CLASS_CONSTANT pentru a minimiza poluarea spa?iului global de nume în PHP.

Schimbari în clase ?i obiecte
Sus?inerea Datei/orei
Migrarea de la PHP 5.0.x la PHP 5.1.x


Sus?inerea Datei/orei

Sus?inerea Datei/orei a fost rescrisa complet în PHP 5.1.x, ?i mai mult nu utilizeaza setarile sistemului pentru a '?ti' zona orara în care se opereaza. Aceasta va fi aflata dupa urmatoarele regunli, în urmatoarea ordine:

  • Zona orara stabilita cu func?ia date_default_timezone_set() (daca a fost stabilita)

  • Variabila de mediu TZ (daca nu este vida)

  • Ghicirea "magica" (daca sistemul de operare o sus?ine)

  • Daca toate op?iunile precedente e?ueaza, se stabile?te UTC

Pentru a asigura acurate?ea (?i a evita o avertizare E_STRICT), va trebui sa defini?i zona dumneavoastra orara în php.ini utilizând urmatorul format:

date.timezone = Europe/London

Zonele orare sus?inute sunt enumerate, în acest format, în anexa cu zonele orare.

De asemenea observa?i ca strtotime() acum întoarce FALSE la e?ec, în loc de -1.

Extensiile
Modificari în sus?inerea bazelor de date
Migrarea de la PHP 5.0.x la PHP 5.1.x


Modificari în sus?inerea bazelor de date

  • Prezentarea generala a PDO

  • Modificari în sus?inerea MySQL

  • Modificari în sus?inerea SQLite

Prezentarea generala a PDO

PHP Data Objects (PDO) — Obiectele de Date PHP au fost introduse ca extensii PECL în PHP 5.0 ?i au devenit parte componenta a distributivului PHP în versiunea PHP 5.1.x. Extensia PDO furnizeaza o interfa?a consistenta pentru acces la baze de date ?i este utilizata împreuna cu driver-e specifice PDO pentru fiecare baza de date. Fiecare driver de asemenea poate avea func?iile sale specifice pentru baza de date, dar func?ionalitatea de baza de acces la date, cum ar fi efectuarea interpelarilor ?i primirea datelor, este asigurata de func?iile PDO utilizând driver-ul indicat în PDO::__construct().

Observa?i ca extensia PDO ?i driver-ele sale se inten?ioneaza a fi asamblate ca extensii partajate. Aceasta va va permite sa reînnoi?i în mod clar ?i simplu driver-ele din PECL, fara a va for?a sa reasambla?i întregul PHP.

La momentul lansarii PHP 5.1.x, PDO este mai mult decât gata pentru testari extensive ?i poate fi adoptat în majoritatea situa?iilor. Oricum însa este important de a în?elege ca PDO ?i driver-ele sale sunt relativ tinere ?i în ele pot sa lipseasca anumite facilita?i specifice anumitor baze de date; evalua?i atent PDO înainte de a-l utiliza în proiecte noi.

Codul-sursa vechi la general se va baza pe extensiile de baze de date existente, care deocamdata sunt înca men?inute.

Modificari în sus?inerea MySQL

În PHP 4, sus?inerea MySQL 3 era încorporata. Odata cu lansarea PHP 5.0 au aparut doua extensii MySQL numite 'mysql' ?i 'mysqli', care au fost proiectate sa sus?ina MySQL < 4.1 ?i MySQL 4.1 ?i ulterior respectiv. Odata cu introducerea PDO, care ofera o interfa?a foarte rapida catre toate API-urile de baze de date sus?inute de PHP, driver-ul PDO_MYSQL poate sus?ine orice versiune curenta (MySQL 3, 4 or 5) în codul-sursa PHP scris pentru PDO, în dependen?a de versiunea bibliotecii MySQL utilizata în timpul compilarii. Extensiile vechi MySQL ramân prezente din motivul compatibilita?ii inverse, dar nu sunt activate implicit.

Modificari în sus?inerea SQLite

În PHP 5.0.x sus?inerea SQLite 2 era asigurata de extensia sqlite incorporata, care de asemenea era disponibila ca extensie PECL în PHP 4.3 ?i PHP 4.4. Odata cu introducerea PDO, extensia sqlite ac?ioneaza ?i ca driver 'sqlite2' pentru PDO; datorita acestui fapt extensia sqlite în PHP 5.1.x are o dependen?a fa?a de extensia PDO.

PHP 5.1.x este furnizat cu câteva interfe?e alternative pentru sqlite:

Extensia sqlite ofera un API procedural/obiect-orientat "clasic", pe care posibil l-a?i utilizat în versiunile anterioare ale PHP. Ea de asemenea ofera driver-ul PDO 'sqlite2', care va permite sa accesa?i baze de date vechi SQLite 2 utilizând API al PDO.

PDO_SQLITE ofera driver-ul 'sqlite' de versiunea 3. SQLite de versiunea 3 este net superior SQLite de versiunea 2, însa formatele fi?ierelor acestor doua versiuni nu sunt compatibile.

Daca proiectul dumneavoastra bazat pe PHP este de acum scris ?i func?ioneaza cu versiunile anterioare ale PHP atunci pute?i sa utiliza?i mai departe ext/sqlite fara probleme, dar va trebui sa activa?i în mod explicit ambele extensii PDO ?i sqlite. Noile proiecte ar trebui sa utilizeze drive-ele PDO ?i 'sqlite' (versiunea 3), deoarece acesta e mai rapid decât SQLite 2, poseda o concuren?a de blocare îmbunata?ita ?i sus?ine nativ atât declara?ii pregatite anterior cât ?i coloane binare.

Trebuie sa activa?i PDO pentru a utiliza extensia SQLite. Daca dori?i sa asambla?i extensia PDO în calitate de extensie partajata, atunci ?i extensia SQLite trebuie asamblata ca extensie partajata. Aceasta ramâne în vigoare ?i pentru orice alta extensie care ofera un driver PDO.

Sus?inerea Datei/orei
Verificarea E_STRICT
Migrarea de la PHP 5.0.x la PHP 5.1.x


Verificarea E_STRICT

Daca ave?i de verificat un singur script, pute?i intercepta erorile E_STRICT utilizând facilitatea lint din linia de comanda a PHP:

php -d error_reporting=4095 -l script_to_check.php

Pentru proiecte mai mari, script-ul shell ce urmeaza va executa aceea?i sarcina:

#!/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
Modificari în sus?inerea bazelor de date
Migrarea de la PHP 4 la PHP 5.0.x
Migrarea de la PHP 5.0.x la PHP 5.1.x


Migrarea de la PHP 4 la PHP 5.0.x

Cuprins

  • Ce s-a schimbat în PHP 5.0.x
  • Schimbari incompatibile în sens invers
  • CLI ?i CGI
  • Migrarea fi?ierelor de configurare
  • Func?ii noi
  • Directive noi
  • Bazele de date
  • Noul Model de Obiecte
  • Raportarea erorilor

Accesa?i de asemenea ghidurile de migrare pentru versiunile PHP 5.1.x, 5.2.x, 5.3.x, 5.4.x, 5.5.x ?i 5.6.x.

Verificarea E_STRICT
Ce s-a schimbat în PHP 5.0.x
Anexe


Ce s-a schimbat în PHP 5.0.x

PHP 5 ?i motorul integrat Zend Engine 2 au îmbunata?it considerabil performan?a ?i capacita?ile PHP, dar o mare aten?ie s-a acordat faptului de a deteriora cât mai pu?in posibil codul-sursa existent. Deci migrarea codului dumneavoastra de la PHP 4 la 5 ar trebui sa fie foarte u?oara. O buna parte din codul-sursa existent în PHP 4 ar trebui sa fie gata de a rula fara schimbari, dar totu?i ar trebui sa ?ti?i despre pu?inele diferen?e ?i sa ave?i grija sa testa?i codul dumneavoastra sursa înainte de a schimba versiunile în mediile de producere.

Migrarea de la PHP 4 la PHP 5.0.x
Schimbari incompatibile în sens invers
Migrarea de la PHP 4 la PHP 5.0.x


Schimbari incompatibile în sens invers

Cu toate ca majoritatea codului-sursa existent în PHP 4 ar trebui sa func?ioneze fara schimbari, totu?i ar trebui sa atrage?i aten?ia la urmatoarele schimbari incompatibile în sens invers:

  • Sunt unele noi cuvinte-cheie rezervate.
  • strrpos() ?i strripos() acum utilizeaza întregul string în calitate de 'ac'.
  • Utilizarea nelegala a deplasamentelor în string-uri cauzeaza E_ERROR în loc de E_WARNING. Un exemplu de utilizare nelegala ar fi: $str = 'abc'; unset($str[0]);.
  • array_merge() a fost schimbata pentru ca sa accepte numai tablouri. Daca îi este transmisa o variabila care nu este tablou, un E_WARNING va fi aruncat pentru fiecare astfel de parametru. Fi?i atent, deoarece codul dumneavoastra poate sa înceapa sa emita E_WARNING din senin.
  • Variabila de server PATH_TRANSLATED nu mai este stabilita implicit sub Apache2 SAPI în contrast cu situa?ia în PHP 4, unde ea este stabilita la aceea?i valoare ca ?i variabila de server SCRIPT_FILENAME, atunci când nu este populata de Apache. Aceasta schimbare a fost facuta pentru a ne conforma cu » specifica?ia CGI/1.1. Va rugam sa va referi?i la » bug #23610 pentru informa?ii suplimentare ?i vede?i de asemenea descrierea $_SERVER['PATH_TRANSLATED'] în manual. Aceasta problema de asemenea afecteaza versiunile PHP >= 4.3.2.
  • Constanta T_ML_COMMENT nu mai este definita de catre extensia Tokenizer. Daca error_reporting este stabilita la E_ALL, PHP va genera o notificare. Cu toate ca T_ML_COMMENT niciodata nu a fost utilizata, ea a fost definita în PHP 4. În ambele PHP 4 ?i PHP 5 // ?i /* */ sunt solu?ionate ca constante T_COMMENT. Însa comentariile în stil PHPDoc /** */, care începând cu PHP 5 sunt în?elese de PHP, sunt recunoscute ca T_DOC_COMMENT.
  • $_SERVER ar trebui sa fie populata cu argc ?i argv daca variables_order include "S". Daca a?i configurat sistemul dumneavoastra în mod specific sa nu creeze $_SERVER, atunci desigur ea nu va fi. Schimbarea a fost de a face argc ?i argv disponibile în versiunea CLI indiferent de setarea variables_order. Deci versiunea CLI acum întotdeauna va popula variabilele globale $argc ?i $argv.
  • Un obiect fara proprieta?i nu mai este considerat "vid".
  • În unele cazuri clasele trebuiesc declarate înainte de a fi utilizate. Aceasta se întâmpla numai daca unele facilita?i noi ale PHP 5 (cum ar fi interfe?ele) sunt utilizate. În caz contrar, comportamentul este pe vechi.
  • get_class(), get_parent_class() ?i get_class_methods() acum întorc numele claselor/metodelor a?a cum ele au fost declarate (respectându-se literele majuscule/minuscule), ceea ce poate duce la probleme cu script-urile mai vechi care se bazeaza pe comportamentul vechi (numele claselor/metodelor întotdeauna erau întoarse cu litere minuscule). O solu?ie posibila este de a cauta aceste func?ii în toate script-urile ?i de a le aplica strtolower(). Aceasta diferen?iere a literelor majuscule/minuscule de asemenea se aplica la constantele predefinite magice __CLASS__, __METHOD__ ?i __FUNCTION__. Valorile sunt întoarse exact cum sunt declarate (respectându-se literele majuscule/minuscule).
  • ip2long() acum întoarce FALSE când o adresa IP nevalida îi este transmisa ca argument ?i nu -1 ca înainte.
  • Daca exista func?ii definite într-un fi?ier inclus, ele pot fi utilizate în fi?ierul de baza indiferent daca se afla înainte de return sau dupa. Daca fi?ierul este inclus de doua ori, PHP 5 va emite o eroare fatala deoarece func?iile au fost declarate deja, în timp ce PHP 4 nu se plânge de acest fapt. Este recomandat de a utiliza include_once în loc de a verifica daca fi?ierul a fost inclus deja ?i de a ie?i în acest caz din fi?ierul inclus.
  • include_once ?i require_once întâi normalizeaza calea fi?ierului inclus în Windows astfel încât includerea A.php ?i a.php va include fi?ierul numai o singura data.
  • Transmiterea unui masiv prin valoare unei func?ii nu mai reseteaza indicatorul intern al tabloului pentru accesele la tablou prin intermediul acestei func?ii. Cu alte cuvinte, în PHP 4 când transmitea?i un tablou unei func?ii, indicatorul intern al tabloului era resetat, în timp ce în PHP 5, când transmite?i un tablou unei func?ii, indicatorul tabloului în interiorul func?iei rîmâne acolo unde era la momentul când tabloul a fost transmis func?iei.

Example #1 strrpos() ?i strripos() acum utilizeaza întregul string în calitate de 'ac'

<?php
var_dump(strrpos('ABCDEF','DEF')); //int(3)

var_dump(strrpos('ABCDEF','DAF')); //bool(false)
?>

Example #2 Un obiect fara proprieta?i nu mai este considerat "vid"

<?php
class test { }
$t = new test();

var_dump(empty($t)); // echo bool(false)

if ($t) {
    // Va fi executat
}
?>

Example #3 În unele cazuri clasele trebuie declarate înainte de a fi utilizate

<?php

// func?ioneaza fara erori:
$a = new a();
class a {
}

// arunca o eroare:
$a = new b();

interface c{
}
class b implements c {
}

?>

Ce s-a schimbat în PHP 5.0.x
CLI ?i CGI
Migrarea de la PHP 4 la PHP 5.0.x


CLI ?i CGI

În PHP 5 au survenit unele modificari ale denumirilor fi?ierelor CLI ?i CGI. În PHP 5 versiunea CGI a fost redenumita în php-cgi.exe (anterior php.exe) ?i versiunea CLI acum se afla în directorul principal (anterior cli/php.exe).

În PHP 5 a fost introdus un mod nou: php-win.exe. Acesta este echivalent cu versiunea CLI, cu excep?ia ca php-win nu afi?eaza nimic ?i astfel nu ofera o consola (pe ecran nu apare "cutia DOS"). Acest comportament este similar cu cel al php-gtk.

În PHP 5, versiunea CLI întotdeauna va popula variabilele globale $argv ?i $argc indiferent de careva setari ale directivelor php.ini. Chiar având register_argc_argv stabilit off nu va avea efect în CLI.

Accesa?i de asemenea referin?a liniei de comanda.

Schimbari incompatibile în sens invers
Migrarea fi?ierelor de configurare
Migrarea de la PHP 4 la PHP 5.0.x


Migrarea fi?ierelor de configurare

Deoarece modulele ISAPI ?i-au schimbat denumirile din php4xxx în php5xxx, trebuie sa face?i anumite schimbari ?i în fi?ierele de configurare. Au survenit schimbari ?i în denumirile fi?ierelor CLI ?i CGI. Va rugam sa va referi?i la sec?iunea coresponden?elor pentru informa?ii suplimentare.

Migrarea configura?iei Apache este foarte simpla. Vede?i în exemplul de mai jos ce schimbare trebuie sa face?i:

Example #1 Migrarea fi?ierelor de configurare Apache pentru PHP 5

# change this line:
LoadModule php4_module /php/sapi/php4apache2.dll

# with this one:
LoadModule php5_module /php/php5apache2.dll

Daca serverul dumneavoastra web ruleaza PHP în mod CGI, ar trebui sa ?ine?i cont de aceea ca versiunea CGI ?i-a schimbat denumirea din php.exe în php-cgi.exe. În Apache, ar trebui sa face?i ceva de felul urmator:

Example #2 Migrarea fi?ierelor de configurare Apache pentru PHP 5, modul CGI

# change this line:
Action application/x-httpd-php "/php/php.exe"

# with this one:
Action application/x-httpd-php "/php/php-cgi.exe"

În alte servere web trebuie sa schimba?i denumirea fi?ierului modulului CGI sau ISAPI.

CLI ?i CGI
Func?ii noi
Migrarea de la PHP 4 la PHP 5.0.x


Func?ii noi

În PHP 5 sunt unele func?ii noi. Iata lista lor:

Tablouri:

  • array_combine() - Creaza un tablou folosind un tablou pentru chei ?i alt tablou pentru valorile lor
  • array_diff_uassoc() - Calculeaza diferen?a dintre tablouri cu verificarea suplimentara a indicilor, care este efectuata de o func?ie de apel invers furnizata de utilizator
  • array_udiff() - Calculeaza diferen?a dintre tablouri utilizând o func?ie de apel invers pentru compararea datelor
  • array_udiff_assoc() - Calculeaza diferen?a dintre tablouri cu verificarea suplimentara a indicilor. Datele sunt comparate utilizând o func?ie de apel invers
  • array_udiff_uassoc() - Calculeaza diferen?a dintre tablouri cu verificarea suplimentara a indicilor. Datele sunt comparate utilizând o func?ie de apel invers. Verificarea indicilor de asemenea este efectuata cu o func?ie de apel invers
  • array_walk_recursive() - Aplica recursiv o func?ie a utilizatorului fiecarui membru (element) al tabloului
  • array_uintersect_assoc() - Calculeaza intersec?ia tablourilor cu o verificare suplimentara a indicilor. Datele sunt comparate utilizând o func?ie de apel invers
  • array_uintersect_uassoc() - Calculeaza intersec?ia tablourilor cu o verificare suplimentara a indicilor. Atât datele, cât ?i indicii sunt compara?i utilizând func?ii separate de apel invers
  • array_uintersect() - Calculeaza intersec?ia tablourilor. Datele sunt comparate utilizând o func?ie de apel invers

InterBase:

  • ibase_affected_rows() - Întoarce numarul rândurilor afectate de interpelarea precedenta
  • ibase_backup() - Ini?iaza o opera?iune de copiere de rezerva în managerul serviciilor ?i întoarce controlul imediat
  • ibase_commit_ret() - Efectueaza tranzac?ia fara a o închide
  • ibase_db_info() - Cere statistica despre o baza de date
  • ibase_drop_db() - Elimina o baza de date
  • ibase_errcode() - Întoarce codul erorii
  • ibase_free_event_handler() - Anuleaza o procedura înregistrata de prelucrare a unui eveniment
  • ibase_gen_id() - Cre?te valoarea generatorului denumit ?i întoarce noua sa valoare
  • ibase_maintain_db() - Executa o comanda de între?inere pe server-ul de baze de date
  • ibase_name_result() - Atribuie un nume unui set de rezultate
  • ibase_num_params() - Întoarce numarul parametrilor într-o interpelare pregatitia
  • ibase_param_info() - Întoarce informa?ia despre un parametru într-o interpelare pregatitia
  • ibase_restore() - Ini?iaza o opera?iune de restabilire în managerul serviciilor ?i întoarce execu?ia imediat
  • ibase_rollback_ret() - Anuleaza tranzac?ia ?i re?ine contextul tranzac?iei
  • ibase_server_info() - Cere statistica despre un server de baze de date
  • ibase_service_attach() - Conectarea la managerul serviciilor
  • ibase_service_detach() - Deconectarea de la managerul serviciilor
  • ibase_set_event_handler() - Înregistreaza o func?ie de apel invers pentru a fi apelata atunci când evenimentele sunt afi?ate (declan?ate)
  • ibase_wait_event() - A?teapta pâna când un eveniment este afi?at (declan?at) de baza de date

iconv:

  • iconv_mime_decode() - Decodifica un câmp cu antet MIME
  • iconv_mime_decode_headers() - Decodifica mai multe câmpuri de antete MIME concomitent
  • iconv_mime_encode() - Compune un câmp de antet MIME
  • iconv_strlen() - Întoarce numarul de caractere din string
  • iconv_strpos() - Gase?te pozi?ia primei apari?ii a acului în stogul de fân (a needle within a haystack)
  • iconv_strrpos() - Gase?te pozi?ia ultimei apari?ii a acului în stogul de fân (a needle within a haystack)
  • iconv_substr() - Taie o parte a unui string

Fluxuri:

  • stream_copy_to_stream() - Copie datele dintr-un flux în altul
  • stream_get_line() - Ob?ine o linie din resursa de flux pâna la un separator dat
  • stream_socket_accept() - Accepta o conexiune printr-un socket creat cu stream_socket_server()
  • stream_socket_client() - Deschide o conexiune printr-un socket Internet sau de domeniu Unix
  • stream_socket_get_name() - Ob?ine denumirea socket-urilor locale sau îndepartate
  • stream_socket_recvfrom() - Prime?te date de la un socket, fie connectat, sau nu
  • stream_socket_sendto() - Trimite un mesaj catre un socket, fie conectat, sau nu
  • stream_socket_server() - Creaza un socket server Internet sau de domeniu Unix

Func?ii referitoare la data ?i timp:

  • idate() - Formateaza o valoare timp/data locala ca integer
  • date_sunset() - Ora apusului Soarelui pentru o zi ?i o loca?ie date
  • date_sunrise() - Ora rasaritului Soarelui pentru o zi ?i o loca?ie date
  • time_nanosleep() - Pauza pentru un numar de secunde ?i nanosecunde

String-uri:

  • str_split() - Converte?te un string într-un tablou
  • strpbrk() - Cauta în string un caracter dintr-un set de caractere
  • substr_compare() - Compara?ia sigura din punct de vedere binar, op?ional nesensibila la tipul caracterelor (majuscule / minuscule) a doua string-uri de la un deplasament, pâna la un anumit numar de caractere

Altele:

  • convert_uudecode() - decodifica un string codificat cu uuencode
  • convert_uuencode() - codifica un string cu uuencode
  • curl_copy_handle() - Copie un handle cURL, împreuna cu toate preferin?ele sale
  • dba_key_split() - Desparte o cheie din reprezentare string în reprezentare pentru tablouri
  • dbase_get_header_info() - Ob?ine informa?ia de antet a unei beze de date dBase
  • dbx_fetch_row() - Ob?ine rânduri dintr-un rezultat al interpelarii, care a avut stabilit fanionul DBX_RESULT_UNBUFFERED
  • fbsql_set_password() - Modifica parola pentru un utilizator dat
  • file_put_contents() - Înscrie un string într-un fi?ier
  • ftp_alloc() - Aloca spa?iu pentru încarcarea unui fi?ier
  • get_declared_interfaces() - Întoarce un tablou al tuturor interfe?elor declarate
  • get_headers() - Intercepteaza toate antetele trimise de catre server ca raspuns la o interpelare HTTP
  • headers_list() - Întoarce lista antetelor de raspuns trimise (sau care sunt gata de a fi trimise)
  • http_build_query() - Genereaza un string de interpelare codificat cu URL-encode
  • image_type_to_extension() - Ob?ine extensia fi?ierului
pentru tipul imaginii întoarse de getimagesize(),
exif_read_data(), exif_thumbnail(),
exif_imagetype()
  • imagefilter() - Aplica un filtru asupra unei imagini utilizând argumentele indicate
  • imap_getacl() - Ob?ine ACL-ul pentru o cutie po?tala data
  • ldap_sasl_bind() - Legatura cu un director LDAP utilizând SASL
  • mb_list_encodings() - Întoarce un tablou al tuturor codificarilor sus?inute
  • pcntl_getpriority() - Ob?ine prioritatea oricarui proces
  • pcntl_wait() - A?teapta sau întoarce starea unui proces-fiu bifurcat, dupa cum e definit de catre apelul de sistem waitpid()
  • pg_version() - Întoarce un tablou cu informa?ia despre client, protocol ?i versiunea server-ului (daca este disponibila)
  • php_check_syntax() - Verifica sintaxa fi?ierului specificat
  • php_strip_whitespace() - Întoarce sursa cu comentariile ?i spa?iile suprimate
  • proc_nice() - Modifica prioritatea procesului curent
  • pspell_config_data_dir() - Modifica localizarea fi?ierelor cu date ale limbii
  • pspell_config_dict_dir() - Modifica localizarea listei de baza a cuvintelor
  • setrawcookie() - Trimite o prajitura fara a codifica valoarea cu URL-encode
  • scandir() - Listeaza fi?ierele ?i directoarele din calea specificata
  • snmp_read_mib() - Cite?te ?i încarca un fi?ier MIB în arborele MIB activ
  • sqlite_fetch_column_types() - Întoarce un tablou cu tipurile coloanelor dintr-un careva tabel

Nota:

Extensia Tidy de asemenea ?i-a schimbat complet API-ul.

Migrarea fi?ierelor de configurare
Directive noi
Migrarea de la PHP 4 la PHP 5.0.x


Directive noi

În PHP 5 au fost introduse unele directive noi php.ini. Iata lista lor:

  • mail.force_extra_parameters - For?eaza trimiterea parametrilor specifica?i în calitate de parametri suplimentari pentru binarul sendmail. Ace?ti parametri întotdeauna vor înlocui valoarea parametrului al 5-lea cu mail(), chiar ?i în modul sigur
  • register_long_arrays - permite/interzice PHP sa înregistreze variabilele lungi învechite $HTTP_*_VARS
  • session.hash_function - selecteaza o func?ie hash (MD5 sau SHA-1)
  • session.hash_bits_per_character - define?te câ?i bi?i sunt stoca?i în fiecare caracter la convertirea datelor binare hash în ceva lizibil (de la 4 pâna la 6)
  • zend.ze1_compatibility_mode - Activeaza modul de compatibilitate cu Zend Engine 1 (PHP 4)
Func?ii noi
Bazele de date
Migrarea de la PHP 4 la PHP 5.0.x


Bazele de date

În PHP 5 au survenit unele schimbari în privin?a bazelor de date (MySQL ?i SQLite).

În PHP 5 bibliotecile clientului MySQL nu sunt încorporate din cauza problemelor de licen?iere ?i mentenan?a. MySQL este sus?inut cu unica modificare ca aceasta sus?inere nu este activata implicit în PHP 5. Aceasta în esen?a înseamna ca PHP nu include op?iunea --with-mysql în linia de configurare ?i deci trebuie sa o include?i manual la compilarea PHP. Utilizatorii Windows vor trebui sa redacteze php.ini ?i sa activeze biblioteca php_mysql.dll deoarece în PHP 4 un astfel de DLL nu exista, ci era pur ?i simplu încorporat în binarele PHP sub Windows.

De asemenea este o noua extensie, MySQLi (MySQL îmbunata?it), care este proiectat sa lucreze cu MySQL 4.1 ?i ulterior.

Începând cu PHP 5, extensia SQLite este încorporata în PHP. SQLite este un motor de baze de date SQL u?or încorporabil ?i nu este o biblioteca-client utilizata pentru conectarea la un server mare de baze de date (ca MySQL sau PostgreSQL). Biblioteca SQLite cite?te ?i înscrie direct în fi?ierele cu baza de date de pe disc.

Directive noi
Noul Model de Obiecte
Migrarea de la PHP 4 la PHP 5.0.x


Noul Model de Obiecte

În PHP 5 este un nou Model de Obiecte. Manipularea obiectelor în PHP a fost complet rescrisa, îmbunata?ind performan?a ?i introducând mai multe facilita?i. În versiunile precedente ale PHP obiectele erau manipulate ca tipuri primitive (ca de exemplu întregi sau string-uri). Neajunsul acestei metode era ca din punct de vedere semantic întregul obiect era copiat atunci când era atribuit unei variabile, sau când era transmis ca parametru unei metode. În noua abordare, obiectele sunt accesate prin handle, ?i nu prin valoare (pute?i sa considera?i handle ca un identificator al obiectului).

Mul?i programatori PHP nici nu-?i dau seama despre trucurile cu copierea în modelul de obiecte vechi, de aceea majoritatea aplica?iilor PHP vor lucra fara modificari, sau cu foarte pu?ine modificari.

Noul Model de Obiecte este documentat în Prezentarea Limbajului.

În PHP 5, func?ia cu denumirea clasei este numita constructor, dar numai daca este definita în aceasta clasa. În PHP 4, ea este apelata de asemenea daca este definita în clasa-parinte.

Vede?i de asemenea directiva zend.ze1_compatibility_mode pentru informa?ii despre compatibilitatea cu PHP 4.

Bazele de date
Raportarea erorilor
Migrarea de la PHP 4 la PHP 5.0.x


Raportarea erorilor

Începând cu PHP 5 este disponibila constanta de raportare a erorilor E_STRICT cu valoarea 2048. Când este activata, vor fi emise mesaje ce va vor avertiza despre utilizarea unui cod-sursa care este dezapreciat sau care poate sa nu fie compatibil în viitor.

Nota: E_ALL nu include E_STRICT, de aceea ea nu e activata implicit. Trebuie sa stabili?i în mod explicit nivelul de raportare a erorilor sa includa E_STRICT pentru a vedea aceste mesaje.

Accesa?i Constantele predefinite pentru informa?ii suplimentare.

Noul Model de Obiecte
Depistarea erorilor (debugging) în PHP
Migrarea de la PHP 4 la PHP 5.0.x


Depistarea erorilor (debugging) în PHP

Cuprins

  • Despre debugging în PHP
Raportarea erorilor
Despre debugging în PHP
Anexe


Despre debugging în PHP

PHP 5.6 este furnizat cu debugger-ul interactiv phpdbg. Însa versiunile PHP anterioare 5.6 nu au o facilitate interna de debugging. Însa pute?i folosi unul dintre debugger-ele externe. » Mediul Zend IDE include un debugger, ?i mai sunt ?i alte extensii gratuite de debugging, cum ar fi DBG la » http://www.php-debugger.com/dbg/, » Advanced PHP Debugger (APD) sau » Xdebug.

Depistarea erorilor (debugging) în PHP
Op?iunile de configurare
Depistarea erorilor (debugging) în PHP


Op?iunile de configurare

Cuprins

  • Lista op?iunilor de configurare de baza
Despre debugging în PHP
Lista op?iunilor de configurare de baza
Anexe


Lista op?iunilor de configurare de baza

Mai jos este prezentata lista par?iala a op?iunilor de configurare, folosite de scripturile configure ale PHP, atunci când se efectueaza compilarea în mediile de tip Unix. Majoritatea op?iunilor de configurare sunt listate în loca?iile corespunzatoare din paginile de referin?a ale extensiilor, ?i nu aici. Pentru o lista completa ?i reînnoita a op?iunilor de configurare lansa?i ./configure --help în directorul cu sursa dumneavoastra PHP, dupa ce a fost lansat autoconf (vede?i, de asemenea capitolul despre instalare). Dumneavoastra pute?i fi cointeresat sa citi?i ?i documenta?ia » GNU configure pentru informa?ii despre op?iunile configure suplimentare, cum ar fi --prefix=PREFIX.

Nota:

Acestea sunt utilizate doar în timpul compilarii. Daca dori?i sa modifica?i configura?ia PHP în timpul rularii, va rugam sa vede?i capitolul despre Configura?ia la rulare.

  • Diverse
  • Comportamentul PHP
  • Server

Op?iunile de configurare din PHP

Op?iuni diverse

--enable-debug

Compileaza cu simbolurile de debugging.

--with-layout=TYPE

Seteaza modul în care fi?ierele instalate vor fi amplasate. TYPE este una din valorile PHP (implicit) sau GNU.

--with-pear=DIR

Instaleaza PEAR în DIR (implicit PREFIX/lib/php).

--without-pear

Fara instalarea PEAR.

--enable-sigchild

Activeaza propriul handler SIGCHLD al PHP.

--disable-rpath

Dezactiveaza posibilitatea indicarii cailor de cautare suplimentare ale bibliotecii la rulare.

--enable-libgcc

Activeaza în mod explicit legatura cu libgcc.

--enable-php-streams

Include fluxurile PHP experimentale. Nu folosi?i decât daca testa?i codul sursa!

--with-zlib-dir[=DIR]

Define?te loca?ia directorului de instalare zlib.

--with-tsrm-pthreads

Folose?te firele POSIX (implicit).

--enable-shared[=PKGS]

Asambleaza biblioteci partajate [implicit=da].

--enable-static[=PKGS]

Asambleaza biblioteci statice [implicit=da].

--enable-fast-install[=PKGS]

Optimizeaza pentru o instalare rapida [implicit=da].

--with-gnu-ld

Presupune ca compilatorul C folose?te ld al GNU [implicit=nu].

--disable-libtool-lock

Evita închiderea (poate deteriora asamblarile paralele).

--with-pic

Încearca folosirea numai a obiectelor PIC/non-PIC [implicit=folose?te ambele].

--enable-memory-limit

Compileaza cu sus?ineara limitelor de memorie. (nu este disponibila începând cu PHP 5.2.1 - mereu activata)

--disable-url-fopen-wrapper

Dezactiveaza înveli?ul pentru func?ia fopen, care sus?ine accesarea fi?ierelor prin HTTP sau FTP. (nu este disponibil începând cu PHP 5.2.5)

--enable-versioning

Exporta numai simbolurile necesare. Vezi INSTALL pentru informa?ii suplimentare.

Op?iunile PHP

--enable-maintainer-mode

Activeaza regulile ?i dependen?ele make nefolositoare (?i uneori neclare) pentru un instalator obi?nuit.

--with-config-file-path=PATH

Seteaza calea în care este cautat php.ini, implicit aceasta este PREFIX/lib.

--enable-safe-mode

Implicit activeaza modul sigur (safe mode).

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

--with-exec-dir[=DIR]

Permite executarea fi?ierelor numai din directorul DIR, atunci când este activat modul sigur. Implicit este /usr/local/php/bin.

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

--enable-magic-quotes

Implicit activeaza citatele magice (magic quotes).

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

--disable-short-tags

Dezactiveaza forma scurta implicita a etichetei de startare <? .

--enable-zend-multibyte

Permite executarea codului-sursa multibyte în interpretorul ?i scanerul limbajului. Când PHP este compilat cu aceasta op?iune, se activeaza de asemenea ?i directiva encoding în construc?ia declare.

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

--with-libdir

Specifica directorul unde se afla bibliotecile cu ajutorul carora a fost asamblat PHP pe un sistem Unix. Pentru sisteme pe 64 bi?i, este necesar de a stabili acest argument cu valoarea directorului lib64 în felul urmator: --with-libdir=lib64.

Op?iunile SAPI

Lista ce urmeaza con?ine interfe?ele SAPI (Server Application Programming Interface — Interfa?a de Programare a Aplica?iilor pentru Server) disponibile pentru PHP.

--with-aolserver=DIR

Specifica calea spre AOLserver instalat.

--with-apxs[=FILE]

Asambleaza un modul partajat pentru Apache. FILE este calea op?ionala spre instrumentul apxs; implicit este apxs. Asigura?i-va ca specifica?i versiunea apxs care este într-adevar instalata pe sistemul dumneavoastra, NU aceea ce se con?ine în pachetul cu sursa apache.

--with-apache[=DIR]

Asambleaza un modul static pentru Apache. DIR este directorul de vârf al serverului Apache asamblat, implicit este /usr/local/apache.

--with-mod_charset

Activeaza tabelele de transfer pentru mod_charset (Apache rusesc).

--with-apxs2[=FILE]

Asambleaza un modul partajat pentru Apache 2.0. FILE este calea op?ionala spre instrumentul apxs; implicit este apxs.

--with-caudium=DIR

Asambleaza PHP în calitate de modul Pike, pentru a fi folosit cu Caudium. DIR este directorul serverului Caudium, cu valoarea implicita /usr/local/caudium/server.

--disable-cli

Disponibil odata cu PHP 4.3.0. Dezactiveaza asamblarea versiunii CLI a PHP (aceasta impune ?i --without-pear). Mai multe informa?ii sunt disponibile în sec?iunea desspre Utilizarea PHP din linia de comanda.

--enable-phpdbg

Activeaza sus?inerea debugger-ului interactiv phpdbg ca modul SAPI în PHP 5.6.x sau ulterior.

--enable-embed[=TYPE]

Activeaza asamblarea unei biblioteci SAPI încorporate. TYPE poate fi sau shared, sau static ?i implicit este shared. Disponibil odata cu PHP 4.3.0.

--with-fhttpd[=DIR]

Asambleaza un modul fhttpd. DIR este directorul cu sursele fhttpd, implicit are valoarea /usr/local/src/fhttpd. Nu mai este disponibil începând cu PHP 4.3.0.

--with-isapi=DIR

Asambleaza PHP în calitate de modul ISAPI, pentru a fi utilizat cu Zeus.

--with-nsapi=DIR

Specifica calea spre web server-ele instalate Netscape/iPlanet/SunONE.

--with-phttpd=DIR

Deocamdata nu exista informa?ii.

--with-pi3web=DIR

Asambleaza PHP în calitate de modul, pentru a fi utilizat cu Pi3Web.

--with-roxen=DIR

Asambleaza PHP în calitate de modul Pike. DIR este directorul de baza al Roxen, în mod normal /usr/local/roxen/server.

--enable-roxen-zts

Asambleaza modulul Roxen utilizând Zend Thread Safety.

--with-servlet[=DIR]

Include sus?inerea servlet-urilor. DIR este directorul de baza, unde este instalat JSDK. Acest SAPI necesita ca extensia java sa fie asamblata ca un 'dl' partajat.

--with-thttpd=SRCDIR

Asambleaza PHP în calitate de modul thttpd.

--with-tux=MODULEDIR

Asambleaza PHP în calitate de modul TUX (numai în Linux).

--with-webjames=SRCDIR

Asambleaza PHP în calitate de modul WebJames (numai în RISC OS)

--disable-cgi

Dezactiveaza asamblarea versiunii CGI a PHP. Disponibil începând cu PHP 4.3.0.

Începând cu PHP 5.3.0 acest argument activeaza FastCGI, care anterior trebuia activat cu ajutorul --enable-fastcgi.

--enable-force-cgi-redirect

Activeaza controlul de securitate pentru redirec?ionarile interne ale serverului. Ar trebui sa utiliza?i aceasta op?iune daca rula?i versiunea CGI cu Apache.

Începând cu PHP 5.3.0 acest argument este activat implicit ?i nu mai exista. Pentru a dezactiva aceasta func?ionalitate, directiva ini cgi.force_redirect trebuie stabilita în 0.

--enable-discard-path

Daca aceasta op?iune e activata, fi?ierul binar CGI al PHP poate fi plasat în mod sigur în afara arborelui web ?i nimeni nu va putea sparge securitatea .htaccess.

Începând cu PHP 5.3.0 acest argument este dezactivat implicit ?i nu mai exista. Pentru a activa aceasta facilitate, directiva ini cgi.discard_path trebuie stabilita în 1.

--enable-fastcgi

Daca aceasta op?iune e activata, modulul CGI va fi asamblat de asemenea cu sus?inerea FastCGI.

Începând cu PHP 5.3.0 acest argument nu mai exista ?i este activat cu --enable-cgi în loc.

--disable-path-info-check

Daca aceasta op?iune e dezactivata, caile ca /info.php/test?a=b nu vor func?iona. Pentru informa?ii suplimentare, accesa?i » Manualul Apache.

Op?iunile de configurare
Directive php.ini
Op?iunile de configurare


Directive php.ini

Cuprins

  • Lista directivelor php.ini
  • Lista sec?iunilor php.ini
  • Descrierea directivelor de baza ale php.ini
Lista op?iunilor de configurare de baza
Lista directivelor php.ini
Anexe


Lista directivelor php.ini

Aceasta lista include directivele php.ini pe care le pute?i stabili pentru a configura PHP.

Coloana "Poate fi schimbat" arata modurile ce determina când ?i unde o directiva poate fi stabilita. Accesa?i sec?iunea Valorile modurilor ce pot fi schimbate pentru a vedea defini?iile lor.

Op?iunile de configurare
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
allow_call_time_pass_reference | "1" | PHP_INI_PERDIR | PHP_INI_ALL în PHP 4.0.0. Eliminata în PHP 5.4.0.
allow_url_fopen | "1" | PHP_INI_SYSTEM | PHP_INI_ALL în PHP <= 4.3.4.
allow_url_include | "0" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.2.0.
always_populate_raw_post_data | "0" | PHP_INI_PERDIR | PHP_INI_ALL în PHP <= 4.2.3. Disponibila începând cu PHP 4.1.0.
apc.cache_by_default | "1" | PHP_INI_ALL | PHP_INI_SYSTEM în APC <= 3.0.12. Disponibila începând cu APC 3.0.0.
apc.enabled | "1" | PHP_INI_SYSTEM | PHP_INI_SYSTEM în APC 2. PHP_INI_ALL în APC <= 3.0.12.
apc.enable_cli | "0" | PHP_INI_SYSTEM | Disponibila începând cu APC 3.0.7.
apc.file_update_protection | "2" | PHP_INI_SYSTEM | Disponibila începând cu 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 | Disponibila începând cu APC 3.0.12.
apc.localcache | "0" | PHP_INI_SYSTEM | Disponibila începând cu APC 3.0.14.
apc.localcache.size | "512" | PHP_INI_SYSTEM | Disponibila începând cu APC 3.0.14.
apc.max_file_size | "1M" | PHP_INI_SYSTEM | Disponibila începând cu 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 în APC 2. Eliminata în APC 3.0.13.
apc.report_autofilter | "0" | PHP_INI_SYSTEM | Disponibila începând cu APC 3.0.11.
apc.rfc1867 | "0" | PHP_INI_SYSTEM | Disponibila începând cu 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 | Disponibila începând cu APC 3.0.0.
apc.stat | "1" | PHP_INI_SYSTEM | Disponibila începând cu APC 3.0.10.
apc.stat_ctime | "0" | PHP_INI_SYSTEM | Disponibila începând cu APC 3.0.13.
apc.ttl | "0" | PHP_INI_SYSTEM | Disponibila începând cu APC 3.0.0.
apc.user_entries_hint | "4096" | PHP_INI_SYSTEM | Disponibila începând cu APC 3.0.0.
apc.user_ttl | "0" | PHP_INI_SYSTEM | Disponibila începând cu APC 3.0.0.
apc.write_lock | "1" | PHP_INI_SYSTEM | Disponibila începând cu APC 3.0.11.
apd.bitmask | "0" | PHP_INI_ALL | Eliminata în apd 0.9.
apd.dumpdir | NULL | PHP_INI_ALL |
apd.statement_tracing | "0" | PHP_INI_ALL | Disponibila începând cu apd 0.9.
arg_separator | "&" | PHP_INI_ALL | Eliminata în PHP 4.0.6.
arg_separator.input | "&" | PHP_INI_PERDIR | Disponibila începând cu PHP 4.0.5.
arg_separator.output | "&" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.5.
asp_tags | "0" | PHP_INI_PERDIR | PHP_INI_ALL în PHP 4.0.0.
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.exception | "0" | PHP_INI_ALL | Disponibila începând cu PHP 7.0.0.
assert.quiet_eval | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
async_send | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.2.0. Eliminata în PHP 4.3.0.
auto_append_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL în PHP <= 4.2.3.
auto_detect_line_endings | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
auto_globals_jit | "1" | PHP_INI_PERDIR | Disponibila începând cu PHP 5.0.0.
auto_prepend_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL în 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 | Disponibila începând cu bcompiler 0.8.
blenc.key_file | "/usr/local/etc/blenckeys" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.2.1.
cgi.discard_path | "0" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.3.0.
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM | PHP_INI_ALL în PHP <= 5.2.0. Disponibila începând cu PHP 4.3.0.
cgi.force_redirect | "1" | PHP_INI_SYSTEM | PHP_INI_ALL în PHP <= 5.2.0. Disponibila începând cu PHP 4.2.0.
cgi.nph | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.5.
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM | PHP_INI_ALL în PHP <= 5.2.0. Disponibila începând cu PHP 4.2.0.
cgi.rfc2616_headers | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
child_terminate | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.5.
cli.pager | "" | PHP_INI_ALL | Disponibila începând cu PHP 5.4.0.
cli.prompt | "\\b \\> " | PHP_INI_ALL | Disponibila începând cu PHP 5.4.0.
cli_server.color | "0" | PHP_INI_ALL | Disponibila începând cu PHP 5.4.0.
coin_acceptor.autoreset | "On" | PHP_INI_ALL | Eliminata în coin_acceptor 0.2.
coin_acceptor.auto_initialize | "Off" | PHP_INI_ALL | Disponibila începând cu coin_acceptor 0.2.
coin_acceptor.auto_reset | "On" | PHP_INI_ALL | Disponibila începând cu coin_acceptor 0.2.
coin_acceptor.command_function | "Off" | PHP_INI_ALL | Disponibila începând cu coin_acceptor 0.3.
coin_acceptor.delay | "53132" | PHP_INI_ALL | Eliminata în coin_acceptor 0.2.
coin_acceptor.delay_coins | "53132" | PHP_INI_ALL | Disponibila începând cu coin_acceptor 0.2.
coin_acceptor.delay_prom | "55748" | PHP_INI_ALL | Disponibila începând cu coin_acceptor 0.2.
coin_acceptor.device | "/dev/ttyS1" | PHP_INI_ALL | Eliminata în coin_acceptor 0.2.
coin_acceptor.lock_on_close | "Off" | PHP_INI_ALL | Disponibila începând cu coin_acceptor 0.2.
coin_acceptor.start_unlocked | "On" | PHP_INI_ALL | Disponibila începând cu coin_acceptor 0.2.
com.allow_dcom | "0" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.5.
com.autoregister_casesensitive | "1" | PHP_INI_ALL | PHP_INI_SYSTEM în PHP 4. Disponibila începând cu PHP 4.1.0.
com.autoregister_typelib | "0" | PHP_INI_ALL | PHP_INI_SYSTEM în PHP 4. Disponibila începând cu PHP 4.1.0.
com.autoregister_verbose | "0" | PHP_INI_ALL | PHP_INI_SYSTEM în PHP 4. Disponibila începând cu PHP 4.1.0.
com.code_page | "" | PHP_INI_ALL | Disponibila începând cu PHP 5.0.0.
com.typelib_file | "" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.5.
curl.cainfo | NULL | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.3.7.
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 | Disponibila începând cu PHP 5.0.0.
date.default_longitude | "35.2333" | PHP_INI_ALL | Disponibila începând cu PHP 5.0.0.
date.sunrise_zenith | "90.583333" | PHP_INI_ALL | Disponibila începând cu PHP 5.0.0.
date.sunset_zenith | "90.583333" | PHP_INI_ALL | Disponibila începând cu PHP 5.0.0.
date.timezone | "" | PHP_INI_ALL | Disponibila începând cu PHP 5.1.0.
dba.default_handler | "" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.3.
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.3.0. Eliminata în PHP 5.1.0.
default_charset | "UTF-8" | PHP_INI_ALL | Implicit are valoarea "UTF-8" începând cu PHP >= 5.6.0, valoare vida pentru PHP < 5.6.0.
default_mimetype | "text/html" | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
define_syslog_variables | "0" | PHP_INI_ALL | Eliminata în PHP 5.4.0.
detect_unicode | "1" | PHP_INI_ALL | Disponibila începând cu PHP 5.1.0. Redenumita în zend.detect_unicode începând cu PHP 5.4.0.
disable_classes | "" | php.ini only | Disponibila începând cu PHP 4.3.2.
disable_functions | "" | php.ini only | Disponibila începând cu PHP 4.0.1.
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.3.
docref_ext | "" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.2.
docref_root | "" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
doc_root | NULL | PHP_INI_SYSTEM |
enable_dl | "1" | PHP_INI_SYSTEM | Aceasta facilitate învechita cu siguran?a va fi eliminata în viitor.
enable_post_data_reading | On | PHP_INI_PERDIR | Disponibila începând cu PHP 5.4.0.
engine | "1" | PHP_INI_ALL | Disponibila începând cu 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 |
exif.decode_jis_intel | "JIS" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
exif.encode_jis | "" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
exit_on_timeout | "" | PHP_INI_ALL | Disponibila începând cu PHP 5.3.0
expect.logfile | "" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.timeout | "10" | PHP_INI_ALL |
expose_php | "1" | Doar în php.ini |
extension | NULL | Doar în php.ini |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM | PHP_INI_ALL în PHP <= 5.2.0. Disponibila începând cu PHP 4.3.0.
fastcgi.logging | "1" | PHP_INI_SYSTEM | PHP_INI_ALL în PHP <= 5.2.0. Disponibila începând cu PHP 4.4.0.
fbsql.allow_persistant | "1" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.6. Eliminata în PHP 4.2.0.
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.2.0.
fbsql.autocommit | "1" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.6.
fbsql.batchSize | "1000" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.2.0. Eliminata în PHP 5.1.0.
fbsql.batchsize | "1000" | PHP_INI_ALL | Disponibila începând cu PHP 5.1.0.
fbsql.default_database | "" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.6.
fbsql.default_database_password | "" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.6.
fbsql.default_host | NULL | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.6.
fbsql.default_password | "" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.6.
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.6.
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.6.
fbsql.max_connections | "128" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.6.
fbsql.max_links | "128" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.6.
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.6.
fbsql.max_results | "128" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.6.
fbsql.mbatchSize | "1000" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.0.6. Eliminata în PHP 4.2.0.
fbsql.show_timestamp_decimals | "0" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.1.5.
file_uploads | "1" | PHP_INI_SYSTEM | PHP_INI_ALL în PHP <= 4.2.3. Disponibila începând cu PHP 4.0.3.
filter.default | "unsafe_raw" | PHP_INI_PERDIR | PHP_INI_ALL în filter <= 0.9.4. Disponibila începând cu PHP 5.2.0.
filter.default_flags | NULL | PHP_INI_PERDIR | PHP_INI_ALL în filter <= 0.9.4. Disponibila începând cu PHP 5.2.0.
from | "" | PHP_INI_ALL |
gd.jpeg_ignore_warning | "0" | PHP_INI_ALL | Disponibila începând cu PHP 5.1.3.
geoip.custom_directory | NULL | PHP_INI_ALL | Disponibila începând cu geoip 1.0.1.
geoip.database_standard | "GeoIP.dat" | PHP_INI_ALL | Eliminata în geoip 1.0.1.
hidef.ini_path | (char*)default_ini_path | PHP_INI_SYSTEM |
highlight.bg | "#FFFFFF" | PHP_INI_ALL | Eliminata în 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 în PHP <= 4.2.3. Disponibila începând cu PHP 4.0.2.
htscanner.config_file | ".htaccess" | PHP_INI_SYSTEM |
htscanner.default_docroot | "/" | PHP_INI_SYSTEM |
htscanner.default_ttl | "300" | PHP_INI_SYSTEM | Disponibila începând cu htscanner 0.6.0.
htscanner.stop_on_error | "0" | PHP_INI_SYSTEM | Disponibila începând cu htscanner 0.7.0.
http.allowed_methods | "" | PHP_INI_ALL | Disponibila începând cu pecl_http 0.4.0. Eliminata în pecl_http 1.0.0.
http.allowed_methods_log | "" | PHP_INI_ALL | Disponibila începând cu pecl_http 0.12.0. Eliminata în pecl_http 1.0.0.
http.cache_log | "" | PHP_INI_ALL | Disponibila începând cu pecl_http 0.8.0. Eliminata în pecl_http 1.0.0.
http.composite_log | "" | PHP_INI_ALL | Disponibila începând cu pecl_http 0.12.0. Eliminata în pecl_http 1.0.0.
http.etag.mode | "MD5" | PHP_INI_ALL | Disponibila începând cu pecl_http 1.0.0.
http.etag_mode | "MD5" | PHP_INI_ALL | Disponibila începând cu pecl_http 0.12.0. Eliminata în pecl_http 1.0.0.
http.force_exit | "1" | PHP_INI_ALL | Disponibila începând cu pecl_http 0.18.0.
http.log.allowed_methods | "" | PHP_INI_ALL | Disponibila începând cu pecl_http 1.0.0.
http.log.cache | "" | PHP_INI_ALL | Disponibila începând cu pecl_http 1.0.0.
http.log.composite | "" | PHP_INI_ALL | Disponibila începând cu pecl_http 1.0.0.
http.log.not_found | "" | PHP_INI_ALL | Disponibila începând cu pecl_http 1.0.0.
http.log.redirect | "" | PHP_INI_ALL | Disponibila începând cu pecl_http 1.0.0.
http.ob_deflate_auto | "0" | PHP_INI_PERDIR | Disponibila începând cu pecl_http 0.21.0. Eliminata în pecl_http 1.0.0.
http.ob_deflate_flags | "0" | PHP_INI_ALL | Disponibila începând cu pecl_http 0.21.0. Eliminata în pecl_http 1.0.0.
http.ob_inflate_auto | "0" | PHP_INI_PERDIR | Disponibila începând cu pecl_http 0.21.0. Eliminata în pecl_http 1.0.0.
http.ob_inflate_flags | "0" | PHP_INI_ALL | Disponibila începând cu pecl_http 0.21.0. Eliminata în pecl_http 1.0.0.
http.only_exceptions | "0" | PHP_INI_ALL | Disponibila începând cu pecl_http 0.11.0.
http.persistent.handles.ident | "GLOBAL" | PHP_INI_ALL | Disponibila începând cu pecl_http 1.5.0.
http.persistent.handles.limit | "-1" | PHP_INI_SYSTEM | Disponibila începând cu pecl_http 1.5.0.
http.redirect_log | "" | PHP_INI_ALL | Disponibila începând cu pecl_http 0.12.0. Eliminata în pecl_http 1.0.0.
http.request.datashare.connect | "0" | PHP_INI_SYSTEM | Disponibila începând cu pecl_http 1.3.0.
http.request.datashare.cookie | "0" | PHP_INI_SYSTEM | Disponibila începând cu pecl_http 1.3.0.
http.request.datashare.dns | "1" | PHP_INI_SYSTEM | Disponibila începând cu pecl_http 1.3.0.
http.request.datashare.ssl | "0" | PHP_INI_SYSTEM | Disponibila începând cu pecl_http 1.3.0.
http.request.methods.allowed | "" | PHP_INI_ALL | Disponibila începând cu pecl_http 1.0.0.
http.request.methods.custom | "" | PHP_INI_PERDIR | Disponibila începând cu pecl_http 1.0.0.
http.send.deflate.start_auto | "0" | PHP_INI_PERDIR | Disponibila începând cu pecl_http 1.0.0.
http.send.deflate.start_flags | "0" | PHP_INI_ALL | Disponibila începând cu pecl_http 1.0.0.
http.send.inflate.start_auto | "0" | PHP_INI_PERDIR | Disponibila începând cu pecl_http 1.0.0.
http.send.inflate.start_flags | "0" | PHP_INI_ALL | Disponibila începând cu pecl_http 1.0.0.
http.send.not_found_404 | "1" | PHP_INI_ALL | Disponibila începând cu pecl_http 1.0.0.
ibase.allow_persistent | "1" | PHP_INI_SYSTEM |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL | Disponibila începând cu PHP 5.0.0.
ibase.default_db | NULL | PHP_INI_SYSTEM | Disponibila începând cu 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_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.
iconv.input_encoding | "ISO-8859-1" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.5.
iconv.internal_encoding | "ISO-8859-1" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.5.
iconv.output_encoding | "ISO-8859-1" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.5.
ifx.allow_persistent | "1" | PHP_INI_SYSTEM | Eliminata în PHP 5.2.1.
ifx.blobinfile | "1" | PHP_INI_ALL | Eliminata în PHP 5.2.1.
ifx.byteasvarchar | "0" | PHP_INI_ALL | Eliminata în PHP 5.2.1.
ifx.charasvarchar | "0" | PHP_INI_ALL | Eliminata în PHP 5.2.1.
ifx.default_host | NULL | PHP_INI_SYSTEM | Eliminata în PHP 5.2.1.
ifx.default_password | NULL | PHP_INI_SYSTEM | Eliminata în PHP 5.2.1.
ifx.default_user | NULL | PHP_INI_SYSTEM | Eliminata în PHP 5.2.1.
ifx.max_links | "-1" | PHP_INI_SYSTEM | Eliminata în PHP 5.2.1.
ifx.max_persistent | "-1" | PHP_INI_SYSTEM | Eliminata în PHP 5.2.1.
ifx.nullformat | "0" | PHP_INI_ALL | Eliminata în PHP 5.2.1.
ifx.textasvarchar | "0" | PHP_INI_ALL | Eliminata în PHP 5.2.1.
ignore_repeated_errors | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
ignore_repeated_source | "0" | PHP_INI_ALL | Disponibila începând cu 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 în PHP <= 4.2.3.
include_path | ".;/path/to/php/pear" | PHP_INI_ALL |
intl.default_locale | "" | PHP_INI_ALL | Disponibila începând cu PHP 5.3.0.
intl.error_level | "0" | PHP_INI_ALL | Disponibila începând cu PHP 5.3.0.
intl.use_exceptions | "0" | PHP_INI_ALL | Disponibila începând cu PHP 5.5.0.
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.
last_modified | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.5.
ldap.base_dn | NULL | PHP_INI_ALL | Eliminata în PHP 4.2.0.
ldap.max_links | "-1" | PHP_INI_SYSTEM |
log.dbm_dir | "" | PHP_INI_ALL | Eliminata în PHP 4.0.1.
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
magic_quotes_gpc | "1" | PHP_INI_PERDIR | PHP_INI_ALL în PHP <= 4.2.3. Deprecated în PHP 5.3.0. Eliminata în PHP 5.4.0.
magic_quotes_runtime | "0" | PHP_INI_ALL | Eliminata în PHP 5.4.0.
magic_quotes_sybase | "0" | PHP_INI_ALL | Eliminata în PHP 5.4.0.
mail.add_x_header | "0" | PHP_INI_PERDIR | Disponibila începând cu PHP 5.3.0.
mail.force_extra_parameters | NULL | Doar în php.ini | Disponibila începând cu PHP 5.0.0.
mail.log | "" | PHP_INI_PERDIR | Disponibila începând cu PHP 5.3.0 (PHP_INI_SYSTEM|PHP_INI_PERDIR)
mailparse.def_charset | "us-ascii" | PHP_INI_ALL | Disponibila începând cu PHP 4.1.0. Eliminata în 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 | Disponibila începând cu PHP 4.4.8 ?i PHP 5.2.3.
max_input_vars | 1000 | PHP_INI_PERDIR | Disponibila începând cu PHP 5.3.9.
max_input_time | "-1" | PHP_INI_PERDIR | Disponibila începând cu PHP 4.3.0.
mbstring.detect_order | NULL | PHP_INI_ALL | Disponibila începând cu PHP 4.0.6.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR | Disponibila începând cu PHP 4.3.0.
mbstring.func_overload | "0" | PHP_INI_SYSTEM | PHP_INI_SYSTEM în PHP <= 4.2.3; PHP_INI_SYSTEM | PHP_INI_PERDIR de la PHP 4.3 pâna la 5.2.6. Disponibila începând cu PHP 4.2.0.
mbstring.http_input | "pass" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.6.
mbstring.http_output | "pass" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.6.
mbstring.internal_encoding | NULL | PHP_INI_ALL | Disponibila începând cu PHP 4.0.6.
mbstring.language | "neutral" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.; PHP_INI_PERDIR în PHP <= 5.2.6
mbstring.script_encoding | NULL | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0. Eliminata în PHP 5.4.0. Utiliza?i în loc zend.script_encoding.
mbstring.http_output_conv_mimetypes | "^(text/|application/xhtml\+xml)" | PHP_INI_ALL | Disponibila începând cu PHP 5.3.0.
mbstring.strict_detection | "0" | PHP_INI_ALL | Disponibila începând cu PHP 5.1.2.
mbstring.substitute_character | NULL | PHP_INI_ALL | Disponibila începând cu PHP 4.0.6.
mcrypt.algorithms_dir | NULL | PHP_INI_ALL | Disponibila începând cu PHP 4.0.2.
mcrypt.modes_dir | NULL | PHP_INI_ALL | Disponibila începând cu PHP 4.0.2.
memcache.allow_failover | "1" | PHP_INI_ALL | Disponibila începând cu memcache 2.0.2.
memcache.chunk_size | "8192" | PHP_INI_ALL | Disponibila începând cu memcache 2.0.2.
memcache.default_port | "11211" | PHP_INI_ALL | Disponibila începând cu memcache 2.0.2.
memcache.hash_function | "crc32" | PHP_INI_ALL | Disponibila începând cu memcache 2.2.0.
memcache.hash_strategy | "standard" | PHP_INI_ALL | Disponibila începând cu memcache 2.2.0.
memcache.max_failover_attempts | "20" | PHP_INI_ALL | Disponibila începând cu memcache 2.1.0.
memory_limit | "128M" | PHP_INI_ALL |
mime_magic.debug | "0" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.0.0.
mime_magic.magicfile | "/path/to/php/magic.mime" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.3.0.
mongo.allow_empty_keys | 0 | PHP_INI_ALL |
mongo.allow_persistent | 1 | PHP_INI_ALL | Removed in 1.2.0
mongo.chunk_size | 262144 | PHP_INI_ALL |
mongo.cmd | "$" | PHP_INI_ALL |
mongo.default_host | "localhost" | PHP_INI_ALL |
mongo.default_port | 27017 | PHP_INI_ALL |
mongo.is_master_interval | 15 | PHP_INI_ALL | Added in 1.2.10, before 1.3.0 the default value was 60.
mongo.long_as_object | 0 | PHP_INI_ALL |
mongo.native_long | 1 | PHP_INI_ALL | Before 1.5.0, the default value was 0.
mongo.ping_interval | 5 | PHP_INI_ALL | Added in 1.2.10
mongo.utf8 | 1 | PHP_INI_ALL |
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 | Disponibila începând cu PHP 4.0.4.
mssql.charset | "" | PHP_INI_ALL | Disponibila începând cu PHP 5.1.2.
mssql.compatability_mode | "0" | PHP_INI_ALL |
mssql.connect_timeout | "5" | PHP_INI_ALL |
mssql.datetimeconvert | "1" | PHP_INI_ALL | Disponibila începând cu 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 | Disponibila începând cu 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 | Disponibila începând cu PHP 4.3.0.
mssql.textlimit | "-1" | PHP_INI_ALL |
mssql.textsize | "-1" | PHP_INI_ALL |
mssql.timeout | "60" | PHP_INI_ALL | Disponibila începând cu PHP 4.1.0.
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 | Disponibil începând cu PHP 4.3.0.
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL | Disponibil începând cu 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 în PHP <= 4.3.2. Disponibil începând cu PHP 4.3.0.
mysqli.allow_local_infile | "1" | PHP_INI_SYSTEM | Available since PHP 5.2.4.
mysqli.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqli.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqli.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
mysqli.default_port | "3306" | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_socket | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_host | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_user | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_pw | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.reconnect | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.5.
mysqli.rollback_on_cached_plink | TRUE | PHP_INI_SYSTEM | Available since PHP 5.6.0.
mysqli.cache_size | "2000" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.collect_memory_statistics | "0" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.3.0.
mysqlnd.collect_statistics | "1" | PHP_INI_ALL | Disponibila începând cu PHP 5.3.0.
mysqlnd.debug | "" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.3.0.
mysqlnd.log_mask | "0" | PHP_INI_ALL | Disponibila începând cu PHP 5.4.0.
mysqlnd.mempool_default_size | "16000" | PHP_INI_ALL | Disponibila începând cu PHP 5.4.0.
mysqlnd.net_cmd_buffer_size | "4096" | PHP_INI_ALL | Disponibila începând cu PHP 5.4.0.
mysqlnd.net_read_buffer_size | "32768" | PHP_INI_ALL | Disponibila începând cu PHP 5.3.0.
mysqlnd.net_read_timeout | "31536000" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.4.0.
mysqlnd.sha256_server_public_key | "" | PHP_INI_PERDIR | Disponibila începând cu PHP 5.5.0.
mysqlnd.trace_alloc | "" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.5.0.
mysqlnd_memcache.enable | 1 | PHP_INI_SYSTEM | Available since 1.0.0
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.config_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 |
mysqlnd_mux.enable | 0 | PHP_INI_SYSTEM |
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.collect_normalized_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.ignore_sql_comments | 1 | PHP_INI_ALL |
mysqlnd_qc.slam_defense | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.slam_defense_ttl | 30 | 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 |
mysqlnd_uh.enable | 1 | PHP_INI_SYSTEM |
mysqlnd_uh.report_wrong_types | 1 | PHP_INI_ALL |
nsapi.read_timeout | "60" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.3.
oci8.connection_class | "" | PHP_INI_ALL | Disponibila începând cu PHP 5.3 (PECL OCI8 1.3).
oci8.default_prefetch | "10" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.1.2.
oci8.events | Off | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.3 (PECL OCI8 1.3).
oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.1.2.
oci8.old_oci_close_semantics | "0" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.1.2.
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.1.2.
oci8.ping_interval | "60" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.1.2.
oci8.privileged_connect | "0" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.1.2.
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Disponibila începând cu 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_cursortype | "3" | PHP_INI_ALL | Disponibila începând cu PHP 5.3.0.
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 | Disponibila începând cu 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 | Eliminata în opendirectory 0.2.2.
opendirectory.max_refs | "-1" | PHP_INI_ALL |
opendirectory.separator | "/" | PHP_INI_ALL | Disponibila începând cu opendirectory 0.2.2.
open_basedir | NULL | PHP_INI_ALL | PHP_INI_SYSTEM în PHP < 5.2.3.
oracle.allow_persistent | "-1" | PHP_INI_ALL | Eliminata în PHP 5.1.0.
oracle.max_links | "-1" | PHP_INI_ALL | Eliminata în PHP 5.1.0.
oracle.max_persistent | "-1" | PHP_INI_ALL | Eliminata în PHP 5.1.0.
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR | Disponibila începând cu PHP 4.0.4.
pam.servicename | "php" | PHP_INI_ALL |
pcre.backtrack_limit | "1000000" | PHP_INI_ALL | Disponibila începând cu PHP 5.2.0.
pcre.recursion_limit | "100000" | PHP_INI_ALL | Disponibila începând cu PHP 5.2.0.
pcre.jit | "1" | PHP_INI_ALL | Disponibila începând cu PHP 7.0.0.
pdo.dsn.* |  | Doar în php.ini | Disponibila începând cu PHP 5.1.0.
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL | Disponibila începând cu PHP 5.1.0.
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.1.1. Aceasta facilitate învechita cu siguran?a va fi eliminata în viitor.
pfpro.defaulthost | "test-payflow.verisign.com" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.2. Eliminata în PHP 5.1.0.
pfpro.defaultport | "443" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.2. Eliminata în PHP 5.1.0.
pfpro.defaulttimeout | "30" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.2. Eliminata în PHP 5.1.0.
pfpro.proxyaddress | "" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.2. Eliminata în PHP 5.1.0.
pfpro.proxylogon | "" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.2. Eliminata în PHP 5.1.0.
pfpro.proxypassword | "" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.2. Eliminata în PHP 5.1.0.
pfpro.proxyport | "" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.2. Eliminata în PHP 5.1.0.
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.2.0.
pgsql.ignore_notice | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
pgsql.log_notice | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
pgsql.max_links | "-1" | PHP_INI_SYSTEM |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM |
phar.cache_list | "" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.4.0.
phar.extract_list | "" | PHP_INI_ALL | Disponibila începând cu phar 1.1.0.
phar.readonly | "1" | PHP_INI_ALL |
phar.require_hash | "1" | PHP_INI_ALL |
post_max_size | "8M" | PHP_INI_PERDIR | PHP_INI_SYSTEM în PHP <= 4.2.3. Disponibila începând cu PHP 4.0.3.
precision | "14" | PHP_INI_ALL |
printer.default_printer | "" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.6. Eliminata în PHP 4.1.1.
python.append_path | "" | PHP_INI_ALL |
python.prepend_path | "." | PHP_INI_ALL |
realpath_cache_size | "16K" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.1.0.
realpath_cache_ttl | "120" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.1.0.
register_argc_argv | "1" | PHP_INI_PERDIR | PHP_INI_ALL în PHP <= 4.2.3.
register_globals | "0" | PHP_INI_PERDIR | PHP_INI_ALL în PHP <= 4.2.3. Învechita în PHP 5.3.0. Eliminata în PHP 5.4.0.
register_long_arrays | "1" | PHP_INI_PERDIR | Disponibila începând cu PHP 5.0.0. Învechita în PHP 5.3.0. Eliminata în PHP 5.4.0.
report_memleaks | "1" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
report_zend_debug | "1" | PHP_INI_ALL | Disponibila începând cu PHP 5.0.0.
request_order | "" | PHP_INI_PERDIR | Adaugata în PHP 5.3.0
runkit.internal_override | "0" | PHP_INI_SYSTEM |
runkit.superglobal | "" | PHP_INI_PERDIR |
safe_mode | "0" | PHP_INI_SYSTEM | Eliminata în PHP 5.4.0.
safe_mode_allowed_env_vars | "PHP_" | PHP_INI_SYSTEM | Eliminata în PHP 5.4.0.
safe_mode_exec_dir | "" | PHP_INI_SYSTEM | Eliminata în PHP 5.4.0.
safe_mode_gid | "0" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.1.0. Eliminata în PHP 5.4.0.
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.1.0. Eliminata în PHP 5.4.0.
safe_mode_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM | Eliminata în 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 | Disponibila începând cu PHP 4.3.2. Pâna la PHP 5.3.5, valoarea implicita era 100.
session.auto_start | "0" | PHP_INI_PERDIR | PHP_INI_ALL în PHP <= 5.4.19 ?i în PHP <= 5.5.1.
session.bug_compat_42 | "1" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0. Eliminata în PHP 5.4.0.
session.bug_compat_warn | "1" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0. Eliminata în 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 | Disponibila începând cu PHP 5.2.0.
session.cookie_lifetime | "0" | PHP_INI_ALL |
session.cookie_path | "/" | PHP_INI_ALL |
session.cookie_secure | "" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.4.
session.entropy_file | "" | PHP_INI_ALL |
session.entropy_length | "0" | PHP_INI_ALL |
session.gc_dividend | "100" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0. Eliminata în PHP 4.3.2.
session.gc_divisor | "100" | PHP_INI_ALL | Disponibila începând cu 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 | Disponibila începând cu PHP 5.0.0.
session.hash_function | "0" | PHP_INI_ALL | Disponibila începând cu PHP 5.0.0.
session.lazy_write | "1" | PHP_INI_ALL | Disponibila începând cu PHP 7.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.upload_progress.cleanup | "1" | PHP_INI_PERDIR | Disponibila începând cu PHP 5.4.0.
session.upload_progress.enabled | "1" | PHP_INI_PERDIR | Disponibila începând cu PHP 5.4.0.
session.upload_progress.freq | "1%" | PHP_INI_PERDIR | Disponibila începând cu PHP 5.4.0.
session.upload_progress.min_freq | "1" | PHP_INI_PERDIR | Disponibila începând cu PHP 5.4.0.
session.upload_progress.name | "PHP_SESSION_UPLOAD_PROGRESS" | PHP_INI_PERDIR | Disponibila începând cu PHP 5.4.0.
session.upload_progress.prefix | "upload_progress_" | PHP_INI_PERDIR | Disponibila începând cu PHP 5.4.0.
session.use_strict_mode | "0" | PHP_INI_ALL | Disponibila începând cu PHP 5.5.2.
session.use_cookies | "1" | PHP_INI_ALL |
session.use_only_cookies | "1" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
session.use_trans_sid | "0" | PHP_INI_ALL | PHP_INI_ALL în PHP <= 4.2.3. PHP_INI_PERDIR în PHP < 5. Disponibila începând cu 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_PERDIR | PHP_INI_ALL în PHP 4.0.0. PHP_INI_PERDIR în PHP >= 4.0.1.
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
soap.wsdl_cache | "1" | PHP_INI_ALL | Disponibila începând cu PHP 5.1.5.
soap.wsdl_cache_dir | "/tmp" | PHP_INI_ALL | Disponibila începând cu PHP 5.0.0.
soap.wsdl_cache_enabled | "1" | PHP_INI_ALL | Disponibila începând cu PHP 5.0.0.
soap.wsdl_cache_limit | "5" | PHP_INI_ALL | Disponibila începând cu PHP 5.1.5.
soap.wsdl_cache_ttl | "86400" | PHP_INI_ALL | Disponibila începând cu PHP 5.0.0.
sql.safe_mode | "0" | PHP_INI_SYSTEM |
sqlite.assoc_case | "0" | PHP_INI_ALL | Disponibila începând cu PHP 5.0.0.
sqlite3.extension_dir | "" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.3.11.
sybase.allow_persistent | "1" | PHP_INI_ALL | PHP_INI_ALL în PHP <= 4.0.2. PHP_INI_SYSTEM în PHP <= 4.0.3.
sybase.hostname | NULL | PHP_INI_ALL | Eliminata în PHP 4.0.2.
sybase.interface_file | "" | PHP_INI_ALL |
sybase.login_timeout | "0" | PHP_INI_ALL | Eliminata în PHP 4.0.2.
sybase.max_links | "-1" | PHP_INI_ALL | PHP_INI_ALL în PHP <= 4.0.2. PHP_INI_SYSTEM în PHP <= 4.0.3.
sybase.max_persistent | "-1" | PHP_INI_ALL | PHP_INI_ALL în PHP <= 4.0.2. PHP_INI_SYSTEM în PHP <= 4.0.3.
sybase.min_client_severity | "10" | PHP_INI_ALL | Eliminata în 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 | Eliminata în PHP 4.0.2.
sybase.timeout | "0" | PHP_INI_ALL | Eliminata în PHP 4.0.2.
sybct.deadlock_retry_count | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
sybct.login_timeout | "-1" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.2.
sybct.packet_size | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.5.
sybct.timeout | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.2.
sys_temp_dir | "" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.5.0.
sysvshm.init_mem | "10000" | PHP_INI_ALL |
tidy.clean_output | "0" | PHP_INI_USER | PHP_INI_PERDIR în PHP 5. Disponibila începând cu PHP 5.0.0.
tidy.default_config | "" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.0.0.
track_errors | "0" | PHP_INI_ALL |
unserialize_callback_func | NULL | PHP_INI_ALL | Disponibila începând cu 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 în PHP <= 4.2.3.
max_file_uploads | 20 | PHP_INI_SYSTEM | Disponibila începând cu 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 | Disponibila începând cu PHP 4.0.4.
user_agent | NULL | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
user_dir | NULL | PHP_INI_SYSTEM |
user_ini.cache_ttl | "300" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.3.0.
user_ini.filename | ".user.ini" | PHP_INI_SYSTEM | Disponibila începând cu 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 în PHP <= 5.0.5.
vld.active | "0" | PHP_INI_SYSTEM |
vld.execute | "1" | PHP_INI_SYSTEM | Disponibila începând cu vld 0.8.0.
vld.skip_append | "0" | PHP_INI_SYSTEM | Disponibila începând cu vld 0.8.0.
vld.skip_prepend | "0" | PHP_INI_SYSTEM | Disponibila începând cu vld 0.8.0.
windows.show_crt_warning | "0" | PHP_INI_ALL | Disponibila începând cu PHP 5.5.0.
windows_show_crt_warning | "0" | PHP_INI_ALL | Disponibila începând cu PHP 5.4.0.
xbithack | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.5.
xdebug.auto_profile | "0" | PHP_INI_ALL | Eliminata în Xdebug 2.0.0.
xdebug.auto_profile_mode | "0" | PHP_INI_ALL | Eliminata în Xdebug 2.0.0.
xdebug.auto_trace | "0" | PHP_INI_ALL |
xdebug.collect_includes | "1" | PHP_INI_ALL | Disponibila începând cu Xdebug 2.0.0.
xdebug.collect_params | "0" | PHP_INI_ALL |
xdebug.collect_return | "0" | PHP_INI_ALL | Disponibila începând cu Xdebug 2.0.0.
xdebug.collect_vars | "0" | PHP_INI_ALL | Disponibila începând cu Xdebug 2.0.0.
xdebug.default_enable | "1" | PHP_INI_ALL | PHP_INI_SYSTEM în 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 | Disponibila începând cu 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 | Disponibila începând cu Xdebug 2.0.0.
xdebug.idekey | "" | PHP_INI_ALL | Disponibila începând cu 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 în Xdebug <= 1.2.0. Eliminata în Xdebug 2.0.0.
xdebug.profiler_aggregate | "0" | PHP_INI_PERDIR | Disponibila începând cu Xdebug 2.0.0.
xdebug.profiler_append | "0" | PHP_INI_PERDIR | Disponibila începând cu Xdebug 2.0.0.
xdebug.profiler_enable | "0" | PHP_INI_PERDIR | Disponibila începând cu Xdebug 2.0.0.
xdebug.profiler_enable_trigger | "0" | PHP_INI_PERDIR | Disponibila începând cu Xdebug 2.0.0.
xdebug.profiler_output_dir | "/tmp" | PHP_INI_PERDIR | Disponibila începând cu Xdebug 2.0.0.
xdebug.profiler_output_name | "cachegrind.out.%p" | PHP_INI_PERDIR | Disponibila începând cu Xdebug 2.0.0.
xdebug.remote_autostart | "0" | PHP_INI_ALL | Disponibila începând cu 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 | Disponibila începând cu 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 | Disponibila începând cu Xdebug 2.0.0.
xdebug.show_local_vars | "0" | PHP_INI_ALL | Disponibila începând cu Xdebug 2.0.0.
xdebug.show_mem_delta | "0" | PHP_INI_ALL | Disponibila începând cu Xdebug 2.0.0.
xdebug.trace_format | "0" | PHP_INI_ALL | Disponibila începând cu Xdebug 2.0.0.
xdebug.trace_options | "0" | PHP_INI_ALL | Disponibila începând cu Xdebug 2.0.0.
xdebug.trace_output_dir | "/tmp" | PHP_INI_ALL | Disponibila începând cu Xdebug 2.0.0.
xdebug.trace_output_name | "trace.%c" | PHP_INI_ALL | Disponibila începând cu Xdebug 2.0.0.
xdebug.var_display_max_children | "128" | PHP_INI_ALL | Disponibila începând cu Xdebug 2.0.0.
xdebug.var_display_max_data | "512" | PHP_INI_ALL | Disponibila începând cu Xdebug 2.0.0.
xdebug.var_display_max_depth | "3" | PHP_INI_ALL | Disponibila începând cu Xdebug 2.0.0.
xmlrpc_errors | "0" | PHP_INI_SYSTEM | Disponibila începând cu PHP 4.1.0.
xmlrpc_error_number | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.1.0.
xmms.path | "/usr/bin/xmms" | PHP_INI_ALL |
xmms.session | "0" | PHP_INI_ALL |
xsl.security_prefs | "44" | PHP_INI_ALL | Disponibila începând cu PHP 5.5.0.
y2k_compliance | "1" | PHP_INI_ALL | Eliminata în PHP 5.4.0.
yami.response.timeout | "5" | PHP_INI_ALL | Disponibila începând cu yami 1.0.1.
yaz.keepalive | "120" | PHP_INI_ALL |
yaz.log_mask | NULL | PHP_INI_ALL | Disponibila începând cu yaz 1.0.3.
yaz.max_links | "100" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0. Eliminata în PHP 5.0.0.
zend.assertions | "1" | PHP_INI_ALL | Disponibila începând cu PHP 7.0.0.
zend.detect_unicode | "1" | PHP_INI_ALL | Disponibila începând cu PHP 5.4.0.
zend.enable_gc | "1" | PHP_INI_ALL | Disponibila începând cu PHP 5.3.0.
zend.multibyte | "0" | PHP_INI_PERDIR | Disponibila începând cu PHP 5.4.0.
zend.script_encoding | NULL | PHP_INI_ALL | Disponibila începând cu PHP 5.4.0
zend.signal_check | "0" | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.4.0
zend.ze1_compatibility_mode | "0" | PHP_INI_ALL | Disponibila începând cu PHP 5.0.0. Eliminata în PHP 5.3.0.
zend_extension | NULL | Doar în php.ini |
zend_extension_debug | NULL | Doar în php.ini |
zend_extension_debug_ts | NULL | Doar în php.ini |
zend_extension_ts | NULL | Doar în php.ini |
zlib.output_compression | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.0.5.
zlib.output_compression_level | "-1" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.
zlib.output_handler | "" | PHP_INI_ALL | Disponibila începând cu PHP 4.3.0.

Directive php.ini
Lista sec?iunilor php.ini
Directive php.ini


Lista sec?iunilor php.ini

Aceasta lista include sec?iunile php.ini pe care le pute?i stabili în configurarea PHP pe baza de 'Host' sau 'Path'. Aceste sec?iuni sunt op?ionale.

Aceste sec?iuni nu afecteaza în mod direct PHP. Ele sunt utilizate pentru a grupa directivele php.ini ?i pentru a stabili ca ele sa ac?ioneze asupra unui host sau asupra unei cai anumite.

Aceste sec?iuni sunt utilizate doar în modul CGI/FastCGI ?i nu pot stabili directivele extension ?i zend_extension.

Sec?iuni
Denumire | Poate fi modificata | Jurnal al modificarilor
[HOST=] | PHP_INI_SYSTEM | Adaugat în PHP 5.3.0.
[PATH=] | PHP_INI_SYSTEM | Adaugat în PHP 5.3.0.

Iata o explica?ie pe scurt a directivelor de configurare.

[HOST=<host>]

Aceasta sec?iune va permite sa defini?i un set de directive php.ini care vor avea efect asupra host-ului denumit.

Example #1 Activeaza raportarea deplina a erorilor pe ecran pentru domeniul dev.

[HOST=dev.site.com]
error_reporting = E_ALL
display_errors = On

[PATH=<path>]

Aceasta sec?iune va permite sa defini?i un set de directive php.ini care vor avea efect când un script ruleaza în calea specificata.

Example #2 Adauga un script de securitate pentru regiunile protejate

[PATH=/home/site/public/secure]
auto_prepend_file=security.php

Lista directivelor php.ini
Descrierea directivelor de baza ale php.ini
Directive php.ini


Descrierea directivelor de baza ale php.ini

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.

Nota:

Valorile implicite afi?ate aici sunt utilizate când php.ini nu este încarcat; valorile pentru mediul de producere ?i dezvoltare ale php.ini pot varia.

Op?iunile Httpd

Op?iunile Httpd
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
async_send | "0" | PHP_INI_ALL | Disponibila începând cu PHP 4.2.0. Eliminata în PHP 4.3.0.

Op?iunile limbajului

Op?iuni de configurare a limbajului ?i op?iuni diverse
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
short_open_tag | "1" | PHP_INI_PERDIR | PHP_INI_ALL în PHP 4.0.0. PHP_INI_PERDIR în PHP >= 4.0.1.
asp_tags | "0" | PHP_INI_PERDIR | PHP_INI_ALL în PHP 4.0.0. Eliminata în PHP 7.0.0.
precision | "14" | PHP_INI_ALL |
serialize_precision | "17" | PHP_INI_ALL | Disponibil începând cu PHP 4.3.2. Pâna la PHP 5.3.5, valoarea implicta a fost 100.
y2k_compliance | "1" | PHP_INI_ALL | Eliminat începând cu PHP 5.4.0.
allow_call_time_pass_reference | "1" | PHP_INI_PERDIR | PHP_INI_ALL în PHP 4.0.0. Eliminat începând cu PHP 5.4.0.
disable_functions | "" | Numai în PHP_INI_SYSTEM | Disponibil începând cu PHP 4.0.1.
disable_classes | "" | numai în php.ini | Disponibil începând cu PHP 4.3.2.
exit_on_timeout | "" | PHP_INI_ALL | Disponibil începând cu PHP 5.3.0.
expose_php | "1" | numai în php.ini |
zend.multibyte | "0" | PHP_INI_ALL | Disponibil începând cu PHP 5.4.0.
zend.script_encoding | NULL | PHP_INI_ALL | Disponibil începând cu PHP 5.4.0
zend.detect-unicode | NULL | PHP_INI_ALL | Disponibil începând cu PHP 5.4.0
zend.signal_check | "0" | PHP_INI_SYSTEM | Disponibil începând cu PHP 5.4.0
zend.assertions | "1" | PHP_INI_ALL cu restric?ii | Disponibila începând cu PHP 7.0.0.
zend.ze1_compatibility_mode | "0" | PHP_INI_ALL | Disponibil începând cu PHP 5.0.0. Eliminat în PHP 5.3.0
detect_unicode | "1" | PHP_INI_ALL | Disponibil începând cu PHP 5.1.0. Redenumit în zend.detect-unicode începând cu PHP 5.4.0.

Iata o explica?ie pe scurt a directivelor de configurare.

short_open_tag boolean

Indica PHP daca forma prescurtata ( <? ?>) a etichetei de deschidere a PHP este permisa. Daca dori?i sa utiliza?i PHP în combina?ie cu XML, pute?i dezactiva aceasta op?iune pentru a utiliza <?xml ?> direct în text. În caz contrar, pute?i sa le tipari?i cu PHP, de exemplu: <?php echo '<?xml version="1.0"?>'; ?> . De asemenea, daca este dezactivata, trebuie sa utiliza?i forma lunga a etichetei de deschidere PHP (<?php ?> ).

Nota:

Aceasta directiva de asemenea afecteaza scurtatura <?= înainte de PHP 5.4.0, care este identica cu <? echo. Utilizarea acestei scurtaturi necesita ca short_open_tag sa fie activata. Începând cu PHP 5.4.0, <?= este întotdeauna disponibila.

asp_tags boolean
Permite utilizarea etichetelor de tip ASP <% %> în plus fa?a de etichetele obi?nuite <?php ?>. Aceasta include ?i scurtatura pentru tiparul valorii variabilei <%= $value %>. Pentru mai multe informa?ii accesa?i Evadarea din HTML.

Istoricul schimbarilor pentru asp_tags
Versiune | Descriere
7.0.0 | Eliminat din PHP.

precision integer
Numarul cifrelor semnificative afi?ate în numerele cu virgula flotanta.
serialize_precision integer
Numarul cifrelor semnificative memorate la serializarea numerele cu virgula flotanta.
y2k_compliance boolean
For?eaza conformarea cu anul 2000 (va cauza probleme cu navigatoarele nonconformante)
allow_call_time_pass_reference boolean

Afi?area avertizarii în cazul când argumentele sunt transmise prin referin?a în timpul apelarii func?iei. Metoda încurajata de specificare a argumentelor ce trebuie transmise prin referin?a este în declara?ia func?iei. Sunte?i încurajat sa încerca?i sa dezactiva?i aceasta op?iune ?i sa ave?i grija ca scripturile sa lucreze în mod normal cu ea, pentru a va asigura ca ele vor func?iona cu versiunile viitoare ale limbajului (ve?i primi o avertizare de fiecare data când utiliza?i aceasta facilitate).

Transmiterea argumentelor prin referin?a la momentul apelarii func?iei a fost descurajata din motivul cura?eniei codului-sursa. O func?ie poate sa-?i modifice argumentul într-un mod nedocumentat daca nu a declarat ca argumentul este transmis prin referin?a. Pentru a evita efecte secundare este mai bine de a specifica care argumente sunt transmise prin referin?a numai în declara?ia func?iei.

Vezi de asemenea ?i References Explained.

Jurnal de schimbari pentru allow_call_time_pass_reference
Versiune | Descriere
5.4.0 | Eliminat din PHP.
5.3.0 | Emite o eroare de nivel E_DEPRECATED.
5.0.0 | Învechit, ?i genereaza o eroare de nivel E_COMPILE_WARNING.

expose_php boolean

Expune în lume faptul ca PHP este instalat pe server, ceea ce include versiunea PHP în antetul HTTP (de ex. X-Powered-By: PHP/5.3.7). Anterior versiunii PHP 5.5.0 guid-urile logotipului PHP sunt de asemenea expuse, astfel încât adaugându-le la URL, scriptul dvs. va afi?a logotipul corespunzator (de ex. » http://www.php.net/?=PHPE9568F34-D428-11d2-A769-00AA001ACF42). Aceasta de asemenea afecteaza informa?iile afi?ate de phpinfo(); daca parametrul e dezactivat, logotipul PHP ?i informa?iile despre autori nu vor fi afi?ate.

Nota:

Începând cu PHP 5.5.0 aceste guid-uri ?i func?ia php_logo_guid() au fost eliminate din PHP ?i guid-urile sunt înlocuite cu URI-uri de date. Astfel, accesânt logotipul PHP prin adaugarea guid-ului la URL nu mai func?ioneaza. În mod similar, dezactivarea expose_php nu va afecta afi?area logotipului PHP în phpinfo().

Vezi de asemenea php_logo_guid() ?i phpcredits().

disable_functions string

Aceasta directiva va permite sa dezactiva?i anumite func?ii din motive de securitate. Ea con?ine o lista a denumirilor func?iilor, separate prin virgula. disable_functions nu este afectata de Modul securizat.

Doar internal functions poate fi dezactivata utilizând aceasta directiva. Func?iile definite de utilizator nu sunt afectate.

Aceasta directiva trebuie sa fie stabilita în php.ini De exemplu nu pute?i stabili aceasta în httpd.conf.

disable_classes string
Aceasta directiva va permite sa dezactiva?i anumite clase din motive de securitate. Ea con?ine o lista a denumirilor claselor, separate prin virgula. disable_classes nu este afectata de Modul securizat. Aceasta directiva trebuie sa fie stabilita în php.ini De exemplu nu pute?i stabili aceasta în httpd.conf.
zend.assertions integer
Când este stabilita în 1, va fi generat ?i executat cod de aser?iune (în regimul de dezvoltare). Când este stabilita în 0, va fi generat cod de aser?iune, dar nu va fi executat la rulare. Când este stabilit în -1, nu va fi generat cod de aser?iune, facând ca aser?iunile sa fie cu cost nul (în regimul de produc?ie).

Nota:

Daca un proces e lansat în regim de produc?ie, zend.assertions nu poate fi schimbata în timpul rularii, deoarece codul pentru aser?iuni nu a fost generat.

Daca un proces e lansat în regim de dezvoltare, zend.assertions nu poate fi stabilita în -1 în timpul rularii.

zend.ze1_compatibility_mode boolean

Activeaza modul de compatibilitate cu Zend Engine 1 (PHP 4). Aceasta afecteaza clonarea, transformarea (obiectele fara proprieta?i se transforma în FALSE sau 0), ?i compara?ia obiectelor. În acest mod, obiectele sunt transmise prin valoare, dar nu prin referin?a, cum e stabilit implicit.

Accesa?i de asemenea sec?iunea întitulata Migrarea de la PHP 4 la PHP 5.

Avertizare

Aceasta facilitate este ÎNVECHITA ?i ELIMINATA începând cu PHP 5.3.0.

zend.multibyte boolean

Activeaza interpretarea fi?ierelor sursa cu seturi de caractere multi-byte. Activarea zend.multibyte este necesara pentru a utiliza codificari ale caracterelor precum SJIS, BIG5, etc. care con?in caractere speciale în datele ?irurilor de caractere multi-byte. Codificarile compatibile cu ISO-8859-1, precum UTF-8, EUC, etc. nu necesita aceasta op?iune.

Pentru a activa zend.multibyte este necesar ca extensia mbstring sa fie disponibila.

zend.script_encoding string

Aceasta valoarea va fi folosita numa daca directiva declare(encoding=...) apare la începutul scriptului. Când este utilizata o codificare incompatibila cu ISO-8859-1, trebuie utilizate atât zend.multibyte, cât ?i zend.script_encoding.

?irurile de caractere literale vor fi transliterate din zend.script_enconding în mbstring.internal_encoding, ca ?i cum ar fi fost apelata mb_convert_encoding().

zend.detect_unicode boolean

Verifica prezen?a BOM (Byte Order Mark) ?i daca fi?ierul con?ine caractere multioctet valide. Aceasta detectare este efectuata înaintea procesarii __halt_compiler(). Este disponibila doar în modul Zend Multibyte.

zend.signal_check boolean

Verifica semnale suprascrise la încheierea scriptului.

exit_on_timeout boolean

Aceasta directiva folosita cu Apache1 ?i mod mod_php for?eaza terminarea copilului Apache daca în scriptul sa atins limita de execu?ie. Acea limita causa un apel catre longjmp() î Apache1 care ar putea lasa unele extensii într-o stare inconsisenta. Prin terminarea procesului orice blocare pe memorie va fi eliminata.

Limitele resurselor

Limitele resurselor
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
memory_limit | "128M" | PHP_INI_ALL | "8M" înainte de PHP 5.2.0, "16M" în PHP 5.2.0

Iata o explica?ie pe scurt a directivelor de configurare.

memory_limit integer

Aceata stabile?te marimea maxima a memoriei în bai?i, pe care un script o poate aloca. Astfel se evita situa?ia când scripturile scrise rau consuma toata memoria disponibila pe server. Atrage?i aten?ia ca pentru a dezactiva limita de memorie, trebuie sa stabili?i aceasta directiva la valoarea -1.

Înainte de PHP 5.2.1, pentru a utiliza aceasta directiva, ea trebuia sa fi fost activata la momentul compilarii indicând --enable-memory-limit în linia de configurare. Acest fanion indicat la momentul compilarii era de asemenea necesar pentru a defini func?iile memory_get_usage() ?i memory_get_peak_usage() anterior versiunii 5.2.1.

În cazul utilizarii unui integer, valoarea este masurata în octe?i. De asemenea poate fi utilizata nota?ia prescurtata, dupa cum este descris în acest FAQ.

Accesa?i de asemenea: max_execution_time.

Reglarea performan?ei

Reglarea performan?ei
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
realpath_cache_size | "16K" | PHP_INI_SYSTEM | Disponibil începând cu PHP 5.1.0.
realpath_cache_ttl | "120" | PHP_INI_SYSTEM | Disponibil începând cu PHP 5.1.0.

Iata o explica?ie pe scurt a directivelor de configurare.

realpath_cache_size integer

Determina marimea cache-ului cailor folosite de PHP. Aceasta valoare trebuie marita pe sistemele unde PHP deschide multe fi?iere, pentru a reflecta cantitatea opera?iunilor efectuate cu fi?iere.

Dimensiunea reprezinta numarul total de octe?i din ?irurile cu cai stocate, plus dimensiunea datelor asociate cu înregistrarea cache. Aceasta înseamna ca pentru a stoca cai mai lungi în memoria cache, dimensiunea acesteia trebuie sa fie mai mare. Aceasta valoare nu controleaza direct numarul de cai distincte, care pot fi stocate în memoria cache.

Dimensiunea necesara pentru datele înregistrarii din memoria cache este dependenta de sistem.

realpath_cache_ttl integer

Durata de timp (în secunde) pentru a pastra în cache informa?ia despre calea unui fi?ier sau director. Pentru sisteme cu fi?iere care se modifica rar, considera?i marirea acestei valori.

Manipularea datelor

Op?iunile de configurare pentru manipularea datelor
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
arg_separator.output | "&" | PHP_INI_ALL | Disponibil începând cu PHP 4.0.5.
arg_separator.input | "&" | PHP_INI_PERDIR | Disponibil începând cu PHP 4.0.5.
variables_order | "EGPCS" | PHP_INI_PERDIR | PHP_INI_ALL în PHP <= 5.0.5.
request_order | "" | PHP_INI_PERDIR | Disponibil începând cu PHP 5.3.0
auto_globals_jit | "1" | PHP_INI_PERDIR | Disponibil începând cu PHP 5.0.0.
register_globals | "0" | PHP_INI_PERDIR | PHP_INI_ALL în PHP <= 4.2.3. Eliminat începând cu PHP 5.4.0.
register_argc_argv | "1" | PHP_INI_PERDIR | PHP_INI_ALL în PHP <= 4.2.3.
register_long_arrays | "1" | PHP_INI_PERDIR | Disponibil începând cu PHP 5.0.0. Defavorizat în PHP 5.3.0. Eliminat începând cu PHP 5.4.0.
enable_post_data_reading | "1" | PHP_INI_PERDIR | Available since PHP 5.4.0
post_max_size | "8M" | PHP_INI_PERDIR | PHP_INI_SYSTEM în PHP <= 4.2.3. Disponibil începând cu PHP 4.0.3.
auto_prepend_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL în PHP <= 4.2.3.
auto_append_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL în PHP <= 4.2.3.
default_mimetype | "text/html" | PHP_INI_ALL |
default_charset | "UTF-8" | PHP_INI_ALL | Are valoarea implicita "UTF-8" începând cu PHP >= 5.6.0; vida pentru PHP < 5.6.0.
always_populate_raw_post_data | "0" | PHP_INI_PERDIR | PHP_INI_ALL în PHP <= 4.2.3. Disponibil începând cu PHP 4.1.0. Eliminat în PHP 7.0.0.

Iata o explica?ie pe scurt a directivelor de configurare.

arg_separator.output string

Separatorul utilizat în URL-urile generate de PHP pentru a separa argumentele.

arg_separator.input string

Lista separator(arelor) folosite de PHP pentru a analiza ?i transfera URL-urile de intrare în variabile.

Nota:

Fiecare caracter din aceasta directiva este considerat separator!

variables_order string

Stabile?te ordinea prelucrarii variabileleor EGPCS (Environment, Get, Post, Cookie ?i Server). Spre exemplu, daca variables_order este stabilit în "SP", atunci PHP va crea superglobals $_SERVER ?i $_POST, dar nu va crea $_ENV, $_GET ?i $_COOKIE. Stabilirea valorii "" înseamna ca nici un superglobals nu va fi stabilit.

Daca directiva învechita register_globals este stabilita, atunci variables_order de asemenea configureaza ordinea în care variabilele ENV, GET, POST, COOKIE ?i SERVER sunt populate în domeniul global. Deci, spre exemplu, daca variables_order este stabilit în "EGPCS", register_globals este activat, ?i ambele $_GET['action'] ?i $_POST['action'] sunt stabilite, atunci $action va con?ine valoarea $_POST['action'] deoarece P urmeaza dupa G în valoarea directivei din exemplul dat.

Avertizare

În ambele SAPI-uri CGI ?i FastCGI, $_SERVER este de asemenea populat cu valori din mediu; S este întotdeauna echivalent cu ES independent de amplasarea E în aceasta directiva.

Nota:

Con?inutul ?i ordinea valorilor din variabila $_REQUEST sunt de asemenea afectate de aceasta directiva.

request_order string

Aceasta directuva descrie ordinea în care PHP PHP înregistreaza variabilele GET, POST ?i Cookie în tabloul _REQUEST. Înregistrarea este efectuata de la stânga la dreapta, valorile noi se suprapun peste cele vechi.

Daca aceasta directiva nu este stabilita, variables_order este utilizata pentru a umple con?inutul $_REQUEST.

Observa?i ca fi?ierul php.ini din distributivul original nu con?ine 'C' pentru cookies din motive de securitate.

auto_globals_jit boolean

Când este activata, variabilele SERVER ?i ENV sunt create prima data când sunt utilizate (Exact la timp - Just In Time) în loc sa fie create la lansarea scriptului. Daca aceste variabile nu sunt utilizate în script, atunci activarea acestei directive va duce la o cre?tere a performan?ei.

Directivele PHP register_globals, register_long_arrays ?i register_argc_argv trebuie sa fie dezactivate pentru ca aceasta directiva sa aiba efect. Începând cu PHP 5.1.3 nu este necesar de a avea register_argc_argv dezactivat.

Avertizare

Utilizarea variabilelor SERVER ?i ENV este verificata în timpul compilarii de aceea utilizarea lor prin de ex. variabile variabile nu va cauza ini?ializarea lor.

register_globals boolean

Indica daca variabilele EGPCS (Environment, GET, POST, Cookie, Server) trebuie sa fie înregistrate ca variabile globale, sau nu.

Începând cu » PHP 4.2.0, aceasta directiva are valoarea implicita off.

Va rugam sa citi?i capitolul ce ?ine de securitate Utilizarea register_globals pentru mai multe informa?ii.

Va rugam sa atrage?i aten?ia ca register_globals nu poate fi stabilit în timpul execu?iei ( ini_set()). Cu toate acestea pute?i utiliza .htaccess daca serverul permite aceasta, dupa cum e descris anterior. Un exemplu de înregistrare .htaccess: php_flag register_globals off.

Nota:

register_globals este afectata de directiva variables_order.

Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

register_argc_argv boolean
Indica PHP daca trebuie declarate variabilele argv & argc (care ar con?ine informa?ia GET). Accesa?i de asemenea linia de comanda.
register_long_arrays boolean
Indica PHP daca trebuie înregistrate, sau nu $HTTP_*_VARS - variabilele predefinite lungi învechite. Când este stabilita în On (implicit), variabilele PHP predefinite lungi, cumar fi $HTTP_GET_VARS vor fi definite. Daca nu le utiliza?i, este recomandabil sa le dezactiva?i din motivul performan?ei. În loc, utiliza?i tablourile superglobale, cum ar fi $_GET. Aceasta directiva a devenit disponibila în PHP 5.0.0.
Avertizare

Aceasta facilitate a fost ÎNVECHITA începând cu PHP 5.3.0 ?i ELIMINATA începând cu PHP 5.4.0.

enable_post_data_reading boolean
Oprind aceasta op?iuneva face ca $_POST ?i $_FILES sa nu fie populate. Singura modalitate pentru a citi datele venite prin $_POST va fi prin wrapperul php://input. Acest lucru poate fi util în cazul cererilor prin proxy sau pentru a procesa datele POST într-o maniera eficienta din punctul de vedere al memoriei consumate.
post_max_size integer
Stabile?te marimea maxima permisa a datelor "post". Aceasta marime de asemenea afecteaza încarcarea fi?ierelor. Pentru a încarca fi?iere voluminoase aceasta valoare trebuie sa fie mai mare decât upload_max_filesize. Vorbind la general, memory_limit ar trebui sa fie mai mare decât post_max_size. În cazul utilizarii unui integer, valoarea este masurata în octe?i. De asemenea poate fi utilizata nota?ia prescurtata, dupa cum este descris în acest FAQ. Daca marimea datelor post este mai mare decât post_max_size, atunci $_POST ?i $_FILES (variabile superglobale) sunt vide. Acest fapt poate fi depistat prin diferite metode, de ex. transmi?ând o valoare variabilei $_GET în scriptul care proceseaza datele, de ex. <form action="edit.php?processed=1">, ?i apoi verificând daca $_GET['processed'] este stabilit.

Nota:

PHP permite prescurtari pentru valori în bai?i, inclusiv K (kilo), M (mega) ?i G (giga). PHP va efectua convertirea automat daca ve?i utiliza una din acestea. Fi?i atent sa nu depa?i?i limita de 32 bi?i pentru numere întregi cu semn (daca utiliza?i versiuni pe 32 de bi?i) deoarece aceasta va cauza e?uarea script-ului dumneavoastra.

Istoricul schimbarilor pentru post_max_size
Versiune | Descriere
5.3.4 | post_max_size = 0 nu va dezactiva limita în caz daca tipul con?inutului este application/x-www-form-urlencoded sau daca nu este înregistrat cu PHP.
5.3.2 , 5.2.12 | Permite dimensiunea nelimitata a datelor transmise prin post prin stabilirea post_max_size în 0.

auto_prepend_file string

Specifica denumirea unui fi?ier care va fi automat analizat ?i executat înainte de fi?ierul principal. Acest fi?ier este inclus, ca ?i cum ar fi fost apelat cu func?ia require, deci include_path este utilizat.

Valoarea speciala none anuleaza executarea automata.

auto_append_file string

Specifica denumirea unui fi?ier care va fi automat analizat ?i executat dupa fi?ierul principal. Acest fi?ier este inclus, ca ?i cum ar fi fost apelat cu func?ia require, deci include_path este utilizat.

Valoarea speciala none anuleaza executarea automata.

Nota: Daca scriptul este terminat cu exit(), executarea automata nu va avea loc.

default_mimetype string

Implicit PHP va afi?a un tip de media utilizând antetul Content-Type. Pentru a dezactiva aceasta, stabili?i o valoare vida pentru op?iune.

Tipul de media implicit pentru PHP este text/html.

default_charset string

În PHP 5.6 ?i ulterior, "UTF-8" este valoarea implicita ?i aceasta este folosita ca codare implicita a caracterelor pentru func?iile htmlentities(), html_entity_decode() ?i htmlspecialchars() daca parametrul encoding este omis. Valoarea default_charset de asemenea va fi utilizata pentru a stabili codarea implicita a caracterelor pentru func?iile iconv daca op?iunile de configurare iconv.input_encoding, iconv.output_encoding ?i iconv.internal_encoding nu sunt stabilite, ?i pentru func?iile mbstring daca op?iunile de configurare mbstring.http_input mbstring.http_output mbstring.internal_encoding nu sunt stabilite.

Toate versiunile PHP vor folosi aceasta valoare în calitate de set de caractere în antetul implicit Content-Type transmis de PHP daca antetul nu este suprascris de un apel al func?iei header().

Stabilirea valorii vide a parametrului default_charset nu este recomandata.

input_encoding string

Disponibil începând cu PHP 5.6.0. Acest parametru e utilizat pentru module multi-byte, precum mbstring ?i iconv. Implicit valoarea e vida.

output_encoding string

Disponibil începând cu PHP 5.6.0. Acest parametru e utilizat pentru module multi-byte, precum mbstring ?i iconv. Implicit valoarea e vida.

internal_encoding string

Disponibil începând cu PHP 5.6.0. Acest parametru e utilizat pentru module multi-byte, precum mbstring ?i iconv. Implicit valoarea e vida. Daca este utilizat default_charset vid.

always_populate_raw_post_data mixed
Avertizare

Aceasta facilitate este ÎNVECHITA începând cu PHP 5.6.0 ?i ELIMINATA începând cu PHP 7.0.0.

Daca este stabilit în TRUE, PHP întotdeauna va popula $HTTP_RAW_POST_DATA cu con?inutul neprelucrat al datelor POST. În caz contrar, variabila e populata doar când tipul MIME al datelor nu este cunoscut.

Metoda preferabila de accesare a datelor POST neprelucrate este php://input, ?i $HTTP_RAW_POST_DATA este descurajata în PHP 5.6.0 ?i ulterior. Stabilirea always_populate_raw_post_data în -1 va activa noul comportament, care va fi implementat într-o versiune viitoare a PHP, conform caruia $HTTP_RAW_POST_DATA nici nu este definita.

Indiferent de setare, $HTTP_RAW_POST_DATA nu este disponibila cu enctype="multipart/form-data".

Accesa?i de asemenea: magic_quotes_gpc, magic_quotes_runtime ?i magic_quotes_sybase.

Caile ?i directoarele

Op?iunile de configurare a cailor ?i directoarelor
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
include_path | ".;/calea/spre/php/pear" | PHP_INI_ALL |
open_basedir | NULL | PHP_INI_ALL | PHP_INI_SYSTEM în PHP < 5.3.0
doc_root | NULL | PHP_INI_SYSTEM |
user_dir | NULL | PHP_INI_SYSTEM |
extension_dir | "/calea/spre/php" | PHP_INI_SYSTEM |
extension | NULL | numai în php.ini |
zend_extension | NULL | numai în php.ini |
zend_extension_debug | NULL | numai în php.ini |
zend_extension_debug_ts | NULL | numai în php.ini |
zend_extension_ts | NULL | numai în php.ini |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM | Disponibil începând cu PHP 5.2.0.
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM | Disponibil începând cu PHP 4.3.0. PHP_INI_ALL anterior versiunii PHP 5.2.1.
cgi.force_redirect | "1" | PHP_INI_SYSTEM | Disponibil începând cu PHP 4.2.0. PHP_INI_ALL anterior versiunii PHP 5.2.1.
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM | Disponibil începând cu PHP 4.2.0. PHP_INI_ALL anterior versiunii PHP 5.2.1.
cgi.rfc2616_headers | "0" | PHP_INI_ALL | Disponibil începând cu PHP 4.3.0.
fastcgi.impersonate | "0" | PHP_INI_SYSTEM | Disponibil începând cu PHP 4.3.0. PHP_INI_ALL anterior versiunii PHP 5.2.1.
fastcgi.logging | "1" | PHP_INI_SYSTEM | Disponibil începând cu PHP 4.3.0. PHP_INI_ALL anterior versiunii PHP 5.2.1.

Iata o explica?ie pe scurt a directivelor de configurare.

include_path string

Specifica o lista de directoare, unde func?iile require, include, fopen(), file(), readfile() ?i file_get_contents() vor cauta fi?ierele. Formatul este ca ?i în cazul variabilei de mediu a sistemului PATH: o lista de directoare separate prin doua puncte în Unix, sau punct ?i virgula în Windows.

PHP ia în considera?ie fiecare înregistrare separata din calea de includere atunci când cauta fi?ierele spre a fi incluse. El va verifica prima cale ?i daca nu-l va gasi va cauta în urmatoarea cale ?i a?a pâna când fi?ierul este localizat, sau va întoarce o avertizare sau o eroare. Pute?i sa stabili?i sau sa modifica?i calea de includere în timpul rularii utilizând func?ia set_include_path().

Example #1 include_path în Unix

include_path=".:/php/includes"

Example #2 include_path în Windows

include_path=".;c:\php\includes"

Utilizarea unui . în calea de includere permite includeri relative, deoarece desemneaza directorul curent. Însa este mai eficient de a utiliza în mod explicit include './file' decât de a impune PHP sa verifice permanent toate fi?ierele din directorul curent ce vor fi incluse.

Nota:

Variabilele ENV sunt de asemenea accesibile în fi?iere .ini. Astfel, este posibil de a ob?ine referin?a catre directorul home utilizând ${LOGIN} ?i ${USER}.

Variabilele de mediu pot varia în diferite API ale serverelor, deoarece mediile pot fi diferite.

Example #3 include_path în Unix, utilizând variabile de mediu ${USER}

include_path = ".:${USER}/pear/php"

open_basedir string

Limiteaza fi?ierele ce pot fi accesate de PHP în arborele directoarelor specificat, inclusiv ?i însu?i fi?ierul. Aceasta directiva NU este afectata de activarea sau dezactivarea Modului securizat.

Când un script încearca sa acceseze sistemul de fi?iere, de exemplu utilizând include sau fopen(), se verifica amplasarea fi?ierului. Daca fi?ierul este în afara arborelui de directoare specificat, PHP va refuza sa-l acceseze. Toate legaturile simbolice sunt rezolvate, de aceea nu este posibil de a evita aceasta restric?ie cu un symlink. Daca fi?ierul nu exista atunci symlink-ul nu poate fi rezolvat ?i denumireas fi?ierului este comparata cu open_basedir (rezolvata).

open_basedir poate afecta mai mult decât func?iile sistemului de fi?iere; spre exemplu daca MySQL este configurat sa utilizeze driverele mysqlnd, atunci LOAD DATA INFILE va fi afectat de open_basedir . Majoritatea func?ionalita?ii extinse a PHP utilizeaza open_basedir în acest mod.

Valoarea speciala . indica ca directorul de lucru al script-ului va fi utilizat în calitate de director de baza. Aceasta însa este un pic periculos, deoarece directorul de lucru al script-ului poate fi u?or schimbat cu chdir().

În httpd.conf, open_basedir poate fi deconectata (de ex. pentru unele gazde virtuale) în acela?i mod ca ?i orice alta directiva de configurare astfel: "php_admin_value open_basedir none".

În Windows, denumirile directoarelor trebuie separate cu punct ?i virgula. În celelalte sisteme denumirile directoarelor trebuie separate cu doua puncte. În calitate de modul Apache, caile pentru open_basedir din directoarele-parinte sunt acum mo?tenite automat.

Restric?ia specificata cu open_basedir este de fapt un prefix, ?i nu o denumire a directorului. Aceasta înseamna ca "open_basedir = /dir/incl" de asemenea permite accesul la "/dir/include" ?i "/dir/incls", daca acestea exista. Atunci când dori?i sa restric?iona?i accesul doar la un anumit director, adauga?i un slash la sfâr?it. De exemplu: open_basedir = /dir/incl/

Modul implicit este de a permite deschiderea tuturor fi?ierelor.

Nota:

Începând cu PHP 5.3.0 open_basedir poate fi restrânsa în timpul rularii. Aceasta înseamna ca daca open_basedir este stabilita la /www/ în php.ini, un script poate restrânge configura?ia la /www/tmp/ în timpul rularii cu ini_set(). Când se listeaza câteva directoare, pute?i utiliza constanta PATH_SEPARATOR ca separator, indiferent de sistemul de operare.

doc_root string

"Directorul root" al PHP de pe server. Este utilizat numai daca nu este vid. Daca PHP este configurat cu modul securizat, nici un fi?ier din afara acestui director nu este servit. Daca PHP nu a fost compilat cu FORCE_REDIRECT, trebuie sa stabili?i doc_root daca rula?i PHP în calitate de CGI cu orice web server (în afara de IIS). Alternativa este de a utiliza configura?ia cgi.force_redirect de mai jos.

user_dir string

Denumirea de baza a directorului utilizat într-un director de baza al utilizatorului pentru fi?ierele PHP, spre exemplu public_html.

extension_dir string

În care director PHP ar trebui sa caute extensiile încarcate dinamic. Accesa?i de asemenea: enable_dl, ?i dl().

extension string

Care extensie dinamica trebuie încarcata atunci când PHP este lansat.

zend_extension string

Denumirea extensiei Zend încarcabile dinamic (spre exemplu APD) ce va fi încarcata la startarea PHP.

zend_extension_debug string

Varianta zend_extension pentru extensii compilate cu informa?ii de debug.

zend_extension_debug_ts string

Varianta zend_extension pentru extensii compilate cu informa?ii de debug ?i protec?ia firelor de execu?ie.

zend_extension_ts string

Varianta zend_extension pentru extensii compilate cu protec?ia firelor de execu?ie.

cgi.check_shebang_line boolean

Controleaza daca PHP în varianta CGI verifica existen?a liniei ce începe cu #! (shebang) la începutul scriptului ce va fi rulat. Aceasta linie poate fi necesara daca script-ul sus?ine rularea atât în calitate de script independent, cât ?i ca PHP CGI. PHP în mod CGI trece peste aceasta linie ?i ignora con?inutul ei daca aceasta directiva e activata.

cgi.fix_pathinfo boolean

Ofera sus?inerea reala a PATH_INFO/ PATH_TRANSLATED pentru CGI. Comportamentul precedent al PHP era de a stabili PATH_TRANSLATED în SCRIPT_FILENAME ?i de a nu analiza care este PATH_INFO. Pentru mai multe informa?ii despre PATH_INFO, vede?i specificarile CGI. Stabilirea valorii 1 va cauza PHP CGI sa-?i corecteze caile pentru a se conforma specifica?iilor. Stabilirea valorii zero cauzeaza PHP sa se comporte ca mai înainte. Valoarea implicita este zero. Dumneavoastra ar trebui sa va corecta?i script-urile ca sa utilizeze SCRIPT_FILENAME ?i nu PATH_TRANSLATED.

cgi.force_redirect boolean

cgi.force_redirect este necesar pentru a oferi securitate la rularea PHP în calitate de CGI cu majoritatea serverelor web. Daca nu este definita, PHP implicit activeaza aceasta directiva. Pute?i sa o dezectiva?i la propriul risc.

Nota:

Utilizatorii Windows: Când utiliza?i IIS, aceasta op?iune trebuie dezactivata. Acela?i lucru se aplica ?i pentru OmniHTTPD sau Xitami.

cgi.redirect_status_env string

Daca cgi.force_redirect este activata ?i nu rula?i web server-ele Apache sau Netscape (iPlanet), s-ar putea sa fie necesar sa stabili?i o variabila de mediu, pe care PHP o va cauta pentru a ?ti daca e OK de a continua execu?ia.

Nota:

Stabilirea acestei variabile ar putea cauza probleme se securitate, întâi clarifica?i ce dori?i sa realiza?i.

cgi.rfc2616_headers int

Indica PHP ce tip de antete sa utilizeze la trimiterea codului de raspuns HTTP. Daca este stabilita în 0, PHP trimite un antet "Status:", conform » RFC 3875, care este sus?inut de Apache ?i alte servere web. Când aceasta op?iune este stabilita în 1, PHP va trimite antete ce se conformeaza cu » RFC 2616.

Daca aceasta op?iune este activata ?i rula?i PHP într-un mediu CGI (de ex. PHP-FPM), nu trebuie sa utiliza?i antete de raspuns HTTP conform RFC 2616, în loc trebuie sa utiliza?i echivalentele lor conform RFC 3875, de ex. în loc de header("HTTP/1.0 404 Not found"); trebuie sa utiliza?i header("Status: 404 Not Found");

Schimba?i valoarea din 0 numai daca cunoa?te?i ce face?i.

fastcgi.impersonate string

FastCGI sub IIS (pe sisteme bazate pe WINNT) sus?in posibilitatea de a juca rolul tichetelor de securitate ale clientului apelant. Aceasta îi permite IIS sa defineasca contextul de securitate sub care ruleaza cererea. mod_fastcgi sub Apache nu sus?ine în prezent (03/17/2002) aceasta facilitate. Stabili?i valoarea 1 la rularea sub IIS. Implicit este zero.

fastcgi.logging boolean

Activeaza logarea SAPI la utilizarea FastCGI. Impicit logarea este activata.

Încarcarea fi?ierelor

Op?iunile de configurare a încarcarii fi?ierelor
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
file_uploads | "1" | PHP_INI_SYSTEM | PHP_INI_ALL în PHP <= 4.2.3. Disponibil începând cu PHP 4.0.3.
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
max_input_nesting_level | 64 | PHP_INI_PERDIR | Disponibil începând cu PHP 5.3.9.
max_input_vars | 1000 | PHP_INI_PERDIR | Disponibil începând cu PHP 5.3.9.
upload_max_filesize | "2M" | PHP_INI_PERDIR | PHP_INI_ALL în PHP <= 4.2.3.
max_file_uploads | 20 | PHP_INI_SYSTEM | Disponibila începând cu PHP 5.2.12.

Iata o explica?ie pe scurt a directivelor de configurare.

file_uploads boolean

Daca sa permita, sau nu încarcari de fi?iere prin HTTP. Accesa?i de asemenea directivele upload_max_filesize, upload_tmp_dir ?i post_max_size.

upload_tmp_dir string

Directorul temporar utilizat pentru stocarea fi?ierelor la încarcare. Trebuie sa aiba drept de înscriere pentru utilizatorul cu care ruleaza PHP. Daca nu este specificat, PHP va folosi directorul implicit al sistemului.

Daca în directorul specificat aici nu este posibilitate de a înscrie, PHP revine la directorul temporar implicit al sistemului. Daca open_basedir este activat, atunci trebuie permisa înscrierea în directorul temporar de sistem pentru ca încarcarea sa se efectueze cu succes.

upload_max_filesize integer

Marimea maxima a unui fi?ier încarcat.

În cazul utilizarii unui integer, valoarea este masurata în octe?i. De asemenea poate fi utilizata nota?ia prescurtata, dupa cum este descris în acest FAQ.
max_file_uploads integer

Numarul maxim de fi?iere permise de a fi încarcate simultan. Începând cu PHP 5.3.4, câmpurile pentru încarcare necompletate nu sunt luate în considerare la verificarea acestei limite.

SQL general

Op?iunile de configurare ale SQL general
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
sql.safe_mode | "0" | PHP_INI_SYSTEM |

Iata o explica?ie pe scurt a directivelor de configurare.

sql.safe_mode boolean

Daca este activata, func?iile de conectare la baze de date care utilizeaza valori implicite, le vor utiliza pe acestea, în locul argumentelor furnizate de utilizator. Pentru a afla detalii despre valorile implicite, accesa?i documenta?ia func?iei de conectare pentru baza de date respectiva.

Specifice Windows

Op?iuni de configurare specifice Windows
Denumire | Valoare implicita | Poate fi modificata | Jurnal al modificarilor
windows_show_crt_warning | "0" | PHP_INI_ALL | Disponibil începând cu PHP 5.4.0.

Iata o explica?ie pe scurt a directivelor de configurare.

windows_show_crt_warning boolean

Aceasta directiva afi?eaza aten?ionari Windows CRT la activare. Aceste anten?ionari erau afi?ate implicit pâna în versiunea PHP 5.4.0.

Lista sec?iunilor php.ini
Lista/Categoriile extensiilor
Directive php.ini


Lista/Categoriile extensiilor

Cuprins

  • În ordine alfabetica
  • Apartenen?a
  • Statutul

Aceasta anexa categorizeaza peste 150 extensii documentate în Manualul PHP dupa câteva criterii.

Descrierea directivelor de baza ale php.ini
În ordine alfabetica
Anexe


În ordine alfabetica

  • Apache
  • APC
  • APCu
  • APD
  • Arrays
  • BBCode
  • BC Math
  • bcompiler
  • BLENC
  • Bzip2
  • Cairo
  • Calendar
  • chdb
  • Classkit
  • Classes/Objects
  • COM
  • Crack
  • CSPRNG
  • Ctype
  • CUBRID
  • cURL
  • Cyrus
  • Date/Time
  • DBA
  • dBase
  • DB++
  • dbx
  • Direct IO
  • Directorii
  • DOM
  • Data Structures
  • Eio
  • Enchant
  • Error Handling
  • Ev
  • Event
  • Program execution
  • Exif
  • Expect
  • FAM
  • FANN
  • FrontBase
  • FDF
  • Fileinfo
  • filePro
  • Filesystem
  • Filter
  • Managerul de procese FastCGI
  • FriBiDi
  • FTP
  • Manipularea func?iilor
  • Gearman
  • Gender
  • GeoIP
  • Gettext
  • Gmagick
  • GMP
  • GnuPG
  • Gupnp
  • haru
  • Hash
  • HRTime
  • htscanner
  • Hyperwave API
  • Firebird/InterBase
  • IBM DB2
  • iconv
  • ID3
  • Informix
  • IIS
  • GD
  • ImageMagick
  • IMAP
  • inclued
  • PHP Options/Info
  • Ingres
  • Inotify
  • intl
  • JSON
  • Judy
  • KADM5
  • KTaglib
  • Lapack
  • LDAP
  • Libevent
  • libxml
  • Lua
  • LZF
  • Po?ta
  • Mailparse
  • Math
  • MaxDB
  • Stringuri multioctet
  • Mcrypt
  • MCVE
  • Memcache
  • Memcached
  • Memtrack
  • Mhash
  • Mimetype
  • Ming
  • Diverse
  • mnoGoSearch
  • Mongo
  • MongoDB\Driver
  • mqseries
  • Msession
  • mSQL
  • Mssql
  • MySQL (Original)
  • MySQLi
  • Mysqlnd
  • mysqlnd_memcache
  • mysqlnd_ms
  • mysqlnd_mux
  • mysqlnd_qc
  • mysqlnd_uh
  • Ncurses
  • Gopher
  • Network
  • Newt
  • YP/NIS
  • NSAPI
  • OAuth
  • OCI8
  • oggvorbis
  • OPcache
  • OpenAL
  • OpenSSL
  • Output Control
  • Paradox
  • Parsekit
  • Password Hashing
  • PCNTL
  • PCRE
  • PDF
  • PDO
  • 4D (PDO)
  • CUBRID (PDO)
  • MS SQL Server (PDO)
  • Firebird (PDO)
  • IBM (PDO)
  • Informix (PDO)
  • MySQL (PDO)
  • Oracle (PDO)
  • ODBC and DB2 (PDO)
  • PostgreSQL (PDO)
  • SQLite (PDO)
  • MS SQL Server (PDO)
  • PostgreSQL
  • Phar
  • POSIX
  • Proctitle
  • PS
  • Pspell
  • pthreads
  • Quickhash
  • 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
  • SQLite
  • SQLite3
  • SQLSRV
  • ssdeep
  • SSH2
  • Statistics
  • Stomp
  • Streams
  • Strings
  • SVM
  • SVN
  • Swish
  • Sybase
  • Sync
  • Taint
  • TCP
  • Tidy
  • Tokenizer
  • tokyo_tyrant
  • Trader
  • UI
  • ODBC
  • uopz
  • URL-uri
  • V8js
  • Manipularea variabilelor
  • Varnish
  • vpopmail
  • WDDX
  • Weakref
  • win32ps
  • win32service
  • WinCache
  • xattr
  • xdiff
  • Xhprof
  • XML Parser
  • XMLReader
  • XML-RPC
  • XMLWriter
  • XSL
  • Yaf
  • Yaml
  • Yar
  • YAZ
  • Zip
  • Zlib
  • 0MQ messaging
  • ZooKeeper
Lista/Categoriile extensiilor
Apartenen?a
Lista/Categoriile extensiilor


Apartenen?a

Extensiile de baza

Acestea de fapt nu sunt extensii. Ele fac parte din nucleul PHP ?i nu pot fi separate de binarul PHP folosind op?iuni de compilare.

  • Arrays

  • Classes/Objects

  • Date/Time

  • Directorii

  • Error Handling

  • Program execution

  • Filesystem

  • Filter

  • Manipularea func?iilor

  • Hash

  • PHP Options/Info

  • Po?ta

  • Math

  • Diverse

  • Network

  • Output Control

  • Password Hashing

  • Phar

  • Reflection

  • POSIX Regex

  • Sessions

  • SPL

  • Streams

  • Strings

  • Tokenizer

  • URL-uri

  • Manipularea variabilelor

Extensii adi?ionale

Aceste extensii sunt livrate împreuna cu PHP.

  • Apache

  • BC Math

  • Calendar

  • COM

  • Ctype

  • DBA

  • Exif

  • Fileinfo

  • FTP

  • iconv

  • GD

  • intl

  • JSON

  • Stringuri multioctet

  • NSAPI

  • PCNTL

  • PCRE

  • PDO

  • POSIX

  • Semaphore

  • Shared Memory

  • Sockets

  • SQLite3

  • XML-RPC

  • Zlib

Extensii externe

Aceste extensii intra în componen?a PHP, dar pentru a le compila vor fi necesare biblioteci externe.

  • Bzip2

  • cURL

  • dBase

  • DOM

  • Enchant

  • FrontBase

  • Gettext

  • GMP

  • Firebird/InterBase

  • Informix

  • IMAP

  • LDAP

  • libxml

  • Mcrypt

  • Mhash

  • mSQL

  • Mssql

  • MySQL (Original)

  • MySQLi

  • Mysqlnd

  • OCI8

  • OpenSSL

  • MS SQL Server (PDO)

  • Firebird (PDO)

  • MySQL (PDO)

  • Oracle (PDO)

  • ODBC and DB2 (PDO)

  • PostgreSQL (PDO)

  • SQLite (PDO)

  • PostgreSQL

  • Pspell

  • Readline

  • Recode

  • SimpleXML

  • SNMP

  • SOAP

  • Sybase

  • Tidy

  • ODBC

  • WDDX

  • XML Parser

  • XMLReader

  • XMLWriter

  • XSL

  • Zip

Extensii PECL

Aceste extensii sunt disponibile în » PECL. Ele pot sa necesite biblioteci externe. Exista mai multe extensii PECL, dar ele nu sunt documentate în manualul PHP deocamdata.

  • APC

  • APD

  • BBCode

  • bcompiler

  • Cairo

  • chdb

  • Classkit

  • Crack

  • CUBRID

  • Cyrus

  • DB++

  • dbx

  • Direct IO

  • Eio

  • Ev

  • Event

  • Expect

  • FAM

  • FDF

  • filePro

  • FriBiDi

  • Gearman

  • Gender

  • GeoIP

  • Gmagick

  • GnuPG

  • Gupnp

  • haru

  • htscanner

  • Hyperwave API

  • IBM DB2

  • ID3

  • IIS

  • ImageMagick

  • inclued

  • Ingres

  • Inotify

  • Judy

  • KADM5

  • KTaglib

  • Lapack

  • Libevent

  • Lua

  • LZF

  • Mailparse

  • MaxDB

  • MCVE

  • Memcache

  • Memcached

  • Memtrack

  • Mimetype

  • Ming

  • mnoGoSearch

  • Mongo

  • mqseries

  • Msession

  • mysqlnd_memcache

  • mysqlnd_ms

  • mysqlnd_mux

  • mysqlnd_qc

  • mysqlnd_uh

  • Ncurses

  • Gopher

  • Newt

  • YP/NIS

  • OAuth

  • oggvorbis

  • OpenAL

  • Paradox

  • Parsekit

  • PDF

  • 4D (PDO)

  • CUBRID (PDO)

  • IBM (PDO)

  • Informix (PDO)

  • MS SQL Server (PDO)

  • Proctitle

  • PS

  • pthreads

  • Quickhash

  • Radius

  • Rar

  • RPM Reader

  • RRD

  • runkit

  • SAM

  • SCA

  • scream

  • SDO

  • SDO DAS XML

  • SDO-DAS-Relational

  • Session PgSQL

  • Solr

  • Sphinx

  • SPL Types

  • SQLite

  • SQLSRV

  • ssdeep

  • SSH2

  • Statistics

  • Stomp

  • SVM

  • SVN

  • Swish

  • Taint

  • TCP

  • tokyo_tyrant

  • Trader

  • V8js

  • Varnish

  • vpopmail

  • Weakref

  • win32ps

  • win32service

  • WinCache

  • xattr

  • xdiff

  • Xhprof

  • Yaf

  • Yaml

  • YAZ

  • ZooKeeper

În ordine alfabetica
Statutul
Lista/Categoriile extensiilor


Statutul

Acest compartiment enumera extensiile care nu sunt destinate folosirii în producere - ele sunt sau prea "învechite" (scoase din uz), sau "noi" (experimentale).

Extensiile scoase din uz

Aceste extensii au fost scoase din uz în favoarea unor alte extensii, de regula.

  • Memtrack

  • Mimetype

Extensii experimentale

Comportamentul acestor extensii - inclusiv numele func?iilor lor ?i orice alte aspecte documentate despre aceste extensii - pot fi schimbate fara preaviz într-o versiune viitoare a PHP. Utiliza?i aceste extensii la propriul risc.

  • bcompiler

  • DB++

  • haru

  • Hash

  • ImageMagick

  • Ming

  • Ncurses

  • Newt

  • Paradox

  • MS SQL Server (PDO)

  • Firebird (PDO)

  • Oracle (PDO)

  • PS

  • SCA

  • SDO-DAS-Relational

  • Swish

  • vpopmail

  • XML-RPC

Apartenen?a
Lista pseudonimelor func?iilor
Lista/Categoriile extensiilor


Lista pseudonimelor func?iilor

Exista câteva func?ii în PHP, pe care pute?i sa le apela?i cu mai multe nume. În unele cazuri nu este vre-un nume preferat dintre aceste câteva, is_int() ?i is_integer() sunt la fel de potrivite, de exemplu. Însa sunt ?i func?ii care ?i-au schimbat numele din cauza cura?irii interfe?elor API, sau din alte motive ?i numele vechi sunt pastrate doar pentru a men?ine compatibilitatea inversa. De obicei nu este o idee buna de a utiliza astfel de pseudonime, deoarece ele pot fi scoase din uz sau redenumite, ceea ce va duce la un script neportabil. Aceasta lista e oferita celor ce doresc sa-?i modernizeze scripturile vechi folosind sintaxa noua.

Pseudonimele
Pseudonimul | Func?ia de baza | Extensia utilizata
_ | gettext() | Gettext
add | swfmovie_add() | Ming (flash)
add | swfsprite_add() | Ming (flash)
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)
chop | rtrim() | Sintaxa de baza
close | closedir() | Sintaxa de baza
com_get | com_propget() | COM
com_propset | com_propput() | COM
com_set | com_propput() | COM
die | exit() | Func?ii diverse
diskfreespace | disk_free_space() | Sistemul de fi?iere
doubleval | floatval() | Sintaxa de baza
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)
fbsql | fbsql_db_query() | FrontBase
fputs | fwrite() | Sintaxa de baza
getascent | swffont_getAscent() | Ming (flash)
getascent | swftext_getAscent() | Ming (flash)
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() | String-uri de mai mul?i bai?i
i18n_discover_encoding | mb_detect_encoding() | String-uri de mai mul?i bai?i
i18n_http_input | mb_http_input() | String-uri de mai mul?i bai?i
i18n_http_output | mb_http_output() | String-uri de mai mul?i bai?i
i18n_internal_encoding | mb_internal_encoding() | String-uri de mai mul?i bai?i
i18n_ja_jp_hantozen | mb_convert_kana() | String-uri de mai mul?i bai?i
i18n_mime_header_decode | mb_decode_mimeheader() | String-uri de mai mul?i bai?i
i18n_mime_header_encode | mb_encode_mimeheader() | String-uri de mai mul?i bai?i
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() | Sintaxa de baza
is_double | is_float() | Sintaxa de baza
is_integer | is_int() | Sintaxa de baza
is_long | is_int() | Sintaxa de baza
is_real | is_float() | Sintaxa de baza
is_writeable | is_writable() | Sintaxa de baza
join | implode() | Sintaxa de baza
key_exists | array_key_exists() | Sintaxa de baza
labelframe | swfmovie_labelFrame() | Ming (flash)
labelframe | swfsprite_labelFrame() | Ming (flash)
ldap_close | ldap_unbind() | LDAP
magic_quotes_runtime | set_magic_quotes_runtime() | Sintaxa de baza
mbstrcut | mb_strcut() | String-uri de mai mul?i bai?i
mbstrlen | mb_strlen() | String-uri de mai mul?i bai?i
mbstrpos | mb_strpos() | String-uri de mai mul?i bai?i
mbstrrpos | mb_strrpos() | String-uri de mai mul?i bai?i
mbsubstr | mb_substr() | String-uri de mai mul?i bai?i
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
nextframe | swfmovie_nextFrame() | Ming (flash)
nextframe | swfsprite_nextFrame() | Ming (flash)
ociassignelem | OCI-Collection::assignElem | OCI8
ocibindbyname | oci_bind_by_name() | OCI8
ocicancel | oci_cancel() | OCI8
ocicloselob | OCI-Lob::close | OCI8
ocicollappend | OCI-Collection::append | OCI8
ocicollassign | OCI-Collection::assign | OCI8
ocicollmax | OCI-Collection::max | OCI8
ocicollsize | OCI-Collection::size | OCI8
ocicolltrim | OCI-Collection::trim | OCI8
ocicolumnisnull | oci_field_is_null() | OCI8
ocicolumnname | oci_field_name() | OCI8
ocicolumnprecision | oci_field_precision() | OCI8
ocicolumnscale | oci_field_scale() | OCI8
ocicolumnsize | oci_field_size() | OCI8
ocicolumntype | oci_field_type() | OCI8
ocicolumntyperaw | oci_field_type_raw() | OCI8
ocicommit | oci_commit() | OCI8
ocidefinebyname | oci_define_by_name() | OCI8
ocierror | oci_error() | OCI8
ociexecute | oci_execute() | OCI8
ocifetch | oci_fetch() | OCI8
ocifetchinto | oci_fetch_array(), oci_fetch_row(), oci_fetch_assoc(), oci_fetch_object() | OCI8
ocifetchstatement | oci_fetch_all() | OCI8
ocifreecollection | OCI-Collection::free | OCI8
ocifreecursor | oci_free_statement() | OCI8
ocifreedesc | oci_free_descriptor() | OCI8
ocifreestatement | oci_free_statement() | OCI8
ocigetelem | OCI-Collection::getElem | OCI8
ociinternaldebug | oci_internal_debug() | OCI8
ociloadlob | OCI-Lob::load | OCI8
ocilogon | oci_connect() | OCI8
ocinewcollection | oci_new_collection() | OCI8
ocinewcursor | oci_new_cursor() | OCI8
ocinewdescriptor | oci_new_descriptor() | OCI8
ocinlogon | oci_new_connect() | OCI8
ocinumcols | oci_num_fields() | OCI8
ociparse | oci_parse() | OCI8
ocipasswordchange | oci_password_change() | OCI8
ociplogon | oci_pconnect() | OCI8
ociresult | oci_result() | OCI8
ocirollback | oci_rollback() | OCI8
ocisavelob | OCI-Lob::save | OCI8
ocisavelobfile | OCI-Lob::import | OCI8
ociserverversion | oci_server_version() | OCI8
ocisetprefetch | oci_set_prefetch() | OCI8
ocistatementtype | oci_statement_type() | OCI8
ociwritelobtofile | OCI-Lob::export | OCI8
ociwritetemporarylob | OCI-Lob::writeTemporary | OCI8
odbc_do | odbc_exec() | ODBC
odbc_field_precision | odbc_field_len() | ODBC
output | swfmovie_output() | Ming (flash)
pdf_add_outline | pdf_add_bookmark() | PDF
pg_clientencoding | pg_client_encoding() | PostgreSQL
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL
pos | current() | Sintaxa de baza
recode | recode_string() | Recode
remove | swfmovie_remove() | Ming (flash)
remove | swfsprite_remove() | Ming (flash)
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)
setaction | swfbutton_setAction() | Ming (flash)
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() | Sintaxa de baza
sizeof | count() | Sintaxa de baza
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() | Sintaxa de baza
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)
xptr_new_context | xpath_new_context() |

Statutul
Lista cuvintelor rezervate
Anexe


Lista cuvintelor rezervate

Cuprins

  • Lista cuvintelor-cheie
  • Clase predefinite
  • Constante predefinite
  • Lista altor cuvinte rezervate

În continuare urmeaza lista identificatorilor predefini?i în PHP. Nici unul din identificatorii enumera?i aici nu trebuie sa fie utiliza?i ca identificatori în script-urile dumneavoastra, doar daca nu este specificat în mod explicit altfel. Aceste liste includ cuvinte-cheie ?i variabile predefinite, denumiri de constante ?i clase. Aceste liste nu sunt exhaustive sau depline.

Lista pseudonimelor func?iilor
Lista cuvintelor-cheie
Anexe


Lista cuvintelor-cheie

Aceste cuvinte au o semnifica?ie speciala în PHP. Unele din ele se aseamana cu func?ii, altele cu constante ?.a.m.d., însa aceasta nu este a?a: ele sunt construc?ii ale limbajului. Nu pute?i utiliza cuvintele ce urmeaza ca constante, denumiri ale claselor, func?iilor sau metodelor. Utilizarea lor ca denumiri ale variabilelor este în general OK, dar poate duce la confuzie.

Începând cu PHP 7.0.0 aceste cuvinte-cheie sunt permise în denumiri de proprieta?i, constante ?i metode ale claselor, interfe?elor ?i trasaturilor, cu excep?ia ca class nu poate fi folosit ca nume de constanta.

Cuvinte-cheie PHP
__halt_compiler() | abstract | and | array() | as
break | callable (începând cu PHP 5.4) | case | catch | class
clone | const | continue | declare | default
die() | do | echo | else | elseif
empty() | enddeclare | endfor | endforeach | endif
endswitch | endwhile | eval() | exit() | extends
final | finally (începând cu PHP 5.5) | for | foreach | function
global | goto (începând cu PHP 5.3) | if | implements | include
include_once | instanceof | insteadof (începând cu PHP 5.4) | interface | isset()
list() | namespace (începând cu PHP 5.3) | new | or | print
private | protected | public | require | require_once
return | static | switch | throw | trait (începând cu PHP 5.4)
try | unset() | use | var | while
xor | yield (începând cu PHP 5.5) |  |  |
Constante la compilare
__CLASS__ | __DIR__ (începând cu PHP 5.3) | __FILE__ | __FUNCTION__ | __LINE__ | __METHOD__
__NAMESPACE__ (începând cu PHP 5.3) | __TRAIT__ (începând cu PHP 5.4) |  |  |  |
Lista cuvintelor rezervate
Clase predefinite
Lista cuvintelor rezervate


Clase predefinite

Aceasta sec?iune prezinta clasele standarde predefinite. Diferite extensii definesc alte clase care sunt descrise în referin?ele lor.

Clase standarde definite

Aceste clase sunt definite în setul standard de func?ii inclus în distribu?ia PHP.

Directory
Creata de dir().
stdClass
Creat prin transformarea tipului în object.
__PHP_Incomplete_Class
Posibil creata cu unserialize().

Clase predefinite începând cu PHP 5

Aceste clase predefinite suplimentare au fost introduse în PHP 5.0.0.

Exception
ErrorException
Disponibila începând cu PHP 5.1.0.
php_user_filter

Closure

Clasa predefinita finala Closure a fost introdusa în PHP 5.3.0. Ea este utilizata pentru a reprezenta func?ii anonime.

Pentru informa?ii suplimentare accesa?i pagina clasei.

Generator

Clasa finala predefinita Generator a fost introdusa în PHP 5.5.0. Ea este utilizata pentru reprezentarea generatoarelor.

Pentru informa?ii suplimentare accesa?i pagina clasei.

Interfe?e ?i clase predefinite începând cu PHP 7

Aceste interfe?e ?i clase predefinite suplimentare au fost introduse în PHP 7.0.0.

ArithmeticError
AssertionError
DivisionByZeroError
Error
Throwable
ParseError
TypeError

Clase speciale

Urmatorii identificatori nu pot fi utiliza?i ca denumiri de clase, deoarece au destina?ii speciale.

self
Clasa curenta.
static
Clasa curenta la momentul rularii.
parent
Clasa-parinte.
Lista cuvintelor-cheie
Constante predefinite
Lista cuvintelor rezervate


Constante predefinite

Constantele predefinite de baza

Aceste constante sunt definite de nucleul PHP. Aceasta include PHP, motorul Zend ?i modulele SAPI.

PHP_VERSION (string)
Versiunea curenta a PHP ca ?ir de caractere în notarea "major.minor.release[extra]".
PHP_MAJOR_VERSION (integer)
Versiunea "major" curenta a PHP ca numar întreg (de ex. int(5) pentru versiunea "5.2.7-extra"). Disponibila începând cu PHP 5.2.7.
PHP_MINOR_VERSION (integer)
Versiunea "minor" curenta a PHP ca numar întreg (de ex. int(2) pentru versiunea "5.2.7-extra"). Disponibila începând cu PHP 5.2.7.
PHP_RELEASE_VERSION (integer)
Versiunea "release" curenta a PHP ca numar întreg (de ex. int(7) pentru versiunea "5.2.7-extra"). Disponibila începând cu PHP 5.2.7.
PHP_VERSION_ID (integer)
Versiunea curenta a PHP ca numar întreg, util pentru compararea versiunilor (de ex. int(50207) pentru versiunea "5.2.7-extra"). Disponibila începând cu PHP 5.2.7.
PHP_EXTRA_VERSION (string)
Versiunea "extra" curenta a PHP ca ?ir de caractere (de ex. '-extra' pentru versiunea "5.2.7-extra"). Deseori utilizata de distribuitori pentru a indica versiunea pachetului. Disponibila începând cu PHP 5.2.7.
PHP_ZTS (integer)
Disponibila începând cu PHP 5.2.7.
PHP_DEBUG (integer)
Disponibila începând cu PHP 5.2.7.
PHP_MAXPATHLEN (integer)
Lungimea maxima a numelor de fi?iere (inclusiv calea) sus?inuta de aceasta asamblare a PHP. Disponibila începând cu PHP 5.3.0.
PHP_OS (string)
PHP_SAPI (string)
API al serverului pentru aceasta asamblare a PHP. A se vedea ?i php_sapi_name().
PHP_EOL (string)
Simbolul corect pentru 'End Of Line' (sfâr?it de linie) pentru aceasta platforma. Disponibila începând cu PHP 5.0.2
PHP_INT_MAX (integer)
Cea mai mare valoare întreaga sus?inuta în aceasta asamblare a PHP. De regula int(2147483647). Disponibila începând cu PHP 5.0.5
PHP_INT_MIN (integer)
Cea mai mica valoare întreaga sus?inuta în aceasta asamblare a PHP. De regula int(-2147483648) pe sisteme de 32 bi?i ?i int(-9223372036854775808) pe sisteme de 64 bi?i. Disponibila începând cu PHP 7.0.0. De obicei PHP_INT_MIN === ~PHP_INT_MAX.
PHP_INT_SIZE (integer)
Dimensiunea în octe?i a unui întreg în aceasta asamblare a PHP. Disponibila începând cu PHP 5.0.5.
DEFAULT_INCLUDE_PATH (string)
PEAR_INSTALL_DIR (string)
PEAR_EXTENSION_DIR (string)
PHP_EXTENSION_DIR (string)
PHP_PREFIX (string)
Valoarea ce a fost stabilita pentru "--prefix" la etapa de configurare.
PHP_BINDIR (string)
Specifica unde au fost instalate binarele.
PHP_BINARY (string)
Specifica calea catre binarul PHP la executarea scriptului. Disponibila începând cu PHP 5.4.
PHP_MANDIR (string)
Specifica unde au fost instalate paginile de manual. Disponibila începând cu 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)
Sufixul bibliotecilor partajate pe platforma respectiva, cum ar fi "so" (pentru majoritatea sistemelor Unix) sau "dll" (pentru Windows).
E_ERROR (integer)
Constanta de raportare a erorilor
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)
Disponibila începând cu PHP 5.3.0
E_USER_DEPRECATED (integer)
Disponibila începând cu PHP 5.3.0
E_ALL (integer)
E_STRICT (integer)
__COMPILER_HALT_OFFSET__ (integer)
Disponibila începând cu PHP 5.1.0
TRUE (boolean)
See Booleans.
FALSE (boolean)
See Booleans.
NULL (null)
See Null.

A se vedea de asemenea: Constantele magice.

Constante standard predefinite

Toate constantele din cadrul extensiilor de baza sunt definite în PHP în mod implicit.

Clase predefinite
Lista altor cuvinte rezervate
Lista cuvintelor rezervate


Lista altor cuvinte rezervate

Urmatoarele cuvinte nu pot fi utilizate pentru a denumi o clasa, interfa?a sau trasatura ?i de asemenea nu pot fi utilizate în spa?ii de nume.

Cuvinte rezervate
int (începând cu PHP 7) | float (începând cu PHP 7) | bool (începând cu PHP 7) | string (începând cu PHP 7)
true (începând cu PHP 7) | false (începând cu PHP 7) | null (începând cu PHP 7)

Urmatoarea lista de cuvinte are o rezervare ”lejera”. Cu toate ca aceste cuvinte pot fi înca utilizare pentru denumiri de clase, interfe?e ?i trasaturi (la fel ca ?i pentru spa?ii de nume), utilizarea lor este foarte nerecomandata deoarece ele pot fi utilizate în versiuni viitoare ale PHP.

Cuvinte rezervate ”lejer”
resource (începând cu PHP 7) object (începând cu PHP 7) mixed (începând cu PHP 7) numeric (începând cu PHP 7)

Constante predefinite
Lisa tipurilor de resurse
Lista cuvintelor rezervate


Lisa tipurilor de resurse

Urmeaza lista func?iilor ce creeaza, utilizeaza sau sidtrug resurse PHP. Func?ia is_resource() poate fi utilizata pentru a determina daca o variabila este o resursa, iar func?ia get_resource_type() va întoarce tipul acestei resurse.

Tipuri de Resurse
Denumire a tipului resursei | Creata de | Utilizata de | Distrusa de | Defini?ie
aspell | aspell_new() | aspell_check(), aspell_check_raw(), aspell_suggest() | Nu este | Dic?ionar Aspell
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Fi?ier Bzip2
COM | com_load() | com_invoke(), com_propget(), com_get(), com_propput(), com_set(), com_propput() | Nu este | Referin?a la un obiect 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() | Document PDF cu biblioteca CPDF
cpdf outline
conexiune cubrid | cubrid_connect() cubrid_connect_with_url() | cubrid_col_get() cubrid_col_size() cubrid_commit() cubrid_drop() cubrid_execute() cubrid_get_autocommit() cubrid_get_charset() cubrid_get_class_name() cubrid_get_db_parameter() cubrid_get_server_info() cubrid_get() cubrid_insert_id() cubrid_is_instance() cubrid_lob_export() cubrid_lob_get() cubrid_lob_send() cubrid_lock_read() cubrid_lock_write() cubrid_prepare() cubrid_put() cubrid_rollback() cubrid_schema() cubrid_seq_drop() cubrid_seq_insert() cubrid_seq_put() cubrid_set_add() cubrid_set_autocommit() cubrid_set_db_parameter() cubrid_set_drop() cubrid_affected_rows() cubrid_client_encoding() cubrid_errno() cubrid_error() cubrid_list_dbs() cubrid_ping() cubrid_query() cubrid_real_escape_string() | cubrid_close() cubrid_disconnect() | Conexiune la o baza de date CUBRID
conexiune cubrid persistenta | cubrid_pconnect() cubrid_pconnect_with_url() | cubrid_col_get() cubrid_col_size() cubrid_commit() cubrid_drop() cubrid_execute() cubrid_get_autocommit() cubrid_get_charset() cubrid_get_class_name() cubrid_get_db_parameter() cubrid_get_server_info() cubrid_get() cubrid_insert_id() cubrid_is_instance() cubrid_lob_export() cubrid_lob_get() cubrid_lob_send() cubrid_lock_read() cubrid_lock_write() cubrid_prepare() cubrid_put() cubrid_rollback() cubrid_schema() cubrid_seq_drop() cubrid_seq_insert() cubrid_seq_put() cubrid_set_add() cubrid_set_autocommit() cubrid_set_db_parameter() cubrid_set_drop() cubrid_affected_rows() cubrid_client_encoding() cubrid_errno() cubrid_error() cubrid_list_dbs() cubrid_ping() cubrid_query() cubrid_real_escape_string() cubrid_lob2_new() | Conexiune persistenta la o baza de date CUBRID
interpelare cubrid | cubrid_prepare() cubrid_execute() cubrid_query() cubrid_unbuffered_query() | cubrid_bind() cubrid_column_names() cubrid_column_types() cubrid_current_oid() cubrid_execute() cubrid_free_result() cubrid_get_query_timeout() cubrid_move_cursor() cubrid_next_result() cubrid_num_cols() cubrid_num_rows() cubrid_set_query_timeout() cubrid_data_seek() cubrid_fetch_array() cubrid_fetch_assoc() cubrid_fetch_field() cubrid_fetch_lengths() cubrid_fetch_object() cubrid_fetch_row() cubrid_field_flags() cubrid_field_len() cubrid_field_name() cubrid_field_seek() cubrid_field_table() cubrid_field_type() cubrid_num_fields() cubrid_result() cubrid_lob2_bind() | cubrid_close_prepare() cubrid_close_request() | Interpelare CUBRID
lob cubrid | cubrid_lob_get() | cubrid_lob_export() cubrid_lob_send() cubrid_lob_size() | cubrid_lob_close() | None
cubrid lob2 | cubrid_lob2_new() cubrid_fetch() cubrid_fetch_row() cubrid_fetch_array() cubrid_fetch_assoc() cubrid_fetch_object() | cubrid_lob2_export() cubrid_lob2_import() cubrid_lob2_read() cubrid_lob2_write() cubrid_lob2_tell() cubrid_lob2_tell64() cubrid_lob2_seek() cubrid_lob2_seek64() cubrid_lob2_size() cubrid_lob2_size64() | cubrid_lob2_close() | None
curl | curl_copy_handle(), curl_init() | curl_copy_handle(), curl_errno(), curl_error(), curl_exec(), curl_getinfo(), curl_setopt() | curl_close() | Sesiune Curl
dbm | dbmopen() | dbmexists(), dbmfetch(), dbminsert(), dbmreplace(), dbmdelete(), dbmfirstkey(), dbmnextkey() | dbmclose() | Legatura catre o baza de date DBM
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Legatura catre o baza da date DBA
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | Nu este | Legatura persistenta catre o baza de date 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() | Legatura catre o baza da date Dbase
dbx_link_object | dbx_connect() | dbx_query() | dbx_close() | Conexiune dbx
dbx_result_object | dbx_query() | Nu este | Rezultat dbx
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() | Legatura catre o baza da date 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() | Nu este | Legatura persistenta catre o baza da date 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() | Rezultat 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() | Fi?ier 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() | Torent FTP
gd | imagecreate(), imagecreatefromgd(), imagecreatefromgd2(), imagecreatefromgd2part(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), 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() | Imagine GD
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | Nu este | Font pentru GD
gd PS encoding
gd PS font | imagepsloadfont() | imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() | imagepsfreefont() | Font PS pentru 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() | Nu este | Numar 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() | Obiect 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() | Legatura catre un server 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() | Nu este | Legatura persistenta catre un server Hyperwave
icap | icap_open() | icap_fetch_event(), icap_list_events(), icap_store_event(), icap_snooze(), icap_list_alarms(), icap_delete_event() | icap_close() | Legatura catre un server 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() | Legatura catre un server 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() | Legatura catre o baza de date 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() | Nu este | Legatura persistenta catre o baza de date ingresII
interbase blob
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Legatura catre o baza de date Interbase
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | Nu este | Legatura persistenta catre o baza de date Interbase
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Interpelare Interbase
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Rezultat Interbase
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Tranzac?ie 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() | Conexiune 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() | Rezultat al cautarii în 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_none(), 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() | Legatura catre un server de calendar
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() | Legatura catre o baza de date mSQL
msql link persistent | msql_pconnect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | Nu este | Legatura persistenta catre o baza de date 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_flags(), msql_field_len(), msql_field_name(), 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() | Legatura catre o baza de date Microsoft SQL Server
mssql link persistent | mssql_pconnect() | mssql_query(), mssql_select_db() | Nu este | Legatura persistenta catre o baza de date 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_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Legatura catre o baza de date 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() | Nu este | Legatura persistenta catre o baza de date MySQL
mysql result | mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_processes(), 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 | oci_new_collection() | OCI-Collection::append(), OCI-Collection::assign(), OCI-Collection::assignElem(), OCI-Collection::getElem(), OCI-Collection::max(), OCI-Collection::size(), OCI-Collection::trim() | OCI-Collection::free() | Colec?ie Oracle
oci8 connection | oci_connect(), oci_pconnect(), oci_new_connect() | oci_commit(), oci_error(), oci_new_cursor(), oci_parse(), oci_password_change(), oci_rollback(), oci_server_version(), oci_set_action(), oci_set_client_identifier(), oci_set_client_info(), oci_set_module_name() | oci_close() | Conexiune catre o baza de date Oracle
oci8 lob | oci_new_descriptor() | OCI-Lob::append(), OCI-Lob::close(), OCI-Lob::eof(), OCI-Lob::erase(), OCI-Lob::export(), OCI-Lob::flush(), OCI-Lob::getBuffering(), OCI-Lob::import(), OCI-Lob::load(), OCI-Lob::read(), OCI-Lob::rewind(), OCI-Lob::save(), OCI-Lob::saveFile(), OCI-Lob::seek(), OCI-Lob::setBuffering(), OCI-Lob::size(), OCI-Lob::tell(), OCI-Lob::truncate(), OCI-Lob::write(), OCI-Lob::writeTemporary(), OCI-Lob::writeToFile(), oci_lob_copy(), oci_lob_is_equal() | OCI-Lob::free() | Obiectele largi Oracle
oci8 statement | oci_parse(), oci_new_cursor() | oci_bind_array_by_name(), oci_bind_by_name(), oci_cancel(), oci_define_by_name(), oci_error() oci_execute(), oci_fetch_all(), oci_fetch_array(), oci_fetch_assoc(), oci_fetch_object(), oci_fetch_row(), oci_fetch(), oci_field_is_null(), oci_field_name(), oci_field_precision(), oci_field_scale(), oci_field_size(), oci_field_type_raw(), oci_field_type(), oci_num_fields(), oci_num_rows(), oci_result(), oci_set_prefetch(), oci_statement_type() | oci_free_statement() | Cursor 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() | Legatura catre o baza de date 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() | Nu este | Legatura persistenta catre o baza de date 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() | Cheie OpenSSL
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Cheie publica
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() | Document 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() | Imagine într-un fi?ier 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() | PostgreSQL Large Object
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() | Legatura catre o baza de date 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() | Nu este | Legatura persistenta catre o baza de date 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() | Nu este | Dic?ionar pspell
pspell config | pspell_config_create() | pspell_new_config() | Nu este | Configura?ie 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() | Interpretor 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() | Socket
sockets i/o vector
stream | opendir() | readdir(), rewinddir() | closedir() | Handle catre Dir
stream | fopen(), tmpfile() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | Handle catre File
stream | popen(), fsockopen(), pfsockopen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Handle catre Process
socket | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Handle catre Socket
sybase-db link | sybase_connect() | sybase_query(), sybase_select_db() | sybase_close() | Legatura catre o baza de date Sybase utilizând biblioteca DB
sybase-db link persistent | sybase_pconnect() | sybase_query(), sybase_select_db() | Nu este | Legatura persistenta catre o baza de date Sybase utilizând biblioteca 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 utilizând biblioteca DB
sybase-ct link | sybase_connect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | sybase_close() | Legatura catre o baza de date Sybase utilizând biblioteca CT
sybase-ct link persistent | sybase_pconnect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | Nu este | Legatura persistenta catre o baza de date Sybase utilizând biblioteca 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 utilizând biblioteca 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() | Memorie partajata System V
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | Pachet 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() | Interpretor XML
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | Fi?ier comprimat gz

Lista altor cuvinte rezervate
Lista filtrelor disponibile
Anexe


Lista filtrelor disponibile

Cuprins

  • Filtrele string-urilor
  • Filtre de conversie
  • Filtrele de compresie
  • Filtrele de criptare

Urmeaza o lista a câtorva filtre de flux pentru a fi utilizate cu stream_filter_append(). Versiunea dumneavoastra a PHP poate avea mai multre filtre (sau mai pu?ine) decât cele listate aici.

Merita de a fi remarcata mica asimetrie dintre stream_filter_append() ?i stream_filter_prepend(). Fiecare flux PHP con?ine o mica zona-tampon de citire unde el stocheaza blocuri de date recep?ionate de la sistemul de fi?iere sau alte resurse pentru a procesa datele în modul cel mai eficient. Imediat ce datele sunt extrase din resursa în zona-tampon interna a fluxului, ele sunt procesate prin orice filtru ata?at, indiferent daca aplica?ia PHP este pregatita de a primi datele, sau nu. Daca datele se afla în zona-tampon de citire în timp ce sunt anexate la filtru, aceste date vor fi imediat procesate prin acel filtru, astfel încât faptul aflarii lor în zona-tampon trece neobservat. Însa daca datele se afla în zona-tampon de citire în timp ce sunt prefixate la filtru, ele NU vor fi procesate prin acel filtru. În schimb se va a?tepta momentul când urmatorul bloc de date va fi extras din resursa.

Pentru a vedea lista filtrelor instalate în versiunea dumneavoastra a PHP, folosi?i stream_get_filters().

Lisa tipurilor de resurse
Filtrele string-urilor
Anexe


Filtrele string-urilor

Fiecare dintre aceste filtre efectueaza exact ceea ce indica denumirea lor ?i corespund cu comportamentul unei func?ii de manipulare a stringurilor incorporate în PHP. Pentru mai multe informa?ii despre un anumit filtru, referi?i-va la pagina din manual pentru func?ia corespunzatoare.

string.rot13 Folosirea acestui filtru este echivalenta cu procesarea tuturor datelor din flux prin func?ia str_rot13().

Example #1 string.rot13

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "This is a test.\n");
/* Afi?eaza:  Guvf vf n grfg.   */
?>

string.toupper Folosirea acestui filtru este echivalenta cu procesarea tuturor datelor din flux prin func?ia strtoupper().

Example #2 string.toupper

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "This is a test.\n");
/* Afi?eaza:  THIS IS A TEST.   */
?>

string.tolower Folosirea acestui filtru este echivalenta cu procesarea tuturor datelor din flux prin func?ia strtolower().

Example #3 string.tolower

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "This is a test.\n");
/* Afi?eaza:  this is a test.   */
?>

string.strip_tags (începând cu PHP 5.0.0) Folosirea acestui filtru este echivalenta cu procesarea tuturor datelor din flux prin func?ia strip_tags(). El accepta parametrii în unul din aceste doua moduri: un string con?inând o lista de tag-uri, similar celui de-al doilea parametru al func?iei strip_tags(), sau ca un tablou cu denumirile tag-urilor.

Example #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);
/* Afi?eaza:  <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);
/* Afi?eaza:  <b>bolded text</b> enlarged to a level 1 heading   */
?>
Lista filtrelor disponibile
Filtre de conversie
Lista filtrelor disponibile


Filtre de conversie

Ca ?i filtrele string.*, filtrele convert.* efectueaza ac?iuni similare numelor lor. Filtrele de conversie au fost introduse odata cu PHP 5.0.0. Pentru mai multe informa?ii despre un anumit filtru, referi?i-va la pagina din manual pentru func?ia corespunzatoare.

convert.base64-encode ?i convert.base64-decode Utilizarea acestor filtre este echivalenta cu procesarea tuturor datelor din flux prin func?iile base64_encode() ?i base64_decode() respectiv. convert.base64-encode sus?ine parametri sub forma unui tablou asociativ. Daca parametrul line-length este specificat, ie?irile sub forma base64 for fi separate în por?iuni de câte line-length caractere fiecare. Daca parametrul line-break-chars este specificat, fiecare por?iune va fi delimitata cu caracterele specificaate în parametru. Ace?ti parametri produc acela?i efect ca ?i utilizarea base64_encode() cu chunk_split().

Example #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);
/* Afi?eaza:  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);
/* Afi?eaza:  VGhpcyBp
           :  cyBhIHRl
           :  c3QuCg==  */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* Afi?eaza:  This is a test.  */
?>

convert.quoted-printable-encode ?i convert.quoted-printable-decode Utilizarea versiunii decode a acestui filtru este echivalenta cu procesarea tuturor datelor din flux prin func?ia quoted_printable_decode(). Nu exista o func?ie echivalenta pentru convert.quoted-printable-encode. convert.quoted-printable-encode sus?ine parametrii sub forma unui tablou asociativ. Adaugator la parametrii sus?inu?i de convert.base64-encode, convert.quoted-printable-encode de asemenea sus?ine argumente boolean binary ?i force-encode-first. convert.base64-decode sus?ine numai parametrul line-break-chars în calitate de indiciu al caracterelor ce trebiue eliminate din încarcatura utila codificata.

Example #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");
/* Afi?eaza:  =This is a test.=0A  */
?>
Filtrele string-urilor
Filtrele de compresie
Lista filtrelor disponibile


Filtrele de compresie

În timp ce înveli?urile de compresie ofera o modalitate de a crea fi?iere compatibile cu gzip and bz2 pe sistemul de fi?iere local, ele nu ofera o modalitate de compresie generalizata prin fluxuri în re?ea, nici nu ofera o modalitate de a începe cu un flux necomprimat ?i a trece la unul comprimat. Pentru acestea, un filtru de compresie poate fi aplicat oricând asupra oricarei resurse-flux.

Nota: Filtrele de compresie nu genereaza antete sau sfâr?ituri utilizate de utilitele din linie de comanda, cum ar fi gzip. Ele numai comprima ?i decomprima por?iunile cu încarcatura utila a fluxurilor de date.

zlib.deflate (compresie) ?i zlib.inflate (decompresie) sunt implementari ale metodelor de compresie descrise în » RFC 1951. Filtrul deflate preia pâna la trei parametri transmi?i sub forma unui tablou asociativ. level descrie nivelul de compresie utilizat (1-9). Numere mai mari vor produce în general încarcaturi utile mai mici fara a necesita timp de procesare suplimentar. De asemenea exista ?i doua nivele speciale de compresie: 0 (fara compresie), ?i -1 (valoarea interna implicita a zlib -- în prezent 6). window este logaritmul în baza 2 a marimii ferestrei de compresie în bucla inversa. Valorile mai mari (pâna la 15 -- 32768 bai?i) produc o compresie mai buna, costul fiind mai multa memorie, în timp ce valorile mai mici (pâna la 9 -- 512 bai?i) produc o compresie mai rea într-un volum de memorie mai mic. Valoarea implicita a marimii window este în prezent 15. memory este o scara care indica ce volum de memorie de lucru trebiue allocated. Valori permise sunt în intervalul de la 1 (alocare minima) pâna la 9 (alocare maxima). Aceata alocare de memorie influen?eaza doar viteza ?i nu are impact asupra marimii încarcaturii de lucru generate.

Nota: Deoarece nivelul compresiei este cel mai des utilizat parametru, el poate fi transmis, îm mod alternativ, sub forma unei simple valori întregi (?i nu sub forma unui tablou dintr-un element).

Filtrele de compresie zlib.* sunt disponibile în PHP începând cu versiunea 5.1.0, daca sus?inerea zlib a fost activata. Ele de asemenea sunt disponibile în calitate de cod portabil ?i pentru versiunea 5.0.x instalând pachetul » zlib_filter din » PECL.

Example #1 zlib.deflate ?i 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";
/* Folosim readfile ?i zlib.inflate pentru a decomprima datele 'din zbor' */
readfile('php://filter/zlib.inflate/resource=test.deflated');

/* Genereaza utmatoarele:

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.

 */
?>

Example #2 zlib.deflate simplu

<?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');
/* Aici "6" indica nivelul de compresie 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";

/* Genereaza urmatoarele:

The original text is 70 characters long.
The compressed file is 56 bytes long.

 */
?>

bzip2.compress ?i bzip2.decompress func?ioneaza în acela?i mod ca ?i filtrele zlib descrise anterior. Filtrul bzip2.compress accepta pâna la doi parametri transmi?i sub forma de elemente ale unui tablou asociativ: blocks este o valoare de tip întreg de la 1 pâna la 9, specificând numarul de blocuri de memorie de 100 kbai?i pentru a fi aloca?i în spa?iul de lucru. work este de asemenea o valoare de tip întreg din intervalul de la 0 pâna la 250 indicând ce volum de efort trebuie cheltuit folosind metoda normala de compresie, înainte de a trece înapoi la o metoda mai lenta, dar mai sigura. Reglarea acestui parametru afecteaza doar viteza de compresie. Nici marimea datelor finale, nici utilizarea memoriei nu sunt afectate de modificarea acestui parametru. Valoarea 0 instruie?te biblioteca bzip sa utilizeze valoarea interna implicita. Filtrul bzip2.decompress accepta doar un parametru, care poate fi transmis sub forma unei valori boolean obi?nuite sau sub forma elementului small al unui tablou asociativ. small, când este stabilit la valoarea TRUE, instruie?te biblioteca bzip sa efectueze decomprimarea cu utilizarea unui volum minimal al memoriei la costul vitezei de procesare.

Filtrele de copresie bzip2.* sunt disponibile în PHP începând cu versiunea 5.1.0 daca sus?inerea bz2 a fost activata. Ele de asemenea sunt disponibile în calitate de cod portabil ?i pentru versiunea 5.0.x instalând pachetul » bz2_filter din » PECL.

Example #3 bzip2.compress ?i 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";

/* Genereaza urmatoarele:

The original text is 3288 characters long.
The compressed file is 1488 bytes long.

 */
?>
Filtre de conversie
Filtrele de criptare
Lista filtrelor disponibile


Filtrele de criptare

mcrypt.* ?i mdecrypt.* ofera criptare ?i decriptare simetrica, utilizând libmcrypt. Ambele seturi de filtre sus?in aceia?i algoritmi disponibili extensiei mcrypt sub forma mcrypt.ciphername, unde ciphername este denumirea algoritmului de criptare, care ar fi putut fi transmis func?iei mcrypt_module_open(). De asemenea sunt disponibili ?i urmatorii cinci parametri:

Parametrii filtrului mcrypt
Parametrul | Necesar? | Implicit | Valori-exemple
mode | Op?ional | cbc | cbc, cfb, ecb, nofb, ofb, stream
algorithms_dir | Op?ional | ini_get('mcrypt.algorithms_dir') | Localizarea modulelor algoritmilor
modes_dir | Op?ional | ini_get('mcrypt.modes_dir') | Localizarea modulelor modurilor
iv | Necesar | nu este | De obicei 8, 16, sau 32 bai?i de date binare. Depinde de cifru
key | Necesar | nu este | De obicei 8, 16, sau 32 bai?i de date binare. Depinde de cifru

Example #1 Criptarea con?inutului unui fi?ier utilizând 3DES

<?php
$passphrase = 'My secret';

/* Transforma parola în text deschis
 * într-o pereche iv/key reproductibila
 */
$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);
?>

Example #2 Citirea unui fi?ier criptat

<?php
$passphrase = 'My secret';

/* Transforma parola în text deschis
 * într-o pereche iv/key reproductibila
 */
$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;
?>
Filtrele de compresie
Lista transporturilor prin socket-e sus?inute
Lista filtrelor disponibile


Lista transporturilor prin socket-e sus?inute

Cuprins

  • Domeniul Internet: TCP, UDP, SSL ?i TLS
  • Domeniul Unix: Unix ?i UDG

În continuare urmeaza lista diferitor transporturi prin socket-e în stil de URL pe care PHP le are încorporate, ce pot fi utilizate cu func?ii de socket bazate pe fluxuri cum ar fi fsockopen() ?i stream_socket_client(). Aceste transporturi nu se refera la Extensiile de socket-uri.

Pentru a vedea lista transporturilor instalate în versiunea dumneavoastra a PHP utiliza?i stream_get_transports().

Filtrele de criptare
Domeniul Internet: TCP, UDP, SSL ?i TLS
Anexe


Domeniul Internet: TCP, UDP, SSL ?i TLS

PHP 4, PHP 5. ssl:// & tls:// începând cu PHP 4.3.0 sslv2:// & sslv3:// începând cu PHP 5.0.2

Nota: Daca nu este specificat un transport se va considera implicit tcp://.

  • 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

Socket-urile din domeniul Internet necesita ?i un numar al portului suplimentar la adresa destina?iei. În cazul fsockopen() acesta este specificat în al doilea parametru ?i de aceea nu are vre-un impact asupra formatului adresei URL a transportului. Însa în cazul stream_socket_client() ?i a altor func?ii asociate, ca ?i în cazul URL-urilor tradi?ionale, numarul portului este specificat în calitate de sufix al URL-ului de transport separat prin doua puncte.

  • tcp://127.0.0.1:80
  • tcp://[fe80::1]:80
  • tcp://www.example.com:80

Nota: Adresa numerica IPv6 cu numerele porturilor
Observa?i al doilea exemplu de mai sus. În timp ce adresele IPv4 ?i denumirile gazdelor ramân neschimbate, cu excep?ia adaugarii a doua puncte ?i a numarului portului, adresele IPv6 sunt înconjurate de paranteze patrate: [fe80::1]. Aceasta se face pentru a face distinc?ie între doua puncte ce se utilizeaza la scrierea adresei IPv6 ?i doua puncte ce separa numarul portului.

Transporturile ssl:// ?i tls:// (disponibile doar atunci când sus?inerea openssl este compilata în PHP) sunt ni?te extensii ale transportului tcp:// care ofera criptare SSL. Începând cu PHP 4.3.0 sus?inerea OpenSSL trebuie sa fie compilata static în PHP, începând cu PHP 5.0.0 aceasta poate fi compilata fie ca modul, sau static.

ssl:// va încerca sa negocieze o conexiune SSL V2, sau SSL V3 în dependen?a de capacita?ile ?i configurarile gazdei îndepartate. sslv2:// ?i sslv3:// va selecta protocolul SSL V2 sau SSL V3 în mod explicit.

Lista transporturilor prin socket-e sus?inute
Domeniul Unix: Unix ?i UDG
Lista transporturilor prin socket-e sus?inute


Domeniul Unix: Unix ?i UDG

unix:// ?i udg:// (udg:// începând cu PHP 5).

  • unix:///tmp/mysock
  • udg:///tmp/mysock

unix:// ofera acces la o conexiune de flux prin socket în domeniul Unix. udg:// ofera un transport alternativ unui socket din domeniul Unix utilizând protocolul datagramelor utilizatorului.

Socket-urile din domeniul Unix, spre deosebire de cele din domeniul Internet, nu necesita un numar de port. În cazul fsockopen() parametrul portno trebuie sa fie stabilit 0.

Domeniul Internet: TCP, UDP, SSL ?i TLS
Tabelele de compara?ii ale tipurilor PHP
Lista transporturilor prin socket-e sus?inute


Tabelele de compara?ii ale tipurilor PHP

Tabelele urmatoare demonstreaza comportamentul tipurilor ?i operatorilor de comparare din PHP, pentru ambele tipuri de compara?ii — libere ?i stricte. Acest supliment de asemenea are legatura ?i cu sec?iunea din manual despre jonglarea cu tipurile. Inspira?ia a fost adusa de diverse comentarii ale utilizatorilor ?i de lucrarile de la » BlueShoes.

Înainte de a utiliza aceste tabele, este important de a întelege tipurile ?i însemnatatea lor. Spre exemplu "42" este un string, în timp ce 42 este un integer. FALSE este un boolean, în timp ce "false" este un string.

Nota:

Formularele HTML nu transmit tipuri integer, float, sau boolean; ele transmit string-uri. Pentru a afla daca un string este numeric, pute?i folosi is_numeric().

Nota:

Facând, pur ?i simplu, if ($x), în timp ce $x nu este definit va genera o eroare de nivelul E_NOTICE. În loc, considera?i utilizarea empty() sau isset() ?i/sau ini?ializa?i variabilele.

Nota:

Unele opera?ii numerice pot da o valoare reprezentata de constanta NAN. Orice compara?ii lejere sau stricte ale acestei valori cu orice alta valoare, inclusiv ea însa?i, va avea un rezultat FALSE. (de ex. NAN != NAN ?i NAN !== NAN) Exemple de opera?ii care produc NAN includ sqrt(-1), asin(2) ?i asinh(0).

Compara?iile $x cu func?iile PHP
Expresia | 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 is undefined | NULL | TRUE | TRUE | FALSE | FALSE
$x = array(); | array | TRUE | FALSE | TRUE | FALSE
$x = array('a', 'b'); | array | FALSE | FALSE | TRUE | TRUE
$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

Compara?iile lejere cu ==
 | 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

Compara?iile stricte cu ===
 | 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

Domeniul Unix: Unix ?i UDG
Lista semnelor interpretorului
Anexe


Lista semnelor interpretorului

Diverse par?i ale limbajului PHP sunt reprezentate intern de tipuri precum T_SR. PHP afi?eaza asemenea identificatori în erori de interpretare astfel: "Parse error: unexpected T_SR, expecting ',' or ';' in script.php on line 10."

Trebuie sa cunoa?te?i ce reprezinta T_SR. Pentru cei ce nu cunosc, iata un tabel cu ace?ti identificatori, sintaxa PHP ?i referin?e catre locurile corespunzatoare din manual.

Nota: Utilizarea constantelor T_*

Toate semnele afi?ate mai jos sunt de asemenea definite ?i ca constante PHP. Valorile lor este generata automat în baza infrastructurii din cadrul analizatorului PHP. Aceasta înseamna ca valoarea concreta a unui semn poate sa se modifice între doua versiuni PHP. Spre exemplu constanta T_FILE este 365 în PHP 5.3, în timp ce aceea?i valoare acum se refera la T_TRAIT în PHP 5.4 ?i valoarea T_FILE este 369. Aceasta înseamna ca codul dumneavoastra nu trebuie sa se bazeze direct pe valorile T_* originale ale PHP de versiunea X.Y.Z, pentru a oferi o compatibilitate între mai multe versiuni ale PHP. În loc, în codul dumneavoastra ar trebui sa utiliza?i valori personalizate (de ex. numere mari cum ar fi 10000) ?i o strategie potrivita care va lucra cu ambele versiuni PHP ?i cu valorile T_*.

Semne
Semn | Sintaxa | Referin?a
T_ABSTRACT | abstract | Clase Abstracte (disponibil începând cu PHP 5.0.0)
T_AND_EQUAL | &= | operatori de atribuire
T_ARRAY | array() | array(), sintaxa tabloutilor
T_ARRAY_CAST | (array) | type-casting
T_AS | as | foreach
T_BAD_CHARACTER |  | orice caracter cu codul ASCII mai mic decât 32 cu excep?ia \t (0x09), \n (0x0a) ?i \r (0x0d)
T_BOOLEAN_AND | && | operatori logici
T_BOOLEAN_OR | || | operatori logici
T_BOOL_CAST | (bool) sau (boolean) | type-casting
T_BREAK | break | break
T_CALLABLE | callable | callable
T_CASE | case | switch
T_CATCH | catch | Exceptions (disponibil începând cu PHP 5.0.0)
T_CHARACTER |  | nu mai este utilizat
T_CLASS | class | clase ?i obiecte
T_CLASS_C | __CLASS__ | constante magice
T_CLONE | clone | clase ?i obiecte
T_CLOSE_TAG | ?> sau %> | evadarea din HTML
T_COMMENT | // sau #, ?i /* */ | comentarii
T_CONCAT_EQUAL | .= | operatori de atribuire
T_CONST | const | constante ale claselor
T_CONSTANT_ENCAPSED_STRING | "foo" sau 'bar' | sintaxa string-urilor
T_CONTINUE | continue | continue
T_CURLY_OPEN | {$ | sintaxa interpretata complexa a variabilei
T_DEC | -- | operatori de incrementare / decrementare
T_DECLARE | declare | declare
T_DEFAULT | default | switch
T_DIR | __DIR__ | constante magice (disponibile începând cu PHP 5.3.0)
T_DIV_EQUAL | /= | operatori de atribuire
T_DNUMBER | 0.12, etc. | numere cu virgula flotanta
T_DOC_COMMENT | /** */ | comentarii în stil PHPDoc
T_DO | do | do..while
T_DOLLAR_OPEN_CURLY_BRACES | ${ | sintaxa variabilelor interpretate complex
T_DOUBLE_ARROW | => | sintaxa tablourilor
T_DOUBLE_CAST | (real), (double) sau (float) | type-casting
T_DOUBLE_COLON | :: | vezi T_PAAMAYIM_NEKUDOTAYIM mai jos
T_ECHO | echo | echo
T_ELLIPSIS | ... | argumentele func?iilor (disponibila începând cu PHP 5.6.0)
T_ELSE | else | else
T_ELSEIF | elseif | elseif
T_EMPTY | empty | empty()
T_ENCAPSED_AND_WHITESPACE | " $a" | partea constanta a ?irurilor cu variabile
T_ENDDECLARE | enddeclare | declare, sintaxa alternativa
T_ENDFOR | endfor | for, sintaxa alternativa
T_ENDFOREACH | endforeach | foreach, sintaxa alternativa
T_ENDIF | endif | if, sintaxa alternativa
T_ENDSWITCH | endswitch | switch, sintaxa alternativa
T_ENDWHILE | endwhile | while, sintaxa alternativa
T_END_HEREDOC |  | sintaxa heredoc
T_EVAL | eval() | eval()
T_EXIT | exit sau die | exit(), die()
T_EXTENDS | extends | extends, clase ?i obiecte
T_FILE | __FILE__ | constante magice
T_FINAL | final | Final Keyword
T_FINALLY | finally | Exceptions (disponibil începând cu PHP 5.5.0)
T_FOR | for | for
T_FOREACH | foreach | foreach
T_FUNCTION | function sau cfunction | func?ii
T_FUNC_C | __FUNCTION__ | constante magice
T_GLOBAL | global | circumstan?a variabilei
T_GOTO | goto | (disponibil începând cu PHP 5.3.0)
T_HALT_COMPILER | __halt_compiler() | __halt_compiler (disponibil începând cu PHP 5.1.0)
T_IF | if | if
T_IMPLEMENTS | implements | Object Interfaces
T_INC | ++ | operatori de incrementare / decrementare
T_INCLUDE | include() | include
T_INCLUDE_ONCE | include_once() | include_once
T_INLINE_HTML |  | text în afara PHP
T_INSTANCEOF | instanceof | operatori ai tipurilor
T_INSTEADOF | insteadof | Traits (disponibila începând cu PHP 5.4.0)
T_INT_CAST | (int) sau (integer) | type-casting
T_INTERFACE | interface | Object Interfaces
T_ISSET | isset() | isset()
T_IS_EQUAL | == | operatori de comparare
T_IS_GREATER_OR_EQUAL | >= | operatori de comparare
T_IS_IDENTICAL | === | operatori de comparare
T_IS_NOT_EQUAL | != sau <> | operatori de comparare
T_IS_NOT_IDENTICAL | !== | operatori de comparare
T_IS_SMALLER_OR_EQUAL | <= | operatori de comparare
T_SPACESHIP | <=> | operatori de comparare (disponibil începând cu PHP 7.0.0)
T_LINE | __LINE__ | constante magice
T_LIST | list() | list()
T_LNUMBER | 123, 012, 0x1ac, etc. | întregi
T_LOGICAL_AND | and | operatori logici
T_LOGICAL_OR | or | operatori logici
T_LOGICAL_XOR | xor | operatori logici
T_METHOD_C | __METHOD__ | constante magice
T_MINUS_EQUAL | -= | operatori de atribuire
T_MOD_EQUAL | %= | operatori de atribuire
T_MUL_EQUAL | *= | operatori de atribuire
T_NAMESPACE | namespace | spa?iile de nume (disponibile începând cu PHP 5.3.0)
T_NS_C | __NAMESPACE__ | spa?iile de nume (disponibile începând cu PHP 5.3.0)
T_NS_SEPARATOR | \ | spa?iile de nume (disponibile începând cu PHP 5.3.0)
T_NEW | new | clase ?i obiecte
T_NUM_STRING | "$a[0]" | indice numeric al tabloului în interiorul unui string
T_OBJECT_CAST | (object) | type-casting
T_OBJECT_OPERATOR | -> | clase ?i obiecte
T_OPEN_TAG | <?php, <? sau <% | evadarea din HTML
T_OPEN_TAG_WITH_ECHO | <?= sau <%= | evadarea din HTML
T_OR_EQUAL | |= | operatori de atribuire
T_PAAMAYIM_NEKUDOTAYIM | :: | ::. De asemenea definit ca T_DOUBLE_COLON.
T_PLUS_EQUAL | += | operatori de atribuire
T_POW | ** | operatori aritmetici (disponibil începând cu PHP 5.6.0)
T_POW_EQUAL | **= | operatori de atribuire (disponibil începând cu PHP 5.6.0)
T_PRINT | print() | print
T_PRIVATE | private | clase ?i obiecte
T_PUBLIC | public | clase ?i obiecte
T_PROTECTED | protected | clase ?i obiecte
T_REQUIRE | require() | require
T_REQUIRE_ONCE | require_once() | require_once
T_RETURN | return | întoarcerea valorilor
T_SL | << | operatori pe bi?i
T_SL_EQUAL | <<= | operatori de atribuire
T_SR | >> | operatori pe bi?i
T_SR_EQUAL | >>= | operatori de atribuire
T_START_HEREDOC | <<< | sintaxa heredoc
T_STATIC | static | circumstan?a variabilei
T_STRING | parent, self, etc. | identificatori, de ex. cuvinte-cheie ca parent ?i self, denumiri de func?ii, denumiri de clase ?i altele se potrivesc. A se vedea ?i T_CONSTANT_ENCAPSED_STRING.
T_STRING_CAST | (string) | type-casting
T_STRING_VARNAME | "${a | sintaxa complexa de interpretare a variabilelor
T_SWITCH | switch | switch
T_THROW | throw | Exceptions
T_TRAIT | trait | Traits (disponibila începând cu PHP 5.4.0)
T_TRAIT_C | __TRAIT__ | __TRAIT__ (disponibila începând cu PHP 5.4.0)
T_TRY | try | Exceptions
T_UNSET | unset() | unset()
T_UNSET_CAST | (unset) | type-casting
T_USE | use | spa?ii de nume (disponibil începând cu PHP 5.3.0; rezervat începând cu PHP 4.0.0)
T_VAR | var | clase ?i obiecte
T_VARIABLE | $foo | variabile
T_WHILE | while | while, do..while
T_WHITESPACE | \t \r\n |
T_XOR_EQUAL | ^= | operatori de atribuire
T_YIELD | yield | generators (disponibila începând cu PHP 5.5.0)

A se vedea ?i token_name().

Tabelele de compara?ii ale tipurilor PHP
Ghidul de stabilire a denumirilor de catre utilizatori
Anexe


Ghidul de stabilire a denumirilor de catre utilizatori

Cuprins

  • Spa?iul global de denumiri
  • Reguli
  • Sfaturi

În continuare urmeaza un ghid pentru alegerea cea mai potrivita a denumirilor pentru identificatori în codul PHP al utilizatorului. La alegerea denumirilor în orice cod ce creaza simboluri în spa?iul global de denumiri este important de a lua în considera?ie urmatoarele sfaturi pentru a exclude posibilitatea ca versiunile viitoare ale PHP sa conflicteze cu simbolurile dumneavoastra.

Lista semnelor interpretorului
Spa?iul global de denumiri
Anexe


Spa?iul global de denumiri

Iata o trecere în revista a construc?iilor de limbaj care fac parte din spa?iul global de denumiri:

  • func?ii

  • clase

  • interfe?e

  • constante (nu constante de clasa)

  • variabile definite în afara func?iilor/metodelor

Ghidul de stabilire a denumirilor de catre utilizatori
Reguli
Ghidul de stabilire a denumirilor de catre utilizatori


Reguli

Urmatoarea lista ofera o trecere în revista a drepturilor pe care proiectul PHP ?i le rezerveaza pentru sine la alegerea denumirilor pentru identificatorii interni noi. Ghidul definitiv oficial este » STANDARDELE DE CODIFICARE:

  • PHP gestioneaza spa?iul de denumiri de nivel superior dar încearca sa gaseasca ni?te denumiri decente, descriptive pentru a evita unele conflicte evidente.

  • Denumirile func?iilor utilizeaza linii de subliniere între cuvinte, în timp ce denumirile claselor utilizeaza atât reguli de tip camelCase, cât ?i de tip PascalCase.

  • PHP va prefixa orice simbol global al unei extensii cu denumirea extensiei. (În trecut au fost numeroase excep?ii de la aceasta regula.) Exemple:

    • curl_close()

    • mysql_query()

    • PREG_SPLIT_DELIM_CAPTURE

    • new DOMDocument()

    • strpos() (exemplu al unei gre?eli din trecut)

    • new SplFileObject()

  • Iteratoarele ?i Excep?iile sunt însa pur ?i simplu sufixate cu "Iterator" ?i "Exception." Exemple:

    • ArrayIterator

    • LogicException

  • PHP rezerveaza toate simbolurile ce încep cu __ ca simboluri magice. Se recomanda sa nu crea?i în PHP simboluri ce încep cu __, doar daca dori?i sa utiliza?i func?ionalita?ile magice documentate. Exemple:

    • __get()

    • __autoload()

Spa?iul global de denumiri
Sfaturi
Ghidul de stabilire a denumirilor de catre utilizatori


Sfaturi

Pentru a scrie cod-sursa valid în viitor se recomanda sa prefixa?i (sau sa sufixa?i) orice nimere?te în spa?iul global al denumirilor cu un prefix (sau sufix) din 3-4 litere separat cu o linie de subliniere. Pentru a evita conflicte de denumiri cu alt cod-sursa este recomandabil ca proiectele în PHP sa cerceteze prefixele (sau sufixele) existente utilizate în alte proiecte ?i sa dea publicita?ii prefixele (sau sufixele) proprii. Exemple:

  • MyPx_someFunc()

  • Foo_Date

  • $asdf_dbh

Reguli
Despre manual
Ghidul de stabilire a denumirilor de catre utilizatori


Despre manual

Cuprins

  • Formate
  • Despre adnotarile utilizatorilor
  • Cum se cite?te defini?ia unei func?ii (prototipul)
  • Versiunile PHP documentate în acest manual
  • Cum sa gasim mai multa informa?ie despre PHP
  • Cum sa contribuim la îmbunata?irea documenta?iei
  • Cum generam formatele
  • Traduceri
Sfaturi
Formate
Anexe


Formate

Manualul PHP este disponibil în câteva formate. Aceste formate pot fi divizate în doua grupuri: formate, ce pot fi citite online ?i pachete, ce pot fi descarcate.

Nota:

Unii editori au pus la dispozi?ie versiuni tiparite ale acestui manual. Nu putem sa va recomandam careva din acestea, deoarece ele tind sa se învecheasca foarte repede.

Manualul poate fi citit online pe » web site-ul PHP.net, ?i pe numeroasele oglinzi ale acestuia. Pentru performan?a optima, alege?i cea mai apropiata oglinda. Versiunea online a manualului PHP are în prezent doua foi de stil CSS, o foaie de stil pentru acces web ?i una pentru tipar.

Doua avantaje remarcabile ale manualului online fa?a de majoritatea formatelor offline este integrarea adnotarilor contribuite de utilizatori ?i » scurtaturilor URL , care pot fi utilizate pentru a ajunge rapid la sec?iunea dorita a manualului. Un dezavantaj evident este necesitatea de a fi conectat online pentru a vizualiza aceasta edi?ie a manualului.

Exista cîteva formate offline ale manualului, iar cel mai potrivit format depinde de sistemul de operare ?i stilul personal al cititorului. Pentru informa?ii despre modul în care manualul este generat în a?a multe formate, pute?i citi sec?iunea 'Cum generam formatele' a acestei anexe.

Formatul manualului potrivit pentru cele mai multe platforme (sisteme de operare) este versiunea HTML. Aceasta este oferita în doua modalita?i — sub forma unui fi?ier HTML unic ?i sub forma unui pachet din mai multe fi?iere individuale pentru fiecare sec?iune (ceea ce rezulta într-o colec?ie de câteva mii de fi?iere). Noi furnizam aceste versiuni în forma comprimata, deci este necesara o utilita de decompresie pentru a capata fi?ierele con?inute în arhive.

Pentru platformele Windows, versiunea Windows HTML Help a manualului îmbunata?e?te formatul HTML pentru a fi utilizat în cadrul aplica?iei Windows HTML Help. Aceasta versiune ofera cautare deplina în text, un indice complet ?i repere de carte. Multe medii de dezvoltare PHP în Windows utilizate pe larg, de asemenea se integreaza cu aceasta versiune a documenta?iei, pentru a oferi un acces simplu. De asemenea sunt disponibile ?i programe de vizualizare CHM pentru sistemele Linux. Verifica?i » xCHM sau » GnoCHM.

De asemenea este disponibila si o » versiune CHM extinsa, care este reînnoita mai rar, dar ofera multe facilita?i suplimentare. Doar ca ea va func?iona numai pe Microsoft Windows, din cauza tehnologiilor folosite pentru a construi paginile de ajutor.

Despre manual
Despre adnotarile utilizatorilor
Despre manual


Despre adnotarile utilizatorilor

Adnotarile scrise de utilizatori joaca un rol important în dezvoltarea acestui manual. Oferind cititorilor manualului posibilitatea de a contribui cu exemple, obiec?ii ?i clarificari suplimentare direct din navigatorul lor, suntem în stare sa le încorporam apoi în textul de baza al manualului. ?i pâna când adnotarile nu au fost încorporate, ele pot fi vizualizate în forma în care au fost înscrise online ?i în unele formate offline.

Nota:

Adnotarile scrise de catre utilizatori nu sunt verificate înainte ca sa apara online, deci calitatea scrierii sau exemplele de cod-sursa, ?i chiar veridicitatea contribu?iei nu pot fi garantate. (De fapt, nu exista nici o garan?ie a calita?ii sau exactita?ii textului manualului însu?i.)

Nota:

În scopul licen?ierii corecte a materialului, adnotarile scrise de utilizatori sunt considerate ca parte integranta a manualului PHP ?i deci sunt sub inciden?a aceleia?i licen?e, care cuprinde aceasta documenta?ie (Licen?a "Creative Commons Attribution" pentru moment). Pentru mai multe detalii, accesa?i pagina de copyright a manualului.

Formate
Cum se cite?te defini?ia unei func?ii (prototipul)
Despre manual


Cum se cite?te defini?ia unei func?ii (prototipul)

Fiecare func?ie din manual este documentata pentru referin?a rapida. ?tiind cum se cite?te ?i se interpreteaza textul va face studierea PHP mult mai facila. În loc sa se bazeze pe exemple sau pe 'taiere/inserare', oricine ar trebui sa ?tie cum sa citeasca defini?iile func?iilor (prototipurile). Sa începem:

Nota: Condi?ie esen?iala: Cuno?tin?e de baza a tipurilor

Cu toate ca PHP este un limbaj liber tipizat, este important de a avea cuno?tin?e de baza a tipurilor deoarece ele au o însemnatate importanta.

Defini?iile functiilor ne spun ce tip de valoare este întoarsa. Sa folosim defini?ia pentru strlen() ca primul nostru exemplu:

strlen

(PHP 4, PHP 5)
strlen -- Ob?ine lungimea ?irului de caractere

Descrierea
int strlen ( string $string )

Întoarce lungimea ?irului dat de caractere.

Explica?ia unei defini?ii a func?iei
Partea | Descrierea
strlen | Numele func?iei.
(PHP 4, PHP 5) | strlen() este prezenta în toate versiunile PHP 4 ?i PHP 5
int | Tipul valorii, pe care aceasta func?ie o întoarce, care este integer (adica lungimea ?irului de caractere masurata în numere).
( string $string ) | Primul (?i în cazul dat unicul) parametru/argument pentru aceasta func?ie este numit string, ?i este de tipul string.

Am putea rescrie defini?ia func?iei anterioare într-o forma generica:

      tipul întors    numele func?iei    ( tipul parametrului   numele parametrului )

Multe func?ii preiau parametri multipli, cum ar fi in_array(). Prototipul sau este dupa cum urmeaza:

      bool in_array ( mixed $needle, array $haystack [, bool $strict = FALSE])

Ce înseamna aceasta? in_array() întoarce o valoare boolean, TRUE în cazul succesului (daca needle a fost gasit în haystack), sau FALSE în cazul e?ecului (daca needle nu a fost gasit în haystack). Primul parametru este numit needle ?i el poate fi de mai multe tipuri diferite, de aceea îl numim "mixed". Acest needle mixt (ceea ce cautam) poate fi o valoare scalara (string, integer, sau float), sau un array. haystack (tabloul în care efectuam cautarea) este al doilea parametru. Al treilea parametru op?ional este numit strict. To?i parametrii op?ionali se gasesc între [ astfel de paranteze ]. Mmanual afirma ca parametrul strict are valoarea implicita boolean FALSE. Vede?i pagina manualului referitoare la fiecare func?ie pentru detalii despre cum ea func?ioneaza.

În plus, simbolul & (ampersand) plasat la începutul unui parametru al func?iei permite ca parametrul sa fie transmis prin referin?a, supa cum e prezentat mai jos:

       int preg_match ( string $pattern , string $subject [, array &$matches
      [, int $flags = 0 [, int $offset = 0 ]]] )

În acest exemplu observam ca al treilea parametru op?ional &$matches va fi transmis prin referin?a.

Exista func?ii cu informa?ie mai complexa despre versiunea PHP. Sa luam html_entity_decode() ca exemplu:

(PHP 4 >= 4.3.0, PHP 5)

Aceasta înseamna ca aceasta func?ie a devenit disponibila numai începând cu versiunea PHP 4.3.0.

Despre adnotarile utilizatorilor
Versiunile PHP documentate în acest manual
Despre manual


Versiunile PHP documentate în acest manual

Acest manual con?ine informa?ii despre versiunile trecute, curente ?i viitoare ale PHP. Schimbarile în comportament sunt documentate ca adnotari, jurnale ale schimbarilor, texte incluse în paginile manualului. Cea mai anterioara versiune documentata este PHP 5.0.0.

Atunci când este disponibila documenta?ia pentru ultimele versiuni de dezvoltare (nelansate) ale PHP, ea va fi marcata ca "disponibila în Git" sau "versiune de dezvoltare". ?i cu toate ca trebuie sa fi?i pregatit pentru modificari ale acestei documenta?ii, aceasta se întâmpla în cazuri rare.

Toate lucrarile de dezvoltare se efectueaza în Git ?i pot fi verificate dupa cum este descris în pagina » accesul anonim la Git.

?i pentru a clarifica lucrurile, manualul se va referi la versiuni majore, minore ?i "punct" ale PHP. Spre exemplu în denumirea PHP 5.3.1, 5 reprezinta versiunea majora, 3 reprezinta versiunea minora ?i 1 este versiunea-punct. În mod normal PHP capata noi facilita?i doar în versiuni majore ?i minore, iar în versiunile-punct se corecteaza defectele. Oricum, însa aceasta conven?ie nu este întotdeauna adevarata.

De asemenea, retineti ca manualul PHP este scris la timpul prezent, nu la viitor, chiar si pentru facilita?i documentate care nu sunt înca disponibile. Motivul pentru aceasta este ca manualul sa poata rezista la testul timpului, prin urmare, sa nu necesite actualizari gramaticale plictisitoare cu fiecare versiune PHP.

De multe ori manualul PHP ofera "valori implicite" pentru directivele PHP. Aceste valori se bazeaza pe modul în care PHP se comporta fara fisierul de configurare php.ini, astfel ca aceste valori pot sa difere de valorile din fi?ierele php.ini-development ?i php.ini-production. Acestea se refera de asemenea la cea mai recenta versiune a PHP, desi intrarile din jurnalul de modificari fac referire la valorile din trecut. A se vedea anexa directivelor PHP pentru detalii cu privire la aceste valori si schimbarile.

Cum se cite?te defini?ia unei func?ii (prototipul)
Cum sa gasim mai multa informa?ie despre PHP
Despre manual


Cum sa gasim mai multa informa?ie despre PHP

Acest manual nu încearca sa ofere instruc?iuni despre practici generale de programare. Programatorii începatori, sau cei ce încearca PHP pentru prima data vor întâlni dificulta?i în studierea programarii în PHP folosind în exclusivitate acest manual. În acest caz, cauta?i un text orientat mai mult spre începatori.

Exista cîteva liste de distribu?ie po?tale active pentru discu?ii despre toate aspectele programarii cu PHP. Daca sunte?i bloca?i cu o problema, considera?i folosirea acestor liste de distribu?ie. Pentru a vedea op?iunile de suport, inclusiv listele de distribu?ie po?tale, vizita?i » pagina de suport PHP.net.

Versiunile PHP documentate în acest manual
Cum sa contribuim la îmbunata?irea documenta?iei
Despre manual


Cum sa contribuim la îmbunata?irea documenta?iei

Exista trei modalita?i pentru ca oricine sa contribuie la îmbunata?irea acestei documenta?ii.

Daca în acest manual este gasita o eroare, în orice limba, va rugam sa o raporta?i folosind sistemul de erori la adresa » http://bugs.php.net/. Clasifica?i eroarea ca "Documentation Problem" — "Problema în documenta?ie". Toate problemele ce ?in de documenta?ie, inclusiv cele ce ?in de formatele manualului, trebuie sa fie înaintate în calitate de rapoarte de erori.

Nota:

Va rugam sa nu abuza?i sistemul de erori înaintând cereri pentru ajutor. În schimb, folosi?i una din multitudinea de » op?iuni pentru ajutor.

Contribuind cu adnotari, utilizatorii pot furniza propriile exemple, obiec?ii ?i clarificari pentru al?i cititori. Dar va rugam sa nu trimite?i rapoarte de erori folosind sistemul de adnotari. Pentru detalii, pute?i citi sec?iunea întitulata 'Despre adnotarile utilizatorilor'.

Manualul PHP este tradus în multe limbi. Cunoa?terea englezei ?i a unei limbi straine ofera înca o modalitate de a îmbunata?i manualul PHP, lucrînd într-o echipa de traducatori. Pentru informa?ii despre începerea unei traduceri noi, sau contribuirea la o versiune deja tradusa, va rugam sa citi?i » http://doc.php.net/tutorial/.

Proiectul de Documentare PHP are de asemenea ?i un canal IRC, unde se aduna mul?i autori ai manualului. Intra?i în #php.doc la irc.efnet.org ?i discuta?i despre modalita?ile de îmbunata?ire a documenta?iei PHP.

Cum sa gasim mai multa informa?ie despre PHP
Cum generam formatele
Despre manual


Cum generam formatele

Acest manual este scris în XML folosind » DocBook XML DTD, folosind » PhD (The [PH]P based [D]ocBook renderer — interpretorul DocBook bazat pe PHP) pentru între?inere ?i formatare.

Utilizarea XML în calitate de format al sursei ofera posibilitatea de a genera multe formate de ie?ire din fi?ierele sursa, între?inerea efectuându-se pentru doar un document sursa pentru toate formatele. Unealta utilizata pentru formatarea manualului online este » PhD. Noi utilizam » Microsoft HTML Help Workshop pentru a genera formatul Windows HTML Help al manualului, ?i desugur însu?i PHP pentru a face careva transformari ?i formatari adi?ionale.

Manualul PHP este generat în diverse limbi ?i formate, vezi » http://www.php.net/docs.php pentru detalii suplimentare. Codul sursa XML poate fi descarcat din SVN ?i vizualizat la » http://svn.php.net/viewvc/. Documenta?ia este stocata în modulul phpdoc.

Cum sa contribuim la îmbunata?irea documenta?iei
Traduceri
Despre manual


Traduceri

Manualul PHP este disponibil nu numai în diverse formate, dar ?i în diverse limbi. Textul manualului este scris mai întâi în engleza, apoi echipe de oameni din toata lumea au grija sa-l traduca în limba lor de origine. Daca traducerea unei func?ii specifice sau a unui capitol nu a fost înca efectuata, sistemul de asamblare automata a manualului revine la versiunea engleza a documentului respectiv.

Persoanele implicate în traducere încep de la sursa în XML disponibila la » http://svn.php.net/viewvc/ ?i din ea efectueaza traducerea în limba lor de origine. Ei nu folosesc versiunile generate (cum ar fi HTML sau textul simplu), deoarece sistemul de asamblare are grija de conversiile din XML în formate care pot fi citite de oameni.

Nota:

Pentru a ajuta la traducerea acestei documenta?ii, va rugam sa face?i legatura cu echipa de traducere/documentare înscriindu-va la lista de distribu?ie po?tala phpdoc: trimite?i un mesaj vid la » phpdoc-subscribe@lists.php.net. Adresa listei de distribu?ie este phpdoc@lists.php.net. Men?iona?i în mesaj despre interesul dumneavoastra în traducerea manualului ?i cineva va va raspunde cu detalii despre aceea cum sa purcede?i mai departe ca sa începe?i o noua traducere, sau cum sa contacta?i echipa existenta pentru limba dorita.

La moment manualul este disponibil, par?ial sau integral, în peste 10 limbi.

Toate acestea pot fi descarcate aici: » http://www.php.net/docs.php.

Cum generam formatele
Creative Commons Attribution 3.0
Despre 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.
Traduceri
Listingul-indice
Anexe


Listingul-indice

Cuprins

  • Listingul func?iilor ?i metodelor
  • Listingul exemplelor
Creative Commons Attribution 3.0
Listingul func?iilor ?i metodelor
Anexe


Listingul func?iilor ?i metodelor

Lista tuturor func?iilor ?i metodelor din manual

a b c d e f g h i j k l m n o p q r s t u v w x y z _

  • a
    • abs - Absolute value
    • acos - Arc cosine
    • acosh - Inverse hyperbolic cosine
    • addcslashes - Quote string with slashes in a C style
    • addslashes - Quote string with slashes
    • apache_child_terminate - Termina (lichideaza) procesul apache dupa aceasta cerere
    • 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 - Efectueaza o interpelare par?iala pentru URI specificat ?i întoarce toate informa?iile despre el
    • apache_note - Ob?ine ?i stabile?te note ale interpelarilor apache
    • apache_request_headers - Fetch all HTTP request headers
    • apache_reset_timeout - Reset the Apache write timer
    • apache_response_headers - Fetch all HTTP response headers
    • apache_setenv - Stabile?te o variabila de mediu a unui subprocess Apache
    • 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
    • APCUIterator::current - Get current item
    • APCUIterator::getTotalCount - Get total count
    • APCUIterator::getTotalHits - Get total cache hits
    • APCUIterator::getTotalSize - Get total cache size
    • APCUIterator::key - Get iterator key
    • APCUIterator::next - Move pointer to next item
    • APCUIterator::rewind - Rewinds iterator
    • APCUIterator::valid - Checks if current position is valid
    • APCUIterator::__construct - Constructs an APCUIterator iterator object
    • apcu_add - Cache a new variable in the data store
    • apcu_cache_info - Retrieves cached information from APCu's data store
    • apcu_cas - Updates an old value with a new value
    • apcu_clear_cache - Clears the APCu cache
    • apcu_dec - Decrease a stored number
    • apcu_delete - Removes a stored variable from the cache
    • apcu_entry - Atomically fetch or generate a cache entry
    • apcu_exists - Checks if entry exists
    • apcu_fetch - Fetch a stored variable from the cache
    • apcu_inc - Increase a stored number
    • apcu_sma_info - Retrieves APCu Shared Memory Allocation information
    • apcu_store - Cache a variable in the data store
    • apc_add - Cache a new 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 - Gets the ArrayIterator
    • AppendIterator::getInnerIterator - Gets the 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 - Creeaza un tablou
    • ArrayAccess::offsetExists - Whether an offset exists
    • ArrayAccess::offsetGet - Offset to retrieve
    • ArrayAccess::offsetSet - Assign a value to the specified offset
    • ArrayAccess::offsetUnset - Unset an offset
    • 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 - Modifica caracterele (minuscule/majuscule) tuturor cheilor unui tablou
    • array_chunk - Desparte un tablou în por?iuni
    • array_column - Return the values from a single column in the input array
    • array_combine - Creates an array by using one array for keys and another for its values
    • array_count_values - Numara toate valorile unui tablou
    • array_diff - Calculeaza diferen?a dintre tablouri
    • array_diff_assoc - Computes the difference of arrays with additional index check
    • array_diff_key - Computes the difference of arrays using keys for comparison
    • array_diff_uassoc - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
    • array_diff_ukey - Computes the difference of arrays using a callback function on the keys for comparison
    • array_fill - Completeaza un tablou cu valori
    • array_fill_keys - Fill an array with values, specifying keys
    • array_filter - Filtreaza elementele unui tablou utilizând o func?ie de apel invers
    • array_flip - Exchanges all keys with their associated values in an array
    • array_intersect - Computes the intersection of arrays
    • array_intersect_assoc - Computes the intersection of arrays with additional index check
    • 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 - Return all the keys or a subset of the keys of an array
    • array_key_exists - Checks if the given key or index exists in the array
    • array_map - Applies the callback to the elements of the given arrays
    • array_merge - Merge one or more arrays
    • array_merge_recursive - Merge two or more arrays recursively
    • array_multisort - Sort multiple or multi-dimensional arrays
    • array_pad - Pad array to the specified length with a value
    • array_pop - Pop the element off the end of array
    • array_product - Calculate the product of values in an array
    • array_push - Push one or more elements onto the end of array
    • array_rand - Pick one or more random entries out of an array
    • array_reduce - Iteratively reduce the array to a single value using a callback function
    • 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 - Return an array with elements in reverse order
    • array_search - Searches the array for a given value and returns the first corresponding key if successful
    • array_shift - Shift an element off the beginning of array
    • array_slice - Extract a slice of the array
    • array_splice - Remove a portion of the array and replace it with something else
    • array_sum - Calculate the sum of values in an array
    • 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 - Computes the intersection of arrays with additional index check, compares data by a callback function
    • array_uintersect_uassoc - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
    • array_unique - Removes duplicate values from an array
    • array_unshift - Prepend one or more elements to the beginning of an array
    • array_values - Return all the values of an array
    • array_walk - Apply a user supplied function to every member of an array
    • array_walk_recursive - Apply a user function recursively to every member of an array
    • arsort - Sort an array in reverse order and maintain index association
    • asin - Arc sine
    • asinh - Inverse hyperbolic sine
    • asort - Sort an array and maintain index association
    • assert - Checks if assertion is FALSE
    • assert_options - Set/get the various assert flags
    • atan - Arc tangent
    • atan2 - Arc tangent of two variables
    • atanh - Inverse hyperbolic tangent
  • b
    • base64_decode - Decodes data encoded with MIME base64
    • base64_encode - Encodes data with MIME base64
    • basename - Returns trailing name component of path
    • base_convert - Convert a number between arbitrary bases
    • 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 - Add two arbitrary precision numbers
    • bccomp - Compare two arbitrary precision numbers
    • bcdiv - Divide two arbitrary precision numbers
    • bcmod - Get modulus of an arbitrary precision number
    • bcmul - Multiply two arbitrary precision numbers
    • 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 a 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 a 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 - Raise an arbitrary precision number to another
    • bcpowmod - Raise an arbitrary precision number to another, reduced by a specified modulus
    • bcscale - Set default scale parameter for all bc math functions
    • bcsqrt - Get the square root of an arbitrary precision number
    • bcsub - Subtract one arbitrary precision number from another
    • bin2hex - Convert binary data into hexadecimal representation
    • bindec - Binary to decimal
    • 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
    • blenc_encrypt - Encrypt a PHP script with BLENC.
    • boolval - Get the boolean value of a variable
    • bson_decode - Deserializes a BSON object into a PHP array
    • bson_encode - Serializes a PHP variable into a BSON string
    • bzclose - Close a bzip2 file
    • bzcompress - Compress a string into bzip2 encoded data
    • bzdecompress - Decompresses bzip2 encoded data
    • bzerrno - Returns a bzip2 error number
    • bzerror - Returns the bzip2 error number and error string in an array
    • bzerrstr - Returns a bzip2 error string
    • bzflush - Force a write of all buffered data
    • bzopen - Opens a bzip2 compressed file
    • bzread - Binary safe bzip2 file read
    • bzwrite - Binary safe bzip2 file write
  • c
    • CachingIterator::count - The number of elements in the iterator
    • CachingIterator::current - Return the current element
    • CachingIterator::getCache - Retrieve the contents of the cache
    • 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 - Pseudonim pentru 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
    • 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 - Call a user method on an specific object
    • call_user_method_array - Call a user method given with an array of parameters
    • 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 - Round fractions up
    • chdb::get - Gets the value associated with a key
    • chdb::__construct - Creates a chdb instance
    • chdb_create - Creates a chdb file
    • chdir - Change directory
    • checkdate - Valideaza o data Gregoriana
    • checkdnsrr - Check DNS records corresponding to a given Internet host name or IP address
    • chgrp - Changes file group
    • chmod - Changes file mode
    • chop - Pseudonim pentru rtrim
    • chown - Changes file owner
    • chr - Return a specific character
    • chroot - Change the root directory
    • 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 - Verifica daca clasa a fost definita
    • class_implements - Return the interfaces which are implemented by the given class or interface
    • class_parents - Return the parent classes of the given class
    • class_uses - Return the traits used by the given class
    • clearstatcache - Clears file status cache
    • cli_get_process_title - Returns the current process title
    • cli_set_process_title - Sets the process title
    • closedir - Close directory handle
    • 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::call - Binds and calls the closure
    • 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
    • Collectable::isGarbage - Determine whether an object has been marked as garbage
    • Collectable::setGarbage - Mark an object as garbage
    • compact - Create array containing variables and their values
    • 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_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
    • Cond::broadcast - Broadcast a Condition
    • Cond::create - Create a Condition
    • Cond::destroy - Destroy a Condition
    • Cond::signal - Signal a Condition
    • Cond::wait - Wait for Condition
    • connection_aborted - Check whether client disconnected
    • connection_status - Returns connection status bitfield
    • 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 - Copies file
    • cos - Cosine
    • cosh - Hyperbolic cosine
    • count - Count all elements in an array, or something in an object
    • 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 - Performs an obscure check with the given password
    • crack_closedict - Closes an open CrackLib dictionary
    • crack_getlastmessage - Returns the message from the last obscure check
    • crack_opendict - Opens a new CrackLib dictionary
    • 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 - Fetch the next row and return 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 last 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_lob2_bind - Bind a lob object or a string as a lob object to a prepared statement as parameters.
    • cubrid_lob2_close - Close LOB object.
    • cubrid_lob2_export - Export the lob object to a file.
    • cubrid_lob2_import - Import BLOB/CLOB data from a file.
    • cubrid_lob2_new - Create a lob object.
    • cubrid_lob2_read - Read from BLOB/CLOB data.
    • cubrid_lob2_seek - Move the cursor of a lob object.
    • cubrid_lob2_seek64 - Move the cursor of a lob object.
    • cubrid_lob2_size - Get a lob object's size.
    • cubrid_lob2_size64 - Get a lob object's size.
    • cubrid_lob2_tell - Tell the cursor position of the LOB object.
    • cubrid_lob2_tell64 - Tell the cursor position of the LOB object.
    • cubrid_lob2_write - Write to a lob object.
    • 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 a 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
    • CURLFile::getFilename - Get file name
    • CURLFile::getMimeType - Get MIME type
    • CURLFile::getPostFilename - Get file name for POST
    • CURLFile::setMimeType - Set MIME type
    • CURLFile::setPostFilename - Set file name for POST
    • CURLFile::__construct - Create a CURLFile object
    • CURLFile::__wakeup - Unserialization handler
    • 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_escape - URL encodes the given string
    • 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_multi_setopt - Set an option for the cURL multi handle
    • curl_multi_strerror - Return string describing error code
    • curl_pause - Pause and unpause a connection
    • curl_reset - Reset all options of a libcurl session handle
    • curl_setopt - Set an option for a cURL transfer
    • curl_setopt_array - Set multiple options for a cURL transfer
    • curl_share_close - Close a cURL share handle
    • curl_share_init - Initialize a cURL share handle
    • curl_share_setopt - Set an option for a cURL share handle.
    • curl_strerror - Return string describing the given error code
    • curl_unescape - Decodes the given URL encoded string
    • curl_version - Gets cURL version information
    • current - Return the current element in an array
    • 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 - Formateaza o ora/data
    • DateInterval::createFromDateString - Sets up a DateInterval from the relative parts of the string
    • DateInterval::format - Formats the interval
    • DateInterval::__construct - Creates a new DateInterval object
    • DatePeriod::getDateInterval - Gets the interval
    • DatePeriod::getEndDate - Gets the end date
    • DatePeriod::getStartDate - Gets the start date
    • DatePeriod::__construct - Creates a new DatePeriod object
    • DateTime::add - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
    • DateTime::createFromFormat - Parses a time string according to a 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
    • DateTimeImmutable::add - Adds an amount of days, months, years, hours, minutes and seconds
    • DateTimeImmutable::createFromFormat - Returns new DateTimeImmutable object formatted according to the specified format
    • DateTimeImmutable::createFromMutable - Returns new DateTimeImmutable object encapsulating the given DateTime object
    • DateTimeImmutable::getLastErrors - Returns the warnings and errors
    • DateTimeImmutable::modify - Creates a new object with modified timestamp
    • DateTimeImmutable::setDate - Sets the date
    • DateTimeImmutable::setISODate - Sets the ISO date
    • DateTimeImmutable::setTime - Sets the time
    • DateTimeImmutable::setTimestamp - Sets the date and time based on an Unix timestamp
    • DateTimeImmutable::setTimezone - Sets the time zone
    • DateTimeImmutable::sub - Subtracts an amount of days, months, years, hours, minutes and seconds
    • DateTimeImmutable::__construct - Returns new DateTimeImmutable object
    • DateTimeImmutable::__set_state - The __set_state 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 a numerically indexed array containing all defined timezone identifiers
    • DateTimeZone::__construct - Creates new DateTimeZone object
    • date_add - Pseudonim pentru DateTime::add
    • date_create - Pseudonim pentru DateTime::__construct
    • date_create_from_format - Pseudonim pentru DateTime::createFromFormat
    • date_create_immutable - Pseudonim pentru DateTimeImmutable::__construct
    • date_create_immutable_from_format - Pseudonim pentru DateTimeImmutable::createFromFormat
    • date_date_set - Pseudonim pentru 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 - Pseudonim pentru DateTime::diff
    • date_format - Pseudonim pentru DateTime::format
    • date_get_last_errors - Pseudonim pentru DateTime::getLastErrors
    • date_interval_create_from_date_string - Pseudonim pentru DateInterval::createFromDateString
    • date_interval_format - Pseudonim pentru DateInterval::format
    • date_isodate_set - Pseudonim pentru DateTime::setISODate
    • date_modify - Pseudonim pentru DateTime::modify
    • date_offset_get - Pseudonim pentru 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 - Pseudonim pentru 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 - Pseudonim pentru DateTime::getTimestamp
    • date_timestamp_set - Pseudonim pentru DateTime::setTimestamp
    • date_timezone_get - Pseudonim pentru DateTime::getTimezone
    • date_timezone_set - Pseudonim pentru DateTime::setTimezone
    • date_time_set - Pseudonim pentru 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
    • 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 - Decimal to binary
    • dechex - Decimal to hexadecimal
    • decoct - Decimal to octal
    • define - Defines a named constant
    • defined - Checks whether a given named constant exists
    • define_syslog_variables - Initializes all syslog related variables
    • deflate_add - Incrementally deflate data
    • deflate_init - Initialize an incremental deflate context
    • deg2rad - Converts the number in degrees to the radian equivalent
    • delete - See unlink or unset
    • dgettext - Override the current domain
    • die - Echivalenta cu 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 - Gets the file extension
    • 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 - Returns a parent directory's path
    • diskfreespace - Pseudonim pentru disk_free_space
    • disk_free_space - Returns available space on filesystem or disk partition
    • disk_total_space - Returns the total size of a filesystem or disk partition
    • dl - Loads a PHP extension at runtime
    • dngettext - Plural version of dgettext
    • dns_check_record - Pseudonim pentru checkdnsrr
    • dns_get_mx - Pseudonim pentru 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
    • 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::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
    • DOMDocument::__construct - Creates a new DOMDocument object
    • DOMDocumentFragment::appendXML - Append raw XML data
    • 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
    • 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 - Creeaza un obiect nou DOMImplementation
    • 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::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::item - Retrieves a node specified by index
    • 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
    • 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
    • dom_import_simplexml - Gets a DOMElement object from a SimpleXMLElement object
    • doubleval - Pseudonim pentru floatval
    • Ds\Collection::clear - Removes all values.
    • Ds\Collection::copy - Returns a shallow copy of the collection.
    • Ds\Collection::isEmpty - Returns whether the collection is empty
    • Ds\Collection::toArray - Converts the collection to an array.
    • Ds\Deque::allocate - Allocates enough memory for a required capacity.
    • Ds\Deque::apply - Updates all values by applying a callback function to each value.
    • Ds\Deque::capacity - Returns the current capacity.
    • Ds\Deque::clear - Removes all values from the deque.
    • Ds\Deque::contains - Determines if the deque contains given values.
    • Ds\Deque::copy - Returns a shallow copy of the deque.
    • Ds\Deque::count - Returns the number of values in the collection.
    • Ds\Deque::filter - Creates a new deque using a callable to determine which values to include.
    • Ds\Deque::find - Attempts to find a value's index.
    • Ds\Deque::first - Returns the first value in the deque.
    • Ds\Deque::get - Returns the value at a given index.
    • Ds\Deque::insert - Inserts values at a given index.
    • Ds\Deque::isEmpty - Returns whether the deque is empty
    • Ds\Deque::join - Joins all values together as a string.
    • Ds\Deque::jsonSerialize - Returns a representation that can be converted to JSON.
    • Ds\Deque::last - Returns the last value.
    • Ds\Deque::map - Returns the result of applying a callback to each value.
    • Ds\Deque::merge - Returns the result of adding all given values to the deque.
    • Ds\Deque::pop - Removes and returns the last value.
    • Ds\Deque::push - Adds values to the end of the deque.
    • Ds\Deque::reduce - Reduces the deque to a single value using a callback function.
    • Ds\Deque::remove - Removes and returns a value by index.
    • Ds\Deque::reverse - Reverses the deque in-place.
    • Ds\Deque::reversed - Returns a reversed copy.
    • Ds\Deque::rotate - Rotates the deque by a given number of rotations.
    • Ds\Deque::set - Updates a value at a given index.
    • Ds\Deque::shift - Removes and returns the first value.
    • Ds\Deque::slice - Returns a sub-deque of a given range.
    • Ds\Deque::sort - Sorts the deque in-place.
    • Ds\Deque::sorted - Returns a sorted copy.
    • Ds\Deque::sum - Returns the sum of all values in the deque.
    • Ds\Deque::toArray - Converts the deque to an array.
    • Ds\Deque::unshift - Adds values to the front of the deque.
    • Ds\Deque::__construct - Creates a new instance.
    • Ds\Hashable::equals - Determines whether an object is equal to the current instance.
    • Ds\Hashable::hash - Returns a scalar value to be used as a hash value.
    • Ds\Map::allocate - Allocates enough memory for a required capacity.
    • Ds\Map::apply - Updates all values by applying a callback function to each value.
    • Ds\Map::capacity - Returns the current capacity.
    • Ds\Map::clear - Removes all values.
    • Ds\Map::copy - Returns a shallow copy of the map.
    • Ds\Map::count - Returns the number of values in the map.
    • Ds\Map::diff - Creates a new map using keys that aren't in another map.
    • Ds\Map::filter - Creates a new map using a callable to determine which pairs to include.
    • Ds\Map::first - Returns the first pair in the map.
    • Ds\Map::get - Returns the value for a given key.
    • Ds\Map::hasKey - Determines whether the map contains a given key.
    • Ds\Map::hasValue - Determines whether the map contains a given value.
    • Ds\Map::intersect - Creates a new map by intersecting keys with another map.
    • Ds\Map::isEmpty - Returns whether the map is empty
    • Ds\Map::jsonSerialize - Returns a representation that can be converted to JSON.
    • Ds\Map::keys - Returns a set of the map's keys.
    • Ds\Map::ksort - Sorts the map in-place by key.
    • Ds\Map::ksorted - Returns a copy, sorted by key.
    • Ds\Map::last - Returns the last pair of the map.
    • Ds\Map::map - Returns the result of applying a callback to each value.
    • Ds\Map::merge - Returns the result of adding all given associations.
    • Ds\Map::pairs - Returns a sequence containing all the pairs of the map.
    • Ds\Map::put - Associates a key with a value.
    • Ds\Map::putAll - Associates all key-value pairs of a traversable object or array.
    • Ds\Map::reduce - Reduces the map to a single value using a callback function.
    • Ds\Map::remove - Removes and returns a value by key.
    • Ds\Map::reverse - Reverses the map in-place.
    • Ds\Map::reversed - Returns a reversed copy.
    • Ds\Map::skip - Returns the pair at a given positional index.
    • Ds\Map::slice - Returns a subset of the map defined by a starting index and length.
    • Ds\Map::sort - Sorts the map in-place by value.
    • Ds\Map::sorted - Returns a copy, sorted by value.
    • Ds\Map::sum - Returns the sum of all values in the map.
    • Ds\Map::toArray - Converts the map to an array.
    • Ds\Map::union - Creates a new map using values from the current instance and another map.
    • Ds\Map::values - Returns a sequence of the map's values.
    • Ds\Map::xor - Creates a new map using keys of either the current instance or of another map, but not of both.
    • Ds\Map::__construct - Creates a new instance.
    • Ds\Pair::clear - Removes all values.
    • Ds\Pair::copy - Returns a shallow copy of the pair.
    • Ds\Pair::isEmpty - Returns whether the pair is empty
    • Ds\Pair::jsonSerialize - Returns a representation that can be converted to JSON.
    • Ds\Pair::toArray - Converts the pair to an array.
    • Ds\Pair::__construct - Creates a new instance.
    • Ds\PriorityQueue::allocate - Allocates enough memory for a required capacity.
    • Ds\PriorityQueue::capacity - Returns the current capacity.
    • Ds\PriorityQueue::clear - Removes all values.
    • Ds\PriorityQueue::copy - Returns a shallow copy of the queue.
    • Ds\PriorityQueue::count - Returns the number of values in the queue.
    • Ds\PriorityQueue::isEmpty - Returns whether the queue is empty
    • Ds\PriorityQueue::jsonSerialize - Returns a representation that can be converted to JSON.
    • Ds\PriorityQueue::peek - Returns the value at the front of the queue.
    • Ds\PriorityQueue::pop - Removes and returns the value with the highest priority.
    • Ds\PriorityQueue::push - Pushes values into the queue.
    • Ds\PriorityQueue::toArray - Converts the queue to an array.
    • Ds\PriorityQueue::__construct - Creates a new instance.
    • Ds\Queue::allocate - Allocates enough memory for a required capacity.
    • Ds\Queue::capacity - Returns the current capacity.
    • Ds\Queue::clear - Removes all values.
    • Ds\Queue::copy - Returns a shallow copy of the queue.
    • Ds\Queue::count - Returns the number of values in the queue.
    • Ds\Queue::isEmpty - Returns whether the queue is empty
    • Ds\Queue::jsonSerialize - Returns a representation that can be converted to JSON.
    • Ds\Queue::peek - Returns the value at the front of the queue.
    • Ds\Queue::pop - Removes and returns the value at the front of the queue.
    • Ds\Queue::push - Pushes values into the queue.
    • Ds\Queue::toArray - Converts the queue to an array.
    • Ds\Queue::__construct - Creates a new instance.
    • Ds\Sequence::allocate - Allocates enough memory for a required capacity.
    • Ds\Sequence::apply - Updates all values by applying a callback function to each value.
    • Ds\Sequence::capacity - Returns the current capacity.
    • Ds\Sequence::contains - Determines if the sequence contains given values.
    • Ds\Sequence::filter - Creates a new sequence using a callable to determine which values to include.
    • Ds\Sequence::find - Attempts to find a value's index.
    • Ds\Sequence::first - Returns the first value in the sequence.
    • Ds\Sequence::get - Returns the value at a given index.
    • Ds\Sequence::insert - Inserts values at a given index.
    • Ds\Sequence::join - Joins all values together as a string.
    • Ds\Sequence::last - Returns the last value.
    • Ds\Sequence::map - Returns the result of applying a callback to each value.
    • Ds\Sequence::merge - Returns the result of adding all given values to the sequence.
    • Ds\Sequence::pop - Removes and returns the last value.
    • Ds\Sequence::push - Adds values to the end of the sequence.
    • Ds\Sequence::reduce - Reduces the sequence to a single value using a callback function.
    • Ds\Sequence::remove - Removes and returns a value by index.
    • Ds\Sequence::reverse - Reverses the sequence in-place.
    • Ds\Sequence::reversed - Returns a reversed copy.
    • Ds\Sequence::rotate - Rotates the sequence by a given number of rotations.
    • Ds\Sequence::set - Updates a value at a given index.
    • Ds\Sequence::shift - Removes and returns the first value.
    • Ds\Sequence::slice - Returns a sub-sequence of a given range.
    • Ds\Sequence::sort - Sorts the sequence in-place.
    • Ds\Sequence::sorted - Returns a sorted copy.
    • Ds\Sequence::sum - Returns the sum of all values in the sequence.
    • Ds\Sequence::unshift - Adds values to the front of the sequence.
    • Ds\Set::add - Adds values to the set.
    • Ds\Set::allocate - Allocates enough memory for a required capacity.
    • Ds\Set::capacity - Returns the current capacity.
    • Ds\Set::clear - Removes all values.
    • Ds\Set::contains - Determines if the set contains all values.
    • Ds\Set::copy - Returns a shallow copy of the set.
    • Ds\Set::count - Returns the number of values in the set.
    • Ds\Set::diff - Creates a new set using values that aren't in another set.
    • Ds\Set::filter - Creates a new set using a callable to determine which values to include.
    • Ds\Set::first - Returns the first value in the set.
    • Ds\Set::get - Returns the value at a given index.
    • Ds\Set::intersect - Creates a new set by intersecting values with another set.
    • Ds\Set::isEmpty - Returns whether the set is empty
    • Ds\Set::join - Joins all values together as a string.
    • Ds\Set::jsonSerialize - Returns a representation that can be converted to JSON.
    • Ds\Set::last - Returns the last value in the set.
    • Ds\Set::merge - Returns the result of adding all given values to the set.
    • Ds\Set::reduce - Reduces the set to a single value using a callback function.
    • Ds\Set::remove - Removes all given values from the set.
    • Ds\Set::reverse - Reverses the set in-place.
    • Ds\Set::reversed - Returns a reversed copy.
    • Ds\Set::slice - Returns a sub-set of a given range.
    • Ds\Set::sort - Sorts the set in-place.
    • Ds\Set::sorted - Returns a sorted copy.
    • Ds\Set::sum - Returns the sum of all values in the set.
    • Ds\Set::toArray - Converts the set to an array.
    • Ds\Set::union - Creates a new set using values from the current instance and another set.
    • Ds\Set::xor - Creates a new set using values in either the current instance or in another set, but not in both.
    • Ds\Set::__construct - Creates a new instance.
    • Ds\Stack::allocate - Allocates enough memory for a required capacity.
    • Ds\Stack::capacity - Returns the current capacity.
    • Ds\Stack::clear - Removes all values.
    • Ds\Stack::copy - Returns a shallow copy of the stack.
    • Ds\Stack::count - Returns the number of values in the stack.
    • Ds\Stack::isEmpty - Returns whether the stack is empty
    • Ds\Stack::jsonSerialize - Returns a representation that can be converted to JSON.
    • Ds\Stack::peek - Returns the value at the top of the stack.
    • Ds\Stack::pop - Removes and returns the value at the top of the stack.
    • Ds\Stack::push - Pushes values onto the stack.
    • Ds\Stack::toArray - Converts the stack to an array.
    • Ds\Stack::__construct - Creates a new instance.
    • Ds\Vector::allocate - Allocates enough memory for a required capacity.
    • Ds\Vector::apply - Updates all values by applying a callback function to each value.
    • Ds\Vector::capacity - Returns the current capacity.
    • Ds\Vector::clear - Removes all values.
    • Ds\Vector::contains - Determines if the vector contains given values.
    • Ds\Vector::copy - Returns a shallow copy of the vector.
    • Ds\Vector::count - Returns the number of values in the collection.
    • Ds\Vector::filter - Creates a new vector using a callable to determine which values to include.
    • Ds\Vector::find - Attempts to find a value's index.
    • Ds\Vector::first - Returns the first value in the vector.
    • Ds\Vector::get - Returns the value at a given index.
    • Ds\Vector::insert - Inserts values at a given index.
    • Ds\Vector::isEmpty - Returns whether the vector is empty
    • Ds\Vector::join - Joins all values together as a string.
    • Ds\Vector::jsonSerialize - Returns a representation that can be converted to JSON.
    • Ds\Vector::last - Returns the last value.
    • Ds\Vector::map - Returns the result of applying a callback to each value.
    • Ds\Vector::merge - Returns the result of adding all given values to the vector.
    • Ds\Vector::pop - Removes and returns the last value.
    • Ds\Vector::push - Adds values to the end of the vector.
    • Ds\Vector::reduce - Reduces the vector to a single value using a callback function.
    • Ds\Vector::remove - Removes and returns a value by index.
    • Ds\Vector::reverse - Reverses the vector in-place.
    • Ds\Vector::reversed - Returns a reversed copy.
    • Ds\Vector::rotate - Rotates the vector by a given number of rotations.
    • Ds\Vector::set - Updates a value at a given index.
    • Ds\Vector::shift - Removes and returns the first value.
    • Ds\Vector::slice - Returns a sub-vector of a given range.
    • Ds\Vector::sort - Sorts the vector in-place.
    • Ds\Vector::sorted - Returns a sorted copy.
    • Ds\Vector::sum - Returns the sum of all values in the vector.
    • Ds\Vector::toArray - Converts the vector to an array.
    • Ds\Vector::unshift - Adds values to the front of the vector.
    • Ds\Vector::__construct - Creates a new instance.
  • e
    • each - Return the current key and value pair from an array and advance the array cursor
    • 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_get_last_error - Returns string describing the last error associated with a request resource
    • eio_grp - Creates a 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_init - (Re-)initialize Eio
    • 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_seek - Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence
    • 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 - Determina daca o variabila este vida
    • 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_dict_path - Get the directory path for a given backend
    • 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_dict_path - Set the directory path for a given backend
    • 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 - Set the internal pointer of an array to its last element
    • ereg - Regular expression match
    • eregi - Case insensitive regular expression match
    • eregi_replace - Replace regular expression case insensitive
    • ereg_replace - Replace regular expression
    • Error::getCode - Gets the error code
    • Error::getFile - Gets the file in which the error occurred
    • Error::getLine - Gets the line in which the error occurred
    • Error::getMessage - Gets the error message
    • Error::getPrevious - Returns previous Throwable
    • Error::getTrace - Gets the stack trace
    • Error::getTraceAsString - Gets the stack trace as a string
    • Error::__clone - Clone the error
    • Error::__construct - Construct the error object
    • Error::__toString - String representation of the error
    • ErrorException::getSeverity - Gets the exception severity
    • ErrorException::__construct - Constructs the exception
    • error_clear_last - Clear the most recent error
    • error_get_last - Get the last occurred error
    • error_log - Trimite un mesaj de eroare catre rutinele definite de prelucrare a erorilor
    • error_reporting - Stabile?te ce erori PHP vor fi raportate
    • escapeshellarg - Escape a string to be used as a shell argument
    • escapeshellcmd - Escape shell metacharacters
    • Ev::backend - Returns an integer describing the backend used by libev.
    • Ev::depth - Returns recursion depth
    • Ev::embeddableBackends - Returns the set of backends that are embeddable in other event loops.
    • Ev::feedSignal - Feed a signal event info Ev
    • Ev::feedSignalEvent - Feed signal event into the default loop
    • Ev::iteration - Return the number of times the default event loop has polled for new events.
    • Ev::now - Returns the time when the last iteration of the default event loop has started.
    • Ev::nowUpdate - Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.
    • Ev::recommendedBackends - Returns a bit mask of recommended backends for current platform.
    • Ev::resume - Resume previously suspended default event loop
    • Ev::run - Begin checking for events and calling callbacks for the default loop
    • Ev::sleep - Block the process for the given number of seconds.
    • Ev::stop - Stops the default event loop
    • Ev::supportedBackends - Returns the set of backends supported by current libev configuration.
    • Ev::suspend - Suspend the default event loop
    • Ev::time - Returns the current time in fractional seconds since the epoch.
    • Ev::verify - Performs internal consistency checks(for debugging)
    • eval - Evaluate a string as PHP code
    • EvCheck::createStopped - Create instance of a stopped EvCheck watcher
    • EvCheck::__construct - Constructs the EvCheck watcher object
    • EvChild::createStopped - Create instance of a stopped EvCheck watcher
    • EvChild::set - Configures the watcher
    • EvChild::__construct - Constructs the EvChild watcher object
    • EvEmbed::createStopped - Create stopped EvEmbed watcher object
    • EvEmbed::set - Configures the watcher
    • EvEmbed::sweep - Make a single, non-blocking sweep over the embedded loop.
    • EvEmbed::__construct - Constructs the EvEmbed object
    • Event::add - Makes event pending
    • Event::addSignal - Makes signal event pending
    • Event::addTimer - Makes timer event pending
    • Event::del - Makes event non-pending
    • Event::delSignal - Makes signal event non-pending
    • Event::delTimer - Makes timer event non-pending
    • Event::free - Make event non-pending and free resources allocated for this event.
    • Event::getSupportedMethods - Returns array with of the names of the methods supported in this version of Libevent
    • Event::pending - Detects whether event is pending or scheduled
    • Event::set - Re-configures event
    • Event::setPriority - Set event priority
    • Event::setTimer - Re-configures timer event
    • Event::signal - Constructs signal event object
    • Event::timer - Constructs timer event object
    • Event::__construct - Constructs Event object
    • EventBase::dispatch - Dispatch pending events
    • EventBase::exit - Stop dispatching events
    • EventBase::free - Free resources allocated for this event base
    • EventBase::getFeatures - Returns bitmask of features supported
    • EventBase::getMethod - Returns event method in use
    • EventBase::getTimeOfDayCached - Returns the current event base time
    • EventBase::gotExit - Checks if the event loop was told to exit
    • EventBase::gotStop - Checks if the event loop was told to exit
    • EventBase::loop - Dispatch pending events
    • EventBase::priorityInit - Sets number of priorities per event base
    • EventBase::reInit - Re-initialize event base(after a fork).
    • EventBase::stop - Tells event_base to stop dispatching events
    • EventBase::__construct - Constructs EventBase object
    • EventBuffer::add - Append data to the end of an event buffer
    • EventBuffer::addBuffer - Move all data from a buffer provided to the current instance of EventBuffer
    • EventBuffer::appendFrom - Moves the specified number of bytes from a source buffer to the end of the current buffer
    • EventBuffer::copyout - Copies out specified number of bytes from the front of the buffer
    • EventBuffer::drain - Removes specified number of bytes from the front of the buffer without copying it anywhere
    • EventBuffer::enableLocking - Descrierea
    • EventBuffer::expand - Reserves space in buffer
    • EventBuffer::freeze - Prevent calls that modify an event buffer from succeeding
    • EventBuffer::lock - Acquires a lock on buffer
    • EventBuffer::prepend - Prepend data to the front of the buffer
    • EventBuffer::prependBuffer - Moves all data from source buffer to the front of current buffer
    • EventBuffer::pullup - Linearizes data within buffer and returns it's contents as a string
    • EventBuffer::read - Read data from an evbuffer and drain the bytes read
    • EventBuffer::readFrom - Read data from a file onto the end of the buffer
    • EventBuffer::readLine - Extracts a line from the front of the buffer
    • EventBuffer::search - Scans the buffer for an occurrence of a string
    • EventBuffer::searchEol - Scans the buffer for an occurrence of an end of line
    • EventBuffer::substr - Substracts a portion of the buffer data
    • EventBuffer::unfreeze - Re-enable calls that modify an event buffer
    • EventBuffer::unlock - Releases lock acquired by EventBuffer::lock
    • EventBuffer::write - Write contents of the buffer to a file or socket
    • EventBuffer::__construct - Constructs EventBuffer object
    • EventBufferEvent::close - Closes file descriptor associated with the current buffer event
    • EventBufferEvent::connect - Connect buffer event's file descriptor to given address or UNIX socket
    • EventBufferEvent::connectHost - Connects to a hostname with optionally asyncronous DNS resolving
    • EventBufferEvent::createPair - Creates two buffer events connected to each other
    • EventBufferEvent::disable - Disable events read, write, or both on a buffer event.
    • EventBufferEvent::enable - Enable events read, write, or both on a buffer event.
    • EventBufferEvent::free - Free a buffer event
    • EventBufferEvent::getDnsErrorString - Returns string describing the last failed DNS lookup attempt
    • EventBufferEvent::getEnabled - Returns bitmask of events currently enabled on the buffer event
    • EventBufferEvent::getInput - Returns underlying input buffer associated with current buffer event
    • EventBufferEvent::getOutput - Returns underlying output buffer associated with current buffer event
    • EventBufferEvent::read - Read buffer's data
    • EventBufferEvent::readBuffer - Drains the entire contents of the input buffer and places them into buf
    • EventBufferEvent::setCallbacks - Assigns read, write and event(status) callbacks
    • EventBufferEvent::setPriority - Assign a priority to a bufferevent
    • EventBufferEvent::setTimeouts - Set the read and write timeout for a buffer event
    • EventBufferEvent::setWatermark - Adjusts read and/or write watermarks
    • EventBufferEvent::sslError - Returns most recent OpenSSL error reported on the buffer event
    • EventBufferEvent::sslFilter - Create a new SSL buffer event to send its data over another buffer event
    • EventBufferEvent::sslGetCipherInfo - Returns a textual description of the cipher.
    • EventBufferEvent::sslGetCipherName - Returns the current cipher name of the SSL connection.
    • EventBufferEvent::sslGetCipherVersion - Returns version of cipher used by current SSL connection.
    • EventBufferEvent::sslGetProtocol - Returns the name of the protocol used for current SSL connection.
    • EventBufferEvent::sslRenegotiate - Tells a bufferevent to begin SSL renegotiation.
    • EventBufferEvent::sslSocket - Creates a new SSL buffer event to send its data over an SSL on a socket
    • EventBufferEvent::write - Adds data to a buffer event's output buffer
    • EventBufferEvent::writeBuffer - Adds contents of the entire buffer to a buffer event's output buffer
    • EventBufferEvent::__construct - Constructs EventBufferEvent object
    • EventConfig::avoidMethod - Tells libevent to avoid specific event method
    • EventConfig::requireFeatures - Enters a required event method feature that the application demands
    • EventConfig::setMaxDispatchInterval - Prevents priority inversion
    • EventConfig::__construct - Constructs EventConfig object
    • EventDnsBase::addNameserverIp - Adds a nameserver to the DNS base
    • EventDnsBase::addSearch - Adds a domain to the list of search domains
    • EventDnsBase::clearSearch - Removes all current search suffixes
    • EventDnsBase::countNameservers - Gets the number of configured nameservers
    • EventDnsBase::loadHosts - Loads a hosts file (in the same format as /etc/hosts) from hosts file
    • EventDnsBase::parseResolvConf - Scans the resolv.conf-formatted file
    • EventDnsBase::setOption - Set the value of a configuration option
    • EventDnsBase::setSearchNdots - Set the 'ndots' parameter for searches
    • EventDnsBase::__construct - Constructs EventDnsBase object
    • EventHttp::accept - Makes an HTTP server accept connections on the specified socket stream or resource
    • EventHttp::addServerAlias - Adds a server alias to the HTTP server object
    • EventHttp::bind - Binds an HTTP server on the specified address and port
    • EventHttp::removeServerAlias - Removes server alias
    • EventHttp::setAllowedMethods - Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks
    • EventHttp::setCallback - Sets a callback for specified URI
    • EventHttp::setDefaultCallback - Sets default callback to handle requests that are not caught by specific callbacks
    • EventHttp::setMaxBodySize - Sets maximum request body size
    • EventHttp::setMaxHeadersSize - Sets maximum HTTP header size
    • EventHttp::setTimeout - Sets the timeout for an HTTP request
    • EventHttp::__construct - Constructs EventHttp object(the HTTP server)
    • EventHttpConnection::getBase - Returns event base associated with the connection
    • EventHttpConnection::getPeer - Gets the remote address and port associated with the connection
    • EventHttpConnection::makeRequest - Makes an HTTP request over the specified connection
    • EventHttpConnection::setCloseCallback - Set callback for connection close
    • EventHttpConnection::setLocalAddress - Sets the IP address from which HTTP connections are made
    • EventHttpConnection::setLocalPort - Sets the local port from which connections are made
    • EventHttpConnection::setMaxBodySize - Sets maximum body size for the connection
    • EventHttpConnection::setMaxHeadersSize - Sets maximum header size
    • EventHttpConnection::setRetries - Sets the retry limit for the connection
    • EventHttpConnection::setTimeout - Sets the timeout for the connection
    • EventHttpConnection::__construct - Constructs EventHttpConnection object
    • EventHttpRequest::addHeader - Adds an HTTP header to the headers of the request
    • EventHttpRequest::cancel - Cancels a pending HTTP request
    • EventHttpRequest::clearHeaders - Removes all output headers from the header list of the request
    • EventHttpRequest::closeConnection - Closes associated HTTP connection
    • EventHttpRequest::findHeader - Finds the value belonging a header
    • EventHttpRequest::free - Frees the object and removes associated events
    • EventHttpRequest::getBufferEvent - Returns EventBufferEvent object
    • EventHttpRequest::getCommand - Returns the request command(method)
    • EventHttpRequest::getConnection - Returns EventHttpConnection object
    • EventHttpRequest::getHost - Returns the request host
    • EventHttpRequest::getInputBuffer - Returns the input buffer
    • EventHttpRequest::getInputHeaders - Returns associative array of the input headers
    • EventHttpRequest::getOutputBuffer - Returns the output buffer of the request
    • EventHttpRequest::getOutputHeaders - Returns associative array of the output headers
    • EventHttpRequest::getResponseCode - Returns the response code
    • EventHttpRequest::getUri - Returns the request URI
    • EventHttpRequest::removeHeader - Removes an HTTP header from the headers of the request
    • EventHttpRequest::sendError - Send an HTML error message to the client
    • EventHttpRequest::sendReply - Send an HTML reply to the client
    • EventHttpRequest::sendReplyChunk - Send another data chunk as part of an ongoing chunked reply
    • EventHttpRequest::sendReplyEnd - Complete a chunked reply, freeing the request as appropriate
    • EventHttpRequest::sendReplyStart - Initiate a chunked reply
    • EventHttpRequest::__construct - Constructs EventHttpRequest object
    • EventListener::disable - Disables an event connect listener object
    • EventListener::enable - Enables an event connect listener object
    • EventListener::getBase - Returns event base associated with the event listener
    • EventListener::getSocketName - Retreives the current address to which the listener's socket is bound.
    • EventListener::setCallback - The setCallback purpose
    • EventListener::setErrorCallback - Set event listener's error callback
    • EventListener::__construct - Creates new connection listener associated with an event base
    • EventSslContext::__construct - Constructs an OpenSSL context for use with Event classes
    • EventUtil::getLastSocketErrno - Returns the most recent socket error number
    • EventUtil::getLastSocketError - Returns the most recent socket error
    • EventUtil::getSocketFd - Returns numeric file descriptor of a socket, or stream
    • EventUtil::getSocketName - Retreives the current address to which the socket is bound.
    • EventUtil::setSocketOption - Sets socket options
    • EventUtil::sslRandPoll - Generates entropy by means of OpenSSL's RAND_poll()
    • EventUtil::__construct - The abstract constructor
    • 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_reinit - Reinitialize the event base after a fork
    • 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_new - Create new event
    • event_priority_set - Assign a priority to an event.
    • event_timer_add - Pseudonim pentru event_add
    • event_timer_del - Pseudonim pentru event_del
    • event_timer_new - Pseudonim pentru event_new
    • event_timer_set - Prepare a timer event
    • EvFork::createStopped - Creates a stopped instance of EvFork watcher class
    • EvFork::__construct - Constructs the EvFork watcher object
    • EvIdle::createStopped - Creates instance of a stopped EvIdle watcher object
    • EvIdle::__construct - Constructs the EvIdle watcher object
    • EvIo::createStopped - Create stopped EvIo watcher object
    • EvIo::set - Configures the watcher
    • EvIo::__construct - Constructs EvIo watcher object
    • EvLoop::backend - Returns an integer describing the backend used by libev.
    • EvLoop::check - Creates EvCheck object associated with the current event loop instance
    • EvLoop::child - Creates EvChild object associated with the current event loop
    • EvLoop::defaultLoop - Returns or creates the default event loop.
    • EvLoop::embed - Creates an instance of EvEmbed watcher associated with the current EvLoop object.
    • EvLoop::fork - Creates EvFork watcher object associated with the current event loop instance
    • EvLoop::idle - Creates EvIdle watcher object associated with the current event loop instance
    • EvLoop::invokePending - Invoke all pending watchers while resetting their pending state
    • EvLoop::io - Create EvIo watcher object associated with the current event loop instance
    • EvLoop::loopFork - Must be called after a fork
    • EvLoop::now - Returns the current "event loop time"
    • EvLoop::nowUpdate - Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress.
    • EvLoop::periodic - Creates EvPeriodic watcher object associated with the current event loop instance
    • EvLoop::prepare - Creates EvPrepare watcher object associated with the current event loop instance
    • EvLoop::resume - Resume previously suspended default event loop
    • EvLoop::run - Begin checking for events and calling callbacks for the loop
    • EvLoop::signal - Creates EvSignal watcher object associated with the current event loop instance
    • EvLoop::stat - Creates EvStat watcher object associated with the current event loop instance
    • EvLoop::stop - Stops the event loop
    • EvLoop::suspend - Suspend the loop
    • EvLoop::timer - Creates EvTimer watcher object associated with the current event loop instance
    • EvLoop::verify - Performs internal consistency checks(for debugging)
    • EvLoop::__construct - Constructs the event loop object
    • EvPeriodic::again - Simply stops and restarts the periodic watcher again.
    • EvPeriodic::at - Returns the absolute time that this watcher is supposed to trigger next
    • EvPeriodic::createStopped - Create a stopped EvPeriodic watcher
    • EvPeriodic::set - Configures the watcher
    • EvPeriodic::__construct - Constructs EvPeriodic watcher object
    • EvPrepare::createStopped - Creates a stopped instance of EvPrepare watcher
    • EvPrepare::__construct - Constructs EvPrepare watcher object
    • EvSignal::createStopped - Create stopped EvSignal watcher object
    • EvSignal::set - Configures the watcher
    • EvSignal::__construct - Constructs EvPeriodic watcher object
    • EvStat::attr - Returns the values most recently detected by Ev
    • EvStat::createStopped - Create a stopped EvStat watcher object
    • EvStat::prev - Returns the previous set of values returned by EvStat::attr
    • EvStat::set - Configures the watcher
    • EvStat::stat - Initiates the stat call
    • EvStat::__construct - Constructs EvStat watcher object
    • EvTimer::again - Restarts the timer watcher
    • EvTimer::createStopped - Creates EvTimer stopped watcher object
    • EvTimer::set - Configures the watcher
    • EvTimer::__construct - Constructs an EvTimer watcher object
    • EvWatcher::clear - Clear watcher pending status
    • EvWatcher::feed - Feeds the given revents set into the event loop
    • EvWatcher::getLoop - Returns the loop responsible for the watcher
    • EvWatcher::invoke - Invokes the watcher callback with the given received events bit mask
    • EvWatcher::keepalive - Configures whether to keep the loop from returning
    • EvWatcher::setCallback - Sets new callback for the watcher
    • EvWatcher::start - Starts the watcher
    • EvWatcher::stop - Stops the watcher
    • EvWatcher::__construct - Abstract constructor of a watcher object
    • Examples with PDO_4D - Examples PDO_4D
    • Exception::getCode - Gets the Exception code
    • Exception::getFile - Gets the file in which the exception was created
    • Exception::getLine - Gets the line in which the exception was created
    • 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 - Calculates the exponent of 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 - Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
    • extension_loaded - Find out whether an extension is loaded
    • extract - Import variables into the current symbol table from an array
    • ezmlm_hash - Calculeaza valoarea hash necesara 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
    • FANNConnection::getFromNeuron - Returns the postions of starting neuron.
    • FANNConnection::getToNeuron - Returns the postions of terminating neuron
    • FANNConnection::getWeight - Returns the connection weight
    • FANNConnection::setWeight - Sets the connections weight
    • FANNConnection::__construct - The connection constructor
    • fann_cascadetrain_on_data - Trains on an entire dataset, for a period of time using the Cascade2 training algorithm
    • fann_cascadetrain_on_file - Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm.
    • fann_clear_scaling_params - Clears scaling parameters
    • fann_copy - Creates a copy of a fann structure
    • fann_create_from_file - Constructs a backpropagation neural network from a configuration file
    • fann_create_shortcut - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_shortcut_array - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_sparse - Creates a standard backpropagation neural network, which is not fully connected
    • fann_create_sparse_array - Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
    • fann_create_standard - Creates a standard fully connected backpropagation neural network
    • fann_create_standard_array - Creates a standard fully connected backpropagation neural network using an array of layer sizes
    • fann_create_train - Creates an empty training data struct
    • fann_create_train_from_callback - Creates the training data struct from a user supplied function
    • fann_descale_input - Scale data in input vector after get it from ann based on previously calculated parameters
    • fann_descale_output - Scale data in output vector after get it from ann based on previously calculated parameters
    • fann_descale_train - Descale input and output data based on previously calculated parameters
    • fann_destroy - Destroys the entire network and properly freeing all the associated memory
    • fann_destroy_train - Destructs the training data
    • fann_duplicate_train_data - Returns an exact copy of a fann train data
    • fann_get_activation_function - Returns the activation function
    • fann_get_activation_steepness - Returns the activation steepness for supplied neuron and layer number
    • fann_get_bias_array - Get the number of bias in each layer in the network
    • fann_get_bit_fail - The number of fail bits
    • fann_get_bit_fail_limit - Returns the bit fail limit used during training
    • fann_get_cascade_activation_functions - Returns the cascade activation functions
    • fann_get_cascade_activation_functions_count - Returns the number of cascade activation functions
    • fann_get_cascade_activation_steepnesses - Returns the cascade activation steepnesses
    • fann_get_cascade_activation_steepnesses_count - The number of activation steepnesses
    • fann_get_cascade_candidate_change_fraction - Returns the cascade candidate change fraction
    • fann_get_cascade_candidate_limit - Return the candidate limit
    • fann_get_cascade_candidate_stagnation_epochs - Returns the number of cascade candidate stagnation epochs
    • fann_get_cascade_max_cand_epochs - Returns the maximum candidate epochs
    • fann_get_cascade_max_out_epochs - Returns the maximum out epochs
    • fann_get_cascade_min_cand_epochs - Returns the minimum candidate epochs
    • fann_get_cascade_min_out_epochs - Returns the minimum out epochs
    • fann_get_cascade_num_candidates - Returns the number of candidates used during training
    • fann_get_cascade_num_candidate_groups - Returns the number of candidate groups
    • fann_get_cascade_output_change_fraction - Returns the cascade output change fraction
    • fann_get_cascade_output_stagnation_epochs - Returns the number of cascade output stagnation epochs
    • fann_get_cascade_weight_multiplier - Returns the weight multiplier
    • fann_get_connection_array - Get connections in the network
    • fann_get_connection_rate - Get the connection rate used when the network was created
    • fann_get_errno - Returns the last error number
    • fann_get_errstr - Returns the last errstr
    • fann_get_layer_array - Get the number of neurons in each layer in the network
    • fann_get_learning_momentum - Returns the learning momentum
    • fann_get_learning_rate - Returns the learning rate
    • fann_get_MSE - Reads the mean square error from the network
    • fann_get_network_type - Get the type of neural network it was created as
    • fann_get_num_input - Get the number of input neurons
    • fann_get_num_layers - Get the number of layers in the neural network
    • fann_get_num_output - Get the number of output neurons
    • fann_get_quickprop_decay - Returns the decay which is a factor that weights should decrease in each iteration during quickprop training
    • fann_get_quickprop_mu - Returns the mu factor
    • fann_get_rprop_decrease_factor - Returns the increase factor used during RPROP training
    • fann_get_rprop_delta_max - Returns the maximum step-size
    • fann_get_rprop_delta_min - Returns the minimum step-size
    • fann_get_rprop_delta_zero - Returns the initial step-size
    • fann_get_rprop_increase_factor - Returns the increase factor used during RPROP training
    • fann_get_sarprop_step_error_shift - Returns the sarprop step error shift
    • fann_get_sarprop_step_error_threshold_factor - Returns the sarprop step error threshold factor
    • fann_get_sarprop_temperature - Returns the sarprop temperature
    • fann_get_sarprop_weight_decay_shift - Returns the sarprop weight decay shift
    • fann_get_total_connections - Get the total number of connections in the entire network
    • fann_get_total_neurons - Get the total number of neurons in the entire network
    • fann_get_training_algorithm - Returns the training algorithm
    • fann_get_train_error_function - Returns the error function used during training
    • fann_get_train_stop_function - Returns the stop function used during training
    • fann_init_weights - Initialize the weights using Widrow + Nguyen’s algorithm
    • fann_length_train_data - Returns the number of training patterns in the train data
    • fann_merge_train_data - Merges the train data
    • fann_num_input_train_data - Returns the number of inputs in each of the training patterns in the train data
    • fann_num_output_train_data - Returns the number of outputs in each of the training patterns in the train data
    • fann_print_error - Prints the error string
    • fann_randomize_weights - Give each connection a random weight between min_weight and max_weight
    • fann_read_train_from_file - Reads a file that stores training data
    • fann_reset_errno - Resets the last error number
    • fann_reset_errstr - Resets the last error string
    • fann_reset_MSE - Resets the mean square error from the network
    • fann_run - Will run input through the neural network
    • fann_save - Saves the entire network to a configuration file
    • fann_save_train - Save the training structure to a file
    • fann_scale_input - Scale data in input vector before feed it to ann based on previously calculated parameters
    • fann_scale_input_train_data - Scales the inputs in the training data to the specified range
    • fann_scale_output - Scale data in output vector before feed it to ann based on previously calculated parameters
    • fann_scale_output_train_data - Scales the outputs in the training data to the specified range
    • fann_scale_train - Scale input and output data based on previously calculated parameters
    • fann_scale_train_data - Scales the inputs and outputs in the training data to the specified range
    • fann_set_activation_function - Sets the activation function for supplied neuron and layer
    • fann_set_activation_function_hidden - Sets the activation function for all of the hidden layers
    • fann_set_activation_function_layer - Sets the activation function for all the neurons in the supplied layer.
    • fann_set_activation_function_output - Sets the activation function for the output layer
    • fann_set_activation_steepness - Sets the activation steepness for supplied neuron and layer number
    • fann_set_activation_steepness_hidden - Sets the steepness of the activation steepness for all neurons in the all hidden layers
    • fann_set_activation_steepness_layer - Sets the activation steepness for all of the neurons in the supplied layer number
    • fann_set_activation_steepness_output - Sets the steepness of the activation steepness in the output layer
    • fann_set_bit_fail_limit - Set the bit fail limit used during training
    • fann_set_callback - Sets the callback function for use during training
    • fann_set_cascade_activation_functions - Sets the array of cascade candidate activation functions
    • fann_set_cascade_activation_steepnesses - Sets the array of cascade candidate activation steepnesses
    • fann_set_cascade_candidate_change_fraction - Sets the cascade candidate change fraction
    • fann_set_cascade_candidate_limit - Sets the candidate limit
    • fann_set_cascade_candidate_stagnation_epochs - Sets the number of cascade candidate stagnation epochs
    • fann_set_cascade_max_cand_epochs - Sets the max candidate epochs
    • fann_set_cascade_max_out_epochs - Sets the maximum out epochs
    • fann_set_cascade_min_cand_epochs - Sets the min candidate epochs
    • fann_set_cascade_min_out_epochs - Sets the minimum out epochs
    • fann_set_cascade_num_candidate_groups - Sets the number of candidate groups
    • fann_set_cascade_output_change_fraction - Sets the cascade output change fraction
    • fann_set_cascade_output_stagnation_epochs - Sets the number of cascade output stagnation epochs
    • fann_set_cascade_weight_multiplier - Sets the weight multiplier
    • fann_set_error_log - Sets where the errors are logged to
    • fann_set_input_scaling_params - Calculate input scaling parameters for future use based on training data
    • fann_set_learning_momentum - Sets the learning momentum
    • fann_set_learning_rate - Sets the learning rate
    • fann_set_output_scaling_params - Calculate output scaling parameters for future use based on training data
    • fann_set_quickprop_decay - Sets the quickprop decay factor
    • fann_set_quickprop_mu - Sets the quickprop mu factor
    • fann_set_rprop_decrease_factor - Sets the decrease factor used during RPROP training
    • fann_set_rprop_delta_max - Sets the maximum step-size
    • fann_set_rprop_delta_min - Sets the minimum step-size
    • fann_set_rprop_delta_zero - Sets the initial step-size
    • fann_set_rprop_increase_factor - Sets the increase factor used during RPROP training
    • fann_set_sarprop_step_error_shift - Sets the sarprop step error shift
    • fann_set_sarprop_step_error_threshold_factor - Sets the sarprop step error threshold factor
    • fann_set_sarprop_temperature - Sets the sarprop temperature
    • fann_set_sarprop_weight_decay_shift - Sets the sarprop weight decay shift
    • fann_set_scaling_params - Calculate input and output scaling parameters for future use based on training data
    • fann_set_training_algorithm - Sets the training algorithm
    • fann_set_train_error_function - Sets the error function used during training
    • fann_set_train_stop_function - Sets the stop function used during training
    • fann_set_weight - Set a connection in the network
    • fann_set_weight_array - Set connections in the network
    • fann_shuffle_train_data - Shuffles training data, randomizing the order
    • fann_subset_train_data - Returns an copy of a subset of the train data
    • fann_test - Test with a set of inputs, and a set of desired outputs
    • fann_test_data - Test a set of training data and calculates the MSE for the training data
    • fann_train - Train one iteration with a set of inputs, and a set of desired outputs
    • fann_train_epoch - Train one epoch with a set of training data
    • fann_train_on_data - Trains on an entire dataset for a period of time
    • fann_train_on_file - Trains on an entire dataset, which is read from file, for a period of time
    • fastcgi_finish_request - Flushes all response data to the client
    • 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 - Close FrontBase connection
    • fbsql_commit - Commits a transaction to the database
    • fbsql_connect - Open a connection to a FrontBase Server
    • 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 - Get the status for a given database
    • 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 - Get name of the table the specified field is in
    • fbsql_field_type - Get the type of the specified field in a result
    • fbsql_free_result - Free result memory
    • fbsql_get_autostart_info - Descrierea
    • fbsql_hostname - Get or set the host name used with a connection
    • 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 - Get or set the user password used with a connection
    • fbsql_pconnect - Open a persistent connection to a FrontBase Server
    • fbsql_query - Send a FrontBase query
    • 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 - Change input/output character set
    • 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 - Start a database on local or remote server
    • fbsql_stop_db - Stop a database on local or remote server
    • fbsql_tablename - Pseudonim pentru fbsql_table_name
    • fbsql_table_name - Get table name of field
    • fbsql_username - Get or set the username for the connection
    • fbsql_warnings - Enable or disable FrontBase warnings
    • fclose - Closes an open file pointer
    • 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 - Tests for end-of-file on a file pointer
    • fflush - Flushes the output to a file
    • fgetc - Gets character from file pointer
    • fgetcsv - Gets line from file pointer and parse for CSV fields
    • fgets - Gets line from file pointer
    • fgetss - Gets line from file pointer and strip HTML tags
    • file - Reads entire file into an array
    • file:// - Accessing local filesystem
    • fileatime - Gets last access time of file
    • filectime - Gets inode change time of file
    • filegroup - Gets file group
    • fileinode - Gets file inode
    • filemtime - Gets file modification time
    • fileowner - Gets file owner
    • fileperms - Gets file permissions
    • 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 - Gets file size
    • 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 - Gets file type
    • file_exists - Checks whether a file or directory exists
    • 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 - Pseudonim pentru finfo_buffer()
    • finfo::file - Pseudonim pentru finfo_file()
    • finfo::set_flags - Pseudonim pentru finfo_set_flags()
    • finfo::__construct - Pseudonim pentru finfo_open
    • finfo_close - Close fileinfo resource
    • finfo_open - Create a new fileinfo resource
    • floatval - Ob?ine valoarea float a unei variabile
    • flock - Portable advisory file locking
    • floor - Round fractions down
    • flush - Flush system output buffer
    • fmod - Returns the floating point remainder (modulo) of the division of the arguments
    • fnmatch - Match filename against a pattern
    • fopen - Opens file or 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 - Pseudonim pentru fwrite
    • fread - Binary-safe file read
    • 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 - Parses input from a file according to a format
    • fseek - Seeks on a file pointer
    • fsockopen - Open Internet or Unix domain socket connection
    • fstat - Gets information about a file using an open file pointer
    • ftell - Returns the current position of the file read/write pointer
    • 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 - Changes to the parent directory
    • ftp_chdir - Changes the current directory on a FTP server
    • ftp_chmod - Set permissions on a file via FTP
    • ftp_close - Closes an FTP connection
    • ftp_connect - Opens an FTP connection
    • ftp_delete - Deletes a file on the FTP server
    • ftp_exec - Requests execution of a command on the FTP server
    • ftp_fget - Downloads a file from the FTP server and saves to an open file
    • ftp_fput - Uploads from an open file to the FTP server
    • ftp_get - Downloads a file from the FTP server
    • ftp_get_option - Retrieves various runtime behaviours of the current FTP stream
    • ftp_login - Logs in to an FTP connection
    • ftp_mdtm - Returns the last modified time of the given file
    • ftp_mkdir - Creates a directory
    • 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 - Returns a list of files in the given directory
    • ftp_pasv - Turns passive mode on or off
    • ftp_put - Uploads a file to the FTP server
    • ftp_pwd - Returns the current directory name
    • ftp_quit - Pseudonim pentru ftp_close
    • ftp_raw - Sends an arbitrary command to an FTP server
    • ftp_rawlist - Returns a detailed list of files in the given directory
    • ftp_rename - Renames a file or a directory on the FTP server
    • ftp_rmdir - Removes a directory
    • ftp_set_option - Set miscellaneous runtime FTP options
    • ftp_site - Sends a SITE command to the server
    • ftp_size - Returns the size of the given file
    • ftp_ssl_connect - Opens an Secure SSL-FTP connection
    • ftp_systype - Returns the system type identifier of the remote FTP server
    • ftruncate - Truncates a file to a given length
    • 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 - Binary-safe file write
  • 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
    • gc_mem_caches - Reclaims memory used by the Zend Engine memory manager
    • 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::setId - Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers.
    • 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
    • Gender\Gender::connect - Connect to an external name dictionary.
    • Gender\Gender::country - Get textual country representation
    • Gender\Gender::get - Get gender of a name.
    • Gender\Gender::isNick - Check if the name0 is an alias of the name1.
    • Gender\Gender::similarNames - Get similar names.
    • Gender\Gender::__construct - Construct the Gender object.
    • Generator::current - Get the yielded value
    • Generator::getReturn - Get the return value of a generator
    • Generator::key - Get the yielded key
    • Generator::next - Resume execution of the generator
    • Generator::rewind - Rewind the iterator
    • Generator::send - Send a value to the generator
    • Generator::throw - Throw an exception into the generator
    • Generator::valid - Check if the iterator has been closed
    • Generator::__wakeup - Serialize callback
    • geoip_asnum_by_name - Get the Autonomous System Numbers (ASN)
    • 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_domain_by_name - Get the second level domain name
    • geoip_id_by_name - Get the Internet connection type
    • geoip_isp_by_name - Get the Internet Service Provider (ISP) name
    • geoip_netspeedcell_by_name - Get the Internet connection speed
    • 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_setup_custom_directory - Set a custom directory for the GeoIP database.
    • geoip_time_zone_by_country_and_region - Returns the time zone for some country and region code combo
    • getallheaders - Ob?ine toate antetele interpelarii HTTP
    • getcwd - Gets the current working directory
    • getdate - Ob?ine informa?ia despre data/ora
    • 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
    • getimagesizefromstring - Get the size of an image from a string
    • 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 - Show largest possible random value
    • 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 - Ob?ine timpul curent
    • gettype - Ob?ine tipul unei variabile
    • 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 - Returns the name of the class of an object
    • get_class_methods - Gets the class methods' names
    • get_class_vars - Get the default properties of the class
    • get_current_user - Gets the name of the owner of the current PHP script
    • get_declared_classes - Returns an array with the name of the defined classes
    • 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 - Întoarce un msiv cu toate variabilele definite
    • 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 - Gets the properties of the given object
    • get_parent_class - Retrieves the parent class name for object or class
    • get_required_files - Pseudonim pentru get_included_files
    • get_resources - Returns active resources
    • get_resource_type - Întoarce tipul resursei
    • 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 - Check 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::setCompressionQuality - Sets the object's default compression quality
    • 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 - Sets 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 - Pseudonim pentru Gmagick::writeimage
    • 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 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 - Formateaza o data/ora GMT/UTC
    • gmmktime - Ob?ine momentul de timp Unix pentru o data 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 - Pseudonim pentru 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_export - Export to a binary string
    • gmp_fact - Factorial
    • gmp_gcd - Calculate GCD
    • gmp_gcdext - Calculate GCD and multipliers
    • gmp_hamdist - Hamming distance
    • gmp_import - Import from a binary string
    • 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_random_bits - Random number
    • gmp_random_range - Random number
    • gmp_random_seed - Sets the RNG seed
    • gmp_root - Take the integer part of nth root
    • gmp_rootrem - Take the integer part and remainder of nth root
    • 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 - Formateaza o data/ora GMT/UTC în conformitate cu setarile locale
    • 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 successfully
    • 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 - Pseudonim pentru 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 byte length of characters which can be included on one line of 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_equals - Timing attack safe string comparison
    • 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_pbkdf2 - Generate a PBKDF2 key derivation of a supplied password
    • 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 - Checks if or where headers have been sent
    • 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 - Decodes a hexadecimally encoded binary string
    • hexdec - Hexadecimal to decimal
    • highlight_file - Syntax highlighting of a file
    • highlight_string - Syntax highlighting of a string
    • HRTime\PerformanceCounter::getFrequency - Timer frequency in ticks per second
    • HRTime\PerformanceCounter::getTicks - Current ticks from the system
    • HRTime\PerformanceCounter::getTicksSince - Ticks elapsed since the given value
    • HRTime\StopWatch::getElapsedTicks - Get elapsed ticks for all intervals.
    • HRTime\StopWatch::getElapsedTime - Get elapsed time for all intervals.
    • HRTime\StopWatch::getLastElapsedTicks - Get elapsed ticks for the last interval.
    • HRTime\StopWatch::getLastElapsedTime - Get elapsed time for the last interval.
    • HRTime\StopWatch::isRunning - Whether the measurement is running.
    • HRTime\StopWatch::start - Start time measurement
    • HRTime\StopWatch::stop - Stop time measurement
    • 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
    • http_build_query - Generate URL-encoded query string
    • http_response_code - Get or Set the HTTP response code
    • 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
    • hypot - Calculate the length of the hypotenuse of a right-angle triangle
  • i
    • ibase_add_user - Add a user to a security database
    • 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_blob_add - Add data into a newly created blob
    • ibase_blob_cancel - Cancel creating blob
    • ibase_blob_close - Close blob
    • ibase_blob_create - Create a new blob for adding data
    • ibase_blob_echo - Output blob contents to browser
    • ibase_blob_get - Get len bytes data from open blob
    • ibase_blob_import - Create blob, copy file in it, and close it
    • ibase_blob_info - Return blob length and other useful info
    • ibase_blob_open - Open blob for retrieving data parts
    • ibase_close - Close a connection to an InterBase database
    • ibase_commit - Commit a transaction
    • ibase_commit_ret - Commit a transaction without closing it
    • ibase_connect - Open a connection to a database
    • ibase_db_info - Request statistics about a database
    • ibase_delete_user - Delete a user from a security database
    • ibase_drop_db - Drops a database
    • ibase_errcode - Return an error code
    • ibase_errmsg - Return error messages
    • ibase_execute - Execute a previously prepared query
    • ibase_fetch_assoc - Fetch a result row from a query as an associative array
    • ibase_fetch_object - Get an object from a InterBase database
    • ibase_fetch_row - Fetch a row from an InterBase database
    • ibase_field_info - Get information about a field
    • ibase_free_event_handler - Cancels a registered event handler
    • ibase_free_query - Free memory allocated by a prepared query
    • ibase_free_result - Free a result set
    • ibase_gen_id - Increments the named generator and returns its new value
    • ibase_maintain_db - Execute a maintenance command on the database server
    • ibase_modify_user - Modify a user to a security database
    • ibase_name_result - Assigns a name to a result set
    • ibase_num_fields - Get the number of fields in 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_pconnect - Open a persistent connection to an InterBase database
    • ibase_prepare - Prepare a query for later binding of parameter placeholders and execution
    • ibase_query - Execute a query on an InterBase database
    • ibase_restore - Initiates a restore task in the service manager and returns immediately
    • ibase_rollback - Roll back a transaction
    • ibase_rollback_ret - Roll back a transaction without closing it
    • ibase_server_info - Request information 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_trans - Begin a transaction
    • ibase_wait_event - Wait for an event to be posted by the database
    • iconv - Convert string to requested character encoding
    • iconv_get_encoding - Retrieve internal configuration variables of iconv extension
    • 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 - Set current setting for character encoding conversion
    • 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_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 - Creeaza un nou web server virtual
    • iis_get_dir_security - Ob?ine Securitatea Directorului
    • iis_get_script_map - Ob?ine maparea script-urilor într-un director virtual pentru o extensie specifica
    • iis_get_server_by_comment - Întoarce numarul instan?ei asociate cu Comentariul
    • iis_get_server_by_path - Întoarce numarul instan?ei asociate cu Calea
    • iis_get_server_rights - Ob?ine permisiunile serverului
    • iis_get_service_state - Întoarce starea serviciului definit prin ServiceId
    • iis_remove_server - Elimina web serverul virtual indicat de ServerInstance
    • iis_set_app_settings - Creeaza domeniul aplica?iei pentru un director virtual
    • iis_set_dir_security - Stabile?te Securitatea Directorului
    • iis_set_script_map - Stabile?te maparea script-urilor într-un director virtual
    • iis_set_server_rights - Stabile?te drepturile serverului
    • iis_start_server - Porne?te serverul web virtual
    • iis_start_service - Porne?te serviciul definit prin ServiceId
    • iis_stop_server - Opre?te serverul web virtual
    • iis_stop_service - Opre?te serviciul definit prin ServiceId
    • image2wbmp - Afi?eaza imaginea în navigator sau în fi?ier
    • imageaffine - Return an image containing the affine transformed src image, using an optional clipping area
    • imageaffinematrixconcat - Concatenate two affine transformation matrices
    • imageaffinematrixget - Get an affine transformation matrix
    • imagealphablending - Set the blending mode for an image
    • imageantialias - Should antialias functions be used or not
    • imagearc - Draws an arc
    • imagebmp - Output a BMP image to browser or file
    • 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
    • imagecreatefrombmp - Creeaza o imagine noua din fi?ier sau din URL
    • 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 - Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatefromjpeg - Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatefrompng - Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatefromstring - Create a new image from the image stream in the string
    • imagecreatefromwbmp - Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatefromwebp - Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatefromxbm - Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatefromxpm - Creeaza o imagine noua din fi?ier sau din URL
    • imagecreatetruecolor - Create a new true color image
    • imagecrop - Crop an image to the given rectangle
    • imagecropauto - Crop an image automatically using one of the available modes
    • 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
    • imageflip - Flips an image using a given mode
    • 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
    • imagegetclip - Get the clipping rectangle
    • imagegif - Afi?eaza imaginea în navigator sau în fi?ier
    • imagegrabscreen - Captures the whole screen
    • imagegrabwindow - Captures a window
    • imageinterlace - Enable or disable interlace
    • imageistruecolor - Finds whether an image is a truecolor image
    • imagejpeg - Afi?eaza imaginea în navigator sau în fi?ier
    • imagelayereffect - Set the alpha blending flag to use layering effects
    • imageline - Draw a line
    • imageloadfont - Load a new font
    • imageopenpolygon - Draws an open polygon
    • imagepalettecopy - Copy the palette from one image to another
    • imagepalettetotruecolor - Converts a palette based image to true color
    • 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
    • imageresolution - Get or set the resolution of the image
    • 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
    • imagescale - Scale an image using the given new width and height
    • imagesetbrush - Set the brush image for line drawing
    • imagesetclip - Set the clipping rectangle
    • imagesetinterpolation - Set the interpolation method
    • 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 - Afi?eaza imaginea în navigator sau în fi?ier
    • imagewebp - Output a WebP image to browser or file
    • imagexbm - Output an 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::autoLevelImage - Description
    • Imagick::averageImages - Average a set of images
    • Imagick::blackThresholdImage - Forces all pixels below the threshold into black
    • Imagick::blueShiftImage - Description
    • Imagick::blurImage - Adds blur filter to image
    • Imagick::borderImage - Surrounds the image with a border
    • Imagick::brightnessContrastImage - Description
    • Imagick::charcoalImage - Simulates a charcoal drawing
    • Imagick::chopImage - Removes a region of an image and trims
    • Imagick::clampImage - Description
    • Imagick::clear - Clears all resources associated to Imagick object
    • Imagick::clipImage - Clips along the first path from the 8BIM profile
    • Imagick::clipImagePath - Description
    • 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::colorMatrixImage - Description
    • 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::count - Description
    • 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::deleteImageProperty - Description
    • 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::filter - Description
    • 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::forwardFourierTransformImage - Description
    • 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::getImageAttribute - Description
    • 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::getImageMimeType - Description
    • 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::getQuantum - Description
    • Imagick::getQuantumDepth - Gets the quantum depth
    • Imagick::getQuantumRange - Returns the Imagick quantum range
    • Imagick::getRegistry - Description
    • 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::identifyFormat - Description
    • Imagick::identifyImage - Identifies an image and fetches attributes
    • Imagick::implodeImage - Creates a new image as a copy
    • Imagick::importImagePixels - Imports image pixels
    • Imagick::inverseFourierTransformImage - Description
    • 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::listRegistry - Description
    • 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::morphology - Description
    • 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::readimages - Description
    • 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::rotationalBlurImage - Description
    • 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::selectiveBlurImage - Description
    • 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::setImageAttribute - Description
    • Imagick::setImageBackgroundColor - Sets the image background color
    • Imagick::setImageBias - Sets the image bias for any method that convolves an image
    • Imagick::setImageBiasQuantum - Description
    • 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::setProgressMonitor - Description
    • Imagick::setRegistry - Description
    • 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::smushImages - Description
    • 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::statisticImage - Description
    • 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::subImageMatch - Description
    • 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::transformImageColorspace - Transforms an image to a new colorspace.
    • 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
    • Imagick::__toString - Returns the image as a string.
    • 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::getFontStretch - Description
    • 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::getTextInterlineSpacing - Description
    • ImagickDraw::getTextInterwordSpacing - Description
    • ImagickDraw::getTextKerning - Description
    • 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::resetVectorGraphics - Description
    • 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::setResolution - Description
    • 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 the text code set
    • ImagickDraw::setTextInterlineSpacing - Description
    • ImagickDraw::setTextInterwordSpacing - Description
    • ImagickDraw::setTextKerning - Description
    • 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
    • ImagickKernel::addKernel - Description
    • ImagickKernel::addUnityKernel - Description
    • ImagickKernel::fromBuiltIn - Description
    • ImagickKernel::fromMatrix - Description
    • ImagickKernel::getMatrix - Description
    • ImagickKernel::scale - Description
    • ImagickKernel::separate - Description
    • 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::getColorQuantum - Description
    • ImagickPixel::getColorValue - Gets the normalized value of the provided color channel
    • ImagickPixel::getColorValueQuantum - Description
    • ImagickPixel::getHSL - Returns the normalized HSL color of the ImagickPixel object
    • ImagickPixel::getIndex - Description
    • ImagickPixel::isPixelSimilar - Check the distance between this color and another
    • ImagickPixel::isPixelSimilarQuantum - Description
    • ImagickPixel::isSimilar - Check the distance between this color and another
    • ImagickPixel::setColor - Sets the color
    • ImagickPixel::setColorCount - Description
    • ImagickPixel::setColorValue - Sets the normalized value of one of the channels
    • ImagickPixel::setColorValueQuantum - Description
    • ImagickPixel::setHSL - Sets the normalized HSL color
    • ImagickPixel::setIndex - Description
    • 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 - Converte?te un string "8bit" într-un string "quoted-printable"
    • imap_alerts - Întoarce toate mesajele de alerta IMAP care au avut loc
    • 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 - Pseudonim pentru 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 occurred
    • 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 - Pseudonim pentru 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 - Pseudonim pentru 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 - Pseudonim pentru imap_list
    • imap_listscan - Returns the list of mailboxes that matches the given text
    • imap_listsubscribed - Pseudonim pentru 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 - Pseudonim pentru 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 - Pseudonim pentru imap_listscan
    • imap_scanmailbox - Pseudonim pentru imap_listscan
    • imap_search - This function returns an array of messages matching the given search criteria
    • imap_setacl - Sets the ACL for a given 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 - Importa variabilele GET/POST/Cookie în circumstan?a globala
    • 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
    • inflate_add - Incrementally inflate encoded data
    • inflate_init - Initialize an incremental inflate context
    • ingres_autocommit - Switch autocommit on or off
    • ingres_autocommit_state - Test if the connection is using autocommit
    • ingres_charset - Returns the installation character set
    • ingres_close - Close an Ingres database connection
    • ingres_commit - Commit a transaction
    • ingres_connect - Open a connection to an Ingres database
    • ingres_cursor - Get a cursor name for a given result resource
    • ingres_errno - Get the last Ingres error number generated
    • ingres_error - Get a meaningful error message for the last error generated
    • ingres_errsqlstate - Get the last SQLSTATE error code generated
    • 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 - Get the name of a field in a query result
    • ingres_field_nullable - Test if a field is nullable
    • 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 - Get the number of fields returned by the last query
    • 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 - Roll back a transaction
    • ingres_set_environment - Set environment features controlling output options
    • ingres_unbuffered_query - Send an unbuffered SQL query to Ingres
    • ini_alter - Pseudonim pentru 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
    • intdiv - Integer division
    • interface_exists - Checks if the interface has been defined
    • IntlBreakIterator::createCharacterInstance - Create break iterator for boundaries of combining character sequences
    • IntlBreakIterator::createCodePointInstance - Create break iterator for boundaries of code points
    • IntlBreakIterator::createLineInstance - Create break iterator for logically possible line breaks
    • IntlBreakIterator::createSentenceInstance - Create break iterator for sentence breaks
    • IntlBreakIterator::createTitleInstance - Create break iterator for title-casing breaks
    • IntlBreakIterator::createWordInstance - Create break iterator for word breaks
    • IntlBreakIterator::current - Get index of current position
    • IntlBreakIterator::first - Set position to the first character in the text
    • IntlBreakIterator::following - Advance the iterator to the first boundary following specified offset
    • IntlBreakIterator::getErrorCode - Get last error code on the object
    • IntlBreakIterator::getErrorMessage - Get last error message on the object
    • IntlBreakIterator::getLocale - Get the locale associated with the object
    • IntlBreakIterator::getPartsIterator - Create iterator for navigating fragments between boundaries
    • IntlBreakIterator::getText - Get the text being scanned
    • IntlBreakIterator::isBoundary - Tell whether an offset is a boundary's offset
    • IntlBreakIterator::last - Set the iterator position to index beyond the last character
    • IntlBreakIterator::next - Advance the iterator the next boundary
    • IntlBreakIterator::preceding - Set the iterator position to the first boundary before an offset
    • IntlBreakIterator::previous - Set the iterator position to the boundary immediately before the current
    • IntlBreakIterator::setText - Set the text being scanned
    • IntlBreakIterator::__construct - Private constructor for disallowing instantiation
    • IntlCalendar::add - Add a (signed) amount of time to a field
    • IntlCalendar::after - Whether this object's time is after that of the passed object
    • IntlCalendar::before - Whether this object's time is before that of the passed object
    • IntlCalendar::clear - Clear a field or all fields
    • IntlCalendar::createInstance - Create a new IntlCalendar
    • IntlCalendar::equals - Compare time of two IntlCalendar objects for equality
    • IntlCalendar::fieldDifference - Calculate difference between given time and this object's time
    • IntlCalendar::fromDateTime - Create an IntlCalendar from a DateTime object or string
    • IntlCalendar::get - Get the value for a field
    • IntlCalendar::getActualMaximum - The maximum value for a field, considering the object's current time
    • IntlCalendar::getActualMinimum - The minimum value for a field, considering the object's current time
    • IntlCalendar::getAvailableLocales - Get array of locales for which there is data
    • IntlCalendar::getDayOfWeekType - Tell whether a day is a weekday, weekend or a day that has a transition between the two
    • IntlCalendar::getErrorCode - Get last error code on the object
    • IntlCalendar::getErrorMessage - Get last error message on the object
    • IntlCalendar::getFirstDayOfWeek - Get the first day of the week for the calendar's locale
    • IntlCalendar::getGreatestMinimum - Get the largest local minimum value for a field
    • IntlCalendar::getKeywordValuesForLocale - Get set of locale keyword values
    • IntlCalendar::getLeastMaximum - Get the smallest local maximum for a field
    • IntlCalendar::getLocale - Get the locale associated with the object
    • IntlCalendar::getMaximum - Get the global maximum value for a field
    • IntlCalendar::getMinimalDaysInFirstWeek - Get minimal number of days the first week in a year or month can have
    • IntlCalendar::getMinimum - Get the global minimum value for a field
    • IntlCalendar::getNow - Get number representing the current time
    • IntlCalendar::getRepeatedWallTimeOption - Get behavior for handling repeating wall time
    • IntlCalendar::getSkippedWallTimeOption - Get behavior for handling skipped wall time
    • IntlCalendar::getTime - Get time currently represented by the object
    • IntlCalendar::getTimeZone - Get the object's timezone
    • IntlCalendar::getType - Get the calendar type
    • IntlCalendar::getWeekendTransition - Get time of the day at which weekend begins or ends
    • IntlCalendar::inDaylightTime - Whether the object's time is in Daylight Savings Time
    • IntlCalendar::isEquivalentTo - Whether another calendar is equal but for a different time
    • IntlCalendar::isLenient - Whether date/time interpretation is in lenient mode
    • IntlCalendar::isSet - Whether a field is set
    • IntlCalendar::isWeekend - Whether a certain date/time is in the weekend
    • IntlCalendar::roll - Add value to field without carrying into more significant fields
    • IntlCalendar::set - Set a time field or several common fields at once
    • IntlCalendar::setFirstDayOfWeek - Set the day on which the week is deemed to start
    • IntlCalendar::setLenient - Set whether date/time interpretation is to be lenient
    • IntlCalendar::setMinimalDaysInFirstWeek - Set minimal number of days the first week in a year or month can have
    • IntlCalendar::setRepeatedWallTimeOption - Set behavior for handling repeating wall times at negative timezone offset transitions
    • IntlCalendar::setSkippedWallTimeOption - Set behavior for handling skipped wall times at positive timezone offset transitions
    • IntlCalendar::setTime - Set the calendar time in milliseconds since the epoch
    • IntlCalendar::setTimeZone - Set the timezone used by this calendar
    • IntlCalendar::toDateTime - Convert an IntlCalendar into a DateTime object
    • IntlCalendar::__construct - Private constructor for disallowing instantiation
    • IntlChar::charAge - Get the "age" of the code point
    • IntlChar::charDigitValue - Get the decimal digit value of a decimal digit character
    • IntlChar::charDirection - Get bidirectional category value for a code point
    • IntlChar::charFromName - Find Unicode character by name and return its code point value
    • IntlChar::charMirror - Get the "mirror-image" character for a code point
    • IntlChar::charName - Retrieve the name of a Unicode character
    • IntlChar::charType - Get the general category value for a code point
    • IntlChar::chr - Return Unicode character by code point value
    • IntlChar::digit - Get the decimal digit value of a code point for a given radix
    • IntlChar::enumCharNames - Enumerate all assigned Unicode characters within a range
    • IntlChar::enumCharTypes - Enumerate all code points with their Unicode general categories
    • IntlChar::foldCase - Perform case folding on a code point
    • IntlChar::forDigit - Get character representation for a given digit and radix
    • IntlChar::getBidiPairedBracket - Get the paired bracket character for a code point
    • IntlChar::getBlockCode - Get the Unicode allocation block containing a code point
    • IntlChar::getCombiningClass - Get the combining class of a code point
    • IntlChar::getFC_NFKC_Closure - Get the FC_NFKC_Closure property for a code point
    • IntlChar::getIntPropertyMaxValue - Get the max value for a Unicode property
    • IntlChar::getIntPropertyMinValue - Get the min value for a Unicode property
    • IntlChar::getIntPropertyValue - Get the value for a Unicode property for a code point
    • IntlChar::getNumericValue - Get the numeric value for a Unicode code point
    • IntlChar::getPropertyEnum - Get the property constant value for a given property name
    • IntlChar::getPropertyName - Get the Unicode name for a property
    • IntlChar::getPropertyValueEnum - Get the property value for a given value name
    • IntlChar::getPropertyValueName - Get the Unicode name for a property value
    • IntlChar::getUnicodeVersion - Get the Unicode version
    • IntlChar::hasBinaryProperty - Check a binary Unicode property for a code point
    • IntlChar::isalnum - Check if code point is an alphanumeric character
    • IntlChar::isalpha - Check if code point is a letter character
    • IntlChar::isbase - Check if code point is a base character
    • IntlChar::isblank - Check if code point is a "blank" or "horizontal space" character
    • IntlChar::iscntrl - Check if code point is a control character
    • IntlChar::isdefined - Check whether the code point is defined
    • IntlChar::isdigit - Check if code point is a digit character
    • IntlChar::isgraph - Check if code point is a graphic character
    • IntlChar::isIDIgnorable - Check if code point is an ignorable character
    • IntlChar::isIDPart - Check if code point is permissible in an identifier
    • IntlChar::isIDStart - Check if code point is permissible as the first character in an identifier
    • IntlChar::isISOControl - Check if code point is an ISO control code
    • IntlChar::isJavaIDPart - Check if code point is permissible in a Java identifier
    • IntlChar::isJavaIDStart - Check if code point is permissible as the first character in a Java identifier
    • IntlChar::isJavaSpaceChar - Check if code point is a space character according to Java
    • IntlChar::islower - Check if code point is a lowercase letter
    • IntlChar::isMirrored - Check if code point has the Bidi_Mirrored property
    • IntlChar::isprint - Check if code point is a printable character
    • IntlChar::ispunct - Check if code point is punctuation character
    • IntlChar::isspace - Check if code point is a space character
    • IntlChar::istitle - Check if code point is a titlecase letter
    • IntlChar::isUAlphabetic - Check if code point has the Alphabetic Unicode property
    • IntlChar::isULowercase - Check if code point has the Lowercase Unicode property
    • IntlChar::isupper - Check if code point has the general category "Lu" (uppercase letter)
    • IntlChar::isUUppercase - Check if code point has the Uppercase Unicode property
    • IntlChar::isUWhiteSpace - Check if code point has the White_Space Unicode property
    • IntlChar::isWhitespace - Check if code point is a whitespace character according to ICU
    • IntlChar::isxdigit - Check if code point is a hexadecimal digit
    • IntlChar::ord - Return Unicode code point value of character
    • IntlChar::tolower - Make Unicode character lowercase
    • IntlChar::totitle - Make Unicode character titlecase
    • IntlChar::toupper - Make Unicode character uppercase
    • IntlCodePointBreakIterator::getLastCodePoint - Get last code point passed over after advancing or receding the iterator
    • IntlDateFormatter::create - Create a date formatter
    • IntlDateFormatter::format - Format the date/time value as a string
    • IntlDateFormatter::formatObject - Formats an object
    • IntlDateFormatter::getCalendar - Get the calendar type used for the IntlDateFormatter
    • IntlDateFormatter::getCalendarObject - Get copy of formatter's calendar object
    • 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::getTimeZone - Get formatter's timezone
    • 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 type used by the formatter
    • IntlDateFormatter::setLenient - Set the leniency of the parser
    • IntlDateFormatter::setPattern - Set the pattern used for the IntlDateFormatter
    • IntlDateFormatter::setTimeZone - Sets formatter's timezone
    • IntlDateFormatter::setTimeZoneId - Sets the time zone to use
    • IntlIterator::current - Get the current element
    • IntlIterator::key - Get the current key
    • IntlIterator::next - Move forward to the next element
    • IntlIterator::rewind - Rewind the iterator to the first element
    • IntlIterator::valid - Check if current position is valid
    • IntlPartsIterator::getBreakIterator - Get IntlBreakIterator backing this parts iterator
    • IntlRuleBasedBreakIterator::getBinaryRules - Get the binary form of compiled rules
    • IntlRuleBasedBreakIterator::getRules - Get the rule set used to create this object
    • IntlRuleBasedBreakIterator::getRuleStatus - Get the largest status value from the break rules that determined the current break position
    • IntlRuleBasedBreakIterator::getRuleStatusVec - Get the status values from the break rules that determined the current break position
    • IntlRuleBasedBreakIterator::__construct - Create iterator from ruleset
    • IntlTimeZone::countEquivalentIDs - Get the number of IDs in the equivalency group that includes the given ID
    • IntlTimeZone::createDefault - Create a new copy of the default timezone for this host
    • IntlTimeZone::createEnumeration - Get an enumeration over time zone IDs associated with the given country or offset
    • IntlTimeZone::createTimeZone - Create a timezone object for the given ID
    • IntlTimeZone::fromDateTimeZone - Create a timezone object from DateTimeZone
    • IntlTimeZone::getCanonicalID - Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID
    • IntlTimeZone::getDisplayName - Get a name of this time zone suitable for presentation to the user
    • IntlTimeZone::getDSTSavings - Get the amount of time to be added to local standard time to get local wall clock time
    • IntlTimeZone::getEquivalentID - Get an ID in the equivalency group that includes the given ID
    • IntlTimeZone::getErrorCode - Get last error code on the object
    • IntlTimeZone::getErrorMessage - Get last error message on the object
    • IntlTimeZone::getGMT - Create GMT (UTC) timezone
    • IntlTimeZone::getID - Get timezone ID
    • IntlTimeZone::getOffset - Get the time zone raw and GMT offset for the given moment in time
    • IntlTimeZone::getRawOffset - Get the raw GMT offset (before taking daylight savings time into account
    • IntlTimeZone::getTZDataVersion - Get the timezone data version currently used by ICU
    • IntlTimeZone::hasSameRules - Check if this zone has the same rules and offset as another zone
    • IntlTimeZone::toDateTimeZone - Convert to DateTimeZone object
    • IntlTimeZone::useDaylightTime - Check if this time zone uses daylight savings time
    • 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 - Ob?ine valoarea întreaga a unei variabile
    • in_array - Checks if a value exists in an array
    • ip2long - Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer
    • iptcembed - Embeds binary IPTC data into a JPEG image
    • iptcparse - Parse a binary IPTC block into single tags.
    • isset - Determina daca o variabla este stabilita ?i nu este NULL
    • is_a - Checks if the object is of this class or has this class as one of its parents
    • is_array - Determina daca o variabila este un array
    • is_bool - Determina daca o variabla este un boolean
    • is_callable - Verifica daca con?inutul unei variabile poate fi apelat în calitate de func?ie
    • is_dir - Tells whether the filename is a directory
    • is_double - Pseudonim pentru is_float
    • is_executable - Tells whether the filename is executable
    • is_file - Tells whether the filename is a regular file
    • is_finite - Finds whether a value is a legal finite number
    • is_float - Determina daca tipul unei variabile este float
    • is_infinite - Finds whether a value is infinite
    • is_int - Determina daca tipul unei variabile este integer
    • is_integer - Pseudonim pentru is_int
    • is_link - Tells whether the filename is a symbolic link
    • is_long - Pseudonim pentru is_int
    • is_nan - Finds whether a value is not a number
    • is_null - Determina daca o variabila este NULL
    • is_numeric - Determina daca o variabila este un numar sau un string numeric
    • is_object - Determina daca o variabila este un obiect
    • is_readable - Tells whether a file exists and is readable
    • is_real - Pseudonim pentru is_float
    • is_resource - Determina daca o variabila este o resursa
    • is_scalar - Determina daca o variabila este un scalar
    • is_soap_fault - Checks if a SOAP call has failed
    • is_string - Determina daca tipul variabilei este string
    • is_subclass_of - Checks if the object has this class as one of its parents or implements it.
    • is_tainted - Checks whether a string is tainted
    • is_uploaded_file - Tells whether the file was uploaded via HTTP POST
    • is_writable - Tells whether the filename is writable
    • is_writeable - Pseudonim pentru 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
    • 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 - Pseudonim pentru implode
    • jpeg2wbmp - Convert JPEG image file to WBMP image file
    • JsonSerializable::jsonSerialize - Specify data which should be serialized to JSON
    • json_decode - Converte?te într-o variabila un ?ir reprezentat JSON
    • json_encode - Întoarce o reprezentare JSON pentru valoarea data
    • json_last_error - Întoarce ultima eroare ce a survenit
    • json_last_error_msg - Întoarce ?irul de eroare a ultimului apel json_encode() sau json_decode()
    • 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 - Fetch a key from an array
    • key_exists - Pseudonim pentru array_key_exists
    • krsort - Sort an array by key in reverse order
    • ksort - Sort an array by key
    • 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 copyright status of an MPEG file
    • KTaglib_MPEG_AudioProperties::isOriginal - Returns if the file is marked as the original file
    • KTaglib_MPEG_AudioProperties::isProtectionEnabled - Returns if protection mechanisms of an MPEG file are enabled
    • 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
    • Lapack::eigenValues - This function returns the eigenvalues for a given square matrix
    • Lapack::identity - Return an identity matrix
    • Lapack::leastSquaresByFactorisation - Calculate the linear least squares solution of a matrix using QR factorisation
    • Lapack::leastSquaresBySVD - Solve the linear least squares problem, using SVD
    • Lapack::pseudoInverse - Calculate the inverse of a matrix
    • Lapack::singularValues - Calculated the singular values of a matrix
    • Lapack::solveLinearEquation - Solve a system of linear equations
    • lcfirst - Make a string's first character lowercase
    • lcg_value - Combined linear congruential generator
    • 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 - Pseudonim pentru ldap_unbind
    • ldap_compare - Compare value of attribute found in entry specified with DN
    • ldap_connect - Connect to an LDAP server
    • ldap_control_paged_result - Send LDAP pagination control
    • ldap_control_paged_result_response - Retrieve the LDAP pagination cookie
    • 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_escape - Escape a string for use in an LDAP filter or DN
    • 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_modify_batch - Batch and execute modifications on 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 on the client side
    • ldap_start_tls - Ini?iaza TLS
    • ldap_t61_to_8859 - Transleaza caractere t61 în caractere 8859
    • 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_external_entity_loader - Changes the default external entity loader
    • 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 - Create a hard link
    • linkinfo - Gets information about a link
    • list - Assign variables as if they were an array
    • Locale::acceptFromHttp - Tries to find out best available locale based on HTTP "Accept-Language" header
    • Locale::canonicalize - Canonicalize the locale string
    • 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 - Ob?ine timpul local
    • log - Natural logarithm
    • log1p - Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
    • log10 - Base-10 logarithm
    • log_cmd_delete - Callback When Deleting Documents
    • log_cmd_insert - Callback When Inserting Documents
    • log_cmd_update - Callback When Updating Documents
    • log_getmore - Callback When Retrieving Next Cursor Batch
    • log_killcursor - Callback When Executing KILLCURSOR operations
    • log_reply - Callback When Reading the MongoDB reply
    • log_write_batch - Callback When Writing Batches
    • long2ip - Converts an long integer address into a string in (IPv4) Internet standard dotted format
    • lstat - Gives information about a file or symbolic link
    • 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 - Pseudonim pentru set_magic_quotes_runtime
    • mail - Trimite mesaje e-mail
    • 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 - Find highest value
    • 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 - Pseudonim pentru maxdb_stmt_bind_param
    • maxdb_bind_result - Pseudonim pentru 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 - Pseudonim pentru maxdb_character_set_name
    • maxdb_close - Closes a previously opened database connection
    • maxdb_close_long_data - Pseudonim pentru 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 - Interzice citirea din stapân
    • maxdb_disable_rpl_parse - Deconecteaza interpretarea RPL
    • maxdb_dump_debug_info - Înscrie informa?ia de depanare în jurnal
    • maxdb_embedded_connect - Deschide o conexiune catre un server MaxDB încorporat
    • maxdb_enable_reads_from_master - Permite citirea din stapân
    • maxdb_enable_rpl_parse - Activeaza interpretarea RPL
    • 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 - Pseudonim pentru maxdb_real_escape_string
    • maxdb_execute - Pseudonim pentru maxdb_stmt_execute
    • maxdb_fetch - Pseudonim pentru 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 - Pseudonim pentru 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 - Impune execu?ia unei interpelari catre stapân într-o configura?ie stapân/subordonat
    • 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 - Pseudonim pentru 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 - Verifica daca interpretarea RPL este activata
    • maxdb_rpl_probe - Sonda RPL
    • maxdb_rpl_query_type - Întoarce tipul interpelarii RPL
    • maxdb_select_db - Selects the default database for database queries
    • maxdb_send_long_data - Pseudonim pentru maxdb_stmt_send_long_data
    • maxdb_send_query - Transmite interpelarea ?i întoarce execu?ia
    • maxdb_server_end - Deconecteaza serverul încorporat
    • maxdb_server_init - Ini?ializeaza serverul încorporat
    • maxdb_set_opt - Pseudonim pentru 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 - Anuleaza o declara?ie pregatita anterior
    • 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 - Întoarce informa?ia despre faptul daca protec?ia firelor de execu?ie este activata sau nu
    • 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_replace_callback - Perform a regular expresssion seach and replace with multibyte support using a callback
    • 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 - Set/Get character encoding for multibyte regex
    • 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::decrementByKey - Decrement numeric item's value, stored on a specific server
    • Memcached::delete - Delete an item
    • Memcached::deleteByKey - Delete an item from a specific server
    • Memcached::deleteMulti - Delete multiple items
    • Memcached::deleteMultiByKey - Delete multiple items 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::getAllKeys - Gets the keys stored on all the servers
    • 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::incrementByKey - Increment numeric item's value, stored on a specific server
    • Memcached::isPersistent - Check if a persitent connection to memcache is being used
    • Memcached::isPristine - Check if the instance was recently created
    • Memcached::prepend - Prepend data to an existing item
    • Memcached::prependByKey - Prepend data to an existing item on a specific server
    • Memcached::quit - Close any open connections
    • Memcached::replace - Replace the item under an existing key
    • Memcached::replaceByKey - Replace the item under an existing key on a specific server
    • Memcached::resetServerList - Clears all servers from the server list
    • 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::setOptions - Set Memcached options
    • Memcached::setSaslAuthData - Set the credentials to use for authentication
    • Memcached::touch - Set a new expiration on an item
    • Memcached::touchByKey - Set a new expiration on an item on a specific server
    • 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 - Checks if the class method exists
    • 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 - Întoarce timpul curent Unix cu microsecunde
    • mime_content_type - Detect MIME Content-type for a file
    • min - Find lowest value
    • 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 - Makes directory
    • mktime - Ob?ine timestamp-ul Unix pentru o data ?i ora
    • money_format - Formats a number as a currency string
    • Mongo::connectUtil - Connects with a database server
    • 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::poolDebug - Returns information about all connection pools.
    • Mongo::setPoolSize - Set the size for future connection pools.
    • Mongo::setSlaveOkay - Change slaveOkay setting for this connection
    • Mongo::switchSlave - Choose a new secondary for slaveOkay reads
    • Mongo::__construct - The __construct purpose
    • MongoBinData::__construct - Creates a new binary data object.
    • MongoBinData::__toString - The string representation of this binary data object.
    • MongoClient::close - Closes this connection
    • MongoClient::connect - Connects to a database server
    • MongoClient::dropDB - Drops a database [deprecated]
    • MongoClient::getConnections - Return info about all open connections
    • MongoClient::getHosts - Updates status for all associated hosts
    • MongoClient::getReadPreference - Get the read preference for this connection
    • MongoClient::getWriteConcern - Get the write concern for this connection
    • MongoClient::killCursor - Kills a specific cursor on the server
    • MongoClient::listDBs - Lists all of the databases available.
    • MongoClient::selectCollection - Gets a database collection
    • MongoClient::selectDB - Gets a database
    • MongoClient::setReadPreference - Set the read preference for this connection
    • MongoClient::setWriteConcern - Set the write concern for this connection
    • MongoClient::__construct - Creates a new database connection object
    • MongoClient::__get - Gets a database
    • MongoClient::__toString - String representation of this connection
    • MongoCode::__construct - Creates a new code object
    • MongoCode::__toString - Returns this code as a string
    • MongoCollection::aggregate - Perform an aggregation using the aggregation framework
    • MongoCollection::aggregateCursor - Execute an aggregation pipeline command and retrieve results through a cursor
    • 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::createIndex - Creates an index on the specified field(s) if it does not already exist.
    • MongoCollection::deleteIndex - Deletes an index from this collection
    • MongoCollection::deleteIndexes - Delete all indices for this collection
    • MongoCollection::distinct - Retrieve a list of distinct values for the given key across a collection.
    • MongoCollection::drop - Drops this collection
    • MongoCollection::ensureIndex - Creates an index on the specified field(s) if it does not already exist.
    • MongoCollection::find - Queries this collection, returning a MongoCursor for the result set
    • MongoCollection::findAndModify - Update a document and return it
    • MongoCollection::findOne - Queries 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::getReadPreference - Get the read preference for this collection
    • MongoCollection::getSlaveOkay - Get slaveOkay setting for this collection
    • MongoCollection::getWriteConcern - Get the write concern for this collection
    • MongoCollection::group - Performs an operation similar to SQL's GROUP BY command
    • MongoCollection::insert - Inserts a document into the collection
    • MongoCollection::parallelCollectionScan - Returns an array of cursors to iterator over a full collection in parallel
    • MongoCollection::remove - Remove records from this collection
    • MongoCollection::save - Saves a document to this collection
    • MongoCollection::setReadPreference - Set the read preference for this collection
    • MongoCollection::setSlaveOkay - Change slaveOkay setting for this collection
    • MongoCollection::setWriteConcern - Set the write concern for this database
    • 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
    • MongoCommandCursor::batchSize - Limits the number of elements returned in one batch.
    • MongoCommandCursor::createFromDocument - Create a new command cursor from an existing command response document
    • MongoCommandCursor::current - Returns the current element
    • MongoCommandCursor::dead - Checks if there are results that have not yet been sent from the database
    • MongoCommandCursor::getReadPreference - Get the read preference for this command
    • MongoCommandCursor::info - Gets information about the cursor's creation and iteration
    • MongoCommandCursor::key - Returns the current result's index within the result set
    • MongoCommandCursor::next - Advances the cursor to the next result
    • MongoCommandCursor::rewind - Executes the command and resets the cursor to the start of the result set
    • MongoCommandCursor::setReadPreference - Set the read preference for this command
    • MongoCommandCursor::timeout - Sets a client-side timeout for this command
    • MongoCommandCursor::valid - Checks if the cursor is reading a valid result.
    • MongoCommandCursor::__construct - Create a new command cursor
    • MongoCursor::addOption - Adds a top-level key/value pair to a query
    • MongoCursor::awaitData - Sets whether this cursor will wait for a while for a tailable cursor to return more data
    • MongoCursor::batchSize - Limits the number of elements returned in one batch.
    • MongoCursor::count - Counts the number of results for this query
    • MongoCursor::current - Returns the current element
    • MongoCursor::dead - Checks if there are results that have not yet been sent from the database
    • 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 - Advances the cursor to the next result, and returns that result
    • MongoCursor::getReadPreference - Get the read preference for this query
    • 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 information about the cursor's creation and iteration
    • MongoCursor::key - Returns the current result's _id, or its index within the result set
    • MongoCursor::limit - Limits the number of results returned
    • MongoCursor::maxTimeMS - Sets a server-side timeout for this query
    • MongoCursor::next - Advances the cursor to the next result, and returns that 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::setFlag - Sets arbitrary flags in case there is no method available the specific flag
    • MongoCursor::setReadPreference - Set the read preference for this query
    • MongoCursor::skip - Skips a number of results
    • MongoCursor::slaveOkay - Sets whether this query can be done on a secondary [deprecated]
    • 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
    • MongoCursorException::getHost - The hostname of the server that encountered the error
    • MongoCursorInterface::batchSize - Limits the number of elements returned in one batch.
    • MongoCursorInterface::dead - Checks if there are results that have not yet been sent from the database
    • MongoCursorInterface::getReadPreference - Get the read preference for this query
    • MongoCursorInterface::info - Gets information about the cursor's creation and iteration
    • MongoCursorInterface::setReadPreference - Set the read preference for this query
    • MongoCursorInterface::timeout - Sets a client-side timeout for this query
    • MongoDate::toDateTime - Returns a DateTime object representing this date
    • 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 [deprecated]
    • MongoDB::forceError - Creates a database error
    • MongoDB::getCollectionInfo - Returns information about collections in this database
    • MongoDB::getCollectionNames - Gets an array of names for all collections in this database
    • 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::getReadPreference - Get the read preference for this database
    • MongoDB::getSlaveOkay - Get slaveOkay setting for this database
    • MongoDB::getWriteConcern - Get the write concern for this database
    • MongoDB::lastError - Check if there was an error on the most recent db operation performed
    • MongoDB::listCollections - Gets an array of MongoCollection objects for all 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::setReadPreference - Set the read preference for this database
    • MongoDB::setSlaveOkay - Change slaveOkay setting for this database
    • MongoDB::setWriteConcern - Set the write concern for this database
    • MongoDB::__construct - Creates a new database
    • MongoDB::__get - Gets a collection
    • MongoDB::__toString - The name of this database
    • MongoDB context options - MongoDB context option listing
    • 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
    • MongoDB\BSON\Binary::getData - Returns the Binary's data
    • MongoDB\BSON\Binary::getType - Returns the Binary's type
    • MongoDB\BSON\Binary::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Binary::serialize - Serialize a Binary
    • MongoDB\BSON\Binary::unserialize - Unserialize a Binary
    • MongoDB\BSON\Binary::__construct - Construct a new Binary
    • MongoDB\BSON\Binary::__toString - Returns the Binary's data
    • MongoDB\BSON\fromJSON - Returns the BSON representation of a JSON value
    • MongoDB\BSON\fromPHP - Returns the BSON representation of a PHP value
    • MongoDB\BSON\Javascript::getCode - Returns the Javascript's code
    • MongoDB\BSON\Javascript::getScope - Returns the Javascript's scope document
    • MongoDB\BSON\Javascript::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Javascript::serialize - Serialize a Javascript
    • MongoDB\BSON\Javascript::unserialize - Unserialize a Javascript
    • MongoDB\BSON\Javascript::__construct - Construct a new Javascript
    • MongoDB\BSON\Javascript::__toString - Returns the Javascript's code
    • MongoDB\BSON\MaxKey::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\MaxKey::serialize - Serialize a MaxKey
    • MongoDB\BSON\MaxKey::unserialize - Unserialize a MaxKey
    • MongoDB\BSON\MaxKey::__construct - Construct a new MaxKey
    • MongoDB\BSON\MinKey::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\MinKey::serialize - Serialize a MinKey
    • MongoDB\BSON\MinKey::unserialize - Unserialize a MinKey
    • MongoDB\BSON\MinKey::__construct - Construct a new MinKey
    • MongoDB\BSON\ObjectID::getTimestamp - Returns the timestamp component of this ObjectID
    • MongoDB\BSON\ObjectID::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\ObjectID::serialize - Serialize an ObjectID
    • MongoDB\BSON\ObjectID::unserialize - Unserialize an ObjectID
    • MongoDB\BSON\ObjectID::__construct - Construct a new ObjectID
    • MongoDB\BSON\ObjectID::__toString - Returns the hexidecimal representation of this ObjectID
    • MongoDB\BSON\Regex::getFlags - Returns the Regex's flags
    • MongoDB\BSON\Regex::getPattern - Returns the Regex's pattern
    • MongoDB\BSON\Regex::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Regex::serialize - Serialize a Regex
    • MongoDB\BSON\Regex::unserialize - Unserialize a Regex
    • MongoDB\BSON\Regex::__construct - Construct a new Regex
    • MongoDB\BSON\Regex::__toString - Returns the string representation of this Regex
    • MongoDB\BSON\Serializable::bsonSerialize - Provides an array or document to serialize as BSON
    • MongoDB\BSON\Timestamp::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Timestamp::serialize - Serialize a Timestamp
    • MongoDB\BSON\Timestamp::unserialize - Unserialize a Timestamp
    • MongoDB\BSON\Timestamp::__construct - Construct a new Timestamp
    • MongoDB\BSON\Timestamp::__toString - Returns the string representation of this Timestamp
    • MongoDB\BSON\toJSON - Returns the JSON representation of a BSON value
    • MongoDB\BSON\toPHP - Returns the PHP representation of a BSON value
    • MongoDB\BSON\Unserializable::bsonUnserialize - Constructs the object from a BSON array or document
    • MongoDB\BSON\UTCDateTime::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\UTCDateTime::serialize - Serialize a UTCDateTime
    • MongoDB\BSON\UTCDateTime::toDateTime - Returns the DateTime representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTime::unserialize - Unserialize a UTCDateTime
    • MongoDB\BSON\UTCDateTime::__construct - Construct a new UTCDateTime
    • MongoDB\BSON\UTCDateTime::__toString - Returns the string representation of this UTCDateTime
    • MongoDB\Driver\BulkWrite::count - Count number of write operations in the bulk
    • MongoDB\Driver\BulkWrite::delete - Add a delete operation to the bulk
    • MongoDB\Driver\BulkWrite::insert - Add an insert operation to the bulk
    • MongoDB\Driver\BulkWrite::update - Add an update operation to the bulk
    • MongoDB\Driver\BulkWrite::__construct - Create a new BulkWrite
    • MongoDB\Driver\Command::__construct - Create a new Command
    • MongoDB\Driver\Cursor::getId - Returns the ID for this cursor
    • MongoDB\Driver\Cursor::getServer - Returns the server associated with this cursor
    • MongoDB\Driver\Cursor::isDead - Checks if the cursor is still open on the server
    • MongoDB\Driver\Cursor::setTypeMap - Sets a type map to use for BSON unserialization
    • MongoDB\Driver\Cursor::toArray - Returns an array containing all results for this cursor
    • MongoDB\Driver\Cursor::__construct - Create a new Cursor (not used)
    • MongoDB\Driver\CursorId::__construct - Create a new CursorId (not used)
    • MongoDB\Driver\CursorId::__toString - String representation of the cursor ID
    • MongoDB\Driver\Exception\WriteException::getWriteResult - Returns the WriteResult for the failed write operation
    • MongoDB\Driver\Manager::executeBulkWrite - Execute one or more write operations
    • MongoDB\Driver\Manager::executeCommand - Execute a database command
    • MongoDB\Driver\Manager::executeQuery - Execute a database query
    • MongoDB\Driver\Manager::getReadConcern - Return the ReadConcern for the Manager
    • MongoDB\Driver\Manager::getReadPreference - Return the ReadPreference for the Manager
    • MongoDB\Driver\Manager::getServers - Return the servers to which this manager is connected
    • MongoDB\Driver\Manager::getWriteConcern - Return the WriteConcern for the Manager
    • MongoDB\Driver\Manager::selectServer - Select a server matching a read preference
    • MongoDB\Driver\Manager::__construct - Create new MongoDB Manager
    • MongoDB\Driver\Query::__construct - Construct new Query
    • MongoDB\Driver\ReadConcern::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\ReadConcern::getLevel - Returns the ReadConcern's "level" option
    • MongoDB\Driver\ReadConcern::__construct - Construct immutable ReadConcern
    • MongoDB\Driver\ReadPreference::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\ReadPreference::getMaxStalenessSeconds - Returns the ReadPreference's "maxStalenessSeconds" option
    • MongoDB\Driver\ReadPreference::getMode - Returns the ReadPreference's "mode" option
    • MongoDB\Driver\ReadPreference::getTagSets - Returns the ReadPreference's "tagSets" option
    • MongoDB\Driver\ReadPreference::__construct - Construct immutable ReadPreference
    • MongoDB\Driver\Server::executeBulkWrite - Execute one or more write operations on this server
    • MongoDB\Driver\Server::executeCommand - Execute a database command on this server
    • MongoDB\Driver\Server::executeQuery - Execute a database query on this server
    • MongoDB\Driver\Server::getHost - Returns the hostname of this server
    • MongoDB\Driver\Server::getInfo - Returns an array of information about this server
    • MongoDB\Driver\Server::getLatency - Returns the latency of this server
    • MongoDB\Driver\Server::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Server::getTags - Returns an array of tags describing this server in a replica set
    • MongoDB\Driver\Server::getType - Returns an integer denoting the type of this server
    • MongoDB\Driver\Server::isArbiter - Checks if this server is an arbiter member of a replica set
    • MongoDB\Driver\Server::isHidden - Checks if this server is a hidden member of a replica set
    • MongoDB\Driver\Server::isPassive - Checks if this server is a passive member of a replica set
    • MongoDB\Driver\Server::isPrimary - Checks if this server is a primary member of a replica set
    • MongoDB\Driver\Server::isSecondary - Checks if this server is a secondary member of a replica set
    • MongoDB\Driver\Server::__construct - Create a new Server (not used)
    • MongoDB\Driver\WriteConcern::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\WriteConcern::getJournal - Returns the WriteConcern's "journal" option
    • MongoDB\Driver\WriteConcern::getW - Returns the WriteConcern's "w" option
    • MongoDB\Driver\WriteConcern::getWtimeout - Returns the WriteConcern's "wtimeout" option
    • MongoDB\Driver\WriteConcern::__construct - Construct immutable WriteConcern
    • MongoDB\Driver\WriteConcernError::getCode - Returns the WriteConcernError's error code
    • MongoDB\Driver\WriteConcernError::getInfo - Returns additional metadata for the WriteConcernError
    • MongoDB\Driver\WriteConcernError::getMessage - Returns the WriteConcernError's error message
    • MongoDB\Driver\WriteError::getCode - Returns the WriteError's error code
    • MongoDB\Driver\WriteError::getIndex - Returns the index of the write operation corresponding to this WriteError
    • MongoDB\Driver\WriteError::getInfo - Returns additional metadata for the WriteError
    • MongoDB\Driver\WriteError::getMessage - Returns the WriteError's error message
    • MongoDB\Driver\WriteResult::getDeletedCount - Returns the number of documents deleted
    • MongoDB\Driver\WriteResult::getInsertedCount - Returns the number of documents inserted (excluding upserts)
    • MongoDB\Driver\WriteResult::getMatchedCount - Returns the number of documents selected for update
    • MongoDB\Driver\WriteResult::getModifiedCount - Returns the number of existing documents updated
    • MongoDB\Driver\WriteResult::getServer - Returns the server associated with this write result
    • MongoDB\Driver\WriteResult::getUpsertedCount - Returns the number of documents inserted by an upsert
    • MongoDB\Driver\WriteResult::getUpsertedIds - Returns an array of identifiers for upserted documents
    • MongoDB\Driver\WriteResult::getWriteConcernError - Returns any write concern error that occurred
    • MongoDB\Driver\WriteResult::getWriteErrors - Returns any write errors that occurred
    • MongoDB\Driver\WriteResult::isAcknowledged - Returns whether the write was acknowledged
    • MongoDeleteBatch::__construct - Description
    • MongoGridFS::delete - Remove a file and its chunks 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 - Remove files and their chunks from the database
    • MongoGridFS::storeBytes - Stores a string of bytes in the database
    • MongoGridFS::storeFile - Stores a file in the database
    • MongoGridFS::storeUpload - Stores an uploaded file in 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
    • MongoId::getTimestamp - Gets the number of seconds since the epoch that this id was created
    • MongoId::isValid - Check if a value is a valid ObjectId
    • MongoId::__construct - Creates a new id
    • MongoId::__set_state - Create a dummy MongoId
    • MongoId::__toString - Returns a hexidecimal representation of this id
    • MongoInsertBatch::__construct - Description
    • 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::getCallback - Gets the previously set callback function
    • MongoLog::getLevel - Gets the level(s) currently being logged
    • MongoLog::getModule - Gets the module(s) currently being logged
    • MongoLog::setCallback - Sets a callback function to be invoked for events
    • MongoLog::setLevel - Sets the level(s) to be logged
    • MongoLog::setModule - Sets the module(s) to be logged
    • 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
    • MongoResultException::getDocument - Retrieve the full result document
    • MongoTimestamp::__construct - Creates a new timestamp.
    • MongoTimestamp::__toString - Returns a string representation of this timestamp
    • MongoUpdateBatch::__construct - Description
    • MongoWriteBatch::add - Adds a write operation to a batch
    • MongoWriteBatch::execute - Executes a batch of write operations
    • MongoWriteBatch::__construct - Creates a new batch of write operations
    • MongoWriteConcernException::getDocument - Get the error document
    • move_uploaded_file - Moves an uploaded file to a new location
    • 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 - Efectueaza conectarea la un server msession
    • msession_count - Ob?ine numarul de sesiuni
    • msession_create - Creeaza o sesiune
    • msession_destroy - Distruge o sesiune
    • msession_disconnect - Închide conexiunea catre serverul msession
    • msession_find - Gase?te toate sesiunile dupa denumire ?i valoare
    • msession_get - Ob?ine valoarea din sesiune
    • msession_get_array - Ob?ine tabloul variabilelor msession
    • msession_get_data - Ob?ine datele nestructurate a unei sesiuni de date
    • msession_inc - Incrementeaza valoarea din sesiune
    • msession_list - Listeaza toate sesiunile
    • msession_listvar - Listeaza sessiunile cu variabila
    • msession_lock - Încuie o sesiune
    • msession_plugin - Apeleaza o func?ie de evadare în interiorul personalita?ii modulului msession
    • msession_randstr - Ob?ine un ?ir aleator
    • msession_set - Stabile?te o valoare în sesiune
    • msession_set_array - Stabile?te variabilele msession dintr-un tablou
    • msession_set_data - Stabile?te datele nestructurate a unei sesiuni de date
    • msession_timeout - Stabile?te/ob?ine limita de timp pentru sesiune
    • msession_uniq - Ob?ine un identificator unic
    • msession_unlock - Descuie o sesiune
    • 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 - Pseudonim al msql_db_query
    • msql_affected_rows - Returns number of affected rows
    • msql_close - Close mSQL connection
    • msql_connect - Open mSQL connection
    • msql_createdb - Pseudonim pentru msql_create_db
    • msql_create_db - Create mSQL database
    • msql_data_seek - Move internal row pointer
    • msql_dbname - Pseudonim pentru msql_result
    • msql_db_query - Send mSQL query
    • msql_drop_db - Drop (delete) mSQL database
    • 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 - Pseudonim al msql_field_flags
    • msql_fieldlen - Pseudonim al msql_field_len
    • msql_fieldname - Pseudonim al msql_field_name
    • msql_fieldtable - Pseudonim al msql_field_table
    • msql_fieldtype - Pseudonim al 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 - Pseudonim al msql_num_fields
    • msql_numrows - Pseudonim al msql_num_rows
    • msql_num_fields - Get number of fields in result
    • msql_num_rows - Get number of rows in result
    • msql_pconnect - Open persistent mSQL connection
    • msql_query - Send mSQL query
    • msql_regcase - Pseudonim al sql_regcase
    • msql_result - Get result data
    • msql_select_db - Select mSQL database
    • msql_tablename - Pseudonim al msql_result
    • mssql_bind - Adds a parameter to a stored procedure or a remote stored procedure
    • mssql_close - Close MS SQL Server connection
    • mssql_connect - Open MS SQL server connection
    • 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 - Returns the last message from the server
    • 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 - Sets the minimum error severity
    • mssql_min_message_severity - Sets the minimum message severity
    • mssql_next_result - Move the internal result pointer to the next result
    • mssql_num_fields - Gets the number of fields in result
    • mssql_num_rows - Gets the number of rows in result
    • mssql_pconnect - Open persistent MS SQL connection
    • mssql_query - Send MS SQL query
    • mssql_result - Get result data
    • mssql_rows_affected - Returns the number of records affected by the query
    • mssql_select_db - Select MS SQL database
    • mt_getrandmax - Show largest possible random value
    • mt_rand - Generate a random value via the Mersenne Twister Random Number Generator
    • mt_srand - Seeds the Mersenne Twister Random Number Generator
    • 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
    • Mutex::create - Create a Mutex
    • Mutex::destroy - Destroy Mutex
    • Mutex::lock - Acquire Mutex
    • Mutex::trylock - Attempt to Acquire Mutex
    • Mutex::unlock - Release Mutex
    • mysqli::$affected_rows - Gets the number of affected rows in a previous MySQL operation
    • mysqli::$client_info - 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::$error_list - Returns a list of errors from the last command executed
    • 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 latest 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-committing database modifications
    • mysqli::begin_transaction - Starts a transaction
    • 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 - Get MySQL client info
    • 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::release_savepoint - Removes the named savepoint from the set of savepoints of the current transaction
    • mysqli::rollback - Rolls back current transaction
    • mysqli::rpl_query_type - Returns RPL query type
    • mysqli::savepoint - Set a named transaction savepoint
    • 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::set_opt - Pseudonim al mysqli_options
    • 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 - Pseudonim pentru mysqli::__construct
    • mysqli_disable_rpl_parse - Disable RPL parse
    • mysqli_driver::$report_mode - Enables or disables internal report functions
    • 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 - Pseudonim pentru 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_client_version - Returns the MySQL client version as an integer
    • mysqli_get_links_stats - Return information about open and cached links
    • 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 - Pseudonim pentru mysqli_driver->report_mode
    • 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 arbitrary 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_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::$error_list - Returns a list of errors from the last statement executed
    • 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::more_results - Check if there are more query results from a multiple query
    • mysqli_stmt::next_result - Reads the next result from a multiple query
    • 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_stmt::__construct - Constructs a new mysqli_stmt object
    • 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-committing 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_memcache_get_config - Returns information about the plugin configuration
    • mysqlnd_memcache_set - Associate a MySQL connection with a Memcache connection
    • mysqlnd_ms_dump_servers - Returns a list of currently configured servers
    • mysqlnd_ms_fabric_select_global - Switch to global sharding server for a given table
    • mysqlnd_ms_fabric_select_shard - Switch to shard
    • 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_ms_xa_begin - Starts a distributed/XA transaction among MySQL servers
    • mysqlnd_ms_xa_commit - Commits a distributed/XA transaction among MySQL servers
    • mysqlnd_ms_xa_gc - Garbage collects unfinished XA transactions after severe errors
    • mysqlnd_ms_xa_rollback - Rolls back a distributed/XA transaction among MySQL servers
    • 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_cache_condition - Set conditions for automatic caching
    • 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 - Ob?ine numarul de rânduri afectate de precedenta opera?iune MySQL
    • mysql_client_encoding - Întoarce denumirea setului de caractere
    • mysql_close - Închide conexiunea MySQL
    • mysql_connect - Deschide o conexiune la un server MySQL
    • mysql_create_db - Creeaza o baza de date MySQL
    • mysql_data_seek - Move internal result pointer
    • mysql_db_name - Retrieves database name from the call to mysql_list_dbs
    • mysql_db_query - Selects a database and executes a query on it
    • mysql_drop_db - Drop (delete) a MySQL database
    • mysql_errno - Returns the numerical value of the error message from previous MySQL operation
    • mysql_error - Returns the text of the error message from previous MySQL operation
    • mysql_escape_string - Escapeaza un string pentru fi folosit in mysql_query
    • mysql_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • mysql_fetch_assoc - Fetch a result row as an associative array
    • mysql_fetch_field - Get column information from a result and return as an object
    • mysql_fetch_lengths - Get the length of each output in a result
    • mysql_fetch_object - Fetch a result row as an object
    • mysql_fetch_row - Get a result row as an enumerated array
    • mysql_field_flags - Get the flags associated with the specified field in a result
    • mysql_field_len - Returns the length of the specified field
    • mysql_field_name - Get the name of the specified field in a result
    • mysql_field_seek - Stabile?te indicatorul rezultatului la deplasamentul câmpului specificat
    • mysql_field_table - Get name of the table the specified field is in
    • mysql_field_type - Get the type of the specified field in a result
    • mysql_free_result - Free result memory
    • mysql_get_client_info - Ob?ine informa?ia clientului MySQL
    • mysql_get_host_info - Get MySQL host info
    • mysql_get_proto_info - Get MySQL protocol info
    • mysql_get_server_info - Get MySQL server info
    • mysql_info - Get information about the most recent query
    • mysql_insert_id - Get the ID generated in the last query
    • mysql_list_dbs - List databases available on a MySQL server
    • mysql_list_fields - List MySQL table fields
    • mysql_list_processes - List MySQL processes
    • mysql_list_tables - List tables in a MySQL database
    • mysql_num_fields - Get number of fields in result
    • mysql_num_rows - Get number of rows in result
    • mysql_pconnect - Open a persistent connection to a MySQL server
    • mysql_ping - Ping a server connection or reconnect if there is no connection
    • mysql_query - Send a MySQL query
    • mysql_real_escape_string - Escapes special characters in a string for use in an SQL statement
    • mysql_result - Get result data
    • mysql_select_db - Select a MySQL database
    • mysql_set_charset - Sets the client character set
    • mysql_stat - Get current system status
    • mysql_tablename - Get table name of field
    • mysql_thread_id - Return the current thread ID
    • mysql_unbuffered_query - Send an SQL query to MySQL without fetching and buffering the result rows.
    • 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 - Sort an array using a case insensitive "natural order" algorithm
    • natsort - Sort an array using a "natural order" algorithm
    • ncurses_addch - Adauga caracterul în pozi?ia curenta ?i avanseaza cursorul
    • ncurses_addchnstr - Adauga ?irul de caractere cu atribute, cu lungimea specificata, în pozi?ia curenta
    • ncurses_addchstr - Adauga ?irul de caractere cu atribute în pozi?ia curenta
    • ncurses_addnstr - Adauga ?irul de caractere cu lungimea specificata în pozi?ia curenta
    • ncurses_addstr - Afi?eaza textul în pozi?ia curenta
    • ncurses_assume_default_colors - Define?te culorile implicite pentru culoarea 0
    • ncurses_attroff - Deconecteaza atributele date
    • ncurses_attron - Conecteaza atributele date
    • ncurses_attrset - Stabile?te atributele date
    • ncurses_baudrate - Întoarce rata baud a terminalului
    • ncurses_beep - Face ca terminalul sa emita un semnal sonor
    • ncurses_bkgd - Stabile?te proprietatea fundalului pentru ecranul terminalului
    • ncurses_bkgdset - Controleaza fundalul ecranului
    • ncurses_border - Deseneaza o bordura în jurul ecranului utilizând caractere cu atribute
    • ncurses_bottom_panel - Muta panelul vizibil la fundul stivei
    • ncurses_can_change_color - Verifica daca defini?iile culorilor terminalului pot fi schimbate
    • ncurses_cbreak - Deconecteaza buferizarea intrarilor
    • ncurses_clear - Cura?a ecranul
    • ncurses_clrtobot - Cura?a ecranul din pozi?ia curenta pâna jos
    • ncurses_clrtoeol - Cura?a ecranul din pozi?ia curenta pâna la sfâr?itul liniei
    • ncurses_color_content - Ob?ine componentele RGB ale culorii
    • ncurses_color_set - Stabile?te culorile de prim plan ?i de fundal active
    • ncurses_curs_set - Stabile?te starea cursorului
    • ncurses_define_key - Define?te un cod de cheie
    • ncurses_def_prog_mode - Salveaza modul terminalului (pentru program)
    • ncurses_def_shell_mode - Salveaza modul terminalului (pentru înveli?)
    • ncurses_delay_output - Încetine?te afi?area la terminal utilizând caractere de umplutura
    • ncurses_delch - Elimina caracterul de la pozi?ia curenta, deplaseaza restul liniei în stânga
    • ncurses_deleteln - Elimina linia de la pozi?ia curenta, deplaseaza restul ecranului în sus
    • ncurses_delwin - Elimina o fereastra ncurses
    • ncurses_del_panel - Extrage panelul din stiva ?i îl elimina (dar nu ?i fereastra asociata)
    • ncurses_doupdate - Înscrie în terminal toate actualizarile pregatite
    • ncurses_echo - Activeaza afi?area la ecran a intrarilor de la tastatura
    • ncurses_echochar - Afi?area unui singur caracter, inclusiv actualizarea
    • ncurses_end - Opre?te utilizarea ncurses, cura?a ecranul
    • ncurses_erase - Cura?a ecranul terminalului
    • ncurses_erasechar - Întoarce caracterul de eliminare curent
    • ncurses_filter - Stabile?te LINES pentru iniscr() ?i newterm() în 1
    • ncurses_flash - Sclipe?te ecranul terminalului (clopo?el vizual)
    • ncurses_flushinp - Gole?te zona-tampon a intrarilor de la tastatura
    • ncurses_getch - Cite?te un caracter de la tastaura
    • ncurses_getmaxyx - Întoarce marimea unei ferestre
    • ncurses_getmouse - Cite?te evenimentul ?oricelului
    • ncurses_getyx - Întoarce pozi?ia curenta a cursorului într-o fereastra
    • ncurses_halfdelay - Stabile?te terminalul în mod semipauza
    • ncurses_has_colors - Verifica daca terminalul are capacita?i de redare a culorilor
    • ncurses_has_ic - Verifica capacita?ile de inserare ?i eliminare
    • ncurses_has_il - Verifica capacita?ile de inserare ?i eliminare a liniilor
    • ncurses_has_key - Verifica prezen?a unei taste func?ionale pe tastatura terminalului
    • ncurses_hide_panel - Elimina panelul din stiva, facându-l invizibil
    • ncurses_hline - Deseneaza o linie orizontala în pozi?ia curenta folosind un caracter atribuit ?i o lungime de maximum n caractere
    • ncurses_inch - Ob?ine caracterul ?i atributul de la pozi?ia curenta
    • ncurses_init - Ini?ializeaza ncurses
    • ncurses_init_color - Define?te o culoare a terminalului
    • ncurses_init_pair - Define?te o pereche de culori
    • ncurses_insch - Insereaza un caracter deplasând restul liniei, inclusiv caracterul din pozi?ia curenta
    • ncurses_insdelln - Insereaza linii înainte de linia curenta ?i deplaseaza afi?ajul în jos (numerele negative elimina ?i deplaseaza afi?ajul în sus)
    • ncurses_insertln - Insereaza o linie, deplaseaza restul ecranului în jos
    • ncurses_insstr - Insereaza un ?ir de caractere în pozi?ia curenta, deplasând restul liniei în dreapta
    • ncurses_instr - Cite?te un ?ir de caractere de la ecranul terminalului
    • ncurses_isendwin - Ncurses este în mod endwin, pot fi efectuate afi?ari normale la ecran
    • ncurses_keyok - Activeaza sau dezactiveaza un cod al tastei
    • ncurses_keypad - Conecteaza sau deconecteaza tastatura numerica
    • ncurses_killchar - Întoarce caracterul curent de eliminare a liniei
    • ncurses_longname - Întoarce descrierea terminalului
    • ncurses_meta - Activeaza / Dezactiveaza informa?iile de 8 bi?i despre meta chei
    • ncurses_mouseinterval - Stabile?te timpul de expirare pentru apasarile butoanelor ?oricelului
    • ncurses_mousemask - Stabile?te op?iunile ?oricelului
    • ncurses_mouse_trafo - Transforma coordonate
    • ncurses_move - Deplaseaza pozi?ia de afi?are
    • ncurses_move_panel - Deplaseaza un panel astfel încât col?ul stânga-sus sa fie în pozi?ia [startx, starty]
    • ncurses_mvaddch - Deplaseaza pozi?ia curenta ?i adauga un caracter
    • ncurses_mvaddchnstr - Deplaseaza pozi?ia ?i adauga ?irul de caractere cu atribute de lungime specificata
    • ncurses_mvaddchstr - Deplaseaza pozi?ia ?i adauga un ?ir de caractere cu atribute
    • ncurses_mvaddnstr - Deplaseaza pozi?ia ?i adauga un ?ir de caractere de lungime specificata
    • ncurses_mvaddstr - Deplaseaza pozi?ia ?i adauga un ?ir de caractere
    • ncurses_mvcur - Deplaseaza imediat cursorul
    • ncurses_mvdelch - Deplaseaza pozi?ia ?i elimina caracterul, deplaseaza restul liniei în stânga
    • ncurses_mvgetch - Deplaseaza pozi?ia ?i ob?ine caracterul din noua pozi?ie
    • ncurses_mvhline - Stabile?te pozi?ia noua ?i deseneaza o linie orizontala folosind un caracter cu atribute ?i o lungime maxima de n caractere
    • ncurses_mvinch - Deplaseaza pozi?ia ?i ob?ine caracterul cu atribute din pozi?ia noua
    • ncurses_mvvline - Stabile?te pozi?ia noua ?i deseneaza o linie verticala folosint un caracter cu atribute ?i o înal?ime maxima de n caractere
    • ncurses_mvwaddstr - Adauga un ?ir de caractere într-o pozi?ie noua din fereastra
    • ncurses_napms - Adoarme
    • ncurses_newpad - Creeaza un nou pad (fereastra)
    • ncurses_newwin - Creeaza o fereastra noua
    • ncurses_new_panel - Creeaza un nou panel ?i îl asociaza cu o fereastra
    • ncurses_nl - Transleaza caracterul de trecere în linie noua ?i caracterele "carriage return" / "line feed"
    • ncurses_nocbreak - Schimba terminalul în mod cooked
    • ncurses_noecho - Deconecteaza afi?area la ecran a tastelor apasate
    • ncurses_nonl - Nu transleaza caracterul de trecere în linie noua ?i caracterele "carriage return" / "line feed"
    • ncurses_noqiflush - Nu gole?te zona-tampon la caracterele de semnal
    • ncurses_noraw - Schimba terminalul din modul raw
    • ncurses_pair_content - Ob?ine culorile de prim plan ?i de fundal ale unei perechi de culori
    • ncurses_panel_above - Întoarce panelul care este de asupra altui panel
    • ncurses_panel_below - Întoarce panelul care este de sub alt panel
    • ncurses_panel_window - Întoarce fereastra asociata cu un panel
    • ncurses_pnoutrefresh - Copie o regiune dintr-un pad în ecranul virtual
    • ncurses_prefresh - Copie o regiune dintr-un pad în ecranul virtual
    • ncurses_putp - Aplica informa?ia de completare la ?irul de caractere ?i îl afi?eaza
    • ncurses_qiflush - Gole?te zona-tampon la caracterele de semnal
    • ncurses_raw - Schimba terminalul în mod raw
    • ncurses_refresh - Actualizeaza ecranul
    • ncurses_replace_panel - Înlocuie?te fereastra asociata cu un panel
    • ncurses_resetty - Restabile?te starea terminalului salvata
    • ncurses_reset_prog_mode - Reseteaza modul programului salvat cu def_prog_mode
    • ncurses_reset_shell_mode - Reseteaza modul înveli?ului salvat cu def_shell_mode
    • ncurses_savetty - Salveaza starea terminalului
    • ncurses_scrl - Deplaseaza con?inutul ferestrei în sus sau în jos fara a modifica pozi?ia curenta
    • ncurses_scr_dump - Salveaza con?inutul ecranului într-un fi?ier
    • ncurses_scr_init - Ini?ializeaza ecranul dintr-un fi?ier salvat
    • ncurses_scr_restore - Restabile?te ecranul dintr-un fi?ier salvat
    • ncurses_scr_set - Stabile?te con?inutul ecranului dintr-un fi?ier salvat
    • ncurses_show_panel - Plaseaza un panel invizibil în vârful stivei, facându-l vizibil
    • ncurses_slk_attr - Întoarce atributul curent al etichetelor soft ale tastelor
    • ncurses_slk_attroff - Deconecteaza atribute specificate pentru taste func?ionale cu etichete soft
    • ncurses_slk_attron - Conecteaza atribute specificate pentru taste func?ionale cu etichete soft
    • ncurses_slk_attrset - Stabile?te atribute specificate pentru taste func?ionale cu etichete soft
    • ncurses_slk_clear - Elimina etichetele soft de la ecran
    • ncurses_slk_color - Stabile?te culoarea pentru tastele cu eticheta soft
    • ncurses_slk_init - Ini?ializeaza taste func?ionale cu eticheta soft
    • ncurses_slk_noutrefresh - Copie cheile soft label pe ecranul virtual
    • ncurses_slk_refresh - Copie tastele etichetelor soft la ecran
    • ncurses_slk_restore - Restabile?te tastele cu etichete soft
    • ncurses_slk_set - Stabile?te etichetele tastelor func?ionale
    • ncurses_slk_touch - For?eaza afi?area când este efectuat ncurses_slk_noutrefresh
    • ncurses_standend - Stopeaza utilizarea atributului 'standout'
    • ncurses_standout - Începe utilizarea atributului 'standout'
    • ncurses_start_color - Ini?ializeaza func?ionalitatea culorilor
    • ncurses_termattrs - Întoarce un SAU logic al tuturor fanioanelor de atribute sus?inute de terminal
    • ncurses_termname - Întoarce denumirea scurta a terminalului
    • ncurses_timeout - Stabile?te timpul de expirare pentru secven?e speciale de taste
    • ncurses_top_panel - Deplaseaza un panel vizibil în vârful stivei
    • ncurses_typeahead - Specifica un descriptor de fi?ier diferit pentru verificarea typeahead
    • ncurses_ungetch - Plaseaza un caracter înapoi în fluxul de intrari
    • ncurses_ungetmouse - Plaseaza evenimentele ?oricelului în rând
    • ncurses_update_panels - Actualizeaza ecranul virtual pentru a reflecta rela?iile dintre panelurile din stiva
    • ncurses_use_default_colors - Atribuie culorile implicite ale terminalului culorii cu indicele -1
    • ncurses_use_env - Controleaza utilizarea informa?iilor de mediu despre dimensiunea terminalului
    • ncurses_use_extended_names - Controlezaa utilizarea denumirilor extinse în descrieri terminfo
    • ncurses_vidattr - Afi?eaza ?irul de caractere la terminal în modul video atribut
    • ncurses_vline - Deseneaza o linie verticala în pozi?ia curenta utilizând un caracter cu atribute, de o înal?ime maxima de n caractere
    • ncurses_waddch - Adauga un caracter în pozi?ia curenta din fereastra ?i avanseaza cursorul
    • ncurses_waddstr - Afi?eaza un text în pozi?ia curenta din fereastra
    • ncurses_wattroff - Deconecteaza atribute pentru o fereastra
    • ncurses_wattron - Conecteaza atribute pentru o fereastra
    • ncurses_wattrset - Stabile?te atribute pentru o fereastra
    • ncurses_wborder - Deseneaza o bordura în jurul ferestrei utilizând caractere cu atribute
    • ncurses_wclear - Cura?a fereastra
    • ncurses_wcolor_set - Stabile?te perechile de culori ale ferestrei
    • ncurses_werase - ?terge con?inutul ferestrei
    • ncurses_wgetch - Cite?te un caracter de la tastatura (fereastra)
    • ncurses_whline - Deseneaza o linie orizontala într-o fereastra în pozi?ia curenta utilizând un caracter cu atribute ?i o lungime maxima de n caractere
    • ncurses_wmouse_trafo - Transforma coordonate window/stdscr
    • ncurses_wmove - Deplaseaza pozi?ia de afi?are în fereastra
    • ncurses_wnoutrefresh - Copie fereastra în ecranul virtual
    • ncurses_wrefresh - Actualizeaza fereastra la ecranul terminalului
    • ncurses_wstandend - Încheie modul standout pentru o fereastra
    • ncurses_wstandout - Transfera o fererastra în mod standout
    • ncurses_wvline - Deseneaza o linie verticala într-o fereastra în pozi?ia curenta utilizând un caracter cu atribute, de o lungime maxima de n caractere
    • 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 - Descrierea
    • 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 - Descrierea
    • 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 - Descrierea
    • newt_checkbox_tree_get_multi_selection - Descrierea
    • newt_checkbox_tree_get_selection - Descrierea
    • newt_checkbox_tree_multi - Descrierea
    • newt_checkbox_tree_set_current - Descrierea
    • newt_checkbox_tree_set_entry - Descrierea
    • newt_checkbox_tree_set_entry_value - Descrierea
    • newt_checkbox_tree_set_width - Descrierea
    • newt_clear_key_buffer - Discards the contents of the terminal's input buffer without waiting for additional input
    • newt_cls - Descrierea
    • newt_compact_button - Descrierea
    • newt_component_add_callback - Descrierea
    • newt_component_takes_focus - Descrierea
    • newt_create_grid - Descrierea
    • newt_cursor_off - Descrierea
    • newt_cursor_on - Descrierea
    • newt_delay - Descrierea
    • newt_draw_form - Descrierea
    • newt_draw_root_text - Displays the string text at the position indicated
    • newt_entry - Descrierea
    • newt_entry_get_value - Descrierea
    • newt_entry_set - Descrierea
    • newt_entry_set_filter - Descrierea
    • newt_entry_set_flags - Descrierea
    • 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 - Descrierea
    • newt_form_destroy - Destroys a form
    • newt_form_get_current - Descrierea
    • newt_form_run - Runs a form
    • newt_form_set_background - Descrierea
    • newt_form_set_height - Descrierea
    • newt_form_set_size - Descrierea
    • newt_form_set_timer - Descrierea
    • newt_form_set_width - Descrierea
    • newt_form_watch_fd - Descrierea
    • newt_get_screen_size - Fills in the passed references with the current size of the terminal
    • newt_grid_add_components_to_form - Descrierea
    • newt_grid_basic_window - Descrierea
    • newt_grid_free - Descrierea
    • newt_grid_get_size - Descrierea
    • newt_grid_h_close_stacked - Descrierea
    • newt_grid_h_stacked - Descrierea
    • newt_grid_place - Descrierea
    • newt_grid_set_field - Descrierea
    • newt_grid_simple_window - Descrierea
    • newt_grid_v_close_stacked - Descrierea
    • newt_grid_v_stacked - Descrierea
    • newt_grid_wrapped_window - Descrierea
    • newt_grid_wrapped_window_at - Descrierea
    • newt_init - Initialize newt
    • newt_label - Descrierea
    • newt_label_set_text - Descrierea
    • newt_listbox - Descrierea
    • newt_listbox_append_entry - Descrierea
    • newt_listbox_clear - Descrierea
    • newt_listbox_clear_selection - Descrierea
    • newt_listbox_delete_entry - Descrierea
    • newt_listbox_get_current - Descrierea
    • newt_listbox_get_selection - Descrierea
    • newt_listbox_insert_entry - Descrierea
    • newt_listbox_item_count - Descrierea
    • newt_listbox_select_item - Descrierea
    • newt_listbox_set_current - Descrierea
    • newt_listbox_set_current_by_key - Descrierea
    • newt_listbox_set_data - Descrierea
    • newt_listbox_set_entry - Descrierea
    • newt_listbox_set_width - Descrierea
    • newt_listitem - Descrierea
    • newt_listitem_get_data - Descrierea
    • newt_listitem_set - Descrierea
    • 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 - Descrierea
    • newt_radio_get_current - Descrierea
    • newt_redraw_help_line - Descrierea
    • newt_reflow_text - Descrierea
    • newt_refresh - Updates modified portions of the screen
    • newt_resize_screen - Descrierea
    • newt_resume - Resume using the newt interface after calling newt_suspend
    • newt_run_form - Runs a form
    • newt_scale - Descrierea
    • newt_scale_set - Descrierea
    • newt_scrollbar_set - Descrierea
    • newt_set_help_callback - Descrierea
    • 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 - Descrierea
    • newt_textbox_get_num_lines - Descrierea
    • newt_textbox_reflowed - Descrierea
    • newt_textbox_set_height - Descrierea
    • newt_textbox_set_text - Descrierea
    • newt_vertical_scrollbar - Descrierea
    • newt_wait_for_key - Doesn't return until a key has been pressed
    • newt_win_choice - Descrierea
    • newt_win_entries - Descrierea
    • newt_win_menu - Descrierea
    • newt_win_message - Descrierea
    • newt_win_messagev - Descrierea
    • newt_win_ternary - Descrierea
    • next - Advance the internal array pointer of an array
    • 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
    • nsapi_request_headers - Fetch all HTTP request headers
    • nsapi_response_headers - Fetch all HTTP response headers
    • nsapi_virtual - Perform an NSAPI sub-request
    • 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 - Format a number with grouped thousands
  • 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_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_iconv_handler - Convert character encoding as output buffer handler
    • ob_implicit_flush - Turn implicit flush on/off
    • ob_list_handlers - List all output handlers in use
    • ob_start - Turn on output buffering
    • ob_tidyhandler - ob_start callback function to repair the buffer
    • 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 - Adauga datele dintr-un obiect de tip LOB în alt obiect de tip LOB
    • OCI-Lob::close - Închide un descriptor LOB
    • 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 - Gole?te/scrie zona-tampon LOB pe 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 - Pseudonim pentru 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 - Scrie un LOB temporar
    • OCI-Lob::writeToFile - Pseudonim pentru OCI-Lob::export
    • ocibindbyname - Pseudonim pentru oci_bind_by_name
    • ocicancel - Pseudonim pentru oci_cancel
    • ocicloselob - Pseudonim pentru OCI-Lob::close
    • ocicollappend - Pseudonim pentru OCI-Collection::append
    • ocicollassign - Pseudonim pentru OCI-Collection::assign
    • ocicollassignelem - Pseudonim pentru OCI-Collection::assignElem
    • ocicollgetelem - Pseudonim pentru OCI-Collection::getElem
    • ocicollmax - Pseudonim pentru OCI-Collection::max
    • ocicollsize - Pseudonim pentru OCI-Collection::size
    • ocicolltrim - Pseudonim pentru OCI-Collection::trim
    • ocicolumnisnull - Pseudonim pentru oci_field_is_null
    • ocicolumnname - Pseudonim pentru oci_field_name
    • ocicolumnprecision - Pseudonim pentru oci_field_precision
    • ocicolumnscale - Pseudonim pentru oci_field_scale
    • ocicolumnsize - Pseudonim pentru oci_field_size
    • ocicolumntype - Pseudonim pentru oci_field_type
    • ocicolumntyperaw - Pseudonim pentru oci_field_type_raw
    • ocicommit - Pseudonim pentru oci_commit
    • ocidefinebyname - Pseudonim pentru oci_define_by_name
    • ocierror - Pseudonim pentru oci_error
    • ociexecute - Pseudonim pentru oci_execute
    • ocifetch - Pseudonim pentru oci_fetch
    • ocifetchinto - Varianta învechita a oci_fetch_array, oci_fetch_object, oci_fetch_assoc ?i oci_fetch_row
    • ocifetchstatement - Pseudonim pentru oci_fetch_all
    • ocifreecollection - Pseudonim pentru OCI-Collection::free
    • ocifreecursor - Pseudonim pentru oci_free_statement
    • ocifreedesc - Pseudonim pentru OCI-Lob::free
    • ocifreestatement - Pseudonim pentru oci_free_statement
    • ociinternaldebug - Pseudonim pentru oci_internal_debug
    • ociloadlob - Pseudonim pentru OCI-Lob::load
    • ocilogoff - Pseudonim pentru oci_close
    • ocilogon - Pseudonim pentru oci_connect
    • ocinewcollection - Pseudonim pentru oci_new_collection
    • ocinewcursor - Pseudonim pentru oci_new_cursor
    • ocinewdescriptor - Pseudonim pentru oci_new_descriptor
    • ocinlogon - Pseudonim pentru oci_new_connect
    • ocinumcols - Pseudonim pentru oci_num_fields
    • ociparse - Pseudonim pentru oci_parse
    • ociplogon - Pseudonim pentru oci_pconnect
    • ociresult - Pseudonim pentru oci_result
    • ocirollback - Pseudonim pentru oci_rollback
    • ocirowcount - Pseudonim pentru oci_num_rows
    • ocisavelob - Pseudonim pentru OCI-Lob::save
    • ocisavelobfile - Pseudonim pentru OCI-Lob::import
    • ociserverversion - Pseudonim pentru oci_server_version
    • ocisetprefetch - Pseudonim pentru oci_set_prefetch
    • ocistatementtype - Pseudonim pentru oci_statement_type
    • ociwritelobtofile - Pseudonim pentru OCI-Lob::export
    • ociwritetemporarylob - Pseudonim pentru 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 - Cancels reading from cursor
    • 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 a field in the currently fetched row 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 a field's data type name
    • oci_field_type_raw - Tell the raw Oracle data type of the field
    • oci_free_descriptor - Frees a descriptor
    • oci_free_statement - Frees all resources associated with statement or cursor
    • oci_get_implicit_resultset - Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets
    • 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 - Octal to decimal
    • 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 - Pseudonim pentru 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 - Pseudonim pentru 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
    • opcache_compile_file - Compiles and caches a PHP script without executing it
    • opcache_get_configuration - Get configuration information about the cache
    • opcache_get_status - Get status information about the cache
    • opcache_invalidate - Invalidates a cached script
    • opcache_is_script_cached - Tells whether a script is cached in OPCache
    • opcache_reset - Resets the contents of the opcode cache
    • 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 - Open directory handle
    • 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_cert_locations - Retrieve the available certificate locations
    • openssl_get_cipher_methods - Gets available cipher methods
    • openssl_get_md_methods - Gets available digest methods
    • openssl_get_privatekey - Pseudonim pentru openssl_pkey_get_private
    • openssl_get_publickey - Pseudonim pentru openssl_pkey_get_public
    • openssl_open - Open sealed data
    • openssl_pbkdf2 - Generates a PKCS5 v2 PBKDF2 string, defaults to SHA-1
    • 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_spki_export - Exports a valid PEM formatted public key signed public key and challenge
    • openssl_spki_export_challenge - Exports the challenge assoicated with a signed public key and challenge
    • openssl_spki_new - Generate a new signed public key and challenge
    • openssl_spki_verify - Verifies a signed public key and challenge
    • 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_fingerprint - Calculates the fingerprint, or digest, of a given X.509 certificate
    • 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
    • override_function - Overrides built-in functions
  • 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 PHP file 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 - Parse a URL and return its components
    • passthru - Execute an external program and display raw output
    • password_get_info - Returns information about the given hash
    • password_hash - Creates a password hash
    • password_needs_rehash - Checks if the given hash matches the given options
    • password_verify - Verifies that a password matches a hash
    • pathinfo - Returns information about a file path
    • pclose - Closes process file pointer
    • pcntl_alarm - Set an alarm clock for delivery of a signal
    • pcntl_errno - Pseudonim pentru pcntl_strerror
    • 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_get_last_error - Retrieve the error number set by the last pcntl function which failed
    • pcntl_setpriority - Change the priority of any process
    • pcntl_signal - Installs a signal handler
    • pcntl_signal_dispatch - Calls signal handlers for pending signals
    • pcntl_signal_get_handler - Get the current handler for specified signal
    • pcntl_sigprocmask - Sets and retrieves blocked signals
    • pcntl_sigtimedwait - Waits for signals, with a timeout
    • pcntl_sigwaitinfo - Waits for signals
    • pcntl_strerror - Retrieve the system error message associated with the given errno
    • 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 - Activeaza un element de structura sau un alt element de con?inut
    • PDF_add_annotation - Adauga o adnotare [învechit]
    • PDF_add_bookmark - Adauga un semn de carte pentru pagina curenta [învechit]
    • PDF_add_launchlink - Adauga o adnotare de lansare pentru pagina curenta [învechit]
    • PDF_add_locallink - Adauga o adnotare de referin?a pentru pagina curenta [învechit]
    • PDF_add_nameddest - Creeaza o destina?ie cu denumire
    • PDF_add_note - Stabile?te o adnotare pentru pagina curenta [învechit]
    • PDF_add_outline - Adauga un semn de carte pentru pagina curenta [învechit]
    • PDF_add_pdflink - Adauga o adnotare-referin?a catre fi?ier pentru pagina curenta [învechit]
    • PDF_add_table_cell - Adauga o celula catre un tabel nou sau existent
    • PDF_add_textflow - Creaza un Textflow sau adauga text catre un Textflow existent
    • PDF_add_thumbnail - Adauga o miniatura pentru pagina curenta
    • PDF_add_weblink - Adauga o referin?a web pentru pagina curenta [învechit]
    • PDF_arc - Deseneaza un segment de arc de circumferin?a contra sensului acelor de ceasornic
    • PDF_arcn - Deseneaza un segment de arc de circumferin?a în sensul acelor de ceasornic
    • PDF_attach_file - Adauga un fi?ier ata?at la pagina curenta [învechit]
    • PDF_begin_document - Creeaza un fi?ier PDF nou
    • PDF_begin_font - Începe o defini?ie de font de Tip 3
    • PDF_begin_glyph - Începe o defini?ie de simbol pentru un font de Tip 3
    • PDF_begin_item - Deschide un element de structura sau un alt element de con?inut
    • PDF_begin_layer - Începe un strat
    • PDF_begin_page - Începe o pagina noua [învechit]
    • PDF_begin_page_ext - Începe o pagina noua
    • PDF_begin_pattern - Începe defini?ia unui tipar
    • PDF_begin_template - Începe defini?ia unui tipar [învechit]
    • PDF_begin_template_ext - Începe defini?ia unui tipar
    • PDF_circle - Deseneaza un cerc
    • PDF_clip - Taie conform caii curente
    • PDF_close - Închite resursa PDF [învechit]
    • PDF_closepath - Închide calea curenta
    • PDF_closepath_fill_stroke - Închide, umple ?i traseaza calea curenta
    • PDF_closepath_stroke - Închide ?i traseaza calea
    • PDF_close_image - Închide o imagine
    • PDF_close_pdi - Închide documentul PDF de intrare [învechit]
    • PDF_close_pdi_page - Închide handle-ul paginii
    • PDF_concat - Concateneaza o matrice la MCT
    • PDF_continue_text - Afi?eaza textul în linia urmatoare
    • PDF_create_3dview - Creeaza o imagine 3D
    • PDF_create_action - Creeaza ac?iuni pentru obiecte sau evenimente
    • PDF_create_annotation - Creeaza o adnotare dreptunghiulara
    • PDF_create_bookmark - Creeaza un semn de carte
    • PDF_create_field - Creeaza un câmp în formular
    • PDF_create_fieldgroup - Creeaza un grup de câmpuri de formular
    • PDF_create_gstate - Creeaza un obiect de stare grafica
    • PDF_create_pvf - Creeaza un fi?ier virtual PDFlib
    • PDF_create_textflow - Creeaza un obiect textflow
    • PDF_curveto - Deseneaza o curba Bezier
    • PDF_define_layer - Creeaza o defini?ie a stratului
    • PDF_delete - Elimina un obiect PDFlib
    • PDF_delete_pvf - Elimina un fi?ier virtual PDFlib
    • PDF_delete_table - Elimina un obiect-tabel
    • PDF_delete_textflow - Elimina un obiect textflow
    • PDF_encoding_set_char - Adauga denumirea unui simbol ?i/sau valoarea Unicode
    • PDF_endpath - Încheie calea curenta
    • PDF_end_document - Închide un fi?ier PDF
    • PDF_end_font - Încheie o defini?ie de font te Tip 3
    • PDF_end_glyph - Încheie o defini?ie a simbolului pentru un font de Tip 3
    • PDF_end_item - Închide un element de structura sau un alt element de con?inut
    • PDF_end_layer - Dezactiveaza toate straturile active
    • PDF_end_page - Încheie o pagina
    • PDF_end_page_ext - Încheie o pagina
    • PDF_end_pattern - Încheie un tipar
    • PDF_end_template - Încheie un ?ablon
    • PDF_fill - Umple calea curenta
    • PDF_fill_imageblock - Umple un bloc de imagine cu date variabile
    • PDF_fill_pdfblock - Umple un bloc PDF cu date variabile
    • PDF_fill_stroke - Umple ?i traseaza o cale
    • PDF_fill_textblock - Umple un bloc de text cu date variabile
    • PDF_findfont - Pregate?te un font pentru utilizarea sa ulterioara [învechit]
    • PDF_fit_image - Plaseaza o imagine sau un ?ablon
    • PDF_fit_pdi_page - Plaseaza o pagina PDF importata
    • PDF_fit_table - Plaseaza un tabel pe pagina
    • PDF_fit_textflow - Formateaza un textflow într-o zona dreptunghiulara
    • PDF_fit_textline - Plaseaza o singura linie de text
    • PDF_get_apiname - Ob?ine denumirea func?iei API care a e?uat
    • PDF_get_buffer - Ob?ine zona-tampon de ie?ire a PDF
    • PDF_get_errmsg - Ob?ine textul erorii
    • PDF_get_errnum - Ob?ine numarul erorii
    • PDF_get_font - Ob?ine fontul [învechit]
    • PDF_get_fontname - Ob?ine denumirea fontului [învechit]
    • PDF_get_fontsize - Manipularea fontului [învechit]
    • PDF_get_image_height - Ob?ine înal?imea imaginii [învechit]
    • PDF_get_image_width - Ob?ine la?imea imaginii [învechit]
    • PDF_get_majorversion - Ob?ine numarul major al versiunii [învechit]
    • PDF_get_minorversion - Ob?ine numarul minor al versiunii [învechit]
    • PDF_get_parameter - Ob?ine un parametru string
    • PDF_get_pdi_parameter - Ob?ine un parametru string al PDI [învechit]
    • PDF_get_pdi_value - Ob?ine un parametru numeric PDI [învechit]
    • PDF_get_value - Ob?ine un parametru numeric
    • PDF_info_font - Transmite o interpelare a informa?iilor detaliate despre un font încarcat
    • PDF_info_matchbox - Transmite o interpelare despre informa?ia matchbox
    • PDF_info_table - Ob?ine informa?ii despre tabel
    • PDF_info_textflow - Interpeleaza starea textflow
    • PDF_info_textline - Efectueaza formatarea unei linii de text ?i interpeleaza metricile
    • PDF_initgraphics - Restabile?te starea grafica
    • PDF_lineto - Deseneaza o linie
    • PDF_load_3ddata - Încarca un model 3D
    • PDF_load_font - Cauta ?i pregate?te un font
    • PDF_load_iccprofile - Cauta ?i pregate?te un profil ICC
    • PDF_load_image - Deschide un fi?ier cu imagine
    • PDF_makespotcolor - Creeaza o culoare a punctului
    • PDF_moveto - Stabile?te punctul curent
    • PDF_new - Creeaza un obiect PDFlib
    • PDF_open_ccitt - Deschide o imagine bruta CCITT [învechit]
    • PDF_open_file - Creeaza un fi?ier PDF [învechit]
    • PDF_open_gif - Deschide o imagine GIF [învechit]
    • PDF_open_image - Utilizeaza datele imaginii [învechit]
    • PDF_open_image_file - Cite?te o imagine dintr-un fi?ier [învechit]
    • PDF_open_jpeg - Deschide o imagine JPEG [învechit]
    • PDF_open_memory_image - Deschide o imagine creata cu func?iile de imagini ale PHP [nu este sus?inut]
    • PDF_open_pdi - Deschide un fi?ier PDF [învechit]
    • PDF_open_pdi_document - Prepare a pdi document
    • PDF_open_pdi_page - Pregate?te o pagina
    • PDF_open_tiff - Deschide o imagine TIFF [învechit]
    • PDF_pcos_get_number - Ob?ine valoarea unei cai pCOS, de tip numeric sau boolean
    • PDF_pcos_get_stream - Ob?ine con?inutul unei cai pCOS, de tip stream, fstream sau string
    • PDF_pcos_get_string - Ob?ine valoarea unei cai pCOS, de tip name, string sau boolean
    • PDF_place_image - Plaseaza o imagine pe pagina [învechit]
    • PDF_place_pdi_page - Plaseaza o pagina PDF [învechit]
    • PDF_process_pdi - Proceseaza un document PDF importat
    • PDF_rect - Deseneaza un dreptunghi
    • PDF_restore - Restabile?te starea grafica
    • PDF_resume_page - Continua o pagina
    • PDF_rotate - Rote?te sistemul de coordonate
    • PDF_save - Salveaza starea grafica
    • PDF_scale - Modifica scara sistemului de coordonate
    • PDF_setcolor - Stabile?te culorile de umplere ?i de trasare
    • PDF_setdash - Stabile?te un tipar al liniei obi?nuit
    • PDF_setdashpattern - Stabile?te tiparul liniei
    • PDF_setflat - Stabile?te platitudinea
    • PDF_setfont - Stabile?te fontul
    • PDF_setgray - Stabile?te culoarea în sur [învechit]
    • PDF_setgray_fill - Stabile?te culoarea de umplere în sur [învechit]
    • PDF_setgray_stroke - Stabile?te culoarea de trasare în sur [învechit]
    • PDF_setlinecap - Stabile?te parametrul capului de linie
    • PDF_setlinejoin - Stabile?te parametrul linejoin
    • PDF_setlinewidth - Stabile?te grosimea liniei
    • PDF_setmatrix - Stabile?te matricea curenta de transformare
    • PDF_setmiterlimit - Stabile?te limita mitrei
    • PDF_setpolydash - Stabile?te un tipar al liniei complicat [învechit]
    • PDF_setrgbcolor - Stabile?te valorile rgb ale culorilor de umplere ?i de trasare [învechit]
    • PDF_setrgbcolor_fill - Stabile?te valorile rgb ale culorii de umplere [învechit]
    • PDF_setrgbcolor_stroke - Stabile?te valorile rgb ale culorii de trasare [învechit]
    • PDF_set_border_color - Stabile?te culoarea bordurii adnotarilor [învechit]
    • PDF_set_border_dash - Stabile?te stilul liniei bordurii adnotarilor [învechit]
    • PDF_set_border_style - Stabile?te stilul bordurii adnotarilor [învechit]
    • PDF_set_char_spacing - Stabile?te spa?ierea dintre caractere [învechit]
    • PDF_set_duration - Stabile?te durata dintre pagini [învechit]
    • PDF_set_gstate - Activeaza obiectul starii grafice
    • PDF_set_horiz_scaling - Stabile?te marimea scarii textului pe orizontala [învechit]
    • PDF_set_info - Completeaza un câmp informa?ional al documentului
    • PDF_set_info_author - Completeaza câmpul documentului cu informa?ia despre autor [învechit]
    • PDF_set_info_creator - Completeaza câmpul documentului cu informa?ia despre creator [învechit]
    • PDF_set_info_keywords - Completeaza câmpul documentului cu cuvintele-cheie [învechit]
    • PDF_set_info_subject - Completeaza câmpul documentului cu subiectul [învechit]
    • PDF_set_info_title - Completeaza câmpul documentului cu titlul [învechit]
    • PDF_set_layer_dependency - Define?te rela?iile dintre straturi
    • PDF_set_leading - Stabile?te distan?a dintre liniile de text [învechit]
    • PDF_set_parameter - Stabile?te un parametru string
    • PDF_set_text_matrix - Stabile?te matricea textului [învechit]
    • PDF_set_text_pos - Stabile?te pozi?ia textului
    • PDF_set_text_rendering - Determina redarea textului [învechit]
    • PDF_set_text_rise - Stabile?te înal?area textului [învechit]
    • PDF_set_value - Stabile?te un parametru numeric
    • PDF_set_word_spacing - Stabile?te spa?ierea dintre cuvinte [învechit]
    • PDF_shading - Define?te amestecarea
    • PDF_shading_pattern - Define?te tiparul de umbrire
    • PDF_shfill - Umple o regiune cu umbrire
    • PDF_show - Afi?eaza un text în pozi?ia curenta
    • PDF_show_boxed - Afi?eaza un text într-o caseta [învechit]
    • PDF_show_xy - Afi?eaza un text la pozi?ia data
    • PDF_skew - Deformeaza oblic sistemul de coordonate
    • PDF_stringwidth - Întoarce la?imea textului
    • PDF_stroke - Traseaza o cale
    • PDF_suspend_page - Suspendeaza o pagina
    • PDF_translate - Stabile?te originea sistemului de coordonate
    • PDF_utf8_to_utf16 - Converte?te un string din UTF-8 în UTF-16
    • PDF_utf16_to_utf8 - Converte?te un string din UTF-16 în UTF-8
    • PDF_utf32_to_utf16 - Converte?te un string din UTF-32 în 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::pgsqlCopyFromArray - Copy data from PHP array into table
    • PDO::pgsqlCopyFromFile - Copy data from file into table
    • PDO::pgsqlCopyToArray - Copy data from database table into PHP array
    • PDO::pgsqlCopyToFile - Copy data from table into file
    • PDO::pgsqlGetNotify - Get asynchronous notification
    • PDO::pgsqlGetPid - Get the server PID
    • 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::sqliteCreateCollation - Registers a User Defined Function for use as a collating function 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 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 - Returns number of affected records (tuples)
    • pg_cancel_query - Cancel an asynchronous query
    • pg_client_encoding - Gets the client encoding
    • pg_close - Closes a PostgreSQL connection
    • pg_connect - Open a PostgreSQL connection
    • pg_connection_busy - Get connection is busy or not
    • pg_connection_reset - Reset connection (reconnect)
    • pg_connection_status - Get connection status
    • pg_connect_poll - Poll the status of an in-progress asynchronous PostgreSQL connection attempt.
    • pg_consume_input - Reads input on the connection
    • pg_convert - Convert associative array values into suitable for SQL statement
    • pg_copy_from - Insert records into a table from an array
    • pg_copy_to - Copy a table to an array
    • pg_dbname - Get the database name
    • pg_delete - Deletes records
    • pg_end_copy - Sync with PostgreSQL backend
    • pg_escape_bytea - Escape a string for insertion into a bytea field
    • 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 - Escape a string for query
    • 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 - Fetch a row as an array
    • pg_fetch_assoc - Fetch a row as an associative array
    • pg_fetch_object - Fetch a row as an object
    • pg_fetch_result - Returns values from a result resource
    • pg_fetch_row - Get a row as an enumerated array
    • pg_field_is_null - Test if a field is SQL NULL
    • pg_field_name - Returns the name of a field
    • pg_field_num - Returns the field number of the named field
    • pg_field_prtlen - Returns the printed length
    • pg_field_size - Returns the internal storage size of the named field
    • pg_field_table - Returns the name or oid of the tables field
    • pg_field_type - Returns the type name for the corresponding field number
    • pg_field_type_oid - Returns the type ID (OID) for the corresponding field number
    • pg_flush - Flush outbound query data on the connection
    • pg_free_result - Free result memory
    • pg_get_notify - Gets SQL NOTIFY message
    • pg_get_pid - Gets the backend's process ID
    • pg_get_result - Get asynchronous query result
    • pg_host - Returns the host name associated with the connection
    • pg_insert - Insert array into table
    • pg_last_error - Get the last error message string of a connection
    • pg_last_notice - Returns the last notice message from PostgreSQL server
    • pg_last_oid - Returns the last row's OID
    • pg_lo_close - Close a large object
    • pg_lo_create - Create a large object
    • pg_lo_export - Export a large object to file
    • pg_lo_import - Import a large object from file
    • pg_lo_open - Open a large object
    • pg_lo_read - Read a large object
    • pg_lo_read_all - Reads an entire large object and send straight to browser
    • pg_lo_seek - Seeks position within a large object
    • pg_lo_tell - Returns current seek position a of large object
    • pg_lo_truncate - Truncates a large object
    • pg_lo_unlink - Delete a large object
    • pg_lo_write - Write to a large object
    • pg_meta_data - Get meta data for table
    • pg_num_fields - Returns the number of fields in a result
    • pg_num_rows - Returns the number of rows in a result
    • pg_options - Get the options associated with the connection
    • pg_parameter_status - Looks up a current parameter setting of the server.
    • pg_pconnect - Open a persistent PostgreSQL connection
    • pg_ping - Ping database connection
    • pg_port - Return the port number associated with the connection
    • pg_prepare - Submits a request to create a prepared statement with the given parameters, and waits for completion.
    • pg_put_line - Send a NULL-terminated string to PostgreSQL backend
    • pg_query - Execute a query
    • 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 - Get error message associated with result
    • 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 - Get status of query result
    • pg_select - Select records
    • 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 - Sends asynchronous query
    • pg_send_query_params - Submits a command and separate parameters to the server without waiting for the result(s).
    • pg_set_client_encoding - Set the client encoding
    • pg_set_error_verbosity - Determines the verbosity of messages returned by pg_last_error and pg_result_error.
    • pg_socket - Get a read only handle to the socket underlying a PostgreSQL connection
    • pg_trace - Enable tracing a PostgreSQL connection
    • pg_transaction_status - Returns the current in-transaction status of the server.
    • pg_tty - Return the TTY name associated with the connection
    • pg_unescape_bytea - Unescape binary for bytea type
    • pg_untrace - Disable tracing of a PostgreSQL connection
    • pg_update - Update table
    • 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 a string 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.
    • 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
    • php_user_filter::filter - Called when applying the filter
    • php_user_filter::onClose - Called when closing the filter
    • php_user_filter::onCreate - Called when creating the filter
    • pi - Get value of pi
    • png2wbmp - Convert PNG image file to WBMP image file
    • Pool::collect - Collect references to completed tasks
    • Pool::resize - Resize the Pool
    • Pool::shutdown - Shutdown all workers
    • Pool::submit - Submits an object for execution
    • Pool::submitTo - Submits a task to a specific worker for execution
    • Pool::__construct - Creates a new Pool of Workers
    • popen - Opens process file pointer
    • pos - Pseudonim pentru current
    • posix_access - Determine accessibility of a file
    • posix_ctermid - Get path name of controlling terminal
    • posix_errno - Pseudonim pentru 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_setrlimit - Set system resource limits
    • 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 - Exponential expression
    • 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_replace_callback_array - Perform a regular expression search and replace using callbacks
    • preg_split - Split string by a regular expression
    • prev - Rewind the internal array pointer
    • print - Output a string
    • printf - Output a formatted string
    • print_r - Afi?eaza informa?ie lizibila de om despre o variabila
    • 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
    • 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 - Converts the radian number to the equivalent number in degrees
    • 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_tagged_attr_data - Extracts the data from a tagged attribute
    • radius_get_tagged_attr_tag - Extracts the tag from a tagged 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_salt_encrypt_attr - Salt-encrypts a value
    • 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 - Generate a random integer
    • random_bytes - Generates cryptographically secure pseudo-random bytes
    • random_int - Generates cryptographically secure pseudo-random integers
    • range - Create an array containing a range of elements
    • 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 - Decode URL-encoded strings
    • rawurlencode - URL-encode according to RFC 3986
    • readdir - Read entry from directory handle
    • readfile - Outputs a file
    • readgzfile - Output a gz-file
    • readline - Reads a line
    • readline_add_history - Adds a line to the history
    • 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 - Clears the history
    • readline_completion_function - Registers a completion function
    • readline_info - Gets/sets various internal readline variables
    • readline_list_history - Lists the history
    • readline_on_new_line - Inform readline that the cursor has moved to a new line
    • readline_read_history - Reads the history
    • readline_redisplay - Redraws the display
    • readline_write_history - Writes the history
    • readlink - Returns the target of a symbolic link
    • read_exif_data - Pseudonim pentru exif_read_data
    • realpath - Returns canonicalized absolute pathname
    • realpath_cache_get - Get realpath cache entries
    • realpath_cache_size - Get realpath cache size
    • recode - Pseudonim pentru 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 the constructor of the class
    • ReflectionClass::getDefaultProperties - Gets default properties
    • ReflectionClass::getDocComment - Gets doc comments
    • ReflectionClass::getEndLine - Gets end line
    • ReflectionClass::getExtension - Gets a ReflectionExtension object for the extension which defined the class
    • ReflectionClass::getExtensionName - Gets the name of the extension which defined the class
    • 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 for a class method.
    • ReflectionClass::getMethods - Gets an array 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 a ReflectionProperty for a class's 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::isAnonymous - Checks if class is anonymous
    • 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 the class is instantiable
    • ReflectionClass::isInterface - Checks if the class is an interface
    • ReflectionClass::isInternal - Checks if class is defined internally by an extension, or the core
    • 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::__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::getClosureScopeClass - Returns the scope associated to the closure
    • 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::getReturnType - Gets the specified return type of a function
    • ReflectionFunctionAbstract::getShortName - Gets function short name
    • ReflectionFunctionAbstract::getStartLine - Gets starting line number
    • ReflectionFunctionAbstract::getStaticVariables - Gets static variables
    • ReflectionFunctionAbstract::hasReturnType - Checks if the function has a specified return type
    • ReflectionFunctionAbstract::inNamespace - Checks if function in namespace
    • ReflectionFunctionAbstract::isClosure - Checks if closure
    • ReflectionFunctionAbstract::isDeprecated - Checks if deprecated
    • ReflectionFunctionAbstract::isGenerator - Returns whether this function is a generator
    • ReflectionFunctionAbstract::isInternal - Checks if is internal
    • ReflectionFunctionAbstract::isUserDefined - Checks if user defined
    • ReflectionFunctionAbstract::isVariadic - Checks if the function is variadic
    • ReflectionFunctionAbstract::returnsReference - Checks if returns reference
    • ReflectionFunctionAbstract::__clone - Clones function
    • ReflectionFunctionAbstract::__toString - To string
    • ReflectionGenerator::getExecutingFile - Gets the file name of the currently executing generator
    • ReflectionGenerator::getExecutingGenerator - Gets the executing Generator object
    • ReflectionGenerator::getExecutingLine - Gets the currently executing line of the generator
    • ReflectionGenerator::getFunction - Gets the function name of the generator
    • ReflectionGenerator::getThis - Gets the $this value of the generator
    • ReflectionGenerator::getTrace - Gets the trace of the executing generator
    • ReflectionGenerator::__construct - Constructs a ReflectionGenerator object
    • 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 the type hinted class
    • ReflectionParameter::getDeclaringClass - Gets declaring class
    • ReflectionParameter::getDeclaringFunction - Gets declaring function
    • ReflectionParameter::getDefaultValue - Gets default parameter value
    • ReflectionParameter::getDefaultValueConstantName - Returns the default value's constant name if default value is constant or null
    • ReflectionParameter::getName - Gets parameter name
    • ReflectionParameter::getPosition - Gets parameter position
    • ReflectionParameter::getType - Gets a parameter's type
    • ReflectionParameter::hasType - Checks if parameter has a type
    • ReflectionParameter::isArray - Checks if parameter expects an array
    • ReflectionParameter::isCallable - Returns whether parameter MUST be callable
    • ReflectionParameter::isDefaultValueAvailable - Checks if a default value is available
    • ReflectionParameter::isDefaultValueConstant - Returns whether the default value of this parameter is constant
    • ReflectionParameter::isOptional - Checks if optional
    • ReflectionParameter::isPassedByReference - Checks if passed by reference
    • ReflectionParameter::isVariadic - Checks if the parameter is variadic
    • ReflectionParameter::__clone - Clone
    • ReflectionParameter::__construct - Construct
    • ReflectionParameter::__toString - To string
    • ReflectionProperty::export - Export
    • ReflectionProperty::getDeclaringClass - Gets declaring class
    • ReflectionProperty::getDocComment - Gets the property doc comment
    • ReflectionProperty::getModifiers - Gets modifiers
    • ReflectionProperty::getName - Gets property name
    • ReflectionProperty::getValue - Gets value
    • ReflectionProperty::isDefault - Checks if property is a default property
    • 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
    • ReflectionType::allowsNull - Checks if null is allowed
    • ReflectionType::isBuiltin - Checks if it is a built-in type
    • ReflectionType::__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 - Set the internal pointer of an array to its first 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 - Restabile?te func?ia precedenta de gestionare a erorilor
    • 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 - Rewind directory handle
    • rmdir - Removes directory
    • round - Rounds a float
    • 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
    • rrdc_disconnect - Close any outstanding connection to rrd caching daemon
    • 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 - Sort an array in reverse order
    • 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 - List files and directories inside the specified path
    • 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 - Genereaza o reprezentare ce poate fi stocata a unei valori
    • SessionHandler::close - Close the session
    • SessionHandler::create_sid - Return a new session ID
    • SessionHandler::destroy - Destroy a session
    • SessionHandler::gc - Cleanup old sessions
    • SessionHandler::open - Initialize session
    • SessionHandler::read - Read session data
    • SessionHandler::write - Write session data
    • SessionHandlerInterface::close - Close the session
    • SessionHandlerInterface::destroy - Destroy a session
    • SessionHandlerInterface::gc - Cleanup old sessions
    • SessionHandlerInterface::open - Initialize session
    • SessionHandlerInterface::read - Read session data
    • SessionHandlerInterface::write - Write session data
    • session_abort - Discard session array changes and finish session
    • session_cache_expire - Return current cache expire
    • session_cache_limiter - Get and/or set the current cache limiter
    • session_commit - Pseudonim pentru session_write_close
    • session_create_id - Create new session id
    • session_decode - Decodes session data from a session encoded string
    • session_destroy - Destroys all data registered to a session
    • session_encode - Encodes the current session data as a session encoded string
    • session_gc - Perform session data garbage collection
    • session_get_cookie_params - Get the session cookie parameters
    • session_id - Get and/or set the current session id
    • session_is_registered - Find out whether a global variable is registered in a session
    • session_module_name - Get and/or set the current session module
    • session_name - Get and/or set the current session name
    • 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 - Update the current session id with a newly generated one
    • session_register - Register one or more global variables with the current session
    • session_register_shutdown - Session shutdown function
    • session_reset - Re-initialize session array with original values
    • session_save_path - Get and/or set the current session save path
    • session_set_cookie_params - Set the session cookie parameters
    • session_set_save_handler - Sets user-level session storage functions
    • session_start - Start new or resume existing session
    • session_status - Returns the current session status
    • session_unregister - Unregister a global variable from the current session
    • session_unset - Free all session variables
    • session_write_close - Write session data and end session
    • 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 - Stabile?te tipul unei variabile
    • set_error_handler - Stabile?te o func?ie definita de utilizator pentru prelucrarea erorilor
    • set_exception_handler - Sets a user-defined exception handler function
    • set_file_buffer - Pseudonim pentru 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 - Pseudonim pentru 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 - Pseudonim pentru highlight_file
    • shuffle - Shuffle an array
    • 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 - Pseudonim pentru SimpleXMLElement::asXML
    • SimpleXMLElement::xpath - Runs XPath query on XML data
    • SimpleXMLElement::__construct - Creates a new SimpleXMLElement object
    • SimpleXMLElement::__toString - Returns the string content
    • 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 - Sine
    • sinh - Hyperbolic sine
    • sizeof - Pseudonim pentru 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 - Set the OID output format
    • 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_cmsg_space - Calculate message buffer size
    • 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_getopt - Pseudonim pentru socket_get_option
    • 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 - Pseudonim pentru stream_get_meta_data
    • socket_import_stream - Import a stream
    • 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_recvmsg - Read a message
    • 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_sendmsg - Send a message
    • socket_sendto - Sends a message to a socket, whether it is connected or not
    • socket_setopt - Pseudonim pentru socket_set_option
    • socket_set_block - Sets blocking mode on a socket resource
    • socket_set_blocking - Pseudonim pentru 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 - Pseudonim pentru 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::getById - Get Document By Id. Utilizes Solr Realtime Get (RTG).
    • SolrClient::getByIds - Get Documents by their Ids. Utilizes Solr Realtime Get (RTG).
    • 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::system - Retrieve Solr Server information
    • 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
    • SolrCollapseFunction::getField - Returns the field that is being collapsed on.
    • SolrCollapseFunction::getHint - Returns collapse hint
    • SolrCollapseFunction::getMax - Returns max parameter
    • SolrCollapseFunction::getMin - Returns min parameter
    • SolrCollapseFunction::getNullPolicy - Returns null policy
    • SolrCollapseFunction::getSize - Returns size parameter
    • SolrCollapseFunction::setField - Sets the field to collapse on
    • SolrCollapseFunction::setHint - Sets collapse hint
    • SolrCollapseFunction::setMax - Selects the group heads by the max value of a numeric field or function query.
    • SolrCollapseFunction::setMin - Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::setNullPolicy - Sets the NULL Policy
    • SolrCollapseFunction::setSize - Sets the initial size of the collapse data structures when collapsing on a numeric field only.
    • SolrCollapseFunction::__construct - Constructor
    • SolrCollapseFunction::__toString - Returns a string representing the constructed collapse function
    • SolrDisMaxQuery::addBigramPhraseField - Adds a Phrase Bigram Field (pf2 parameter)
    • SolrDisMaxQuery::addBoostQuery - Adds a boost query field with value and optional boost (bq parameter)
    • SolrDisMaxQuery::addPhraseField - Adds a Phrase Field (pf parameter)
    • SolrDisMaxQuery::addQueryField - Add a query field with optional boost (qf parameter)
    • SolrDisMaxQuery::addTrigramPhraseField - Adds a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::addUserField - Adds a field to User Fields Parameter (uf)
    • SolrDisMaxQuery::removeBigramPhraseField - Removes phrase bigram field (pf2 parameter)
    • SolrDisMaxQuery::removeBoostQuery - Removes a boost query partial by field name (bq)
    • SolrDisMaxQuery::removePhraseField - Removes a Phrase Field (pf parameter)
    • SolrDisMaxQuery::removeQueryField - Removes a Query Field (qf parameter)
    • SolrDisMaxQuery::removeTrigramPhraseField - Removes a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::removeUserField - Removes a field from The User Fields Parameter (uf)
    • SolrDisMaxQuery::setBigramPhraseFields - Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setBigramPhraseSlop - Sets Bigram Phrase Slop (ps2 parameter)
    • SolrDisMaxQuery::setBoostFunction - Sets a Boost Function (bf parameter).
    • SolrDisMaxQuery::setBoostQuery - Directly Sets Boost Query Parameter (bq)
    • SolrDisMaxQuery::setMinimumMatch - Set Minimum "Should" Match (mm)
    • SolrDisMaxQuery::setPhraseFields - Sets Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setPhraseSlop - Sets the default slop on phrase queries (ps parameter)
    • SolrDisMaxQuery::setQueryAlt - Set Query Alternate (q.alt parameter)
    • SolrDisMaxQuery::setQueryPhraseSlop - specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)
    • SolrDisMaxQuery::setTieBreaker - Sets Tie Breaker parameter (tie parameter)
    • SolrDisMaxQuery::setTrigramPhraseFields - Directly Sets Trigram Phrase Fields (pf3 parameter)
    • SolrDisMaxQuery::setTrigramPhraseSlop - Sets Trigram Phrase Slop (ps3 parameter)
    • SolrDisMaxQuery::setUserFields - Sets User Fields parameter (uf)
    • SolrDisMaxQuery::useDisMaxQueryParser - Switch QueryParser to be DisMax Query Parser
    • SolrDisMaxQuery::useEDisMaxQueryParser - Switch QueryParser to be EDisMax
    • SolrDisMaxQuery::__construct - Class Constructor
    • 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::getChildDocuments - Returns an array of child documents (SolrDocument)
    • SolrDocument::getChildDocumentsCount - Returns the number of child documents
    • 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::hasChildDocuments - Checks whether the document has any child documents
    • 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 - Access 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::addChildDocument - Adds a child document for block indexing
    • SolrInputDocument::addChildDocuments - Adds an array of child documents
    • 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::getChildDocuments - Returns an array of child documents (SolrInputDocument)
    • SolrInputDocument::getChildDocumentsCount - Returns the number of child documents
    • 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::hasChildDocuments - Returns true if the document has any child documents
    • 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 - Unsets 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::addExpandFilterQuery - Overrides main filter query, determines which documents to include in the main group.
    • SolrQuery::addExpandSortField - Orders the documents within the expanded groups (expand.sort parameter).
    • 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::addGroupField - Add a field to be used to group results.
    • SolrQuery::addGroupFunction - Allows grouping results based on the unique values of a function query (group.func parameter).
    • SolrQuery::addGroupQuery - Allows grouping of documents that match the given query.
    • SolrQuery::addGroupSortField - Add a group sort field (group.sort parameter).
    • 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::collapse - Collapses the result set to a single document per group
    • SolrQuery::getExpand - Returns true if group expanding is enabled
    • SolrQuery::getExpandFilterQueries - Returns the expand filter queries
    • SolrQuery::getExpandQuery - Returns the expand query expand.q parameter
    • SolrQuery::getExpandRows - Returns The number of rows to display in each group (expand.rows)
    • SolrQuery::getExpandSortFields - Returns an array of fields
    • 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::getGroup - Returns true if grouping is enabled
    • SolrQuery::getGroupCachePercent - Returns group cache percent value
    • SolrQuery::getGroupFacet - Returns the group.facet parameter value
    • SolrQuery::getGroupFields - Returns group fields (group.field parameter values)
    • SolrQuery::getGroupFormat - Returns the group.format value
    • SolrQuery::getGroupFunctions - Returns group functions (group.func parameter values)
    • SolrQuery::getGroupLimit - Returns the group.limit value
    • SolrQuery::getGroupMain - Returns the group.main value
    • SolrQuery::getGroupNGroups - Returns the group.ngroups value
    • SolrQuery::getGroupOffset - Returns the group.offset value
    • SolrQuery::getGroupQueries - Returns all the group.query parameter values
    • SolrQuery::getGroupSortFields - Returns the group.sort value
    • SolrQuery::getGroupTruncate - Returns the group.truncate value
    • 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::removeExpandFilterQuery - Removes an expand filter query
    • SolrQuery::removeExpandSortField - Removes an expand sort field from the expand.sort parameter.
    • 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::setExpand - Enables/Disables the Expand Component
    • SolrQuery::setExpandQuery - Sets the expand.q parameter
    • SolrQuery::setExpandRows - Sets the number of rows to display in each group (expand.rows). Server Default 5
    • 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::setGroup - Enable/Disable result grouping (group parameter)
    • SolrQuery::setGroupCachePercent - Enables caching for result grouping
    • SolrQuery::setGroupFacet - Sets group.facet parameter
    • SolrQuery::setGroupFormat - Sets the group format, result structure (group.format parameter).
    • SolrQuery::setGroupLimit - Specifies the number of results to return for each group. The server default value is 1.
    • SolrQuery::setGroupMain - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.
    • SolrQuery::setGroupNGroups - If true, Solr includes the number of groups that have matched the query in the results.
    • SolrQuery::setGroupOffset - Sets the group.offset parameter.
    • SolrQuery::setGroupTruncate - If true, facet counts are based on the most relevant document of each group matching the query.
    • 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
    • SolrServerException::getInternalInfo - Returns internal information where the Exception was thrown
    • 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 - Sort an array
    • 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::add - Add/insert a new value at the specified index
    • 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::serialize - Serializes the storage
    • 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::unserialize - Unserializes the storage
    • 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 used with SplFileInfo::openFile
    • SplFileInfo::setInfoClass - Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::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 - Write a field array as a CSV line
    • SplFileObject::fread - Read from file
    • 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, enclosure and escape character for CSV
    • SplFileObject::getCurrentLine - Pseudonim al 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, enclosure and escape 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 - Pseudonim al 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
    • SplFixedArray::__wakeup - Reinitialises the array after being unserialised
    • 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 shift 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 given strings can be confused
    • 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::createCollation - Registers a PHP function for use as an SQL collating function
    • SQLite3::createFunction - Registers a PHP function for use as an SQL scalar function
    • SQLite3::enableExceptions - Enable throwing exceptions
    • 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::openBlob - Opens a stream resource to read a BLOB
    • 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::readOnly() - Returns whether a statement is definitely read only
    • 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 - Pseudonim pentru 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 - Square root
    • srand - Seed the random number generator
    • 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_agent - Authenticate over SSH using the ssh agent
    • 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_chmod - Changes file mode
    • 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 - Descrierea
    • 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 - Descrierea
    • 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 - Descrierea
    • 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 - Pseudonim pentru 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 a 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 metadata
    • 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_truncate - Truncate 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 - Creates a stream context
    • stream_context_get_default - Retrieve the default stream 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 stream 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 parameter
    • stream_register_wrapper - Pseudonim pentru 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_chunk_size - Set the stream chunk size
    • 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 - Formateaza o ora/data locala în conformitate cu setarile locale
    • 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 - Find the last occurrence of a character in a string
    • strrev - Reverse a string
    • strripos - Find the position of the last occurrence of a case-insensitive substring in a string
    • strrpos - Find the position of the last occurrence of a substring in a string
    • 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 - Make a string lowercase
    • strtotime - Transleaza aproape orice descriere textuala în limba engleza a datei ?i orei într-un timestamp Unix
    • strtoupper - Make a string uppercase
    • strtr - Translate characters or replace substrings
    • strval - Ob?ine valoarea string a unei variabile
    • 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 - Replace text within a portion of a string
    • 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 - Descrierea
    • SWFDisplayItem::getX - Descrierea
    • SWFDisplayItem::getXScale - Descrierea
    • SWFDisplayItem::getXSkew - Descrierea
    • SWFDisplayItem::getY - Descrierea
    • SWFDisplayItem::getYScale - Descrierea
    • SWFDisplayItem::getYSkew - Descrierea
    • 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 - Descrierea
    • SWFMovie::addFont - Descrierea
    • SWFMovie::importChar - Descrierea
    • SWFMovie::importFont - Descrierea
    • 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 - Descrierea
    • 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 - Descrierea
    • SWFMovie::stopSound - Descrierea
    • SWFMovie::streamMP3 - Streams a MP3 file
    • SWFMovie::writeExports - Descrierea
    • 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 - Descrierea
    • SWFSoundInstance::loopInPoint - Descrierea
    • SWFSoundInstance::loopOutPoint - Descrierea
    • SWFSoundInstance::noMultiple - Descrierea
    • 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 - Descrierea
    • SWFSprite::stopSound - Descrierea
    • SWFSprite::__construct - Creeaza un videoclip (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
    • 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 - Creates a symbolic link
    • SyncEvent::fire - Fires/sets the event
    • SyncEvent::reset - Resets a manual event
    • SyncEvent::wait - Waits for the event to be fired/set
    • SyncEvent::__construct - Constructs a new SyncEvent object
    • SyncMutex::lock - Waits for an exclusive lock
    • SyncMutex::unlock - Unlocks the mutex
    • SyncMutex::__construct - Constructs a new SyncMutex object
    • SyncReaderWriter::readlock - Waits for a read lock
    • SyncReaderWriter::readunlock - Releases a read lock
    • SyncReaderWriter::writelock - Waits for an exclusive write lock
    • SyncReaderWriter::writeunlock - Releases a write lock
    • SyncReaderWriter::__construct - Constructs a new SyncReaderWriter object
    • SyncSemaphore::lock - Decreases the count of the semaphore or waits
    • SyncSemaphore::unlock - Increases the count of the semaphore
    • SyncSemaphore::__construct - Constructs a new SyncSemaphore object
    • SyncSharedMemory::first - Check to see if the object is the first instance system-wide of named shared memory
    • SyncSharedMemory::read - Copy data from named shared memory
    • SyncSharedMemory::size - Returns the size of the named shared memory
    • SyncSharedMemory::write - Copy data to named shared memory
    • SyncSharedMemory::__construct - Constructs a new SyncSharedMemory object
    • 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
    • taint - Taint a string
    • tan - Tangent
    • tanh - Hyperbolic tangent
    • tcpwrap_check - Performs a tcpwrap check
    • tempnam - Create file with unique file name
    • textdomain - Sets the default domain
    • Thread::detach - Execution
    • Thread::getCreatorId - Identification
    • Thread::getCurrentThread - Identification
    • Thread::getCurrentThreadId - Identification
    • Thread::getThreadId - Identification
    • Thread::globally - Execution
    • Thread::isJoined - State Detection
    • Thread::isStarted - State Detection
    • Thread::join - Synchronization
    • Thread::kill - Execution
    • Thread::start - Execution
    • Threaded::chunk - Manipulation
    • Threaded::count - Manipulation
    • Threaded::extend - Runtime Manipulation
    • Threaded::from - Creation
    • Threaded::getTerminationInfo - Error Detection
    • Threaded::isRunning - State Detection
    • Threaded::isTerminated - State Detection
    • Threaded::isWaiting - State Detection
    • Threaded::lock - Synchronization
    • Threaded::merge - Manipulation
    • Threaded::notify - Synchronization
    • Threaded::pop - Manipulation
    • Threaded::run - Execution
    • Threaded::shift - Manipulation
    • Threaded::synchronized - Synchronization
    • Threaded::unlock - Synchronization
    • Threaded::wait - Synchronization
    • Throwable::getCode - Gets the exception code
    • Throwable::getFile - Gets the file in which the exception was created
    • Throwable::getLine - Gets the line on which the object was instantiated
    • Throwable::getMessage - Gets the message
    • Throwable::getPrevious - Returns the previous Throwable
    • Throwable::getTrace - Gets the stack trace
    • Throwable::getTraceAsString - Gets the stack trace as a string
    • Throwable::__toString - Gets a string representation of the thrown object
    • 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 - Returns the parent node of the current node
    • tidyNode::hasChildren - Checks if a node has children
    • tidyNode::hasSiblings - Checks if a node has siblings
    • tidyNode::isAsp - Checks if this node is ASP
    • tidyNode::isComment - Checks if a node represents a comment
    • tidyNode::isHtml - Checks if a node is part of a HTML document
    • tidyNode::isJste - Checks if this node is JSTE
    • tidyNode::isPhp - Checks if a node is PHP
    • tidyNode::isText - Checks if a node represents text (no markup)
    • tidy_access_count - Returns the Number of Tidy accessibility warnings encountered for specified document
    • tidy_config_count - Returns the Number of Tidy configuration errors encountered for specified document
    • tidy_error_count - Returns the Number of Tidy errors encountered for specified document
    • tidy_get_output - Return a string representing the parsed tidy markup
    • tidy_load_config - Load an ASCII Tidy configuration file with the specified encoding
    • tidy_reset_config - Restore Tidy configuration to default values
    • tidy_save_config - Save current settings to named file
    • tidy_setopt - Updates the configuration settings for the specified tidy document
    • tidy_set_encoding - Set the input/output character encoding for parsing markup
    • tidy_warning_count - Returns the Number of Tidy warnings encountered for specified document
    • time - Întoarce timpul curent Unix
    • timezone_abbreviations_list - Pseudonim pentru DateTimeZone::listAbbreviations
    • timezone_identifiers_list - Pseudonim pentru DateTimeZone::listIdentifiers
    • timezone_location_get - Pseudonim pentru DateTimeZone::getLocation
    • timezone_name_from_abbr - Returns the timezone name from abbreviation
    • timezone_name_get - Pseudonim pentru DateTimeZone::getName
    • timezone_offset_get - Pseudonim pentru DateTimeZone::getOffset
    • timezone_open - Pseudonim pentru DateTimeZone::__construct
    • timezone_transitions_get - Pseudonim pentru 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 - Creates a temporary file
    • token_get_all - Split given source into PHP tokens
    • token_name - Get the symbolic name of a given PHP token
    • 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 - Sets access and modification time of file
    • trader_acos - Vector Trigonometric ACos
    • trader_ad - Chaikin A/D Line
    • trader_add - Vector Arithmetic Add
    • trader_adosc - Chaikin A/D Oscillator
    • trader_adx - Average Directional Movement Index
    • trader_adxr - Average Directional Movement Index Rating
    • trader_apo - Absolute Price Oscillator
    • trader_aroon - Aroon
    • trader_aroonosc - Aroon Oscillator
    • trader_asin - Vector Trigonometric ASin
    • trader_atan - Vector Trigonometric ATan
    • trader_atr - Average True Range
    • trader_avgprice - Average Price
    • trader_bbands - Bollinger Bands
    • trader_beta - Beta
    • trader_bop - Balance Of Power
    • trader_cci - Commodity Channel Index
    • trader_cdl2crows - Two Crows
    • trader_cdl3blackcrows - Three Black Crows
    • trader_cdl3inside - Three Inside Up/Down
    • trader_cdl3linestrike - Three-Line Strike
    • trader_cdl3outside - Three Outside Up/Down
    • trader_cdl3starsinsouth - Three Stars In The South
    • trader_cdl3whitesoldiers - Three Advancing White Soldiers
    • trader_cdlabandonedbaby - Abandoned Baby
    • trader_cdladvanceblock - Advance Block
    • trader_cdlbelthold - Belt-hold
    • trader_cdlbreakaway - Breakaway
    • trader_cdlclosingmarubozu - Closing Marubozu
    • trader_cdlconcealbabyswall - Concealing Baby Swallow
    • trader_cdlcounterattack - Counterattack
    • trader_cdldarkcloudcover - Dark Cloud Cover
    • trader_cdldoji - Doji
    • trader_cdldojistar - Doji Star
    • trader_cdldragonflydoji - Dragonfly Doji
    • trader_cdlengulfing - Engulfing Pattern
    • trader_cdleveningdojistar - Evening Doji Star
    • trader_cdleveningstar - Evening Star
    • trader_cdlgapsidesidewhite - Up/Down-gap side-by-side white lines
    • trader_cdlgravestonedoji - Gravestone Doji
    • trader_cdlhammer - Hammer
    • trader_cdlhangingman - Hanging Man
    • trader_cdlharami - Harami Pattern
    • trader_cdlharamicross - Harami Cross Pattern
    • trader_cdlhighwave - High-Wave Candle
    • trader_cdlhikkake - Hikkake Pattern
    • trader_cdlhikkakemod - Modified Hikkake Pattern
    • trader_cdlhomingpigeon - Homing Pigeon
    • trader_cdlidentical3crows - Identical Three Crows
    • trader_cdlinneck - In-Neck Pattern
    • trader_cdlinvertedhammer - Inverted Hammer
    • trader_cdlkicking - Kicking
    • trader_cdlkickingbylength - Kicking - bull/bear determined by the longer marubozu
    • trader_cdlladderbottom - Ladder Bottom
    • trader_cdllongleggeddoji - Long Legged Doji
    • trader_cdllongline - Long Line Candle
    • trader_cdlmarubozu - Marubozu
    • trader_cdlmatchinglow - Matching Low
    • trader_cdlmathold - Mat Hold
    • trader_cdlmorningdojistar - Morning Doji Star
    • trader_cdlmorningstar - Morning Star
    • trader_cdlonneck - On-Neck Pattern
    • trader_cdlpiercing - Piercing Pattern
    • trader_cdlrickshawman - Rickshaw Man
    • trader_cdlrisefall3methods - Rising/Falling Three Methods
    • trader_cdlseparatinglines - Separating Lines
    • trader_cdlshootingstar - Shooting Star
    • trader_cdlshortline - Short Line Candle
    • trader_cdlspinningtop - Spinning Top
    • trader_cdlstalledpattern - Stalled Pattern
    • trader_cdlsticksandwich - Stick Sandwich
    • trader_cdltakuri - Takuri (Dragonfly Doji with very long lower shadow)
    • trader_cdltasukigap - Tasuki Gap
    • trader_cdlthrusting - Thrusting Pattern
    • trader_cdltristar - Tristar Pattern
    • trader_cdlunique3river - Unique 3 River
    • trader_cdlupsidegap2crows - Upside Gap Two Crows
    • trader_cdlxsidegap3methods - Upside/Downside Gap Three Methods
    • trader_ceil - Vector Ceil
    • trader_cmo - Chande Momentum Oscillator
    • trader_correl - Pearson's Correlation Coefficient (r)
    • trader_cos - Vector Trigonometric Cos
    • trader_cosh - Vector Trigonometric Cosh
    • trader_dema - Double Exponential Moving Average
    • trader_div - Vector Arithmetic Div
    • trader_dx - Directional Movement Index
    • trader_ema - Exponential Moving Average
    • trader_errno - Get error code
    • trader_exp - Vector Arithmetic Exp
    • trader_floor - Vector Floor
    • trader_get_compat - Get compatibility mode
    • trader_get_unstable_period - Get unstable period
    • trader_ht_dcperiod - Hilbert Transform - Dominant Cycle Period
    • trader_ht_dcphase - Hilbert Transform - Dominant Cycle Phase
    • trader_ht_phasor - Hilbert Transform - Phasor Components
    • trader_ht_sine - Hilbert Transform - SineWave
    • trader_ht_trendline - Hilbert Transform - Instantaneous Trendline
    • trader_ht_trendmode - Hilbert Transform - Trend vs Cycle Mode
    • trader_kama - Kaufman Adaptive Moving Average
    • trader_linearreg - Linear Regression
    • trader_linearreg_angle - Linear Regression Angle
    • trader_linearreg_intercept - Linear Regression Intercept
    • trader_linearreg_slope - Linear Regression Slope
    • trader_ln - Vector Log Natural
    • trader_log10 - Vector Log10
    • trader_ma - Moving average
    • trader_macd - Moving Average Convergence/Divergence
    • trader_macdext - MACD with controllable MA type
    • trader_macdfix - Moving Average Convergence/Divergence Fix 12/26
    • trader_mama - MESA Adaptive Moving Average
    • trader_mavp - Moving average with variable period
    • trader_max - Highest value over a specified period
    • trader_maxindex - Index of highest value over a specified period
    • trader_medprice - Median Price
    • trader_mfi - Money Flow Index
    • trader_midpoint - MidPoint over period
    • trader_midprice - Midpoint Price over period
    • trader_min - Lowest value over a specified period
    • trader_minindex - Index of lowest value over a specified period
    • trader_minmax - Lowest and highest values over a specified period
    • trader_minmaxindex - Indexes of lowest and highest values over a specified period
    • trader_minus_di - Minus Directional Indicator
    • trader_minus_dm - Minus Directional Movement
    • trader_mom - Momentum
    • trader_mult - Vector Arithmetic Mult
    • trader_natr - Normalized Average True Range
    • trader_obv - On Balance Volume
    • trader_plus_di - Plus Directional Indicator
    • trader_plus_dm - Plus Directional Movement
    • trader_ppo - Percentage Price Oscillator
    • trader_roc - Rate of change : ((price/prevPrice)-1)*100
    • trader_rocp - Rate of change Percentage: (price-prevPrice)/prevPrice
    • trader_rocr - Rate of change ratio: (price/prevPrice)
    • trader_rocr100 - Rate of change ratio 100 scale: (price/prevPrice)*100
    • trader_rsi - Relative Strength Index
    • trader_sar - Parabolic SAR
    • trader_sarext - Parabolic SAR - Extended
    • trader_set_compat - Set compatibility mode
    • trader_set_unstable_period - Set unstable period
    • trader_sin - Vector Trigonometric Sin
    • trader_sinh - Vector Trigonometric Sinh
    • trader_sma - Simple Moving Average
    • trader_sqrt - Vector Square Root
    • trader_stddev - Standard Deviation
    • trader_stoch - Stochastic
    • trader_stochf - Stochastic Fast
    • trader_stochrsi - Stochastic Relative Strength Index
    • trader_sub - Vector Arithmetic Subtraction
    • trader_sum - Summation
    • trader_t3 - Triple Exponential Moving Average (T3)
    • trader_tan - Vector Trigonometric Tan
    • trader_tanh - Vector Trigonometric Tanh
    • trader_tema - Triple Exponential Moving Average
    • trader_trange - True Range
    • trader_trima - Triangular Moving Average
    • trader_trix - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
    • trader_tsf - Time Series Forecast
    • trader_typprice - Typical Price
    • trader_ultosc - Ultimate Oscillator
    • trader_var - Variance
    • trader_wclprice - Weighted Close Price
    • trader_willr - Williams' %R
    • trader_wma - Weighted Moving Average
    • 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 - Private constructor to deny instantiation
    • trigger_error - Genereaza un mesaj de eroare/avertizare/notificare la nivelul utilizatorului
    • trim - Strip whitespace (or other characters) from the beginning and end of a string
  • u
    • uasort - Sort an array with a user-defined comparison function and maintain index association
    • ucfirst - Make a string's first character uppercase
    • UConverter::convert - Convert string from one charset to another
    • UConverter::fromUCallback - Default "from" callback function
    • UConverter::getAliases - Get the aliases of the given name
    • UConverter::getAvailable - Get the available canonical converter names
    • UConverter::getDestinationEncoding - Get the destination encoding
    • UConverter::getDestinationType - Get the destination converter type
    • UConverter::getErrorCode - Get last error code on the object
    • UConverter::getErrorMessage - Get last error message on the object
    • UConverter::getSourceEncoding - Get the source encoding
    • UConverter::getSourceType - Get the source convertor type
    • UConverter::getStandards - Get standards associated to converter names
    • UConverter::getSubstChars - Get substitution chars
    • UConverter::reasonText - Get string representation of the callback reason
    • UConverter::setDestinationEncoding - Set the destination encoding
    • UConverter::setSourceEncoding - Set the source encoding
    • UConverter::setSubstChars - Set the substitution chars
    • UConverter::toUCallback - Default "to" callback function
    • UConverter::transcode - Convert string from one charset to another
    • UConverter::__construct - Create UConverter object
    • 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_clear_search_limits - Clear all mnoGoSearch search restrictions
    • 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 given string
    • udm_load_ispell_data - Load ispell data
    • udm_set_agent_param - Set mnoGoSearch agent session parameters
    • UI\Area::onDraw - Draw Callback
    • UI\Area::onKey - Key Callback
    • UI\Area::onMouse - Mouse Callback
    • UI\Area::redraw - Redraw Area
    • UI\Area::scrollTo - Area Scroll
    • UI\Area::setSize - Set Size
    • UI\Control::destroy - Destroy Control
    • UI\Control::disable - Disable Control
    • UI\Control::enable - Enable Control
    • UI\Control::getParent - Get Parent Control
    • UI\Control::getTopLevel - Get Top Level
    • UI\Control::hide - Hide Control
    • UI\Control::isEnabled - Determine if Control is enabled
    • UI\Control::isVisible - Determine if Control is visible
    • UI\Control::setParent - Set Parent Control
    • UI\Control::show - Control Show
    • UI\Controls\Box::append - Append Control
    • UI\Controls\Box::delete - Delete Control
    • UI\Controls\Box::getOrientation - Get Orientation
    • UI\Controls\Box::isPadded - Padding Detection
    • UI\Controls\Box::setPadded - Set Padding
    • UI\Controls\Box::__construct - Construct a new Box
    • UI\Controls\Button::getText - Get Text
    • UI\Controls\Button::onClick - Click Handler
    • UI\Controls\Button::setText - Set Text
    • UI\Controls\Button::__construct - Construct a new Button
    • UI\Controls\Check::getText - Get Text
    • UI\Controls\Check::isChecked - Checked Detection
    • UI\Controls\Check::onToggle - Toggle Callback
    • UI\Controls\Check::setChecked - Set Checked
    • UI\Controls\Check::setText - Set Text
    • UI\Controls\Check::__construct - Construct a new Check
    • UI\Controls\ColorButton::getColor - Get Color
    • UI\Controls\ColorButton::onChange - Change Handler
    • UI\Controls\ColorButton::setColor - Set Color
    • UI\Controls\Combo::append - Append Option
    • UI\Controls\Combo::getSelected - Get Selected Option
    • UI\Controls\Combo::onSelected - Selected Handler
    • UI\Controls\Combo::setSelected - Set Selected Option
    • UI\Controls\EditableCombo::append - Append Option
    • UI\Controls\EditableCombo::getText - Get Text
    • UI\Controls\EditableCombo::onChange - Change Handler
    • UI\Controls\EditableCombo::setText - Set Text
    • UI\Controls\Entry::getText - Get Text
    • UI\Controls\Entry::isReadOnly - Detect Read Only
    • UI\Controls\Entry::onChange - Change Handler
    • UI\Controls\Entry::setReadOnly - Set Read Only
    • UI\Controls\Entry::setText - Set Text
    • UI\Controls\Entry::__construct - Construct a new Entry
    • UI\Controls\Form::append - Append Control
    • UI\Controls\Form::delete - Delete Control
    • UI\Controls\Form::isPadded - Padding Detection
    • UI\Controls\Form::setPadded - Set Padding
    • UI\Controls\Grid::append - Append Control
    • UI\Controls\Grid::isPadded - Padding Detection
    • UI\Controls\Grid::setPadded - Set Padding
    • UI\Controls\Group::append - Append Control
    • UI\Controls\Group::getTitle - Get Title
    • UI\Controls\Group::hasMargin - Margin Detection
    • UI\Controls\Group::setMargin - Set Margin
    • UI\Controls\Group::setTitle - Set Title
    • UI\Controls\Group::__construct - Construct a new Group
    • UI\Controls\Label::getText - Get Text
    • UI\Controls\Label::setText - Set Text
    • UI\Controls\Label::__construct - Construct a new Label
    • UI\Controls\MultilineEntry::append - Append Text
    • UI\Controls\MultilineEntry::getText - Get Text
    • UI\Controls\MultilineEntry::isReadOnly - Read Only Detection
    • UI\Controls\MultilineEntry::onChange - Change Handler
    • UI\Controls\MultilineEntry::setReadOnly - Set Read Only
    • UI\Controls\MultilineEntry::setText - Set Text
    • UI\Controls\MultilineEntry::__construct - Construct a new Multiline Entry
    • UI\Controls\Picker::__construct - Construct a new Picker
    • UI\Controls\Progress::getValue - Get Value
    • UI\Controls\Progress::setValue - Set Value
    • UI\Controls\Radio::append - Append Option
    • UI\Controls\Radio::getSelected - Get Selected Option
    • UI\Controls\Radio::onSelected - Selected Handler
    • UI\Controls\Radio::setSelected - Set Selected Option
    • UI\Controls\Separator::__construct - Construct a new Separator
    • UI\Controls\Slider::getValue - Get Value
    • UI\Controls\Slider::onChange - Change Handler
    • UI\Controls\Slider::setValue - Set Value
    • UI\Controls\Slider::__construct - Construct a new Slider
    • UI\Controls\Spin::getValue - Get Value
    • UI\Controls\Spin::onChange - Change Handler
    • UI\Controls\Spin::setValue - Set Value
    • UI\Controls\Spin::__construct - Construct a new Spin
    • UI\Controls\Tab::append - Append Page
    • UI\Controls\Tab::delete - Delete Page
    • UI\Controls\Tab::hasMargin - Margin Detection
    • UI\Controls\Tab::insertAt - Insert Page
    • UI\Controls\Tab::pages - Page Count
    • UI\Controls\Tab::setMargin - Set Margin
    • UI\Draw\Brush::getColor - Get Color
    • UI\Draw\Brush::setColor - Set Color
    • UI\Draw\Brush::__construct - Construct a new Brush
    • UI\Draw\Brush\Gradient::addStop - Stop Manipulation
    • UI\Draw\Brush\Gradient::delStop - Stop Manipulation
    • UI\Draw\Brush\Gradient::setStop - Stop Manipulation
    • UI\Draw\Brush\LinearGradient::__construct - Construct a Linear Gradient
    • UI\Draw\Brush\RadialGradient::__construct - Construct a new Radial Gradient
    • UI\Draw\Color::getChannel - Color Manipulation
    • UI\Draw\Color::setChannel - Color Manipulation
    • UI\Draw\Color::__construct - Construct new Color
    • UI\Draw\Matrix::invert - Invert Matrix
    • UI\Draw\Matrix::isInvertible - Invertible Detection
    • UI\Draw\Matrix::multiply - Multiply Matrix
    • UI\Draw\Matrix::rotate - Rotate Matrix
    • UI\Draw\Matrix::scale - Scale Matrix
    • UI\Draw\Matrix::skew - Skew Matrix
    • UI\Draw\Matrix::translate - Translate Matrix
    • UI\Draw\Path::addRectangle - Draw a Rectangle
    • UI\Draw\Path::arcTo - Draw an Arc
    • UI\Draw\Path::bezierTo - Draw Bezier Curve
    • UI\Draw\Path::closeFigure - Close Figure
    • UI\Draw\Path::end - Finalize Path
    • UI\Draw\Path::lineTo - Draw a Line
    • UI\Draw\Path::newFigure - Draw Figure
    • UI\Draw\Path::newFigureWithArc - Draw Figure with Arc
    • UI\Draw\Path::__construct - Construct a new Path
    • UI\Draw\Pen::clip - Clip a Path
    • UI\Draw\Pen::fill - Fill a Path
    • UI\Draw\Pen::restore - Restore
    • UI\Draw\Pen::save - Save
    • UI\Draw\Pen::stroke - Stroke a Path
    • UI\Draw\Pen::transform - Matrix Transform
    • UI\Draw\Pen::write - Draw Text at Point
    • UI\Draw\Stroke::getCap - Get Line Cap
    • UI\Draw\Stroke::getJoin - Get Line Join
    • UI\Draw\Stroke::getMiterLimit - Get Miter Limit
    • UI\Draw\Stroke::getThickness - Get Thickness
    • UI\Draw\Stroke::setCap - Set Line Cap
    • UI\Draw\Stroke::setJoin - Set Line Join
    • UI\Draw\Stroke::setMiterLimit - Set Miter Limit
    • UI\Draw\Stroke::setThickness - Set Thickness
    • UI\Draw\Stroke::__construct - Construct a new Stroke
    • UI\Draw\Text\Font::getAscent - Font Metrics
    • UI\Draw\Text\Font::getDescent - Font Metrics
    • UI\Draw\Text\Font::getLeading - Font Metrics
    • UI\Draw\Text\Font::getUnderlinePosition - Font Metrics
    • UI\Draw\Text\Font::getUnderlineThickness - Font Metrics
    • UI\Draw\Text\Font::__construct - Construct a new Font
    • UI\Draw\Text\Font\Descriptor::getFamily - Get Font Family
    • UI\Draw\Text\Font\Descriptor::getItalic - Style Detection
    • UI\Draw\Text\Font\Descriptor::getSize - Size Detection
    • UI\Draw\Text\Font\Descriptor::getStretch - Style Detection
    • UI\Draw\Text\Font\Descriptor::getWeight - Weight Detection
    • UI\Draw\Text\Font\Descriptor::__construct - Construct a new Font Descriptor
    • UI\Draw\Text\Font\fontFamilies - Retrieve Font Families
    • UI\Draw\Text\Layout::setColor - Set Color
    • UI\Draw\Text\Layout::setWidth - Set Width
    • UI\Draw\Text\Layout::__construct - Construct a new Text Layout
    • UI\Executor::kill - Stop Executor
    • UI\Executor::onExecute - Execution Callback
    • UI\Executor::setInterval - Interval Manipulation
    • UI\Executor::__construct - Construct a new Executor
    • UI\Menu::append - Append Menu Item
    • UI\Menu::appendAbout - Append About Menu Item
    • UI\Menu::appendCheck - Append Checkable Menu Item
    • UI\Menu::appendPreferences - Append Preferences Menu Item
    • UI\Menu::appendQuit - Append Quit Menu Item
    • UI\Menu::appendSeparator - Append Menu Item Separator
    • UI\Menu::__construct - Construct a new Menu
    • UI\MenuItem::disable - Disable Menu Item
    • UI\MenuItem::enable - Enable Menu Item
    • UI\MenuItem::isChecked - Detect Checked
    • UI\MenuItem::onClick - On Click Callback
    • UI\MenuItem::setChecked - Set Checked
    • UI\Point::at - Size Coercion
    • UI\Point::getX - Retrieves X
    • UI\Point::getY - Retrieves Y
    • UI\Point::setX - Set X
    • UI\Point::setY - Set Y
    • UI\Point::__construct - Construct a new Point
    • UI\quit - Quit UI Loop
    • UI\run - Enter UI Loop
    • UI\Size::getHeight - Retrieves Height
    • UI\Size::getWidth - Retrives Width
    • UI\Size::of - Point Coercion
    • UI\Size::setHeight - Set Height
    • UI\Size::setWidth - Set Width
    • UI\Size::__construct - Construct a new Size
    • UI\Window::add - Add a Control
    • UI\Window::error - Show Error Box
    • UI\Window::getSize - Get Window Size
    • UI\Window::getTitle - Get Title
    • UI\Window::hasBorders - Border Detection
    • UI\Window::hasMargin - Margin Detection
    • UI\Window::isFullScreen - Full Screen Detection
    • UI\Window::msg - Show Message Box
    • UI\Window::onClosing - Closing Callback
    • UI\Window::open - Open Dialog
    • UI\Window::save - Save Dialog
    • UI\Window::setBorders - Border Use
    • UI\Window::setFullScreen - Full Screen Use
    • UI\Window::setMargin - Margin Use
    • UI\Window::setSize - Set Size
    • UI\Window::setTitle - Window Title
    • UI\Window::__construct - Construct a new Window
    • uksort - Sort an array by keys using a user-defined comparison function
    • umask - Changes the current umask
    • uniqid - Generate a unique ID
    • unixtojd - Convert Unix timestamp to Julian Day
    • unlink - Deletes a file
    • unpack - Unpack data from binary string
    • unregister_tick_function - De-register a function for execution on each tick
    • unserialize - Creeaza o valoare PHP dintr-o reprezentare stocata
    • unset - Elimina o variabila data
    • untaint - Untaint strings
    • uopz_backup - Backup a function
    • uopz_compose - Compose a class
    • uopz_copy - Copy a function
    • uopz_delete - Delete a function
    • uopz_extend - Extend a class at runtime
    • uopz_flags - Get or set flags on function or class
    • uopz_function - Creates a function at runtime
    • uopz_implement - Implements an interface at runtime
    • uopz_overload - Overload a VM opcode
    • uopz_redefine - Redefine a constant
    • uopz_rename - Rename a function at runtime
    • uopz_restore - Restore a previously backed up function
    • uopz_undefine - Undefine a constant
    • urldecode - Decodes URL-encoded string
    • urlencode - URL-encodes string
    • user_error - Pseudonim al trigger_error
    • use_soap_error_handler - Set whether to use the SOAP error handler
    • usleep - Delay execution in microseconds
    • usort - Sort an array by values using a user-defined comparison function
    • utf8_decode - Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1
    • utf8_encode - Encodes an ISO-8859-1 string to 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::disconnect - Disconnect from 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 - Afi?eaza informa?ia despre o variabila
    • var_export - Afi?eaza sau întoarce o reprezentare string, ce poate fi prelucrata, a unei variabile
    • version_compare - Compares two "PHP-standardized" version number strings
    • vfprintf - Write a formatted string to a stream
    • virtual - Efectueaza o sub-interpelare Apache
    • vpopmail_add_alias_domain - Add an alias for a virtual domain
    • vpopmail_add_alias_domain_ex - Add alias to an existing virtual domain
    • vpopmail_add_domain - Add a new virtual domain
    • vpopmail_add_domain_ex - Add a new virtual domain
    • vpopmail_add_user - Add a new user to the specified virtual domain
    • vpopmail_alias_add - Insert a virtual alias
    • vpopmail_alias_del - Deletes all virtual aliases of a user
    • vpopmail_alias_del_domain - Deletes all virtual aliases of a domain
    • vpopmail_alias_get - Get all lines of an alias for a domain
    • vpopmail_alias_get_all - Get all lines of an alias for a domain
    • vpopmail_auth_user - Attempt to validate a username/domain/password
    • vpopmail_del_domain - Delete a virtual domain
    • vpopmail_del_domain_ex - Delete a virtual domain
    • vpopmail_del_user - Delete a user from a virtual domain
    • vpopmail_error - Ob?ine mesajul textual pentru ultima eroare vpopmail
    • vpopmail_passwd - Change a virtual user's password
    • vpopmail_set_user_quota - Sets a virtual user's quota
    • vprintf - Output a formatted string
    • vsprintf - Return a formatted string
  • w
    • wddx_add_vars - Adauga variable la un pachet WDDX cu un ID specificat
    • wddx_deserialize - Deserializeaza un pachet WDDX
    • wddx_packet_end - Sfâr?e?te un pachet WDDX cu un ID specificat
    • wddx_packet_start - Ini?iaza un pachet nou WDDX cu structura sa interna
    • wddx_serialize_value - Serializeaza o singura valoare într-un pachet WDDX
    • wddx_serialize_vars - Serializeaza variabile într-un pachet WDDX
    • WeakMap::count - Counts the number of live entries in the map
    • WeakMap::current - Returns the current value under iteration
    • WeakMap::key - Returns the current key under iteration.
    • WeakMap::next - Advances to the next map element
    • WeakMap::offsetExists - Checks whether a certain object is in the map
    • WeakMap::offsetGet - Returns the value pointed to by a certain object
    • WeakMap::offsetSet - Updates the map with a new key-value pair
    • WeakMap::offsetUnset - Removes an entry from the map
    • WeakMap::rewind - Rewinds the iterator to the beginning of the map
    • WeakMap::valid - Returns whether the iterator is still on a valid map element
    • WeakMap::__construct - Constructs a new map
    • 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 - Wraps a string to a given number of characters
    • Worker::collect - Collect references to completed tasks
    • Worker::getStacked - Gets the remaining stack size
    • Worker::isShutdown - State Detection
    • Worker::isWorking - State Detection
    • Worker::shutdown - Shutdown the worker
    • Worker::stack - Stacking work
    • Worker::unstack - Unstacking work
  • 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 - Start XHProf profiling in sampling mode
    • XMLDiff\Base::diff - Produce diff of two XML documents
    • XMLDiff\Base::merge - Produce new XML document based on diff
    • XMLDiff\Base::__construct - Constructor
    • XMLDiff\DOM::diff - Diff two DOMDocument objects
    • XMLDiff\DOM::merge - Produce merged DOMDocument
    • XMLDiff\File::diff - Diff two XML files
    • XMLDiff\File::merge - Produce merged XML document
    • XMLDiff\Memory::diff - Diff two XML documents
    • XMLDiff\Memory::merge - Produce merged XML document
    • 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 itself
    • 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 - Decodifica XML în tipuri indigene PHP
    • xmlrpc_decode_request - Decodifica XML în tipuri PHP indigene
    • xmlrpc_encode - Genereaza XML pentru o valoare PHP
    • xmlrpc_encode_request - Genereaza XML pentru o cerere de metoda
    • xmlrpc_get_type - Ob?ine tipul xmlrpc pentru o valoare PHP
    • xmlrpc_is_fault - Determina daca o valoare din array reprezinta o gre?eala XMLRPC
    • xmlrpc_parse_method_descriptions - Decodifica XML într-o lista de descrieri ale metodelor
    • xmlrpc_server_add_introspection_data - Adauga documenta?ia de introspec?ie
    • xmlrpc_server_call_method - Prelucreaza interpelarile ?i metodele de apel XML
    • xmlrpc_server_create - Creeaza un server xmlrpc
    • xmlrpc_server_destroy - Destroys server resources
    • xmlrpc_server_register_introspection_callback - Înregistreaza o func?ie PHP pentru a genera documenta?ie
    • xmlrpc_server_register_method - Înregistreaza o func?ie PHP unei metode de resursa ce corespunde method_name
    • xmlrpc_set_type - Stabile?te tipul xmlrpc, base64 sau datetime, pentru o valoare string PHP
    • 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 - Get XML parser error string
    • xml_get_current_byte_index - Get current byte index for an XML parser
    • xml_get_current_column_number - Get current column number for an XML parser
    • xml_get_current_line_number - Get current line number for an XML parser
    • xml_get_error_code - Get XML parser error code
    • xml_parse - Start parsing an XML document
    • xml_parser_create - Create an XML parser
    • xml_parser_create_ns - Create an XML parser with namespace support
    • xml_parser_free - Free an XML parser
    • 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 - Set up start and end element handlers
    • 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
    • XSLTProcessor::getParameter - Get value of a parameter
    • XsltProcessor::getSecurityPrefs - Get security preferences
    • 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::setSecurityPrefs - Set security preferences
    • XSLTProcessor::transformToDoc - Transform to a DOMDocument
    • XSLTProcessor::transformToUri - Transform to URI
    • XSLTProcessor::transformToXML - Transform to XML
    • XSLTProcessor::__construct - Creates a new XSLTProcessor object
  • y
    • Yaf_Action_Abstract::execute - Action entry point
    • Yaf_Action_Abstract::getController - Retrieve controller object
    • Yaf_Application::app - Retrieve 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 - Returns a PHP array
    • Yaf_Config_Ini::valid - The valid purpose
    • Yaf_Config_Ini::__construct - Yaf_Config_Ini constructor
    • 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 - Returns a PHP array
    • 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 - foward to another action
    • Yaf_Controller_Abstract::getInvokeArg - The getInvokeArg purpose
    • Yaf_Controller_Abstract::getInvokeArgs - The getInvokeArgs purpose
    • Yaf_Controller_Abstract::getModuleName - Get module name
    • Yaf_Controller_Abstract::getRequest - Retrieve current request object
    • Yaf_Controller_Abstract::getResponse - Retrieve current response object
    • Yaf_Controller_Abstract::getView - Retrieve the view engine
    • Yaf_Controller_Abstract::getViewpath - The getViewpath purpose
    • Yaf_Controller_Abstract::init - Controller initializer
    • Yaf_Controller_Abstract::initView - The initView purpose
    • Yaf_Controller_Abstract::redirect - Redirect to a URL
    • Yaf_Controller_Abstract::render - Render view template
    • 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::setDefaultAction - Change default action name
    • Yaf_Dispatcher::setDefaultController - Change default controller name
    • Yaf_Dispatcher::setDefaultModule - Change default module name
    • Yaf_Dispatcher::setErrorHandler - Set error handler
    • 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 - register local class prefix
    • 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 - Remove an item from registry
    • Yaf_Registry::get - Retrieve an item from registry
    • Yaf_Registry::has - Check whether an item exists
    • Yaf_Registry::set - Add an item into registry
    • Yaf_Registry::__clone - The __clone purpose
    • Yaf_Registry::__construct - Yaf_Registry implements singleton
    • 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 - Retrieve ENV varialbe
    • 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 - Retrieve SERVER variable
    • 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 - set base URI
    • 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 - Retrieve variable from client
    • Yaf_Request_Http::getCookie - Retrieve Cookie variable
    • Yaf_Request_Http::getFiles - The getFiles purpose
    • Yaf_Request_Http::getPost - Retrieve POST variable
    • Yaf_Request_Http::getQuery - Fetch a query parameter
    • Yaf_Request_Http::getRequest - The getRequest purpose
    • Yaf_Request_Http::isXmlHttpRequest - Whether a Ajax Request
    • Yaf_Request_Http::__clone - The __clone purpose
    • Yaf_Request_Http::__construct - Constructor of Yaf_Request_Http
    • 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 - Constructor of Yaf_Request_Simple
    • Yaf_Response_Abstract::appendBody - append to body
    • Yaf_Response_Abstract::clearBody - The clearBody purpose
    • Yaf_Response_Abstract::clearHeaders - The clearHeaders purpose
    • Yaf_Response_Abstract::getBody - Retrieve a exists content
    • Yaf_Response_Abstract::getHeader - The getHeader purpose
    • Yaf_Response_Abstract::prependBody - The prependBody purpose
    • Yaf_Response_Abstract::response - send response
    • Yaf_Response_Abstract::setAllHeaders - The setAllHeaders purpose
    • Yaf_Response_Abstract::setBody - Set content to response
    • 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 - Retrieve a route by name
    • Yaf_Router::getRoutes - Retrieve registered routes
    • Yaf_Router::route - The route purpose
    • Yaf_Router::__construct - Yaf_Router constructor
    • Yaf_Route_Interface::assemble - assemble a request
    • Yaf_Route_Interface::route - route a request
    • Yaf_Route_Map::assemble - Assemble a url
    • Yaf_Route_Map::route - The route purpose
    • Yaf_Route_Map::__construct - The __construct purpose
    • Yaf_Route_Regex::assemble - Assemble a url
    • Yaf_Route_Regex::route - The route purpose
    • Yaf_Route_Regex::__construct - Yaf_Route_Regex constructor
    • Yaf_Route_Rewrite::assemble - Assemble a url
    • Yaf_Route_Rewrite::route - The route purpose
    • Yaf_Route_Rewrite::__construct - Yaf_Route_Rewrite constructor
    • Yaf_Route_Simple::assemble - Assemble a url
    • Yaf_Route_Simple::route - Route a request
    • Yaf_Route_Simple::__construct - Yaf_Route_Simple constructor
    • Yaf_Route_Static::assemble - Assemble a url
    • Yaf_Route_Static::match - The match purpose
    • Yaf_Route_Static::route - Route a request
    • Yaf_Route_Supervar::assemble - Assemble a url
    • 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 - Constructor of Yaf_Session
    • 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::clear - Clear Assigned values
    • Yaf_View_Simple::display - Render and display
    • Yaf_View_Simple::eval - Render template
    • Yaf_View_Simple::getScriptPath - Get templates directory
    • Yaf_View_Simple::render - Render template
    • Yaf_View_Simple::setScriptPath - Set tempaltes directory
    • Yaf_View_Simple::__construct - Constructor of Yaf_View_Simple
    • Yaf_View_Simple::__get - Retrieve assigned variable
    • 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
    • Yar_Client::setOpt - Set calling contexts
    • Yar_Client::__call - Call service
    • Yar_Client::__construct - Create a client
    • Yar_Client_Exception::getType - The getType purpose
    • Yar_Concurrent_Client::call - Register a concurrent call
    • Yar_Concurrent_Client::loop - Send all calls
    • Yar_Concurrent_Client::reset - Clean all registered calls
    • Yar_Server::handle - Start RPC Server
    • Yar_Server::__construct - Register a server
    • Yar_Server_Exception::getType - The getType purpose
    • 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::addGlob - Add files from a directory by glob pattern
    • ZipArchive::addPattern - Add files from a directory by PCRE pattern
    • 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::getExternalAttributesIndex - Retrieve the external attributes of an entry defined by its index
    • ZipArchive::getExternalAttributesName - Retrieve the external attributes of an entry defined by its 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::setCompressionIndex - Set the compression method of an entry defined by its index
    • ZipArchive::setCompressionName - Set the compression method of an entry defined by its name
    • ZipArchive::setExternalAttributesIndex - Set the external attributes of an entry defined by its index
    • ZipArchive::setExternalAttributesName - Set the external attributes of an entry defined by its name
    • ZipArchive::setPassword - Set the password for the active archive
    • 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_decode - Uncompress any raw/gzip/zlib encoded data
    • zlib_encode - Compress data with the specified encoding
    • zlib_get_coding_type - Returns the coding type used for output compression
    • ZMQ::__construct - ZMQ constructor
    • ZMQContext::getOpt - Get context option
    • ZMQContext::getSocket - Create a new socket
    • ZMQContext::isPersistent - Whether the context is persistent
    • ZMQContext::setOpt - Set a socket option
    • ZMQContext::__construct - Construct a new ZMQContext object
    • ZMQDevice::getIdleTimeout - Get the idle timeout
    • ZMQDevice::getTimerTimeout - Get the timer timeout
    • ZMQDevice::run - Run the new device
    • ZMQDevice::setIdleCallback - Set the idle callback function
    • ZMQDevice::setIdleTimeout - Set the idle timeout
    • ZMQDevice::setTimerCallback - Set the timer callback function
    • ZMQDevice::setTimerTimeout - Set the timer timeout
    • ZMQDevice::__construct - Construct a new device
    • ZMQPoll::add - Add item to the poll set
    • ZMQPoll::clear - Clear the poll set
    • ZMQPoll::count - Count items in the poll set
    • ZMQPoll::getLastErrors - Get poll errors
    • ZMQPoll::poll - Poll the items
    • ZMQPoll::remove - Remove item from poll set
    • ZMQSocket::bind - Bind the socket
    • ZMQSocket::connect - Connect the socket
    • ZMQSocket::disconnect - Disconnect a socket
    • ZMQSocket::getEndpoints - Get list of endpoints
    • ZMQSocket::getPersistentId - Get the persistent id
    • ZMQSocket::getSocketType - Get the socket type
    • ZMQSocket::getSockOpt - Get socket option
    • ZMQSocket::isPersistent - Whether the socket is persistent
    • ZMQSocket::recv - Receives a message
    • ZMQSocket::recvMulti - Receives a multipart message
    • ZMQSocket::send - Sends a message
    • ZMQSocket::sendmulti - Sends a multipart message
    • ZMQSocket::setSockOpt - Set a socket option
    • ZMQSocket::unbind - Unbind the socket
    • ZMQSocket::__construct - Construct a new ZMQSocket
    • Zookeeper::addAuth - Specify application credentials.
    • Zookeeper::connect - Create a handle to used communicate with zookeeper.
    • Zookeeper::create - Create a node synchronously.
    • Zookeeper::delete - Delete a node in zookeeper synchronously.
    • Zookeeper::exists - Checks the existence of a node in zookeeper synchronously.
    • Zookeeper::get - Gets the data associated with a node synchronously.
    • Zookeeper::getAcl - Gets the acl associated with a node synchronously.
    • Zookeeper::getClientId - return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
    • Zookeeper::getRecvTimeout - Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect.
    • Zookeeper::getState - Get the state of the zookeeper connection.
    • Zookeeper::isRecoverable - Checks if the current zookeeper connection state can be recovered.
    • Zookeeper::set - Sets the data associated with a node.
    • Zookeeper::setAcl - Sets the acl associated with a node synchronously.
    • Zookeeper::setDebugLevel - Sets the debugging level for the library.
    • Zookeeper::setDeterministicConnOrder - Enable/disable quorum endpoint order randomization.
    • Zookeeper::setLogStream - Sets the stream to be used by the library for logging.
    • Zookeeper::setWatcher - Set a watcher function.
    • Zookeeper::__construct - Create a handle to used communicate with zookeeper.
  • _
    • __autoload - Attempt to load undefined class
    • __halt_compiler - Halts the compiler execution
Listingul-indice
Listingul exemplelor
Listingul-indice


Listingul exemplelor

Lista tuturor exemplelor din manual

  • Example#0 - Un exemplu introductiv
  • 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 - Partial lighttpd.conf
  • Example#25 - Spawning FastCGI Responders
  • Example#26 - Connecting to remote php-fastcgi instances
  • Example#27 -
  • Example#28 -
  • 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 - Recommended OpCache configuration
  • Example#35 - Recommended WinCache configuration
  • Example#36 - Command line to configure IIS and PHP
  • Example#37 - PHP 5 package structure
  • Example#38 - CGI and FastCGI settings in php.ini
  • Example#39 - Configuring FastCGI extension to handle PHP requests
  • Example#40 - Configuring file access permissions
  • Example#41 - Configuring FastCGI and PHP recycling
  • Example#42 - Configuring FastCGI timeout settings
  • Example#43 - Changing the location of php.ini file
  • Example#44 - CGI and FastCGI settings in php.ini
  • Example#45 - Creating IIS FastCGI process pool
  • Example#46 - Creating handler mapping for PHP requests
  • Example#47 - Determining the account used as IIS anonymous identity
  • Example#48 - Configuring file access permissions
  • Example#49 - Set index.php as a default document in IIS
  • Example#50 - Configuring FastCGI and PHP recycling
  • Example#51 - Configuring FastCGI timeout settings
  • Example#52 - Changing the location of php.ini file
  • Example#53 - PHP as an Apache 1.3.x module
  • Example#54 - PHP and Apache 1.3.x as CGI
  • Example#55 - PHP and Apache 2.x as handler
  • Example#56 -
  • Example#57 - PHP and Apache 2.x as CGI
  • Example#58 - Configure Apache to run PHP as FastCGI
  • Example#59 - ISAPI configuration of Sambar
  • Example#60 - Enable Bzip2 extension for PHP-Windows
  • Example#61 - Registry changes
  • Example#62 - Passing environment variables and PHP settings to a pool
  • Example#63 - set PHP settings in nginx.conf
  • Example#64 - phpinfo call
  • Example#65 - php.ini Environment Variables
  • Example#66 - php.ini example
  • Example#67 - Apache configuration example
  • Example#68 -
  • Example#69 - Evadare avansata folosind condi?ii
  • Example#70 - Tag-uri PHP de deschidere ?i închidere
  • Example#71 - Integer literals
  • Example#72 - Integer overflow on a 32-bit system
  • Example#73 - Integer overflow on a 64-bit system
  • Example#74 - Invalid example
  • Example#75 - Valid example
  • Example#76 - Heredoc string quoting example
  • Example#77 - Heredoc in arguments example
  • Example#78 - Using Heredoc to initialize static values
  • Example#79 - Using double quotes in Heredoc
  • Example#80 - Nowdoc string quoting example
  • Example#81 - Static data example
  • Example#82 - Simple syntax example
  • Example#83 - Negative numeric indices
  • Example#84 - Some string examples
  • Example#85 - Differences between PHP 5.3 and PHP 5.4
  • Example#86 - A simple array
  • Example#87 - Type Casting and Overwriting example
  • Example#88 - Mixed integer and string keys
  • Example#89 - Indexed arrays without key
  • Example#90 - Keys not on all elements
  • Example#91 - Accessing array elements
  • Example#92 - Array dereferencing
  • Example#93 - Using array()
  • Example#94 - Collection
  • Example#95 - Changing element in the loop
  • Example#96 - One-based index
  • Example#97 - Filling an array
  • Example#98 - Sorting an array
  • Example#99 - Recursive and multi-dimensional arrays
  • Example#100 - Callback function examples
  • Example#101 - Callback example using a Closure
  • Example#102 - Default values of uninitialized variables
  • Example#103 - Using global
  • Example#104 - Using $GLOBALS instead of global
  • Example#105 - Example demonstrating superglobals and scope
  • Example#106 - Example demonstrating need for static variables
  • Example#107 - Example use of static variables
  • Example#108 - Static variables with recursive functions
  • Example#109 - Declaring static variables
  • Example#110 - Variable property example
  • Example#111 - A simple HTML form
  • Example#112 - Accessing data from a simple POST HTML form
  • Example#113 - Old methods of accessing user input
  • Example#114 - More complex form variables
  • Example#115 - A setcookie example
  • Example#116 - Valid and invalid constant names
  • Example#117 - Defining Constants
  • Example#118 - Defining Constants using the const keyword
  • Example#119 - Associativity
  • Example#120 - Undefined order of evaluation
  • Example#121 - +, - and . have the same precedence
  • Example#122 - Assigning by reference
  • Example#123 - Bitwise AND, OR and XOR operations on integers
  • Example#124 - Bitwise XOR operations on strings
  • Example#125 - Bit shifting on integers
  • Example#126 - Boolean/null comparison
  • Example#127 - Transcription of standard array comparison
  • Example#128 - Assigning a default value
  • Example#129 - Non-obvious Ternary Behaviour
  • Example#130 - Assigning a default value
  • Example#131 - Nesting null coalescing operator
  • Example#132 - Arithmetic Operations on Character Variables
  • Example#133 - Logical operators illustrated
  • Example#134 - Comparing arrays
  • Example#135 - Using instanceof with classes
  • Example#136 - Using instanceof with inherited classes
  • Example#137 - Using instanceof to check if object is not an instanceof a class
  • Example#138 - Using instanceof for class
  • Example#139 - Using instanceof with other variables
  • Example#140 - Using instanceof to test other variables
  • Example#141 - Avoiding classname lookups and fatal errors with instanceof in PHP 5.0
  • Example#142 - switch structure
  • Example#143 - switch structure allows usage of strings
  • Example#144 - Tick usage example
  • Example#145 - Ticks usage example
  • Example#146 - Declaring an encoding for the script.
  • Example#147 - Basic include example
  • Example#148 - Including within functions
  • Example#149 - include through HTTP
  • Example#150 - Comparing return value of include
  • Example#151 - include and the return statement
  • Example#152 - Using output buffering to include a PHP file into a string
  • Example#153 - include_once with a case insensitive OS in PHP 4
  • Example#154 - goto example
  • Example#155 - goto loop example
  • Example#156 - This will not work
  • Example#157 - Pseudo code to demonstrate function uses
  • Example#158 - Conditional functions
  • Example#159 - Functions within functions
  • Example#160 - Recursive functions
  • Example#161 - Passing arrays to functions
  • Example#162 - Passing function parameters by reference
  • Example#163 - Use of default parameters in functions
  • Example#164 - Using non-scalar types as default values
  • Example#165 - Incorrect usage of default function arguments
  • Example#166 - Correct usage of default function arguments
  • Example#167 -
  • Example#168 - Basic class type declaration
  • Example#169 - Basic interface type declaration
  • Example#170 - Nullable type declaration
  • Example#171 - Strict typing
  • Example#172 - Weak typing
  • Example#173 - Catching TypeError
  • Example#174 - Using ... to access variable arguments
  • Example#175 - Using ... to provide arguments
  • Example#176 - Type hinted variable arguments
  • Example#177 - Accessing variable arguments in PHP 5.5 and earlier
  • Example#178 - Use of return
  • Example#179 - Returning an array to get multiple values
  • Example#180 - Returning a reference from a function
  • Example#181 - Basic return type declaration
  • Example#182 - Strict mode in action
  • Example#183 - Returning an object
  • Example#184 - Variable function example
  • Example#185 - Variable method example
  • Example#186 - Variable method example with static properties
  • Example#187 - Complex callables
  • Example#188 - Anonymous function example
  • Example#189 - Anonymous function variable assignment example
  • Example#190 - Inheriting variables from the parent scope
  • Example#191 - Closures and scoping
  • Example#192 - Automatic binding of $this
  • Example#193 - Attempting to use $this inside a static anonymous function
  • Example#194 - Attempting to bind an object to a static anonymous function
  • Example#195 - Simple Class definition
  • Example#196 - Some examples of the $this pseudo-variable
  • Example#197 - Creating an instance
  • Example#198 - Object Assignment
  • Example#199 - Creating new objects
  • Example#200 - Access member of newly created object
  • Example#201 - Property access vs. method call
  • Example#202 - Calling an anonymous function stored in a property
  • Example#203 - Simple Class Inheritance
  • Example#204 - Class name resolution
  • Example#205 - property declarations
  • Example#206 - Example of using a nowdoc to initialize a property
  • Example#207 - Defining and using a constant
  • Example#208 - Static data example
  • Example#209 - Namespaced ::class example
  • Example#210 - Constant expression example
  • Example#211 - Class constant visibility modifiers
  • Example#212 - Exemplu cu autoîncarcare
  • Example#213 - Un alt exemplu Autoload
  • Example#214 - Autoîncarcarea cu tratarea excep?iilor pentru 5.3.0+
  • Example#215 - Autoîncarcarea cu tratarea excep?iilor pentru 5.3.0+ - Fara excep?ie personalizata
  • Example#216 - utilizarea noilor constructori unifica?i
  • Example#217 - Constructori în clasele cu spa?ii de nume
  • Example#218 - Exemplu destructor
  • Example#219 - Declarare proprieta?ilor
  • Example#220 - Declara?ie metode
  • Example#221 - Accesarea membrelor private ale unui obiect de acela?i tip
  • Example#222 - Inheritance Example
  • Example#223 - :: from outside the class definition
  • Example#224 - :: from inside the class definition
  • Example#225 - Calling a parent's method
  • Example#226 - Static method example
  • Example#227 - Static property example
  • Example#228 - Exemplu de clasa abstracta
  • Example#229 - Exemplu cu clasa abstracta
  • Example#230 - Interface example
  • Example#231 - Extendable Interfaces
  • Example#232 - Multiple interface inheritance
  • Example#233 - Interfaces with constants
  • Example#234 - Trait example
  • Example#235 - Precedence Order Example
  • Example#236 - Alternate Precedence Order Example
  • Example#237 - Multiple Traits Usage
  • Example#238 - Conflict Resolution
  • Example#239 - Changing Method Visibility
  • Example#240 - Traits Composed from Traits
  • Example#241 - Express Requirements by Abstract Methods
  • Example#242 - Static Variables
  • Example#243 - Static Methods
  • Example#244 - Defining Properties
  • Example#245 - Conflict Resolution
  • Example#246 - Overloading properties via the __get(), __set(), __isset() and __unset() methods
  • Example#247 - Overloading methods via the __call() and __callStatic() methods
  • Example#248 - Simple Object Iteration
  • Example#249 - Object Iteration implementing Iterator
  • Example#250 - Object Iteration implementing IteratorAggregate
  • Example#251 - Sleep and wakeup
  • Example#252 - Simple example
  • Example#253 - Using __invoke()
  • Example#254 - Using __set_state() (since PHP 5.1.0)
  • Example#255 - Using __debugInfo()
  • Example#256 - Final methods example
  • Example#257 - Final class example
  • Example#258 - Cloning an object
  • Example#259 - Access member of freshly cloned object
  • Example#260 - Example of object comparison in PHP 5
  • Example#261 - self:: usage
  • Example#262 - static:: simple usage
  • Example#263 - static:: usage in a non-static context
  • Example#264 - Forwarding and non-forwarding calls
  • Example#265 - References and Objects
  • Example#266 - Namespace syntax example
  • Example#267 - Declaring a single namespace
  • Example#268 - Declaring a single namespace
  • Example#269 - Declaring a single namespace with hierarchy
  • Example#270 - Declaring multiple namespaces, simple combination syntax
  • Example#271 - Declaring multiple namespaces, bracketed syntax
  • Example#272 - Declaring multiple namespaces and unnamespaced code
  • Example#273 - Declaring multiple namespaces and unnamespaced code
  • Example#274 - Accessing global classes, functions and constants from within a namespace
  • Example#275 - Dynamically accessing elements
  • Example#276 - Dynamically accessing namespaced elements
  • Example#277 - __NAMESPACE__ example, namespaced code
  • Example#278 - __NAMESPACE__ example, global code
  • Example#279 - using __NAMESPACE__ for dynamic name construction
  • Example#280 - the namespace operator, inside a namespace
  • Example#281 - the namespace operator, in global code
  • Example#282 - importing/aliasing with the use operator
  • Example#283 - importing/aliasing with the use operator, multiple use statements combined
  • Example#284 - Importing and dynamic names
  • Example#285 - Importing and fully qualified names
  • Example#286 - Illegal importing rule
  • Example#287 - Using global space specification
  • Example#288 - Accessing global classes inside a namespace
  • Example#289 - global functions/constants fallback inside a namespace
  • Example#290 - Name resolutions illustrated
  • Example#291 - Accessing global classes outside a namespace
  • Example#292 - Accessing global classes outside a namespace
  • Example#293 - Accessing internal classes in namespaces
  • Example#294 - Accessing internal classes, functions or constants in namespaces
  • Example#295 - Fully Qualified names
  • Example#296 - Qualified names
  • Example#297 - Unqualified class names
  • Example#298 - Unqualified function or constant names
  • Example#299 - Dangers of using namespaced names inside a double-quoted string
  • Example#300 - Undefined constants
  • Example#301 - Undefined constants
  • Example#302 - The Built in Exception class
  • Example#303 - Extending the Exception class (PHP 5.3.0+)
  • Example#304 - Throwing an Exception
  • Example#305 - Exception handling with a finally block
  • Example#306 - Nested Exception
  • Example#307 - Implementing range as a generator
  • Example#308 - A simple example of yielding values
  • Example#309 - Yielding a key/value pair
  • Example#310 - Yielding NULLs
  • Example#311 - Yielding values by reference
  • Example#312 - yield from with iterator_to_array
  • Example#313 - Basic use of yield from
  • Example#314 - yield from and return values
  • Example#315 - Using references with undefined variables
  • Example#316 - Referencing global variables inside functions
  • Example#317 - References and foreach statement
  • Example#318 - $GLOBALS example
  • Example#319 - $_SERVER example
  • Example#320 - $_GET example
  • Example#321 - $_POST example
  • Example#322 - $_ENV example
  • Example#323 - $_COOKIE example
  • Example#324 - $php_errormsg example
  • Example#325 - $http_response_header example
  • Example#326 - $argc example
  • Example#327 - $argv example
  • Example#328 - Exception::getMessage example
  • Example#329 - Exception::getPrevious example
  • Example#330 - Exception::getCode example
  • Example#331 - Exception::getFile example
  • Example#332 - Exception::getLine example
  • Example#333 - Exception::getTrace example
  • Example#334 - Exception::getTraceAsString example
  • Example#335 - Exception::__toString example
  • Example#336 - Use set_error_handler to change error messages into ErrorException.
  • Example#337 - ErrorException::getSeverity example
  • Example#338 - Error::getMessage example
  • Example#339 - Error::getPrevious example
  • Example#340 - Error::getCode example
  • Example#341 - Error::getFile example
  • Example#342 - Error::getLine example
  • Example#343 - Error::getTrace example
  • Example#344 - Error::getTraceAsString example
  • Example#345 - Error::__toString example
  • Example#346 - Basic usage
  • Example#347 - Basic usage
  • Example#348 - Basic usage
  • Example#349 - ArrayAccess::offsetExists example
  • Example#350 - Basic usage
  • Example#351 - Closure::bind example
  • Example#352 - Closure::bindTo example
  • Example#353 - Closure::call example
  • Example#354 - Generator::getReturn example
  • Example#355 - Generator::key example
  • Example#356 - Using Generator::send to inject values
  • Example#357 - Throwing an exception into a generator
  • Example#358 - Basic bindto usage example
  • Example#359 - Fetch a page and send POST data
  • Example#360 - Ignore redirects but fetch headers and content
  • Example#361 - Fetch a page and send POST data
  • Example#362 - Detecting which URL we ended up on after redirects
  • Example#363 - php://temp/maxmemory
  • Example#364 - php://filter/resource=<stream to be filtered>
  • Example#365 - php://filter/read=<filter list to apply to read chain>
  • Example#366 - php://filter/write=<filter list to apply to write chain>
  • Example#367 - php://memory and php://temp are not reusable
  • Example#368 - Print data:// contents
  • Example#369 - Fetch the media type
  • Example#370 - Basic usage
  • Example#371 - Opening a stream from an active connection
  • Example#372 - This $session variable must be kept available!
  • Example#373 - Traversing a RAR archive
  • Example#374 - Opening an encrypted file (header encryption)
  • Example#375 - Poor variable checking leads to....
  • Example#376 - ... A filesystem attack
  • Example#377 - More secure file name checking
  • Example#378 - More secure file name checking
  • Example#379 - Script vulnerable to null bytes
  • Example#380 - Correctly validating the input
  • Example#381 - Transformarea parolei în hash
  • Example#382 - Transformarea parolei în hash utilizând crypt
  • Example#383 - Împar?irea rezultatelor în mai multe pagini ... ?i crearea de superuseri (PostgreSQL)
  • Example#384 - Listarea unor articole ... ?i a unor parole (orice server de baze de date)
  • Example#385 - De la resetarea unei parole ... pâna la ob?inerea mai multor privilegii (orice server de baze de date)
  • Example#386 - Atacarea sistemului de operare pe care lucreaza baza de date (MSSQL Server)
  • Example#387 - O metoda mai sigura de formare a interpelarii pentru paginare
  • Example#388 - Attacking Variables with a custom HTML page
  • Example#389 - Exploiting common debugging variables
  • Example#390 - Finding dangerous variables with E_ALL
  • Example#391 - Example misuse with register_globals = on
  • Example#392 - Example use of sessions with register_globals on or off
  • Example#393 - Detecting simple variable poisoning
  • Example#394 - Dangerous Variable Usage
  • Example#395 - Disabling magic quotes server side
  • Example#396 - Disabling magic quotes at runtime
  • Example#397 - Ascunderea PHP ca alt limbaj de scripting
  • Example#398 - Utilizarea tipurilor necunoscute în calitate de extensii PHP
  • Example#399 - Folosirea tipurilor HTML pentru extensiile PHP
  • Example#400 - Basic HTTP Authentication example
  • Example#401 - Digest HTTP Authentication example
  • Example#402 - HTTP Authentication example forcing a new name/password
  • Example#403 - A simple XForms search form
  • Example#404 - Using an XForm to populate $_POST
  • Example#405 - File Upload Form
  • Example#406 - Validating file uploads
  • Example#407 - Uploading array of files
  • Example#408 - Uploading multiple files
  • Example#409 - Saving HTTP PUT files
  • Example#410 - Getting the title of a remote page
  • Example#411 - Storing data on a remote server
  • Example#412 - Example showing the difference to the CGI SAPI:
  • Example#413 -
  • Example#414 - Printing built in (and loaded) PHP and Zend modules
  • Example#415 - Getting a syntax error when using double quotes
  • Example#416 - Using single quotes to prevent the shell's variable substitution
  • Example#417 - Using the -B, -R and -E options to count the number of lines of a project.
  • Example#418 - Using -v to get the SAPI name and the version of PHP and Zend
  • Example#419 - --ini example
  • Example#420 - basic --rf usage
  • Example#421 - --rc example
  • Example#422 - --re example
  • Example#423 - --ri example
  • Example#424 - Execute PHP script as shell script
  • Example#425 - Script intended to be run from command line (script.php)
  • Example#426 - Batch file to run a command line PHP script (script.bat)
  • Example#427 - Executing code using the interactive shell
  • Example#428 - Tab completion
  • Example#429 - Setting php.ini settings in the interactive shell
  • Example#430 - Starting the web server
  • Example#431 - Starting with a specific document root directory
  • Example#432 - Using a Router Script
  • Example#433 - Checking for CLI Web Server Use
  • Example#434 - Handling Unsupported File Types
  • Example#435 - Accessing the CLI Web Server From Remote Machines
  • Example#436 - Creating a new zval container
  • Example#437 - Displaying zval information
  • Example#438 - Increasing refcount of a zval
  • Example#439 - Decreasing zval refcount
  • Example#440 - Creating a array zval
  • Example#441 - Adding already existing element to an array
  • Example#442 - Removing an element from an array
  • Example#443 - Adding the array itself as an element of it self
  • Example#444 - Unsetting $a
  • Example#445 - Memory usage example
  • Example#446 - GC performance influences
  • Example#447 - Running the above script
  • Example#448 - Recompiling PHP to enable GC benchmarking
  • Example#449 - GC statistics
  • Example#450 - all_probes.d for tracing all PHP Static Probes with DTrace
  • Example#451 - all_probes.stp for tracing all PHP Static Probes with SystemTap
  • Example#452 - An apc.rfc1867 example
  • Example#453 - A apc_add example
  • Example#454 - apc_bin_load example
  • Example#455 - A apc_cache_info example
  • Example#456 - apc_cas example
  • Example#457 - apc_dec example
  • Example#458 - apc_define_constants example
  • Example#459 - apc_delete_file example
  • Example#460 - A apc_delete example
  • Example#461 - apc_exists example
  • Example#462 - A apc_fetch example
  • Example#463 - apc_inc example
  • Example#464 - apc_load_constants example
  • Example#465 - A apc_sma_info example
  • Example#466 - A apc_store example
  • Example#467 - A APCIterator::__construct example
  • Example#468 - An apc.rfc1867 example
  • Example#469 - A apcu_add example
  • Example#470 - A apcu_cache_info example
  • Example#471 - apcu_cas example
  • Example#472 - apcu_dec example
  • Example#473 - A apcu_delete example
  • Example#474 - An apcu_entry example
  • Example#475 - apcu_exists example
  • Example#476 - A apcu_fetch example
  • Example#477 - apcu_inc example
  • Example#478 - A apcu_sma_info example
  • Example#479 - A apcu_store example
  • Example#480 - A APCUIterator::__construct example
  • Example#481 - Typical session using tcplisten
  • Example#482 - apd_callstack example
  • Example#483 - apd_clunk example
  • Example#484 - apd_continue example
  • Example#485 - apd_croak example
  • Example#486 - apd_dump_function_table example
  • Example#487 - apd_dump_persistent_resources example
  • Example#488 - apd_dump_regular_resources example
  • Example#489 - apd_echo example
  • Example#490 - apd_get_active_symbols example
  • Example#491 - apd_set_pprof_trace example
  • Example#492 - apd_set_session_trace_socket example
  • Example#493 - apd_set_session_trace example
  • Example#494 - apd_set_session example
  • Example#495 - override_function example
  • Example#496 - rename_function example
  • Example#497 - bcompiler_load_exe example
  • Example#498 - bcompiler_load example
  • Example#499 - bcompiler_parse_class example
  • Example#500 - bcompiler_read example
  • Example#501 - bcompiler_write_class example
  • Example#502 - bcompiler_write_constant example
  • Example#503 - bcompiler_write_exe_footer example
  • Example#504 - bcompiler_write_file example
  • Example#505 - bcompiler_write_footer example
  • Example#506 - bcompiler_write_function example
  • Example#507 - bcompiler_write_functions_from_file example
  • Example#508 - bcompiler_write_header example
  • Example#509 - blenc_encrypt example
  • Example#510 - Using error handling in a script
  • Example#511 - debug_backtrace example
  • Example#512 - debug_print_backtrace example
  • Example#513 - An error_clear_last example
  • Example#514 - An error_get_last example
  • Example#515 - Exemple error_log
  • Example#516 - Exemple error_reporting
  • Example#517 - Exemplu restore_error_handler
  • Example#518 - restore_exception_handler example
  • Example#519 - Controlul erorilor cu set_error_handler ?i trigger_error
  • Example#520 - set_exception_handler example
  • Example#521 - Exemplu trigger_error
  • Example#522 - Getting the data within the PHP application itself (function)
  • Example#523 - Example use of gengraph.php
  • Example#524 - Listing data via inclued dumps (configuration)
  • Example#525 - inclued_get_data example
  • Example#526 - Creating large array in a function
  • Example#527 - Output Control example
  • Example#528 - Output rewrite example
  • Example#529 - ob_end_clean example
  • Example#530 - ob_end_flush example
  • Example#531 - A simple ob_get_clean example
  • Example#532 - A simple ob_get_contents example
  • Example#533 - ob_get_flush example
  • Example#534 - A simple ob_get_length example
  • Example#535 - ob_gzhandler example
  • Example#536 - ob_list_handlers example
  • Example#537 - User defined callback function example
  • Example#538 - Creating an uneraseable output buffer in a way compatible with both PHP 5.3 and 5.4
  • Example#539 - output_add_rewrite_var example
  • Example#540 - output_reset_rewrite_vars example
  • Example#541 - assert_options example
  • Example#542 - Handle a failed assertion with a custom handler
  • Example#543 - Using a custom handler to print a description
  • Example#544 - Expectations without a custom exception
  • Example#545 - Expectations with a custom exception
  • Example#546 - cli_get_process_title example
  • Example#547 - cli_set_process_title example
  • Example#548 - dl examples
  • Example#549 - extension_loaded example
  • Example#550 - A gc_enabled example
  • Example#551 - get_current_user example
  • Example#552 - get_defined_constants Example
  • Example#553 - Prints the XML functions
  • Example#554 - get_include_path example
  • Example#555 - get_included_files example
  • Example#556 - get_loaded_extensions Example
  • Example#557 - get_magic_quotes_gpc example
  • Example#558 - get_magic_quotes_runtime example
  • Example#559 - Unfiltered get_resources
  • Example#560 - Filtered get_resources
  • Example#561 - getenv Example
  • Example#562 - getlastmod example
  • Example#563 - getopt example: The basics
  • Example#564 - getopt example: Introducing long options
  • Example#565 - getopt example: Passing multiple options as one
  • Example#566 - getopt example: Using optind
  • Example#567 - getrusage example
  • Example#568 - ini_get_all examples
  • Example#569 - Disabling details
  • Example#570 - A few ini_get examples
  • Example#571 - ini_restore example
  • Example#572 - Setting an ini option
  • Example#573 - A memory_get_usage example
  • Example#574 - php_ini_loaded_file example
  • Example#575 - A simple example to list the returned ini files
  • Example#576 - php_logo_guid example
  • Example#577 - php_sapi_name example
  • Example#578 - Some php_uname examples
  • Example#579 - A few OS related constant examples
  • Example#580 - Prints the general credits
  • Example#581 - Prints the core developers and the documentation group
  • Example#582 - Printing all the credits
  • Example#583 - phpinfo Example
  • Example#584 - phpversion example
  • Example#585 - PHP_VERSION_ID example and usage
  • Example#586 - Setting an environment variable
  • Example#587 - restore_include_path example
  • Example#588 - set_include_path example
  • Example#589 - Adding to the include path
  • Example#590 - set_magic_quotes_runtime example
  • Example#591 - sys_get_temp_dir example
  • Example#592 - version_compare examples
  • Example#593 - zend_logo_guid example
  • Example#594 - zend_thread_id example
  • Example#595 - zend_version example
  • Example#596 - Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini
  • Example#597 - Instantiating a restricted sandbox
  • Example#598 - Working with variables in a sandbox
  • Example#599 - Calling sandbox functions
  • Example#600 - Passing arguments to sandbox functions
  • Example#601 - Working with variables in a sandbox
  • Example#602 - Accessing parental variables
  • Example#603 - A runkit_class_adopt example
  • Example#604 - A runkit_class_emancipate example
  • Example#605 - A runkit_function_add example
  • Example#606 - A runkit_function_copy example
  • Example#607 - A runkit_function_redefine example
  • Example#608 - runkit_import example
  • Example#609 - runkit_method_add example
  • Example#610 - runkit_method_copy example
  • Example#611 - runkit_method_redefine example
  • Example#612 - runkit_method_remove example
  • Example#613 - runkit_method_rename example
  • Example#614 - runkit_return_value_used example
  • Example#615 - Feeding output to a variable
  • Example#616 - Enabling and disabling scream at runtime
  • Example#617 - uopz_backup example
  • Example#618 - uopz_compose example
  • Example#619 - uopz_copy example
  • Example#620 - uopz_delete example
  • Example#621 - uopz_delete class example
  • Example#622 - uopz_extend example
  • Example#623 - uopz_flags example
  • Example#624 - uopz_function example
  • Example#625 - uopz_function class example
  • Example#626 - uopz_implement example
  • Example#627 - uopz_overload example
  • Example#628 - uopz_redefine example
  • Example#629 - uopz_rename example
  • Example#630 - uopz_rename class example
  • Example#631 - uopz_restore example
  • Example#632 - uopz_undefine example
  • Example#633 - Weakref usage example
  • Example#634 - WeakRef usage example
  • Example#635 - Weakref::acquire example
  • Example#636 - Nested acquire/release example
  • Example#637 - Weakref::__construct example
  • Example#638 - Weakref::release example
  • Example#639 - Weakmap usage example
  • Example#640 - wincache.ignorelist example
  • Example#641 - Authentication configuration for wincache.php
  • Example#642 - Enabling WinCache session handler
  • Example#643 - Enabling WinCache functions reroutes
  • Example#644 - Reroute.ini file content
  • Example#645 - A wincache_fcache_fileinfo example
  • Example#646 - A wincache_fcache_meminfo example
  • Example#647 - Using wincache_lock
  • Example#648 - A wincache_ocache_fileinfo example
  • Example#649 - A wincache_ocache_meminfo example
  • Example#650 - A wincache_refresh_if_changed example
  • Example#651 - A wincache_rplist_fileinfo example
  • Example#652 - A wincache_rplist_meminfo example
  • Example#653 - A wincache_scache_info example
  • Example#654 - A wincache_scache_meminfo example
  • Example#655 - wincache_ucache_add with key as a string
  • Example#656 - wincache_ucache_add with key as an array
  • Example#657 - Using wincache_ucache_cas
  • Example#658 - using wincache_ucache_clear
  • Example#659 - Using wincache_ucache_dec
  • Example#660 - Using wincache_ucache_delete with key as a string
  • Example#661 - Usingwincache_ucache_delete with key as an array
  • Example#662 - Using wincache_ucache_delete with key as an array where some elements cannot be deleted
  • Example#663 - Using wincache_ucache_exists
  • Example#664 - wincache_ucache_get with key as a string
  • Example#665 - wincache_ucache_get with key as an array
  • Example#666 - Using wincache_ucache_inc
  • Example#667 - Using wincache_ucache_info
  • Example#668 - A wincache_ucache_meminfo example
  • Example#669 - wincache_ucache_set with key as a string
  • Example#670 - wincache_ucache_set with key as an array
  • Example#671 - Using wincache_unlock
  • Example#672 - Xhprof example with the optional GUI
  • Example#673 - xhprof_disable example
  • Example#674 - xhprof_enable examples
  • Example#675 - xhprof_sample_disable example
  • Example#676 - id3_get_frame_long_name example
  • Example#677 - id3_get_frame_short_name example
  • Example#678 - id3_get_genre_id example
  • Example#679 - id3_get_genre_list example
  • Example#680 - id3_get_genre_name example
  • Example#681 - id3_get_tag example
  • Example#682 - id3_get_tag example
  • Example#683 - id3_get_version example
  • Example#684 - id3_remove_tag example
  • Example#685 - id3_set_tag example
  • Example#686 - Opens a new MP3 file and read the title
  • Example#687 - Reading an OGG/Vorbis file
  • Example#688 - Encode an audio file to OGG/Vorbis
  • Example#689 - KADM5 extension overview example
  • Example#690 - Example of changing principal's password
  • Example#691 - Example of principal's creation
  • Example#692 - kadm5_delete_principal example
  • Example#693 - kadm5_get_policies example
  • Example#694 - kadm5_get_principal example
  • Example#695 - kadm5_get_principals example
  • Example#696 - KADM5 initialization example
  • Example#697 - Example of modifying principal
  • Example#698 - Using CHAP passwords
  • Example#699 - radius_acct_open example
  • Example#700 - radius_add_server example
  • Example#701 - radius_auth_open example
  • Example#702 - radius_create_request example
  • Example#703 - radius_cvt_addr example
  • Example#704 - radius_cvt_int example
  • Example#705 - radius_cvt_string example
  • Example#706 - radius_get_attr example
  • Example#707 - radius_get_tagged_attr_data example
  • Example#708 - radius_get_tagged_attr_tag example
  • Example#709 - radius_get_vendor_attr example
  • Example#710 - radius_put_attr example
  • Example#711 - radius_put_int example
  • Example#712 - radius_put_string example
  • Example#713 - radius_put_vendor_attr example
  • Example#714 - Afi?area la ecran a unui ?ir de caractere cu o culoare specificata
  • Example#715 - Exemplu ncurses_getmouse
  • Example#716 - Afi?area la ecran a unui ?ir de caractere cu o culoare specificata
  • Example#717 - Afi?area la ecran a unui ?ir de caractere cu o culoare specificata
  • Example#718 - Exemplu ncurses_mousemask
  • Example#719 - Afi?area la ecran a unui ?ir de caractere cu o culoare specificata
  • Example#720 - Newt Usage Example
  • Example#721 - A newt_button example
  • Example#722 - A newt_draw_root_text example
  • Example#723 - A newt_form_add_component example
  • Example#724 - A newt_form_add_components example
  • Example#725 - A newt_form example
  • Example#726 - A newt_get_screen_size example
  • Example#727 - A newt_win_entries example
  • Example#728 - Readline Callback Interface Example
  • Example#729 - readline Example
  • Example#730 - Small bzip2 Example
  • Example#731 - Compressing data
  • Example#732 - Decompressing a String
  • Example#733 - bzerror example
  • Example#734 - bzopen example
  • Example#735 - bzread example
  • Example#736 - bzwrite example
  • Example#737 - Using an external file
  • Example#738 - Using a file within a phar archive
  • Example#739 - Converting a phar archive from phar to tar file format
  • Example#740 - phar.extract_list usage example
  • Example#741 - phar.cache_list usage example
  • Example#742 - A Phar::addEmptyDir example
  • Example#743 - A Phar::addFile example
  • Example#744 - A Phar::addFromString example
  • Example#745 - A Phar::apiVersion example
  • Example#746 - A Phar::buildFromDirectory example
  • Example#747 - A Phar::buildFromIterator with SplFileInfo
  • Example#748 - A Phar::buildFromIterator with other iterators
  • Example#749 - A Phar::canCompress example
  • Example#750 - A Phar::canWrite example
  • Example#751 - A Phar::compress example
  • Example#752 - A Phar::compressAllFilesBZIP2 example
  • Example#753 - A Phar::compressAllFilesGZ example
  • Example#754 - A Phar::compressFiles example
  • Example#755 - A Phar::__construct example
  • Example#756 - A Phar::convertToData example
  • Example#757 - A Phar::convertToExecutable example
  • Example#758 - A Phar::copy example
  • Example#759 - A Phar::count example
  • Example#760 - A Phar::createDefaultStub example
  • Example#761 - A Phar::decompress example
  • Example#762 - A Phar::decompressFiles example
  • Example#763 - A Phar::delMetaData example
  • Example#764 - A Phar::delete example
  • Example#765 - A Phar::extractTo example
  • Example#766 - A Phar::getMetadata example
  • Example#767 - A Phar::getStub example
  • Example#768 - A Phar::hasMetadata example
  • Example#769 - A Phar::interceptFileFuncs example
  • Example#770 - A Phar::interceptFileFuncs example
  • Example#771 - A Phar::isBuffering example
  • Example#772 - A Phar::isCompressed example
  • Example#773 - A Phar::loadPhar example
  • Example#774 - A Phar::mapPhar example
  • Example#775 - A Phar::mount example
  • Example#776 - A Phar::mungServer example
  • Example#777 - A Phar::offsetExists example
  • Example#778 - Phar::offsetGet example
  • Example#779 - A Phar::offsetSet example
  • Example#780 - A Phar::offsetUnset example
  • Example#781 - A Phar::running example
  • Example#782 - A Phar::setAlias example
  • Example#783 - A Phar::setDefaultStub example
  • Example#784 - A Phar::setMetadata example
  • Example#785 - A Phar::setStub example
  • Example#786 - A Phar::startBuffering example
  • Example#787 - A Phar::stopBuffering example
  • Example#788 - A Phar::uncompressAllFiles example
  • Example#789 - A Phar::unlinkArchive example
  • Example#790 - A Phar::webPhar example
  • Example#791 - A PharData::addEmptyDir example
  • Example#792 - A PharData::addFile example
  • Example#793 - A PharData::addFromString example
  • Example#794 - A PharData::buildFromDirectory example
  • Example#795 - A PharData::buildFromIterator with SplFileInfo
  • Example#796 - A PharData::buildFromIterator with other iterators
  • Example#797 - A PharData::compress example
  • Example#798 - A PharData::compressFiles example
  • Example#799 - A PharData::__construct example
  • Example#800 - A PharData::convertToData example
  • Example#801 - A PharData::convertToExecutable example
  • Example#802 - A PharData::copy example
  • Example#803 - A PharData::decompress example
  • Example#804 - A PharData::decompressFiles example
  • Example#805 - A PharData::delMetaData example
  • Example#806 - A PharData::delete example
  • Example#807 - A PharData::extractTo example
  • Example#808 - A PharData::offsetSet example
  • Example#809 - A PharData::offsetUnset example
  • Example#810 - A Phar::setMetadata example
  • Example#811 - A PharFileInfo::chmod example
  • Example#812 - A PharFileInfo::compress example
  • Example#813 - A PharFileInfo::__construct example
  • Example#814 - A PharFileInfo::decompress example
  • Example#815 - A PharFileInfo::delMetaData example
  • Example#816 - A PharFileInfo::getCRC32 example
  • Example#817 - A PharFileInfo::getCompressedSize example
  • Example#818 - A PharFileInfo::getMetadata example
  • Example#819 - A PharFileInfo::getPharFlags example
  • Example#820 - A PharFileInfo::isCRCChecked example
  • Example#821 - A PharFileInfo::isCompressed example
  • Example#822 - A PharFileInfo::isCompressedBZIP2 example
  • Example#823 - A PharFileInfo::isCompressedGZ example
  • Example#824 - A PharFileInfo::setCompressedBZIP2 example
  • Example#825 - A PharFileInfo::setCompressedGZ example
  • Example#826 - A PharFileInfo::setMetadata example
  • Example#827 - A PharFileInfo::setUncompressed example
  • Example#828 - Rar installation
  • Example#829 - On-the-fly decompression
  • Example#830 - RAR extension filesystem extraction example
  • Example#831 - Stil obiect-orientat
  • Example#832 - Stil procedural
  • Example#833 - Stil obiect-orientat
  • Example#834 - Stil procedural
  • Example#835 - Stil obiect-orientat
  • Example#836 - Stil procedural
  • Example#837 - Stil obiect-orientat
  • Example#838 - Stil procedural
  • Example#839 - Stil obiect-orientat
  • Example#840 - Stil procedural
  • Example#841 - Stil obiect-orientat
  • Example#842 - Stil procedural
  • Example#843 - Stil obiect-orientat
  • Example#844 - Stil procedural
  • Example#845 - Volume Callback
  • Example#846 - Stil obiect-orientat
  • Example#847 - Stil procedural
  • Example#848 - RarArchive::__toString example
  • Example#849 - RarEntry::extract example
  • Example#850 - How to extract all files in archive:
  • Example#851 - RarEntry::getAttr example
  • Example#852 - RarEntry::getHostOs example (version >= 2.0.0)
  • Example#853 - RarEntry::getHostOs example (version <= 1.0.0)
  • Example#854 - RarEntry::getMethod example
  • Example#855 - RarEntry::getName example
  • Example#856 - RarEntry::getPackedSize example
  • Example#857 - RarEntry::getStream example
  • Example#858 - RarEntry::getUnpackedSize example
  • Example#859 - RarEntry::getVersion example
  • Example#860 - RarException::isUsingExceptions example
  • Example#861 - RarException::setUsingExceptions example
  • Example#862 - Create a Zip archive
  • Example#863 - Dump the archive details and listing
  • Example#864 - Zip stream wrapper, read an OpenOffice meta info
  • Example#865 - Zip Usage Example
  • Example#866 - Create a new directory in an archive
  • Example#867 - Open and add
  • Example#868 - Add an entry to a new archive
  • Example#869 - Add file to a directory inside an archive
  • Example#870 - ZipArchive::addGlob example
  • Example#871 - ZipArchive::addPattern example
  • Example#872 - Delete file from archive using its index
  • Example#873 - Deleting a file and directory from an archive, using names
  • Example#874 - Extract all entries
  • Example#875 - Extract two entries
  • Example#876 - Dump an archive comment
  • Example#877 - Dump an entry comment
  • Example#878 - Dump an entry comment
  • Example#879 - Extract all entries with Unix rights
  • Example#880 - Get the file contents
  • Example#881 - Get the file contents
  • Example#882 - Convert an image from a zip entry
  • Example#883 - ZipArchive::getNameIndex example
  • Example#884 - Get the entry contents with fread and store it
  • Example#885 - Same as the previous example but with fopen and the zip stream wrapper
  • Example#886 - Stream wrapper and image, can be used with the xml function as well
  • Example#887 - Create an archive and then use it with ZipArchive::locateName
  • Example#888 - Open and extract
  • Example#889 - Create an archive
  • Example#890 - Rename one entry
  • Example#891 - Rename one entry
  • Example#892 - Create an archive and set a comment
  • Example#893 - Open an archive and set a comment for an entry
  • Example#894 - Open an archive and set a comment for an entry
  • Example#895 - Add files with different compression methods to an archive
  • Example#896 - Add files with different compression methods to an archive
  • Example#897 - Archive a file, with its Unix rights
  • Example#898 - Dump the stat info of an entry
  • Example#899 - Dump the stat info of an entry
  • Example#900 - Small Zlib Example
  • Example#901 - Working with the incremental compression and decompression API as of PHP 7.0.0
  • Example#902 - gzclose example
  • Example#903 - gzcompress example
  • Example#904 - gzdeflate example
  • Example#905 - Creating a gzip file
  • Example#906 - gzeof example
  • Example#907 - gzfile example
  • Example#908 - gzgetc example
  • Example#909 - gzgets example
  • Example#910 - gzgetss example
  • Example#911 - gzinflate example
  • Example#912 - gzopen Example
  • Example#913 - gzpassthru example
  • Example#914 - gzread example
  • Example#915 - gzseek example
  • Example#916 - gzuncompress example
  • Example#917 - gzwrite example
  • Example#918 - zlib_encode example
  • Example#919 - CrackLib example
  • Example#920 - random_bytes example
  • Example#921 - random_int example
  • Example#922 - hash_algos example
  • Example#923 - hash_copy example
  • Example#924 - example
  • Example#925 - Using hash_file
  • Example#926 - hash_final example
  • Example#927 - hash_hmac_file example
  • Example#928 - hash_hmac example
  • Example#929 - Incremental hashing example
  • Example#930 - hash_pbkdf2 example, basic usage
  • Example#931 - hash_update_stream example
  • Example#932 - A hash example
  • Example#933 - Calculate pre PHP-5.4 tiger hashes with PHP-5.4 and higher
  • Example#934 - Encrypt an input value with AES with a 256-bit key under 2.4.x and higher in CBC mode
  • Example#935 - mcrypt_create_iv Example
  • Example#936 - mcrypt_enc_get_algorithms_name example
  • Example#937 - mcrypt_enc_get_modes_name example
  • Example#938 - mcrypt_enc_get_supported_key_sizes example
  • Example#939 - mcrypt_encrypt Example
  • Example#940 - mcrypt_get_block_size example
  • Example#941 - mcrypt_get_cipher_name Example
  • Example#942 - mcrypt_get_iv_size Example
  • Example#943 - mcrypt_get_key_size Example
  • Example#944 - mcrypt_list_algorithms Example
  • Example#945 - mcrypt_list_modes Example
  • Example#946 - mcrypt_module_open Examples
  • Example#947 - Using mcrypt_module_open in encryption
  • Example#948 - mcrypt_module_self_test example
  • Example#949 - mdecrypt_generic Example
  • Example#950 - Computes the MD5 digest and hmac and print it out as hex
  • Example#951 - Traversing all hashes
  • Example#952 - mhash_get_block_size Example
  • Example#953 - mhash_get_hash_name Example
  • Example#954 - openssl_cipher_iv_length example
  • Example#955 - Creating a self-signed-certificate
  • Example#956 - openssl_csr_sign example - signing a CSR (how to implement your own CA)
  • Example#957 - openssl_error_string example
  • Example#958 - openssl_get_cert_locations example
  • Example#959 - openssl_get_cipher_methods example
  • Example#960 - openssl_get_md_methods example
  • Example#961 - openssl_open example
  • Example#962 - openssl_pkcs12_read example
  • Example#963 - openssl_pkcs7_decrypt example
  • Example#964 - openssl_pkcs7_encrypt example
  • Example#965 - openssl_pkcs7_sign example
  • Example#966 - openssl_random_pseudo_bytes example
  • Example#967 - openssl_seal example
  • Example#968 - openssl_sign example
  • Example#969 - openssl_sign example
  • Example#970 - openssl_spki_export_challenge example
  • Example#971 - openssl_spki_export_challenge example from <keygen>
  • Example#972 - openssl_spki_export example
  • Example#973 - openssl_spki_export example from <keygen>
  • Example#974 - openssl_spki_new example
  • Example#975 - openssl_spki_verify example
  • Example#976 - openssl_spki_verify example from <keygen>
  • Example#977 - openssl_verify example
  • Example#978 - openssl_verify example
  • Example#979 - password_hash example
  • Example#980 - password_hash example setting cost manually
  • Example#981 - password_hash example setting salt manually
  • Example#982 - password_hash example finding a good cost
  • Example#983 - Usage of password_needs_rehash
  • Example#984 - password_verify example
  • Example#985 - DBA example
  • Example#986 - Traversing a database
  • Example#987 - dba_handlers Example
  • Example#988 - dbx_close example
  • Example#989 - dbx_compare example
  • Example#990 - dbx_connect example
  • Example#991 - dbx_error example
  • Example#992 - dbx_escape_string example
  • Example#993 - How to handle the returned value
  • Example#994 - lists each field's name and type
  • Example#995 - outputs the content of data property into HTML table
  • Example#996 - How to handle UNBUFFERED queries
  • Example#997 - How to handle the returned value
  • Example#998 - dbx_sort example
  • Example#999 - DSN-less connections
  • Example#1000 - odbc_execute and odbc_prepare example
  • Example#1001 - odbc_fetch_into examples
  • Example#1002 - odbc_next_result
  • Example#1003 - odbc_execute and odbc_prepare example
  • Example#1004 - odbc_result examples
  • Example#1005 - odbc_setoption examples
  • Example#1006 - using PDO::ATTR_DRIVER_NAME
  • Example#1007 - Connecting to MySQL
  • Example#1008 - Handling connection errors
  • Example#1009 - Closing a connection
  • Example#1010 - Persistent connections
  • Example#1011 - Executing a batch in a transaction
  • Example#1012 - Repeated inserts using prepared statements
  • Example#1013 - Repeated inserts using prepared statements
  • Example#1014 - Fetching data using prepared statements
  • Example#1015 - Calling a stored procedure with an output parameter
  • Example#1016 - Calling a stored procedure with an input/output parameter
  • Example#1017 - Invalid use of placeholder
  • Example#1018 - Create a PDO instance and set the error mode
  • Example#1019 - Create a PDO instance and set the error mode from the constructor
  • Example#1020 - Displaying an image from a database
  • Example#1021 - Inserting an image into a database
  • Example#1022 - Inserting an image into a database: Oracle
  • Example#1023 - Roll back a transaction
  • Example#1024 - Committing a basic transaction
  • Example#1025 - Committing a DDL transaction
  • Example#1026 - Create a PDO instance via driver invocation
  • Example#1027 - Create a PDO instance via URI invocation
  • Example#1028 - Create a PDO instance using an alias
  • Example#1029 - Retrieving an SQLSTATE code
  • Example#1030 - Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
  • Example#1031 - Issuing a DELETE statement
  • Example#1032 - Retrieving database connection attributes
  • Example#1033 - A PDO::getAvailableDrivers example
  • Example#1034 - Prepare an SQL statement with named parameters
  • Example#1035 - Prepare an SQL statement with question mark parameters
  • Example#1036 - Demonstrate PDO::query
  • Example#1037 - Quoting a normal string
  • Example#1038 - Quoting a dangerous string
  • Example#1039 - Quoting a complex string
  • Example#1040 - Roll back a transaction
  • Example#1041 - Binding result set output to PHP variables
  • Example#1042 - Execute a prepared statement with named placeholders
  • Example#1043 - Execute a prepared statement with question mark placeholders
  • Example#1044 - Call a stored procedure with an INOUT parameter
  • Example#1045 - Execute a prepared statement with named placeholders
  • Example#1046 - Execute a prepared statement with question mark placeholders
  • Example#1047 - A PDOStatement::closeCursor example
  • Example#1048 - Counting columns
  • Example#1049 - PDOStatement::debugDumpParams example with named parameters
  • Example#1050 - PDOStatement::debugDumpParams example with unnamed parameters
  • Example#1051 - Retrieving an SQLSTATE code
  • Example#1052 - Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
  • Example#1053 - Execute a prepared statement with a bound variable and value
  • Example#1054 - Execute a prepared statement with an array of insert values (named parameters)
  • Example#1055 - Execute a prepared statement with an array of insert values (placeholders)
  • Example#1056 - Execute a prepared statement with question mark placeholders
  • Example#1057 - Execute a prepared statement using array for IN clause
  • Example#1058 - Fetching rows using different fetch styles
  • Example#1059 - Fetching rows with a scrollable cursor
  • Example#1060 - Construction order
  • Example#1061 - Fetch all remaining rows in a result set
  • Example#1062 - Fetching all values of a single column from a result set
  • Example#1063 - Grouping all values by a single column
  • Example#1064 - Instantiating a class for each result
  • Example#1065 - Calling a function for each result
  • Example#1066 - Return first column of the next row
  • Example#1067 - Retrieving column metadata
  • Example#1068 - Fetching multiple rowsets returned from a stored procedure
  • Example#1069 - Return the number of deleted rows
  • Example#1070 - Counting rows returned by a SELECT statement
  • Example#1071 - Setting the fetch mode
  • Example#1072 - Insert LOBs in CUBRID PDO
  • Example#1073 - Fetch LOBs in CUBRID PDO
  • Example#1074 - Insert set in CUBRID PDO with default data type.
  • Example#1075 - Specify data type when insert set in CUBRID PDO
  • Example#1076 - PDO_CUBRID DSN examples
  • Example#1077 - A PDO::cubrid_schema example
  • Example#1078 - PDO_DBLIB DSN examples
  • Example#1079 - PDO_FIREBIRD DSN example with path
  • Example#1080 - PDO_FIREBIRD DSN example with port and path
  • Example#1081 - PDO_FIREBIRD DSN example with localhost and path to employee.fdb on Debian system
  • Example#1082 - PDO_IBM DSN example using db2cli.ini
  • Example#1083 - PDO_IBM DSN example using a connection string
  • Example#1084 - PDO_INFORMIX DSN example using odbc.ini
  • Example#1085 - PDO_INFORMIX DSN example using a connection string
  • Example#1086 - Forcing queries to be buffered in mysql
  • Example#1087 - Setting the connection character set to UTF-8 prior to PHP 5.3.6
  • Example#1088 - PDO_MYSQL DSN examples
  • Example#1089 - PDO_SQLSRV DSN examples
  • Example#1090 - PDO_OCI DSN examples
  • Example#1091 - PDO_ODBC DSN example (ODBC driver manager)
  • Example#1092 - PDO_ODBC DSN example (IBM DB2 uncataloged connection)
  • Example#1093 - PDO_ODBC DSN example (Microsoft Access uncataloged connection)
  • Example#1094 - PDO_PGSQL DSN examples
  • Example#1095 - A PDO::pgsqlLOBCreate example
  • Example#1096 - A PDO::pgsqlLOBOpen example
  • Example#1097 - A PDO::pgsqlLOBUnlink example
  • Example#1098 - PDO_SQLITE DSN examples
  • Example#1099 - max_length aggregation function example
  • Example#1100 - PDO::sqliteCreateCollation example
  • Example#1101 - PDO::sqliteCreateFunction example
  • Example#1102 - DSN examples for PDO_4D
  • Example#1103 - Basic example with PDO_4D
  • Example#1104 - Accessing 4D language from pdo_4d
  • Example#1105 - Escaping 4D table names
  • Example#1106 - Example of Data Retrieval
  • Example#1107 - Example of Data Insertion
  • Example#1108 - cubrid_bind example
  • Example#1109 - cubrid_bind BLOB/CLOB example
  • Example#1110 - cubrid_bind BLOB/CLOB example
  • Example#1111 - cubrid_close_prepare example
  • Example#1112 - cubrid_close_request example
  • Example#1113 - cubrid_col_get example
  • Example#1114 - cubrid_col_size example
  • Example#1115 - cubrid_column_names example
  • Example#1116 - cubrid_column_types example
  • Example#1117 - cubrid_commit example
  • Example#1118 - cubrid_connect_with_url url without properties example
  • Example#1119 - cubrid_connect_with_url url with properties example
  • Example#1120 - cubrid_connect example
  • Example#1121 - cubrid_current_oid example
  • Example#1122 - cubrid_disconnect example
  • Example#1123 - cubrid_drop example
  • Example#1124 - cubrid_error_code_facility example
  • Example#1125 - cubrid_error_code example
  • Example#1126 - cubrid_error_msg example
  • Example#1127 - cubrid_execute example
  • Example#1128 - cubrid_fetch example
  • Example#1129 - cubrid_free_result example
  • Example#1130 - cubrid_get_charset example
  • Example#1131 - cubrid_get_class_name example
  • Example#1132 - cubrid_get_client_info example
  • Example#1133 - cubrid_get_db_parameter example
  • Example#1134 - cubrid_get_query_timeout example
  • Example#1135 - cubrid_get_server_info example
  • Example#1136 - cubrid_get example
  • Example#1137 - cubrid_insert_id example
  • Example#1138 - cubrid_is_instance example
  • Example#1139 - cubrid_lob_close example
  • Example#1140 - cubrid_lob_export example
  • Example#1141 - cubrid_lob_get example
  • Example#1142 - cubrid_lob_send example
  • Example#1143 - cubrid_lob_size example
  • Example#1144 - cubrid_lob2_bind example
  • Example#1145 - cubrid_lob2_export example
  • Example#1146 - cubrid_lob2_export example
  • Example#1147 - cubrid_lob2_read example 1
  • Example#1148 - cubrid_lob2_read example 2
  • Example#1149 - cubrid_lob2_seek64 example
  • Example#1150 - cubrid_lob2_seek example
  • Example#1151 - cubrid_lob2_write example 1
  • Example#1152 - cubrid_lob2_write example 2
  • Example#1153 - cubrid_lock_read example
  • Example#1154 - cubrid_lock_write example
  • Example#1155 - cubrid_move_cursor example
  • Example#1156 - cubrid_next_result example
  • Example#1157 - cubrid_num_cols example
  • Example#1158 - cubrid_num_rows example
  • Example#1159 - cubrid_pconnect_with_url url without properties example
  • Example#1160 - cubrid_pconnect_with_url url with properties example
  • Example#1161 - cubrid_connect example
  • Example#1162 - cubrid_prepare example
  • Example#1163 - cubrid_put example
  • Example#1164 - cubrid_rollback example
  • Example#1165 - cubrid_schema example
  • Example#1166 - cubrid_seq_drop example
  • Example#1167 - cubrid_seq_insert example
  • Example#1168 - cubrid_seq_put example
  • Example#1169 - cubrid_set_add example
  • Example#1170 - cubrid_get_db_parameter example
  • Example#1171 - cubrid_set_drop example
  • Example#1172 - cubrid_version example
  • Example#1173 - cubrid_affected_rows example
  • Example#1174 - cubrid_client_encoding example
  • Example#1175 - cubrid_close example
  • Example#1176 - cubrid_data_seek example
  • Example#1177 - cubrid_db_name example
  • Example#1178 - cubrid_errno example
  • Example#1179 - cubrid_error example
  • Example#1180 - cubrid_fetch_array example
  • Example#1181 - cubrid_fetch_assoc example
  • Example#1182 - cubrid_fetch_field example
  • Example#1183 - cubrid_fetch_lengths example
  • Example#1184 - cubrid_fetch_object example
  • Example#1185 - cubrid_fetch_row example
  • Example#1186 - cubrid_field_flags example
  • Example#1187 - cubrid_field_len example
  • Example#1188 - cubrid_field_name example
  • Example#1189 - cubrid_field_seek example
  • Example#1190 - cubrid_field_table example
  • Example#1191 - cubrid_field_type example
  • Example#1192 - cubrid_list_dbs example
  • Example#1193 - cubrid_num_fields example
  • Example#1194 - cubrid_ping example
  • Example#1195 - Invalid Query
  • Example#1196 - Valid Query
  • Example#1197 - cubrid_real_escape_string example
  • Example#1198 - cubrid_result example
  • Example#1199 - cubrid_unbuffered_query example
  • Example#1200 - cubrid_load_from_glo example
  • Example#1201 - cubrid_new_glo example
  • Example#1202 - cubrid_save_to_glo example
  • Example#1203 - cubrid_send_glo example
  • Example#1204 - Inserting a record in a dBase database
  • Example#1205 - Closing a dBase database file
  • Example#1206 - Creating a dBase database file
  • Example#1207 - Showing header information for a dBase database file
  • Example#1208 - Listing all the registered members in the database
  • Example#1209 - dbase_numfields Example
  • Example#1210 - Looping over all the records of the database
  • Example#1211 - Opening a dBase database file
  • Example#1212 - Emptying a dBase database
  • Example#1213 - Updating a record in the database
  • Example#1214 - ibase_blob_get example
  • Example#1215 - ibase_blob_import example
  • Example#1216 - ibase_connect example
  • Example#1217 - ibase_execute example
  • Example#1218 - ibase_fetch_object example
  • Example#1219 - ibase_field_info example
  • Example#1220 - ibase_name_result example
  • Example#1221 - ibase_num_fields example
  • Example#1222 - ibase_query example
  • Example#1223 - ibase_set_event_handler example
  • Example#1224 - fbsql_close example
  • Example#1225 - fbsql_connect example
  • Example#1226 - fbsql_create_blob example
  • Example#1227 - fbsql_create_clob example
  • Example#1228 - fbsql_create_db example
  • Example#1229 - fbsql_data_seek example
  • Example#1230 - fbsql_create_clob example
  • Example#1231 - fbsql_errno Example
  • Example#1232 - fbsql_error Example
  • Example#1233 - fbsql_fetch_array example
  • Example#1234 - fbsql_fetch_assoc example
  • Example#1235 - fbsql_fetch_field example
  • Example#1236 - fbsql_fetch_object example
  • Example#1237 - fbsql_field_name example
  • Example#1238 - fbsql_field_type example
  • Example#1239 - fbsql_list_dbs example
  • Example#1240 - fbsql_list_fields example
  • Example#1241 - fbsql_next_result example
  • Example#1242 - fbsql_num_rows example
  • Example#1243 - fbsql_query example
  • Example#1244 - fbsql_query example
  • Example#1245 - fbsql_read_blob example
  • Example#1246 - fbsql_read_clob example
  • Example#1247 - fbsql_table_name example
  • Example#1248 - Retrieving the AUTOCOMMIT value for a connection
  • Example#1249 - Setting the AUTOCOMMIT value for a connection
  • Example#1250 - Binding PHP variables to a prepared statement
  • Example#1251 - Calling stored procedures with IN and OUT parameters
  • Example#1252 - Inserting a binary large object (BLOB) directly from a file
  • Example#1253 - A db2_client_info example
  • Example#1254 - Closing a connection
  • Example#1255 - Retrieving an SQLSTATE value for a failed connection attempt
  • Example#1256 - Retrieving the error message returned by a failed connection attempt
  • Example#1257 - Creating a cataloged connection
  • Example#1258 - Creating an uncataloged connection
  • Example#1259 - Creating a connection with autocommit off by default
  • Example#1260 - i5/OS best performance
  • Example#1261 - Using trusted context
  • Example#1262 - A db2_escape_string example
  • Example#1263 - Creating a table with db2_exec
  • Example#1264 - Executing a SELECT statement with a scrollable cursor
  • Example#1265 - Returning XML data as an SQL ResultSet
  • Example#1266 - Performing a "JOIN" with XML data
  • Example#1267 - Returning SQL data as part of a larger XML document
  • Example#1268 - Preparing and executing an SQL statement with parameter markers
  • Example#1269 - Calling a stored procedure with an OUT parameter
  • Example#1270 - Returning XML data as an SQL ResultSet
  • Example#1271 - Performing a "JOIN" with XML data
  • Example#1272 - Returning SQL data as part of a larger XML document
  • Example#1273 - Iterating through a forward-only cursor
  • Example#1274 - Retrieving specific rows with db2_fetch_array from a scrollable cursor
  • Example#1275 - Iterating through a forward-only cursor
  • Example#1276 - Retrieving specific rows with db2_fetch_assoc from a scrollable cursor
  • Example#1277 - Iterating through a forward-only cursor
  • Example#1278 - Retrieving specific rows with db2_fetch_both from a scrollable cursor
  • Example#1279 - A db2_fetch_object example
  • Example#1280 - Iterating through a result set
  • Example#1281 - i5/OS recommended alternatives to db2_fetch_row/db2_result
  • Example#1282 - Setting and retrieving parameters through a connection resource
  • Example#1283 - A db2_last_insert_id example
  • Example#1284 - Iterating through different types of data
  • Example#1285 - Calling a stored procedure that returns multiple result sets
  • Example#1286 - Retrieving the number of fields in a result set
  • Example#1287 - Closing a persistent connection
  • Example#1288 - A db2_pconnect example
  • Example#1289 - Using trusted context
  • Example#1290 - Preparing and executing an SQL statement with parameter markers
  • Example#1291 - A db2_result example
  • Example#1292 - Rolling back a DELETE statement
  • Example#1293 - A db2_server_info example
  • Example#1294 - Setting one parameter with a connection resource
  • Example#1295 - Setting multiple parameters with a connection resource
  • Example#1296 - Setting multiple parameters with an invalid key
  • Example#1297 - Setting multiple parameters with an invalid value
  • Example#1298 - Setting multiple parameters with a connection resource and the wrong type
  • Example#1299 - Setting multiple parameters with the wrong resource
  • Example#1300 - Putting it all together
  • Example#1301 - i5/OS cursors are read-only
  • Example#1302 - Informix affected rows
  • Example#1303 - Closing a Informix connection
  • Example#1304 - Connect to a Informix database
  • Example#1305 - ifx_do Example
  • Example#1306 - ifx_errormsg example
  • Example#1307 - Informix fetch rows
  • Example#1308 - Informix SQL fieldproperties
  • Example#1309 - Fieldnames and SQL fieldtypes
  • Example#1310 - Retrieve Informix sqlca.sqlerrd[x] values
  • Example#1311 - Informix results as HTML table
  • Example#1312 - ifx_num_fields Example
  • Example#1313 - Show all rows of the "orders" table as a HTML table
  • Example#1314 - Insert some values into the "catalog" table
  • Example#1315 - Example usage of PassEnv for Ingres
  • Example#1316 - Simple Ingres Example
  • Example#1317 - ingres_charset - Get the installation character set
  • Example#1318 - Open a connection to an Ingres database
  • Example#1319 - Get cursor name for a query resource
  • Example#1320 - Get the last Ingres error number generated
  • Example#1321 - Get a message for the last error generated
  • Example#1322 - Get the last SQLSTATE error code generated
  • Example#1323 - Escape special characters for use in a query
  • Example#1324 - Fetch a row of result into an array
  • Example#1325 - Fetch a row into an associative array
  • Example#1326 - Fetch a row into an object
  • Example#1327 - Get the return value from a procedure call
  • Example#1328 - Fetch a row of result into an enumerated array
  • Example#1329 - Free a result resource
  • Example#1330 - Send a simple select
  • Example#1331 - Passing query parameters to ingres_query
  • Example#1332 - Inserting a BLOB with parameter types
  • Example#1333 - Position the cursor on the 3rd row
  • Example#1334 - Set date_format to ISO4
  • Example#1335 - Set timezone to HONG-KONG
  • Example#1336 - Issue a simple un-buffered select
  • Example#1337 - Passing query parameters to ingres_unbuffered_query
  • Example#1338 - Inserting a BLOB with parameter types
  • Example#1339 - MaxDB extension overview example
  • Example#1340 - Example for use of SELECT INTO statements
  • Example#1341 - Example fore using database procedures
  • Example#1342 - Stil obiect-orientat
  • Example#1343 - Stil procedural
  • Example#1344 - Stil obiect-orientat
  • Example#1345 - Stil procedural
  • Example#1346 - Stil obiect-orientat
  • Example#1347 - Stil procedural
  • Example#1348 - Stil obiect-orientat
  • Example#1349 - Stil procedural
  • Example#1350 - Stil obiect-orientat
  • Example#1351 - Stil procedural
  • Example#1352 - maxdb_connect_errno sample
  • Example#1353 - maxdb_connect_error sample
  • Example#1354 - Stil obiect-orientat
  • Example#1355 - Stil procedural
  • Example#1356 - Stil obiect-orientat
  • Example#1357 - Stil procedural
  • Example#1358 - Stil procedural
  • Example#1359 - Stil obiect-orientat
  • Example#1360 - Stil procedural
  • Example#1361 - Stil obiect-orientat
  • Example#1362 - Stil procedural
  • Example#1363 - Stil obiect-orientat
  • Example#1364 - Stil procedural
  • Example#1365 - Stil obiect-orientat
  • Example#1366 - Stil procedural
  • Example#1367 - Stil obiect-orientat
  • Example#1368 - Stil procedural
  • Example#1369 - Stil obiect-orientat
  • Example#1370 - Stil procedural
  • Example#1371 - Stil obiect-orientat
  • Example#1372 - Stil procedural
  • Example#1373 - Stil obiect-orientat
  • Example#1374 - Stil procedural
  • Example#1375 - Stil obiect-orientat
  • Example#1376 - Stil procedural
  • Example#1377 - Stil obiect-orientat
  • Example#1378 - Stil procedural
  • Example#1379 - Stil obiect-orientat
  • Example#1380 - Stil procedural
  • Example#1381 - Stil obiect-orientat
  • Example#1382 - Stil procedural
  • Example#1383 - Stil obiect-orientat
  • Example#1384 - Stil procedural
  • Example#1385 - maxdb_get_client_info
  • Example#1386 - maxdb_get_client_version
  • Example#1387 - Stil obiect-orientat
  • Example#1388 - Stil procedural
  • Example#1389 - Stil obiect-orientat
  • Example#1390 - Stil procedural
  • Example#1391 - Stil obiect-orientat
  • Example#1392 - Stil procedural
  • Example#1393 - Stil obiect-orientat
  • Example#1394 - Stil procedural
  • Example#1395 - Stil obiect-orientat
  • Example#1396 - Stil procedural
  • Example#1397 - Stil obiect-orientat
  • Example#1398 - Stil procedural
  • Example#1399 - Stil obiect-orientat
  • Example#1400 - Stil procedural
  • Example#1401 - Stil obiect-orientat
  • Example#1402 - Stil procedural
  • Example#1403 - Stil obiect-orientat
  • Example#1404 - Stil procedural
  • Example#1405 - Stil obiect-orientat
  • Example#1406 - Stil procedural
  • Example#1407 - Stil obiect-orientat
  • Example#1408 - Stil procedural
  • Example#1409 - Stil obiect-orientat
  • Example#1410 - Stil procedural
  • Example#1411 - Stil obiect-orientat
  • Example#1412 - Stil procedural
  • Example#1413 - Stil obiect-orientat
  • Example#1414 - Stil procedural
  • Example#1415 - Stil obiect-orientat
  • Example#1416 - Stil procedural
  • Example#1417 - Stil procedural
  • Example#1418 - Stil obiect-orientat
  • Example#1419 - Stil procedural
  • Example#1420 - Stil obiect-orientat
  • Example#1421 - Stil procedural
  • Example#1422 - Stil obiect-orientat
  • Example#1423 - Stil procedural
  • Example#1424 - Stil obiect-orientat
  • Example#1425 - Stil procedural
  • Example#1426 - Stil obiect-orientat
  • Example#1427 - Stil procedural
  • Example#1428 - Stil obiect-orientat
  • Example#1429 - Stil procedural
  • Example#1430 - Stil procedural (SELECT INTO)
  • Example#1431 - Stil procedural (DB procedure)
  • Example#1432 - Stil obiect-orientat (extended syntax)
  • Example#1433 - Stil obiect-orientat
  • Example#1434 - Stil procedural
  • Example#1435 - Stil obiect-orientat
  • Example#1436 - Stil procedural
  • Example#1437 - Stil obiect-orientat
  • Example#1438 - Stil procedural
  • Example#1439 - Stil obiect-orientat
  • Example#1440 - Stil procedural
  • Example#1441 - Stil obiect-orientat
  • Example#1442 - Stil procedural
  • Example#1443 - Stil obiect-orientat
  • Example#1444 - Stil procedural
  • Example#1445 - Stil obiect-orientat
  • Example#1446 - Stil procedural
  • Example#1447 - Stil obiect-orientat
  • Example#1448 - Stil procedural
  • Example#1449 - Stil obiect-orientat
  • Example#1450 - Stil procedural
  • Example#1451 - Stil obiect-orientat
  • Example#1452 - Stil procedural
  • Example#1453 - Stil obiect-orientat
  • Example#1454 - Stil procedural
  • Example#1455 - Stil obiect-orientat
  • Example#1456 - Stil procedural
  • Example#1457 - Stil obiect-orientat
  • Example#1458 - Stil procedural
  • Example#1459 - Stil obiect-orientat
  • Example#1460 - Stil procedural
  • Example#1461 - Stil obiect-orientat
  • Example#1462 - Stil procedural
  • Example#1463 -
  • Example#1464 -
  • Example#1465 -
  • Example#1466 -
  • Example#1467 -
  • Example#1468 -
  • Example#1469 -
  • Example#1470 -
  • Example#1471 -
  • Example#1472 -
  • Example#1473 -
  • Example#1474 -
  • Example#1475 -
  • Example#1476 -
  • Example#1477 -
  • Example#1478 - Connection URI read preferences with query string syntax
  • Example#1479 - Setting read preferences with array syntax for tag sets
  • Example#1480 - Passing a WriteConcern to a write operation
  • Example#1481 - Connection string WriteConcerns
  • Example#1482 - MongoDB::setWriteConcern and MongoCollection::setWriteConcern
  • Example#1483 - Unacknowledged WriteConcern, followed with Acknowledged Write
  • Example#1484 - Acknowledged Writes
  • Example#1485 - Majority Acknowledged Write
  • Example#1486 - Acknowledged and Journaled Write
  • Example#1487 - Connect to MongoDB Instance with SSL Encryption
  • Example#1488 - Connect to MongoDB Instance with SSL Encryption, verifying it is who we think it is
  • Example#1489 - Connect to MongoDB Instance that Requires Client Certificates
  • Example#1490 - Authenticating with X.509 certificates
  • Example#1491 - Authenticating against the "admin" database
  • Example#1492 - Authenticating against normal databases
  • Example#1493 - ReplicaSet seed list
  • Example#1494 - Wrong replica set name duplication
  • Example#1495 - Correct use of two replica set names
  • Example#1496 -
  • Example#1497 -
  • Example#1498 -
  • Example#1499 -
  • Example#1500 -
  • Example#1501 -
  • Example#1502 - Inheriting read preferences from the database level down to the cursor
  • Example#1503 -
  • Example#1504 -
  • Example#1505 -
  • Example#1506 -
  • Example#1507 -
  • Example#1508 -
  • Example#1509 -
  • Example#1510 - MongoClient basic usage
  • Example#1511 - MongoClient::close example
  • Example#1512 - MongoClient::__construct replica set example
  • Example#1513 - Connecting to a domain socket
  • Example#1514 - MongoClient::__construct authentication example
  • Example#1515 - MongoClient::__construct read preference example
  • Example#1516 - MongoClient::__construct options example
  • Example#1517 - MongoClient::__construct read preference example
  • Example#1518 - MongoClient::getConnections example
  • Example#1519 - MongoClient::getReadPreference return value example
  • Example#1520 - MongoClient::getWriteConcern return value example
  • Example#1521 - MongoClient::killCursor example
  • Example#1522 - MongoClient::listDBs example
  • Example#1523 - MongoClient::selectCollection example
  • Example#1524 - MongoClient::setReadPreference tag set array syntax example
  • Example#1525 - MongoClient::setWriteConcern example
  • Example#1526 - Selecting a database
  • Example#1527 - MongoDB::command "distinct" example
  • Example#1528 - MongoDB::command "distinct" example
  • Example#1529 - MongoDB::command MapReduce example
  • Example#1530 - MongoDB::command "geoNear" example
  • Example#1531 - MongoDB::createCollection capped collection example
  • Example#1532 - MongoDB::createDBRef example
  • Example#1533 - MongoDB::createDBRef example
  • Example#1534 - MongoDB::drop example
  • Example#1535 - Simple MongoDB::execute example
  • Example#1536 - Parameter MongoDB::execute example
  • Example#1537 - Scope example
  • Example#1538 - MongoDB::getCollectionInfo example
  • Example#1539 - MongoDB::getCollectionNames example
  • Example#1540 - MongoDB::getDBRef example
  • Example#1541 - MongoDB::getGridFS example
  • Example#1542 - MongoDB::getReadPreference return value example
  • Example#1543 - MongoDB::getWriteConcern return value example
  • Example#1544 - MongoDB::lastError NULL error example
  • Example#1545 - MongoDB::lastError duplicate key example
  • Example#1546 - MongoDB::listCollections example
  • Example#1547 - MongoDB::repair example
  • Example#1548 - MongoDB::setReadPreference tag set array syntax example
  • Example#1549 - MongoDB::setWriteConcern example
  • Example#1550 - MongoCollection::aggregate example
  • Example#1551 - MongoCollection::aggregate example
  • Example#1552 - MongoCollection::aggregate example
  • Example#1553 - MongoCollection::aggregate with command options
  • Example#1554 - MongoCollection::aggregateCursor example
  • Example#1555 - MongoCollection::aggregateCursor example with different initial batch size
  • Example#1556 - MongoCollection::batchInsert example
  • Example#1557 - MongoCollection::batchInsert example with ignoring errors
  • Example#1558 - MongoCollection::count example
  • Example#1559 - MongoCollection::createDBRef example
  • Example#1560 - MongoCollection::createIndex example
  • Example#1561 - Geospatial Indexing
  • Example#1562 - Drop duplicates example
  • Example#1563 - MongoCollection::deleteIndex example
  • Example#1564 - MongoCollection::deleteIndexes example
  • Example#1565 - MongoCollection::distinct example
  • Example#1566 - MongoCollection::distinct example on a embedded document
  • Example#1567 - MongoCollection::drop example
  • Example#1568 - MongoCollection::ensureIndex example
  • Example#1569 - Geospatial Indexing
  • Example#1570 - Drop duplicates example
  • Example#1571 - MongoCollection::find example
  • Example#1572 - MongoCollection::find example
  • Example#1573 - MongoCollection::find example using $where
  • Example#1574 - MongoCollection::find example using $in
  • Example#1575 - Getting results as an array
  • Example#1576 - MongoCollection::findAndModify example
  • Example#1577 - MongoCollection::findAndModify error handling
  • Example#1578 - MongoCollection::findOne document by its id.
  • Example#1579 - MongoCollection::findOne document by some condition.
  • Example#1580 - MongoCollection::getDBRef example
  • Example#1581 - MongoCollection::getIndexInfo example
  • Example#1582 - MongoCollection::getName example
  • Example#1583 - MongoCollection::getReadPreference return value example
  • Example#1584 - MongoCollection::getWriteConcern return value example
  • Example#1585 - MongoCollection::group example
  • Example#1586 - MongoCollection::group example
  • Example#1587 - Passing a keys function
  • Example#1588 - MongoCollection::insert _id example
  • Example#1589 - MongoCollection::insert acknowledged write example
  • Example#1590 - MongoCollection::parallelCollectionScan example
  • Example#1591 - MongoCollection::remove with justOne example
  • Example#1592 - MongoCollection::save example
  • Example#1593 - MongoCollection::setReadPreference tag set array syntax example
  • Example#1594 - MongoDB::setWriteConcern example
  • Example#1595 - MongoCollection::toIndexString example
  • Example#1596 - MongoCollection::__toString example
  • Example#1597 - MongoCollection::update
  • Example#1598 - MongoCollection::update upsert examples
  • Example#1599 - MongoCollection::update multiple example
  • Example#1600 - MongoCursor basic usage
  • Example#1601 - Iterating over MongoCursor
  • Example#1602 - Adding options to MongoCursor
  • Example#1603 - Adding a comment with MongoCursor::addOption example
  • Example#1604 - MongoCursor::addOption example
  • Example#1605 - MongoCursor::awaitData example
  • Example#1606 - MongoCursor::batchSize and combinations with MongoCursor::limit
  • Example#1607 - MongoCursor::count example
  • Example#1608 - MongoCursor::doQuery example
  • Example#1609 - MongoCursor::explain example
  • Example#1610 - MongoCursor::getReadPreference return value example
  • Example#1611 - MongoCursor::info example
  • Example#1612 - MongoCursor::maxTimeMS example
  • Example#1613 - MongoCursor::setFlag example
  • Example#1614 - MongoCursor::setReadPreference tag set array syntax example
  • Example#1615 - MongoCursor::slaveOkay example
  • Example#1616 - MongoCursor::sort example
  • Example#1617 - MongoCursor::tailable example
  • Example#1618 - MongoCursor::timeout example
  • Example#1619 - Adding options to MongoCommandCursor
  • Example#1620 - MongoCommandCursor::batchSize
  • Example#1621 - MongoCommandCursor example
  • Example#1622 - MongoCommandCursor::createFromDocument
  • Example#1623 - MongoCommandCursor::getReadPreference return value example
  • Example#1624 - MongoCommandCursor::info example
  • Example#1625 - MongoCommandCursor::rewind
  • Example#1626 - MongoCommandCursor::setReadPreference tag set array syntax example
  • Example#1627 - MongoCommandCursor::timeout example
  • Example#1628 - MongoId::__construct example
  • Example#1629 - Parameter example
  • Example#1630 - MongoId::__toString example
  • Example#1631 - MongoCode::__construct example
  • Example#1632 - Using MongoCode with $where
  • Example#1633 - MongoCode::__toString example
  • Example#1634 - Storing dates with MongoDate
  • Example#1635 - MongoDate::__construct example
  • Example#1636 - MongoDate::toDateTime example
  • Example#1637 - Regular expression pattern
  • Example#1638 - MongoRegex::__construct example
  • Example#1639 - MongoRegex::__toString example
  • Example#1640 -
  • Example#1641 - Linking documents
  • Example#1642 - Creating MongoDBRef links
  • Example#1643 - MongoDBRef::create example
  • Example#1644 - MongoCollection::createDBRef example
  • Example#1645 - MongoGridFS::findOne example
  • Example#1646 - MongoGridFS::storeBytes with additional metadata
  • Example#1647 - MongoGridFS::storeFile with additional metadata
  • Example#1648 - MongoGridFS::storeUpload HTML form example
  • Example#1649 - MongoGridFSFile::getBytes example
  • Example#1650 - MongoGridFSFile::getResource example
  • Example#1651 - MongoGridFSFile::write example
  • Example#1652 - MongoWriteBatch example
  • Example#1653 - MongoWriteBatch::add example
  • Example#1654 - MongoWriteBatch::add example
  • Example#1655 - MongoWriteBatch::add example
  • Example#1656 - MongoWriteBatch::add example
  • Example#1657 - MongoWriteBatch::add example
  • Example#1658 - MongoWriteBatch::add example
  • Example#1659 - MongoLog::setCallback example
  • Example#1660 - Changing pool size
  • Example#1661 - Mongo::setPoolSize example
  • Example#1662 - Changing pool size
  • Example#1663 - Mongo::setPoolSize example
  • Example#1664 - MongoResultException::getDocument example
  • Example#1665 - Catching MongoDuplicateKeyException
  • Example#1666 - Catching MongoProtocolException
  • Example#1667 - MongoDB\Driver\Manager::__construct basic example
  • Example#1668 - MongoDB\Driver\Manager::__construct basic examples
  • Example#1669 - MongoDB\Driver\Manager::executeBulkWrite example
  • Example#1670 - MongoDB\Driver\Manager::executeCommand with a command returning a single result document
  • Example#1671 - MongoDB\Driver\Manager::executeCommand with a command returning a cursor
  • Example#1672 - MongoDB\Driver\Manager::executeQuery example
  • Example#1673 - MongoDB\Driver\Manager::getReadConcern example
  • Example#1674 - MongoDB\Driver\Manager::getReadPreference example
  • Example#1675 - MongoDB\Driver\Manager::getServers example
  • Example#1676 - MongoDB\Driver\Manager::getWriteConcern example
  • Example#1677 - Composing MongoDB\Driver\Command to provide a helper to create collections
  • Example#1678 - MongoDB\Driver\Command::__construct example
  • Example#1679 - MongoDB\Driver\Query::__construct example
  • Example#1680 - Mixed write operations are grouped by type
  • Example#1681 - Ordered write operations causing an error
  • Example#1682 - MongoDB\Driver\BulkWrite::__construct example
  • Example#1683 - MongoDB\Driver\BulkWrite::count example
  • Example#1684 - MongoDB\Driver\BulkWrite::delete example
  • Example#1685 - MongoDB\Driver\BulkWrite::insert example
  • Example#1686 - MongoDB\Driver\BulkWrite::update example
  • Example#1687 - MongoDB\Driver\WriteConcern::bsonSerialize with majority write concern
  • Example#1688 - MongoDB\Driver\WriteConcern::bsonSerialize with wtimeout and journal
  • Example#1689 - MongoDB\Driver\WriteConcern::__construct example
  • Example#1690 - MongoDB\Driver\WriteConcern::getJournal example
  • Example#1691 - MongoDB\Driver\WriteConcern::getW example
  • Example#1692 - MongoDB\Driver\WriteConcern::getWtimeout example
  • Example#1693 - MongoDB\Driver\ReadPreference::bsonSerialize with primary read preference
  • Example#1694 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and tag sets
  • Example#1695 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and max staleness
  • Example#1696 - MongoDB\Driver\ReadPreference::__construct example
  • Example#1697 - MongoDB\Driver\ReadPreference::getMaxStalenessSeconds example
  • Example#1698 - MongoDB\Driver\ReadPreference::getMode example
  • Example#1699 - MongoDB\Driver\ReadPreference::getTagSets example
  • Example#1700 - MongoDB\Driver\ReadConcern::bsonSerialize with empty read concern
  • Example#1701 - MongoDB\Driver\ReadConcern::bsonSerialize with local read concern
  • Example#1702 - MongoDB\Driver\ReadConcern::__construct example
  • Example#1703 - MongoDB\Driver\ReadConcern::getLevel example
  • Example#1704 - MongoDB\Driver\Cursor::getId example
  • Example#1705 - MongoDB\Driver\Cursor::getServer example
  • Example#1706 - MongoDB\Driver\Cursor::isDead example
  • Example#1707 - MongoDB\Driver\Cursor::setTypeMap example
  • Example#1708 - MongoDB\Driver\Cursor::toArray example
  • Example#1709 - MongoDB\Driver\CursorId::__toString example
  • Example#1710 - MongoDB\Driver\Server::getHost example
  • Example#1711 - MongoDB\Driver\Server::getInfo example
  • Example#1712 - MongoDB\Driver\Server::getLatency example
  • Example#1713 - MongoDB\Driver\Server::getPort example
  • Example#1714 - MongoDB\Driver\WriteConcernError::getCode example
  • Example#1715 - MongoDB\Driver\WriteConcernError::getInfo example
  • Example#1716 - MongoDB\Driver\WriteConcernError::getMessage example
  • Example#1717 - MongoDB\Driver\WriteError::getCode example
  • Example#1718 - MongoDB\Driver\WriteError::getIndex example
  • Example#1719 - MongoDB\Driver\WriteError::getMessage example
  • Example#1720 - MongoDB\Driver\WriteResult::getDeletedCount example
  • Example#1721 - MongoDB\Driver\WriteResult::getInsertedCount example
  • Example#1722 - MongoDB\Driver\WriteResult::getMatchedCount example
  • Example#1723 - MongoDB\Driver\WriteResult::getModifiedCount example
  • Example#1724 - MongoDB\Driver\WriteResult::getServer example
  • Example#1725 - MongoDB\Driver\WriteResult::getUpsertedCount example
  • Example#1726 - MongoDB\Driver\WriteResult::getUpsertedIds example
  • Example#1727 - MongoDB\Driver\WriteResult::getWriteConcernError example
  • Example#1728 - MongoDB\Driver\WriteResult::getWriteErrors with a single error
  • Example#1729 - MongoDB\Driver\WriteResult::getWriteErrors with multiple errors
  • Example#1730 - MongoDB\Driver\WriteResult::isAcknowledged with acknowledged write concern
  • Example#1731 - MongoDB\Driver\WriteResult::isAcknowledged with unacknowledged write concern
  • Example#1732 - MongoDB\BSON\fromJSON example
  • Example#1733 - MongoDB\BSON\fromPHP example
  • Example#1734 - MongoDB\BSON\toJSON example
  • Example#1735 - MongoDB\BSON\toPHP example
  • Example#1736 - MongoDB\BSON\Binary::__construct example
  • Example#1737 - MongoDB\BSON\Binary::getData example
  • Example#1738 - MongoDB\BSON\Binary::getType example
  • Example#1739 - MongoDB\BSON\Binary::__toString example
  • Example#1740 - MongoDB\BSON\Javascript::__construct example
  • Example#1741 - MongoDB\BSON\Javascript::getCode example
  • Example#1742 - MongoDB\BSON\Javascript::getScope example
  • Example#1743 - MongoDB\BSON\Javascript::__toString example
  • Example#1744 - MongoDB\BSON\MaxKey::__construct example
  • Example#1745 - MongoDB\BSON\MinKey::__construct example
  • Example#1746 - MongoDB\BSON\ObjectID::__construct example
  • Example#1747 - MongoDB\BSON\ObjectID::getTimestamp example
  • Example#1748 - MongoDB\BSON\ObjectID::__toString example
  • Example#1749 - MongoDB\BSON\Regex::__construct example
  • Example#1750 - MongoDB\BSON\Regex::getFlags example
  • Example#1751 - MongoDB\BSON\Regex::getPattern example
  • Example#1752 - MongoDB\BSON\Regex::__toString example
  • Example#1753 - MongoDB\BSON\Timestamp::__construct example
  • Example#1754 - MongoDB\BSON\Timestamp::__toString example
  • Example#1755 - MongoDB\BSON\UTCDateTime::__construct example
  • Example#1756 - MongoDB\BSON\UTCDatetime::toDateTime example
  • Example#1757 - MongoDB\BSON\UTCDateTime::__toString example
  • Example#1758 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for root document
  • Example#1759 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for root document
  • Example#1760 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for document field
  • Example#1761 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for document field
  • Example#1762 - MongoDB\BSON\Unserializable::bsonUnserialize example
  • Example#1763 - MongoDB\Driver\Exception\WriteException::getWriteResult example
  • Example#1764 - mSQL usage example
  • Example#1765 - msql_fetch_array example
  • Example#1766 - msql_fetch_object example
  • Example#1767 - msql_fetch_row example
  • Example#1768 - msql_query example
  • Example#1769 - mssql_bind example
  • Example#1770 - mssql_close example
  • Example#1771 - mssql_connect example
  • Example#1772 - mssql_data_seek example
  • Example#1773 - mssql_execute example
  • Example#1774 - mssql_fetch_array example
  • Example#1775 - mssql_fetch_assoc example
  • Example#1776 - mssql_fetch_batch example
  • Example#1777 - mssql_fetch_field example
  • Example#1778 - mssql_fetch_object example
  • Example#1779 - mssql_fetch_row example
  • Example#1780 - mssql_field_length example
  • Example#1781 - mssql_field_name example
  • Example#1782 - Using mssql_field_seek on the example for mssql_fetch_field
  • Example#1783 - mssql_field_type example
  • Example#1784 - mssql_free_result example
  • Example#1785 - mssql_free_statement example
  • Example#1786 - mssql_get_last_message example
  • Example#1787 - mssql_guid_string example
  • Example#1788 - mssql_init example
  • Example#1789 - mssql_min_error_severity example
  • Example#1790 - mssql_min_message_severity example
  • Example#1791 - mssql_next_result example
  • Example#1792 - mssql_num_fields example
  • Example#1793 - mssql_num_rows example
  • Example#1794 - mssql_pconnect using the new_link parameter
  • Example#1795 - mssql_query example
  • Example#1796 - mssql_result example
  • Example#1797 - Faster alternative to above example
  • Example#1798 - mssql_rows_affected example
  • Example#1799 - mssql_select_db example
  • Example#1800 - Escaping the database name with square brackets
  • Example#1801 - Comparing the three MySQL APIs
  • Example#1802 - Configure commands for using mysqlnd or libmysqlclient
  • Example#1803 - Unbuffered query example: mysqli
  • Example#1804 - Unbuffered query example: pdo_mysql
  • Example#1805 - Unbuffered query example: mysql
  • Example#1806 - Problems with setting the character set with SQL
  • Example#1807 - Setting the character set example: mysqli
  • Example#1808 - Setting the character set example: pdo_mysql
  • Example#1809 - Setting the character set example: mysql
  • Example#1810 - Easy migration from the old mysql extension
  • Example#1811 - Object-oriented and procedural interface
  • Example#1812 - Bad coding style
  • Example#1813 - Special meaning of localhost
  • Example#1814 - Setting defaults
  • Example#1815 - Connecting to MySQL
  • Example#1816 - Navigation through buffered results
  • Example#1817 - Navigation through unbuffered results
  • Example#1818 - Text protocol returns strings by default
  • Example#1819 - Native data types with mysqlnd and connection option
  • Example#1820 - First stage: prepare
  • Example#1821 - Second stage: bind and execute
  • Example#1822 - INSERT prepared once, executed multiple times
  • Example#1823 - Less round trips using multi-INSERT SQL
  • Example#1824 - Native datatypes
  • Example#1825 - Output variable binding
  • Example#1826 - Using mysqli_result to fetch results
  • Example#1827 - Buffered result set for flexible read out
  • Example#1828 - Calling a stored procedure
  • Example#1829 - Using session variables
  • Example#1830 - Fetching results from stored procedures
  • Example#1831 - Stored Procedures and Prepared Statements
  • Example#1832 - Stored Procedures and Prepared Statements using bind API
  • Example#1833 - Multiple Statements
  • Example#1834 - SQL Injection
  • Example#1835 - Setting auto commit mode with SQL and through the API
  • Example#1836 - Commit and rollback
  • Example#1837 - Accessing result set meta data
  • Example#1838 - Prepared statements metadata
  • Example#1839 - MySQLi extension overview example
  • Example#1840 - $mysqli->affected_rows example
  • Example#1841 - mysqli::autocommit example
  • Example#1842 - $mysqli->begin_transaction example
  • Example#1843 - mysqli::change_user example
  • Example#1844 - mysqli::character_set_name example
  • Example#1845 - mysqli_get_client_info
  • Example#1846 - mysqli_get_client_version
  • Example#1847 - mysqli::commit example
  • Example#1848 - $mysqli->connect_errno example
  • Example#1849 - $mysqli->connect_error example
  • Example#1850 - mysqli::__construct example
  • Example#1851 - Generating a Trace File
  • Example#1852 - $mysqli->errno example
  • Example#1853 - $mysqli->error_list example
  • Example#1854 - $mysqli->error example
  • Example#1855 - $mysqli->field_count example
  • Example#1856 - mysqli::get_charset example
  • Example#1857 - mysqli_get_client_info
  • Example#1858 - A mysqli_get_client_stats example
  • Example#1859 - mysqli_get_client_version
  • Example#1860 - A mysqli_get_connection_stats example
  • Example#1861 - $mysqli->host_info example
  • Example#1862 - $mysqli->protocol_version example
  • Example#1863 - $mysqli->server_info example
  • Example#1864 - $mysqli->server_version example
  • Example#1865 - $mysqli->info example
  • Example#1866 - $mysqli->insert_id example
  • Example#1867 - mysqli::kill example
  • Example#1868 - mysqli::multi_query example
  • Example#1869 - mysqli::ping example
  • Example#1870 - A mysqli_poll example
  • Example#1871 - mysqli::prepare example
  • Example#1872 - mysqli::query example
  • Example#1873 - mysqli::real_connect example
  • Example#1874 - mysqli::real_escape_string example
  • Example#1875 - mysqli::rollback example
  • Example#1876 - mysqli::select_db example
  • Example#1877 - mysqli::set_charset example
  • Example#1878 - mysqli::set_local_infile_handler example
  • Example#1879 - $mysqli->sqlstate example
  • Example#1880 - mysqli::stat example
  • Example#1881 - $mysqli->thread_id example
  • Example#1882 - mysqli::use_result example
  • Example#1883 - $mysqli->warning_count example
  • Example#1884 - Stil obiect-orientat
  • Example#1885 - Stil procedural
  • Example#1886 - Stil obiect-orientat
  • Example#1887 - Stil procedural
  • Example#1888 - Stil obiect-orientat
  • Example#1889 - Stil procedural
  • Example#1890 - Stil obiect-orientat
  • Example#1891 - Stil procedural
  • Example#1892 - Stil obiect-orientat
  • Example#1893 - Stil procedural
  • Example#1894 - Stil obiect-orientat
  • Example#1895 - Stil procedural
  • Example#1896 - Stil obiect-orientat
  • Example#1897 - Stil procedural
  • Example#1898 - Stil obiect-orientat
  • Example#1899 - Stil procedural
  • Example#1900 - Stil obiect-orientat
  • Example#1901 - Stil procedural
  • Example#1902 - Stil obiect-orientat
  • Example#1903 - Stil procedural
  • Example#1904 - Stil obiect-orientat
  • Example#1905 - Stil procedural
  • Example#1906 - Stil obiect-orientat
  • Example#1907 - Stil procedural
  • Example#1908 - Stil obiect-orientat
  • Example#1909 - Stil procedural
  • Example#1910 - Stil obiect-orientat
  • Example#1911 - Stil procedural
  • Example#1912 - Stil obiect-orientat
  • Example#1913 - Stil obiect-orientat
  • Example#1914 - Stil procedural
  • Example#1915 - Stil obiect-orientat
  • Example#1916 - Stil procedural
  • Example#1917 - Stil obiect-orientat
  • Example#1918 - Stil procedural
  • Example#1919 - Stil obiect-orientat
  • Example#1920 - Stil procedural
  • Example#1921 - Stil obiect-orientat
  • Example#1922 - Stil procedural
  • Example#1923 - Stil obiect-orientat
  • Example#1924 - Stil procedural
  • Example#1925 - A mysqli_result example comparing iterator usage
  • Example#1926 - Stil obiect-orientat
  • Example#1927 - Stil procedural
  • Example#1928 - Stil obiect-orientat
  • Example#1929 - Stil procedural
  • Example#1930 - Stil obiect-orientat
  • Example#1931 - Stil procedural
  • Example#1932 - Stil obiect-orientat
  • Example#1933 - Stil procedural
  • Example#1934 - Stil obiect-orientat
  • Example#1935 - Stil procedural
  • Example#1936 - Stil obiect-orientat
  • Example#1937 - Stil procedural
  • Example#1938 - Stil obiect-orientat
  • Example#1939 - Stil procedural
  • Example#1940 - Stil obiect-orientat
  • Example#1941 - Stil procedural
  • Example#1942 - Stil obiect-orientat
  • Example#1943 - Stil procedural
  • Example#1944 - Stil obiect-orientat
  • Example#1945 - Stil procedural
  • Example#1946 - Exemplu mysqli_connect
  • Example#1947 - Exemplu general de utilizare a extensiei MySQL
  • Example#1948 - Exemplu mysql_affected_rows
  • Example#1949 - Exemplu mysql_affected_rows utilizând tranzac?ii
  • Example#1950 - Exemplu mysql_client_encoding
  • Example#1951 - Exemplu mysql_close
  • Example#1952 - Exemplu mysql_connect
  • Example#1953 - Exemplu mysql_connect utilizând sintaxa hostname:port
  • Example#1954 - Exemplu mysql_connect utilizând sintaxa ":/calea/spre/socket"
  • Example#1955 - Un exemplu alternativ mysql_create_db
  • Example#1956 - mysql_data_seek example
  • Example#1957 - mysql_db_name example
  • Example#1958 - mysql_db_query alternative example
  • Example#1959 - mysql_drop_db alternative example
  • Example#1960 - mysql_errno example
  • Example#1961 - mysql_error example
  • Example#1962 - exemplu de uz al functiei mysql_escape_string
  • Example#1963 - Query with aliased duplicate field names
  • Example#1964 - mysql_fetch_array with MYSQL_NUM
  • Example#1965 - mysql_fetch_array with MYSQL_ASSOC
  • Example#1966 - mysql_fetch_array with MYSQL_BOTH
  • Example#1967 - An expanded mysql_fetch_assoc example
  • Example#1968 - mysql_fetch_field example
  • Example#1969 - A mysql_fetch_lengths example
  • Example#1970 - mysql_fetch_object example
  • Example#1971 - mysql_fetch_object example
  • Example#1972 - Fetching one row with mysql_fetch_row
  • Example#1973 - A mysql_field_flags example
  • Example#1974 - mysql_field_len example
  • Example#1975 - mysql_field_name example
  • Example#1976 - A mysql_field_table example
  • Example#1977 - mysql_field_type example
  • Example#1978 - A mysql_free_result example
  • Example#1979 - Exemplu mysql_get_client_info
  • Example#1980 - mysql_get_host_info example
  • Example#1981 - mysql_get_proto_info example
  • Example#1982 - mysql_get_server_info example
  • Example#1983 - Relevant MySQL Statements
  • Example#1984 - mysql_insert_id example
  • Example#1985 - mysql_list_dbs example
  • Example#1986 - Alternate to deprecated mysql_list_fields
  • Example#1987 - mysql_list_processes example
  • Example#1988 - mysql_list_tables alternative example
  • Example#1989 - A mysql_num_fields example
  • Example#1990 - mysql_num_rows example
  • Example#1991 - A mysql_ping example
  • Example#1992 - Invalid Query
  • Example#1993 - Valid Query
  • Example#1994 - Simple mysql_real_escape_string example
  • Example#1995 - mysql_real_escape_string requires a connection example
  • Example#1996 - An example SQL Injection Attack
  • Example#1997 - mysql_result example
  • Example#1998 - mysql_select_db example
  • Example#1999 - mysql_stat example
  • Example#2000 - Alternative mysql_stat example
  • Example#2001 - mysql_tablename example
  • Example#2002 - mysql_thread_id example
  • Example#2003 - Enabling the plugin (php.ini)
  • Example#2004 - Minimal plugin-specific configuration file (mysqlnd_ms_plugin.ini)
  • Example#2005 - Recommended minimal plugin-specific config (mysqlnd_ms_plugin.ini)
  • Example#2006 - Using one server as a master and as a slave (testing only!)
  • Example#2007 - Plugin specific configuration file (mysqlnd_ms_plugin.ini)
  • Example#2008 - Opening a load balanced connection
  • Example#2009 - Executing statements
  • Example#2010 - Plugin config with one slave and one master
  • Example#2011 - Pitfall: connection state and SQL user variables
  • Example#2012 - Plugin config with one slave and one master
  • Example#2013 - SQL hints to prevent connection switches
  • Example#2014 - Fighting replication lag
  • Example#2015 - Table creation on a slave
  • Example#2016 - Plugin config with one slave and one master
  • Example#2017 - Using SQL hints for transactions
  • Example#2018 - Transaction aware load balancing: trx_stickiness setting
  • Example#2019 - Transaction aware
  • Example#2020 - General pattern for XA transactions
  • Example#2021 - Local and global transactions are mutually exclusive
  • Example#2022 - Transaction coordinator state store
  • Example#2023 - Session consistency: read your writes
  • Example#2024 - Requesting session consistency
  • Example#2025 - Maximum age/slave lag
  • Example#2026 - Limiting slave lag
  • Example#2027 - Fail over not set
  • Example#2028 - No slave within time limit
  • Example#2029 - Create counter table on master
  • Example#2030 - Plugin config: SQL for client-side GTID injection
  • Example#2031 - Transparent global transaction ID injection
  • Example#2032 - Plugin config: SQL for fetching GTID
  • Example#2033 - Obtaining GTID after injection
  • Example#2034 - Plugin config: Checking for a certain GTID
  • Example#2035 - Session consistency service level and GTID combined
  • Example#2036 - Plugin config: using MySQL 5.6.5-m8 built-in GTID feature
  • Example#2037 - Recap: quality of service to request read your writes
  • Example#2038 - Plugin config: no special entries for caching
  • Example#2039 - Caching a slave request
  • Example#2040 - Read your writes and caching combined
  • Example#2041 - Manual failover, automatic optional
  • Example#2042 - Manual failover
  • Example#2043 - Cluster node groups
  • Example#2044 - Manual partitioning using SQL hints
  • Example#2045 - Plugin config: Fabric hosts instead of MySQL servers
  • Example#2046 - Manual partitioning using SQL hints
  • Example#2047 - Provoking a connection error
  • Example#2048 - Connection error on query execution
  • Example#2049 - Provoking a connection error
  • Example#2050 - Most basic failover
  • Example#2051 - Provoking a transient error
  • Example#2052 - Transient error retry loop
  • Example#2053 - Enabling the plugin (php.ini)
  • Example#2054 - Basic plugin configuration (mysqlnd_ms_plugin.ini) for MySQL Replication
  • Example#2055 - Multiple primaries - multi master (php.ini)
  • Example#2056 - Primary copy with multiple primaries and paritioning
  • Example#2057 - Multiple primaries - multi master (php.ini)
  • Example#2058 - Synchronous update anywhere cluster
  • Example#2059 - General pattern for XA transactions
  • Example#2060 - Converting a PHP array (hash) into JSON format
  • Example#2061 - Using section names example
  • Example#2062 - List of anonymous slaves
  • Example#2063 - Master list using symbolic names
  • Example#2064 - Keywords to configure a server
  • Example#2065 - New roundrobin filter, old functionality
  • Example#2066 - The user filter replaces mysqlnd_ms_set_user_pick_server
  • Example#2067 - Common error message in case of configuration file issues (upto version 1.5.0)
  • Example#2068 - Improved configuration file validation since 1.5.0
  • Example#2069 - Possibly more precise error due to mysqlnd_ms.force_config_usage=1
  • Example#2070 - Minimum pluging configuration for use with MySQL Fabric
  • Example#2071 - Optional timeout for communication with Fabric
  • Example#2072 - Warnings about the violation of transaction boundaries
  • Example#2073 - Invalid filter sequence
  • Example#2074 - Random load balancing with random filter
  • Example#2075 - Random once load balancing with random filter
  • Example#2076 - Referencing error
  • Example#2077 - Assigning a weight for load balancing
  • Example#2078 - roundrobin filter
  • Example#2079 - Setting a callback
  • Example#2080 - Using a callback
  • Example#2081 - Returning random masters and slaves
  • Example#2082 - Manual partitioning
  • Example#2083 - Global limit on slave lag
  • Example#2084 - Optional master failover when failing to connect to slave (PECL/mysqlnd_ms < 1.4.0)
  • Example#2085 - New syntax since 1.4.0
  • Example#2086 - Disabling lazy connection
  • Example#2087 - String escaping on a lazy connection handle
  • Example#2088 - Master on write for consistent reads
  • Example#2089 - Using master to execute transactions
  • Example#2090 - No automatic failover, error handling pitfall
  • Example#2091 - Retry loop for transient errors
  • Example#2092 - SQL definition for the MySQL state store transaction table
  • Example#2093 - SQL definition for the MySQL state store transaction table
  • Example#2094 - SQL definition for the MySQL state store garbage collection table
  • Example#2095 - Using section names example
  • Example#2096 - List-like syntax
  • Example#2097 - Verify plugin activity in a non-threaded deployment model
  • Example#2098 - Recording statistics during shutdown
  • Example#2099 - Example demonstrating the usage of mysqlnd_ms constants
  • Example#2100 - mysqlnd_ms_dump_servers example
  • Example#2101 - mysqlnd_ms_get_last_gtid example
  • Example#2102 - mysqlnd_ms_get_last_used_connection example
  • Example#2103 - mysqlnd_ms_get_stats example
  • Example#2104 - mysqlnd_ms_match_wild example
  • Example#2105 - mysqlnd_ms_query_is_select example
  • Example#2106 - mysqlnd_ms_set_qos example
  • Example#2107 - mysqlnd_ms_set_user_pick_server example
  • Example#2108 - Enabling the plugin (php.ini)
  • Example#2109 - Using the MYSQLND_QC_ENABLE_SWITCH SQL hint
  • Example#2110 - Using the MYSQLND_QC_DISABLE_SWITCH SQL hint
  • Example#2111 - Example showing which type of statements are not cached
  • Example#2112 - Enabling caching for all statements using the mysqlnd_qc.cache_no_table ini setting
  • Example#2113 - Setting the TTL with the mysqlnd_qc.ttl ini setting
  • Example#2114 - Setting TTL with SQL hints
  • Example#2115 - Setting a callback with mysqlnd_qc_set_is_select
  • Example#2116 - Enabling the slam defense mechanism
  • Example#2117 - Collecting a query trace
  • Example#2118 - Setting the backtrace depth with the mysqlnd_qc.query_trace_bt_depth ini setting
  • Example#2119 - Collecting statistics data with the mysqlnd_qc.time_statistics ini setting
  • Example#2120 - Example mysqlnd_qc_get_cache_info usage
  • Example#2121 - Example mysqlnd_qc_get_normalized_query_trace_log usage
  • Example#2122 - Using a user-defined storage handler
  • Example#2123 - Using SQL hint constants
  • Example#2124 - Example mysqlnd_qc_set_cache_condition usage
  • Example#2125 - mysqlnd_qc_get_available_handlers example
  • Example#2126 - mysqlnd_qc_get_cache_info example
  • Example#2127 - mysqlnd_qc_get_core_stats example
  • Example#2128 - mysqlnd_qc_get_normalized_query_trace_log example
  • Example#2129 - mysqlnd_qc_get_query_trace_log example
  • Example#2130 - mysqlnd_qc_set_cache_condition example
  • Example#2131 - mysqlnd_qc_set_is_select example
  • Example#2132 - mysqlnd_qc_set_storage_handler example
  • Example#2133 - Enabling the plugin (php.ini)
  • Example#2134 - Pseudo-code: what a built-in class does
  • Example#2135 - Installing a proxy
  • Example#2136 - Proxy registration, mysqlnd_uh.enable=1
  • Example#2137 - Proxy installation disabled
  • Example#2138 - Connection proxy
  • Example#2139 - Prepared statement proxy
  • Example#2140 - Basic Monitoring
  • Example#2141 - MysqlndUhConnection::changeUser example
  • Example#2142 - MysqlndUhConnection::charsetName example
  • Example#2143 - MysqlndUhConnection::close example
  • Example#2144 - MysqlndUhConnection::connect example
  • Example#2145 - MysqlndUhConnection::endPSession example
  • Example#2146 - MysqlndUhConnection::escapeString example
  • Example#2147 - MysqlndUhConnection::getAffectedRows example
  • Example#2148 - MysqlndUhConnection::getErrorNumber example
  • Example#2149 - MysqlndUhConnection::getErrorString example
  • Example#2150 - MysqlndUhConnection::getFieldCount example
  • Example#2151 - MysqlndUhConnection::getHostInformation example
  • Example#2152 - MysqlndUhConnection::getLastInsertId example
  • Example#2153 - MysqlndUhConnection::getLastMessage example
  • Example#2154 - MysqlndUhConnection::getProtocolInformation example
  • Example#2155 - MysqlndUhConnection::getServerInformation example
  • Example#2156 - MysqlndUhConnection::getServerStatistics example
  • Example#2157 - MysqlndUhConnection::getServerVersion example
  • Example#2158 - MysqlndUhConnection::getSqlstate example
  • Example#2159 - MysqlndUhConnection::getStatistics example
  • Example#2160 - MysqlndUhConnection::getThreadId example
  • Example#2161 - MysqlndUhConnection::getWarningCount example
  • Example#2162 - MysqlndUhConnection::init example
  • Example#2163 - MysqlndUhConnection::kill example
  • Example#2164 - MysqlndUhConnection::listFields example
  • Example#2165 - MysqlndUhConnection::listMethod example
  • Example#2166 - MysqlndUhConnection::moreResults example
  • Example#2167 - MysqlndUhConnection::nextResult example
  • Example#2168 - MysqlndUhConnection::ping example
  • Example#2169 - MysqlndUhConnection::query example
  • Example#2170 - MysqlndUhConnection::queryReadResultsetHeader example
  • Example#2171 - MysqlndUhConnection::reapQuery example
  • Example#2172 - MysqlndUhConnection::refreshServer example
  • Example#2173 - MysqlndUhConnection::restartPSession example
  • Example#2174 - MysqlndUhConnection::selectDb example
  • Example#2175 - MysqlndUhConnection::sendClose example
  • Example#2176 - MysqlndUhConnection::sendQuery example
  • Example#2177 - MysqlndUhConnection::serverDumpDebugInformation example
  • Example#2178 - MysqlndUhConnection::setAutocommit example
  • Example#2179 - MysqlndUhConnection::setCharset example
  • Example#2180 - MysqlndUhConnection::setClientOption example
  • Example#2181 - MysqlndUhConnection::setServerOption example
  • Example#2182 - MysqlndUhConnection::simpleCommand example
  • Example#2183 - MysqlndUhConnection::simpleCommandHandleResponse example
  • Example#2184 - MysqlndUhConnection::sslSet example
  • Example#2185 - MysqlndUhConnection::stmtInit example
  • Example#2186 - MysqlndUhConnection::storeResult example
  • Example#2187 - MysqlndUhConnection::txCommit example
  • Example#2188 - MysqlndUhConnection::txRollback example
  • Example#2189 - MysqlndUhConnection::useResult example
  • Example#2190 - MysqlndUhPreparedStatement::execute example
  • Example#2191 - MysqlndUhPreparedStatement::prepare example
  • Example#2192 - mysqlnd_uh_convert_to_mysqlnd example
  • Example#2193 - mysqlnd_uh_set_connection_proxy example
  • Example#2194 - Enabling the plugin (php.ini)
  • Example#2195 - SQL table used for the Quickstart
  • Example#2196 - Basic example.
  • Example#2197 - mysqlnd_memcache_get_config example
  • Example#2198 - mysqlnd_memcache_set example with var_dump as a simple debugging callback.
  • Example#2199 - Basic query
  • Example#2200 - Inserting with bind variables
  • Example#2201 - Binding in the WHERE clause of a query
  • Example#2202 - Inserting and fetching a CLOB
  • Example#2203 - Using a PL/SQL stored function
  • Example#2204 - Using a PL/SQL stored procedure
  • Example#2205 - Calling a PL/SQL function that returns a REF CURSOR
  • Example#2206 - user_oci8_probes.d for tracing all user-level PHP OCI8 Static Probes with DTrace
  • Example#2207 - oci_bind_array_by_name example
  • Example#2208 - Inserting data with oci_bind_by_name
  • Example#2209 - Binding once for multiple executions
  • Example#2210 - Binding with a foreach loop
  • Example#2211 - Binding in a WHERE clause
  • Example#2212 - Binding with a LIKE clause
  • Example#2213 - Binding with REGEXP_LIKE
  • Example#2214 - Binding Multiple Values in an IN Clause
  • Example#2215 - Binding a ROWID returned by a query
  • Example#2216 - Binding a ROWID on INSERT
  • Example#2217 - Binding for a PL/SQL stored function
  • Example#2218 - Binding parameters for a PL/SQL stored procedure
  • Example#2219 - Binding a CLOB column
  • Example#2220 - Binding a PL/SQL BOOLEAN
  • Example#2221 - oci_client_version example
  • Example#2222 - Closing a connection
  • Example#2223 - Database connections are not closed until all references are closed
  • Example#2224 - Closing a connection opened more than once
  • Example#2225 - Connections are closed when variables go out of scope
  • Example#2226 - oci_commit example
  • Example#2227 - Basic oci_connect using Easy Connect syntax
  • Example#2228 - Basic oci_connect using a Network Connect name
  • Example#2229 - oci_connect with an explicit character set
  • Example#2230 - Using multiple calls to oci_connect
  • Example#2231 - oci_define_by_name example
  • Example#2232 - oci_define_by_name with case sensitive column names
  • Example#2233 - oci_define_by_name with LOB columns
  • Example#2234 - oci_define_by_name with an explicit type
  • Example#2235 - Displaying the Oracle error message after a connection error
  • Example#2236 - Displaying the Oracle error message after a parsing error
  • Example#2237 - Displaying the Oracle error message, the problematic statement, and the position of the problem of an execution error
  • Example#2238 - oci_execute for queries
  • Example#2239 - oci_execute without specifying a mode example
  • Example#2240 - oci_execute with OCI_NO_AUTO_COMMIT example
  • Example#2241 - oci_execute with different commit modes example
  • Example#2242 - oci_execute with OCI_DESCRIBE_ONLY example
  • Example#2243 - oci_fetch_all example
  • Example#2244 - oci_fetch_all example with OCI_FETCHSTATEMENT_BY_ROW
  • Example#2245 - oci_fetch_all with OCI_NUM
  • Example#2246 - oci_fetch_array with OCI_BOTH
  • Example#2247 - oci_fetch_array with OCI_NUM
  • Example#2248 - oci_fetch_array with OCI_ASSOC
  • Example#2249 - oci_fetch_array with OCI_RETURN_NULLS
  • Example#2250 - oci_fetch_array with OCI_RETURN_LOBS
  • Example#2251 - oci_fetch_array with case sensitive column names
  • Example#2252 - oci_fetch_array with columns having duplicate names
  • Example#2253 - oci_fetch_array with DATE columns
  • Example#2254 - oci_fetch_array with REF CURSOR
  • Example#2255 - Pagination with oci_fetch_array using a LIMIT-like query
  • Example#2256 - oci_fetch_array with Oracle Database 12c Implicit Result Sets
  • Example#2257 - oci_fetch_assoc Example
  • Example#2258 - oci_fetch_object example
  • Example#2259 - oci_fetch_object with case sensitive column names
  • Example#2260 - oci_fetch_object with LOBs
  • Example#2261 - oci_fetch_row Example
  • Example#2262 - oci_fetch with defined variables
  • Example#2263 - oci_fetch with oci_result
  • Example#2264 - oci_field_name example
  • Example#2265 - oci_field_name example
  • Example#2266 - oci_field_precision Example
  • Example#2267 - oci_field_scale Example
  • Example#2268 - oci_field_size example
  • Example#2269 - oci_field_type_raw Example
  • Example#2270 - oci_field_type example
  • Example#2271 - Fetching Implicit Result Sets in a loop
  • Example#2272 - Getting child statement handles individually
  • Example#2273 - Explicitly setting the Prefetch Count
  • Example#2274 - Implicit Result Set example without using oci_get_implicit_resultset
  • Example#2275 - oci_new_connect example
  • Example#2276 - Binding a REF CURSOR in an Oracle stored procedure call
  • Example#2277 - oci_new_descriptor example
  • Example#2278 - oci_new_descriptor example
  • Example#2279 - oci_num_fields example
  • Example#2280 - oci_num_rows example
  • Example#2281 - oci_parse example for SQL statements
  • Example#2282 - oci_parse example for PL/SQL statements
  • Example#2283 - oci_password_change example changing the password of an already connected user
  • Example#2284 - oci_password_change example of connecting and changing the password in one step
  • Example#2285 - Basic oci_pconnect Example using Easy Connect syntax
  • Example#2286 - oci_fetch with oci_result
  • Example#2287 - oci_rollback example
  • Example#2288 - Rolling back to a SAVEPOINT example
  • Example#2289 - oci_server_version example
  • Example#2290 - Setting the action
  • Example#2291 - Setting the client identifier to the application user
  • Example#2292 - Setting the client information
  • Example#2293 - Two scripts can use different versions of myfunc() at the same time
  • Example#2294 - Setting the module name
  • Example#2295 - Changing the default prefetch value for a query
  • Example#2296 - Changing the default prefetch for a REF CURSOR fetch
  • Example#2297 - Setting the prefetch value when passing a REF CURSOR back to Oracle
  • Example#2298 - oci_statement_type example
  • Example#2299 - Creating a Paradox database with two fields
  • Example#2300 - Turn a paradox date into a human readable form
  • Example#2301 - Set the date/time fields in a paradox database to the current date/time
  • Example#2302 - Opening a Paradox database
  • Example#2303 - Opening a Paradox database
  • Example#2304 - Turn a paradox timestamp into a human readable form
  • Example#2305 - PostgreSQL extension overview example
  • Example#2306 - pg_affected_rows example
  • Example#2307 - pg_cancel_query example
  • Example#2308 - pg_client_encoding example
  • Example#2309 - pg_close example
  • Example#2310 - Using pg_connect
  • Example#2311 - pg_connection_busy example
  • Example#2312 - pg_connection_reset example
  • Example#2313 - pg_connection_status example
  • Example#2314 - pg_convert example
  • Example#2315 - pg_copy_from example
  • Example#2316 - pg_copy_to example
  • Example#2317 - pg_dbname example
  • Example#2318 - pg_delete example
  • Example#2319 - pg_end_copy example
  • Example#2320 - pg_escape_bytea example
  • Example#2321 - pg_escape_identifier example
  • Example#2322 - pg_escape_literal example
  • Example#2323 - pg_escape_string example
  • Example#2324 - Using pg_execute
  • Example#2325 - pg_fetch_all_columns example
  • Example#2326 - PostgreSQL fetch all
  • Example#2327 - pg_fetch_array example
  • Example#2328 - pg_fetch_assoc example
  • Example#2329 - pg_fetch_object example
  • Example#2330 - pg_fetch_result example
  • Example#2331 - pg_fetch_row example
  • Example#2332 - pg_field_is_null example
  • Example#2333 - Getting information about fields
  • Example#2334 - Getting information about fields
  • Example#2335 - Getting information about fields
  • Example#2336 - Getting information about fields
  • Example#2337 - Getting table information about a field
  • Example#2338 - Getting information about fields
  • Example#2339 - Getting information about fields
  • Example#2340 - pg_free_result example
  • Example#2341 - PostgreSQL NOTIFY message
  • Example#2342 - PostgreSQL backend PID
  • Example#2343 - pg_get_result example
  • Example#2344 - pg_host example
  • Example#2345 - pg_insert example
  • Example#2346 - pg_last_error example
  • Example#2347 - pg_last_notice example
  • Example#2348 - pg_last_oid example
  • Example#2349 - pg_lo_close example
  • Example#2350 - pg_lo_create example
  • Example#2351 - pg_lo_export example
  • Example#2352 - pg_lo_import example
  • Example#2353 - pg_lo_open example
  • Example#2354 - pg_lo_read_all example
  • Example#2355 - pg_lo_read example
  • Example#2356 - pg_lo_seek example
  • Example#2357 - pg_lo_tell example
  • Example#2358 - pg_lo_truncate example
  • Example#2359 - pg_lo_unlink example
  • Example#2360 - pg_lo_write example
  • Example#2361 - Getting table metadata
  • Example#2362 - pg_num_fields example
  • Example#2363 - pg_num_rows example
  • Example#2364 - pg_options example
  • Example#2365 - pg_parameter_status example
  • Example#2366 - Using pg_pconnect
  • Example#2367 - pg_ping example
  • Example#2368 - pg_port example
  • Example#2369 - Using pg_prepare
  • Example#2370 - pg_put_line example
  • Example#2371 - Using pg_query_params
  • Example#2372 - pg_query example
  • Example#2373 - Using pg_query with multiple statements
  • Example#2374 - pg_result_error_field example
  • Example#2375 - pg_result_error example
  • Example#2376 - pg_result_seek example
  • Example#2377 - pg_result_status example
  • Example#2378 - pg_select example
  • Example#2379 - Using pg_send_execute
  • Example#2380 - Using pg_send_prepare
  • Example#2381 - Using pg_send_query_params
  • Example#2382 - pg_send_query example
  • Example#2383 - pg_set_client_encoding example
  • Example#2384 - pg_set_error_verbosity example
  • Example#2385 - pg_trace example
  • Example#2386 - pg_transaction_status example
  • Example#2387 - pg_tty example
  • Example#2388 - pg_unescape_bytea example
  • Example#2389 - pg_untrace example
  • Example#2390 - pg_update example
  • Example#2391 - pg_version example
  • Example#2392 - Stil procedural
  • Example#2393 - Object-oriented style
  • Example#2394 - Stil procedural
  • Example#2395 - Stil obiect-orientat
  • Example#2396 - Stil procedural
  • Example#2397 - Stil obiect-orientat
  • Example#2398 - sqlite_close example
  • Example#2399 - max_length aggregation function example
  • Example#2400 - sqlite_create_function example
  • Example#2401 - Example of using the PHP function
  • Example#2402 - Procedural example
  • Example#2403 - Object-oriented example
  • Example#2404 - sqlite_factory example
  • Example#2405 - Procedural example
  • Example#2406 - Object-oriented example
  • Example#2407 - Procedural example
  • Example#2408 - Object-oriented example
  • Example#2409 - Procedural example
  • Example#2410 - Object-oriented example
  • Example#2411 - A sqlite_fetch_single example
  • Example#2412 - Procedural example
  • Example#2413 - Object-oriented example
  • Example#2414 - sqlite_open example
  • Example#2415 - binary-safe max_length aggregation function example
  • Example#2416 - SQLite3::changes example
  • Example#2417 - SQLite3::close example
  • Example#2418 - SQLite3::__construct example
  • Example#2419 - SQLite3::createCollation example
  • Example#2420 - SQLite3::createFunction example
  • Example#2421 - SQLite3::enableExceptions example
  • Example#2422 - SQLite3::exec example
  • Example#2423 - SQLite3::loadExtension example
  • Example#2424 - SQLite3::open example
  • Example#2425 - SQLite3::openBlob example
  • Example#2426 - SQLite3::prepare example
  • Example#2427 - SQLite3::query example
  • Example#2428 - SQLite3::querySingle example
  • Example#2429 - SQLite3::version example
  • Example#2430 - SQLite3Stmt::bindValue example
  • Example#2431 - sqlsrv_begin_transaction example
  • Example#2432 - sqlsrv_cancel example
  • Example#2433 - sqlsrv_client_info example
  • Example#2434 - sqlsrv_close example
  • Example#2435 - sqlsrv_commit example
  • Example#2436 - Connect using Windows Authentication.
  • Example#2437 - Connect by specifying a user name and password.
  • Example#2438 - Connect on a specifed port.
  • Example#2439 - functionname example
  • Example#2440 - sqlsrv_execute example
  • Example#2441 - Retrieving an associative array.
  • Example#2442 - Retrieving a numeric array.
  • Example#2443 - sqlsrv_fetch_object example
  • Example#2444 - sqlsrv_fetch example
  • Example#2445 - sqlsrv_field_metadata example
  • Example#2446 - sqlsrv_free_stmt example
  • Example#2447 - sqlsrv_get_field example
  • Example#2448 - sqlsrv_has_rows example
  • Example#2449 - sqlsrv_next_result example
  • Example#2450 - sqlsrv_num_fields example
  • Example#2451 - sqlsrv_num_rows example
  • Example#2452 - sqlsrv_prepare example
  • Example#2453 - sqlsrv_query example
  • Example#2454 - sqlsrv_rollback example
  • Example#2455 - sqlsrv_rows_affected example
  • Example#2456 - sqlsrv_send_stream_data example
  • Example#2457 - sqlsrv_server_info example
  • Example#2458 - Delete-Query
  • Example#2459 - sybase_connect example
  • Example#2460 - Identical fieldnames
  • Example#2461 - sybase_fetch_object return as Foo
  • Example#2462 - sybase_set_message_handler callback function
  • Example#2463 - sybase_set_message_handler callback to a class
  • Example#2464 - sybase_set_message_handler unhandled messages
  • Example#2465 - sybase_unbuffered_query example
  • Example#2466 - Stabilirea ?i ob?inerea perechilor cheie-valoare
  • Example#2467 - TokyoTyrant::add example
  • Example#2468 - TokyoTyrant::connect example
  • Example#2469 - TokyoTyrant::connectUri example
  • Example#2470 - TokyoTyrant::copy example
  • Example#2471 - TokyoTyrant::ext example
  • Example#2472 - TokyoTyrant::fwmKeys example
  • Example#2473 - TokyoTyrant::get example
  • Example#2474 - TokyoTyrant::getIterator example
  • Example#2475 - TokyoTyrant::num example
  • Example#2476 - TokyoTyrant::out example
  • Example#2477 - TokyoTyrant::put example
  • Example#2478 - TokyoTyrant::putCat example
  • Example#2479 - tokyotyrant::putKeep example
  • Example#2480 - TokyoTyrant::putNr example
  • Example#2481 - TokyoTyrant::putShl example
  • Example#2482 - TokyoTyrant::setMaster example
  • Example#2483 - TokyoTyrant::size example
  • Example#2484 - TokyoTyrant::stat example
  • Example#2485 - TokyoTyrant::vanish example
  • Example#2486 - TokyoTyrantTable::genUid example
  • Example#2487 - TokyoTyrantTable::get example
  • Example#2488 - TokyoTyrantTable::getIterator example
  • Example#2489 - TokyoTyrantTable::getQuery example
  • Example#2490 - TokyoTyrantTable::out example
  • Example#2491 - TokyoTyrantTable::put example
  • Example#2492 - TokyoTyrantTable::putCat example
  • Example#2493 - TokyoTyrantTable::putKeep example
  • Example#2494 - TokyoTyrantQuery::addCond example
  • Example#2495 - TokyoTyrantQuery::__construct example
  • Example#2496 - TokyoTyrantQuery::count example
  • Example#2497 - TokyoTyrantQuery iterator example
  • Example#2498 - TokyoTyrantQuery::hint example
  • Example#2499 - TokyoTyrantQuery iterator example
  • Example#2500 - TokyoTyrantQuery::metaSearch example
  • Example#2501 - TokyoTyrantQuery iterator example
  • Example#2502 - TokyoTyrantQuery::out example
  • Example#2503 - TokyoTyrantQuery iterator example
  • Example#2504 - TokyoTyrantQuery::search example
  • Example#2505 - TokyoTyrantQuery iterator example
  • Example#2506 - TokyoTyrantIterator::__construct example
  • Example#2507 - cal_days_in_month example
  • Example#2508 - cal_from_jd example
  • Example#2509 - cal_info example
  • Example#2510 - easter_date example
  • Example#2511 - easter_days example
  • Example#2512 - Calendar functions
  • Example#2513 - jdtojewish Example
  • Example#2514 - DateTime::add/sub add intervals which cover elapsed time
  • Example#2515 - DateTime::modify and strtotime increment or decrement individual component values
  • Example#2516 - Adding or subtracting times can over- or underflow dates
  • Example#2517 - DateTime::add example
  • Example#2518 - Further DateTime::add examples
  • Example#2519 - Beware when adding months
  • Example#2520 - DateTime::__construct example
  • Example#2521 - Intricacies of DateTime::__construct
  • Example#2522 - DateTime::createFromFormat example
  • Example#2523 - Intricacies of DateTime::createFromFormat
  • Example#2524 - Format string with literal characters
  • Example#2525 - DateTime::getLastErrors example
  • Example#2526 - DateTime::modify example
  • Example#2527 - Beware when adding or subtracting months
  • Example#2528 - DateTime::setDate example
  • Example#2529 - Values exceeding ranges are added to their parent values
  • Example#2530 - DateTime::setISODate example
  • Example#2531 - Values exceeding ranges are added to their parent values
  • Example#2532 - Finding the month a week is in
  • Example#2533 - DateTime::setTime example
  • Example#2534 - Values exceeding ranges are added to their parent values
  • Example#2535 - DateTime::setTimestamp example
  • Example#2536 - DateTime::setTimestamp alternative in PHP 5.2
  • Example#2537 - DateTime::setTimeZone example
  • Example#2538 - DateTime::sub example
  • Example#2539 - Further DateTime::sub examples
  • Example#2540 - Beware when subtracting months
  • Example#2541 - Creating an immutable date time object
  • Example#2542 - DateTime::diff example
  • Example#2543 - DateTime object comparison
  • Example#2544 - DateTime::format example
  • Example#2545 - DateTime::getOffset example
  • Example#2546 - DateTime::getTimestamp example
  • Example#2547 - DateTime::getTimezone example
  • Example#2548 - Catching errors when instantiating DateTimeZone
  • Example#2549 - DateTimeZone::getLocation example
  • Example#2550 - DateTimeZone::getOffset examples
  • Example#2551 - A timezone_transitions_get example
  • Example#2552 - A timezone_abbreviations_list example
  • Example#2553 - A timezone_identifiers_list example
  • Example#2554 - DateInterval example
  • Example#2555 - Parsing valid date intervals
  • Example#2556 - DateInterval example
  • Example#2557 - DateInterval and carry over points
  • Example#2558 - DateInterval and DateTime::diff with the %a and %d modifiers
  • Example#2559 - DatePeriod example
  • Example#2560 - DatePeriod example with DatePeriod::EXCLUDE_START_DATE
  • Example#2561 - DatePeriod::getDateInterval example
  • Example#2562 - DatePeriod::getEndDate example
  • Example#2563 - DatePeriod::getEndDate without an end date
  • Example#2564 - DatePeriod::getStartDate example
  • Example#2565 - Exemplu checkdate
  • Example#2566 - Getting the default timezone
  • Example#2567 - Getting the abbreviation of a timezone
  • Example#2568 - Getting the default timezone
  • Example#2569 - date_parse_from_format example
  • Example#2570 - A date_parse example
  • Example#2571 - date_parse with relative formats
  • Example#2572 - A date_sun_info example
  • Example#2573 - date_sunrise example
  • Example#2574 - date_sunset example
  • Example#2575 - Exemple date
  • Example#2576 - Evadarea caracterelor în date
  • Example#2577 - Exemplu date ?i mktime
  • Example#2578 - Formatarea date
  • Example#2579 - Exemplu getdate
  • Example#2580 - Exemplu gettimeofday
  • Example#2581 - Exemple gmdate
  • Example#2582 - Exemplu simplu gmmktime
  • Example#2583 - Exemplu gmstrftime
  • Example#2584 - idate example
  • Example#2585 - Exemplu localtime
  • Example#2586 - Masurarea timpului de execu?ie a script-ului cu ajutorul microtime
  • Example#2587 - Masurarea timpului de execu?ie a script-ului în PHP 5
  • Example#2588 - microtime ?i REQUEST_TIME_FLOAT (începând cu PHP 5.4.0)
  • Example#2589 - Exemplu simplu mktime
  • Example#2590 - Exemple mktime
  • Example#2591 - Ultima zi a lunii
  • Example#2592 - Exemple strftime
  • Example#2593 - Exemplu al numerelor saptamânilor conform standardului ISO 8601:1988
  • Example#2594 - Un exemplu de func?ie compatibila pe mai multe platforme, ce utilizeaza modificatorul %e
  • Example#2595 - Afi?eaza toate formatele cunoscute ?i necunoscute.
  • Example#2596 - strptime example
  • Example#2597 - Exemplu strtotime
  • Example#2598 - Verificarea e?ecului
  • Example#2599 - Exemplu time
  • Example#2600 - A timezone_name_from_abbr example
  • Example#2601 - Getting the timezonedb version
  • Example#2602 - Measure several code blocks execution and get the total
  • Example#2603 - Closing an open file descriptor
  • Example#2604 - Setting and clearing a lock
  • Example#2605 - Opening a file descriptor
  • Example#2606 - Positioning in a file
  • Example#2607 - Setting the baud rate on a serial port
  • Example#2608 - chdir example
  • Example#2609 - chroot example
  • Example#2610 - closedir example
  • Example#2611 - dir example
  • Example#2612 - getcwd example
  • Example#2613 - opendir example
  • Example#2614 - List all entries in a directory
  • Example#2615 - List all entries in the current directory and strip out . and ..
  • Example#2616 - A simple scandir example
  • Example#2617 - PHP 4 alternatives to scandir
  • Example#2618 - A finfo_buffer example
  • Example#2619 - A finfo_file example
  • Example#2620 - Stil obiect-orientat
  • Example#2621 - Stil procedural
  • Example#2622 - mime_content_type Example
  • Example#2623 - basename example
  • Example#2624 - Changing a file's group
  • Example#2625 - Simple chown usage
  • Example#2626 - clearstatcache example
  • Example#2627 - copy example
  • Example#2628 - dirname example
  • Example#2629 - disk_free_space example
  • Example#2630 - disk_total_space example
  • Example#2631 - A simple fclose example
  • Example#2632 - Handling timeouts with feof
  • Example#2633 - feof example with an invalid file pointer
  • Example#2634 - File write example using fflush
  • Example#2635 - A fgetc example
  • Example#2636 - Read and print the entire contents of a CSV file
  • Example#2637 - Reading a file line by line
  • Example#2638 - Reading a PHP file line-by-line
  • Example#2639 - Testing whether a file exists
  • Example#2640 - Get and output the source of the homepage of a website
  • Example#2641 - Searching within the include_path
  • Example#2642 - Reading a section of a file
  • Example#2643 - Using stream contexts
  • Example#2644 - Simple usage example
  • Example#2645 - Using flags
  • Example#2646 - file example
  • Example#2647 - fileatime example
  • Example#2648 - A filectime example
  • Example#2649 - Finding the group of a file
  • Example#2650 - Comparing the inode of a file with the current file
  • Example#2651 - filemtime example
  • Example#2652 - Finding the owner of a file
  • Example#2653 - Display permissions as an octal value
  • Example#2654 - Display full permissions
  • Example#2655 - filesize example
  • Example#2656 - filetype example
  • Example#2657 - flock example
  • Example#2658 - flock using the LOCK_NB option
  • Example#2659 - Checking a color name against a shell wildcard pattern
  • Example#2660 - fopen examples
  • Example#2661 - Using fpassthru with binary files
  • Example#2662 - fputcsv example
  • Example#2663 - A simple fread example
  • Example#2664 - Binary fread example
  • Example#2665 - Remote fread examples
  • Example#2666 - fscanf Example
  • Example#2667 - Contents of users.txt
  • Example#2668 - fseek example
  • Example#2669 - fstat example
  • Example#2670 - ftell example
  • Example#2671 - File truncation example
  • Example#2672 - A simple fwrite example
  • Example#2673 - Convenient way how glob can replace opendir and friends.
  • Example#2674 - is_dir example
  • Example#2675 - is_executable example
  • Example#2676 - is_file example
  • Example#2677 - Create and confirm if a file is a symbolic link
  • Example#2678 - is_readable example
  • Example#2679 - is_uploaded_file example
  • Example#2680 - is_writable example
  • Example#2681 - Changing the group of a symbolic link
  • Example#2682 - Changing the owner of a symbolic link
  • Example#2683 - Creating a simple hard link
  • Example#2684 - linkinfo example
  • Example#2685 - Comparison of stat and lstat
  • Example#2686 - mkdir example
  • Example#2687 - mkdir using the recursive parameter
  • Example#2688 - Uploading multiple files
  • Example#2689 - Contents of sample.ini
  • Example#2690 - parse_ini_file example
  • Example#2691 - parse_ini_file parsing a php.ini file
  • Example#2692 - pathinfo Example
  • Example#2693 - pathinfo example showing difference between null and no extension
  • Example#2694 - pathinfo example for a dot-file
  • Example#2695 - pclose example
  • Example#2696 - popen example
  • Example#2697 - popen example
  • Example#2698 - Forcing a download using readfile
  • Example#2699 - readlink example
  • Example#2700 - realpath_cache_get example
  • Example#2701 - realpath_cache_size example
  • Example#2702 - realpath example
  • Example#2703 - realpath on Windows
  • Example#2704 - Example with rename
  • Example#2705 - rewind overwriting example
  • Example#2706 - rmdir example
  • Example#2707 - stat example
  • Example#2708 - Using stat information together with touch
  • Example#2709 - Create a symbolic link
  • Example#2710 - tempnam example
  • Example#2711 - tmpfile example
  • Example#2712 - touch example
  • Example#2713 - touch using the time parameter
  • Example#2714 - umask example
  • Example#2715 - Basic unlink usage
  • Example#2716 - Example usage of inotify
  • Example#2717 - Setting the path to magic.mime
  • Example#2718 - setproctitle example
  • Example#2719 - setthreadtitle example
  • Example#2720 - Checks if system administrator has signed the file
  • Example#2721 - Prints names of all extended attributes of file
  • Example#2722 - Removes all extended attributes of a file
  • Example#2723 - Sets extended attributes on .wav file
  • Example#2724 - xattr_supported example
  • Example#2725 - xdiff_file_bdiff_size example
  • Example#2726 - xdiff_file_bdiff example
  • Example#2727 - xdiff_file_bpatch example
  • Example#2728 - xdiff_file_diff_binary example
  • Example#2729 - xdiff_file_diff example
  • Example#2730 - xdiff_file_merge3 example
  • Example#2731 - xdiff_file_patch_binary example
  • Example#2732 - xdiff_file_patch example
  • Example#2733 - Patch reversing example
  • Example#2734 - xdiff_file_rabdiff example
  • Example#2735 - xdiff_string_bdiff_size example
  • Example#2736 - xdiff_string_diff example
  • Example#2737 - xdiff_string_patch example
  • Example#2738 - Enchant Usage Example
  • Example#2739 - List the backends provided by the given broker
  • Example#2740 - A enchant_broker_dict_exists example
  • Example#2741 - List all available dictionaries for one broker
  • Example#2742 - A enchant_broker_request_dict example
  • Example#2743 - Adding a word to a PWL
  • Example#2744 - A enchant_dict_describe example
  • Example#2745 - A enchant_dict_quick_check example
  • Example#2746 - A enchant_dict_suggest example
  • Example#2747 - Usage example.
  • Example#2748 - Using Gender\Gender::country
  • Example#2749 - bindtextdomain example
  • Example#2750 - gettext-check
  • Example#2751 - ngettext example
  • Example#2752 - iconv_get_encoding example
  • Example#2753 - iconv_mime_decode_headers example
  • Example#2754 - iconv_mime_decode example
  • Example#2755 - iconv_mime_encode example
  • Example#2756 - iconv_set_encoding example
  • Example#2757 - iconv example
  • Example#2758 - ob_iconv_handler example:
  • Example#2759 - Example of using the procedural API
  • Example#2760 - Example of using the object-oriented API
  • Example#2761 - FRENCH_COLLATION rules
  • Example#2762 - ALTERNATE_HANDLING rules
  • Example#2763 - CASE_FIRST rules
  • Example#2764 - CASE_LEVEL rules
  • Example#2765 - collator_asortexample
  • Example#2766 - collator_compareexample
  • Example#2767 - Collator::__construct example
  • Example#2768 - collator_create example
  • Example#2769 - collator_get_attribute example
  • Example#2770 - collator_get_error_code example
  • Example#2771 - collator_get_error_message example
  • Example#2772 - collator_get_locale example
  • Example#2773 - collator_get_sort_keyexample
  • Example#2774 - collator_get_strength example
  • Example#2775 - collator_set_attribute example
  • Example#2776 - collator_set_strength example
  • Example#2777 - collator_sort_with_sort_keys example
  • Example#2778 - collator_sort example
  • Example#2779 - numfmt_create example
  • Example#2780 - NumberFormatter::create example
  • Example#2781 - numfmt_format_currency example
  • Example#2782 - OO example
  • Example#2783 - numfmt_format example
  • Example#2784 - OO example
  • Example#2785 - numfmt_get_attribute example
  • Example#2786 - OO example
  • Example#2787 - numfmt_get_error_code example
  • Example#2788 - OO example
  • Example#2789 - numfmt_get_error_message example
  • Example#2790 - OO example
  • Example#2791 - numfmt_get_locale example
  • Example#2792 - numfmt_get_pattern example
  • Example#2793 - OO example
  • Example#2794 - numfmt_get_symbol example
  • Example#2795 - OO example
  • Example#2796 - numfmt_get_text_attribute example
  • Example#2797 - OO example
  • Example#2798 - numfmt_parse_currency example
  • Example#2799 - OO example
  • Example#2800 - numfmt_parse example
  • Example#2801 - OO example
  • Example#2802 - numfmt_set_attribute example
  • Example#2803 - OO example
  • Example#2804 - numfmt_set_pattern example
  • Example#2805 - OO example
  • Example#2806 - numfmt_set_symbol example
  • Example#2807 - OO example
  • Example#2808 - numfmt_set_text_attribute example
  • Example#2809 - OO example
  • Example#2810 - locale_accept_from_http example
  • Example#2811 - OO example
  • Example#2812 - locale_compose example
  • Example#2813 - OO example
  • Example#2814 - locale_filter_matches example
  • Example#2815 - OO example
  • Example#2816 - locale_get_all_variants example
  • Example#2817 - OO example
  • Example#2818 - locale_get_default example
  • Example#2819 - OO example
  • Example#2820 - locale_get_display_language example
  • Example#2821 - OO example
  • Example#2822 - locale_get_display_name example
  • Example#2823 - OO example
  • Example#2824 - locale_get_display_region example
  • Example#2825 - OO example
  • Example#2826 - locale_get_display_script example
  • Example#2827 - OO example
  • Example#2828 - locale_get_display_variant example
  • Example#2829 - OO example
  • Example#2830 - locale_get_keywords example
  • Example#2831 - OO example
  • Example#2832 - locale_get_primary_language example
  • Example#2833 - OO example
  • Example#2834 - locale_get_region example
  • Example#2835 - OO example
  • Example#2836 - locale_get_script example
  • Example#2837 - OO example
  • Example#2838 - locale_lookup example
  • Example#2839 - OO example
  • Example#2840 - locale_parse example
  • Example#2841 - OO example
  • Example#2842 - locale_set_default example
  • Example#2843 - OO example
  • Example#2844 - normalizer_is_normalized example
  • Example#2845 - OO example
  • Example#2846 - normalizer_normalize example
  • Example#2847 - OO example
  • Example#2848 - msgfmt_create example
  • Example#2849 - OO example
  • Example#2850 - msgfmt_format_message example
  • Example#2851 - OO example
  • Example#2852 - msgfmt_format example
  • Example#2853 - OO example
  • Example#2854 - msgfmt_get_error_code example
  • Example#2855 - OO example
  • Example#2856 - msgfmt_get_error_message example
  • Example#2857 - OO example
  • Example#2858 - msgfmt_get_locale example
  • Example#2859 - OO example
  • Example#2860 - msgfmt_get_pattern example
  • Example#2861 - OO example
  • Example#2862 - msgfmt_parse_message example
  • Example#2863 - OO example
  • Example#2864 - msgfmt_parse example
  • Example#2865 - OO example
  • Example#2866 - msgfmt_set_pattern example
  • Example#2867 - OO example
  • Example#2868 - IntlCalendar::add
  • Example#2869 - IntlCalendar::after
  • Example#2870 - IntlCalendar::clear examples
  • Example#2871 - IntlCalendar::createInstance
  • Example#2872 - IntlCalendar::equals
  • Example#2873 - IntlCalendar::fieldDifference
  • Example#2874 - IntlCalendar::fromDateTime
  • Example#2875 - IntlCalendar::get
  • Example#2876 - IntlCalendar::getActualMaximum
  • Example#2877 - IntlCalendar::getAvailableLocales()
  • Example#2878 - IntlCalendar::getDayOfWeekType
  • Example#2879 - IntlCalendar::getErrorCode and IntlCalendar::getErrorMessage
  • Example#2880 - IntlCalendar::getErrorMessage
  • Example#2881 - IntlCalendar::getFirstDayOfWeek
  • Example#2882 - IntlCalendar::getKeyworkValuesForLocale
  • Example#2883 - Maxima examples
  • Example#2884 - IntlCalendar::getLocale
  • Example#2885 - IntlCalendar::getMinimalDaysInFirstWeek
  • Example#2886 - IntlCalendar::getNow
  • Example#2887 - IntlCalendar::getRepeatedWallTimeOption
  • Example#2888 - IntlCalendar::getSkippedWallTimeOption
  • Example#2889 - IntlCalendar::getTime
  • Example#2890 - IntlCalendar::getTimeZone
  • Example#2891 - IntlCalendar::getType
  • Example#2892 - IntlCalendar::inDaylightTime
  • Example#2893 - IntlCalendar::isEquivalentTo
  • Example#2894 - IntlCalendar::isLenient
  • Example#2895 - IntlCalendar::isWeekend
  • Example#2896 - IntlCalendar::roll
  • Example#2897 - IntlCalendar::set
  • Example#2898 - IntlCalendar::setFirstDayOfWeek
  • Example#2899 - IntlCalendar::setTime
  • Example#2900 - IntlCalendar::setTimeZone
  • Example#2901 - IntlCalendar::toDateTime
  • Example#2902 - datefmt_create example
  • Example#2903 - OO example
  • Example#2904 - datefmt_format example
  • Example#2905 - OO example
  • Example#2906 - With IntlCalendar object
  • Example#2907 - IntlDateFormatter::formatObject examples
  • Example#2908 - datefmt_get_calendar example
  • Example#2909 - OO example
  • Example#2910 - datefmt_get_datetype example
  • Example#2911 - OO example
  • Example#2912 - datefmt_get_error_code example
  • Example#2913 - OO example
  • Example#2914 - datefmt_get_error_message example
  • Example#2915 - OO example
  • Example#2916 - datefmt_get_locale example
  • Example#2917 - OO example
  • Example#2918 - datefmt_get_pattern example
  • Example#2919 - OO example
  • Example#2920 - datefmt_get_timetype example
  • Example#2921 - OO example
  • Example#2922 - datefmt_get_timezone_id example
  • Example#2923 - OO example
  • Example#2924 - IntlDateFormatter::getCalendarObject example
  • Example#2925 - IntlDateFormatter::getTimeZone examples
  • Example#2926 - datefmt_is_lenient example
  • Example#2927 - OO example
  • Example#2928 - datefmt_localtime example
  • Example#2929 - OO example
  • Example#2930 - OO example
  • Example#2931 - datefmt_parse example
  • Example#2932 - datefmt_set_calendar example
  • Example#2933 - OO example
  • Example#2934 - Example with IntlCalendar argument
  • Example#2935 - datefmt_set_lenient example
  • Example#2936 - OO example
  • Example#2937 - datefmt_set_pattern example
  • Example#2938 - OO example
  • Example#2939 - datefmt_set_timezone_id example
  • Example#2940 - OO example
  • Example#2941 - IntlDateFormatter::setTimeZone examples
  • Example#2942 - resourcebundle_count example
  • Example#2943 - OO example
  • Example#2944 - resourcebundle_create example
  • Example#2945 - ResourceBundle::create example
  • Example#2946 - resourcebundle_get_error_code example
  • Example#2947 - OO example
  • Example#2948 - resourcebundle_get_error_message example
  • Example#2949 - OO example
  • Example#2950 - resourcebundle_get example
  • Example#2951 - OO example
  • Example#2952 - resourcebundle_locales example
  • Example#2953 - OO example
  • Example#2954 - Spoofchecker::areConfusable example
  • Example#2955 - Spoofchecker::isSuspicious example
  • Example#2956 - Converting escaped UTF-16 code units
  • Example#2957 - grapheme_extract example
  • Example#2958 - grapheme_stripos example
  • Example#2959 - grapheme_stristr example
  • Example#2960 - grapheme_strlen example
  • Example#2961 - grapheme_strpos example
  • Example#2962 - grapheme_strripos example
  • Example#2963 - grapheme_strrpos example
  • Example#2964 - grapheme_strstr example
  • Example#2965 - grapheme_substr example
  • Example#2966 - idn_to_ascii example
  • Example#2967 - idn_to_utf8 example
  • Example#2968 - Testarea diferitor code points
  • Example#2969 - Testarea diferitor code points
  • Example#2970 - Testarea diferitor code points
  • Example#2971 - Testarea diferitor code points
  • Example#2972 - Testarea diferitor code points
  • Example#2973 - Testarea diferitor code points
  • Example#2974 - Testarea diferitor code points
  • Example#2975 - Testarea diferitor code points
  • Example#2976 - Testarea diferitor code points
  • Example#2977 - Enumerating over a sample range of code points
  • Example#2978 - Enumerating over a sample range of code points
  • Example#2979 - Testarea diferitor code points
  • Example#2980 - Testarea diferitor code points
  • Example#2981 - Testarea diferitor code points
  • Example#2982 - Testarea diferitor code points
  • Example#2983 - Testarea diferitor code points
  • Example#2984 - Testarea diferitor proprieta?i
  • Example#2985 - Testarea diferitor proprieta?i
  • Example#2986 - Testarea diferitor proprieta?i
  • Example#2987 - Testarea diferitor code points
  • Example#2988 - Testarea diferitor proprieta?i
  • Example#2989 - Testarea diferitor proprieta?i
  • Example#2990 - Testarea diferitor proprieta?i
  • Example#2991 - Testarea diferitor proprieta?i
  • Example#2992 - Testarea diferitor proprieta?i
  • Example#2993 - Testarea diferitor proprieta?i
  • Example#2994 - Testarea diferitor code points
  • Example#2995 - Testarea diferitor code points
  • Example#2996 - Testarea diferitor code points
  • Example#2997 - Testarea diferitor code points
  • Example#2998 - Testarea diferitor code points
  • Example#2999 - Testarea diferitor code points
  • Example#3000 - Testarea diferitor code points
  • Example#3001 - Testarea diferitor code points
  • Example#3002 - Testarea diferitor code points
  • Example#3003 - Testarea diferitor code points
  • Example#3004 - Testarea diferitor code points
  • Example#3005 - Testarea diferitor code points
  • Example#3006 - Testarea diferitor code points
  • Example#3007 - Testarea diferitor code points
  • Example#3008 - Testarea diferitor code points
  • Example#3009 - Testarea diferitor code points
  • Example#3010 - Testarea diferitor code points
  • Example#3011 - Testarea diferitor code points
  • Example#3012 - Testarea diferitor code points
  • Example#3013 - Testarea diferitor code points
  • Example#3014 - Testarea diferitor code points
  • Example#3015 - Testarea diferitor code points
  • Example#3016 - Testarea diferitor code points
  • Example#3017 - Testarea diferitor code points
  • Example#3018 - Testarea diferitor code points
  • Example#3019 - Testarea diferitor code points
  • Example#3020 - Testarea diferitor code points
  • Example#3021 - Testarea diferitor code points
  • Example#3022 - Testarea diferitor code points
  • Example#3023 - Testarea diferitor code points
  • Example#3024 - Testarea diferitor code points
  • Example#3025 - Testarea diferitor code points
  • Example#3026 - intl_error_name example
  • Example#3027 - intl_get_error_code example
  • Example#3028 - intl_get_error_message example
  • Example#3029 - intl_is_failure example
  • Example#3030 - exemple de setari în php.ini
  • Example#3031 - setari în php.ini pentru utilizatorii EUC-JP
  • Example#3032 - setari în php.ini pentru utilizatorii SJIS
  • Example#3033 - Disable HTTP input conversion in php.ini
  • Example#3034 - php.ini setting example
  • Example#3035 - Script example
  • Example#3036 - mb_convert_case example
  • Example#3037 - mb_convert_case example with non-Latin UTF-8 text
  • Example#3038 - mb_convert_encoding example
  • Example#3039 - mb_convert_kana example
  • Example#3040 - mb_convert_variables example
  • Example#3041 - convmap example
  • Example#3042 - convmap example escapes JavaScript string
  • Example#3043 - mb_detect_encoding example
  • Example#3044 - mb_detect_order examples
  • Example#3045 - Example showing useless detect orders
  • Example#3046 - mb_encode_mimeheader example
  • Example#3047 - convmap example
  • Example#3048 - mb_encode_numericentity example
  • Example#3049 - mb_encoding_aliases example
  • Example#3050 - mb_ereg_replace_callback example
  • Example#3051 - mb_ereg_replace_callback using anonymous function supported in PHP 5.3.0 or later
  • Example#3052 - mb_internal_encoding example
  • Example#3053 - mb_list_encodings example
  • Example#3054 - mb_output_handler example
  • Example#3055 - mb_preferred_mime_name example
  • Example#3056 - mb_strimwidth example
  • Example#3057 - mb_strtolower example
  • Example#3058 - mb_strtolower example with non-Latin UTF-8 text
  • Example#3059 - mb_strtoupper example
  • Example#3060 - mb_strtoupper example with non-Latin UTF-8 text
  • Example#3061 - mb_substitute_character example
  • Example#3062 - mb_substr_count example
  • Example#3063 - pspell_add_to_personal
  • Example#3064 - pspell_check Example
  • Example#3065 - pspell_add_to_personal Example
  • Example#3066 - pspell_config_create
  • Example#3067 - pspell_config_ignore
  • Example#3068 - pspell_config_mode Example
  • Example#3069 - pspell_config_personal
  • Example#3070 - pspell_config_repl
  • Example#3071 - pspell_config_runtogether
  • Example#3072 - pspell_new_config
  • Example#3073 - pspell_new_personal
  • Example#3074 - pspell_new
  • Example#3075 - pspell_add_to_personal
  • Example#3076 - pspell_store_replacement
  • Example#3077 - pspell_suggest example
  • Example#3078 - Basic recode_file example
  • Example#3079 - Basic recode_string example
  • Example#3080 - Exemplu Cairo
  • Example#3081 - cairo_create example
  • Example#3082 - cairo_font_face_get_type example
  • Example#3083 - cairo_font_face_status example
  • Example#3084 - cairo_font_options_create example
  • Example#3085 - cairo_font_options_equal example
  • Example#3086 - cairo_font_options_get_antialias example
  • Example#3087 - cairo_font_options_get_hint_metrics example
  • Example#3088 - cairo_font_options_get_hint_style example
  • Example#3089 - cairo_font_options_get_subpixel_order example
  • Example#3090 - cairo_font_options_hash example
  • Example#3091 - cairo_font_options_merge example
  • Example#3092 - cairo_font_options_set_antialias example
  • Example#3093 - cairo_font_options_set_hint_metrics example
  • Example#3094 - cairo_font_options_set_hint_style example
  • Example#3095 - cairo_font_options_set_subpixel_order example
  • Example#3096 - cairo_font_options_status example
  • Example#3097 - cairo_format_stride_for_width example
  • Example#3098 - cairo_image_surface_create_for_data example
  • Example#3099 - cairo_image_surface_create_from_png example
  • Example#3100 - cairo_image_surface_create example
  • Example#3101 - cairo_image_surface_get_data example
  • Example#3102 - cairo_image_surface_get_format example
  • Example#3103 - cairo_image_surface_get_height example
  • Example#3104 - cairo_image_surface_get_stride example
  • Example#3105 - cairo_image_surface_get_width example
  • Example#3106 - cairo_matrix_invert example
  • Example#3107 - cairo_matrix_multiply example
  • Example#3108 - cairo_matrix_rotate example
  • Example#3109 - cairo_matrix_transform_distance example
  • Example#3110 - cairo_matrix_transform_point example
  • Example#3111 - cairo_matrix_translate example
  • Example#3112 - cairo_pattern_add_color_stop_rgb example
  • Example#3113 - cairo_pattern_add_color_stop_rgba example
  • Example#3114 - cairo_pattern_create_for_surface example
  • Example#3115 - cairo_pattern_create_linear example
  • Example#3116 - cairo_pattern_create_radial example
  • Example#3117 - cairo_pattern_create_rgb example
  • Example#3118 - cairo_pattern_create_rgba example
  • Example#3119 - cairo_pattern_get_color_stop_count example
  • Example#3120 - cairo_pattern_get_color_stop_rgba example
  • Example#3121 - cairo_pattern_get_extend example
  • Example#3122 - cairo_pattern_get_filter example
  • Example#3123 - cairo_pattern_get_linear_points example
  • Example#3124 - cairo_pattern_get_matrix example
  • Example#3125 - cairo_pattern_get_radial_circles example
  • Example#3126 - cairo_pattern_get_rgba example
  • Example#3127 - cairo_pattern_get_surface example
  • Example#3128 - cairo_pattern_get_type example
  • Example#3129 - cairo_pattern_set_extend example
  • Example#3130 - cairo_pattern_set_filter example
  • Example#3131 - cairo_pattern_set_matrix example
  • Example#3132 - cairo_pattern_status example
  • Example#3133 - cairo_pdf_surface_create example
  • Example#3134 - cairo_pdf_surface_set_size example
  • Example#3135 - cairo_ps_get_levels example
  • Example#3136 - cairo_ps_level_to_string example
  • Example#3137 - cairo_ps_surface_create example
  • Example#3138 - cairo_ps_surface_dsc_begin_page_setup example
  • Example#3139 - cairo_ps_surface_dsc_begin_setup example
  • Example#3140 - cairo_ps_surface_dsc_comment example
  • Example#3141 - cairo_ps_surface_get_eps example
  • Example#3142 - cairo_ps_surface_restrict_to_level example
  • Example#3143 - cairo_ps_surface_set_eps example
  • Example#3144 - cairo_ps_surface_set_size example
  • Example#3145 - cairo_scaled_font_create example
  • Example#3146 - cairo_scaled_font_extents example
  • Example#3147 - cairo_scaled_font_get_ctm example
  • Example#3148 - cairo_scaled_font_get_font_face example
  • Example#3149 - cairo_scaled_font_get_font_matrix example
  • Example#3150 - cairo_scaled_font_get_font_options example
  • Example#3151 - cairo_scaled_font_get_scale_matrix example
  • Example#3152 - cairo_scaled_font_get_type example
  • Example#3153 - cairo_scaled_font_glyph_extents example
  • Example#3154 - cairo_scaled_font_status example
  • Example#3155 - cairo_scaled_font_text_extents example
  • Example#3156 - cairo_surface_copy_page example
  • Example#3157 - cairo_surface_create_similar example
  • Example#3158 - cairo_surface_finish example
  • Example#3159 - cairo_surface_flush example
  • Example#3160 - cairo_surface_get_content example
  • Example#3161 - cairo_surface_get_device_offset example
  • Example#3162 - cairo_surface_get_font_options example
  • Example#3163 - cairo_surface_get_type example
  • Example#3164 - cairo_surface_mark_dirty_rectangle example
  • Example#3165 - cairo_surface_mark_dirty example
  • Example#3166 - cairo_surface_set_device_offset example
  • Example#3167 - cairo_surface_set_fallback_resolution example
  • Example#3168 - cairo_surface_show_page example
  • Example#3169 - cairo_surface_status example
  • Example#3170 - cairo_surface_write_to_png example
  • Example#3171 - cairo_svg_surface_create example
  • Example#3172 - cairo_svg_surface_restrict_to_version example
  • Example#3173 - cairo_svg_version_to_string example
  • Example#3174 - Stil obiect-orientat
  • Example#3175 - Stil procedural
  • Example#3176 - Stil obiect-orientat
  • Example#3177 - Stil procedural
  • Example#3178 - Stil obiect-orientat
  • Example#3179 - Stil procedural
  • Example#3180 - Stil obiect-orientat
  • Example#3181 - Stil procedural
  • Example#3182 - Stil obiect-orientat
  • Example#3183 - Stil procedural
  • Example#3184 - Stil obiect-orientat
  • Example#3185 - Stil procedural
  • Example#3186 - Stil obiect-orientat
  • Example#3187 - Stil procedural
  • Example#3188 - Stil obiect-orientat
  • Example#3189 - Stil procedural
  • Example#3190 - Stil obiect-orientat
  • Example#3191 - Stil procedural
  • Example#3192 - Stil obiect-orientat
  • Example#3193 - Stil procedural
  • Example#3194 - Stil obiect-orientat
  • Example#3195 - Stil procedural
  • Example#3196 - Stil obiect-orientat
  • Example#3197 - Stil procedural
  • Example#3198 - Stil obiect-orientat
  • Example#3199 - Stil procedural
  • Example#3200 - CairoContext::__construct example
  • Example#3201 - Stil obiect-orientat
  • Example#3202 - Stil procedural
  • Example#3203 - Stil obiect-orientat
  • Example#3204 - Stil procedural
  • Example#3205 - Stil obiect-orientat
  • Example#3206 - Stil procedural
  • Example#3207 - Stil obiect-orientat
  • Example#3208 - Stil procedural
  • Example#3209 - Stil obiect-orientat
  • Example#3210 - Stil procedural
  • Example#3211 - Stil obiect-orientat
  • Example#3212 - Stil procedural
  • Example#3213 - Stil obiect-orientat
  • Example#3214 - Stil procedural
  • Example#3215 - Stil obiect-orientat
  • Example#3216 - Stil procedural
  • Example#3217 - Stil obiect-orientat
  • Example#3218 - Stil procedural
  • Example#3219 - Stil obiect-orientat
  • Example#3220 - Stil procedural
  • Example#3221 - Stil obiect-orientat
  • Example#3222 - Stil procedural
  • Example#3223 - Stil obiect-orientat
  • Example#3224 - Stil procedural
  • Example#3225 - Stil obiect-orientat
  • Example#3226 - Stil procedural
  • Example#3227 - Stil obiect-orientat
  • Example#3228 - Stil procedural
  • Example#3229 - Stil obiect-orientat
  • Example#3230 - Stil procedural
  • Example#3231 - Stil obiect-orientat
  • Example#3232 - Stil procedural
  • Example#3233 - Stil obiect-orientat
  • Example#3234 - Stil procedural
  • Example#3235 - Stil obiect-orientat
  • Example#3236 - Stil procedural
  • Example#3237 - Stil obiect-orientat
  • Example#3238 - Stil procedural
  • Example#3239 - Stil obiect-orientat
  • Example#3240 - Stil procedural
  • Example#3241 - Stil obiect-orientat
  • Example#3242 - Stil procedural
  • Example#3243 - Stil obiect-orientat
  • Example#3244 - Stil procedural
  • Example#3245 - Stil obiect-orientat
  • Example#3246 - Stil procedural
  • Example#3247 - Stil obiect-orientat
  • Example#3248 - Stil procedural
  • Example#3249 - Stil obiect-orientat
  • Example#3250 - Stil procedural
  • Example#3251 - Stil obiect-orientat
  • Example#3252 - Stil procedural
  • Example#3253 - Stil obiect-orientat
  • Example#3254 - Stil procedural
  • Example#3255 - Stil obiect-orientat
  • Example#3256 - Stil procedural
  • Example#3257 - Stil obiect-orientat
  • Example#3258 - Stil procedural
  • Example#3259 - Stil obiect-orientat
  • Example#3260 - Stil procedural
  • Example#3261 - Stil obiect-orientat
  • Example#3262 - Stil procedural
  • Example#3263 - Stil obiect-orientat
  • Example#3264 - Stil procedural
  • Example#3265 - Stil obiect-orientat
  • Example#3266 - Stil procedural
  • Example#3267 - Stil obiect-orientat
  • Example#3268 - Stil procedural
  • Example#3269 - Stil obiect-orientat
  • Example#3270 - Stil procedural
  • Example#3271 - Stil obiect-orientat
  • Example#3272 - Stil procedural
  • Example#3273 - Stil obiect-orientat
  • Example#3274 - Stil procedural
  • Example#3275 - Stil obiect-orientat
  • Example#3276 - Stil procedural
  • Example#3277 - Stil obiect-orientat
  • Example#3278 - Stil procedural
  • Example#3279 - Stil obiect-orientat
  • Example#3280 - Stil procedural
  • Example#3281 - Stil obiect-orientat
  • Example#3282 - Stil procedural
  • Example#3283 - Stil obiect-orientat
  • Example#3284 - Stil procedural
  • Example#3285 - Stil obiect-orientat
  • Example#3286 - Stil procedural
  • Example#3287 - Stil obiect-orientat
  • Example#3288 - Stil procedural
  • Example#3289 - Stil obiect-orientat
  • Example#3290 - Stil procedural
  • Example#3291 - Stil obiect-orientat
  • Example#3292 - Stil procedural
  • Example#3293 - Stil obiect-orientat
  • Example#3294 - Stil procedural
  • Example#3295 - Stil obiect-orientat
  • Example#3296 - Stil procedural
  • Example#3297 - Stil obiect-orientat
  • Example#3298 - Stil procedural
  • Example#3299 - Stil obiect-orientat
  • Example#3300 - Stil procedural
  • Example#3301 - Stil obiect-orientat
  • Example#3302 - Stil procedural
  • Example#3303 - Stil obiect-orientat
  • Example#3304 - Stil procedural
  • Example#3305 - Stil obiect-orientat
  • Example#3306 - Stil procedural
  • Example#3307 - Stil obiect-orientat
  • Example#3308 - Stil procedural
  • Example#3309 - Stil obiect-orientat
  • Example#3310 - Stil procedural
  • Example#3311 - Stil obiect-orientat
  • Example#3312 - Stil procedural
  • Example#3313 - Stil obiect-orientat
  • Example#3314 - Stil procedural
  • Example#3315 - Stil obiect-orientat
  • Example#3316 - Stil procedural
  • Example#3317 - Stil obiect-orientat
  • Example#3318 - Stil procedural
  • Example#3319 - Stil obiect-orientat
  • Example#3320 - Stil procedural
  • Example#3321 - Stil obiect-orientat
  • Example#3322 - Stil procedural
  • Example#3323 - Stil obiect-orientat
  • Example#3324 - Stil procedural
  • Example#3325 - Stil obiect-orientat
  • Example#3326 - Stil procedural
  • Example#3327 - Stil obiect-orientat
  • Example#3328 - Stil procedural
  • Example#3329 - Stil obiect-orientat
  • Example#3330 - Stil procedural
  • Example#3331 - Stil obiect-orientat
  • Example#3332 - Stil procedural
  • Example#3333 - Stil obiect-orientat
  • Example#3334 - Stil procedural
  • Example#3335 - Stil obiect-orientat
  • Example#3336 - Stil procedural
  • Example#3337 - Stil obiect-orientat
  • Example#3338 - Stil procedural
  • Example#3339 - Stil obiect-orientat
  • Example#3340 - Stil procedural
  • Example#3341 - Stil obiect-orientat
  • Example#3342 - Stil procedural
  • Example#3343 - Stil obiect-orientat
  • Example#3344 - Stil procedural
  • Example#3345 - Stil obiect-orientat
  • Example#3346 - Stil procedural
  • Example#3347 - Stil obiect-orientat
  • Example#3348 - Stil procedural
  • Example#3349 - Stil obiect-orientat
  • Example#3350 - Stil procedural
  • Example#3351 - Stil obiect-orientat
  • Example#3352 - Stil procedural
  • Example#3353 - Stil obiect-orientat
  • Example#3354 - Stil procedural
  • Example#3355 - Stil obiect-orientat
  • Example#3356 - Stil procedural
  • Example#3357 - Stil obiect-orientat
  • Example#3358 - Stil procedural
  • Example#3359 - Stil obiect-orientat
  • Example#3360 - Stil procedural
  • Example#3361 - Stil obiect-orientat
  • Example#3362 - Stil procedural
  • Example#3363 - Stil obiect-orientat
  • Example#3364 - Stil procedural
  • Example#3365 - Stil obiect-orientat
  • Example#3366 - Stil procedural
  • Example#3367 - Stil obiect-orientat
  • Example#3368 - Stil procedural
  • Example#3369 - Stil obiect-orientat
  • Example#3370 - Stil procedural
  • Example#3371 - Stil obiect-orientat
  • Example#3372 - Stil procedural
  • Example#3373 - Stil obiect-orientat
  • Example#3374 - Stil procedural
  • Example#3375 - CairoSurface::createSimilar example
  • Example#3376 - CairoSurface::finish example
  • Example#3377 - CairoSurface::flush example
  • Example#3378 - CairoSurface::getContent example
  • Example#3379 - CairoSurface::getDeviceOffset example
  • Example#3380 - Stil obiect-orientat
  • Example#3381 - Stil procedural
  • Example#3382 - CairoSurface::getType example
  • Example#3383 - CairoSurface::markDirty example
  • Example#3384 - CairoSurface::markDirtyRectangle example
  • Example#3385 - CairoSurface::setDeviceOffset example
  • Example#3386 - CairoSurface::setFallbackResolution example
  • Example#3387 - Stil obiect-orientat
  • Example#3388 - Stil procedural
  • Example#3389 - Stil obiect-orientat
  • Example#3390 - Stil procedural
  • Example#3391 - CairoSurface::writeToPng example
  • Example#3392 - CairoSvgSurface::__construct example
  • Example#3393 - CairoSvgSurface::getVersions example
  • Example#3394 - Stil procedural
  • Example#3395 - CairoSvgSurface::restrictToVersion example
  • Example#3396 - CairoSvgSurface::versionToString example
  • Example#3397 - CairoImageSurface::__construct example
  • Example#3398 - CairoImageSurface::createForData example
  • Example#3399 - CairoImageSurface::createFromPng example
  • Example#3400 - CairoImageSurface::getData example
  • Example#3401 - CairoImageSurface::getFormat example
  • Example#3402 - CairoImageSurface::getHeight example
  • Example#3403 - CairoImageSurface::getStride example
  • Example#3404 - CairoImageSurface::getWidth example
  • Example#3405 - CairoPdfSurface::__construct example
  • Example#3406 - CairoPdfSurface::setSize example
  • Example#3407 - CairoPsSurface::__construct example
  • Example#3408 - CairoPsSurface::dscBeginPageSetup example
  • Example#3409 - CairoPsSurface::dscBeginSetup example
  • Example#3410 - CairoPsSurface::dscComment example
  • Example#3411 - CairoPsSurface::getEps example
  • Example#3412 - CairoPsSurface::getLevels example
  • Example#3413 - CairoPsSurface::levelToString example
  • Example#3414 - CairoPsSurface::restrictToLevel example
  • Example#3415 - CairoPsSurface::setEps example
  • Example#3416 - CairoPsSurface::setSize example
  • Example#3417 - CairoFontFace::__construct example
  • Example#3418 - CairoFontFace::getType example
  • Example#3419 - Stil obiect-orientat
  • Example#3420 - Stil procedural
  • Example#3421 - CairoFontOptions::__construct example
  • Example#3422 - CairoFontOptions::equal example
  • Example#3423 - Stil obiect-orientat
  • Example#3424 - Stil procedural
  • Example#3425 - CairoFontOptions::getHintMetrics example
  • Example#3426 - CairoFontOptions::getHintStyle example
  • Example#3427 - CairoFontOptions::getSubpixelOrder example
  • Example#3428 - CairoFontOptions::hash example
  • Example#3429 - CairoFontOptions::merge example
  • Example#3430 - Stil obiect-orientat
  • Example#3431 - Stil procedural
  • Example#3432 - CairoFontOptions::setHintMetrics example
  • Example#3433 - CairoFontOptions::setHintStyle example
  • Example#3434 - CairoFontOptions::setSubpixelOrder example
  • Example#3435 - Stil obiect-orientat
  • Example#3436 - Stil procedural
  • Example#3437 - CairoScaledFont::__construct example
  • Example#3438 - CairoScaledFont::extents example
  • Example#3439 - CairoScaledFont::getCtm example
  • Example#3440 - Stil obiect-orientat
  • Example#3441 - Stil procedural
  • Example#3442 - Stil obiect-orientat
  • Example#3443 - Stil procedural
  • Example#3444 - Stil obiect-orientat
  • Example#3445 - Stil procedural
  • Example#3446 - CairoScaledFont::getScaleMatrix example
  • Example#3447 - CairoScaledFont::getType example
  • Example#3448 - CairoScaledFont::glyphExtents example
  • Example#3449 - Stil obiect-orientat
  • Example#3450 - Stil procedural
  • Example#3451 - Stil obiect-orientat
  • Example#3452 - Stil procedural
  • Example#3453 - CairoPattern::__construct example
  • Example#3454 - Stil obiect-orientat
  • Example#3455 - Stil procedural
  • Example#3456 - CairoPattern::getType example
  • Example#3457 - Stil obiect-orientat
  • Example#3458 - Stil procedural
  • Example#3459 - Stil obiect-orientat
  • Example#3460 - Stil procedural
  • Example#3461 - CairoGradientPattern::addColorStopRgb example
  • Example#3462 - CairoGradientPattern::addColorStopRgba example
  • Example#3463 - CairoGradientPattern::getColorStopCount example
  • Example#3464 - CairoGradientPattern::getColorStopRgba example
  • Example#3465 - CairoGradientPattern::getExtend example
  • Example#3466 - CairoGradientPattern::setExtend example
  • Example#3467 - CairoSolidPattern::__construct example
  • Example#3468 - CairoSolidPattern::getRgba example
  • Example#3469 - CairoSurfacePattern::__construct example
  • Example#3470 - CairoSurfacePattern::getExtend example
  • Example#3471 - CairoSurfacePattern::getFilter example
  • Example#3472 - CairoSurfacePattern::getSurface example
  • Example#3473 - CairoSurfacePattern::setExtend example
  • Example#3474 - CairoSurfacePattern::setFilter example
  • Example#3475 - CairoLinearGradient::__construct example
  • Example#3476 - CairoLinearGradient::getPoints example
  • Example#3477 - CairoRadialGradient::__construct example
  • Example#3478 - CairoRadialGradient::getCircles example
  • Example#3479 - CairoFormat::strideForWidth example
  • Example#3480 - Stil obiect-orientat
  • Example#3481 - Stil procedural
  • Example#3482 - Stil obiect-orientat
  • Example#3483 - Stil procedural
  • Example#3484 - Stil obiect-orientat
  • Example#3485 - Stil procedural
  • Example#3486 - Stil obiect-orientat
  • Example#3487 - Stil procedural
  • Example#3488 - Stil obiect-orientat
  • Example#3489 - Stil procedural
  • Example#3490 - CairoMatrix::invert example
  • Example#3491 - CairoMatrix::multiply example
  • Example#3492 - Stil obiect-orientat
  • Example#3493 - Stil procedural
  • Example#3494 - Stil obiect-orientat
  • Example#3495 - Stil procedural
  • Example#3496 - CairoMatrix::transformDistance example
  • Example#3497 - CairoMatrix::transformPoint example
  • Example#3498 - Stil obiect-orientat
  • Example#3499 - Stil procedural
  • Example#3500 - exif_imagetype example
  • Example#3501 - exif_read_data example
  • Example#3502 - exif_tagname example
  • Example#3503 - exif_thumbnail example
  • Example#3504 - PNG creation with PHP
  • Example#3505 - Adding watermarks to images using alpha channels
  • Example#3506 - Using imagecopymerge to create a translucent watermark
  • Example#3507 - Using gd_info
  • Example#3508 - getimagesize and MIME types
  • Example#3509 - getimagesize example
  • Example#3510 - getimagesize (URL)
  • Example#3511 - getimagesize() returning IPTC
  • Example#3512 - getimagesizefromstring example
  • Example#3513 - image_type_to_extension example
  • Example#3514 - image_type_to_mime_type example
  • Example#3515 - image2wbmp example
  • Example#3516 - imageaffinematrixconcat example
  • Example#3517 - imageaffinematrixget example
  • Example#3518 - imagealphablending usage example
  • Example#3519 - A comparison of two lines, one with anti-aliasing switched on
  • Example#3520 - Drawing a circle with imagearc
  • Example#3521 - Saving a BMP file
  • Example#3522 - imagechar example
  • Example#3523 - imagecharup example
  • Example#3524 - imagecolorallocate example
  • Example#3525 - Example of using imagecolorallocatealpha
  • Example#3526 - Access distinct RGB values
  • Example#3527 - Human-readable RGB values using imagecolorsforindex
  • Example#3528 - Search for a set of colors in an image
  • Example#3529 - Search for a set of colors in an image
  • Example#3530 - Example of using imagecolorclosesthwb
  • Example#3531 - Using imagecolordeallocate
  • Example#3532 - Get colors from the GD logo
  • Example#3533 - Get colors from the GD logo
  • Example#3534 - imagecolormatch example
  • Example#3535 - Using imagecoloresolve to get colors from an image
  • Example#3536 - Using imagecoloresolvealpha to get colors from an image
  • Example#3537 - imagecolorset example
  • Example#3538 - imagecolorsforindex example
  • Example#3539 - Getting total number of colors in an image using imagecolorstotal
  • Example#3540 - imagecolortransparent example
  • Example#3541 - Embossing the PHP.net logo
  • Example#3542 - Gaussian blur
  • Example#3543 - Cropping the PHP.net logo
  • Example#3544 - Merging two copies of the PHP.net logo with 75% transparency
  • Example#3545 - imagecopymergegray usage
  • Example#3546 - Simple example
  • Example#3547 - Resampling an image proportionally
  • Example#3548 - Resizing an image
  • Example#3549 - Creating a new GD image stream and outputting an image.
  • Example#3550 - Convert an BMP image to a PNG image using imagecreatefrombmp
  • Example#3551 - imagecreatefromgd2 example
  • Example#3552 - imagecreatefromgd2part example
  • Example#3553 - imagecreatefromgd example
  • Example#3554 - Example to handle an error during loading of a GIF
  • Example#3555 - Example to handle an error during loading of a JPEG
  • Example#3556 - Example to handle an error during loading of a PNG
  • Example#3557 - imagecreatefromstring example
  • Example#3558 - Example to handle an error during loading of a WBMP
  • Example#3559 - Convert an WebP image to a jpeg image using imagecreatefromwebp
  • Example#3560 - Convert an XBM image to a png image using imagecreatefromxbm
  • Example#3561 - Creating an image instance using imagecreatefromxpm
  • Example#3562 - Creating a new GD image stream and outputting an image.
  • Example#3563 - imagecrop example
  • Example#3564 - Proper handling of auto-cropping
  • Example#3565 - imagedashedline example
  • Example#3566 - Alternative to imagedashedline
  • Example#3567 - Using imagedestroy example
  • Example#3568 - imageellipse example
  • Example#3569 - imagefill example
  • Example#3570 - Creating a 3D looking pie
  • Example#3571 - imagefilledellipse example
  • Example#3572 - imagefilledpolygon example
  • Example#3573 - imagefilledrectangle usage
  • Example#3574 - Filling an ellipse with a color
  • Example#3575 - imagefilter grayscale example
  • Example#3576 - imagefilter brightness example
  • Example#3577 - imagefilter colorize example
  • Example#3578 - imagefilter negate example
  • Example#3579 - imagefilter pixelate example
  • Example#3580 - Flips an image vertically
  • Example#3581 - Flips the image horizontally
  • Example#3582 - Using imagefontheight on built-in fonts
  • Example#3583 - Using imagefontheight together with imageloadfont
  • Example#3584 - Using imagefontwidth on built-in fonts
  • Example#3585 - Using imagefontwidth together with imageloadfont
  • Example#3586 - imageftbbox example
  • Example#3587 - imagefttext example
  • Example#3588 - imagegammacorrect usage
  • Example#3589 - Outputting a GD2 image
  • Example#3590 - Saving a GD2 image
  • Example#3591 - Outputting a GD image
  • Example#3592 - Saving a GD image
  • Example#3593 - imagegetclip example
  • Example#3594 - Outputting an image using imagegif
  • Example#3595 - Converting a PNG image to GIF using imagegif
  • Example#3596 - imagegrabscreen example
  • Example#3597 - imagegrabwindow example
  • Example#3598 - Turn on interlacing using imageinterlace
  • Example#3599 - Simple detection of true color image instances using imageistruecolor
  • Example#3600 - Outputting a JPEG image to the browser
  • Example#3601 - Saving a JPEG image to a file
  • Example#3602 - Outputting the image at 75% quality to the browser
  • Example#3603 - imagelayereffect example
  • Example#3604 - Drawing a thick line
  • Example#3605 - imageloadfont usage example
  • Example#3606 - imageopenpolygon example
  • Example#3607 - imagepalettecopy example
  • Example#3608 - Converts any image resource to true color
  • Example#3609 - imagepolygon example
  • Example#3610 - imagepsbbox usage
  • Example#3611 - imagepsencodefont example
  • Example#3612 - imagepsextendfont example
  • Example#3613 - imagepsfreefont example
  • Example#3614 - imagepsloadfont example
  • Example#3615 - imagepsslantfont example
  • Example#3616 - imagepstext usage
  • Example#3617 - Simple imagerectangle example
  • Example#3618 - Setting and getting the resolution of an image
  • Example#3619 - Rotate an image 180 degrees
  • Example#3620 - imagesavealpha example
  • Example#3621 - imagesetbrush example
  • Example#3622 - imagesetinterpolation example
  • Example#3623 - imagesetpixel example
  • Example#3624 - imagesetstyle example
  • Example#3625 - imagesetthickness example
  • Example#3626 - imagesettile example
  • Example#3627 - imagestring example
  • Example#3628 - imagestringup example
  • Example#3629 - Using imagesx
  • Example#3630 - Using imagesy
  • Example#3631 - Converting a true color image to a palette-based image
  • Example#3632 - imagettfbbox example
  • Example#3633 - imagettftext example
  • Example#3634 - Checking for PNG support
  • Example#3635 - Outputting a WBMP image
  • Example#3636 - Saving the WBMP image
  • Example#3637 - Outputting the image with a different foreground
  • Example#3638 - Saving an WebP file
  • Example#3639 - Saving an XBM file
  • Example#3640 - Saving an XBM file with a different foreground color
  • Example#3641 - Embedding IPTC data into a JPEG
  • Example#3642 - iptcparse() used together with getimagesize
  • Example#3643 - jpeg2wbmp example
  • Example#3644 - png2wbmp example
  • Example#3645 - Gmagick Example
  • Example#3646 - Gmagick::despeckleimage example
  • Example#3647 - Gmagick::setCompressionQuality
  • Example#3648 - Creating a thumbnail in Imagick
  • Example#3649 - Make a thumbnail of all JPG files in a directory
  • Example#3650 - Creating a reflection of an image
  • Example#3651 - Filling text with gradient
  • Example#3652 - Read in GIF image and resize all frames
  • Example#3653 - Create a PHP logo
  • Example#3654 - Using Imagick::adaptiveBlurImage:
  • Example#3655 - Using Imagick::adaptiveResizeImage
  • Example#3656 - A Imagick::adaptiveSharpenImage example
  • Example#3657 - Imagick::adaptiveThresholdImage
  • Example#3658 - Imagick::addNoiseImage
  • Example#3659 - Imagick::affineTransformImage
  • Example#3660 - Using Imagick::annotateImage:
  • Example#3661 - Imagick::appendImages example
  • Example#3662 - Imagick::autoLevelImage
  • Example#3663 - Imagick::blackThresholdImage
  • Example#3664 - Imagick::blueShiftImage
  • Example#3665 - Using Imagick::blurImage:
  • Example#3666 - Imagick::borderImage
  • Example#3667 - Imagick::brightnessContrastImage
  • Example#3668 - Imagick::charcoalImage
  • Example#3669 - Using Imagick::chopImage:
  • Example#3670 - Imagick object cloning in different versions of imagick
  • Example#3671 - Using Imagick::clutImage:
  • Example#3672 - Imagick::colorizeImage
  • Example#3673 - Imagick::colorMatrixImage
  • Example#3674 - Using Imagick::commentImage:
  • Example#3675 - Using Imagick::compareImageLayers
  • Example#3676 - Using Imagick::compareImages:
  • Example#3677 - Using Imagick::compositeImage:
  • Example#3678 - Imagick::contrastImage
  • Example#3679 - Imagick::convolveImage
  • Example#3680 - Imagick::cropImage
  • Example#3681 - Imagick::deskewImage
  • Example#3682 - Imagick::despeckleImage
  • Example#3683 - Using Imagick::distortImage:
  • Example#3684 - Imagick::edgeImage
  • Example#3685 - Imagick::embossImage
  • Example#3686 - Imagick::enhanceImage
  • Example#3687 - Imagick::equalizeImage
  • Example#3688 - Using Imagick::evaluateImage
  • Example#3689 - Using Imagick::exportImagePixels
  • Example#3690 - Imagick::filter
  • Example#3691 - Imagick::flipImage
  • Example#3692 - Imagick::floodfillPaintImage example
  • Example#3693 - Imagick::flopImage
  • Example#3694 - Imagick::forwardFourierTransformImage
  • Example#3695 - Imagick::frameImage
  • Example#3696 - Create a sinusoidal gradient
  • Example#3697 - Create a gradient from the polynomial (4x^2 - 4x + 1)
  • Example#3698 - Create a complex gradient from the polynomial (4x^2 - 4x^2 + 1) modulated by a sinusoidal gradient
  • Example#3699 - Imagick::fxImage
  • Example#3700 - Imagick::gammaImage
  • Example#3701 - Imagick::gaussianBlurImage
  • Example#3702 - Imagick::getImageGeometry
  • Example#3703 - Generates Imagick::getImageHistogram
  • Example#3704 - Using Imagick::getImageLength:
  • Example#3705 - Using Imagick::getImageProperties:
  • Example#3706 - Using Imagick::getImageProperty:
  • Example#3707 - Using Imagick::getIteratorIndex:
  • Example#3708 - Imagick::getPixelIterator
  • Example#3709 - Imagick::getPixelRegionIterator example
  • Example#3710 - Imagick::haldClutImage
  • Example#3711 - Imagick::identifyFormat
  • Example#3712 - Example Result Format
  • Example#3713 - Imagick::implodeImage
  • Example#3714 - Imagick::importImagePixels example
  • Example#3715 - Imagick::levelImage
  • Example#3716 - Imagick::linearStretchImage
  • Example#3717 - Imagick::magnifyImage
  • Example#3718 - Imagick::medianFilterImage
  • Example#3719 - Imagick::mergeImageLayers
  • Example#3720 - Imagick::modulateImage
  • Example#3721 - Convolve Imagick::morphology
  • Example#3722 - Correlate Imagick::morphology
  • Example#3723 - Erode Imagick::morphology
  • Example#3724 - Erode Intensity Imagick::morphology
  • Example#3725 - Dilate Imagick::morphology
  • Example#3726 - Dilate intensity Imagick::morphology
  • Example#3727 - Distance with Chebyshev kernel Imagick::morphology
  • Example#3728 - Distance with Manhattan kernel Imagick::morphology
  • Example#3729 - Distance with ocatagonal kernel Imagick::morphology
  • Example#3730 - Distance with Euclidean kernel Imagick::morphology
  • Example#3731 - Edge Imagick::morphology
  • Example#3732 - Open Imagick::morphology
  • Example#3733 - Open intensity Imagick::morphology
  • Example#3734 - Close Imagick::morphology
  • Example#3735 - Close Intensity Imagick::morphology
  • Example#3736 - Smooth Imagick::morphology
  • Example#3737 - Edge in Imagick::morphology
  • Example#3738 - Edge out Imagick::morphology
  • Example#3739 - The 'TopHat' method, or more specifically 'White Top Hat', returns the pixels that were removed by a Opening of the shape, that is the pixels that were removed to round off the points, and the connecting bridged between shapes. Imagick::morphology
  • Example#3740 - The 'BottomHat' method, also known as 'Black TopHat' is the pixels that a Closing of the shape adds to the image. That is the the pixels that were used to fill in the 'holes', 'gaps', and 'bridges'. Imagick::morphology
  • Example#3741 - Hit and Miss Imagick::morphology
  • Example#3742 - Thinning Imagick::morphology
  • Example#3743 - Thicken Imagick::morphology
  • Example#3744 - Thick to generate a convex hull Imagick::morphology
  • Example#3745 - Iterative morphology Imagick::morphology
  • Example#3746 - Helper functon to get an image silhouette Imagick::morphology
  • Example#3747 - Imagick::motionBlurImage
  • Example#3748 - Imagick::negateImage
  • Example#3749 - Using Imagick::newImage:
  • Example#3750 - Imagick::newPseudoImage
  • Example#3751 - Imagick::normalizeImage
  • Example#3752 - Imagick::oilPaintImage
  • Example#3753 - Using Imagick::optimizeImageLayers
  • Example#3754 - Imagick::orderedPosterizeImage
  • Example#3755 - Using Imagick::pingImageBlob
  • Example#3756 - Using Imagick::pingImageFile
  • Example#3757 - A Imagick::polaroidImage example
  • Example#3758 - Imagick::posterizeImage
  • Example#3759 - Imagick::quantizeImage
  • Example#3760 - Using Imagick::queryFontMetrics:
  • Example#3761 - Imagick::queryFonts
  • Example#3762 - Imagick::queryFormats
  • Example#3763 - Imagick::radialBlurImage
  • Example#3764 - Imagick::raiseImage
  • Example#3765 - Imagick::randomThresholdImage
  • Example#3766 - Imagick::readImageBlob
  • Example#3767 - Imagick::recolorImage
  • Example#3768 - Imagick::reduceNoiseImage
  • Example#3769 - Imagick::resampleImage
  • Example#3770 - Imagick::resizeImage
  • Example#3771 - Imagick::rollImage
  • Example#3772 - Imagick::rotateImage
  • Example#3773 - Imagick::rotationalBlurImage
  • Example#3774 - Using Imagick::roundCorners:
  • Example#3775 - Imagick::scaleImage
  • Example#3776 - Imagick::segmentImage
  • Example#3777 - Imagick::selectiveBlurImage
  • Example#3778 - Imagick::separateImageChannel
  • Example#3779 - Imagick::sepiaToneImage
  • Example#3780 - Imagick::setCompressionQuality
  • Example#3781 - A Imagick::setFont example
  • Example#3782 - A Imagick::setImage example
  • Example#3783 - Imagick::setImageArtifact
  • Example#3784 - Imagick::setImageBias
  • Example#3785 - Imagick::setImageClipMask
  • Example#3786 - Imagick::setImageCompressionQuality
  • Example#3787 - Modify animated Gif with Imagick::setImageDelay
  • Example#3788 - Basic Imagick::setImageIterations usage
  • Example#3789 - A Imagick::setImageOpacity example
  • Example#3790 - Imagick::setImageOrientation
  • Example#3791 - Using Imagick::setImageProperty:
  • Example#3792 - Imagick::setImageResolution
  • Example#3793 - Modify animated Gif with Imagick::setImageTicksPerSecond
  • Example#3794 - Using Imagick::setIteratorIndex:
  • Example#3795 - Attempt to reach '$extent' sizeImagick::setOption
  • Example#3796 - Imagick::setOption
  • Example#3797 - Imagick::setOption
  • Example#3798 - A Imagick::setPointSize example
  • Example#3799 - Imagick::setProgressMonitor
  • Example#3800 - Imagick::setSamplingFactors
  • Example#3801 - Imagick::shadeImage
  • Example#3802 - Imagick::shadowImage
  • Example#3803 - Imagick::sharpenImage
  • Example#3804 - Imagick::shaveImage
  • Example#3805 - Imagick::shearImage
  • Example#3806 - Create a gradient image using Imagick::sigmoidalContrastImage suitable for blending two images together smoothly, with the blending defined by $contrast and $the midpoint
  • Example#3807 - Imagick::sketchImage
  • Example#3808 - Imagick::smushImages
  • Example#3809 - Imagick::solarizeImage
  • Example#3810 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#3811 - SPARSECOLORMETHOD_BILINEAR Imagick::sparseColorImage
  • Example#3812 - SPARSECOLORMETHOD_SPEPARDS Imagick::sparseColorImage
  • Example#3813 - SPARSECOLORMETHOD_VORONOI Imagick::sparseColorImage
  • Example#3814 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#3815 - createGradientImage is used by other examples. Imagick::sparseColorImage
  • Example#3816 - Imagick::spliceImage
  • Example#3817 - Imagick::spreadImage
  • Example#3818 - Imagick::statisticImage
  • Example#3819 - Imagick::subImageMatch
  • Example#3820 - Imagick::swirlImage
  • Example#3821 - Imagick::textureImage
  • Example#3822 - Imagick::thresholdImage
  • Example#3823 - Imagick::thumbnailImage
  • Example#3824 - Imagick::tintImage
  • Example#3825 - Using Imagick::transformImage:
  • Example#3826 - Imagick::transformImageColorspace example
  • Example#3827 - Imagick::transformImageColorspace
  • Example#3828 - Imagick::transparentPaintImage
  • Example#3829 - Imagick::transposeImage
  • Example#3830 - Imagick::transverseImage
  • Example#3831 - Using Imagick::trimImage:
  • Example#3832 - Imagick::uniqueImageColors
  • Example#3833 - Imagick::unsharpMaskImage
  • Example#3834 - Imagick::vignetteImage
  • Example#3835 - WaveImage can be quite slow Imagick::waveImage
  • Example#3836 - Imagick::whiteThresholdImage
  • Example#3837 - ImagickDraw::affine
  • Example#3838 - ImagickDraw::arc
  • Example#3839 - ImagickDraw::bezier
  • Example#3840 - ImagickDraw::circle
  • Example#3841 - ImagickDraw::composite
  • Example#3842 - ImagickDraw::ellipse
  • Example#3843 - ImagickDraw::line
  • Example#3844 - ImagickDraw::matte
  • Example#3845 - ImagickDraw::pathCurveToQuadraticBezierAbsolute
  • Example#3846 - ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
  • Example#3847 - ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
  • Example#3848 - ImagickDraw::pathStart
  • Example#3849 - ImagickDraw::point
  • Example#3850 - ImagickDraw::polygon
  • Example#3851 - ImagickDraw::polyline
  • Example#3852 - ImagickDraw::popDefs
  • Example#3853 - ImagickDraw::push
  • Example#3854 - ImagickDraw::pushPattern
  • Example#3855 - ImagickDraw::rectangle
  • Example#3856 - ImagickDraw::rotate
  • Example#3857 - ImagickDraw::roundRectangle
  • Example#3858 - ImagickDraw::scale
  • Example#3859 - ImagickDraw::setClipPath
  • Example#3860 - ImagickDraw::setClipRule
  • Example#3861 - ImagickDraw::setClipUnits
  • Example#3862 - ImagickDraw::setFillAlpha
  • Example#3863 - ImagickDraw::setFillColor
  • Example#3864 - ImagickDraw::setFillOpacity
  • Example#3865 - ImagickDraw::setFillRule
  • Example#3866 - ImagickDraw::setFont
  • Example#3867 - ImagickDraw::setFontFamily
  • Example#3868 - ImagickDraw::setFontSize
  • Example#3869 - ImagickDraw::setFontStretch
  • Example#3870 - ImagickDraw::setFontStyle
  • Example#3871 - ImagickDraw::setFontWeight
  • Example#3872 - ImagickDraw::setGravity
  • Example#3873 - ImagickDraw::setStrokeAlpha
  • Example#3874 - ImagickDraw::setStrokeAntialias
  • Example#3875 - ImagickDraw::setStrokeColor
  • Example#3876 - ImagickDraw::setStrokeDashArray
  • Example#3877 - ImagickDraw::setStrokeDashOffset
  • Example#3878 - ImagickDraw::setStrokeLineCap
  • Example#3879 - ImagickDraw::setStrokeLineJoin
  • Example#3880 - ImagickDraw::setStrokeMiterLimit
  • Example#3881 - ImagickDraw::setStrokeOpacity
  • Example#3882 - ImagickDraw::setStrokeWidth
  • Example#3883 - ImagickDraw::setTextAlignment
  • Example#3884 - ImagickDraw::setTextAntialias
  • Example#3885 - ImagickDraw::setTextDecoration
  • Example#3886 - ImagickDraw::setTextUnderColor
  • Example#3887 - ImagickDraw::setVectorGraphics
  • Example#3888 - ImagickDraw::setViewBox
  • Example#3889 - ImagickDraw::skewX
  • Example#3890 - ImagickDraw::skewY
  • Example#3891 - ImagickDraw::translate
  • Example#3892 - ImagickPixel::construct
  • Example#3893 - Basic Imagick::getColor usage
  • Example#3894 - Basic Imagick::getColorAsString usage
  • Example#3895 - ImagickPixel getColorCount
  • Example#3896 - Basic Imagick::getColorValue usage
  • Example#3897 - ImagickPixel::getColorValueQuantum
  • Example#3898 - Basic Imagick::getHSL example
  • Example#3899 - ImagickPixel::isSimilar
  • Example#3900 - ImagickPixel::setColor
  • Example#3901 - Basic Imagick::setColorValue usage
  • Example#3902 - ImagickPixel::setColorValueQuantum
  • Example#3903 - Use ImagickPixel::setHSL to modify a color
  • Example#3904 - ImagickPixelIterator::clear
  • Example#3905 - ImagickPixelIterator::construct
  • Example#3906 - ImagickPixelIterator::getNextIteratorRow
  • Example#3907 - ImagickPixelIterator::resetIterator
  • Example#3908 - ImagickPixelIterator::setIteratorRow
  • Example#3909 - ImagickKernel::addKernel
  • Example#3910 - ImagickKernel::addUnityKernel
  • Example#3911 - ImagickKernel::addUnityKernel
  • Example#3912 - ImagickKernel::fromBuiltin
  • Example#3913 - ImagickKernel::fromMatrix
  • Example#3914 - ImagickKernel::getMatrix
  • Example#3915 - ImagickKernel::scale
  • Example#3916 - ImagickKernel::separate
  • Example#3917 - imap_append example
  • Example#3918 - imap_check example
  • Example#3919 - imap_createmailbox example
  • Example#3920 - imap_delete example
  • Example#3921 - imap_fetch_overview example
  • Example#3922 - imap_gc example
  • Example#3923 - imap_get_quota example
  • Example#3924 - imap_get_quota 4.3 or greater example
  • Example#3925 - imap_get_quotaroot example
  • Example#3926 - imap_getacl example
  • Example#3927 - imap_getmailboxes example
  • Example#3928 - imap_list example
  • Example#3929 - imap_mail_compose example
  • Example#3930 - imap_mailboxmsginfo example
  • Example#3931 - imap_mime_header_decode example
  • Example#3932 - Different use of imap_open
  • Example#3933 - imap_open example
  • Example#3934 - imap_ping Example
  • Example#3935 - imap_reopen example
  • Example#3936 - imap_rfc822_parse_adrlist example
  • Example#3937 - imap_rfc822_write_address example
  • Example#3938 - imap_search example
  • Example#3939 - imap_set_quota example
  • Example#3940 - imap_setflag_full example
  • Example#3941 - imap_status example
  • Example#3942 - imap_thread Example
  • Example#3943 - imap_timeout example
  • Example#3944 - Calcularea hash-ului ?i înscrierea în lista a unui utilizator
  • Example#3945 - Trimiterea mesajelor.
  • Example#3946 - Trimiterea unui mesaj cu antete suplimentare.
  • Example#3947 - Trimiterea unui mesaj cu un parametru suplimentar în linia de comanda.
  • Example#3948 - Transmiterea unui mesaj HTML
  • Example#3949 - mailparse_determine_best_xfer_encoding example
  • Example#3950 - mailparse_rfc822_parse_addresses example
  • Example#3951 - mailparse_stream_encode example
  • Example#3952 - mailparse_uudecode_all example
  • Example#3953 - bcadd example
  • Example#3954 - bccomp example
  • Example#3955 - bcdiv example
  • Example#3956 - bcmod example
  • Example#3957 - bcmul example
  • Example#3958 - bcpow example
  • Example#3959 - bcpow scale example
  • Example#3960 - bcscale example
  • Example#3961 - bcsqrt example
  • Example#3962 - bcsub example
  • Example#3963 - Exemplu de func?ie factoriala utilizând GMP
  • Example#3964 - gmp_abs example
  • Example#3965 - gmp_add example
  • Example#3966 - gmp_and example
  • Example#3967 - gmp_clrbit example
  • Example#3968 - gmp_cmp example
  • Example#3969 - gmp_com example
  • Example#3970 - gmp_div_q example
  • Example#3971 - Division of GMP numbers
  • Example#3972 - gmp_div_r example
  • Example#3973 - gmp_divexact example
  • Example#3974 - gmp_export example
  • Example#3975 - gmp_fact example
  • Example#3976 - gmp_gcd example
  • Example#3977 - Solving a linear Diophantine equation
  • Example#3978 - gmp_hamdist example
  • Example#3979 - gmp_import example
  • Example#3980 - Creating GMP number
  • Example#3981 - gmp_intval example
  • Example#3982 - gmp_invert example
  • Example#3983 - gmp_jacobi example
  • Example#3984 - gmp_legendre example
  • Example#3985 - gmp_mod example
  • Example#3986 - gmp_mul example
  • Example#3987 - gmp_neg example
  • Example#3988 - gmp_nextprime example
  • Example#3989 - gmp_or example
  • Example#3990 - gmp_perfect_square example
  • Example#3991 - gmp_popcount example
  • Example#3992 - gmp_pow example
  • Example#3993 - gmp_powm example
  • Example#3994 - gmp_prob_prime example
  • Example#3995 - gmp_random_bits example
  • Example#3996 - gmp_random_range example
  • Example#3997 - gmp_random_seed example
  • Example#3998 - gmp_random example
  • Example#3999 - gmp_scan0 example
  • Example#4000 - gmp_scan1 example
  • Example#4001 - gmp_setbit example - 0 index
  • Example#4002 - gmp_setbit example - 1 index
  • Example#4003 - gmp_setbit example - clearing a bit
  • Example#4004 - gmp_sign example
  • Example#4005 - gmp_sqrt example
  • Example#4006 - gmp_sqrtrem example
  • Example#4007 - Converting a GMP number to a string
  • Example#4008 - gmp_sub example
  • Example#4009 - gmp_testbit example
  • Example#4010 - gmp_xor example
  • Example#4011 - Using Lapack::eigenValues:
  • Example#4012 - Using Lapack::leastSquaresByFactorisation:
  • Example#4013 - Using Lapack::leastSquaresBySVD:
  • Example#4014 - Using Lapack::pseudoInverse:
  • Example#4015 - Using Lapack::singularValues:
  • Example#4016 - Using Lapack::singularValues:
  • Example#4017 - abs example
  • Example#4018 - base_convert example
  • Example#4019 - bindec example
  • Example#4020 - bindec interprets input as unsigned integers
  • Example#4021 - ceil example
  • Example#4022 - cos example
  • Example#4023 - decbin example
  • Example#4024 - dechex example
  • Example#4025 - dechex example with large integers
  • Example#4026 - decoct example
  • Example#4027 - deg2rad example
  • Example#4028 - exp example
  • Example#4029 - floor example
  • Example#4030 - Using fmod
  • Example#4031 - hexdec example
  • Example#4032 - intdiv example
  • Example#4033 - is_nan example
  • Example#4034 - Example uses of max
  • Example#4035 - Example uses of min
  • Example#4036 - Calculate a random floating-point number
  • Example#4037 - mt_rand example
  • Example#4038 - mt_srand example
  • Example#4039 - octdec example
  • Example#4040 - pi example
  • Example#4041 - Some examples of pow
  • Example#4042 - rad2deg example
  • Example#4043 - rand example
  • Example#4044 - round examples
  • Example#4045 - mode examples
  • Example#4046 - mode with precision examples
  • Example#4047 - sin example
  • Example#4048 - sqrt example
  • Example#4049 - srand example
  • Example#4050 - tan example
  • Example#4051 - Evaluating a FDF document
  • Example#4052 - Adding JavaScript code to a FDF
  • Example#4053 - Populating a PDF document
  • Example#4054 - Storing an uploaded file
  • Example#4055 - Detecting all fieldnames in a FDF
  • Example#4056 - Accessing the form data
  • Example#4057 - Accessing the form data
  • Example#4058 - Retrieving FDF as a string
  • Example#4059 - Passing FDF data to a second form
  • Example#4060 - gnupg clearsign example (procedural)
  • Example#4061 - gnupg clearsign example (OO)
  • Example#4062 - keylistiterator
  • Example#4063 - Procedural gnupg_adddecryptkey example
  • Example#4064 - OO gnupg_adddecryptkey example
  • Example#4065 - Procedural gnupg_addencryptkey example
  • Example#4066 - OO gnupg_addencryptkey example
  • Example#4067 - Procedural gnupg_addsignkey example
  • Example#4068 - OO gnupg_addsignkey example
  • Example#4069 - Procedural gnupg_cleardecryptkeys example
  • Example#4070 - OO gnupg_cleardecryptkeys example
  • Example#4071 - Procedural gnupg_clearencryptkeys example
  • Example#4072 - OO gnupg_clearencryptkeys example
  • Example#4073 - Procedural gnupg_clearsignkeys example
  • Example#4074 - OO gnupg_clearsignkeys example
  • Example#4075 - Procedural gnupg_decrypt example
  • Example#4076 - OO gnupg_encrypt example
  • Example#4077 - Procedural gnupg_decryptverify example
  • Example#4078 - OO gnupg_decryptverify example
  • Example#4079 - Procedural gnupg_encrypt example
  • Example#4080 - OO gnupg_encrypt example
  • Example#4081 - Procedural gnupg_encryptsign example
  • Example#4082 - OO gnupg_encryptsign example
  • Example#4083 - Procedural gnupg_export example
  • Example#4084 - OO gnupg_export example
  • Example#4085 - Procedural gnupg_geterror example
  • Example#4086 - OO gnupg_geterror example
  • Example#4087 - Procedural gnupg_getprotocol example
  • Example#4088 - OO gnupg_getprotocol example
  • Example#4089 - Procedural gnupg_import example
  • Example#4090 - OO gnupg_import example
  • Example#4091 - Procedural gnupg_init example
  • Example#4092 - OO gnupg initializer example
  • Example#4093 - Procedural gnupg_keyinfo example
  • Example#4094 - OO gnupg_keyinfo example
  • Example#4095 - Procedural gnupg_setarmor example
  • Example#4096 - OO gnupg_setarmor example
  • Example#4097 - Procedural gnupg_seterrormode example
  • Example#4098 - OO gnupg_seterrormode example
  • Example#4099 - Procedural gnupg_setsignmode example
  • Example#4100 - OO gnupg_setsignmode example
  • Example#4101 - Procedural gnupg_sign example
  • Example#4102 - OO gnupg_sign example
  • Example#4103 - Procedural gnupg_verify example
  • Example#4104 - OO gnupg_verify example
  • Example#4105 - Fancy "Hello world"
  • Example#4106 - swfaction example
  • Example#4107 - swfaction example
  • Example#4108 - swfaction example
  • Example#4109 - swfsprite example
  • Example#4110 - ming_useswfversion example
  • Example#4111 - Importing a DBL file
  • Example#4112 - Using an alpha mask
  • Example#4113 - Usual interactions with buttons
  • Example#4114 - Drag example
  • Example#4115 - swfdisplayitem::multcolor example
  • Example#4116 - swfdisplayitem::rotateto example
  • Example#4117 - swfdisplayitem::setname example
  • Example#4118 - swfgradient example
  • Example#4119 - swfmorph example
  • Example#4120 - Displaying your $movie in a browser
  • Example#4121 - Streaming example
  • Example#4122 - SWFShape::addFill example
  • Example#4123 - swfshape example
  • Example#4124 - swfshape::setline example
  • Example#4125 - swftext example
  • Example#4126 - Hello World example from PDFlib distribution for PHP 4
  • Example#4127 - Hello World example from PDFlib distribution for PHP 5
  • Example#4128 - Creating and using a pattern
  • Example#4129 - Creating and using a template
  • Example#4130 - Hyphennate a text
  • Example#4131 - Drawing a rectangle
  • Example#4132 - Creating and using a spot color
  • Example#4133 - Rotation of the coordinate system
  • Example#4134 - Placing text at a given position
  • Example#4135 - Drawing a dashed line
  • Example#4136 - Translation of the coordinate system
  • Example#4137 - Basic RPMReader Example
  • Example#4138 - rpm_close example
  • Example#4139 - rpm_get_tag example
  • Example#4140 - rpm_is_valid example
  • Example#4141 - rpm_open example
  • Example#4142 - rpm_version example
  • Example#4143 - Incorrect requests
  • Example#4144 - Calling request from a request callback
  • Example#4145 - Calling request from a request callback
  • Example#4146 - Using eio with libevent
  • Example#4147 - Cancelling a request
  • Example#4148 - Calling eio_chmod
  • Example#4149 - Making a custom request
  • Example#4150 - Grouping requests
  • Example#4151 - Using eio with libevent extension
  • Example#4152 - Using eio with event extension
  • Example#4153 - eio_cancel example
  • Example#4154 - eio_custom example
  • Example#4155 - eio_event_loop example
  • Example#4156 - eio_lstat example
  • Example#4157 - Using eio with libevent
  • Example#4158 - Grouping requests
  • Example#4159 - eio_grp example
  • Example#4160 - eio_link example
  • Example#4161 - eio_lstat example
  • Example#4162 - eio_mkdir example
  • Example#4163 - eio_mknod example
  • Example#4164 - eio_nreqs example
  • Example#4165 - eio_open example
  • Example#4166 - eio_poll example
  • Example#4167 - eio_read example
  • Example#4168 - eio_readdir example
  • Example#4169 - eio_readlink example
  • Example#4170 - eio_realpath example
  • Example#4171 - eio_rename example
  • Example#4172 - eio_rmdir example
  • Example#4173 - eio_stat example
  • Example#4174 - eio_statvfs example
  • Example#4175 - eio_symlink example
  • Example#4176 - Simple timers
  • Example#4177 - Periodic timer. Tick each 10.5 seconds
  • Example#4178 - Periodic timer. Use reschedule callback
  • Example#4179 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#4180 - Wait until STDIN is readable
  • Example#4181 - Use some async I/O to access a socket
  • Example#4182 - Embedding one loop into another
  • Example#4183 - Embedding loop created with kqueue backend into the default loop
  • Example#4184 - Handle SIGTERM signal
  • Example#4185 - Monitor changes of /var/log/messages
  • Example#4186 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#4187 - Process status changes
  • Example#4188 - Using reschedule callback
  • Example#4189 - Embedding loop created with kqueue backend into the default loop
  • Example#4190 - Embedding one loop into another
  • Example#4191 - Embedding loop created with kqueue backend into the default loop
  • Example#4192 - Embedding loop created with kqueue backend into the default loop
  • Example#4193 - Periodic timer. Use reschedule callback
  • Example#4194 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#4195 - Hourly watcher
  • Example#4196 - Handle SIGTERM signal
  • Example#4197 - Monitor changes of /var/log/messages
  • Example#4198 - Monitor changes of /var/log/messages
  • Example#4199 - Simple timers
  • Example#4200 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#4201 - Register an I/O watcher for some UDP socket but do not keep the event loop from running just because of that watcher.
  • Example#4202 - Expect Usage Example
  • Example#4203 - Another Expect Usage Example
  • Example#4204 - expect_expectl example
  • Example#4205 - expect_popen example
  • Example#4206 - polling STDIN using basic API
  • Example#4207 - polling STDIN using buffered event API
  • Example#4208 - Process Control Example
  • Example#4209 - pcntl_fork example
  • Example#4210 - pcntl_signal_dispatch example
  • Example#4211 - pcntl_signal_get_handler example
  • Example#4212 - pcntl_signal example
  • Example#4213 - pcntl_sigprocmask example
  • Example#4214 - pcntl_sigwaitinfo example
  • Example#4215 - posix_access example
  • Example#4216 - posix_ctermid example
  • Example#4217 - posix_get_last_error example
  • Example#4218 - posix_getcwd example
  • Example#4219 - posix_getegid example
  • Example#4220 - posix_geteuid example
  • Example#4221 - posix_getgid example
  • Example#4222 - Example use of posix_getgrgid
  • Example#4223 - Example use of posix_getgrnam
  • Example#4224 - Example use of posix_getgroups
  • Example#4225 - Example use of posix_getlogin
  • Example#4226 - Example use of posix_getpgid
  • Example#4227 - Example use of posix_getpid
  • Example#4228 - Example use of posix_getppid
  • Example#4229 - Example use of posix_getpwnam
  • Example#4230 - Example use of posix_getpwuid
  • Example#4231 - Example use of posix_getrlimit
  • Example#4232 - Example use of posix_getsid
  • Example#4233 - Example use of posix_getuid
  • Example#4234 - A posix_mknod example
  • Example#4235 - posix_setegid example
  • Example#4236 - posix_setgid example
  • Example#4237 - posix_setuid example
  • Example#4238 - posix_strerror example
  • Example#4239 - Example use of posix_times
  • Example#4240 - Example use of posix_uname
  • Example#4241 - escapeshellarg example
  • Example#4242 - escapeshellcmd example
  • Example#4243 - An exec example
  • Example#4244 - Using proc_open to set the process priority to high
  • Example#4245 - A proc_open example
  • Example#4246 - A shell_exec example
  • Example#4247 - system example
  • Example#4248 - Fetch a chunk of the property table
  • Example#4249 - Counting the properties of an object
  • Example#4250 - Runtime inheritance
  • Example#4251 - Thread safe objects from closures
  • Example#4252 - Detecting fatal errors in Threads
  • Example#4253 - Detect the state of the referenced object
  • Example#4254 - Detect the state of the referenced object
  • Example#4255 - Detect the state of the referenced object
  • Example#4256 - Locking Object Properties
  • Example#4257 - Merging into the property table of a threaded object
  • Example#4258 - Notifications and Waiting
  • Example#4259 - Popping the last item from the property table of a threaded object
  • Example#4260 - Shifting the first item from the property table of a threaded object
  • Example#4261 - Synchronizing
  • Example#4262 - Locking the property table of a threaded object
  • Example#4263 - Notifications and Waiting
  • Example#4264 - Return the identity of the Thread or Process that created the referenced Thread
  • Example#4265 - Return the currently executing Thread
  • Example#4266 - Return the identity of the currently executing Thread
  • Example#4267 - Return the identity of the referenced Thread
  • Example#4268 - Execute in the global scope
  • Example#4269 - Detect the state of the referenced Thread
  • Example#4270 - Tell if the referenced Thread was started
  • Example#4271 - Join with the referenced Thread
  • Example#4272 - Kill the referenced Thread
  • Example#4273 - Starting Threads
  • Example#4274 - A basic example of Worker::collect
  • Example#4275 - A basic example of Worker::getStacked
  • Example#4276 - Detect the state of a worker
  • Example#4277 - Detect the state of a Worker
  • Example#4278 - Shutdown the referenced worker
  • Example#4279 - Stacking a task for execution onto a worker
  • Example#4280 - Removing objects from the stack of Workers
  • Example#4281 - protected method example: protected methods can only be executed by one Thread at a time.
  • Example#4282 - private method example: private methods may only be executed by the Threaded object during execution
  • Example#4283 - A basic example of Pool::collect
  • Example#4284 - Creating Pools
  • Example#4285 - Shutting down a pool
  • Example#4286 - Submitting Tasks
  • Example#4287 - Submitting tasks to a specific worker
  • Example#4288 - Mutex Creation and Destruction
  • Example#4289 - Mutex Creation and Destruction
  • Example#4290 - Mutex Locking and Unlocking
  • Example#4291 - Mutex Locking and Unlocking
  • Example#4292 - Mutex Locking and Unlocking
  • Example#4293 - Condition Broadcasting
  • Example#4294 - Condition Creation and Destruction
  • Example#4295 - Condition Creation and Destruction
  • Example#4296 - Condition Signalling
  • Example#4297 - Waiting for Conditions
  • Example#4298 -
  • Example#4299 - Shared Memory Operations Overview
  • Example#4300 - Closing shared memory block
  • Example#4301 - Deleting shared memory block
  • Example#4302 - Create a new shared memory block
  • Example#4303 - Reading shared memory block
  • Example#4304 - Getting the size of the shared memory block
  • Example#4305 - Writing to shared memory block
  • Example#4306 - SyncMutex::__construct named mutex with lock timeout example
  • Example#4307 - SyncMutex::__construct unnamed mutex example
  • Example#4308 - SyncMutex::lock example
  • Example#4309 - SyncMutex::unlock example
  • Example#4310 - SyncSemaphore::__construct example
  • Example#4311 - SyncSemaphore::lock example
  • Example#4312 - SyncSemaphore::unlock example
  • Example#4313 - SyncEvent::__construct example
  • Example#4314 - SyncEvent::fire example
  • Example#4315 - SyncEvent::reset example
  • Example#4316 - SyncEvent::wait example
  • Example#4317 - SyncReaderWriter::__construct example
  • Example#4318 - SyncReaderWriter::readlock example
  • Example#4319 - SyncReaderWriter::readunlock example
  • Example#4320 - SyncReaderWriter::writelock example
  • Example#4321 - SyncReaderWriter::writeunlock example
  • Example#4322 - SyncSharedMemory::__construct example
  • Example#4323 - SyncSharedMemory::first example
  • Example#4324 - SyncSharedMemory::__construct example
  • Example#4325 - SyncSharedMemory::size example
  • Example#4326 - SyncSharedMemory::write example
  • Example#4327 - A geoip_asnum_by_name example
  • Example#4328 - A geoip_continent_code_by_name example
  • Example#4329 - A geoip_country_code_by_name example
  • Example#4330 - A geoip_country_code3_by_name example
  • Example#4331 - A geoip_country_name_by_name example
  • Example#4332 - A geoip_database_info example
  • Example#4333 - A geoip_db_avail example
  • Example#4334 - A geoip_db_filename example
  • Example#4335 - A geoip_db_get_all_info example
  • Example#4336 - A geoip_db_get_all_info example
  • Example#4337 - A geoip_domain_by_name example
  • Example#4338 - A geoip_id_by_name example
  • Example#4339 - A geoip_isp_by_name example
  • Example#4340 - A geoip_netspeedcell_by_name example
  • Example#4341 - A geoip_org_by_name example
  • Example#4342 - A geoip_record_by_name example
  • Example#4343 - A geoip_region_by_name example
  • Example#4344 - A geoip_region_name_by_code example using region code for US/Canada
  • Example#4345 - A geoip_region_name_by_code example using FIPS codes
  • Example#4346 - A geoip_setup_custom_directory example
  • Example#4347 - A geoip_time_zone_by_country_and_region example using region code for US/Canada
  • Example#4348 - A geoip_time_zone_by_country_and_region example using FIPS codes
  • Example#4349 - xor.data file
  • Example#4350 - Simple train
  • Example#4351 - Simple test
  • Example#4352 - fann_create_train_from_callback example
  • Example#4353 - fann_read_train_from_file example
  • Example#4354 - JsonSerializable::jsonSerialize example returning an array
  • Example#4355 - JsonSerializable::jsonSerialize example returning an associative array
  • Example#4356 - JsonSerializable::jsonSerialize example returning an integer
  • Example#4357 - JsonSerializable::jsonSerialize example returning a string
  • Example#4358 - Exemple json_decode
  • Example#4359 - Accesarea proprieta?ilor nevalide ale unui obiect
  • Example#4360 - Gre?eli tipice la utilizarea json_decode
  • Example#4361 - Erori la parametrul depth
  • Example#4362 - json_decode cu numere întregi mari
  • Example#4363 - Un exemplu json_encode
  • Example#4364 - Un exemplu json_encode ce demonstreaza utilizarea op?iunilor
  • Example#4365 - Exemplu a op?iunii JSON_NUMERIC_CHECK
  • Example#4366 - Un exemplu cu tablou secven?ial versus un tablou non-secven?ial
  • Example#4367 - Exemplu cu op?iunea JSON_PRESERVE_ZERO_FRACTION
  • Example#4368 - Exemplu json_last_error
  • Example#4369 - Exemplu json_last_error cu json_encode
  • Example#4370 - Judy array example
  • Example#4371 - Lua::assignexample
  • Example#4372 - Lua::callexample
  • Example#4373 - Lua::evalexample
  • Example#4374 - Lua::registerCallbackexample
  • Example#4375 - LuaClosure::__invokeexample
  • Example#4376 - constant example
  • Example#4377 - Defining Constants
  • Example#4378 - Checking Constants
  • Example#4379 - eval example - simple text merge
  • Example#4380 - exit example
  • Example#4381 - exit status example
  • Example#4382 - Shutdown functions and destructors run regardless
  • Example#4383 - Listing all information about the users browser
  • Example#4384 - A __halt_compiler example
  • Example#4385 - highlight_string example
  • Example#4386 - A ignore_user_abort example
  • Example#4387 - pack example
  • Example#4388 - php_strip_whitespace example
  • Example#4389 - sleep example
  • Example#4390 - A sys_getloadavg example
  • Example#4391 - time_nanosleep example
  • Example#4392 - A time_sleep_until example
  • Example#4393 - uniqid Example
  • Example#4394 - unpack example
  • Example#4395 - unpack example with a repeater
  • Example#4396 - unpack example with unnamed keys
  • Example#4397 - usleep example
  • Example#4398 - parsekit_compile_file example
  • Example#4399 - parsekit_compile_string example
  • Example#4400 - parsekit_func_arginfo example
  • Example#4401 - SplDoublyLinkedList::__construct example
  • Example#4402 - SplStack::__construct example
  • Example#4403 - SplQueue::__construct example
  • Example#4404 - Efficiently handling tasks with SplQueue
  • Example#4405 - SplFixedArray usage example
  • Example#4406 - SplFixedArray::__construct example
  • Example#4407 - SplFixedArray::count example
  • Example#4408 - SplFixedArray::fromArray example
  • Example#4409 - SplFixedArray::getSize example
  • Example#4410 - SplFixedArray::setSize example
  • Example#4411 - SplFixedArray::toArray example
  • Example#4412 - SplObjectStorage as a set
  • Example#4413 - SplObjectStorage as a map
  • Example#4414 - SplObjectStorage::addAll example
  • Example#4415 - SplObjectStorage::attach example
  • Example#4416 - SplObjectStorage::contains example
  • Example#4417 - SplObjectStorage::count example
  • Example#4418 - SplObjectStorage::current example
  • Example#4419 - SplObjectStorage::detach example
  • Example#4420 - SplObjectStorage::getHash example
  • Example#4421 - SplObjectStorage::getInfo example
  • Example#4422 - SplObjectStorage::key example
  • Example#4423 - SplObjectStorage::next example
  • Example#4424 - SplObjectStorage::offsetExists example
  • Example#4425 - SplObjectStorage::offsetGet example
  • Example#4426 - SplObjectStorage::offsetSet example
  • Example#4427 - SplObjectStorage::offsetUnset example
  • Example#4428 - SplObjectStorage::removeAll example
  • Example#4429 - SplObjectStorage::removeAllExcept example
  • Example#4430 - SplObjectStorage::rewind example
  • Example#4431 - SplObjectStorage::serialize example
  • Example#4432 - SplObjectStorage::setInfo example
  • Example#4433 - SplObjectStorage::unserialize example
  • Example#4434 - SplObjectStorage::valid example
  • Example#4435 - AppendIterator::append example
  • Example#4436 - Iterating AppendIterator with foreach
  • Example#4437 - Iterating AppendIterator with the AppendIterator API
  • Example#4438 - AppendIterator::getInnerIterator example
  • Example#4439 - AppendIterator.getIteratorIndex basic example
  • Example#4440 - AppendIterator::key basic example
  • Example#4441 - ArrayIterator::current example
  • Example#4442 - ArrayIterator::key example
  • Example#4443 - ArrayIterator::next example
  • Example#4444 - ArrayIterator::rewind example
  • Example#4445 - ArrayIterator::valid example
  • Example#4446 - CachingIterator::getCache example
  • Example#4447 - Available callback arguments
  • Example#4448 - Callback basic examples
  • Example#4449 - A DirectoryIterator::__construct example
  • Example#4450 - A DirectoryIterator::current example
  • Example#4451 - A DirectoryIterator::getATime example
  • Example#4452 - A DirectoryIterator::getBasename example
  • Example#4453 - DirectoryIterator::getCTime example
  • Example#4454 - DirectoryIterator::getExtension example
  • Example#4455 -
  • Example#4456 - A DirectoryIterator::getFilename example
  • Example#4457 - DirectoryIterator::getGroup example
  • Example#4458 - DirectoryIterator::getInode example
  • Example#4459 - A DirectoryIterator::getMTime example
  • Example#4460 - DirectoryIterator::getOwner example
  • Example#4461 - DirectoryIterator::getPath example
  • Example#4462 - DirectoryIterator::getPathname example
  • Example#4463 - DirectoryIterator::getPerms example
  • Example#4464 - DirectoryIterator::getSize example
  • Example#4465 - DirectoryIterator::getType example
  • Example#4466 - DirectoryIterator::isDir example
  • Example#4467 - A DirectoryIterator::isDot example
  • Example#4468 - DirectoryIterator::isExecutable example
  • Example#4469 - DirectoryIterator::isFile example
  • Example#4470 - A DirectoryIterator::isLink example
  • Example#4471 - DirectoryIterator::isReadable example
  • Example#4472 - DirectoryIterator::isWritable example
  • Example#4473 - A DirectoryIterator::key example
  • Example#4474 - DirectoryIterator::next example
  • Example#4475 - DirectoryIterator::rewind example
  • Example#4476 - DirectoryIterator::seek example
  • Example#4477 - A DirectoryIterator::__toString example
  • Example#4478 - A DirectoryIterator::valid example
  • Example#4479 - FilesystemIterator::__construct example
  • Example#4480 - FilesystemIterator::current example
  • Example#4481 - FilesystemIterator::key example
  • Example#4482 - FilesystemIterator::next example
  • Example#4483 - FilesystemIterator::rewind example
  • Example#4484 - FilesystemIterator::key example
  • Example#4485 - FilterIterator::accept example
  • Example#4486 - GlobIterator example
  • Example#4487 - GlobIterator::count example
  • Example#4488 - InfiniteIterator::__construct example
  • Example#4489 - LimitIterator usage example
  • Example#4490 - LimitIterator::__construct example
  • Example#4491 - LimitIterator::getPosition example
  • Example#4492 - Iterating a MultipleIterator
  • Example#4493 - NoRewindIterator::__construct example
  • Example#4494 - NoRewindIterator::rewind example
  • Example#4495 - RecursiveArrayIterator::getChildren example
  • Example#4496 - RecursiveArrayIterator::hasChildren example
  • Example#4497 - Available callback arguments
  • Example#4498 - Recursive callback basic example
  • Example#4499 - RecursiveCallbackFilterIterator::hasChildren basic usage
  • Example#4500 - RecursiveDirectoryIterator example
  • Example#4501 - Basic RecursiveFilterIterator example
  • Example#4502 - RecursiveFilterIterator example
  • Example#4503 - Iterating a RecursiveIteratorIterator
  • Example#4504 - RecursiveRegexIterator::__construct example
  • Example#4505 - RecursiveRegexIterator::getChildren example
  • Example#4506 - RecursiveRegexIterator::hasChildren example
  • Example#4507 - RegexIterator::accept example
  • Example#4508 - RegexIterator::__construct example
  • Example#4509 - RegexIterator::getFlags example
  • Example#4510 - RegexIterator::getMode example
  • Example#4511 - RegexIterator::getPregFlags example
  • Example#4512 - RegexIterator::setFlags example
  • Example#4513 - RegexIterator::setMode example
  • Example#4514 - RegexIterator::setPregFlags example
  • Example#4515 - Countable::count example
  • Example#4516 - Basic usage
  • Example#4517 - SeekableIterator::seek example
  • Example#4518 - class_implements example
  • Example#4519 - class_parents example
  • Example#4520 - class_uses example
  • Example#4521 - iterator_apply example
  • Example#4522 - iterator_count example
  • Example#4523 - iterator_count modifies position
  • Example#4524 - iterator_count in foreach loops
  • Example#4525 - iterator_to_array example
  • Example#4526 - spl_autoload_register as a replacement for an __autoload function
  • Example#4527 - spl_autoload_register example where the class is not loaded
  • Example#4528 - spl_classes example
  • Example#4529 - A spl_object_hash example
  • Example#4530 - SplFileInfo::__construct example
  • Example#4531 - SplFileInfo::getBasename example
  • Example#4532 - SplFileInfo::getCTime example
  • Example#4533 - SplFileInfo::getExtension example
  • Example#4534 -
  • Example#4535 - SplFileInfo::getFilename example
  • Example#4536 - SplFileInfo::getGroup example
  • Example#4537 - SplFileInfo::getLinkTarget example
  • Example#4538 - SplFileInfo::getOwner example
  • Example#4539 - SplFileInfo::getPath example
  • Example#4540 - SplFileInfo::getPathInfo example
  • Example#4541 - SplFileInfo::getPathname example
  • Example#4542 - SplFileInfo::getPerms example
  • Example#4543 - SplFileInfo::getRealPath example
  • Example#4544 - SplFileInfo::getType example
  • Example#4545 - SplFileInfo::isDir example
  • Example#4546 - SplFileInfo::isExecutable example
  • Example#4547 - SplFileInfo::isFile example
  • Example#4548 - SplFileInfo::isLink example
  • Example#4549 - SplFileInfo::isReadable example
  • Example#4550 - SplFileInfo::openFile example
  • Example#4551 - SplFileInfo::setFileClass example
  • Example#4552 - SplFileInfo::setFileClass example
  • Example#4553 - SplFileInfo::__toString example
  • Example#4554 - SplFileObject::__construct example
  • Example#4555 - SplFileObject::current example
  • Example#4556 - SplFileObject::eof example
  • Example#4557 - SplFileObject::fflush example
  • Example#4558 - SplFileObject::fgetc example
  • Example#4559 - SplFileObject::fgetcsv example
  • Example#4560 - SplFileObject::READ_CSV example
  • Example#4561 - SplFileObject::fgets example
  • Example#4562 - SplFileObject::fgetss example
  • Example#4563 - SplFileObject::flock example
  • Example#4564 - SplFileObject::fpassthru example
  • Example#4565 - SplFileObject::fputcsv example
  • Example#4566 - SplFileObject::fread example
  • Example#4567 - SplFileObject::fscanf example
  • Example#4568 - SplFileObject::fseek example
  • Example#4569 - SplFileObject::fstat example
  • Example#4570 - SplFileObject::ftell example
  • Example#4571 - SplFileObject::ftruncate example
  • Example#4572 - SplFileObject::fwrite example
  • Example#4573 - SplFileObject::getCsvControl example
  • Example#4574 - SplFileObject::getFlags example
  • Example#4575 - SplFileObject::getMaxLineLen example
  • Example#4576 - SplFileObject::key example
  • Example#4577 - SplFileObject::key example with SplFileObject::setMaxLineLen
  • Example#4578 - SplFileObject::next example
  • Example#4579 - SplFileObject::rewind example
  • Example#4580 - SplFileObject::seek example
  • Example#4581 - SplFileObject::setCsvControl example
  • Example#4582 - SplFileObject::setFlags example
  • Example#4583 - SplFileObject::setMaxLineLen example
  • Example#4584 - SplFileObject::valid example
  • Example#4585 - SplTempFileObject example
  • Example#4586 - ArrayObject::append example
  • Example#4587 - ArrayObject::asort example
  • Example#4588 - ArrayObject::__construct example
  • Example#4589 - ArrayObject::count example
  • Example#4590 - ArrayObject::exchangeArray example
  • Example#4591 - ArrayObject::getArrayCopy example
  • Example#4592 - ArrayObject::getFlags example
  • Example#4593 - ArrayObject::getIterator example
  • Example#4594 - ArrayObject::getIteratorClass example
  • Example#4595 - ArrayObject::ksort example
  • Example#4596 - ArrayObject::natcasesort example
  • Example#4597 - ArrayObject::natsort example
  • Example#4598 - ArrayObject::offsetExists example
  • Example#4599 - ArrayObject::offsetGet example
  • Example#4600 - ArrayObject::offsetSet example
  • Example#4601 - ArrayObject::offsetUnset example
  • Example#4602 - ArrayObject::serialize example
  • Example#4603 - ArrayObject::setFlags example
  • Example#4604 - ArrayObject::setIteratorClass example
  • Example#4605 - ArrayObject::uasort example
  • Example#4606 - ArrayObject::uksort example
  • Example#4607 - SplInt usage example
  • Example#4608 - SplFloat usage example
  • Example#4609 - SplEnum usage example
  • Example#4610 - SplEnum::getConstList example
  • Example#4611 - SplBool usage example
  • Example#4612 - SplString usage example
  • Example#4613 - Using file_get_contents to retrieve data from multiple sources
  • Example#4614 - Making a POST request to an https server
  • Example#4615 - Writing data to a compressed file
  • Example#4616 - A Stream for reading/writing global variables
  • Example#4617 - Listing files from tar archives
  • Example#4618 - stream_bucket_prepend examples
  • Example#4619 - Using stream_context_create
  • Example#4620 - Using stream_context_get_default
  • Example#4621 - stream_context_get_options example
  • Example#4622 - stream_context_get_params example
  • Example#4623 - stream_context_set_default example
  • Example#4624 - A stream_copy_to_stream example
  • Example#4625 - Controlling where filters are applied
  • Example#4626 - Filter for capitalizing characters on foo-bar.txt stream
  • Example#4627 - Registering a generic filter class to match multiple filter names.
  • Example#4628 - Dynamicly refiltering a stream
  • Example#4629 - stream_get_contents example
  • Example#4630 - Using stream_get_filters
  • Example#4631 - stream_get_meta_data example
  • Example#4632 - Using stream_get_transports
  • Example#4633 - stream_get_wrappers example
  • Example#4634 - Checking for the existence of a stream wrapper
  • Example#4635 - stream_is_local example
  • Example#4636 - stream_notification_callback example
  • Example#4637 - Simple progressbar for commandline download client
  • Example#4638 - stream_resolve_include_path example
  • Example#4639 - stream_select Example
  • Example#4640 - stream_set_timeout example
  • Example#4641 - stream_set_write_buffer example
  • Example#4642 - stream_socket_client example
  • Example#4643 - Using UDP connection
  • Example#4644 - stream_socket_enable_crypto example
  • Example#4645 - A stream_socket_pair example
  • Example#4646 - stream_socket_recvfrom example
  • Example#4647 - stream_socket_sendto Example
  • Example#4648 - Using TCP server sockets
  • Example#4649 - Using UDP server sockets
  • Example#4650 - A stream_socket_shutdown example
  • Example#4651 - How to register a stream wrapper
  • Example#4652 - Basic Tidy usage
  • Example#4653 - tidy::getBody example
  • Example#4654 - tidy::cleanrepair example
  • Example#4655 - tidy::__construct example
  • Example#4656 - tidy::diagnose example
  • Example#4657 - tidy_get_error_buffer example
  • Example#4658 - tidy::getConfig example
  • Example#4659 - tidy_getopt example
  • Example#4660 - Print all options along with their documentation and default value
  • Example#4661 - tidy::getStatus example
  • Example#4662 - tidy::head example
  • Example#4663 - tidy::html example
  • Example#4664 - tidy::parseFile example
  • Example#4665 - tidy::parseString example
  • Example#4666 - tidy::repairFile example
  • Example#4667 - tidy::repairString example
  • Example#4668 - tidy::root example
  • Example#4669 - tidyNode::hasChildren example
  • Example#4670 - tidyNode::hasChildren example
  • Example#4671 - tidyNode::hasSiblings example
  • Example#4672 - Extract ASP code from a mixed HTML document
  • Example#4673 - Extract comments from a mixed HTML document
  • Example#4674 - Extract HTML code from a mixed HTML document
  • Example#4675 - Extract JSTE code from a mixed HTML document
  • Example#4676 - Extract PHP code from a mixed HTML document
  • Example#4677 - Extract text from a mixed HTML document
  • Example#4678 - ob_tidyhandler example
  • Example#4679 - tidy_access_count example
  • Example#4680 - tidy_config_count example
  • Example#4681 - tidy_error_count example
  • Example#4682 - tidy_get_output example
  • Example#4683 - tidy_setopt example
  • Example#4684 - tidy_warning_count example
  • Example#4685 - Strip comments with the tokenizer
  • Example#4686 - token_get_all example
  • Example#4687 - token_get_all incorrect usage example
  • Example#4688 - token_get_all on a class using a reserved word example
  • Example#4689 - token_name example
  • Example#4690 - base64_decode example
  • Example#4691 - base64_encode example
  • Example#4692 - get_headers example
  • Example#4693 - get_headers using HEAD example
  • Example#4694 - What get_meta_tags parses
  • Example#4695 - What get_meta_tags returns
  • Example#4696 - Simple usage of http_build_query
  • Example#4697 - http_build_query with numerically index elements.
  • Example#4698 - http_build_query with complex arrays
  • Example#4699 - Using http_build_query with an object
  • Example#4700 - A parse_url example
  • Example#4701 - A parse_url example with missing scheme
  • Example#4702 - rawurldecode example
  • Example#4703 - including a password in an FTP URL
  • Example#4704 - rawurlencode example 2
  • Example#4705 - urldecode example
  • Example#4706 - urlencode example
  • Example#4707 - urlencode and htmlentities example
  • Example#4708 - Executarea de baza a unui Javascript
  • Example#4709 - Yaml Example
  • Example#4710 - Parse callback example
  • Example#4711 - Emit callback example
  • Example#4712 - yaml_emit example
  • Example#4713 - yaml_parse example
  • Example#4714 - A classic Application directory layout
  • Example#4715 - Entry
  • Example#4716 - Rewrite rule
  • Example#4717 - Application config
  • Example#4718 - Default controller
  • Example#4719 - Default view template
  • Example#4720 - Run the Applicatioin
  • Example#4721 - An PHP array example
  • Example#4722 - An ini file example
  • Example#4723 - A Bootstrapexample
  • Example#4724 - Yaf_Application::bootstrapexample
  • Example#4725 - Yaf_Application::clearLastErrorexample
  • Example#4726 - A ini config file example
  • Example#4727 - Yaf_Application::__constructexample
  • Example#4728 - Yaf_Application::__constructexample
  • Example#4729 - Yaf_Application::environexample
  • Example#4730 - Yaf_Application::executeexample
  • Example#4731 - Yaf_Application::getConfigexample
  • Example#4732 - Yaf_Application::getDispatcherexample
  • Example#4733 - Yaf_Application::getLastErrorMsgexample
  • Example#4734 - Yaf_Application::getLastErrorNoexample
  • Example#4735 - Yaf_Application::getModulesexample
  • Example#4736 - Bootstrap example
  • Example#4737 - Yaf_Dispatcher::autoRenderexample
  • Example#4738 - Yaf_Dispatcher::catchExceptionexample
  • Example#4739 - Yaf_Dispatcher::registerPluginexample
  • Example#4740 - A custom View engineexample
  • Example#4741 - Yaf_Dispatcher::setViewexample
  • Example#4742 - Yaf_Dispatcher::throwexceptionexample
  • Example#4743 - Yaf_Dispatcher::throwexceptionexample
  • Example#4744 - Yaf_Config_Iniexample
  • Example#4745 - define action in a separate file
  • Example#4746 - Dummy_action.php
  • Example#4747 - Yaf_Controller_Abstract::forwardexample
  • Example#4748 - Yaf_Action_Abstract::executeexample
  • Example#4749 - Yaf_Action_Abstract::executeexample
  • Example#4750 - Yaf_View_Simple::assignexample
  • Example#4751 - templateexample
  • Example#4752 - Yaf_View_Simple::assignRefexample
  • Example#4753 - templateexample
  • Example#4754 - Yaf_View_Simple::clearexample
  • Example#4755 - Yaf_View_Simple::__constructorexample
  • Example#4756 - Yaf_View_Simple::__setexample
  • Example#4757 - Config example
  • Example#4758 - Register localnamespace
  • Example#4759 - Load class example
  • Example#4760 - Load namespace class example
  • Example#4761 - MVC class loading example
  • Example#4762 - MVC class distinctions
  • Example#4763 - MVC loading example
  • Example#4764 - Yaf_Loader::registerLocalNamespaceexample
  • Example#4765 - Plugin example
  • Example#4766 - Yaf_Plugin_Abstract::routerShutdownexample
  • Example#4767 - Yaf_Response_Abstract::appendBodyexample
  • Example#4768 - Yaf_Response_Abstract::getBodyexample
  • Example#4769 - Yaf_Response_Abstract::prependBodyexample
  • Example#4770 - Yaf_Response_Abstract::responseexample
  • Example#4771 - Yaf_Response_Abstract::setBodyexample
  • Example#4772 - Yaf_Route_Map::assembleexample
  • Example#4773 - Yaf_Route_Mapexample
  • Example#4774 - Yaf_Route_Mapexample
  • Example#4775 - Yaf_Route_Mapexample
  • Example#4776 - Yaf_Route_Regex::assembleexample
  • Example#4777 - Yaf_Route_Regexexample
  • Example#4778 - Yaf_Route_Regex(as of 2.3.0)example
  • Example#4779 - Yaf_Route_Regex and named capture ground(as of 2.3.0)example
  • Example#4780 - Yaf_Route_Regexexample
  • Example#4781 - Yaf_Route_Rewrite::assembleexample
  • Example#4782 - Yaf_Route_Rewriteexample
  • Example#4783 - Yaf_Route_Rewriteexample
  • Example#4784 - Yaf_Route_Rewrite(as of 2.3.0)example
  • Example#4785 - Rewrite rule for Apache
  • Example#4786 - Rewrite rule for Apache
  • Example#4787 - Rewrite rule for Lighttpd
  • Example#4788 - Rewrite rule for Nginx
  • Example#4789 - Yaf_Route_Static(default route)example
  • Example#4790 - application.iniexample
  • Example#4791 - Yaf_Dispatcher::autoConfigexample
  • Example#4792 - Yaf_Dispatcher::autoRenderexample
  • Example#4793 - Register some routes in Bootstrap
  • Example#4794 - plugin Dummy.php (under application.directory/plugins)
  • Example#4795 - Yaf_Route_Simple::assembleexample
  • Example#4796 - Yaf_Route_Simple::routeexample
  • Example#4797 - Yaf_Route_Simple::routeexample
  • Example#4798 - Yaf_Route_Static::assembleexample
  • Example#4799 - Yaf_Route_Static::routeexample
  • Example#4800 - Yaf_Route_Supervar::assembleexample
  • Example#4801 - Yaf_Route_Supervarexample
  • Example#4802 - Taintexample
  • Example#4803 - Creating a chdb file
  • Example#4804 - Loading and looking up a chdb file
  • Example#4805 - chdb::get example
  • Example#4806 - chdb_create example
  • Example#4807 - Using PHP's cURL module to fetch the example.com homepage
  • Example#4808 - Initializing a new cURL session and fetching a web page
  • Example#4809 - Copying a cURL handle
  • Example#4810 - curl_errno example
  • Example#4811 - curl_error example
  • Example#4812 - curl_escape example
  • Example#4813 - Fetching a web page
  • Example#4814 - curl_getinfo example
  • Example#4815 - curl_getinfo example with opt parameter
  • Example#4816 - Initializing a new cURL session and fetching a web page
  • Example#4817 - curl_multi_add_handle example
  • Example#4818 - curl_multi_close example
  • Example#4819 - curl_multi_exec example
  • Example#4820 - A curl_multi_info_read example
  • Example#4821 - curl_multi_init example
  • Example#4822 - curl_multi_strerror example
  • Example#4823 - curl_reset example
  • Example#4824 - Initializing a new cURL session and fetching a web page
  • Example#4825 - Our own implementation of curl_setopt_array
  • Example#4826 - Initializing a new cURL session and fetching a web page
  • Example#4827 - Uploading file (deprecated as of PHP 5.5.0)
  • Example#4828 - curl_share_setopt example
  • Example#4829 - curl_share_init example
  • Example#4830 - curl_share_setopt example
  • Example#4831 - curl_errno example
  • Example#4832 - curl_escape example
  • Example#4833 - curl_version example
  • Example#4834 - CURLFile::__construct example
  • Example#4835 - Simple HTTP client
  • Example#4836 - HTTP client using asynchronous DNS resolver
  • Example#4837 - Echo server
  • Example#4838 - SSL echo server
  • Example#4839 - Signal handler
  • Example#4840 - Use libevent's loop to process requests of `eio' extension
  • Example#4841 - Miscellaneous
  • Example#4842 - Simple HTTP server
  • Example#4843 - Simple HTTPS server
  • Example#4844 - OpenSSL connection
  • Example#4845 - EventHttpConnection::makeRequest example
  • Example#4846 - Connection listener based on a UNIX domain socket
  • Example#4847 - Simple SMTP server
  • Example#4848 - Handling SIGTERM signal
  • Example#4849 - Event::addSignal example
  • Example#4850 - Event::addTimer example
  • Example#4851 - EventBase::getFeatures example
  • Example#4852 - EventBase::getMethod example
  • Example#4853 - EventBuffer::search example
  • Example#4854 - EventBufferEvent::connect example
  • Example#4855 - Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console
  • Example#4856 - EventBufferEvent::connectHost example
  • Example#4857 - Buffer event's read callback
  • Example#4858 - EventBufferEvent::getOutput example
  • Example#4859 - EventBufferEvent::sslError example
  • Example#4860 - Simple SMTP server
  • Example#4861 - EventConfig::avoidMethod example
  • Example#4862 - EventConfig::__construct example
  • Example#4863 - EventConfig::requireFeatures example
  • Example#4864 - EventHttp::accept example
  • Example#4865 - EventHttp::addServerAlias example
  • Example#4866 - EventHttp::bind example
  • Example#4867 - Simple HTTP server
  • Example#4868 - EventHttp::setCallback example
  • Example#4869 - EventHttp::setDefaultCallback example
  • Example#4870 - EventHttpConnection::makeRequest example
  • Example#4871 - EventHttpConnection::setCloseCallback example
  • Example#4872 - EventHttpRequest::__construct example
  • Example#4873 - EventHttpRequest::sendError example
  • Example#4874 - EventListener::__construct example
  • Example#4875 - EventSslContext::__construct example
  • Example#4876 - FTP example
  • Example#4877 - ftp_alloc example
  • Example#4878 - ftp_cdup example
  • Example#4879 - ftp_chdir example
  • Example#4880 - ftp_chmod example
  • Example#4881 - ftp_close example
  • Example#4882 - ftp_connect example
  • Example#4883 - ftp_delete example
  • Example#4884 - ftp_exec example
  • Example#4885 - ftp_fget example
  • Example#4886 - ftp_fput example
  • Example#4887 - ftp_get_option example
  • Example#4888 - ftp_get example
  • Example#4889 - ftp_login example
  • Example#4890 - ftp_mdtm example
  • Example#4891 - ftp_mkdir example
  • Example#4892 - ftp_nb_continue example
  • Example#4893 - ftp_nb_fget example
  • Example#4894 - ftp_nb_fput example
  • Example#4895 - ftp_nb_get example
  • Example#4896 - Resuming a download with ftp_nb_get
  • Example#4897 - Resuming a download at position 100 to a new file with ftp_nb_get
  • Example#4898 - ftp_nb_put example
  • Example#4899 - Resuming an upload with ftp_nb_put
  • Example#4900 - ftp_nlist example
  • Example#4901 - ftp_pasv example
  • Example#4902 - ftp_put example
  • Example#4903 - ftp_pwd example
  • Example#4904 - Using ftp_raw to login to an FTP server manually.
  • Example#4905 - ftp_rawlist example
  • Example#4906 - ftp_rename example
  • Example#4907 - ftp_rmdir example
  • Example#4908 - ftp_set_option example
  • Example#4909 - Sending a SITE command to an ftp server
  • Example#4910 - ftp_size example
  • Example#4911 - ftp_ssl_connect example
  • Example#4912 - ftp_systype example
  • Example#4913 - Basic Gearman client and worker
  • Example#4914 - Basic Gearman client and worker, background
  • Example#4915 - Basic Gearman client and worker, submitting tasks
  • Example#4916 - Adding two job servers
  • Example#4917 - Add two job servers
  • Example#4918 - Basic submission of two tasks
  • Example#4919 - Basic submission of two tasks with passing application context
  • Example#4920 - Two tasks, one background and one not
  • Example#4921 - A high priority task along with two normal tasks
  • Example#4922 - A low priority task along with two normal tasks
  • Example#4923 - Monitor completion of multiple background tasks
  • Example#4924 - Simple job submission with immediate return
  • Example#4925 - Submitting a job and retrieving incremental status
  • Example#4926 - Submit and monitor a background job
  • Example#4927 - Simple job submission with immediate return
  • Example#4928 - Submitting a job and retrieving incremental status
  • Example#4929 - Get the status of a long running job
  • Example#4930 - Monitor the status of a long running background job
  • Example#4931 - Simple worker making use of extra application context data
  • Example#4932 - Add alternate Gearman servers
  • Example#4933 - Add two job servers
  • Example#4934 - GearmanWorker::setId example
  • Example#4935 - A simple worker with a 5 second timeout
  • Example#4936 - Running worker in non-blocking mode
  • Example#4937 - GearmanWorker::work example
  • Example#4938 - Hypothetical output from gopher://gopher.example.com/
  • Example#4939 - Using gopher_parsedir
  • Example#4940 - Search for all UPnP devices and services.
  • Example#4941 - Implementing light server
  • Example#4942 - Implementing light client
  • Example#4943 - Create new UPnP context and get IP address of the host
  • Example#4944 - Create new UPnP context and get port number
  • Example#4945 - Create new UPnP context and set host path
  • Example#4946 - Create new UPnP context
  • Example#4947 - Create new UPnP context and set callback
  • Example#4948 - Create new UPnP context and start browsing
  • Example#4949 - Create new UPnP context and start browsing
  • Example#4950 - Create new UPnP context and get device info service
  • Example#4951 - Create new UPnP context and get device info service
  • Example#4952 - Retrieve an object
  • Example#4953 - LDAP search example
  • Example#4954 - Complete example with authenticated bind
  • Example#4955 - Using LDAP Bind
  • Example#4956 - Using LDAP Bind Anonymously
  • Example#4957 - Complete example of password check
  • Example#4958 - Example of connecting to LDAP server.
  • Example#4959 - Example of connecting securely to LDAP server.
  • Example#4960 - LDAP pagination
  • Example#4961 - LDAP pagination
  • Example#4962 - ldap-count-entries example
  • Example#4963 - Enumerating all LDAP error messages
  • Example#4964 - Generating and catching an error
  • Example#4965 - Show the list of attributes held for a particular directory entry
  • Example#4966 - Check protocol version
  • Example#4967 - List all values of the "mail" attribute for a directory entry
  • Example#4968 - Produce a list of all organizational units of an organization
  • Example#4969 - Add a telephone number to a contact
  • Example#4970 - Rename a user
  • Example#4971 - Add two e-mail addresses to a user
  • Example#4972 - Change a user's password
  • Example#4973 - Change a user's password (Active Directory)
  • Example#4974 - ldap_parse_result example
  • Example#4975 - LDAP search
  • Example#4976 - Set protocol version
  • Example#4977 - Set server controls
  • Example#4978 - LDAP sort
  • Example#4979 - memcache extension overview example
  • Example#4980 - Using memcache session handler
  • Example#4981 - Memcache::add example
  • Example#4982 - Memcache::addServer example
  • Example#4983 - Memcache::close example
  • Example#4984 - Memcache::connect example
  • Example#4985 - Memcache::decrement example
  • Example#4986 - Memcache::delete example
  • Example#4987 - Memcache::flush example
  • Example#4988 - Memcache::get example
  • Example#4989 - Memcache::getExtendedStats example
  • Example#4990 - Memcache::getServerStatus example
  • Example#4991 - Memcache::getVersion example
  • Example#4992 - Memcache::increment example
  • Example#4993 - Memcache::pconnect example
  • Example#4994 - Memcache::replace example
  • Example#4995 - Memcache::set example
  • Example#4996 - Memcache::set example
  • Example#4997 - Memcache::setCompressThreshold example
  • Example#4998 - Memcache::setServerParams example
  • Example#4999 - Result callback example
  • Example#5000 - Read-through callback example
  • Example#5001 - Memcached::addServer example
  • Example#5002 - Memcached::addServers example
  • Example#5003 - Memcached::append example
  • Example#5004 - Memcached::cas example
  • Example#5005 - Creating a Memcached object
  • Example#5006 - Memcached::decrement example
  • Example#5007 - Memcached::delete example
  • Example#5008 - Memcached::fetch example
  • Example#5009 - Memcached::getDelayed example
  • Example#5010 - Memcached::flush example
  • Example#5011 - Memcached::get example #1
  • Example#5012 - Memcached::get example #2
  • Example#5013 - Memcached::getDelayed example
  • Example#5014 - Memcached::getMulti example
  • Example#5015 - Memcached::GET_PRESERVE_ORDER example
  • Example#5016 - Retrieving Memcached options
  • Example#5017 - Memcached::getResultCode example
  • Example#5018 - Memcached::getResultMessage example
  • Example#5019 - Memcached::getServerByKey example
  • Example#5020 - Memcached::getServerList example
  • Example#5021 - Memcached::getStats example
  • Example#5022 - Memcached::getVersion example
  • Example#5023 - Memcached::increment example
  • Example#5024 - Memcached::prepend example
  • Example#5025 - Memcached::set example
  • Example#5026 - Memcached::setByKey example
  • Example#5027 - Memcached::setMulti example
  • Example#5028 - Setting a Memcached option
  • Example#5029 - Setting Memcached options
  • Example#5030 - mqseries_back example
  • Example#5031 - mqseries_begin example
  • Example#5032 - mqseries_close example
  • Example#5033 - mqseries_cmit example
  • Example#5034 - mqseries_conn example
  • Example#5035 - mqseries_connx example
  • Example#5036 - mqseries_connx example using SSL connection & OCSP Responder URL
  • Example#5037 - mqseries_disc example
  • Example#5038 - mqseries_get example
  • Example#5039 - mqseries_inq example
  • Example#5040 - mqseries_open example
  • Example#5041 - mqseries_put example
  • Example#5042 - mqseries_strerror example
  • Example#5043 - define_syslog_variables example
  • Example#5044 - Using dns_get_record
  • Example#5045 - Using dns_get_record and DNS_ANY
  • Example#5046 - fsockopen Example
  • Example#5047 - Using UDP connection
  • Example#5048 - A simple gethostbyaddr example
  • Example#5049 - A simple gethostbyname example
  • Example#5050 - gethostbynamel example
  • Example#5051 - A simple gethostname example
  • Example#5052 - getprotobyname example
  • Example#5053 - getservbyname example
  • Example#5054 - header_register_callback example
  • Example#5055 - Unsetting specific header.
  • Example#5056 - Unsetting all previously set headers.
  • Example#5057 - Download dialog
  • Example#5058 - Caching directives
  • Example#5059 - Examples using headers_list
  • Example#5060 - Examples using headers_sent
  • Example#5061 - Using http_response_code in a web server environment
  • Example#5062 - Using http_response_code in a CLI environment
  • Example#5063 - inet_ntop Example
  • Example#5064 - inet_pton Example
  • Example#5065 - ip2long Example
  • Example#5066 - Displaying an IP address
  • Example#5067 - setcookie send example
  • Example#5068 - setcookie delete example
  • Example#5069 - setcookie and arrays
  • Example#5070 - Using syslog
  • Example#5071 - Procedural usage of rrd
  • Example#5072 - OO usage of rrd
  • Example#5073 - RRDGraph::setOptions example
  • Example#5074 - Set multiple color options
  • Example#5075 - RRDUpdater::update examples
  • Example#5076 - Creating a connection and connecting to a remote WebSphere MQSeries Messaging Server
  • Example#5077 - Creating a connection and connecting to a remote WebSphere Application Server
  • Example#5078 - Creating a connection and connecting to an MQTT server
  • Example#5079 - Creating a message with a simple text body
  • Example#5080 - Setting a text format property using the default syntax
  • Example#5081 - Setting a property using a type hint
  • Example#5082 - Retrieving a property from a message header
  • Example#5083 - Adding a message to a queue and receiving a response
  • Example#5084 - Creating a durable subscription to a topic
  • Example#5085 - Subscribing to a topic using a WebSphere Platform Messaging (WPM) server
  • Example#5086 - Receiving published data using a durable subscription
  • Example#5087 - Deleting a durable subscription to a topic
  • Example#5088 - Handling an error from a method that returns no result
  • Example#5089 - Handling an error from a method that returns a result
  • Example#5090 - Committing the current unit of work
  • Example#5091 - Creating a connection to a Messaging Server using the IBM MQSeries protocol (WMQ)
  • Example#5092 - Creating a connection with application transaction control and default host and port values
  • Example#5093 - Creating a connection to a Messaging Server using the IBM WebSphere Platform Messaging protocol (WPM)
  • Example#5094 - Creating a connection object and connecting to a Messaging Server
  • Example#5095 - Disconnecting from a Messaging Server
  • Example#5096 - Using the error number and description properties
  • Example#5097 - Using the error number and description properties
  • Example#5098 - Checking whether there us a connection to a Messaging Server
  • Example#5099 - Retrieve the next message from a queue without removing it
  • Example#5100 - Retrieve a specific message from a queue without removing it from the queue
  • Example#5101 - Retrieve all messages in a queue without removing them
  • Example#5102 - Retrieve all messages from a queue with a matching correlation id
  • Example#5103 - Receiving a message from a queue
  • Example#5104 - Receiving a message from a queue with options
  • Example#5105 - Receiving a message from a subscription
  • Example#5106 - Removing a message from a queue by message id
  • Example#5107 - Cancelling an in-flight unit of work
  • Example#5108 - Send a message to a queue
  • Example#5109 - Publish a message to a topic
  • Example#5110 - Send a request and receive a response
  • Example#5111 - Turn on debugging output
  • Example#5112 - Turn off debugging output
  • Example#5113 - Subscribe to a topic
  • Example#5114 - Delete a subscription
  • Example#5115 - Setting a text string into the body of a message
  • Example#5116 - Creating a message
  • Example#5117 - Creating a message with a simple text payload
  • Example#5118 - Setting a text format property using the default syntax
  • Example#5119 - Setting a text format property using a type hint
  • Example#5120 - Setting properties as the sender of a message
  • Example#5121 - Retreiving property values from a message
  • Example#5122 - snmp_get_quick_print example
  • Example#5123 - Using snmp_get_valueretrieval
  • Example#5124 - Using snmp_read_mib
  • Example#5125 - Using snmp_set_enum_print
  • Example#5126 - Using snmprealwalk
  • Example#5127 - Using snmp_set_quick_print
  • Example#5128 - Using snmp_set_valueretrieval
  • Example#5129 - Using snmp2_get
  • Example#5130 - Using snmp2_get_next
  • Example#5131 - Using snmp2_real_walk
  • Example#5132 - Using snmp2_set
  • Example#5133 - Using snmp2_set for setting BITS SNMP object id
  • Example#5134 - snm2_pwalk Example
  • Example#5135 - Using snmp3_get
  • Example#5136 - Using snmp3_getnext
  • Example#5137 - Using snmp3_real_walk
  • Example#5138 - Using snmp3_set
  • Example#5139 - Using snmp3_set for setting BITS SNMP object id
  • Example#5140 - snmp3_walk Example
  • Example#5141 - Using snmpget
  • Example#5142 - Using snmpgetnext
  • Example#5143 - Using snmprealwalk
  • Example#5144 - Using snmpset
  • Example#5145 - Using snmpset for setting BITS SNMP object id
  • Example#5146 - snmpwalk Example
  • Example#5147 - snmpwalkoid Example
  • Example#5148 - SNMP::close example
  • Example#5149 - Fetching sysLocation
  • Example#5150 - Single SNMP object
  • Example#5151 - Multiple SNMP objects
  • Example#5152 - SNMP::getErrno example
  • Example#5153 - SNMP::getError example
  • Example#5154 - Single SNMP object
  • Example#5155 - Miltiple SNMP objects
  • Example#5156 - Set single SNMP object id
  • Example#5157 - Set multiple values using single SNMP::set call
  • Example#5158 - Using SNMP::set for setting BITS SNMP object id
  • Example#5159 - SNMP::setSecurity example
  • Example#5160 - SNMP::walk example
  • Example#5161 - suffix_as_key example
  • Example#5162 - Socket example: Simple TCP/IP server
  • Example#5163 - Socket example: Simple TCP/IP client
  • Example#5164 - Using socket_bind to set the source address
  • Example#5165 - socket_create_pair example
  • Example#5166 - socket_create_pair IPC example
  • Example#5167 - socket_get_option example
  • Example#5168 - socket_import_stream example
  • Example#5169 - socket_last_error example
  • Example#5170 - socket_recv example
  • Example#5171 - socket_recvfrom example
  • Example#5172 - Using NULL with socket_select
  • Example#5173 - Understanding socket_select's result
  • Example#5174 - socket_select example
  • Example#5175 - socket_sendto Example
  • Example#5176 - socket_set_block example
  • Example#5177 - socket_set_nonblock example
  • Example#5178 - socket_set_option example
  • Example#5179 - socket_strerror example
  • Example#5180 - Authenticating with a ssh agent
  • Example#5181 - Authentication using a public hostkey
  • Example#5182 - Retrieving a list of authentication methods
  • Example#5183 - Authenticating with a password
  • Example#5184 - Authentication using a public key
  • Example#5185 - ssh2_connect example
  • Example#5186 - Executing a command
  • Example#5187 - Opening a shell and retrieving the stderr stream associated with it
  • Example#5188 - Checking the fingerprint against a known value
  • Example#5189 - Determining what methods were negotiated
  • Example#5190 - Adding a publickey with ssh2_publickey_add
  • Example#5191 - Listing authorized keys with ssh2_publickey_list
  • Example#5192 - Downloading a file via SCP
  • Example#5193 - Uploading a file via SCP
  • Example#5194 - Changing the mode of a file on a remote server
  • Example#5195 - Stating a symbolic link via SFTP
  • Example#5196 - Creating a directory on a remote server
  • Example#5197 - Reading a symbolic link
  • Example#5198 - Resolving a pathname
  • Example#5199 - Renaming a file via sftp
  • Example#5200 - Removing a directory on a remote server
  • Example#5201 - Stating a file via SFTP
  • Example#5202 - Creating a symbolic link
  • Example#5203 - Deleting a file
  • Example#5204 - Opening a file via SFTP
  • Example#5205 - Requesting an interactive shell
  • Example#5206 - Opening a tunnel to an arbitrary host
  • Example#5207 - Stil obiect-orientat
  • Example#5208 - Stil procedural
  • Example#5209 - stomp_connect_error example
  • Example#5210 - stomp_version example
  • Example#5211 - Stil obiect-orientat
  • Example#5212 - Stil procedural
  • Example#5213 - Stil obiect-orientat
  • Example#5214 - Stil procedural
  • Example#5215 - Stil obiect-orientat
  • Example#5216 - Stil procedural
  • Example#5217 - Stil obiect-orientat
  • Example#5218 - Stil procedural
  • Example#5219 - Stil obiect-orientat
  • Example#5220 - Stil procedural
  • Example#5221 - Stil obiect-orientat
  • Example#5222 - Stil procedural
  • Example#5223 - Stil obiect-orientat
  • Example#5224 - Stil procedural
  • Example#5225 - Stil obiect-orientat
  • Example#5226 - Stil procedural
  • Example#5227 - Stil obiect-orientat
  • Example#5228 - Stil procedural
  • Example#5229 - Train from array
  • Example#5230 - Train from a file
  • Example#5231 - svn_add example
  • Example#5232 - Default authentication example
  • Example#5233 - svn_blame example
  • Example#5234 - Basic example
  • Example#5235 - Basic example
  • Example#5236 - Basic example
  • Example#5237 - Basic example
  • Example#5238 - Basic example
  • Example#5239 - Basic example
  • Example#5240 - Diffing two revisions of a repository path
  • Example#5241 - Portably diffing two local files
  • Example#5242 - svn_export example
  • Example#5243 - Basic example
  • Example#5244 - svn_log example
  • Example#5245 - svn_ls example
  • Example#5246 - Basic example
  • Example#5247 - Basic example
  • Example#5248 - Deny all connections from localhost
  • Example#5249 - Ban an URL
  • Example#5250 - Get statistic snapshot
  • Example#5251 - Read varnish shared memory log
  • Example#5252 - VarnishAdmin::__construct example
  • Example#5253 - Parallel searching using Yaz
  • Example#5254 - CCL configuration
  • Example#5255 - CCL Parsing
  • Example#5256 - Record Update
  • Example#5257 - Array for GRS-1 record
  • Example#5258 - Working with MARCXML
  • Example#5259 - PHP function that scans titles
  • Example#5260 - Query Examples
  • Example#5261 - Sort Criterias
  • Example#5262 - Example for NIS errors
  • Example#5263 - Example for the NIS first
  • Example#5264 - Example for the default domain
  • Example#5265 - Example for the NIS master
  • Example#5266 - Example for NIS match
  • Example#5267 - Example for NIS next
  • Example#5268 - Example for the NIS order
  • Example#5269 - A ZMQContext example
  • Example#5270 - A ZMQContext example
  • Example#5271 - A ZMQContext example
  • Example#5272 - A ZMQSocket example
  • Example#5273 - A send/recv example
  • Example#5274 - A ZMQPoll example
  • Example#5275 - Zookeeper::addAuth example
  • Example#5276 - Zookeeper::create example
  • Example#5277 - Zookeeper::delete example
  • Example#5278 - Zookeeper::exists example
  • Example#5279 - Zookeeper::get example
  • Example#5280 - Zookeeper::getAcl example
  • Example#5281 - Zookeeper::set example
  • Example#5282 - Zookeeper::setAcl example
  • Example#5283 - Zookeeper::setDebugLevel example
  • Example#5284 -
  • Example#5285 - udm_api_version example
  • Example#5286 - udm_cat_listexample
  • Example#5287 - Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'
  • Example#5288 - udm_load_ispell_data example
  • Example#5289 - udm_load_ispell_data example
  • Example#5290 - solr_get_version example
  • Example#5291 - Contents of the BootStrap file
  • Example#5292 - Adding a document to the index
  • Example#5293 - Merging one document into another document
  • Example#5294 - Searching for documents - SolrObject responses
  • Example#5295 - Searching for documents - SolrDocument responses
  • Example#5296 - Simple TermsComponent example - basic
  • Example#5297 - Simple TermsComponent example - using a prefix
  • Example#5298 - Simple TermsComponent example - specifying a minimum frequency
  • Example#5299 - Simple Facet Example
  • Example#5300 - Simple Facet Example - with optional field override for mincount
  • Example#5301 - Facet Date Example
  • Example#5302 - Connecting to SSL-Enabled Server
  • Example#5303 - Collapsing a SolrQuery
  • Example#5304 - Solr Real Time Get (RTG) example SolrClient::getById
  • Example#5305 - SolrInputDocument::addChildDocument example
  • Example#5306 - SolrInputDocument::addChildDocuments example
  • Example#5307 - SolrDocument::toArray example
  • Example#5308 - SolrObject::__construct example
  • Example#5309 - SolrObject::offsetUnset example
  • Example#5310 - SolrClient::addDocument example
  • Example#5311 - SolrClient::addDocument example 2
  • Example#5312 - SolrClient::addDocuments example
  • Example#5313 - SolrClient::__construct example
  • Example#5314 - SolrQuery::deleteByQuery example
  • Example#5315 - SolrClient::getById example
  • Example#5316 - SolrClient::getByIds example
  • Example#5317 - SolrClient::ping example
  • Example#5318 - SolrClient::query example
  • Example#5319 - SolrClient::request example
  • Example#5320 - SolrClient::setResponseWriter example
  • Example#5321 - SolrParams::setParam example
  • Example#5322 - SolrQuery::addFacetField example
  • Example#5323 - SolrQuery::addFacetField example
  • Example#5324 - SolrQuery::addFilterQuery example
  • Example#5325 - SolrQuery::addGroupSortField example
  • Example#5326 - SolrQuery::collapse example
  • Example#5327 - SolrQuery::setExpand example
  • Example#5328 - SolrDisMaxQuery::addBigramPhraseField example
  • Example#5329 - SolrDisMaxQuery::addBoostQuery example
  • Example#5330 - SolrDisMaxQuery::addPhraseField example
  • Example#5331 - SolrDisMaxQuery::addQueryField example
  • Example#5332 - SolrDisMaxQuery::addTrigramPhraseField example
  • Example#5333 - SolrDisMaxQuery::addUserField example
  • Example#5334 - SolrDisMaxQuery::__construct example
  • Example#5335 - SolrDisMaxQuery::removeBigramPhraseField example
  • Example#5336 - SolrDisMaxQuery::removeBoostQuery example
  • Example#5337 - SolrDisMaxQuery::removePhraseField example
  • Example#5338 - SolrDisMaxQuery::removeQueryField example
  • Example#5339 - SolrDisMaxQuery::removeTrigramPhraseField example
  • Example#5340 - SolrDisMaxQuery::removeUserField example
  • Example#5341 - SolrDisMaxQuery::setBigramPhraseFields example
  • Example#5342 - SolrDisMaxQuery::setBigramPhraseSlop example
  • Example#5343 - SolrDisMaxQuery::setBoostFunction example
  • Example#5344 - SolrDisMaxQuery::setBoostQuery example
  • Example#5345 - SolrDisMaxQuery::setMinimumMatch example
  • Example#5346 - SolrDisMaxQuery::setPhraseFields example
  • Example#5347 - SolrDisMaxQuery::setPhraseSlop example
  • Example#5348 - SolrDisMaxQuery::setQueryAlt example
  • Example#5349 - SolrDisMaxQuery::setQueryPhraseSlop example
  • Example#5350 - SolrDisMaxQuery::setTieBreaker example
  • Example#5351 - SolrDisMaxQuery::setTrigramPhraseFields example
  • Example#5352 - SolrDisMaxQuery::setTrigramPhraseSlop example
  • Example#5353 - SolrDisMaxQuery::setUserFields example
  • Example#5354 - SolrDisMaxQuery::useDisMaxQueryParser example
  • Example#5355 - SolrDisMaxQuery::useEDisMaxQueryParser example
  • Example#5356 - SolrCollapseFunction::__construct example
  • Example#5357 - SolrCollapseFunction::setHint example
  • Example#5358 - SolrCollapseFunction::setMax example
  • Example#5359 - Basic usage example
  • Example#5360 - Basic search query
  • Example#5361 - A Swish::__construct example
  • Example#5362 - Basic Swish::getMetaList example
  • Example#5363 - Basic Swish::getPropertyList example
  • Example#5364 - Basic Swish::prepare example
  • Example#5365 - Basic Swish::query example
  • Example#5366 - Basic SwishResult::stem example
  • Example#5367 - Basic SwishResults::getParsedWords example
  • Example#5368 - Basic SwishResults::nextResult example
  • Example#5369 - Basic SwishResults::seekResult example
  • Example#5370 - Basic SwishSearch::execute example
  • Example#5371 - Basic SwishSearch::resetLimit example
  • Example#5372 - Basic SwishSearch::setLimit example
  • Example#5373 - Basic SwishSearch::setPhraseDelimiter example
  • Example#5374 - Basic SwishSearch::setSort example
  • Example#5375 - Basic SwishSearch::setStructure example
  • Example#5376 - Deconectarea prelucrarii PHP pentru un director utilizând .htaccess
  • Example#5377 - apache_get_modules example
  • Example#5378 - apache_get_version example
  • Example#5379 - apache_getenv example
  • Example#5380 - Exemplu apache_lookup_uri
  • Example#5381 - Transmiterea informa?iei între PHP ?i Perl
  • Example#5382 - Logarea valorilor în access.log
  • Example#5383 - apache_request_headers example
  • Example#5384 - apache_response_headers example
  • Example#5385 - Stabilirea unei variabile de mediu Apache cu ajutorul apache_setenv
  • Example#5386 - Exemplu getallheaders
  • Example#5387 - nsapi_request_headers example
  • Example#5388 - Registering a variable with $_SESSION.
  • Example#5389 - Unregistering a variable with $_SESSION.
  • Example#5390 - Counting the number of hits of a single user
  • Example#5391 - Example information
  • Example#5392 - session_cache_expire example
  • Example#5393 - session_cache_limiter example
  • Example#5394 - session_create_id example with session_regenerate_id
  • Example#5395 - Destroying a session with $_SESSION
  • Example#5396 - session_gc example for task managers like cron
  • Example#5397 - session_gc example for user accessible script
  • Example#5398 - session_name example
  • Example#5399 - A session_regenerate_id example
  • Example#5400 - Avoiding lost session by session_regenerate_id
  • Example#5401 - Custom session handler: see full code in SessionHandlerInterface synposis.
  • Example#5402 - Custom session save handler using objects
  • Example#5403 - page1.php
  • Example#5404 - page2.php
  • Example#5405 - Overriding the cookie lifetime
  • Example#5406 - Reading the session and closing it
  • Example#5407 - Using SessionHandler to add encryption to internal PHP save handlers.
  • Example#5408 - Example using SessionHandlerInterface
  • Example#5409 - bbcode_add_smiley usage example
  • Example#5410 - bbcode_create example
  • Example#5411 - bbcode_set_arg_parser usage example
  • Example#5412 - bbcode_set_flags usage example
  • Example#5413 - Examples of valid patterns
  • Example#5414 - Examples of invalid patterns
  • Example#5415 - Example comparing preg_filter with preg_replace
  • Example#5416 - preg_grep example
  • Example#5417 - preg_last_error example
  • Example#5418 - Getting all phone numbers out of some text.
  • Example#5419 - Find matching HTML tags (greedy)
  • Example#5420 - Using named subpattern
  • Example#5421 - Find the string of text "php"
  • Example#5422 - Find the word "web"
  • Example#5423 - Getting the domain name out of a URL
  • Example#5424 - Using named subpattern
  • Example#5425 - preg_quote example
  • Example#5426 - Italicizing a word within some text
  • Example#5427 - preg_replace_callback_array example
  • Example#5428 - preg_replace_callback and anonymous function
  • Example#5429 - preg_replace_callback example
  • Example#5430 - preg_replace_callback using recursive structure to handle encapsulated BB code
  • Example#5431 - Using backreferences followed by numeric literals
  • Example#5432 - Using indexed arrays with preg_replace
  • Example#5433 - Replacing several values
  • Example#5434 - Strip whitespace
  • Example#5435 - Using the count parameter
  • Example#5436 - preg_split example : Get the parts of a search string
  • Example#5437 - Splitting a string into component characters
  • Example#5438 - Splitting a string into matches and their offsets
  • Example#5439 - Regular Expression Examples
  • Example#5440 - ereg_replace example
  • Example#5441 - ereg_replace example
  • Example#5442 - Replace URLs with links
  • Example#5443 - ereg example
  • Example#5444 - Highlight search results
  • Example#5445 - eregi example
  • Example#5446 - split example
  • Example#5447 - split example
  • Example#5448 - spliti example
  • Example#5449 - sql_regcase example
  • Example#5450 - addcslashes example
  • Example#5451 - An addslashes example
  • Example#5452 - chr example
  • Example#5453 - Overflow behavior
  • Example#5454 - chunk_split example
  • Example#5455 - convert_uudecode example
  • Example#5456 - convert_uuencode example
  • Example#5457 - count_chars example
  • Example#5458 - Displaying a crc32 checksum
  • Example#5459 - crypt examples
  • Example#5460 - Using crypt with htpasswd
  • Example#5461 - Using crypt with different hash types
  • Example#5462 - echo examples
  • Example#5463 - explode examples
  • Example#5464 - explode return examples
  • Example#5465 - limit parameter examples
  • Example#5466 - fprintf: zero-padded integers
  • Example#5467 - fprintf: formatting currency
  • Example#5468 - Translation Table Example
  • Example#5469 - hex2bin example
  • Example#5470 - Decoding HTML entities
  • Example#5471 - A htmlentities example
  • Example#5472 - Usage of ENT_IGNORE
  • Example#5473 - A htmlspecialchars_decode example
  • Example#5474 - htmlspecialchars example
  • Example#5475 - implode example
  • Example#5476 - lcfirst example
  • Example#5477 - levenshtein example
  • Example#5478 - localeconv example
  • Example#5479 - Usage example of ltrim
  • Example#5480 - Usage example of md5_file
  • Example#5481 - A md5 example
  • Example#5482 - metaphone basic example
  • Example#5483 - Using the phonemes parameter
  • Example#5484 - money_format Example
  • Example#5485 - Using nl2br
  • Example#5486 - Generating valid HTML markup using the is_xhtml parameter
  • Example#5487 - Various newline separators
  • Example#5488 - number_format Example
  • Example#5489 - ord example
  • Example#5490 - Using parse_str
  • Example#5491 - parse_str name mangling
  • Example#5492 - print examples
  • Example#5493 - Usage example of rtrim
  • Example#5494 - setlocale Examples
  • Example#5495 - setlocale Examples for Windows
  • Example#5496 - sha1_file example
  • Example#5497 - A sha1 example
  • Example#5498 - Soundex Examples
  • Example#5499 - Argument swapping
  • Example#5500 - Argument swapping
  • Example#5501 - Argument swapping
  • Example#5502 - Argument swapping
  • Example#5503 - Specifying padding character
  • Example#5504 - Position specifier with other specifiers
  • Example#5505 - printf: various examples
  • Example#5506 - printf: string specifiers
  • Example#5507 - sprintf: zero-padded integers
  • Example#5508 - sprintf: formatting currency
  • Example#5509 - sprintf: scientific notation
  • Example#5510 - sscanf Example
  • Example#5511 - sscanf - using optional parameters
  • Example#5512 - str_ireplace example
  • Example#5513 - str_pad example
  • Example#5514 - str_repeat example
  • Example#5515 - Basic str_replace examples
  • Example#5516 - Examples of potential str_replace gotchas
  • Example#5517 - str_rot13 example
  • Example#5518 - str_shuffle example
  • Example#5519 - Example uses of str_split
  • Example#5520 - A str_word_count example
  • Example#5521 - strcasecmp example
  • Example#5522 - strcmp example
  • Example#5523 - strcspn example
  • Example#5524 - strip_tags example
  • Example#5525 - stripos examples
  • Example#5526 - A stripslashes example
  • Example#5527 - Using stripslashes on an array
  • Example#5528 - stristr example
  • Example#5529 - Testing if a string is found or not
  • Example#5530 - Using a non "string" needle
  • Example#5531 - A strlen example
  • Example#5532 - strpbrk example
  • Example#5533 - Using ===
  • Example#5534 - Using !==
  • Example#5535 - Using an offset
  • Example#5536 - strrchr example
  • Example#5537 - Reversing a string with strrev
  • Example#5538 - A simple strripos example
  • Example#5539 - Checking if a needle is in the haystack
  • Example#5540 - Searching with offsets
  • Example#5541 - strspn example
  • Example#5542 - strstr example
  • Example#5543 - strtok example
  • Example#5544 - strtok behavior on empty part found
  • Example#5545 - strtolower example
  • Example#5546 - strtoupper example
  • Example#5547 - strtr example
  • Example#5548 - strtr example with two arguments
  • Example#5549 - strtr behavior comparison
  • Example#5550 - A substr_compare example
  • Example#5551 - A substr_count example
  • Example#5552 - Simple substr_replace examples
  • Example#5553 - Using substr_replace to replace multiple strings at once
  • Example#5554 - Using a negative start
  • Example#5555 - Using a negative length
  • Example#5556 - Basic substr usage
  • Example#5557 - substr casting behaviour
  • Example#5558 -
  • Example#5559 - Usage example of trim
  • Example#5560 - Trimming array values with trim
  • Example#5561 - ucfirst example
  • Example#5562 - ucwords example
  • Example#5563 - ucwords example with custom delimiter
  • Example#5564 - vfprintf: zero-padded integers
  • Example#5565 - vprintf: zero-padded integers
  • Example#5566 - vsprintf: zero-padded integers
  • Example#5567 - wordwrap example
  • Example#5568 - wordwrap example
  • Example#5569 - wordwrap example
  • Example#5570 - Exemplu array_change_key_case
  • Example#5571 - Exemplu array_chunk
  • Example#5572 - Get the column of first names from a recordset
  • Example#5573 - Get the column of last names from a recordset, indexed by the "id" column
  • Example#5574 - Get the column of usernames from the public "username" property of an object
  • Example#5575 - Get the column of names from the private "name" property of an object using the magic __get method.
  • Example#5576 - A simple array_combine example
  • Example#5577 - Exemplu array_count_values
  • Example#5578 - array_diff_assoc example
  • Example#5579 - array_diff_assoc example
  • Example#5580 - array_diff_key example
  • Example#5581 - array_diff_uassoc example
  • Example#5582 - array_diff_ukey example
  • Example#5583 - Exemplu array_diff
  • Example#5584 - array_fill_keys example
  • Example#5585 - Exemplu array_fill
  • Example#5586 - Exemplu array_filter
  • Example#5587 - array_filter fara callback
  • Example#5588 - array_filter cu flag
  • Example#5589 - array_flip example
  • Example#5590 - array_flip example : collision
  • Example#5591 - array_intersect_assoc example
  • Example#5592 - array_intersect_key example
  • Example#5593 - array_intersect_uassoc example
  • Example#5594 - array_intersect_ukey example
  • Example#5595 - array_intersect example
  • Example#5596 - array_key_exists example
  • Example#5597 - array_key_exists vs isset
  • Example#5598 - array_keys example
  • Example#5599 - array_map example
  • Example#5600 - array_map using a lambda function (as of PHP 5.3.0)
  • Example#5601 - array_map - using more arrays
  • Example#5602 - Creating an array of arrays
  • Example#5603 - array_map - with string keys
  • Example#5604 - array_merge_recursive example
  • Example#5605 - array_merge example
  • Example#5606 - Simple array_merge example
  • Example#5607 - array_merge with non-array types
  • Example#5608 - Sorting multiple arrays
  • Example#5609 - Sorting multi-dimensional array
  • Example#5610 - Sorting database results
  • Example#5611 - Case insensitive sorting
  • Example#5612 - array_pad example
  • Example#5613 - array_pop example
  • Example#5614 - array_product examples
  • Example#5615 - array_push example
  • Example#5616 - array_rand example
  • Example#5617 - array_reduce example
  • Example#5618 - array_replace_recursive example
  • Example#5619 - array_replace_recursive and recursive behavior
  • Example#5620 - array_replace example
  • Example#5621 - array_reverse example
  • Example#5622 - array_search example
  • Example#5623 - array_shift example
  • Example#5624 - array_slice examples
  • Example#5625 - array_splice examples
  • Example#5626 - array_splice examples
  • Example#5627 - array_sum examples
  • Example#5628 - array_udiff_assoc example
  • Example#5629 - array_udiff_uassoc example
  • Example#5630 - array_udiff example using stdClass Objects
  • Example#5631 - array_udiff example using DateTime Objects
  • Example#5632 - array_uintersect_assoc example
  • Example#5633 - array_uintersect_uassoc example
  • Example#5634 - array_uintersect example
  • Example#5635 - array_unique example
  • Example#5636 - array_unique and types
  • Example#5637 - array_unshift example
  • Example#5638 - array_values example
  • Example#5639 - array_walk_recursive example
  • Example#5640 - array_walk example
  • Example#5641 - Exemplu array
  • Example#5642 - Indexarea automata cu array
  • Example#5643 - Indicele începând cu 1 cu ajutorul array
  • Example#5644 - Accesarea unui tablou între ghilimele duble
  • Example#5645 - arsort example
  • Example#5646 - asort example
  • Example#5647 - compact example
  • Example#5648 - count example
  • Example#5649 - Recursive count example
  • Example#5650 - Example use of current and friends
  • Example#5651 - each examples
  • Example#5652 - Traversing an array with each
  • Example#5653 - end example
  • Example#5654 - extract example
  • Example#5655 - in_array example
  • Example#5656 - in_array with strict example
  • Example#5657 - in_array with an array as needle
  • Example#5658 - key example
  • Example#5659 - krsort example
  • Example#5660 - ksort example
  • Example#5661 - list examples
  • Example#5662 - An example use of list
  • Example#5663 - Using nested list
  • Example#5664 - Using list with array indices
  • Example#5665 - list and order of index definitions
  • Example#5666 - natcasesort example
  • Example#5667 - natsort examples demonstrating basic usage
  • Example#5668 - natsort examples demonstrating potential gotchas
  • Example#5669 - Example use of next and friends
  • Example#5670 - Example use of prev and friends
  • Example#5671 - range examples
  • Example#5672 - reset example
  • Example#5673 - rsort example
  • Example#5674 - shuffle example
  • Example#5675 - sort example
  • Example#5676 - sort example using case-insensitive natural ordering
  • Example#5677 - Basic uasort example
  • Example#5678 - uksort example
  • Example#5679 - usort example
  • Example#5680 - usort example using multi-dimensional array
  • Example#5681 - usort example using a member function of an object
  • Example#5682 - usort example using a closure to sort a multi-dimensional array
  • Example#5683 - classes.inc
  • Example#5684 - test_script.php
  • Example#5685 - call_user_method_array alternative
  • Example#5686 - call_user_method alternative
  • Example#5687 - class_alias example
  • Example#5688 - Exemplu class_exists
  • Example#5689 - Exemplu cu parametrul autoload
  • Example#5690 - Using get_called_class
  • Example#5691 - get_class_methods example
  • Example#5692 - get_class_vars example
  • Example#5693 - get_class_vars and scoping behaviour
  • Example#5694 - Using get_class
  • Example#5695 - Using get_class in superclass
  • Example#5696 - Using get_class with namespaced classes
  • Example#5697 - get_declared_classes example
  • Example#5698 - get_declared_interfaces example
  • Example#5699 - Use of get_object_vars
  • Example#5700 - Using get_parent_class
  • Example#5701 - interface_exists example
  • Example#5702 - is_a example
  • Example#5703 - Using the instanceof operator in PHP 5
  • Example#5704 - is_subclass_of example
  • Example#5705 - is_subclass_of using interface example
  • Example#5706 - method_exists example
  • Example#5707 - Static method_exists example
  • Example#5708 - A property_exists example
  • Example#5709 - classkit_import example
  • Example#5710 - classkit_method_add example
  • Example#5711 - classkit_method_copy example
  • Example#5712 - classkit_method_redefine example
  • Example#5713 - classkit_method_remove example
  • Example#5714 - classkit_method_rename example
  • Example#5715 - A ctype_alnum example (using the default locale)
  • Example#5716 - A ctype_alpha example (using the default locale)
  • Example#5717 - A ctype_cntrl example
  • Example#5718 - A ctype_digit example
  • Example#5719 - A ctype_digit example comparing strings with integers
  • Example#5720 - A ctype_graph example
  • Example#5721 - A ctype_lower example (using the default locale)
  • Example#5722 - A ctype_print example
  • Example#5723 - A ctype_punct example
  • Example#5724 - A ctype_space example
  • Example#5725 - A ctype_upper example (using the default locale)
  • Example#5726 - A ctype_xdigit example
  • Example#5727 - Vector
  • Example#5728 - Map
  • Example#5729 - Ds\Collection::clear example
  • Example#5730 - Ds\Collection::copy example
  • Example#5731 - Ds\Collection::isEmpty example
  • Example#5732 - Ds\Collection::toArray example
  • Example#5733 - Ds\Hashable::hash example
  • Example#5734 - Ds\Sequence::allocate example
  • Example#5735 - Ds\Sequence::apply example
  • Example#5736 - Ds\Sequence::capacity example
  • Example#5737 - Ds\Sequence::contains example
  • Example#5738 - Ds\Sequence::filter example using callback function
  • Example#5739 - Ds\Sequence::filter example without a callback function
  • Example#5740 - Ds\Sequence::find example
  • Example#5741 - Ds\Sequence::first example
  • Example#5742 - Ds\Sequence::get example
  • Example#5743 - Ds\Sequence::get example using array syntax
  • Example#5744 - Ds\Sequence::insert example
  • Example#5745 - Ds\Sequence::join example using a separator string
  • Example#5746 - Ds\Sequence::join example without a separator string
  • Example#5747 - Ds\Sequence::last example
  • Example#5748 - Ds\Sequence::map example
  • Example#5749 - Ds\Sequence::merge example
  • Example#5750 - Ds\Sequence::pop example
  • Example#5751 - Ds\Sequence::push example
  • Example#5752 - Ds\Sequence::reduce with initial value example
  • Example#5753 - Ds\Sequence::reduce without an initial value example
  • Example#5754 - Ds\Sequence::remove example
  • Example#5755 - Ds\Sequence::reverse example
  • Example#5756 - Ds\Sequence::reversed example
  • Example#5757 - Ds\Sequence::rotate example
  • Example#5758 - Ds\Sequence::set example
  • Example#5759 - Ds\Sequence::set example using array syntax
  • Example#5760 - Ds\Sequence::shift example
  • Example#5761 - Ds\Sequence::slice example
  • Example#5762 - Ds\Sequence::sort example
  • Example#5763 - Ds\Sequence::sort example using a comparator
  • Example#5764 - Ds\Sequence::sorted example
  • Example#5765 - Ds\Sequence::sorted example using a comparator
  • Example#5766 - Ds\Sequence::sum integer example
  • Example#5767 - Ds\Sequence::sum float example
  • Example#5768 - Ds\Sequence::unshift example
  • Example#5769 - Ds\Vector::allocate example
  • Example#5770 - Ds\Vector::apply example
  • Example#5771 - Ds\Vector::capacity example
  • Example#5772 - Ds\Vector::clear example
  • Example#5773 - Ds\Vector::__construct example
  • Example#5774 - Ds\Vector::contains example
  • Example#5775 - Ds\Vector::copy example
  • Example#5776 - Ds\Vector::filter example using callback function
  • Example#5777 - Ds\Vector::filter example without a callback function
  • Example#5778 - Ds\Vector::find example
  • Example#5779 - Ds\Vector::first example
  • Example#5780 - Ds\Vector::get example
  • Example#5781 - Ds\Vector::get example using array syntax
  • Example#5782 - Ds\Vector::insert example
  • Example#5783 - Ds\Vector::isEmpty example
  • Example#5784 - Ds\Vector::join example using a separator string
  • Example#5785 - Ds\Vector::join example without a separator string
  • Example#5786 - Ds\Vector::last example
  • Example#5787 - Ds\Vector::map example
  • Example#5788 - Ds\Vector::merge example
  • Example#5789 - Ds\Vector::pop example
  • Example#5790 - Ds\Vector::push example
  • Example#5791 - Ds\Vector::reduce with initial value example
  • Example#5792 - Ds\Vector::reduce without an initial value example
  • Example#5793 - Ds\Vector::remove example
  • Example#5794 - Ds\Vector::reverse example
  • Example#5795 - Ds\Vector::reversed example
  • Example#5796 - Ds\Vector::rotate example
  • Example#5797 - Ds\Vector::set example
  • Example#5798 - Ds\Vector::set example using array syntax
  • Example#5799 - Ds\Vector::shift example
  • Example#5800 - Ds\Vector::slice example
  • Example#5801 - Ds\Vector::sort example
  • Example#5802 - Ds\Vector::sort example using a comparator
  • Example#5803 - Ds\Vector::sorted example
  • Example#5804 - Ds\Vector::sorted example using a comparator
  • Example#5805 - Ds\Vector::sum integer example
  • Example#5806 - Ds\Vector::sum float example
  • Example#5807 - Ds\Vector::toArray example
  • Example#5808 - Ds\Vector::unshift example
  • Example#5809 - Ds\Deque::allocate example
  • Example#5810 - Ds\Deque::apply example
  • Example#5811 - Ds\Deque::capacity example
  • Example#5812 - Ds\Deque::clear example
  • Example#5813 - Ds\Deque::__construct example
  • Example#5814 - Ds\Deque::contains example
  • Example#5815 - Ds\Deque::copy example
  • Example#5816 - Ds\Deque::filter example using callback function
  • Example#5817 - Ds\Deque::filter example without a callback function
  • Example#5818 - Ds\Deque::find example
  • Example#5819 - Ds\Deque::first example
  • Example#5820 - Ds\Deque::get example
  • Example#5821 - Ds\Deque::get example using array syntax
  • Example#5822 - Ds\Deque::insert example
  • Example#5823 - Ds\Deque::isEmpty example
  • Example#5824 - Ds\Deque::join example using a separator string
  • Example#5825 - Ds\Deque::join example without a separator string
  • Example#5826 - Ds\Deque::last example
  • Example#5827 - Ds\Deque::map example
  • Example#5828 - Ds\Deque::merge example
  • Example#5829 - Ds\Deque::pop example
  • Example#5830 - Ds\Deque::push example
  • Example#5831 - Ds\Deque::reduce with initial value example
  • Example#5832 - Ds\Deque::reduce without an initial value example
  • Example#5833 - Ds\Deque::remove example
  • Example#5834 - Ds\Deque::reverse example
  • Example#5835 - Ds\Deque::reversed example
  • Example#5836 - Ds\Deque::rotate example
  • Example#5837 - Ds\Deque::set example
  • Example#5838 - Ds\Deque::set example using array syntax
  • Example#5839 - Ds\Deque::shift example
  • Example#5840 - Ds\Deque::slice example
  • Example#5841 - Ds\Deque::sort example
  • Example#5842 - Ds\Deque::sort example using a comparator
  • Example#5843 - Ds\Deque::sorted example
  • Example#5844 - Ds\Deque::sorted example using a comparator
  • Example#5845 - Ds\Deque::sum integer example
  • Example#5846 - Ds\Deque::sum float example
  • Example#5847 - Ds\Deque::toArray example
  • Example#5848 - Ds\Deque::unshift example
  • Example#5849 - Ds\Map::allocate example
  • Example#5850 - Ds\Map::apply example
  • Example#5851 - Ds\Map::capacity example
  • Example#5852 - Ds\Map::clear example
  • Example#5853 - Ds\Map::__construct example
  • Example#5854 - Ds\Map::copy example
  • Example#5855 - Ds\Map::diff example
  • Example#5856 - Ds\Map::filter example using callback function
  • Example#5857 - Ds\Map::filter example without a callback function
  • Example#5858 - Ds\Map::first example
  • Example#5859 - Ds\Map::get example
  • Example#5860 - Ds\Map::get example using array syntax
  • Example#5861 - Ds\Map::hasKey example
  • Example#5862 - Ds\Map::hasValue example
  • Example#5863 - Ds\Map::intersect example
  • Example#5864 - Ds\Map::isEmpty example
  • Example#5865 - Ds\Map::keys example
  • Example#5866 - Ds\Map::ksort example
  • Example#5867 - Ds\Map::ksort example using a comparator
  • Example#5868 - Ds\Map::ksorted example
  • Example#5869 - Ds\Map::ksorted example using a comparator
  • Example#5870 - Ds\Map::last example
  • Example#5871 - Ds\Map::map example
  • Example#5872 - Ds\Map::merge example
  • Example#5873 - Ds\Map::pairs example
  • Example#5874 - Ds\Map::put example
  • Example#5875 - Ds\Map::put example using objects as keys
  • Example#5876 - Ds\Map::putAll example
  • Example#5877 - Ds\Map::reduce with initial value example
  • Example#5878 - Ds\Map::reduce without an initial value example
  • Example#5879 - Ds\Map::remove example
  • Example#5880 - Ds\Map::reverse example
  • Example#5881 - Ds\Map::reversed example
  • Example#5882 - Ds\Map::skip example
  • Example#5883 - Ds\Map::slice example
  • Example#5884 - Ds\Map::sort example
  • Example#5885 - Ds\Map::sort example using a comparator
  • Example#5886 - Ds\Map::sort example
  • Example#5887 - Ds\Map::sort example using a comparator
  • Example#5888 - Ds\Map::sum integer example
  • Example#5889 - Ds\Map::sum float example
  • Example#5890 - Ds\Map::toArray example
  • Example#5891 - Ds\Map::union example
  • Example#5892 - Ds\Map::values example
  • Example#5893 - Ds\Map::xor example
  • Example#5894 - Ds\Pair::clear example
  • Example#5895 - Ds\Pair::copy example
  • Example#5896 - Ds\Pair::isEmpty example
  • Example#5897 - Ds\Pair::toArray example
  • Example#5898 - Ds\Set::add example using integers
  • Example#5899 - Ds\Set::add example using objects
  • Example#5900 - Ds\Set::allocate example
  • Example#5901 - Ds\Set::capacity example
  • Example#5902 - Ds\Set::clear example
  • Example#5903 - Ds\Set::__construct example
  • Example#5904 - Ds\Set::contains example
  • Example#5905 - Ds\Set::copy example
  • Example#5906 - Ds\Set::diff example
  • Example#5907 - Ds\Set::filter example using callback function
  • Example#5908 - Ds\Set::filter example without a callback function
  • Example#5909 - Ds\Set::first example
  • Example#5910 - Ds\Set::get example
  • Example#5911 - Ds\Set::get example using array syntax
  • Example#5912 - Ds\Set::intersect example
  • Example#5913 - Ds\Set::isEmpty example
  • Example#5914 - Ds\Set::join example using a separator string
  • Example#5915 - Ds\Set::join example without a separator string
  • Example#5916 - Ds\Set::last example
  • Example#5917 - Ds\Set::merge example
  • Example#5918 - Ds\Set::reduce with initial value example
  • Example#5919 - Ds\Set::reduce without an initial value example
  • Example#5920 - Ds\Set::remove example
  • Example#5921 - Ds\Set::reverse example
  • Example#5922 - Ds\Set::reversed example
  • Example#5923 - Ds\Set::slice example
  • Example#5924 - Ds\Set::sort example
  • Example#5925 - Ds\Set::sort example using a comparator
  • Example#5926 - Ds\Set::sorted example
  • Example#5927 - Ds\Set::sorted example using a comparator
  • Example#5928 - Ds\Set::sum integer example
  • Example#5929 - Ds\Set::sum float example
  • Example#5930 - Ds\Set::toArray example
  • Example#5931 - Ds\Set::union example
  • Example#5932 - Ds\Set::xor example
  • Example#5933 - Ds\Stack::clear example
  • Example#5934 - Ds\Stack::__construct example
  • Example#5935 - Ds\Stack::copy example
  • Example#5936 - Ds\Stack::isEmpty example
  • Example#5937 - Ds\Stack::peek example
  • Example#5938 - Ds\Stack::pop example
  • Example#5939 - Ds\Stack::push example
  • Example#5940 - Ds\Stack::toArray example
  • Example#5941 - Ds\Queue::allocate example
  • Example#5942 - Ds\Queue::capacity example
  • Example#5943 - Ds\Queue::clear example
  • Example#5944 - Ds\Queue::__construct example
  • Example#5945 - Ds\Queue::copy example
  • Example#5946 - Ds\Queue::isEmpty example
  • Example#5947 - Ds\Queue::peek example
  • Example#5948 - Ds\Queue::pop example
  • Example#5949 - Ds\Queue::push example
  • Example#5950 - Ds\Queue::toArray example
  • Example#5951 - Ds\PriorityQueue::allocate example
  • Example#5952 - Ds\PriorityQueue::capacity example
  • Example#5953 - Ds\PriorityQueue::clear example
  • Example#5954 - Ds\PriorityQueue::__construct example
  • Example#5955 - Ds\PriorityQueue::copy example
  • Example#5956 - Ds\PriorityQueue::isEmpty example
  • Example#5957 - Ds\PriorityQueue::peek example
  • Example#5958 - Ds\PriorityQueue::pop example
  • Example#5959 - Ds\PriorityQueue::push example
  • Example#5960 - Ds\PriorityQueue::toArray example
  • Example#5961 - Configuring the default filter to act like htmlspecialchars
  • Example#5962 - Configuring the default filter to act like htmlspecialchars
  • Example#5963 - Validating email addresses with filter_var
  • Example#5964 - Validating IP addresses with filter_var
  • Example#5965 - Passing options to filter_var
  • Example#5966 - Sanitizing and validating email addresses
  • Example#5967 - Configuring a default filter
  • Example#5968 - A filter_input_array example
  • Example#5969 - A filter_input example
  • Example#5970 - A filter_list example
  • Example#5971 - A filter_var_array example
  • Example#5972 - A filter_var example
  • Example#5973 - call_user_func_array example
  • Example#5974 - call_user_func_array using namespace name
  • Example#5975 - Using lambda function
  • Example#5976 - Passing values by reference
  • Example#5977 - call_user_func example and references
  • Example#5978 - call_user_func example
  • Example#5979 - call_user_func using namespace name
  • Example#5980 - Using a class method with call_user_func
  • Example#5981 - Using lambda function with call_user_func
  • Example#5982 - Creating an anonymous function with create_function
  • Example#5983 - Making a general processing function with create_function
  • Example#5984 - Using anonymous functions as callback functions
  • Example#5985 - forward_static_call_array example
  • Example#5986 - forward_static_call example
  • Example#5987 - func_get_arg example
  • Example#5988 - func_get_arg example before and after PHP 5.3
  • Example#5989 - func_get_arg example of byref and byval arguments
  • Example#5990 - func_get_args example
  • Example#5991 - func_get_args example before and after PHP 5.3
  • Example#5992 - func_get_args example of byref and byval arguments
  • Example#5993 - func_num_args example
  • Example#5994 - func_num_args example before and after PHP 5.3
  • Example#5995 - function_exists example
  • Example#5996 - get_defined_functions example
  • Example#5997 - register_shutdown_function example
  • Example#5998 - register_tick_function example
  • Example#5999 - Quickhash Example
  • Example#6000 - Quickhash ArrayAccess Example
  • Example#6001 - Quickhash Iterator Example
  • Example#6002 - Quickhash String Values Example
  • Example#6003 - QuickHashIntSet::add example
  • Example#6004 - QuickHashIntSet::__construct example
  • Example#6005 - QuickHashIntSet::delete example
  • Example#6006 - QuickHashIntSet::exists example
  • Example#6007 - QuickHashIntSet::getSize example
  • Example#6008 - QuickHashIntSet::loadFromFile example
  • Example#6009 - QuickHashIntSet::loadFromString example
  • Example#6010 - QuickHashIntSet::saveToFile example
  • Example#6011 - QuickHashIntSet::saveToString example
  • Example#6012 - QuickHashIntHash::add example
  • Example#6013 - QuickHashIntHash::__construct example
  • Example#6014 - QuickHashIntHash::delete example
  • Example#6015 - QuickHashIntHash::exists example
  • Example#6016 - QuickHashIntHash::get example
  • Example#6017 - QuickHashIntHash::getSize example
  • Example#6018 - QuickHash IntHash file format
  • Example#6019 - QuickHash IntHash file format
  • Example#6020 - QuickHashIntHash::loadFromFile example
  • Example#6021 - QuickHashIntHash::loadFromString example
  • Example#6022 - QuickHashIntHash::saveToFile example
  • Example#6023 - QuickHashIntHash::saveToString example
  • Example#6024 - QuickHashIntHash::set example
  • Example#6025 - QuickHashIntHash::update example
  • Example#6026 - QuickHashStringIntHash::add example
  • Example#6027 - QuickHashStringIntHash::__construct example
  • Example#6028 - QuickHashStringIntHash::delete example
  • Example#6029 - QuickHashStringIntHash::get example
  • Example#6030 - QuickHashStringIntHash::getSize example
  • Example#6031 - QuickHash StringIntHash file format
  • Example#6032 - QuickHash IntHash file format
  • Example#6033 - QuickHashStringIntHash::loadFromFile example
  • Example#6034 - QuickHashStringIntHash::loadFromString example
  • Example#6035 - QuickHashStringIntHash::saveToFile example
  • Example#6036 - QuickHashStringIntHash::saveToString example
  • Example#6037 - QuickHashStringIntHash::set example
  • Example#6038 - QuickHashStringIntHash::update example
  • Example#6039 - QuickHashIntStringHash::add example
  • Example#6040 - QuickHashIntStringHash::__construct example
  • Example#6041 - QuickHashIntStringHash::delete example
  • Example#6042 - QuickHashIntStringHash::get example
  • Example#6043 - QuickHashIntStringHash::getSize example
  • Example#6044 - QuickHash IntString file format
  • Example#6045 - QuickHash IntString file format
  • Example#6046 - QuickHashIntStringHash::loadFromFile example
  • Example#6047 - QuickHashIntStringHash::loadFromString example
  • Example#6048 - QuickHashIntStringHash::saveToFile example
  • Example#6049 - QuickHashIntStringHash::saveToString example
  • Example#6050 - QuickHashIntStringHash::set example
  • Example#6051 - QuickHashIntStringHash::update example
  • Example#6052 - Reflection Example from Shell (a Terminal)
  • Example#6053 - Extending the built-in classes
  • Example#6054 - Basic usage ReflectionClass
  • Example#6055 - Basic usage of ReflectionClass::export
  • Example#6056 - Basic usage of ReflectionClass::getConstructor
  • Example#6057 - ReflectionClass::getDefaultProperties example
  • Example#6058 - ReflectionClass::getDocComment example
  • Example#6059 - ReflectionClass::getEndLine example
  • Example#6060 - Basic usage of ReflectionClass::getExtension
  • Example#6061 - Basic usage of ReflectionClass::getExtensionName
  • Example#6062 - ReflectionClass::getInterfaceNames example
  • Example#6063 - ReflectionClass::getInterfaces example
  • Example#6064 - Basic usage of ReflectionClass::getMethod
  • Example#6065 - Basic usage of ReflectionClass::getMethods
  • Example#6066 - Filtering results from ReflectionClass::getMethods
  • Example#6067 - ReflectionClass::getName example
  • Example#6068 - ReflectionClass::getNamespaceName example
  • Example#6069 - ReflectionClass::getProperties filtering example
  • Example#6070 - Basic usage of ReflectionClass::getProperty
  • Example#6071 - ReflectionClass::getShortName example
  • Example#6072 - Basic usage of ReflectionClass::getStaticPropertyValue
  • Example#6073 - ReflectionClass::hasConstant example
  • Example#6074 - ReflectionClass::hasMethod example
  • Example#6075 - ReflectionClass::hasProperty example
  • Example#6076 - ReflectionClass::inNamespace example
  • Example#6077 - ReflectionClass::isAbstract example
  • Example#6078 - ReflectionClass::isAnonymous example
  • Example#6079 - Basic usage of ReflectionClass::isCloneable
  • Example#6080 - ReflectionClass::isFinal example
  • Example#6081 - ReflectionClass::isInstance related examples
  • Example#6082 - ReflectionClass::isInstantiable example
  • Example#6083 - Basic usage of ReflectionClass::isInterface
  • Example#6084 - Basic usage of ReflectionClass::isInternal
  • Example#6085 - ReflectionClass::isIterateable example
  • Example#6086 - Basic usage of ReflectionClass::newInstanceArgs
  • Example#6087 - ReflectionClass::__toString example
  • Example#6088 - ReflectionExtension example
  • Example#6089 - ReflectionExtension::getClasses example
  • Example#6090 - ReflectionExtension::getClassNames example
  • Example#6091 - ReflectionExtension::getConstants example
  • Example#6092 - ReflectionExtension::getDependencies example
  • Example#6093 - ReflectionExtension::getFunctions example
  • Example#6094 - ReflectionExtension::getINIEntries example
  • Example#6095 - ReflectionExtension::getName example
  • Example#6096 - ReflectionExtension::getVersion example
  • Example#6097 - ReflectionExtension::info example
  • Example#6098 - ReflectionFunction::__construct example
  • Example#6099 - ReflectionFunction::invoke example
  • Example#6100 - ReflectionFunction::invokeArgs example
  • Example#6101 - ReflectionFunction::invokeArgs with references example
  • Example#6102 - ReflectionFunction::__toString example
  • Example#6103 - ReflectionFunctionAbstract::getReturnType example
  • Example#6104 - Usage on built-in functions
  • Example#6105 - ReflectionFunctionAbstract::hasReturnType example
  • Example#6106 - Usage on built-in functions
  • Example#6107 - ReflectionFunctionAbstract::isClosure example
  • Example#6108 - ReflectionFunctionAbstract::isDeprecated example
  • Example#6109 - ReflectionMethod::__construct example
  • Example#6110 - ReflectionMethod::getDeclaringClass example
  • Example#6111 - ReflectionMethod::getModifiers example
  • Example#6112 - ReflectionMethod::getPrototype example
  • Example#6113 - ReflectionMethod::invoke example
  • Example#6114 - ReflectionMethod::invokeArgs example
  • Example#6115 - ReflectionMethod::__toString example
  • Example#6116 - Using the ReflectionParameter class
  • Example#6117 - Using the ReflectionParameter class
  • Example#6118 - Getting the class that declared the method
  • Example#6119 - Getting
  • Example#6120 - ReflectionParameter::getType example
  • Example#6121 - ReflectionParameter::hasType example
  • Example#6122 - ReflectionProperty::__construct example
  • Example#6123 - Getting value from private and protected properties using ReflectionProperty class
  • Example#6124 - ReflectionProperty::getDocComment example
  • Example#6125 - ReflectionProperty::getValue example
  • Example#6126 - ReflectionClass::isDefault example
  • Example#6127 - ReflectionProperty::setValue example
  • Example#6128 - ReflectionType::allowsNull example
  • Example#6129 - ReflectionType::isBuiltin example
  • Example#6130 - ReflectionType::__toString example
  • Example#6131 - ReflectionGenerator::__construct example
  • Example#6132 - ReflectionGenerator::getExecutingFile example
  • Example#6133 - ReflectionGenerator::getExecutingGenerator example
  • Example#6134 - ReflectionGenerator::getExecutingLine example
  • Example#6135 - ReflectionGenerator::getFunction example
  • Example#6136 - ReflectionGenerator::getThis example
  • Example#6137 - ReflectionGenerator::getTrace example
  • Example#6138 - boolval examples
  • Example#6139 - debug_zval_dump example
  • Example#6140 -
  • Example#6141 -
  • Example#6142 - O simpla conpara?ie între empty / isset.
  • Example#6143 - empty cu deplasamente în ?iruri de caractere
  • Example#6144 - Exemplu floatval
  • Example#6145 - Exemplu floatval cu cele mai din stânga caractere non-numerice
  • Example#6146 - Exemplu get_defined_vars
  • Example#6147 - Exemplu get_resource_type
  • Example#6148 - Exemplu gettype
  • Example#6149 - Exemplu import_request_variables
  • Example#6150 - Exemple intval
  • Example#6151 - Verifica daca variabla este un array
  • Example#6152 - Exemple is_bool
  • Example#6153 - Exemplu is_callable
  • Example#6154 - is_callable ?i constructori
  • Example#6155 - Exemplu is_float
  • Example#6156 - is_int example
  • Example#6157 - Exemplu is_null
  • Example#6158 - Exemple is_numeric
  • Example#6159 - Exemplu is_object
  • Example#6160 - Exemplu is_resource
  • Example#6161 - Exemplu is_scalar
  • Example#6162 - Exemplu is_string
  • Example#6163 - Ecemple isset
  • Example#6164 - isset cu deplasamente în ?iruri de caractere
  • Example#6165 - Exemplu print_r
  • Example#6166 - Exemplu cu parametrul return
  • Example#6167 - Exemplu serialize
  • Example#6168 - Exemplu settype
  • Example#6169 - Exemplu strval cu utilizarea metodei magice a PHP 5 __toString().
  • Example#6170 - Exemplu unserialize
  • Example#6171 - Exemplu unserialize_callback_func
  • Example#6172 - Exemplu unset
  • Example#6173 - Utilizarea modificatorului (unset)
  • Example#6174 - Exemple var_dump
  • Example#6175 - Exemple var_export
  • Example#6176 - Exportarea claselor începând cu PHP 5.1.0
  • Example#6177 - Utilizarea __set_state() (începând cu PHP 5.1.0)
  • Example#6178 -
  • Example#6179 - OAuth::fetch example
  • Example#6180 - OAuth::getAccessToken example
  • Example#6181 - OAuth::getRequestToken example
  • Example#6182 - OAuth::setRequestEngine example
  • Example#6183 - An OAuth::setRsaCertificate example
  • Example#6184 - OAuth::setToken example
  • Example#6185 - OAuthProvider::__construct example
  • Example#6186 - Example OAuthProvider::consumerHandler callback
  • Example#6187 - OAuthProvider::generateToken example
  • Example#6188 - OAuthProvider::is2LeggedEndpoint example
  • Example#6189 - Example OAuthProvider::timestampNonceHandler callback
  • Example#6190 - Example OAuthProvider::tokenHandler callback
  • Example#6191 - A sample SCA component
  • Example#6192 - The structure of an SCA for PHP component
  • Example#6193 - Obtaining a proxy for a local PHP class
  • Example#6194 - Obtaining a proxy for a web service
  • Example#6195 - Calling services
  • Example#6196 - Obtaining a proxy using getService
  • Example#6197 - Making calls on the proxy
  • Example#6198 - StockQuote Service
  • Example#6199 - Generated WSDL
  • Example#6200 - Generated WSDL
  • Example#6201 - location attribute
  • Example#6202 - method with two arguments
  • Example#6203 - types section illustrating named parameters
  • Example#6204 - A Component that uses Data Structures
  • Example#6205 - An SCA::getService example
  • Example#6206 - is_soap_fault example
  • Example#6207 - SOAP's standard method for error reporting is exceptions
  • Example#6208 - SoapClient::__doRequest example
  • Example#6209 - SoapClient::__getFunctions example
  • Example#6210 - SoapClient::__getLastRequest() example
  • Example#6211 - SoapClient::__getLastRequestHeaders() example
  • Example#6212 - SoapClient::__getLastResponse() example
  • Example#6213 - SoapClient::__getLastResponse() example
  • Example#6214 - SoapClient::__getTypes example
  • Example#6215 - SoapClient::__setLocation example
  • Example#6216 - SoapClient::__setSoapHeaders example
  • Example#6217 - Set Multiple Headers
  • Example#6218 - SoapClient::__soapCall example
  • Example#6219 - SoapClient::SoapClient example
  • Example#6220 - SoapServer::addFunction example
  • Example#6221 - SoapServer::getFunctions example
  • Example#6222 - SoapServer::handle example
  • Example#6223 - SoapServer::setPersistence example
  • Example#6224 - SoapServer::SoapServer example
  • Example#6225 - Some examples
  • Example#6226 - Some examples
  • Example#6227 - SoapHeader::SoapHeader example
  • Example#6228 - SoapParam::SoapParam example
  • Example#6229 - SoapVar::SoapVar example
  • Example#6230 - Yar Server Example
  • Example#6231 - Access the server in borwser(GET request)
  • Example#6232 - Yar Client Example
  • Example#6233 - Yar Concurrent Client Example
  • Example#6234 - Yar_Server::__construct example
  • Example#6235 - Yar_Server::handle example
  • Example#6236 - Yar_Client::__call example
  • Example#6237 - Yar_Client::__construct example
  • Example#6238 - Yar_Client::setOpt example
  • Example#6239 - Yar_Concurrent_Client::call example
  • Example#6240 - Yar_Concurrent_Client::loop example
  • Example#6241 - Yar_Concurrent_Client::reset example
  • Example#6242 - Yar_Server_Exception::getType example
  • Example#6243 - Yar_Client_Exception::getType example
  • Example#6244 - Exemplu al func?iilor client XMLRPC
  • Example#6245 - Exemplu cu tip XML-RPC
  • Example#6246 - Un exemplu xmlrpc_set_type
  • Example#6247 - For Each in ASP
  • Example#6248 - foreach in PHP
  • Example#6249 - COM example (1)
  • Example#6250 - COM example (2)
  • Example#6251 - DOTNET example
  • Example#6252 - Variant example, PHP 4.x style
  • Example#6253 - Variant example, PHP 5 style
  • Example#6254 - COM event sink example
  • Example#6255 - Statistics about the current PHP process
  • Example#6256 - Statistics about global memory utilization
  • Example#6257 - Registering a PHP script to run as a service
  • Example#6258 - Unregistering a service
  • Example#6259 - Running as a service
  • Example#6260 - A win32_create_service example
  • Example#6261 - A win32_delete_service example
  • Example#6262 - A win32_start_service_ctrl_dispatcher example
  • Example#6263 - book.xml
  • Example#6264 - Creating a new DOMAttr object
  • Example#6265 - DOMAttr::isId() Example
  • Example#6266 - Creating a new DOMCdataSection object
  • Example#6267 - Creating a new DOMComment
  • Example#6268 - Creating a new DOMDocument
  • Example#6269 - Creating a new element and inserting it as root
  • Example#6270 - Passing text containing an unescaped & as value
  • Example#6271 - Creating a new element and inserting it as root
  • Example#6272 - A namespace prefix example
  • Example#6273 - DOMDocument::getElementById() Example
  • Example#6274 - Basic Usage Example
  • Example#6275 - Get all the XInclude elements
  • Example#6276 - DOMDocument::importNode example
  • Example#6277 - Creating a Document
  • Example#6278 - Creating a Document
  • Example#6279 - Creating a Document
  • Example#6280 - Creating a Document
  • Example#6281 - Static invocation of loadXML
  • Example#6282 - Adding a new method to DOMElement to ease our code
  • Example#6283 - Retrieving elements as custom class
  • Example#6284 - Retrieving owner document
  • Example#6285 - Saving a DOM tree into a file
  • Example#6286 - Saving a HTML tree into a string
  • Example#6287 - Saving a HTML tree into a file
  • Example#6288 - Saving a DOM tree into a string
  • Example#6289 - Example of DTD validation
  • Example#6290 - DOMDocument::xinclude() example
  • Example#6291 - Appending XML data to your document
  • Example#6292 - Creating a new DOMElement
  • Example#6293 - Setting an attribute
  • Example#6294 - Creating a new DOMEntityReference
  • Example#6295 - Creating a document with an attached DTD
  • Example#6296 - Testing your DOM Implementation
  • Example#6297 - Adding a child
  • Example#6298 - DOMNode::getLineNo example
  • Example#6299 - DOMNode::getNodePath example
  • Example#6300 - Removing a child
  • Example#6301 - Traversing all the entries of the table
  • Example#6302 - Creating a new DOMProcessingInstruction object
  • Example#6303 - Creating a new DOMText
  • Example#6304 - Getting the count of all the english books
  • Example#6305 - Getting all the english books
  • Example#6306 - book.xml
  • Example#6307 - DOMXPath::registerPHPFunctions with php:functionString
  • Example#6308 - DOMXPath::registerPHPFunctions with php:function
  • Example#6309 - Import SimpleXML into DOM with dom_import_simplexml
  • Example#6310 - A libxml_get_errors example
  • Example#6311 - libxml_set_external_entity_loader example
  • Example#6312 - A libxml_set_streams_context example
  • Example#6313 - A libxml_use_internal_errors example
  • Example#6314 - Access via property name
  • Example#6315 - Access via property name as array index
  • Example#6316 - Data Object iteration
  • Example#6317 - Access many-valued property by name
  • Example#6318 - Many-valued element access
  • Example#6319 - Many-valued property iteration
  • Example#6320 - Chained property access
  • Example#6321 - XPath navigation
  • Example#6322 - XPath querying
  • Example#6323 - Creating child data objects
  • Example#6324 - Unset a primitive property
  • Example#6325 - Unset a data object
  • Example#6326 - Unset a referenced data object
  • Example#6327 - Access via property index
  • Example#6328 - Getting the SDO_Sequence interface
  • Example#6329 - Get/set sequence values
  • Example#6330 - Sequence iteration
  • Example#6331 - Sequence versus Data Object
  • Example#6332 - Adding to a sequence
  • Example#6333 - Removing from a sequence
  • Example#6334 - Reflecting on a Data Object
  • Example#6335 - Accessing the type information
  • Example#6336 - A SDO_DAS_DataFactory::addPropertyToType example
  • Example#6337 - A SDO_DAS_DataFactory::addType example
  • Example#6338 - Creating a data object
  • Example#6339 - Retrieving a data object
  • Example#6340 - Updating a data object
  • Example#6341 - Deleting a data object
  • Example#6342 - One company, one department - Create
  • Example#6343 - One company, one department - Retrieve and Update
  • Example#6344 - One company, two departments - Retrieve and Delete
  • Example#6345 - One company, one department, one employee - Create
  • Example#6346 - One company, one department, one employee - Retrieve and update
  • Example#6347 - One company, two departments, two employees - Retrieve and delete
  • Example#6348 - Retrieving a data object using executePreparedQuery
  • Example#6349 - Loading, altering, and saving an XML document
  • Example#6350 - Creating a new XML document
  • Example#6351 - Setting XML document properties
  • Example#6352 - Using an open type
  • Example#6353 - Finding out what you can from the document
  • Example#6354 - Printing the SDO model
  • Example#6355 - Include file example.php with XML string
  • Example#6356 - Getting <plot>
  • Example#6357 - Getting <line>
  • Example#6358 - Accessing non-unique elements in SimpleXML
  • Example#6359 - Using attributes
  • Example#6360 - Comparing Elements and Attributes with Text
  • Example#6361 - Comparing Two Elements
  • Example#6362 - Using XPath
  • Example#6363 - Setting values
  • Example#6364 - Adding elements and attributes
  • Example#6365 - DOM Interoperability
  • Example#6366 - Loading broken XML string
  • Example#6367 - Add attributes and children to a SimpleXML element
  • Example#6368 - Add attributes and children to a SimpleXML element
  • Example#6369 - Get XML
  • Example#6370 - Using asXML() on SimpleXMLElement::xpath results
  • Example#6371 - Interpret an XML string
  • Example#6372 - Traversing a children() pseudo-array
  • Example#6373 - Using namespaces
  • Example#6374 - Create a SimpleXMLElement object
  • Example#6375 - Create a SimpleXMLElement object from a URL
  • Example#6376 - Counting the number of children
  • Example#6377 - Get document namespaces
  • Example#6378 - Working with multiple namespaces
  • Example#6379 - Get XML element names
  • Example#6380 - Get document namespaces in use
  • Example#6381 - Setting a namespace prefix to use in an XPath query
  • Example#6382 - Get string content
  • Example#6383 - Xpath
  • Example#6384 - Return the current element
  • Example#6385 - Return the sub-elements of the current element
  • Example#6386 - Check whether the current element has sub-elements
  • Example#6387 - Get the current XML tag key
  • Example#6388 - Move to the next element
  • Example#6389 - Rewind to the first element
  • Example#6390 - Check whether the current element is valid
  • Example#6391 - Importing DOM
  • Example#6392 - Interpret an XML document
  • Example#6393 - Interpret an XML string
  • Example#6394 - Serializarea unei singure valori cu WDDX
  • Example#6395 - Utilizarea pachetelor incrementale cu WDDX
  • Example#6396 - Exemplu wddx_serialize_vars
  • Example#6397 - Show XML Element Structure
  • Example#6398 - Map XML to HTML
  • Example#6399 - External Entity Example
  • Example#6400 - xmltest.xml
  • Example#6401 - xmltest2.xml
  • Example#6402 - xml_parse_into_struct example
  • Example#6403 - moldb.xml - small database of molecular information
  • Example#6404 - parsemoldb.php - parses moldb.xml into an array of molecular objects
  • Example#6405 - xml_set_object example
  • Example#6406 - Validating XML
  • Example#6407 - collection.xml
  • Example#6408 - collection.xsl
  • Example#6409 - fruits.xml
  • Example#6410 - fruits.xsl
  • Example#6411 - Collating and printing errors
  • Example#6412 - Creating an XSLTProcessor
  • Example#6413 - Testing EXSLT support
  • Example#6414 - Simple PHP Function call from a stylesheet
  • Example#6415 - Changing the owner before the transformation
  • Example#6416 - Example profiling output
  • Example#6417 - Transforming to a DOMDocument
  • Example#6418 - Transforming to a HTML file
  • Example#6419 - Transforming to a string
  • Example#6420 - Leak Detection in Action
  • Example#6421 - Accessor macros for per-module globals
  • Example#6422 - "counter"'s basic interface
  • Example#6423 - "counter"'s extended interface
  • Example#6424 - "counter"'s objective interface
  • Example#6425 - An example config.m4 file
  • Example#6426 - Sample configure output
  • Example#6427 - counter's config.m4 file
  • Example#6428 - An example config.w32 file
  • Example#6429 - counter's config.w32 file
  • Example#6430 - Files in the counter extension, in no particular order
  • Example#6431 - zend_module declaration in the counter extension
  • Example#6432 - zend_module definition in PHP 5.3
  • Example#6433 - Counter extension module definition
  • Example#6434 - The wrong way to store the basic counter interface's value
  • Example#6435 - The counter module's globals
  • Example#6436 - The counter module's global structure declaration
  • Example#6437 - Accessor macros for per-module globals
  • Example#6438 - The right way to store the basic counter interface's value
  • Example#6439 - counter's PHP_MINFO function
  • Example#6440 - Example macros for invoking pdo_SKEL_error
  • Example#6441 - Using pdo_parse_params
  • Example#6442 - Implementing preparer for drivers that don't support native prepared statements
  • Example#6443 - simple stream example that displays the PHP home page
  • Example#6444 - How to accept a stream as a parameter
  • Example#6445 - How to return a stream from a function
  • Example#6446 - The default config.m4.
  • Example#6447 - A simple extension.
  • Example#6448 - A test file for first_module.so.
  • Example#6449 - Internal declaration of zend_function_entry.
  • Example#6450 - Internal declaration of zend_module_entry.
  • Example#6451 - PHP's implementation of variable arguments in fsockopen().
  • Example#6452 - PHP/Zend zval type definition.
  • Example#6453 - Testing for referenced parameter passing.
  • Example#6454 - Creating variables with different scopes.
  • Example#6455 - Creation of a long.
  • Example#6456 - Adding an element to an associative array.
  • Example#6457 - Adding an element to an indexed array.
  • Example#6458 - Source code and screenshot for output in phpinfo.
  • Example#6459 - Printing execution information.
  • Example#6460 - Calling user functions.
  • Example#6461 - A hidden HTML form element
  • Example#6462 - Data to be edited by the user
  • Example#6463 - In a URL
  • Example#6464 - Generating Javascript with PHP
  • Example#6465 - Emulating Register Globals
  • Example#6466 - Exemplu de cod PHP/FI
  • Example#6467 - În nucleul PHP
  • Example#6468 - Cod-sursa obiect-orientat în nucleul PHP
  • Example#6469 - În extensia bzip2
  • Example#6470 - În extensia datetime
  • Example#6471 - În extensia dBase
  • Example#6472 - În extensia mcrypt
  • Example#6473 - În extensia oci8
  • Example#6474 - În extensia SPL
  • Example#6475 - În extensia Semaphore (sysvmsg)
  • Example#6476 - Un exemplu Zip 5.2.1+
  • Example#6477 - strrpos ?i strripos acum utilizeaza întregul string în calitate de 'ac'
  • Example#6478 - Un obiect fara proprieta?i nu mai este considerat "vid"
  • Example#6479 - În unele cazuri clasele trebuie declarate înainte de a fi utilizate
  • Example#6480 - Migrarea fi?ierelor de configurare Apache pentru PHP 5
  • Example#6481 - Migrarea fi?ierelor de configurare Apache pentru PHP 5, modul CGI
  • Example#6482 - Activeaza raportarea deplina a erorilor pe ecran pentru domeniul dev.
  • Example#6483 - Adauga un script de securitate pentru regiunile protejate
  • Example#6484 - include_path în Unix
  • Example#6485 - include_path în Windows
  • Example#6486 - include_path în Unix, utilizând variabile de mediu ${USER}
  • Example#6487 - string.rot13
  • Example#6488 - string.toupper
  • Example#6489 - string.tolower
  • Example#6490 - string.strip_tags
  • Example#6491 - convert.base64-encode & convert.base64-decode
  • Example#6492 - convert.quoted-printable-encode & convert.quoted-printable-decode
  • Example#6493 - zlib.deflate ?i zlib.inflate
  • Example#6494 - zlib.deflate simplu
  • Example#6495 - bzip2.compress ?i bzip2.decompress
  • Example#6496 - Criptarea con?inutului unui fi?ier utilizând 3DES
  • Example#6497 - Citirea unui fi?ier criptat
Listingul func?iilor ?i metodelor
Jurnalul modificarilor
Listingul-indice


Jurnalul modificarilor

Au fost efectuate urmatoarele modificari ale func?iilor extensiilor încorporate.

Version | Function | Description
PHP 7.0.15, PHP 7.1.1 | get_defined_functions | The exclude_disabled parameter has been added.
Enter the version of change here | pcntl_signal_get_handler | Describe the change
dbase 7.0.0 | dbase_add_record | dbase_identifier is now a resource instead of an int.
dbase_close | dbase_identifier is now a resource instead of an int.
dbase_create | The return value is now a resource instead of an int.
dbase_delete_record | dbase_identifier is now a resource instead of an int.
dbase_get_header_info | dbase_identifier is now a resource instead of an int.
dbase_get_record | dbase_identifier is now a resource instead of an int.
dbase_get_record_with_names | dbase_identifier is now a resource instead of an int.
dbase_numfields | dbase_identifier is now a resource instead of an int.
dbase_numrecords | dbase_identifier is now a resource instead of an int.
dbase_open | The return value is now a resource instead of an int.
dbase_pack | dbase_identifier is now a resource instead of an int.
dbase_replace_record | dbase_identifier is now a resource instead of an int.
7.2.0 | idn_to_ascii | INTL_IDNA_VARIANT_2003 has been deprecated; use INTL_IDNA_VARIANT_UTS46 instead.
idn_to_utf8 | INTL_IDNA_VARIANT_2003 has been deprecated; use INTL_IDNA_VARIANT_UTS46 instead.
imageantialias | imageantialias is now generally available. Formerly it was only available if PHP was compiled with the bundled version of the GD library.
imagegd | imagegd now allows to output truecolor images. Formerly, these have been implicitly converted to palette.
imagelayereffect | Added IMG_EFFECT_MULTIPLY (requires system libgd >= 2.1.1 or the bundled libgd).
imagetypes | IMG_BMP added.
proc_nice | This function is now available on Windows.
7.1.0 | array_rand | The internal randomization algorithm has been changed to use the Mersenne Twister Random Number Generator instead of the libc rand function.
curl_multi_setopt | Introduced CURLMOPT_PUSHFUNCTION.
file_get_contents | Support for negative offsets has been added.
getimagesize | Added WebP support.
getopt | Added the optind parameter.
grapheme_extract | Support for negative starts has been added.
grapheme_stripos | Support for negative offsets has been added.
grapheme_strpos | Support for negative offsets has been added.
iconv_strpos | Support for negative offsets has been added.
mb_ereg | mb_ereg will now set regs to an empty array, if nothing matched. Formerly, regs was not modified in that case.
mb_ereg_replace | The e modifier has been deprecated.
mb_ereg_search_setpos | Support for negative positions has been added.
mb_eregi | mb_eregi will now set regs to an empty array, if nothing matched. Formerly, regs was not modified in that case.
mb_eregi_replace | The e modifier has been deprecated.
mb_strimwidth | Support for negative starts and widths has been added.
mb_stripos | Support for negative offsets has been added.
mb_strpos | Support for negative offsets has been added.
mt_rand | rand has been made an alias of mt_rand.
mt_rand | mt_randhas been updated to use the fixed, correct, version of the Mersenne Twister algorithm. To fall back to the old behaviour, use mt_srand with MT_RAND_PHP as the second paramter.
mt_srand | srand has been made an alias of mt_srand.
mt_srand | mt_randhas been updated to use the fixed, correct, version of the Mersenne Twister algorithm. To fall back to the old behaviour, use mt_srand with MT_RAND_PHP as the second paramter.
openssl_decrypt | The tag and aad parameters were added.
openssl_encrypt | The tag, aad and tag_length parameters were added.
output_add_rewrite_var | Before PHP 7.1.0, rewrite vars set by output_add_rewrite_var use the same Session module trans sid output buffer. Since PHP 7.1.0, dedicated output buffer is used, url_rewriter.tags is used solely for output functions, url_rewriter.hosts is addedd.
output_reset_rewrite_vars | Before PHP 7.1.0, rewrite vars set by output_add_rewrite_var use the same Session module trans sid output buffer. Since PHP 7.1.0, dedicated output buffer is used and output_reset_rewrite_vars only removes rewrite vars defined by output_add_rewrite_var.
pcntl_signal | As of PHP 7.1.0 the handler callback is given a second argument containing the signinfo of the specific signal. This data is only supplied if the operating system has the signinfo_t structure. If the OS does not implement siginfo_t NULL is supplied.
rand | rand has been made an alias of mt_rand.
shuffle | The internal randomization algorithm has been changed to use the Mersenne Twister Random Number Generator instead of the libc rand function.
srand | srand has been made an alias of mt_srand.
str_shuffle | The internal randomization algorithm has been changed to use the Mersenne Twister Random Number Generator instead of the libc rand function.
stripos | Support for negative offsets has been added.
strpos | Support for negative offsets has been added.
substr_count | Support for negative offsets and lengths has been added.
7.0.16, 7.1.2 | fopen | The 'e' option were added.
7.0.16 | dns_get_record | Added support for CAA record type.
7.0.11 | iconv_substr | If str is equal to offset characters long, an empty string will be returned. Prior to this version, FALSE was returned in this case.
7.0.7 | curl_multi_setopt | Introduced CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLMOPT_MAX_HOST_CONNECTIONS, CURLMOPT_MAX_PIPELINE_LENGTH and CURLMOPT_MAX_TOTAL_CONNECTIONS.
curl_setopt | Introduced CURL_HTTP_VERSION_2, CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, CURL_HTTP_VERSION_2TLS, CURL_REDIR_POST_301, CURL_REDIR_POST_302, CURL_REDIR_POST_303, CURL_REDIR_POST_ALL, CURL_VERSION_KERBEROS5, CURL_VERSION_PSL, CURL_VERSION_UNIX_SOCKETS, CURLAUTH_NEGOTIATE, CURLAUTH_NTLM_WB, CURLFTP_CREATE_DIR, CURLFTP_CREATE_DIR_NONE, CURLFTP_CREATE_DIR_RETRY, CURLHEADER_SEPARATE, CURLHEADER_UNIFIED, CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLMOPT_MAX_HOST_CONNECTIONS, CURLMOPT_MAX_PIPELINE_LENGTH, CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPT_CONNECT_TO, CURLOPT_DEFAULT_PROTOCOL, CURLOPT_DNS_INTERFACE, CURLOPT_DNS_LOCAL_IP4, CURLOPT_DNS_LOCAL_IP6, CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOPT_HEADEROPT, CURLOPT_LOGIN_OPTIONS, CURLOPT_PATH_AS_IS, CURLOPT_PINNEDPUBLICKEY, CURLOPT_PIPEWAIT, CURLOPT_PROXY_SERVICE_NAME, CURLOPT_PROXYHEADER, CURLOPT_SASL_IR, CURLOPT_SERVICE_NAME, CURLOPT_SSL_ENABLE_ALPN, CURLOPT_SSL_ENABLE_NPN, CURLOPT_SSL_FALSESTART, CURLOPT_SSL_VERIFYSTATUS, CURLOPT_STREAM_WEIGHT, CURLOPT_TCP_FASTOPEN, CURLOPT_TFTP_NO_OPTIONS, CURLOPT_UNIX_SOCKET_PATH, CURLOPT_XOAUTH2_BEARER, CURLPROTO_SMB, CURLPROTO_SMBS, CURLPROXY_HTTP_1_0, CURLSSH_AUTH_AGENT and CURLSSLOPT_NO_REVOKE.
7.0.0 | array_column | Added the ability for the input parameter to be an array of objects.
assert | assert is now a language construct and not a function. assertion can now be an expression. The second parameter is now interpreted either as an exception (if a Throwable object is given), or as the description supported from PHP 5.4.8 onwards.
curl_setopt | Support for disabling the CURLOPT_SAFE_UPLOAD option has been removed. All curl file uploads must use CURLFile.
define | array values are allowed.
dirname | Added the optional levels parameter.
dl | dl is disabled in PHP-FPM.
getrusage | This function is now supported on Windows.
gmmktime | Parametrul is_dst a fost eliminat.
imagepsbbox | T1Lib support was removed from PHP, thus this function was removed.
imagepsencodefont | T1Lib support was removed from PHP, thus this function was removed.
imagepsextendfont | T1Lib support was removed from PHP, thus this function was removed.
imagepsfreefont | T1Lib support was removed from PHP, thus this function was removed.
imagepsloadfont | T1Lib support was removed from PHP, thus this function was removed.
imagepsslantfont | T1Lib support was removed from PHP, thus this function was removed.
imagepstext | T1Lib support was removed from PHP, thus this function was removed.
is_numeric | ?iruri în nota?ie hexadecimala (de ex. 0xf4c3b00c) nu mai sunt privite ca ?iruri numerice, în consecin?a is_numeric acum întoarce FALSE.
list | Strings can no longer be unpacked.
list | list expressions can no longer be completely empty.
list | The order that the assignment operations are performed in has changed.
mktime | Parametrul is_dst a fost eliminat.
ob_start | In case ob_start is used inside an output buffer callback, this function will no longer issue an E_ERROR but instead an E_RECOVERABLE_ERROR, allowing custom error handlers to catch such errors.
parse_ini_file | Hash marks (#) are no longer recognized as comments.
preg_replace | Support for the /e modifier has been removed. Use preg_replace_callback instead.
session_regenerate_id | session_regenerate_id saves old session data before closing.
session_start | The options parameter was added.
set_exception_handler | The type of parameter passed into exception_handler changed from Exception to Throwable
setlocale | Support for the category parameter passed as a string has been removed. Only LC_* constants can be used as of this version.
shmop_close | The type of shmid has been changed from int to resource.
shmop_delete | The type of shmid has been changed from int to resource.
shmop_open | The return type of shmop_open has been changed from int to resource.
shmop_read | The type of shmid has been changed from int to resource.
shmop_size | The type of shmid has been changed from int to resource.
shmop_write | The type of shmid has been changed from int to resource.
substr | If string is equal to start characters long, an empty string will be returned. Prior to this version, FALSE was returned in this case.
token_get_all | Added the optional flags parameter along with the TOKEN_PARSE flag.
unserialize | Parametrul options a fost adaugat.
IntlDateFormatter::setTimeZoneId | This function has been removed.
5.6.25, 7.0.10 | imagetypes | IMG_WEBP added.
SplFileObject::getCsvControl | Added the escape character to the returned array.
5.6.16 | mysqli::real_connect | Added the MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT flag for MySQL Native Driver
5.6.12 | gd_info | WebP Support added.
5.6.6 | json_encode | option JSON_PRESERVE_ZERO_FRACTION a fost adaugata.
5.6.5 | crypt | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.6 would incorrectly return a DES hash.
5.6.3 | pack | The "q", "Q", "J" and "P" codes were added to enable working with 64-bit numbers.
5.6.1 | parse_ini_file | Added new INI_SCANNER_TYPED mode.
sem_acquire | The $nowait parameter was added.
5.6.0 | array_fill | num nu poate fi zero. Anterior num trebuia sa fie mai mare decât zero.
array_filter | A fost adaugat parametrul op?ional flag ?i constantele ARRAY_FILTER_USE_KEY ?i ARRAY_FILTER_USE_BOTH
crypt | Raise E_NOTICE security warning if salt is omitted.
curl_setopt | CURLOPT_SAFE_UPLOAD is now TRUE by default.
curl_setopt | Removed CURLOPT_CLOSEPOLICY and associated values.
escapeshellarg | Valoarea implicita a parametrului encoding a fost schimbata pentru a coincide cu valoarea op?iunii de configurare default_charset.
escapeshellcmd | Valoarea implicita a parametrului encoding a fost schimbata pentru a coincide cu valoarea op?iunii de configurare default_charset.
hash_algos | Support for gost-crypto was added. This implements the GOST hash function using the CryptoPro S-box tables as specified by RFC 4357, section 11.2.
html_entity_decode | Valoarea implicita a parametrului encoding a fost schimbata pentru a coincide cu valoarea op?iunii de configurare default_charset.
htmlentities | Valoarea implicita a parametrului encoding a fost schimbata pentru a coincide cu valoarea op?iunii de configurare default_charset.
htmlspecialchars | Valoarea implicita a parametrului encoding a fost schimbata pentru a coincide cu valoarea op?iunii de configurare default_charset.
json_decode | Variantele cuvintelor-cheie true, false ?i null care nu sunt scrise în întregime cu litere minuscule nu mai sunt acceptate ca date de intrare valide ?i vor genera avertismente.
mb_regex_encoding | Default encoding is changed to UTF-8. It was EUC-JP Previously.
mcrypt_create_iv | MCRYPT_DEV_URANDOM is now the default value of source.
mcrypt_decrypt | Invalid key and iv sizes are no longer accepted. mcrypt_decrypt will now throw a warning and return FALSE if the inputs are invalid. Previously keys and IVs were padded with '\0' bytes to the next valid size.
mcrypt_encrypt | Invalid key and iv sizes are no longer accepted. mcrypt_encrypt will now throw a warning and return FALSE if the inputs are invalid. Previously keys and IVs were padded with '\0' bytes to the next valid size.
pg_connect | Support for giving the PGSQL_CONNECT_ASYNC constant as the connect_type was added.
pg_convert | No longer experimental. Boolean/NULL data types are supported. Unknown/unsupported data types are escaped without validation. pg_convert could be used with any data types.
pg_delete | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
pg_insert | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
pg_insert | Unless PGSQL_DML_STRING is passed, the function now returns the connection resource instead of TRUE on success.
pg_lo_seek | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.
pg_lo_tell | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.
pg_lo_truncate | Added truncate function. It supports PostgreSQL 9.3's 64bit large object. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.
pg_meta_data | No longer experimental. Added "is enum" as default attribute. extended flag is added.
pg_select | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
pg_update | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
stream_socket_enable_crypto | The crypto_type is now optional.
stream_socket_enable_crypto | Introduce STREAM_CRYPTO_METHOD_ANY_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT, STREAM_CRYPTO_METHOD_ANY_SERVER, STREAM_CRYPTO_METHOD_TLSv1_0_SERVER, STREAM_CRYPTO_METHOD_TLSv1_1_SERVER, STREAM_CRYPTO_METHOD_TLSv1_2_SERVER.
substr_compare | length may now be 0.
unserialize | Manipularea datelor serialiate prin înlocuirea C: cu O: pentru a for?a instan?ierea obiectului fara a apela constructorul acum va e?ua.
ReflectionClass::newInstanceWithoutConstructor | All internal classes can now be instantiated except for those declared final.
XMLReader::getAttributeNo | XMLReader::getAttributeNo now returns NULL if the attribute doesn't exist.
XMLReader::getAttributeNs | XMLReader::getAttributeNS now returns NULL if the attribute doesn't exist.
5.5.22, 5.6.6 | flock | Added support for the wouldblock parameter on Windows.
5.5.21, 5.6.5 | SplFileObject::fputcsv | Added the escape parameter.
5.5.21 | crypt | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.5 (and earlier branches) would incorrectly return a DES hash.
5.5.19/5.6.3 | imagescale | The calculation of the height if new_height was negative or omitted was fixed; prior to these versions, the aspect ratio was not maintained correctly.
5.5.8 | DatePeriod::__construct | end type changed to DateTimeInterface. Previously, DateTime.
5.5.7 | apache_request_headers | This function became available in the CLI server.
apache_response_headers | This function became available in the CLI server.
getallheaders | Aceasta func?ie a devenit disponibila în serverul CLI.
5.5.4 | fputcsv | The escape_char parameter was added
5.5.3/5.4.19 | pg_delete | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.
pg_insert | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.
pg_select | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.
pg_update | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.
5.5.2 | DOMDocument::schemaValidate | Added the flags parameter
DOMDocument::schemaValidateSource | Added the flags parameter
5.5.1 | hex2bin | A warning is thrown if the input string is invalid hexadecimal string.
pg_unescape_bytea | A warning is thrown if the input string is invalid.
session_set_save_handler | Added the optional create_sid parameter.
5.5.0/PECL 3.0.0 | IntlDateFormatter::create | An IntlCalendar object is allowed for calendar. Objects of type IntlTimeZone and DateTimeZone are allowed for timezone. Invalid timezone identifiers (including empty strings) are no longer allowed for timezone. If NULL is given for timezone, the timezone identifier given by date_default_timezone_get will be used instead of ICU's default.
IntlDateFormatter::format | Support for providing IntlCalendar objects to the value parameter was added.
IntlDateFormatter::setCalendar | It became possible to pass an IntlCalendar object.
5.5.0 | DatePeriod::__construct | start type changed to DateTimeInterface. Previously, DateTime.
curl_getinfo | Introduced CURLINFO_RESPONSE_CODE, CURLINFO_HTTP_CONNECTCODE, CURLINFO_HTTPAUTH_AVAIL, CURLINFO_PROXYAUTH_AVAIL, CURLINFO_OS_ERRNO, CURLINFO_NUM_CONNECTS, CURLINFO_SSL_ENGINES, CURLINFO_COOKIELIST, CURLINFO_FTP_ENTRY_PATH, CURLINFO_APPCONNECT_TIME, CURLINFO_CONDITION_UNMET, CURLINFO_RTSP_CLIENT_CSEQ, CURLINFO_RTSP_CSEQ_RECV, CURLINFO_RTSP_SERVER_CSEQ and CURLINFO_RTSP_SESSION_ID.
curl_setopt | Added the cURL resource as the first argument to the CURLOPT_PROGRESSFUNCTION callback.
curl_setopt | Introduced CURLOPT_SHARE.
empty | empty acum sus?ine ?i expresii, nu doar variabile.
imagerotate | This function is now affected by the interpolation method set by the imagesetinterpolation function.
imagerotate | The ignore_transparent is now silently ignored.
ip2long | Prior to this version, on Windows ip2long would sometimes return a valid number even if passed a value which was not an (IPv4) Internet Protocol dotted address.
iterator_to_array | iterator_to_array gained support for key types other than integer and string when the use_keys parameter is enabled.
json_encode | A fost adaugat parametrul depth.
mysql_connect | Aceasta func?ie va genera o eroare E_DEPRECATED.
mysql_db_name | The mysql_list_dbs function is deprecated, and emits an E_DEPRECATED level error.
mysql_pconnect | This function will generate an E_DEPRECATED error.
mysql_tablename | The mysql_tablename function is deprecated, and emits an E_DEPRECATED level error.
pack | The "Z" code was added with equivalent functionality to "a" for Perl compatibility.
php_logo_guid | php_logo_guid has been removed from PHP.
phpinfo | Logo GUIDs were replaced with data URIs, and so turning off expose_php now has no effect on the result of phpinfo(). Credits are also now embedded within the output itself instead of linked.
preg_replace | The /e modifier is deprecated. Use preg_replace_callback instead. See the PREG_REPLACE_EVAL documentation for additional information about security risks.
set_error_handler | error_handler acum accepta NULL.
set_exception_handler | Previously, if NULL was passed then this function returned TRUE. It returns the previous handler since PHP 5.5.0.
setcookie | A Max-Age attribute is now included in the Set-Cookie header sent to the client.
setrawcookie | A Max-Age attribute is now included in the Set-Cookie header sent to the client.
unpack | Changes were made to bring this function into line with Perl: The "a" code now retains trailing NULL bytes. The "A" code now strips all trailing ASCII whitespace (spaces, tabs, newlines, carriage returns, and NULL bytes). The "Z" code was added for NULL-padded strings, and removes trailing NULL bytes.
zend_logo_guid | zend_logo_guid has been removed from PHP.
IntlDateFormatter::setTimeZoneId | This function has been deprecated.
mysqli::commit | Added flags and name parameters.
mysqli::options | The MYSQLI_SERVER_PUBLIC_KEY and MYSQLI_SERVER_PUBLIC_KEY options were added.
mysqli::rollback | Added flags and name parameters.
SoapClient::SoapClient | New ssl_method option.
5.4.43, 5.5.27, 5.6.11 | escapeshellarg | Exclamation marks are replaced by spaces.
escapeshellcmd | Exclamation marks are replaced by spaces.
5.4.32, 5.5.16 | ucwords | Added the delimiters parameter.
5.4.8 | assert | The description parameter was added. The description is also now provided to a callback function in ASSERT_CALLBACK mode as the fourth argument.
mb_strcut | Passing NULL as length extracts all bytes to the end of the string. Prior to this version NULL was treated the same as 0.
mb_substr | Passing NULL as length extracts all characters to the end of the string. Prior to this version NULL was treated the same as 0.
5.4.7 | curl_getinfo | Introduced CURLINFO_PRIMARY_IP, CURLINFO_PRIMARY_PORT, CURLINFO_LOCAL_IP and CURLINFO_LOCAL_PORT.
parse_url | Fixed host recognition when scheme is omitted and a leading component separator is present.
5.4.4 | hex2bin | A warning is thrown if the input string is of odd length. In PHP 5.4.0 the string was silently accepted, but the last byte was truncated.
5.4.0/PECL 2.0.0b1 | idn_to_ascii | Added the parameters variant and idna_info; UTS #46 support.
idn_to_utf8 | Added the parameters variant and idna_info; UTS #46 support.
5.4.0 | DOMDocument::loadHTML | Added options parameter.
DOMDocument::loadHTMLFile | Added options parameter.
apache_child_terminate | Aceasta func?ie a devenit disponibila în FastCGI. Anterior ea era sus?inuta doar când PHP era instalat ca modul Apache.
apache_request_headers | This function became available under FastCGI. Previously, it was supported when PHP was installed as an Apache module or by the NSAPI server module in Netscape/iPlanet/SunONE webservers.
apache_response_headers | This function became available under FastCGI. Previously, it was supported when PHP was installed as an Apache module or by the NSAPI server module in Netscape/iPlanet/SunONE webservers.
array_combine | Previous versions issued E_WARNING and returned FALSE for empty arrays.
array_multisort | The SORT_NATURAL and SORT_FLAG_CASE were added to array1_sort_flags as possible sort flags.
date_default_timezone_get | The TZ environment variable is no longer used to guess the timezone.
date_default_timezone_get | The timezone is no longer guessed from information available through the operating system as the guessed timezone can not be relied on.
debug_backtrace | Added the optional parameter limit.
debug_print_backtrace | Added the optional parameter limit.
define_syslog_variables | This function was removed from PHP.
dns_get_record | Added raw parameter.
empty | Verificarea deplasamentelor non-numerice ale ?irurilor de caractere întoarce TRUE.
error_reporting | E_STRICT a devenit parte componenta a E_ALL.
filter_input_array | Added add_empty parameter.
filter_var_array | Added add_empty parameter.
get_html_translation_table | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
get_html_translation_table | The default value for the encoding parameter was changed to UTF-8.
get_magic_quotes_gpc | Always returns FALSE because the magic quotes feature was removed from PHP.
get_magic_quotes_runtime | Always returns FALSE because the magic quotes feature was removed from PHP.
getallheaders | Aceasta func?ie a devenit disponibila în FastCGI. Anterior ea era sus?inuta daca PHP era instalat ca modul Apache sau ca modul server NSAPI în serverele web Netscape/iPlanet/SunONE.
gzcompress | Added encoding parameter.
gzdeflate | Added encoding parameter.
gzencode | FORCE_DEFLATE now generates RFC 1950 compliant output.
hash | The tiger algorithm now uses big-endian byte ordering. See also example below.
hash_algos | Support for joaat, fnv132 and fnv164 was added. Support for Salsa10 and Salsa20 was removed.
html_entity_decode | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
html_entity_decode | Default encoding changed from ISO-8859-1 to UTF-8.
htmlentities | The default value for the encoding parameter was changed to UTF-8.
htmlentities | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
htmlspecialchars | The default value for the encoding parameter was changed to UTF-8.
htmlspecialchars | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
htmlspecialchars_decode | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
http_build_query | The enc_type parameter was added.
iconv | Since this version, the function returns FALSE on illegal characters, unless //IGNORE is specified in output charset. Before, it returned partial output string.
imagecolorset | The alpha parameter was added.
imagegd | Added support for passing a stream resource to to.
imagegd2 | Added support for passing a stream resource to to.
imagegif | Added support for passing a stream resource to to.
imagejpeg | Disallowed passing an empty string to to to skip this argument.
imagejpeg | Added support for passing a stream resource to to.
imagepng | Added support for passing a stream resource to to.
imagewbmp | Added support for passing a stream resource to to.
imagewebp | Added support for passing a stream resource to to.
isset | Verificarea deplasamentelor non-numerice în ?iruri de caractere acum întoarce FALSE.
json_decode | A fost adaugat parametrul options.
json_encode | Au fost adaugate constantele JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE pentru parametrul options.
mb_encode_numericentity | Added is_hex parameter.
mysqli_get_cache_stats | The mysqli_get_cache_stats was removed.
number_format | This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions.
ob_start | The third parameter of ob_start changed from a boolean parameter called erase (which, if set to FALSE, would prevent the output buffer from being deleted until the script finished executing) to an integer parameter called flags. Unfortunately, this results in an API compatibility break for code written prior to PHP 5.4.0 that uses the third parameter. See the flags example for an example of how to handle this with code that needs to be compatible with both.
ob_start | A chunk size of 1 now results in chunks of 1 byte being sent to the output buffer.
openssl_decrypt | The raw_output was changed to options.
openssl_encrypt | The raw_output was changed to options.
preg_match_all | The matches parameter became optional.
scandir | sorting_order constants were added. Any nonzero value caused descending order in previous versions. So for all PHP versions, use 0 for ascending order, and 1 for descending order. An option for SCANDIR_SORT_NONE behavior did not exist prior to PHP 5.4.0.
session_set_save_handler | Added SessionHandlerInterface for implementing session handlers and SessionHandler to expose internal PHP session handlers.
snmp_set_valueretrieval | 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.
sort | Added support for SORT_NATURAL and SORT_FLAG_CASE as sort_flags
Phar::setStub | Added len parameter.
PharData::setStub | Added len parameter.
SimpleXMLElement::getDocNamespaces | Added from_root parameter.
SoapClient::SoapClient | New keep_alive option.
5.4 | grapheme_substr | 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.
5.3.19 | imagecreatefromxpm | imagecreatefromxpm is available on Windows.
5.3.9 | DateTime::createFromFormat | The + format specifier has been added.
dl | dl is enabled in PHP-FPM, albeit discouraged.
is_a | Added allow_string parameter
is_subclass_of | Added allow_string parameter
5.3.7 | crypt | Added $2x$ and $2y$ Blowfish modes to deal with potential high-bit attacks.
curl_getinfo | Introduced CURLINFO_REDIRECT_URL.
is_subclass_of | Added support for class_name to work with interfaces
5.3.6 | DateTime::modify | Absolute date/time statements now take effect. Previously, only relative parts were used.
DOMDocument::saveHTML | The node parameter was added.
array_product | The product of an empty array is now 1, when before this function would return 0 for an empty array.
debug_backtrace | The parameter provide_object changed to options and additional option DEBUG_BACKTRACE_IGNORE_ARGS is added.
debug_print_backtrace | Added the optional parameter options.
preg_match | Returns FALSE if offset is higher than subject length.
preg_match_all | Returns FALSE if offset is higher than subject length.
PDO_MYSQL DSN | Prior to version 5.3.6, charset was ignored.
5.3.4 | copy | Changed the context parameter to actually have an effect. Previously, any context was ignored.
get_html_translation_table | The encoding parameter was added.
mt_rand | Issues an E_WARNING and returns FALSE if max < min.
rawurlencode | Tilde characters are no longer encoded when rawurlencode is used with EBCDIC strings.
sleep | Before PHP 5.3.4, on Windows, sleep always returns NULL when sleep has occurred, regardless of whether the sleep was interrupted or not.
strip_tags | strip_tags ignores self-closing XHTML tags in allowable_tags.
IntlDateFormatter::format | Support for providing DateTime objects to the value parameter was added.
mysqli_driver::$report_mode | Changing the reporting mode is now be per-request, rather than per-process.
5.3.3 | DOMXPath::evaluate | The registerNodeNS parameter was added.
DOMXPath::query | The registerNodeNS parameter was added.
imap_fetch_overview | Add the update property.
json_encode | A fost adaugata constanta JSON_NUMERIC_CHECK pentru parametrul option.
ldap_sasl_bind | Support on Windows was added.
openssl_decrypt | The iv parameter was added.
openssl_encrypt | The iv parameter was added.
parse_url | Removed the E_WARNING that was emitted when URL parsing failed.
5.3.2 (PECL OCI8 1.4) | oci_set_prefetch | Before this release, rows must be >= 1.
5.3.2 | crypt | Added SHA-256 and SHA-512 crypt based on Ulrich Drepper's implementation.
crypt | Fixed Blowfish behaviour on invalid rounds to return "failure" string ("*0" or "*1"), instead of falling back to DES.
flock | The automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually.
gmp_init | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.
gmp_strval | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.
imap_append | Added INTERNALDATE support to imap_append.
imap_open | params added
5.3.1 | get_defined_constants | Windows only: Core constants are categorized under Core, previously mhash.
ibase_query | On success the function now returns TRUE if there were no affected rows, where it previously returned 0 (a zero followed by an empty space).
rename | rename can now rename files across drives in Windows.
5.3.0 (PECL OCI8 1.3.4) | oci_set_prefetch | Before this release, prefetching was limited to the lesser of rows rows and 1024 * rows bytes. The byte size restriction has now been removed.
5.3.0 | DateTime::__construct | If time contains an invalid date/time format, then an exception is now thrown. Previously an error was emitted.
DateTime::modify | A fost schimbata valoarea întoarsa în caz de succes din NULL în DateTime.
DateTime::setDate | A fost schimbata valoarea întoarsa în caz de succes din NULL în DateTime.
DateTime::setISODate | A fost schimbata valoarea întoarsa în caz de succes din NULL în DateTime.
DateTime::setTime | A fost schimbata valoarea întoarsa în caz de succes din NULL în DateTime.
DateTime::setTimezone | A fost schimbata valoarea întoarsa în caz de succes din NULL în DateTime.
DateTimeZone::getTransitions | The optional timestamp_begin and timestamp_end were added.
DateTimeZone::listIdentifiers | Added the optional what and country parameters.
DirectoryIterator::__construct | Throws UnexpectedValueException if the path cannot be opened.
acosh | This function is now available on all platforms
array_multisort | The SORT_LOCALE_STRING was added to array1_sort_flags as possible sort flags.
array_reduce | Changed initial to allow mixed, previously integer.
array_search | As with all internal PHP functions as of 5.3.0, array_search returns NULL if invalid parameters are passed to it.
asinh | This function is now available on all platforms
atanh | This function is now available on all platforms
call_user_func | 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.
call_user_func_array | 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.
checkdnsrr | This function is now available on Windows platforms.
clearstatcache | Added optional clear_realpath_cache and filename parameters.
copy | Added context support.
crypt | 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.
curl_getinfo | Introduced CURLINFO_CERTINFO.
curl_setopt | Introduced CURLOPT_PROGRESSFUNCTION.
date_default_timezone_set | Now throws E_WARNING rather than E_STRICT.
define_syslog_variables | This function now throws an E_DEPRECATED notice.
dl | 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.
dns_get_record | This function is now available on Windows platforms.
dns_get_record | Prior to this release, if the authns parameter was given, the addtl parameter was also required.
error_reporting | Au fost introduse E_DEPRECATED ?i E_USER_DEPRECATED.
exif_imagetype | Added icon support.
expm1 | This function is now available on all platforms
fgetcsv | The escape parameter was added
fnmatch | This function is now available on Windows platforms.
func_get_arg | This function can now be used in parameter lists.
func_get_arg | 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.
func_get_args | This function can now be used in parameter lists.
func_get_args | 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.
func_num_args | This function can now be used in parameter lists.
func_num_args | 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.
gd_info | JPG Support attribute renamed to JPEG Support.
get_cfg_var | get_cfg_var was fixed to be able to return "array" ini options.
get_class | NULL became the default value for object, so passing NULL to object now has the same result as not passing any value.
get_defined_constants | Core constants are categorized under Core, previously internal. On Windows, the Core Constants are categorized under mhash.
get_object_vars | This function now returns NULL if the object isn't an object. Previously FALSE was returned.
getimagesize | Added icon support.
getmxrr | This function is now available on Windows platforms.
getopt | Added support for "=" as argument/value separator.
getopt | Added support for optional values (specified with "::").
getopt | This function is no longer system dependent, and now works on Windows, too.
getopt | Parameter longopts is available on all systems.
hash_algos | Support for md2, ripemd256, ripemd320, salsa10, salsa20, snefru256 and sha224 was added
htmlentities | The constant ENT_IGNORE was added.
htmlspecialchars | The constant ENT_IGNORE was added.
imagecolorclosesthwb | This function is now available on Windows
imagefilter | Pixelation support (IMG_FILTER_PIXELATE) was added.
inet_ntop | This function is now available on Windows platforms.
inet_pton | This function is now available on Windows platforms.
ini_get | Previously, the empty string was returned if the configuration option didn't exist. now, FALSE is returned instead.
ini_get_all | Added details.
is_a | This function is no longer deprecated, and will therefore no longer throw E_STRICT warnings.
json_decode | A fost adaugat parametrul op?ional depth. Limita de imbricare implicita a fost marita de la 128 la 512.
json_encode | A fost adaugat parametrul options.
link | This function is now available on Windows platforms (Vista, Server 2008 or greater).
linkinfo | This function is now available on Windows platforms (Vista, Server 2008 or greater).
log1p | This function is now available on all platforms
mb_get_info | The entry "http_output_conv_mimetypes" was made available.
mcrypt_create_iv | It is no longer required to call srand first. This is now done automatically.
mcrypt_create_iv | MCRYPT_DEV_RANDOM and MCRYPT_DEV_URANDOM became available on Windows platforms.
mktime | mktime acum emite o notificare E_DEPRECATED daca este utilizat parametrul is_dst.
mysql_db_query | This function now throws an E_DEPRECATED notice.
mysql_escape_string | Aceasta functie returneaza o notificare de tip E_DEPRECATED.
mysqli_get_cache_stats | The mysqli_get_cache_stats was added as stub.
nl2br | Added the optional is_xhtml parameter. Before this version '<br />' was always inserted.
openssl_seal | The method parameter was added.
parse_ini_file | Added optional scanner_mode parameter. Single quotes may now be used around variable assignments. Hash marks (#) should no longer be used as comments and will throw a deprecation warning if used.
pg_lo_create | The optional object_id was added.
pg_lo_import | The optional object_id was added.
preg_quote | The - character is now quoted
property_exists | This function checks the existence of a property independent of accessibility.
rawurlencode | Now conforms to RFC 3986.
readlink | This function is now available on Windows platforms (Vista, Server 2008 or greater).
realpath | 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.
register_tick_function | Ticks are now supported on threaded web server modules.
round | The mode parameter was introduced.
session_start | If a session fails to start, then FALSE is returned. Previously TRUE was returned.
setlocale | This function now throws an E_DEPRECATED notice if a string is passed to the category parameter instead of one of the LC_* constants.
shm_attach | This function now returns a resource instead of an integer.
socket_create_pair | This function is now re-enabled on Windows platforms.
spl_autoload_register | Namespaces support was introduced.
spl_autoload_register | The prepend parameter was added.
stream_context_create | Added the optional params argument.
stream_socket_pair | This function is now available on Windows platforms.
stristr | Added the optional parameter before_needle.
strlen | Prior versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error.
strstr | Added the optional parameter before_needle.
strtotime | Anterior versiunii PHP 5.3.0, formatele de timp relative transmise prin argumentul time al func?iei strtotime, cum ar fi this week, previous week, last week ?i next week erau interpretate ca perioada de 7 zile relativ cu data/ora curenta, ?i nu ca o perioada de o saptamâna de la Monday pâna la Sunday.
strtotime | Anterior versiunii PHP 5.3.0, 24:00 nu era un format valid ?i strtotime întorcea FALSE.
sybase_connect | The new parameter was added.
symlink | This function is now available on Windows platforms (Vista, Server 2008 or greater).
time_nanosleep | This function is now available on Windows platforms.
time_sleep_until | This function is now available on Windows platforms.
touch | It became possible to change the modification time of a directory under Windows.
mysqli::__construct | Added the ability of persistent connections.
mysqli::options | The MYSQLI_OPT_INT_AND_FLOAT_NATIVE, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, MYSQLI_OPT_NET_READ_BUFFER_SIZE, and MYSQLI_OPT_SSL_VERIFY_SERVER_CERT options were added.
mysqli::query | Added the ability of async queries.
ReflectionFunction::__construct | name can now be a closure.
SplFileObject::setCsvControl | Added the escape parameter.
SplObjectStorage::attach | Added the data parameter.
XMLReader::expand | The parameter basenode was added.
5.2.15 | mysqli_driver::$report_mode | Changing the reporting mode is now be per-request, rather than per-process.
5.2.11 | get_defined_constants | 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.2.10 | array_rand | The resulting array of keys is no longer shuffled.
array_unique | Changed the default value of sort_flags back to SORT_STRING.
curl_setopt | Introduced CURLOPT_PROTOCOLS, and CURLOPT_REDIR_PROTOCOLS.
ip2long | Prior to this version, ip2long would sometimes return a valid number even if passed a value which was not an (IPv4) Internet Protocol dotted address.
natsort | Zero padded numeric strings (e.g., '00005') now essentially ignore the 0 padding.
5.2.9 | array_unique | Added the optional sort_flags defaulting to SORT_REGULAR. Prior to 5.2.9, this function used to sort the array with SORT_STRING internally.
5.2.8 | XSLTProcessor::importStylesheet | Accepts SimpleXMLElement again which was broken since PHP 5.2.6.
5.2.7 | error_log | A fost adaugata valoarea posibila 4 la message_type.
parse_ini_file | On syntax error this function will return FALSE rather than an empty array.
round | The inner workings of round was changed to conform to the C99 standard.
strtotime | În PHP 5 anterior versiunii 5.2.7, cererea de a ob?ine o anumita zi a saptamânii într-o luna, unde aceasta zi este prima zi a lunii, adauga în mod incorect o saptamâna la valoarea întoarsa. Aceasta a fost corectat în versiunea 5.2.7 ?i cele ulterioare.
5.2.6 | fopen | The 'c' and 'c+' options were added
5.2.5 | addcslashes | The escape sequences \v and \f were added.
debug_backtrace | Added the optional parameter provide_object.
imagefilter | Alpha support for IMG_FILTER_COLORIZE was added.
5.2.4 | array_slice | The default value of the length parameter was changed to NULL. A NULL length now tells the function to use the length of array. Prior to this version, a NULL length was taken to mean a zero length (nothing will be returned).
checkdnsrr | TXT type was added.
curl_getinfo | Introduced CURLINFO_PRIVATE.
curl_setopt | Introduced CURLOPT_PRIVATE.
get_loaded_extensions | The optional zend_extensions parameter was added
ldap_first_attribute | The ber_identifier was removed. This is now handled automatically by PHP.
ldap_next_attribute | The ber_identifier was removed. This is now handled automatically by PHP.
parse_ini_file | 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.
stream_wrapper_register | Added the flags parameter.
5.2.3 | getimagesize | Read errors generated by this function downgraded to E_NOTICE from E_WARNING.
htmlentities | The double_encode parameter was added.
htmlspecialchars | The double_encode parameter was added.
json_decode | Limita de imbricare a fost marita de la 20 la 128.
XMLWriter::writeElement | The content parameter became optional.
XMLWriter::writeElementNS | The content parameter became optional.
PDOStatement::getColumnMeta | table field
5.2.2 - 5.2.6 | substr | If the start parameter indicates the position of a negative truncation or beyond, false is returned. Other versions get the string from start.
5.2.2 | DOMDocument::registerNodeClass | 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.
ftp_ssl_connect | 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.
phpinfo | The "Loaded Configuration File" information was added, when before only "Configuration File (php.ini) Path" existed.
preg_match | Named subpatterns now accept the syntax (?<name>) and (?'name') as well as (?P<name>). Previous versions accepted only (?P<name>).
preg_match_all | Named subpatterns now accept the syntax (?<name>) and (?'name') as well as (?P<name>). Previous versions accepted only (?P<name>).
proc_terminate | Previous versions used to destroy the given process resource.
token_get_all | Line numbers are returned in element 2
5.2.1 | iterator_to_array | The use_keys parameter was added.
json_decode | A fost adaugata sus?inerea decodificarii JSON a tipurilor de baza.
memory_get_peak_usage | Compiling with --enable-memory-limit is no longer required for this function to exist.
memory_get_usage | Compiling with --enable-memory-limit is no longer required for this function to exist.
mt_srand | The Mersenne Twister implementation in PHP now uses a new seeding algorithm by Richard Wagner. Identical seeds no longer produce the same sequence of values they did in previous versions. This behavior is not expected to change again, but it is considered unsafe to rely upon it nonetheless.
proc_open | Added the bypass_shell option to the other_options parameter.
realpath | Prior to this version, realpath returned FALSE if path is an empty string or NULL.
5.2.0 | base64_decode | strict added
curl_multi_info_read | msgs_in_queue was added.
error_reporting | A fost introdusa E_RECOVERABLE_ERROR.
imagettftext | It is now possible to specify an hexadecimal entity in text.
imap_open | n_retries added
imap_reopen | n_retries added
mb_strrpos | Added the optional parameter offset.
memory_get_peak_usage | real_usage was added.
memory_get_usage | real_usage was added.
openssl_verify | The signature_alg parameter was added.
pathinfo | The PATHINFO_FILENAME constant was added.
pg_escape_bytea | connection added
pg_escape_string | connection added
session_get_cookie_params | The "httponly" entry was added in the returned array.
session_set_cookie_params | The httponly parameter was added.
set_error_handler | Func?ia de prelucrare a erorii trebuie sa întoarca FALSE pentru a popula $php_errormsg.
setcookie | The httponly parameter was added.
setrawcookie | The httponly parameter was added.
snmp_set_oid_numeric_print | Since PHP 5.2.0.
PDOStatement::execute | The keys from input_parameters must match the ones declared in the SQL. Before PHP 5.2.0 this was silently ignored.
SimpleXMLElement::children | The optional parameter is_prefix was added.
SimpleXMLElement::__construct | Added the ns and is_prefix parameters.
SoapServer::SoapServer | Added the typemap option.
XMLReader::open | encoding and options were added.
XMLReader::XML | encoding and options were added.
5.1.3 | DirectoryIterator::__construct | Throws RuntimeException if the path is an empty string.
curl_getinfo | Introduced CURLINFO_HEADER_OUT.
get_headers | This function now uses the default stream context, which can be set/changed with the stream_context_set_default function.
http_build_query | Square brackets are escaped.
imagecolorallocate | Returns FALSE if the allocation failed. Previously -1 was returned.
imagecolorallocatealpha | Returns FALSE if the allocation failed. Previously -1 was returned.
imagepng | Added the filters parameter.
mb_get_info | The entries "mail_charset", "mail_header_encoding", and "mail_body_encoding" were made available.
SoapClient::__doRequest | The one_way parameter was added.
XMLReader::getAttribute | Return NULL if no attribute found. Previously, returned an empty string.
5.1.2 | date_default_timezone_set | The function started to validate the timezone_identifier parameter.
header | This function now prevents more than one header to be sent at once as a protection against header injection attacks.
http_build_query | The arg_separator parameter was added.
imagepng | Added the quality parameter.
parse_url | Added the component parameter.
SimpleXMLElement::__construct | Added the options and data_is_url parameters.
5.1.1 | date | Exista constante utile pentru formate standarde de date/ore, ce pot fi utilizate pentru a specifica parametrul format.
debug_backtrace | Added the current object as a possible return element.
gmdate | Exista constante utile a unor formate standarde ale datei/orei ce pot fi utilizate pentru a specifica parametrul format.
5.1.0 | DirectoryIterator::__construct | Throws RuntimeException on error. Previously, threw Exception.
DOMDocument::save | Added the options parameter
DOMDocument::saveXML | Added the options parameter
class_implements | Added the option to pass the class parameter as a string. Added the autoload parameter.
class_parents | Added the option to pass the class parameter as a string. Added the autoload parameter.
ctype_digit | Before PHP 5.1.0, this function returned TRUE when text was an empty string.
curl_setopt | Introduced CURLOPT_AUTOREFERER, CURLOPT_BINARYTRANSFER, CURLOPT_FTPSSLAUTH, CURLOPT_PROXYAUTH, and CURLOPT_TIMECONDITION.
date | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.
date | Domeniul valid al unui timestamp este de obicei de la Fri, 13 Dec 1901 20:45:54 GMT pâna la Tue, 19 Jan 2038 03:14:07 GMT. (Acestea sunt datele ce corespund valorilor minima ?i maxima pentru un întreg cu semn pe 32 de bi?i). Însa înainte de PHP 5.1.0 acest domeniu era limitat de la 01-01-1970 pâna la 19-01-2038 pe unele sisteme (de ex. Windows).
date_sunrise | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.
date_sunset | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.
explode | Support for negative limits was added
fgetcsv | The length is now optional. Default is 0, meaning no length limit.
file_get_contents | Added the offset and maxlen parameters.
file_put_contents | Added support for LOCK_EX and the ability to pass a stream resource to the data parameter
get_parent_class | If called without parameter outside object, this function would have returned NULL with a warning, but now returns FALSE.
gettimeofday | A fost adaugat parametrul return_float.
glob | GLOB_ERR was added
gmdate | Domeniul valid al unui timestamp este de obicei de la Fri, 13 Dec 1901 20:45:54 GMT pâna la Tue, 19 Jan 2038 03:14:07 GMT. (Acestea sunt datele ce corespund valorilor minima ?i maxima a unui integer pe 32 de bi?i). Însa pâna la PHP 5.1.0 acest domeniu era limitat de la 01-01-1970 pâna la 19-01-2038 pe unele sisteme (de ex. Windows).
gmmktime | Începând cu PHP 5.1.0, parametrul is_dst a devenit învechit. În rezultat, trabuie utilizata în loc noua facilitate de manipulare cu fusul orar.
idate | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.
imagerotate | ignore_transparent was added.
intval | Emite E_NOTICE ?i întoarce 1, când un obiect este transmis catre var.
localtime | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.
md5_file | Changed the function to use the streams API. It means that you can use it with wrappers, like md5_file('http://example.com/..')
mktime | Parametrul is_dst a devenit dezapreciat. Func?ia a fost modificata sa întoarca FALSE în caz de eroare, în loc de -1. Func?ia a fost modificata sa accepte anul, luna ?i ziua cu valorile zero.
mktime | Când este apelata fara argumente, mktime arunca o notificare E_STRICT. Utiliza?i func?ia time în loc.
mktime | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.
mssql_connect | The new_link parameter was added
openssl_pkcs7_verify | The content parameter was added.
preg_replace | Added the count parameter
preg_replace_callback | The count parameter was added
session_regenerate_id | Added the delete_old_session parameter.
sha1_file | Changed the function to use the streams API. It means that you can use it with wrappers, like sha1_file('http://example.com/..')
str_word_count | Added the charlist parameter
stream_copy_to_stream | Added the offset parameter
stream_filter_append | Prior to PHP 5.1.0, this function returns TRUE on success sau FALSE în cazul e?ecului.
stream_filter_prepend | Prior to PHP 5.1.0, this function returns TRUE on success sau FALSE în cazul e?ecului.
stream_get_contents | The offset was added.
strftime | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.
strtotime | Acum întoarce FALSE în caz de e?ec, în loc de -1.
strtotime | Acum genereaza erori ale zonei orare de tip E_STRICT ?i E_NOTICE.
substr_compare | Added the possibility to use a negative offset.
substr_count | Added the offset and the length parameters
var_export | Posibilitatea de a exporta clase ?i tablouri con?inând clase utilizând metoda magica __set_state().
XSLTProcessor::registerPHPFunctions | The restrict parameter was added.
5.0.5 | php_check_syntax | This function was removed from PHP.
5.0.4 | msql_fetch_array | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.
msql_fetch_object | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.
msql_fetch_row | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.
5.0.3 | get_class_vars | get_class_vars will only return the properties that can be accessed from the current scope.
is_subclass_of | You may also specify the object parameter as a string (the name of the class)
php_check_syntax | Calling exit after php_check_syntax resulted in a Segfault.
5.0.2 | array_slice | The optional preserve_keys parameter was added.
class_exists | Nu mai întoarce TRUE pentru interfe?e definite. Folosi?i interface_exists.
get_class_vars | Calling get_class_vars will now expose all the properties as an array, unlike previous behaviour where protected and private properties were prefixed with nul bytes.
sort | Added SORT_LOCALE_STRING
strtotime | În PHP 5 pâna la versiunea 5.0.2, "now" ?i alte momente de timp relative erau calculate gre?it relativ la miezul nop?ii de astazi. Aceasta difera de alte versiuni, unde el este calculat corect relativ la ora curenta.
5.0.1 | get_class_vars | Calling get_class_vars will expose all properties, as when converting an object to a class.
php_check_syntax | error_message is passed by reference.
5.0.0 | apache_get_modules | 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.
curl_setopt | Introduced CURLOPT_FTP_USE_EPRT, CURLOPT_NOSIGNAL, CURLOPT_UNRESTRICTED_AUTH, CURLOPT_BUFFERSIZE, CURLOPT_HTTPAUTH, CURLOPT_PROXYPORT, CURLOPT_PROXYTYPE, CURLOPT_SSLCERTTYPE, and CURLOPT_HTTP200ALIASES.
dirname | dirname is now binary safe
error_reporting | A fost introdusa E_STRICT (nu face parte din E_ALL).
is_a | This function became deprecated in favour of the instanceof operator. Calling this function will result in an E_STRICT warning.
opendir | path supports the ftp:// URL wrapper.
parse_ini_file | Values enclosed in double quotes can contain new lines.
rename | rename can now also be used with some URL wrappers. Refer to for a listing of which wrappers support rename.
rmdir | As of PHP 5.0.0 rmdir can also be used with some URL wrappers. Refer to for a listing of which wrappers support rmdir.
strip_tags | strip_tags is now binary safe.
strrpos | The needle may now be a string of more than one character.
strtotime | Microsecundele au început sa fie permise, dar sunt ignorate.
unlink | As of PHP 5.0.0 unlink can also be used with some URL wrappers. Refer to for a listing of which wrappers support unlink.
Listingul exemplelor
Edi?ia în formatul HTML Help
Anexe


Edi?ia în formatul 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
  • Integrating the PHP Manual
Jurnalul modificarilor
About This Edition
Manualul 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.

Edi?ia în formatul HTML Help
Using PHP Manual CHM Edition
Edi?ia în formatul HTML Help


Using PHP Manual CHM Edition

Cuprins

  • 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
Edi?ia în formatul 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 | 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

Cuprins

  • 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
Edi?ia în formatul 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.

Nota:

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.

Nota:

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".

Nota:

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
Integrating the PHP Manual
The Full Text Search


Integrating the PHP Manual

Nota:

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.

Nota:

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.

Using nested expressions when searching
Edi?ia în formatul HTML Help